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
ExampleBuffer.parallel_fill
games is a list of .tfrecord.zz game records.
reinforcement/tensorflow/minigo/rl_loop/example_buffer.py
def parallel_fill(self, games, threads=8): """ games is a list of .tfrecord.zz game records. """ games.sort(key=os.path.basename) # A couple extra in case parsing fails max_games = int(self.max_size / self.sampling_frac / 200) + 480 if len(games) > max_games: games = ...
def parallel_fill(self, games, threads=8): """ games is a list of .tfrecord.zz game records. """ games.sort(key=os.path.basename) # A couple extra in case parsing fails max_games = int(self.max_size / self.sampling_frac / 200) + 480 if len(games) > max_games: games = ...
[ "games", "is", "a", "list", "of", ".", "tfrecord", ".", "zz", "game", "records", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/rl_loop/example_buffer.py#L87-L98
[ "def", "parallel_fill", "(", "self", ",", "games", ",", "threads", "=", "8", ")", ":", "games", ".", "sort", "(", "key", "=", "os", ".", "path", ".", "basename", ")", "# A couple extra in case parsing fails", "max_games", "=", "int", "(", "self", ".", "m...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
ExampleBuffer.update
new_games is a list of .tfrecord.zz new game records.
reinforcement/tensorflow/minigo/rl_loop/example_buffer.py
def update(self, new_games): """ new_games is a list of .tfrecord.zz new game records. """ new_games.sort(key=os.path.basename) first_new_game = None for idx, game in enumerate(new_games): timestamp = file_timestamp(game) if timestamp <= self.examples[-1][0]: ...
def update(self, new_games): """ new_games is a list of .tfrecord.zz new game records. """ new_games.sort(key=os.path.basename) first_new_game = None for idx, game in enumerate(new_games): timestamp = file_timestamp(game) if timestamp <= self.examples[-1][0]: ...
[ "new_games", "is", "a", "list", "of", ".", "tfrecord", ".", "zz", "new", "game", "records", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/rl_loop/example_buffer.py#L100-L117
[ "def", "update", "(", "self", ",", "new_games", ")", ":", "new_games", ".", "sort", "(", "key", "=", "os", ".", "path", ".", "basename", ")", "first_new_game", "=", "None", "for", "idx", ",", "game", "in", "enumerate", "(", "new_games", ")", ":", "ti...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
RetinaNetPostProcessor.forward_for_single_feature_map
Arguments: anchors: list[BoxList] box_cls: tensor of size N, A * C, H, W box_regression: tensor of size N, A * 4, H, W
object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/retinanet/inference.py
def forward_for_single_feature_map( self, anchors, box_cls, box_regression): """ Arguments: anchors: list[BoxList] box_cls: tensor of size N, A * C, H, W box_regression: tensor of size N, A * 4, H, W """ device = box_cls.device N, _...
def forward_for_single_feature_map( self, anchors, box_cls, box_regression): """ Arguments: anchors: list[BoxList] box_cls: tensor of size N, A * C, H, W box_regression: tensor of size N, A * 4, H, W """ device = box_cls.device N, _...
[ "Arguments", ":", "anchors", ":", "list", "[", "BoxList", "]", "box_cls", ":", "tensor", "of", "size", "N", "A", "*", "C", "H", "W", "box_regression", ":", "tensor", "of", "size", "N", "A", "*", "4", "H", "W" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/retinanet/inference.py#L59-L125
[ "def", "forward_for_single_feature_map", "(", "self", ",", "anchors", ",", "box_cls", ",", "box_regression", ")", ":", "device", "=", "box_cls", ".", "device", "N", ",", "_", ",", "H", ",", "W", "=", "box_cls", ".", "shape", "A", "=", "box_regression", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
make_tf_example
Args: features: [N, N, FEATURE_DIM] nparray of uint8 pi: [N * N + 1] nparray of float32 value: float
reinforcement/tensorflow/minigo/preprocessing.py
def make_tf_example(features, pi, value): """ Args: features: [N, N, FEATURE_DIM] nparray of uint8 pi: [N * N + 1] nparray of float32 value: float """ return tf.train.Example(features=tf.train.Features(feature={ 'x': tf.train.Feature( bytes_list=tf.train.Bytes...
def make_tf_example(features, pi, value): """ Args: features: [N, N, FEATURE_DIM] nparray of uint8 pi: [N * N + 1] nparray of float32 value: float """ return tf.train.Example(features=tf.train.Features(feature={ 'x': tf.train.Feature( bytes_list=tf.train.Bytes...
[ "Args", ":", "features", ":", "[", "N", "N", "FEATURE_DIM", "]", "nparray", "of", "uint8", "pi", ":", "[", "N", "*", "N", "+", "1", "]", "nparray", "of", "float32", "value", ":", "float" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/preprocessing.py#L39-L55
[ "def", "make_tf_example", "(", "features", ",", "pi", ",", "value", ")", ":", "return", "tf", ".", "train", ".", "Example", "(", "features", "=", "tf", ".", "train", ".", "Features", "(", "feature", "=", "{", "'x'", ":", "tf", ".", "train", ".", "F...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
write_tf_examples
Args: filename: Where to write tf.records tf_examples: An iterable of tf.Example serialize: whether to serialize the examples.
reinforcement/tensorflow/minigo/preprocessing.py
def write_tf_examples(filename, tf_examples, serialize=True): """ Args: filename: Where to write tf.records tf_examples: An iterable of tf.Example serialize: whether to serialize the examples. """ with tf.python_io.TFRecordWriter( filename, options=TF_RECORD_CONFIG) a...
def write_tf_examples(filename, tf_examples, serialize=True): """ Args: filename: Where to write tf.records tf_examples: An iterable of tf.Example serialize: whether to serialize the examples. """ with tf.python_io.TFRecordWriter( filename, options=TF_RECORD_CONFIG) a...
[ "Args", ":", "filename", ":", "Where", "to", "write", "tf", ".", "records", "tf_examples", ":", "An", "iterable", "of", "tf", ".", "Example", "serialize", ":", "whether", "to", "serialize", "the", "examples", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/preprocessing.py#L58-L71
[ "def", "write_tf_examples", "(", "filename", ",", "tf_examples", ",", "serialize", "=", "True", ")", ":", "with", "tf", ".", "python_io", ".", "TFRecordWriter", "(", "filename", ",", "options", "=", "TF_RECORD_CONFIG", ")", "as", "writer", ":", "for", "ex", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
batch_parse_tf_example
Args: example_batch: a batch of tf.Example Returns: A tuple (feature_tensor, dict of output tensors)
reinforcement/tensorflow/minigo/preprocessing.py
def batch_parse_tf_example(batch_size, example_batch): """ Args: example_batch: a batch of tf.Example Returns: A tuple (feature_tensor, dict of output tensors) """ features = { 'x': tf.FixedLenFeature([], tf.string), 'pi': tf.FixedLenFeature([], tf.string), 'o...
def batch_parse_tf_example(batch_size, example_batch): """ Args: example_batch: a batch of tf.Example Returns: A tuple (feature_tensor, dict of output tensors) """ features = { 'x': tf.FixedLenFeature([], tf.string), 'pi': tf.FixedLenFeature([], tf.string), 'o...
[ "Args", ":", "example_batch", ":", "a", "batch", "of", "tf", ".", "Example", "Returns", ":", "A", "tuple", "(", "feature_tensor", "dict", "of", "output", "tensors", ")" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/preprocessing.py#L74-L95
[ "def", "batch_parse_tf_example", "(", "batch_size", ",", "example_batch", ")", ":", "features", "=", "{", "'x'", ":", "tf", ".", "FixedLenFeature", "(", "[", "]", ",", "tf", ".", "string", ")", ",", "'pi'", ":", "tf", ".", "FixedLenFeature", "(", "[", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
read_tf_records
Args: batch_size: batch size to return tf_records: a list of tf_record filenames num_repeats: how many times the data should be read (default: One) shuffle_records: whether to shuffle the order of files read shuffle_examples: whether to shuffle the tf.Examples shuffle_buf...
reinforcement/tensorflow/minigo/preprocessing.py
def read_tf_records(batch_size, tf_records, num_repeats=1, shuffle_records=True, shuffle_examples=True, shuffle_buffer_size=None, interleave=True, filter_amount=1.0): """ Args: batch_size: batch size to return tf_records: a list of tf_r...
def read_tf_records(batch_size, tf_records, num_repeats=1, shuffle_records=True, shuffle_examples=True, shuffle_buffer_size=None, interleave=True, filter_amount=1.0): """ Args: batch_size: batch size to return tf_records: a list of tf_r...
[ "Args", ":", "batch_size", ":", "batch", "size", "to", "return", "tf_records", ":", "a", "list", "of", "tf_record", "filenames", "num_repeats", ":", "how", "many", "times", "the", "data", "should", "be", "read", "(", "default", ":", "One", ")", "shuffle_re...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/preprocessing.py#L98-L147
[ "def", "read_tf_records", "(", "batch_size", ",", "tf_records", ",", "num_repeats", "=", "1", ",", "shuffle_records", "=", "True", ",", "shuffle_examples", "=", "True", ",", "shuffle_buffer_size", "=", "None", ",", "interleave", "=", "True", ",", "filter_amount"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_input_tensors
Read tf.Records and prepare them for ingestion by dual_net. See `read_tf_records` for parameter documentation. Returns a dict of tensors (see return value of batch_parse_tf_example)
reinforcement/tensorflow/minigo/preprocessing.py
def get_input_tensors(batch_size, tf_records, num_repeats=1, shuffle_records=True, shuffle_examples=True, shuffle_buffer_size=None, filter_amount=0.05, random_rotation=True): """Read tf.Records and prepare them for ingestion by dual_net. See `re...
def get_input_tensors(batch_size, tf_records, num_repeats=1, shuffle_records=True, shuffle_examples=True, shuffle_buffer_size=None, filter_amount=0.05, random_rotation=True): """Read tf.Records and prepare them for ingestion by dual_net. See `re...
[ "Read", "tf", ".", "Records", "and", "prepare", "them", "for", "ingestion", "by", "dual_net", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/preprocessing.py#L181-L207
[ "def", "get_input_tensors", "(", "batch_size", ",", "tf_records", ",", "num_repeats", "=", "1", ",", "shuffle_records", "=", "True", ",", "shuffle_examples", "=", "True", ",", "shuffle_buffer_size", "=", "None", ",", "filter_amount", "=", "0.05", ",", "random_ro...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
make_dataset_from_selfplay
Returns an iterable of tf.Examples. Args: data_extracts: An iterable of (position, pi, result) tuples
reinforcement/tensorflow/minigo/preprocessing.py
def make_dataset_from_selfplay(data_extracts): """ Returns an iterable of tf.Examples. Args: data_extracts: An iterable of (position, pi, result) tuples """ tf_examples = (make_tf_example(features_lib.extract_features(pos), pi, result) for pos, pi, result in data_extracts)...
def make_dataset_from_selfplay(data_extracts): """ Returns an iterable of tf.Examples. Args: data_extracts: An iterable of (position, pi, result) tuples """ tf_examples = (make_tf_example(features_lib.extract_features(pos), pi, result) for pos, pi, result in data_extracts)...
[ "Returns", "an", "iterable", "of", "tf", ".", "Examples", ".", "Args", ":", "data_extracts", ":", "An", "iterable", "of", "(", "position", "pi", "result", ")", "tuples" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/preprocessing.py#L265-L273
[ "def", "make_dataset_from_selfplay", "(", "data_extracts", ")", ":", "tf_examples", "=", "(", "make_tf_example", "(", "features_lib", ".", "extract_features", "(", "pos", ")", ",", "pi", ",", "result", ")", "for", "pos", ",", "pi", ",", "result", "in", "data...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
ROIBoxHead.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/box_head/box_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/box_head/box_head.py#L23-L61
[ "def", "forward", "(", "self", ",", "features", ",", "proposals", ",", "targets", "=", "None", ")", ":", "if", "self", ".", "training", ":", "# Faster R-CNN subsamples during training the proposals with a fixed", "# positive / negative ratio", "with", "torch", ".", "n...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
past_stop_threshold
Return a boolean representing whether a model should be stopped. Args: stop_threshold: float, the threshold above which a model should stop training. eval_metric: float, the current value of the relevant metric to check. Returns: True if training should stop, False otherwise. Raises: Valu...
image_classification/tensorflow/official/utils/misc/model_helpers.py
def past_stop_threshold(stop_threshold, eval_metric): """Return a boolean representing whether a model should be stopped. Args: stop_threshold: float, the threshold above which a model should stop training. eval_metric: float, the current value of the relevant metric to check. Returns: True if...
def past_stop_threshold(stop_threshold, eval_metric): """Return a boolean representing whether a model should be stopped. Args: stop_threshold: float, the threshold above which a model should stop training. eval_metric: float, the current value of the relevant metric to check. Returns: True if...
[ "Return", "a", "boolean", "representing", "whether", "a", "model", "should", "be", "stopped", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/utils/misc/model_helpers.py#L26-L55
[ "def", "past_stop_threshold", "(", "stop_threshold", ",", "eval_metric", ")", ":", "if", "stop_threshold", "is", "None", ":", "return", "False", "if", "not", "isinstance", "(", "stop_threshold", ",", "numbers", ".", "Number", ")", ":", "raise", "ValueError", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
RPNModule.forward
Arguments: images (ImageList): images for which we want to compute the predictions features (list[Tensor]): features computed from the images that are used for computing the predictions. Each tensor in the list correspond to different feature levels ta...
object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/rpn.py
def forward(self, images, features, targets=None): """ Arguments: images (ImageList): images for which we want to compute the predictions features (list[Tensor]): features computed from the images that are used for computing the predictions. Each tensor in the lis...
def forward(self, images, features, targets=None): """ Arguments: images (ImageList): images for which we want to compute the predictions features (list[Tensor]): features computed from the images that are used for computing the predictions. Each tensor in the lis...
[ "Arguments", ":", "images", "(", "ImageList", ")", ":", "images", "for", "which", "we", "want", "to", "compute", "the", "predictions", "features", "(", "list", "[", "Tensor", "]", ")", ":", "features", "computed", "from", "the", "images", "that", "are", ...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/rpn.py#L81-L102
[ "def", "forward", "(", "self", ",", "images", ",", "features", ",", "targets", "=", "None", ")", ":", "objectness", ",", "rpn_box_regression", "=", "self", ".", "head", "(", "features", ")", "anchors", "=", "self", ".", "anchor_generator", "(", "images", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
synchronize
Helper function to synchronize (barrier) among all processes when using distributed training
object_detection/pytorch/maskrcnn_benchmark/utils/comm.py
def synchronize(): """ Helper function to synchronize (barrier) among all processes when using distributed training """ if not dist.is_available(): return if not dist.is_initialized(): return world_size = dist.get_world_size() if world_size == 1: return dist.b...
def synchronize(): """ Helper function to synchronize (barrier) among all processes when using distributed training """ if not dist.is_available(): return if not dist.is_initialized(): return world_size = dist.get_world_size() if world_size == 1: return dist.b...
[ "Helper", "function", "to", "synchronize", "(", "barrier", ")", "among", "all", "processes", "when", "using", "distributed", "training" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/utils/comm.py#L33-L45
[ "def", "synchronize", "(", ")", ":", "if", "not", "dist", ".", "is_available", "(", ")", ":", "return", "if", "not", "dist", ".", "is_initialized", "(", ")", ":", "return", "world_size", "=", "dist", ".", "get_world_size", "(", ")", "if", "world_size", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
all_gather
Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank
object_detection/pytorch/maskrcnn_benchmark/utils/comm.py
def all_gather(data): """ Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank """ world_size = get_world_size() if world_size == 1: return [data] # seriali...
def all_gather(data): """ Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank """ world_size = get_world_size() if world_size == 1: return [data] # seriali...
[ "Run", "all_gather", "on", "arbitrary", "picklable", "data", "(", "not", "necessarily", "tensors", ")", "Args", ":", "data", ":", "any", "picklable", "object", "Returns", ":", "list", "[", "data", "]", ":", "list", "of", "data", "gathered", "from", "each",...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/utils/comm.py#L48-L88
[ "def", "all_gather", "(", "data", ")", ":", "world_size", "=", "get_world_size", "(", ")", "if", "world_size", "==", "1", ":", "return", "[", "data", "]", "# serialized to a Tensor", "buffer", "=", "pickle", ".", "dumps", "(", "data", ")", "storage", "=", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
reduce_dict
Args: input_dict (dict): all the values will be reduced average (bool): whether to do average or sum Reduce the values in the dictionary from all processes so that process with rank 0 has the averaged results. Returns a dict with the same fields as input_dict, after reduction.
object_detection/pytorch/maskrcnn_benchmark/utils/comm.py
def reduce_dict(input_dict, average=True): """ Args: input_dict (dict): all the values will be reduced average (bool): whether to do average or sum Reduce the values in the dictionary from all processes so that process with rank 0 has the averaged results. Returns a dict with the same fi...
def reduce_dict(input_dict, average=True): """ Args: input_dict (dict): all the values will be reduced average (bool): whether to do average or sum Reduce the values in the dictionary from all processes so that process with rank 0 has the averaged results. Returns a dict with the same fi...
[ "Args", ":", "input_dict", "(", "dict", ")", ":", "all", "the", "values", "will", "be", "reduced", "average", "(", "bool", ")", ":", "whether", "to", "do", "average", "or", "sum", "Reduce", "the", "values", "in", "the", "dictionary", "from", "all", "pr...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/utils/comm.py#L91-L117
[ "def", "reduce_dict", "(", "input_dict", ",", "average", "=", "True", ")", ":", "world_size", "=", "get_world_size", "(", ")", "if", "world_size", "<", "2", ":", "return", "input_dict", "with", "torch", ".", "no_grad", "(", ")", ":", "names", "=", "[", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
main
Bootstrap random weights.
reinforcement/tensorflow/minigo/bootstrap.py
def main(unused_argv): """Bootstrap random weights.""" utils.ensure_dir_exists(os.path.dirname(FLAGS.export_path)) if FLAGS.create_bootstrap: dual_net.bootstrap() dual_net.export_model(FLAGS.export_path)
def main(unused_argv): """Bootstrap random weights.""" utils.ensure_dir_exists(os.path.dirname(FLAGS.export_path)) if FLAGS.create_bootstrap: dual_net.bootstrap() dual_net.export_model(FLAGS.export_path)
[ "Bootstrap", "random", "weights", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bootstrap.py#L39-L44
[ "def", "main", "(", "unused_argv", ")", ":", "utils", ".", "ensure_dir_exists", "(", "os", ".", "path", ".", "dirname", "(", "FLAGS", ".", "export_path", ")", ")", "if", "FLAGS", ".", "create_bootstrap", ":", "dual_net", ".", "bootstrap", "(", ")", "dual...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
SequenceGenerator.greedy_search
Greedy decoder. :param batch_size: decoder batch size :param initial_input: initial input, usually tensor of BOS tokens :param initial_context: initial context, usually [encoder_context, src_seq_lengths, None] returns: (translation, lengths, counter) translation...
rnn_translator/pytorch/seq2seq/inference/beam_search.py
def greedy_search(self, batch_size, initial_input, initial_context=None): """ Greedy decoder. :param batch_size: decoder batch size :param initial_input: initial input, usually tensor of BOS tokens :param initial_context: initial context, usually [encoder_context, sr...
def greedy_search(self, batch_size, initial_input, initial_context=None): """ Greedy decoder. :param batch_size: decoder batch size :param initial_input: initial input, usually tensor of BOS tokens :param initial_context: initial context, usually [encoder_context, sr...
[ "Greedy", "decoder", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/inference/beam_search.py#L53-L118
[ "def", "greedy_search", "(", "self", ",", "batch_size", ",", "initial_input", ",", "initial_context", "=", "None", ")", ":", "max_seq_len", "=", "self", ".", "max_seq_len", "translation", "=", "torch", ".", "zeros", "(", "batch_size", ",", "max_seq_len", ",", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
SequenceGenerator.beam_search
Beam search decoder. :param batch_size: decoder batch size :param initial_input: initial input, usually tensor of BOS tokens :param initial_context: initial context, usually [encoder_context, src_seq_lengths, None] returns: (translation, lengths, counter) transl...
rnn_translator/pytorch/seq2seq/inference/beam_search.py
def beam_search(self, batch_size, initial_input, initial_context=None): """ Beam search decoder. :param batch_size: decoder batch size :param initial_input: initial input, usually tensor of BOS tokens :param initial_context: initial context, usually [encoder_context, ...
def beam_search(self, batch_size, initial_input, initial_context=None): """ Beam search decoder. :param batch_size: decoder batch size :param initial_input: initial input, usually tensor of BOS tokens :param initial_context: initial context, usually [encoder_context, ...
[ "Beam", "search", "decoder", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/inference/beam_search.py#L120-L303
[ "def", "beam_search", "(", "self", ",", "batch_size", ",", "initial_input", ",", "initial_context", "=", "None", ")", ":", "beam_size", "=", "self", ".", "beam_size", "norm_const", "=", "self", ".", "len_norm_const", "norm_factor", "=", "self", ".", "len_norm_...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
evaluate
evaluate dataset using different methods based on dataset type. Args: dataset: Dataset object predictions(list[BoxList]): each item in the list represents the prediction results for one image. output_folder: output folder, to save evaluation files or results. **kwargs: ot...
object_detection/pytorch/maskrcnn_benchmark/data/datasets/evaluation/__init__.py
def evaluate(dataset, predictions, output_folder, **kwargs): """evaluate dataset using different methods based on dataset type. Args: dataset: Dataset object predictions(list[BoxList]): each item in the list represents the prediction results for one image. output_folder: outp...
def evaluate(dataset, predictions, output_folder, **kwargs): """evaluate dataset using different methods based on dataset type. Args: dataset: Dataset object predictions(list[BoxList]): each item in the list represents the prediction results for one image. output_folder: outp...
[ "evaluate", "dataset", "using", "different", "methods", "based", "on", "dataset", "type", ".", "Args", ":", "dataset", ":", "Dataset", "object", "predictions", "(", "list", "[", "BoxList", "]", ")", ":", "each", "item", "in", "the", "list", "represents", "...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/data/datasets/evaluation/__init__.py#L7-L27
[ "def", "evaluate", "(", "dataset", ",", "predictions", ",", "output_folder", ",", "*", "*", "kwargs", ")", ":", "args", "=", "dict", "(", "dataset", "=", "dataset", ",", "predictions", "=", "predictions", ",", "output_folder", "=", "output_folder", ",", "*...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
cat
Efficient version of torch.cat that avoids a copy if there is only a single element in a list
object_detection/pytorch/maskrcnn_benchmark/modeling/utils.py
def cat(tensors, dim=0): """ Efficient version of torch.cat that avoids a copy if there is only a single element in a list """ assert isinstance(tensors, (list, tuple)) if len(tensors) == 1: return tensors[0] return torch.cat(tensors, dim)
def cat(tensors, dim=0): """ Efficient version of torch.cat that avoids a copy if there is only a single element in a list """ assert isinstance(tensors, (list, tuple)) if len(tensors) == 1: return tensors[0] return torch.cat(tensors, dim)
[ "Efficient", "version", "of", "torch", ".", "cat", "that", "avoids", "a", "copy", "if", "there", "is", "only", "a", "single", "element", "in", "a", "list" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/utils.py#L9-L16
[ "def", "cat", "(", "tensors", ",", "dim", "=", "0", ")", ":", "assert", "isinstance", "(", "tensors", ",", "(", "list", ",", "tuple", ")", ")", "if", "len", "(", "tensors", ")", "==", "1", ":", "return", "tensors", "[", "0", "]", "return", "torch...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
validate_examples
Validate that examples are well formed. Pi should sum to 1.0 value should be {-1,1} Usage: validate_examples("../data/300.tfrecord.zz")
reinforcement/tensorflow/minigo/oneoffs/validate_misc.py
def validate_examples(example_file): """Validate that examples are well formed. Pi should sum to 1.0 value should be {-1,1} Usage: validate_examples("../data/300.tfrecord.zz") """ def test_example(raw): example = tf.train.Example() example.ParseFromString(raw) ...
def validate_examples(example_file): """Validate that examples are well formed. Pi should sum to 1.0 value should be {-1,1} Usage: validate_examples("../data/300.tfrecord.zz") """ def test_example(raw): example = tf.train.Example() example.ParseFromString(raw) ...
[ "Validate", "that", "examples", "are", "well", "formed", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/oneoffs/validate_misc.py#L22-L43
[ "def", "validate_examples", "(", "example_file", ")", ":", "def", "test_example", "(", "raw", ")", ":", "example", "=", "tf", ".", "train", ".", "Example", "(", ")", "example", ".", "ParseFromString", "(", "raw", ")", "pi", "=", "np", ".", "frombuffer", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_train_hooks
Factory for getting a list of TensorFlow hooks for training by name. Args: name_list: a list of strings to name desired hook classes. Allowed: LoggingTensorHook, ProfilerHook, ExamplesPerSecondHook, which are defined as keys in HOOKS **kwargs: a dictionary of arguments to the hooks. Returns: ...
image_classification/tensorflow/official/utils/logs/hooks_helper.py
def get_train_hooks(name_list, **kwargs): """Factory for getting a list of TensorFlow hooks for training by name. Args: name_list: a list of strings to name desired hook classes. Allowed: LoggingTensorHook, ProfilerHook, ExamplesPerSecondHook, which are defined as keys in HOOKS **kwargs: a dict...
def get_train_hooks(name_list, **kwargs): """Factory for getting a list of TensorFlow hooks for training by name. Args: name_list: a list of strings to name desired hook classes. Allowed: LoggingTensorHook, ProfilerHook, ExamplesPerSecondHook, which are defined as keys in HOOKS **kwargs: a dict...
[ "Factory", "for", "getting", "a", "list", "of", "TensorFlow", "hooks", "for", "training", "by", "name", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/utils/logs/hooks_helper.py#L37-L64
[ "def", "get_train_hooks", "(", "name_list", ",", "*", "*", "kwargs", ")", ":", "if", "not", "name_list", ":", "return", "[", "]", "train_hooks", "=", "[", "]", "for", "name", "in", "name_list", ":", "hook_name", "=", "HOOKS", ".", "get", "(", "name", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_logging_tensor_hook
Function to get LoggingTensorHook. Args: every_n_iter: `int`, print the values of `tensors` once every N local steps taken on the current worker. tensors_to_log: List of tensor names or dictionary mapping labels to tensor names. If not set, log _TENSORS_TO_LOG by default. **kwargs: a dictiona...
image_classification/tensorflow/official/utils/logs/hooks_helper.py
def get_logging_tensor_hook(every_n_iter=100, tensors_to_log=None, **kwargs): # pylint: disable=unused-argument """Function to get LoggingTensorHook. Args: every_n_iter: `int`, print the values of `tensors` once every N local steps taken on the current worker. tensors_to_log: List of tensor names or...
def get_logging_tensor_hook(every_n_iter=100, tensors_to_log=None, **kwargs): # pylint: disable=unused-argument """Function to get LoggingTensorHook. Args: every_n_iter: `int`, print the values of `tensors` once every N local steps taken on the current worker. tensors_to_log: List of tensor names or...
[ "Function", "to", "get", "LoggingTensorHook", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/utils/logs/hooks_helper.py#L67-L86
[ "def", "get_logging_tensor_hook", "(", "every_n_iter", "=", "100", ",", "tensors_to_log", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "if", "tensors_to_log", "is", "None", ":", "tensors_to_log", "=", "_TENSORS_TO_LOG", "retur...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_examples_per_second_hook
Function to get ExamplesPerSecondHook. Args: every_n_steps: `int`, print current and average examples per second every N steps. batch_size: `int`, total batch size used to calculate examples/second from global time. warm_steps: skip this number of steps before logging and running average. ...
image_classification/tensorflow/official/utils/logs/hooks_helper.py
def get_examples_per_second_hook(every_n_steps=100, batch_size=128, warm_steps=5, **kwargs): # pylint: disable=unused-argument """Function to get ExamplesPerSecondHook. Args: every_n_steps: `int`, print current ...
def get_examples_per_second_hook(every_n_steps=100, batch_size=128, warm_steps=5, **kwargs): # pylint: disable=unused-argument """Function to get ExamplesPerSecondHook. Args: every_n_steps: `int`, print current ...
[ "Function", "to", "get", "ExamplesPerSecondHook", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/utils/logs/hooks_helper.py#L103-L123
[ "def", "get_examples_per_second_hook", "(", "every_n_steps", "=", "100", ",", "batch_size", "=", "128", ",", "warm_steps", "=", "5", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "return", "hooks", ".", "ExamplesPerSecondHook", "(", "ever...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_logging_metric_hook
Function to get LoggingMetricHook. Args: benchmark_log_dir: `string`, directory path to save the metric log. tensors_to_log: List of tensor names or dictionary mapping labels to tensor names. If not set, log _TENSORS_TO_LOG by default. every_n_secs: `int`, the frequency for logging the metric. Defa...
image_classification/tensorflow/official/utils/logs/hooks_helper.py
def get_logging_metric_hook(benchmark_log_dir=None, tensors_to_log=None, every_n_secs=600, **kwargs): # pylint: disable=unused-argument """Function to get LoggingMetricHook. Args: benchmark_log_dir: `string`, directory path to...
def get_logging_metric_hook(benchmark_log_dir=None, tensors_to_log=None, every_n_secs=600, **kwargs): # pylint: disable=unused-argument """Function to get LoggingMetricHook. Args: benchmark_log_dir: `string`, directory path to...
[ "Function", "to", "get", "LoggingMetricHook", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/utils/logs/hooks_helper.py#L126-L150
[ "def", "get_logging_metric_hook", "(", "benchmark_log_dir", "=", "None", ",", "tensors_to_log", "=", "None", ",", "every_n_secs", "=", "600", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "if", "benchmark_log_dir", "is", "None", ":", "rai...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
parse_rec
Parse a PASCAL VOC xml file
single_stage_detector/ssd/eval.py
def parse_rec(filename): """ Parse a PASCAL VOC xml file """ tree = ET.parse(filename) objects = [] for obj in tree.findall('object'): obj_struct = {} obj_struct['name'] = obj.find('name').text obj_struct['pose'] = obj.find('pose').text obj_struct['truncated'] = int(obj.f...
def parse_rec(filename): """ Parse a PASCAL VOC xml file """ tree = ET.parse(filename) objects = [] for obj in tree.findall('object'): obj_struct = {} obj_struct['name'] = obj.find('name').text obj_struct['pose'] = obj.find('pose').text obj_struct['truncated'] = int(obj.f...
[ "Parse", "a", "PASCAL", "VOC", "xml", "file" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/single_stage_detector/ssd/eval.py#L40-L57
[ "def", "parse_rec", "(", "filename", ")", ":", "tree", "=", "ET", ".", "parse", "(", "filename", ")", "objects", "=", "[", "]", "for", "obj", "in", "tree", ".", "findall", "(", "'object'", ")", ":", "obj_struct", "=", "{", "}", "obj_struct", "[", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
voc_eval
rec, prec, ap = voc_eval(detpath, annopath, imagesetfile, classname, [ovthresh], [use_07_metric]) Top level function that does the PASCAL VOC evaluation. detpath: Path to detections ...
single_stage_detector/ssd/eval.py
def voc_eval(detpath, annopath, imagesetfile, classname, cachedir, ovthresh=0.5, use_07_metric=True): """rec, prec, ap = voc_eval(detpath, annopath, imagesetfile, ...
def voc_eval(detpath, annopath, imagesetfile, classname, cachedir, ovthresh=0.5, use_07_metric=True): """rec, prec, ap = voc_eval(detpath, annopath, imagesetfile, ...
[ "rec", "prec", "ap", "=", "voc_eval", "(", "detpath", "annopath", "imagesetfile", "classname", "[", "ovthresh", "]", "[", "use_07_metric", "]", ")", "Top", "level", "function", "that", "does", "the", "PASCAL", "VOC", "evaluation", ".", "detpath", ":", "Path"...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/single_stage_detector/ssd/eval.py#L59-L192
[ "def", "voc_eval", "(", "detpath", ",", "annopath", ",", "imagesetfile", ",", "classname", ",", "cachedir", ",", "ovthresh", "=", "0.5", ",", "use_07_metric", "=", "True", ")", ":", "# assumes detections are in detpath.format(classname)", "# assumes annotations are in a...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
build_collate_fn
Factory for collate_fn functions. :param batch_first: if True returns batches in (batch, seq) format, if False returns in (seq, batch) format :param parallel: if True builds batches from parallel corpus (src, tgt) :param sort: if True sorts by src sequence length within each batch
rnn_translator/pytorch/seq2seq/data/dataset.py
def build_collate_fn(batch_first=False, parallel=True, sort=False): """ Factory for collate_fn functions. :param batch_first: if True returns batches in (batch, seq) format, if False returns in (seq, batch) format :param parallel: if True builds batches from parallel corpus (src, tgt) :para...
def build_collate_fn(batch_first=False, parallel=True, sort=False): """ Factory for collate_fn functions. :param batch_first: if True returns batches in (batch, seq) format, if False returns in (seq, batch) format :param parallel: if True builds batches from parallel corpus (src, tgt) :para...
[ "Factory", "for", "collate_fn", "functions", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/data/dataset.py#L15-L81
[ "def", "build_collate_fn", "(", "batch_first", "=", "False", ",", "parallel", "=", "True", ",", "sort", "=", "False", ")", ":", "def", "collate_seq", "(", "seq", ")", ":", "\"\"\"\n Builds batches for training or inference.\n Batches are returned as pytorch ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
TextDataset.sort_by_length
Sorts dataset by the sequence length.
rnn_translator/pytorch/seq2seq/data/dataset.py
def sort_by_length(self): """ Sorts dataset by the sequence length. """ self.lengths, indices = self.lengths.sort(descending=True) self.src = [self.src[idx] for idx in indices] self.indices = indices.tolist() self.sorted = True
def sort_by_length(self): """ Sorts dataset by the sequence length. """ self.lengths, indices = self.lengths.sort(descending=True) self.src = [self.src[idx] for idx in indices] self.indices = indices.tolist() self.sorted = True
[ "Sorts", "dataset", "by", "the", "sequence", "length", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/data/dataset.py#L115-L123
[ "def", "sort_by_length", "(", "self", ")", ":", "self", ".", "lengths", ",", "indices", "=", "self", ".", "lengths", ".", "sort", "(", "descending", "=", "True", ")", "self", ".", "src", "=", "[", "self", ".", "src", "[", "idx", "]", "for", "idx", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
TextDataset.unsort
"Unsorts" given array (restores original order of elements before dataset was sorted by sequence length). :param array: array to be "unsorted"
rnn_translator/pytorch/seq2seq/data/dataset.py
def unsort(self, array): """ "Unsorts" given array (restores original order of elements before dataset was sorted by sequence length). :param array: array to be "unsorted" """ if self.sorted: inverse = sorted(enumerate(self.indices), key=itemgetter(1)) ...
def unsort(self, array): """ "Unsorts" given array (restores original order of elements before dataset was sorted by sequence length). :param array: array to be "unsorted" """ if self.sorted: inverse = sorted(enumerate(self.indices), key=itemgetter(1)) ...
[ "Unsorts", "given", "array", "(", "restores", "original", "order", "of", "elements", "before", "dataset", "was", "sorted", "by", "sequence", "length", ")", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/data/dataset.py#L125-L135
[ "def", "unsort", "(", "self", ",", "array", ")", ":", "if", "self", ".", "sorted", ":", "inverse", "=", "sorted", "(", "enumerate", "(", "self", ".", "indices", ")", ",", "key", "=", "itemgetter", "(", "1", ")", ")", "array", "=", "[", "array", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
TextDataset.filter_data
Preserves only samples which satisfy the following inequality: min_len <= sample sequence length <= max_len :param min_len: minimum sequence length :param max_len: maximum sequence length
rnn_translator/pytorch/seq2seq/data/dataset.py
def filter_data(self, min_len, max_len): """ Preserves only samples which satisfy the following inequality: min_len <= sample sequence length <= max_len :param min_len: minimum sequence length :param max_len: maximum sequence length """ logging.info(f'Filteri...
def filter_data(self, min_len, max_len): """ Preserves only samples which satisfy the following inequality: min_len <= sample sequence length <= max_len :param min_len: minimum sequence length :param max_len: maximum sequence length """ logging.info(f'Filteri...
[ "Preserves", "only", "samples", "which", "satisfy", "the", "following", "inequality", ":", "min_len", "<", "=", "sample", "sequence", "length", "<", "=", "max_len" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/data/dataset.py#L137-L155
[ "def", "filter_data", "(", "self", ",", "min_len", ",", "max_len", ")", ":", "logging", ".", "info", "(", "f'Filtering data, min len: {min_len}, max len: {max_len}'", ")", "initial_len", "=", "len", "(", "self", ".", "src", ")", "filtered_src", "=", "[", "]", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
TextDataset.process_data
Loads data from the input file. :param fname: input file name :param tokenizer: tokenizer :param max_size: loads at most 'max_size' samples from the input file, if None loads the entire dataset
rnn_translator/pytorch/seq2seq/data/dataset.py
def process_data(self, fname, tokenizer, max_size): """ Loads data from the input file. :param fname: input file name :param tokenizer: tokenizer :param max_size: loads at most 'max_size' samples from the input file, if None loads the entire dataset """ ...
def process_data(self, fname, tokenizer, max_size): """ Loads data from the input file. :param fname: input file name :param tokenizer: tokenizer :param max_size: loads at most 'max_size' samples from the input file, if None loads the entire dataset """ ...
[ "Loads", "data", "from", "the", "input", "file", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/data/dataset.py#L157-L175
[ "def", "process_data", "(", "self", ",", "fname", ",", "tokenizer", ",", "max_size", ")", ":", "logging", ".", "info", "(", "f'Processing data from {fname}'", ")", "data", "=", "[", "]", "with", "open", "(", "fname", ")", "as", "dfile", ":", "for", "idx"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
ParallelDataset.sort_by_length
Sorts dataset by the sequence length.
rnn_translator/pytorch/seq2seq/data/dataset.py
def sort_by_length(self): """ Sorts dataset by the sequence length. """ self.lengths, indices = self.lengths.sort(descending=True) self.src = [self.src[idx] for idx in indices] self.tgt = [self.tgt[idx] for idx in indices] self.src_lengths = [self.src_lengths[idx...
def sort_by_length(self): """ Sorts dataset by the sequence length. """ self.lengths, indices = self.lengths.sort(descending=True) self.src = [self.src[idx] for idx in indices] self.tgt = [self.tgt[idx] for idx in indices] self.src_lengths = [self.src_lengths[idx...
[ "Sorts", "dataset", "by", "the", "sequence", "length", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/data/dataset.py#L251-L262
[ "def", "sort_by_length", "(", "self", ")", ":", "self", ".", "lengths", ",", "indices", "=", "self", ".", "lengths", ".", "sort", "(", "descending", "=", "True", ")", "self", ".", "src", "=", "[", "self", ".", "src", "[", "idx", "]", "for", "idx", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
ParallelDataset.filter_data
Preserves only samples which satisfy the following inequality: min_len <= src sample sequence length <= max_len AND min_len <= tgt sample sequence length <= max_len :param min_len: minimum sequence length :param max_len: maximum sequence length
rnn_translator/pytorch/seq2seq/data/dataset.py
def filter_data(self, min_len, max_len): """ Preserves only samples which satisfy the following inequality: min_len <= src sample sequence length <= max_len AND min_len <= tgt sample sequence length <= max_len :param min_len: minimum sequence length :param max_le...
def filter_data(self, min_len, max_len): """ Preserves only samples which satisfy the following inequality: min_len <= src sample sequence length <= max_len AND min_len <= tgt sample sequence length <= max_len :param min_len: minimum sequence length :param max_le...
[ "Preserves", "only", "samples", "which", "satisfy", "the", "following", "inequality", ":", "min_len", "<", "=", "src", "sample", "sequence", "length", "<", "=", "max_len", "AND", "min_len", "<", "=", "tgt", "sample", "sequence", "length", "<", "=", "max_len"...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/data/dataset.py#L264-L287
[ "def", "filter_data", "(", "self", ",", "min_len", ",", "max_len", ")", ":", "logging", ".", "info", "(", "f'Filtering data, min len: {min_len}, max len: {max_len}'", ")", "initial_len", "=", "len", "(", "self", ".", "src", ")", "filtered_src", "=", "[", "]", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
LazyParallelDataset.process_raw_data
Loads data from the input file. :param fname: input file name :param max_size: loads at most 'max_size' samples from the input file, if None loads the entire dataset
rnn_translator/pytorch/seq2seq/data/dataset.py
def process_raw_data(self, fname, max_size): """ Loads data from the input file. :param fname: input file name :param max_size: loads at most 'max_size' samples from the input file, if None loads the entire dataset """ logging.info(f'Processing data from {fna...
def process_raw_data(self, fname, max_size): """ Loads data from the input file. :param fname: input file name :param max_size: loads at most 'max_size' samples from the input file, if None loads the entire dataset """ logging.info(f'Processing data from {fna...
[ "Loads", "data", "from", "the", "input", "file", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/data/dataset.py#L331-L346
[ "def", "process_raw_data", "(", "self", ",", "fname", ",", "max_size", ")", ":", "logging", ".", "info", "(", "f'Processing data from {fname}'", ")", "data", "=", "[", "]", "with", "open", "(", "fname", ")", "as", "dfile", ":", "for", "idx", ",", "line",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
LazyParallelDataset.filter_raw_data
Preserves only samples which satisfy the following inequality: min_len <= src sample sequence length <= max_len AND min_len <= tgt sample sequence length <= max_len :param min_len: minimum sequence length :param max_len: maximum sequence length
rnn_translator/pytorch/seq2seq/data/dataset.py
def filter_raw_data(self, min_len, max_len): """ Preserves only samples which satisfy the following inequality: min_len <= src sample sequence length <= max_len AND min_len <= tgt sample sequence length <= max_len :param min_len: minimum sequence length :param ma...
def filter_raw_data(self, min_len, max_len): """ Preserves only samples which satisfy the following inequality: min_len <= src sample sequence length <= max_len AND min_len <= tgt sample sequence length <= max_len :param min_len: minimum sequence length :param ma...
[ "Preserves", "only", "samples", "which", "satisfy", "the", "following", "inequality", ":", "min_len", "<", "=", "src", "sample", "sequence", "length", "<", "=", "max_len", "AND", "min_len", "<", "=", "tgt", "sample", "sequence", "length", "<", "=", "max_len"...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/data/dataset.py#L348-L377
[ "def", "filter_raw_data", "(", "self", ",", "min_len", ",", "max_len", ")", ":", "initial_len", "=", "len", "(", "self", ".", "raw_src", ")", "filtered_src", "=", "[", "]", "filtered_tgt", "=", "[", "]", "filtered_src_len", "=", "[", "]", "filtered_tgt_len...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
heatmaps_to_keypoints
Extract predicted keypoint locations from heatmaps. Output has shape (#rois, 4, #keypoints) with the 4 rows corresponding to (x, y, logit, prob) for each keypoint.
object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/keypoint_head/inference.py
def heatmaps_to_keypoints(maps, rois): """Extract predicted keypoint locations from heatmaps. Output has shape (#rois, 4, #keypoints) with the 4 rows corresponding to (x, y, logit, prob) for each keypoint. """ # This function converts a discrete image coordinate in a HEATMAP_SIZE x # HEATMAP_SIZ...
def heatmaps_to_keypoints(maps, rois): """Extract predicted keypoint locations from heatmaps. Output has shape (#rois, 4, #keypoints) with the 4 rows corresponding to (x, y, logit, prob) for each keypoint. """ # This function converts a discrete image coordinate in a HEATMAP_SIZE x # HEATMAP_SIZ...
[ "Extract", "predicted", "keypoint", "locations", "from", "heatmaps", ".", "Output", "has", "shape", "(", "#rois", "4", "#keypoints", ")", "with", "the", "4", "rows", "corresponding", "to", "(", "x", "y", "logit", "prob", ")", "for", "each", "keypoint", "."...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/keypoint_head/inference.py#L40-L94
[ "def", "heatmaps_to_keypoints", "(", "maps", ",", "rois", ")", ":", "# This function converts a discrete image coordinate in a HEATMAP_SIZE x", "# HEATMAP_SIZE image to a continuous keypoint coordinate. We maintain", "# consistency with keypoints_to_heatmap_labels by using the conversion from", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
build_tensor_serving_input_receiver_fn
Returns a input_receiver_fn that can be used during serving. This expects examples to come through as float tensors, and simply wraps them as TensorServingInputReceivers. Arguably, this should live in tf.estimator.export. Testing here first. Args: shape: list representing target size of a single example....
image_classification/tensorflow/official/utils/export/export.py
def build_tensor_serving_input_receiver_fn(shape, dtype=tf.float32, batch_size=1): """Returns a input_receiver_fn that can be used during serving. This expects examples to come through as float tensors, and simply wraps them as TensorServingInputReceivers. Arguably, ...
def build_tensor_serving_input_receiver_fn(shape, dtype=tf.float32, batch_size=1): """Returns a input_receiver_fn that can be used during serving. This expects examples to come through as float tensors, and simply wraps them as TensorServingInputReceivers. Arguably, ...
[ "Returns", "a", "input_receiver_fn", "that", "can", "be", "used", "during", "serving", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/utils/export/export.py#L24-L49
[ "def", "build_tensor_serving_input_receiver_fn", "(", "shape", ",", "dtype", "=", "tf", ".", "float32", ",", "batch_size", "=", "1", ")", ":", "def", "serving_input_receiver_fn", "(", ")", ":", "# Prep a placeholder where the input example will be fed in", "features", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_within_box
Validate which keypoints are contained inside a given box. points: NxKx2 boxes: Nx4 output: NxK
object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/keypoint_head/loss.py
def _within_box(points, boxes): """Validate which keypoints are contained inside a given box. points: NxKx2 boxes: Nx4 output: NxK """ x_within = (points[..., 0] >= boxes[:, 0, None]) & ( points[..., 0] <= boxes[:, 2, None] ) y_within = (points[..., 1] >= boxes[:, 1, None]) & ( ...
def _within_box(points, boxes): """Validate which keypoints are contained inside a given box. points: NxKx2 boxes: Nx4 output: NxK """ x_within = (points[..., 0] >= boxes[:, 0, None]) & ( points[..., 0] <= boxes[:, 2, None] ) y_within = (points[..., 1] >= boxes[:, 1, None]) & ( ...
[ "Validate", "which", "keypoints", "are", "contained", "inside", "a", "given", "box", ".", "points", ":", "NxKx2", "boxes", ":", "Nx4", "output", ":", "NxK" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/keypoint_head/loss.py#L39-L51
[ "def", "_within_box", "(", "points", ",", "boxes", ")", ":", "x_within", "=", "(", "points", "[", "...", ",", "0", "]", ">=", "boxes", "[", ":", ",", "0", ",", "None", "]", ")", "&", "(", "points", "[", "...", ",", "0", "]", "<=", "boxes", "[...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
ExamplesPerSecondHook.begin
Called once before using the session to check global step.
image_classification/tensorflow/official/utils/logs/hooks.py
def begin(self): """Called once before using the session to check global step.""" self._global_step_tensor = tf.train.get_global_step() if self._global_step_tensor is None: raise RuntimeError( 'Global step should be created to use StepCounterHook.')
def begin(self): """Called once before using the session to check global step.""" self._global_step_tensor = tf.train.get_global_step() if self._global_step_tensor is None: raise RuntimeError( 'Global step should be created to use StepCounterHook.')
[ "Called", "once", "before", "using", "the", "session", "to", "check", "global", "step", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/utils/logs/hooks.py#L69-L74
[ "def", "begin", "(", "self", ")", ":", "self", ".", "_global_step_tensor", "=", "tf", ".", "train", ".", "get_global_step", "(", ")", "if", "self", ".", "_global_step_tensor", "is", "None", ":", "raise", "RuntimeError", "(", "'Global step should be created to us...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
ExamplesPerSecondHook.after_run
Called after each call to run(). Args: run_context: A SessionRunContext object. run_values: A SessionRunValues object.
image_classification/tensorflow/official/utils/logs/hooks.py
def after_run(self, run_context, run_values): # pylint: disable=unused-argument """Called after each call to run(). Args: run_context: A SessionRunContext object. run_values: A SessionRunValues object. """ global_step = run_values.results if self._timer.should_trigger_for_step( ...
def after_run(self, run_context, run_values): # pylint: disable=unused-argument """Called after each call to run(). Args: run_context: A SessionRunContext object. run_values: A SessionRunValues object. """ global_step = run_values.results if self._timer.should_trigger_for_step( ...
[ "Called", "after", "each", "call", "to", "run", "()", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/utils/logs/hooks.py#L87-L115
[ "def", "after_run", "(", "self", ",", "run_context", ",", "run_values", ")", ":", "# pylint: disable=unused-argument", "global_step", "=", "run_values", ".", "results", "if", "self", ".", "_timer", ".", "should_trigger_for_step", "(", "global_step", ")", "and", "g...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
vis_keypoints
Visualizes keypoints (adapted from vis_one_image). kps has shape (4, #keypoints) where 4 rows are (x, y, logit, prob).
object_detection/pytorch/demo/predictor.py
def vis_keypoints(img, kps, kp_thresh=2, alpha=0.7): """Visualizes keypoints (adapted from vis_one_image). kps has shape (4, #keypoints) where 4 rows are (x, y, logit, prob). """ dataset_keypoints = PersonKeypoints.NAMES kp_lines = PersonKeypoints.CONNECTIONS # Convert from plt 0-1 RGBA colors ...
def vis_keypoints(img, kps, kp_thresh=2, alpha=0.7): """Visualizes keypoints (adapted from vis_one_image). kps has shape (4, #keypoints) where 4 rows are (x, y, logit, prob). """ dataset_keypoints = PersonKeypoints.NAMES kp_lines = PersonKeypoints.CONNECTIONS # Convert from plt 0-1 RGBA colors ...
[ "Visualizes", "keypoints", "(", "adapted", "from", "vis_one_image", ")", ".", "kps", "has", "shape", "(", "4", "#keypoints", ")", "where", "4", "rows", "are", "(", "x", "y", "logit", "prob", ")", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/demo/predictor.py#L376-L434
[ "def", "vis_keypoints", "(", "img", ",", "kps", ",", "kp_thresh", "=", "2", ",", "alpha", "=", "0.7", ")", ":", "dataset_keypoints", "=", "PersonKeypoints", ".", "NAMES", "kp_lines", "=", "PersonKeypoints", ".", "CONNECTIONS", "# Convert from plt 0-1 RGBA colors t...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCODemo.build_transform
Creates a basic transformation that was used to train the models
object_detection/pytorch/demo/predictor.py
def build_transform(self): """ Creates a basic transformation that was used to train the models """ cfg = self.cfg # we are loading images with OpenCV, so we don't need to convert them # to BGR, they are already! So all we need to do is to normalize # by 255 if w...
def build_transform(self): """ Creates a basic transformation that was used to train the models """ cfg = self.cfg # we are loading images with OpenCV, so we don't need to convert them # to BGR, they are already! So all we need to do is to normalize # by 255 if w...
[ "Creates", "a", "basic", "transformation", "that", "was", "used", "to", "train", "the", "models" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/demo/predictor.py#L132-L160
[ "def", "build_transform", "(", "self", ")", ":", "cfg", "=", "self", ".", "cfg", "# we are loading images with OpenCV, so we don't need to convert them", "# to BGR, they are already! So all we need to do is to normalize", "# by 255 if we want to convert to BGR255 format, or flip the channe...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCODemo.run_on_opencv_image
Arguments: image (np.ndarray): an image as returned by OpenCV Returns: prediction (BoxList): the detected objects. Additional information of the detection properties can be found in the fields of the BoxList via `prediction.fields()`
object_detection/pytorch/demo/predictor.py
def run_on_opencv_image(self, image): """ Arguments: image (np.ndarray): an image as returned by OpenCV Returns: prediction (BoxList): the detected objects. Additional information of the detection properties can be found in the fields of t...
def run_on_opencv_image(self, image): """ Arguments: image (np.ndarray): an image as returned by OpenCV Returns: prediction (BoxList): the detected objects. Additional information of the detection properties can be found in the fields of t...
[ "Arguments", ":", "image", "(", "np", ".", "ndarray", ")", ":", "an", "image", "as", "returned", "by", "OpenCV" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/demo/predictor.py#L162-L185
[ "def", "run_on_opencv_image", "(", "self", ",", "image", ")", ":", "predictions", "=", "self", ".", "compute_prediction", "(", "image", ")", "top_predictions", "=", "self", ".", "select_top_predictions", "(", "predictions", ")", "result", "=", "image", ".", "c...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCODemo.compute_prediction
Arguments: original_image (np.ndarray): an image as returned by OpenCV Returns: prediction (BoxList): the detected objects. Additional information of the detection properties can be found in the fields of the BoxList via `prediction.fields()`
object_detection/pytorch/demo/predictor.py
def compute_prediction(self, original_image): """ Arguments: original_image (np.ndarray): an image as returned by OpenCV Returns: prediction (BoxList): the detected objects. Additional information of the detection properties can be found in the fields of ...
def compute_prediction(self, original_image): """ Arguments: original_image (np.ndarray): an image as returned by OpenCV Returns: prediction (BoxList): the detected objects. Additional information of the detection properties can be found in the fields of ...
[ "Arguments", ":", "original_image", "(", "np", ".", "ndarray", ")", ":", "an", "image", "as", "returned", "by", "OpenCV" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/demo/predictor.py#L187-L222
[ "def", "compute_prediction", "(", "self", ",", "original_image", ")", ":", "# apply pre-processing to image", "image", "=", "self", ".", "transforms", "(", "original_image", ")", "# convert to an ImageList, padded so that it is divisible by", "# cfg.DATALOADER.SIZE_DIVISIBILITY",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCODemo.select_top_predictions
Select only predictions which have a `score` > self.confidence_threshold, and returns the predictions in descending order of score Arguments: predictions (BoxList): the result of the computation by the model. It should contain the field `scores`. Returns: ...
object_detection/pytorch/demo/predictor.py
def select_top_predictions(self, predictions): """ Select only predictions which have a `score` > self.confidence_threshold, and returns the predictions in descending order of score Arguments: predictions (BoxList): the result of the computation by the model. ...
def select_top_predictions(self, predictions): """ Select only predictions which have a `score` > self.confidence_threshold, and returns the predictions in descending order of score Arguments: predictions (BoxList): the result of the computation by the model. ...
[ "Select", "only", "predictions", "which", "have", "a", "score", ">", "self", ".", "confidence_threshold", "and", "returns", "the", "predictions", "in", "descending", "order", "of", "score" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/demo/predictor.py#L224-L243
[ "def", "select_top_predictions", "(", "self", ",", "predictions", ")", ":", "scores", "=", "predictions", ".", "get_field", "(", "\"scores\"", ")", "keep", "=", "torch", ".", "nonzero", "(", "scores", ">", "self", ".", "confidence_threshold", ")", ".", "sque...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCODemo.compute_colors_for_labels
Simple function that adds fixed colors depending on the class
object_detection/pytorch/demo/predictor.py
def compute_colors_for_labels(self, labels): """ Simple function that adds fixed colors depending on the class """ colors = labels[:, None] * self.palette colors = (colors % 255).numpy().astype("uint8") return colors
def compute_colors_for_labels(self, labels): """ Simple function that adds fixed colors depending on the class """ colors = labels[:, None] * self.palette colors = (colors % 255).numpy().astype("uint8") return colors
[ "Simple", "function", "that", "adds", "fixed", "colors", "depending", "on", "the", "class" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/demo/predictor.py#L245-L251
[ "def", "compute_colors_for_labels", "(", "self", ",", "labels", ")", ":", "colors", "=", "labels", "[", ":", ",", "None", "]", "*", "self", ".", "palette", "colors", "=", "(", "colors", "%", "255", ")", ".", "numpy", "(", ")", ".", "astype", "(", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCODemo.overlay_boxes
Adds the predicted boxes on top of the image Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `labels`.
object_detection/pytorch/demo/predictor.py
def overlay_boxes(self, image, predictions): """ Adds the predicted boxes on top of the image Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `lab...
def overlay_boxes(self, image, predictions): """ Adds the predicted boxes on top of the image Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `lab...
[ "Adds", "the", "predicted", "boxes", "on", "top", "of", "the", "image" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/demo/predictor.py#L253-L274
[ "def", "overlay_boxes", "(", "self", ",", "image", ",", "predictions", ")", ":", "labels", "=", "predictions", ".", "get_field", "(", "\"labels\"", ")", "boxes", "=", "predictions", ".", "bbox", "colors", "=", "self", ".", "compute_colors_for_labels", "(", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCODemo.overlay_mask
Adds the instances contours for each predicted object. Each label has a different color. Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `mask` and `label...
object_detection/pytorch/demo/predictor.py
def overlay_mask(self, image, predictions): """ Adds the instances contours for each predicted object. Each label has a different color. Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the mode...
def overlay_mask(self, image, predictions): """ Adds the instances contours for each predicted object. Each label has a different color. Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the mode...
[ "Adds", "the", "instances", "contours", "for", "each", "predicted", "object", ".", "Each", "label", "has", "a", "different", "color", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/demo/predictor.py#L276-L300
[ "def", "overlay_mask", "(", "self", ",", "image", ",", "predictions", ")", ":", "masks", "=", "predictions", ".", "get_field", "(", "\"mask\"", ")", ".", "numpy", "(", ")", "labels", "=", "predictions", ".", "get_field", "(", "\"labels\"", ")", "colors", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCODemo.create_mask_montage
Create a montage showing the probability heatmaps for each one one of the detected objects Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `mask`.
object_detection/pytorch/demo/predictor.py
def create_mask_montage(self, image, predictions): """ Create a montage showing the probability heatmaps for each one one of the detected objects Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by...
def create_mask_montage(self, image, predictions): """ Create a montage showing the probability heatmaps for each one one of the detected objects Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by...
[ "Create", "a", "montage", "showing", "the", "probability", "heatmaps", "for", "each", "one", "one", "of", "the", "detected", "objects" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/demo/predictor.py#L311-L345
[ "def", "create_mask_montage", "(", "self", ",", "image", ",", "predictions", ")", ":", "masks", "=", "predictions", ".", "get_field", "(", "\"mask\"", ")", "masks_per_dim", "=", "self", ".", "masks_per_dim", "masks", "=", "L", ".", "interpolate", "(", "masks...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCODemo.overlay_class_names
Adds detected class names and scores in the positions defined by the top-left corner of the predicted bounding box Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain t...
object_detection/pytorch/demo/predictor.py
def overlay_class_names(self, image, predictions): """ Adds detected class names and scores in the positions defined by the top-left corner of the predicted bounding box Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the resu...
def overlay_class_names(self, image, predictions): """ Adds detected class names and scores in the positions defined by the top-left corner of the predicted bounding box Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the resu...
[ "Adds", "detected", "class", "names", "and", "scores", "in", "the", "positions", "defined", "by", "the", "top", "-", "left", "corner", "of", "the", "predicted", "bounding", "box" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/demo/predictor.py#L347-L370
[ "def", "overlay_class_names", "(", "self", ",", "image", ",", "predictions", ")", ":", "scores", "=", "predictions", ".", "get_field", "(", "\"scores\"", ")", ".", "tolist", "(", ")", "labels", "=", "predictions", ".", "get_field", "(", "\"labels\"", ")", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_collect_cpu_info
Collect the CPU information for the local environment.
image_classification/tensorflow/official/utils/logs/logger.py
def _collect_cpu_info(run_info): """Collect the CPU information for the local environment.""" cpu_info = {} cpu_info["num_cores"] = multiprocessing.cpu_count() # Note: cpuinfo is not installed in the TensorFlow OSS tree. # It is installable via pip. import cpuinfo # pylint: disable=g-import-not-at-top ...
def _collect_cpu_info(run_info): """Collect the CPU information for the local environment.""" cpu_info = {} cpu_info["num_cores"] = multiprocessing.cpu_count() # Note: cpuinfo is not installed in the TensorFlow OSS tree. # It is installable via pip. import cpuinfo # pylint: disable=g-import-not-at-top ...
[ "Collect", "the", "CPU", "information", "for", "the", "local", "environment", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/utils/logs/logger.py#L146-L160
[ "def", "_collect_cpu_info", "(", "run_info", ")", ":", "cpu_info", "=", "{", "}", "cpu_info", "[", "\"num_cores\"", "]", "=", "multiprocessing", ".", "cpu_count", "(", ")", "# Note: cpuinfo is not installed in the TensorFlow OSS tree.", "# It is installable via pip.", "im...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_collect_gpu_info
Collect local GPU information by TF device library.
image_classification/tensorflow/official/utils/logs/logger.py
def _collect_gpu_info(run_info): """Collect local GPU information by TF device library.""" gpu_info = {} local_device_protos = device_lib.list_local_devices() gpu_info["count"] = len([d for d in local_device_protos if d.device_type == "GPU"]) # The device description usually is a J...
def _collect_gpu_info(run_info): """Collect local GPU information by TF device library.""" gpu_info = {} local_device_protos = device_lib.list_local_devices() gpu_info["count"] = len([d for d in local_device_protos if d.device_type == "GPU"]) # The device description usually is a J...
[ "Collect", "local", "GPU", "information", "by", "TF", "device", "library", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/utils/logs/logger.py#L163-L178
[ "def", "_collect_gpu_info", "(", "run_info", ")", ":", "gpu_info", "=", "{", "}", "local_device_protos", "=", "device_lib", ".", "list_local_devices", "(", ")", "gpu_info", "[", "\"count\"", "]", "=", "len", "(", "[", "d", "for", "d", "in", "local_device_pro...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
BenchmarkLogger.log_estimator_evaluation_result
Log the evaluation result for a estimator. The evaluate result is a directory that contains metrics defined in model_fn. It also contains a entry for global_step which contains the value of the global step when evaluation was performed. Args: eval_results: dict, the result of evaluate() from a e...
image_classification/tensorflow/official/utils/logs/logger.py
def log_estimator_evaluation_result(self, eval_results): """Log the evaluation result for a estimator. The evaluate result is a directory that contains metrics defined in model_fn. It also contains a entry for global_step which contains the value of the global step when evaluation was performed. A...
def log_estimator_evaluation_result(self, eval_results): """Log the evaluation result for a estimator. The evaluate result is a directory that contains metrics defined in model_fn. It also contains a entry for global_step which contains the value of the global step when evaluation was performed. A...
[ "Log", "the", "evaluation", "result", "for", "a", "estimator", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/utils/logs/logger.py#L47-L64
[ "def", "log_estimator_evaluation_result", "(", "self", ",", "eval_results", ")", ":", "if", "not", "isinstance", "(", "eval_results", ",", "dict", ")", ":", "tf", ".", "logging", ".", "warning", "(", "\"eval_results should be directory for logging. Got %s\"", ",", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
BenchmarkLogger.log_metric
Log the benchmark metric information to local file. Currently the logging is done in a synchronized way. This should be updated to log asynchronously. Args: name: string, the name of the metric to log. value: number, the value of the metric. The value will not be logged if it is not a ...
image_classification/tensorflow/official/utils/logs/logger.py
def log_metric(self, name, value, unit=None, global_step=None, extras=None): """Log the benchmark metric information to local file. Currently the logging is done in a synchronized way. This should be updated to log asynchronously. Args: name: string, the name of the metric to log. value: n...
def log_metric(self, name, value, unit=None, global_step=None, extras=None): """Log the benchmark metric information to local file. Currently the logging is done in a synchronized way. This should be updated to log asynchronously. Args: name: string, the name of the metric to log. value: n...
[ "Log", "the", "benchmark", "metric", "information", "to", "local", "file", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/utils/logs/logger.py#L66-L103
[ "def", "log_metric", "(", "self", ",", "name", ",", "value", ",", "unit", "=", "None", ",", "global_step", "=", "None", ",", "extras", "=", "None", ")", ":", "if", "not", "isinstance", "(", "value", ",", "numbers", ".", "Number", ")", ":", "tf", "....
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
BenchmarkLogger.log_run_info
Collect most of the TF runtime information for the local env. The schema of the run info follows official/benchmark/datastore/schema. Args: model_name: string, the name of the model.
image_classification/tensorflow/official/utils/logs/logger.py
def log_run_info(self, model_name): """Collect most of the TF runtime information for the local env. The schema of the run info follows official/benchmark/datastore/schema. Args: model_name: string, the name of the model. """ run_info = { "model_name": model_name, "machine_co...
def log_run_info(self, model_name): """Collect most of the TF runtime information for the local env. The schema of the run info follows official/benchmark/datastore/schema. Args: model_name: string, the name of the model. """ run_info = { "model_name": model_name, "machine_co...
[ "Collect", "most", "of", "the", "TF", "runtime", "information", "for", "the", "local", "env", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/utils/logs/logger.py#L105-L130
[ "def", "log_run_info", "(", "self", ",", "model_name", ")", ":", "run_info", "=", "{", "\"model_name\"", ":", "model_name", ",", "\"machine_config\"", ":", "{", "}", ",", "\"run_date\"", ":", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftim...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
read_existing_paths
Return the SGF filename for each existing eval record.
reinforcement/tensorflow/minigo/oneoffs/eval_sgf_to_cbt.py
def read_existing_paths(bt_table): """Return the SGF filename for each existing eval record.""" rows = bt_table.read_rows( filter_=row_filters.ColumnRangeFilter( METADATA, SGF_FILENAME, SGF_FILENAME)) names = (row.cell_value(METADATA, SGF_FILENAME).decode() for row in rows) processed...
def read_existing_paths(bt_table): """Return the SGF filename for each existing eval record.""" rows = bt_table.read_rows( filter_=row_filters.ColumnRangeFilter( METADATA, SGF_FILENAME, SGF_FILENAME)) names = (row.cell_value(METADATA, SGF_FILENAME).decode() for row in rows) processed...
[ "Return", "the", "SGF", "filename", "for", "each", "existing", "eval", "record", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/oneoffs/eval_sgf_to_cbt.py#L87-L94
[ "def", "read_existing_paths", "(", "bt_table", ")", ":", "rows", "=", "bt_table", ".", "read_rows", "(", "filter_", "=", "row_filters", ".", "ColumnRangeFilter", "(", "METADATA", ",", "SGF_FILENAME", ",", "SGF_FILENAME", ")", ")", "names", "=", "(", "row", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
canonical_name
Keep filename and some date folders
reinforcement/tensorflow/minigo/oneoffs/eval_sgf_to_cbt.py
def canonical_name(sgf_name): """Keep filename and some date folders""" sgf_name = os.path.normpath(sgf_name) assert sgf_name.endswith('.sgf'), sgf_name # Strip off '.sgf' sgf_name = sgf_name[:-4] # Often eval is inside a folder with the run name. # include from folder before /eval/ if part...
def canonical_name(sgf_name): """Keep filename and some date folders""" sgf_name = os.path.normpath(sgf_name) assert sgf_name.endswith('.sgf'), sgf_name # Strip off '.sgf' sgf_name = sgf_name[:-4] # Often eval is inside a folder with the run name. # include from folder before /eval/ if part...
[ "Keep", "filename", "and", "some", "date", "folders" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/oneoffs/eval_sgf_to_cbt.py#L97-L111
[ "def", "canonical_name", "(", "sgf_name", ")", ":", "sgf_name", "=", "os", ".", "path", ".", "normpath", "(", "sgf_name", ")", "assert", "sgf_name", ".", "endswith", "(", "'.sgf'", ")", ",", "sgf_name", "# Strip off '.sgf'", "sgf_name", "=", "sgf_name", "[",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
read_games
Read all SGFs that match glob Parse each game and extract relevant metadata for eval games table.
reinforcement/tensorflow/minigo/oneoffs/eval_sgf_to_cbt.py
def read_games(glob, existing_paths): """Read all SGFs that match glob Parse each game and extract relevant metadata for eval games table. """ globbed = sorted(gfile.Glob(glob)) skipped = 0 to_parse = [] for sgf_name in tqdm(globbed): assert sgf_name.lower().endswith('.sgf'), sgf_...
def read_games(glob, existing_paths): """Read all SGFs that match glob Parse each game and extract relevant metadata for eval games table. """ globbed = sorted(gfile.Glob(glob)) skipped = 0 to_parse = [] for sgf_name in tqdm(globbed): assert sgf_name.lower().endswith('.sgf'), sgf_...
[ "Read", "all", "SGFs", "that", "match", "glob" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/oneoffs/eval_sgf_to_cbt.py#L149-L176
[ "def", "read_games", "(", "glob", ",", "existing_paths", ")", ":", "globbed", "=", "sorted", "(", "gfile", ".", "Glob", "(", "glob", ")", ")", "skipped", "=", "0", "to_parse", "=", "[", "]", "for", "sgf_name", "in", "tqdm", "(", "globbed", ")", ":", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
write_eval_records
Write all eval_records to eval_table In addition to writing new rows table_state must be updated in row `table_state` columns `metadata:eval_game_counter` Args: bt_table: bigtable table to add rows to. game_data: metadata pairs (column name, value) for each eval record. last_game: last...
reinforcement/tensorflow/minigo/oneoffs/eval_sgf_to_cbt.py
def write_eval_records(bt_table, game_data, last_game): """Write all eval_records to eval_table In addition to writing new rows table_state must be updated in row `table_state` columns `metadata:eval_game_counter` Args: bt_table: bigtable table to add rows to. game_data: metadata pairs (c...
def write_eval_records(bt_table, game_data, last_game): """Write all eval_records to eval_table In addition to writing new rows table_state must be updated in row `table_state` columns `metadata:eval_game_counter` Args: bt_table: bigtable table to add rows to. game_data: metadata pairs (c...
[ "Write", "all", "eval_records", "to", "eval_table" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/oneoffs/eval_sgf_to_cbt.py#L179-L233
[ "def", "write_eval_records", "(", "bt_table", ",", "game_data", ",", "last_game", ")", ":", "eval_num", "=", "last_game", "# Each column counts as a mutation so max rows is ~10000", "GAMES_PER_COMMIT", "=", "2000", "for", "games", "in", "grouper", "(", "tqdm", "(", "g...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
main
All of the magic together.
reinforcement/tensorflow/minigo/oneoffs/eval_sgf_to_cbt.py
def main(unusedargv): """All of the magic together.""" del unusedargv bt_table = (bigtable .Client(FLAGS.cbt_project, admin=True) .instance(FLAGS.cbt_instance) .table(FLAGS.cbt_table)) assert bt_table.exists(), "Table doesn't exist" # Get current gam...
def main(unusedargv): """All of the magic together.""" del unusedargv bt_table = (bigtable .Client(FLAGS.cbt_project, admin=True) .instance(FLAGS.cbt_instance) .table(FLAGS.cbt_table)) assert bt_table.exists(), "Table doesn't exist" # Get current gam...
[ "All", "of", "the", "magic", "together", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/oneoffs/eval_sgf_to_cbt.py#L236-L270
[ "def", "main", "(", "unusedargv", ")", ":", "del", "unusedargv", "bt_table", "=", "(", "bigtable", ".", "Client", "(", "FLAGS", ".", "cbt_project", ",", "admin", "=", "True", ")", ".", "instance", "(", "FLAGS", ".", "cbt_instance", ")", ".", "table", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
initialize_from_checkpoint
Initialize the reinforcement learning loop from a checkpoint.
reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py
def initialize_from_checkpoint(state): """Initialize the reinforcement learning loop from a checkpoint.""" # The checkpoint's work_dir should contain the most recently trained model. model_paths = glob.glob(os.path.join(FLAGS.checkpoint_dir, 'work_dir/model.ckpt-*.pb')) i...
def initialize_from_checkpoint(state): """Initialize the reinforcement learning loop from a checkpoint.""" # The checkpoint's work_dir should contain the most recently trained model. model_paths = glob.glob(os.path.join(FLAGS.checkpoint_dir, 'work_dir/model.ckpt-*.pb')) i...
[ "Initialize", "the", "reinforcement", "learning", "loop", "from", "a", "checkpoint", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py#L144-L171
[ "def", "initialize_from_checkpoint", "(", "state", ")", ":", "# The checkpoint's work_dir should contain the most recently trained model.", "model_paths", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "FLAGS", ".", "checkpoint_dir", ",", "'work_dir...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
run
Run the given subprocess command in a coroutine. Args: *cmd: the command to run and its arguments. Returns: The output that the command wrote to stdout as a list of strings, one line per element (stderr output is piped to stdout). Raises: RuntimeError: if the command returns a non-zero result.
reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py
async def run(*cmd): """Run the given subprocess command in a coroutine. Args: *cmd: the command to run and its arguments. Returns: The output that the command wrote to stdout as a list of strings, one line per element (stderr output is piped to stdout). Raises: RuntimeError: if the command r...
async def run(*cmd): """Run the given subprocess command in a coroutine. Args: *cmd: the command to run and its arguments. Returns: The output that the command wrote to stdout as a list of strings, one line per element (stderr output is piped to stdout). Raises: RuntimeError: if the command r...
[ "Run", "the", "given", "subprocess", "command", "in", "a", "coroutine", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py#L191-L215
[ "async", "def", "run", "(", "*", "cmd", ")", ":", "stdout", "=", "await", "checked_run", "(", "*", "cmd", ")", "log_path", "=", "os", ".", "path", ".", "join", "(", "FLAGS", ".", "base_dir", ",", "get_cmd_name", "(", "cmd", ")", "+", "'.log'", ")",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_golden_chunk_records
Return up to num_records of golden chunks to train on. Returns: A list of golden chunks up to num_records in length, sorted by path.
reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py
def get_golden_chunk_records(): """Return up to num_records of golden chunks to train on. Returns: A list of golden chunks up to num_records in length, sorted by path. """ pattern = os.path.join(fsdb.golden_chunk_dir(), '*.zz') return sorted(tf.gfile.Glob(pattern), reverse=True)[:FLAGS.window_size]
def get_golden_chunk_records(): """Return up to num_records of golden chunks to train on. Returns: A list of golden chunks up to num_records in length, sorted by path. """ pattern = os.path.join(fsdb.golden_chunk_dir(), '*.zz') return sorted(tf.gfile.Glob(pattern), reverse=True)[:FLAGS.window_size]
[ "Return", "up", "to", "num_records", "of", "golden", "chunks", "to", "train", "on", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py#L218-L226
[ "def", "get_golden_chunk_records", "(", ")", ":", "pattern", "=", "os", ".", "path", ".", "join", "(", "fsdb", ".", "golden_chunk_dir", "(", ")", ",", "'*.zz'", ")", "return", "sorted", "(", "tf", ".", "gfile", ".", "Glob", "(", "pattern", ")", ",", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
selfplay
Run selfplay and write a training chunk to the fsdb golden_chunk_dir. Args: state: the RL loop State instance. flagfile: the name of the flagfile to use for selfplay, either 'selfplay' (the default) or 'boostrap'.
reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py
async def selfplay(state, flagfile='selfplay'): """Run selfplay and write a training chunk to the fsdb golden_chunk_dir. Args: state: the RL loop State instance. flagfile: the name of the flagfile to use for selfplay, either 'selfplay' (the default) or 'boostrap'. """ output_dir = os.path.join...
async def selfplay(state, flagfile='selfplay'): """Run selfplay and write a training chunk to the fsdb golden_chunk_dir. Args: state: the RL loop State instance. flagfile: the name of the flagfile to use for selfplay, either 'selfplay' (the default) or 'boostrap'. """ output_dir = os.path.join...
[ "Run", "selfplay", "and", "write", "a", "training", "chunk", "to", "the", "fsdb", "golden_chunk_dir", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py#L230-L273
[ "async", "def", "selfplay", "(", "state", ",", "flagfile", "=", "'selfplay'", ")", ":", "output_dir", "=", "os", ".", "path", ".", "join", "(", "fsdb", ".", "selfplay_dir", "(", ")", ",", "state", ".", "output_model_name", ")", "holdout_dir", "=", "os", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
train
Run training and write a new model to the fsdb models_dir. Args: state: the RL loop State instance. tf_records: a list of paths to TensorFlow records to train on.
reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py
async def train(state, tf_records): """Run training and write a new model to the fsdb models_dir. Args: state: the RL loop State instance. tf_records: a list of paths to TensorFlow records to train on. """ model_path = os.path.join(fsdb.models_dir(), state.train_model_name) await run( 'python3...
async def train(state, tf_records): """Run training and write a new model to the fsdb models_dir. Args: state: the RL loop State instance. tf_records: a list of paths to TensorFlow records to train on. """ model_path = os.path.join(fsdb.models_dir(), state.train_model_name) await run( 'python3...
[ "Run", "training", "and", "write", "a", "new", "model", "to", "the", "fsdb", "models_dir", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py#L276-L297
[ "async", "def", "train", "(", "state", ",", "tf_records", ")", ":", "model_path", "=", "os", ".", "path", ".", "join", "(", "fsdb", ".", "models_dir", "(", ")", ",", "state", ".", "train_model_name", ")", "await", "run", "(", "'python3'", ",", "'train....
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
validate
Validate the trained model against holdout games. Args: state: the RL loop State instance. holdout_glob: a glob that matches holdout games.
reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py
async def validate(state, holdout_glob): """Validate the trained model against holdout games. Args: state: the RL loop State instance. holdout_glob: a glob that matches holdout games. """ if not glob.glob(holdout_glob): print('Glob "{}" didn\'t match any files, skipping validation'.format( ...
async def validate(state, holdout_glob): """Validate the trained model against holdout games. Args: state: the RL loop State instance. holdout_glob: a glob that matches holdout games. """ if not glob.glob(holdout_glob): print('Glob "{}" didn\'t match any files, skipping validation'.format( ...
[ "Validate", "the", "trained", "model", "against", "holdout", "games", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py#L300-L315
[ "async", "def", "validate", "(", "state", ",", "holdout_glob", ")", ":", "if", "not", "glob", ".", "glob", "(", "holdout_glob", ")", ":", "print", "(", "'Glob \"{}\" didn\\'t match any files, skipping validation'", ".", "format", "(", "holdout_glob", ")", ")", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
evaluate_model
Evaluate one model against a target. Args: eval_model_path: the path to the model to evaluate. target_model_path: the path to the model to compare to. sgf_dif: directory path to write SGF output to. seed: random seed to use when running eval. Returns: The win-rate of eval_model against target_...
reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py
async def evaluate_model(eval_model_path, target_model_path, sgf_dir, seed): """Evaluate one model against a target. Args: eval_model_path: the path to the model to evaluate. target_model_path: the path to the model to compare to. sgf_dif: directory path to write SGF output to. seed: random seed to...
async def evaluate_model(eval_model_path, target_model_path, sgf_dir, seed): """Evaluate one model against a target. Args: eval_model_path: the path to the model to evaluate. target_model_path: the path to the model to compare to. sgf_dif: directory path to write SGF output to. seed: random seed to...
[ "Evaluate", "one", "model", "against", "a", "target", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py#L318-L345
[ "async", "def", "evaluate_model", "(", "eval_model_path", ",", "target_model_path", ",", "sgf_dir", ",", "seed", ")", ":", "lines", "=", "await", "run", "(", "'bazel-bin/cc/eval'", ",", "'--flagfile={}'", ".", "format", "(", "os", ".", "path", ".", "join", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
evaluate_trained_model
Evaluate the most recently trained model against the current best model. Args: state: the RL loop State instance.
reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py
async def evaluate_trained_model(state): """Evaluate the most recently trained model against the current best model. Args: state: the RL loop State instance. """ return await evaluate_model( state.train_model_path, state.best_model_path, os.path.join(fsdb.eval_dir(), state.train_model_name), s...
async def evaluate_trained_model(state): """Evaluate the most recently trained model against the current best model. Args: state: the RL loop State instance. """ return await evaluate_model( state.train_model_path, state.best_model_path, os.path.join(fsdb.eval_dir(), state.train_model_name), s...
[ "Evaluate", "the", "most", "recently", "trained", "model", "against", "the", "current", "best", "model", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py#L348-L357
[ "async", "def", "evaluate_trained_model", "(", "state", ")", ":", "return", "await", "evaluate_model", "(", "state", ".", "train_model_path", ",", "state", ".", "best_model_path", ",", "os", ".", "path", ".", "join", "(", "fsdb", ".", "eval_dir", "(", ")", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
rl_loop
The main reinforcement learning (RL) loop.
reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py
def rl_loop(): """The main reinforcement learning (RL) loop.""" state = State() if FLAGS.checkpoint_dir: # Start from a partially trained model. initialize_from_checkpoint(state) else: # Play the first round of selfplay games with a fake model that returns # random noise. We do this instead of...
def rl_loop(): """The main reinforcement learning (RL) loop.""" state = State() if FLAGS.checkpoint_dir: # Start from a partially trained model. initialize_from_checkpoint(state) else: # Play the first round of selfplay games with a fake model that returns # random noise. We do this instead of...
[ "The", "main", "reinforcement", "learning", "(", "RL", ")", "loop", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py#L360-L414
[ "def", "rl_loop", "(", ")", ":", "state", "=", "State", "(", ")", "if", "FLAGS", ".", "checkpoint_dir", ":", "# Start from a partially trained model.", "initialize_from_checkpoint", "(", "state", ")", "else", ":", "# Play the first round of selfplay games with a fake mode...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
main
Run the reinforcement learning loop.
reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py
def main(unused_argv): """Run the reinforcement learning loop.""" print('Wiping dir %s' % FLAGS.base_dir, flush=True) shutil.rmtree(FLAGS.base_dir, ignore_errors=True) dirs = [fsdb.models_dir(), fsdb.selfplay_dir(), fsdb.holdout_dir(), fsdb.eval_dir(), fsdb.golden_chunk_dir(), fsdb.working_dir()] f...
def main(unused_argv): """Run the reinforcement learning loop.""" print('Wiping dir %s' % FLAGS.base_dir, flush=True) shutil.rmtree(FLAGS.base_dir, ignore_errors=True) dirs = [fsdb.models_dir(), fsdb.selfplay_dir(), fsdb.holdout_dir(), fsdb.eval_dir(), fsdb.golden_chunk_dir(), fsdb.working_dir()] f...
[ "Run", "the", "reinforcement", "learning", "loop", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py#L417-L447
[ "def", "main", "(", "unused_argv", ")", ":", "print", "(", "'Wiping dir %s'", "%", "FLAGS", ".", "base_dir", ",", "flush", "=", "True", ")", "shutil", ".", "rmtree", "(", "FLAGS", ".", "base_dir", ",", "ignore_errors", "=", "True", ")", "dirs", "=", "[...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
replay_position
Wrapper for a go.Position which replays its history. Assumes an empty start position! (i.e. no handicap, and history must be exhaustive.) Result must be passed in, since a resign cannot be inferred from position history alone. for position_w_context in replay_position(position): print(position...
reinforcement/tensorflow/minigo/go.py
def replay_position(position, result): """ Wrapper for a go.Position which replays its history. Assumes an empty start position! (i.e. no handicap, and history must be exhaustive.) Result must be passed in, since a resign cannot be inferred from position history alone. for position_w_context i...
def replay_position(position, result): """ Wrapper for a go.Position which replays its history. Assumes an empty start position! (i.e. no handicap, and history must be exhaustive.) Result must be passed in, since a resign cannot be inferred from position history alone. for position_w_context i...
[ "Wrapper", "for", "a", "go", ".", "Position", "which", "replays", "its", "history", ".", "Assumes", "an", "empty", "start", "position!", "(", "i", ".", "e", ".", "no", "handicap", "and", "history", "must", "be", "exhaustive", ".", ")" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/go.py#L71-L87
[ "def", "replay_position", "(", "position", ",", "result", ")", ":", "assert", "position", ".", "n", "==", "len", "(", "position", ".", "recent", ")", ",", "\"Position history is incomplete\"", "pos", "=", "Position", "(", "komi", "=", "position", ".", "komi"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
is_koish
Check if c is surrounded on all sides by 1 color, and return that color
reinforcement/tensorflow/minigo/go.py
def is_koish(board, c): 'Check if c is surrounded on all sides by 1 color, and return that color' if board[c] != EMPTY: return None neighbors = {board[n] for n in NEIGHBORS[c]} if len(neighbors) == 1 and EMPTY not in neighbors: return list(neighbors)[0] else: return None
def is_koish(board, c): 'Check if c is surrounded on all sides by 1 color, and return that color' if board[c] != EMPTY: return None neighbors = {board[n] for n in NEIGHBORS[c]} if len(neighbors) == 1 and EMPTY not in neighbors: return list(neighbors)[0] else: return None
[ "Check", "if", "c", "is", "surrounded", "on", "all", "sides", "by", "1", "color", "and", "return", "that", "color" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/go.py#L106-L114
[ "def", "is_koish", "(", "board", ",", "c", ")", ":", "if", "board", "[", "c", "]", "!=", "EMPTY", ":", "return", "None", "neighbors", "=", "{", "board", "[", "n", "]", "for", "n", "in", "NEIGHBORS", "[", "c", "]", "}", "if", "len", "(", "neighb...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
is_eyeish
Check if c is an eye, for the purpose of restricting MC rollouts.
reinforcement/tensorflow/minigo/go.py
def is_eyeish(board, c): 'Check if c is an eye, for the purpose of restricting MC rollouts.' # pass is fine. if c is None: return color = is_koish(board, c) if color is None: return None diagonal_faults = 0 diagonals = DIAGONALS[c] if len(diagonals) < 4: diagonal_...
def is_eyeish(board, c): 'Check if c is an eye, for the purpose of restricting MC rollouts.' # pass is fine. if c is None: return color = is_koish(board, c) if color is None: return None diagonal_faults = 0 diagonals = DIAGONALS[c] if len(diagonals) < 4: diagonal_...
[ "Check", "if", "c", "is", "an", "eye", "for", "the", "purpose", "of", "restricting", "MC", "rollouts", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/go.py#L117-L135
[ "def", "is_eyeish", "(", "board", ",", "c", ")", ":", "# pass is fine.", "if", "c", "is", "None", ":", "return", "color", "=", "is_koish", "(", "board", ",", "c", ")", "if", "color", "is", "None", ":", "return", "None", "diagonal_faults", "=", "0", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Position.is_move_legal
Checks that a move is on an empty space, not on ko, and not suicide
reinforcement/tensorflow/minigo/go.py
def is_move_legal(self, move): 'Checks that a move is on an empty space, not on ko, and not suicide' if move is None: return True if self.board[move] != EMPTY: return False if move == self.ko: return False if self.is_move_suicidal(move): ...
def is_move_legal(self, move): 'Checks that a move is on an empty space, not on ko, and not suicide' if move is None: return True if self.board[move] != EMPTY: return False if move == self.ko: return False if self.is_move_suicidal(move): ...
[ "Checks", "that", "a", "move", "is", "on", "an", "empty", "space", "not", "on", "ko", "and", "not", "suicide" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/go.py#L384-L395
[ "def", "is_move_legal", "(", "self", ",", "move", ")", ":", "if", "move", "is", "None", ":", "return", "True", "if", "self", ".", "board", "[", "move", "]", "!=", "EMPTY", ":", "return", "False", "if", "move", "==", "self", ".", "ko", ":", "return"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Position.all_legal_moves
Returns a np.array of size go.N**2 + 1, with 1 = legal, 0 = illegal
reinforcement/tensorflow/minigo/go.py
def all_legal_moves(self): 'Returns a np.array of size go.N**2 + 1, with 1 = legal, 0 = illegal' # by default, every move is legal legal_moves = np.ones([N, N], dtype=np.int8) # ...unless there is already a stone there legal_moves[self.board != EMPTY] = 0 # calculate whic...
def all_legal_moves(self): 'Returns a np.array of size go.N**2 + 1, with 1 = legal, 0 = illegal' # by default, every move is legal legal_moves = np.ones([N, N], dtype=np.int8) # ...unless there is already a stone there legal_moves[self.board != EMPTY] = 0 # calculate whic...
[ "Returns", "a", "np", ".", "array", "of", "size", "go", ".", "N", "**", "2", "+", "1", "with", "1", "=", "legal", "0", "=", "illegal" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/go.py#L397-L424
[ "def", "all_legal_moves", "(", "self", ")", ":", "# by default, every move is legal", "legal_moves", "=", "np", ".", "ones", "(", "[", "N", ",", "N", "]", ",", "dtype", "=", "np", ".", "int8", ")", "# ...unless there is already a stone there", "legal_moves", "["...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Position.score
Return score from B perspective. If W is winning, score is negative.
reinforcement/tensorflow/minigo/go.py
def score(self): 'Return score from B perspective. If W is winning, score is negative.' working_board = np.copy(self.board) while EMPTY in working_board: unassigned_spaces = np.where(working_board == EMPTY) c = unassigned_spaces[0][0], unassigned_spaces[1][0] ...
def score(self): 'Return score from B perspective. If W is winning, score is negative.' working_board = np.copy(self.board) while EMPTY in working_board: unassigned_spaces = np.where(working_board == EMPTY) c = unassigned_spaces[0][0], unassigned_spaces[1][0] ...
[ "Return", "score", "from", "B", "perspective", ".", "If", "W", "is", "winning", "score", "is", "negative", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/go.py#L505-L523
[ "def", "score", "(", "self", ")", ":", "working_board", "=", "np", ".", "copy", "(", "self", ".", "board", ")", "while", "EMPTY", "in", "working_board", ":", "unassigned_spaces", "=", "np", ".", "where", "(", "working_board", "==", "EMPTY", ")", "c", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
parse_sgf_to_examples
Return supervised examples from positions NOTE: last move is not played because no p.next_move after.
reinforcement/tensorflow/minigo/oneoffs/oneoff_utils.py
def parse_sgf_to_examples(sgf_path): """Return supervised examples from positions NOTE: last move is not played because no p.next_move after. """ return zip(*[(p.position, p.next_move, p.result) for p in sgf_wrapper.replay_sgf_file(sgf_path)])
def parse_sgf_to_examples(sgf_path): """Return supervised examples from positions NOTE: last move is not played because no p.next_move after. """ return zip(*[(p.position, p.next_move, p.result) for p in sgf_wrapper.replay_sgf_file(sgf_path)])
[ "Return", "supervised", "examples", "from", "positions" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/oneoffs/oneoff_utils.py#L34-L41
[ "def", "parse_sgf_to_examples", "(", "sgf_path", ")", ":", "return", "zip", "(", "*", "[", "(", "p", ".", "position", ",", "p", ".", "next_move", ",", "p", ".", "result", ")", "for", "p", "in", "sgf_wrapper", ".", "replay_sgf_file", "(", "sgf_path", ")...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
find_and_filter_sgf_files
Finds all sgf files in base_dir with year >= min_year and komi
reinforcement/tensorflow/minigo/oneoffs/oneoff_utils.py
def find_and_filter_sgf_files(base_dir, min_year=None, komi=None): """Finds all sgf files in base_dir with year >= min_year and komi""" sgf_files = [] for dirpath, dirnames, filenames in os.walk(base_dir): for filename in filenames: if filename.endswith('.sgf'): path = os...
def find_and_filter_sgf_files(base_dir, min_year=None, komi=None): """Finds all sgf files in base_dir with year >= min_year and komi""" sgf_files = [] for dirpath, dirnames, filenames in os.walk(base_dir): for filename in filenames: if filename.endswith('.sgf'): path = os...
[ "Finds", "all", "sgf", "files", "in", "base_dir", "with", "year", ">", "=", "min_year", "and", "komi" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/oneoffs/oneoff_utils.py#L77-L95
[ "def", "find_and_filter_sgf_files", "(", "base_dir", ",", "min_year", "=", "None", ",", "komi", "=", "None", ")", ":", "sgf_files", "=", "[", "]", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "base_dir", ")", ":", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_model_paths
Returns all model paths in the model_dir.
reinforcement/tensorflow/minigo/oneoffs/oneoff_utils.py
def get_model_paths(model_dir): """Returns all model paths in the model_dir.""" all_models = gfile.Glob(os.path.join(model_dir, '*.meta')) model_filenames = [os.path.basename(m) for m in all_models] model_numbers_names = [ (shipname.detect_model_num(m), shipname.detect_model_name(m)) for...
def get_model_paths(model_dir): """Returns all model paths in the model_dir.""" all_models = gfile.Glob(os.path.join(model_dir, '*.meta')) model_filenames = [os.path.basename(m) for m in all_models] model_numbers_names = [ (shipname.detect_model_num(m), shipname.detect_model_name(m)) for...
[ "Returns", "all", "model", "paths", "in", "the", "model_dir", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/oneoffs/oneoff_utils.py#L98-L106
[ "def", "get_model_paths", "(", "model_dir", ")", ":", "all_models", "=", "gfile", ".", "Glob", "(", "os", ".", "path", ".", "join", "(", "model_dir", ",", "'*.meta'", ")", ")", "model_filenames", "=", "[", "os", ".", "path", ".", "basename", "(", "m", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
make_sgf
Turn a game into SGF. Doesn't handle handicap games or positions with incomplete history. Args: move_history: iterable of PlayerMoves result_string: "B+R", "W+0.5", etc. comments: iterable of string/None. Will be zipped with move_history.
reinforcement/tensorflow/minigo/sgf_wrapper.py
def make_sgf( move_history, result_string, ruleset="Chinese", komi=7.5, white_name=PROGRAM_IDENTIFIER, black_name=PROGRAM_IDENTIFIER, comments=[] ): """Turn a game into SGF. Doesn't handle handicap games or positions with incomplete history. Args: move_history: iterable...
def make_sgf( move_history, result_string, ruleset="Chinese", komi=7.5, white_name=PROGRAM_IDENTIFIER, black_name=PROGRAM_IDENTIFIER, comments=[] ): """Turn a game into SGF. Doesn't handle handicap games or positions with incomplete history. Args: move_history: iterable...
[ "Turn", "a", "game", "into", "SGF", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/sgf_wrapper.py#L54-L76
[ "def", "make_sgf", "(", "move_history", ",", "result_string", ",", "ruleset", "=", "\"Chinese\"", ",", "komi", "=", "7.5", ",", "white_name", "=", "PROGRAM_IDENTIFIER", ",", "black_name", "=", "PROGRAM_IDENTIFIER", ",", "comments", "=", "[", "]", ")", ":", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
handle_node
A node can either add B+W stones, play as B, or play as W.
reinforcement/tensorflow/minigo/sgf_wrapper.py
def handle_node(pos, node): 'A node can either add B+W stones, play as B, or play as W.' props = node.properties black_stones_added = [coords.from_sgf( c) for c in props.get('AB', [])] white_stones_added = [coords.from_sgf( c) for c in props.get('AW', [])] if black_stones_added or wh...
def handle_node(pos, node): 'A node can either add B+W stones, play as B, or play as W.' props = node.properties black_stones_added = [coords.from_sgf( c) for c in props.get('AB', [])] white_stones_added = [coords.from_sgf( c) for c in props.get('AW', [])] if black_stones_added or wh...
[ "A", "node", "can", "either", "add", "B", "+", "W", "stones", "play", "as", "B", "or", "play", "as", "W", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/sgf_wrapper.py#L93-L110
[ "def", "handle_node", "(", "pos", ",", "node", ")", ":", "props", "=", "node", ".", "properties", "black_stones_added", "=", "[", "coords", ".", "from_sgf", "(", "c", ")", "for", "c", "in", "props", ".", "get", "(", "'AB'", ",", "[", "]", ")", "]",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
replay_sgf
Wrapper for sgf files, returning go.PositionWithContext instances. It does NOT return the very final position, as there is no follow up. To get the final position, call pwc.position.play_move(pwc.next_move) on the last PositionWithContext returned. Example usage: with open(filename) as f: ...
reinforcement/tensorflow/minigo/sgf_wrapper.py
def replay_sgf(sgf_contents): """Wrapper for sgf files, returning go.PositionWithContext instances. It does NOT return the very final position, as there is no follow up. To get the final position, call pwc.position.play_move(pwc.next_move) on the last PositionWithContext returned. Example usage: ...
def replay_sgf(sgf_contents): """Wrapper for sgf files, returning go.PositionWithContext instances. It does NOT return the very final position, as there is no follow up. To get the final position, call pwc.position.play_move(pwc.next_move) on the last PositionWithContext returned. Example usage: ...
[ "Wrapper", "for", "sgf", "files", "returning", "go", ".", "PositionWithContext", "instances", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/sgf_wrapper.py#L142-L170
[ "def", "replay_sgf", "(", "sgf_contents", ")", ":", "root_node", "=", "get_sgf_root_node", "(", "sgf_contents", ")", "props", "=", "root_node", ".", "properties", "assert", "int", "(", "sgf_prop", "(", "props", ".", "get", "(", "'GM'", ",", "[", "'1'", "]"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Seq2Seq.decode
Applies the decoder to inputs, given the context from the encoder. :param inputs: tensor with inputs (batch, seq_len) if 'batch_first' else (seq_len, batch) :param context: context from the encoder :param inference: if True inference mode, if False training mode
rnn_translator/pytorch/seq2seq/models/seq2seq_base.py
def decode(self, inputs, context, inference=False): """ Applies the decoder to inputs, given the context from the encoder. :param inputs: tensor with inputs (batch, seq_len) if 'batch_first' else (seq_len, batch) :param context: context from the encoder :param infere...
def decode(self, inputs, context, inference=False): """ Applies the decoder to inputs, given the context from the encoder. :param inputs: tensor with inputs (batch, seq_len) if 'batch_first' else (seq_len, batch) :param context: context from the encoder :param infere...
[ "Applies", "the", "decoder", "to", "inputs", "given", "the", "context", "from", "the", "encoder", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/models/seq2seq_base.py#L33-L42
[ "def", "decode", "(", "self", ",", "inputs", ",", "context", ",", "inference", "=", "False", ")", ":", "return", "self", ".", "decoder", "(", "inputs", ",", "context", ",", "inference", ")" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Seq2Seq.generate
Autoregressive generator, works with SequenceGenerator class. Executes decoder (in inference mode), applies log_softmax and topK for inference with beam search decoding. :param inputs: tensor with inputs to the decoder :param context: context from the encoder :param beam_size: b...
rnn_translator/pytorch/seq2seq/models/seq2seq_base.py
def generate(self, inputs, context, beam_size): """ Autoregressive generator, works with SequenceGenerator class. Executes decoder (in inference mode), applies log_softmax and topK for inference with beam search decoding. :param inputs: tensor with inputs to the decoder ...
def generate(self, inputs, context, beam_size): """ Autoregressive generator, works with SequenceGenerator class. Executes decoder (in inference mode), applies log_softmax and topK for inference with beam search decoding. :param inputs: tensor with inputs to the decoder ...
[ "Autoregressive", "generator", "works", "with", "SequenceGenerator", "class", ".", "Executes", "decoder", "(", "in", "inference", "mode", ")", "applies", "log_softmax", "and", "topK", "for", "inference", "with", "beam", "search", "decoding", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/models/seq2seq_base.py#L44-L64
[ "def", "generate", "(", "self", ",", "inputs", ",", "context", ",", "beam_size", ")", ":", "logits", ",", "scores", ",", "new_context", "=", "self", ".", "decode", "(", "inputs", ",", "context", ",", "True", ")", "logprobs", "=", "log_softmax", "(", "l...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Translator.build_eval_path
Appends index of the current epoch and index of the current iteration to the name of the file with results. :param epoch: index of the current epoch :param iteration: index of the current iteration
rnn_translator/pytorch/seq2seq/inference/inference.py
def build_eval_path(self, epoch, iteration): """ Appends index of the current epoch and index of the current iteration to the name of the file with results. :param epoch: index of the current epoch :param iteration: index of the current iteration """ if iteration...
def build_eval_path(self, epoch, iteration): """ Appends index of the current epoch and index of the current iteration to the name of the file with results. :param epoch: index of the current epoch :param iteration: index of the current iteration """ if iteration...
[ "Appends", "index", "of", "the", "current", "epoch", "and", "index", "of", "the", "current", "iteration", "to", "the", "name", "of", "the", "file", "with", "results", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/inference/inference.py#L72-L85
[ "def", "build_eval_path", "(", "self", ",", "epoch", ",", "iteration", ")", ":", "if", "iteration", "is", "not", "None", ":", "eval_fname", "=", "f'eval_epoch_{epoch}_iter_{iteration}'", "else", ":", "eval_fname", "=", "f'eval_epoch_{epoch}'", "eval_path", "=", "o...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Translator.run
Runs translation on test dataset. :param calc_bleu: if True compares results with reference and computes BLEU score :param epoch: index of the current epoch :param iteration: index of the current iteration :param eval_path: path to the file for saving results :param ...
rnn_translator/pytorch/seq2seq/inference/inference.py
def run(self, calc_bleu=True, epoch=None, iteration=None, eval_path=None, summary=False, reference_path=None): """ Runs translation on test dataset. :param calc_bleu: if True compares results with reference and computes BLEU score :param epoch: index of the curre...
def run(self, calc_bleu=True, epoch=None, iteration=None, eval_path=None, summary=False, reference_path=None): """ Runs translation on test dataset. :param calc_bleu: if True compares results with reference and computes BLEU score :param epoch: index of the curre...
[ "Runs", "translation", "on", "test", "dataset", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/inference/inference.py#L87-L145
[ "def", "run", "(", "self", ",", "calc_bleu", "=", "True", ",", "epoch", "=", "None", ",", "iteration", "=", "None", ",", "eval_path", "=", "None", ",", "summary", "=", "False", ",", "reference_path", "=", "None", ")", ":", "if", "self", ".", "cuda", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Translator.evaluate
Runs evaluation on test dataset. :param epoch: index of the current epoch :param iteration: index of the current iteration :param summary: if True prints summary
rnn_translator/pytorch/seq2seq/inference/inference.py
def evaluate(self, epoch, iteration, summary): """ Runs evaluation on test dataset. :param epoch: index of the current epoch :param iteration: index of the current iteration :param summary: if True prints summary """ batch_time = AverageMeter(False) tot_t...
def evaluate(self, epoch, iteration, summary): """ Runs evaluation on test dataset. :param epoch: index of the current epoch :param iteration: index of the current iteration :param summary: if True prints summary """ batch_time = AverageMeter(False) tot_t...
[ "Runs", "evaluation", "on", "test", "dataset", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/inference/inference.py#L147-L255
[ "def", "evaluate", "(", "self", ",", "epoch", ",", "iteration", ",", "summary", ")", ":", "batch_time", "=", "AverageMeter", "(", "False", ")", "tot_tok_per_sec", "=", "AverageMeter", "(", "False", ")", "iterations", "=", "AverageMeter", "(", "False", ")", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Translator.run_detokenizer
Executes moses detokenizer on eval_path file and saves result to eval_path + ".detok" file. :param eval_path: path to the tokenized input
rnn_translator/pytorch/seq2seq/inference/inference.py
def run_detokenizer(self, eval_path): """ Executes moses detokenizer on eval_path file and saves result to eval_path + ".detok" file. :param eval_path: path to the tokenized input """ logging.info('Running detokenizer') detok_path = os.path.join(self.dataset_dir,...
def run_detokenizer(self, eval_path): """ Executes moses detokenizer on eval_path file and saves result to eval_path + ".detok" file. :param eval_path: path to the tokenized input """ logging.info('Running detokenizer') detok_path = os.path.join(self.dataset_dir,...
[ "Executes", "moses", "detokenizer", "on", "eval_path", "file", "and", "saves", "result", "to", "eval_path", "+", ".", "detok", "file", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/inference/inference.py#L257-L271
[ "def", "run_detokenizer", "(", "self", ",", "eval_path", ")", ":", "logging", ".", "info", "(", "'Running detokenizer'", ")", "detok_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dataset_dir", ",", "config", ".", "DETOKENIZER", ")", "detok...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Translator.run_sacrebleu
Executes sacrebleu and returns BLEU score. :param detok_eval_path: path to the test file :param reference_path: path to the reference file
rnn_translator/pytorch/seq2seq/inference/inference.py
def run_sacrebleu(self, detok_eval_path, reference_path): """ Executes sacrebleu and returns BLEU score. :param detok_eval_path: path to the test file :param reference_path: path to the reference file """ if reference_path is None: reference_path = os.path.jo...
def run_sacrebleu(self, detok_eval_path, reference_path): """ Executes sacrebleu and returns BLEU score. :param detok_eval_path: path to the test file :param reference_path: path to the reference file """ if reference_path is None: reference_path = os.path.jo...
[ "Executes", "sacrebleu", "and", "returns", "BLEU", "score", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/inference/inference.py#L273-L289
[ "def", "run_sacrebleu", "(", "self", ",", "detok_eval_path", ",", "reference_path", ")", ":", "if", "reference_path", "is", "None", ":", "reference_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dataset_dir", ",", "config", ".", "TGT_TEST_TAR...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
configure
Configures cloud logging This is called for all main calls. If a $LOGGING_PROJECT is environment variable configured, then STDERR and STDOUT are redirected to cloud logging.
reinforcement/tensorflow/minigo/cloud_logging.py
def configure(project=LOGGING_PROJECT): """Configures cloud logging This is called for all main calls. If a $LOGGING_PROJECT is environment variable configured, then STDERR and STDOUT are redirected to cloud logging. """ if not project: sys.stderr.write('!! Error: The $LOGGING_PROJECT e...
def configure(project=LOGGING_PROJECT): """Configures cloud logging This is called for all main calls. If a $LOGGING_PROJECT is environment variable configured, then STDERR and STDOUT are redirected to cloud logging. """ if not project: sys.stderr.write('!! Error: The $LOGGING_PROJECT e...
[ "Configures", "cloud", "logging" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/cloud_logging.py#L28-L48
[ "def", "configure", "(", "project", "=", "LOGGING_PROJECT", ")", ":", "if", "not", "project", ":", "sys", ".", "stderr", ".", "write", "(", "'!! Error: The $LOGGING_PROJECT enviroment '", "'variable is required in order to set up cloud logging. '", "'Cloud logging is disabled...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
align_and_update_state_dicts
Strategy: suppose that the models that we will create will have prefixes appended to each of its keys, for example due to an extra level of nesting that the original pre-trained weights from ImageNet won't contain. For example, model.state_dict() might return backbone[0].body.res2.conv1.weight, while the pr...
object_detection/pytorch/maskrcnn_benchmark/utils/model_serialization.py
def align_and_update_state_dicts(model_state_dict, loaded_state_dict): """ Strategy: suppose that the models that we will create will have prefixes appended to each of its keys, for example due to an extra level of nesting that the original pre-trained weights from ImageNet won't contain. For example, m...
def align_and_update_state_dicts(model_state_dict, loaded_state_dict): """ Strategy: suppose that the models that we will create will have prefixes appended to each of its keys, for example due to an extra level of nesting that the original pre-trained weights from ImageNet won't contain. For example, m...
[ "Strategy", ":", "suppose", "that", "the", "models", "that", "we", "will", "create", "will", "have", "prefixes", "appended", "to", "each", "of", "its", "keys", "for", "example", "due", "to", "an", "extra", "level", "of", "nesting", "that", "the", "original...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/utils/model_serialization.py#L10-L58
[ "def", "align_and_update_state_dicts", "(", "model_state_dict", ",", "loaded_state_dict", ")", ":", "current_keys", "=", "sorted", "(", "list", "(", "model_state_dict", ".", "keys", "(", ")", ")", ")", "loaded_keys", "=", "sorted", "(", "list", "(", "loaded_stat...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
compute_update_ratio
Compute the ratio of gradient norm to weight norm.
reinforcement/tensorflow/minigo/train.py
def compute_update_ratio(weight_tensors, before_weights, after_weights): """Compute the ratio of gradient norm to weight norm.""" deltas = [after - before for after, before in zip(after_weights, before_weights)] delta_norms = [np.linalg.norm(d.ravel()) for d in deltas] weight_norms = [np.l...
def compute_update_ratio(weight_tensors, before_weights, after_weights): """Compute the ratio of gradient norm to weight norm.""" deltas = [after - before for after, before in zip(after_weights, before_weights)] delta_norms = [np.linalg.norm(d.ravel()) for d in deltas] weight_norms = [np.l...
[ "Compute", "the", "ratio", "of", "gradient", "norm", "to", "weight", "norm", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/train.py#L93-L104
[ "def", "compute_update_ratio", "(", "weight_tensors", ",", "before_weights", ",", "after_weights", ")", ":", "deltas", "=", "[", "after", "-", "before", "for", "after", ",", "before", "in", "zip", "(", "after_weights", ",", "before_weights", ")", "]", "delta_n...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
train
Train on examples.
reinforcement/tensorflow/minigo/train.py
def train(*tf_records: "Records to train on"): """Train on examples.""" tf.logging.set_verbosity(tf.logging.INFO) estimator = dual_net.get_estimator() effective_batch_size = FLAGS.train_batch_size if FLAGS.use_tpu: effective_batch_size *= FLAGS.num_tpu_cores if FLAGS.use_tpu: i...
def train(*tf_records: "Records to train on"): """Train on examples.""" tf.logging.set_verbosity(tf.logging.INFO) estimator = dual_net.get_estimator() effective_batch_size = FLAGS.train_batch_size if FLAGS.use_tpu: effective_batch_size *= FLAGS.num_tpu_cores if FLAGS.use_tpu: i...
[ "Train", "on", "examples", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/train.py#L142-L207
[ "def", "train", "(", "*", "tf_records", ":", "\"Records to train on\"", ")", ":", "tf", ".", "logging", ".", "set_verbosity", "(", "tf", ".", "logging", ".", "INFO", ")", "estimator", "=", "dual_net", ".", "get_estimator", "(", ")", "effective_batch_size", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
main
Train on examples and export the updated model weights.
reinforcement/tensorflow/minigo/train.py
def main(argv): """Train on examples and export the updated model weights.""" tf_records = argv[1:] logging.info("Training on %s records: %s to %s", len(tf_records), tf_records[0], tf_records[-1]) with utils.logged_timer("Training"): train(*tf_records) if FLAGS.export_path: ...
def main(argv): """Train on examples and export the updated model weights.""" tf_records = argv[1:] logging.info("Training on %s records: %s to %s", len(tf_records), tf_records[0], tf_records[-1]) with utils.logged_timer("Training"): train(*tf_records) if FLAGS.export_path: ...
[ "Train", "on", "examples", "and", "export", "the", "updated", "model", "weights", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/train.py#L210-L223
[ "def", "main", "(", "argv", ")", ":", "tf_records", "=", "argv", "[", "1", ":", "]", "logging", ".", "info", "(", "\"Training on %s records: %s to %s\"", ",", "len", "(", "tf_records", ")", ",", "tf_records", "[", "0", "]", ",", "tf_records", "[", "-", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
main
Freeze a model to a GraphDef proto.
reinforcement/tensorflow/minigo/freeze_graph.py
def main(unused_argv): """Freeze a model to a GraphDef proto.""" if FLAGS.use_tpu: dual_net.freeze_graph_tpu(FLAGS.model_path) else: dual_net.freeze_graph(FLAGS.model_path)
def main(unused_argv): """Freeze a model to a GraphDef proto.""" if FLAGS.use_tpu: dual_net.freeze_graph_tpu(FLAGS.model_path) else: dual_net.freeze_graph(FLAGS.model_path)
[ "Freeze", "a", "model", "to", "a", "GraphDef", "proto", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/freeze_graph.py#L27-L32
[ "def", "main", "(", "unused_argv", ")", ":", "if", "FLAGS", ".", "use_tpu", ":", "dual_net", ".", "freeze_graph_tpu", "(", "FLAGS", ".", "model_path", ")", "else", ":", "dual_net", ".", "freeze_graph", "(", "FLAGS", ".", "model_path", ")" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
grouper
Itertools recipe >>> list(grouper(3, iter('ABCDEFG'))) [['A', 'B', 'C'], ['D', 'E', 'F'], ['G']]
reinforcement/tensorflow/minigo/oneoffs/sharp_positions.py
def grouper(n, iterable): """Itertools recipe >>> list(grouper(3, iter('ABCDEFG'))) [['A', 'B', 'C'], ['D', 'E', 'F'], ['G']] """ return (iterable[i:i + n] for i in range(0, len(iterable), n))
def grouper(n, iterable): """Itertools recipe >>> list(grouper(3, iter('ABCDEFG'))) [['A', 'B', 'C'], ['D', 'E', 'F'], ['G']] """ return (iterable[i:i + n] for i in range(0, len(iterable), n))
[ "Itertools", "recipe", ">>>", "list", "(", "grouper", "(", "3", "iter", "(", "ABCDEFG", ")))", "[[", "A", "B", "C", "]", "[", "D", "E", "F", "]", "[", "G", "]]" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/oneoffs/sharp_positions.py#L91-L96
[ "def", "grouper", "(", "n", ",", "iterable", ")", ":", "return", "(", "iterable", "[", "i", ":", "i", "+", "n", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "iterable", ")", ",", "n", ")", ")" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
subsample
Sample num_positions postions from each game in sgf_dir Usage: python3 sharp_positions.py subsample --num_positions 10 --sgf_dir data/s NOTE(sethtroisi): see link for a script to truncate SGFs at move number https://github.com/sethtroisi/go-scripts
reinforcement/tensorflow/minigo/oneoffs/sharp_positions.py
def subsample(): """Sample num_positions postions from each game in sgf_dir Usage: python3 sharp_positions.py subsample --num_positions 10 --sgf_dir data/s NOTE(sethtroisi): see link for a script to truncate SGFs at move number https://github.com/sethtroisi/go-scripts """ sgf_file...
def subsample(): """Sample num_positions postions from each game in sgf_dir Usage: python3 sharp_positions.py subsample --num_positions 10 --sgf_dir data/s NOTE(sethtroisi): see link for a script to truncate SGFs at move number https://github.com/sethtroisi/go-scripts """ sgf_file...
[ "Sample", "num_positions", "postions", "from", "each", "game", "in", "sgf_dir" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/oneoffs/sharp_positions.py#L115-L143
[ "def", "subsample", "(", ")", ":", "sgf_files", "=", "oneoff_utils", ".", "find_and_filter_sgf_files", "(", "FLAGS", ".", "sgf_dir", ",", "None", ",", "None", ")", "with", "open", "(", "FLAG", ".", "collection", ",", "'w'", ")", "as", "collection", ":", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
evaluate
Get Policy and Value for each network, for each position Usage: python3 sharp_positions.py evaluate --sgf_dir data/s --model_dir models/
reinforcement/tensorflow/minigo/oneoffs/sharp_positions.py
def evaluate(): """Get Policy and Value for each network, for each position Usage: python3 sharp_positions.py evaluate --sgf_dir data/s --model_dir models/ """ def short_str(v): if isinstance(v, float): return "{.3f}".format(v) return str(v) # Load positons ...
def evaluate(): """Get Policy and Value for each network, for each position Usage: python3 sharp_positions.py evaluate --sgf_dir data/s --model_dir models/ """ def short_str(v): if isinstance(v, float): return "{.3f}".format(v) return str(v) # Load positons ...
[ "Get", "Policy", "and", "Value", "for", "each", "network", "for", "each", "position" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/oneoffs/sharp_positions.py#L146-L206
[ "def", "evaluate", "(", ")", ":", "def", "short_str", "(", "v", ")", ":", "if", "isinstance", "(", "v", ",", "float", ")", ":", "return", "\"{.3f}\"", ".", "format", "(", "v", ")", "return", "str", "(", "v", ")", "# Load positons", "sgf_names", ",", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
minimize
Find a subset of problems that maximal explains rating. Usage: python3 sharp_positions.py minimize \ --model_dir models --sgf_dir data/s --rating_json ratings.json --results results.csv
reinforcement/tensorflow/minigo/oneoffs/sharp_positions.py
def minimize(): """Find a subset of problems that maximal explains rating. Usage: python3 sharp_positions.py minimize \ --model_dir models --sgf_dir data/s --rating_json ratings.json --results results.csv """ ########################### HYPER PARAMETERS #################...
def minimize(): """Find a subset of problems that maximal explains rating. Usage: python3 sharp_positions.py minimize \ --model_dir models --sgf_dir data/s --rating_json ratings.json --results results.csv """ ########################### HYPER PARAMETERS #################...
[ "Find", "a", "subset", "of", "problems", "that", "maximal", "explains", "rating", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/oneoffs/sharp_positions.py#L209-L438
[ "def", "minimize", "(", ")", ":", "########################### HYPER PARAMETERS ###############################", "# Stop when r2 is this much worse than full set of positions", "r2_stopping_percent", "=", "0.96", "# for this many iterations", "stopping_iterations", "=", "5", "# Limit SV...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4