partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
play_match
Plays matches between two neural nets. Args: black_model: Path to the model for black player white_model: Path to the model for white player
reinforcement/tensorflow/minigo/evaluate.py
def play_match(black_model, white_model, games, sgf_dir): """Plays matches between two neural nets. Args: black_model: Path to the model for black player white_model: Path to the model for white player """ with utils.logged_timer("Loading weights"): black_net = dual_net.DualNetw...
def play_match(black_model, white_model, games, sgf_dir): """Plays matches between two neural nets. Args: black_model: Path to the model for black player white_model: Path to the model for white player """ with utils.logged_timer("Loading weights"): black_net = dual_net.DualNetw...
[ "Plays", "matches", "between", "two", "neural", "nets", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/evaluate.py#L38-L111
[ "def", "play_match", "(", "black_model", ",", "white_model", ",", "games", ",", "sgf_dir", ")", ":", "with", "utils", ".", "logged_timer", "(", "\"Loading weights\"", ")", ":", "black_net", "=", "dual_net", ".", "DualNetwork", "(", "black_model", ")", "white_n...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
main
Play matches between two neural nets.
reinforcement/tensorflow/minigo/evaluate.py
def main(argv): """Play matches between two neural nets.""" _, black_model, white_model = argv utils.ensure_dir_exists(FLAGS.eval_sgf_dir) play_match(black_model, white_model, FLAGS.num_evaluation_games, FLAGS.eval_sgf_dir)
def main(argv): """Play matches between two neural nets.""" _, black_model, white_model = argv utils.ensure_dir_exists(FLAGS.eval_sgf_dir) play_match(black_model, white_model, FLAGS.num_evaluation_games, FLAGS.eval_sgf_dir)
[ "Play", "matches", "between", "two", "neural", "nets", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/evaluate.py#L114-L118
[ "def", "main", "(", "argv", ")", ":", "_", ",", "black_model", ",", "white_model", "=", "argv", "utils", ".", "ensure_dir_exists", "(", "FLAGS", ".", "eval_sgf_dir", ")", "play_match", "(", "black_model", ",", "white_model", ",", "FLAGS", ".", "num_evaluatio...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
main
Discards all pairs of sentences which can't be decoded by latin-1 encoder. It aims to filter out sentences with rare unicode glyphs and pairs which are most likely not valid English-German sentences. Examples of discarded sentences: ✿★★★Hommage au king de la pop ★★★✿ ✿★★★Que son âme repos... ...
rnn_translator/pytorch/scripts/filter_dataset.py
def main(): """ Discards all pairs of sentences which can't be decoded by latin-1 encoder. It aims to filter out sentences with rare unicode glyphs and pairs which are most likely not valid English-German sentences. Examples of discarded sentences: ✿★★★Hommage au king de la pop ★★★✿ ✿★★★Q...
def main(): """ Discards all pairs of sentences which can't be decoded by latin-1 encoder. It aims to filter out sentences with rare unicode glyphs and pairs which are most likely not valid English-German sentences. Examples of discarded sentences: ✿★★★Hommage au king de la pop ★★★✿ ✿★★★Q...
[ "Discards", "all", "pairs", "of", "sentences", "which", "can", "t", "be", "decoded", "by", "latin", "-", "1", "encoder", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/scripts/filter_dataset.py#L17-L75
[ "def", "main", "(", ")", ":", "args", "=", "parse_args", "(", ")", "c", "=", "Counter", "(", ")", "skipped", "=", "0", "valid", "=", "0", "data1", "=", "[", "]", "data2", "=", "[", "]", "with", "open", "(", "args", ".", "file1", ")", "as", "f...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
BoxCoder.encode
Encode a set of proposals with respect to some reference boxes Arguments: reference_boxes (Tensor): reference boxes proposals (Tensor): boxes to be encoded
object_detection/pytorch/maskrcnn_benchmark/modeling/box_coder.py
def encode(self, reference_boxes, proposals): """ Encode a set of proposals with respect to some reference boxes Arguments: reference_boxes (Tensor): reference boxes proposals (Tensor): boxes to be encoded """ TO_REMOVE = 1 # TODO remove ...
def encode(self, reference_boxes, proposals): """ Encode a set of proposals with respect to some reference boxes Arguments: reference_boxes (Tensor): reference boxes proposals (Tensor): boxes to be encoded """ TO_REMOVE = 1 # TODO remove ...
[ "Encode", "a", "set", "of", "proposals", "with", "respect", "to", "some", "reference", "boxes" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/box_coder.py#L22-L50
[ "def", "encode", "(", "self", ",", "reference_boxes", ",", "proposals", ")", ":", "TO_REMOVE", "=", "1", "# TODO remove", "ex_widths", "=", "proposals", "[", ":", ",", "2", "]", "-", "proposals", "[", ":", ",", "0", "]", "+", "TO_REMOVE", "ex_heights", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
BoxCoder.decode
From a set of original boxes and encoded relative box offsets, get the decoded boxes. Arguments: rel_codes (Tensor): encoded boxes boxes (Tensor): reference boxes.
object_detection/pytorch/maskrcnn_benchmark/modeling/box_coder.py
def decode(self, rel_codes, boxes): """ From a set of original boxes and encoded relative box offsets, get the decoded boxes. Arguments: rel_codes (Tensor): encoded boxes boxes (Tensor): reference boxes. """ boxes = boxes.to(rel_codes.dtype) ...
def decode(self, rel_codes, boxes): """ From a set of original boxes and encoded relative box offsets, get the decoded boxes. Arguments: rel_codes (Tensor): encoded boxes boxes (Tensor): reference boxes. """ boxes = boxes.to(rel_codes.dtype) ...
[ "From", "a", "set", "of", "original", "boxes", "and", "encoded", "relative", "box", "offsets", "get", "the", "decoded", "boxes", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/box_coder.py#L52-L95
[ "def", "decode", "(", "self", ",", "rel_codes", ",", "boxes", ")", ":", "boxes", "=", "boxes", ".", "to", "(", "rel_codes", ".", "dtype", ")", "TO_REMOVE", "=", "1", "# TODO remove", "widths", "=", "boxes", "[", ":", ",", "2", "]", "-", "boxes", "[...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
launch_eval_job
Launches an evaluator job. tag: name for this eval job (used as top level folder name) m1_path, m2_path: full gs:// paths to the .pb files to match up job_name: string, appended to the container, used to differentiate the job names (e.g. 'minigo-cc-evaluator-v5-123-v7-456') completions: the number o...
reinforcement/tensorflow/minigo/cluster/eval_server/launch_eval.py
def launch_eval_job(tag, m1_path, m2_path, job_name, completions): """Launches an evaluator job. tag: name for this eval job (used as top level folder name) m1_path, m2_path: full gs:// paths to the .pb files to match up job_name: string, appended to the container, used to differentiate the job name...
def launch_eval_job(tag, m1_path, m2_path, job_name, completions): """Launches an evaluator job. tag: name for this eval job (used as top level folder name) m1_path, m2_path: full gs:// paths to the .pb files to match up job_name: string, appended to the container, used to differentiate the job name...
[ "Launches", "an", "evaluator", "job", ".", "tag", ":", "name", "for", "this", "eval", "job", "(", "used", "as", "top", "level", "folder", "name", ")", "m1_path", "m2_path", ":", "full", "gs", ":", "//", "paths", "to", "the", ".", "pb", "files", "to",...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/cluster/eval_server/launch_eval.py#L33-L88
[ "def", "launch_eval_job", "(", "tag", ",", "m1_path", ",", "m2_path", ",", "job_name", ",", "completions", ")", ":", "print", "(", ")", "if", "not", "re", ".", "match", "(", "r'[a-z0-9-]*$'", ",", "tag", ",", "re", ".", "I", ")", ":", "print", "(", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
launch_eval_job
Launches an evaluator job. m1_path, m2_path: full gs:// paths to the .pb files to match up job_name: string, appended to the container, used to differentiate the job names (e.g. 'minigo-cc-evaluator-v5-123-v7-456') bucket_name: Where to write the sgfs, passed into the job as $BUCKET_NAME completions...
reinforcement/tensorflow/minigo/cluster/evaluator/launch_eval.py
def launch_eval_job(m1_path, m2_path, job_name, bucket_name, completions=5, flags_path=None): """Launches an evaluator job. m1_path, m2_path: full gs:// paths to the .pb files to match up job_name: string, appended to the container, used to differentiate the job names (e.g. 'minigo-cc-evaluator-...
def launch_eval_job(m1_path, m2_path, job_name, bucket_name, completions=5, flags_path=None): """Launches an evaluator job. m1_path, m2_path: full gs:// paths to the .pb files to match up job_name: string, appended to the container, used to differentiate the job names (e.g. 'minigo-cc-evaluator-...
[ "Launches", "an", "evaluator", "job", ".", "m1_path", "m2_path", ":", "full", "gs", ":", "//", "paths", "to", "the", ".", "pb", "files", "to", "match", "up", "job_name", ":", "string", "appended", "to", "the", "container", "used", "to", "differentiate", ...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/cluster/evaluator/launch_eval.py#L37-L69
[ "def", "launch_eval_job", "(", "m1_path", ",", "m2_path", ",", "job_name", ",", "bucket_name", ",", "completions", "=", "5", ",", "flags_path", "=", "None", ")", ":", "if", "not", "all", "(", "[", "m1_path", ",", "m2_path", ",", "job_name", ",", "bucket_...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
same_run_eval
Shorthand to spawn a job matching up two models from the same run, identified by their model number
reinforcement/tensorflow/minigo/cluster/evaluator/launch_eval.py
def same_run_eval(black_num=0, white_num=0, completions=4): """Shorthand to spawn a job matching up two models from the same run, identified by their model number """ if black_num <= 0 or white_num <= 0: print("Need real model numbers") return b = fsdb.get_model(black_num) w = fsdb....
def same_run_eval(black_num=0, white_num=0, completions=4): """Shorthand to spawn a job matching up two models from the same run, identified by their model number """ if black_num <= 0 or white_num <= 0: print("Need real model numbers") return b = fsdb.get_model(black_num) w = fsdb....
[ "Shorthand", "to", "spawn", "a", "job", "matching", "up", "two", "models", "from", "the", "same", "run", "identified", "by", "their", "model", "number" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/cluster/evaluator/launch_eval.py#L72-L94
[ "def", "same_run_eval", "(", "black_num", "=", "0", ",", "white_num", "=", "0", ",", "completions", "=", "4", ")", ":", "if", "black_num", "<=", "0", "or", "white_num", "<=", "0", ":", "print", "(", "\"Need real model numbers\"", ")", "return", "b", "=",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_append_pairs
Load the pairlist, add new stuff, save it out
reinforcement/tensorflow/minigo/cluster/evaluator/launch_eval.py
def _append_pairs(new_pairs): """ Load the pairlist, add new stuff, save it out """ desired_pairs = restore_pairs() or [] desired_pairs += new_pairs print("Adding {} new pairs, queue has {} pairs".format(len(new_pairs), len(desired_pairs))) save_pairs(desired_pairs)
def _append_pairs(new_pairs): """ Load the pairlist, add new stuff, save it out """ desired_pairs = restore_pairs() or [] desired_pairs += new_pairs print("Adding {} new pairs, queue has {} pairs".format(len(new_pairs), len(desired_pairs))) save_pairs(desired_pairs)
[ "Load", "the", "pairlist", "add", "new", "stuff", "save", "it", "out" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/cluster/evaluator/launch_eval.py#L97-L102
[ "def", "_append_pairs", "(", "new_pairs", ")", ":", "desired_pairs", "=", "restore_pairs", "(", ")", "or", "[", "]", "desired_pairs", "+=", "new_pairs", "print", "(", "\"Adding {} new pairs, queue has {} pairs\"", ".", "format", "(", "len", "(", "new_pairs", ")", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
add_top_pairs
Pairs up the top twenty models against each other. #1 plays 2,3,4,5, #2 plays 3,4,5,6 etc. for a total of 15*4 matches. Default behavior is to add the pairs to the working pairlist. `pair_now` will immediately create the pairings on the cluster. `dry_run` makes it only print the pairings that would be ...
reinforcement/tensorflow/minigo/cluster/evaluator/launch_eval.py
def add_top_pairs(dry_run=False, pair_now=False): """ Pairs up the top twenty models against each other. #1 plays 2,3,4,5, #2 plays 3,4,5,6 etc. for a total of 15*4 matches. Default behavior is to add the pairs to the working pairlist. `pair_now` will immediately create the pairings on the cluster. ...
def add_top_pairs(dry_run=False, pair_now=False): """ Pairs up the top twenty models against each other. #1 plays 2,3,4,5, #2 plays 3,4,5,6 etc. for a total of 15*4 matches. Default behavior is to add the pairs to the working pairlist. `pair_now` will immediately create the pairings on the cluster. ...
[ "Pairs", "up", "the", "top", "twenty", "models", "against", "each", "other", ".", "#1", "plays", "2", "3", "4", "5", "#2", "plays", "3", "4", "5", "6", "etc", ".", "for", "a", "total", "of", "15", "*", "4", "matches", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/cluster/evaluator/launch_eval.py#L113-L133
[ "def", "add_top_pairs", "(", "dry_run", "=", "False", ",", "pair_now", "=", "False", ")", ":", "top", "=", "ratings", ".", "top_n", "(", "15", ")", "new_pairs", "=", "[", "]", "for", "idx", ",", "t", "in", "enumerate", "(", "top", "[", ":", "10", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
zoo_loop
Manages creating and cleaning up match jobs. - Load whatever pairs didn't get queued last time, and whatever our most recently seen model was. - Loop and... - If a new model is detected, create and append new pairs to the list - Automatically queue models from a list of pairs to keep a cl...
reinforcement/tensorflow/minigo/cluster/evaluator/launch_eval.py
def zoo_loop(sgf_dir=None, max_jobs=40): """Manages creating and cleaning up match jobs. - Load whatever pairs didn't get queued last time, and whatever our most recently seen model was. - Loop and... - If a new model is detected, create and append new pairs to the list - Automaticall...
def zoo_loop(sgf_dir=None, max_jobs=40): """Manages creating and cleaning up match jobs. - Load whatever pairs didn't get queued last time, and whatever our most recently seen model was. - Loop and... - If a new model is detected, create and append new pairs to the list - Automaticall...
[ "Manages", "creating", "and", "cleaning", "up", "match", "jobs", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/cluster/evaluator/launch_eval.py#L158-L247
[ "def", "zoo_loop", "(", "sgf_dir", "=", "None", ",", "max_jobs", "=", "40", ")", ":", "desired_pairs", "=", "restore_pairs", "(", ")", "or", "[", "]", "random", ".", "shuffle", "(", "desired_pairs", ")", "last_model_queued", "=", "restore_last_model", "(", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
cleanup
Remove completed jobs from the cluster
reinforcement/tensorflow/minigo/cluster/evaluator/launch_eval.py
def cleanup(api_instance=None): """ Remove completed jobs from the cluster """ api = api_instance or get_api() r = api.list_job_for_all_namespaces() delete_opts = kubernetes.client.V1DeleteOptions( propagation_policy="Background") for job in r.items: if job.status.succeeded == jo...
def cleanup(api_instance=None): """ Remove completed jobs from the cluster """ api = api_instance or get_api() r = api.list_job_for_all_namespaces() delete_opts = kubernetes.client.V1DeleteOptions( propagation_policy="Background") for job in r.items: if job.status.succeeded == jo...
[ "Remove", "completed", "jobs", "from", "the", "cluster" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/cluster/evaluator/launch_eval.py#L279-L289
[ "def", "cleanup", "(", "api_instance", "=", "None", ")", ":", "api", "=", "api_instance", "or", "get_api", "(", ")", "r", "=", "api", ".", "list_job_for_all_namespaces", "(", ")", "delete_opts", "=", "kubernetes", ".", "client", ".", "V1DeleteOptions", "(", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
make_pairs_for_model
Create a list of pairs of model nums; play every model nearby, then every other model after that, then every fifth, etc. Returns a list like [[N, N-1], [N, N-2], ... , [N, N-12], ... , [N, N-50]]
reinforcement/tensorflow/minigo/cluster/evaluator/launch_eval.py
def make_pairs_for_model(model_num=0): """ Create a list of pairs of model nums; play every model nearby, then every other model after that, then every fifth, etc. Returns a list like [[N, N-1], [N, N-2], ... , [N, N-12], ... , [N, N-50]] """ if model_num == 0: return pairs = [] mm...
def make_pairs_for_model(model_num=0): """ Create a list of pairs of model nums; play every model nearby, then every other model after that, then every fifth, etc. Returns a list like [[N, N-1], [N, N-2], ... , [N, N-12], ... , [N, N-50]] """ if model_num == 0: return pairs = [] mm...
[ "Create", "a", "list", "of", "pairs", "of", "model", "nums", ";", "play", "every", "model", "nearby", "then", "every", "other", "model", "after", "that", "then", "every", "fifth", "etc", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/cluster/evaluator/launch_eval.py#L292-L309
[ "def", "make_pairs_for_model", "(", "model_num", "=", "0", ")", ":", "if", "model_num", "==", "0", ":", "return", "pairs", "=", "[", "]", "mm_fib", "=", "lambda", "n", ":", "int", "(", "(", "np", ".", "matrix", "(", "[", "[", "2", ",", "1", "]", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
convert_coco_stuff_mat
Convert to png and save json with path. This currently only contains the segmentation labels for objects+stuff in cocostuff - if we need to combine with other labels from original COCO that will be a TODO.
object_detection/pytorch/tools/cityscapes/convert_cityscapes_to_coco.py
def convert_coco_stuff_mat(data_dir, out_dir): """Convert to png and save json with path. This currently only contains the segmentation labels for objects+stuff in cocostuff - if we need to combine with other labels from original COCO that will be a TODO.""" sets = ['train', 'val'] categories = [] ...
def convert_coco_stuff_mat(data_dir, out_dir): """Convert to png and save json with path. This currently only contains the segmentation labels for objects+stuff in cocostuff - if we need to combine with other labels from original COCO that will be a TODO.""" sets = ['train', 'val'] categories = [] ...
[ "Convert", "to", "png", "and", "save", "json", "with", "path", ".", "This", "currently", "only", "contains", "the", "segmentation", "labels", "for", "objects", "+", "stuff", "in", "cocostuff", "-", "if", "we", "need", "to", "combine", "with", "other", "lab...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/tools/cityscapes/convert_cityscapes_to_coco.py#L53-L90
[ "def", "convert_coco_stuff_mat", "(", "data_dir", ",", "out_dir", ")", ":", "sets", "=", "[", "'train'", ",", "'val'", "]", "categories", "=", "[", "]", "json_name", "=", "'coco_stuff_%s.json'", "ann_dict", "=", "{", "}", "for", "data_set", "in", "sets", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
convert_cityscapes_instance_only
Convert from cityscapes format to COCO instance seg format - polygons
object_detection/pytorch/tools/cityscapes/convert_cityscapes_to_coco.py
def convert_cityscapes_instance_only( data_dir, out_dir): """Convert from cityscapes format to COCO instance seg format - polygons""" sets = [ 'gtFine_val', 'gtFine_train', 'gtFine_test', # 'gtCoarse_train', # 'gtCoarse_val', # 'gtCoarse_train_extra' ...
def convert_cityscapes_instance_only( data_dir, out_dir): """Convert from cityscapes format to COCO instance seg format - polygons""" sets = [ 'gtFine_val', 'gtFine_train', 'gtFine_test', # 'gtCoarse_train', # 'gtCoarse_val', # 'gtCoarse_train_extra' ...
[ "Convert", "from", "cityscapes", "format", "to", "COCO", "instance", "seg", "format", "-", "polygons" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/tools/cityscapes/convert_cityscapes_to_coco.py#L101-L211
[ "def", "convert_cityscapes_instance_only", "(", "data_dir", ",", "out_dir", ")", ":", "sets", "=", "[", "'gtFine_val'", ",", "'gtFine_train'", ",", "'gtFine_test'", ",", "# 'gtCoarse_train',", "# 'gtCoarse_val',", "# 'gtCoarse_train_extra'", "]", "ann_dirs", "=", "[", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_mg_path
model_run = integer, e.g. 15, 16, corresponding to the v-number model_num = integer, e.g 939, for the model number in that run
reinforcement/tensorflow/minigo/cluster/ringmaster/setup_ringmaster.py
def get_mg_path(model_run, model_num): """ model_run = integer, e.g. 15, 16, corresponding to the v-number model_num = integer, e.g 939, for the model number in that run """ fsdb.switch_base("minigo-pub/v{:d}-19x19".format(model_run)) model = fsdb.get_model(model_num) return os.path.join(fsd...
def get_mg_path(model_run, model_num): """ model_run = integer, e.g. 15, 16, corresponding to the v-number model_num = integer, e.g 939, for the model number in that run """ fsdb.switch_base("minigo-pub/v{:d}-19x19".format(model_run)) model = fsdb.get_model(model_num) return os.path.join(fsd...
[ "model_run", "=", "integer", "e", ".", "g", ".", "15", "16", "corresponding", "to", "the", "v", "-", "number", "model_num", "=", "integer", "e", ".", "g", "939", "for", "the", "model", "number", "in", "that", "run" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/cluster/ringmaster/setup_ringmaster.py#L47-L54
[ "def", "get_mg_path", "(", "model_run", ",", "model_num", ")", ":", "fsdb", ".", "switch_base", "(", "\"minigo-pub/v{:d}-19x19\"", ".", "format", "(", "model_run", ")", ")", "model", "=", "fsdb", ".", "get_model", "(", "model_num", ")", "return", "os", ".", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
make_single_array
Create a single numpy array from a dataset. The dataset must have only one dimension, that is, the length of its `output_shapes` and `output_types` is 1, and its output shape must be `[]`, that is, every tensor in the dataset must be a scalar. Args: ds: a TF Dataset. batch_size: how ...
reinforcement/tensorflow/minigo/bigtable_input.py
def make_single_array(ds, batch_size=8*1024): """Create a single numpy array from a dataset. The dataset must have only one dimension, that is, the length of its `output_shapes` and `output_types` is 1, and its output shape must be `[]`, that is, every tensor in the dataset must be a scalar. A...
def make_single_array(ds, batch_size=8*1024): """Create a single numpy array from a dataset. The dataset must have only one dimension, that is, the length of its `output_shapes` and `output_types` is 1, and its output shape must be `[]`, that is, every tensor in the dataset must be a scalar. A...
[ "Create", "a", "single", "numpy", "array", "from", "a", "dataset", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L106-L141
[ "def", "make_single_array", "(", "ds", ",", "batch_size", "=", "8", "*", "1024", ")", ":", "if", "isinstance", "(", "ds", ".", "output_types", ",", "tuple", ")", "or", "isinstance", "(", "ds", ".", "output_shapes", ",", "tuple", ")", ":", "raise", "Val...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_histogram_move_keys_by_game
Given dataset of key names, return histogram of moves/game. Move counts are written by the game players, so this is mostly useful for repair or backfill. Args: sess: TF session ds: TF dataset containing game move keys. batch_size: performance tuning parameter
reinforcement/tensorflow/minigo/bigtable_input.py
def _histogram_move_keys_by_game(sess, ds, batch_size=8*1024): """Given dataset of key names, return histogram of moves/game. Move counts are written by the game players, so this is mostly useful for repair or backfill. Args: sess: TF session ds: TF dataset containing game move keys. ...
def _histogram_move_keys_by_game(sess, ds, batch_size=8*1024): """Given dataset of key names, return histogram of moves/game. Move counts are written by the game players, so this is mostly useful for repair or backfill. Args: sess: TF session ds: TF dataset containing game move keys. ...
[ "Given", "dataset", "of", "key", "names", "return", "histogram", "of", "moves", "/", "game", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L144-L168
[ "def", "_histogram_move_keys_by_game", "(", "sess", ",", "ds", ",", "batch_size", "=", "8", "*", "1024", ")", ":", "ds", "=", "ds", ".", "batch", "(", "batch_size", ")", "# Turns 'g_0000001234_m_133' into 'g_0000001234'", "ds", "=", "ds", ".", "map", "(", "l...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_game_keys_as_array
Turn keys of a Bigtable dataset into an array. Take g_GGG_m_MMM and create GGG.MMM numbers. Valuable when visualizing the distribution of a given dataset in the game keyspace.
reinforcement/tensorflow/minigo/bigtable_input.py
def _game_keys_as_array(ds): """Turn keys of a Bigtable dataset into an array. Take g_GGG_m_MMM and create GGG.MMM numbers. Valuable when visualizing the distribution of a given dataset in the game keyspace. """ ds = ds.map(lambda row_key, cell: row_key) # want 'g_0000001234_m_133' is '000...
def _game_keys_as_array(ds): """Turn keys of a Bigtable dataset into an array. Take g_GGG_m_MMM and create GGG.MMM numbers. Valuable when visualizing the distribution of a given dataset in the game keyspace. """ ds = ds.map(lambda row_key, cell: row_key) # want 'g_0000001234_m_133' is '000...
[ "Turn", "keys", "of", "a", "Bigtable", "dataset", "into", "an", "array", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L171-L186
[ "def", "_game_keys_as_array", "(", "ds", ")", ":", "ds", "=", "ds", ".", "map", "(", "lambda", "row_key", ",", "cell", ":", "row_key", ")", "# want 'g_0000001234_m_133' is '0000001234.133' and so forth", "ds", "=", "ds", ".", "map", "(", "lambda", "x", ":", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_delete_rows
Delete the given row keys from the given Bigtable. The args are (BigtableSpec, row_keys), but are passed as a single argument in order to work with multiprocessing.Pool.map. This is also the reason why this is a top-level function instead of a method.
reinforcement/tensorflow/minigo/bigtable_input.py
def _delete_rows(args): """Delete the given row keys from the given Bigtable. The args are (BigtableSpec, row_keys), but are passed as a single argument in order to work with multiprocessing.Pool.map. This is also the reason why this is a top-level function instead of a method. """ btspec...
def _delete_rows(args): """Delete the given row keys from the given Bigtable. The args are (BigtableSpec, row_keys), but are passed as a single argument in order to work with multiprocessing.Pool.map. This is also the reason why this is a top-level function instead of a method. """ btspec...
[ "Delete", "the", "given", "row", "keys", "from", "the", "given", "Bigtable", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L189-L205
[ "def", "_delete_rows", "(", "args", ")", ":", "btspec", ",", "row_keys", "=", "args", "bt_table", "=", "bigtable", ".", "Client", "(", "btspec", ".", "project", ")", ".", "instance", "(", "btspec", ".", "instance", ")", ".", "table", "(", "btspec", "."...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
set_fresh_watermark
Sets the metadata cell used to block until some quantity of games have been played. This sets the 'freshness mark' on the `game_queue`, used to block training until enough new games have been played. The number of fresh games required is the larger of: - The fraction of the total window size ...
reinforcement/tensorflow/minigo/bigtable_input.py
def set_fresh_watermark(game_queue, count_from, window_size, fresh_fraction=0.05, minimum_fresh=20000): """Sets the metadata cell used to block until some quantity of games have been played. This sets the 'freshness mark' on the `game_queue`, used to block training until enough new ...
def set_fresh_watermark(game_queue, count_from, window_size, fresh_fraction=0.05, minimum_fresh=20000): """Sets the metadata cell used to block until some quantity of games have been played. This sets the 'freshness mark' on the `game_queue`, used to block training until enough new ...
[ "Sets", "the", "metadata", "cell", "used", "to", "block", "until", "some", "quantity", "of", "games", "have", "been", "played", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L574-L599
[ "def", "set_fresh_watermark", "(", "game_queue", ",", "count_from", ",", "window_size", ",", "fresh_fraction", "=", "0.05", ",", "minimum_fresh", "=", "20000", ")", ":", "already_played", "=", "game_queue", ".", "latest_game_number", "-", "count_from", "print", "(...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_unparsed_moves_from_last_n_games
Get a dataset of serialized TFExamples from the last N games. Args: games, games_nr: GameQueues of the regular selfplay and calibration (aka 'no resign') games to sample from. n: an integer indicating how many past games should be sourced. moves: an integer indicating how many moves sho...
reinforcement/tensorflow/minigo/bigtable_input.py
def get_unparsed_moves_from_last_n_games(games, games_nr, n, moves=2**21, shuffle=True, column_family=TFEXAMPLE, column='example', ...
def get_unparsed_moves_from_last_n_games(games, games_nr, n, moves=2**21, shuffle=True, column_family=TFEXAMPLE, column='example', ...
[ "Get", "a", "dataset", "of", "serialized", "TFExamples", "from", "the", "last", "N", "games", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L602-L651
[ "def", "get_unparsed_moves_from_last_n_games", "(", "games", ",", "games_nr", ",", "n", ",", "moves", "=", "2", "**", "21", ",", "shuffle", "=", "True", ",", "column_family", "=", "TFEXAMPLE", ",", "column", "=", "'example'", ",", "values_only", "=", "True",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
count_elements_in_dataset
Count and return all the elements in the given dataset. Debugging function. The elements in a dataset cannot be counted without enumerating all of them. By counting in batch and in parallel, this method allows rapid traversal of the dataset. Args: ds: The dataset whose elements should be coun...
reinforcement/tensorflow/minigo/bigtable_input.py
def count_elements_in_dataset(ds, batch_size=1*1024, parallel_batch=8): """Count and return all the elements in the given dataset. Debugging function. The elements in a dataset cannot be counted without enumerating all of them. By counting in batch and in parallel, this method allows rapid traversal ...
def count_elements_in_dataset(ds, batch_size=1*1024, parallel_batch=8): """Count and return all the elements in the given dataset. Debugging function. The elements in a dataset cannot be counted without enumerating all of them. By counting in batch and in parallel, this method allows rapid traversal ...
[ "Count", "and", "return", "all", "the", "elements", "in", "the", "given", "dataset", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L654-L687
[ "def", "count_elements_in_dataset", "(", "ds", ",", "batch_size", "=", "1", "*", "1024", ",", "parallel_batch", "=", "8", ")", ":", "with", "tf", ".", "Session", "(", ")", "as", "sess", ":", "dsc", "=", "ds", ".", "apply", "(", "tf", ".", "contrib", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
GameQueue.create
Create the table underlying the queue. Create the 'metadata' and 'tfexample' column families and their properties.
reinforcement/tensorflow/minigo/bigtable_input.py
def create(self): """Create the table underlying the queue. Create the 'metadata' and 'tfexample' column families and their properties. """ if self.bt_table.exists(): utils.dbg('Table already exists') return max_versions_rule = bigtable_column_fa...
def create(self): """Create the table underlying the queue. Create the 'metadata' and 'tfexample' column families and their properties. """ if self.bt_table.exists(): utils.dbg('Table already exists') return max_versions_rule = bigtable_column_fa...
[ "Create", "the", "table", "underlying", "the", "queue", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L231-L244
[ "def", "create", "(", "self", ")", ":", "if", "self", ".", "bt_table", ".", "exists", "(", ")", ":", "utils", ".", "dbg", "(", "'Table already exists'", ")", "return", "max_versions_rule", "=", "bigtable_column_family", ".", "MaxVersionsGCRule", "(", "1", ")...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
GameQueue.games_by_time
Given a range of games, return the games sorted by time. Returns [(time, game_number), ...] The time will be a `datetime.datetime` and the game number is the integer used as the basis of the row ID. Note that when a cluster of self-play nodes are writing concurrently, the game...
reinforcement/tensorflow/minigo/bigtable_input.py
def games_by_time(self, start_game, end_game): """Given a range of games, return the games sorted by time. Returns [(time, game_number), ...] The time will be a `datetime.datetime` and the game number is the integer used as the basis of the row ID. Note that when a cluster of ...
def games_by_time(self, start_game, end_game): """Given a range of games, return the games sorted by time. Returns [(time, game_number), ...] The time will be a `datetime.datetime` and the game number is the integer used as the basis of the row ID. Note that when a cluster of ...
[ "Given", "a", "range", "of", "games", "return", "the", "games", "sorted", "by", "time", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L263-L285
[ "def", "games_by_time", "(", "self", ",", "start_game", ",", "end_game", ")", ":", "move_count", "=", "b'move_count'", "rows", "=", "self", ".", "bt_table", ".", "read_rows", "(", "ROWCOUNT_PREFIX", ".", "format", "(", "start_game", ")", ",", "ROWCOUNT_PREFIX"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
GameQueue.delete_row_range
Delete rows related to the given game range. Args: format_str: a string to `.format()` by the game numbers in order to create the row prefixes. start_game: the starting game number of the deletion. end_game: the ending game number of the deletion.
reinforcement/tensorflow/minigo/bigtable_input.py
def delete_row_range(self, format_str, start_game, end_game): """Delete rows related to the given game range. Args: format_str: a string to `.format()` by the game numbers in order to create the row prefixes. start_game: the starting game number of the deletion. ...
def delete_row_range(self, format_str, start_game, end_game): """Delete rows related to the given game range. Args: format_str: a string to `.format()` by the game numbers in order to create the row prefixes. start_game: the starting game number of the deletion. ...
[ "Delete", "rows", "related", "to", "the", "given", "game", "range", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L287-L329
[ "def", "delete_row_range", "(", "self", ",", "format_str", ",", "start_game", ",", "end_game", ")", ":", "row_keys", "=", "make_single_array", "(", "self", ".", "tf_table", ".", "keys_by_range_dataset", "(", "format_str", ".", "format", "(", "start_game", ")", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
GameQueue.trim_games_since
Trim off the games since the given time. Search back no more than max_games for this time point, locate the game there, and remove all games since that game, resetting the latest game counter. If `t` is a `datetime.timedelta`, then the target time will be found by subtracting t...
reinforcement/tensorflow/minigo/bigtable_input.py
def trim_games_since(self, t, max_games=500000): """Trim off the games since the given time. Search back no more than max_games for this time point, locate the game there, and remove all games since that game, resetting the latest game counter. If `t` is a `datetime.timedelta`,...
def trim_games_since(self, t, max_games=500000): """Trim off the games since the given time. Search back no more than max_games for this time point, locate the game there, and remove all games since that game, resetting the latest game counter. If `t` is a `datetime.timedelta`,...
[ "Trim", "off", "the", "games", "since", "the", "given", "time", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L331-L363
[ "def", "trim_games_since", "(", "self", ",", "t", ",", "max_games", "=", "500000", ")", ":", "latest", "=", "self", ".", "latest_game_number", "earliest", "=", "int", "(", "latest", "-", "max_games", ")", "gbt", "=", "self", ".", "games_by_time", "(", "e...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
GameQueue.bleakest_moves
Given a range of games, return the bleakest moves. Returns a list of (game, move, q) sorted by q.
reinforcement/tensorflow/minigo/bigtable_input.py
def bleakest_moves(self, start_game, end_game): """Given a range of games, return the bleakest moves. Returns a list of (game, move, q) sorted by q. """ bleak = b'bleakest_q' rows = self.bt_table.read_rows( ROW_PREFIX.format(start_game), ROW_PREFIX.format...
def bleakest_moves(self, start_game, end_game): """Given a range of games, return the bleakest moves. Returns a list of (game, move, q) sorted by q. """ bleak = b'bleakest_q' rows = self.bt_table.read_rows( ROW_PREFIX.format(start_game), ROW_PREFIX.format...
[ "Given", "a", "range", "of", "games", "return", "the", "bleakest", "moves", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L365-L382
[ "def", "bleakest_moves", "(", "self", ",", "start_game", ",", "end_game", ")", ":", "bleak", "=", "b'bleakest_q'", "rows", "=", "self", ".", "bt_table", ".", "read_rows", "(", "ROW_PREFIX", ".", "format", "(", "start_game", ")", ",", "ROW_PREFIX", ".", "fo...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
GameQueue.require_fresh_games
Require a given number of fresh games to be played. Args: number_fresh: integer, number of new fresh games needed Increments the cell `table_state=metadata:wait_for_game_number` by the given number of games. This will cause `self.wait_for_fresh_games()` to block until the g...
reinforcement/tensorflow/minigo/bigtable_input.py
def require_fresh_games(self, number_fresh): """Require a given number of fresh games to be played. Args: number_fresh: integer, number of new fresh games needed Increments the cell `table_state=metadata:wait_for_game_number` by the given number of games. This will cause ...
def require_fresh_games(self, number_fresh): """Require a given number of fresh games to be played. Args: number_fresh: integer, number of new fresh games needed Increments the cell `table_state=metadata:wait_for_game_number` by the given number of games. This will cause ...
[ "Require", "a", "given", "number", "of", "fresh", "games", "to", "be", "played", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L384-L399
[ "def", "require_fresh_games", "(", "self", ",", "number_fresh", ")", ":", "latest", "=", "self", ".", "latest_game_number", "table_state", "=", "self", ".", "bt_table", ".", "row", "(", "TABLE_STATE", ")", "table_state", ".", "set_cell", "(", "METADATA", ",", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
GameQueue.wait_for_fresh_games
Block caller until required new games have been played. Args: poll_interval: number of seconds to wait between checks If the cell `table_state=metadata:wait_for_game_number` exists, then block the caller, checking every `poll_interval` seconds, until `table_state=metadata:ga...
reinforcement/tensorflow/minigo/bigtable_input.py
def wait_for_fresh_games(self, poll_interval=15.0): """Block caller until required new games have been played. Args: poll_interval: number of seconds to wait between checks If the cell `table_state=metadata:wait_for_game_number` exists, then block the caller, checking every ...
def wait_for_fresh_games(self, poll_interval=15.0): """Block caller until required new games have been played. Args: poll_interval: number of seconds to wait between checks If the cell `table_state=metadata:wait_for_game_number` exists, then block the caller, checking every ...
[ "Block", "caller", "until", "required", "new", "games", "have", "been", "played", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L401-L427
[ "def", "wait_for_fresh_games", "(", "self", ",", "poll_interval", "=", "15.0", ")", ":", "wait_until_game", "=", "self", ".", "read_wait_cell", "(", ")", "if", "not", "wait_until_game", ":", "return", "latest_game", "=", "self", ".", "latest_game_number", "last_...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
GameQueue.read_wait_cell
Read the value of the cell holding the 'wait' value, Returns the int value of whatever it has, or None if the cell doesn't exist.
reinforcement/tensorflow/minigo/bigtable_input.py
def read_wait_cell(self): """Read the value of the cell holding the 'wait' value, Returns the int value of whatever it has, or None if the cell doesn't exist. """ table_state = self.bt_table.read_row( TABLE_STATE, filter_=bigtable_row_filters.ColumnRange...
def read_wait_cell(self): """Read the value of the cell holding the 'wait' value, Returns the int value of whatever it has, or None if the cell doesn't exist. """ table_state = self.bt_table.read_row( TABLE_STATE, filter_=bigtable_row_filters.ColumnRange...
[ "Read", "the", "value", "of", "the", "cell", "holding", "the", "wait", "value" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L429-L450
[ "def", "read_wait_cell", "(", "self", ")", ":", "table_state", "=", "self", ".", "bt_table", ".", "read_row", "(", "TABLE_STATE", ",", "filter_", "=", "bigtable_row_filters", ".", "ColumnRangeFilter", "(", "METADATA", ",", "WAIT_CELL", ",", "WAIT_CELL", ")", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
GameQueue.count_moves_in_game_range
Count the total moves in a game range. Args: game_begin: integer, starting game game_end: integer, ending game Uses the `ct_` keyspace for rapid move summary.
reinforcement/tensorflow/minigo/bigtable_input.py
def count_moves_in_game_range(self, game_begin, game_end): """Count the total moves in a game range. Args: game_begin: integer, starting game game_end: integer, ending game Uses the `ct_` keyspace for rapid move summary. """ rows = self.bt_table.read_rows(...
def count_moves_in_game_range(self, game_begin, game_end): """Count the total moves in a game range. Args: game_begin: integer, starting game game_end: integer, ending game Uses the `ct_` keyspace for rapid move summary. """ rows = self.bt_table.read_rows(...
[ "Count", "the", "total", "moves", "in", "a", "game", "range", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L452-L466
[ "def", "count_moves_in_game_range", "(", "self", ",", "game_begin", ",", "game_end", ")", ":", "rows", "=", "self", ".", "bt_table", ".", "read_rows", "(", "ROWCOUNT_PREFIX", ".", "format", "(", "game_begin", ")", ",", "ROWCOUNT_PREFIX", ".", "format", "(", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
GameQueue.moves_from_games
Dataset of samples and/or shuffled moves from game range. Args: n: an integer indicating how many past games should be sourced. moves: an integer indicating how many moves should be sampled from those N games. column_family: name of the column family containing move...
reinforcement/tensorflow/minigo/bigtable_input.py
def moves_from_games(self, start_game, end_game, moves, shuffle, column_family, column): """Dataset of samples and/or shuffled moves from game range. Args: n: an integer indicating how many past games should be sourced. moves: an integer indicating how man...
def moves_from_games(self, start_game, end_game, moves, shuffle, column_family, column): """Dataset of samples and/or shuffled moves from game range. Args: n: an integer indicating how many past games should be sourced. moves: an integer indicating how man...
[ "Dataset", "of", "samples", "and", "/", "or", "shuffled", "moves", "from", "game", "range", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L468-L500
[ "def", "moves_from_games", "(", "self", ",", "start_game", ",", "end_game", ",", "moves", ",", "shuffle", ",", "column_family", ",", "column", ")", ":", "start_row", "=", "ROW_PREFIX", ".", "format", "(", "start_game", ")", "end_row", "=", "ROW_PREFIX", ".",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
GameQueue.moves_from_last_n_games
Randomly choose a given number of moves from the last n games. Args: n: number of games at the end of this GameQueue to source. moves: number of moves to be sampled from `n` games. shuffle: if True, shuffle the selected moves. column_family: name of the column family...
reinforcement/tensorflow/minigo/bigtable_input.py
def moves_from_last_n_games(self, n, moves, shuffle, column_family, column): """Randomly choose a given number of moves from the last n games. Args: n: number of games at the end of this GameQueue to source. moves: number of moves to be sampled from...
def moves_from_last_n_games(self, n, moves, shuffle, column_family, column): """Randomly choose a given number of moves from the last n games. Args: n: number of games at the end of this GameQueue to source. moves: number of moves to be sampled from...
[ "Randomly", "choose", "a", "given", "number", "of", "moves", "from", "the", "last", "n", "games", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L502-L525
[ "def", "moves_from_last_n_games", "(", "self", ",", "n", ",", "moves", ",", "shuffle", ",", "column_family", ",", "column", ")", ":", "self", ".", "wait_for_fresh_games", "(", ")", "latest_game", "=", "self", ".", "latest_game_number", "utils", ".", "dbg", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
GameQueue._write_move_counts
Add move counts from the given histogram to the table. Used to update the move counts in an existing table. Should not be needed except for backfill or repair. Args: sess: TF session to use for doing a Bigtable write. tf_table: TF Cloud Bigtable to use for writing. ...
reinforcement/tensorflow/minigo/bigtable_input.py
def _write_move_counts(self, sess, h): """Add move counts from the given histogram to the table. Used to update the move counts in an existing table. Should not be needed except for backfill or repair. Args: sess: TF session to use for doing a Bigtable write. tf_t...
def _write_move_counts(self, sess, h): """Add move counts from the given histogram to the table. Used to update the move counts in an existing table. Should not be needed except for backfill or repair. Args: sess: TF session to use for doing a Bigtable write. tf_t...
[ "Add", "move", "counts", "from", "the", "given", "histogram", "to", "the", "table", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L527-L550
[ "def", "_write_move_counts", "(", "self", ",", "sess", ",", "h", ")", ":", "def", "gen", "(", ")", ":", "for", "k", ",", "v", "in", "h", ".", "items", "(", ")", ":", "# The keys in the histogram may be of type 'bytes'", "k", "=", "str", "(", "k", ",", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
GameQueue.update_move_counts
Used to update the move_count cell for older games. Should not be needed except for backfill or repair. move_count cells will be updated in both g_<game_id>_m_000 rows and ct_<game_id>_<move_count> rows.
reinforcement/tensorflow/minigo/bigtable_input.py
def update_move_counts(self, start_game, end_game, interval=1000): """Used to update the move_count cell for older games. Should not be needed except for backfill or repair. move_count cells will be updated in both g_<game_id>_m_000 rows and ct_<game_id>_<move_count> rows. """ ...
def update_move_counts(self, start_game, end_game, interval=1000): """Used to update the move_count cell for older games. Should not be needed except for backfill or repair. move_count cells will be updated in both g_<game_id>_m_000 rows and ct_<game_id>_<move_count> rows. """ ...
[ "Used", "to", "update", "the", "move_count", "cell", "for", "older", "games", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L552-L571
[ "def", "update_move_counts", "(", "self", ",", "start_game", ",", "end_game", ",", "interval", "=", "1000", ")", ":", "for", "g", "in", "range", "(", "start_game", ",", "end_game", ",", "interval", ")", ":", "with", "tf", ".", "Session", "(", ")", "as"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_filenames
Return filenames for dataset.
image_classification/tensorflow/official/resnet/imagenet_main.py
def get_filenames(is_training, data_dir): """Return filenames for dataset.""" if is_training: return [ os.path.join(data_dir, 'train-%05d-of-01024' % i) for i in range(_NUM_TRAIN_FILES)] else: return [ os.path.join(data_dir, 'validation-%05d-of-00128' % i) for i in range(12...
def get_filenames(is_training, data_dir): """Return filenames for dataset.""" if is_training: return [ os.path.join(data_dir, 'train-%05d-of-01024' % i) for i in range(_NUM_TRAIN_FILES)] else: return [ os.path.join(data_dir, 'validation-%05d-of-00128' % i) for i in range(12...
[ "Return", "filenames", "for", "dataset", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/imagenet_main.py#L51-L60
[ "def", "get_filenames", "(", "is_training", ",", "data_dir", ")", ":", "if", "is_training", ":", "return", "[", "os", ".", "path", ".", "join", "(", "data_dir", ",", "'train-%05d-of-01024'", "%", "i", ")", "for", "i", "in", "range", "(", "_NUM_TRAIN_FILES"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_parse_example_proto
Parses an Example proto containing a training example of an image. The output of the build_image_data.py image preprocessing script is a dataset containing serialized Example protocol buffers. Each Example proto contains the following fields (values are included as examples): image/height: 462 image/wid...
image_classification/tensorflow/official/resnet/imagenet_main.py
def _parse_example_proto(example_serialized): """Parses an Example proto containing a training example of an image. The output of the build_image_data.py image preprocessing script is a dataset containing serialized Example protocol buffers. Each Example proto contains the following fields (values are included...
def _parse_example_proto(example_serialized): """Parses an Example proto containing a training example of an image. The output of the build_image_data.py image preprocessing script is a dataset containing serialized Example protocol buffers. Each Example proto contains the following fields (values are included...
[ "Parses", "an", "Example", "proto", "containing", "a", "training", "example", "of", "an", "image", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/imagenet_main.py#L63-L117
[ "def", "_parse_example_proto", "(", "example_serialized", ")", ":", "# Dense features in Example proto.", "feature_map", "=", "{", "'image/encoded'", ":", "tf", ".", "FixedLenFeature", "(", "[", "]", ",", "dtype", "=", "tf", ".", "string", ",", "default_value", "=...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
parse_record
Parses a record containing a training example of an image. The input record is parsed into a label and image, and the image is passed through preprocessing steps (cropping, flipping, and so on). Args: raw_record: scalar Tensor tf.string containing a serialized Example protocol buffer. is_training:...
image_classification/tensorflow/official/resnet/imagenet_main.py
def parse_record(raw_record, is_training, dtype): """Parses a record containing a training example of an image. The input record is parsed into a label and image, and the image is passed through preprocessing steps (cropping, flipping, and so on). Args: raw_record: scalar Tensor tf.string containing a ser...
def parse_record(raw_record, is_training, dtype): """Parses a record containing a training example of an image. The input record is parsed into a label and image, and the image is passed through preprocessing steps (cropping, flipping, and so on). Args: raw_record: scalar Tensor tf.string containing a ser...
[ "Parses", "a", "record", "containing", "a", "training", "example", "of", "an", "image", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/imagenet_main.py#L120-L145
[ "def", "parse_record", "(", "raw_record", ",", "is_training", ",", "dtype", ")", ":", "image_buffer", ",", "label", "=", "_parse_example_proto", "(", "raw_record", ")", "image", "=", "imagenet_preprocessing", ".", "preprocess_image", "(", "image_buffer", "=", "ima...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
input_fn
Input function which provides batches for train or eval. Args: is_training: A boolean denoting whether the input is for training. data_dir: The directory containing the input data. batch_size: The number of samples per batch. num_epochs: The number of epochs to repeat the dataset. num_gpus: The n...
image_classification/tensorflow/official/resnet/imagenet_main.py
def input_fn(is_training, data_dir, batch_size, num_epochs=1, num_gpus=None, dtype=tf.float32): """Input function which provides batches for train or eval. Args: is_training: A boolean denoting whether the input is for training. data_dir: The directory containing the input data. batch_size...
def input_fn(is_training, data_dir, batch_size, num_epochs=1, num_gpus=None, dtype=tf.float32): """Input function which provides batches for train or eval. Args: is_training: A boolean denoting whether the input is for training. data_dir: The directory containing the input data. batch_size...
[ "Input", "function", "which", "provides", "batches", "for", "train", "or", "eval", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/imagenet_main.py#L148-L184
[ "def", "input_fn", "(", "is_training", ",", "data_dir", ",", "batch_size", ",", "num_epochs", "=", "1", ",", "num_gpus", "=", "None", ",", "dtype", "=", "tf", ".", "float32", ")", ":", "mlperf_log", ".", "resnet_print", "(", "key", "=", "mlperf_log", "."...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_get_block_sizes
Retrieve the size of each block_layer in the ResNet model. The number of block layers used for the Resnet model varies according to the size of the model. This helper grabs the layer set we want, throwing an error if a non-standard size has been selected. Args: resnet_size: The number of convolutional lay...
image_classification/tensorflow/official/resnet/imagenet_main.py
def _get_block_sizes(resnet_size): """Retrieve the size of each block_layer in the ResNet model. The number of block layers used for the Resnet model varies according to the size of the model. This helper grabs the layer set we want, throwing an error if a non-standard size has been selected. Args: resn...
def _get_block_sizes(resnet_size): """Retrieve the size of each block_layer in the ResNet model. The number of block layers used for the Resnet model varies according to the size of the model. This helper grabs the layer set we want, throwing an error if a non-standard size has been selected. Args: resn...
[ "Retrieve", "the", "size", "of", "each", "block_layer", "in", "the", "ResNet", "model", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/imagenet_main.py#L242-L273
[ "def", "_get_block_sizes", "(", "resnet_size", ")", ":", "choices", "=", "{", "18", ":", "[", "2", ",", "2", ",", "2", ",", "2", "]", ",", "34", ":", "[", "3", ",", "4", ",", "6", ",", "3", "]", ",", "50", ":", "[", "3", ",", "4", ",", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
imagenet_model_fn
Our model_fn for ResNet to be used with our Estimator.
image_classification/tensorflow/official/resnet/imagenet_main.py
def imagenet_model_fn(features, labels, mode, params): """Our model_fn for ResNet to be used with our Estimator.""" # Warmup and higher lr may not be valid for fine tuning with small batches # and smaller numbers of training images. if params['fine_tune']: base_lr = .1 else: base_lr = .128 learnin...
def imagenet_model_fn(features, labels, mode, params): """Our model_fn for ResNet to be used with our Estimator.""" # Warmup and higher lr may not be valid for fine tuning with small batches # and smaller numbers of training images. if params['fine_tune']: base_lr = .1 else: base_lr = .128 learnin...
[ "Our", "model_fn", "for", "ResNet", "to", "be", "used", "with", "our", "Estimator", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/imagenet_main.py#L276-L308
[ "def", "imagenet_model_fn", "(", "features", ",", "labels", ",", "mode", ",", "params", ")", ":", "# Warmup and higher lr may not be valid for fine tuning with small batches", "# and smaller numbers of training images.", "if", "params", "[", "'fine_tune'", "]", ":", "base_lr"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
gnmt_print
Wrapper for MLPerf compliance logging calls. All arguments but 'sync' are passed to mlperf_log.gnmt_print function. If 'sync' is set to True then the wrapper will synchronize all distributed workers. 'sync' should be set to True for all compliance tags that require accurate timing (RUN_START, RUN_STOP e...
rnn_translator/pytorch/seq2seq/utils.py
def gnmt_print(*args, **kwargs): """ Wrapper for MLPerf compliance logging calls. All arguments but 'sync' are passed to mlperf_log.gnmt_print function. If 'sync' is set to True then the wrapper will synchronize all distributed workers. 'sync' should be set to True for all compliance tags that requi...
def gnmt_print(*args, **kwargs): """ Wrapper for MLPerf compliance logging calls. All arguments but 'sync' are passed to mlperf_log.gnmt_print function. If 'sync' is set to True then the wrapper will synchronize all distributed workers. 'sync' should be set to True for all compliance tags that requi...
[ "Wrapper", "for", "MLPerf", "compliance", "logging", "calls", ".", "All", "arguments", "but", "sync", "are", "passed", "to", "mlperf_log", ".", "gnmt_print", "function", ".", "If", "sync", "is", "set", "to", "True", "then", "the", "wrapper", "will", "synchro...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/utils.py#L16-L28
[ "def", "gnmt_print", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "pop", "(", "'sync'", ")", ":", "barrier", "(", ")", "if", "get_rank", "(", ")", "==", "0", ":", "kwargs", "[", "'stack_offset'", "]", "=", "2", "mlper...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
init_lstm_
Initializes weights of LSTM layer. Weights and biases are initialized with uniform(-init_weight, init_weight) distribution. :param lstm: instance of torch.nn.LSTM :param init_weight: range for the uniform initializer
rnn_translator/pytorch/seq2seq/utils.py
def init_lstm_(lstm, init_weight=0.1): """ Initializes weights of LSTM layer. Weights and biases are initialized with uniform(-init_weight, init_weight) distribution. :param lstm: instance of torch.nn.LSTM :param init_weight: range for the uniform initializer """ # Initialize hidden-hid...
def init_lstm_(lstm, init_weight=0.1): """ Initializes weights of LSTM layer. Weights and biases are initialized with uniform(-init_weight, init_weight) distribution. :param lstm: instance of torch.nn.LSTM :param init_weight: range for the uniform initializer """ # Initialize hidden-hid...
[ "Initializes", "weights", "of", "LSTM", "layer", ".", "Weights", "and", "biases", "are", "initialized", "with", "uniform", "(", "-", "init_weight", "init_weight", ")", "distribution", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/utils.py#L31-L57
[ "def", "init_lstm_", "(", "lstm", ",", "init_weight", "=", "0.1", ")", ":", "# Initialize hidden-hidden weights", "init", ".", "uniform_", "(", "lstm", ".", "weight_hh_l0", ".", "data", ",", "-", "init_weight", ",", "init_weight", ")", "# Initialize input-hidden w...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
setup_seeds
Generates seeds from one master_seed. Function returns (worker_seeds, shuffling_seeds), worker_seeds are later used to initialize per-worker random number generators (mostly for dropouts), shuffling_seeds are for RNGs resposible for reshuffling the dataset before each epoch. Seeds are generated on w...
rnn_translator/pytorch/seq2seq/utils.py
def setup_seeds(master_seed, epochs, device): """ Generates seeds from one master_seed. Function returns (worker_seeds, shuffling_seeds), worker_seeds are later used to initialize per-worker random number generators (mostly for dropouts), shuffling_seeds are for RNGs resposible for reshuffling the ...
def setup_seeds(master_seed, epochs, device): """ Generates seeds from one master_seed. Function returns (worker_seeds, shuffling_seeds), worker_seeds are later used to initialize per-worker random number generators (mostly for dropouts), shuffling_seeds are for RNGs resposible for reshuffling the ...
[ "Generates", "seeds", "from", "one", "master_seed", ".", "Function", "returns", "(", "worker_seeds", "shuffling_seeds", ")", "worker_seeds", "are", "later", "used", "to", "initialize", "per", "-", "worker", "random", "number", "generators", "(", "mostly", "for", ...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/utils.py#L86-L127
[ "def", "setup_seeds", "(", "master_seed", ",", "epochs", ",", "device", ")", ":", "if", "master_seed", "is", "None", ":", "# random master seed, random.SystemRandom() uses /dev/urandom on Unix", "master_seed", "=", "random", ".", "SystemRandom", "(", ")", ".", "randin...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
barrier
Works as a temporary distributed barrier, currently pytorch doesn't implement barrier for NCCL backend. Calls all_reduce on dummy tensor and synchronizes with GPU.
rnn_translator/pytorch/seq2seq/utils.py
def barrier(): """ Works as a temporary distributed barrier, currently pytorch doesn't implement barrier for NCCL backend. Calls all_reduce on dummy tensor and synchronizes with GPU. """ if torch.distributed.is_available() and torch.distributed.is_initialized(): torch.distributed.all_red...
def barrier(): """ Works as a temporary distributed barrier, currently pytorch doesn't implement barrier for NCCL backend. Calls all_reduce on dummy tensor and synchronizes with GPU. """ if torch.distributed.is_available() and torch.distributed.is_initialized(): torch.distributed.all_red...
[ "Works", "as", "a", "temporary", "distributed", "barrier", "currently", "pytorch", "doesn", "t", "implement", "barrier", "for", "NCCL", "backend", ".", "Calls", "all_reduce", "on", "dummy", "tensor", "and", "synchronizes", "with", "GPU", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/utils.py#L130-L138
[ "def", "barrier", "(", ")", ":", "if", "torch", ".", "distributed", ".", "is_available", "(", ")", "and", "torch", ".", "distributed", ".", "is_initialized", "(", ")", ":", "torch", ".", "distributed", ".", "all_reduce", "(", "torch", ".", "cuda", ".", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_rank
Gets distributed rank or returns zero if distributed is not initialized.
rnn_translator/pytorch/seq2seq/utils.py
def get_rank(): """ Gets distributed rank or returns zero if distributed is not initialized. """ if torch.distributed.is_available() and torch.distributed.is_initialized(): rank = torch.distributed.get_rank() else: rank = 0 return rank
def get_rank(): """ Gets distributed rank or returns zero if distributed is not initialized. """ if torch.distributed.is_available() and torch.distributed.is_initialized(): rank = torch.distributed.get_rank() else: rank = 0 return rank
[ "Gets", "distributed", "rank", "or", "returns", "zero", "if", "distributed", "is", "not", "initialized", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/utils.py#L141-L149
[ "def", "get_rank", "(", ")", ":", "if", "torch", ".", "distributed", ".", "is_available", "(", ")", "and", "torch", ".", "distributed", ".", "is_initialized", "(", ")", ":", "rank", "=", "torch", ".", "distributed", ".", "get_rank", "(", ")", "else", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_world_size
Gets total number of distributed workers or returns one if distributed is not initialized.
rnn_translator/pytorch/seq2seq/utils.py
def get_world_size(): """ Gets total number of distributed workers or returns one if distributed is not initialized. """ if torch.distributed.is_available() and torch.distributed.is_initialized(): world_size = torch.distributed.get_world_size() else: world_size = 1 return wor...
def get_world_size(): """ Gets total number of distributed workers or returns one if distributed is not initialized. """ if torch.distributed.is_available() and torch.distributed.is_initialized(): world_size = torch.distributed.get_world_size() else: world_size = 1 return wor...
[ "Gets", "total", "number", "of", "distributed", "workers", "or", "returns", "one", "if", "distributed", "is", "not", "initialized", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/utils.py#L152-L161
[ "def", "get_world_size", "(", ")", ":", "if", "torch", ".", "distributed", ".", "is_available", "(", ")", "and", "torch", ".", "distributed", ".", "is_initialized", "(", ")", ":", "world_size", "=", "torch", ".", "distributed", ".", "get_world_size", "(", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
setup_logging
Configures logging. By default logs from all workers are printed to the console, entries are prefixed with "N: " where N is the rank of the worker. Logs printed to the console don't include timestaps. Full logs with timestamps are saved to the log_file file.
rnn_translator/pytorch/seq2seq/utils.py
def setup_logging(log_file=os.devnull): """ Configures logging. By default logs from all workers are printed to the console, entries are prefixed with "N: " where N is the rank of the worker. Logs printed to the console don't include timestaps. Full logs with timestamps are saved to the log_file...
def setup_logging(log_file=os.devnull): """ Configures logging. By default logs from all workers are printed to the console, entries are prefixed with "N: " where N is the rank of the worker. Logs printed to the console don't include timestaps. Full logs with timestamps are saved to the log_file...
[ "Configures", "logging", ".", "By", "default", "logs", "from", "all", "workers", "are", "printed", "to", "the", "console", "entries", "are", "prefixed", "with", "N", ":", "where", "N", "is", "the", "rank", "of", "the", "worker", ".", "Logs", "printed", "...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/utils.py#L187-L217
[ "def", "setup_logging", "(", "log_file", "=", "os", ".", "devnull", ")", ":", "class", "RankFilter", "(", "logging", ".", "Filter", ")", ":", "def", "__init__", "(", "self", ",", "rank", ")", ":", "self", ".", "rank", "=", "rank", "def", "filter", "(...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
set_device
Sets device based on local_rank and returns instance of torch.device. :param cuda: if True: use cuda :param local_rank: local rank of the worker
rnn_translator/pytorch/seq2seq/utils.py
def set_device(cuda, local_rank): """ Sets device based on local_rank and returns instance of torch.device. :param cuda: if True: use cuda :param local_rank: local rank of the worker """ if cuda: torch.cuda.set_device(local_rank) device = torch.device('cuda') else: d...
def set_device(cuda, local_rank): """ Sets device based on local_rank and returns instance of torch.device. :param cuda: if True: use cuda :param local_rank: local rank of the worker """ if cuda: torch.cuda.set_device(local_rank) device = torch.device('cuda') else: d...
[ "Sets", "device", "based", "on", "local_rank", "and", "returns", "instance", "of", "torch", ".", "device", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/utils.py#L220-L232
[ "def", "set_device", "(", "cuda", ",", "local_rank", ")", ":", "if", "cuda", ":", "torch", ".", "cuda", ".", "set_device", "(", "local_rank", ")", "device", "=", "torch", ".", "device", "(", "'cuda'", ")", "else", ":", "device", "=", "torch", ".", "d...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
init_distributed
Initializes distributed backend. :param cuda: (bool) if True initializes nccl backend, if False initializes gloo backend
rnn_translator/pytorch/seq2seq/utils.py
def init_distributed(cuda): """ Initializes distributed backend. :param cuda: (bool) if True initializes nccl backend, if False initializes gloo backend """ world_size = int(os.environ.get('WORLD_SIZE', 1)) distributed = (world_size > 1) if distributed: backend = 'nccl' if c...
def init_distributed(cuda): """ Initializes distributed backend. :param cuda: (bool) if True initializes nccl backend, if False initializes gloo backend """ world_size = int(os.environ.get('WORLD_SIZE', 1)) distributed = (world_size > 1) if distributed: backend = 'nccl' if c...
[ "Initializes", "distributed", "backend", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/utils.py#L235-L249
[ "def", "init_distributed", "(", "cuda", ")", ":", "world_size", "=", "int", "(", "os", ".", "environ", ".", "get", "(", "'WORLD_SIZE'", ",", "1", ")", ")", "distributed", "=", "(", "world_size", ">", "1", ")", "if", "distributed", ":", "backend", "=", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
log_env_info
Prints information about execution environment.
rnn_translator/pytorch/seq2seq/utils.py
def log_env_info(): """ Prints information about execution environment. """ logging.info('Collecting environment information...') env_info = torch.utils.collect_env.get_pretty_env_info() logging.info(f'{env_info}')
def log_env_info(): """ Prints information about execution environment. """ logging.info('Collecting environment information...') env_info = torch.utils.collect_env.get_pretty_env_info() logging.info(f'{env_info}')
[ "Prints", "information", "about", "execution", "environment", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/utils.py#L252-L258
[ "def", "log_env_info", "(", ")", ":", "logging", ".", "info", "(", "'Collecting environment information...'", ")", "env_info", "=", "torch", ".", "utils", ".", "collect_env", ".", "get_pretty_env_info", "(", ")", "logging", ".", "info", "(", "f'{env_info}'", ")"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
debug_tensor
Simple utility which helps with debugging. Takes a tensor and outputs: min, max, avg, std, number of NaNs, number of INFs. :param tensor: torch tensor :param name: name of the tensor (only for logging)
rnn_translator/pytorch/seq2seq/utils.py
def debug_tensor(tensor, name): """ Simple utility which helps with debugging. Takes a tensor and outputs: min, max, avg, std, number of NaNs, number of INFs. :param tensor: torch tensor :param name: name of the tensor (only for logging) """ logging.info(name) tensor = tensor.detach...
def debug_tensor(tensor, name): """ Simple utility which helps with debugging. Takes a tensor and outputs: min, max, avg, std, number of NaNs, number of INFs. :param tensor: torch tensor :param name: name of the tensor (only for logging) """ logging.info(name) tensor = tensor.detach...
[ "Simple", "utility", "which", "helps", "with", "debugging", ".", "Takes", "a", "tensor", "and", "outputs", ":", "min", "max", "avg", "std", "number", "of", "NaNs", "number", "of", "INFs", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/utils.py#L338-L351
[ "def", "debug_tensor", "(", "tensor", ",", "name", ")", ":", "logging", ".", "info", "(", "name", ")", "tensor", "=", "tensor", ".", "detach", "(", ")", ".", "float", "(", ")", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "logging", ".", "info",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
AverageMeter.reduce
Reduces average value over all workers. :param op: 'sum' or 'mean', reduction operator
rnn_translator/pytorch/seq2seq/utils.py
def reduce(self, op): """ Reduces average value over all workers. :param op: 'sum' or 'mean', reduction operator """ if op not in ('sum', 'mean'): raise NotImplementedError distributed = (get_world_size() > 1) if distributed: # Backward/f...
def reduce(self, op): """ Reduces average value over all workers. :param op: 'sum' or 'mean', reduction operator """ if op not in ('sum', 'mean'): raise NotImplementedError distributed = (get_world_size() > 1) if distributed: # Backward/f...
[ "Reduces", "average", "value", "over", "all", "workers", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/utils.py#L293-L335
[ "def", "reduce", "(", "self", ",", "op", ")", ":", "if", "op", "not", "in", "(", "'sum'", ",", "'mean'", ")", ":", "raise", "NotImplementedError", "distributed", "=", "(", "get_world_size", "(", ")", ">", "1", ")", "if", "distributed", ":", "# Backward...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
build_dataset
Arguments: dataset_list (list[str]): Contains the names of the datasets, i.e., coco_2014_trian, coco_2014_val, etc transforms (callable): transforms to apply to each (image, target) sample dataset_catalog (DatasetCatalog): contains the information on how to construct a da...
object_detection/pytorch/maskrcnn_benchmark/data/build.py
def build_dataset(dataset_list, transforms, dataset_catalog, is_train=True): """ Arguments: dataset_list (list[str]): Contains the names of the datasets, i.e., coco_2014_trian, coco_2014_val, etc transforms (callable): transforms to apply to each (image, target) sample datase...
def build_dataset(dataset_list, transforms, dataset_catalog, is_train=True): """ Arguments: dataset_list (list[str]): Contains the names of the datasets, i.e., coco_2014_trian, coco_2014_val, etc transforms (callable): transforms to apply to each (image, target) sample datase...
[ "Arguments", ":", "dataset_list", "(", "list", "[", "str", "]", ")", ":", "Contains", "the", "names", "of", "the", "datasets", "i", ".", "e", ".", "coco_2014_trian", "coco_2014_val", "etc", "transforms", "(", "callable", ")", ":", "transforms", "to", "appl...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/data/build.py#L17-L58
[ "def", "build_dataset", "(", "dataset_list", ",", "transforms", ",", "dataset_catalog", ",", "is_train", "=", "True", ")", ":", "if", "not", "isinstance", "(", "dataset_list", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "RuntimeError", "(", "\"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
to_image_list
tensors can be an ImageList, a torch.Tensor or an iterable of Tensors. It can't be a numpy array. When tensors is an iterable of Tensors, it pads the Tensors with zeros so that they have the same shape
object_detection/pytorch/maskrcnn_benchmark/structures/image_list.py
def to_image_list(tensors, size_divisible=0): """ tensors can be an ImageList, a torch.Tensor or an iterable of Tensors. It can't be a numpy array. When tensors is an iterable of Tensors, it pads the Tensors with zeros so that they have the same shape """ if isinstance(tensors, torch.Ten...
def to_image_list(tensors, size_divisible=0): """ tensors can be an ImageList, a torch.Tensor or an iterable of Tensors. It can't be a numpy array. When tensors is an iterable of Tensors, it pads the Tensors with zeros so that they have the same shape """ if isinstance(tensors, torch.Ten...
[ "tensors", "can", "be", "an", "ImageList", "a", "torch", ".", "Tensor", "or", "an", "iterable", "of", "Tensors", ".", "It", "can", "t", "be", "a", "numpy", "array", ".", "When", "tensors", "is", "an", "iterable", "of", "Tensors", "it", "pads", "the", ...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/structures/image_list.py#L29-L70
[ "def", "to_image_list", "(", "tensors", ",", "size_divisible", "=", "0", ")", ":", "if", "isinstance", "(", "tensors", ",", "torch", ".", "Tensor", ")", "and", "size_divisible", ">", "0", ":", "tensors", "=", "[", "tensors", "]", "if", "isinstance", "(",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
ROIKeypointHead.forward
Arguments: features (list[Tensor]): feature-maps from possibly several levels proposals (list[BoxList]): proposal boxes targets (list[BoxList], optional): the ground-truth targets. Returns: x (Tensor): the result of the feature extractor proposals (li...
object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/keypoint_head/keypoint_head.py
def forward(self, features, proposals, targets=None): """ Arguments: features (list[Tensor]): feature-maps from possibly several levels proposals (list[BoxList]): proposal boxes targets (list[BoxList], optional): the ground-truth targets. Returns: ...
def forward(self, features, proposals, targets=None): """ Arguments: features (list[Tensor]): feature-maps from possibly several levels proposals (list[BoxList]): proposal boxes targets (list[BoxList], optional): the ground-truth targets. Returns: ...
[ "Arguments", ":", "features", "(", "list", "[", "Tensor", "]", ")", ":", "feature", "-", "maps", "from", "possibly", "several", "levels", "proposals", "(", "list", "[", "BoxList", "]", ")", ":", "proposal", "boxes", "targets", "(", "list", "[", "BoxList"...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/keypoint_head/keypoint_head.py#L18-L46
[ "def", "forward", "(", "self", ",", "features", ",", "proposals", ",", "targets", "=", "None", ")", ":", "if", "self", ".", "training", ":", "with", "torch", ".", "no_grad", "(", ")", ":", "proposals", "=", "self", ".", "loss_evaluator", ".", "subsampl...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_inference_input
Set up placeholders for input features/labels. Returns the feature, output tensors that get passed into model_fn.
reinforcement/tensorflow/minigo/dual_net.py
def get_inference_input(): """Set up placeholders for input features/labels. Returns the feature, output tensors that get passed into model_fn.""" return (tf.placeholder(tf.float32, [None, go.N, go.N, features_lib.NEW_FEATURES_PLANES], name='pos_tensor'...
def get_inference_input(): """Set up placeholders for input features/labels. Returns the feature, output tensors that get passed into model_fn.""" return (tf.placeholder(tf.float32, [None, go.N, go.N, features_lib.NEW_FEATURES_PLANES], name='pos_tensor'...
[ "Set", "up", "placeholders", "for", "input", "features", "/", "labels", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/dual_net.py#L208-L216
[ "def", "get_inference_input", "(", ")", ":", "return", "(", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "[", "None", ",", "go", ".", "N", ",", "go", ".", "N", ",", "features_lib", ".", "NEW_FEATURES_PLANES", "]", ",", "name", "=", "'pos...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
model_fn
Create the model for estimator api Args: features: tensor with shape [BATCH_SIZE, go.N, go.N, features_lib.NEW_FEATURES_PLANES] labels: dict from string to tensor with shape 'pi_tensor': [BATCH_SIZE, go.N * go.N + 1] 'value_tensor': [BATCH_SIZE] mode: a t...
reinforcement/tensorflow/minigo/dual_net.py
def model_fn(features, labels, mode, params): """ Create the model for estimator api Args: features: tensor with shape [BATCH_SIZE, go.N, go.N, features_lib.NEW_FEATURES_PLANES] labels: dict from string to tensor with shape 'pi_tensor': [BATCH_SIZE, go.N * go.N + 1] ...
def model_fn(features, labels, mode, params): """ Create the model for estimator api Args: features: tensor with shape [BATCH_SIZE, go.N, go.N, features_lib.NEW_FEATURES_PLANES] labels: dict from string to tensor with shape 'pi_tensor': [BATCH_SIZE, go.N * go.N + 1] ...
[ "Create", "the", "model", "for", "estimator", "api" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/dual_net.py#L219-L376
[ "def", "model_fn", "(", "features", ",", "labels", ",", "mode", ",", "params", ")", ":", "policy_output", ",", "value_output", ",", "logits", "=", "model_inference_fn", "(", "features", ",", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAI...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
model_inference_fn
Builds just the inference part of the model graph. Args: features: input features tensor. training: True if the model is training. params: A dictionary Returns: (policy_output, value_output, logits) tuple of tensors.
reinforcement/tensorflow/minigo/dual_net.py
def model_inference_fn(features, training, params): """Builds just the inference part of the model graph. Args: features: input features tensor. training: True if the model is training. params: A dictionary Returns: (policy_output, value_output, logits) tuple of tensors. ...
def model_inference_fn(features, training, params): """Builds just the inference part of the model graph. Args: features: input features tensor. training: True if the model is training. params: A dictionary Returns: (policy_output, value_output, logits) tuple of tensors. ...
[ "Builds", "just", "the", "inference", "part", "of", "the", "model", "graph", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/dual_net.py#L379-L496
[ "def", "model_inference_fn", "(", "features", ",", "training", ",", "params", ")", ":", "mg_batchn", "=", "functools", ".", "partial", "(", "tf", ".", "layers", ".", "batch_normalization", ",", "axis", "=", "-", "1", ",", "momentum", "=", ".95", ",", "ep...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
tpu_model_inference_fn
Builds the model graph suitable for running on TPU. It does two things: 1) Mark all weights as constant, which improves TPU inference performance because it prevents the weights being transferred to the TPU every call to Session.run(). 2) Adds constant to the graph with a unique value and...
reinforcement/tensorflow/minigo/dual_net.py
def tpu_model_inference_fn(features): """Builds the model graph suitable for running on TPU. It does two things: 1) Mark all weights as constant, which improves TPU inference performance because it prevents the weights being transferred to the TPU every call to Session.run(). 2) Adds ...
def tpu_model_inference_fn(features): """Builds the model graph suitable for running on TPU. It does two things: 1) Mark all weights as constant, which improves TPU inference performance because it prevents the weights being transferred to the TPU every call to Session.run(). 2) Adds ...
[ "Builds", "the", "model", "graph", "suitable", "for", "running", "on", "TPU", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/dual_net.py#L499-L523
[ "def", "tpu_model_inference_fn", "(", "features", ")", ":", "def", "custom_getter", "(", "getter", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "tf", ".", "control_dependencies", "(", "None", ")", ":", "return", "tf", ".", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
bootstrap
Initialize a tf.Estimator run with random initial weights.
reinforcement/tensorflow/minigo/dual_net.py
def bootstrap(): """Initialize a tf.Estimator run with random initial weights.""" # a bit hacky - forge an initial checkpoint with the name that subsequent # Estimator runs will expect to find. # # Estimator will do this automatically when you call train(), but calling # train() requires data, a...
def bootstrap(): """Initialize a tf.Estimator run with random initial weights.""" # a bit hacky - forge an initial checkpoint with the name that subsequent # Estimator runs will expect to find. # # Estimator will do this automatically when you call train(), but calling # train() requires data, a...
[ "Initialize", "a", "tf", ".", "Estimator", "run", "with", "random", "initial", "weights", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/dual_net.py#L582-L599
[ "def", "bootstrap", "(", ")", ":", "# a bit hacky - forge an initial checkpoint with the name that subsequent", "# Estimator runs will expect to find.", "#", "# Estimator will do this automatically when you call train(), but calling", "# train() requires data, and I didn't feel like creating train...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
export_model
Take the latest checkpoint and copy it to model_path. Assumes that all relevant model files are prefixed by the same name. (For example, foo.index, foo.meta and foo.data-00000-of-00001). Args: model_path: The path (can be a gs:// path) to export model
reinforcement/tensorflow/minigo/dual_net.py
def export_model(model_path): """Take the latest checkpoint and copy it to model_path. Assumes that all relevant model files are prefixed by the same name. (For example, foo.index, foo.meta and foo.data-00000-of-00001). Args: model_path: The path (can be a gs:// path) to export model """ ...
def export_model(model_path): """Take the latest checkpoint and copy it to model_path. Assumes that all relevant model files are prefixed by the same name. (For example, foo.index, foo.meta and foo.data-00000-of-00001). Args: model_path: The path (can be a gs:// path) to export model """ ...
[ "Take", "the", "latest", "checkpoint", "and", "copy", "it", "to", "model_path", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/dual_net.py#L602-L619
[ "def", "export_model", "(", "model_path", ")", ":", "estimator", "=", "tf", ".", "estimator", ".", "Estimator", "(", "model_fn", ",", "model_dir", "=", "FLAGS", ".", "work_dir", ",", "params", "=", "FLAGS", ".", "flag_values_dict", "(", ")", ")", "latest_c...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
freeze_graph_tpu
Custom freeze_graph implementation for Cloud TPU.
reinforcement/tensorflow/minigo/dual_net.py
def freeze_graph_tpu(model_path): """Custom freeze_graph implementation for Cloud TPU.""" assert model_path assert FLAGS.tpu_name if FLAGS.tpu_name.startswith('grpc://'): tpu_grpc_url = FLAGS.tpu_name else: tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver( ...
def freeze_graph_tpu(model_path): """Custom freeze_graph implementation for Cloud TPU.""" assert model_path assert FLAGS.tpu_name if FLAGS.tpu_name.startswith('grpc://'): tpu_grpc_url = FLAGS.tpu_name else: tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver( ...
[ "Custom", "freeze_graph", "implementation", "for", "Cloud", "TPU", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/dual_net.py#L630-L671
[ "def", "freeze_graph_tpu", "(", "model_path", ")", ":", "assert", "model_path", "assert", "FLAGS", ".", "tpu_name", "if", "FLAGS", ".", "tpu_name", ".", "startswith", "(", "'grpc://'", ")", ":", "tpu_grpc_url", "=", "FLAGS", ".", "tpu_name", "else", ":", "tp...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
DualNetwork.initialize_weights
Initialize the weights from the given save_file. Assumes that the graph has been constructed, and the save_file contains weights that match the graph. Used to set the weights to a different version of the player without redifining the entire graph.
reinforcement/tensorflow/minigo/dual_net.py
def initialize_weights(self, save_file): """Initialize the weights from the given save_file. Assumes that the graph has been constructed, and the save_file contains weights that match the graph. Used to set the weights to a different version of the player without redifining the e...
def initialize_weights(self, save_file): """Initialize the weights from the given save_file. Assumes that the graph has been constructed, and the save_file contains weights that match the graph. Used to set the weights to a different version of the player without redifining the e...
[ "Initialize", "the", "weights", "from", "the", "given", "save_file", ".", "Assumes", "that", "the", "graph", "has", "been", "constructed", "and", "the", "save_file", "contains", "weights", "that", "match", "the", "graph", ".", "Used", "to", "set", "the", "we...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/dual_net.py#L182-L188
[ "def", "initialize_weights", "(", "self", ",", "save_file", ")", ":", "tf", ".", "train", ".", "Saver", "(", ")", ".", "restore", "(", "self", ".", "sess", ",", "save_file", ")" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
parse_helpfull_output
Parses the output of --helpfull. Args: help_output: str, the full output of --helpfull. Returns: A set of flags that are valid flags.
reinforcement/tensorflow/minigo/mask_flags.py
def parse_helpfull_output(help_output, regex=FLAG_HELP_RE_PY): """Parses the output of --helpfull. Args: help_output: str, the full output of --helpfull. Returns: A set of flags that are valid flags. """ valid_flags = set() for _, no_prefix, flag_name in regex.findall(help_outp...
def parse_helpfull_output(help_output, regex=FLAG_HELP_RE_PY): """Parses the output of --helpfull. Args: help_output: str, the full output of --helpfull. Returns: A set of flags that are valid flags. """ valid_flags = set() for _, no_prefix, flag_name in regex.findall(help_outp...
[ "Parses", "the", "output", "of", "--", "helpfull", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/mask_flags.py#L50-L64
[ "def", "parse_helpfull_output", "(", "help_output", ",", "regex", "=", "FLAG_HELP_RE_PY", ")", ":", "valid_flags", "=", "set", "(", ")", "for", "_", ",", "no_prefix", ",", "flag_name", "in", "regex", ".", "findall", "(", "help_output", ")", ":", "valid_flags...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
filter_flags
Return the subset of `parsed_flags` that are found in the list `valid_flags`
reinforcement/tensorflow/minigo/mask_flags.py
def filter_flags(parsed_flags, valid_flags): """Return the subset of `parsed_flags` that are found in the list `valid_flags`""" def valid_argv(argv): """Figures out if a flag parsed from the flagfile matches a flag in the command about to be run.""" flagname_match = FLAG_RE.match(argv) ...
def filter_flags(parsed_flags, valid_flags): """Return the subset of `parsed_flags` that are found in the list `valid_flags`""" def valid_argv(argv): """Figures out if a flag parsed from the flagfile matches a flag in the command about to be run.""" flagname_match = FLAG_RE.match(argv) ...
[ "Return", "the", "subset", "of", "parsed_flags", "that", "are", "found", "in", "the", "list", "valid_flags" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/mask_flags.py#L67-L77
[ "def", "filter_flags", "(", "parsed_flags", ",", "valid_flags", ")", ":", "def", "valid_argv", "(", "argv", ")", ":", "\"\"\"Figures out if a flag parsed from the flagfile matches a flag in\n the command about to be run.\"\"\"", "flagname_match", "=", "FLAG_RE", ".", "ma...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
prepare_subprocess_cmd
Prepares a subprocess command by running --helpfull and masking flags. Args: subprocess_cmd: List[str], what would be passed into subprocess.call() i.e. ['python', 'train.py', '--flagfile=flags'] Returns: ['python', 'train.py', '--train_flag=blah', '--more_flags']
reinforcement/tensorflow/minigo/mask_flags.py
def prepare_subprocess_cmd(subprocess_cmd): """Prepares a subprocess command by running --helpfull and masking flags. Args: subprocess_cmd: List[str], what would be passed into subprocess.call() i.e. ['python', 'train.py', '--flagfile=flags'] Returns: ['python', 'train.py', '--...
def prepare_subprocess_cmd(subprocess_cmd): """Prepares a subprocess command by running --helpfull and masking flags. Args: subprocess_cmd: List[str], what would be passed into subprocess.call() i.e. ['python', 'train.py', '--flagfile=flags'] Returns: ['python', 'train.py', '--...
[ "Prepares", "a", "subprocess", "command", "by", "running", "--", "helpfull", "and", "masking", "flags", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/mask_flags.py#L80-L100
[ "def", "prepare_subprocess_cmd", "(", "subprocess_cmd", ")", ":", "help_cmd", "=", "subprocess_cmd", "+", "[", "'--helpfull'", "]", "help_output", "=", "subprocess", ".", "run", "(", "help_cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", ".", "stdout"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
run
Prepare and run a subprocess cmd, returning a CompletedProcess.
reinforcement/tensorflow/minigo/mask_flags.py
def run(cmd): """Prepare and run a subprocess cmd, returning a CompletedProcess.""" print("Preparing the following cmd:") cmd = prepare_subprocess_cmd(cmd) print("Running the following cmd:") print('\n'.join(cmd)) return subprocess.run(cmd, stdout=sys.stdout, stderr=sys.stderr)
def run(cmd): """Prepare and run a subprocess cmd, returning a CompletedProcess.""" print("Preparing the following cmd:") cmd = prepare_subprocess_cmd(cmd) print("Running the following cmd:") print('\n'.join(cmd)) return subprocess.run(cmd, stdout=sys.stdout, stderr=sys.stderr)
[ "Prepare", "and", "run", "a", "subprocess", "cmd", "returning", "a", "CompletedProcess", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/mask_flags.py#L103-L109
[ "def", "run", "(", "cmd", ")", ":", "print", "(", "\"Preparing the following cmd:\"", ")", "cmd", "=", "prepare_subprocess_cmd", "(", "cmd", ")", "print", "(", "\"Running the following cmd:\"", ")", "print", "(", "'\\n'", ".", "join", "(", "cmd", ")", ")", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
checked_run
Prepare and run a subprocess cmd, checking for successful completion.
reinforcement/tensorflow/minigo/mask_flags.py
def checked_run(cmd): """Prepare and run a subprocess cmd, checking for successful completion.""" completed_process = run(cmd) if completed_process.returncode > 0: print("Command failed! Hanging around in case someone needs a " "docker connection. (Ctrl-C to quit now)") time.s...
def checked_run(cmd): """Prepare and run a subprocess cmd, checking for successful completion.""" completed_process = run(cmd) if completed_process.returncode > 0: print("Command failed! Hanging around in case someone needs a " "docker connection. (Ctrl-C to quit now)") time.s...
[ "Prepare", "and", "run", "a", "subprocess", "cmd", "checking", "for", "successful", "completion", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/mask_flags.py#L112-L120
[ "def", "checked_run", "(", "cmd", ")", ":", "completed_process", "=", "run", "(", "cmd", ")", "if", "completed_process", ".", "returncode", ">", "0", ":", "print", "(", "\"Command failed! Hanging around in case someone needs a \"", "\"docker connection. (Ctrl-C to quit n...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
process_record_dataset
Given a Dataset with raw records, return an iterator over the records. Args: dataset: A Dataset representing raw records is_training: A boolean denoting whether the input is for training. batch_size: The number of samples per batch. shuffle_buffer: The buffer size to use when shuffling records. A lar...
image_classification/tensorflow/official/resnet/resnet_run_loop.py
def process_record_dataset(dataset, is_training, batch_size, shuffle_buffer, parse_record_fn, num_epochs=1, num_gpus=None, examples_per_epoch=None, dtype=tf.float32): """Given a Dataset with raw records, return an iterator over the records. Args: dataset: A...
def process_record_dataset(dataset, is_training, batch_size, shuffle_buffer, parse_record_fn, num_epochs=1, num_gpus=None, examples_per_epoch=None, dtype=tf.float32): """Given a Dataset with raw records, return an iterator over the records. Args: dataset: A...
[ "Given", "a", "Dataset", "with", "raw", "records", "return", "an", "iterator", "over", "the", "records", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/resnet_run_loop.py#L46-L99
[ "def", "process_record_dataset", "(", "dataset", ",", "is_training", ",", "batch_size", ",", "shuffle_buffer", ",", "parse_record_fn", ",", "num_epochs", "=", "1", ",", "num_gpus", "=", "None", ",", "examples_per_epoch", "=", "None", ",", "dtype", "=", "tf", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_synth_input_fn
Returns an input function that returns a dataset with zeroes. This is useful in debugging input pipeline performance, as it removes all elements of file reading and image preprocessing. Args: height: Integer height that will be used to create a fake image tensor. width: Integer width that will be used t...
image_classification/tensorflow/official/resnet/resnet_run_loop.py
def get_synth_input_fn(height, width, num_channels, num_classes): """Returns an input function that returns a dataset with zeroes. This is useful in debugging input pipeline performance, as it removes all elements of file reading and image preprocessing. Args: height: Integer height that will be used to c...
def get_synth_input_fn(height, width, num_channels, num_classes): """Returns an input function that returns a dataset with zeroes. This is useful in debugging input pipeline performance, as it removes all elements of file reading and image preprocessing. Args: height: Integer height that will be used to c...
[ "Returns", "an", "input", "function", "that", "returns", "a", "dataset", "with", "zeroes", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/resnet_run_loop.py#L102-L124
[ "def", "get_synth_input_fn", "(", "height", ",", "width", ",", "num_channels", ",", "num_classes", ")", ":", "def", "input_fn", "(", "is_training", ",", "data_dir", ",", "batch_size", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=un...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
learning_rate_with_decay
Get a learning rate that decays step-wise as training progresses. Args: batch_size: the number of examples processed in each training batch. batch_denom: this value will be used to scale the base learning rate. `0.1 * batch size` is divided by this number, such that when batch_denom == batch_size...
image_classification/tensorflow/official/resnet/resnet_run_loop.py
def learning_rate_with_decay( batch_size, batch_denom, num_images, boundary_epochs, decay_rates, base_lr=0.1, enable_lars=False): """Get a learning rate that decays step-wise as training progresses. Args: batch_size: the number of examples processed in each training batch. batch_denom: this value w...
def learning_rate_with_decay( batch_size, batch_denom, num_images, boundary_epochs, decay_rates, base_lr=0.1, enable_lars=False): """Get a learning rate that decays step-wise as training progresses. Args: batch_size: the number of examples processed in each training batch. batch_denom: this value w...
[ "Get", "a", "learning", "rate", "that", "decays", "step", "-", "wise", "as", "training", "progresses", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/resnet_run_loop.py#L130-L218
[ "def", "learning_rate_with_decay", "(", "batch_size", ",", "batch_denom", ",", "num_images", ",", "boundary_epochs", ",", "decay_rates", ",", "base_lr", "=", "0.1", ",", "enable_lars", "=", "False", ")", ":", "initial_learning_rate", "=", "base_lr", "*", "batch_si...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
resnet_model_fn
Shared functionality for different resnet model_fns. Initializes the ResnetModel representing the model layers and uses that model to build the necessary EstimatorSpecs for the `mode` in question. For training, this means building losses, the optimizer, and the train op that get passed into the EstimatorSpec. ...
image_classification/tensorflow/official/resnet/resnet_run_loop.py
def resnet_model_fn(features, labels, mode, model_class, resnet_size, weight_decay, learning_rate_fn, momentum, data_format, version, loss_scale, loss_filter_fn=None, dtype=resnet_model.DEFAULT_DTYPE, label_smoothing=0.0, enable_lars=False)...
def resnet_model_fn(features, labels, mode, model_class, resnet_size, weight_decay, learning_rate_fn, momentum, data_format, version, loss_scale, loss_filter_fn=None, dtype=resnet_model.DEFAULT_DTYPE, label_smoothing=0.0, enable_lars=False)...
[ "Shared", "functionality", "for", "different", "resnet", "model_fns", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/resnet_run_loop.py#L221-L402
[ "def", "resnet_model_fn", "(", "features", ",", "labels", ",", "mode", ",", "model_class", ",", "resnet_size", ",", "weight_decay", ",", "learning_rate_fn", ",", "momentum", ",", "data_format", ",", "version", ",", "loss_scale", ",", "loss_filter_fn", "=", "None...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
per_device_batch_size
For multi-gpu, batch-size must be a multiple of the number of GPUs. Note that this should eventually be handled by DistributionStrategies directly. Multi-GPU support is currently experimental, however, so doing the work here until that feature is in place. Args: batch_size: Global batch size to be divided...
image_classification/tensorflow/official/resnet/resnet_run_loop.py
def per_device_batch_size(batch_size, num_gpus): """For multi-gpu, batch-size must be a multiple of the number of GPUs. Note that this should eventually be handled by DistributionStrategies directly. Multi-GPU support is currently experimental, however, so doing the work here until that feature is in place. ...
def per_device_batch_size(batch_size, num_gpus): """For multi-gpu, batch-size must be a multiple of the number of GPUs. Note that this should eventually be handled by DistributionStrategies directly. Multi-GPU support is currently experimental, however, so doing the work here until that feature is in place. ...
[ "For", "multi", "-", "gpu", "batch", "-", "size", "must", "be", "a", "multiple", "of", "the", "number", "of", "GPUs", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/resnet_run_loop.py#L405-L433
[ "def", "per_device_batch_size", "(", "batch_size", ",", "num_gpus", ")", ":", "if", "num_gpus", "<=", "1", ":", "return", "batch_size", "remainder", "=", "batch_size", "%", "num_gpus", "if", "remainder", ":", "err", "=", "(", "'When running with multiple GPUs, bat...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
resnet_main
Shared main loop for ResNet Models. Args: flags: FLAGS object that contains the params for running. See ResnetArgParser for created flags. model_function: the function that instantiates the Model and builds the ops for train/eval. This will be passed directly into the estimator. input_functio...
image_classification/tensorflow/official/resnet/resnet_run_loop.py
def resnet_main(seed, flags, model_function, input_function, shape=None): """Shared main loop for ResNet Models. Args: flags: FLAGS object that contains the params for running. See ResnetArgParser for created flags. model_function: the function that instantiates the Model and builds the ops for...
def resnet_main(seed, flags, model_function, input_function, shape=None): """Shared main loop for ResNet Models. Args: flags: FLAGS object that contains the params for running. See ResnetArgParser for created flags. model_function: the function that instantiates the Model and builds the ops for...
[ "Shared", "main", "loop", "for", "ResNet", "Models", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/resnet_run_loop.py#L436-L589
[ "def", "resnet_main", "(", "seed", ",", "flags", ",", "model_function", ",", "input_function", ",", "shape", "=", "None", ")", ":", "mlperf_log", ".", "resnet_print", "(", "key", "=", "mlperf_log", ".", "RUN_START", ")", "# Using the Winograd non-fused algorithms ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
compute_ratings
Returns the tuples of (model_id, rating, sigma) N.B. that `model_id` here is NOT the model number in the run 'data' is tuples of (winner, loser) model_ids (not model numbers)
reinforcement/tensorflow/minigo/ratings/ratings.py
def compute_ratings(data=None): """ Returns the tuples of (model_id, rating, sigma) N.B. that `model_id` here is NOT the model number in the run 'data' is tuples of (winner, loser) model_ids (not model numbers) """ if data is None: with sqlite3.connect("ratings.db") as db: data ...
def compute_ratings(data=None): """ Returns the tuples of (model_id, rating, sigma) N.B. that `model_id` here is NOT the model number in the run 'data' is tuples of (winner, loser) model_ids (not model numbers) """ if data is None: with sqlite3.connect("ratings.db") as db: data ...
[ "Returns", "the", "tuples", "of", "(", "model_id", "rating", "sigma", ")", "N", ".", "B", ".", "that", "model_id", "here", "is", "NOT", "the", "model", "number", "in", "the", "run" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/ratings/ratings.py#L165-L208
[ "def", "compute_ratings", "(", "data", "=", "None", ")", ":", "if", "data", "is", "None", ":", "with", "sqlite3", ".", "connect", "(", "\"ratings.db\"", ")", "as", "db", ":", "data", "=", "db", ".", "execute", "(", "\"select model_winner, model_loser from wi...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
suggest_pairs
Find the maximally interesting pairs of players to match up First, sort the ratings by uncertainty. Then, take the ten highest players with the highest uncertainty For each of them, call them `p1` Sort all the models by their distance from p1's rating and take the 20 nearest rated models. ('candidat...
reinforcement/tensorflow/minigo/ratings/ratings.py
def suggest_pairs(top_n=10, per_n=3, ignore_before=300): """ Find the maximally interesting pairs of players to match up First, sort the ratings by uncertainty. Then, take the ten highest players with the highest uncertainty For each of them, call them `p1` Sort all the models by their distance from...
def suggest_pairs(top_n=10, per_n=3, ignore_before=300): """ Find the maximally interesting pairs of players to match up First, sort the ratings by uncertainty. Then, take the ten highest players with the highest uncertainty For each of them, call them `p1` Sort all the models by their distance from...
[ "Find", "the", "maximally", "interesting", "pairs", "of", "players", "to", "match", "up", "First", "sort", "the", "ratings", "by", "uncertainty", ".", "Then", "take", "the", "ten", "highest", "players", "with", "the", "highest", "uncertainty", "For", "each", ...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/ratings/ratings.py#L233-L268
[ "def", "suggest_pairs", "(", "top_n", "=", "10", ",", "per_n", "=", "3", ",", "ignore_before", "=", "300", ")", ":", "db", "=", "sqlite3", ".", "connect", "(", "\"ratings.db\"", ")", "data", "=", "db", ".", "execute", "(", "\"select model_winner, model_los...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
time_recommendation
Given the current move number and the 'desired' seconds per move, return how much time should actually be used. This is intended specifically for CGOS time controls, which has an absolute 15-minute time limit. The strategy is to spend the maximum possible moves using seconds_per_move, and then switch t...
reinforcement/tensorflow/minigo/strategies.py
def time_recommendation(move_num, seconds_per_move=5, time_limit=15 * 60, decay_factor=0.98): """Given the current move number and the 'desired' seconds per move, return how much time should actually be used. This is intended specifically for CGOS time controls, which has an absolute...
def time_recommendation(move_num, seconds_per_move=5, time_limit=15 * 60, decay_factor=0.98): """Given the current move number and the 'desired' seconds per move, return how much time should actually be used. This is intended specifically for CGOS time controls, which has an absolute...
[ "Given", "the", "current", "move", "number", "and", "the", "desired", "seconds", "per", "move", "return", "how", "much", "time", "should", "actually", "be", "used", ".", "This", "is", "intended", "specifically", "for", "CGOS", "time", "controls", "which", "h...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/strategies.py#L54-L80
[ "def", "time_recommendation", "(", "move_num", ",", "seconds_per_move", "=", "5", ",", "time_limit", "=", "15", "*", "60", ",", "decay_factor", "=", "0.98", ")", ":", "# Divide by two since you only play half the moves in a game.", "player_move_num", "=", "move_num", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
MCTSPlayer.suggest_move
Used for playing a single game. For parallel play, use initialize_move, select_leaf, incorporate_results, and pick_move
reinforcement/tensorflow/minigo/strategies.py
def suggest_move(self, position): """Used for playing a single game. For parallel play, use initialize_move, select_leaf, incorporate_results, and pick_move """ start = time.time() if self.timed_match: while time.time() - start < self.seconds_per_move: ...
def suggest_move(self, position): """Used for playing a single game. For parallel play, use initialize_move, select_leaf, incorporate_results, and pick_move """ start = time.time() if self.timed_match: while time.time() - start < self.seconds_per_move: ...
[ "Used", "for", "playing", "a", "single", "game", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/strategies.py#L123-L149
[ "def", "suggest_move", "(", "self", ",", "position", ")", ":", "start", "=", "time", ".", "time", "(", ")", "if", "self", ".", "timed_match", ":", "while", "time", ".", "time", "(", ")", "-", "start", "<", "self", ".", "seconds_per_move", ":", "self"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
MCTSPlayer.play_move
Notable side effects: - finalizes the probability distribution according to this roots visit counts into the class' running tally, `searches_pi` - Makes the node associated with this move the root, for future `inject_noise` calls.
reinforcement/tensorflow/minigo/strategies.py
def play_move(self, c): """Notable side effects: - finalizes the probability distribution according to this roots visit counts into the class' running tally, `searches_pi` - Makes the node associated with this move the root, for future `inject_noise` calls. """ ...
def play_move(self, c): """Notable side effects: - finalizes the probability distribution according to this roots visit counts into the class' running tally, `searches_pi` - Makes the node associated with this move the root, for future `inject_noise` calls. """ ...
[ "Notable", "side", "effects", ":", "-", "finalizes", "the", "probability", "distribution", "according", "to", "this", "roots", "visit", "counts", "into", "the", "class", "running", "tally", "searches_pi", "-", "Makes", "the", "node", "associated", "with", "this"...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/strategies.py#L151-L173
[ "def", "play_move", "(", "self", ",", "c", ")", ":", "if", "not", "self", ".", "two_player_mode", ":", "self", ".", "searches_pi", ".", "append", "(", "self", ".", "root", ".", "children_as_pi", "(", "self", ".", "root", ".", "position", ".", "n", "<...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
MCTSPlayer.pick_move
Picks a move to play, based on MCTS readout statistics. Highest N is most robust indicator. In the early stage of the game, pick a move weighted by visit count; later on, pick the absolute max.
reinforcement/tensorflow/minigo/strategies.py
def pick_move(self): """Picks a move to play, based on MCTS readout statistics. Highest N is most robust indicator. In the early stage of the game, pick a move weighted by visit count; later on, pick the absolute max.""" if self.root.position.n >= self.temp_threshold: fcoord...
def pick_move(self): """Picks a move to play, based on MCTS readout statistics. Highest N is most robust indicator. In the early stage of the game, pick a move weighted by visit count; later on, pick the absolute max.""" if self.root.position.n >= self.temp_threshold: fcoord...
[ "Picks", "a", "move", "to", "play", "based", "on", "MCTS", "readout", "statistics", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/strategies.py#L175-L188
[ "def", "pick_move", "(", "self", ")", ":", "if", "self", ".", "root", ".", "position", ".", "n", ">=", "self", ".", "temp_threshold", ":", "fcoord", "=", "self", ".", "root", ".", "best_child", "(", ")", "else", ":", "cdf", "=", "self", ".", "root"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
RecurrentAttention.forward
Execute RecurrentAttention. :param inputs: tensor with inputs :param hidden: hidden state for LSTM layer :param context: context tensor from encoder :param context_len: vector of encoder sequence lengths :returns (rnn_outputs, hidden, attn_output, attn_scores)
rnn_translator/pytorch/seq2seq/models/decoder.py
def forward(self, inputs, hidden, context, context_len): """ Execute RecurrentAttention. :param inputs: tensor with inputs :param hidden: hidden state for LSTM layer :param context: context tensor from encoder :param context_len: vector of encoder sequence lengths ...
def forward(self, inputs, hidden, context, context_len): """ Execute RecurrentAttention. :param inputs: tensor with inputs :param hidden: hidden state for LSTM layer :param context: context tensor from encoder :param context_len: vector of encoder sequence lengths ...
[ "Execute", "RecurrentAttention", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/models/decoder.py#L42-L62
[ "def", "forward", "(", "self", ",", "inputs", ",", "hidden", ",", "context", ",", "context_len", ")", ":", "# set attention mask, sequences have different lengths, this mask", "# allows to include only valid elements of context in attention's", "# softmax", "self", ".", "attn",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
ResidualRecurrentDecoder.init_hidden
Converts flattened hidden state (from sequence generator) into a tuple of hidden states. :param hidden: None or flattened hidden state for decoder RNN layers
rnn_translator/pytorch/seq2seq/models/decoder.py
def init_hidden(self, hidden): """ Converts flattened hidden state (from sequence generator) into a tuple of hidden states. :param hidden: None or flattened hidden state for decoder RNN layers """ if hidden is not None: # per-layer chunks hidden =...
def init_hidden(self, hidden): """ Converts flattened hidden state (from sequence generator) into a tuple of hidden states. :param hidden: None or flattened hidden state for decoder RNN layers """ if hidden is not None: # per-layer chunks hidden =...
[ "Converts", "flattened", "hidden", "state", "(", "from", "sequence", "generator", ")", "into", "a", "tuple", "of", "hidden", "states", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/models/decoder.py#L149-L165
[ "def", "init_hidden", "(", "self", ",", "hidden", ")", ":", "if", "hidden", "is", "not", "None", ":", "# per-layer chunks", "hidden", "=", "hidden", ".", "chunk", "(", "self", ".", "num_layers", ")", "# (h, c) chunks for LSTM layer", "hidden", "=", "tuple", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
ResidualRecurrentDecoder.package_hidden
Flattens the hidden state from all LSTM layers into one tensor (for the sequence generator).
rnn_translator/pytorch/seq2seq/models/decoder.py
def package_hidden(self): """ Flattens the hidden state from all LSTM layers into one tensor (for the sequence generator). """ if self.inference: hidden = torch.cat(tuple(itertools.chain(*self.next_hidden))) else: hidden = None return hidde...
def package_hidden(self): """ Flattens the hidden state from all LSTM layers into one tensor (for the sequence generator). """ if self.inference: hidden = torch.cat(tuple(itertools.chain(*self.next_hidden))) else: hidden = None return hidde...
[ "Flattens", "the", "hidden", "state", "from", "all", "LSTM", "layers", "into", "one", "tensor", "(", "for", "the", "sequence", "generator", ")", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/models/decoder.py#L176-L185
[ "def", "package_hidden", "(", "self", ")", ":", "if", "self", ".", "inference", ":", "hidden", "=", "torch", ".", "cat", "(", "tuple", "(", "itertools", ".", "chain", "(", "*", "self", ".", "next_hidden", ")", ")", ")", "else", ":", "hidden", "=", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
ResidualRecurrentDecoder.forward
Execute the decoder. :param inputs: tensor with inputs to the decoder :param context: state of encoder, encoder sequence lengths and hidden state of decoder's LSTM layers :param inference: if True stores and repackages hidden state
rnn_translator/pytorch/seq2seq/models/decoder.py
def forward(self, inputs, context, inference=False): """ Execute the decoder. :param inputs: tensor with inputs to the decoder :param context: state of encoder, encoder sequence lengths and hidden state of decoder's LSTM layers :param inference: if True stores and re...
def forward(self, inputs, context, inference=False): """ Execute the decoder. :param inputs: tensor with inputs to the decoder :param context: state of encoder, encoder sequence lengths and hidden state of decoder's LSTM layers :param inference: if True stores and re...
[ "Execute", "the", "decoder", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/models/decoder.py#L187-L222
[ "def", "forward", "(", "self", ",", "inputs", ",", "context", ",", "inference", "=", "False", ")", ":", "self", ".", "inference", "=", "inference", "enc_context", ",", "enc_len", ",", "hidden", "=", "context", "hidden", "=", "self", ".", "init_hidden", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
log_deferred
Helper method inserting compliance logging ops. Note: This helper is not guaranteed to be efficient, as it will insert ops and control dependencies. If this proves to be a bottleneck, submitters may wish to consider other methods such as extracting values from an .events file. Args: op...
compliance/mlperf_compliance/tf_mlperf_log.py
def log_deferred(op, log_id, every_n=1, first_n=None): """Helper method inserting compliance logging ops. Note: This helper is not guaranteed to be efficient, as it will insert ops and control dependencies. If this proves to be a bottleneck, submitters may wish to consider other methods such as ext...
def log_deferred(op, log_id, every_n=1, first_n=None): """Helper method inserting compliance logging ops. Note: This helper is not guaranteed to be efficient, as it will insert ops and control dependencies. If this proves to be a bottleneck, submitters may wish to consider other methods such as ext...
[ "Helper", "method", "inserting", "compliance", "logging", "ops", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/compliance/mlperf_compliance/tf_mlperf_log.py#L33-L62
[ "def", "log_deferred", "(", "op", ",", "log_id", ",", "every_n", "=", "1", ",", "first_n", "=", "None", ")", ":", "prefix", "=", "\":::MLPv0.5.0 [{}]\"", ".", "format", "(", "log_id", ")", "if", "not", "first_n", "is", "not", "None", "and", "first_n", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
cache_url
r"""Loads the Torch serialized object at the given URL. If the object is already present in `model_dir`, it's deserialized and returned. The filename part of the URL should follow the naming convention ``filename-<sha256>.ext`` where ``<sha256>`` is the first eight or more digits of the SHA256 hash of t...
object_detection/pytorch/maskrcnn_benchmark/utils/model_zoo.py
def cache_url(url, model_dir=None, progress=True): r"""Loads the Torch serialized object at the given URL. If the object is already present in `model_dir`, it's deserialized and returned. The filename part of the URL should follow the naming convention ``filename-<sha256>.ext`` where ``<sha256>`` is the...
def cache_url(url, model_dir=None, progress=True): r"""Loads the Torch serialized object at the given URL. If the object is already present in `model_dir`, it's deserialized and returned. The filename part of the URL should follow the naming convention ``filename-<sha256>.ext`` where ``<sha256>`` is the...
[ "r", "Loads", "the", "Torch", "serialized", "object", "at", "the", "given", "URL", ".", "If", "the", "object", "is", "already", "present", "in", "model_dir", "it", "s", "deserialized", "and", "returned", ".", "The", "filename", "part", "of", "the", "URL", ...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/utils/model_zoo.py#L15-L56
[ "def", "cache_url", "(", "url", ",", "model_dir", "=", "None", ",", "progress", "=", "True", ")", ":", "if", "model_dir", "is", "None", ":", "torch_home", "=", "os", ".", "path", ".", "expanduser", "(", "os", ".", "getenv", "(", "'TORCH_HOME'", ",", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Attention.split_heads
Split x into different heads, and transpose the resulting value. The tensor is transposed to insure the inner dimensions hold the correct values during the matrix multiplication. Args: x: A tensor with shape [batch_size, length, hidden_size] Returns: A tensor with shape [batch_size, num_h...
translation/tensorflow/transformer/model/attention_layer.py
def split_heads(self, x): """Split x into different heads, and transpose the resulting value. The tensor is transposed to insure the inner dimensions hold the correct values during the matrix multiplication. Args: x: A tensor with shape [batch_size, length, hidden_size] Returns: A ten...
def split_heads(self, x): """Split x into different heads, and transpose the resulting value. The tensor is transposed to insure the inner dimensions hold the correct values during the matrix multiplication. Args: x: A tensor with shape [batch_size, length, hidden_size] Returns: A ten...
[ "Split", "x", "into", "different", "heads", "and", "transpose", "the", "resulting", "value", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/attention_layer.py#L56-L79
[ "def", "split_heads", "(", "self", ",", "x", ")", ":", "with", "tf", ".", "name_scope", "(", "\"split_heads\"", ")", ":", "batch_size", "=", "tf", ".", "shape", "(", "x", ")", "[", "0", "]", "length", "=", "tf", ".", "shape", "(", "x", ")", "[", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Attention.combine_heads
Combine tensor that has been split. Args: x: A tensor [batch_size, num_heads, length, hidden_size/num_heads] Returns: A tensor with shape [batch_size, length, hidden_size]
translation/tensorflow/transformer/model/attention_layer.py
def combine_heads(self, x): """Combine tensor that has been split. Args: x: A tensor [batch_size, num_heads, length, hidden_size/num_heads] Returns: A tensor with shape [batch_size, length, hidden_size] """ with tf.name_scope("combine_heads"): batch_size = tf.shape(x)[0] le...
def combine_heads(self, x): """Combine tensor that has been split. Args: x: A tensor [batch_size, num_heads, length, hidden_size/num_heads] Returns: A tensor with shape [batch_size, length, hidden_size] """ with tf.name_scope("combine_heads"): batch_size = tf.shape(x)[0] le...
[ "Combine", "tensor", "that", "has", "been", "split", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/attention_layer.py#L81-L94
[ "def", "combine_heads", "(", "self", ",", "x", ")", ":", "with", "tf", ".", "name_scope", "(", "\"combine_heads\"", ")", ":", "batch_size", "=", "tf", ".", "shape", "(", "x", ")", "[", "0", "]", "length", "=", "tf", ".", "shape", "(", "x", ")", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Attention.call
Apply attention mechanism to x and y. Args: x: a tensor with shape [batch_size, length_x, hidden_size] y: a tensor with shape [batch_size, length_y, hidden_size] bias: attention bias that will be added to the result of the dot product. cache: (Used during prediction) dictionary with tensors...
translation/tensorflow/transformer/model/attention_layer.py
def call(self, x, y, bias, cache=None): """Apply attention mechanism to x and y. Args: x: a tensor with shape [batch_size, length_x, hidden_size] y: a tensor with shape [batch_size, length_y, hidden_size] bias: attention bias that will be added to the result of the dot product. cache: (...
def call(self, x, y, bias, cache=None): """Apply attention mechanism to x and y. Args: x: a tensor with shape [batch_size, length_x, hidden_size] y: a tensor with shape [batch_size, length_y, hidden_size] bias: attention bias that will be added to the result of the dot product. cache: (...
[ "Apply", "attention", "mechanism", "to", "x", "and", "y", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/attention_layer.py#L96-L154
[ "def", "call", "(", "self", ",", "x", ",", "y", ",", "bias", ",", "cache", "=", "None", ")", ":", "# Linearly project the query (q), key (k) and value (v) using different", "# learned projections. This is in preparation of splitting them into", "# multiple heads. Multi-head atten...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_save_vocab_file
Save subtokens to file.
translation/tensorflow/transformer/utils/tokenizer.py
def _save_vocab_file(vocab_file, subtoken_list): """Save subtokens to file.""" with tf.gfile.Open(vocab_file, mode="w") as f: for subtoken in subtoken_list: f.write("'%s'\n" % _unicode_to_native(subtoken))
def _save_vocab_file(vocab_file, subtoken_list): """Save subtokens to file.""" with tf.gfile.Open(vocab_file, mode="w") as f: for subtoken in subtoken_list: f.write("'%s'\n" % _unicode_to_native(subtoken))
[ "Save", "subtokens", "to", "file", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L185-L189
[ "def", "_save_vocab_file", "(", "vocab_file", ",", "subtoken_list", ")", ":", "with", "tf", ".", "gfile", ".", "Open", "(", "vocab_file", ",", "mode", "=", "\"w\"", ")", "as", "f", ":", "for", "subtoken", "in", "subtoken_list", ":", "f", ".", "write", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_load_vocab_file
Load vocabulary while ensuring reserved tokens are at the top.
translation/tensorflow/transformer/utils/tokenizer.py
def _load_vocab_file(vocab_file, reserved_tokens=None): """Load vocabulary while ensuring reserved tokens are at the top.""" if reserved_tokens is None: reserved_tokens = RESERVED_TOKENS subtoken_list = [] with tf.gfile.Open(vocab_file, mode="r") as f: for line in f: subtoken = _native_to_unicode...
def _load_vocab_file(vocab_file, reserved_tokens=None): """Load vocabulary while ensuring reserved tokens are at the top.""" if reserved_tokens is None: reserved_tokens = RESERVED_TOKENS subtoken_list = [] with tf.gfile.Open(vocab_file, mode="r") as f: for line in f: subtoken = _native_to_unicode...
[ "Load", "vocabulary", "while", "ensuring", "reserved", "tokens", "are", "at", "the", "top", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L192-L205
[ "def", "_load_vocab_file", "(", "vocab_file", ",", "reserved_tokens", "=", "None", ")", ":", "if", "reserved_tokens", "is", "None", ":", "reserved_tokens", "=", "RESERVED_TOKENS", "subtoken_list", "=", "[", "]", "with", "tf", ".", "gfile", ".", "Open", "(", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_native_to_unicode
Convert string to unicode (required in Python 2).
translation/tensorflow/transformer/utils/tokenizer.py
def _native_to_unicode(s): """Convert string to unicode (required in Python 2).""" if six.PY2: return s if isinstance(s, unicode) else s.decode("utf-8") else: return s
def _native_to_unicode(s): """Convert string to unicode (required in Python 2).""" if six.PY2: return s if isinstance(s, unicode) else s.decode("utf-8") else: return s
[ "Convert", "string", "to", "unicode", "(", "required", "in", "Python", "2", ")", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L208-L213
[ "def", "_native_to_unicode", "(", "s", ")", ":", "if", "six", ".", "PY2", ":", "return", "s", "if", "isinstance", "(", "s", ",", "unicode", ")", "else", "s", ".", "decode", "(", "\"utf-8\"", ")", "else", ":", "return", "s" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_unicode_to_native
Convert string from unicode to native format (required in Python 2).
translation/tensorflow/transformer/utils/tokenizer.py
def _unicode_to_native(s): """Convert string from unicode to native format (required in Python 2).""" if six.PY2: return s.encode("utf-8") if isinstance(s, unicode) else s else: return s
def _unicode_to_native(s): """Convert string from unicode to native format (required in Python 2).""" if six.PY2: return s.encode("utf-8") if isinstance(s, unicode) else s else: return s
[ "Convert", "string", "from", "unicode", "to", "native", "format", "(", "required", "in", "Python", "2", ")", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L216-L221
[ "def", "_unicode_to_native", "(", "s", ")", ":", "if", "six", ".", "PY2", ":", "return", "s", ".", "encode", "(", "\"utf-8\"", ")", "if", "isinstance", "(", "s", ",", "unicode", ")", "else", "s", "else", ":", "return", "s" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_split_string_to_tokens
Splits text to a list of string tokens.
translation/tensorflow/transformer/utils/tokenizer.py
def _split_string_to_tokens(text): """Splits text to a list of string tokens.""" if not text: return [] ret = [] token_start = 0 # Classify each character in the input string is_alnum = [c in _ALPHANUMERIC_CHAR_SET for c in text] for pos in xrange(1, len(text)): if is_alnum[pos] != is_alnum[pos - ...
def _split_string_to_tokens(text): """Splits text to a list of string tokens.""" if not text: return [] ret = [] token_start = 0 # Classify each character in the input string is_alnum = [c in _ALPHANUMERIC_CHAR_SET for c in text] for pos in xrange(1, len(text)): if is_alnum[pos] != is_alnum[pos - ...
[ "Splits", "text", "to", "a", "list", "of", "string", "tokens", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L224-L240
[ "def", "_split_string_to_tokens", "(", "text", ")", ":", "if", "not", "text", ":", "return", "[", "]", "ret", "=", "[", "]", "token_start", "=", "0", "# Classify each character in the input string", "is_alnum", "=", "[", "c", "in", "_ALPHANUMERIC_CHAR_SET", "for...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_escape_token
r"""Replace characters that aren't in the alphabet and append "_" to token. Apply three transformations to the token: 1. Replace underline character "_" with "\u", and backslash "\" with "\\". 2. Replace characters outside of the alphabet with "\###;", where ### is the character's Unicode code point. ...
translation/tensorflow/transformer/utils/tokenizer.py
def _escape_token(token, alphabet): r"""Replace characters that aren't in the alphabet and append "_" to token. Apply three transformations to the token: 1. Replace underline character "_" with "\u", and backslash "\" with "\\". 2. Replace characters outside of the alphabet with "\###;", where ### is the ...
def _escape_token(token, alphabet): r"""Replace characters that aren't in the alphabet and append "_" to token. Apply three transformations to the token: 1. Replace underline character "_" with "\u", and backslash "\" with "\\". 2. Replace characters outside of the alphabet with "\###;", where ### is the ...
[ "r", "Replace", "characters", "that", "aren", "t", "in", "the", "alphabet", "and", "append", "_", "to", "token", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L254-L272
[ "def", "_escape_token", "(", "token", ",", "alphabet", ")", ":", "token", "=", "token", ".", "replace", "(", "u\"\\\\\"", ",", "u\"\\\\\\\\\"", ")", ".", "replace", "(", "u\"_\"", ",", "u\"\\\\u\"", ")", "ret", "=", "[", "c", "if", "c", "in", "alphabet...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_unescape_token
r"""Replaces escaped characters in the token with their unescaped versions. Applies inverse transformations as _escape_token(): 1. Replace "\u" with "_", and "\\" with "\". 2. Replace "\###;" with the unicode character the ### refers to. Args: token: escaped string Returns: unescaped string
translation/tensorflow/transformer/utils/tokenizer.py
def _unescape_token(token): r"""Replaces escaped characters in the token with their unescaped versions. Applies inverse transformations as _escape_token(): 1. Replace "\u" with "_", and "\\" with "\". 2. Replace "\###;" with the unicode character the ### refers to. Args: token: escaped string Ret...
def _unescape_token(token): r"""Replaces escaped characters in the token with their unescaped versions. Applies inverse transformations as _escape_token(): 1. Replace "\u" with "_", and "\\" with "\". 2. Replace "\###;" with the unicode character the ### refers to. Args: token: escaped string Ret...
[ "r", "Replaces", "escaped", "characters", "in", "the", "token", "with", "their", "unescaped", "versions", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L275-L327
[ "def", "_unescape_token", "(", "token", ")", ":", "def", "match", "(", "m", ")", ":", "r\"\"\"Returns replacement string for matched object.\n\n Matched objects contain one of the strings that matches the regex pattern:\n r\"\\\\u|\\\\\\\\|\\\\([0-9]+);\"\n The strings can be '\\u...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_count_tokens
Return token counts of words in the files. Samples file_byte_limit bytes from each file, and counts the words that appear in the samples. The samples are semi-evenly distributed across the file. Args: files: List of filepaths file_byte_limit: Max number of bytes that will be read from each file. Retu...
translation/tensorflow/transformer/utils/tokenizer.py
def _count_tokens(files, file_byte_limit=1e6): """Return token counts of words in the files. Samples file_byte_limit bytes from each file, and counts the words that appear in the samples. The samples are semi-evenly distributed across the file. Args: files: List of filepaths file_byte_limit: Max numbe...
def _count_tokens(files, file_byte_limit=1e6): """Return token counts of words in the files. Samples file_byte_limit bytes from each file, and counts the words that appear in the samples. The samples are semi-evenly distributed across the file. Args: files: List of filepaths file_byte_limit: Max numbe...
[ "Return", "token", "counts", "of", "words", "in", "the", "files", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L330-L364
[ "def", "_count_tokens", "(", "files", ",", "file_byte_limit", "=", "1e6", ")", ":", "token_counts", "=", "collections", ".", "defaultdict", "(", "int", ")", "for", "filepath", "in", "files", ":", "with", "tf", ".", "gfile", ".", "Open", "(", "filepath", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_split_token_to_subtokens
Splits a token into subtokens defined in the subtoken dict.
translation/tensorflow/transformer/utils/tokenizer.py
def _split_token_to_subtokens(token, subtoken_dict, max_subtoken_length): """Splits a token into subtokens defined in the subtoken dict.""" ret = [] start = 0 token_len = len(token) while start < token_len: # Find the longest subtoken, so iterate backwards. for end in xrange(min(token_len, start + max...
def _split_token_to_subtokens(token, subtoken_dict, max_subtoken_length): """Splits a token into subtokens defined in the subtoken dict.""" ret = [] start = 0 token_len = len(token) while start < token_len: # Find the longest subtoken, so iterate backwards. for end in xrange(min(token_len, start + max...
[ "Splits", "a", "token", "into", "subtokens", "defined", "in", "the", "subtoken", "dict", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L372-L391
[ "def", "_split_token_to_subtokens", "(", "token", ",", "subtoken_dict", ",", "max_subtoken_length", ")", ":", "ret", "=", "[", "]", "start", "=", "0", "token_len", "=", "len", "(", "token", ")", "while", "start", "<", "token_len", ":", "# Find the longest subt...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4