INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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 = RESERVED_TOKENS
if min_count is not None:
tf.logging.in... |
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 in token}
alphabet |= {c for token in reserved_tokens for c in token... |
Count number of times subtokens appear and generate new subtokens. | def _count_and_gen_subtokens(
token_counts, alphabet, subtoken_dict, max_subtoken_length):
"""Count number of times subtokens appear, and generate new subtokens.
Args:
token_counts: dict mapping tokens to the number of times they appear in the
original files.
alphabet: list of allowed characters.... |
Return a bucketed list of subtokens that are filtered by count. | def _filter_and_bucket_subtokens(subtoken_counts, min_count):
"""Return a bucketed list of subtokens that are filtered by count.
Args:
subtoken_counts: defaultdict mapping subtokens to their counts
min_count: int count used to filter subtokens
Returns:
List of subtoken sets, where subtokens in set i... |
Generate candidate subtokens ordered by count and new max subtoken length. | def _gen_new_subtoken_list(
subtoken_counts, min_count, alphabet, reserved_tokens=None):
"""Generate candidate subtokens ordered by count, and new max subtoken length.
Add subtokens to the candiate list in order of length (longest subtokens
first). When a subtoken is added, the counts of each of its prefixes... |
Create a list of subtokens in decreasing order of frequency. | def _generate_subtokens(
token_counts, alphabet, min_count, num_iterations=4,
reserved_tokens=None):
"""Create a list of subtokens in decreasing order of frequency.
Args:
token_counts: dict mapping str tokens -> int count
alphabet: set of characters
min_count: int minimum number of times a subt... |
Create subtoken vocabulary based on files and save vocab to file. | def init_from_files(
vocab_file, files, target_vocab_size, threshold, min_count=None,
file_byte_limit=1e6, reserved_tokens=None):
"""Create subtoken vocabulary based on files, and save vocab to file.
Args:
vocab_file: String name of vocab file to store subtoken vocabulary.
files: List o... |
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))
if add_eos:
ret.append(EOS_ID)
return ret |
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
ret = _split_token_to_subtokens(
_escape_tok... |
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 array and its items.
subtokens = subtokens.toli... |
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 = escaped_tokens.split("_")
# All tokens in the vocabulary... |
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 be a member function of
player.network?"""
prob_list = []
value_list = []
for idx in range(0, len(positions), batch_size):
prob... |
Arguments: x ( Tensor ): the mask logits boxes ( list [ BoxList ] ): bounding boxes that are used as reference one for ech image | def forward(self, x, boxes):
"""
Arguments:
x (Tensor): the mask logits
boxes (list[BoxList]): bounding boxes that are used as
reference, one for ech image
Returns:
results (list[BoxList]): one BoxList for each image, containing
... |
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 will provide
the caller of the function calling this function. Notice that stack_index
of 2 or more will fail if called from global scope. '''
caller = inspect.getframeinfo(inspect.stack()[stack_i... |
Prints out an MLPerf Log Line. | def _mlperf_print(key, value=None, benchmark=None, stack_offset=0,
tag_set=None, deferred=False, root_dir=None,
extra_print=False, prefix=""):
''' Prints out an MLPerf Log Line.
key: The MLPerf log key such as 'CLOCK' or 'QUALITY'. See the list of log keys in the spec.
value: ... |
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. | def detect_model_num(string):
"""Takes a string related to a model name and extract its model number.
For example:
'000000-bootstrap.index' => 0
"""
match = re.match(MODEL_NUM_REGEX, string)
if match:
return int(match.group())
return None |
Takes a string related to a model name and extract its model name. | def detect_model_name(string):
"""Takes a string related to a model name and extract its model name.
For example:
'000000-bootstrap.index' => '000000-bootstrap'
"""
match = re.match(MODEL_NAME_REGEX, string)
if match:
return match.group()
return None |
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_fused_ops
outputs = tf.layers.batch_normalization(
inputs=i... |
Pads the input along the spatial dimensions independently of input size. | def fixed_padding(inputs, kernel_size, data_format):
"""Pads the input along the spatial dimensions independently of input size.
Args:
inputs: A tensor of size [batch, channels, height_in, width_in] or
[batch, height_in, width_in, channels] depending on data_format.
kernel_size: The kernel to be used... |
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.conv2d` alone).
inputs_for_logging = inputs
if... |
A single block for ResNet v1 with a bottleneck. | def _bottleneck_block_v1(inputs, filters, training, projection_shortcut,
strides, data_format):
"""A single block for ResNet v1, with a bottleneck.
Similar to _building_block_v1(), except using the "bottleneck" blocks
described in:
Convolution then batch normalization then ReLU as de... |
Creates one layer of blocks for the ResNet model. | def block_layer(inputs, filters, bottleneck, block_fn, blocks, strides,
training, name, data_format):
"""Creates one layer of blocks for the ResNet model.
Args:
inputs: A tensor of size [batch, channels, height_in, width_in] or
[batch, height_in, width_in, channels] depending on data_form... |
Creates variables in fp32 then casts to fp16 if necessary. | def _custom_dtype_getter(self, getter, name, shape=None, dtype=DEFAULT_DTYPE,
*args, **kwargs):
"""Creates variables in fp32, then casts to fp16 if necessary.
This function is a custom getter. A custom getter is a function with the
same signature as tf.get_variable, except it has... |
Creates 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_seed(seed)
return rng |
Assigns batches to workers. Consecutive ranks are getting consecutive batches. | def distribute_batches(self, indices):
"""
Assigns batches to workers.
Consecutive ranks are getting consecutive batches.
:param indices: torch.tensor with batch indices
"""
assert len(indices) == self.num_samples
indices = indices.view(-1, self.batch_size)
... |
Permutes global batches | def reshuffle_batches(self, indices, rng):
"""
Permutes global batches
:param indices: torch.tensor with batch indices
:param rng: instance of torch.Generator
"""
indices = indices.view(-1, self.global_batch_size)
num_batches = indices.shape[0]
order = to... |
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 targets ( list [ BoxList ): ground - truth boxes present in the... | def forward(self, images, features, targets=None):
"""
Arguments:
images (ImageList): images for which we want to compute the predictions
features (list[Tensor]): features computed from the images that are
used for computing the predictions. Each tensor in the lis... |
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
loss = torch.where(cond, 0.5 * n ** 2 / beta, n - 0.5 * beta)
if size_average:
... |
Evaluate all positions with all models save the policy heatmaps as CSVs | def eval_policy(eval_positions):
"""Evaluate all positions with all models save the policy heatmaps as CSVs
CSV name is "heatmap-<position_name>-<model-index>.csv"
CSV format is: model number, value network output, policy network outputs
position_name is taken from the SGF file
Policy network outp... |
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.
if next_chunk:
yield next_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_depth
depth = root[len(path) + 1:].count(os.sep)
if depth... |
Return raw files from source. Downloads/ extracts if needed. | def get_raw_files(raw_dir, data_source):
"""Return raw files from source. Downloads/extracts if needed.
Args:
raw_dir: string directory to store raw files
data_source: dictionary with
{"url": url of compressed dataset containing input and target files
"input": file with data in input language
... |
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. | def compile_files(raw_dir, raw_files, tag):
"""Compile raw files into a single file for each language.
Args:
raw_dir: Directory containing downloaded raw files.
raw_files: Dict containing filenames of input and target data.
{"inputs": list of files containing data in input language
"targets": ... |
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. | def encode_and_save_files(
subtokenizer, data_dir, raw_files, tag, total_shards):
"""Save data from files as encoded Examples in TFrecord format.
Args:
subtokenizer: Subtokenizer object that will be used to encode the strings.
data_dir: The directory in which to write the examples
raw_files: A tupl... |
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_fname)
records = []
for record i... |
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.train.Features(feature=features)) |
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 files.
tf.logging.info("Step 1/4: Downloading data from source")
... |
Generate continuous representation for inputs. | def encode(self, inputs, attention_bias):
"""Generate continuous representation for inputs.
Args:
inputs: int tensor with shape [batch_size, input_length].
attention_bias: float tensor with shape [batch_size, 1, 1, input_length]
Returns:
float tensor with shape [batch_size, input_length,... |
Generate logits for each value in the target sequence. | def decode(self, targets, encoder_outputs, attention_bias):
"""Generate logits for each value in the target sequence.
Args:
targets: target values for the output sequence.
int tensor with shape [batch_size, target_length]
encoder_outputs: continuous representation of input sequence.
... |
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)
decoder_self_attention_bias = model_utils.get_decoder_self_attentio... |
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_fn = self._get_symbols_to_l... |
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"] = ratings_df["userId"].apply(
lambda x: user_id_to_user_id... |
Separate the rating datafram into train and test sets. | def _preprocess_movie_lens(ratings_df):
"""Separate the rating datafram into train and test sets.
Filters out users with less than two distinct timestamps. Creates train set
and test set. The test set contains all the last interactions of users with
more than two distinct timestamps.
Args:
ratings_df: p... |
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 ( boolean ): get anns for given crowd label ( False or True ):... | def getAnnIds(self, imgIds=[], catIds=[], areaRng=[], iscrowd=None):
"""
Get ann ids that satisfy given filter conditions. default skips that filter
:param imgIds (int array) : get anns for given imgs
catIds (int array) : get anns for given cats
areaRng (f... |
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 | def getCatIds(self, catNms=[], supNms=[], catIds=[]):
"""
filtering parameters. default skips that filter.
:param catNms (str array) : get cats for given cat names
:param supNms (str array) : get cats for given supercategory names
:param catIds (int array) : get cats for given... |
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 satisfy given filter conditions.
:param imgIds (int array) : get imgs for given ids
:param catIds (int array) : get imgs with all given cats
:return: ids (int array) : integer array of img ids
'''
im... |
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
:return: anns (object array) : loaded ann objects
"""
if _isArrayLike(ids):
return [self.anns[id] for id in ids]
elif type(ids)... |
Load cats with the specified ids.: param ids ( int array ): integer ids specifying cats: return: cats ( object array ): loaded cat objects | def loadCats(self, ids=[]):
"""
Load cats with the specified ids.
:param ids (int array) : integer ids specifying cats
:return: cats (object array) : loaded cat objects
"""
if _isArrayLike(ids):
return [self.cats[id] for id in ids]
elif type(ids)... |
Load 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
:return: imgs (object array) : loaded img objects
"""
if _isArrayLike(ids):
return [self.imgs[id] for id in ids]
elif type(ids) ... |
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) == 0:
return 0
if 'segmentation' in anns[0] or 'keypoints' in anns[0]:
datasetType = 'inst... |
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 file
:return: res (obj) : result api object
"""
res = COCO()
res.dataset['images'] = [img for img in self.dataset['images']]
... |
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']]
h, w = t['height'], t['width']
segm = ann['segmentation']
if type(segm) == list:
... |
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)
"""
rle = self.annToRLE(ann)
m = maskUtils.decode(rle)
return m |
Arguments: images ( list [ Tensor ] or ImageList ): images to be processed targets ( list [ BoxList ] ): ground - truth boxes present in the image ( optional ) | def forward(self, images, targets=None):
"""
Arguments:
images (list[Tensor] or ImageList): images to be processed
targets (list[BoxList]): ground-truth boxes present in the image (optional)
Returns:
result (list[BoxList] or dict[Tensor]): the output from the... |
Wrapper around SciPy s Singular Value Decomposition for sparse matrices. | def sparse_svd(sparse_matrix, num_values, max_iter):
"""Wrapper around SciPy's Singular Value Decomposition for sparse matrices.
Args:
sparse_matrix: a SciPy sparse matrix (typically large).
num_values: the number of largest singular values to compute.
max_iter: maximum number of iterations (>= 0) in t... |
Get token embeddings of x. | def call(self, x):
"""Get token embeddings of x.
Args:
x: An int64 tensor with shape [batch_size, length]
Returns:
embeddings: float32 tensor with shape [batch_size, length, embedding_size]
padding: float32 tensor with shape [batch_size, length] indicating the
locations of the pad... |
Computes logits by running x through a linear layer. | def linear(self, x):
"""Computes logits by running x through a linear layer.
Args:
x: A float32 tensor with shape [batch_size, length, hidden_size]
Returns:
float32 tensor with shape [batch_size, length, vocab_size].
"""
with tf.name_scope("presoftmax_linear"):
batch_size = tf.sha... |
Performs one iteration of the training/ validation. | def iterate(self, src, tgt, update=True, training=True):
"""
Performs one iteration of the training/validation.
:param src: batch of examples from the source language
:param tgt: batch of examples from the target language
:param update: if True: optimizer does update of the weig... |
Runs training or validation on batches from data_loader. | def feed_data(self, data_loader, training=True):
"""
Runs training or validation on batches from data_loader.
:param data_loader: data loader
:param training: if True runs training else runs validation
"""
if training:
assert self.optimizer is not None
... |
Generates maximum sequence length batch and runs forward and backward pass without updating model parameters. | def preallocate(self, data_loader, training):
"""
Generates maximum sequence length batch and runs forward and backward
pass without updating model parameters.
:param data_loader: data loader
:param training: if True preallocates memory for backward pass
"""
batc... |
Sets model in training mode preallocates memory and runs training on data provided by data_loader. | def optimize(self, data_loader):
"""
Sets model in training mode, preallocates memory and runs training on
data provided by data_loader.
:param data_loader: data loader
"""
torch.set_grad_enabled(True)
self.model.train()
torch.cuda.empty_cache()
s... |
Sets model in eval mode disables gradients preallocates memory and runs validation on data provided by data_loader. | def evaluate(self, data_loader):
"""
Sets model in eval mode, disables gradients, preallocates memory and
runs validation on data provided by data_loader.
:param data_loader: data loader
"""
torch.set_grad_enabled(False)
self.model.eval()
torch.cuda.empty... |
Loads checkpoint from filename. | def load(self, filename):
"""
Loads checkpoint from filename.
:param filename: path to the checkpoint file
"""
if os.path.isfile(filename):
checkpoint = torch.load(filename, map_location={'cuda:0': 'cpu'})
if self.distributed:
self.model.m... |
Stores checkpoint to a file. | def save(self, identifier=None, is_best=False, save_all=False):
"""
Stores checkpoint to a file.
:param identifier: identifier for periodic checkpoint
:param is_best: if True stores checkpoint to 'model_best.pth'
:param save_all: if True stores checkpoint after completed trainin... |
Given a set of BoxList containing the labels field return a set of BoxList for which labels > 0. | def keep_only_positive_boxes(boxes):
"""
Given a set of BoxList containing the `labels` field,
return a set of BoxList for which `labels > 0`.
Arguments:
boxes (list of BoxList)
"""
assert isinstance(boxes, (list, tuple))
assert isinstance(boxes[0], BoxList)
assert boxes[0].has_... |
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:
... |
Gets the 95th percentile of bleakest_eval from bigtable | def get_95_percentile_bleak(games_nr, n_back=500):
"""Gets the 95th percentile of bleakest_eval from bigtable"""
end_game = int(games_nr.latest_game_number)
start_game = end_game - n_back if end_game >= n_back else 0
moves = games_nr.bleakest_moves(start_game, end_game)
evals = np.array([m[2] for m ... |
Updates the flagfile at flags_path changing the value for resign_threshold to new_threshold | def update_flagfile(flags_path, new_threshold):
"""Updates the flagfile at `flags_path`, changing the value for
`resign_threshold` to `new_threshold`
"""
if abs(new_threshold) > 1:
raise ValueError("Invalid new percentile for resign threshold")
with tf.gfile.GFile(flags_path) as f:
l... |
Prints the current MCTS search status to stderr. | def _minigui_report_search_status(self, leaves):
"""Prints the current MCTS search status to stderr.
Reports the current search path, root node's child_Q, root node's
child_N, the most visited path in a format that can be parsed by
one of the STDERR_HANDLERS in minigui.ts.
Args... |
Parse commandline arguments. | def parse_args():
"""
Parse commandline arguments.
"""
def exclusive_group(group, name, default, help):
destname = name.replace('-', '_')
subgroup = group.add_mutually_exclusive_group(required=False)
subgroup.add_argument(f'--{name}', dest=f'{destname}',
... |
Launches data - parallel multi - gpu training. | def main():
"""
Launches data-parallel multi-gpu training.
"""
mlperf_log.ROOT_DIR_GNMT = os.path.dirname(os.path.abspath(__file__))
mlperf_log.LOGGER.propagate = False
args = parse_args()
device = utils.set_device(args.cuda, args.local_rank)
distributed = utils.init_distributed(args.cu... |
Validate on held - out selfplay data. | def validate_holdout_selfplay():
"""Validate on held-out selfplay data."""
holdout_dirs = (os.path.join(fsdb.holdout_dir(), d)
for d in reversed(gfile.ListDirectory(fsdb.holdout_dir()))
if gfile.IsDirectory(os.path.join(fsdb.holdout_dir(), d))
for f in... |
Validate on professional data. | def validate_pro():
"""Validate on professional data."""
cmd = ['python3', 'validate.py', FLAGS.pro_dataset,
'--use_tpu',
'--tpu_name={}'.format(TPU_NAME),
'--work_dir={}'.format(fsdb.working_dir()),
'--flagfile=rl_loop/distributed_flags',
'--validate_name=... |
get number of groups used by GroupNorm based on number of channels. | def get_group_gn(dim, dim_per_gp, num_groups):
"""get number of groups used by GroupNorm, based on number of channels."""
assert dim_per_gp == -1 or num_groups == -1, \
"GroupNorm: can only specify G or C/G."
if dim_per_gp > 0:
assert dim % dim_per_gp == 0, \
"dim: {}, dim_per_g... |
Caffe2 implementation uses XavierFill which in fact corresponds to kaiming_uniform_ in PyTorch | def make_fc(dim_in, hidden_dim, use_gn=False):
'''
Caffe2 implementation uses XavierFill, which in fact
corresponds to kaiming_uniform_ in PyTorch
'''
if use_gn:
fc = nn.Linear(dim_in, hidden_dim, bias=False)
nn.init.kaiming_uniform_(fc.weight, a=1)
return nn.Sequenti... |
Returns a resized copy of this bounding box | def resize(self, size, *args, **kwargs):
"""
Returns a resized copy of this bounding box
:param size: The requested size in pixels, as a 2-tuple:
(width, height).
"""
ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(size, self.size))
if ratios[0]... |
Transpose bounding box ( flip or rotate in 90 degree steps ): param method: One of: py: attr: PIL. Image. FLIP_LEFT_RIGHT: py: attr: PIL. Image. FLIP_TOP_BOTTOM: py: attr: PIL. Image. ROTATE_90: py: attr: PIL. Image. ROTATE_180: py: attr: PIL. Image. ROTATE_270: py: attr: PIL. Image. TRANSPOSE or: py: attr: PIL. Image.... | def transpose(self, method):
"""
Transpose bounding box (flip or rotate in 90 degree steps)
:param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`,
:py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`,
:py:attr:`PIL.Image.ROTATE_180`, :py:attr:`PIL.Image.R... |
Cropss a rectangular region from this bounding box. The box is a 4 - tuple defining the left upper right and lower pixel coordinate. | def crop(self, box):
"""
Cropss a rectangular region from this bounding box. The box is a
4-tuple defining the left, upper, right, and lower pixel
coordinate.
"""
xmin, ymin, xmax, ymax = self._split_into_xyxy()
w, h = box[2] - box[0], box[3] - box[1]
crop... |
Parse commandline arguments. | def parse_args():
"""
Parse commandline arguments.
"""
def exclusive_group(group, name, default, help):
destname = name.replace('-', '_')
subgroup = group.add_mutually_exclusive_group(required=False)
subgroup.add_argument(f'--{name}', dest=f'{destname}',
... |
Launches translation ( inference ). Inference is executed on a single GPU implementation supports beam search with length normalization and coverage penalty. | def main():
"""
Launches translation (inference).
Inference is executed on a single GPU, implementation supports beam search
with length normalization and coverage penalty.
"""
args = parse_args()
utils.set_device(args.cuda, args.local_rank)
utils.init_distributed(args.cuda)
setup_lo... |
Given a list of numeric sequences returns the corresponding strings | def convert_to_strings(self, sequences, sizes=None):
"""Given a list of numeric sequences, returns the corresponding strings"""
strings = []
for x in xrange(len(sequences)):
seq_len = sizes[x] if sizes is not None else len(sequences[x])
string = self._convert_to_string(se... |
Given a list of strings removes blanks and replace space character with space. Option to remove repetitions ( e. g. abbca - > abca ). | def process_strings(self, sequences, remove_repetitions=False):
"""
Given a list of strings, removes blanks and replace space character with space.
Option to remove repetitions (e.g. 'abbca' -> 'abca').
Arguments:
sequences: list of 1-d array of integers
remove_r... |
Computes the Word Error Rate defined as the edit distance between the two provided sentences after tokenizing to words. Arguments: s1 ( string ): space - separated sentence s2 ( string ): space - separated sentence | def wer(self, s1, s2):
"""
Computes the Word Error Rate, defined as the edit distance between the
two provided sentences after tokenizing to words.
Arguments:
s1 (string): space-separated sentence
s2 (string): space-separated sentence
"""
# build ... |
Returns the argmax decoding given the probability matrix. Removes repeated elements in the sequence as well as blanks. | def decode(self, probs, sizes=None):
"""
Returns the argmax decoding given the probability matrix. Removes
repeated elements in the sequence, as well as blanks.
Arguments:
probs: Tensor of character probabilities from the network. Expected shape of seq_length x batch x outpu... |
Arguments: x ( tuple [ tensor tensor ] ): x contains the class logits and the box_regression from the model. boxes ( list [ BoxList ] ): bounding boxes that are used as reference one for ech image | def forward(self, x, boxes):
"""
Arguments:
x (tuple[tensor, tensor]): x contains the class logits
and the box_regression from the model.
boxes (list[BoxList]): bounding boxes that are used as
reference, one for ech image
Returns:
... |
Returns BoxList from boxes and adds probability scores information as an extra field boxes has shape ( #detections 4 * #classes ) where each row represents a list of predicted bounding boxes for each of the object classes in the dataset ( including the background class ). The detections in each row originate from the s... | def prepare_boxlist(self, boxes, scores, image_shape):
"""
Returns BoxList from `boxes` and adds probability scores information
as an extra field
`boxes` has shape (#detections, 4 * #classes), where each row represents
a list of predicted bounding boxes for each of the object cla... |
Returns bounding - box detection results by thresholding on scores and applying non - maximum suppression ( NMS ). | def filter_results(self, boxlist, num_classes):
"""Returns bounding-box detection results by thresholding on scores and
applying non-maximum suppression (NMS).
"""
# unwrap the boxlist to avoid additional overhead.
# if we had multi-class NMS, we could perform this directly on th... |
Returns the full path of the chunk to make ( gs://... ) and a boolean indicating whether we should wait for a new model or if we re behind and should just write out our current chunk immediately True == write immediately. | def _determine_chunk_to_make(write_dir):
"""
Returns the full path of the chunk to make (gs://...)
and a boolean, indicating whether we should wait for a new model
or if we're 'behind' and should just write out our current chunk immediately
True == write immediately.
"""
models = fsdb.get_mo... |
Fills a ringbuffer with positions from the most recent games then continually rsync s and updates the buffer until a new model is promoted. Once it detects a new model iit then dumps its contents for training to immediately begin on the next model. | def fill_and_wait_models(bufsize=EXAMPLES_PER_GENERATION,
write_dir=None,
threads=8,
model_window=100,
skip_first_rsync=False):
""" Fills a ringbuffer with positions from the most recent games, then
continually r... |
Explicitly make a golden chunk for a given model model_num ( not necessarily the most recent one ). | def make_chunk_for(output_dir=LOCAL_DIR,
local_dir=LOCAL_DIR,
game_dir=None,
model_num=1,
positions=EXAMPLES_PER_GENERATION,
threads=8,
sampling_frac=0.02):
"""
Explicitly make a golden chunk for a ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.