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
_generate_subtokens_with_target_vocab_size
Generate subtoken vocabulary close to the target size.
translation/tensorflow/transformer/utils/tokenizer.py
def _generate_subtokens_with_target_vocab_size( token_counts, alphabet, target_size, threshold, min_count=None, reserved_tokens=None): """Generate subtoken vocabulary close to the target size.""" if reserved_tokens is None: reserved_tokens = RESERVED_TOKENS if min_count is not None: tf.logging.in...
def _generate_subtokens_with_target_vocab_size( token_counts, alphabet, target_size, threshold, min_count=None, reserved_tokens=None): """Generate subtoken vocabulary close to the target size.""" if reserved_tokens is None: reserved_tokens = RESERVED_TOKENS if min_count is not None: tf.logging.in...
[ "Generate", "subtoken", "vocabulary", "close", "to", "the", "target", "size", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L394-L435
[ "def", "_generate_subtokens_with_target_vocab_size", "(", "token_counts", ",", "alphabet", ",", "target_size", ",", "threshold", ",", "min_count", "=", "None", ",", "reserved_tokens", "=", "None", ")", ":", "if", "reserved_tokens", "is", "None", ":", "reserved_token...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_generate_alphabet_dict
Create set of characters that appear in any element in the iterable.
translation/tensorflow/transformer/utils/tokenizer.py
def _generate_alphabet_dict(iterable, reserved_tokens=None): """Create set of characters that appear in any element in the iterable.""" if reserved_tokens is None: reserved_tokens = RESERVED_TOKENS alphabet = {c for token in iterable for c in token} alphabet |= {c for token in reserved_tokens for c in token...
def _generate_alphabet_dict(iterable, reserved_tokens=None): """Create set of characters that appear in any element in the iterable.""" if reserved_tokens is None: reserved_tokens = RESERVED_TOKENS alphabet = {c for token in iterable for c in token} alphabet |= {c for token in reserved_tokens for c in token...
[ "Create", "set", "of", "characters", "that", "appear", "in", "any", "element", "in", "the", "iterable", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L438-L445
[ "def", "_generate_alphabet_dict", "(", "iterable", ",", "reserved_tokens", "=", "None", ")", ":", "if", "reserved_tokens", "is", "None", ":", "reserved_tokens", "=", "RESERVED_TOKENS", "alphabet", "=", "{", "c", "for", "token", "in", "iterable", "for", "c", "i...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_count_and_gen_subtokens
Count number of times subtokens appear, and generate new subtokens. Args: token_counts: dict mapping tokens to the number of times they appear in the original files. alphabet: list of allowed characters. Used to escape the tokens, which guarantees that all tokens can be split into subtokens. ...
translation/tensorflow/transformer/utils/tokenizer.py
def _count_and_gen_subtokens( token_counts, alphabet, subtoken_dict, max_subtoken_length): """Count number of times subtokens appear, and generate new subtokens. Args: token_counts: dict mapping tokens to the number of times they appear in the original files. alphabet: list of allowed characters....
def _count_and_gen_subtokens( token_counts, alphabet, subtoken_dict, max_subtoken_length): """Count number of times subtokens appear, and generate new subtokens. Args: token_counts: dict mapping tokens to the number of times they appear in the original files. alphabet: list of allowed characters....
[ "Count", "number", "of", "times", "subtokens", "appear", "and", "generate", "new", "subtokens", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L448-L478
[ "def", "_count_and_gen_subtokens", "(", "token_counts", ",", "alphabet", ",", "subtoken_dict", ",", "max_subtoken_length", ")", ":", "subtoken_counts", "=", "collections", ".", "defaultdict", "(", "int", ")", "for", "token", ",", "count", "in", "six", ".", "iter...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_filter_and_bucket_subtokens
Return a bucketed list of subtokens that are filtered by count. Args: subtoken_counts: defaultdict mapping subtokens to their counts min_count: int count used to filter subtokens Returns: List of subtoken sets, where subtokens in set i have the same length=i.
translation/tensorflow/transformer/utils/tokenizer.py
def _filter_and_bucket_subtokens(subtoken_counts, min_count): """Return a bucketed list of subtokens that are filtered by count. Args: subtoken_counts: defaultdict mapping subtokens to their counts min_count: int count used to filter subtokens Returns: List of subtoken sets, where subtokens in set i...
def _filter_and_bucket_subtokens(subtoken_counts, min_count): """Return a bucketed list of subtokens that are filtered by count. Args: subtoken_counts: defaultdict mapping subtokens to their counts min_count: int count used to filter subtokens Returns: List of subtoken sets, where subtokens in set i...
[ "Return", "a", "bucketed", "list", "of", "subtokens", "that", "are", "filtered", "by", "count", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L481-L499
[ "def", "_filter_and_bucket_subtokens", "(", "subtoken_counts", ",", "min_count", ")", ":", "# Create list of buckets, where subtokens in bucket i have length i.", "subtoken_buckets", "=", "[", "]", "for", "subtoken", ",", "count", "in", "six", ".", "iteritems", "(", "subt...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_gen_new_subtoken_list
Generate candidate subtokens ordered by count, and new max subtoken length. Add subtokens to the candiate list in order of length (longest subtokens first). When a subtoken is added, the counts of each of its prefixes are decreased. Prefixes that don't appear much outside the subtoken are not added to the cand...
translation/tensorflow/transformer/utils/tokenizer.py
def _gen_new_subtoken_list( subtoken_counts, min_count, alphabet, reserved_tokens=None): """Generate candidate subtokens ordered by count, and new max subtoken length. Add subtokens to the candiate list in order of length (longest subtokens first). When a subtoken is added, the counts of each of its prefixes...
def _gen_new_subtoken_list( subtoken_counts, min_count, alphabet, reserved_tokens=None): """Generate candidate subtokens ordered by count, and new max subtoken length. Add subtokens to the candiate list in order of length (longest subtokens first). When a subtoken is added, the counts of each of its prefixes...
[ "Generate", "candidate", "subtokens", "ordered", "by", "count", "and", "new", "max", "subtoken", "length", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L502-L571
[ "def", "_gen_new_subtoken_list", "(", "subtoken_counts", ",", "min_count", ",", "alphabet", ",", "reserved_tokens", "=", "None", ")", ":", "if", "reserved_tokens", "is", "None", ":", "reserved_tokens", "=", "RESERVED_TOKENS", "# Create a list of (count, subtoken) for each...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_generate_subtokens
Create a list of subtokens in decreasing order of frequency. Args: token_counts: dict mapping str tokens -> int count alphabet: set of characters min_count: int minimum number of times a subtoken must appear before it is added to the vocabulary. num_iterations: int number of iterations to gener...
translation/tensorflow/transformer/utils/tokenizer.py
def _generate_subtokens( token_counts, alphabet, min_count, num_iterations=4, reserved_tokens=None): """Create a list of subtokens in decreasing order of frequency. Args: token_counts: dict mapping str tokens -> int count alphabet: set of characters min_count: int minimum number of times a subt...
def _generate_subtokens( token_counts, alphabet, min_count, num_iterations=4, reserved_tokens=None): """Create a list of subtokens in decreasing order of frequency. Args: token_counts: dict mapping str tokens -> int count alphabet: set of characters min_count: int minimum number of times a subt...
[ "Create", "a", "list", "of", "subtokens", "in", "decreasing", "order", "of", "frequency", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L574-L616
[ "def", "_generate_subtokens", "(", "token_counts", ",", "alphabet", ",", "min_count", ",", "num_iterations", "=", "4", ",", "reserved_tokens", "=", "None", ")", ":", "if", "reserved_tokens", "is", "None", ":", "reserved_tokens", "=", "RESERVED_TOKENS", "# Use alph...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Subtokenizer.init_from_files
Create subtoken vocabulary based on files, and save vocab to file. Args: vocab_file: String name of vocab file to store subtoken vocabulary. files: List of file paths that will be used to generate vocabulary. target_vocab_size: target vocabulary size to generate. threshold: int threshold of...
translation/tensorflow/transformer/utils/tokenizer.py
def init_from_files( vocab_file, files, target_vocab_size, threshold, min_count=None, file_byte_limit=1e6, reserved_tokens=None): """Create subtoken vocabulary based on files, and save vocab to file. Args: vocab_file: String name of vocab file to store subtoken vocabulary. files: List o...
def init_from_files( vocab_file, files, target_vocab_size, threshold, min_count=None, file_byte_limit=1e6, reserved_tokens=None): """Create subtoken vocabulary based on files, and save vocab to file. Args: vocab_file: String name of vocab file to store subtoken vocabulary. files: List o...
[ "Create", "subtoken", "vocabulary", "based", "on", "files", "and", "save", "vocab", "to", "file", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L87-L126
[ "def", "init_from_files", "(", "vocab_file", ",", "files", ",", "target_vocab_size", ",", "threshold", ",", "min_count", "=", "None", ",", "file_byte_limit", "=", "1e6", ",", "reserved_tokens", "=", "None", ")", ":", "if", "reserved_tokens", "is", "None", ":",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Subtokenizer.encode
Encodes a string into a list of int subtoken ids.
translation/tensorflow/transformer/utils/tokenizer.py
def encode(self, raw_string, add_eos=False): """Encodes a string into a list of int subtoken ids.""" ret = [] tokens = _split_string_to_tokens(_native_to_unicode(raw_string)) for token in tokens: ret.extend(self._token_to_subtoken_ids(token)) if add_eos: ret.append(EOS_ID) return ret
def encode(self, raw_string, add_eos=False): """Encodes a string into a list of int subtoken ids.""" ret = [] tokens = _split_string_to_tokens(_native_to_unicode(raw_string)) for token in tokens: ret.extend(self._token_to_subtoken_ids(token)) if add_eos: ret.append(EOS_ID) return ret
[ "Encodes", "a", "string", "into", "a", "list", "of", "int", "subtoken", "ids", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L128-L136
[ "def", "encode", "(", "self", ",", "raw_string", ",", "add_eos", "=", "False", ")", ":", "ret", "=", "[", "]", "tokens", "=", "_split_string_to_tokens", "(", "_native_to_unicode", "(", "raw_string", ")", ")", "for", "token", "in", "tokens", ":", "ret", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Subtokenizer._token_to_subtoken_ids
Encode a single token into a list of subtoken ids.
translation/tensorflow/transformer/utils/tokenizer.py
def _token_to_subtoken_ids(self, token): """Encode a single token into a list of subtoken ids.""" cache_location = hash(token) % self._cache_size cache_key, cache_value = self._cache[cache_location] if cache_key == token: return cache_value ret = _split_token_to_subtokens( _escape_tok...
def _token_to_subtoken_ids(self, token): """Encode a single token into a list of subtoken ids.""" cache_location = hash(token) % self._cache_size cache_key, cache_value = self._cache[cache_location] if cache_key == token: return cache_value ret = _split_token_to_subtokens( _escape_tok...
[ "Encode", "a", "single", "token", "into", "a", "list", "of", "subtoken", "ids", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L138-L151
[ "def", "_token_to_subtoken_ids", "(", "self", ",", "token", ")", ":", "cache_location", "=", "hash", "(", "token", ")", "%", "self", ".", "_cache_size", "cache_key", ",", "cache_value", "=", "self", ".", "_cache", "[", "cache_location", "]", "if", "cache_key...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Subtokenizer.decode
Converts list of int subtokens ids into a string.
translation/tensorflow/transformer/utils/tokenizer.py
def decode(self, subtokens): """Converts list of int subtokens ids into a string.""" if isinstance(subtokens, np.ndarray): # Note that list(subtokens) converts subtokens to a python list, but the # items remain as np.int32. This converts both the array and its items. subtokens = subtokens.toli...
def decode(self, subtokens): """Converts list of int subtokens ids into a string.""" if isinstance(subtokens, np.ndarray): # Note that list(subtokens) converts subtokens to a python list, but the # items remain as np.int32. This converts both the array and its items. subtokens = subtokens.toli...
[ "Converts", "list", "of", "int", "subtokens", "ids", "into", "a", "string", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L153-L167
[ "def", "decode", "(", "self", ",", "subtokens", ")", ":", "if", "isinstance", "(", "subtokens", ",", "np", ".", "ndarray", ")", ":", "# Note that list(subtokens) converts subtokens to a python list, but the", "# items remain as np.int32. This converts both the array and its ite...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Subtokenizer._subtoken_ids_to_tokens
Convert list of int subtoken ids to a list of string tokens.
translation/tensorflow/transformer/utils/tokenizer.py
def _subtoken_ids_to_tokens(self, subtokens): """Convert list of int subtoken ids to a list of string tokens.""" escaped_tokens = "".join([ self.subtoken_list[s] for s in subtokens if s < len(self.subtoken_list)]) escaped_tokens = escaped_tokens.split("_") # All tokens in the vocabulary...
def _subtoken_ids_to_tokens(self, subtokens): """Convert list of int subtoken ids to a list of string tokens.""" escaped_tokens = "".join([ self.subtoken_list[s] for s in subtokens if s < len(self.subtoken_list)]) escaped_tokens = escaped_tokens.split("_") # All tokens in the vocabulary...
[ "Convert", "list", "of", "int", "subtoken", "ids", "to", "a", "list", "of", "string", "tokens", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L169-L182
[ "def", "_subtoken_ids_to_tokens", "(", "self", ",", "subtokens", ")", ":", "escaped_tokens", "=", "\"\"", ".", "join", "(", "[", "self", ".", "subtoken_list", "[", "s", "]", "for", "s", "in", "subtokens", "if", "s", "<", "len", "(", "self", ".", "subto...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
batch_run_many
Used to avoid a memory oveflow issue when running the network on too many positions. TODO: This should be a member function of player.network?
reinforcement/tensorflow/minigo/oneoffs/training_curve.py
def batch_run_many(player, positions, batch_size=100): """Used to avoid a memory oveflow issue when running the network on too many positions. TODO: This should be a member function of player.network?""" prob_list = [] value_list = [] for idx in range(0, len(positions), batch_size): prob...
def batch_run_many(player, positions, batch_size=100): """Used to avoid a memory oveflow issue when running the network on too many positions. TODO: This should be a member function of player.network?""" prob_list = [] value_list = [] for idx in range(0, len(positions), batch_size): prob...
[ "Used", "to", "avoid", "a", "memory", "oveflow", "issue", "when", "running", "the", "network", "on", "too", "many", "positions", ".", "TODO", ":", "This", "should", "be", "a", "member", "function", "of", "player", ".", "network?" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/oneoffs/training_curve.py#L62-L72
[ "def", "batch_run_many", "(", "player", ",", "positions", ",", "batch_size", "=", "100", ")", ":", "prob_list", "=", "[", "]", "value_list", "=", "[", "]", "for", "idx", "in", "range", "(", "0", ",", "len", "(", "positions", ")", ",", "batch_size", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
MaskPostProcessor.forward
Arguments: x (Tensor): the mask logits boxes (list[BoxList]): bounding boxes that are used as reference, one for ech image Returns: results (list[BoxList]): one BoxList for each image, containing the extra field mask
object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/mask_head/inference.py
def forward(self, x, boxes): """ Arguments: x (Tensor): the mask logits boxes (list[BoxList]): bounding boxes that are used as reference, one for ech image Returns: results (list[BoxList]): one BoxList for each image, containing ...
def forward(self, x, boxes): """ Arguments: x (Tensor): the mask logits boxes (list[BoxList]): bounding boxes that are used as reference, one for ech image Returns: results (list[BoxList]): one BoxList for each image, containing ...
[ "Arguments", ":", "x", "(", "Tensor", ")", ":", "the", "mask", "logits", "boxes", "(", "list", "[", "BoxList", "]", ")", ":", "bounding", "boxes", "that", "are", "used", "as", "reference", "one", "for", "ech", "image" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/mask_head/inference.py#L27-L61
[ "def", "forward", "(", "self", ",", "x", ",", "boxes", ")", ":", "mask_prob", "=", "x", ".", "sigmoid", "(", ")", "# select masks coresponding to the predicted classes", "num_masks", "=", "x", ".", "shape", "[", "0", "]", "labels", "=", "[", "bbox", ".", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_caller
Returns file.py:lineno of your caller. A stack_index of 2 will provide the caller of the function calling this function. Notice that stack_index of 2 or more will fail if called from global scope.
compliance/mlperf_compliance/mlperf_log.py
def get_caller(stack_index=2, root_dir=None): ''' Returns file.py:lineno of your caller. A stack_index of 2 will provide the caller of the function calling this function. Notice that stack_index of 2 or more will fail if called from global scope. ''' caller = inspect.getframeinfo(inspect.stack()[stack_i...
def get_caller(stack_index=2, root_dir=None): ''' Returns file.py:lineno of your caller. A stack_index of 2 will provide the caller of the function calling this function. Notice that stack_index of 2 or more will fail if called from global scope. ''' caller = inspect.getframeinfo(inspect.stack()[stack_i...
[ "Returns", "file", ".", "py", ":", "lineno", "of", "your", "caller", ".", "A", "stack_index", "of", "2", "will", "provide", "the", "caller", "of", "the", "function", "calling", "this", "function", ".", "Notice", "that", "stack_index", "of", "2", "or", "m...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/compliance/mlperf_compliance/mlperf_log.py#L67-L77
[ "def", "get_caller", "(", "stack_index", "=", "2", ",", "root_dir", "=", "None", ")", ":", "caller", "=", "inspect", ".", "getframeinfo", "(", "inspect", ".", "stack", "(", ")", "[", "stack_index", "]", "[", "0", "]", ")", "# Trim the filenames for readabi...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_mlperf_print
Prints out an MLPerf Log Line. key: The MLPerf log key such as 'CLOCK' or 'QUALITY'. See the list of log keys in the spec. value: The value which contains no newlines. benchmark: The short code for the benchmark being run, see the MLPerf log spec. stack_offset: Increase the value to go deeper into the stack to...
compliance/mlperf_compliance/mlperf_log.py
def _mlperf_print(key, value=None, benchmark=None, stack_offset=0, tag_set=None, deferred=False, root_dir=None, extra_print=False, prefix=""): ''' Prints out an MLPerf Log Line. key: The MLPerf log key such as 'CLOCK' or 'QUALITY'. See the list of log keys in the spec. value: ...
def _mlperf_print(key, value=None, benchmark=None, stack_offset=0, tag_set=None, deferred=False, root_dir=None, extra_print=False, prefix=""): ''' Prints out an MLPerf Log Line. key: The MLPerf log key such as 'CLOCK' or 'QUALITY'. See the list of log keys in the spec. value: ...
[ "Prints", "out", "an", "MLPerf", "Log", "Line", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/compliance/mlperf_compliance/mlperf_log.py#L80-L138
[ "def", "_mlperf_print", "(", "key", ",", "value", "=", "None", ",", "benchmark", "=", "None", ",", "stack_offset", "=", "0", ",", "tag_set", "=", "None", ",", "deferred", "=", "False", ",", "root_dir", "=", "None", ",", "extra_print", "=", "False", ","...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
generate
Generates a new model name, given the model number.
reinforcement/tensorflow/minigo/rl_loop/shipname.py
def generate(model_num): """Generates a new model name, given the model number.""" if model_num == 0: new_name = 'bootstrap' else: new_name = random.choice(NAMES) full_name = "%06d-%s" % (model_num, new_name) return full_name
def generate(model_num): """Generates a new model name, given the model number.""" if model_num == 0: new_name = 'bootstrap' else: new_name = random.choice(NAMES) full_name = "%06d-%s" % (model_num, new_name) return full_name
[ "Generates", "a", "new", "model", "name", "given", "the", "model", "number", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/rl_loop/shipname.py#L27-L34
[ "def", "generate", "(", "model_num", ")", ":", "if", "model_num", "==", "0", ":", "new_name", "=", "'bootstrap'", "else", ":", "new_name", "=", "random", ".", "choice", "(", "NAMES", ")", "full_name", "=", "\"%06d-%s\"", "%", "(", "model_num", ",", "new_...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
detect_model_num
Takes a string related to a model name and extract its model number. For example: '000000-bootstrap.index' => 0
reinforcement/tensorflow/minigo/rl_loop/shipname.py
def detect_model_num(string): """Takes a string related to a model name and extract its model number. For example: '000000-bootstrap.index' => 0 """ match = re.match(MODEL_NUM_REGEX, string) if match: return int(match.group()) return None
def detect_model_num(string): """Takes a string related to a model name and extract its model number. For example: '000000-bootstrap.index' => 0 """ match = re.match(MODEL_NUM_REGEX, string) if match: return int(match.group()) return None
[ "Takes", "a", "string", "related", "to", "a", "model", "name", "and", "extract", "its", "model", "number", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/rl_loop/shipname.py#L37-L46
[ "def", "detect_model_num", "(", "string", ")", ":", "match", "=", "re", ".", "match", "(", "MODEL_NUM_REGEX", ",", "string", ")", "if", "match", ":", "return", "int", "(", "match", ".", "group", "(", ")", ")", "return", "None" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
detect_model_name
Takes a string related to a model name and extract its model name. For example: '000000-bootstrap.index' => '000000-bootstrap'
reinforcement/tensorflow/minigo/rl_loop/shipname.py
def detect_model_name(string): """Takes a string related to a model name and extract its model name. For example: '000000-bootstrap.index' => '000000-bootstrap' """ match = re.match(MODEL_NAME_REGEX, string) if match: return match.group() return None
def detect_model_name(string): """Takes a string related to a model name and extract its model name. For example: '000000-bootstrap.index' => '000000-bootstrap' """ match = re.match(MODEL_NAME_REGEX, string) if match: return match.group() return None
[ "Takes", "a", "string", "related", "to", "a", "model", "name", "and", "extract", "its", "model", "name", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/rl_loop/shipname.py#L49-L58
[ "def", "detect_model_name", "(", "string", ")", ":", "match", "=", "re", ".", "match", "(", "MODEL_NAME_REGEX", ",", "string", ")", "if", "match", ":", "return", "match", ".", "group", "(", ")", "return", "None" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
batch_norm
Performs a batch normalization using a standard set of parameters.
image_classification/tensorflow/official/resnet/resnet_model.py
def batch_norm(inputs, training, data_format): """Performs a batch normalization using a standard set of parameters.""" # We set fused=True for a significant performance boost. See # https://www.tensorflow.org/performance/performance_guide#common_fused_ops outputs = tf.layers.batch_normalization( inputs=i...
def batch_norm(inputs, training, data_format): """Performs a batch normalization using a standard set of parameters.""" # We set fused=True for a significant performance boost. See # https://www.tensorflow.org/performance/performance_guide#common_fused_ops outputs = tf.layers.batch_normalization( inputs=i...
[ "Performs", "a", "batch", "normalization", "using", "a", "standard", "set", "of", "parameters", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/resnet_model.py#L51-L64
[ "def", "batch_norm", "(", "inputs", ",", "training", ",", "data_format", ")", ":", "# We set fused=True for a significant performance boost. See", "# https://www.tensorflow.org/performance/performance_guide#common_fused_ops", "outputs", "=", "tf", ".", "layers", ".", "batch_norma...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
fixed_padding
Pads the input along the spatial dimensions independently of input size. Args: inputs: A tensor of size [batch, channels, height_in, width_in] or [batch, height_in, width_in, channels] depending on data_format. kernel_size: The kernel to be used in the conv2d or max_pool2d operation. S...
image_classification/tensorflow/official/resnet/resnet_model.py
def fixed_padding(inputs, kernel_size, data_format): """Pads the input along the spatial dimensions independently of input size. Args: inputs: A tensor of size [batch, channels, height_in, width_in] or [batch, height_in, width_in, channels] depending on data_format. kernel_size: The kernel to be used...
def fixed_padding(inputs, kernel_size, data_format): """Pads the input along the spatial dimensions independently of input size. Args: inputs: A tensor of size [batch, channels, height_in, width_in] or [batch, height_in, width_in, channels] depending on data_format. kernel_size: The kernel to be used...
[ "Pads", "the", "input", "along", "the", "spatial", "dimensions", "independently", "of", "input", "size", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/resnet_model.py#L67-L91
[ "def", "fixed_padding", "(", "inputs", ",", "kernel_size", ",", "data_format", ")", ":", "pad_total", "=", "kernel_size", "-", "1", "pad_beg", "=", "pad_total", "//", "2", "pad_end", "=", "pad_total", "-", "pad_beg", "if", "data_format", "==", "'channels_first...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
conv2d_fixed_padding
Strided 2-D convolution with explicit padding.
image_classification/tensorflow/official/resnet/resnet_model.py
def conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format): """Strided 2-D convolution with explicit padding.""" # The padding is consistent and is based only on `kernel_size`, not on the # dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone). inputs_for_logging = inputs if...
def conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format): """Strided 2-D convolution with explicit padding.""" # The padding is consistent and is based only on `kernel_size`, not on the # dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone). inputs_for_logging = inputs if...
[ "Strided", "2", "-", "D", "convolution", "with", "explicit", "padding", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/resnet_model.py#L94-L114
[ "def", "conv2d_fixed_padding", "(", "inputs", ",", "filters", ",", "kernel_size", ",", "strides", ",", "data_format", ")", ":", "# The padding is consistent and is based only on `kernel_size`, not on the", "# dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone).", "i...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_bottleneck_block_v1
A single block for ResNet v1, with a bottleneck. Similar to _building_block_v1(), except using the "bottleneck" blocks described in: Convolution then batch normalization then ReLU as described by: Deep Residual Learning for Image Recognition https://arxiv.org/pdf/1512.03385.pdf by Kaiming He,...
image_classification/tensorflow/official/resnet/resnet_model.py
def _bottleneck_block_v1(inputs, filters, training, projection_shortcut, strides, data_format): """A single block for ResNet v1, with a bottleneck. Similar to _building_block_v1(), except using the "bottleneck" blocks described in: Convolution then batch normalization then ReLU as de...
def _bottleneck_block_v1(inputs, filters, training, projection_shortcut, strides, data_format): """A single block for ResNet v1, with a bottleneck. Similar to _building_block_v1(), except using the "bottleneck" blocks described in: Convolution then batch normalization then ReLU as de...
[ "A", "single", "block", "for", "ResNet", "v1", "with", "a", "bottleneck", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/resnet_model.py#L130-L196
[ "def", "_bottleneck_block_v1", "(", "inputs", ",", "filters", ",", "training", ",", "projection_shortcut", ",", "strides", ",", "data_format", ")", ":", "resnet_log_helper", ".", "log_begin_block", "(", "input_tensor", "=", "inputs", ",", "block_type", "=", "mlper...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
block_layer
Creates one layer of blocks for the ResNet model. Args: inputs: A tensor of size [batch, channels, height_in, width_in] or [batch, height_in, width_in, channels] depending on data_format. filters: The number of filters for the first convolution of the layer. bottleneck: Is the block created a bottl...
image_classification/tensorflow/official/resnet/resnet_model.py
def block_layer(inputs, filters, bottleneck, block_fn, blocks, strides, training, name, data_format): """Creates one layer of blocks for the ResNet model. Args: inputs: A tensor of size [batch, channels, height_in, width_in] or [batch, height_in, width_in, channels] depending on data_form...
def block_layer(inputs, filters, bottleneck, block_fn, blocks, strides, training, name, data_format): """Creates one layer of blocks for the ResNet model. Args: inputs: A tensor of size [batch, channels, height_in, width_in] or [batch, height_in, width_in, channels] depending on data_form...
[ "Creates", "one", "layer", "of", "blocks", "for", "the", "ResNet", "model", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/resnet_model.py#L204-L242
[ "def", "block_layer", "(", "inputs", ",", "filters", ",", "bottleneck", ",", "block_fn", ",", "blocks", ",", "strides", ",", "training", ",", "name", ",", "data_format", ")", ":", "# Bottleneck blocks end with 4x the number of filters as they start with", "filters_out",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Model._custom_dtype_getter
Creates variables in fp32, then casts to fp16 if necessary. This function is a custom getter. A custom getter is a function with the same signature as tf.get_variable, except it has an additional getter parameter. Custom getters can be passed as the `custom_getter` parameter of tf.variable_scope. Then,...
image_classification/tensorflow/official/resnet/resnet_model.py
def _custom_dtype_getter(self, getter, name, shape=None, dtype=DEFAULT_DTYPE, *args, **kwargs): """Creates variables in fp32, then casts to fp16 if necessary. This function is a custom getter. A custom getter is a function with the same signature as tf.get_variable, except it has...
def _custom_dtype_getter(self, getter, name, shape=None, dtype=DEFAULT_DTYPE, *args, **kwargs): """Creates variables in fp32, then casts to fp16 if necessary. This function is a custom getter. A custom getter is a function with the same signature as tf.get_variable, except it has...
[ "Creates", "variables", "in", "fp32", "then", "casts", "to", "fp16", "if", "necessary", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/resnet_model.py#L328-L367
[ "def", "_custom_dtype_getter", "(", "self", ",", "getter", ",", "name", ",", "shape", "=", "None", ",", "dtype", "=", "DEFAULT_DTYPE", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "dtype", "in", "CASTABLE_TYPES", ":", "var", "=", "getter"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
DistributedSampler.init_rng
Creates new RNG, seed depends on current epoch idx.
rnn_translator/pytorch/seq2seq/data/sampler.py
def init_rng(self): """ Creates new RNG, seed depends on current epoch idx. """ rng = torch.Generator() seed = self.seeds[self.epoch] logging.info(f'Sampler for epoch {self.epoch} uses seed {seed}') rng.manual_seed(seed) return rng
def init_rng(self): """ Creates new RNG, seed depends on current epoch idx. """ rng = torch.Generator() seed = self.seeds[self.epoch] logging.info(f'Sampler for epoch {self.epoch} uses seed {seed}') rng.manual_seed(seed) return rng
[ "Creates", "new", "RNG", "seed", "depends", "on", "current", "epoch", "idx", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/data/sampler.py#L42-L50
[ "def", "init_rng", "(", "self", ")", ":", "rng", "=", "torch", ".", "Generator", "(", ")", "seed", "=", "self", ".", "seeds", "[", "self", ".", "epoch", "]", "logging", ".", "info", "(", "f'Sampler for epoch {self.epoch} uses seed {seed}'", ")", "rng", "."...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
DistributedSampler.distribute_batches
Assigns batches to workers. Consecutive ranks are getting consecutive batches. :param indices: torch.tensor with batch indices
rnn_translator/pytorch/seq2seq/data/sampler.py
def distribute_batches(self, indices): """ Assigns batches to workers. Consecutive ranks are getting consecutive batches. :param indices: torch.tensor with batch indices """ assert len(indices) == self.num_samples indices = indices.view(-1, self.batch_size) ...
def distribute_batches(self, indices): """ Assigns batches to workers. Consecutive ranks are getting consecutive batches. :param indices: torch.tensor with batch indices """ assert len(indices) == self.num_samples indices = indices.view(-1, self.batch_size) ...
[ "Assigns", "batches", "to", "workers", ".", "Consecutive", "ranks", "are", "getting", "consecutive", "batches", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/data/sampler.py#L52-L67
[ "def", "distribute_batches", "(", "self", ",", "indices", ")", ":", "assert", "len", "(", "indices", ")", "==", "self", ".", "num_samples", "indices", "=", "indices", ".", "view", "(", "-", "1", ",", "self", ".", "batch_size", ")", "indices", "=", "ind...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
DistributedSampler.reshuffle_batches
Permutes global batches :param indices: torch.tensor with batch indices :param rng: instance of torch.Generator
rnn_translator/pytorch/seq2seq/data/sampler.py
def reshuffle_batches(self, indices, rng): """ Permutes global batches :param indices: torch.tensor with batch indices :param rng: instance of torch.Generator """ indices = indices.view(-1, self.global_batch_size) num_batches = indices.shape[0] order = to...
def reshuffle_batches(self, indices, rng): """ Permutes global batches :param indices: torch.tensor with batch indices :param rng: instance of torch.Generator """ indices = indices.view(-1, self.global_batch_size) num_batches = indices.shape[0] order = to...
[ "Permutes", "global", "batches" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/data/sampler.py#L69-L81
[ "def", "reshuffle_batches", "(", "self", ",", "indices", ",", "rng", ")", ":", "indices", "=", "indices", ".", "view", "(", "-", "1", ",", "self", ".", "global_batch_size", ")", "num_batches", "=", "indices", ".", "shape", "[", "0", "]", "order", "=", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
RetinaNetModule.forward
Arguments: images (ImageList): images for which we want to compute the predictions features (list[Tensor]): features computed from the images that are used for computing the predictions. Each tensor in the list correspond to different feature levels ta...
object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/retinanet/retinanet.py
def forward(self, images, features, targets=None): """ Arguments: images (ImageList): images for which we want to compute the predictions features (list[Tensor]): features computed from the images that are used for computing the predictions. Each tensor in the lis...
def forward(self, images, features, targets=None): """ Arguments: images (ImageList): images for which we want to compute the predictions features (list[Tensor]): features computed from the images that are used for computing the predictions. Each tensor in the lis...
[ "Arguments", ":", "images", "(", "ImageList", ")", ":", "images", "for", "which", "we", "want", "to", "compute", "the", "predictions", "features", "(", "list", "[", "Tensor", "]", ")", ":", "features", "computed", "from", "the", "images", "that", "are", ...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/retinanet/retinanet.py#L113-L134
[ "def", "forward", "(", "self", ",", "images", ",", "features", ",", "targets", "=", "None", ")", ":", "box_cls", ",", "box_regression", "=", "self", ".", "head", "(", "features", ")", "anchors", "=", "self", ".", "anchor_generator", "(", "images", ",", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
smooth_l1_loss
very similar to the smooth_l1_loss from pytorch, but with the extra beta parameter
object_detection/pytorch/maskrcnn_benchmark/layers/smooth_l1_loss.py
def smooth_l1_loss(input, target, beta=1. / 9, size_average=True): """ very similar to the smooth_l1_loss from pytorch, but with the extra beta parameter """ n = torch.abs(input - target) cond = n < beta loss = torch.where(cond, 0.5 * n ** 2 / beta, n - 0.5 * beta) if size_average: ...
def smooth_l1_loss(input, target, beta=1. / 9, size_average=True): """ very similar to the smooth_l1_loss from pytorch, but with the extra beta parameter """ n = torch.abs(input - target) cond = n < beta loss = torch.where(cond, 0.5 * n ** 2 / beta, n - 0.5 * beta) if size_average: ...
[ "very", "similar", "to", "the", "smooth_l1_loss", "from", "pytorch", "but", "with", "the", "extra", "beta", "parameter" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/layers/smooth_l1_loss.py#L6-L16
[ "def", "smooth_l1_loss", "(", "input", ",", "target", ",", "beta", "=", "1.", "/", "9", ",", "size_average", "=", "True", ")", ":", "n", "=", "torch", ".", "abs", "(", "input", "-", "target", ")", "cond", "=", "n", "<", "beta", "loss", "=", "torc...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
eval_policy
Evaluate all positions with all models save the policy heatmaps as CSVs CSV name is "heatmap-<position_name>-<model-index>.csv" CSV format is: model number, value network output, policy network outputs position_name is taken from the SGF file Policy network outputs (19x19) are saved in flat order (see...
reinforcement/tensorflow/minigo/oneoffs/heatmap.py
def eval_policy(eval_positions): """Evaluate all positions with all models save the policy heatmaps as CSVs CSV name is "heatmap-<position_name>-<model-index>.csv" CSV format is: model number, value network output, policy network outputs position_name is taken from the SGF file Policy network outp...
def eval_policy(eval_positions): """Evaluate all positions with all models save the policy heatmaps as CSVs CSV name is "heatmap-<position_name>-<model-index>.csv" CSV format is: model number, value network output, policy network outputs position_name is taken from the SGF file Policy network outp...
[ "Evaluate", "all", "positions", "with", "all", "models", "save", "the", "policy", "heatmaps", "as", "CSVs" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/oneoffs/heatmap.py#L45-L85
[ "def", "eval_policy", "(", "eval_positions", ")", ":", "model_paths", "=", "oneoff_utils", ".", "get_model_paths", "(", "fsdb", ".", "models_dir", "(", ")", ")", "idx_start", "=", "FLAGS", ".", "idx_start", "eval_every", "=", "FLAGS", ".", "eval_every", "print...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
dbg
Helper function to print to stderr and flush
reinforcement/tensorflow/minigo/utils.py
def dbg(*objects, file=sys.stderr, flush=True, **kwargs): "Helper function to print to stderr and flush" print(*objects, file=file, flush=flush, **kwargs)
def dbg(*objects, file=sys.stderr, flush=True, **kwargs): "Helper function to print to stderr and flush" print(*objects, file=file, flush=flush, **kwargs)
[ "Helper", "function", "to", "print", "to", "stderr", "and", "flush" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/utils.py#L27-L29
[ "def", "dbg", "(", "*", "objects", ",", "file", "=", "sys", ".", "stderr", ",", "flush", "=", "True", ",", "*", "*", "kwargs", ")", ":", "print", "(", "*", "objects", ",", "file", "=", "file", ",", "flush", "=", "flush", ",", "*", "*", "kwargs"...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
ensure_dir_exists
Creates local directories if they don't exist.
reinforcement/tensorflow/minigo/utils.py
def ensure_dir_exists(directory): "Creates local directories if they don't exist." if directory.startswith('gs://'): return if not os.path.exists(directory): dbg("Making dir {}".format(directory)) os.makedirs(directory, exist_ok=True)
def ensure_dir_exists(directory): "Creates local directories if they don't exist." if directory.startswith('gs://'): return if not os.path.exists(directory): dbg("Making dir {}".format(directory)) os.makedirs(directory, exist_ok=True)
[ "Creates", "local", "directories", "if", "they", "don", "t", "exist", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/utils.py#L32-L38
[ "def", "ensure_dir_exists", "(", "directory", ")", ":", "if", "directory", ".", "startswith", "(", "'gs://'", ")", ":", "return", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "dbg", "(", "\"Making dir {}\"", ".", "format", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
parse_game_result
Parse an SGF result string into value target.
reinforcement/tensorflow/minigo/utils.py
def parse_game_result(result): "Parse an SGF result string into value target." if re.match(r'[bB]\+', result): return 1 if re.match(r'[wW]\+', result): return -1 return 0
def parse_game_result(result): "Parse an SGF result string into value target." if re.match(r'[bB]\+', result): return 1 if re.match(r'[wW]\+', result): return -1 return 0
[ "Parse", "an", "SGF", "result", "string", "into", "value", "target", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/utils.py#L41-L47
[ "def", "parse_game_result", "(", "result", ")", ":", "if", "re", ".", "match", "(", "r'[bB]\\+'", ",", "result", ")", ":", "return", "1", "if", "re", ".", "match", "(", "r'[wW]\\+'", ",", "result", ")", ":", "return", "-", "1", "return", "0" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
iter_chunks
Yield from an iterator in chunks of chunk_size.
reinforcement/tensorflow/minigo/utils.py
def iter_chunks(chunk_size, iterator): "Yield from an iterator in chunks of chunk_size." iterator = iter(iterator) while True: next_chunk = _take_n(chunk_size, iterator) # If len(iterable) % chunk_size == 0, don't return an empty chunk. if next_chunk: yield next_chunk ...
def iter_chunks(chunk_size, iterator): "Yield from an iterator in chunks of chunk_size." iterator = iter(iterator) while True: next_chunk = _take_n(chunk_size, iterator) # If len(iterable) % chunk_size == 0, don't return an empty chunk. if next_chunk: yield next_chunk ...
[ "Yield", "from", "an", "iterator", "in", "chunks", "of", "chunk_size", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/utils.py#L59-L68
[ "def", "iter_chunks", "(", "chunk_size", ",", "iterator", ")", ":", "iterator", "=", "iter", "(", "iterator", ")", "while", "True", ":", "next_chunk", "=", "_take_n", "(", "chunk_size", ",", "iterator", ")", "# If len(iterable) % chunk_size == 0, don't return an emp...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
timer
Context manager for timing snippets of code.
reinforcement/tensorflow/minigo/utils.py
def timer(message): "Context manager for timing snippets of code." tick = time.time() yield tock = time.time() print("%s: %.3f seconds" % (message, (tock - tick)))
def timer(message): "Context manager for timing snippets of code." tick = time.time() yield tock = time.time() print("%s: %.3f seconds" % (message, (tock - tick)))
[ "Context", "manager", "for", "timing", "snippets", "of", "code", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/utils.py#L72-L77
[ "def", "timer", "(", "message", ")", ":", "tick", "=", "time", ".", "time", "(", ")", "yield", "tock", "=", "time", ".", "time", "(", ")", "print", "(", "\"%s: %.3f seconds\"", "%", "(", "message", ",", "(", "tock", "-", "tick", ")", ")", ")" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
logged_timer
Context manager for timing snippets of code. Echos to logging module.
reinforcement/tensorflow/minigo/utils.py
def logged_timer(message): "Context manager for timing snippets of code. Echos to logging module." tick = time.time() yield tock = time.time() logging.info("%s: %.3f seconds", message, (tock - tick))
def logged_timer(message): "Context manager for timing snippets of code. Echos to logging module." tick = time.time() yield tock = time.time() logging.info("%s: %.3f seconds", message, (tock - tick))
[ "Context", "manager", "for", "timing", "snippets", "of", "code", ".", "Echos", "to", "logging", "module", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/utils.py#L81-L86
[ "def", "logged_timer", "(", "message", ")", ":", "tick", "=", "time", ".", "time", "(", ")", "yield", "tock", "=", "time", ".", "time", "(", ")", "logging", ".", "info", "(", "\"%s: %.3f seconds\"", ",", "message", ",", "(", "tock", "-", "tick", ")",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
find_file
Returns full filepath if the file is in path or a subdirectory.
translation/tensorflow/transformer/data_download.py
def find_file(path, filename, max_depth=5): """Returns full filepath if the file is in path or a subdirectory.""" for root, dirs, files in os.walk(path): if filename in files: return os.path.join(root, filename) # Don't search past max_depth depth = root[len(path) + 1:].count(os.sep) if depth...
def find_file(path, filename, max_depth=5): """Returns full filepath if the file is in path or a subdirectory.""" for root, dirs, files in os.walk(path): if filename in files: return os.path.join(root, filename) # Don't search past max_depth depth = root[len(path) + 1:].count(os.sep) if depth...
[ "Returns", "full", "filepath", "if", "the", "file", "is", "in", "path", "or", "a", "subdirectory", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/data_download.py#L86-L96
[ "def", "find_file", "(", "path", ",", "filename", ",", "max_depth", "=", "5", ")", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "path", ")", ":", "if", "filename", "in", "files", ":", "return", "os", ".", "path", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_raw_files
Return raw files from source. Downloads/extracts if needed. Args: raw_dir: string directory to store raw files data_source: dictionary with {"url": url of compressed dataset containing input and target files "input": file with data in input language "target": file with data in target lang...
translation/tensorflow/transformer/data_download.py
def get_raw_files(raw_dir, data_source): """Return raw files from source. Downloads/extracts if needed. Args: raw_dir: string directory to store raw files data_source: dictionary with {"url": url of compressed dataset containing input and target files "input": file with data in input language ...
def get_raw_files(raw_dir, data_source): """Return raw files from source. Downloads/extracts if needed. Args: raw_dir: string directory to store raw files data_source: dictionary with {"url": url of compressed dataset containing input and target files "input": file with data in input language ...
[ "Return", "raw", "files", "from", "source", ".", "Downloads", "/", "extracts", "if", "needed", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/data_download.py#L102-L127
[ "def", "get_raw_files", "(", "raw_dir", ",", "data_source", ")", ":", "raw_files", "=", "{", "\"inputs\"", ":", "[", "]", ",", "\"targets\"", ":", "[", "]", ",", "}", "# keys", "for", "d", "in", "data_source", ":", "input_file", ",", "target_file", "=", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
txt_line_iterator
Iterate through lines of file.
translation/tensorflow/transformer/data_download.py
def txt_line_iterator(path): """Iterate through lines of file.""" with tf.gfile.Open(path) as f: for line in f: yield line.strip()
def txt_line_iterator(path): """Iterate through lines of file.""" with tf.gfile.Open(path) as f: for line in f: yield line.strip()
[ "Iterate", "through", "lines", "of", "file", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/data_download.py#L210-L214
[ "def", "txt_line_iterator", "(", "path", ")", ":", "with", "tf", ".", "gfile", ".", "Open", "(", "path", ")", "as", "f", ":", "for", "line", "in", "f", ":", "yield", "line", ".", "strip", "(", ")" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
compile_files
Compile raw files into a single file for each language. Args: raw_dir: Directory containing downloaded raw files. raw_files: Dict containing filenames of input and target data. {"inputs": list of files containing data in input language "targets": list of files containing corresponding data in ta...
translation/tensorflow/transformer/data_download.py
def compile_files(raw_dir, raw_files, tag): """Compile raw files into a single file for each language. Args: raw_dir: Directory containing downloaded raw files. raw_files: Dict containing filenames of input and target data. {"inputs": list of files containing data in input language "targets": ...
def compile_files(raw_dir, raw_files, tag): """Compile raw files into a single file for each language. Args: raw_dir: Directory containing downloaded raw files. raw_files: Dict containing filenames of input and target data. {"inputs": list of files containing data in input language "targets": ...
[ "Compile", "raw", "files", "into", "a", "single", "file", "for", "each", "language", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/data_download.py#L217-L245
[ "def", "compile_files", "(", "raw_dir", ",", "raw_files", ",", "tag", ")", ":", "tf", ".", "logging", ".", "info", "(", "\"Compiling files with tag %s.\"", "%", "tag", ")", "filename", "=", "\"%s-%s\"", "%", "(", "_PREFIX", ",", "tag", ")", "input_compiled_f...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
write_file
Write all of lines from file using the writer.
translation/tensorflow/transformer/data_download.py
def write_file(writer, filename): """Write all of lines from file using the writer.""" for line in txt_line_iterator(filename): writer.write(line) writer.write("\n")
def write_file(writer, filename): """Write all of lines from file using the writer.""" for line in txt_line_iterator(filename): writer.write(line) writer.write("\n")
[ "Write", "all", "of", "lines", "from", "file", "using", "the", "writer", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/data_download.py#L248-L252
[ "def", "write_file", "(", "writer", ",", "filename", ")", ":", "for", "line", "in", "txt_line_iterator", "(", "filename", ")", ":", "writer", ".", "write", "(", "line", ")", "writer", ".", "write", "(", "\"\\n\"", ")" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
encode_and_save_files
Save data from files as encoded Examples in TFrecord format. Args: subtokenizer: Subtokenizer object that will be used to encode the strings. data_dir: The directory in which to write the examples raw_files: A tuple of (input, target) data files. Each line in the input and the corresponding line in...
translation/tensorflow/transformer/data_download.py
def encode_and_save_files( subtokenizer, data_dir, raw_files, tag, total_shards): """Save data from files as encoded Examples in TFrecord format. Args: subtokenizer: Subtokenizer object that will be used to encode the strings. data_dir: The directory in which to write the examples raw_files: A tupl...
def encode_and_save_files( subtokenizer, data_dir, raw_files, tag, total_shards): """Save data from files as encoded Examples in TFrecord format. Args: subtokenizer: Subtokenizer object that will be used to encode the strings. data_dir: The directory in which to write the examples raw_files: A tupl...
[ "Save", "data", "from", "files", "as", "encoded", "Examples", "in", "TFrecord", "format", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/data_download.py#L258-L305
[ "def", "encode_and_save_files", "(", "subtokenizer", ",", "data_dir", ",", "raw_files", ",", "tag", ",", "total_shards", ")", ":", "# Create a file for each shard.", "filepaths", "=", "[", "shard_filename", "(", "data_dir", ",", "tag", ",", "n", "+", "1", ",", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
shard_filename
Create filename for data shard.
translation/tensorflow/transformer/data_download.py
def shard_filename(path, tag, shard_num, total_shards): """Create filename for data shard.""" return os.path.join( path, "%s-%s-%s-%.5d-of-%.5d" % (_PREFIX, _ENCODE_TAG, tag, shard_num, total_shards))
def shard_filename(path, tag, shard_num, total_shards): """Create filename for data shard.""" return os.path.join( path, "%s-%s-%s-%.5d-of-%.5d" % (_PREFIX, _ENCODE_TAG, tag, shard_num, total_shards))
[ "Create", "filename", "for", "data", "shard", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/data_download.py#L308-L311
[ "def", "shard_filename", "(", "path", ",", "tag", ",", "shard_num", ",", "total_shards", ")", ":", "return", "os", ".", "path", ".", "join", "(", "path", ",", "\"%s-%s-%s-%.5d-of-%.5d\"", "%", "(", "_PREFIX", ",", "_ENCODE_TAG", ",", "tag", ",", "shard_num...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
shuffle_records
Shuffle records in a single file.
translation/tensorflow/transformer/data_download.py
def shuffle_records(fname): """Shuffle records in a single file.""" tf.logging.info("Shuffling records in file %s" % fname) # Rename file prior to shuffling tmp_fname = fname + ".unshuffled" tf.gfile.Rename(fname, tmp_fname) reader = tf.python_io.tf_record_iterator(tmp_fname) records = [] for record i...
def shuffle_records(fname): """Shuffle records in a single file.""" tf.logging.info("Shuffling records in file %s" % fname) # Rename file prior to shuffling tmp_fname = fname + ".unshuffled" tf.gfile.Rename(fname, tmp_fname) reader = tf.python_io.tf_record_iterator(tmp_fname) records = [] for record i...
[ "Shuffle", "records", "in", "a", "single", "file", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/data_download.py#L314-L338
[ "def", "shuffle_records", "(", "fname", ")", ":", "tf", ".", "logging", ".", "info", "(", "\"Shuffling records in file %s\"", "%", "fname", ")", "# Rename file prior to shuffling", "tmp_fname", "=", "fname", "+", "\".unshuffled\"", "tf", ".", "gfile", ".", "Rename...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
dict_to_example
Converts a dictionary of string->int to a tf.Example.
translation/tensorflow/transformer/data_download.py
def dict_to_example(dictionary): """Converts a dictionary of string->int to a tf.Example.""" features = {} for k, v in six.iteritems(dictionary): features[k] = tf.train.Feature(int64_list=tf.train.Int64List(value=v)) return tf.train.Example(features=tf.train.Features(feature=features))
def dict_to_example(dictionary): """Converts a dictionary of string->int to a tf.Example.""" features = {} for k, v in six.iteritems(dictionary): features[k] = tf.train.Feature(int64_list=tf.train.Int64List(value=v)) return tf.train.Example(features=tf.train.Features(feature=features))
[ "Converts", "a", "dictionary", "of", "string", "-", ">", "int", "to", "a", "tf", ".", "Example", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/data_download.py#L341-L346
[ "def", "dict_to_example", "(", "dictionary", ")", ":", "features", "=", "{", "}", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "dictionary", ")", ":", "features", "[", "k", "]", "=", "tf", ".", "train", ".", "Feature", "(", "int64_list",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
all_exist
Returns true if all files in the list exist.
translation/tensorflow/transformer/data_download.py
def all_exist(filepaths): """Returns true if all files in the list exist.""" for fname in filepaths: if not tf.gfile.Exists(fname): return False return True
def all_exist(filepaths): """Returns true if all files in the list exist.""" for fname in filepaths: if not tf.gfile.Exists(fname): return False return True
[ "Returns", "true", "if", "all", "files", "in", "the", "list", "exist", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/data_download.py#L349-L354
[ "def", "all_exist", "(", "filepaths", ")", ":", "for", "fname", "in", "filepaths", ":", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "fname", ")", ":", "return", "False", "return", "True" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
main
Obtain training and evaluation data for the Transformer model.
translation/tensorflow/transformer/data_download.py
def main(unused_argv): """Obtain training and evaluation data for the Transformer model.""" tf.logging.set_verbosity(tf.logging.INFO) make_dir(FLAGS.raw_dir) make_dir(FLAGS.data_dir) # Get paths of download/extracted training and evaluation files. tf.logging.info("Step 1/4: Downloading data from source") ...
def main(unused_argv): """Obtain training and evaluation data for the Transformer model.""" tf.logging.set_verbosity(tf.logging.INFO) make_dir(FLAGS.raw_dir) make_dir(FLAGS.data_dir) # Get paths of download/extracted training and evaluation files. tf.logging.info("Step 1/4: Downloading data from source") ...
[ "Obtain", "training", "and", "evaluation", "data", "for", "the", "Transformer", "model", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/data_download.py#L363-L397
[ "def", "main", "(", "unused_argv", ")", ":", "tf", ".", "logging", ".", "set_verbosity", "(", "tf", ".", "logging", ".", "INFO", ")", "make_dir", "(", "FLAGS", ".", "raw_dir", ")", "make_dir", "(", "FLAGS", ".", "data_dir", ")", "# Get paths of download/ex...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Transformer.encode
Generate continuous representation for inputs. Args: inputs: int tensor with shape [batch_size, input_length]. attention_bias: float tensor with shape [batch_size, 1, 1, input_length] Returns: float tensor with shape [batch_size, input_length, hidden_size]
translation/tensorflow/transformer/model/transformer.py
def encode(self, inputs, attention_bias): """Generate continuous representation for inputs. Args: inputs: int tensor with shape [batch_size, input_length]. attention_bias: float tensor with shape [batch_size, 1, 1, input_length] Returns: float tensor with shape [batch_size, input_length,...
def encode(self, inputs, attention_bias): """Generate continuous representation for inputs. Args: inputs: int tensor with shape [batch_size, input_length]. attention_bias: float tensor with shape [batch_size, 1, 1, input_length] Returns: float tensor with shape [batch_size, input_length,...
[ "Generate", "continuous", "representation", "for", "inputs", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/transformer.py#L106-L135
[ "def", "encode", "(", "self", ",", "inputs", ",", "attention_bias", ")", ":", "with", "tf", ".", "name_scope", "(", "\"encode\"", ")", ":", "# Prepare inputs to the layer stack by adding positional encodings and", "# applying dropout.", "embedded_inputs", "=", "self", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Transformer.decode
Generate logits for each value in the target sequence. Args: targets: target values for the output sequence. int tensor with shape [batch_size, target_length] encoder_outputs: continuous representation of input sequence. float tensor with shape [batch_size, input_length, hidden_size] ...
translation/tensorflow/transformer/model/transformer.py
def decode(self, targets, encoder_outputs, attention_bias): """Generate logits for each value in the target sequence. Args: targets: target values for the output sequence. int tensor with shape [batch_size, target_length] encoder_outputs: continuous representation of input sequence. ...
def decode(self, targets, encoder_outputs, attention_bias): """Generate logits for each value in the target sequence. Args: targets: target values for the output sequence. int tensor with shape [batch_size, target_length] encoder_outputs: continuous representation of input sequence. ...
[ "Generate", "logits", "for", "each", "value", "in", "the", "target", "sequence", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/transformer.py#L137-L176
[ "def", "decode", "(", "self", ",", "targets", ",", "encoder_outputs", ",", "attention_bias", ")", ":", "with", "tf", ".", "name_scope", "(", "\"decode\"", ")", ":", "# Prepare inputs to decoder layers by shifting targets, adding positional", "# encoding and applying dropout...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Transformer._get_symbols_to_logits_fn
Returns a decoding function that calculates logits of the next tokens.
translation/tensorflow/transformer/model/transformer.py
def _get_symbols_to_logits_fn(self, max_decode_length): """Returns a decoding function that calculates logits of the next tokens.""" timing_signal = model_utils.get_position_encoding( max_decode_length + 1, self.params.hidden_size) decoder_self_attention_bias = model_utils.get_decoder_self_attentio...
def _get_symbols_to_logits_fn(self, max_decode_length): """Returns a decoding function that calculates logits of the next tokens.""" timing_signal = model_utils.get_position_encoding( max_decode_length + 1, self.params.hidden_size) decoder_self_attention_bias = model_utils.get_decoder_self_attentio...
[ "Returns", "a", "decoding", "function", "that", "calculates", "logits", "of", "the", "next", "tokens", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/transformer.py#L178-L215
[ "def", "_get_symbols_to_logits_fn", "(", "self", ",", "max_decode_length", ")", ":", "timing_signal", "=", "model_utils", ".", "get_position_encoding", "(", "max_decode_length", "+", "1", ",", "self", ".", "params", ".", "hidden_size", ")", "decoder_self_attention_bia...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Transformer.predict
Return predicted sequence.
translation/tensorflow/transformer/model/transformer.py
def predict(self, encoder_outputs, encoder_decoder_attention_bias): """Return predicted sequence.""" batch_size = tf.shape(encoder_outputs)[0] input_length = tf.shape(encoder_outputs)[1] max_decode_length = input_length + self.params.extra_decode_length symbols_to_logits_fn = self._get_symbols_to_l...
def predict(self, encoder_outputs, encoder_decoder_attention_bias): """Return predicted sequence.""" batch_size = tf.shape(encoder_outputs)[0] input_length = tf.shape(encoder_outputs)[1] max_decode_length = input_length + self.params.extra_decode_length symbols_to_logits_fn = self._get_symbols_to_l...
[ "Return", "predicted", "sequence", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/transformer.py#L217-L261
[ "def", "predict", "(", "self", ",", "encoder_outputs", ",", "encoder_decoder_attention_bias", ")", ":", "batch_size", "=", "tf", ".", "shape", "(", "encoder_outputs", ")", "[", "0", "]", "input_length", "=", "tf", ".", "shape", "(", "encoder_outputs", ")", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_create_row_col_indices
Maps user and items ids to their locations in the rating matrix.
data_generation/fractal_graph_expansions/run_expansion.py
def _create_row_col_indices(ratings_df): """Maps user and items ids to their locations in the rating matrix.""" user_id_to_user_idx = _create_index(ratings_df, "userId") item_id_to_item_idx = _create_index(ratings_df, "movieId") ratings_df["row"] = ratings_df["userId"].apply( lambda x: user_id_to_user_id...
def _create_row_col_indices(ratings_df): """Maps user and items ids to their locations in the rating matrix.""" user_id_to_user_idx = _create_index(ratings_df, "userId") item_id_to_item_idx = _create_index(ratings_df, "movieId") ratings_df["row"] = ratings_df["userId"].apply( lambda x: user_id_to_user_id...
[ "Maps", "user", "and", "items", "ids", "to", "their", "locations", "in", "the", "rating", "matrix", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/data_generation/fractal_graph_expansions/run_expansion.py#L72-L82
[ "def", "_create_row_col_indices", "(", "ratings_df", ")", ":", "user_id_to_user_idx", "=", "_create_index", "(", "ratings_df", ",", "\"userId\"", ")", "item_id_to_item_idx", "=", "_create_index", "(", "ratings_df", ",", "\"movieId\"", ")", "ratings_df", "[", "\"row\""...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_preprocess_movie_lens
Separate the rating datafram into train and test sets. Filters out users with less than two distinct timestamps. Creates train set and test set. The test set contains all the last interactions of users with more than two distinct timestamps. Args: ratings_df: pandas dataframe with columns 'userId', 'movie...
data_generation/fractal_graph_expansions/run_expansion.py
def _preprocess_movie_lens(ratings_df): """Separate the rating datafram into train and test sets. Filters out users with less than two distinct timestamps. Creates train set and test set. The test set contains all the last interactions of users with more than two distinct timestamps. Args: ratings_df: p...
def _preprocess_movie_lens(ratings_df): """Separate the rating datafram into train and test sets. Filters out users with less than two distinct timestamps. Creates train set and test set. The test set contains all the last interactions of users with more than two distinct timestamps. Args: ratings_df: p...
[ "Separate", "the", "rating", "datafram", "into", "train", "and", "test", "sets", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/data_generation/fractal_graph_expansions/run_expansion.py#L85-L119
[ "def", "_preprocess_movie_lens", "(", "ratings_df", ")", ":", "ratings_df", "[", "\"data\"", "]", "=", "1.0", "num_timestamps", "=", "ratings_df", "[", "[", "\"userId\"", ",", "\"timestamp\"", "]", "]", ".", "groupby", "(", "\"userId\"", ")", ".", "nunique", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCO.getAnnIds
Get ann ids that satisfy given filter conditions. default skips that filter :param imgIds (int array) : get anns for given imgs catIds (int array) : get anns for given cats areaRng (float array) : get anns for given area range (e.g. [0 inf]) iscrowd (bool...
single_stage_detector/ssd/coco.py
def getAnnIds(self, imgIds=[], catIds=[], areaRng=[], iscrowd=None): """ Get ann ids that satisfy given filter conditions. default skips that filter :param imgIds (int array) : get anns for given imgs catIds (int array) : get anns for given cats areaRng (f...
def getAnnIds(self, imgIds=[], catIds=[], areaRng=[], iscrowd=None): """ Get ann ids that satisfy given filter conditions. default skips that filter :param imgIds (int array) : get anns for given imgs catIds (int array) : get anns for given cats areaRng (f...
[ "Get", "ann", "ids", "that", "satisfy", "given", "filter", "conditions", ".", "default", "skips", "that", "filter", ":", "param", "imgIds", "(", "int", "array", ")", ":", "get", "anns", "for", "given", "imgs", "catIds", "(", "int", "array", ")", ":", "...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/single_stage_detector/ssd/coco.py#L129-L155
[ "def", "getAnnIds", "(", "self", ",", "imgIds", "=", "[", "]", ",", "catIds", "=", "[", "]", ",", "areaRng", "=", "[", "]", ",", "iscrowd", "=", "None", ")", ":", "imgIds", "=", "imgIds", "if", "_isArrayLike", "(", "imgIds", ")", "else", "[", "im...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCO.getCatIds
filtering parameters. default skips that filter. :param catNms (str array) : get cats for given cat names :param supNms (str array) : get cats for given supercategory names :param catIds (int array) : get cats for given cat ids :return: ids (int array) : integer array of cat ids
single_stage_detector/ssd/coco.py
def getCatIds(self, catNms=[], supNms=[], catIds=[]): """ filtering parameters. default skips that filter. :param catNms (str array) : get cats for given cat names :param supNms (str array) : get cats for given supercategory names :param catIds (int array) : get cats for given...
def getCatIds(self, catNms=[], supNms=[], catIds=[]): """ filtering parameters. default skips that filter. :param catNms (str array) : get cats for given cat names :param supNms (str array) : get cats for given supercategory names :param catIds (int array) : get cats for given...
[ "filtering", "parameters", ".", "default", "skips", "that", "filter", ".", ":", "param", "catNms", "(", "str", "array", ")", ":", "get", "cats", "for", "given", "cat", "names", ":", "param", "supNms", "(", "str", "array", ")", ":", "get", "cats", "for"...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/single_stage_detector/ssd/coco.py#L157-L177
[ "def", "getCatIds", "(", "self", ",", "catNms", "=", "[", "]", ",", "supNms", "=", "[", "]", ",", "catIds", "=", "[", "]", ")", ":", "catNms", "=", "catNms", "if", "_isArrayLike", "(", "catNms", ")", "else", "[", "catNms", "]", "supNms", "=", "su...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCO.getImgIds
Get img ids that satisfy given filter conditions. :param imgIds (int array) : get imgs for given ids :param catIds (int array) : get imgs with all given cats :return: ids (int array) : integer array of img ids
single_stage_detector/ssd/coco.py
def getImgIds(self, imgIds=[], catIds=[]): ''' Get img ids that satisfy given filter conditions. :param imgIds (int array) : get imgs for given ids :param catIds (int array) : get imgs with all given cats :return: ids (int array) : integer array of img ids ''' im...
def getImgIds(self, imgIds=[], catIds=[]): ''' Get img ids that satisfy given filter conditions. :param imgIds (int array) : get imgs for given ids :param catIds (int array) : get imgs with all given cats :return: ids (int array) : integer array of img ids ''' im...
[ "Get", "img", "ids", "that", "satisfy", "given", "filter", "conditions", ".", ":", "param", "imgIds", "(", "int", "array", ")", ":", "get", "imgs", "for", "given", "ids", ":", "param", "catIds", "(", "int", "array", ")", ":", "get", "imgs", "with", "...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/single_stage_detector/ssd/coco.py#L179-L198
[ "def", "getImgIds", "(", "self", ",", "imgIds", "=", "[", "]", ",", "catIds", "=", "[", "]", ")", ":", "imgIds", "=", "imgIds", "if", "_isArrayLike", "(", "imgIds", ")", "else", "[", "imgIds", "]", "catIds", "=", "catIds", "if", "_isArrayLike", "(", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCO.loadAnns
Load anns with the specified ids. :param ids (int array) : integer ids specifying anns :return: anns (object array) : loaded ann objects
single_stage_detector/ssd/coco.py
def loadAnns(self, ids=[]): """ Load anns with the specified ids. :param ids (int array) : integer ids specifying anns :return: anns (object array) : loaded ann objects """ if _isArrayLike(ids): return [self.anns[id] for id in ids] elif type(ids)...
def loadAnns(self, ids=[]): """ Load anns with the specified ids. :param ids (int array) : integer ids specifying anns :return: anns (object array) : loaded ann objects """ if _isArrayLike(ids): return [self.anns[id] for id in ids] elif type(ids)...
[ "Load", "anns", "with", "the", "specified", "ids", ".", ":", "param", "ids", "(", "int", "array", ")", ":", "integer", "ids", "specifying", "anns", ":", "return", ":", "anns", "(", "object", "array", ")", ":", "loaded", "ann", "objects" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/single_stage_detector/ssd/coco.py#L200-L209
[ "def", "loadAnns", "(", "self", ",", "ids", "=", "[", "]", ")", ":", "if", "_isArrayLike", "(", "ids", ")", ":", "return", "[", "self", ".", "anns", "[", "id", "]", "for", "id", "in", "ids", "]", "elif", "type", "(", "ids", ")", "==", "int", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCO.loadCats
Load cats with the specified ids. :param ids (int array) : integer ids specifying cats :return: cats (object array) : loaded cat objects
single_stage_detector/ssd/coco.py
def loadCats(self, ids=[]): """ Load cats with the specified ids. :param ids (int array) : integer ids specifying cats :return: cats (object array) : loaded cat objects """ if _isArrayLike(ids): return [self.cats[id] for id in ids] elif type(ids)...
def loadCats(self, ids=[]): """ Load cats with the specified ids. :param ids (int array) : integer ids specifying cats :return: cats (object array) : loaded cat objects """ if _isArrayLike(ids): return [self.cats[id] for id in ids] elif type(ids)...
[ "Load", "cats", "with", "the", "specified", "ids", ".", ":", "param", "ids", "(", "int", "array", ")", ":", "integer", "ids", "specifying", "cats", ":", "return", ":", "cats", "(", "object", "array", ")", ":", "loaded", "cat", "objects" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/single_stage_detector/ssd/coco.py#L211-L220
[ "def", "loadCats", "(", "self", ",", "ids", "=", "[", "]", ")", ":", "if", "_isArrayLike", "(", "ids", ")", ":", "return", "[", "self", ".", "cats", "[", "id", "]", "for", "id", "in", "ids", "]", "elif", "type", "(", "ids", ")", "==", "int", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCO.loadImgs
Load anns with the specified ids. :param ids (int array) : integer ids specifying img :return: imgs (object array) : loaded img objects
single_stage_detector/ssd/coco.py
def loadImgs(self, ids=[]): """ Load anns with the specified ids. :param ids (int array) : integer ids specifying img :return: imgs (object array) : loaded img objects """ if _isArrayLike(ids): return [self.imgs[id] for id in ids] elif type(ids) ...
def loadImgs(self, ids=[]): """ Load anns with the specified ids. :param ids (int array) : integer ids specifying img :return: imgs (object array) : loaded img objects """ if _isArrayLike(ids): return [self.imgs[id] for id in ids] elif type(ids) ...
[ "Load", "anns", "with", "the", "specified", "ids", ".", ":", "param", "ids", "(", "int", "array", ")", ":", "integer", "ids", "specifying", "img", ":", "return", ":", "imgs", "(", "object", "array", ")", ":", "loaded", "img", "objects" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/single_stage_detector/ssd/coco.py#L222-L231
[ "def", "loadImgs", "(", "self", ",", "ids", "=", "[", "]", ")", ":", "if", "_isArrayLike", "(", "ids", ")", ":", "return", "[", "self", ".", "imgs", "[", "id", "]", "for", "id", "in", "ids", "]", "elif", "type", "(", "ids", ")", "==", "int", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCO.showAnns
Display the specified annotations. :param anns (array of object): annotations to display :return: None
single_stage_detector/ssd/coco.py
def showAnns(self, anns): """ Display the specified annotations. :param anns (array of object): annotations to display :return: None """ if len(anns) == 0: return 0 if 'segmentation' in anns[0] or 'keypoints' in anns[0]: datasetType = 'inst...
def showAnns(self, anns): """ Display the specified annotations. :param anns (array of object): annotations to display :return: None """ if len(anns) == 0: return 0 if 'segmentation' in anns[0] or 'keypoints' in anns[0]: datasetType = 'inst...
[ "Display", "the", "specified", "annotations", ".", ":", "param", "anns", "(", "array", "of", "object", ")", ":", "annotations", "to", "display", ":", "return", ":", "None" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/single_stage_detector/ssd/coco.py#L233-L295
[ "def", "showAnns", "(", "self", ",", "anns", ")", ":", "if", "len", "(", "anns", ")", "==", "0", ":", "return", "0", "if", "'segmentation'", "in", "anns", "[", "0", "]", "or", "'keypoints'", "in", "anns", "[", "0", "]", ":", "datasetType", "=", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCO.loadRes
Load result file and return a result api object. :param resFile (str) : file name of result file :return: res (obj) : result api object
single_stage_detector/ssd/coco.py
def loadRes(self, resFile): """ Load result file and return a result api object. :param resFile (str) : file name of result file :return: res (obj) : result api object """ res = COCO() res.dataset['images'] = [img for img in self.dataset['images']] ...
def loadRes(self, resFile): """ Load result file and return a result api object. :param resFile (str) : file name of result file :return: res (obj) : result api object """ res = COCO() res.dataset['images'] = [img for img in self.dataset['images']] ...
[ "Load", "result", "file", "and", "return", "a", "result", "api", "object", ".", ":", "param", "resFile", "(", "str", ")", ":", "file", "name", "of", "result", "file", ":", "return", ":", "res", "(", "obj", ")", ":", "result", "api", "object" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/single_stage_detector/ssd/coco.py#L297-L356
[ "def", "loadRes", "(", "self", ",", "resFile", ")", ":", "res", "=", "COCO", "(", ")", "res", ".", "dataset", "[", "'images'", "]", "=", "[", "img", "for", "img", "in", "self", ".", "dataset", "[", "'images'", "]", "]", "print", "(", "'Loading and ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCO.annToRLE
Convert annotation which can be polygons, uncompressed RLE to RLE. :return: binary mask (numpy 2D array)
single_stage_detector/ssd/coco.py
def annToRLE(self, ann): """ Convert annotation which can be polygons, uncompressed RLE to RLE. :return: binary mask (numpy 2D array) """ t = self.imgs[ann['image_id']] h, w = t['height'], t['width'] segm = ann['segmentation'] if type(segm) == list: ...
def annToRLE(self, ann): """ Convert annotation which can be polygons, uncompressed RLE to RLE. :return: binary mask (numpy 2D array) """ t = self.imgs[ann['image_id']] h, w = t['height'], t['width'] segm = ann['segmentation'] if type(segm) == list: ...
[ "Convert", "annotation", "which", "can", "be", "polygons", "uncompressed", "RLE", "to", "RLE", ".", ":", "return", ":", "binary", "mask", "(", "numpy", "2D", "array", ")" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/single_stage_detector/ssd/coco.py#L405-L424
[ "def", "annToRLE", "(", "self", ",", "ann", ")", ":", "t", "=", "self", ".", "imgs", "[", "ann", "[", "'image_id'", "]", "]", "h", ",", "w", "=", "t", "[", "'height'", "]", ",", "t", "[", "'width'", "]", "segm", "=", "ann", "[", "'segmentation'...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
COCO.annToMask
Convert annotation which can be polygons, uncompressed RLE, or RLE to binary mask. :return: binary mask (numpy 2D array)
single_stage_detector/ssd/coco.py
def annToMask(self, ann): """ Convert annotation which can be polygons, uncompressed RLE, or RLE to binary mask. :return: binary mask (numpy 2D array) """ rle = self.annToRLE(ann) m = maskUtils.decode(rle) return m
def annToMask(self, ann): """ Convert annotation which can be polygons, uncompressed RLE, or RLE to binary mask. :return: binary mask (numpy 2D array) """ rle = self.annToRLE(ann) m = maskUtils.decode(rle) return m
[ "Convert", "annotation", "which", "can", "be", "polygons", "uncompressed", "RLE", "or", "RLE", "to", "binary", "mask", ".", ":", "return", ":", "binary", "mask", "(", "numpy", "2D", "array", ")" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/single_stage_detector/ssd/coco.py#L426-L433
[ "def", "annToMask", "(", "self", ",", "ann", ")", ":", "rle", "=", "self", ".", "annToRLE", "(", "ann", ")", "m", "=", "maskUtils", ".", "decode", "(", "rle", ")", "return", "m" ]
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
GeneralizedRCNN.forward
Arguments: images (list[Tensor] or ImageList): images to be processed targets (list[BoxList]): ground-truth boxes present in the image (optional) Returns: result (list[BoxList] or dict[Tensor]): the output from the model. During training, it returns a dict[Te...
object_detection/pytorch/maskrcnn_benchmark/modeling/detector/generalized_rcnn.py
def forward(self, images, targets=None): """ Arguments: images (list[Tensor] or ImageList): images to be processed targets (list[BoxList]): ground-truth boxes present in the image (optional) Returns: result (list[BoxList] or dict[Tensor]): the output from the...
def forward(self, images, targets=None): """ Arguments: images (list[Tensor] or ImageList): images to be processed targets (list[BoxList]): ground-truth boxes present in the image (optional) Returns: result (list[BoxList] or dict[Tensor]): the output from the...
[ "Arguments", ":", "images", "(", "list", "[", "Tensor", "]", "or", "ImageList", ")", ":", "images", "to", "be", "processed", "targets", "(", "list", "[", "BoxList", "]", ")", ":", "ground", "-", "truth", "boxes", "present", "in", "the", "image", "(", ...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/detector/generalized_rcnn.py#L33-L65
[ "def", "forward", "(", "self", ",", "images", ",", "targets", "=", "None", ")", ":", "if", "self", ".", "training", "and", "targets", "is", "None", ":", "raise", "ValueError", "(", "\"In training mode, targets should be passed\"", ")", "images", "=", "to_image...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
sparse_svd
Wrapper around SciPy's Singular Value Decomposition for sparse matrices. Args: sparse_matrix: a SciPy sparse matrix (typically large). num_values: the number of largest singular values to compute. max_iter: maximum number of iterations (>= 0) in the decomposition. If max_iter is None, runs FLAGS.ma...
data_generation/fractal_graph_expansions/graph_analysis.py
def sparse_svd(sparse_matrix, num_values, max_iter): """Wrapper around SciPy's Singular Value Decomposition for sparse matrices. Args: sparse_matrix: a SciPy sparse matrix (typically large). num_values: the number of largest singular values to compute. max_iter: maximum number of iterations (>= 0) in t...
def sparse_svd(sparse_matrix, num_values, max_iter): """Wrapper around SciPy's Singular Value Decomposition for sparse matrices. Args: sparse_matrix: a SciPy sparse matrix (typically large). num_values: the number of largest singular values to compute. max_iter: maximum number of iterations (>= 0) in t...
[ "Wrapper", "around", "SciPy", "s", "Singular", "Value", "Decomposition", "for", "sparse", "matrices", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/data_generation/fractal_graph_expansions/graph_analysis.py#L33-L64
[ "def", "sparse_svd", "(", "sparse_matrix", ",", "num_values", ",", "max_iter", ")", ":", "if", "num_values", "<=", "0", ":", "raise", "ValueError", "(", "\"num_values should be > 0 but instead is %d.\"", "%", "num_values", ")", "if", "max_iter", "is", "not", "None...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
EmbeddingSharedWeights.call
Get token embeddings of x. Args: x: An int64 tensor with shape [batch_size, length] Returns: embeddings: float32 tensor with shape [batch_size, length, embedding_size] padding: float32 tensor with shape [batch_size, length] indicating the locations of the padding tokens in x.
translation/tensorflow/transformer/model/embedding_layer.py
def call(self, x): """Get token embeddings of x. Args: x: An int64 tensor with shape [batch_size, length] Returns: embeddings: float32 tensor with shape [batch_size, length, embedding_size] padding: float32 tensor with shape [batch_size, length] indicating the locations of the pad...
def call(self, x): """Get token embeddings of x. Args: x: An int64 tensor with shape [batch_size, length] Returns: embeddings: float32 tensor with shape [batch_size, length, embedding_size] padding: float32 tensor with shape [batch_size, length] indicating the locations of the pad...
[ "Get", "token", "embeddings", "of", "x", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/embedding_layer.py#L53-L75
[ "def", "call", "(", "self", ",", "x", ")", ":", "with", "tf", ".", "name_scope", "(", "\"embedding\"", ")", ":", "embeddings", "=", "tf", ".", "gather", "(", "self", ".", "shared_weights", ",", "x", ")", "# Scale embedding by the sqrt of the hidden size", "e...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
EmbeddingSharedWeights.linear
Computes logits by running x through a linear layer. Args: x: A float32 tensor with shape [batch_size, length, hidden_size] Returns: float32 tensor with shape [batch_size, length, vocab_size].
translation/tensorflow/transformer/model/embedding_layer.py
def linear(self, x): """Computes logits by running x through a linear layer. Args: x: A float32 tensor with shape [batch_size, length, hidden_size] Returns: float32 tensor with shape [batch_size, length, vocab_size]. """ with tf.name_scope("presoftmax_linear"): batch_size = tf.sha...
def linear(self, x): """Computes logits by running x through a linear layer. Args: x: A float32 tensor with shape [batch_size, length, hidden_size] Returns: float32 tensor with shape [batch_size, length, vocab_size]. """ with tf.name_scope("presoftmax_linear"): batch_size = tf.sha...
[ "Computes", "logits", "by", "running", "x", "through", "a", "linear", "layer", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/embedding_layer.py#L77-L92
[ "def", "linear", "(", "self", ",", "x", ")", ":", "with", "tf", ".", "name_scope", "(", "\"presoftmax_linear\"", ")", ":", "batch_size", "=", "tf", ".", "shape", "(", "x", ")", "[", "0", "]", "length", "=", "tf", ".", "shape", "(", "x", ")", "[",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Seq2SeqTrainer.iterate
Performs one iteration of the training/validation. :param src: batch of examples from the source language :param tgt: batch of examples from the target language :param update: if True: optimizer does update of the weights :param training: if True: executes optimizer
rnn_translator/pytorch/seq2seq/train/trainer.py
def iterate(self, src, tgt, update=True, training=True): """ Performs one iteration of the training/validation. :param src: batch of examples from the source language :param tgt: batch of examples from the target language :param update: if True: optimizer does update of the weig...
def iterate(self, src, tgt, update=True, training=True): """ Performs one iteration of the training/validation. :param src: batch of examples from the source language :param tgt: batch of examples from the target language :param update: if True: optimizer does update of the weig...
[ "Performs", "one", "iteration", "of", "the", "training", "/", "validation", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/train/trainer.py#L128-L173
[ "def", "iterate", "(", "self", ",", "src", ",", "tgt", ",", "update", "=", "True", ",", "training", "=", "True", ")", ":", "src", ",", "src_length", "=", "src", "tgt", ",", "tgt_length", "=", "tgt", "src_length", "=", "torch", ".", "LongTensor", "(",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Seq2SeqTrainer.feed_data
Runs training or validation on batches from data_loader. :param data_loader: data loader :param training: if True runs training else runs validation
rnn_translator/pytorch/seq2seq/train/trainer.py
def feed_data(self, data_loader, training=True): """ Runs training or validation on batches from data_loader. :param data_loader: data loader :param training: if True runs training else runs validation """ if training: assert self.optimizer is not None ...
def feed_data(self, data_loader, training=True): """ Runs training or validation on batches from data_loader. :param data_loader: data loader :param training: if True runs training else runs validation """ if training: assert self.optimizer is not None ...
[ "Runs", "training", "or", "validation", "on", "batches", "from", "data_loader", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/train/trainer.py#L175-L275
[ "def", "feed_data", "(", "self", ",", "data_loader", ",", "training", "=", "True", ")", ":", "if", "training", ":", "assert", "self", ".", "optimizer", "is", "not", "None", "eval_fractions", "=", "np", ".", "linspace", "(", "0", ",", "1", ",", "self", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Seq2SeqTrainer.preallocate
Generates maximum sequence length batch and runs forward and backward pass without updating model parameters. :param data_loader: data loader :param training: if True preallocates memory for backward pass
rnn_translator/pytorch/seq2seq/train/trainer.py
def preallocate(self, data_loader, training): """ Generates maximum sequence length batch and runs forward and backward pass without updating model parameters. :param data_loader: data loader :param training: if True preallocates memory for backward pass """ batc...
def preallocate(self, data_loader, training): """ Generates maximum sequence length batch and runs forward and backward pass without updating model parameters. :param data_loader: data loader :param training: if True preallocates memory for backward pass """ batc...
[ "Generates", "maximum", "sequence", "length", "batch", "and", "runs", "forward", "and", "backward", "pass", "without", "updating", "model", "parameters", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/train/trainer.py#L277-L301
[ "def", "preallocate", "(", "self", ",", "data_loader", ",", "training", ")", ":", "batch_size", "=", "data_loader", ".", "batch_size", "max_len", "=", "data_loader", ".", "dataset", ".", "max_len", "src_length", "=", "[", "max_len", "]", "*", "batch_size", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Seq2SeqTrainer.optimize
Sets model in training mode, preallocates memory and runs training on data provided by data_loader. :param data_loader: data loader
rnn_translator/pytorch/seq2seq/train/trainer.py
def optimize(self, data_loader): """ Sets model in training mode, preallocates memory and runs training on data provided by data_loader. :param data_loader: data loader """ torch.set_grad_enabled(True) self.model.train() torch.cuda.empty_cache() s...
def optimize(self, data_loader): """ Sets model in training mode, preallocates memory and runs training on data provided by data_loader. :param data_loader: data loader """ torch.set_grad_enabled(True) self.model.train() torch.cuda.empty_cache() s...
[ "Sets", "model", "in", "training", "mode", "preallocates", "memory", "and", "runs", "training", "on", "data", "provided", "by", "data_loader", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/train/trainer.py#L303-L317
[ "def", "optimize", "(", "self", ",", "data_loader", ")", ":", "torch", ".", "set_grad_enabled", "(", "True", ")", "self", ".", "model", ".", "train", "(", ")", "torch", ".", "cuda", ".", "empty_cache", "(", ")", "self", ".", "preallocate", "(", "data_l...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Seq2SeqTrainer.evaluate
Sets model in eval mode, disables gradients, preallocates memory and runs validation on data provided by data_loader. :param data_loader: data loader
rnn_translator/pytorch/seq2seq/train/trainer.py
def evaluate(self, data_loader): """ Sets model in eval mode, disables gradients, preallocates memory and runs validation on data provided by data_loader. :param data_loader: data loader """ torch.set_grad_enabled(False) self.model.eval() torch.cuda.empty...
def evaluate(self, data_loader): """ Sets model in eval mode, disables gradients, preallocates memory and runs validation on data provided by data_loader. :param data_loader: data loader """ torch.set_grad_enabled(False) self.model.eval() torch.cuda.empty...
[ "Sets", "model", "in", "eval", "mode", "disables", "gradients", "preallocates", "memory", "and", "runs", "validation", "on", "data", "provided", "by", "data_loader", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/train/trainer.py#L319-L333
[ "def", "evaluate", "(", "self", ",", "data_loader", ")", ":", "torch", ".", "set_grad_enabled", "(", "False", ")", "self", ".", "model", ".", "eval", "(", ")", "torch", ".", "cuda", ".", "empty_cache", "(", ")", "self", ".", "preallocate", "(", "data_l...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Seq2SeqTrainer.load
Loads checkpoint from filename. :param filename: path to the checkpoint file
rnn_translator/pytorch/seq2seq/train/trainer.py
def load(self, filename): """ Loads checkpoint from filename. :param filename: path to the checkpoint file """ if os.path.isfile(filename): checkpoint = torch.load(filename, map_location={'cuda:0': 'cpu'}) if self.distributed: self.model.m...
def load(self, filename): """ Loads checkpoint from filename. :param filename: path to the checkpoint file """ if os.path.isfile(filename): checkpoint = torch.load(filename, map_location={'cuda:0': 'cpu'}) if self.distributed: self.model.m...
[ "Loads", "checkpoint", "from", "filename", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/train/trainer.py#L335-L354
[ "def", "load", "(", "self", ",", "filename", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "checkpoint", "=", "torch", ".", "load", "(", "filename", ",", "map_location", "=", "{", "'cuda:0'", ":", "'cpu'", "}", ")", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Seq2SeqTrainer.save
Stores checkpoint to a file. :param identifier: identifier for periodic checkpoint :param is_best: if True stores checkpoint to 'model_best.pth' :param save_all: if True stores checkpoint after completed training epoch
rnn_translator/pytorch/seq2seq/train/trainer.py
def save(self, identifier=None, is_best=False, save_all=False): """ Stores checkpoint to a file. :param identifier: identifier for periodic checkpoint :param is_best: if True stores checkpoint to 'model_best.pth' :param save_all: if True stores checkpoint after completed trainin...
def save(self, identifier=None, is_best=False, save_all=False): """ Stores checkpoint to a file. :param identifier: identifier for periodic checkpoint :param is_best: if True stores checkpoint to 'model_best.pth' :param save_all: if True stores checkpoint after completed trainin...
[ "Stores", "checkpoint", "to", "a", "file", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/train/trainer.py#L356-L395
[ "def", "save", "(", "self", ",", "identifier", "=", "None", ",", "is_best", "=", "False", ",", "save_all", "=", "False", ")", ":", "def", "write_checkpoint", "(", "state", ",", "filename", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
keep_only_positive_boxes
Given a set of BoxList containing the `labels` field, return a set of BoxList for which `labels > 0`. Arguments: boxes (list of BoxList)
object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/mask_head/mask_head.py
def keep_only_positive_boxes(boxes): """ Given a set of BoxList containing the `labels` field, return a set of BoxList for which `labels > 0`. Arguments: boxes (list of BoxList) """ assert isinstance(boxes, (list, tuple)) assert isinstance(boxes[0], BoxList) assert boxes[0].has_...
def keep_only_positive_boxes(boxes): """ Given a set of BoxList containing the `labels` field, return a set of BoxList for which `labels > 0`. Arguments: boxes (list of BoxList) """ assert isinstance(boxes, (list, tuple)) assert isinstance(boxes[0], BoxList) assert boxes[0].has_...
[ "Given", "a", "set", "of", "BoxList", "containing", "the", "labels", "field", "return", "a", "set", "of", "BoxList", "for", "which", "labels", ">", "0", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/mask_head/mask_head.py#L13-L33
[ "def", "keep_only_positive_boxes", "(", "boxes", ")", ":", "assert", "isinstance", "(", "boxes", ",", "(", "list", ",", "tuple", ")", ")", "assert", "isinstance", "(", "boxes", "[", "0", "]", ",", "BoxList", ")", "assert", "boxes", "[", "0", "]", ".", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
ROIMaskHead.forward
Arguments: features (list[Tensor]): feature-maps from possibly several levels proposals (list[BoxList]): proposal boxes targets (list[BoxList], optional): the ground-truth targets. Returns: x (Tensor): the result of the feature extractor proposals (li...
object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/mask_head/mask_head.py
def forward(self, features, proposals, targets=None): """ Arguments: features (list[Tensor]): feature-maps from possibly several levels proposals (list[BoxList]): proposal boxes targets (list[BoxList], optional): the ground-truth targets. Returns: ...
def forward(self, features, proposals, targets=None): """ Arguments: features (list[Tensor]): feature-maps from possibly several levels proposals (list[BoxList]): proposal boxes targets (list[BoxList], optional): the ground-truth targets. Returns: ...
[ "Arguments", ":", "features", "(", "list", "[", "Tensor", "]", ")", ":", "feature", "-", "maps", "from", "possibly", "several", "levels", "proposals", "(", "list", "[", "BoxList", "]", ")", ":", "proposal", "boxes", "targets", "(", "list", "[", "BoxList"...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/mask_head/mask_head.py#L45-L78
[ "def", "forward", "(", "self", ",", "features", ",", "proposals", ",", "targets", "=", "None", ")", ":", "if", "self", ".", "training", ":", "# during training, only focus on positive boxes", "all_proposals", "=", "proposals", "proposals", ",", "positive_inds", "=...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_95_percentile_bleak
Gets the 95th percentile of bleakest_eval from bigtable
reinforcement/tensorflow/minigo/rl_loop/update_resign_threshold.py
def get_95_percentile_bleak(games_nr, n_back=500): """Gets the 95th percentile of bleakest_eval from bigtable""" end_game = int(games_nr.latest_game_number) start_game = end_game - n_back if end_game >= n_back else 0 moves = games_nr.bleakest_moves(start_game, end_game) evals = np.array([m[2] for m ...
def get_95_percentile_bleak(games_nr, n_back=500): """Gets the 95th percentile of bleakest_eval from bigtable""" end_game = int(games_nr.latest_game_number) start_game = end_game - n_back if end_game >= n_back else 0 moves = games_nr.bleakest_moves(start_game, end_game) evals = np.array([m[2] for m ...
[ "Gets", "the", "95th", "percentile", "of", "bleakest_eval", "from", "bigtable" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/rl_loop/update_resign_threshold.py#L48-L54
[ "def", "get_95_percentile_bleak", "(", "games_nr", ",", "n_back", "=", "500", ")", ":", "end_game", "=", "int", "(", "games_nr", ".", "latest_game_number", ")", "start_game", "=", "end_game", "-", "n_back", "if", "end_game", ">=", "n_back", "else", "0", "mov...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
update_flagfile
Updates the flagfile at `flags_path`, changing the value for `resign_threshold` to `new_threshold`
reinforcement/tensorflow/minigo/rl_loop/update_resign_threshold.py
def update_flagfile(flags_path, new_threshold): """Updates the flagfile at `flags_path`, changing the value for `resign_threshold` to `new_threshold` """ if abs(new_threshold) > 1: raise ValueError("Invalid new percentile for resign threshold") with tf.gfile.GFile(flags_path) as f: l...
def update_flagfile(flags_path, new_threshold): """Updates the flagfile at `flags_path`, changing the value for `resign_threshold` to `new_threshold` """ if abs(new_threshold) > 1: raise ValueError("Invalid new percentile for resign threshold") with tf.gfile.GFile(flags_path) as f: l...
[ "Updates", "the", "flagfile", "at", "flags_path", "changing", "the", "value", "for", "resign_threshold", "to", "new_threshold" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/rl_loop/update_resign_threshold.py#L56-L79
[ "def", "update_flagfile", "(", "flags_path", ",", "new_threshold", ")", ":", "if", "abs", "(", "new_threshold", ")", ">", "1", ":", "raise", "ValueError", "(", "\"Invalid new percentile for resign threshold\"", ")", "with", "tf", ".", "gfile", ".", "GFile", "(",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
MiniguiBasicCmdHandler._minigui_report_search_status
Prints the current MCTS search status to stderr. Reports the current search path, root node's child_Q, root node's child_N, the most visited path in a format that can be parsed by one of the STDERR_HANDLERS in minigui.ts. Args: leaves: list of leaf MCTSNodes returned by tree_...
reinforcement/tensorflow/minigo/gtp_cmd_handlers.py
def _minigui_report_search_status(self, leaves): """Prints the current MCTS search status to stderr. Reports the current search path, root node's child_Q, root node's child_N, the most visited path in a format that can be parsed by one of the STDERR_HANDLERS in minigui.ts. Args...
def _minigui_report_search_status(self, leaves): """Prints the current MCTS search status to stderr. Reports the current search path, root node's child_Q, root node's child_N, the most visited path in a format that can be parsed by one of the STDERR_HANDLERS in minigui.ts. Args...
[ "Prints", "the", "current", "MCTS", "search", "status", "to", "stderr", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/gtp_cmd_handlers.py#L315-L369
[ "def", "_minigui_report_search_status", "(", "self", ",", "leaves", ")", ":", "root", "=", "self", ".", "_player", ".", "get_root", "(", ")", "msg", "=", "{", "\"id\"", ":", "hex", "(", "id", "(", "root", ")", ")", ",", "\"n\"", ":", "int", "(", "r...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
parse_args
Parse commandline arguments.
rnn_translator/pytorch/train.py
def parse_args(): """ Parse commandline arguments. """ def exclusive_group(group, name, default, help): destname = name.replace('-', '_') subgroup = group.add_mutually_exclusive_group(required=False) subgroup.add_argument(f'--{name}', dest=f'{destname}', ...
def parse_args(): """ Parse commandline arguments. """ def exclusive_group(group, name, default, help): destname = name.replace('-', '_') subgroup = group.add_mutually_exclusive_group(required=False) subgroup.add_argument(f'--{name}', dest=f'{destname}', ...
[ "Parse", "commandline", "arguments", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/train.py#L27-L236
[ "def", "parse_args", "(", ")", ":", "def", "exclusive_group", "(", "group", ",", "name", ",", "default", ",", "help", ")", ":", "destname", "=", "name", ".", "replace", "(", "'-'", ",", "'_'", ")", "subgroup", "=", "group", ".", "add_mutually_exclusive_g...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
main
Launches data-parallel multi-gpu training.
rnn_translator/pytorch/train.py
def main(): """ Launches data-parallel multi-gpu training. """ mlperf_log.ROOT_DIR_GNMT = os.path.dirname(os.path.abspath(__file__)) mlperf_log.LOGGER.propagate = False args = parse_args() device = utils.set_device(args.cuda, args.local_rank) distributed = utils.init_distributed(args.cu...
def main(): """ Launches data-parallel multi-gpu training. """ mlperf_log.ROOT_DIR_GNMT = os.path.dirname(os.path.abspath(__file__)) mlperf_log.LOGGER.propagate = False args = parse_args() device = utils.set_device(args.cuda, args.local_rank) distributed = utils.init_distributed(args.cu...
[ "Launches", "data", "-", "parallel", "multi", "-", "gpu", "training", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/train.py#L258-L523
[ "def", "main", "(", ")", ":", "mlperf_log", ".", "ROOT_DIR_GNMT", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", "mlperf_log", ".", "LOGGER", ".", "propagate", "=", "False", "args", "=", "pa...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
validate_holdout_selfplay
Validate on held-out selfplay data.
reinforcement/tensorflow/minigo/rl_loop/train_and_validate.py
def validate_holdout_selfplay(): """Validate on held-out selfplay data.""" holdout_dirs = (os.path.join(fsdb.holdout_dir(), d) for d in reversed(gfile.ListDirectory(fsdb.holdout_dir())) if gfile.IsDirectory(os.path.join(fsdb.holdout_dir(), d)) for f in...
def validate_holdout_selfplay(): """Validate on held-out selfplay data.""" holdout_dirs = (os.path.join(fsdb.holdout_dir(), d) for d in reversed(gfile.ListDirectory(fsdb.holdout_dir())) if gfile.IsDirectory(os.path.join(fsdb.holdout_dir(), d)) for f in...
[ "Validate", "on", "held", "-", "out", "selfplay", "data", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/rl_loop/train_and_validate.py#L106-L121
[ "def", "validate_holdout_selfplay", "(", ")", ":", "holdout_dirs", "=", "(", "os", ".", "path", ".", "join", "(", "fsdb", ".", "holdout_dir", "(", ")", ",", "d", ")", "for", "d", "in", "reversed", "(", "gfile", ".", "ListDirectory", "(", "fsdb", ".", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
validate_pro
Validate on professional data.
reinforcement/tensorflow/minigo/rl_loop/train_and_validate.py
def validate_pro(): """Validate on professional data.""" cmd = ['python3', 'validate.py', FLAGS.pro_dataset, '--use_tpu', '--tpu_name={}'.format(TPU_NAME), '--work_dir={}'.format(fsdb.working_dir()), '--flagfile=rl_loop/distributed_flags', '--validate_name=...
def validate_pro(): """Validate on professional data.""" cmd = ['python3', 'validate.py', FLAGS.pro_dataset, '--use_tpu', '--tpu_name={}'.format(TPU_NAME), '--work_dir={}'.format(fsdb.working_dir()), '--flagfile=rl_loop/distributed_flags', '--validate_name=...
[ "Validate", "on", "professional", "data", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/rl_loop/train_and_validate.py#L123-L131
[ "def", "validate_pro", "(", ")", ":", "cmd", "=", "[", "'python3'", ",", "'validate.py'", ",", "FLAGS", ".", "pro_dataset", ",", "'--use_tpu'", ",", "'--tpu_name={}'", ".", "format", "(", "TPU_NAME", ")", ",", "'--work_dir={}'", ".", "format", "(", "fsdb", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
get_group_gn
get number of groups used by GroupNorm, based on number of channels.
object_detection/pytorch/maskrcnn_benchmark/modeling/make_layers.py
def get_group_gn(dim, dim_per_gp, num_groups): """get number of groups used by GroupNorm, based on number of channels.""" assert dim_per_gp == -1 or num_groups == -1, \ "GroupNorm: can only specify G or C/G." if dim_per_gp > 0: assert dim % dim_per_gp == 0, \ "dim: {}, dim_per_g...
def get_group_gn(dim, dim_per_gp, num_groups): """get number of groups used by GroupNorm, based on number of channels.""" assert dim_per_gp == -1 or num_groups == -1, \ "GroupNorm: can only specify G or C/G." if dim_per_gp > 0: assert dim % dim_per_gp == 0, \ "dim: {}, dim_per_g...
[ "get", "number", "of", "groups", "used", "by", "GroupNorm", "based", "on", "number", "of", "channels", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/make_layers.py#L14-L28
[ "def", "get_group_gn", "(", "dim", ",", "dim_per_gp", ",", "num_groups", ")", ":", "assert", "dim_per_gp", "==", "-", "1", "or", "num_groups", "==", "-", "1", ",", "\"GroupNorm: can only specify G or C/G.\"", "if", "dim_per_gp", ">", "0", ":", "assert", "dim",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
make_fc
Caffe2 implementation uses XavierFill, which in fact corresponds to kaiming_uniform_ in PyTorch
object_detection/pytorch/maskrcnn_benchmark/modeling/make_layers.py
def make_fc(dim_in, hidden_dim, use_gn=False): ''' Caffe2 implementation uses XavierFill, which in fact corresponds to kaiming_uniform_ in PyTorch ''' if use_gn: fc = nn.Linear(dim_in, hidden_dim, bias=False) nn.init.kaiming_uniform_(fc.weight, a=1) return nn.Sequenti...
def make_fc(dim_in, hidden_dim, use_gn=False): ''' Caffe2 implementation uses XavierFill, which in fact corresponds to kaiming_uniform_ in PyTorch ''' if use_gn: fc = nn.Linear(dim_in, hidden_dim, bias=False) nn.init.kaiming_uniform_(fc.weight, a=1) return nn.Sequenti...
[ "Caffe2", "implementation", "uses", "XavierFill", "which", "in", "fact", "corresponds", "to", "kaiming_uniform_", "in", "PyTorch" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/make_layers.py#L80-L92
[ "def", "make_fc", "(", "dim_in", ",", "hidden_dim", ",", "use_gn", "=", "False", ")", ":", "if", "use_gn", ":", "fc", "=", "nn", ".", "Linear", "(", "dim_in", ",", "hidden_dim", ",", "bias", "=", "False", ")", "nn", ".", "init", ".", "kaiming_uniform...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
BoxList.resize
Returns a resized copy of this bounding box :param size: The requested size in pixels, as a 2-tuple: (width, height).
object_detection/pytorch/maskrcnn_benchmark/structures/bounding_box.py
def resize(self, size, *args, **kwargs): """ Returns a resized copy of this bounding box :param size: The requested size in pixels, as a 2-tuple: (width, height). """ ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(size, self.size)) if ratios[0]...
def resize(self, size, *args, **kwargs): """ Returns a resized copy of this bounding box :param size: The requested size in pixels, as a 2-tuple: (width, height). """ ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(size, self.size)) if ratios[0]...
[ "Returns", "a", "resized", "copy", "of", "this", "bounding", "box" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/structures/bounding_box.py#L91-L127
[ "def", "resize", "(", "self", ",", "size", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ratios", "=", "tuple", "(", "float", "(", "s", ")", "/", "float", "(", "s_orig", ")", "for", "s", ",", "s_orig", "in", "zip", "(", "size", ",", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
BoxList.transpose
Transpose bounding box (flip or rotate in 90 degree steps) :param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`, :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`, :py:attr:`PIL.Image.ROTATE_180`, :py:attr:`PIL.Image.ROTATE_270`, :py:attr:`PIL.Image.TRANSPO...
object_detection/pytorch/maskrcnn_benchmark/structures/bounding_box.py
def transpose(self, method): """ Transpose bounding box (flip or rotate in 90 degree steps) :param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`, :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`, :py:attr:`PIL.Image.ROTATE_180`, :py:attr:`PIL.Image.R...
def transpose(self, method): """ Transpose bounding box (flip or rotate in 90 degree steps) :param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`, :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`, :py:attr:`PIL.Image.ROTATE_180`, :py:attr:`PIL.Image.R...
[ "Transpose", "bounding", "box", "(", "flip", "or", "rotate", "in", "90", "degree", "steps", ")", ":", "param", "method", ":", "One", "of", ":", "py", ":", "attr", ":", "PIL", ".", "Image", ".", "FLIP_LEFT_RIGHT", ":", "py", ":", "attr", ":", "PIL", ...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/structures/bounding_box.py#L129-L165
[ "def", "transpose", "(", "self", ",", "method", ")", ":", "if", "method", "not", "in", "(", "FLIP_LEFT_RIGHT", ",", "FLIP_TOP_BOTTOM", ")", ":", "raise", "NotImplementedError", "(", "\"Only FLIP_LEFT_RIGHT and FLIP_TOP_BOTTOM implemented\"", ")", "image_width", ",", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
BoxList.crop
Cropss a rectangular region from this bounding box. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate.
object_detection/pytorch/maskrcnn_benchmark/structures/bounding_box.py
def crop(self, box): """ Cropss a rectangular region from this bounding box. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. """ xmin, ymin, xmax, ymax = self._split_into_xyxy() w, h = box[2] - box[0], box[3] - box[1] crop...
def crop(self, box): """ Cropss a rectangular region from this bounding box. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. """ xmin, ymin, xmax, ymax = self._split_into_xyxy() w, h = box[2] - box[0], box[3] - box[1] crop...
[ "Cropss", "a", "rectangular", "region", "from", "this", "bounding", "box", ".", "The", "box", "is", "a", "4", "-", "tuple", "defining", "the", "left", "upper", "right", "and", "lower", "pixel", "coordinate", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/structures/bounding_box.py#L167-L193
[ "def", "crop", "(", "self", ",", "box", ")", ":", "xmin", ",", "ymin", ",", "xmax", ",", "ymax", "=", "self", ".", "_split_into_xyxy", "(", ")", "w", ",", "h", "=", "box", "[", "2", "]", "-", "box", "[", "0", "]", ",", "box", "[", "3", "]",...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
parse_args
Parse commandline arguments.
rnn_translator/pytorch/translate.py
def parse_args(): """ Parse commandline arguments. """ def exclusive_group(group, name, default, help): destname = name.replace('-', '_') subgroup = group.add_mutually_exclusive_group(required=False) subgroup.add_argument(f'--{name}', dest=f'{destname}', ...
def parse_args(): """ Parse commandline arguments. """ def exclusive_group(group, name, default, help): destname = name.replace('-', '_') subgroup = group.add_mutually_exclusive_group(required=False) subgroup.add_argument(f'--{name}', dest=f'{destname}', ...
[ "Parse", "commandline", "arguments", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/translate.py#L20-L112
[ "def", "parse_args", "(", ")", ":", "def", "exclusive_group", "(", "group", ",", "name", ",", "default", ",", "help", ")", ":", "destname", "=", "name", ".", "replace", "(", "'-'", ",", "'_'", ")", "subgroup", "=", "group", ".", "add_mutually_exclusive_g...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
main
Launches translation (inference). Inference is executed on a single GPU, implementation supports beam search with length normalization and coverage penalty.
rnn_translator/pytorch/translate.py
def main(): """ Launches translation (inference). Inference is executed on a single GPU, implementation supports beam search with length normalization and coverage penalty. """ args = parse_args() utils.set_device(args.cuda, args.local_rank) utils.init_distributed(args.cuda) setup_lo...
def main(): """ Launches translation (inference). Inference is executed on a single GPU, implementation supports beam search with length normalization and coverage penalty. """ args = parse_args() utils.set_device(args.cuda, args.local_rank) utils.init_distributed(args.cuda) setup_lo...
[ "Launches", "translation", "(", "inference", ")", ".", "Inference", "is", "executed", "on", "a", "single", "GPU", "implementation", "supports", "beam", "search", "with", "length", "normalization", "and", "coverage", "penalty", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/translate.py#L115-L189
[ "def", "main", "(", ")", ":", "args", "=", "parse_args", "(", ")", "utils", ".", "set_device", "(", "args", ".", "cuda", ",", "args", ".", "local_rank", ")", "utils", ".", "init_distributed", "(", "args", ".", "cuda", ")", "setup_logging", "(", ")", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Decoder.convert_to_strings
Given a list of numeric sequences, returns the corresponding strings
speech_recognition/pytorch/decoder.py
def convert_to_strings(self, sequences, sizes=None): """Given a list of numeric sequences, returns the corresponding strings""" strings = [] for x in xrange(len(sequences)): seq_len = sizes[x] if sizes is not None else len(sequences[x]) string = self._convert_to_string(se...
def convert_to_strings(self, sequences, sizes=None): """Given a list of numeric sequences, returns the corresponding strings""" strings = [] for x in xrange(len(sequences)): seq_len = sizes[x] if sizes is not None else len(sequences[x]) string = self._convert_to_string(se...
[ "Given", "a", "list", "of", "numeric", "sequences", "returns", "the", "corresponding", "strings" ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/speech_recognition/pytorch/decoder.py#L41-L48
[ "def", "convert_to_strings", "(", "self", ",", "sequences", ",", "sizes", "=", "None", ")", ":", "strings", "=", "[", "]", "for", "x", "in", "xrange", "(", "len", "(", "sequences", ")", ")", ":", "seq_len", "=", "sizes", "[", "x", "]", "if", "sizes...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Decoder.process_strings
Given a list of strings, removes blanks and replace space character with space. Option to remove repetitions (e.g. 'abbca' -> 'abca'). Arguments: sequences: list of 1-d array of integers remove_repetitions (boolean, optional): If true, repeating characters are re...
speech_recognition/pytorch/decoder.py
def process_strings(self, sequences, remove_repetitions=False): """ Given a list of strings, removes blanks and replace space character with space. Option to remove repetitions (e.g. 'abbca' -> 'abca'). Arguments: sequences: list of 1-d array of integers remove_r...
def process_strings(self, sequences, remove_repetitions=False): """ Given a list of strings, removes blanks and replace space character with space. Option to remove repetitions (e.g. 'abbca' -> 'abca'). Arguments: sequences: list of 1-d array of integers remove_r...
[ "Given", "a", "list", "of", "strings", "removes", "blanks", "and", "replace", "space", "character", "with", "space", ".", "Option", "to", "remove", "repetitions", "(", "e", ".", "g", ".", "abbca", "-", ">", "abca", ")", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/speech_recognition/pytorch/decoder.py#L53-L67
[ "def", "process_strings", "(", "self", ",", "sequences", ",", "remove_repetitions", "=", "False", ")", ":", "processed_strings", "=", "[", "]", "for", "sequence", "in", "sequences", ":", "string", "=", "self", ".", "process_string", "(", "remove_repetitions", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
Decoder.wer
Computes the Word Error Rate, defined as the edit distance between the two provided sentences after tokenizing to words. Arguments: s1 (string): space-separated sentence s2 (string): space-separated sentence
speech_recognition/pytorch/decoder.py
def wer(self, s1, s2): """ Computes the Word Error Rate, defined as the edit distance between the two provided sentences after tokenizing to words. Arguments: s1 (string): space-separated sentence s2 (string): space-separated sentence """ # build ...
def wer(self, s1, s2): """ Computes the Word Error Rate, defined as the edit distance between the two provided sentences after tokenizing to words. Arguments: s1 (string): space-separated sentence s2 (string): space-separated sentence """ # build ...
[ "Computes", "the", "Word", "Error", "Rate", "defined", "as", "the", "edit", "distance", "between", "the", "two", "provided", "sentences", "after", "tokenizing", "to", "words", ".", "Arguments", ":", "s1", "(", "string", ")", ":", "space", "-", "separated", ...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/speech_recognition/pytorch/decoder.py#L83-L101
[ "def", "wer", "(", "self", ",", "s1", ",", "s2", ")", ":", "# build mapping of words to integers", "b", "=", "set", "(", "s1", ".", "split", "(", ")", "+", "s2", ".", "split", "(", ")", ")", "word2char", "=", "dict", "(", "zip", "(", "b", ",", "r...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
GreedyDecoder.decode
Returns the argmax decoding given the probability matrix. Removes repeated elements in the sequence, as well as blanks. Arguments: probs: Tensor of character probabilities from the network. Expected shape of seq_length x batch x output_dim sizes(optional): Size of each sequence ...
speech_recognition/pytorch/decoder.py
def decode(self, probs, sizes=None): """ Returns the argmax decoding given the probability matrix. Removes repeated elements in the sequence, as well as blanks. Arguments: probs: Tensor of character probabilities from the network. Expected shape of seq_length x batch x outpu...
def decode(self, probs, sizes=None): """ Returns the argmax decoding given the probability matrix. Removes repeated elements in the sequence, as well as blanks. Arguments: probs: Tensor of character probabilities from the network. Expected shape of seq_length x batch x outpu...
[ "Returns", "the", "argmax", "decoding", "given", "the", "probability", "matrix", ".", "Removes", "repeated", "elements", "in", "the", "sequence", "as", "well", "as", "blanks", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/speech_recognition/pytorch/decoder.py#L160-L173
[ "def", "decode", "(", "self", ",", "probs", ",", "sizes", "=", "None", ")", ":", "_", ",", "max_probs", "=", "torch", ".", "max", "(", "probs", ".", "transpose", "(", "0", ",", "1", ")", ",", "2", ")", "strings", "=", "self", ".", "convert_to_str...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
PostProcessor.forward
Arguments: x (tuple[tensor, tensor]): x contains the class logits and the box_regression from the model. boxes (list[BoxList]): bounding boxes that are used as reference, one for ech image Returns: results (list[BoxList]): one BoxList for each...
object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/box_head/inference.py
def forward(self, x, boxes): """ Arguments: x (tuple[tensor, tensor]): x contains the class logits and the box_regression from the model. boxes (list[BoxList]): bounding boxes that are used as reference, one for ech image Returns: ...
def forward(self, x, boxes): """ Arguments: x (tuple[tensor, tensor]): x contains the class logits and the box_regression from the model. boxes (list[BoxList]): bounding boxes that are used as reference, one for ech image Returns: ...
[ "Arguments", ":", "x", "(", "tuple", "[", "tensor", "tensor", "]", ")", ":", "x", "contains", "the", "class", "logits", "and", "the", "box_regression", "from", "the", "model", ".", "boxes", "(", "list", "[", "BoxList", "]", ")", ":", "bounding", "boxes...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/box_head/inference.py#L43-L84
[ "def", "forward", "(", "self", ",", "x", ",", "boxes", ")", ":", "class_logits", ",", "box_regression", "=", "x", "class_prob", "=", "F", ".", "softmax", "(", "class_logits", ",", "-", "1", ")", "# TODO think about a representation of batch of boxes", "image_sha...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
PostProcessor.prepare_boxlist
Returns BoxList from `boxes` and adds probability scores information as an extra field `boxes` has shape (#detections, 4 * #classes), where each row represents a list of predicted bounding boxes for each of the object classes in the dataset (including the background class). The detection...
object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/box_head/inference.py
def prepare_boxlist(self, boxes, scores, image_shape): """ Returns BoxList from `boxes` and adds probability scores information as an extra field `boxes` has shape (#detections, 4 * #classes), where each row represents a list of predicted bounding boxes for each of the object cla...
def prepare_boxlist(self, boxes, scores, image_shape): """ Returns BoxList from `boxes` and adds probability scores information as an extra field `boxes` has shape (#detections, 4 * #classes), where each row represents a list of predicted bounding boxes for each of the object cla...
[ "Returns", "BoxList", "from", "boxes", "and", "adds", "probability", "scores", "information", "as", "an", "extra", "field", "boxes", "has", "shape", "(", "#detections", "4", "*", "#classes", ")", "where", "each", "row", "represents", "a", "list", "of", "pred...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/box_head/inference.py#L86-L103
[ "def", "prepare_boxlist", "(", "self", ",", "boxes", ",", "scores", ",", "image_shape", ")", ":", "boxes", "=", "boxes", ".", "reshape", "(", "-", "1", ",", "4", ")", "scores", "=", "scores", ".", "reshape", "(", "-", "1", ")", "boxlist", "=", "Box...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
PostProcessor.filter_results
Returns bounding-box detection results by thresholding on scores and applying non-maximum suppression (NMS).
object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/box_head/inference.py
def filter_results(self, boxlist, num_classes): """Returns bounding-box detection results by thresholding on scores and applying non-maximum suppression (NMS). """ # unwrap the boxlist to avoid additional overhead. # if we had multi-class NMS, we could perform this directly on th...
def filter_results(self, boxlist, num_classes): """Returns bounding-box detection results by thresholding on scores and applying non-maximum suppression (NMS). """ # unwrap the boxlist to avoid additional overhead. # if we had multi-class NMS, we could perform this directly on th...
[ "Returns", "bounding", "-", "box", "detection", "results", "by", "thresholding", "on", "scores", "and", "applying", "non", "-", "maximum", "suppression", "(", "NMS", ")", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/box_head/inference.py#L105-L146
[ "def", "filter_results", "(", "self", ",", "boxlist", ",", "num_classes", ")", ":", "# unwrap the boxlist to avoid additional overhead.", "# if we had multi-class NMS, we could perform this directly on the boxlist", "boxes", "=", "boxlist", ".", "bbox", ".", "reshape", "(", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
_determine_chunk_to_make
Returns the full path of the chunk to make (gs://...) and a boolean, indicating whether we should wait for a new model or if we're 'behind' and should just write out our current chunk immediately True == write immediately.
reinforcement/tensorflow/minigo/rl_loop/example_buffer.py
def _determine_chunk_to_make(write_dir): """ Returns the full path of the chunk to make (gs://...) and a boolean, indicating whether we should wait for a new model or if we're 'behind' and should just write out our current chunk immediately True == write immediately. """ models = fsdb.get_mo...
def _determine_chunk_to_make(write_dir): """ Returns the full path of the chunk to make (gs://...) and a boolean, indicating whether we should wait for a new model or if we're 'behind' and should just write out our current chunk immediately True == write immediately. """ models = fsdb.get_mo...
[ "Returns", "the", "full", "path", "of", "the", "chunk", "to", "make", "(", "gs", ":", "//", "...", ")", "and", "a", "boolean", "indicating", "whether", "we", "should", "wait", "for", "a", "new", "model", "or", "if", "we", "re", "behind", "and", "shou...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/rl_loop/example_buffer.py#L177-L203
[ "def", "_determine_chunk_to_make", "(", "write_dir", ")", ":", "models", "=", "fsdb", ".", "get_models", "(", ")", "# Last model is N. N+1 (should be) training. We should gather games for N+2.", "chunk_to_make", "=", "os", ".", "path", ".", "join", "(", "write_dir", "...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
fill_and_wait_models
Fills a ringbuffer with positions from the most recent games, then continually rsync's and updates the buffer until a new model is promoted. Once it detects a new model, iit then dumps its contents for training to immediately begin on the next model.
reinforcement/tensorflow/minigo/rl_loop/example_buffer.py
def fill_and_wait_models(bufsize=EXAMPLES_PER_GENERATION, write_dir=None, threads=8, model_window=100, skip_first_rsync=False): """ Fills a ringbuffer with positions from the most recent games, then continually r...
def fill_and_wait_models(bufsize=EXAMPLES_PER_GENERATION, write_dir=None, threads=8, model_window=100, skip_first_rsync=False): """ Fills a ringbuffer with positions from the most recent games, then continually r...
[ "Fills", "a", "ringbuffer", "with", "positions", "from", "the", "most", "recent", "games", "then", "continually", "rsync", "s", "and", "updates", "the", "buffer", "until", "a", "new", "model", "is", "promoted", ".", "Once", "it", "detects", "a", "new", "mo...
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/rl_loop/example_buffer.py#L261-L291
[ "def", "fill_and_wait_models", "(", "bufsize", "=", "EXAMPLES_PER_GENERATION", ",", "write_dir", "=", "None", ",", "threads", "=", "8", ",", "model_window", "=", "100", ",", "skip_first_rsync", "=", "False", ")", ":", "write_dir", "=", "write_dir", "or", "fsdb...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4
train
make_chunk_for
Explicitly make a golden chunk for a given model `model_num` (not necessarily the most recent one). While we haven't yet got enough samples (EXAMPLES_PER_GENERATION) Add samples from the games of previous model.
reinforcement/tensorflow/minigo/rl_loop/example_buffer.py
def make_chunk_for(output_dir=LOCAL_DIR, local_dir=LOCAL_DIR, game_dir=None, model_num=1, positions=EXAMPLES_PER_GENERATION, threads=8, sampling_frac=0.02): """ Explicitly make a golden chunk for a ...
def make_chunk_for(output_dir=LOCAL_DIR, local_dir=LOCAL_DIR, game_dir=None, model_num=1, positions=EXAMPLES_PER_GENERATION, threads=8, sampling_frac=0.02): """ Explicitly make a golden chunk for a ...
[ "Explicitly", "make", "a", "golden", "chunk", "for", "a", "given", "model", "model_num", "(", "not", "necessarily", "the", "most", "recent", "one", ")", "." ]
mlperf/training
python
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/rl_loop/example_buffer.py#L294-L329
[ "def", "make_chunk_for", "(", "output_dir", "=", "LOCAL_DIR", ",", "local_dir", "=", "LOCAL_DIR", ",", "game_dir", "=", "None", ",", "model_num", "=", "1", ",", "positions", "=", "EXAMPLES_PER_GENERATION", ",", "threads", "=", "8", ",", "sampling_frac", "=", ...
1c6ae725a81d15437a2b2df05cac0673fde5c3a4