INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Plays matches between two neural nets. | 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. | 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 | 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. | 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 of comple... | 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: the numbe... | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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 ... |
Get a dataset of serialized TFExamples from the last N games. | def get_unparsed_moves_from_last_n_games(games, games_nr, n,
moves=2**21,
shuffle=True,
column_family=TFEXAMPLE,
column='example',
... |
Count and return all the elements in the given dataset. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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 | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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 etc. ) | 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. | 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 worker with rank 0... | 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. | 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. | 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. | 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. | 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 dataset. is_train ( bool ): whether to setu... | 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. | 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. | 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 | 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. | 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. | 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. | 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. | 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. | 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 returning a CompletedProcess. | def run(cmd):
"""Prepare and run a subprocess cmd, returning a CompletedProcess."""
print("Preparing the following cmd:")
cmd = prepare_subprocess_cmd(cmd)
print("Running the following cmd:")
print('\n'.join(cmd))
return subprocess.run(cmd, stdout=sys.stdout, stderr=sys.stderr) |
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. | 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. | 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. | 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. | 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. | 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. | 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 | 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. ( candidate_p2s ) Choose pairings (... | 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. | 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. | 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. | 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. | 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. | 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... |
Execute the decoder. | def forward(self, inputs, context, inference=False):
"""
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 re... |
Helper method inserting compliance logging ops. | def log_deferred(op, log_id, every_n=1, first_n=None):
"""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 ext... |
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 the contents of the file.... | def cache_url(url, model_dir=None, progress=True):
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... |
Split x into different heads and transpose the resulting value. | def split_heads(self, x):
"""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 ten... |
Combine tensor that has been split. | def combine_heads(self, x):
"""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]
"""
with tf.name_scope("combine_heads"):
batch_size = tf.shape(x)[0]
le... |
Apply attention mechanism to x and y. | def call(self, x, y, bias, cache=None):
"""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: (... |
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="r") as f:
for line in f:
subtoken = _native_to_unicode... |
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)):
if is_alnum[pos] != is_alnum[pos - ... |
r Replace characters that aren t in the alphabet and append _ to token. | def _escape_token(token, alphabet):
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
... |
r Replaces escaped characters in the token with their unescaped versions. | def _unescape_token(token):
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
Ret... |
Return token counts of words in the files. | def _count_tokens(files, file_byte_limit=1e6):
"""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 numbe... |
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 iterate backwards.
for end in xrange(min(token_len, start + max... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.