text
stringlengths
81
112k
Returns the tuples of (model_id, rating, sigma) N.B. that `model_id` here is NOT the model number in the run 'data' is tuples of (winner, loser) model_ids (not model numbers) def compute_ratings(data=None): """ Returns the tuples of (model_id, rating, sigma) N.B. that `model_id` here is NOT the model ...
Find the maximally interesting pairs of players to match up First, sort the ratings by uncertainty. Then, take the ten highest players with the highest uncertainty For each of them, call them `p1` Sort all the models by their distance from p1's rating and take the 20 nearest rated models. ('candidat...
Given the current move number and the 'desired' seconds per move, return how much time should actually be used. This is intended specifically for CGOS time controls, which has an absolute 15-minute time limit. The strategy is to spend the maximum possible moves using seconds_per_move, and then switch t...
Used for playing a single game. For parallel play, use initialize_move, select_leaf, incorporate_results, and pick_move def suggest_move(self, position): """Used for playing a single game. For parallel play, use initialize_move, select_leaf, incorporate_results, and pick_move ...
Notable side effects: - finalizes the probability distribution according to this roots visit counts into the class' running tally, `searches_pi` - Makes the node associated with this move the root, for future `inject_noise` calls. def play_move(self, c): """Notable sid...
Picks a move to play, based on MCTS readout statistics. Highest N is most robust indicator. In the early stage of the game, pick a move weighted by visit count; later on, pick the absolute max. def pick_move(self): """Picks a move to play, based on MCTS readout statistics. Highest N i...
Execute RecurrentAttention. :param inputs: tensor with inputs :param hidden: hidden state for LSTM layer :param context: context tensor from encoder :param context_len: vector of encoder sequence lengths :returns (rnn_outputs, hidden, attn_output, attn_scores) def forward(self...
Converts flattened hidden state (from sequence generator) into a tuple of hidden states. :param hidden: None or flattened hidden state for decoder RNN layers def init_hidden(self, hidden): """ Converts flattened hidden state (from sequence generator) into a tuple of hidden stat...
Flattens the hidden state from all LSTM layers into one tensor (for the sequence generator). def package_hidden(self): """ Flattens the hidden state from all LSTM layers into one tensor (for the sequence generator). """ if self.inference: hidden = torch.cat(t...
Execute the decoder. :param inputs: tensor with inputs to the decoder :param context: state of encoder, encoder sequence lengths and hidden state of decoder's LSTM layers :param inference: if True stores and repackages hidden state def forward(self, inputs, context, inference=False...
Helper method inserting compliance logging ops. Note: This helper is not guaranteed to be efficient, as it will insert ops and control dependencies. If this proves to be a bottleneck, submitters may wish to consider other methods such as extracting values from an .events file. Args: op...
r"""Loads the Torch serialized object at the given URL. If the object is already present in `model_dir`, it's deserialized and returned. The filename part of the URL should follow the naming convention ``filename-<sha256>.ext`` where ``<sha256>`` is the first eight or more digits of the SHA256 hash of t...
Split x into different heads, and transpose the resulting value. The tensor is transposed to insure the inner dimensions hold the correct values during the matrix multiplication. Args: x: A tensor with shape [batch_size, length, hidden_size] Returns: A tensor with shape [batch_size, num_h...
Combine tensor that has been split. Args: x: A tensor [batch_size, num_heads, length, hidden_size/num_heads] Returns: A tensor with shape [batch_size, length, hidden_size] def combine_heads(self, x): """Combine tensor that has been split. Args: x: A tensor [batch_size, num_heads, l...
Apply attention mechanism to x and y. Args: x: a tensor with shape [batch_size, length_x, hidden_size] y: a tensor with shape [batch_size, length_y, hidden_size] bias: attention bias that will be added to the result of the dot product. cache: (Used during prediction) dictionary with tensors...
Save subtokens to file. def _save_vocab_file(vocab_file, subtoken_list): """Save subtokens to file.""" with tf.gfile.Open(vocab_file, mode="w") as f: for subtoken in subtoken_list: f.write("'%s'\n" % _unicode_to_native(subtoken))
Load vocabulary while ensuring reserved tokens are at the top. def _load_vocab_file(vocab_file, reserved_tokens=None): """Load vocabulary while ensuring reserved tokens are at the top.""" if reserved_tokens is None: reserved_tokens = RESERVED_TOKENS subtoken_list = [] with tf.gfile.Open(vocab_file, mode="...
Convert string to unicode (required in Python 2). def _native_to_unicode(s): """Convert string to unicode (required in Python 2).""" if six.PY2: return s if isinstance(s, unicode) else s.decode("utf-8") else: return s
Convert string from unicode to native format (required in Python 2). def _unicode_to_native(s): """Convert string from unicode to native format (required in Python 2).""" if six.PY2: return s.encode("utf-8") if isinstance(s, unicode) else s else: return s
Splits text to a list of string tokens. def _split_string_to_tokens(text): """Splits text to a list of string tokens.""" if not text: return [] ret = [] token_start = 0 # Classify each character in the input string is_alnum = [c in _ALPHANUMERIC_CHAR_SET for c in text] for pos in xrange(1, len(text))...
r"""Replace characters that aren't in the alphabet and append "_" to token. Apply three transformations to the token: 1. Replace underline character "_" with "\u", and backslash "\" with "\\". 2. Replace characters outside of the alphabet with "\###;", where ### is the character's Unicode code point. ...
r"""Replaces escaped characters in the token with their unescaped versions. Applies inverse transformations as _escape_token(): 1. Replace "\u" with "_", and "\\" with "\". 2. Replace "\###;" with the unicode character the ### refers to. Args: token: escaped string Returns: unescaped string de...
Return token counts of words in the files. Samples file_byte_limit bytes from each file, and counts the words that appear in the samples. The samples are semi-evenly distributed across the file. Args: files: List of filepaths file_byte_limit: Max number of bytes that will be read from each file. Retu...
Splits a token into subtokens defined in the subtoken dict. def _split_token_to_subtokens(token, subtoken_dict, max_subtoken_length): """Splits a token into subtokens defined in the subtoken dict.""" ret = [] start = 0 token_len = len(token) while start < token_len: # Find the longest subtoken, so iterat...
Generate subtoken vocabulary close to the target size. 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 = RESERV...
Create set of characters that appear in any element in the iterable. 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 ...
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. ...
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. def _filter_and_bucket_subtokens(subtoken...
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...
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...
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...
Encodes a string into a list of int subtoken ids. 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)) ...
Encode a single token into a list of subtoken ids. 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 ...
Converts list of int subtokens ids into a string. 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 ar...
Convert list of int subtoken ids to a list of string tokens. 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 =...
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? 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...
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 def forward(self, x, boxe...
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. def get_caller(stack_index=2, root_dir=None): ''' Returns file.py:lineno of your caller. A stack_index of 2 ...
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...
Generates a new model name, given the model number. 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
Takes a string related to a model name and extract its model number. For example: '000000-bootstrap.index' => 0 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(MOD...
Takes a string related to a model name and extract its model name. For example: '000000-bootstrap.index' => '000000-bootstrap' 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' ...
Performs a batch normalization using a standard set of parameters. 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...
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...
Strided 2-D convolution with explicit padding. 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.con...
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,...
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...
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,...
Creates new RNG, seed depends on current epoch idx. 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_s...
Assigns batches to workers. Consecutive ranks are getting consecutive batches. :param indices: torch.tensor with batch indices def distribute_batches(self, indices): """ Assigns batches to workers. Consecutive ranks are getting consecutive batches. :param indices: torc...
Permutes global batches :param indices: torch.tensor with batch indices :param rng: instance of torch.Generator def reshuffle_batches(self, indices, rng): """ Permutes global batches :param indices: torch.tensor with batch indices :param rng: instance of torch.Generato...
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...
very similar to the smooth_l1_loss from pytorch, but with the extra beta parameter 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 ...
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...
Helper function to print to stderr and flush def dbg(*objects, file=sys.stderr, flush=True, **kwargs): "Helper function to print to stderr and flush" print(*objects, file=file, flush=flush, **kwargs)
Creates local directories if they don't exist. 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)
Parse an SGF result string into value target. 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
Yield from an iterator in chunks of chunk_size. 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. ...
Context manager for timing snippets of code. 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. Echos to logging module. 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))
Returns full filepath if the file is in path or a subdirectory. 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_...
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...
Iterate through lines of file. def txt_line_iterator(path): """Iterate through lines of file.""" with tf.gfile.Open(path) as f: for line in f: yield line.strip()
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...
Write all of lines from file using the writer. 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")
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...
Create filename for data shard. 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))
Shuffle records in a single file. 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_f...
Converts a dictionary of string->int to a tf.Example. 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....
Returns true if all files in the list exist. 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
Obtain training and evaluation data for the Transformer model. 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 fil...
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] def encode(self, inputs, attention...
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] ...
Returns a decoding function that calculates logits of the next tokens. 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)...
Return predicted sequence. 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...
Maps user and items ids to their locations in the rating matrix. 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"...
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...
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...
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 de...
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 def getImgIds(self, imgIds=[], catIds=[]): ''' Get img ids that sati...
Load anns with the specified ids. :param ids (int array) : integer ids specifying anns :return: anns (object array) : loaded ann objects def loadAnns(self, ids=[]): """ Load anns with the specified ids. :param ids (int array) : integer ids specifying anns :re...
Load cats with the specified ids. :param ids (int array) : integer ids specifying cats :return: cats (object array) : loaded cat objects def loadCats(self, ids=[]): """ Load cats with the specified ids. :param ids (int array) : integer ids specifying cats :re...
Load anns with the specified ids. :param ids (int array) : integer ids specifying img :return: imgs (object array) : loaded img objects def loadImgs(self, ids=[]): """ Load anns with the specified ids. :param ids (int array) : integer ids specifying img :retu...
Display the specified annotations. :param anns (array of object): annotations to display :return: None def showAnns(self, anns): """ Display the specified annotations. :param anns (array of object): annotations to display :return: None """ if len(anns) ==...
Load result file and return a result api object. :param resFile (str) : file name of result file :return: res (obj) : result api object def loadRes(self, resFile): """ Load result file and return a result api object. :param resFile (str) : file name of result...
Convert annotation which can be polygons, uncompressed RLE to RLE. :return: binary mask (numpy 2D array) 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'...
Convert annotation which can be polygons, uncompressed RLE, or RLE to binary mask. :return: binary mask (numpy 2D array) def annToMask(self, ann): """ Convert annotation which can be polygons, uncompressed RLE, or RLE to binary mask. :return: binary mask (numpy 2D array) """ ...
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...
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...
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. def cal...
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]. def linear(self, x): """Computes logits by running x through a linear layer. Args: x: A fl...
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 def iterate(self, s...
Runs training or validation on batches from data_loader. :param data_loader: data loader :param training: if True runs training else runs validation def feed_data(self, data_loader, training=True): """ Runs training or validation on batches from data_loader. :param data_loader...
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 def preallocate(self, data_loader, training): """ Generates maximum seque...
Sets model in training mode, preallocates memory and runs training on data provided by data_loader. :param data_loader: data loader def optimize(self, data_loader): """ Sets model in training mode, preallocates memory and runs training on data provided by 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 def evaluate(self, data_loader): """ Sets model in eval mode, disables gradients, preallocates memory and runs validation on dat...
Loads checkpoint from filename. :param filename: path to the checkpoint file 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_lo...
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 def save(self, identifier=None, is_best=False, save_all=False):...
Given a set of BoxList containing the `labels` field, return a set of BoxList for which `labels > 0`. Arguments: boxes (list of BoxList) def keep_only_positive_boxes(boxes): """ Given a set of BoxList containing the `labels` field, return a set of BoxList for which `labels > 0`. Argum...
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...