INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Set the value of an existing hyperparameter. | def set_hparam(self, name, value):
"""Set the value of an existing hyperparameter.
This function verifies that the type of the value matches the type of the
existing hyperparameter.
Args:
name: Name of the hyperparameter.
value: New value of the hyperparameter.
Raises:
KeyError:... |
Removes the hyperparameter with key name. | def del_hparam(self, name):
"""Removes the hyperparameter with key 'name'.
Does nothing if it isn't present.
Args:
name: Name of the hyperparameter.
"""
if hasattr(self, name):
delattr(self, name)
del self._hparam_types[name] |
Override existing hyperparameter values parsing new values from a string. | def parse(self, values):
"""Override existing hyperparameter values, parsing new values from a string.
See parse_values for more detail on the allowed format for values.
Args:
values: String. Comma separated list of `name=value` pairs where 'value'
must follow the syntax described above.
... |
Override existing hyperparameter values parsing new values from a dictionary. | def override_from_dict(self, values_dict):
"""Override existing hyperparameter values, parsing new values from a dictionary.
Args:
values_dict: Dictionary of name:value pairs.
Returns:
The `HParams` instance.
Raises:
KeyError: If a hyperparameter in `values_dict` doesn't exist.
... |
Serializes the hyperparameters into JSON. | def to_json(self, indent=None, separators=None, sort_keys=False):
"""Serializes the hyperparameters into JSON.
Args:
indent: If a non-negative integer, JSON array elements and object members
will be pretty-printed with that indent level. An indent level of 0, or
negative, will only insert... |
Override existing hyperparameter values parsing new values from a json object. | def parse_json(self, values_json):
"""Override existing hyperparameter values, parsing new values from a json object.
Args:
values_json: String containing a json object of name:value pairs.
Returns:
The `HParams` instance.
Raises:
KeyError: If a hyperparameter in `values_json` doesn... |
Return the hyperparameter values as a Python dictionary. | def values(self):
"""Return the hyperparameter values as a Python dictionary.
Returns:
A dictionary with hyperparameter names as keys. The values are the
hyperparameter values.
"""
return {n: getattr(self, n) for n in self._hparam_types.keys()} |
Returns the value of key if it exists else default. | def get(self, key, default=None):
"""Returns the value of `key` if it exists, else `default`."""
if key in self._hparam_types:
# Ensure that default is compatible with the parameter type.
if default is not None:
param_type, is_param_list = self._hparam_types[key]
type_str = 'list<%s>... |
Returns the field name given parameter type and is_list. | def _get_kind_name(param_type, is_list):
"""Returns the field name given parameter type and is_list.
Args:
param_type: Data type of the hparam.
is_list: Whether this is a list.
Returns:
A string representation of the field name.
Raises:
ValueError: If parameter type is not rec... |
Returns the visualizations for query. | def process(self, query):
"""Returns the visualizations for query.
Args:
query: The query to process.
Returns:
A dictionary of results with processing and graph visualizations.
"""
tf.logging.info("Processing new query [%s]" %query)
# Create the new TFDBG hook directory.
hook_... |
Default output directory. | def _default_output_dir():
"""Default output directory."""
try:
dataset_name = gin.query_parameter("inputs.dataset_name")
except ValueError:
dataset_name = "random"
dir_name = "{model_name}_{dataset_name}_{timestamp}".format(
model_name=gin.query_parameter("train.model").configurable.name,
d... |
Setup gin configuration. | def _setup_gin():
"""Setup gin configuration."""
# Imports for configurables
# pylint: disable=g-import-not-at-top,unused-import,g-bad-import-order,reimported,unused-variable
from tensor2tensor.trax import models as _trax_models
from tensor2tensor.trax import optimizers as _trax_opt
# pylint: disable=g-impo... |
Return train and evaluation datasets feature info and supervised keys. | def train_and_eval_dataset(dataset_name, data_dir):
"""Return train and evaluation datasets, feature info and supervised keys.
Args:
dataset_name: a string, the name of the dataset; if it starts with "v1_"
then we'll search T2T Problem registry for it, otherwise we assume it
is a dataset from TFDS ... |
Create an info - like tuple for feature given some shapes and vocab size. | def _make_info(shape_list, num_classes):
"""Create an info-like tuple for feature given some shapes and vocab size."""
feature_info = collections.namedtuple("FeatureInfo", ["shape", "num_classes"])
cur_shape = list(shape_list[0])
# We need to merge the provided shapes, put None where they disagree.
for shape ... |
Select a subset of features from the example dict. | def _select_features(example, feature_list=None):
"""Select a subset of features from the example dict."""
feature_list = feature_list or ["inputs", "targets"]
return {f: example[f] for f in feature_list} |
Return train and evaluation datasets feature info and supervised keys. | def _train_and_eval_dataset_v1(problem_name, data_dir):
"""Return train and evaluation datasets, feature info and supervised keys."""
problem = problems.problem(problem_name)
train_dataset = problem.dataset(tf.estimator.ModeKeys.TRAIN, data_dir)
train_dataset = train_dataset.map(_select_features)
eval_dataset... |
Batching function. | def batch_fn(dataset, training, shapes, target_names,
batch_size=32, eval_batch_size=32, bucket_batch_length=32,
bucket_max_length=256, bucket_min_length=8,
bucket_length_step=1.1, buckets=None):
"""Batching function."""
del target_names
# If bucketing is not specified, chec... |
Shuffle and batch the given dataset. | def shuffle_and_batch_data(dataset, target_names, features_info, training):
"""Shuffle and batch the given dataset."""
def append_targets(example):
"""Append targets to the example dictionary. Needed for Keras."""
if len(target_names) == 1:
return (example, example[target_names[0]])
targets = {}
... |
Compile the model in Keras. | def optimize_fn(model,
optimizer=None,
learning_rate_schedule=None,
loss=None,
metrics=None):
"""Compile the model in Keras."""
learning_rate_schedule = learning_rate_schedule or T2TLearningRateSchedule()
if optimizer:
optimizer = optimizer(learn... |
Train the given model on the given dataset. | def train_fn(data_dir=None, output_dir=None,
model_class=gin.REQUIRED, dataset=gin.REQUIRED,
input_names=None, target_names=None,
train_steps=1000, eval_steps=1, eval_frequency=100):
"""Train the given model on the given dataset.
Args:
data_dir: Directory where the data i... |
Main function to train the given model on the given dataset. | def t2t_train(model_name, dataset_name,
data_dir=None, output_dir=None, config_file=None, config=None):
"""Main function to train the given model on the given dataset.
Args:
model_name: The name of the model to train.
dataset_name: The name of the dataset to train on.
data_dir: Directory ... |
Decode from estimator. Interactive from file or from dataset. | def decode(estimator, hparams, decode_hp):
"""Decode from estimator. Interactive, from file, or from dataset."""
if FLAGS.decode_interactive:
if estimator.config.use_tpu:
raise ValueError("TPU can only decode from dataset.")
decoding.decode_interactively(estimator, hparams, decode_hp,
... |
Score each line in a file and return the scores. | def score_file(filename):
"""Score each line in a file and return the scores."""
# Prepare model.
hparams = create_hparams()
encoders = registry.problem(FLAGS.problem).feature_encoders(FLAGS.data_dir)
has_inputs = "inputs" in encoders
# Prepare features for feeding into the model.
if has_inputs:
inpu... |
Put time dimension on channels in an embedded video. | def time_to_channels(embedded_video):
"""Put time dimension on channels in an embedded video."""
video_shape = common_layers.shape_list(embedded_video)
if len(video_shape) != 5:
raise ValueError("Assuming videos given as tensors in the format "
"[batch, time, height, width, channels] but ... |
Basic autoencoder model. | def autoencoder_basic():
"""Basic autoencoder model."""
hparams = common_hparams.basic_params1()
hparams.optimizer = "adam"
hparams.learning_rate_constant = 0.0002
hparams.learning_rate_warmup_steps = 500
hparams.learning_rate_schedule = "constant * linear_warmup"
hparams.label_smoothing = 0.0
hparams.b... |
Autoregressive autoencoder model. | def autoencoder_autoregressive():
"""Autoregressive autoencoder model."""
hparams = autoencoder_basic()
hparams.add_hparam("autoregressive_forget_base", False)
hparams.add_hparam("autoregressive_mode", "none")
hparams.add_hparam("autoregressive_decode_steps", 0)
hparams.add_hparam("autoregressive_eval_pure_... |
Residual autoencoder model. | def autoencoder_residual():
"""Residual autoencoder model."""
hparams = autoencoder_autoregressive()
hparams.optimizer = "Adafactor"
hparams.clip_grad_norm = 1.0
hparams.learning_rate_constant = 0.5
hparams.learning_rate_warmup_steps = 500
hparams.learning_rate_schedule = "constant * linear_warmup * rsqrt... |
Residual autoencoder model for text. | def autoencoder_residual_text():
"""Residual autoencoder model for text."""
hparams = autoencoder_residual()
hparams.bottleneck_bits = 32
hparams.batch_size = 1024
hparams.hidden_size = 64
hparams.max_hidden_size = 512
hparams.bottleneck_noise = 0.0
hparams.bottom = {
"inputs": modalities.identity... |
Basic autoencoder model. | def autoencoder_basic_discrete():
"""Basic autoencoder model."""
hparams = autoencoder_autoregressive()
hparams.num_hidden_layers = 5
hparams.hidden_size = 64
hparams.bottleneck_bits = 1024
hparams.bottleneck_noise = 0.1
hparams.add_hparam("discretize_warmup_steps", 16000)
return hparams |
Residual discrete autoencoder model. | def autoencoder_residual_discrete():
"""Residual discrete autoencoder model."""
hparams = autoencoder_residual()
hparams.bottleneck_bits = 1024
hparams.bottleneck_noise = 0.05
hparams.add_hparam("discretize_warmup_steps", 16000)
hparams.add_hparam("bottleneck_kind", "tanh_discrete")
hparams.add_hparam("is... |
Residual discrete autoencoder model big version. | def autoencoder_residual_discrete_big():
"""Residual discrete autoencoder model, big version."""
hparams = autoencoder_residual_discrete()
hparams.hidden_size = 128
hparams.max_hidden_size = 4096
hparams.bottleneck_noise = 0.1
hparams.residual_dropout = 0.4
return hparams |
Ordered discrete autoencoder model. | def autoencoder_ordered_discrete():
"""Ordered discrete autoencoder model."""
hparams = autoencoder_residual_discrete()
hparams.bottleneck_noise = 0.05 # Use 0.8 for ordered.
hparams.gan_loss_factor = 0.05
hparams.add_hparam("unordered", True)
return hparams |
Ordered discrete autoencoder model. | def autoencoder_ordered_discrete_image64():
"""Ordered discrete autoencoder model."""
hparams = autoencoder_ordered_discrete()
hparams.batch_size = 32
hparams.num_hidden_layers = 6
hparams.bottleneck_warmup_steps *= 2
hparams.gan_codes_warmup_steps *= 2
return hparams |
Ordered discrete autoencoder model for text. | def autoencoder_ordered_text():
"""Ordered discrete autoencoder model for text."""
hparams = autoencoder_ordered_discrete()
hparams.bottleneck_bits = 1024
hparams.bottleneck_shared_bits = 1024-64
hparams.bottleneck_shared_bits_start_warmup = 75000
hparams.bottleneck_shared_bits_stop_warmup = 275000
hparam... |
Ordered discrete autoencoder model for text small version. | def autoencoder_ordered_text_small():
"""Ordered discrete autoencoder model for text, small version."""
hparams = autoencoder_ordered_text()
hparams.bottleneck_bits = 32
hparams.num_hidden_layers = 3
hparams.hidden_size = 64
hparams.max_hidden_size = 512
hparams.bottleneck_noise = 0.0
hparams.autoregres... |
Discrete autoencoder model for compressing pong frames. | def autoencoder_discrete_pong():
"""Discrete autoencoder model for compressing pong frames."""
hparams = autoencoder_ordered_discrete()
hparams.num_hidden_layers = 3
hparams.bottleneck_bits = 24
hparams.batch_size = 2
hparams.gan_loss_factor = 0.01
hparams.bottleneck_l2_factor = 0.001
hparams.add_hparam... |
Discrete autoencoder model for compressing pong frames for testing. | def autoencoder_discrete_tiny():
"""Discrete autoencoder model for compressing pong frames for testing."""
hparams = autoencoder_ordered_discrete()
hparams.num_hidden_layers = 2
hparams.bottleneck_bits = 24
hparams.batch_size = 2
hparams.gan_loss_factor = 0.
hparams.bottleneck_l2_factor = 0.001
hparams.... |
Discrete autoencoder model for compressing cifar. | def autoencoder_discrete_cifar():
"""Discrete autoencoder model for compressing cifar."""
hparams = autoencoder_ordered_discrete()
hparams.bottleneck_noise = 0.0
hparams.bottleneck_bits = 90
hparams.num_hidden_layers = 2
hparams.hidden_size = 256
hparams.num_residual_layers = 4
hparams.batch_size = 32
... |
Tuning grid of the main autoencoder params. | def autoencoder_range(rhp):
"""Tuning grid of the main autoencoder params."""
rhp.set_float("dropout", 0.01, 0.3)
rhp.set_float("gan_loss_factor", 0.01, 0.1)
rhp.set_float("bottleneck_l2_factor", 0.001, 0.1, scale=rhp.LOG_SCALE)
rhp.set_discrete("bottleneck_warmup_steps", [200, 2000])
rhp.set_float("gumbel_... |
A stack of self attention layers. | def image_encoder(image_feat,
hparams,
name="image_encoder",
save_weights_to=None,
make_image_summary=True):
"""A stack of self attention layers."""
x = image_feat
with tf.variable_scope(name):
for layer in range(hparams.num_encoder_laye... |
Question encoder run LSTM encoder and get the last output as encoding. | def question_encoder(question, hparams, name="encoder"):
"""Question encoder, run LSTM encoder and get the last output as encoding."""
with tf.variable_scope(name, "encoder", values=[question]):
question = common_layers.flatten4d3d(question)
padding = common_attention.embedding_to_padding(question)
leng... |
Attention on image feature with question as query. | def attn(image_feat, query, hparams, name="attn"):
"""Attention on image feature with question as query."""
with tf.variable_scope(name, "attn", values=[image_feat, query]):
attn_dim = hparams.attn_dim
num_glimps = hparams.num_glimps
num_channels = common_layers.shape_list(image_feat)[-1]
if len(com... |
Multi layer perceptron with dropout and relu activation. | def mlp(feature, hparams, name="mlp"):
"""Multi layer perceptron with dropout and relu activation."""
with tf.variable_scope(name, "mlp", values=[feature]):
num_mlp_layers = hparams.num_mlp_layers
mlp_dim = hparams.mlp_dim
for _ in range(num_mlp_layers):
feature = common_layers.dense(feature, mlp_... |
VQA attention baseline hparams. | def vqa_attention_base():
"""VQA attention baseline hparams."""
hparams = common_hparams.basic_params1()
hparams.batch_size = 128
hparams.use_fixed_batch_size = True,
hparams.optimizer = "adam"
hparams.optimizer_adam_beta1 = 0.9
hparams.optimizer_adam_beta2 = 0.999
hparams.optimizer_adam_epsilon = 1e-8
... |
Small range of hyperparameters. | def vqa_attention_base_range(rhp):
"""Small range of hyperparameters."""
# After starting from base, set intervals for some parameters.
rhp.set_float("learning_rate", 0.1, 1.0, scale=rhp.LOG_SCALE)
rhp.set_float("clip_grad_norm", 0.1, 10, scale=rhp.LOG_SCALE)
rhp.set_discrete("batch_size", [128, 256, 512, 102... |
Append ( step value ) pair to history for the given mode and metric. | def append(self, mode, metric, step, value):
"""Append (step, value) pair to history for the given mode and metric."""
if mode not in self._values:
self._values[mode] = collections.defaultdict(list)
self._values[mode][metric].append((step, value)) |
Get the history for the given metric and mode. | def get(self, mode, metric):
"""Get the history for the given metric and mode."""
if mode not in self._values:
logging.info("Metric %s not found for mode %s", metric, mode)
return []
return list(self._values[mode][metric]) |
Metrics available for a given mode. | def metrics_for_mode(self, mode):
"""Metrics available for a given mode."""
if mode not in self._values:
logging.info("Mode %s not found", mode)
return []
return sorted(list(self._values[mode].keys())) |
Performs a batch normalization followed by a ReLU. | def batch_norm_relu(inputs,
is_training,
relu=True,
init_zero=False,
data_format="channels_first"):
"""Performs a batch normalization followed by a ReLU.
Args:
inputs: `Tensor` of shape `[batch, channels, ...]`.
is_training: `b... |
Strided 2 - D convolution with explicit padding. | def conv2d_fixed_padding(inputs,
filters,
kernel_size,
strides,
data_format="channels_first",
use_td=False,
targeting_rate=None,
keep_prob=None,
... |
Standard building block for residual networks with BN before convolutions. | def residual_block(inputs,
filters,
is_training,
projection_shortcut,
strides,
final_block,
data_format="channels_first",
use_td=False,
targeting_rate=None,
... |
Bottleneck block variant for residual networks with BN after convolutions. | def bottleneck_block(inputs,
filters,
is_training,
projection_shortcut,
strides,
final_block,
data_format="channels_first",
use_td=False,
targeting_rate... |
Creates one layer of blocks for the ResNet model. | def block_layer(inputs,
filters,
block_fn,
blocks,
strides,
is_training,
name,
data_format="channels_first",
use_td=False,
targeting_rate=None,
keep_prob=None):... |
Resnet model. | def resnet_v2(inputs,
block_fn,
layer_blocks,
filters,
data_format="channels_first",
is_training=False,
is_cifar=False,
use_td=False,
targeting_rate=None,
keep_prob=None):
"""Resnet model.
... |
Set of hyperparameters. | def resnet_imagenet_34_td_weight_05_05():
"""Set of hyperparameters."""
hp = resnet_imagenet_34()
hp.use_td = "weight"
hp.targeting_rate = 0.5
hp.keep_prob = 0.5
return hp |
Set of hyperparameters. | def resnet_imagenet_34_td_unit_05_05():
"""Set of hyperparameters."""
hp = resnet_imagenet_34()
hp.use_td = "unit"
hp.targeting_rate = 0.5
hp.keep_prob = 0.5
return hp |
Set of hyperparameters. | def resnet_imagenet_34_td_unit_no_drop():
"""Set of hyperparameters."""
hp = resnet_imagenet_34()
hp.use_td = "unit"
hp.targeting_rate = 0.0
hp.keep_prob = 1.0
return hp |
Set of hyperparameters. | def resnet_cifar_15():
"""Set of hyperparameters."""
hp = resnet_base()
hp.block_fn = "residual"
hp.is_cifar = True
hp.layer_sizes = [2, 2, 2]
hp.filter_sizes = [16, 32, 64, 128]
return hp |
Returns the length of the Longest Common Subsequence between two seqs. | def _len_lcs(x, y):
"""Returns the length of the Longest Common Subsequence between two seqs.
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
x: sequence of words
y: sequence of words
Returns
integer: Length of LCS between x and y
"""
table = _lcs(x, y)
n, m =... |
Computes the length of the LCS between two seqs. | def _lcs(x, y):
"""Computes the length of the LCS between two seqs.
The implementation below uses a DP programming algorithm and runs
in O(nm) time where n = len(x) and m = len(y).
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
x: collection of words
y: collection of ... |
Computes ROUGE - L ( sentence level ) of two collections of sentences. | def rouge_l_sentence_level(eval_sentences, ref_sentences):
"""Computes ROUGE-L (sentence level) of two collections of sentences.
Source: https://www.microsoft.com/en-us/research/publication/
rouge-a-package-for-automatic-evaluation-of-summaries/
Calculated according to:
R_lcs = LCS(X,Y)/m
P_lcs = LCS(X,Y)... |
ROUGE scores computation between labels and predictions. | def rouge_l_fscore(predictions, labels, **unused_kwargs):
"""ROUGE scores computation between labels and predictions.
This is an approximate ROUGE scoring method since we do not glue word pieces
or decode the ids and tokenize the output.
Args:
predictions: tensor, model predictions
labels: tensor, gol... |
Calculates n - grams. | def _get_ngrams(n, text):
"""Calculates n-grams.
Args:
n: which n-grams to calculate
text: An array of tokens
Returns:
A set of n-grams
"""
ngram_set = set()
text_length = len(text)
max_index_ngram_start = text_length - n
for i in range(max_index_ngram_start + 1):
ngram_set.add(tuple(t... |
ROUGE - 2 F1 score computation between labels and predictions. | def rouge_2_fscore(predictions, labels, **unused_kwargs):
"""ROUGE-2 F1 score computation between labels and predictions.
This is an approximate ROUGE scoring method since we do not glue word pieces
or decode the ids and tokenize the output.
Args:
predictions: tensor, model predictions
labels: tensor,... |
Normalize the examples from different tasks so they can be merged. | def normalize_example_nlp(task, example, is_infer, vocab_type, vocab_offset,
max_input_length, max_target_length,
fixed_train_length):
"""Normalize the examples from different tasks so they can be merged.
This function is specific to NLP tasks and normalizes them... |
A list of examples to a dataset containing mixed examples. | def flatten_zip_dataset(*args):
"""A list of examples to a dataset containing mixed examples.
Given a list of `n` dataset examples, flatten them by converting
each element into a dataset and concatenating them to convert into a
single dataset.
Args:
*args: A list containing one example each from `n` dif... |
Multiproblem loss function. | def aggregate_task_losses(hparams,
problem_hparams,
logits,
feature_name,
feature):
"""Multiproblem loss function."""
# If no reweighting, we want the default loss to mimic the LM loss.
if not hparams.multipro... |
LM loss for multiproblems. | def aggregate_task_lm_losses(hparams,
problem_hparams,
logits,
feature_name,
feature):
"""LM loss for multiproblems."""
summaries = []
vocab_size = problem_hparams.vocab_size[feature_name]
if voca... |
Normalize the examples from different tasks so they can be merged. | def normalize_example(self, task, example, encoder, hparams, is_infer):
"""Normalize the examples from different tasks so they can be merged."""
# Here we use the default function for NLP tasks that makes everything
# a part of "targets" feature. Override in your subclasses for other uses.
vocab_offset ... |
Generate task_ids for each problem. | def update_task_ids(self, encoder_vocab_size):
"""Generate task_ids for each problem.
These ids correspond to the index of the task in the task_list.
Args:
encoder_vocab_size: the size of the vocab which is used to compute
the index offset.
"""
for idx, task in enumerate(self.task_li... |
Compute the maximum number of classes any subtask has. | def get_max_num_classes(self):
"""Compute the maximum number of classes any subtask has.
This is useful for modifying the size of the softmax to include the output
labels for the classification tasks. Currently, labels from different tasks
are overloaded.
Returns:
num: Highest number of outp... |
Called prior to self - attention to incorporate memory items. | def pre_attention(self, segment, query_antecedent, memory_antecedent, bias):
"""Called prior to self-attention, to incorporate memory items.
Args:
segment: an integer Tensor with shape [batch]
query_antecedent: a Tensor with shape [batch, length_q, channels]
memory_antecedent: must be None. A... |
Called prior to self - attention to incorporate memory items. | def pre_attention(self, segment, query_antecedent, memory_antecedent, bias):
"""Called prior to self-attention, to incorporate memory items.
Args:
segment: an integer Tensor with shape [batch]
query_antecedent: a Tensor with shape [batch, length_q, channels]
memory_antecedent: must be None. A... |
Called after self - attention. The memory can be updated here. | def post_attention(self, token, x):
"""Called after self-attention. The memory can be updated here.
Args:
token: Data returned by pre_attention, which can be used to carry over
state related to the current memory operation.
x: a Tensor of data after self-attention and feed-forward
Retur... |
Compute the safe norm. | def _norm(self, x):
"""Compute the safe norm."""
return tf.sqrt(tf.reduce_sum(tf.square(x), keepdims=True, axis=-1) + 1e-7) |
Address the memory based on content similarity. | def _address_content(self, x):
"""Address the memory based on content similarity.
Args:
x: a tensor in the shape of [batch_size, length, depth].
Returns:
the logits for each memory entry [batch_size, length, memory_size].
"""
mem_keys = tf.layers.dense(self.mem_vals, self.key_depth,
... |
Read from the memory. | def read(self, x):
"""Read from the memory.
An external component can use the results via a simple MLP,
e.g., fn(x W_x + retrieved_mem W_m).
Args:
x: a tensor in the shape of [batch_size, length, depth].
Returns:
access_logits: the logits for accessing the memory in shape of
... |
Write to the memory based on a combination of similarity and least used. | def write(self, x, access_logits):
"""Write to the memory based on a combination of similarity and least used.
Based on arXiv:1607.00036v2 [cs.LG].
Args:
x: a tensor in the shape of [batch_size, length, depth].
access_logits: the logits for accessing the memory.
Returns:
the update o... |
Reset the entries in the memory. | def reset(self, entries_to_reset):
"""Reset the entries in the memory.
Args:
entries_to_reset: a 1D tensor.
Returns:
the reset op.
"""
num_updates = tf.size(entries_to_reset)
update_vals = tf.scatter_update(
self.mem_vals, entries_to_reset,
tf.tile(tf.expand_dims(
... |
Called prior to self - attention to incorporate memory items. | def pre_attention(self, segment_number, query_antecedent,
memory_antecedent, bias):
"""Called prior to self-attention, to incorporate memory items.
Args:
segment_number: an integer Tensor with shape [batch]
query_antecedent: a Tensor with shape [batch, length_q, channels]
... |
Called after self - attention. The memory can be updated here. | def post_attention(self, token, x):
"""Called after self-attention. The memory can be updated here.
Args:
token: Data returned by pre_attention, which can be used to carry over
state related to the current memory operation.
x: a Tensor of data after self-attention and feed-forward
Retur... |
Define the training setup. | def _define_train(
train_env,
ppo_hparams,
eval_env_fn=None,
sampling_temp=1.0,
**collect_kwargs
):
"""Define the training setup."""
memory, collect_summary, train_initialization = (
_define_collect(
train_env,
ppo_hparams,
"ppo_train",
eval_phase=Fa... |
Train. | def _run_train(ppo_hparams,
event_dir,
model_dir,
restarter,
train_summary_op,
eval_summary_op,
initializers,
report_fn=None,
model_save_fn=None):
"""Train."""
summary_writer = tf.summary.FileWrit... |
Metadata for rollouts. | def _rollout_metadata(batch_env):
"""Metadata for rollouts."""
batch_env_shape = batch_env.observ.get_shape().as_list()
batch_size = [batch_env_shape[0]]
shapes_types_names = [
# TODO(piotrmilos): possibly retrieve the observation type for batch_env
(batch_size + batch_env_shape[1:], batch_env.obser... |
Collect trajectories. | def _define_collect(batch_env, ppo_hparams, scope, frame_stack_size, eval_phase,
sampling_temp, force_beginning_resets):
"""Collect trajectories.
Args:
batch_env: Batch environment.
ppo_hparams: PPO hparams, defined in tensor2tensor.models.research.rl.
scope: var scope.
frame_st... |
Deconvolution layer. | def deconv2d(
input_, output_shape, k_h, k_w, d_h, d_w, stddev=0.02, name="deconv2d"):
"""Deconvolution layer."""
with tf.variable_scope(name):
w = tf.get_variable(
"w", [k_h, k_w, output_shape[-1], input_.get_shape()[-1]],
initializer=tf.random_normal_initializer(stddev=stddev))
deconv ... |
Basic parameters for a vanilla_gan. | def sliced_gan():
"""Basic parameters for a vanilla_gan."""
hparams = common_hparams.basic_params1()
hparams.optimizer = "adam"
hparams.learning_rate_constant = 0.0002
hparams.learning_rate_warmup_steps = 500
hparams.learning_rate_schedule = "constant * linear_warmup"
hparams.label_smoothing = 0.0
hpara... |
Discriminator architecture based on InfoGAN. | def discriminator(self, x, is_training, reuse=False):
"""Discriminator architecture based on InfoGAN.
Args:
x: input images, shape [bs, h, w, channels]
is_training: boolean, are we in train or eval model.
reuse: boolean, should params be re-used.
Returns:
out_logit: the output logi... |
Generator outputting image in [ 0 1 ]. | def generator(self, z, is_training, out_shape):
"""Generator outputting image in [0, 1]."""
hparams = self.hparams
height, width, c_dim = out_shape
batch_size = hparams.batch_size
with tf.variable_scope(
"generator",
initializer=tf.random_normal_initializer(stddev=0.02)):
net =... |
Body of the model. | def body(self, features):
"""Body of the model.
Args:
features: a dictionary with the tensors.
Returns:
A pair (predictions, losses) where predictions is the generated image
and losses is a dictionary of losses (that get added for the final loss).
"""
features["targets"] = featur... |
Make Inputs for built - in datasets. | def inputs(num_devices, dataset_name, data_dir=None, input_name=None,
num_chunks=0, append_targets=False):
"""Make Inputs for built-in datasets.
Args:
num_devices: how many devices to build the inputs for.
dataset_name: a TFDS or T2T dataset name. If it's a T2T dataset name, prefix
with "t... |
Make random Inputs for debugging. | def random_inputs(
num_devices,
input_shape=gin.REQUIRED, input_dtype=np.int32, input_range=(0, 255),
output_shape=gin.REQUIRED, output_dtype=np.int32, output_range=(0, 9)):
"""Make random Inputs for debugging.
Args:
num_devices: how many devices to build the inputs for.
input_shape: the shape ... |
Takes a tf. Dataset and creates a numpy stream of ready batches. | def dataset_to_stream(dataset, input_name, num_chunks=0, append_targets=False):
"""Takes a tf.Dataset and creates a numpy stream of ready batches."""
for example in tfds.as_numpy(dataset):
inp, out = example[0][input_name], example[1]
if len(out.shape) > 1 and out.shape[-1] == 1:
out = np.squeeze(out,... |
Return train and evaluation datasets feature info and supervised keys. | def _train_and_eval_dataset_v1(problem_name, data_dir):
"""Return train and evaluation datasets, feature info and supervised keys."""
assert not tf.executing_eagerly(), "tf.eager mode must be turned off."
problem = t2t_problems.problem(problem_name)
train_dataset = problem.dataset(tf.estimator.ModeKeys.TRAIN, d... |
Batching function. | def batch_fun(dataset, training, shapes, target_names, num_devices,
batch_size_per_device=32, batch_size=None, eval_batch_size=32,
bucket_length=32, buckets=None,
batch_shuffle_size=128, max_eval_length=None):
"""Batching function."""
del target_names
# Batch size is batc... |
Preprocessing for LM1B: filter out targets exceeding maximum length. | def lm1b_preprocess(dataset, training,
max_target_length=-1, max_eval_target_length=-1):
"""Preprocessing for LM1B: filter out targets exceeding maximum length."""
def target_right_length(_, target):
return tf.less(tf.shape(target)[0], max_target_length + 1)
def eval_target_right_length(... |
Shuffle and batch the given dataset. | def shuffle_and_batch_data(dataset,
target_names,
features_info,
training,
num_devices,
shuffle_buffer_size=1024,
preprocess_fun=no_preprocess):
"""Shuffle ... |
Return train and eval batches with input name and shape. | def _train_and_eval_batches(dataset, data_dir, input_name, num_devices):
"""Return train and eval batches with input name and shape."""
(train_data, eval_data, features_info, keys) = train_and_eval_dataset(
dataset, data_dir)
input_names, target_names = keys[0], keys[1]
train_batches = shuffle_and_batch_d... |
Returns a Dataset that samples records from one or more Datasets. | def get_multi_dataset(datasets, pmf=None):
"""Returns a Dataset that samples records from one or more Datasets.
Args:
datasets: A list of one or more Dataset objects to sample from.
pmf: A tensor of shape [len(datasets)], the probabilities to sample each
dataset with. This tensor is often constructed... |
Computes the pmf of a schedule given the global_step. | def get_schedule_distribution(schedule, global_step=None):
"""Computes the pmf of a schedule given the global_step.
Args:
schedule: A schedule tuple, see encode_schedule for details.
global_step: A scalar tensor, the step to query the schedule.
Returns:
A 1-D tensor of probs, the sampling distributi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.