INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Drop values from a sparse matrix encoded as a SciPy coo matrix. Args: sparse_matrix: a SciPy coo sparse matrix. rate: if rate > 0 then non-zero elements of the input matrix will be droped uniformly at random. min_dropout_rate: minimum value for the dropout rate. If None FLAGS.min_dropout_rate...
def _dropout_sparse_coo_matrix(sparse_matrix, rate, min_dropout_rate, max_dropout_rate): """Drop values from a sparse matrix encoded as a SciPy coo matrix. Args: sparse_matrix: a SciPy coo sparse matrix. rate: if rate > 0 then non-zero elements of the input matrix will ...
Shuffle sparse matrix encoded as a SciPy coo matrix. Args: sparse_matrix: a SciPy coo sparse matrix. dropout_rate: if dropout_rate > 0 then non-zero elements of the input matrix will be droped uniformly at random. min_dropout_rate: minimum value for the dropout rate. If None FLAGS.min_dropout...
def shuffle_sparse_coo_matrix(sparse_matrix, dropout_rate=0.0, min_dropout_rate=None, max_dropout_rate=None): """Shuffle sparse matrix encoded as a SciPy coo matrix. Args: sparse_matrix: a SciPy coo sparse matrix. dropout_rate: if dropout_rate > 0 then non-zero elements of the...
Takes a played game and record results and game data.
def run_game(load_file, selfplay_dir=None, holdout_dir=None, sgf_dir=None, holdout_pct=0.05): """Takes a played game and record results and game data.""" if sgf_dir is not None: minimal_sgf_dir = os.path.join(sgf_dir, 'clean') full_sgf_dir = os.path.join(sgf_dir, 'full') uti...
Entry point for running one selfplay game.
def main(argv): """Entry point for running one selfplay game.""" del argv # Unused flags.mark_flag_as_required('load_file') run_game( load_file=FLAGS.load_file, selfplay_dir=FLAGS.selfplay_dir, holdout_dir=FLAGS.holdout_dir, holdout_pct=FLAGS.holdout_pct, sgf_di...
Apply algorith 2 in https://arxiv.org/pdf/1901.08910.pdf. Args: usv: matrix to reduce given in SVD form with the spectrum s in increasing order. num_rows: number of rows in the output matrix. num_cols: number of columns in the output matrix. Returns: A resized version of (u, s, v) whose non z...
def resize_matrix(usv, num_rows, num_cols): """Apply algorith 2 in https://arxiv.org/pdf/1901.08910.pdf. Args: usv: matrix to reduce given in SVD form with the spectrum s in increasing order. num_rows: number of rows in the output matrix. num_cols: number of columns in the output matrix. Return...
Fold all values of the matrix into [0, 1].
def normalize_matrix(matrix): """Fold all values of the matrix into [0, 1].""" abs_matrix = np.abs(matrix.copy()) return abs_matrix / abs_matrix.max()
Read and sort lines from the file sorted by decreasing length. Args: filename: String name of file to read inputs from. Returns: Sorted list of inputs, and dictionary mapping original index->sorted index of each element.
def _get_sorted_inputs(filename): """Read and sort lines from the file sorted by decreasing length. Args: filename: String name of file to read inputs from. Returns: Sorted list of inputs, and dictionary mapping original index->sorted index of each element. """ with tf.gfile.Open(filename) as f: ...
Trim EOS and PAD tokens from ids, and decode to return a string.
def _trim_and_decode(ids, subtokenizer): """Trim EOS and PAD tokens from ids, and decode to return a string.""" try: index = list(ids).index(tokenizer.EOS_ID) return subtokenizer.decode(ids[:index]) except ValueError: # No EOS found in sequence return subtokenizer.decode(ids)
Translate lines in file, and save to output file if specified. Args: estimator: tf.Estimator used to generate the translations. subtokenizer: Subtokenizer object for encoding and decoding source and translated lines. input_file: file containing lines to translate output_file: file that stores ...
def translate_file( estimator, subtokenizer, input_file, output_file=None, print_all_translations=True): """Translate lines in file, and save to output file if specified. Args: estimator: tf.Estimator used to generate the translations. subtokenizer: Subtokenizer object for encoding and decoding sou...
Translate a single string.
def translate_text(estimator, subtokenizer, txt): """Translate a single string.""" encoded_txt = _encode_and_add_eos(txt, subtokenizer) def input_fn(): ds = tf.data.Dataset.from_tensors(encoded_txt) ds = ds.batch(_DECODE_BATCH_SIZE) return ds predictions = estimator.predict(input_fn) translation...
Pads vocabulary to a multiple of 'pad' tokens. :param vocab: list with vocabulary :param pad: integer
def pad_vocabulary(self, vocab, pad): """ Pads vocabulary to a multiple of 'pad' tokens. :param vocab: list with vocabulary :param pad: integer """ vocab_size = len(vocab) padded_vocab_size = (vocab_size + pad - 1) // pad * pad for i in range(0, padded_vo...
Tokenizes single sentence and adds special BOS and EOS tokens. :param line: sentence returns: list representing tokenized sentence
def segment(self, line): """ Tokenizes single sentence and adds special BOS and EOS tokens. :param line: sentence returns: list representing tokenized sentence """ line = line.strip().split() entry = [self.tok2idx[i] for i in line] entry = [config.BOS] +...
Detokenizes single sentence and removes token separator characters. :param inputs: sequence of tokens :param delim: tokenization delimiter returns: string representing detokenized sentence
def detokenize(self, inputs, delim=' '): """ Detokenizes single sentence and removes token separator characters. :param inputs: sequence of tokens :param delim: tokenization delimiter returns: string representing detokenized sentence """ detok = delim.join([self...
Arguments: x (list[Tensor]): feature maps for each feature level. Returns: results (tuple[Tensor]): feature maps after FPN layers. They are ordered from highest resolution first.
def forward(self, x): """ Arguments: x (list[Tensor]): feature maps for each feature level. Returns: results (tuple[Tensor]): feature maps after FPN layers. They are ordered from highest resolution first. """ last_inner = getattr(self, self...
Upload benchmark run information to Bigquery. Args: dataset_name: string, the name of bigquery dataset where the data will be uploaded. table_name: string, the name of bigquery table under the dataset where the data will be uploaded. run_id: string, a unique ID that will be attach...
def upload_benchmark_run(self, dataset_name, table_name, run_id): """Upload benchmark run information to Bigquery. Args: dataset_name: string, the name of bigquery dataset where the data will be uploaded. table_name: string, the name of bigquery table under the dataset where the dat...
Upload metric information to Bigquery. Args: dataset_name: string, the name of bigquery dataset where the data will be uploaded. table_name: string, the name of bigquery table under the dataset where the metric data will be uploaded. This is different from the benchmark_run tabl...
def upload_metric(self, dataset_name, table_name, run_id): """Upload metric information to Bigquery. Args: dataset_name: string, the name of bigquery dataset where the data will be uploaded. table_name: string, the name of bigquery table under the dataset where the metric data will ...
Compute BLEU for two files (reference and hypothesis translation).
def bleu_wrapper(ref_filename, hyp_filename, case_sensitive=False): """Compute BLEU for two files (reference and hypothesis translation).""" ref_lines = tf.gfile.Open(ref_filename).read().strip().splitlines() hyp_lines = tf.gfile.Open(hyp_filename).read().strip().splitlines() if len(ref_lines) != len(hyp_lines...
Plays matches between two neural nets. Args: black_model: Path to the model for black player white_model: Path to the model for white player
def play_match(black_model, white_model, games, sgf_dir): """Plays matches between two neural nets. Args: black_model: Path to the model for black player white_model: Path to the model for white player """ with utils.logged_timer("Loading weights"): black_net = dual_net.DualNetw...
Play matches between two neural nets.
def main(argv): """Play matches between two neural nets.""" _, black_model, white_model = argv utils.ensure_dir_exists(FLAGS.eval_sgf_dir) play_match(black_model, white_model, FLAGS.num_evaluation_games, FLAGS.eval_sgf_dir)
Discards all pairs of sentences which can't be decoded by latin-1 encoder. It aims to filter out sentences with rare unicode glyphs and pairs which are most likely not valid English-German sentences. Examples of discarded sentences: ✿★★★Hommage au king de la pop ★★★✿ ✿★★★Que son âme repos... ...
def main(): """ Discards all pairs of sentences which can't be decoded by latin-1 encoder. It aims to filter out sentences with rare unicode glyphs and pairs which are most likely not valid English-German sentences. Examples of discarded sentences: ✿★★★Hommage au king de la pop ★★★✿ ✿★★★Q...
Encode a set of proposals with respect to some reference boxes Arguments: reference_boxes (Tensor): reference boxes proposals (Tensor): boxes to be encoded
def encode(self, reference_boxes, proposals): """ Encode a set of proposals with respect to some reference boxes Arguments: reference_boxes (Tensor): reference boxes proposals (Tensor): boxes to be encoded """ TO_REMOVE = 1 # TODO remove ...
From a set of original boxes and encoded relative box offsets, get the decoded boxes. Arguments: rel_codes (Tensor): encoded boxes boxes (Tensor): reference boxes.
def decode(self, rel_codes, boxes): """ From a set of original boxes and encoded relative box offsets, get the decoded boxes. Arguments: rel_codes (Tensor): encoded boxes boxes (Tensor): reference boxes. """ boxes = boxes.to(rel_codes.dtype) ...
Launches an evaluator job. tag: name for this eval job (used as top level folder name) m1_path, m2_path: full gs:// paths to the .pb files to match up job_name: string, appended to the container, used to differentiate the job names (e.g. 'minigo-cc-evaluator-v5-123-v7-456') completions: the number o...
def launch_eval_job(tag, m1_path, m2_path, job_name, completions): """Launches an evaluator job. tag: name for this eval job (used as top level folder name) m1_path, m2_path: full gs:// paths to the .pb files to match up job_name: string, appended to the container, used to differentiate the job name...
Launches an evaluator job. m1_path, m2_path: full gs:// paths to the .pb files to match up job_name: string, appended to the container, used to differentiate the job names (e.g. 'minigo-cc-evaluator-v5-123-v7-456') bucket_name: Where to write the sgfs, passed into the job as $BUCKET_NAME completions...
def launch_eval_job(m1_path, m2_path, job_name, bucket_name, completions=5, flags_path=None): """Launches an evaluator job. m1_path, m2_path: full gs:// paths to the .pb files to match up job_name: string, appended to the container, used to differentiate the job names (e.g. 'minigo-cc-evaluator-...
Shorthand to spawn a job matching up two models from the same run, identified by their model number
def same_run_eval(black_num=0, white_num=0, completions=4): """Shorthand to spawn a job matching up two models from the same run, identified by their model number """ if black_num <= 0 or white_num <= 0: print("Need real model numbers") return b = fsdb.get_model(black_num) w = fsdb....
Load the pairlist, add new stuff, save it out
def _append_pairs(new_pairs): """ Load the pairlist, add new stuff, save it out """ desired_pairs = restore_pairs() or [] desired_pairs += new_pairs print("Adding {} new pairs, queue has {} pairs".format(len(new_pairs), len(desired_pairs))) save_pairs(desired_pairs)
Pairs up the top twenty models against each other. #1 plays 2,3,4,5, #2 plays 3,4,5,6 etc. for a total of 15*4 matches. Default behavior is to add the pairs to the working pairlist. `pair_now` will immediately create the pairings on the cluster. `dry_run` makes it only print the pairings that would be ...
def add_top_pairs(dry_run=False, pair_now=False): """ Pairs up the top twenty models against each other. #1 plays 2,3,4,5, #2 plays 3,4,5,6 etc. for a total of 15*4 matches. Default behavior is to add the pairs to the working pairlist. `pair_now` will immediately create the pairings on the cluster. ...
Manages creating and cleaning up match jobs. - Load whatever pairs didn't get queued last time, and whatever our most recently seen model was. - Loop and... - If a new model is detected, create and append new pairs to the list - Automatically queue models from a list of pairs to keep a cl...
def zoo_loop(sgf_dir=None, max_jobs=40): """Manages creating and cleaning up match jobs. - Load whatever pairs didn't get queued last time, and whatever our most recently seen model was. - Loop and... - If a new model is detected, create and append new pairs to the list - Automaticall...
Remove completed jobs from the cluster
def cleanup(api_instance=None): """ Remove completed jobs from the cluster """ api = api_instance or get_api() r = api.list_job_for_all_namespaces() delete_opts = kubernetes.client.V1DeleteOptions( propagation_policy="Background") for job in r.items: if job.status.succeeded == jo...
Create a list of pairs of model nums; play every model nearby, then every other model after that, then every fifth, etc. Returns a list like [[N, N-1], [N, N-2], ... , [N, N-12], ... , [N, N-50]]
def make_pairs_for_model(model_num=0): """ Create a list of pairs of model nums; play every model nearby, then every other model after that, then every fifth, etc. Returns a list like [[N, N-1], [N, N-2], ... , [N, N-12], ... , [N, N-50]] """ if model_num == 0: return pairs = [] mm...
Convert to png and save json with path. This currently only contains the segmentation labels for objects+stuff in cocostuff - if we need to combine with other labels from original COCO that will be a TODO.
def convert_coco_stuff_mat(data_dir, out_dir): """Convert to png and save json with path. This currently only contains the segmentation labels for objects+stuff in cocostuff - if we need to combine with other labels from original COCO that will be a TODO.""" sets = ['train', 'val'] categories = [] ...
Convert from cityscapes format to COCO instance seg format - polygons
def convert_cityscapes_instance_only( data_dir, out_dir): """Convert from cityscapes format to COCO instance seg format - polygons""" sets = [ 'gtFine_val', 'gtFine_train', 'gtFine_test', # 'gtCoarse_train', # 'gtCoarse_val', # 'gtCoarse_train_extra' ...
model_run = integer, e.g. 15, 16, corresponding to the v-number model_num = integer, e.g 939, for the model number in that run
def get_mg_path(model_run, model_num): """ model_run = integer, e.g. 15, 16, corresponding to the v-number model_num = integer, e.g 939, for the model number in that run """ fsdb.switch_base("minigo-pub/v{:d}-19x19".format(model_run)) model = fsdb.get_model(model_num) return os.path.join(fsd...
Create a single numpy array from a dataset. The dataset must have only one dimension, that is, the length of its `output_shapes` and `output_types` is 1, and its output shape must be `[]`, that is, every tensor in the dataset must be a scalar. Args: ds: a TF Dataset. batch_size: how ...
def make_single_array(ds, batch_size=8*1024): """Create a single numpy array from a dataset. The dataset must have only one dimension, that is, the length of its `output_shapes` and `output_types` is 1, and its output shape must be `[]`, that is, every tensor in the dataset must be a scalar. A...
Given dataset of key names, return histogram of moves/game. Move counts are written by the game players, so this is mostly useful for repair or backfill. Args: sess: TF session ds: TF dataset containing game move keys. batch_size: performance tuning parameter
def _histogram_move_keys_by_game(sess, ds, batch_size=8*1024): """Given dataset of key names, return histogram of moves/game. Move counts are written by the game players, so this is mostly useful for repair or backfill. Args: sess: TF session ds: TF dataset containing game move keys. ...
Turn keys of a Bigtable dataset into an array. Take g_GGG_m_MMM and create GGG.MMM numbers. Valuable when visualizing the distribution of a given dataset in the game keyspace.
def _game_keys_as_array(ds): """Turn keys of a Bigtable dataset into an array. Take g_GGG_m_MMM and create GGG.MMM numbers. Valuable when visualizing the distribution of a given dataset in the game keyspace. """ ds = ds.map(lambda row_key, cell: row_key) # want 'g_0000001234_m_133' is '000...
Delete the given row keys from the given Bigtable. The args are (BigtableSpec, row_keys), but are passed as a single argument in order to work with multiprocessing.Pool.map. This is also the reason why this is a top-level function instead of a method.
def _delete_rows(args): """Delete the given row keys from the given Bigtable. The args are (BigtableSpec, row_keys), but are passed as a single argument in order to work with multiprocessing.Pool.map. This is also the reason why this is a top-level function instead of a method. """ btspec...
Sets the metadata cell used to block until some quantity of games have been played. This sets the 'freshness mark' on the `game_queue`, used to block training until enough new games have been played. The number of fresh games required is the larger of: - The fraction of the total window size ...
def set_fresh_watermark(game_queue, count_from, window_size, fresh_fraction=0.05, minimum_fresh=20000): """Sets the metadata cell used to block until some quantity of games have been played. This sets the 'freshness mark' on the `game_queue`, used to block training until enough new ...
Count and return all the elements in the given dataset. Debugging function. The elements in a dataset cannot be counted without enumerating all of them. By counting in batch and in parallel, this method allows rapid traversal of the dataset. Args: ds: The dataset whose elements should be coun...
def count_elements_in_dataset(ds, batch_size=1*1024, parallel_batch=8): """Count and return all the elements in the given dataset. Debugging function. The elements in a dataset cannot be counted without enumerating all of them. By counting in batch and in parallel, this method allows rapid traversal ...
Create the table underlying the queue. Create the 'metadata' and 'tfexample' column families and their properties.
def create(self): """Create the table underlying the queue. Create the 'metadata' and 'tfexample' column families and their properties. """ if self.bt_table.exists(): utils.dbg('Table already exists') return max_versions_rule = bigtable_column_fa...
Given a range of games, return the games sorted by time. Returns [(time, game_number), ...] The time will be a `datetime.datetime` and the game number is the integer used as the basis of the row ID. Note that when a cluster of self-play nodes are writing concurrently, the game...
def games_by_time(self, start_game, end_game): """Given a range of games, return the games sorted by time. Returns [(time, game_number), ...] The time will be a `datetime.datetime` and the game number is the integer used as the basis of the row ID. Note that when a cluster of ...
Delete rows related to the given game range. Args: format_str: a string to `.format()` by the game numbers in order to create the row prefixes. start_game: the starting game number of the deletion. end_game: the ending game number of the deletion.
def delete_row_range(self, format_str, start_game, end_game): """Delete rows related to the given game range. Args: format_str: a string to `.format()` by the game numbers in order to create the row prefixes. start_game: the starting game number of the deletion. ...
Trim off the games since the given time. Search back no more than max_games for this time point, locate the game there, and remove all games since that game, resetting the latest game counter. If `t` is a `datetime.timedelta`, then the target time will be found by subtracting t...
def trim_games_since(self, t, max_games=500000): """Trim off the games since the given time. Search back no more than max_games for this time point, locate the game there, and remove all games since that game, resetting the latest game counter. If `t` is a `datetime.timedelta`,...
Given a range of games, return the bleakest moves. Returns a list of (game, move, q) sorted by q.
def bleakest_moves(self, start_game, end_game): """Given a range of games, return the bleakest moves. Returns a list of (game, move, q) sorted by q. """ bleak = b'bleakest_q' rows = self.bt_table.read_rows( ROW_PREFIX.format(start_game), ROW_PREFIX.format...
Require a given number of fresh games to be played. Args: number_fresh: integer, number of new fresh games needed Increments the cell `table_state=metadata:wait_for_game_number` by the given number of games. This will cause `self.wait_for_fresh_games()` to block until the g...
def require_fresh_games(self, number_fresh): """Require a given number of fresh games to be played. Args: number_fresh: integer, number of new fresh games needed Increments the cell `table_state=metadata:wait_for_game_number` by the given number of games. This will cause ...
Block caller until required new games have been played. Args: poll_interval: number of seconds to wait between checks If the cell `table_state=metadata:wait_for_game_number` exists, then block the caller, checking every `poll_interval` seconds, until `table_state=metadata:ga...
def wait_for_fresh_games(self, poll_interval=15.0): """Block caller until required new games have been played. Args: poll_interval: number of seconds to wait between checks If the cell `table_state=metadata:wait_for_game_number` exists, then block the caller, checking every ...
Read the value of the cell holding the 'wait' value, Returns the int value of whatever it has, or None if the cell doesn't exist.
def read_wait_cell(self): """Read the value of the cell holding the 'wait' value, Returns the int value of whatever it has, or None if the cell doesn't exist. """ table_state = self.bt_table.read_row( TABLE_STATE, filter_=bigtable_row_filters.ColumnRange...
Count the total moves in a game range. Args: game_begin: integer, starting game game_end: integer, ending game Uses the `ct_` keyspace for rapid move summary.
def count_moves_in_game_range(self, game_begin, game_end): """Count the total moves in a game range. Args: game_begin: integer, starting game game_end: integer, ending game Uses the `ct_` keyspace for rapid move summary. """ rows = self.bt_table.read_rows(...
Dataset of samples and/or shuffled moves from game range. Args: n: an integer indicating how many past games should be sourced. moves: an integer indicating how many moves should be sampled from those N games. column_family: name of the column family containing move...
def moves_from_games(self, start_game, end_game, moves, shuffle, column_family, column): """Dataset of samples and/or shuffled moves from game range. Args: n: an integer indicating how many past games should be sourced. moves: an integer indicating how man...
Randomly choose a given number of moves from the last n games. Args: n: number of games at the end of this GameQueue to source. moves: number of moves to be sampled from `n` games. shuffle: if True, shuffle the selected moves. column_family: name of the column family...
def moves_from_last_n_games(self, n, moves, shuffle, column_family, column): """Randomly choose a given number of moves from the last n games. Args: n: number of games at the end of this GameQueue to source. moves: number of moves to be sampled from...
Add move counts from the given histogram to the table. Used to update the move counts in an existing table. Should not be needed except for backfill or repair. Args: sess: TF session to use for doing a Bigtable write. tf_table: TF Cloud Bigtable to use for writing. ...
def _write_move_counts(self, sess, h): """Add move counts from the given histogram to the table. Used to update the move counts in an existing table. Should not be needed except for backfill or repair. Args: sess: TF session to use for doing a Bigtable write. tf_t...
Used to update the move_count cell for older games. Should not be needed except for backfill or repair. move_count cells will be updated in both g_<game_id>_m_000 rows and ct_<game_id>_<move_count> rows.
def update_move_counts(self, start_game, end_game, interval=1000): """Used to update the move_count cell for older games. Should not be needed except for backfill or repair. move_count cells will be updated in both g_<game_id>_m_000 rows and ct_<game_id>_<move_count> rows. """ ...
Return filenames for dataset.
def get_filenames(is_training, data_dir): """Return filenames for dataset.""" if is_training: return [ os.path.join(data_dir, 'train-%05d-of-01024' % i) for i in range(_NUM_TRAIN_FILES)] else: return [ os.path.join(data_dir, 'validation-%05d-of-00128' % i) for i in range(12...
Parses an Example proto containing a training example of an image. The output of the build_image_data.py image preprocessing script is a dataset containing serialized Example protocol buffers. Each Example proto contains the following fields (values are included as examples): image/height: 462 image/wid...
def _parse_example_proto(example_serialized): """Parses an Example proto containing a training example of an image. The output of the build_image_data.py image preprocessing script is a dataset containing serialized Example protocol buffers. Each Example proto contains the following fields (values are included...
Parses a record containing a training example of an image. The input record is parsed into a label and image, and the image is passed through preprocessing steps (cropping, flipping, and so on). Args: raw_record: scalar Tensor tf.string containing a serialized Example protocol buffer. is_training:...
def parse_record(raw_record, is_training, dtype): """Parses a record containing a training example of an image. The input record is parsed into a label and image, and the image is passed through preprocessing steps (cropping, flipping, and so on). Args: raw_record: scalar Tensor tf.string containing a ser...
Input function which provides batches for train or eval. Args: is_training: A boolean denoting whether the input is for training. data_dir: The directory containing the input data. batch_size: The number of samples per batch. num_epochs: The number of epochs to repeat the dataset. num_gpus: The n...
def input_fn(is_training, data_dir, batch_size, num_epochs=1, num_gpus=None, dtype=tf.float32): """Input function which provides batches for train or eval. Args: is_training: A boolean denoting whether the input is for training. data_dir: The directory containing the input data. batch_size...
Retrieve the size of each block_layer in the ResNet model. The number of block layers used for the Resnet model varies according to the size of the model. This helper grabs the layer set we want, throwing an error if a non-standard size has been selected. Args: resnet_size: The number of convolutional lay...
def _get_block_sizes(resnet_size): """Retrieve the size of each block_layer in the ResNet model. The number of block layers used for the Resnet model varies according to the size of the model. This helper grabs the layer set we want, throwing an error if a non-standard size has been selected. Args: resn...
Our model_fn for ResNet to be used with our Estimator.
def imagenet_model_fn(features, labels, mode, params): """Our model_fn for ResNet to be used with our Estimator.""" # Warmup and higher lr may not be valid for fine tuning with small batches # and smaller numbers of training images. if params['fine_tune']: base_lr = .1 else: base_lr = .128 learnin...
Wrapper for MLPerf compliance logging calls. All arguments but 'sync' are passed to mlperf_log.gnmt_print function. If 'sync' is set to True then the wrapper will synchronize all distributed workers. 'sync' should be set to True for all compliance tags that require accurate timing (RUN_START, RUN_STOP e...
def gnmt_print(*args, **kwargs): """ Wrapper for MLPerf compliance logging calls. All arguments but 'sync' are passed to mlperf_log.gnmt_print function. If 'sync' is set to True then the wrapper will synchronize all distributed workers. 'sync' should be set to True for all compliance tags that requi...
Initializes weights of LSTM layer. Weights and biases are initialized with uniform(-init_weight, init_weight) distribution. :param lstm: instance of torch.nn.LSTM :param init_weight: range for the uniform initializer
def init_lstm_(lstm, init_weight=0.1): """ Initializes weights of LSTM layer. Weights and biases are initialized with uniform(-init_weight, init_weight) distribution. :param lstm: instance of torch.nn.LSTM :param init_weight: range for the uniform initializer """ # Initialize hidden-hid...
Generates seeds from one master_seed. Function returns (worker_seeds, shuffling_seeds), worker_seeds are later used to initialize per-worker random number generators (mostly for dropouts), shuffling_seeds are for RNGs resposible for reshuffling the dataset before each epoch. Seeds are generated on w...
def setup_seeds(master_seed, epochs, device): """ Generates seeds from one master_seed. Function returns (worker_seeds, shuffling_seeds), worker_seeds are later used to initialize per-worker random number generators (mostly for dropouts), shuffling_seeds are for RNGs resposible for reshuffling the ...
Works as a temporary distributed barrier, currently pytorch doesn't implement barrier for NCCL backend. Calls all_reduce on dummy tensor and synchronizes with GPU.
def barrier(): """ Works as a temporary distributed barrier, currently pytorch doesn't implement barrier for NCCL backend. Calls all_reduce on dummy tensor and synchronizes with GPU. """ if torch.distributed.is_available() and torch.distributed.is_initialized(): torch.distributed.all_red...
Gets distributed rank or returns zero if distributed is not initialized.
def get_rank(): """ Gets distributed rank or returns zero if distributed is not initialized. """ if torch.distributed.is_available() and torch.distributed.is_initialized(): rank = torch.distributed.get_rank() else: rank = 0 return rank
Gets total number of distributed workers or returns one if distributed is not initialized.
def get_world_size(): """ Gets total number of distributed workers or returns one if distributed is not initialized. """ if torch.distributed.is_available() and torch.distributed.is_initialized(): world_size = torch.distributed.get_world_size() else: world_size = 1 return wor...
Configures logging. By default logs from all workers are printed to the console, entries are prefixed with "N: " where N is the rank of the worker. Logs printed to the console don't include timestaps. Full logs with timestamps are saved to the log_file file.
def setup_logging(log_file=os.devnull): """ Configures logging. By default logs from all workers are printed to the console, entries are prefixed with "N: " where N is the rank of the worker. Logs printed to the console don't include timestaps. Full logs with timestamps are saved to the log_file...
Sets device based on local_rank and returns instance of torch.device. :param cuda: if True: use cuda :param local_rank: local rank of the worker
def set_device(cuda, local_rank): """ Sets device based on local_rank and returns instance of torch.device. :param cuda: if True: use cuda :param local_rank: local rank of the worker """ if cuda: torch.cuda.set_device(local_rank) device = torch.device('cuda') else: d...
Initializes distributed backend. :param cuda: (bool) if True initializes nccl backend, if False initializes gloo backend
def init_distributed(cuda): """ Initializes distributed backend. :param cuda: (bool) if True initializes nccl backend, if False initializes gloo backend """ world_size = int(os.environ.get('WORLD_SIZE', 1)) distributed = (world_size > 1) if distributed: backend = 'nccl' if c...
Prints information about execution environment.
def log_env_info(): """ Prints information about execution environment. """ logging.info('Collecting environment information...') env_info = torch.utils.collect_env.get_pretty_env_info() logging.info(f'{env_info}')
Simple utility which helps with debugging. Takes a tensor and outputs: min, max, avg, std, number of NaNs, number of INFs. :param tensor: torch tensor :param name: name of the tensor (only for logging)
def debug_tensor(tensor, name): """ Simple utility which helps with debugging. Takes a tensor and outputs: min, max, avg, std, number of NaNs, number of INFs. :param tensor: torch tensor :param name: name of the tensor (only for logging) """ logging.info(name) tensor = tensor.detach...
Reduces average value over all workers. :param op: 'sum' or 'mean', reduction operator
def reduce(self, op): """ Reduces average value over all workers. :param op: 'sum' or 'mean', reduction operator """ if op not in ('sum', 'mean'): raise NotImplementedError distributed = (get_world_size() > 1) if distributed: # Backward/f...
Arguments: dataset_list (list[str]): Contains the names of the datasets, i.e., coco_2014_trian, coco_2014_val, etc transforms (callable): transforms to apply to each (image, target) sample dataset_catalog (DatasetCatalog): contains the information on how to construct a da...
def build_dataset(dataset_list, transforms, dataset_catalog, is_train=True): """ Arguments: dataset_list (list[str]): Contains the names of the datasets, i.e., coco_2014_trian, coco_2014_val, etc transforms (callable): transforms to apply to each (image, target) sample datase...
tensors can be an ImageList, a torch.Tensor or an iterable of Tensors. It can't be a numpy array. When tensors is an iterable of Tensors, it pads the Tensors with zeros so that they have the same shape
def to_image_list(tensors, size_divisible=0): """ tensors can be an ImageList, a torch.Tensor or an iterable of Tensors. It can't be a numpy array. When tensors is an iterable of Tensors, it pads the Tensors with zeros so that they have the same shape """ if isinstance(tensors, torch.Ten...
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...
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: ...
Set up placeholders for input features/labels. Returns the feature, output tensors that get passed into model_fn.
def get_inference_input(): """Set up placeholders for input features/labels. Returns the feature, output tensors that get passed into model_fn.""" return (tf.placeholder(tf.float32, [None, go.N, go.N, features_lib.NEW_FEATURES_PLANES], name='pos_tensor'...
Create the model for estimator api Args: features: tensor with shape [BATCH_SIZE, go.N, go.N, features_lib.NEW_FEATURES_PLANES] labels: dict from string to tensor with shape 'pi_tensor': [BATCH_SIZE, go.N * go.N + 1] 'value_tensor': [BATCH_SIZE] mode: a t...
def model_fn(features, labels, mode, params): """ Create the model for estimator api Args: features: tensor with shape [BATCH_SIZE, go.N, go.N, features_lib.NEW_FEATURES_PLANES] labels: dict from string to tensor with shape 'pi_tensor': [BATCH_SIZE, go.N * go.N + 1] ...
Builds just the inference part of the model graph. Args: features: input features tensor. training: True if the model is training. params: A dictionary Returns: (policy_output, value_output, logits) tuple of tensors.
def model_inference_fn(features, training, params): """Builds just the inference part of the model graph. Args: features: input features tensor. training: True if the model is training. params: A dictionary Returns: (policy_output, value_output, logits) tuple of tensors. ...
Builds the model graph suitable for running on TPU. It does two things: 1) Mark all weights as constant, which improves TPU inference performance because it prevents the weights being transferred to the TPU every call to Session.run(). 2) Adds constant to the graph with a unique value and...
def tpu_model_inference_fn(features): """Builds the model graph suitable for running on TPU. It does two things: 1) Mark all weights as constant, which improves TPU inference performance because it prevents the weights being transferred to the TPU every call to Session.run(). 2) Adds ...
Initialize a tf.Estimator run with random initial weights.
def bootstrap(): """Initialize a tf.Estimator run with random initial weights.""" # a bit hacky - forge an initial checkpoint with the name that subsequent # Estimator runs will expect to find. # # Estimator will do this automatically when you call train(), but calling # train() requires data, a...
Take the latest checkpoint and copy it to model_path. Assumes that all relevant model files are prefixed by the same name. (For example, foo.index, foo.meta and foo.data-00000-of-00001). Args: model_path: The path (can be a gs:// path) to export model
def export_model(model_path): """Take the latest checkpoint and copy it to model_path. Assumes that all relevant model files are prefixed by the same name. (For example, foo.index, foo.meta and foo.data-00000-of-00001). Args: model_path: The path (can be a gs:// path) to export model """ ...
Custom freeze_graph implementation for Cloud TPU.
def freeze_graph_tpu(model_path): """Custom freeze_graph implementation for Cloud TPU.""" assert model_path assert FLAGS.tpu_name if FLAGS.tpu_name.startswith('grpc://'): tpu_grpc_url = FLAGS.tpu_name else: tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver( ...
Initialize the weights from the given save_file. Assumes that the graph has been constructed, and the save_file contains weights that match the graph. Used to set the weights to a different version of the player without redifining the entire graph.
def initialize_weights(self, save_file): """Initialize the weights from the given save_file. Assumes that the graph has been constructed, and the save_file contains weights that match the graph. Used to set the weights to a different version of the player without redifining the e...
Parses the output of --helpfull. Args: help_output: str, the full output of --helpfull. Returns: A set of flags that are valid flags.
def parse_helpfull_output(help_output, regex=FLAG_HELP_RE_PY): """Parses the output of --helpfull. Args: help_output: str, the full output of --helpfull. Returns: A set of flags that are valid flags. """ valid_flags = set() for _, no_prefix, flag_name in regex.findall(help_outp...
Return the subset of `parsed_flags` that are found in the list `valid_flags`
def filter_flags(parsed_flags, valid_flags): """Return the subset of `parsed_flags` that are found in the list `valid_flags`""" def valid_argv(argv): """Figures out if a flag parsed from the flagfile matches a flag in the command about to be run.""" flagname_match = FLAG_RE.match(argv) ...
Prepares a subprocess command by running --helpfull and masking flags. Args: subprocess_cmd: List[str], what would be passed into subprocess.call() i.e. ['python', 'train.py', '--flagfile=flags'] Returns: ['python', 'train.py', '--train_flag=blah', '--more_flags']
def prepare_subprocess_cmd(subprocess_cmd): """Prepares a subprocess command by running --helpfull and masking flags. Args: subprocess_cmd: List[str], what would be passed into subprocess.call() i.e. ['python', 'train.py', '--flagfile=flags'] Returns: ['python', 'train.py', '--...
Prepare and run a subprocess cmd, checking for successful completion.
def checked_run(cmd): """Prepare and run a subprocess cmd, checking for successful completion.""" completed_process = run(cmd) if completed_process.returncode > 0: print("Command failed! Hanging around in case someone needs a " "docker connection. (Ctrl-C to quit now)") time.s...
Given a Dataset with raw records, return an iterator over the records. Args: dataset: A Dataset representing raw records is_training: A boolean denoting whether the input is for training. batch_size: The number of samples per batch. shuffle_buffer: The buffer size to use when shuffling records. A lar...
def process_record_dataset(dataset, is_training, batch_size, shuffle_buffer, parse_record_fn, num_epochs=1, num_gpus=None, examples_per_epoch=None, dtype=tf.float32): """Given a Dataset with raw records, return an iterator over the records. Args: dataset: A...
Returns an input function that returns a dataset with zeroes. This is useful in debugging input pipeline performance, as it removes all elements of file reading and image preprocessing. Args: height: Integer height that will be used to create a fake image tensor. width: Integer width that will be used t...
def get_synth_input_fn(height, width, num_channels, num_classes): """Returns an input function that returns a dataset with zeroes. This is useful in debugging input pipeline performance, as it removes all elements of file reading and image preprocessing. Args: height: Integer height that will be used to c...
Get a learning rate that decays step-wise as training progresses. Args: batch_size: the number of examples processed in each training batch. batch_denom: this value will be used to scale the base learning rate. `0.1 * batch size` is divided by this number, such that when batch_denom == batch_size...
def learning_rate_with_decay( batch_size, batch_denom, num_images, boundary_epochs, decay_rates, base_lr=0.1, enable_lars=False): """Get a learning rate that decays step-wise as training progresses. Args: batch_size: the number of examples processed in each training batch. batch_denom: this value w...
Shared functionality for different resnet model_fns. Initializes the ResnetModel representing the model layers and uses that model to build the necessary EstimatorSpecs for the `mode` in question. For training, this means building losses, the optimizer, and the train op that get passed into the EstimatorSpec. ...
def resnet_model_fn(features, labels, mode, model_class, resnet_size, weight_decay, learning_rate_fn, momentum, data_format, version, loss_scale, loss_filter_fn=None, dtype=resnet_model.DEFAULT_DTYPE, label_smoothing=0.0, enable_lars=False)...
For multi-gpu, batch-size must be a multiple of the number of GPUs. Note that this should eventually be handled by DistributionStrategies directly. Multi-GPU support is currently experimental, however, so doing the work here until that feature is in place. Args: batch_size: Global batch size to be divided...
def per_device_batch_size(batch_size, num_gpus): """For multi-gpu, batch-size must be a multiple of the number of GPUs. Note that this should eventually be handled by DistributionStrategies directly. Multi-GPU support is currently experimental, however, so doing the work here until that feature is in place. ...
Shared main loop for ResNet Models. Args: flags: FLAGS object that contains the params for running. See ResnetArgParser for created flags. model_function: the function that instantiates the Model and builds the ops for train/eval. This will be passed directly into the estimator. input_functio...
def resnet_main(seed, flags, model_function, input_function, shape=None): """Shared main loop for ResNet Models. Args: flags: FLAGS object that contains the params for running. See ResnetArgParser for created flags. model_function: the function that instantiates the Model and builds the ops for...
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 number in the run 'data' is tuples of (winner, loser) model_ids (not model numbers) """ if data is None: with sqlite3.connect("ratings.db") as db: data ...
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...
def suggest_pairs(top_n=10, per_n=3, ignore_before=300): """ Find the maximally interesting pairs of players to match up First, sort the ratings by uncertainty. Then, take the ten highest players with the highest uncertainty For each of them, call them `p1` Sort all the models by their distance from...
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...
def time_recommendation(move_num, seconds_per_move=5, time_limit=15 * 60, decay_factor=0.98): """Given the current move number and the 'desired' seconds per move, return how much time should actually be used. This is intended specifically for CGOS time controls, which has an absolute...
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 """ start = time.time() if self.timed_match: while time.time() - start < self.seconds_per_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 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. """ ...
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 is most robust indicator. In the early stage of the game, pick a move weighted by visit count; later on, pick the absolute max.""" if self.root.position.n >= self.temp_threshold: fcoord...
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, inputs, hidden, context, context_len): """ Execute RecurrentAttention. :param inputs: tensor with inputs :param hidden: hidden state for LSTM layer :param context: context tensor from encoder :param context_len: vector of encoder sequence lengths ...
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 states. :param hidden: None or flattened hidden state for decoder RNN layers """ if hidden is not None: # per-layer chunks hidden =...
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(tuple(itertools.chain(*self.next_hidden))) else: hidden = None return hidde...