INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Gate values corresponding to the examples in the per-expert `Tensor`s.
Returns:
a list of `num_experts` one-dimensional `Tensor`s with type `tf.float32`
and shapes `[expert_batch_size_i]` | def expert_to_gates(self):
"""Gate values corresponding to the examples in the per-expert `Tensor`s.
Returns:
a list of `num_experts` one-dimensional `Tensor`s with type `tf.float32`
and shapes `[expert_batch_size_i]`
"""
return tf.split(
self._nonzero_gates, self._part_sizes_te... |
Batch indices corresponding to the examples in the per-expert `Tensor`s.
Returns:
a list of `num_experts` one-dimensional `Tensor`s with type `tf.int64`
and shapes `[expert_batch_size_i]` | def expert_to_batch_indices(self):
"""Batch indices corresponding to the examples in the per-expert `Tensor`s.
Returns:
a list of `num_experts` one-dimensional `Tensor`s with type `tf.int64`
and shapes `[expert_batch_size_i]`
"""
return tf.split(
self._batch_index, self._part_si... |
Create one input Tensor for each expert.
Args:
inp: a list of length num_datashards `Tensor`s with shapes
`[batch_size[d], <extra_input_dims>]`.
Returns:
a list of `num_experts` `Tensor`s with shapes
`[num_examples[i], <extra_input_dims>]`. | def dispatch(self, inp):
"""Create one input Tensor for each expert.
Args:
inp: a list of length num_datashards `Tensor`s with shapes
`[batch_size[d], <extra_input_dims>]`.
Returns:
a list of `num_experts` `Tensor`s with shapes
`[num_examples[i], <extra_input_dims>]`.
"""
... |
Sum together the expert output, multiplied by the corresponding gates.
Args:
expert_out: a list of `num_experts` `Tensor`s, each with shape
`[expert_batch_size_i, <extra_output_dims>]`.
multiply_by_gates: a boolean.
Returns:
a list of num_datashards `Tensor`s with shapes
`[ba... | def combine(self, expert_out, multiply_by_gates=True):
"""Sum together the expert output, multiplied by the corresponding gates.
Args:
expert_out: a list of `num_experts` `Tensor`s, each with shape
`[expert_batch_size_i, <extra_output_dims>]`.
multiply_by_gates: a boolean.
Returns:
... |
Gate values corresponding to the examples in the per-expert `Tensor`s.
Returns:
a list of `num_experts` one-dimensional `Tensor`s of type `tf.float32`. | def expert_to_gates(self):
"""Gate values corresponding to the examples in the per-expert `Tensor`s.
Returns:
a list of `num_experts` one-dimensional `Tensor`s of type `tf.float32`.
"""
return self._ep(
tf.concat,
transpose_list_of_lists(
self._dp(lambda d: d.expert_to... |
Send the inputs to the experts.
Args:
inp: a `Tensor` of shape "[batch, length, depth]`
Returns:
a tensor with shape [batch, num_experts, expert_capacity, depth] | def dispatch(self, inp):
"""Send the inputs to the experts.
Args:
inp: a `Tensor` of shape "[batch, length, depth]`
Returns:
a tensor with shape [batch, num_experts, expert_capacity, depth]
"""
inp = tf.reshape(inp, [self._batch * self._length, -1])
# [batch, num_experts, expert_cap... |
Return the output from the experts.
When one example goes to multiple experts, the outputs are summed.
Args:
x: a Tensor with shape [batch, num_experts, expert_capacity, depth]
Returns:
a `Tensor` with shape `[batch, length, depth] | def combine(self, x):
"""Return the output from the experts.
When one example goes to multiple experts, the outputs are summed.
Args:
x: a Tensor with shape [batch, num_experts, expert_capacity, depth]
Returns:
a `Tensor` with shape `[batch, length, depth]
"""
depth = tf.shape(x)[... |
Factory function for envs. | def make_env(env_type, real_env, sim_env_kwargs):
"""Factory function for envs."""
return {
"real": lambda: real_env.new_like( # pylint: disable=g-long-lambda
batch_size=sim_env_kwargs["batch_size"],
store_rollouts=False,
),
"simulated": lambda: rl_utils.SimulatedBatchGymEnvWi... |
Factory function for Agents. | def make_agent(
agent_type, env, policy_hparams, policy_dir, sampling_temp,
sim_env_kwargs_fn=None, frame_stack_size=None, rollout_agent_type=None,
batch_size=None, inner_batch_size=None, env_type=None, **planner_kwargs
):
"""Factory function for Agents."""
if batch_size is None:
batch_size = env.ba... |
Collects frames from real env for random starts of simulated env. | def collect_frames_for_random_starts(
storage_env, stacked_env, agent, frame_stack_size, random_starts_step_limit,
log_every_steps=None
):
"""Collects frames from real env for random starts of simulated env."""
del frame_stack_size
storage_env.start_new_epoch(0)
tf.logging.info(
"Collecting %d fra... |
Creates an Agent from hparams. | def make_agent_from_hparams(
agent_type, base_env, stacked_env, loop_hparams, policy_hparams,
planner_hparams, model_dir, policy_dir, sampling_temp, video_writers=()
):
"""Creates an Agent from hparams."""
def sim_env_kwargs_fn():
return rl.make_simulated_env_kwargs(
base_env, loop_hparams, batc... |
Returns an out-of-graph eval_fn using the Agent API. | def make_eval_fn_with_agent(
agent_type, eval_mode, planner_hparams, model_dir, log_every_steps=None,
video_writers=(), random_starts_step_limit=None
):
"""Returns an out-of-graph eval_fn using the Agent API."""
def eval_fn(env, loop_hparams, policy_hparams, policy_dir, sampling_temp):
"""Eval function.... |
Evaluates the world model. | def evaluate_world_model(
agent_type, loop_hparams, planner_hparams, model_dir, policy_dir,
random_starts_step_limit, debug_video_path, log_every_steps
):
"""Evaluates the world model."""
if debug_video_path:
debug_video_path = os.path.join(debug_video_path, "0.avi")
storage_env = rl_utils.setup_env(... |
Evaluate. | def evaluate(
loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir,
agent_type, eval_mode, eval_with_learner, log_every_steps, debug_video_path,
num_debug_videos=1, random_starts_step_limit=None,
report_fn=None, report_metric=None
):
"""Evaluate."""
if eval_with_learner:
assert... |
Get game for the given worker (directory) id. | def get_game_for_worker(map_name, directory_id):
"""Get game for the given worker (directory) id."""
if map_name == "v100unfriendly":
games = ["chopper_command", "boxing", "asterix", "seaquest"]
worker_per_game = 5
elif map_name == "human_nice":
games = gym_env.ATARI_GAMES_WITH_HUMAN_SCORE_NICE
wo... |
Given a representation of the board, returns a list of open spaces. | def get_open_spaces(board):
"""Given a representation of the board, returns a list of open spaces."""
open_spaces = []
for i in range(3):
for j in range(3):
if board[i][j] == 0:
open_spaces.append(encode_pos(i, j))
return open_spaces |
Given a representation of the board, returns reward and done. | def get_reward_and_done(board):
"""Given a representation of the board, returns reward and done."""
# Returns (reward, done) where:
# reward: -1 means lost, +1 means win, 0 means draw or continuing.
# done: True if the game is over, i.e. someone won or it is a draw.
# Sum all rows ...
all_sums = [np.sum(bo... |
Hyperparameters for decoding. | def decode_hparams(overrides=""):
"""Hyperparameters for decoding."""
hp = hparam.HParams(
save_images=False,
log_results=True,
extra_length=100,
min_length_ratio=0.0,
batch_size=0,
beam_size=4,
alpha=0.6,
eos_penalty=0.0,
block_size=0,
guess_and_check_top... |
Log inference results. | def log_decode_results(inputs,
outputs,
problem_name,
prediction_idx,
inputs_vocab,
targets_vocab,
targets=None,
save_images=False,
outp... |
Perform decoding from dataset. | def decode_from_dataset(estimator,
problem_name,
hparams,
decode_hp,
decode_to_file=None,
dataset_split=None,
checkpoint_path=None):
"""Perform decoding from dataset."""
tf... |
Decodes once.
Args:
estimator: tf.estimator.Estimator instance. Used to generate encoded
predictions.
problem_name: str. Name of problem.
hparams: HParams instance. HParams for model training.
infer_input_fn: zero-arg function. Input function for estimator.
decode_hp: HParams instance. See ... | def decode_once(estimator,
problem_name,
hparams,
infer_input_fn,
decode_hp,
decode_to_file,
output_dir,
log_results=True,
checkpoint_path=None):
"""Decodes once.
Args:
estimator: tf.... |
Compute predictions on entries in filename and write them out. | def decode_from_file(estimator,
filename,
hparams,
decode_hp,
decode_to_file=None,
checkpoint_path=None):
"""Compute predictions on entries in filename and write them out."""
if not decode_hp.batch_size:
dec... |
Generates decode filename.
Args:
base_filename: A string, base of the decode filename.
problem_name: A string, name of the problem.
decode_hp: HParams for decoding.
Returns:
A string, produced decode filename. | def _decode_filename(base_filename, problem_name, decode_hp):
"""Generates decode filename.
Args:
base_filename: A string, base of the decode filename.
problem_name: A string, name of the problem.
decode_hp: HParams for decoding.
Returns:
A string, produced decode filename.
"""
if decode_hp.... |
Use py_func to yield elements from the given generator. | def make_input_fn_from_generator(gen):
"""Use py_func to yield elements from the given generator."""
first_ex = six.next(gen)
flattened = tf.contrib.framework.nest.flatten(first_ex)
types = [t.dtype for t in flattened]
shapes = [[None] * len(t.shape) for t in flattened]
first_ex_list = [first_ex]
def py_... |
Interactive decoding. | def decode_interactively(estimator, hparams, decode_hp, checkpoint_path=None):
"""Interactive decoding."""
is_image = "image" in hparams.problem.name
is_text2class = isinstance(hparams.problem,
text_problems.Text2ClassProblem)
skip_eos_postprocess = (
is_image or is_text2clas... |
Generator to produce batches of inputs. | def _decode_batch_input_fn(num_decode_batches, sorted_inputs, vocabulary,
batch_size, max_input_size,
task_id=-1, has_input=True):
"""Generator to produce batches of inputs."""
tf.logging.info(" batch %d" % num_decode_batches)
for b in range(num_decode_batches... |
Generator that reads from the terminal and yields "interactive inputs".
Due to temporary limitations in tf.learn, if we don't want to reload the
whole graph, then we are stuck encoding all of the input as one fixed-size
numpy array.
We yield int32 arrays with shape [const_array_size]. The format is:
[num_s... | def _interactive_input_fn(hparams, decode_hp):
"""Generator that reads from the terminal and yields "interactive inputs".
Due to temporary limitations in tf.learn, if we don't want to reload the
whole graph, then we are stuck encoding all of the input as one fixed-size
numpy array.
We yield int32 arrays wit... |
Save frames of the videos into files. | def save_video(video, save_path_template):
"""Save frames of the videos into files."""
try:
from PIL import Image # pylint: disable=g-import-not-at-top
except ImportError as e:
tf.logging.warning(
"Showing and saving an image requires PIL library to be "
"installed: %s", e)
raise NotI... |
Shows an image using matplotlib and saves it. | def show_and_save_image(img, save_path):
"""Shows an image using matplotlib and saves it."""
try:
import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top
except ImportError as e:
tf.logging.warning(
"Showing and saving an image requires matplotlib to be "
"installed: %s", e)... |
Read a file of partial texts to continue.
The purpose of append_space_to_final_punctionation is that SubwordTokenizer
groups punctuation and the ensuing space in the same token. Adding a space
causes the token to be completed.
Args:
filename: a string
delimiter: a string
repeat: an integer - we r... | def _get_language_modeling_inputs(filename,
delimiter="\n",
repeat=1,
append_space_to_final_punctionation=True):
"""Read a file of partial texts to continue.
The purpose of append_space_to_final_punctionation is t... |
Returning inputs sorted according to decreasing length.
This causes inputs of similar lengths to be processed in the same batch,
facilitating early stopping for short sequences.
Longer sequences are sorted first so that if you're going to get OOMs,
you'll see it in the first batch.
Args:
filename: path... | def _get_sorted_inputs(filename, delimiter="\n"):
"""Returning inputs sorted according to decreasing length.
This causes inputs of similar lengths to be processed in the same batch,
facilitating early stopping for short sequences.
Longer sequences are sorted first so that if you're going to get OOMs,
you'll... |
Strips everything after the first <EOS> token, which is normally 1. | def _save_until_eos(ids, skip=False):
"""Strips everything after the first <EOS> token, which is normally 1."""
ids = ids.flatten()
if skip:
return ids
try:
index = list(ids).index(text_encoder.EOS_ID)
return ids[0:index]
except ValueError:
# No EOS_ID: return the array as-is.
return ids |
Convert the interactive input format (see above) to a dictionary.
Args:
feature_map: dict with inputs.
hparams: model hyperparameters
Returns:
a features dictionary, as expected by the decoder. | def _interactive_input_tensor_to_features_dict(feature_map, hparams):
"""Convert the interactive input format (see above) to a dictionary.
Args:
feature_map: dict with inputs.
hparams: model hyperparameters
Returns:
a features dictionary, as expected by the decoder.
"""
inputs = tf.convert_to_te... |
Convert the interactive input format (see above) to a dictionary.
Args:
feature_map: dict with inputs.
hparams: model hyperparameters
Returns:
a features dictionary, as expected by the decoder. | def _decode_input_tensor_to_features_dict(feature_map, hparams):
"""Convert the interactive input format (see above) to a dictionary.
Args:
feature_map: dict with inputs.
hparams: model hyperparameters
Returns:
a features dictionary, as expected by the decoder.
"""
inputs = tf.convert_to_tensor(... |
Run hooks after decodes have run. | def run_postdecode_hooks(decode_hook_args, dataset_split):
"""Run hooks after decodes have run."""
hooks = decode_hook_args.problem.decode_hooks
if not hooks:
return
global_step = latest_checkpoint_step(decode_hook_args.estimator.model_dir)
if global_step is None:
tf.logging.info(
"Skipping de... |
Splits of data to produce and number of output shards for each. | def dataset_splits(self):
"""Splits of data to produce and number of output shards for each."""
return [{
"split": problem.DatasetSplit.TRAIN,
"shards": _TRAIN_SHARDS,
}, {
"split": problem.DatasetSplit.EVAL,
"shards": _DEV_SHARDS,
}] |
Image Transformer decoder with local1D spatial layers. | def local_attention1d_spatial_decoder(x, kv_dim, heads_dim,
feedforward_dim, hparams):
"""Image Transformer decoder with local1D spatial layers."""
batch_dim, length_dim, model_dim = x.shape.dims
blocks_w_dim = mtf.Dimension("blocksw", hparams.block_length)
num_w_blocks_dim... |
Image Transformer decoder with local2D spatial layers. | def local_attention2d_spatial_decoder(x, kv_dim, heads_dim,
feedforward_dim, hparams):
"""Image Transformer decoder with local2D spatial layers."""
batch_dim, length_dim, model_dim = x.shape.dims
blocks_h_dim = mtf.Dimension("blocksh", hparams.block_height)
blocks_w_dim = m... |
Image Transformer decoder with local1D masked layers. | def local_attention1d_masked_decoder(x, kv_dim, heads_dim,
feedforward_dim, hparams):
"""Image Transformer decoder with local1D masked layers."""
print(x)
_, length_dim, model_dim = x.shape.dims
for layer in range(hparams.num_decoder_layers):
layer_name = "decoder_layer_... |
Set of hyperparameters. | def mtf_image_transformer_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.no_data_parallelism = True
hparams.use_fixed_batch_size = True
hparams.batch_size = 1
hparams.max_length = 3072
hparams.hidden_size = 256
hparams.label_smoothing = 0.0
# 8-way model-paralle... |
Catch bugs locally... | def mtf_image_transformer_tiny():
"""Catch bugs locally..."""
hparams = mtf_image_transformer_base()
hparams.hidden_size = 128
hparams.d_ff = 256
hparams.batch_size = 4
hparams.num_encoder_layers = 1
hparams.num_decoder_layers = 4
hparams.num_heads = 4
hparams.attention_key_size = 128
hparams.attent... |
Small single parameters. | def mtf_image_transformer_single():
"""Small single parameters."""
hparams = mtf_image_transformer_tiny()
hparams.mesh_shape = ""
hparams.layout = ""
hparams.hidden_size = 32
hparams.filter_size = 32
hparams.batch_size = 1
hparams.num_encoder_layers = 1
hparams.num_decoder_layers = 1
hparams.num_hea... |
Small single parameters. | def mtf_image_transformer_base_single():
"""Small single parameters."""
hparams = mtf_image_transformer_base()
hparams.num_decoder_layers = 6
hparams.filter_size = 256
hparams.block_length = 128
hparams.mesh_shape = ""
hparams.layout = ""
return hparams |
Small single parameters. | def mtf_image_transformer_tiny_spatial1d():
"""Small single parameters."""
hparams = mtf_image_transformer_tiny()
hparams.num_decoder_layers = 6
hparams.filter_size = 128
hparams.block_height = 8
hparams.block_width = 8
hparams.attention_type = "local1d_spatial"
hparams.mesh_shape = ""
hparams.layout ... |
Data parallel CIFAR parameters. | def mtf_image_transformer_base_cifar():
"""Data parallel CIFAR parameters."""
hparams = mtf_image_transformer_base()
hparams.mesh_shape = "batch:8"
hparams.layout = "batch:batch"
hparams.learning_rate_decay_steps = 13600 # one epoch
hparams.batch_size = 32
hparams.num_heads = 4
hparams.num_decoder_laye... |
Data parallel CIFAR parameters. | def mtf_image_transformer_cifar_4x():
"""Data parallel CIFAR parameters."""
hparams = mtf_image_transformer_base_cifar()
hparams.mesh_shape = "batch:32"
hparams.layout = "batch:batch"
hparams.batch_size = 128
return hparams |
Data parallel CIFAR parameters. | def mtf_image_transformer_cifar_mp_4x():
"""Data parallel CIFAR parameters."""
hparams = mtf_image_transformer_base_cifar()
hparams.mesh_shape = "model:4;batch:8"
hparams.layout = "batch:batch;d_ff:model;heads:model"
hparams.batch_size = 32
hparams.num_heads = 8
hparams.d_ff = 8192
return hparams |
Data parallel CIFAR parameters. | def mtf_image_transformer_base_imagenet():
"""Data parallel CIFAR parameters."""
hparams = mtf_image_transformer_base_cifar()
hparams.mesh_shape = "batch:32"
hparams.layout = "batch:batch"
hparams.batch_size = 128
hparams.d_ff = 2048
hparams.hidden_size = 512
hparams.num_decoder_layers = 12
hparams.le... |
Model parallel ImageNet parameters. | def mtf_image_transformer_base_imagenet_mp():
"""Model parallel ImageNet parameters."""
hparams = mtf_image_transformer_base_imagenet()
hparams.mesh_shape = "model:4;batch:8"
hparams.layout = "batch:batch;d_ff:model;heads:model"
hparams.batch_size = 32
hparams.num_heads = 8
hparams.d_ff = 8192
hparams.l... |
Model parallel ImageNet parameters. | def mtf_image_transformer_base_imagenet_mp128():
"""Model parallel ImageNet parameters."""
hparams = mtf_image_transformer_base_imagenet()
hparams.mesh_shape = "model:8;batch:4"
hparams.layout = "batch:batch;d_ff:model;heads:model"
hparams.batch_size = 8
hparams.img_len = 128
hparams.block_length = 128
... |
Model parallel ImageNet parameters. | def mtf_image_transformer_base_imagenet_mp_sp():
"""Model parallel ImageNet parameters."""
hparams = mtf_image_transformer_base_imagenet_mp128()
hparams.mesh_shape = "model:8;batch:4"
hparams.layout = "batch:batch;d_ff:model;num_wblocks:model"
hparams.batch_size = 8
hparams.img_len = 128
hparams.block_len... |
Model parallel ImageNet parameters. | def mtf_image_transformer_base_imagenet_mp64():
"""Model parallel ImageNet parameters."""
hparams = mtf_image_transformer_base_imagenet()
hparams.mesh_shape = "model:8;batch:4"
hparams.layout = "batch:batch;d_ff:model;heads:model"
hparams.batch_size = 8
hparams.img_len = 64
hparams.num_decoder_layers = 8
... |
Returns a list of degree vectors, one for each input and hidden layer.
A unit with degree d can only receive input from units with degree < d. Output
units always have the same degree as their associated input unit.
Args:
input_dim: Number of inputs.
hidden_dims: list with the number of hidden units per... | def create_degrees(input_dim,
hidden_dims,
input_order='left-to-right',
hidden_order='left-to-right'):
"""Returns a list of degree vectors, one for each input and hidden layer.
A unit with degree d can only receive input from units with degree < d. Output
... |
Returns a list of binary mask matrices respecting autoregressive ordering.
Args:
input_dim: Number of inputs.
hidden_dims: list with the number of hidden units per layer. It does not
include the output layer; those number of units will always be set to
input_dim downstream. Each hidden unit size ... | def create_masks(input_dim,
hidden_dims,
input_order='left-to-right',
hidden_order='left-to-right'):
"""Returns a list of binary mask matrices respecting autoregressive ordering.
Args:
input_dim: Number of inputs.
hidden_dims: list with the number of hidde... |
Performs incomplete Sinkhorn normalization to inputs.
By a theorem by Sinkhorn and Knopp [1], a sufficiently well-behaved matrix
with positive entries can be turned into a doubly-stochastic matrix
(i.e. its rows and columns add up to one) via the succesive row and column
normalization.
-To ensure positivity... | def sinkhorn(inputs, n_iters=20):
"""Performs incomplete Sinkhorn normalization to inputs.
By a theorem by Sinkhorn and Knopp [1], a sufficiently well-behaved matrix
with positive entries can be turned into a doubly-stochastic matrix
(i.e. its rows and columns add up to one) via the succesive row and column
... |
Random variable for f(x), where x ~ p(x) and f is reversible. | def TransformedRandomVariable(random_variable, # pylint: disable=invalid-name
reversible_layer,
name=None,
sample_shape=(),
value=None):
"""Random variable for f(x), where x ~ p(x) and f is reversi... |
Returns log det | dx / dy | = num_events * sum log | scale |. | def log_det_jacobian(self, inputs):
"""Returns log det | dx / dy | = num_events * sum log | scale |."""
del inputs # unused
# Number of events is number of all elements excluding the batch and
# channel dimensions.
num_events = tf.reduce_prod(tf.shape(inputs)[1:-1])
log_det_jacobian = num_event... |
Slice encoder hidden state into block_dim.
Args:
x: Encoder hidden state of shape [-1, hidden_size].
Returns:
Sliced states of shape [-1, num_blocks, block_dim]. | def slice_hidden(self, x):
"""Slice encoder hidden state into block_dim.
Args:
x: Encoder hidden state of shape [-1, hidden_size].
Returns:
Sliced states of shape [-1, num_blocks, block_dim].
"""
x_sliced = tf.reshape(
x, shape=[-1, self.hparams.num_blocks, self.hparams.blo... |
Find the nearest element in means to elements in x.
Args:
x: Batch of encoder continuous latent states sliced/projected into
shape [-1, num_blocks, block_dim].
means: Embedding means of shape.
Returns:
Tensor with nearest element in mean encoded in one-hot notation. | def nearest_neighbor(self, x, means):
"""Find the nearest element in means to elements in x.
Args:
x: Batch of encoder continuous latent states sliced/projected into
shape [-1, num_blocks, block_dim].
means: Embedding means of shape.
Returns:
Tensor with nearest element in... |
Compute nearest neighbors and loss for training the embeddings.
Args:
x: Batch of encoder continuous latent states sliced/projected into
shape
[-1, num_blocks, block_dim].
means: Embedding means.
Returns:
The nearest neighbor in one hot form, the nearest neighbor
... | def embedding_lookup(self, x, means):
"""Compute nearest neighbors and loss for training the embeddings.
Args:
x: Batch of encoder continuous latent states sliced/projected into
shape
[-1, num_blocks, block_dim].
means: Embedding means.
Returns:
The nearest neighbor... |
Turn x_int representing numbers into a bitwise (lower-endian) tensor.
Args:
x_int: Tensor containing integer to be converted into base
notation.
num_bits: Number of bits in the representation.
base: Base of the representation.
Returns:
Corresponding number expressed in ... | def int_to_bit(self, x_int, num_bits, base=2):
"""Turn x_int representing numbers into a bitwise (lower-endian) tensor.
Args:
x_int: Tensor containing integer to be converted into base
notation.
num_bits: Number of bits in the representation.
base: Base of the representation.
... |
Embedding function that takes discrete latent and returns embedding.
Args:
x: Input to the discretization bottleneck.
Returns:
Continuous embedding to be passed on to the decoder.
Raises:
ValueError: For unknown or missing arguments. | def embed(self, x):
"""Embedding function that takes discrete latent and returns embedding.
Args:
x: Input to the discretization bottleneck.
Returns:
Continuous embedding to be passed on to the decoder.
Raises:
ValueError: For unknown or missing arguments.
"""
shape_x =... |
Discretization bottleneck for latent variables.
Args:
x: Input to the discretization bottleneck.
Returns:
Embedding to pass to the decoder, discrete latent, loss, and the
embedding
function.
Raises:
ValueError: If projection_tensors is None for reshape_method
... | def discrete_bottleneck(self, x):
"""Discretization bottleneck for latent variables.
Args:
x: Input to the discretization bottleneck.
Returns:
Embedding to pass to the decoder, discrete latent, loss, and the
embedding
function.
Raises:
ValueError: If projection... |
Switch from Adam to Adafactor, approximating the behavior of Adam.
Some minor things may be different, like epsilon and beta1 correction.
Args:
hparams: model hyperparameters where "adam" in hparams.optimizer | def mimic_adam_with_adafactor(hparams):
"""Switch from Adam to Adafactor, approximating the behavior of Adam.
Some minor things may be different, like epsilon and beta1 correction.
Args:
hparams: model hyperparameters where "adam" in hparams.optimizer
"""
assert "adam" in hparams.optimizer
hparams.opt... |
Old version - Adam. | def afx_adam():
"""Old version - Adam."""
hparams = transformer.transformer_base_v2()
hparams.optimizer_adam_beta1 = 0.9
hparams.optimizer_adam_beta2 = 0.999
hparams.symbol_modality_num_shards = 1
hparams.batch_size = 2048
hparams.optimizer = "adam"
hparams.learning_rate_schedule = (
"constant*rsq... |
Adafactor with recommended learning rate schedule. | def afx_adafactor():
"""Adafactor with recommended learning rate schedule."""
hparams = afx_adam()
hparams.optimizer = "Adafactor"
hparams.learning_rate_schedule = "rsqrt_decay"
hparams.learning_rate_warmup_steps = 10000
return hparams |
Small transformer model with small batch size for fast step times. | def afx_small():
"""Small transformer model with small batch size for fast step times."""
hparams = transformer.transformer_tpu()
hparams.filter_size = 1024
hparams.num_heads = 4
hparams.num_hidden_layers = 3
hparams.batch_size = 512
return hparams |
Emily's model hparams. | def next_frame_emily():
"""Emily's model hparams."""
hparams = sv2p_params.next_frame_sv2p()
hparams.video_num_input_frames = 2
hparams.video_num_target_frames = 10
hparams.learning_rate_constant = 1e-4
seq_length = hparams.video_num_input_frames + hparams.video_num_target_frames
# The latent_loss_multipl... |
Convert a file to examples. | def main(_):
"""Convert a file to examples."""
if FLAGS.subword_text_encoder_filename:
encoder = text_encoder.SubwordTextEncoder(
FLAGS.subword_text_encoder_filename)
elif FLAGS.token_text_encoder_filename:
encoder = text_encoder.TokenTextEncoder(FLAGS.token_text_encoder_filename)
elif FLAGS.byt... |
Return a mix of env and video data fields and decoders. | def example_reading_spec(self):
"""Return a mix of env and video data fields and decoders."""
video_fields, video_decoders = (
video_utils.VideoProblem.example_reading_spec(self))
env_fields, env_decoders = env_problem.EnvProblem.example_reading_spec(self)
# Remove raw observations field since ... |
Transforms time step observations to frames of a video. | def _generate_time_steps(self, trajectory_list):
"""Transforms time step observations to frames of a video."""
for time_step in env_problem.EnvProblem._generate_time_steps(
self, trajectory_list):
# Convert the rendered observations from numpy to png format.
frame_np = np.array(time_step.pop... |
Iterate through lines of file. | def txt_line_iterator(txt_path):
"""Iterate through lines of file."""
with tf.gfile.Open(txt_path) as f:
for line in f:
yield line.strip() |
Yield dicts for Text2TextProblem.generate_samples from lines of files. | def text2text_txt_iterator(source_txt_path, target_txt_path):
"""Yield dicts for Text2TextProblem.generate_samples from lines of files."""
for inputs, targets in zip(
txt_line_iterator(source_txt_path), txt_line_iterator(target_txt_path)):
yield {"inputs": inputs, "targets": targets} |
Yield dicts for Text2TextProblem.generate_samples from lines of files. | def text2text_distill_iterator(source_txt_path, target_txt_path,
distill_txt_path):
"""Yield dicts for Text2TextProblem.generate_samples from lines of files."""
for inputs, targets, dist_targets in zip(
txt_line_iterator(source_txt_path), txt_line_iterator(target_txt_path),
... |
Yield dicts for Text2ClassProblem.generate_samples from lines of files.
Args:
source_txt_path: txt file with record per line.
label_txt_path: txt file with label per line, either as int or str. If
string, must provide class_strs.
class_strs: list<str> of class label names. Must be in correct order ... | def text2class_txt_iterator(source_txt_path, label_txt_path, class_strs=None):
"""Yield dicts for Text2ClassProblem.generate_samples from lines of files.
Args:
source_txt_path: txt file with record per line.
label_txt_path: txt file with label per line, either as int or str. If
string, must provide c... |
Yield dicts for Text2TextProblem.generate_samples from lines of txt_path.
Args:
txt_path: path to txt file with a record per line, source and target
are tab-separated.
Yields:
{"inputs": inputs, "targets": targets} | def text2text_txt_tab_iterator(txt_path):
"""Yield dicts for Text2TextProblem.generate_samples from lines of txt_path.
Args:
txt_path: path to txt file with a record per line, source and target
are tab-separated.
Yields:
{"inputs": inputs, "targets": targets}
"""
for line in txt_line_iterator(... |
Encode Text2Text samples from the generator with the vocab. | def text2text_generate_encoded(sample_generator,
vocab,
targets_vocab=None,
has_inputs=True,
inputs_prefix="",
targets_prefix=""):
"""Encode Text2Text samples from... |
For packed datasets, returns a function to pack examples.
Returns:
None or a function from list of TFRecords to list of TFRecords | def _pack_fn(self):
"""For packed datasets, returns a function to pack examples.
Returns:
None or a function from list of TFRecords to list of TFRecords
"""
if not self.packed_length:
return None
def my_fn(records):
"""Function from list of TFRecords to list of TFRecords."""
... |
Wraps generator with packer if self.packed_length. | def _maybe_pack_examples(self, generator):
"""Wraps generator with packer if self.packed_length."""
if not self.packed_length:
return generator
return generator_utils.pack_examples(
generator,
self.has_inputs,
self.packed_length,
spacing=self.packed_spacing,
cho... |
List of input filepaths for a particular training or dev shard.
Args:
tmp_dir: a string
task_id: an integer less than self.num_shards
Returns:
a list of tuples (filepath, start_pos, num_bytes) | def text_filepaths_for_task(self, tmp_dir, task_id):
"""List of input filepaths for a particular training or dev shard.
Args:
tmp_dir: a string
task_id: an integer less than self.num_shards
Returns:
a list of tuples (filepath, start_pos, num_bytes)
"""
assert task_id >= 0
asse... |
Read text out of an input file.
The default just reads the text, converts to unicode and yields one
unicode string.
Subclasses can override this function in order to preprocess, and can
yield any number of strings.
Args:
filepath: a string
Yields:
unicode strings. | def filepath_to_unicode_strings(self, filepath):
"""Read text out of an input file.
The default just reads the text, converts to unicode and yields one
unicode string.
Subclasses can override this function in order to preprocess, and can
yield any number of strings.
Args:
filepath: a st... |
Read complete text of input files and yield unicode strings.
By default, one unicode string is produced per file, but this is
not guaranteed, since subclasses can override
filepath_to_unicode_strings().
max_chars_per_file and max_chars_total can also be specified, in which
case some strings may be... | def file_generator(self,
filepaths,
max_chars_per_file=None,
max_chars_total=None):
"""Read complete text of input files and yield unicode strings.
By default, one unicode string is produced per file, but this is
not guaranteed, since subclasse... |
Generator for examples.
Args:
encoder: a TextEncoder
tmp_dir: a string
task_id: an integer
Yields:
feature dictionaries | def example_generator(self, encoder, tmp_dir, task_id):
"""Generator for examples.
Args:
encoder: a TextEncoder
tmp_dir: a string
task_id: an integer
Yields:
feature dictionaries
"""
filepaths = self.text_filepaths_for_task(tmp_dir, task_id)
if task_id >= self.num_train_... |
Make sure that the data is prepared and the vocab is generated. | def prepare_to_generate(self, data_dir, tmp_dir):
"""Make sure that the data is prepared and the vocab is generated."""
self.get_or_create_vocab(data_dir, tmp_dir)
self.train_text_filepaths(tmp_dir)
self.dev_text_filepaths(tmp_dir) |
Generates training/dev data.
Args:
data_dir: a string
tmp_dir: a string
task_id: an optional integer
Returns:
shard or shards for which data was generated. | def generate_data(self, data_dir, tmp_dir, task_id=-1):
"""Generates training/dev data.
Args:
data_dir: a string
tmp_dir: a string
task_id: an optional integer
Returns:
shard or shards for which data was generated.
"""
tf.logging.info("generate_data task_id=%s" % task_id)
... |
ResNet convolutional striding block. | def ConvBlock(kernel_size, filters, strides):
"""ResNet convolutional striding block."""
ks = kernel_size
filters1, filters2, filters3 = filters
main = layers.Serial(
layers.Conv(filters1, (1, 1), strides),
layers.BatchNorm(),
layers.Relu(),
layers.Conv(filters2, (ks, ks), padding='SAME'... |
ResNet identical size block. | def IdentityBlock(kernel_size, filters):
"""ResNet identical size block."""
ks = kernel_size
filters1, filters2, filters3 = filters
main = layers.Serial(
layers.Conv(filters1, (1, 1)),
layers.BatchNorm(),
layers.Relu(),
layers.Conv(filters2, (ks, ks), padding='SAME'),
layers.BatchN... |
ResNet.
Args:
hidden_size: the size of the first hidden layer (multiplied later).
num_output_classes: how many classes to distinguish.
mode: whether we are training or evaluating or doing inference.
Returns:
The ResNet model with the given layer and output sizes. | def Resnet50(hidden_size=64, num_output_classes=1001, mode='train'):
"""ResNet.
Args:
hidden_size: the size of the first hidden layer (multiplied later).
num_output_classes: how many classes to distinguish.
mode: whether we are training or evaluating or doing inference.
Returns:
The ResNet model... |
WideResnet convolutational block. | def WideResnetBlock(channels, strides=(1, 1), channel_mismatch=False):
"""WideResnet convolutational block."""
main = layers.Serial(layers.BatchNorm(), layers.Relu(),
layers.Conv(channels, (3, 3), strides, padding='SAME'),
layers.BatchNorm(), layers.Relu(),
... |
WideResnet from https://arxiv.org/pdf/1605.07146.pdf.
Args:
num_blocks: int, number of blocks in a group.
hidden_size: the size of the first hidden layer (multiplied later).
num_output_classes: int, number of classes to distinguish.
mode: is it training or eval.
Returns:
The WideResnet model w... | def WideResnet(num_blocks=3, hidden_size=64, num_output_classes=10,
mode='train'):
"""WideResnet from https://arxiv.org/pdf/1605.07146.pdf.
Args:
num_blocks: int, number of blocks in a group.
hidden_size: the size of the first hidden layer (multiplied later).
num_output_classes: int, num... |
Builds a traditional GRU cell with dense internal transformations.
Gated Recurrent Unit paper: https://arxiv.org/abs/1412.3555
Args:
units: Number of hidden units.
Returns:
A Stax model representing a traditional GRU RNN cell. | def GRUCell(units):
"""Builds a traditional GRU cell with dense internal transformations.
Gated Recurrent Unit paper: https://arxiv.org/abs/1412.3555
Args:
units: Number of hidden units.
Returns:
A Stax model representing a traditional GRU RNN cell.
"""
return GeneralGRUCell(
candidate_tra... |
Builds a convolutional GRU.
Paper: https://arxiv.org/abs/1511.06432.
Args:
units: Number of hidden units
kernel_size: Kernel size for convolution
Returns:
A Stax model representing a GRU cell with convolution transforms. | def ConvGRUCell(units, kernel_size=(3, 3)):
"""Builds a convolutional GRU.
Paper: https://arxiv.org/abs/1511.06432.
Args:
units: Number of hidden units
kernel_size: Kernel size for convolution
Returns:
A Stax model representing a GRU cell with convolution transforms.
"""
def BuildConv():
... |
r"""Parametrized Gated Recurrent Unit (GRU) cell construction.
GRU update equations:
$$ Update gate: u_t = \sigmoid(U' * s_{t-1} + B') $$
$$ Reset gate: r_t = \sigmoid(U'' * s_{t-1} + B'') $$
$$ Candidate memory: c_t = \tanh(U * (r_t \odot s_{t-1}) + B) $$
$$ New State: s_t = u_t \odot s_{t-1} + (1 - u_t) \o... | def GeneralGRUCell(candidate_transform,
memory_transform=combinators.Identity,
gate_nonlinearity=core.Sigmoid,
candidate_nonlinearity=core.Tanh,
dropout_rate_c=0.1,
sigmoid_bias=0.5):
r"""Parametrized Gated Recurrent Unit (... |
Create an attention mask to hide padding and future words. | def MakeTargetMask(target, pad=0):
"""Create an attention mask to hide padding and future words."""
target_mask = (target != pad)[ :, np.newaxis, :]
target_dtype = target_mask.dtype
causal_mask = onp.tril(onp.ones((1, target.shape[-1], target.shape[-1]),
dtype=target_dtype), k=... |
Build masks for this batch.
Args:
source: (batch, source_len) array of integer-coded symbols for inputs
target_in: (batch, batch_len) array of integer-coded symbols for targets
pad: int: the padding symbol used to pad the above
Returns:
Prepared batch of tuple of arrays: source, input-target, shif... | def PreparePairedSequenceBatch(source, target_in, pad=0):
"""Build masks for this batch.
Args:
source: (batch, source_len) array of integer-coded symbols for inputs
target_in: (batch, batch_len) array of integer-coded symbols for targets
pad: int: the padding symbol used to pad the above
Returns:
... |
Helper: create layer norm parameters. | def _layer_norm_new_params(input_shape, rng, epsilon=1e-6): # pylint: disable=invalid-name
"""Helper: create layer norm parameters."""
del rng, epsilon
features = input_shape[-1]
scale = np.ones(features)
bias = np.zeros(features)
return (scale, bias) |
Helper: create positional encoding parameters. | def _positional_encoding_new_params(input_shape, rng, max_len=2048): # pylint: disable=invalid-name
"""Helper: create positional encoding parameters."""
del rng
# Check if we are operating on chunked inputs by checking if the first
# shape is a list/tuple of shapes (otherwise it's an int or numpy array).
is_... |
Implements bare positional encoding. | def PositionalEncoding(x, params, **unused_kwargs):
"""Implements bare positional encoding."""
if not isinstance(x, (list, tuple)): # non-chunked inputs
symbol_size = np.shape(x)[1]
return x + params[:, :symbol_size, :]
# Chunked case: apply to all chunks selecting as much as needed.
offset = 0
resul... |
Core dot product self-attention.
Args:
query: array of representations
key: array of representations
value: array of representations
mask: attention-mask, gates attention
dropout: float: dropout rate
mode: 'eval' or 'train': whether to use dropout
rng: JAX PRNGKey: subkey for disposable u... | def DotProductAttention(query, key, value, mask, dropout, mode, rng):
"""Core dot product self-attention.
Args:
query: array of representations
key: array of representations
value: array of representations
mask: attention-mask, gates attention
dropout: float: dropout rate
mode: 'eval' or 't... |
Pure single-headed self-attention.
Args:
dropout: float: dropout rate
mode: str: 'train' or 'eval'
Returns:
Pure single-headed attention layer. (No Dense transforms on input.) | def PureDotProductAttention(dropout=0.0, mode='train'):
"""Pure single-headed self-attention.
Args:
dropout: float: dropout rate
mode: str: 'train' or 'eval'
Returns:
Pure single-headed attention layer. (No Dense transforms on input.)
"""
def init_fun(_, input_shapes): # pylint: disable=invalid... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.