Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def next_frame_basic_recurrent():
hparams = basic_stochastic.next_frame_basic_stochastic_discrete()
hparams.filter_double_steps = 2
hparams.hidden_size = 64
hparams.video_num_input_frames = 4
hparams.video_num_target_frames = 4
hparams.concat_internal_states =... | [
"Basic 2-frame recurrent model with stochastic tower."
] |
Please provide a description of the function:def create_teacher_experiment(run_config, hparams, argv):
tf.logging.info("training teacher")
tf.logging.set_verbosity(tf.logging.INFO)
trainer_lib.set_random_seed(FLAGS.random_seed)
usr_dir.import_usr_dir(FLAGS.t2t_usr_dir)
t2t_trainer.maybe_log_registry_and_ex... | [
"Creates experiment function."
] |
Please provide a description of the function:def tabbed_parsing_token_generator(data_dir, tmp_dir, train, prefix,
source_vocab_size, target_vocab_size):
filename = "parsing_{0}.pairs".format("train" if train else "dev")
source_vocab = generator_utils.get_or_generate_tabbed_voca... | [
"Generate source and target data from a single file."
] |
Please provide a description of the function:def tabbed_parsing_character_generator(tmp_dir, train):
character_vocab = text_encoder.ByteTextEncoder()
filename = "parsing_{0}.pairs".format("train" if train else "dev")
pair_filepath = os.path.join(tmp_dir, filename)
return text_problems.text2text_generate_enco... | [
"Generate source and target data from a single file."
] |
Please provide a description of the function:def _make_list(predictions, targets):
# Our models sometimes return predictions in lists, make it a list always.
# TODO(lukaszkaiser): make abstractions for nested structures and refactor.
if not isinstance(predictions, (list, tuple)):
if isinstance(targets, (l... | [
"Helper: make predictions and targets lists, check they match on length."
] |
Please provide a description of the function:def masked_mean(inputs, targets, mask_id=None):
inputs = [x.astype(np.float32) for x in inputs]
# We assume all elements in the list contribute equally.
# TODO(lukaszkaiser): remove this assumption (e.g., when masks differ).
length = len(inputs)
if mask_id is No... | [
"Mean of the inputs but counting only those where targets != mask_id."
] |
Please provide a description of the function:def accuracy(batch, model_predictions):
_, targets = batch
model_predictions, targets = _make_list(model_predictions, targets)
correct = []
for (prediction, target) in zip(model_predictions, targets):
predicted_class = np.argmax(prediction, axis=-1)
correc... | [
"Calculate accuracy."
] |
Please provide a description of the function:def neg_log_perplexity(batch, model_predictions):
_, targets = batch
model_predictions, targets = _make_list(model_predictions, targets)
xent = []
for (prediction, target) in zip(model_predictions, targets):
hot_target = layers.one_hot(target, prediction.shape... | [
"Calculate negative log perplexity."
] |
Please provide a description of the function:def loss(params, batch, model_predict, rng):
inputs, targets = batch
predictions = model_predict(inputs, params, rng=rng)
predictions, targets = _make_list(predictions, targets)
xent = []
for (pred, target) in zip(predictions, targets):
xent.append(np.sum(pr... | [
"Calculate loss."
] |
Please provide a description of the function:def restore_state(output_dir):
params_file = os.path.join(output_dir, "model.pkl")
if not gfile.exists(params_file):
return State(step=None, params=None, history=trax_history.History())
with gfile.GFile(params_file, "rb") as f:
(params, step, history) = pic... | [
"Restore State."
] |
Please provide a description of the function:def save_state(state, output_dir, keep=False):
params_file = os.path.join(output_dir, "model.pkl")
with gfile.GFile(params_file, "wb") as f:
pickle.dump((state.params, state.step, state.history), f)
if keep:
params_file = os.path.join(output_dir, "model_{}.p... | [
"Save State and optionally gin config."
] |
Please provide a description of the function:def evaluate_train_and_eval(step, inputs, predict_fun, eval_steps, rng,
train_sw=None, eval_sw=None, history=None):
step_log(step, "Evaluation")
train_metrics, eval_metrics = [
evaluate( # pylint: disable=g-complex-comprehension
... | [
"Evalaute on train and eval data, and log metrics."
] |
Please provide a description of the function:def evaluate(inputs_stream, predict_fun, metric_funs, rng):
metrics = collections.defaultdict(float)
count = 0
for inp in inputs_stream:
count += 1
rng, subrng = jax_random.split(rng)
preds = predict_fun(inp[0], rng=subrng)
for m, f in six.iteritems(... | [
"Evaluate.\n\n Args:\n inputs_stream: iterable of inputs to evaluate on.\n predict_fun: function from inputs to predictions. params should already be\n partially applied.\n metric_funs: dict from metric name to metric function, which takes inputs\n and predictions and returns a scalar metric val... |
Please provide a description of the function:def log_metrics(metrics, summ_writer, log_prefix, step, history=None):
rjust_len = max([len(name) for name in metrics])
for name, value in six.iteritems(metrics):
step_log(step, "%s %s | % .8f" % (
log_prefix.ljust(5), name.rjust(rjust_len), value))
fu... | [
"Log metrics to summary writer and history."
] |
Please provide a description of the function:def get_random_number_generator_and_set_seed(seed=None):
random.seed(seed)
# While python random accepts None as seed and uses time/os seed then,
# some other functions expect integers so we create one here.
if seed is None:
seed = random.randint(0, 2**31 - 1)... | [
"Get a JAX random number generator and set random seed everywhere."
] |
Please provide a description of the function:def epochs(steps=None, epoch_steps=1):
try:
iter(epoch_steps)
except TypeError:
epoch_steps = itertools.repeat(epoch_steps)
step = 0
for epoch, epoch_steps in enumerate(epoch_steps):
epoch_steps = min(epoch_steps, steps - step)
yield (epoch + 1, e... | [
"Iterator over epochs until steps is reached. 1-indexed.\n\n Args:\n steps: int, total number of steps. Infinite if None.\n epoch_steps: int, number of steps per epoch. Can also be an iterable<int> to\n enable variable length epochs.\n\n Yields:\n (epoch: int, epoch id, epoch_steps: int, number of s... |
Please provide a description of the function:def _jit_predict_fun(model_predict, num_devices):
def predict(x, params=(), rng=None):
# On one device, jit and run.
if num_devices == 1:
return backend.jit(model_predict)(x, params, rng=rng)
# Multi-devices, pmap and run.
@functools.partial(... | [
"Use jit on model_predict if required.",
"Predict function jited and parallelized as requested."
] |
Please provide a description of the function:def _jit_update_fun(predict_fun, loss_fun, optimizer, lr_fun, num_devices):
if num_devices == 1: # TODO(lukaszkaiser): remove branch when not needed.
def single_update(i, opt_state, batch, rng):
rng, subrng = jax_random.split(rng[0])
_, opt_update = opt... | [
"Get jit-ed update function for loss, optimizer, learning rate function.",
"This is a multi-device version of the update function above."
] |
Please provide a description of the function:def _reshape_by_device_single(x, num_devices):
x_shape = list(x.shape)
batch_size = x_shape[0]
batch_size_per_device = batch_size // num_devices
# We require that num_devices divides batch_size evenly.
if batch_size_per_device * num_devices != batch_size:
lo... | [
"Reshape x into a shape [num_devices, ...]."
] |
Please provide a description of the function:def reshape_by_device(x, num_devices):
return layers.nested_map(
x, lambda x: _reshape_by_device_single(x, num_devices)) | [
"Reshape possibly nested x into a shape [num_devices, ...]."
] |
Please provide a description of the function:def train(output_dir,
model=gin.REQUIRED,
loss_fun=loss,
inputs=trax_inputs.inputs,
optimizer=trax_opt.adam,
lr_schedule=lr.MultifactorSchedule,
train_steps=1000,
save_steps=None,
eval_steps=10,
... | [
"Train the model on the inputs.\n\n Args:\n output_dir: Directory where to put the logs and checkpoints.\n model: The model to train as a callable returning 2 callables, an init_fun\n and apply_fun.\n loss_fun: callable with signature: params, trax.inputs.Inputs, model, rng\n -> loss.\n input... |
Please provide a description of the function:def _compute_fans(shape):
if len(shape) < 1: # Just to avoid errors for constants.
fan_in = fan_out = 1
elif len(shape) == 1:
fan_in = fan_out = shape[0]
elif len(shape) == 2:
fan_in = shape[0]
fan_out = shape[1]
else:
# Assuming convolution k... | [
"Computes the number of input and output units for a weight shape.\n\n Args:\n shape: Integer shape tuple or TF tensor shape.\n\n Returns:\n A tuple of scalars (fan_in, fan_out).\n "
] |
Please provide a description of the function:def get(identifier, value=None):
if value is None:
value = identifier
if identifier is None:
return None
elif isinstance(identifier, dict):
try:
return deserialize(identifier)
except ValueError:
return value
elif isinstance(identifier, ... | [
"Getter for loading from strings; returns value if can't load."
] |
Please provide a description of the function:def add_time_step(self, **create_time_step_kwargs):
ts = time_step.TimeStep.create_time_step(**create_time_step_kwargs)
assert isinstance(ts, time_step.TimeStep)
self._time_steps.append(ts) | [
"Creates a time-step and appends it to the list.\n\n Args:\n **create_time_step_kwargs: Forwarded to\n time_step.TimeStep.create_time_step.\n "
] |
Please provide a description of the function:def change_last_time_step(self, **replace_time_step_kwargs):
# Pre-conditions: self._time_steps shouldn't be empty.
assert self._time_steps
self._time_steps[-1] = self._time_steps[-1].replace(
**replace_time_step_kwargs) | [
"Replace the last time-steps with the given kwargs."
] |
Please provide a description of the function:def reward(self):
raw_rewards, processed_rewards = 0, 0
for ts in self.time_steps:
# NOTE: raw_reward and processed_reward are None for the first time-step.
if ts.raw_reward is not None:
raw_rewards += ts.raw_reward
if ts.processed_rewa... | [
"Returns a tuple of sum of raw and processed rewards."
] |
Please provide a description of the function:def _complete_trajectory(self, trajectory, index):
assert isinstance(trajectory, Trajectory)
# This *should* be the case.
assert trajectory.last_time_step.action is None
# Add to completed trajectories.
self._completed_trajectories.append(trajecto... | [
"Completes the given trajectory at the given index."
] |
Please provide a description of the function:def reset(self, indices, observations):
# Pre-conditions: indices, observations are np arrays.
# : indices is one-dimensional.
# : their first dimension (batch) is the same.
assert isinstance(indices, np.ndarray)
assert l... | [
"Resets trajectories at given indices and populates observations.\n\n Reset can either be called right at the beginning, when there are no\n time-steps, or to reset a currently active trajectory.\n\n If resetting a currently active trajectory then we save it in\n self._completed_trajectories.\n\n Arg... |
Please provide a description of the function:def complete_all_trajectories(self):
for index in range(self.batch_size):
trajectory = self._trajectories[index]
assert trajectory.is_active
self._complete_trajectory(trajectory, index) | [
"Essentially same as reset, but we don't have observations."
] |
Please provide a description of the function:def step(self, observations, raw_rewards, processed_rewards, dones, actions):
# Pre-conditions
assert isinstance(observations, np.ndarray)
assert isinstance(raw_rewards, np.ndarray)
assert isinstance(processed_rewards, np.ndarray)
assert isinstance(d... | [
"Record the information obtained from taking a step in all envs.\n\n Records (observation, rewards, done) in a new time-step and actions in the\n current time-step.\n\n If any trajectory gets done, we move that trajectory to\n completed_trajectories.\n\n Args:\n observations: ndarray of first di... |
Please provide a description of the function:def num_time_steps(self):
num_time_steps = sum(t.num_time_steps for t in self.trajectories)
return num_time_steps + self.num_completed_time_steps | [
"Returns the number of time-steps in completed and incomplete trajectories."
] |
Please provide a description of the function:def observations_np(self, boundary=20):
list_observations_np_ts = [t.observations_np for t in self.trajectories]
# Every element in `list_observations_np_ts` is shaped (t,) + OBS
OBS = list_observations_np_ts[0].shape[1:] # pylint: disable=invalid-name
... | [
"Pads the observations in all the trajectories and returns them.\n\n Args:\n boundary: integer, Observations will be padded to (n * boundary) + 1 where\n n is an integer.\n\n Returns:\n a tuple(padded_observations, time_steps), with shapes:\n padded_observations: (self.batch_size, n * ... |
Please provide a description of the function:def _generate_examples(tmp_dir, dataset_split):
if dataset_split == problem.DatasetSplit.TRAIN:
file_name = _TRAINING_SET
else:
file_name = _DEV_SET
squad_file = generator_utils.maybe_download(tmp_dir,
file_name,... | [
"Generate squad examples.\n\n Args:\n tmp_dir: a string\n dataset_split: problem.DatasetSplit.TRAIN or problem.DatasetSplit.EVAL\n Yields:\n dictionaries representing examples\n "
] |
Please provide a description of the function:def self_attention_layer(hparams, prefix):
return transformer_layers.SelfAttention(
num_heads=hparams.get(prefix + "num_heads"),
num_memory_heads=hparams.get(prefix + "num_memory_heads"),
key_value_size=hparams.d_kv,
shared_kv=hparams.get(prefix ... | [
"Create self-attention layer based on hyperparameters."
] |
Please provide a description of the function:def local_self_attention_layer(hparams, prefix):
return transformer_layers.LocalSelfAttention(
num_heads=hparams.get(prefix + "num_heads"),
num_memory_heads=hparams.get(prefix + "num_memory_heads"),
radius=hparams.local_attention_radius,
key_valu... | [
"Create self-attention layer based on hyperparameters."
] |
Please provide a description of the function:def layer_stack_from_hparams(hparams, prefix):
layers = hparams.get(prefix + "layers")
return transformer.LayerStack(
[layers_registry[l](hparams, prefix) for l in layers],
dropout_rate=hparams.layer_prepostprocess_dropout,
norm_epsilon=hparams.norm_... | [
"Create a layer stack based on the hyperparameter values."
] |
Please provide a description of the function:def mtf_unitransformer_base():
hparams = mtf_transformer2_base()
hparams.add_hparam("autoregressive", True)
# HYPERPARAMETERS FOR THE SINGLE LAYER STACK
hparams.add_hparam("layers", ["self_att", "drd"] * 6)
# number of heads in multihead attention
hparams.add_... | [
"Hyperparameters for single-stack Transformer."
] |
Please provide a description of the function:def mtf_bitransformer_base():
hparams = mtf_transformer2_base()
hparams.max_length = 256
hparams.shared_embedding = True
# HYPERPARAMETERS FOR THE LAYER STACKS
hparams.add_hparam("encoder_layers", ["self_att", "drd"] * 6)
hparams.add_hparam("decoder_layers", [... | [
"Machine translation base configuration."
] |
Please provide a description of the function:def mtf_bitransformer_tiny():
hparams = mtf_bitransformer_base()
hparams.batch_size = 2
hparams.mesh_shape = ""
hparams.d_model = 128
hparams.encoder_layers = ["self_att", "drd"] * 2
hparams.decoder_layers = ["self_att", "enc_att", "drd"] * 2
hparams.num_hea... | [
"Small encoder-decoder model for testing."
] |
Please provide a description of the function:def mtf_unitransformer_all_layers_tiny():
hparams = mtf_unitransformer_tiny()
hparams.moe_num_experts = 4
hparams.moe_expert_x = 4
hparams.moe_expert_y = 4
hparams.moe_hidden_size = 512
hparams.layers = ["self_att", "local_self_att", "moe_1d", "moe_2d", "drd"]... | [
"Test out all the layers on local CPU."
] |
Please provide a description of the function:def mtf_bitransformer_all_layers_tiny():
hparams = mtf_bitransformer_tiny()
hparams.moe_num_experts = 4
hparams.moe_expert_x = 4
hparams.moe_expert_y = 4
hparams.moe_hidden_size = 512
hparams.encoder_layers = [
"self_att", "local_self_att", "moe_1d", "mo... | [
"Test out all the layers on local CPU."
] |
Please provide a description of the function:def mtr_lm_dense(sz):
n = 2 ** sz
hparams = mtf_unitransformer_base()
hparams.d_model = 1024
hparams.max_length = 1024
hparams.batch_size = 128
# Parameters for my_layer_stack()
hparams.num_hidden_layers = 6
hparams.d_ff = 8192 * n
hparams.d_kv = 256
h... | [
"Series of architectures for language modeling.\n\n We assume infinite training data, so no dropout necessary.\n\n You can use languagemodel_wiki_noref_v32k_l1k.\n (1 epoch = ~46000 steps).\n TODO(noam): find a large enough dataset for these experiments.\n\n Args:\n sz: an integer\n\n Returns:\n a hpara... |
Please provide a description of the function:def mtr_lm_v1():
hparams = mtr_lm_dense(0)
hparams.layers = (["local_self_att", "local_self_att", "drd",
"self_att", "drd", "local_self_att",
"local_self_att", "moe_2d"] * 4)[:-1]
hparams.d_kv = 128
hparams.moe_expert_x = ... | [
"Model incorporating mixture-of-experts, local and global attention.\n\n ~6B parameters\n\n 32 experts in 3 hierarchichal moe layers.\n\n Returns:\n a hparams\n "
] |
Please provide a description of the function:def mtr_tr_dense(sz):
n = 2 ** sz
hparams = mtf_bitransformer_base()
hparams.d_model = 1024
hparams.max_length = 256
hparams.batch_size = 128
hparams.d_ff = int(4096 * n)
hparams.d_kv = 128
hparams.encoder_num_heads = int(8 * n)
hparams.decoder_num_heads... | [
"Series of machine translation models.\n\n All models are trained on sequences of 256 tokens.\n\n You can use the dataset translate_enfr_wmt32k_packed.\n 154000 steps = 3 epochs.\n\n Args:\n sz: an integer\n\n Returns:\n a hparams\n "
] |
Please provide a description of the function:def mtr_tr_dense_local(sz):
hparams = mtr_tr_dense(sz)
hparams.decoder_layers = ["local_self_att", "enc_att", "drd"] * 6
hparams.local_attention_radius = 32
return hparams | [
"With local self-attention in the decoder."
] |
Please provide a description of the function:def recurrent_transformer_decoder(
decoder_input,
encoder_output,
decoder_self_attention_bias,
encoder_decoder_attention_bias,
hparams,
name="decoder",
nonpadding=None,
save_weights_to=None,
make_image_summary=True):
x = decoder_input... | [
"Recurrent decoder function."
] |
Please provide a description of the function:def vqa_recurrent_self_attention_base():
hparams = universal_transformer.universal_transformer_base()
hparams.batch_size = 1024
hparams.use_fixed_batch_size = True
hparams.weight_decay = 0.
hparams.clip_grad_norm = 0.
# use default initializer
# hparams.init... | [
"VQA attention baseline hparams."
] |
Please provide a description of the function:def batch_norm_relu(inputs, is_training, relu=True):
inputs = mtf.layers.batch_norm(
inputs,
is_training,
BATCH_NORM_DECAY,
epsilon=BATCH_NORM_EPSILON,
init_zero=(not relu))
if relu:
inputs = mtf.relu(inputs)
return inputs | [
"Block of batch norm and relu."
] |
Please provide a description of the function:def bottleneck_block(inputs,
filters,
is_training,
strides,
projection_shortcut=None,
row_blocks_dim=None,
col_blocks_dim=None):
shortcut = inpu... | [
"Bottleneck block variant for residual networks with BN after convolutions.\n\n Args:\n inputs: a `mtf.Tensor` of shape\n `[batch_dim, row_blocks, col_blocks, rows, cols, in_channels]`.\n filters: `int` number of filters for the first two convolutions. Note\n that the third and final convolutio... |
Please provide a description of the function:def block_layer(inputs,
filters,
blocks,
strides,
is_training,
name,
row_blocks_dim=None,
col_blocks_dim=None):
with tf.variable_scope(name, default_name="blo... | [
"Creates one layer of blocks for the ResNet model.\n\n Args:\n inputs: `Tensor` of size `[batch, channels, height, width]`.\n filters: `int` number of filters for the first convolution of the layer.\n blocks: `int` number of blocks contained in the layer.\n strides: `int` stride to use for the first co... |
Please provide a description of the function:def mtf_resnet_base():
hparams = common_hparams.basic_params1()
hparams.no_data_parallelism = True
hparams.use_fixed_batch_size = True
hparams.batch_size = 32
hparams.max_length = 3072
hparams.hidden_size = 256
hparams.label_smoothing = 0.0
# 8-way model-p... | [
"Set of hyperparameters."
] |
Please provide a description of the function:def mtf_resnet_tiny():
hparams = mtf_resnet_base()
hparams.num_layers = 2
hparams.hidden_size = 64
hparams.filter_size = 64
hparams.batch_size = 16
# data parallelism and model-parallelism
hparams.col_blocks = 1
hparams.mesh_shape = "batch:2"
hparams.lay... | [
"Catch bugs locally..."
] |
Please provide a description of the function:def mtf_resnet_single():
hparams = mtf_resnet_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_layers = 1
hparams.block_length = 16
re... | [
"Small single parameters."
] |
Please provide a description of the function:def mtf_resnet_base_single():
hparams = mtf_resnet_base()
hparams.num_layers = 6
hparams.filter_size = 256
hparams.block_length = 128
hparams.mesh_shape = ""
hparams.layout = ""
return hparams | [
"Small single parameters."
] |
Please provide a description of the function:def mtf_resnet_base_cifar():
hparams = mtf_resnet_base()
hparams.mesh_shape = "batch:32"
hparams.layoyt = "batch:batch"
hparams.batch_size = 8
hparams.num_layers = 12
hparams.block_length = 256
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams... | [
"Data parallel CIFAR parameters."
] |
Please provide a description of the function:def universal_transformer_encoder(encoder_input,
encoder_self_attention_bias,
hparams,
name="encoder",
nonpadding=None,
... | [
"Universal Transformer encoder function.\n\n Prepares all the arguments and the inputs and passes it to a\n universal_transformer_layer to encode the encoder_input.\n\n Args:\n encoder_input: a Tensor\n encoder_self_attention_bias: bias Tensor for self-attention\n (see common_attention.attention_bias... |
Please provide a description of the function:def universal_transformer_layer(x,
hparams,
ffn_unit,
attention_unit,
pad_remover=None):
def add_vanilla_transformer_layer(x, num_layers, nam... | [
"Core function applying the universal transformer layer.\n\n Args:\n x: input\n hparams: model hyper-parameters\n ffn_unit: feed-forward unit\n attention_unit: multi-head attention unit\n pad_remover: to mask out padding in convolutional layers (efficiency).\n\n Returns:\n the output tensor, ex... |
Please provide a description of the function:def get_ut_layer(x,
hparams,
ffn_unit,
attention_unit,
pad_remover=None):
if hparams.recurrence_type == "basic":
ut_initializer = (x, x, x) # (state, input, memory)
ut_function = functools.par... | [
"Provides the function that is used in universal transforemr steps.\n\n Args:\n x: input\n hparams: model hyper-parameters\n ffn_unit: feed-forward unit\n attention_unit: multi-head attention unit\n pad_remover: to mask out padding in convolutional layers (efficiency).\n\n Returns:\n ut_function... |
Please provide a description of the function:def transformer_encoder_ffn_unit(x,
hparams,
nonpadding_mask=None,
pad_remover=None):
with tf.variable_scope("ffn"):
if hparams.transformer_ffn_type == "fc":
y ... | [
"Applies a feed-forward function which is parametrised for encoding.\n\n Args:\n x: input\n hparams: model hyper-parameters\n nonpadding_mask: optional Tensor with shape [batch_size, encoder_length]\n indicating what positions are not padding. This is used\n to mask out padding in convoltutional la... |
Please provide a description of the function:def transformer_encoder_attention_unit(x,
hparams,
encoder_self_attention_bias,
attention_dropout_broadcast_dims,
save_... | [
"Applies multihead attention function which is parametrised for encoding.\n\n Args:\n x: input\n hparams: model hyper-parameters\n encoder_self_attention_bias: a bias tensor for use in encoder self-attention\n attention_dropout_broadcast_dims: Fpr noise broadcasting in the dropout\n layers to save... |
Please provide a description of the function:def transformer_decoder_attention_unit(x,
hparams,
encoder_output,
decoder_self_attention_bias,
encoder_decoder_attenti... | [
"Applies multihead attention function which is parametrised for decoding.\n\n Args:\n x: input (decoder input)\n hparams: model hyper-parameters\n encoder_output: Encoder representation. [batch_size, input_length,\n hidden_dim]\n decoder_self_attention_bias: Bias and mask weights for decoder\n ... |
Please provide a description of the function:def universal_transformer_basic(layer_inputs,
step, hparams,
ffn_unit,
attention_unit):
state, inputs, memory = tf.unstack(layer_inputs, num=None, axis=0,
... | [
"Basic Universal Transformer.\n\n This model is pretty similar to the vanilla transformer in which weights are\n shared between layers. For some tasks, this simple idea brings a\n generalization that is not achievable by playing with the size of the model\n or drop_out parameters in the vanilla transformer.\n\n... |
Please provide a description of the function:def universal_transformer_highway(layer_inputs,
step, hparams,
ffn_unit,
attention_unit,
pad_remover=None):
state, inputs, memory = l... | [
"Universal Transformer with highway connection.\n\n\n It transforms the state using a block contaaining sel-attention and transition\n function and wrap the whole block with a highway connection.\n (the new state is a combination of the state and the transformed-state\n based on cary/transform gates.)\n\n Int... |
Please provide a description of the function:def universal_transformer_depthwise_attention(layer_inputs,
step, hparams,
ffn_unit,
attention_unit):
_, inputs, memory = layer_inpu... | [
"universal_transformer with depth-wise attention.\n\n It uses an attention mechanism-flipped vertically-\n over all the states from previous steps to generate the new_state.\n\n Args:\n layer_inputs:\n - state: state\n - memory: contains states from all the previous steps.\n step: indicating numb... |
Please provide a description of the function:def universal_transformer_with_gru_as_transition_function(
layer_inputs, step, hparams, ffn_unit, attention_unit, pad_remover=None):
state, unused_inputs, unused_memory = tf.unstack(
layer_inputs, num=None, axis=0, name="unstack")
# state (ut_state): outpu... | [
"Universal Transformer which uses a gru as transition function.\n\n It's kind of like having a gru, filliped vertically next to the Universal\n Transformer that controls the flow of the information in depth,\n over different steps of the Universal Transformer.\n\n Args:\n layer_inputs:\n - state: state\... |
Please provide a description of the function:def universal_transformer_with_lstm_as_transition_function(
layer_inputs, step, hparams, ffn_unit, attention_unit, pad_remover=None):
state, unused_inputs, memory = tf.unstack(
layer_inputs, num=None, axis=0, name="unstack")
# NOTE:
# state (ut_state): ou... | [
"Universal Transformer which uses a lstm as transition function.\n\n It's kind of like having a lstm, filliped vertically next to the Universal\n Transformer that controls the flow of the information in depth,\n over different steps of the Universal Transformer.\n\n Args:\n layer_inputs:\n - state: sta... |
Please provide a description of the function:def universal_transformer_act(x, hparams, ffn_unit, attention_unit):
if hparams.act_type not in ["basic", "global", "random", "accumulated"]:
raise ValueError("Unknown act type: %s" % hparams.act_type)
state = x
act_max_steps = hparams.act_max_steps
threshold... | [
"ACT based models.\n\n Implementations of all act models are based on craffel@'s cl/160711592.\n\n (1) Basic AUT based on remainder-distribution ACT (position-wise).\n (2) AUT with global halting probability (not position-wise).\n (3) AUT with random halting probability (not position-wise).\n (4) AUT with fina... |
Please provide a description of the function:def _ffn_layer_multi_inputs(inputs_list,
hparams,
ffn_layer_type="dense",
name="ffn",
kernel_initializer=None,
bias_initializer=None,
... | [
"Implements a Feed-forward layer with multiple inputs, pad-removing, etc.\n\n Args:\n inputs_list: list of input tensors\n hparams: hyper-parameters\n ffn_layer_type: dense / dense_dropconnect/ dense_relu_dense\n name: name\n kernel_initializer: kernel initializer\n bias_initializer: bias initial... |
Please provide a description of the function:def fill_memory_slot(memory, value, index):
mask = tf.to_float(
tf.one_hot(index,
tf.shape(memory)[0])[:, None, None, None])
fill_memory = (1 - mask) * memory + mask * value[None, ...]
return fill_memory | [
"Fills the memory slot at a particular index with the given value.\n\n Args:\n memory: a 4-d tensor [memory_size, batch, length, channel] containing\n the state of all steps\n value: a 3-d tensor [batch, length, channel] as the sate\n index: integer in [0, memory_size)\n\n Returns:\n filled memor... |
Please provide a description of the function:def add_depth_embedding(x):
x_shape = common_layers.shape_list(x)
depth = x_shape[-1]
num_steps = x_shape[0]
shape = [num_steps, 1, 1, depth]
depth_embedding = (
tf.get_variable(
"depth_embedding",
shape,
initializer=tf.random... | [
"Add n-dimensional embedding as the depth embedding (timing signal).\n\n Adds embeddings to represent the position of the step in the recurrent\n tower.\n\n Args:\n x: a tensor with shape [max_step, batch, length, depth]\n\n Returns:\n a Tensor the same shape as x.\n "
] |
Please provide a description of the function:def step_preprocess(x, step, hparams):
original_channel_size = common_layers.shape_list(x)[-1]
if hparams.add_position_timing_signal:
x = add_position_timing_signal(x, step, hparams)
if hparams.add_step_timing_signal:
x = add_step_timing_signal(x, step, hp... | [
"Preprocess the input at the beginning of each step.\n\n Args:\n x: input tensor\n step: step\n hparams: model hyper-parameters\n\n Returns:\n preprocessed input.\n\n "
] |
Please provide a description of the function:def add_position_timing_signal(x, step, hparams):
if not hparams.position_start_index:
index = 0
elif hparams.position_start_index == "random":
# Shift all positions randomly
# TODO(dehghani): What would be reasonable for max number of shift?
index =... | [
"Add n-dimensional embedding as the position (horizontal) timing signal.\n\n Args:\n x: a tensor with shape [batch, length, depth]\n step: step\n hparams: model hyper parameters\n\n Returns:\n a Tensor with the same shape as x.\n\n "
] |
Please provide a description of the function:def add_step_timing_signal(x, step, hparams):
if hparams.recurrence_type == "act":
num_steps = hparams.act_max_steps
else:
num_steps = hparams.num_rec_steps
channels = common_layers.shape_list(x)[-1]
if hparams.step_timing_signal_type == "learned":
si... | [
"Add n-dimensional embedding as the step (vertical) timing signal.\n\n Args:\n x: a tensor with shape [batch, length, depth]\n step: step\n hparams: model hyper parameters\n\n Returns:\n a Tensor with the same shape as x.\n\n "
] |
Please provide a description of the function:def wet_records_from_file_obj(f, take_ownership=False):
while True:
record = WETRecord.read(f)
if record is None:
break
if not record.url:
continue
yield record
if take_ownership:
f.close() | [
"Iterate through records in WET file object."
] |
Please provide a description of the function:def wet_records(wet_filepath):
if wet_filepath.endswith('.gz'):
fopen = gzip.open
else:
fopen = tf.gfile.GFile
with fopen(wet_filepath) as f:
for record in wet_records_from_file_obj(f):
yield record | [
"Generate WETRecords from filepath."
] |
Please provide a description of the function:def filter_paragraph(p):
# Expect a minimum number of words.
tokens = p.split()
if len(tokens) < 6:
return True
# Require some letters.
if not re.search(_SOME_ALPHA_RE, p):
return True
# Keep this one at the end, probably the most complicated logic.
... | [
"Simple filter to remove obviously bad paragraphs (bad text extraction).\n\n Note this needs to run very quickly as it is applied to every paragraph\n in the corpus, so nothing fancy! This whole method should be linear\n expected time in len(p).\n\n Args:\n p: string, paragraph\n\n Returns:\n True if we ... |
Please provide a description of the function:def timing(name=''):
start = datetime.datetime.now()
timestamp = start.strftime('%H:%M')
tf.logging.info('Starting job [%s] at %s', name, timestamp)
yield
end = datetime.datetime.now()
timestamp = end.strftime('%H:%M')
tf.logging.info('Finished job [%s] at %... | [
"Log start, end, and duration."
] |
Please provide a description of the function:def read(cls, f):
url = None
line = f.readline()
if not line:
# EOF
return None
while not line.startswith(cls.LENGTH_HEADER):
if line.startswith(cls.URI_HEADER):
url = line[len(cls.URI_HEADER):].strip()
line = f.readline(... | [
"Read header from file. Headers end with length and then 1 blank line."
] |
Please provide a description of the function:def read(cls, f):
header = WETHeader.read(f)
if header is None:
# EOF
return None
content = f.read(header.length)
# Consume empty separators
f.readline()
f.readline()
return cls(header.url, content) | [
"Read WETRecord from file. Records end with 2 blank lines."
] |
Please provide a description of the function:def MLP(num_hidden_layers=2,
hidden_size=512,
activation_fn=layers.Relu,
num_output_classes=10,
mode="train"):
del mode
cur_layers = [layers.Flatten()]
for _ in range(num_hidden_layers):
cur_layers += [layers.Dense(hidden_size), a... | [
"Multi-layer feed-forward neural network with non-linear activations."
] |
Please provide a description of the function:def _verify_same_spaces(self):
# Pre-conditions: self._envs is initialized.
if self._envs is None:
raise ValueError("Environments not initialized.")
if not isinstance(self._envs, list):
tf.logging.warning("Not checking observation and action s... | [
"Verifies that all the envs have the same observation and action space."
] |
Please provide a description of the function:def initialize_environments(self, batch_size=1):
assert batch_size >= 1
self._batch_size = batch_size
self._envs = [gym.make(self.base_env_name) for _ in range(batch_size)]
if self._env_wrapper_fn is not None:
self._envs = list(map(self._env_wrapp... | [
"Initializes the environments and trajectories.\n\n Subclasses can override this if they don't want a default implementation\n which initializes `batch_size` environments, but must take care to\n initialize self._trajectories (this is checked in __init__ anyways).\n\n Args:\n batch_size: (int) Numb... |
Please provide a description of the function:def process_rewards(self, rewards):
min_reward, max_reward = self.reward_range
# Clips at min and max reward.
rewards = np.clip(rewards, min_reward, max_reward)
# Round to (nearest) int and convert to integral type.
rewards = np.around(rewards, dec... | [
"Clips, rounds, and changes to integer type.\n\n Args:\n rewards: numpy array of raw (float) rewards.\n\n Returns:\n processed_rewards: numpy array of np.int64\n "
] |
Please provide a description of the function:def num_rewards(self):
# Pre-conditions: reward range is finite.
# : processed rewards are discrete.
if not self.is_reward_range_finite:
tf.logging.error("Infinite reward range, `num_rewards returning None`")
return None
if not... | [
"Returns the number of distinct rewards.\n\n Returns:\n Returns None if the reward range is infinite or the processed rewards\n aren't discrete, otherwise returns the number of distinct rewards.\n "
] |
Please provide a description of the function:def _reset(self, indices):
# Pre-conditions: common_preconditions, see `assert_common_preconditions`.
self.assert_common_preconditions()
# This returns a numpy array with first dimension `len(indices)` and the
# rest being the dimensionality of the obs... | [
"Resets environments at indices shouldn't pre-process or record.\n\n Subclasses should override this to do the actual reset if something other\n than the default implementation is desired.\n\n Args:\n indices: list of indices of underlying envs to call reset on.\n\n Returns:\n np.ndarray of st... |
Please provide a description of the function:def reset(self, indices=None):
if indices is None:
indices = np.arange(self.trajectories.batch_size)
# If this is empty (not None) then don't do anything, no env was done.
if indices.size == 0:
tf.logging.warning(
"`reset` called with... | [
"Resets environments at given indices.\n\n Subclasses should override _reset to do the actual reset if something other\n than the default implementation is desired.\n\n Args:\n indices: Indices of environments to reset. If None all envs are reset.\n\n Returns:\n Batch of initial observations o... |
Please provide a description of the function:def _step(self, actions):
# Pre-conditions: common_preconditions, see `assert_common_preconditions`.
# : len(actions) == len(self._envs)
self.assert_common_preconditions()
assert len(actions) == len(self._envs)
observations = []
r... | [
"Takes a step in all environments, shouldn't pre-process or record.\n\n Subclasses should override this to do the actual step if something other\n than the default implementation is desired.\n\n Args:\n actions: (np.ndarray) with first dimension equal to the batch size.\n\n Returns:\n a tuple ... |
Please provide a description of the function:def step(self, actions):
observations, raw_rewards, dones, infos = self._step(actions)
# Process rewards.
raw_rewards = raw_rewards.astype(np.float32)
processed_rewards = self.process_rewards(raw_rewards)
# Process observations.
processed_obse... | [
"Takes a step in all environments.\n\n Subclasses should override _step to do the actual reset if something other\n than the default implementation is desired.\n\n Args:\n actions: Batch of actions.\n\n Returns:\n (preprocessed_observations, processed_rewards, dones, infos).\n "
] |
Please provide a description of the function:def example_reading_spec(self):
# Subclasses can override and/or extend.
processed_reward_type = tf.float32
if self.is_processed_rewards_discrete:
processed_reward_type = tf.int64
data_fields = {
TIMESTEP_FIELD: tf.FixedLenFeature((1,), ... | [
"Data fields to store on disk and their decoders."
] |
Please provide a description of the function:def _generate_time_steps(self, trajectory_list):
for single_trajectory in trajectory_list:
assert isinstance(single_trajectory, trajectory.Trajectory)
# Skip writing trajectories that have only a single time-step -- this
# could just be a repeated... | [
"A generator to yield single time-steps from a list of trajectories."
] |
Please provide a description of the function:def init_vq_bottleneck(bottleneck_size, hidden_size):
means = tf.get_variable(
name="means",
shape=[bottleneck_size, hidden_size],
initializer=tf.uniform_unit_scaling_initializer())
ema_count = tf.get_variable(
name="ema_count",
shape=[bo... | [
"Get lookup table for VQ bottleneck."
] |
Please provide a description of the function:def vq_nearest_neighbor(x, hparams):
bottleneck_size = 2**hparams.bottleneck_bits
means = hparams.means
x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keepdims=True)
means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keepdims=True)
scalar_prod = tf.matmu... | [
"Find the nearest element in means to elements in x."
] |
Please provide a description of the function:def vq_discrete_bottleneck(x, hparams):
tf.logging.info("Using EMA with beta = {}".format(hparams.beta))
bottleneck_size = 2**hparams.bottleneck_bits
x_shape = common_layers.shape_list(x)
x = tf.reshape(x, [-1, hparams.hidden_size])
x_means_hot, e_loss = vq_near... | [
"Simple vector quantized discrete bottleneck."
] |
Please provide a description of the function:def vq_discrete_unbottleneck(x, hparams):
x_shape = common_layers.shape_list(x)
bottleneck_size = 2**hparams.bottleneck_bits
means = hparams.means
x_flat = tf.reshape(x, [-1, bottleneck_size])
result = tf.matmul(x_flat, means)
result = tf.reshape(result, x_sha... | [
"Simple undiscretization from vector quantized representation."
] |
Please provide a description of the function:def residual_conv(x, repeat, k, hparams, name, reuse=None):
with tf.variable_scope(name, reuse=reuse):
dilations_and_kernels = [((1, 1), k) for _ in range(3)]
for i in range(repeat):
with tf.variable_scope("repeat_%d" % i):
y = common_layers.conv_b... | [
"A stack of convolution blocks with residual connections."
] |
Please provide a description of the function:def decompress_step(source, hparams, first_relu, name):
with tf.variable_scope(name):
shape = common_layers.shape_list(source)
multiplier = 2
kernel = (1, 1)
thicker = common_layers.conv_block(
source,
hparams.hidden_size * multiplier, [(... | [
"Decompression function."
] |
Please provide a description of the function:def compress(x, hparams, name):
with tf.variable_scope(name):
# Run compression by strided convs.
cur = x
k1 = (3, 1)
k2 = (2, 1)
cur = residual_conv(cur, hparams.num_compress_steps, k1, hparams, "rc")
for i in range(hparams.num_compress_steps):
... | [
"Compress."
] |
Please provide a description of the function:def encode(x, x_space, hparams, name):
with tf.variable_scope(name):
(encoder_input, encoder_self_attention_bias,
ed) = transformer.transformer_prepare_encoder(x, x_space, hparams)
encoder_input = tf.nn.dropout(encoder_input, 1.0 - hparams.dropout)
retu... | [
"Transformer preparations and encoder."
] |
Please provide a description of the function:def decode_transformer(encoder_output, encoder_decoder_attention_bias, targets,
hparams, name):
with tf.variable_scope(name):
targets = common_layers.flatten4d3d(targets)
decoder_input, decoder_self_bias = (
transformer.transforme... | [
"Original Transformer decoder."
] |
Please provide a description of the function:def get_latent_pred_loss(latents_pred, latents_discrete_hot, hparams):
latents_logits = tf.layers.dense(
latents_pred, 2**hparams.bottleneck_bits, name="extra_logits")
loss = tf.nn.softmax_cross_entropy_with_logits_v2(
labels=tf.stop_gradient(latents_discr... | [
"Latent prediction and loss."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.