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
download_from_url
Download content from a url. Args: path: string directory where file will be downloaded url: string url Returns: Full path to downloaded file
translation/tensorflow/process_data.py
def download_from_url(path, url): """Download content from a url. Args: path: string directory where file will be downloaded url: string url Returns: Full path to downloaded file """ filename = url.split("/")[-1] found_file = find_file(path, filename, max_depth=0) if found_file is None: ...
def download_from_url(path, url): """Download content from a url. Args: path: string directory where file will be downloaded url: string url Returns: Full path to downloaded file """ filename = url.split("/")[-1] found_file = find_file(path, filename, max_depth=0) if found_file is None: ...
[ "Download", "content", "from", "a", "url", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/process_data.py#L146-L170
[ "def", "download_from_url", "(", "path", ",", "url", ")", ":", "filename", "=", "url", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", "found_file", "=", "find_file", "(", "path", ",", "filename", ",", "max_depth", "=", "0", ")", "if", "found_fi...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
project_masks_on_boxes
Given segmentation masks and the bounding boxes corresponding to the location of the masks in the image, this function crops and resizes the masks in the position defined by the boxes. This prepares the masks for them to be fed to the loss computation as the targets. Arguments: segmentation...
object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/mask_head/loss.py
def project_masks_on_boxes(segmentation_masks, proposals, discretization_size): """ Given segmentation masks and the bounding boxes corresponding to the location of the masks in the image, this function crops and resizes the masks in the position defined by the boxes. This prepares the masks for the...
def project_masks_on_boxes(segmentation_masks, proposals, discretization_size): """ Given segmentation masks and the bounding boxes corresponding to the location of the masks in the image, this function crops and resizes the masks in the position defined by the boxes. This prepares the masks for the...
[ "Given", "segmentation", "masks", "and", "the", "bounding", "boxes", "corresponding", "to", "the", "location", "of", "the", "masks", "in", "the", "image", "this", "function", "crops", "and", "resizes", "the", "masks", "in", "the", "position", "defined", "by", ...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/mask_head/loss.py#L11-L44
[ "def", "project_masks_on_boxes", "(", "segmentation_masks", ",", "proposals", ",", "discretization_size", ")", ":", "masks", "=", "[", "]", "M", "=", "discretization_size", "device", "=", "proposals", ".", "bbox", ".", "device", "proposals", "=", "proposals", "....
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
evaluate_box_proposals
Evaluate detection proposal recall metrics. This function is a much faster alternative to the official COCO API recall evaluation code. However, it produces slightly different results.
object_detection/pytorch/maskrcnn_benchmark/data/datasets/evaluation/coco/coco_eval.py
def evaluate_box_proposals( predictions, dataset, thresholds=None, area="all", limit=None ): """Evaluate detection proposal recall metrics. This function is a much faster alternative to the official COCO API recall evaluation code. However, it produces slightly different results. """ # Record ma...
def evaluate_box_proposals( predictions, dataset, thresholds=None, area="all", limit=None ): """Evaluate detection proposal recall metrics. This function is a much faster alternative to the official COCO API recall evaluation code. However, it produces slightly different results. """ # Record ma...
[ "Evaluate", "detection", "proposal", "recall", "metrics", ".", "This", "function", "is", "a", "much", "faster", "alternative", "to", "the", "official", "COCO", "API", "recall", "evaluation", "code", ".", "However", "it", "produces", "slightly", "different", "res...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/data/datasets/evaluation/coco/coco_eval.py#L189-L302
[ "def", "evaluate_box_proposals", "(", "predictions", ",", "dataset", ",", "thresholds", "=", "None", ",", "area", "=", "\"all\"", ",", "limit", "=", "None", ")", ":", "# Record max overlap value for each gt box", "# Return vector of overlap values", "areas", "=", "{",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_decode_crop_and_flip
Crops the given image to a random part of the image, and randomly flips. We use the fused decode_and_crop op, which performs better than the two ops used separately in series, but note that this requires that the image be passed in as an un-decoded string Tensor. Args: image_buffer: scalar string Tensor r...
image_classification/tensorflow/official/resnet/imagenet_preprocessing.py
def _decode_crop_and_flip(image_buffer, num_channels): """Crops the given image to a random part of the image, and randomly flips. We use the fused decode_and_crop op, which performs better than the two ops used separately in series, but note that this requires that the image be passed in as an un-decoded stri...
def _decode_crop_and_flip(image_buffer, num_channels): """Crops the given image to a random part of the image, and randomly flips. We use the fused decode_and_crop op, which performs better than the two ops used separately in series, but note that this requires that the image be passed in as an un-decoded stri...
[ "Crops", "the", "given", "image", "to", "a", "random", "part", "of", "the", "image", "and", "randomly", "flips", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/imagenet_preprocessing.py#L54-L116
[ "def", "_decode_crop_and_flip", "(", "image_buffer", ",", "num_channels", ")", ":", "# A large fraction of image datasets contain a human-annotated bounding box", "# delineating the region of the image containing the object of interest. We", "# choose to create a new bounding box for the object...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_central_crop
Performs central crops of the given image list. Args: image: a 3-D image tensor crop_height: the height of the image following the crop. crop_width: the width of the image following the crop. Returns: 3-D tensor with cropped image.
image_classification/tensorflow/official/resnet/imagenet_preprocessing.py
def _central_crop(image, crop_height, crop_width): """Performs central crops of the given image list. Args: image: a 3-D image tensor crop_height: the height of the image following the crop. crop_width: the width of the image following the crop. Returns: 3-D tensor with cropped image. """ sh...
def _central_crop(image, crop_height, crop_width): """Performs central crops of the given image list. Args: image: a 3-D image tensor crop_height: the height of the image following the crop. crop_width: the width of the image following the crop. Returns: 3-D tensor with cropped image. """ sh...
[ "Performs", "central", "crops", "of", "the", "given", "image", "list", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/imagenet_preprocessing.py#L119-L141
[ "def", "_central_crop", "(", "image", ",", "crop_height", ",", "crop_width", ")", ":", "shape", "=", "tf", ".", "shape", "(", "image", ")", "height", ",", "width", "=", "shape", "[", "0", "]", ",", "shape", "[", "1", "]", "mlperf_log", ".", "resnet_p...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_mean_image_subtraction
Subtracts the given means from each image channel. For example: means = [123.68, 116.779, 103.939] image = _mean_image_subtraction(image, means) Note that the rank of `image` must be known. Args: image: a tensor of size [height, width, C]. means: a C-vector of values to subtract from each chann...
image_classification/tensorflow/official/resnet/imagenet_preprocessing.py
def _mean_image_subtraction(image, means, num_channels): """Subtracts the given means from each image channel. For example: means = [123.68, 116.779, 103.939] image = _mean_image_subtraction(image, means) Note that the rank of `image` must be known. Args: image: a tensor of size [height, width, C...
def _mean_image_subtraction(image, means, num_channels): """Subtracts the given means from each image channel. For example: means = [123.68, 116.779, 103.939] image = _mean_image_subtraction(image, means) Note that the rank of `image` must be known. Args: image: a tensor of size [height, width, C...
[ "Subtracts", "the", "given", "means", "from", "each", "image", "channel", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/imagenet_preprocessing.py#L144-L178
[ "def", "_mean_image_subtraction", "(", "image", ",", "means", ",", "num_channels", ")", ":", "if", "image", ".", "get_shape", "(", ")", ".", "ndims", "!=", "3", ":", "raise", "ValueError", "(", "'Input must be of size [height, width, C>0]'", ")", "if", "len", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_smallest_size_at_least
Computes new shape with the smallest side equal to `smallest_side`. Computes new shape with the smallest side equal to `smallest_side` while preserving the original aspect ratio. Args: height: an int32 scalar tensor indicating the current height. width: an int32 scalar tensor indicating the current widt...
image_classification/tensorflow/official/resnet/imagenet_preprocessing.py
def _smallest_size_at_least(height, width, resize_min): """Computes new shape with the smallest side equal to `smallest_side`. Computes new shape with the smallest side equal to `smallest_side` while preserving the original aspect ratio. Args: height: an int32 scalar tensor indicating the current height. ...
def _smallest_size_at_least(height, width, resize_min): """Computes new shape with the smallest side equal to `smallest_side`. Computes new shape with the smallest side equal to `smallest_side` while preserving the original aspect ratio. Args: height: an int32 scalar tensor indicating the current height. ...
[ "Computes", "new", "shape", "with", "the", "smallest", "side", "equal", "to", "smallest_side", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/imagenet_preprocessing.py#L181-L209
[ "def", "_smallest_size_at_least", "(", "height", ",", "width", ",", "resize_min", ")", ":", "resize_min", "=", "tf", ".", "cast", "(", "resize_min", ",", "tf", ".", "float32", ")", "# Convert to floats to make subsequent calculations go smoothly.", "height", ",", "w...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_aspect_preserving_resize
Resize images preserving the original aspect ratio. Args: image: A 3-D image `Tensor`. resize_min: A python integer or scalar `Tensor` indicating the size of the smallest side after resize. Returns: resized_image: A 3-D tensor containing the resized image.
image_classification/tensorflow/official/resnet/imagenet_preprocessing.py
def _aspect_preserving_resize(image, resize_min): """Resize images preserving the original aspect ratio. Args: image: A 3-D image `Tensor`. resize_min: A python integer or scalar `Tensor` indicating the size of the smallest side after resize. Returns: resized_image: A 3-D tensor containing the...
def _aspect_preserving_resize(image, resize_min): """Resize images preserving the original aspect ratio. Args: image: A 3-D image `Tensor`. resize_min: A python integer or scalar `Tensor` indicating the size of the smallest side after resize. Returns: resized_image: A 3-D tensor containing the...
[ "Resize", "images", "preserving", "the", "original", "aspect", "ratio", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/imagenet_preprocessing.py#L212-L231
[ "def", "_aspect_preserving_resize", "(", "image", ",", "resize_min", ")", ":", "mlperf_log", ".", "resnet_print", "(", "key", "=", "mlperf_log", ".", "INPUT_RESIZE_ASPECT_PRESERVING", ",", "value", "=", "{", "\"min\"", ":", "resize_min", "}", ")", "shape", "=", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_resize_image
Simple wrapper around tf.resize_images. This is primarily to make sure we use the same `ResizeMethod` and other details each time. Args: image: A 3-D image `Tensor`. height: The target height for the resized image. width: The target width for the resized image. Returns: resized_image: A 3-D t...
image_classification/tensorflow/official/resnet/imagenet_preprocessing.py
def _resize_image(image, height, width): """Simple wrapper around tf.resize_images. This is primarily to make sure we use the same `ResizeMethod` and other details each time. Args: image: A 3-D image `Tensor`. height: The target height for the resized image. width: The target width for the resized...
def _resize_image(image, height, width): """Simple wrapper around tf.resize_images. This is primarily to make sure we use the same `ResizeMethod` and other details each time. Args: image: A 3-D image `Tensor`. height: The target height for the resized image. width: The target width for the resized...
[ "Simple", "wrapper", "around", "tf", ".", "resize_images", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/imagenet_preprocessing.py#L234-L251
[ "def", "_resize_image", "(", "image", ",", "height", ",", "width", ")", ":", "return", "tf", ".", "image", ".", "resize_images", "(", "image", ",", "[", "height", ",", "width", "]", ",", "method", "=", "tf", ".", "image", ".", "ResizeMethod", ".", "B...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
preprocess_image
Preprocesses the given image. Preprocessing includes decoding, cropping, and resizing for both training and eval images. Training preprocessing, however, introduces some random distortion of the image to improve accuracy. Args: image_buffer: scalar string Tensor representing the raw JPEG image buffer. ...
image_classification/tensorflow/official/resnet/imagenet_preprocessing.py
def preprocess_image(image_buffer, output_height, output_width, num_channels, is_training=False): """Preprocesses the given image. Preprocessing includes decoding, cropping, and resizing for both training and eval images. Training preprocessing, however, introduces some random distortion o...
def preprocess_image(image_buffer, output_height, output_width, num_channels, is_training=False): """Preprocesses the given image. Preprocessing includes decoding, cropping, and resizing for both training and eval images. Training preprocessing, however, introduces some random distortion o...
[ "Preprocesses", "the", "given", "image", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/imagenet_preprocessing.py#L254-L291
[ "def", "preprocess_image", "(", "image_buffer", ",", "output_height", ",", "output_width", ",", "num_channels", ",", "is_training", "=", "False", ")", ":", "if", "is_training", ":", "# For training, we want to randomize some of the distortions.", "image", "=", "_decode_cr...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
sequence_beam_search
Search for sequence of subtoken ids with the largest probability. Args: symbols_to_logits_fn: A function that takes in ids, index, and cache as arguments. The passed in arguments will have shape: ids -> [batch_size * beam_size, index] index -> [] (scalar) cache -> nested dictionary ...
translation/tensorflow/transformer/model/beam_search.py
def sequence_beam_search( symbols_to_logits_fn, initial_ids, initial_cache, vocab_size, beam_size, alpha, max_decode_length, eos_id): """Search for sequence of subtoken ids with the largest probability. Args: symbols_to_logits_fn: A function that takes in ids, index, and cache as arguments. The p...
def sequence_beam_search( symbols_to_logits_fn, initial_ids, initial_cache, vocab_size, beam_size, alpha, max_decode_length, eos_id): """Search for sequence of subtoken ids with the largest probability. Args: symbols_to_logits_fn: A function that takes in ids, index, and cache as arguments. The p...
[ "Search", "for", "sequence", "of", "subtoken", "ids", "with", "the", "largest", "probability", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/beam_search.py#L387-L417
[ "def", "sequence_beam_search", "(", "symbols_to_logits_fn", ",", "initial_ids", ",", "initial_cache", ",", "vocab_size", ",", "beam_size", ",", "alpha", ",", "max_decode_length", ",", "eos_id", ")", ":", "batch_size", "=", "tf", ".", "shape", "(", "initial_ids", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_shape_list
Return a list of the tensor's shape, and ensure no None values in list.
translation/tensorflow/transformer/model/beam_search.py
def _shape_list(tensor): """Return a list of the tensor's shape, and ensure no None values in list.""" # Get statically known shape (may contain None's for unknown dimensions) shape = tensor.get_shape().as_list() # Ensure that the shape values are not None dynamic_shape = tf.shape(tensor) for i in range(le...
def _shape_list(tensor): """Return a list of the tensor's shape, and ensure no None values in list.""" # Get statically known shape (may contain None's for unknown dimensions) shape = tensor.get_shape().as_list() # Ensure that the shape values are not None dynamic_shape = tf.shape(tensor) for i in range(le...
[ "Return", "a", "list", "of", "the", "tensor", "s", "shape", "and", "ensure", "no", "None", "values", "in", "list", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/beam_search.py#L446-L456
[ "def", "_shape_list", "(", "tensor", ")", ":", "# Get statically known shape (may contain None's for unknown dimensions)", "shape", "=", "tensor", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "# Ensure that the shape values are not None", "dynamic_shape", "=", "tf"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_flatten_beam_dim
Reshapes first two dimensions in to single dimension. Args: tensor: Tensor to reshape of shape [A, B, ...] Returns: Reshaped tensor of shape [A*B, ...]
translation/tensorflow/transformer/model/beam_search.py
def _flatten_beam_dim(tensor): """Reshapes first two dimensions in to single dimension. Args: tensor: Tensor to reshape of shape [A, B, ...] Returns: Reshaped tensor of shape [A*B, ...] """ shape = _shape_list(tensor) shape[0] *= shape[1] shape.pop(1) # Remove beam dim return tf.reshape(tenso...
def _flatten_beam_dim(tensor): """Reshapes first two dimensions in to single dimension. Args: tensor: Tensor to reshape of shape [A, B, ...] Returns: Reshaped tensor of shape [A*B, ...] """ shape = _shape_list(tensor) shape[0] *= shape[1] shape.pop(1) # Remove beam dim return tf.reshape(tenso...
[ "Reshapes", "first", "two", "dimensions", "in", "to", "single", "dimension", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/beam_search.py#L471-L483
[ "def", "_flatten_beam_dim", "(", "tensor", ")", ":", "shape", "=", "_shape_list", "(", "tensor", ")", "shape", "[", "0", "]", "*=", "shape", "[", "1", "]", "shape", ".", "pop", "(", "1", ")", "# Remove beam dim", "return", "tf", ".", "reshape", "(", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_unflatten_beam_dim
Reshapes first dimension back to [batch_size, beam_size]. Args: tensor: Tensor to reshape of shape [batch_size*beam_size, ...] batch_size: Tensor, original batch size. beam_size: int, original beam size. Returns: Reshaped tensor of shape [batch_size, beam_size, ...]
translation/tensorflow/transformer/model/beam_search.py
def _unflatten_beam_dim(tensor, batch_size, beam_size): """Reshapes first dimension back to [batch_size, beam_size]. Args: tensor: Tensor to reshape of shape [batch_size*beam_size, ...] batch_size: Tensor, original batch size. beam_size: int, original beam size. Returns: Reshaped tensor of shape...
def _unflatten_beam_dim(tensor, batch_size, beam_size): """Reshapes first dimension back to [batch_size, beam_size]. Args: tensor: Tensor to reshape of shape [batch_size*beam_size, ...] batch_size: Tensor, original batch size. beam_size: int, original beam size. Returns: Reshaped tensor of shape...
[ "Reshapes", "first", "dimension", "back", "to", "[", "batch_size", "beam_size", "]", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/beam_search.py#L486-L499
[ "def", "_unflatten_beam_dim", "(", "tensor", ",", "batch_size", ",", "beam_size", ")", ":", "shape", "=", "_shape_list", "(", "tensor", ")", "new_shape", "=", "[", "batch_size", ",", "beam_size", "]", "+", "shape", "[", "1", ":", "]", "return", "tf", "."...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_gather_beams
Gather beams from nested structure of tensors. Each tensor in nested represents a batch of beams, where beam refers to a single search state (beam search involves searching through multiple states in parallel). This function is used to gather the top beams, specified by beam_indices, from the nested tensors...
translation/tensorflow/transformer/model/beam_search.py
def _gather_beams(nested, beam_indices, batch_size, new_beam_size): """Gather beams from nested structure of tensors. Each tensor in nested represents a batch of beams, where beam refers to a single search state (beam search involves searching through multiple states in parallel). This function is used to g...
def _gather_beams(nested, beam_indices, batch_size, new_beam_size): """Gather beams from nested structure of tensors. Each tensor in nested represents a batch of beams, where beam refers to a single search state (beam search involves searching through multiple states in parallel). This function is used to g...
[ "Gather", "beams", "from", "nested", "structure", "of", "tensors", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/beam_search.py#L502-L536
[ "def", "_gather_beams", "(", "nested", ",", "beam_indices", ",", "batch_size", ",", "new_beam_size", ")", ":", "# Computes the i'th coodinate that contains the batch index for gather_nd.", "# Batch pos is a tensor like [[0,0,0,0,],[1,1,1,1],..].", "batch_pos", "=", "tf", ".", "ra...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_gather_topk_beams
Gather top beams from nested structure.
translation/tensorflow/transformer/model/beam_search.py
def _gather_topk_beams(nested, score_or_log_prob, batch_size, beam_size): """Gather top beams from nested structure.""" _, topk_indexes = tf.nn.top_k(score_or_log_prob, k=beam_size) return _gather_beams(nested, topk_indexes, batch_size, beam_size)
def _gather_topk_beams(nested, score_or_log_prob, batch_size, beam_size): """Gather top beams from nested structure.""" _, topk_indexes = tf.nn.top_k(score_or_log_prob, k=beam_size) return _gather_beams(nested, topk_indexes, batch_size, beam_size)
[ "Gather", "top", "beams", "from", "nested", "structure", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/beam_search.py#L539-L542
[ "def", "_gather_topk_beams", "(", "nested", ",", "score_or_log_prob", ",", "batch_size", ",", "beam_size", ")", ":", "_", ",", "topk_indexes", "=", "tf", ".", "nn", ".", "top_k", "(", "score_or_log_prob", ",", "k", "=", "beam_size", ")", "return", "_gather_b...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
SequenceBeamSearch.search
Beam search for sequences with highest scores.
translation/tensorflow/transformer/model/beam_search.py
def search(self, initial_ids, initial_cache): """Beam search for sequences with highest scores.""" state, state_shapes = self._create_initial_state(initial_ids, initial_cache) finished_state = tf.while_loop( self._continue_search, self._search_step, loop_vars=[state], shape_invariants=[stat...
def search(self, initial_ids, initial_cache): """Beam search for sequences with highest scores.""" state, state_shapes = self._create_initial_state(initial_ids, initial_cache) finished_state = tf.while_loop( self._continue_search, self._search_step, loop_vars=[state], shape_invariants=[stat...
[ "Beam", "search", "for", "sequences", "with", "highest", "scores", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/beam_search.py#L73-L95
[ "def", "search", "(", "self", ",", "initial_ids", ",", "initial_cache", ")", ":", "state", ",", "state_shapes", "=", "self", ".", "_create_initial_state", "(", "initial_ids", ",", "initial_cache", ")", "finished_state", "=", "tf", ".", "while_loop", "(", "self...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
SequenceBeamSearch._create_initial_state
Return initial state dictionary and its shape invariants. Args: initial_ids: initial ids to pass into the symbols_to_logits_fn. int tensor with shape [batch_size, 1] initial_cache: dictionary storing values to be passed into the symbols_to_logits_fn. Returns: state and shap...
translation/tensorflow/transformer/model/beam_search.py
def _create_initial_state(self, initial_ids, initial_cache): """Return initial state dictionary and its shape invariants. Args: initial_ids: initial ids to pass into the symbols_to_logits_fn. int tensor with shape [batch_size, 1] initial_cache: dictionary storing values to be passed into th...
def _create_initial_state(self, initial_ids, initial_cache): """Return initial state dictionary and its shape invariants. Args: initial_ids: initial ids to pass into the symbols_to_logits_fn. int tensor with shape [batch_size, 1] initial_cache: dictionary storing values to be passed into th...
[ "Return", "initial", "state", "dictionary", "and", "its", "shape", "invariants", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/beam_search.py#L97-L163
[ "def", "_create_initial_state", "(", "self", ",", "initial_ids", ",", "initial_cache", ")", ":", "# Current loop index (starts at 0)", "cur_index", "=", "tf", ".", "constant", "(", "0", ")", "# Create alive sequence with shape [batch_size, beam_size, 1]", "alive_seq", "=", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
SequenceBeamSearch._continue_search
Return whether to continue the search loop. The loops should terminate when 1) when decode length has been reached, or 2) when the worst score in the finished sequences is better than the best score in the alive sequences (i.e. the finished sequences are provably unchanging) Args...
translation/tensorflow/transformer/model/beam_search.py
def _continue_search(self, state): """Return whether to continue the search loop. The loops should terminate when 1) when decode length has been reached, or 2) when the worst score in the finished sequences is better than the best score in the alive sequences (i.e. the finished sequences a...
def _continue_search(self, state): """Return whether to continue the search loop. The loops should terminate when 1) when decode length has been reached, or 2) when the worst score in the finished sequences is better than the best score in the alive sequences (i.e. the finished sequences a...
[ "Return", "whether", "to", "continue", "the", "search", "loop", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/beam_search.py#L165-L209
[ "def", "_continue_search", "(", "self", ",", "state", ")", ":", "i", "=", "state", "[", "_StateKeys", ".", "CUR_INDEX", "]", "alive_log_probs", "=", "state", "[", "_StateKeys", ".", "ALIVE_LOG_PROBS", "]", "finished_scores", "=", "state", "[", "_StateKeys", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
SequenceBeamSearch._search_step
Beam search loop body. Grow alive sequences by a single ID. Sequences that have reached the EOS token are marked as finished. The alive and finished sequences with the highest log probabilities and scores are returned. A sequence's finished score is calculating by dividing the log probability by t...
translation/tensorflow/transformer/model/beam_search.py
def _search_step(self, state): """Beam search loop body. Grow alive sequences by a single ID. Sequences that have reached the EOS token are marked as finished. The alive and finished sequences with the highest log probabilities and scores are returned. A sequence's finished score is calculating by...
def _search_step(self, state): """Beam search loop body. Grow alive sequences by a single ID. Sequences that have reached the EOS token are marked as finished. The alive and finished sequences with the highest log probabilities and scores are returned. A sequence's finished score is calculating by...
[ "Beam", "search", "loop", "body", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/beam_search.py#L211-L241
[ "def", "_search_step", "(", "self", ",", "state", ")", ":", "# Grow alive sequences by one token.", "new_seq", ",", "new_log_probs", ",", "new_cache", "=", "self", ".", "_grow_alive_seq", "(", "state", ")", "# Collect top beam_size alive sequences", "alive_state", "=", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
SequenceBeamSearch._grow_alive_seq
Grow alive sequences by one token, and collect top 2*beam_size sequences. 2*beam_size sequences are collected because some sequences may have reached the EOS token. 2*beam_size ensures that at least beam_size sequences are still alive. Args: state: A dictionary with the current loop state. R...
translation/tensorflow/transformer/model/beam_search.py
def _grow_alive_seq(self, state): """Grow alive sequences by one token, and collect top 2*beam_size sequences. 2*beam_size sequences are collected because some sequences may have reached the EOS token. 2*beam_size ensures that at least beam_size sequences are still alive. Args: state: A dict...
def _grow_alive_seq(self, state): """Grow alive sequences by one token, and collect top 2*beam_size sequences. 2*beam_size sequences are collected because some sequences may have reached the EOS token. 2*beam_size ensures that at least beam_size sequences are still alive. Args: state: A dict...
[ "Grow", "alive", "sequences", "by", "one", "token", "and", "collect", "top", "2", "*", "beam_size", "sequences", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/beam_search.py#L243-L303
[ "def", "_grow_alive_seq", "(", "self", ",", "state", ")", ":", "i", "=", "state", "[", "_StateKeys", ".", "CUR_INDEX", "]", "alive_seq", "=", "state", "[", "_StateKeys", ".", "ALIVE_SEQ", "]", "alive_log_probs", "=", "state", "[", "_StateKeys", ".", "ALIVE...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
SequenceBeamSearch._get_new_alive_state
Gather the top k sequences that are still alive. Args: new_seq: New sequences generated by growing the current alive sequences int32 tensor with shape [batch_size, 2 * beam_size, cur_index + 1] new_log_probs: Log probabilities of new sequences float32 tensor with shape [batch_size, beam...
translation/tensorflow/transformer/model/beam_search.py
def _get_new_alive_state(self, new_seq, new_log_probs, new_cache): """Gather the top k sequences that are still alive. Args: new_seq: New sequences generated by growing the current alive sequences int32 tensor with shape [batch_size, 2 * beam_size, cur_index + 1] new_log_probs: Log probabil...
def _get_new_alive_state(self, new_seq, new_log_probs, new_cache): """Gather the top k sequences that are still alive. Args: new_seq: New sequences generated by growing the current alive sequences int32 tensor with shape [batch_size, 2 * beam_size, cur_index + 1] new_log_probs: Log probabil...
[ "Gather", "the", "top", "k", "sequences", "that", "are", "still", "alive", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/beam_search.py#L305-L333
[ "def", "_get_new_alive_state", "(", "self", ",", "new_seq", ",", "new_log_probs", ",", "new_cache", ")", ":", "# To prevent finished sequences from being considered, set log probs to -INF", "new_finished_flags", "=", "tf", ".", "equal", "(", "new_seq", "[", ":", ",", ":...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
SequenceBeamSearch._get_new_finished_state
Combine new and old finished sequences, and gather the top k sequences. Args: state: A dictionary with the current loop state. new_seq: New sequences generated by growing the current alive sequences int32 tensor with shape [batch_size, beam_size, i + 1] new_log_probs: Log probabilities of...
translation/tensorflow/transformer/model/beam_search.py
def _get_new_finished_state(self, state, new_seq, new_log_probs): """Combine new and old finished sequences, and gather the top k sequences. Args: state: A dictionary with the current loop state. new_seq: New sequences generated by growing the current alive sequences int32 tensor with shape...
def _get_new_finished_state(self, state, new_seq, new_log_probs): """Combine new and old finished sequences, and gather the top k sequences. Args: state: A dictionary with the current loop state. new_seq: New sequences generated by growing the current alive sequences int32 tensor with shape...
[ "Combine", "new", "and", "old", "finished", "sequences", "and", "gather", "the", "top", "k", "sequences", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/beam_search.py#L335-L384
[ "def", "_get_new_finished_state", "(", "self", ",", "state", ",", "new_seq", ",", "new_log_probs", ")", ":", "i", "=", "state", "[", "_StateKeys", ".", "CUR_INDEX", "]", "finished_seq", "=", "state", "[", "_StateKeys", ".", "FINISHED_SEQ", "]", "finished_score...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
BahdanauAttention.reset_parameters
Sets initial random values for trainable parameters.
rnn_translator/pytorch/seq2seq/models/attention.py
def reset_parameters(self, init_weight): """ Sets initial random values for trainable parameters. """ stdv = 1. / math.sqrt(self.num_units) self.linear_att.data.uniform_(-init_weight, init_weight) if self.normalize: self.normalize_scalar.data.fill_(stdv) ...
def reset_parameters(self, init_weight): """ Sets initial random values for trainable parameters. """ stdv = 1. / math.sqrt(self.num_units) self.linear_att.data.uniform_(-init_weight, init_weight) if self.normalize: self.normalize_scalar.data.fill_(stdv) ...
[ "Sets", "initial", "random", "values", "for", "trainable", "parameters", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/models/attention.py#L52-L61
[ "def", "reset_parameters", "(", "self", ",", "init_weight", ")", ":", "stdv", "=", "1.", "/", "math", ".", "sqrt", "(", "self", ".", "num_units", ")", "self", ".", "linear_att", ".", "data", ".", "uniform_", "(", "-", "init_weight", ",", "init_weight", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
BahdanauAttention.set_mask
sets self.mask which is applied before softmax ones for inactive context fields, zeros for active context fields :param context_len: b :param context: if batch_first: (b x t_k x n) else: (t_k x b x n) self.mask: (b x t_k)
rnn_translator/pytorch/seq2seq/models/attention.py
def set_mask(self, context_len, context): """ sets self.mask which is applied before softmax ones for inactive context fields, zeros for active context fields :param context_len: b :param context: if batch_first: (b x t_k x n) else: (t_k x b x n) self.mask: (b x t_k) ...
def set_mask(self, context_len, context): """ sets self.mask which is applied before softmax ones for inactive context fields, zeros for active context fields :param context_len: b :param context: if batch_first: (b x t_k x n) else: (t_k x b x n) self.mask: (b x t_k) ...
[ "sets", "self", ".", "mask", "which", "is", "applied", "before", "softmax", "ones", "for", "inactive", "context", "fields", "zeros", "for", "active", "context", "fields" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/models/attention.py#L63-L81
[ "def", "set_mask", "(", "self", ",", "context_len", ",", "context", ")", ":", "if", "self", ".", "batch_first", ":", "max_len", "=", "context", ".", "size", "(", "1", ")", "else", ":", "max_len", "=", "context", ".", "size", "(", "0", ")", "indices",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
BahdanauAttention.calc_score
Calculate Bahdanau score :param att_query: b x t_q x n :param att_keys: b x t_k x n returns: b x t_q x t_k scores
rnn_translator/pytorch/seq2seq/models/attention.py
def calc_score(self, att_query, att_keys): """ Calculate Bahdanau score :param att_query: b x t_q x n :param att_keys: b x t_k x n returns: b x t_q x t_k scores """ b, t_k, n = att_keys.size() t_q = att_query.size(1) att_query = att_query.unsqu...
def calc_score(self, att_query, att_keys): """ Calculate Bahdanau score :param att_query: b x t_q x n :param att_keys: b x t_k x n returns: b x t_q x t_k scores """ b, t_k, n = att_keys.size() t_q = att_query.size(1) att_query = att_query.unsqu...
[ "Calculate", "Bahdanau", "score" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/models/attention.py#L83-L108
[ "def", "calc_score", "(", "self", ",", "att_query", ",", "att_keys", ")", ":", "b", ",", "t_k", ",", "n", "=", "att_keys", ".", "size", "(", ")", "t_q", "=", "att_query", ".", "size", "(", "1", ")", "att_query", "=", "att_query", ".", "unsqueeze", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_position_encoding
Return positional encoding. Calculates the position encoding as a mix of sine and cosine functions with geometrically increasing wavelengths. Defined and formulized in Attention is All You Need, section 3.5. Args: length: Sequence length. hidden_size: Size of the min_timescale: Minimum scale that ...
translation/tensorflow/transformer/model/model_utils.py
def get_position_encoding( length, hidden_size, min_timescale=1.0, max_timescale=1.0e4): """Return positional encoding. Calculates the position encoding as a mix of sine and cosine functions with geometrically increasing wavelengths. Defined and formulized in Attention is All You Need, section 3.5. Args...
def get_position_encoding( length, hidden_size, min_timescale=1.0, max_timescale=1.0e4): """Return positional encoding. Calculates the position encoding as a mix of sine and cosine functions with geometrically increasing wavelengths. Defined and formulized in Attention is All You Need, section 3.5. Args...
[ "Return", "positional", "encoding", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/model_utils.py#L28-L54
[ "def", "get_position_encoding", "(", "length", ",", "hidden_size", ",", "min_timescale", "=", "1.0", ",", "max_timescale", "=", "1.0e4", ")", ":", "position", "=", "tf", ".", "to_float", "(", "tf", ".", "range", "(", "length", ")", ")", "num_timescales", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_decoder_self_attention_bias
Calculate bias for decoder that maintains model's autoregressive property. Creates a tensor that masks out locations that correspond to illegal connections, so prediction at position i cannot draw information from future positions. Args: length: int length of sequences in batch. Returns: float tens...
translation/tensorflow/transformer/model/model_utils.py
def get_decoder_self_attention_bias(length): """Calculate bias for decoder that maintains model's autoregressive property. Creates a tensor that masks out locations that correspond to illegal connections, so prediction at position i cannot draw information from future positions. Args: length: int length...
def get_decoder_self_attention_bias(length): """Calculate bias for decoder that maintains model's autoregressive property. Creates a tensor that masks out locations that correspond to illegal connections, so prediction at position i cannot draw information from future positions. Args: length: int length...
[ "Calculate", "bias", "for", "decoder", "that", "maintains", "model", "s", "autoregressive", "property", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/model_utils.py#L57-L74
[ "def", "get_decoder_self_attention_bias", "(", "length", ")", ":", "with", "tf", ".", "name_scope", "(", "\"decoder_self_attention_bias\"", ")", ":", "valid_locs", "=", "tf", ".", "matrix_band_part", "(", "tf", ".", "ones", "(", "[", "length", ",", "length", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_padding
Return float tensor representing the padding values in x. Args: x: int tensor with any shape padding_value: int value that Returns: flaot tensor with same shape as x containing values 0 or 1. 0 -> non-padding, 1 -> padding
translation/tensorflow/transformer/model/model_utils.py
def get_padding(x, padding_value=0): """Return float tensor representing the padding values in x. Args: x: int tensor with any shape padding_value: int value that Returns: flaot tensor with same shape as x containing values 0 or 1. 0 -> non-padding, 1 -> padding """ with tf.name_scope("pad...
def get_padding(x, padding_value=0): """Return float tensor representing the padding values in x. Args: x: int tensor with any shape padding_value: int value that Returns: flaot tensor with same shape as x containing values 0 or 1. 0 -> non-padding, 1 -> padding """ with tf.name_scope("pad...
[ "Return", "float", "tensor", "representing", "the", "padding", "values", "in", "x", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/model_utils.py#L77-L89
[ "def", "get_padding", "(", "x", ",", "padding_value", "=", "0", ")", ":", "with", "tf", ".", "name_scope", "(", "\"padding\"", ")", ":", "return", "tf", ".", "to_float", "(", "tf", ".", "equal", "(", "x", ",", "padding_value", ")", ")" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_padding_bias
Calculate bias tensor from padding values in tensor. Bias tensor that is added to the pre-softmax multi-headed attention logits, which has shape [batch_size, num_heads, length, length]. The tensor is zero at non-padding locations, and -1e9 (negative infinity) at padding locations. Args: x: int tensor with...
translation/tensorflow/transformer/model/model_utils.py
def get_padding_bias(x): """Calculate bias tensor from padding values in tensor. Bias tensor that is added to the pre-softmax multi-headed attention logits, which has shape [batch_size, num_heads, length, length]. The tensor is zero at non-padding locations, and -1e9 (negative infinity) at padding locations. ...
def get_padding_bias(x): """Calculate bias tensor from padding values in tensor. Bias tensor that is added to the pre-softmax multi-headed attention logits, which has shape [batch_size, num_heads, length, length]. The tensor is zero at non-padding locations, and -1e9 (negative infinity) at padding locations. ...
[ "Calculate", "bias", "tensor", "from", "padding", "values", "in", "tensor", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/model_utils.py#L92-L110
[ "def", "get_padding_bias", "(", "x", ")", ":", "with", "tf", ".", "name_scope", "(", "\"attention_bias\"", ")", ":", "padding", "=", "get_padding", "(", "x", ")", "attention_bias", "=", "padding", "*", "_NEG_INF", "attention_bias", "=", "tf", ".", "expand_di...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
SubmissionChecks._add_result
Adds a result to the dictionary. Args: dict_entry: main dict to add entry entry: slot for this entry (likely an integer) dt: the timing for the entry start_time: when the entry started unix time float
compliance/verify_submission/mlperf_submission_helper/checks.py
def _add_result(self, dict_entry, entry, dt, start_time): """Adds a result to the dictionary. Args: dict_entry: main dict to add entry entry: slot for this entry (likely an integer) dt: the timing for the entry start_time: when the entry started unix time float """ time_entry = ...
def _add_result(self, dict_entry, entry, dt, start_time): """Adds a result to the dictionary. Args: dict_entry: main dict to add entry entry: slot for this entry (likely an integer) dt: the timing for the entry start_time: when the entry started unix time float """ time_entry = ...
[ "Adds", "a", "result", "to", "the", "dictionary", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/compliance/verify_submission/mlperf_submission_helper/checks.py#L134-L146
[ "def", "_add_result", "(", "self", ",", "dict_entry", ",", "entry", ",", "dt", ",", "start_time", ")", ":", "time_entry", "=", "{", "}", "time_entry", "[", "'dt'", "]", "=", "dt", "time_entry", "[", "'start_time'", "]", "=", "start_time", "dict_entry", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
SubmissionChecks._sorted_results
Sorts dict of results based on log start_time. Sorts the results and returns an array with only the values but sorted by oldest value first.value Args: results_dicts: List of result dicts Returns: List of only the time but sorted oldest first.
compliance/verify_submission/mlperf_submission_helper/checks.py
def _sorted_results(self, results_dicts): """Sorts dict of results based on log start_time. Sorts the results and returns an array with only the values but sorted by oldest value first.value Args: results_dicts: List of result dicts Returns: List of only the time but sorted oldest fir...
def _sorted_results(self, results_dicts): """Sorts dict of results based on log start_time. Sorts the results and returns an array with only the values but sorted by oldest value first.value Args: results_dicts: List of result dicts Returns: List of only the time but sorted oldest fir...
[ "Sorts", "dict", "of", "results", "based", "on", "log", "start_time", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/compliance/verify_submission/mlperf_submission_helper/checks.py#L148-L165
[ "def", "_sorted_results", "(", "self", ",", "results_dicts", ")", ":", "print", "(", "'results dicts:'", ",", "results_dicts", ")", "sorted_dict", "=", "sorted", "(", "results_dicts", ",", "key", "=", "lambda", "k", ":", "k", "[", "'start_time'", "]", ")", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
SubmissionChecks.get_compliance
Get the compliance level of the output file.
compliance/verify_submission/mlperf_submission_helper/checks.py
def get_compliance(self, filename): """Get the compliance level of the output file.""" print('Running Compliance Check on {}'.format(filename)) print('#' * 80) start_time, status, dt, qual, target = mlp_compliance.l2_check_file_w_starttime( filename) print('#' * 80) if status: lev...
def get_compliance(self, filename): """Get the compliance level of the output file.""" print('Running Compliance Check on {}'.format(filename)) print('#' * 80) start_time, status, dt, qual, target = mlp_compliance.l2_check_file_w_starttime( filename) print('#' * 80) if status: lev...
[ "Get", "the", "compliance", "level", "of", "the", "output", "file", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/compliance/verify_submission/mlperf_submission_helper/checks.py#L252-L272
[ "def", "get_compliance", "(", "self", ",", "filename", ")", ":", "print", "(", "'Running Compliance Check on {}'", ".", "format", "(", "filename", ")", ")", "print", "(", "'#'", "*", "80", ")", "start_time", ",", "status", ",", "dt", ",", "qual", ",", "t...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
SubmissionChecks.verify_and_extract_time
Verifies and result and returns timing. Uses submodule mlp_compliance (https://github.com/bitfort/mlp_compliance) Args: log_file: Absolute path to result file. division: open, closed result_name: name of the benchmark, ncf, ssd, etc Returns: Time for the result or `INFINITE_TIME` ...
compliance/verify_submission/mlperf_submission_helper/checks.py
def verify_and_extract_time(self, log_file, division, result_name): """Verifies and result and returns timing. Uses submodule mlp_compliance (https://github.com/bitfort/mlp_compliance) Args: log_file: Absolute path to result file. division: open, closed result_name: name of the benchmark...
def verify_and_extract_time(self, log_file, division, result_name): """Verifies and result and returns timing. Uses submodule mlp_compliance (https://github.com/bitfort/mlp_compliance) Args: log_file: Absolute path to result file. division: open, closed result_name: name of the benchmark...
[ "Verifies", "and", "result", "and", "returns", "timing", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/compliance/verify_submission/mlperf_submission_helper/checks.py#L274-L309
[ "def", "verify_and_extract_time", "(", "self", ",", "log_file", ",", "division", ",", "result_name", ")", ":", "expected_level", "=", "constants", ".", "DIVISION_COMPLIANCE_CHECK_LEVEL", ".", "get", "(", "division", ",", "None", ")", "print", "(", "result_name", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_compute_and_write_row_block
Compute row block (shard) of expansion for row i of the left_matrix. Compute a shard of the randomized Kronecker product and dump it on the fly. A standard Kronecker product between matrices A and B produces [[a_11 B, ..., a_1n B], ... ...
data_generation/fractal_graph_expansions/graph_expansion.py
def _compute_and_write_row_block( i, left_matrix, right_matrix, train_indices_out_path, test_indices_out_path, remove_empty_rows): """Compute row block (shard) of expansion for row i of the left_matrix. Compute a shard of the randomized Kronecker product and dump it on the fly. A standard Kronecker produ...
def _compute_and_write_row_block( i, left_matrix, right_matrix, train_indices_out_path, test_indices_out_path, remove_empty_rows): """Compute row block (shard) of expansion for row i of the left_matrix. Compute a shard of the randomized Kronecker product and dump it on the fly. A standard Kronecker produ...
[ "Compute", "row", "block", "(", "shard", ")", "of", "expansion", "for", "row", "i", "of", "the", "left_matrix", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/data_generation/fractal_graph_expansions/graph_expansion.py#L46-L188
[ "def", "_compute_and_write_row_block", "(", "i", ",", "left_matrix", ",", "right_matrix", ",", "train_indices_out_path", ",", "test_indices_out_path", ",", "remove_empty_rows", ")", ":", "kron_blocks", "=", "[", "]", "num_rows", "=", "0", "num_removed_rows", "=", "0...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
output_randomized_kronecker_to_pickle
Compute randomized Kronecker product and dump it on the fly. A standard Kronecker product between matrices A and B produces [[a_11 B, ..., a_1n B], ... [a_m1 B, ..., a_mn B]] (if A's size is (m, n) and B's size is (p, q) then A Kr...
data_generation/fractal_graph_expansions/graph_expansion.py
def output_randomized_kronecker_to_pickle( left_matrix, right_matrix, train_indices_out_path, test_indices_out_path, train_metadata_out_path=None, test_metadata_out_path=None, remove_empty_rows=True): """Compute randomized Kronecker product and dump it on the fly. A standard Kronecker product betwe...
def output_randomized_kronecker_to_pickle( left_matrix, right_matrix, train_indices_out_path, test_indices_out_path, train_metadata_out_path=None, test_metadata_out_path=None, remove_empty_rows=True): """Compute randomized Kronecker product and dump it on the fly. A standard Kronecker product betwe...
[ "Compute", "randomized", "Kronecker", "product", "and", "dump", "it", "on", "the", "fly", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/data_generation/fractal_graph_expansions/graph_expansion.py#L191-L303
[ "def", "output_randomized_kronecker_to_pickle", "(", "left_matrix", ",", "right_matrix", ",", "train_indices_out_path", ",", "test_indices_out_path", ",", "train_metadata_out_path", "=", "None", ",", "test_metadata_out_path", "=", "None", ",", "remove_empty_rows", "=", "Tru...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
make_gtp_instance
Takes a path to model files and set up a GTP engine instance.
reinforcement/tensorflow/minigo/gtp.py
def make_gtp_instance(load_file, cgos_mode=False, kgs_mode=False, minigui_mode=False): """Takes a path to model files and set up a GTP engine instance.""" n = DualNetwork(load_file) if cgos_mode: player = CGOSPlayer(network=n, seconds_per_move=5, timed_match=True, ...
def make_gtp_instance(load_file, cgos_mode=False, kgs_mode=False, minigui_mode=False): """Takes a path to model files and set up a GTP engine instance.""" n = DualNetwork(load_file) if cgos_mode: player = CGOSPlayer(network=n, seconds_per_move=5, timed_match=True, ...
[ "Takes", "a", "path", "to", "model", "files", "and", "set", "up", "a", "GTP", "engine", "instance", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/gtp.py#L44-L70
[ "def", "make_gtp_instance", "(", "load_file", ",", "cgos_mode", "=", "False", ",", "kgs_mode", "=", "False", ",", "minigui_mode", "=", "False", ")", ":", "n", "=", "DualNetwork", "(", "load_file", ")", "if", "cgos_mode", ":", "player", "=", "CGOSPlayer", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
main
Run Minigo in GTP mode.
reinforcement/tensorflow/minigo/gtp.py
def main(argv): """Run Minigo in GTP mode.""" del argv engine = make_gtp_instance(FLAGS.load_file, cgos_mode=FLAGS.cgos_mode, kgs_mode=FLAGS.kgs_mode, minigui_mode=FLAGS.minigui_mode) dbg("GTP engine ready\n") ...
def main(argv): """Run Minigo in GTP mode.""" del argv engine = make_gtp_instance(FLAGS.load_file, cgos_mode=FLAGS.cgos_mode, kgs_mode=FLAGS.kgs_mode, minigui_mode=FLAGS.minigui_mode) dbg("GTP engine ready\n") ...
[ "Run", "Minigo", "in", "GTP", "mode", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/gtp.py#L73-L83
[ "def", "main", "(", "argv", ")", ":", "del", "argv", "engine", "=", "make_gtp_instance", "(", "FLAGS", ".", "load_file", ",", "cgos_mode", "=", "FLAGS", ".", "cgos_mode", ",", "kgs_mode", "=", "FLAGS", ".", "kgs_mode", ",", "minigui_mode", "=", "FLAGS", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
validate
Validate a model's performance on a set of holdout data.
reinforcement/tensorflow/minigo/validate.py
def validate(*tf_records): """Validate a model's performance on a set of holdout data.""" if FLAGS.use_tpu: def _input_fn(params): return preprocessing.get_tpu_input_tensors( params['batch_size'], tf_records, filter_amount=1.0) else: def _input_fn(): r...
def validate(*tf_records): """Validate a model's performance on a set of holdout data.""" if FLAGS.use_tpu: def _input_fn(params): return preprocessing.get_tpu_input_tensors( params['batch_size'], tf_records, filter_amount=1.0) else: def _input_fn(): r...
[ "Validate", "a", "model", "s", "performance", "on", "a", "set", "of", "holdout", "data", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/validate.py#L47-L65
[ "def", "validate", "(", "*", "tf_records", ")", ":", "if", "FLAGS", ".", "use_tpu", ":", "def", "_input_fn", "(", "params", ")", ":", "return", "preprocessing", ".", "get_tpu_input_tensors", "(", "params", "[", "'batch_size'", "]", ",", "tf_records", ",", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
main
Validate a model's performance on a set of holdout data.
reinforcement/tensorflow/minigo/validate.py
def main(argv): """Validate a model's performance on a set of holdout data.""" _, *validation_paths = argv if FLAGS.expand_validation_dirs: tf_records = [] with utils.logged_timer("Building lists of holdout files"): for record_dir in validation_paths: tf_records.e...
def main(argv): """Validate a model's performance on a set of holdout data.""" _, *validation_paths = argv if FLAGS.expand_validation_dirs: tf_records = [] with utils.logged_timer("Building lists of holdout files"): for record_dir in validation_paths: tf_records.e...
[ "Validate", "a", "model", "s", "performance", "on", "a", "set", "of", "holdout", "data", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/validate.py#L68-L81
[ "def", "main", "(", "argv", ")", ":", "_", ",", "", "*", "validation_paths", "=", "argv", "if", "FLAGS", ".", "expand_validation_dirs", ":", "tf_records", "=", "[", "]", "with", "utils", ".", "logged_timer", "(", "\"Building lists of holdout files\"", ")", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
setup_custom_environment
Load custom environment setup from a Python source file and run the setup function.
object_detection/pytorch/maskrcnn_benchmark/utils/env.py
def setup_custom_environment(custom_module_path): """Load custom environment setup from a Python source file and run the setup function. """ module = import_file("maskrcnn_benchmark.utils.env.custom_module", custom_module_path) assert hasattr(module, "setup_environment") and callable( module...
def setup_custom_environment(custom_module_path): """Load custom environment setup from a Python source file and run the setup function. """ module = import_file("maskrcnn_benchmark.utils.env.custom_module", custom_module_path) assert hasattr(module, "setup_environment") and callable( module...
[ "Load", "custom", "environment", "setup", "from", "a", "Python", "source", "file", "and", "run", "the", "setup", "function", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/utils/env.py#L20-L33
[ "def", "setup_custom_environment", "(", "custom_module_path", ")", ":", "module", "=", "import_file", "(", "\"maskrcnn_benchmark.utils.env.custom_module\"", ",", "custom_module_path", ")", "assert", "hasattr", "(", "module", ",", "\"setup_environment\"", ")", "and", "call...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_models
Finds all models, returning a list of model number and names sorted increasing. Returns: [(13, 000013-modelname), (17, 000017-modelname), ...etc]
reinforcement/tensorflow/minigo/rl_loop/fsdb.py
def get_models(): """Finds all models, returning a list of model number and names sorted increasing. Returns: [(13, 000013-modelname), (17, 000017-modelname), ...etc] """ all_models = gfile.Glob(os.path.join(models_dir(), '*.meta')) model_filenames = [os.path.basename(m) for m in all_models] ...
def get_models(): """Finds all models, returning a list of model number and names sorted increasing. Returns: [(13, 000013-modelname), (17, 000017-modelname), ...etc] """ all_models = gfile.Glob(os.path.join(models_dir(), '*.meta')) model_filenames = [os.path.basename(m) for m in all_models] ...
[ "Finds", "all", "models", "returning", "a", "list", "of", "model", "number", "and", "names", "sorted", "increasing", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/rl_loop/fsdb.py#L76-L87
[ "def", "get_models", "(", ")", ":", "all_models", "=", "gfile", ".", "Glob", "(", "os", ".", "path", ".", "join", "(", "models_dir", "(", ")", ",", "'*.meta'", ")", ")", "model_filenames", "=", "[", "os", ".", "path", ".", "basename", "(", "m", ")"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_hour_dirs
Gets the directories under selfplay_dir that match YYYY-MM-DD-HH.
reinforcement/tensorflow/minigo/rl_loop/fsdb.py
def get_hour_dirs(root=None): """Gets the directories under selfplay_dir that match YYYY-MM-DD-HH.""" root = root or selfplay_dir() return list(filter(lambda s: re.match(r"\d{4}-\d{2}-\d{2}-\d{2}", s), gfile.ListDirectory(root)))
def get_hour_dirs(root=None): """Gets the directories under selfplay_dir that match YYYY-MM-DD-HH.""" root = root or selfplay_dir() return list(filter(lambda s: re.match(r"\d{4}-\d{2}-\d{2}-\d{2}", s), gfile.ListDirectory(root)))
[ "Gets", "the", "directories", "under", "selfplay_dir", "that", "match", "YYYY", "-", "MM", "-", "DD", "-", "HH", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/rl_loop/fsdb.py#L109-L113
[ "def", "get_hour_dirs", "(", "root", "=", "None", ")", ":", "root", "=", "root", "or", "selfplay_dir", "(", ")", "return", "list", "(", "filter", "(", "lambda", "s", ":", "re", ".", "match", "(", "r\"\\d{4}-\\d{2}-\\d{2}-\\d{2}\"", ",", "s", ")", ",", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
game_counts
Prints statistics for the most recent n_back models
reinforcement/tensorflow/minigo/rl_loop/fsdb.py
def game_counts(n_back=20): """Prints statistics for the most recent n_back models""" for _, model_name in get_models[-n_back:]: games = get_games(model_name) print("Model: {}, Games: {}".format(model_name, len(games)))
def game_counts(n_back=20): """Prints statistics for the most recent n_back models""" for _, model_name in get_models[-n_back:]: games = get_games(model_name) print("Model: {}, Games: {}".format(model_name, len(games)))
[ "Prints", "statistics", "for", "the", "most", "recent", "n_back", "models" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/rl_loop/fsdb.py#L120-L124
[ "def", "game_counts", "(", "n_back", "=", "20", ")", ":", "for", "_", ",", "model_name", "in", "get_models", "[", "-", "n_back", ":", "]", ":", "games", "=", "get_games", "(", "model_name", ")", "print", "(", "\"Model: {}, Games: {}\"", ".", "format", "(...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
boxlist_nms
Performs non-maximum suppression on a boxlist, with scores specified in a boxlist field via score_field. Arguments: boxlist(BoxList) nms_thresh (float) max_proposals (int): if > 0, then only the top max_proposals are kept after non-maximum suppression score_field (st...
object_detection/pytorch/maskrcnn_benchmark/structures/boxlist_ops.py
def boxlist_nms(boxlist, nms_thresh, max_proposals=-1, score_field="scores"): """ Performs non-maximum suppression on a boxlist, with scores specified in a boxlist field via score_field. Arguments: boxlist(BoxList) nms_thresh (float) max_proposals (int): if > 0, then only the to...
def boxlist_nms(boxlist, nms_thresh, max_proposals=-1, score_field="scores"): """ Performs non-maximum suppression on a boxlist, with scores specified in a boxlist field via score_field. Arguments: boxlist(BoxList) nms_thresh (float) max_proposals (int): if > 0, then only the to...
[ "Performs", "non", "-", "maximum", "suppression", "on", "a", "boxlist", "with", "scores", "specified", "in", "a", "boxlist", "field", "via", "score_field", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/structures/boxlist_ops.py#L9-L31
[ "def", "boxlist_nms", "(", "boxlist", ",", "nms_thresh", ",", "max_proposals", "=", "-", "1", ",", "score_field", "=", "\"scores\"", ")", ":", "if", "nms_thresh", "<=", "0", ":", "return", "boxlist", "mode", "=", "boxlist", ".", "mode", "boxlist", "=", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
remove_small_boxes
Only keep boxes with both sides >= min_size Arguments: boxlist (Boxlist) min_size (int)
object_detection/pytorch/maskrcnn_benchmark/structures/boxlist_ops.py
def remove_small_boxes(boxlist, min_size): """ Only keep boxes with both sides >= min_size Arguments: boxlist (Boxlist) min_size (int) """ # TODO maybe add an API for querying the ws / hs xywh_boxes = boxlist.convert("xywh").bbox _, _, ws, hs = xywh_boxes.unbind(dim=1) k...
def remove_small_boxes(boxlist, min_size): """ Only keep boxes with both sides >= min_size Arguments: boxlist (Boxlist) min_size (int) """ # TODO maybe add an API for querying the ws / hs xywh_boxes = boxlist.convert("xywh").bbox _, _, ws, hs = xywh_boxes.unbind(dim=1) k...
[ "Only", "keep", "boxes", "with", "both", "sides", ">", "=", "min_size" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/structures/boxlist_ops.py#L34-L48
[ "def", "remove_small_boxes", "(", "boxlist", ",", "min_size", ")", ":", "# TODO maybe add an API for querying the ws / hs", "xywh_boxes", "=", "boxlist", ".", "convert", "(", "\"xywh\"", ")", ".", "bbox", "_", ",", "_", ",", "ws", ",", "hs", "=", "xywh_boxes", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
boxlist_iou
Compute the intersection over union of two set of boxes. The box order must be (xmin, ymin, xmax, ymax). Arguments: box1: (BoxList) bounding boxes, sized [N,4]. box2: (BoxList) bounding boxes, sized [M,4]. Returns: (tensor) iou, sized [N,M]. Reference: https://github.com/chain...
object_detection/pytorch/maskrcnn_benchmark/structures/boxlist_ops.py
def boxlist_iou(boxlist1, boxlist2): """Compute the intersection over union of two set of boxes. The box order must be (xmin, ymin, xmax, ymax). Arguments: box1: (BoxList) bounding boxes, sized [N,4]. box2: (BoxList) bounding boxes, sized [M,4]. Returns: (tensor) iou, sized [N,M]. ...
def boxlist_iou(boxlist1, boxlist2): """Compute the intersection over union of two set of boxes. The box order must be (xmin, ymin, xmax, ymax). Arguments: box1: (BoxList) bounding boxes, sized [N,4]. box2: (BoxList) bounding boxes, sized [M,4]. Returns: (tensor) iou, sized [N,M]. ...
[ "Compute", "the", "intersection", "over", "union", "of", "two", "set", "of", "boxes", ".", "The", "box", "order", "must", "be", "(", "xmin", "ymin", "xmax", "ymax", ")", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/structures/boxlist_ops.py#L53-L88
[ "def", "boxlist_iou", "(", "boxlist1", ",", "boxlist2", ")", ":", "if", "boxlist1", ".", "size", "!=", "boxlist2", ".", "size", ":", "raise", "RuntimeError", "(", "\"boxlists should have same image size, got {}, {}\"", ".", "format", "(", "boxlist1", ",", "boxlist...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
cat_boxlist
Concatenates a list of BoxList (having the same image size) into a single BoxList Arguments: bboxes (list[BoxList])
object_detection/pytorch/maskrcnn_benchmark/structures/boxlist_ops.py
def cat_boxlist(bboxes): """ Concatenates a list of BoxList (having the same image size) into a single BoxList Arguments: bboxes (list[BoxList]) """ assert isinstance(bboxes, (list, tuple)) assert all(isinstance(bbox, BoxList) for bbox in bboxes) size = bboxes[0].size asser...
def cat_boxlist(bboxes): """ Concatenates a list of BoxList (having the same image size) into a single BoxList Arguments: bboxes (list[BoxList]) """ assert isinstance(bboxes, (list, tuple)) assert all(isinstance(bbox, BoxList) for bbox in bboxes) size = bboxes[0].size asser...
[ "Concatenates", "a", "list", "of", "BoxList", "(", "having", "the", "same", "image", "size", ")", "into", "a", "single", "BoxList" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/structures/boxlist_ops.py#L102-L128
[ "def", "cat_boxlist", "(", "bboxes", ")", ":", "assert", "isinstance", "(", "bboxes", ",", "(", "list", ",", "tuple", ")", ")", "assert", "all", "(", "isinstance", "(", "bbox", ",", "BoxList", ")", "for", "bbox", "in", "bboxes", ")", "size", "=", "bb...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Loss._loc_vec
Generate Location Vectors
single_stage_detector/ssd/base_model.py
def _loc_vec(self, loc): """ Generate Location Vectors """ gxy = self.scale_xy*(loc[:, :2, :] - self.dboxes[:, :2, :])/self.dboxes[:, 2:, ] gwh = self.scale_wh*(loc[:, 2:, :]/self.dboxes[:, 2:, :]).log() return torch.cat((gxy, gwh), dim=1).contiguous()
def _loc_vec(self, loc): """ Generate Location Vectors """ gxy = self.scale_xy*(loc[:, :2, :] - self.dboxes[:, :2, :])/self.dboxes[:, 2:, ] gwh = self.scale_wh*(loc[:, 2:, :]/self.dboxes[:, 2:, :]).log() return torch.cat((gxy, gwh), dim=1).contiguous()
[ "Generate", "Location", "Vectors" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/single_stage_detector/ssd/base_model.py#L157-L164
[ "def", "_loc_vec", "(", "self", ",", "loc", ")", ":", "gxy", "=", "self", ".", "scale_xy", "*", "(", "loc", "[", ":", ",", ":", "2", ",", ":", "]", "-", "self", ".", "dboxes", "[", ":", ",", ":", "2", ",", ":", "]", ")", "/", "self", ".",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Loss.forward
ploc, plabel: Nx4x8732, Nxlabel_numx8732 predicted location and labels gloc, glabel: Nx4x8732, Nx8732 ground truth location and labels
single_stage_detector/ssd/base_model.py
def forward(self, ploc, plabel, gloc, glabel): """ ploc, plabel: Nx4x8732, Nxlabel_numx8732 predicted location and labels gloc, glabel: Nx4x8732, Nx8732 ground truth location and labels """ mask = glabel > 0 pos_num = mask.sum(dim...
def forward(self, ploc, plabel, gloc, glabel): """ ploc, plabel: Nx4x8732, Nxlabel_numx8732 predicted location and labels gloc, glabel: Nx4x8732, Nx8732 ground truth location and labels """ mask = glabel > 0 pos_num = mask.sum(dim...
[ "ploc", "plabel", ":", "Nx4x8732", "Nxlabel_numx8732", "predicted", "location", "and", "labels" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/single_stage_detector/ssd/base_model.py#L166-L205
[ "def", "forward", "(", "self", ",", "ploc", ",", "plabel", ",", "gloc", ",", "glabel", ")", ":", "mask", "=", "glabel", ">", "0", "pos_num", "=", "mask", ".", "sum", "(", "dim", "=", "1", ")", "vec_gd", "=", "self", ".", "_loc_vec", "(", "gloc", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Fp16Optimizer.set_grads
Copies gradients from param_with_grad to params :param params: dst parameters :param params_with_grad: src parameters
rnn_translator/pytorch/seq2seq/train/fp_optimizers.py
def set_grads(params, params_with_grad): """ Copies gradients from param_with_grad to params :param params: dst parameters :param params_with_grad: src parameters """ for param, param_w_grad in zip(params, params_with_grad): if param.grad is None: ...
def set_grads(params, params_with_grad): """ Copies gradients from param_with_grad to params :param params: dst parameters :param params_with_grad: src parameters """ for param, param_w_grad in zip(params, params_with_grad): if param.grad is None: ...
[ "Copies", "gradients", "from", "param_with_grad", "to", "params" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/train/fp_optimizers.py#L14-L24
[ "def", "set_grads", "(", "params", ",", "params_with_grad", ")", ":", "for", "param", ",", "param_w_grad", "in", "zip", "(", "params", ",", "params_with_grad", ")", ":", "if", "param", ".", "grad", "is", "None", ":", "param", ".", "grad", "=", "torch", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Fp16Optimizer.set_weights
Copies parameters from new_params to params :param params: dst parameters :param new_params: src parameters
rnn_translator/pytorch/seq2seq/train/fp_optimizers.py
def set_weights(params, new_params): """ Copies parameters from new_params to params :param params: dst parameters :param new_params: src parameters """ for param, new_param in zip(params, new_params): param.data.copy_(new_param.data)
def set_weights(params, new_params): """ Copies parameters from new_params to params :param params: dst parameters :param new_params: src parameters """ for param, new_param in zip(params, new_params): param.data.copy_(new_param.data)
[ "Copies", "parameters", "from", "new_params", "to", "params" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/train/fp_optimizers.py#L27-L35
[ "def", "set_weights", "(", "params", ",", "new_params", ")", ":", "for", "param", ",", "new_param", "in", "zip", "(", "params", ",", "new_params", ")", ":", "param", ".", "data", ".", "copy_", "(", "new_param", ".", "data", ")" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Fp16Optimizer.initialize_model
Initializes internal state and build fp32 master copy of weights. :param model: fp16 model
rnn_translator/pytorch/seq2seq/train/fp_optimizers.py
def initialize_model(self, model): """ Initializes internal state and build fp32 master copy of weights. :param model: fp16 model """ logging.info('Initializing fp32 clone weights') self.fp16_model = model self.fp16_model.zero_grad() self.fp32_params = [p...
def initialize_model(self, model): """ Initializes internal state and build fp32 master copy of weights. :param model: fp16 model """ logging.info('Initializing fp32 clone weights') self.fp16_model = model self.fp16_model.zero_grad() self.fp32_params = [p...
[ "Initializes", "internal", "state", "and", "build", "fp32", "master", "copy", "of", "weights", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/train/fp_optimizers.py#L63-L76
[ "def", "initialize_model", "(", "self", ",", "model", ")", ":", "logging", ".", "info", "(", "'Initializing fp32 clone weights'", ")", "self", ".", "fp16_model", "=", "model", "self", ".", "fp16_model", ".", "zero_grad", "(", ")", "self", ".", "fp32_params", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Fp16Optimizer.step
Performs one step of the optimizer. Applies loss scaling, computes gradients in fp16, converts gradients to fp32, inverts scaling and applies optional gradient norm clipping. If gradients are finite, it applies update to fp32 master weights and copies updated parameters to fp16 model for...
rnn_translator/pytorch/seq2seq/train/fp_optimizers.py
def step(self, loss, optimizer, scheduler, update=True): """ Performs one step of the optimizer. Applies loss scaling, computes gradients in fp16, converts gradients to fp32, inverts scaling and applies optional gradient norm clipping. If gradients are finite, it applies update t...
def step(self, loss, optimizer, scheduler, update=True): """ Performs one step of the optimizer. Applies loss scaling, computes gradients in fp16, converts gradients to fp32, inverts scaling and applies optional gradient norm clipping. If gradients are finite, it applies update t...
[ "Performs", "one", "step", "of", "the", "optimizer", ".", "Applies", "loss", "scaling", "computes", "gradients", "in", "fp16", "converts", "gradients", "to", "fp32", "inverts", "scaling", "and", "applies", "optional", "gradient", "norm", "clipping", ".", "If", ...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/train/fp_optimizers.py#L78-L121
[ "def", "step", "(", "self", ",", "loss", ",", "optimizer", ",", "scheduler", ",", "update", "=", "True", ")", ":", "loss", "*=", "self", ".", "loss_scale", "loss", ".", "backward", "(", ")", "if", "update", ":", "self", ".", "set_grads", "(", "self",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Fp32Optimizer.step
Performs one step of the optimizer. :param loss: value of loss function :param optimizer: optimizer :param update: if True executes weight update
rnn_translator/pytorch/seq2seq/train/fp_optimizers.py
def step(self, loss, optimizer, scheduler, update=True): """ Performs one step of the optimizer. :param loss: value of loss function :param optimizer: optimizer :param update: if True executes weight update """ loss.backward() if update: if se...
def step(self, loss, optimizer, scheduler, update=True): """ Performs one step of the optimizer. :param loss: value of loss function :param optimizer: optimizer :param update: if True executes weight update """ loss.backward() if update: if se...
[ "Performs", "one", "step", "of", "the", "optimizer", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/train/fp_optimizers.py#L149-L163
[ "def", "step", "(", "self", ",", "loss", ",", "optimizer", ",", "scheduler", ",", "update", "=", "True", ")", ":", "loss", ".", "backward", "(", ")", "if", "update", ":", "if", "self", ".", "grad_clip", "!=", "float", "(", "'inf'", ")", ":", "clip_...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_parse_example
Return inputs and targets Tensors from a serialized tf.Example.
translation/tensorflow/transformer/utils/dataset.py
def _parse_example(serialized_example): """Return inputs and targets Tensors from a serialized tf.Example.""" data_fields = { "inputs": tf.VarLenFeature(tf.int64), "targets": tf.VarLenFeature(tf.int64) } parsed = tf.parse_single_example(serialized_example, data_fields) inputs = tf.sparse_tensor_to...
def _parse_example(serialized_example): """Return inputs and targets Tensors from a serialized tf.Example.""" data_fields = { "inputs": tf.VarLenFeature(tf.int64), "targets": tf.VarLenFeature(tf.int64) } parsed = tf.parse_single_example(serialized_example, data_fields) inputs = tf.sparse_tensor_to...
[ "Return", "inputs", "and", "targets", "Tensors", "from", "a", "serialized", "tf", ".", "Example", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/dataset.py#L77-L86
[ "def", "_parse_example", "(", "serialized_example", ")", ":", "data_fields", "=", "{", "\"inputs\"", ":", "tf", ".", "VarLenFeature", "(", "tf", ".", "int64", ")", ",", "\"targets\"", ":", "tf", ".", "VarLenFeature", "(", "tf", ".", "int64", ")", "}", "p...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_filter_max_length
Indicates whether the example's length is lower than the maximum length.
translation/tensorflow/transformer/utils/dataset.py
def _filter_max_length(example, max_length=256): """Indicates whether the example's length is lower than the maximum length.""" return tf.logical_and(tf.size(example[0]) <= max_length, tf.size(example[1]) <= max_length)
def _filter_max_length(example, max_length=256): """Indicates whether the example's length is lower than the maximum length.""" return tf.logical_and(tf.size(example[0]) <= max_length, tf.size(example[1]) <= max_length)
[ "Indicates", "whether", "the", "example", "s", "length", "is", "lower", "than", "the", "maximum", "length", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/dataset.py#L89-L92
[ "def", "_filter_max_length", "(", "example", ",", "max_length", "=", "256", ")", ":", "return", "tf", ".", "logical_and", "(", "tf", ".", "size", "(", "example", "[", "0", "]", ")", "<=", "max_length", ",", "tf", ".", "size", "(", "example", "[", "1"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_get_example_length
Returns the maximum length between the example inputs and targets.
translation/tensorflow/transformer/utils/dataset.py
def _get_example_length(example): """Returns the maximum length between the example inputs and targets.""" length = tf.maximum(tf.shape(example[0])[0], tf.shape(example[1])[0]) return length
def _get_example_length(example): """Returns the maximum length between the example inputs and targets.""" length = tf.maximum(tf.shape(example[0])[0], tf.shape(example[1])[0]) return length
[ "Returns", "the", "maximum", "length", "between", "the", "example", "inputs", "and", "targets", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/dataset.py#L95-L98
[ "def", "_get_example_length", "(", "example", ")", ":", "length", "=", "tf", ".", "maximum", "(", "tf", ".", "shape", "(", "example", "[", "0", "]", ")", "[", "0", "]", ",", "tf", ".", "shape", "(", "example", "[", "1", "]", ")", "[", "0", "]",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_create_min_max_boundaries
Create min and max boundary lists up to max_length. For example, when max_length=24, min_boundary=4 and boundary_scale=2, the returned values will be: buckets_min = [0, 4, 8, 16, 24] buckets_max = [4, 8, 16, 24, 25] Args: max_length: The maximum length of example in dataset. min_boundary: Minimu...
translation/tensorflow/transformer/utils/dataset.py
def _create_min_max_boundaries( max_length, min_boundary=_MIN_BOUNDARY, boundary_scale=_BOUNDARY_SCALE): """Create min and max boundary lists up to max_length. For example, when max_length=24, min_boundary=4 and boundary_scale=2, the returned values will be: buckets_min = [0, 4, 8, 16, 24] buckets_ma...
def _create_min_max_boundaries( max_length, min_boundary=_MIN_BOUNDARY, boundary_scale=_BOUNDARY_SCALE): """Create min and max boundary lists up to max_length. For example, when max_length=24, min_boundary=4 and boundary_scale=2, the returned values will be: buckets_min = [0, 4, 8, 16, 24] buckets_ma...
[ "Create", "min", "and", "max", "boundary", "lists", "up", "to", "max_length", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/dataset.py#L101-L130
[ "def", "_create_min_max_boundaries", "(", "max_length", ",", "min_boundary", "=", "_MIN_BOUNDARY", ",", "boundary_scale", "=", "_BOUNDARY_SCALE", ")", ":", "# Create bucket boundaries list by scaling the previous boundary or adding 1", "# (to ensure increasing boundary sizes).", "buc...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_batch_examples
Group examples by similar lengths, and return batched dataset. Each batch of similar-length examples are padded to the same length, and may have different number of elements in each batch, such that: group_batch_size * padded_length <= batch_size. This decreases the number of padding tokens per batch, which...
translation/tensorflow/transformer/utils/dataset.py
def _batch_examples(dataset, batch_size, max_length): """Group examples by similar lengths, and return batched dataset. Each batch of similar-length examples are padded to the same length, and may have different number of elements in each batch, such that: group_batch_size * padded_length <= batch_size. T...
def _batch_examples(dataset, batch_size, max_length): """Group examples by similar lengths, and return batched dataset. Each batch of similar-length examples are padded to the same length, and may have different number of elements in each batch, such that: group_batch_size * padded_length <= batch_size. T...
[ "Group", "examples", "by", "similar", "lengths", "and", "return", "batched", "dataset", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/dataset.py#L133-L191
[ "def", "_batch_examples", "(", "dataset", ",", "batch_size", ",", "max_length", ")", ":", "# Get min and max boundary lists for each example. These are used to calculate", "# the `bucket_id`, which is the index at which:", "# buckets_min[bucket_id] <= len(example) < buckets_max[bucket_id]", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_read_and_batch_from_files
Create dataset where each item is a dict of "inputs" and "targets". Args: file_pattern: String used to match the input TFRecord files. batch_size: Maximum number of tokens per batch of examples max_length: Maximum number of tokens per example num_cpu_cores: Number of cpu cores for parallel input proc...
translation/tensorflow/transformer/utils/dataset.py
def _read_and_batch_from_files( file_pattern, batch_size, max_length, num_cpu_cores, shuffle, repeat): """Create dataset where each item is a dict of "inputs" and "targets". Args: file_pattern: String used to match the input TFRecord files. batch_size: Maximum number of tokens per batch of examples ...
def _read_and_batch_from_files( file_pattern, batch_size, max_length, num_cpu_cores, shuffle, repeat): """Create dataset where each item is a dict of "inputs" and "targets". Args: file_pattern: String used to match the input TFRecord files. batch_size: Maximum number of tokens per batch of examples ...
[ "Create", "dataset", "where", "each", "item", "is", "a", "dict", "of", "inputs", "and", "targets", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/dataset.py#L194-L241
[ "def", "_read_and_batch_from_files", "(", "file_pattern", ",", "batch_size", ",", "max_length", ",", "num_cpu_cores", ",", "shuffle", ",", "repeat", ")", ":", "dataset", "=", "tf", ".", "data", ".", "Dataset", ".", "list_files", "(", "file_pattern", ")", "if",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
train_input_fn
Load and return dataset of batched examples for use during training.
translation/tensorflow/transformer/utils/dataset.py
def train_input_fn(params): """Load and return dataset of batched examples for use during training.""" file_pattern = os.path.join(getattr(params, "data_dir", ""), "*encoded-train*") return _read_and_batch_from_files( file_pattern, params.batch_size, params.max_length, params.num_cpu_cores, shuffle=Tr...
def train_input_fn(params): """Load and return dataset of batched examples for use during training.""" file_pattern = os.path.join(getattr(params, "data_dir", ""), "*encoded-train*") return _read_and_batch_from_files( file_pattern, params.batch_size, params.max_length, params.num_cpu_cores, shuffle=Tr...
[ "Load", "and", "return", "dataset", "of", "batched", "examples", "for", "use", "during", "training", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/dataset.py#L244-L249
[ "def", "train_input_fn", "(", "params", ")", ":", "file_pattern", "=", "os", ".", "path", ".", "join", "(", "getattr", "(", "params", ",", "\"data_dir\"", ",", "\"\"", ")", ",", "\"*encoded-train*\"", ")", "return", "_read_and_batch_from_files", "(", "file_pat...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
eval_input_fn
Load and return dataset of batched examples for use during evaluation.
translation/tensorflow/transformer/utils/dataset.py
def eval_input_fn(params): """Load and return dataset of batched examples for use during evaluation.""" file_pattern = os.path.join(getattr(params, "data_dir", ""), "*encoded-dev*") return _read_and_batch_from_files( file_pattern, params.batch_size, params.max_length, params.num_cpu_cores, shuffle=Fal...
def eval_input_fn(params): """Load and return dataset of batched examples for use during evaluation.""" file_pattern = os.path.join(getattr(params, "data_dir", ""), "*encoded-dev*") return _read_and_batch_from_files( file_pattern, params.batch_size, params.max_length, params.num_cpu_cores, shuffle=Fal...
[ "Load", "and", "return", "dataset", "of", "batched", "examples", "for", "use", "during", "evaluation", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/dataset.py#L252-L257
[ "def", "eval_input_fn", "(", "params", ")", ":", "file_pattern", "=", "os", ".", "path", ".", "join", "(", "getattr", "(", "params", ",", "\"data_dir\"", ",", "\"\"", ")", ",", "\"*encoded-dev*\"", ")", "return", "_read_and_batch_from_files", "(", "file_patter...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
reduce_loss_dict
Reduce the loss dictionary from all processes so that process with rank 0 has the averaged results. Returns a dict with the same fields as loss_dict, after reduction.
object_detection/pytorch/maskrcnn_benchmark/engine/trainer.py
def reduce_loss_dict(loss_dict): """ Reduce the loss dictionary from all processes so that process with rank 0 has the averaged results. Returns a dict with the same fields as loss_dict, after reduction. """ world_size = get_world_size() if world_size < 2: return loss_dict with t...
def reduce_loss_dict(loss_dict): """ Reduce the loss dictionary from all processes so that process with rank 0 has the averaged results. Returns a dict with the same fields as loss_dict, after reduction. """ world_size = get_world_size() if world_size < 2: return loss_dict with t...
[ "Reduce", "the", "loss", "dictionary", "from", "all", "processes", "so", "that", "process", "with", "rank", "0", "has", "the", "averaged", "results", ".", "Returns", "a", "dict", "with", "the", "same", "fields", "as", "loss_dict", "after", "reduction", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/engine/trainer.py#L14-L36
[ "def", "reduce_loss_dict", "(", "loss_dict", ")", ":", "world_size", "=", "get_world_size", "(", ")", "if", "world_size", "<", "2", ":", "return", "loss_dict", "with", "torch", ".", "no_grad", "(", ")", ":", "loss_names", "=", "[", "]", "all_losses", "=", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
parse_dtype_info
Convert dtype string to tf dtype, and set loss_scale default as needed. Args: flags: namespace object returned by arg parser. Raises: ValueError: If an invalid dtype is provided.
image_classification/tensorflow/official/utils/arg_parsers/parsers.py
def parse_dtype_info(flags): """Convert dtype string to tf dtype, and set loss_scale default as needed. Args: flags: namespace object returned by arg parser. Raises: ValueError: If an invalid dtype is provided. """ if flags.dtype in (i[0] for i in DTYPE_MAP.values()): return # Make function ide...
def parse_dtype_info(flags): """Convert dtype string to tf dtype, and set loss_scale default as needed. Args: flags: namespace object returned by arg parser. Raises: ValueError: If an invalid dtype is provided. """ if flags.dtype in (i[0] for i in DTYPE_MAP.values()): return # Make function ide...
[ "Convert", "dtype", "string", "to", "tf", "dtype", "and", "set", "loss_scale", "default", "as", "needed", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/utils/arg_parsers/parsers.py#L73-L90
[ "def", "parse_dtype_info", "(", "flags", ")", ":", "if", "flags", ".", "dtype", "in", "(", "i", "[", "0", "]", "for", "i", "in", "DTYPE_MAP", ".", "values", "(", ")", ")", ":", "return", "# Make function idempotent", "try", ":", "flags", ".", "dtype", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
calc_iou_tensor
Calculation of IoU based on two boxes tensor, Reference to https://github.com/kuangliu/pytorch-ssd input: box1 (N, 4) box2 (M, 4) output: IoU (N, M)
single_stage_detector/ssd/utils.py
def calc_iou_tensor(box1, box2): """ Calculation of IoU based on two boxes tensor, Reference to https://github.com/kuangliu/pytorch-ssd input: box1 (N, 4) box2 (M, 4) output: IoU (N, M) """ N = box1.size(0) M = box2.size(0) be1 = box1.unsq...
def calc_iou_tensor(box1, box2): """ Calculation of IoU based on two boxes tensor, Reference to https://github.com/kuangliu/pytorch-ssd input: box1 (N, 4) box2 (M, 4) output: IoU (N, M) """ N = box1.size(0) M = box2.size(0) be1 = box1.unsq...
[ "Calculation", "of", "IoU", "based", "on", "two", "boxes", "tensor", "Reference", "to", "https", ":", "//", "github", ".", "com", "/", "kuangliu", "/", "pytorch", "-", "ssd", "input", ":", "box1", "(", "N", "4", ")", "box2", "(", "M", "4", ")", "ou...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/single_stage_detector/ssd/utils.py#L23-L57
[ "def", "calc_iou_tensor", "(", "box1", ",", "box2", ")", ":", "N", "=", "box1", ".", "size", "(", "0", ")", "M", "=", "box2", ".", "size", "(", "0", ")", "be1", "=", "box1", ".", "unsqueeze", "(", "1", ")", ".", "expand", "(", "-", "1", ",", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Encoder.scale_back_batch
Do scale and transform from xywh to ltrb suppose input Nx4xnum_bbox Nxlabel_numxnum_bbox
single_stage_detector/ssd/utils.py
def scale_back_batch(self, bboxes_in, scores_in): """ Do scale and transform from xywh to ltrb suppose input Nx4xnum_bbox Nxlabel_numxnum_bbox """ if bboxes_in.device == torch.device("cpu"): self.dboxes = self.dboxes.cpu() self.dboxes_xywh = self.d...
def scale_back_batch(self, bboxes_in, scores_in): """ Do scale and transform from xywh to ltrb suppose input Nx4xnum_bbox Nxlabel_numxnum_bbox """ if bboxes_in.device == torch.device("cpu"): self.dboxes = self.dboxes.cpu() self.dboxes_xywh = self.d...
[ "Do", "scale", "and", "transform", "from", "xywh", "to", "ltrb", "suppose", "input", "Nx4xnum_bbox", "Nxlabel_numxnum_bbox" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/single_stage_detector/ssd/utils.py#L120-L156
[ "def", "scale_back_batch", "(", "self", ",", "bboxes_in", ",", "scores_in", ")", ":", "if", "bboxes_in", ".", "device", "==", "torch", ".", "device", "(", "\"cpu\"", ")", ":", "self", ".", "dboxes", "=", "self", ".", "dboxes", ".", "cpu", "(", ")", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
generate_anchors
Generates a matrix of anchor boxes in (x1, y1, x2, y2) format. Anchors are centered on stride / 2, have (approximate) sqrt areas of the specified sizes, and aspect ratios as given.
object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/anchor_generator.py
def generate_anchors( stride=16, sizes=(32, 64, 128, 256, 512), aspect_ratios=(0.5, 1, 2) ): """Generates a matrix of anchor boxes in (x1, y1, x2, y2) format. Anchors are centered on stride / 2, have (approximate) sqrt areas of the specified sizes, and aspect ratios as given. """ return _generat...
def generate_anchors( stride=16, sizes=(32, 64, 128, 256, 512), aspect_ratios=(0.5, 1, 2) ): """Generates a matrix of anchor boxes in (x1, y1, x2, y2) format. Anchors are centered on stride / 2, have (approximate) sqrt areas of the specified sizes, and aspect ratios as given. """ return _generat...
[ "Generates", "a", "matrix", "of", "anchor", "boxes", "in", "(", "x1", "y1", "x2", "y2", ")", "format", ".", "Anchors", "are", "centered", "on", "stride", "/", "2", "have", "(", "approximate", ")", "sqrt", "areas", "of", "the", "specified", "sizes", "an...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/anchor_generator.py#L220-L231
[ "def", "generate_anchors", "(", "stride", "=", "16", ",", "sizes", "=", "(", "32", ",", "64", ",", "128", ",", "256", ",", "512", ")", ",", "aspect_ratios", "=", "(", "0.5", ",", "1", ",", "2", ")", ")", ":", "return", "_generate_anchors", "(", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_generate_anchors
Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, base_size - 1, base_size - 1) window.
object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/anchor_generator.py
def _generate_anchors(base_size, scales, aspect_ratios): """Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, base_size - 1, base_size - 1) window. """ anchor = np.array([1, 1, base_size, base_size], dtype=np.float) - 1 anchors = _ratio_enum(anchor, asp...
def _generate_anchors(base_size, scales, aspect_ratios): """Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, base_size - 1, base_size - 1) window. """ anchor = np.array([1, 1, base_size, base_size], dtype=np.float) - 1 anchors = _ratio_enum(anchor, asp...
[ "Generate", "anchor", "(", "reference", ")", "windows", "by", "enumerating", "aspect", "ratios", "X", "scales", "wrt", "a", "reference", "(", "0", "0", "base_size", "-", "1", "base_size", "-", "1", ")", "window", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/anchor_generator.py#L234-L243
[ "def", "_generate_anchors", "(", "base_size", ",", "scales", ",", "aspect_ratios", ")", ":", "anchor", "=", "np", ".", "array", "(", "[", "1", ",", "1", ",", "base_size", ",", "base_size", "]", ",", "dtype", "=", "np", ".", "float", ")", "-", "1", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
from_flat
Converts from a flattened coordinate to a Minigo coordinate.
reinforcement/tensorflow/minigo/coords.py
def from_flat(flat): """Converts from a flattened coordinate to a Minigo coordinate.""" if flat == go.N * go.N: return None return divmod(flat, go.N)
def from_flat(flat): """Converts from a flattened coordinate to a Minigo coordinate.""" if flat == go.N * go.N: return None return divmod(flat, go.N)
[ "Converts", "from", "a", "flattened", "coordinate", "to", "a", "Minigo", "coordinate", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/coords.py#L50-L54
[ "def", "from_flat", "(", "flat", ")", ":", "if", "flat", "==", "go", ".", "N", "*", "go", ".", "N", ":", "return", "None", "return", "divmod", "(", "flat", ",", "go", ".", "N", ")" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
to_flat
Converts from a Minigo coordinate to a flattened coordinate.
reinforcement/tensorflow/minigo/coords.py
def to_flat(coord): """Converts from a Minigo coordinate to a flattened coordinate.""" if coord is None: return go.N * go.N return go.N * coord[0] + coord[1]
def to_flat(coord): """Converts from a Minigo coordinate to a flattened coordinate.""" if coord is None: return go.N * go.N return go.N * coord[0] + coord[1]
[ "Converts", "from", "a", "Minigo", "coordinate", "to", "a", "flattened", "coordinate", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/coords.py#L57-L61
[ "def", "to_flat", "(", "coord", ")", ":", "if", "coord", "is", "None", ":", "return", "go", ".", "N", "*", "go", ".", "N", "return", "go", ".", "N", "*", "coord", "[", "0", "]", "+", "coord", "[", "1", "]" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
from_sgf
Converts from an SGF coordinate to a Minigo coordinate.
reinforcement/tensorflow/minigo/coords.py
def from_sgf(sgfc): """Converts from an SGF coordinate to a Minigo coordinate.""" if sgfc is None or sgfc == '' or (go.N <= 19 and sgfc == 'tt'): return None return _SGF_COLUMNS.index(sgfc[1]), _SGF_COLUMNS.index(sgfc[0])
def from_sgf(sgfc): """Converts from an SGF coordinate to a Minigo coordinate.""" if sgfc is None or sgfc == '' or (go.N <= 19 and sgfc == 'tt'): return None return _SGF_COLUMNS.index(sgfc[1]), _SGF_COLUMNS.index(sgfc[0])
[ "Converts", "from", "an", "SGF", "coordinate", "to", "a", "Minigo", "coordinate", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/coords.py#L64-L68
[ "def", "from_sgf", "(", "sgfc", ")", ":", "if", "sgfc", "is", "None", "or", "sgfc", "==", "''", "or", "(", "go", ".", "N", "<=", "19", "and", "sgfc", "==", "'tt'", ")", ":", "return", "None", "return", "_SGF_COLUMNS", ".", "index", "(", "sgfc", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
from_gtp
Converts from a GTP coordinate to a Minigo coordinate.
reinforcement/tensorflow/minigo/coords.py
def from_gtp(gtpc): """Converts from a GTP coordinate to a Minigo coordinate.""" gtpc = gtpc.upper() if gtpc == 'PASS': return None col = _GTP_COLUMNS.index(gtpc[0]) row_from_bottom = int(gtpc[1:]) return go.N - row_from_bottom, col
def from_gtp(gtpc): """Converts from a GTP coordinate to a Minigo coordinate.""" gtpc = gtpc.upper() if gtpc == 'PASS': return None col = _GTP_COLUMNS.index(gtpc[0]) row_from_bottom = int(gtpc[1:]) return go.N - row_from_bottom, col
[ "Converts", "from", "a", "GTP", "coordinate", "to", "a", "Minigo", "coordinate", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/coords.py#L78-L85
[ "def", "from_gtp", "(", "gtpc", ")", ":", "gtpc", "=", "gtpc", ".", "upper", "(", ")", "if", "gtpc", "==", "'PASS'", ":", "return", "None", "col", "=", "_GTP_COLUMNS", ".", "index", "(", "gtpc", "[", "0", "]", ")", "row_from_bottom", "=", "int", "(...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
to_gtp
Converts from a Minigo coordinate to a GTP coordinate.
reinforcement/tensorflow/minigo/coords.py
def to_gtp(coord): """Converts from a Minigo coordinate to a GTP coordinate.""" if coord is None: return 'pass' y, x = coord return '{}{}'.format(_GTP_COLUMNS[x], go.N - y)
def to_gtp(coord): """Converts from a Minigo coordinate to a GTP coordinate.""" if coord is None: return 'pass' y, x = coord return '{}{}'.format(_GTP_COLUMNS[x], go.N - y)
[ "Converts", "from", "a", "Minigo", "coordinate", "to", "a", "GTP", "coordinate", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/coords.py#L88-L93
[ "def", "to_gtp", "(", "coord", ")", ":", "if", "coord", "is", "None", ":", "return", "'pass'", "y", ",", "x", "=", "coord", "return", "'{}{}'", ".", "format", "(", "_GTP_COLUMNS", "[", "x", "]", ",", "go", ".", "N", "-", "y", ")" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
findContours
Wraps cv2.findContours to maintain compatiblity between versions 3 and 4 Returns: contours, hierarchy
object_detection/pytorch/maskrcnn_benchmark/utils/cv2_util.py
def findContours(*args, **kwargs): """ Wraps cv2.findContours to maintain compatiblity between versions 3 and 4 Returns: contours, hierarchy """ if cv2.__version__.startswith('4'): contours, hierarchy = cv2.findContours(*args, **kwargs) elif cv2.__version__.startswith('3'): ...
def findContours(*args, **kwargs): """ Wraps cv2.findContours to maintain compatiblity between versions 3 and 4 Returns: contours, hierarchy """ if cv2.__version__.startswith('4'): contours, hierarchy = cv2.findContours(*args, **kwargs) elif cv2.__version__.startswith('3'): ...
[ "Wraps", "cv2", ".", "findContours", "to", "maintain", "compatiblity", "between", "versions", "3", "and", "4" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/utils/cv2_util.py#L8-L24
[ "def", "findContours", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "cv2", ".", "__version__", ".", "startswith", "(", "'4'", ")", ":", "contours", ",", "hierarchy", "=", "cv2", ".", "findContours", "(", "*", "args", ",", "*", "*", "k...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
MCTSNode.maybe_add_child
Adds child node for fcoord if it doesn't already exist, and returns it.
reinforcement/tensorflow/minigo/mcts.py
def maybe_add_child(self, fcoord): """ Adds child node for fcoord if it doesn't already exist, and returns it. """ if fcoord not in self.children: new_position = self.position.play_move( coords.from_flat(fcoord)) self.children[fcoord] = MCTSNode( n...
def maybe_add_child(self, fcoord): """ Adds child node for fcoord if it doesn't already exist, and returns it. """ if fcoord not in self.children: new_position = self.position.play_move( coords.from_flat(fcoord)) self.children[fcoord] = MCTSNode( n...
[ "Adds", "child", "node", "for", "fcoord", "if", "it", "doesn", "t", "already", "exist", "and", "returns", "it", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/mcts.py#L158-L165
[ "def", "maybe_add_child", "(", "self", ",", "fcoord", ")", ":", "if", "fcoord", "not", "in", "self", ".", "children", ":", "new_position", "=", "self", ".", "position", ".", "play_move", "(", "coords", ".", "from_flat", "(", "fcoord", ")", ")", "self", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
MCTSNode.add_virtual_loss
Propagate a virtual loss up to the root node. Args: up_to: The node to propagate until. (Keep track of this! You'll need it to reverse the virtual loss later.)
reinforcement/tensorflow/minigo/mcts.py
def add_virtual_loss(self, up_to): """Propagate a virtual loss up to the root node. Args: up_to: The node to propagate until. (Keep track of this! You'll need it to reverse the virtual loss later.) """ self.losses_applied += 1 # This is a "win" for th...
def add_virtual_loss(self, up_to): """Propagate a virtual loss up to the root node. Args: up_to: The node to propagate until. (Keep track of this! You'll need it to reverse the virtual loss later.) """ self.losses_applied += 1 # This is a "win" for th...
[ "Propagate", "a", "virtual", "loss", "up", "to", "the", "root", "node", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/mcts.py#L167-L181
[ "def", "add_virtual_loss", "(", "self", ",", "up_to", ")", ":", "self", ".", "losses_applied", "+=", "1", "# This is a \"win\" for the current node; hence a loss for its parent node", "# who will be deciding whether to investigate this node again.", "loss", "=", "self", ".", "p...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
MCTSNode.backup_value
Propagates a value estimation up to the root node. Args: value: the value to be propagated (1 = black wins, -1 = white wins) up_to: the node to propagate until.
reinforcement/tensorflow/minigo/mcts.py
def backup_value(self, value, up_to): """Propagates a value estimation up to the root node. Args: value: the value to be propagated (1 = black wins, -1 = white wins) up_to: the node to propagate until. """ self.N += 1 self.W += value if self.paren...
def backup_value(self, value, up_to): """Propagates a value estimation up to the root node. Args: value: the value to be propagated (1 = black wins, -1 = white wins) up_to: the node to propagate until. """ self.N += 1 self.W += value if self.paren...
[ "Propagates", "a", "value", "estimation", "up", "to", "the", "root", "node", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/mcts.py#L222-L233
[ "def", "backup_value", "(", "self", ",", "value", ",", "up_to", ")", ":", "self", ".", "N", "+=", "1", "self", ".", "W", "+=", "value", "if", "self", ".", "parent", "is", "None", "or", "self", "is", "up_to", ":", "return", "self", ".", "parent", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
MCTSNode.is_done
True if the last two moves were Pass or if the position is at a move greater than the max depth.
reinforcement/tensorflow/minigo/mcts.py
def is_done(self): """True if the last two moves were Pass or if the position is at a move greater than the max depth.""" return self.position.is_game_over() or self.position.n >= FLAGS.max_game_length
def is_done(self): """True if the last two moves were Pass or if the position is at a move greater than the max depth.""" return self.position.is_game_over() or self.position.n >= FLAGS.max_game_length
[ "True", "if", "the", "last", "two", "moves", "were", "Pass", "or", "if", "the", "position", "is", "at", "a", "move", "greater", "than", "the", "max", "depth", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/mcts.py#L235-L238
[ "def", "is_done", "(", "self", ")", ":", "return", "self", ".", "position", ".", "is_game_over", "(", ")", "or", "self", ".", "position", ".", "n", ">=", "FLAGS", ".", "max_game_length" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
MCTSNode.children_as_pi
Returns the child visit counts as a probability distribution, pi If squash is true, exponentiate the probabilities by a temperature slightly larger than unity to encourage diversity in early play and hopefully to move away from 3-3s
reinforcement/tensorflow/minigo/mcts.py
def children_as_pi(self, squash=False): """Returns the child visit counts as a probability distribution, pi If squash is true, exponentiate the probabilities by a temperature slightly larger than unity to encourage diversity in early play and hopefully to move away from 3-3s """ ...
def children_as_pi(self, squash=False): """Returns the child visit counts as a probability distribution, pi If squash is true, exponentiate the probabilities by a temperature slightly larger than unity to encourage diversity in early play and hopefully to move away from 3-3s """ ...
[ "Returns", "the", "child", "visit", "counts", "as", "a", "probability", "distribution", "pi", "If", "squash", "is", "true", "exponentiate", "the", "probabilities", "by", "a", "temperature", "slightly", "larger", "than", "unity", "to", "encourage", "diversity", "...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/mcts.py#L248-L260
[ "def", "children_as_pi", "(", "self", ",", "squash", "=", "False", ")", ":", "probs", "=", "self", ".", "child_N", "if", "squash", ":", "probs", "=", "probs", "**", ".98", "sum_probs", "=", "np", ".", "sum", "(", "probs", ")", "if", "sum_probs", "=="...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
MCTSNode.mvp_gg
Returns most visited path in go-gui VAR format e.g. 'b r3 w c17...
reinforcement/tensorflow/minigo/mcts.py
def mvp_gg(self): """ Returns most visited path in go-gui VAR format e.g. 'b r3 w c17...""" output = [] for node in self.most_visited_path_nodes(): if max(node.child_N) <= 1: break output.append(coords.to_gtp(coords.from_flat(node.fmove))) return '...
def mvp_gg(self): """ Returns most visited path in go-gui VAR format e.g. 'b r3 w c17...""" output = [] for node in self.most_visited_path_nodes(): if max(node.child_N) <= 1: break output.append(coords.to_gtp(coords.from_flat(node.fmove))) return '...
[ "Returns", "most", "visited", "path", "in", "go", "-", "gui", "VAR", "format", "e", ".", "g", ".", "b", "r3", "w", "c17", "..." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/mcts.py#L285-L292
[ "def", "mvp_gg", "(", "self", ")", ":", "output", "=", "[", "]", "for", "node", "in", "self", ".", "most_visited_path_nodes", "(", ")", ":", "if", "max", "(", "node", ".", "child_N", ")", "<=", "1", ":", "break", "output", ".", "append", "(", "coor...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_convert_args
Convert a list of command arguments to types specified by the handler. Args: handler: a command handler function. args: the list of string arguments to pass to handler. Returns: A new list containing `args` that have been converted to the expected type for `handler`. For each function ...
reinforcement/tensorflow/minigo/gtp_engine.py
def _convert_args(handler, args): """Convert a list of command arguments to types specified by the handler. Args: handler: a command handler function. args: the list of string arguments to pass to handler. Returns: A new list containing `args` that have been converted to the expected typ...
def _convert_args(handler, args): """Convert a list of command arguments to types specified by the handler. Args: handler: a command handler function. args: the list of string arguments to pass to handler. Returns: A new list containing `args` that have been converted to the expected typ...
[ "Convert", "a", "list", "of", "command", "arguments", "to", "types", "specified", "by", "the", "handler", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/gtp_engine.py#L89-L120
[ "def", "_convert_args", "(", "handler", ",", "args", ")", ":", "args", "=", "list", "(", "args", ")", "params", "=", "inspect", ".", "signature", "(", "handler", ")", ".", "parameters", "for", "i", ",", "(", "arg", ",", "name", ")", "in", "enumerate"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Engine.add_cmd_handler
Registers a new command handler object. All methods on `handler_obj` whose name starts with "cmd_" are registered as a GTP command. For example, the method cmd_genmove will be invoked when the engine receives a genmove command. Args: handler_obj: the handler object to registe...
reinforcement/tensorflow/minigo/gtp_engine.py
def add_cmd_handler(self, handler_obj): """Registers a new command handler object. All methods on `handler_obj` whose name starts with "cmd_" are registered as a GTP command. For example, the method cmd_genmove will be invoked when the engine receives a genmove command. Args: ...
def add_cmd_handler(self, handler_obj): """Registers a new command handler object. All methods on `handler_obj` whose name starts with "cmd_" are registered as a GTP command. For example, the method cmd_genmove will be invoked when the engine receives a genmove command. Args: ...
[ "Registers", "a", "new", "command", "handler", "object", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/gtp_engine.py#L133-L151
[ "def", "add_cmd_handler", "(", "self", ",", "handler_obj", ")", ":", "for", "field", "in", "dir", "(", "handler_obj", ")", ":", "if", "field", ".", "startswith", "(", "\"cmd_\"", ")", ":", "cmd", "=", "field", "[", "4", ":", "]", "fn", "=", "getattr"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_pad_tensors_to_same_length
Pad x and y so that the results have the same length (second dimension).
translation/tensorflow/transformer/utils/metrics.py
def _pad_tensors_to_same_length(x, y): """Pad x and y so that the results have the same length (second dimension).""" with tf.name_scope("pad_to_same_length"): x_length = tf.shape(x)[1] y_length = tf.shape(y)[1] max_length = tf.maximum(x_length, y_length) x = tf.pad(x, [[0, 0], [0, max_length - x_...
def _pad_tensors_to_same_length(x, y): """Pad x and y so that the results have the same length (second dimension).""" with tf.name_scope("pad_to_same_length"): x_length = tf.shape(x)[1] y_length = tf.shape(y)[1] max_length = tf.maximum(x_length, y_length) x = tf.pad(x, [[0, 0], [0, max_length - x_...
[ "Pad", "x", "and", "y", "so", "that", "the", "results", "have", "the", "same", "length", "(", "second", "dimension", ")", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/metrics.py#L39-L49
[ "def", "_pad_tensors_to_same_length", "(", "x", ",", "y", ")", ":", "with", "tf", ".", "name_scope", "(", "\"pad_to_same_length\"", ")", ":", "x_length", "=", "tf", ".", "shape", "(", "x", ")", "[", "1", "]", "y_length", "=", "tf", ".", "shape", "(", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
padded_cross_entropy_loss
Calculate cross entropy loss while ignoring padding. Args: logits: Tensor of size [batch_size, length_logits, vocab_size] labels: Tensor of size [batch_size, length_labels] smoothing: Label smoothing constant, used to determine the on and off values vocab_size: int size of the vocabulary Returns: ...
translation/tensorflow/transformer/utils/metrics.py
def padded_cross_entropy_loss(logits, labels, smoothing, vocab_size): """Calculate cross entropy loss while ignoring padding. Args: logits: Tensor of size [batch_size, length_logits, vocab_size] labels: Tensor of size [batch_size, length_labels] smoothing: Label smoothing constant, used to determine th...
def padded_cross_entropy_loss(logits, labels, smoothing, vocab_size): """Calculate cross entropy loss while ignoring padding. Args: logits: Tensor of size [batch_size, length_logits, vocab_size] labels: Tensor of size [batch_size, length_labels] smoothing: Label smoothing constant, used to determine th...
[ "Calculate", "cross", "entropy", "loss", "while", "ignoring", "padding", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/metrics.py#L52-L87
[ "def", "padded_cross_entropy_loss", "(", "logits", ",", "labels", ",", "smoothing", ",", "vocab_size", ")", ":", "with", "tf", ".", "name_scope", "(", "\"loss\"", ",", "[", "logits", ",", "labels", "]", ")", ":", "logits", ",", "labels", "=", "_pad_tensors...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_convert_to_eval_metric
Wrap a metric fn that returns scores and weights as an eval metric fn. The input metric_fn returns values for the current batch. The wrapper aggregates the return values collected over all of the batches evaluated. Args: metric_fn: function that returns scores and weights for the current batch's logit...
translation/tensorflow/transformer/utils/metrics.py
def _convert_to_eval_metric(metric_fn): """Wrap a metric fn that returns scores and weights as an eval metric fn. The input metric_fn returns values for the current batch. The wrapper aggregates the return values collected over all of the batches evaluated. Args: metric_fn: function that returns scores an...
def _convert_to_eval_metric(metric_fn): """Wrap a metric fn that returns scores and weights as an eval metric fn. The input metric_fn returns values for the current batch. The wrapper aggregates the return values collected over all of the batches evaluated. Args: metric_fn: function that returns scores an...
[ "Wrap", "a", "metric", "fn", "that", "returns", "scores", "and", "weights", "as", "an", "eval", "metric", "fn", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/metrics.py#L90-L109
[ "def", "_convert_to_eval_metric", "(", "metric_fn", ")", ":", "def", "problem_metric_fn", "(", "*", "args", ")", ":", "\"\"\"Returns an aggregation of the metric_fn's returned values.\"\"\"", "(", "scores", ",", "weights", ")", "=", "metric_fn", "(", "*", "args", ")",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_eval_metrics
Return dictionary of model evaluation metrics.
translation/tensorflow/transformer/utils/metrics.py
def get_eval_metrics(logits, labels, params): """Return dictionary of model evaluation metrics.""" metrics = { "accuracy": _convert_to_eval_metric(padded_accuracy)(logits, labels), "accuracy_top5": _convert_to_eval_metric(padded_accuracy_top5)( logits, labels), "accuracy_per_sequence": _...
def get_eval_metrics(logits, labels, params): """Return dictionary of model evaluation metrics.""" metrics = { "accuracy": _convert_to_eval_metric(padded_accuracy)(logits, labels), "accuracy_top5": _convert_to_eval_metric(padded_accuracy_top5)( logits, labels), "accuracy_per_sequence": _...
[ "Return", "dictionary", "of", "model", "evaluation", "metrics", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/metrics.py#L112-L130
[ "def", "get_eval_metrics", "(", "logits", ",", "labels", ",", "params", ")", ":", "metrics", "=", "{", "\"accuracy\"", ":", "_convert_to_eval_metric", "(", "padded_accuracy", ")", "(", "logits", ",", "labels", ")", ",", "\"accuracy_top5\"", ":", "_convert_to_eva...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
padded_accuracy
Percentage of times that predictions matches labels on non-0s.
translation/tensorflow/transformer/utils/metrics.py
def padded_accuracy(logits, labels): """Percentage of times that predictions matches labels on non-0s.""" with tf.variable_scope("padded_accuracy", values=[logits, labels]): logits, labels = _pad_tensors_to_same_length(logits, labels) weights = tf.to_float(tf.not_equal(labels, 0)) outputs = tf.to_int32(...
def padded_accuracy(logits, labels): """Percentage of times that predictions matches labels on non-0s.""" with tf.variable_scope("padded_accuracy", values=[logits, labels]): logits, labels = _pad_tensors_to_same_length(logits, labels) weights = tf.to_float(tf.not_equal(labels, 0)) outputs = tf.to_int32(...
[ "Percentage", "of", "times", "that", "predictions", "matches", "labels", "on", "non", "-", "0s", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/metrics.py#L133-L140
[ "def", "padded_accuracy", "(", "logits", ",", "labels", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"padded_accuracy\"", ",", "values", "=", "[", "logits", ",", "labels", "]", ")", ":", "logits", ",", "labels", "=", "_pad_tensors_to_same_length", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
padded_accuracy_topk
Percentage of times that top-k predictions matches labels on non-0s.
translation/tensorflow/transformer/utils/metrics.py
def padded_accuracy_topk(logits, labels, k): """Percentage of times that top-k predictions matches labels on non-0s.""" with tf.variable_scope("padded_accuracy_topk", values=[logits, labels]): logits, labels = _pad_tensors_to_same_length(logits, labels) weights = tf.to_float(tf.not_equal(labels, 0)) eff...
def padded_accuracy_topk(logits, labels, k): """Percentage of times that top-k predictions matches labels on non-0s.""" with tf.variable_scope("padded_accuracy_topk", values=[logits, labels]): logits, labels = _pad_tensors_to_same_length(logits, labels) weights = tf.to_float(tf.not_equal(labels, 0)) eff...
[ "Percentage", "of", "times", "that", "top", "-", "k", "predictions", "matches", "labels", "on", "non", "-", "0s", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/metrics.py#L143-L156
[ "def", "padded_accuracy_topk", "(", "logits", ",", "labels", ",", "k", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"padded_accuracy_topk\"", ",", "values", "=", "[", "logits", ",", "labels", "]", ")", ":", "logits", ",", "labels", "=", "_pad_tens...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
padded_sequence_accuracy
Percentage of times that predictions matches labels everywhere (non-0).
translation/tensorflow/transformer/utils/metrics.py
def padded_sequence_accuracy(logits, labels): """Percentage of times that predictions matches labels everywhere (non-0).""" with tf.variable_scope("padded_sequence_accuracy", values=[logits, labels]): logits, labels = _pad_tensors_to_same_length(logits, labels) weights = tf.to_float(tf.not_equal(labels, 0))...
def padded_sequence_accuracy(logits, labels): """Percentage of times that predictions matches labels everywhere (non-0).""" with tf.variable_scope("padded_sequence_accuracy", values=[logits, labels]): logits, labels = _pad_tensors_to_same_length(logits, labels) weights = tf.to_float(tf.not_equal(labels, 0))...
[ "Percentage", "of", "times", "that", "predictions", "matches", "labels", "everywhere", "(", "non", "-", "0", ")", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/metrics.py#L163-L173
[ "def", "padded_sequence_accuracy", "(", "logits", ",", "labels", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"padded_sequence_accuracy\"", ",", "values", "=", "[", "logits", ",", "labels", "]", ")", ":", "logits", ",", "labels", "=", "_pad_tensors_to...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
padded_neg_log_perplexity
Average log-perplexity excluding padding 0s. No smoothing.
translation/tensorflow/transformer/utils/metrics.py
def padded_neg_log_perplexity(logits, labels, vocab_size): """Average log-perplexity excluding padding 0s. No smoothing.""" num, den = padded_cross_entropy_loss(logits, labels, 0, vocab_size) return -num, den
def padded_neg_log_perplexity(logits, labels, vocab_size): """Average log-perplexity excluding padding 0s. No smoothing.""" num, den = padded_cross_entropy_loss(logits, labels, 0, vocab_size) return -num, den
[ "Average", "log", "-", "perplexity", "excluding", "padding", "0s", ".", "No", "smoothing", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/metrics.py#L176-L179
[ "def", "padded_neg_log_perplexity", "(", "logits", ",", "labels", ",", "vocab_size", ")", ":", "num", ",", "den", "=", "padded_cross_entropy_loss", "(", "logits", ",", "labels", ",", "0", ",", "vocab_size", ")", "return", "-", "num", ",", "den" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
bleu_score
Approximate BLEU score computation between labels and predictions. An approximate BLEU scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4 and use brevity penalty. Also, this does not have beam search. Args: logits: Tensor of size ...
translation/tensorflow/transformer/utils/metrics.py
def bleu_score(logits, labels): """Approximate BLEU score computation between labels and predictions. An approximate BLEU scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4 and use brevity penalty. Also, this does not have beam search....
def bleu_score(logits, labels): """Approximate BLEU score computation between labels and predictions. An approximate BLEU scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4 and use brevity penalty. Also, this does not have beam search....
[ "Approximate", "BLEU", "score", "computation", "between", "labels", "and", "predictions", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/metrics.py#L182-L199
[ "def", "bleu_score", "(", "logits", ",", "labels", ")", ":", "predictions", "=", "tf", ".", "to_int32", "(", "tf", ".", "argmax", "(", "logits", ",", "axis", "=", "-", "1", ")", ")", "# TODO: Look into removing use of py_func", "bleu", "=", "tf", ".", "p...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_get_ngrams_with_counter
Extracts all n-grams up to a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Returns: The Counter containing all n-grams upto max_order in segment with ...
translation/tensorflow/transformer/utils/metrics.py
def _get_ngrams_with_counter(segment, max_order): """Extracts all n-grams up to a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Returns: The Counter con...
def _get_ngrams_with_counter(segment, max_order): """Extracts all n-grams up to a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Returns: The Counter con...
[ "Extracts", "all", "n", "-", "grams", "up", "to", "a", "given", "maximum", "order", "from", "an", "input", "segment", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/metrics.py#L202-L219
[ "def", "_get_ngrams_with_counter", "(", "segment", ",", "max_order", ")", ":", "ngram_counts", "=", "collections", ".", "Counter", "(", ")", "for", "order", "in", "xrange", "(", "1", ",", "max_order", "+", "1", ")", ":", "for", "i", "in", "xrange", "(", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
compute_bleu
Computes BLEU score of translated segments against one or more references. Args: reference_corpus: list of references for each translation. Each reference should be tokenized into a list of tokens. translation_corpus: list of translations to score. Each translation should be tokenized into a ...
translation/tensorflow/transformer/utils/metrics.py
def compute_bleu(reference_corpus, translation_corpus, max_order=4, use_bp=True): """Computes BLEU score of translated segments against one or more references. Args: reference_corpus: list of references for each translation. Each reference should be tokenized into a list of tokens. ...
def compute_bleu(reference_corpus, translation_corpus, max_order=4, use_bp=True): """Computes BLEU score of translated segments against one or more references. Args: reference_corpus: list of references for each translation. Each reference should be tokenized into a list of tokens. ...
[ "Computes", "BLEU", "score", "of", "translated", "segments", "against", "one", "or", "more", "references", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/metrics.py#L222-L285
[ "def", "compute_bleu", "(", "reference_corpus", ",", "translation_corpus", ",", "max_order", "=", "4", ",", "use_bp", "=", "True", ")", ":", "reference_length", "=", "0", "translation_length", "=", "0", "bp", "=", "1.0", "geo_mean", "=", "0", "matches_by_order...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
rouge_2_fscore
ROUGE-2 F1 score computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: logits: tensor, model predictions labels: tensor, gold output. Returns: rouge2_fscore: approx rouge-2 f1 score...
translation/tensorflow/transformer/utils/metrics.py
def rouge_2_fscore(logits, labels): """ROUGE-2 F1 score computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: logits: tensor, model predictions labels: tensor, gold output. Returns: ...
def rouge_2_fscore(logits, labels): """ROUGE-2 F1 score computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: logits: tensor, model predictions labels: tensor, gold output. Returns: ...
[ "ROUGE", "-", "2", "F1", "score", "computation", "between", "labels", "and", "predictions", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/metrics.py#L288-L304
[ "def", "rouge_2_fscore", "(", "logits", ",", "labels", ")", ":", "predictions", "=", "tf", ".", "to_int32", "(", "tf", ".", "argmax", "(", "logits", ",", "axis", "=", "-", "1", ")", ")", "# TODO: Look into removing use of py_func", "rouge_2_f_score", "=", "t...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
rouge_n
Computes ROUGE-N f1 score of two text collections of sentences. Source: https://www.microsoft.com/en-us/research/publication/ rouge-a-package-for-automatic-evaluation-of-summaries/ Args: eval_sentences: Predicted sentences. ref_sentences: Sentences from the reference set n: Size of ngram. Defaults ...
translation/tensorflow/transformer/utils/metrics.py
def rouge_n(eval_sentences, ref_sentences, n=2): """Computes ROUGE-N f1 score of two text collections of sentences. Source: https://www.microsoft.com/en-us/research/publication/ rouge-a-package-for-automatic-evaluation-of-summaries/ Args: eval_sentences: Predicted sentences. ref_sentences: Sentences f...
def rouge_n(eval_sentences, ref_sentences, n=2): """Computes ROUGE-N f1 score of two text collections of sentences. Source: https://www.microsoft.com/en-us/research/publication/ rouge-a-package-for-automatic-evaluation-of-summaries/ Args: eval_sentences: Predicted sentences. ref_sentences: Sentences f...
[ "Computes", "ROUGE", "-", "N", "f1", "score", "of", "two", "text", "collections", "of", "sentences", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/metrics.py#L325-L362
[ "def", "rouge_n", "(", "eval_sentences", ",", "ref_sentences", ",", "n", "=", "2", ")", ":", "f1_scores", "=", "[", "]", "for", "eval_sentence", ",", "ref_sentence", "in", "zip", "(", "eval_sentences", ",", "ref_sentences", ")", ":", "eval_ngrams", "=", "_...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
rouge_l_fscore
ROUGE scores computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: predictions: tensor, model predictions labels: tensor, gold output. Returns: rouge_l_fscore: approx rouge-l f1 sco...
translation/tensorflow/transformer/utils/metrics.py
def rouge_l_fscore(predictions, labels): """ROUGE scores computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: predictions: tensor, model predictions labels: tensor, gold output. Retu...
def rouge_l_fscore(predictions, labels): """ROUGE scores computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: predictions: tensor, model predictions labels: tensor, gold output. Retu...
[ "ROUGE", "scores", "computation", "between", "labels", "and", "predictions", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/metrics.py#L365-L381
[ "def", "rouge_l_fscore", "(", "predictions", ",", "labels", ")", ":", "outputs", "=", "tf", ".", "to_int32", "(", "tf", ".", "argmax", "(", "predictions", ",", "axis", "=", "-", "1", ")", ")", "rouge_l_f_score", "=", "tf", ".", "py_func", "(", "rouge_l...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
parse_args
Helper function parsing the command line options @retval ArgumentParser
single_stage_detector/ssd/bind_launch.py
def parse_args(): """ Helper function parsing the command line options @retval ArgumentParser """ parser = ArgumentParser(description="PyTorch distributed training launch " "helper utilty that will spawn up " "multiple d...
def parse_args(): """ Helper function parsing the command line options @retval ArgumentParser """ parser = ArgumentParser(description="PyTorch distributed training launch " "helper utilty that will spawn up " "multiple d...
[ "Helper", "function", "parsing", "the", "command", "line", "options" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/single_stage_detector/ssd/bind_launch.py#L10-L60
[ "def", "parse_args", "(", ")", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "\"PyTorch distributed training launch \"", "\"helper utilty that will spawn up \"", "\"multiple distributed processes\"", ")", "# Optional arguments for the launch helper", "parser", ".",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
download_and_extract
Extract files from downloaded compressed archive file. Args: path: string directory where the files will be downloaded url: url containing the compressed input and target files input_filename: name of file containing data in source language target_filename: name of file containing data in target lang...
translation/data_download.py
def download_and_extract(path, url, input_filename, target_filename): """Extract files from downloaded compressed archive file. Args: path: string directory where the files will be downloaded url: url containing the compressed input and target files input_filename: name of file containing data in sourc...
def download_and_extract(path, url, input_filename, target_filename): """Extract files from downloaded compressed archive file. Args: path: string directory where the files will be downloaded url: url containing the compressed input and target files input_filename: name of file containing data in sourc...
[ "Extract", "files", "from", "downloaded", "compressed", "archive", "file", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/data_download.py#L146-L185
[ "def", "download_and_extract", "(", "path", ",", "url", ",", "input_filename", ",", "target_filename", ")", ":", "logging", ".", "info", "(", "'Downloading and extracting data to: %s'", "%", "path", ")", "# Check if extracted files already exist in path", "input_file", "=...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
main
Obtain training and evaluation data for the Transformer model.
translation/data_download.py
def main(unused_argv): """Obtain training and evaluation data for the Transformer model.""" make_dir(FLAGS.raw_dir) make_dir(FLAGS.data_dir) # Get paths of download/extracted training and evaluation files. print("Step 1/4: Downloading data from source") train_files = get_raw_files(FLAGS.raw_dir, _TRAIN_DAT...
def main(unused_argv): """Obtain training and evaluation data for the Transformer model.""" make_dir(FLAGS.raw_dir) make_dir(FLAGS.data_dir) # Get paths of download/extracted training and evaluation files. print("Step 1/4: Downloading data from source") train_files = get_raw_files(FLAGS.raw_dir, _TRAIN_DAT...
[ "Obtain", "training", "and", "evaluation", "data", "for", "the", "Transformer", "model", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/data_download.py#L194-L202
[ "def", "main", "(", "unused_argv", ")", ":", "make_dir", "(", "FLAGS", ".", "raw_dir", ")", "make_dir", "(", "FLAGS", ".", "data_dir", ")", "# Get paths of download/extracted training and evaluation files.", "print", "(", "\"Step 1/4: Downloading data from source\"", ")",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4