repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
tensorflow/tensor2tensor
tensor2tensor/envs/env_problem.py
EnvProblem.reset
def reset(self, indices=None): """Resets environments at given indices. Subclasses should override _reset to do the actual reset if something other than the default implementation is desired. Args: indices: Indices of environments to reset. If None all envs are reset. Returns: Batch o...
python
def reset(self, indices=None): """Resets environments at given indices. Subclasses should override _reset to do the actual reset if something other than the default implementation is desired. Args: indices: Indices of environments to reset. If None all envs are reset. Returns: Batch o...
[ "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 w...
Resets environments at given indices. Subclasses should override _reset to do the actual reset if something other than the default implementation is desired. Args: indices: Indices of environments to reset. If None all envs are reset. Returns: Batch of initial observations of reset enviro...
[ "Resets", "environments", "at", "given", "indices", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L474-L502
train
tensorflow/tensor2tensor
tensor2tensor/envs/env_problem.py
EnvProblem._step
def _step(self, actions): """Takes a step in all environments, shouldn't pre-process or record. Subclasses should override this to do the actual step if something other than the default implementation is desired. Args: actions: (np.ndarray) with first dimension equal to the batch size. Retu...
python
def _step(self, actions): """Takes a step in all environments, shouldn't pre-process or record. Subclasses should override this to do the actual step if something other than the default implementation is desired. Args: actions: (np.ndarray) with first dimension equal to the batch size. Retu...
[ "def", "_step", "(", "self", ",", "actions", ")", ":", "# Pre-conditions: common_preconditions, see `assert_common_preconditions`.", "# : len(actions) == len(self._envs)", "self", ".", "assert_common_preconditions", "(", ")", "assert", "len", "(", "actions", ")", ...
Takes a step in all environments, shouldn't pre-process or record. Subclasses should override this to do the actual step if something other than the default implementation is desired. Args: actions: (np.ndarray) with first dimension equal to the batch size. Returns: a tuple of stacked raw...
[ "Takes", "a", "step", "in", "all", "environments", "shouldn", "t", "pre", "-", "process", "or", "record", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L504-L538
train
tensorflow/tensor2tensor
tensor2tensor/envs/env_problem.py
EnvProblem.step
def step(self, actions): """Takes a step in all environments. Subclasses should override _step to do the actual reset if something other than the default implementation is desired. Args: actions: Batch of actions. Returns: (preprocessed_observations, processed_rewards, dones, infos). ...
python
def step(self, actions): """Takes a step in all environments. Subclasses should override _step to do the actual reset if something other than the default implementation is desired. Args: actions: Batch of actions. Returns: (preprocessed_observations, processed_rewards, dones, infos). ...
[ "def", "step", "(", "self", ",", "actions", ")", ":", "observations", ",", "raw_rewards", ",", "dones", ",", "infos", "=", "self", ".", "_step", "(", "actions", ")", "# Process rewards.", "raw_rewards", "=", "raw_rewards", ".", "astype", "(", "np", ".", ...
Takes a step in all environments. Subclasses should override _step to do the actual reset if something other than the default implementation is desired. Args: actions: Batch of actions. Returns: (preprocessed_observations, processed_rewards, dones, infos).
[ "Takes", "a", "step", "in", "all", "environments", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L540-L566
train
tensorflow/tensor2tensor
tensor2tensor/envs/env_problem.py
EnvProblem.example_reading_spec
def example_reading_spec(self): """Data fields to store on disk and their decoders.""" # 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.FixedLenFeatu...
python
def example_reading_spec(self): """Data fields to store on disk and their decoders.""" # 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.FixedLenFeatu...
[ "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", ...
Data fields to store on disk and their decoders.
[ "Data", "fields", "to", "store", "on", "disk", "and", "their", "decoders", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L568-L594
train
tensorflow/tensor2tensor
tensor2tensor/envs/env_problem.py
EnvProblem._generate_time_steps
def _generate_time_steps(self, trajectory_list): """A generator to yield single time-steps from a list of trajectories.""" for single_trajectory in trajectory_list: assert isinstance(single_trajectory, trajectory.Trajectory) # Skip writing trajectories that have only a single time-step -- this ...
python
def _generate_time_steps(self, trajectory_list): """A generator to yield single time-steps from a list of trajectories.""" for single_trajectory in trajectory_list: assert isinstance(single_trajectory, trajectory.Trajectory) # Skip writing trajectories that have only a single time-step -- this ...
[ "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 generator to yield single time-steps from a list of trajectories.
[ "A", "generator", "to", "yield", "single", "time", "-", "steps", "from", "a", "list", "of", "trajectories", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L656-L713
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_nat.py
init_vq_bottleneck
def init_vq_bottleneck(bottleneck_size, hidden_size): """Get lookup table for VQ bottleneck.""" 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=[bottle...
python
def init_vq_bottleneck(bottleneck_size, hidden_size): """Get lookup table for VQ bottleneck.""" 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=[bottle...
[ "def", "init_vq_bottleneck", "(", "bottleneck_size", ",", "hidden_size", ")", ":", "means", "=", "tf", ".", "get_variable", "(", "name", "=", "\"means\"", ",", "shape", "=", "[", "bottleneck_size", ",", "hidden_size", "]", ",", "initializer", "=", "tf", ".",...
Get lookup table for VQ bottleneck.
[ "Get", "lookup", "table", "for", "VQ", "bottleneck", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L31-L48
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_nat.py
vq_nearest_neighbor
def vq_nearest_neighbor(x, hparams): """Find the nearest element in means to elements in x.""" 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_pro...
python
def vq_nearest_neighbor(x, hparams): """Find the nearest element in means to elements in x.""" 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_pro...
[ "def", "vq_nearest_neighbor", "(", "x", ",", "hparams", ")", ":", "bottleneck_size", "=", "2", "**", "hparams", ".", "bottleneck_bits", "means", "=", "hparams", ".", "means", "x_norm_sq", "=", "tf", ".", "reduce_sum", "(", "tf", ".", "square", "(", "x", ...
Find the nearest element in means to elements in x.
[ "Find", "the", "nearest", "element", "in", "means", "to", "elements", "in", "x", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L51-L69
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_nat.py
vq_discrete_bottleneck
def vq_discrete_bottleneck(x, hparams): """Simple vector quantized discrete bottleneck.""" 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...
python
def vq_discrete_bottleneck(x, hparams): """Simple vector quantized discrete bottleneck.""" 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...
[ "def", "vq_discrete_bottleneck", "(", "x", ",", "hparams", ")", ":", "tf", ".", "logging", ".", "info", "(", "\"Using EMA with beta = {}\"", ".", "format", "(", "hparams", ".", "beta", ")", ")", "bottleneck_size", "=", "2", "**", "hparams", ".", "bottleneck_...
Simple vector quantized discrete bottleneck.
[ "Simple", "vector", "quantized", "discrete", "bottleneck", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L72-L107
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_nat.py
vq_discrete_unbottleneck
def vq_discrete_unbottleneck(x, hparams): """Simple undiscretization from vector quantized representation.""" 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...
python
def vq_discrete_unbottleneck(x, hparams): """Simple undiscretization from vector quantized representation.""" 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...
[ "def", "vq_discrete_unbottleneck", "(", "x", ",", "hparams", ")", ":", "x_shape", "=", "common_layers", ".", "shape_list", "(", "x", ")", "bottleneck_size", "=", "2", "**", "hparams", ".", "bottleneck_bits", "means", "=", "hparams", ".", "means", "x_flat", "...
Simple undiscretization from vector quantized representation.
[ "Simple", "undiscretization", "from", "vector", "quantized", "representation", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L110-L118
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_nat.py
residual_conv
def residual_conv(x, repeat, k, hparams, name, reuse=None): """A stack of convolution blocks with residual connections.""" 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 = com...
python
def residual_conv(x, repeat, k, hparams, name, reuse=None): """A stack of convolution blocks with residual connections.""" 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 = com...
[ "def", "residual_conv", "(", "x", ",", "repeat", ",", "k", ",", "hparams", ",", "name", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "reuse", "=", "reuse", ")", ":", "dilations_and_kernels", "=", "[", "(...
A stack of convolution blocks with residual connections.
[ "A", "stack", "of", "convolution", "blocks", "with", "residual", "connections", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L121-L135
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_nat.py
decompress_step
def decompress_step(source, hparams, first_relu, name): """Decompression function.""" 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, [((1, 1), kernel)]...
python
def decompress_step(source, hparams, first_relu, name): """Decompression function.""" 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, [((1, 1), kernel)]...
[ "def", "decompress_step", "(", "source", ",", "hparams", ",", "first_relu", ",", "name", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "shape", "=", "common_layers", ".", "shape_list", "(", "source", ")", "multiplier", "=", "2", "...
Decompression function.
[ "Decompression", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L138-L149
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_nat.py
compress
def compress(x, hparams, name): """Compress.""" 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): cur = common_layers.conv...
python
def compress(x, hparams, name): """Compress.""" 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): cur = common_layers.conv...
[ "def", "compress", "(", "x", ",", "hparams", ",", "name", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "# Run compression by strided convs.", "cur", "=", "x", "k1", "=", "(", "3", ",", "1", ")", "k2", "=", "(", "2", ",", "1...
Compress.
[ "Compress", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L152-L166
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_nat.py
encode
def encode(x, x_space, hparams, name): """Transformer preparations and encoder.""" 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) return...
python
def encode(x, x_space, hparams, name): """Transformer preparations and encoder.""" 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) return...
[ "def", "encode", "(", "x", ",", "x_space", ",", "hparams", ",", "name", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "(", "encoder_input", ",", "encoder_self_attention_bias", ",", "ed", ")", "=", "transformer", ".", "transformer_pr...
Transformer preparations and encoder.
[ "Transformer", "preparations", "and", "encoder", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L169-L176
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_nat.py
decode_transformer
def decode_transformer(encoder_output, encoder_decoder_attention_bias, targets, hparams, name): """Original Transformer decoder.""" with tf.variable_scope(name): targets = common_layers.flatten4d3d(targets) decoder_input, decoder_self_bias = ( transformer.transformer_prepare_...
python
def decode_transformer(encoder_output, encoder_decoder_attention_bias, targets, hparams, name): """Original Transformer decoder.""" with tf.variable_scope(name): targets = common_layers.flatten4d3d(targets) decoder_input, decoder_self_bias = ( transformer.transformer_prepare_...
[ "def", "decode_transformer", "(", "encoder_output", ",", "encoder_decoder_attention_bias", ",", "targets", ",", "hparams", ",", "name", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "targets", "=", "common_layers", ".", "flatten4d3d", "("...
Original Transformer decoder.
[ "Original", "Transformer", "decoder", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L179-L199
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_nat.py
get_latent_pred_loss
def get_latent_pred_loss(latents_pred, latents_discrete_hot, hparams): """Latent prediction and loss.""" 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_discrete_hot), lo...
python
def get_latent_pred_loss(latents_pred, latents_discrete_hot, hparams): """Latent prediction and loss.""" 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_discrete_hot), lo...
[ "def", "get_latent_pred_loss", "(", "latents_pred", ",", "latents_discrete_hot", ",", "hparams", ")", ":", "latents_logits", "=", "tf", ".", "layers", ".", "dense", "(", "latents_pred", ",", "2", "**", "hparams", ".", "bottleneck_bits", ",", "name", "=", "\"ex...
Latent prediction and loss.
[ "Latent", "prediction", "and", "loss", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L202-L208
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_nat.py
ae_transformer_internal
def ae_transformer_internal(inputs, targets, target_space, hparams, cache=None): """Main step used for training.""" # Encoder. inputs = common_layers.flatten4d3d(inputs) inputs, ed = encode(inputs, target_space, hparams, "input_enc") # Autoencoding. losses = {"extra": tf.constant(0.0), "latent_pred": tf.co...
python
def ae_transformer_internal(inputs, targets, target_space, hparams, cache=None): """Main step used for training.""" # Encoder. inputs = common_layers.flatten4d3d(inputs) inputs, ed = encode(inputs, target_space, hparams, "input_enc") # Autoencoding. losses = {"extra": tf.constant(0.0), "latent_pred": tf.co...
[ "def", "ae_transformer_internal", "(", "inputs", ",", "targets", ",", "target_space", ",", "hparams", ",", "cache", "=", "None", ")", ":", "# Encoder.", "inputs", "=", "common_layers", ".", "flatten4d3d", "(", "inputs", ")", "inputs", ",", "ed", "=", "encode...
Main step used for training.
[ "Main", "step", "used", "for", "training", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L245-L316
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_nat.py
transformer_nat_small
def transformer_nat_small(): """Set of hyperparameters.""" hparams = transformer.transformer_small() hparams.batch_size = 2048 hparams.learning_rate = 0.2 hparams.learning_rate_warmup_steps = 4000 hparams.num_hidden_layers = 3 hparams.hidden_size = 384 hparams.filter_size = 2048 hparams.label_smoothin...
python
def transformer_nat_small(): """Set of hyperparameters.""" hparams = transformer.transformer_small() hparams.batch_size = 2048 hparams.learning_rate = 0.2 hparams.learning_rate_warmup_steps = 4000 hparams.num_hidden_layers = 3 hparams.hidden_size = 384 hparams.filter_size = 2048 hparams.label_smoothin...
[ "def", "transformer_nat_small", "(", ")", ":", "hparams", "=", "transformer", ".", "transformer_small", "(", ")", "hparams", ".", "batch_size", "=", "2048", "hparams", ".", "learning_rate", "=", "0.2", "hparams", ".", "learning_rate_warmup_steps", "=", "4000", "...
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L384-L407
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_nat.py
transformer_nat_base
def transformer_nat_base(): """Set of hyperparameters.""" hparams = transformer_nat_small() hparams.batch_size = 2048 hparams.hidden_size = 512 hparams.filter_size = 4096 hparams.num_hidden_layers = 6 return hparams
python
def transformer_nat_base(): """Set of hyperparameters.""" hparams = transformer_nat_small() hparams.batch_size = 2048 hparams.hidden_size = 512 hparams.filter_size = 4096 hparams.num_hidden_layers = 6 return hparams
[ "def", "transformer_nat_base", "(", ")", ":", "hparams", "=", "transformer_nat_small", "(", ")", "hparams", ".", "batch_size", "=", "2048", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "filter_size", "=", "4096", "hparams", ".", "num_hidden_layers"...
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L411-L418
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_nat.py
transformer_nat_big
def transformer_nat_big(): """Set of hyperparameters.""" hparams = transformer_nat_small() hparams.batch_size = 2048 hparams.hidden_size = 1024 hparams.filter_size = 4096 hparams.num_hidden_layers = 6 hparams.num_heads = 16 hparams.layer_prepostprocess_dropout = 0.3 return hparams
python
def transformer_nat_big(): """Set of hyperparameters.""" hparams = transformer_nat_small() hparams.batch_size = 2048 hparams.hidden_size = 1024 hparams.filter_size = 4096 hparams.num_hidden_layers = 6 hparams.num_heads = 16 hparams.layer_prepostprocess_dropout = 0.3 return hparams
[ "def", "transformer_nat_big", "(", ")", ":", "hparams", "=", "transformer_nat_small", "(", ")", "hparams", ".", "batch_size", "=", "2048", "hparams", ".", "hidden_size", "=", "1024", "hparams", ".", "filter_size", "=", "4096", "hparams", ".", "num_hidden_layers"...
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L422-L431
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
policy_net
def policy_net(rng_key, batch_observations_shape, num_actions, bottom_layers=None): """A policy net function.""" # Use the bottom_layers as the bottom part of the network and just add the # required layers on top of it. if bottom_layers is None: bottom_layers = [...
python
def policy_net(rng_key, batch_observations_shape, num_actions, bottom_layers=None): """A policy net function.""" # Use the bottom_layers as the bottom part of the network and just add the # required layers on top of it. if bottom_layers is None: bottom_layers = [...
[ "def", "policy_net", "(", "rng_key", ",", "batch_observations_shape", ",", "num_actions", ",", "bottom_layers", "=", "None", ")", ":", "# Use the bottom_layers as the bottom part of the network and just add the", "# required layers on top of it.", "if", "bottom_layers", "is", "...
A policy net function.
[ "A", "policy", "net", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L78-L92
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
value_net
def value_net(rng_key, batch_observations_shape, num_actions, bottom_layers=None): """A value net function.""" del num_actions if bottom_layers is None: bottom_layers = [] bottom_layers.extend([ layers.Dense(1), ]) net = layers.Serial(*bottom_layers) re...
python
def value_net(rng_key, batch_observations_shape, num_actions, bottom_layers=None): """A value net function.""" del num_actions if bottom_layers is None: bottom_layers = [] bottom_layers.extend([ layers.Dense(1), ]) net = layers.Serial(*bottom_layers) re...
[ "def", "value_net", "(", "rng_key", ",", "batch_observations_shape", ",", "num_actions", ",", "bottom_layers", "=", "None", ")", ":", "del", "num_actions", "if", "bottom_layers", "is", "None", ":", "bottom_layers", "=", "[", "]", "bottom_layers", ".", "extend", ...
A value net function.
[ "A", "value", "net", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L95-L108
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
policy_and_value_net
def policy_and_value_net(rng_key, batch_observations_shape, num_actions, bottom_layers=None): """A policy and value net function.""" # Layers. cur_layers = [] if bottom_layers is not None: cur_layers.extend(bottom_layers) # Now, ...
python
def policy_and_value_net(rng_key, batch_observations_shape, num_actions, bottom_layers=None): """A policy and value net function.""" # Layers. cur_layers = [] if bottom_layers is not None: cur_layers.extend(bottom_layers) # Now, ...
[ "def", "policy_and_value_net", "(", "rng_key", ",", "batch_observations_shape", ",", "num_actions", ",", "bottom_layers", "=", "None", ")", ":", "# Layers.", "cur_layers", "=", "[", "]", "if", "bottom_layers", "is", "not", "None", ":", "cur_layers", ".", "extend...
A policy and value net function.
[ "A", "policy", "and", "value", "net", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L111-L130
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
log_params
def log_params(params, name="params"): """Dumps the params with `logging.error`.""" for i, param in enumerate(params): if not param: # Empty tuple. continue if not isinstance(param, (list, tuple)): logging.error( "%s[%d] : (%s) = [%s]", name, i, param.shape, onp.array(param)) ...
python
def log_params(params, name="params"): """Dumps the params with `logging.error`.""" for i, param in enumerate(params): if not param: # Empty tuple. continue if not isinstance(param, (list, tuple)): logging.error( "%s[%d] : (%s) = [%s]", name, i, param.shape, onp.array(param)) ...
[ "def", "log_params", "(", "params", ",", "name", "=", "\"params\"", ")", ":", "for", "i", ",", "param", "in", "enumerate", "(", "params", ")", ":", "if", "not", "param", ":", "# Empty tuple.", "continue", "if", "not", "isinstance", "(", "param", ",", "...
Dumps the params with `logging.error`.
[ "Dumps", "the", "params", "with", "logging", ".", "error", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L140-L152
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
collect_trajectories
def collect_trajectories(env, policy_fun, num_trajectories=1, policy="greedy", max_timestep=None, epsilon=0.1): """Collect trajectories with the given policy net and behaviour. Args: env...
python
def collect_trajectories(env, policy_fun, num_trajectories=1, policy="greedy", max_timestep=None, epsilon=0.1): """Collect trajectories with the given policy net and behaviour. Args: env...
[ "def", "collect_trajectories", "(", "env", ",", "policy_fun", ",", "num_trajectories", "=", "1", ",", "policy", "=", "\"greedy\"", ",", "max_timestep", "=", "None", ",", "epsilon", "=", "0.1", ")", ":", "trajectories", "=", "[", "]", "for", "t", "in", "r...
Collect trajectories with the given policy net and behaviour. Args: env: A gym env interface, for now this is not-batched. policy_fun: observations(B,T+1) -> log-probabs(B,T+1, A) callable. num_trajectories: int, number of trajectories. policy: string, "greedy", "epsilon-greedy", or "categorical-samp...
[ "Collect", "trajectories", "with", "the", "given", "policy", "net", "and", "behaviour", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L159-L275
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
get_padding_value
def get_padding_value(dtype): """Returns the padding value given a dtype.""" padding_value = None if dtype == np.uint8: padding_value = np.uint8(0) elif dtype == np.uint16: padding_value = np.uint16(0) elif dtype == np.float32: padding_value = 0.0 else: padding_value = 0 assert padding_val...
python
def get_padding_value(dtype): """Returns the padding value given a dtype.""" padding_value = None if dtype == np.uint8: padding_value = np.uint8(0) elif dtype == np.uint16: padding_value = np.uint16(0) elif dtype == np.float32: padding_value = 0.0 else: padding_value = 0 assert padding_val...
[ "def", "get_padding_value", "(", "dtype", ")", ":", "padding_value", "=", "None", "if", "dtype", "==", "np", ".", "uint8", ":", "padding_value", "=", "np", ".", "uint8", "(", "0", ")", "elif", "dtype", "==", "np", ".", "uint16", ":", "padding_value", "...
Returns the padding value given a dtype.
[ "Returns", "the", "padding", "value", "given", "a", "dtype", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L283-L295
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
pad_trajectories
def pad_trajectories(trajectories, boundary=20): """Pad trajectories to a bucket length that is a multiple of boundary. Args: trajectories: list[(observation, actions, rewards)], where each observation is shaped (t+1,) + OBS and actions & rewards are shaped (t,), with the length of the list being B...
python
def pad_trajectories(trajectories, boundary=20): """Pad trajectories to a bucket length that is a multiple of boundary. Args: trajectories: list[(observation, actions, rewards)], where each observation is shaped (t+1,) + OBS and actions & rewards are shaped (t,), with the length of the list being B...
[ "def", "pad_trajectories", "(", "trajectories", ",", "boundary", "=", "20", ")", ":", "# Let's compute max(t) over all trajectories.", "t_max", "=", "max", "(", "r", ".", "shape", "[", "0", "]", "for", "(", "_", ",", "_", ",", "r", ")", "in", "trajectories...
Pad trajectories to a bucket length that is a multiple of boundary. Args: trajectories: list[(observation, actions, rewards)], where each observation is shaped (t+1,) + OBS and actions & rewards are shaped (t,), with the length of the list being B (batch size). boundary: int, bucket length, the a...
[ "Pad", "trajectories", "to", "a", "bucket", "length", "that", "is", "a", "multiple", "of", "boundary", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L299-L369
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
rewards_to_go
def rewards_to_go(rewards, mask, gamma=0.99): r"""Computes rewards to go. Reward to go is defined as follows, the discounted reward that we have to yet collect, going forward from this point, i.e.: r2g_t = \sum_{l=0}^{\infty} (\gamma^{l} * reward_{t+l}) Args: rewards: np.ndarray of shape (B, T) of rewa...
python
def rewards_to_go(rewards, mask, gamma=0.99): r"""Computes rewards to go. Reward to go is defined as follows, the discounted reward that we have to yet collect, going forward from this point, i.e.: r2g_t = \sum_{l=0}^{\infty} (\gamma^{l} * reward_{t+l}) Args: rewards: np.ndarray of shape (B, T) of rewa...
[ "def", "rewards_to_go", "(", "rewards", ",", "mask", ",", "gamma", "=", "0.99", ")", ":", "B", ",", "T", "=", "rewards", ".", "shape", "# pylint: disable=invalid-name,unused-variable", "masked_rewards", "=", "rewards", "*", "mask", "# (B, T)", "# We use the follow...
r"""Computes rewards to go. Reward to go is defined as follows, the discounted reward that we have to yet collect, going forward from this point, i.e.: r2g_t = \sum_{l=0}^{\infty} (\gamma^{l} * reward_{t+l}) Args: rewards: np.ndarray of shape (B, T) of rewards. mask: np.ndarray of shape (B, T) of mas...
[ "r", "Computes", "rewards", "to", "go", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L373-L421
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
value_loss
def value_loss(value_net_apply, value_net_params, observations, rewards, reward_mask, gamma=0.99): """Computes the value loss. Args: value_net_apply: value net apply function with signature (params, ndarray of shape (B, T+1) + OBS...
python
def value_loss(value_net_apply, value_net_params, observations, rewards, reward_mask, gamma=0.99): """Computes the value loss. Args: value_net_apply: value net apply function with signature (params, ndarray of shape (B, T+1) + OBS...
[ "def", "value_loss", "(", "value_net_apply", ",", "value_net_params", ",", "observations", ",", "rewards", ",", "reward_mask", ",", "gamma", "=", "0.99", ")", ":", "B", ",", "T", "=", "rewards", ".", "shape", "# pylint: disable=invalid-name", "assert", "(", "B...
Computes the value loss. Args: value_net_apply: value net apply function with signature (params, ndarray of shape (B, T+1) + OBS) -> ndarray(B, T+1, 1) value_net_params: params of value_net_apply. observations: np.ndarray of shape (B, T+1) + OBS rewards: np.ndarray of shape (B, T) of rewards. ...
[ "Computes", "the", "value", "loss", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L425-L454
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
value_loss_given_predictions
def value_loss_given_predictions(value_prediction, rewards, reward_mask, gamma=0.99): """Computes the value loss given the prediction of the value function. Args: value_prediction: np.ndarray of shape (B, T+1, 1)...
python
def value_loss_given_predictions(value_prediction, rewards, reward_mask, gamma=0.99): """Computes the value loss given the prediction of the value function. Args: value_prediction: np.ndarray of shape (B, T+1, 1)...
[ "def", "value_loss_given_predictions", "(", "value_prediction", ",", "rewards", ",", "reward_mask", ",", "gamma", "=", "0.99", ")", ":", "B", ",", "T", "=", "rewards", ".", "shape", "# pylint: disable=invalid-name", "assert", "(", "B", ",", "T", ")", "==", "...
Computes the value loss given the prediction of the value function. Args: value_prediction: np.ndarray of shape (B, T+1, 1) rewards: np.ndarray of shape (B, T) of rewards. reward_mask: np.ndarray of shape (B, T), the mask over rewards. gamma: float, discount factor. Returns: The average L2 val...
[ "Computes", "the", "value", "loss", "given", "the", "prediction", "of", "the", "value", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L458-L484
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
deltas
def deltas(predicted_values, rewards, mask, gamma=0.99): r"""Computes TD-residuals from V(s) and rewards. Where a `delta`, i.e. a td-residual is defined as: delta_{b,t} = r_{b,t} + \gamma * v_{b,t+1} - v_{b,t}. Args: predicted_values: ndarray of shape (B, T+1). NOTE: Expects axis 2 was squeezed. Th...
python
def deltas(predicted_values, rewards, mask, gamma=0.99): r"""Computes TD-residuals from V(s) and rewards. Where a `delta`, i.e. a td-residual is defined as: delta_{b,t} = r_{b,t} + \gamma * v_{b,t+1} - v_{b,t}. Args: predicted_values: ndarray of shape (B, T+1). NOTE: Expects axis 2 was squeezed. Th...
[ "def", "deltas", "(", "predicted_values", ",", "rewards", ",", "mask", ",", "gamma", "=", "0.99", ")", ":", "# `d`s are basically one-step TD residuals.", "d", "=", "[", "]", "_", ",", "T", "=", "rewards", ".", "shape", "# pylint: disable=invalid-name", "for", ...
r"""Computes TD-residuals from V(s) and rewards. Where a `delta`, i.e. a td-residual is defined as: delta_{b,t} = r_{b,t} + \gamma * v_{b,t+1} - v_{b,t}. Args: predicted_values: ndarray of shape (B, T+1). NOTE: Expects axis 2 was squeezed. These represent V(s_bt) for b < B and t < T+1 rewards: nd...
[ "r", "Computes", "TD", "-", "residuals", "from", "V", "(", "s", ")", "and", "rewards", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L488-L513
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
gae_advantages
def gae_advantages(td_deltas, mask, lambda_=0.95, gamma=0.99): r"""Computes the GAE advantages given the one step TD-residuals. The formula for a GAE advantage estimator is as follows: A_{bt} = \sum_{l=0}^{\infty}(\gamma * \lambda)^{l}(\delta_{b,t+l}). Internally we just call rewards_to_go, since it is the s...
python
def gae_advantages(td_deltas, mask, lambda_=0.95, gamma=0.99): r"""Computes the GAE advantages given the one step TD-residuals. The formula for a GAE advantage estimator is as follows: A_{bt} = \sum_{l=0}^{\infty}(\gamma * \lambda)^{l}(\delta_{b,t+l}). Internally we just call rewards_to_go, since it is the s...
[ "def", "gae_advantages", "(", "td_deltas", ",", "mask", ",", "lambda_", "=", "0.95", ",", "gamma", "=", "0.99", ")", ":", "return", "rewards_to_go", "(", "td_deltas", ",", "mask", ",", "lambda_", "*", "gamma", ")" ]
r"""Computes the GAE advantages given the one step TD-residuals. The formula for a GAE advantage estimator is as follows: A_{bt} = \sum_{l=0}^{\infty}(\gamma * \lambda)^{l}(\delta_{b,t+l}). Internally we just call rewards_to_go, since it is the same computation. Args: td_deltas: np.ndarray of shape (B, ...
[ "r", "Computes", "the", "GAE", "advantages", "given", "the", "one", "step", "TD", "-", "residuals", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L516-L537
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
chosen_probabs
def chosen_probabs(probab_observations, actions): """Picks out the probabilities of the actions along batch and time-steps. Args: probab_observations: ndarray of shape `[B, T+1, A]`, where probab_observations[b, t, i] contains the log-probability of action = i at the t^th time-step in the b^th traj...
python
def chosen_probabs(probab_observations, actions): """Picks out the probabilities of the actions along batch and time-steps. Args: probab_observations: ndarray of shape `[B, T+1, A]`, where probab_observations[b, t, i] contains the log-probability of action = i at the t^th time-step in the b^th traj...
[ "def", "chosen_probabs", "(", "probab_observations", ",", "actions", ")", ":", "B", ",", "T", "=", "actions", ".", "shape", "# pylint: disable=invalid-name", "assert", "(", "B", ",", "T", "+", "1", ")", "==", "probab_observations", ".", "shape", "[", ":", ...
Picks out the probabilities of the actions along batch and time-steps. Args: probab_observations: ndarray of shape `[B, T+1, A]`, where probab_observations[b, t, i] contains the log-probability of action = i at the t^th time-step in the b^th trajectory. actions: ndarray of shape `[B, T]`, with ea...
[ "Picks", "out", "the", "probabilities", "of", "the", "actions", "along", "batch", "and", "time", "-", "steps", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L540-L555
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
compute_probab_ratios
def compute_probab_ratios(p_new, p_old, actions, reward_mask): """Computes the probability ratios for each time-step in a trajectory. Args: p_new: ndarray of shape [B, T+1, A] of the log-probabilities that the policy network assigns to all the actions at each time-step in each batch using the old p...
python
def compute_probab_ratios(p_new, p_old, actions, reward_mask): """Computes the probability ratios for each time-step in a trajectory. Args: p_new: ndarray of shape [B, T+1, A] of the log-probabilities that the policy network assigns to all the actions at each time-step in each batch using the old p...
[ "def", "compute_probab_ratios", "(", "p_new", ",", "p_old", ",", "actions", ",", "reward_mask", ")", ":", "B", ",", "T", "=", "actions", ".", "shape", "# pylint: disable=invalid-name", "assert", "(", "B", ",", "T", "+", "1", ")", "==", "p_old", ".", "sha...
Computes the probability ratios for each time-step in a trajectory. Args: p_new: ndarray of shape [B, T+1, A] of the log-probabilities that the policy network assigns to all the actions at each time-step in each batch using the old parameters. p_old: ndarray of shape [B, T+1, A], same as above, b...
[ "Computes", "the", "probability", "ratios", "for", "each", "time", "-", "step", "in", "a", "trajectory", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L558-L588
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
ppo_loss
def ppo_loss(policy_net_apply, new_policy_params, old_policy_params, value_net_apply, value_net_params, padded_observations, padded_actions, padded_rewards, reward_mask, gamma=0.99, lambda_=...
python
def ppo_loss(policy_net_apply, new_policy_params, old_policy_params, value_net_apply, value_net_params, padded_observations, padded_actions, padded_rewards, reward_mask, gamma=0.99, lambda_=...
[ "def", "ppo_loss", "(", "policy_net_apply", ",", "new_policy_params", ",", "old_policy_params", ",", "value_net_apply", ",", "value_net_params", ",", "padded_observations", ",", "padded_actions", ",", "padded_rewards", ",", "reward_mask", ",", "gamma", "=", "0.99", ",...
PPO objective, with an eventual minus sign, given observations.
[ "PPO", "objective", "with", "an", "eventual", "minus", "sign", "given", "observations", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L602-L645
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
ppo_loss_given_predictions
def ppo_loss_given_predictions(log_probab_actions_new, log_probab_actions_old, predicted_values, padded_actions, padded_rewards, reward_mask, ...
python
def ppo_loss_given_predictions(log_probab_actions_new, log_probab_actions_old, predicted_values, padded_actions, padded_rewards, reward_mask, ...
[ "def", "ppo_loss_given_predictions", "(", "log_probab_actions_new", ",", "log_probab_actions_old", ",", "predicted_values", ",", "padded_actions", ",", "padded_rewards", ",", "reward_mask", ",", "gamma", "=", "0.99", ",", "lambda_", "=", "0.95", ",", "epsilon", "=", ...
PPO objective, with an eventual minus sign, given predictions.
[ "PPO", "objective", "with", "an", "eventual", "minus", "sign", "given", "predictions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L649-L695
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
combined_loss_given_predictions
def combined_loss_given_predictions(log_probab_actions_new, log_probab_actions_old, value_prediction, padded_actions, padded_rewards, reward...
python
def combined_loss_given_predictions(log_probab_actions_new, log_probab_actions_old, value_prediction, padded_actions, padded_rewards, reward...
[ "def", "combined_loss_given_predictions", "(", "log_probab_actions_new", ",", "log_probab_actions_old", ",", "value_prediction", ",", "padded_actions", ",", "padded_rewards", ",", "reward_mask", ",", "gamma", "=", "0.99", ",", "lambda_", "=", "0.95", ",", "epsilon", "...
Computes the combined (clipped loss + value loss) given predictions.
[ "Computes", "the", "combined", "(", "clipped", "loss", "+", "value", "loss", ")", "given", "predictions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L699-L726
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
combined_loss
def combined_loss(new_params, old_params, policy_and_value_net_apply, padded_observations, padded_actions, padded_rewards, reward_mask, gamma=0.99, lambda_=0.95, ...
python
def combined_loss(new_params, old_params, policy_and_value_net_apply, padded_observations, padded_actions, padded_rewards, reward_mask, gamma=0.99, lambda_=0.95, ...
[ "def", "combined_loss", "(", "new_params", ",", "old_params", ",", "policy_and_value_net_apply", ",", "padded_observations", ",", "padded_actions", ",", "padded_rewards", ",", "reward_mask", ",", "gamma", "=", "0.99", ",", "lambda_", "=", "0.95", ",", "epsilon", "...
Computes the combined (clipped loss + value loss) given observations.
[ "Computes", "the", "combined", "(", "clipped", "loss", "+", "value", "loss", ")", "given", "observations", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L731-L761
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
ppo_opt_step
def ppo_opt_step(i, opt_state, ppo_opt_update, policy_net_apply, old_policy_params, value_net_apply, value_net_params, padded_observations, padded_actions, padded_rewa...
python
def ppo_opt_step(i, opt_state, ppo_opt_update, policy_net_apply, old_policy_params, value_net_apply, value_net_params, padded_observations, padded_actions, padded_rewa...
[ "def", "ppo_opt_step", "(", "i", ",", "opt_state", ",", "ppo_opt_update", ",", "policy_net_apply", ",", "old_policy_params", ",", "value_net_apply", ",", "value_net_params", ",", "padded_observations", ",", "padded_actions", ",", "padded_rewards", ",", "reward_mask", ...
PPO optimizer step.
[ "PPO", "optimizer", "step", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L765-L795
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
value_opt_step
def value_opt_step(i, opt_state, opt_update, value_net_apply, padded_observations, padded_rewards, reward_mask, gamma=0.99): """Value optimizer step.""" value_params = trax_opt.get_pa...
python
def value_opt_step(i, opt_state, opt_update, value_net_apply, padded_observations, padded_rewards, reward_mask, gamma=0.99): """Value optimizer step.""" value_params = trax_opt.get_pa...
[ "def", "value_opt_step", "(", "i", ",", "opt_state", ",", "opt_update", ",", "value_net_apply", ",", "padded_observations", ",", "padded_rewards", ",", "reward_mask", ",", "gamma", "=", "0.99", ")", ":", "value_params", "=", "trax_opt", ".", "get_params", "(", ...
Value optimizer step.
[ "Value", "optimizer", "step", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L799-L816
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
policy_and_value_opt_step
def policy_and_value_opt_step(i, opt_state, opt_update, policy_and_value_net_apply, old_params, padded_observations, padded_actions, ...
python
def policy_and_value_opt_step(i, opt_state, opt_update, policy_and_value_net_apply, old_params, padded_observations, padded_actions, ...
[ "def", "policy_and_value_opt_step", "(", "i", ",", "opt_state", ",", "opt_update", ",", "policy_and_value_net_apply", ",", "old_params", ",", "padded_observations", ",", "padded_actions", ",", "padded_rewards", ",", "reward_mask", ",", "c1", "=", "1.0", ",", "c2", ...
Policy and Value optimizer step.
[ "Policy", "and", "Value", "optimizer", "step", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L820-L855
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
training_loop
def training_loop(env=None, env_name="CartPole-v0", epochs=EPOCHS, policy_net_fun=None, value_net_fun=None, policy_and_value_net_fun=None, policy_optimizer_fun=None, value_optimizer_fun=None, ...
python
def training_loop(env=None, env_name="CartPole-v0", epochs=EPOCHS, policy_net_fun=None, value_net_fun=None, policy_and_value_net_fun=None, policy_optimizer_fun=None, value_optimizer_fun=None, ...
[ "def", "training_loop", "(", "env", "=", "None", ",", "env_name", "=", "\"CartPole-v0\"", ",", "epochs", "=", "EPOCHS", ",", "policy_net_fun", "=", "None", ",", "value_net_fun", "=", "None", ",", "policy_and_value_net_fun", "=", "None", ",", "policy_optimizer_fu...
Runs the training loop for PPO, with fixed policy and value nets.
[ "Runs", "the", "training", "loop", "for", "PPO", "with", "fixed", "policy", "and", "value", "nets", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L864-L1215
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multinli.py
_maybe_download_corpora
def _maybe_download_corpora(tmp_dir): """Download corpora for multinli. Args: tmp_dir: a string Returns: a string """ mnli_filename = "MNLI.zip" mnli_finalpath = os.path.join(tmp_dir, "MNLI") if not tf.gfile.Exists(mnli_finalpath): zip_filepath = generator_utils.maybe_download( tmp_di...
python
def _maybe_download_corpora(tmp_dir): """Download corpora for multinli. Args: tmp_dir: a string Returns: a string """ mnli_filename = "MNLI.zip" mnli_finalpath = os.path.join(tmp_dir, "MNLI") if not tf.gfile.Exists(mnli_finalpath): zip_filepath = generator_utils.maybe_download( tmp_di...
[ "def", "_maybe_download_corpora", "(", "tmp_dir", ")", ":", "mnli_filename", "=", "\"MNLI.zip\"", "mnli_finalpath", "=", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "\"MNLI\"", ")", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "mnli_finalpat...
Download corpora for multinli. Args: tmp_dir: a string Returns: a string
[ "Download", "corpora", "for", "multinli", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multinli.py#L42-L59
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multinli.py
_example_generator
def _example_generator(filename): """Generate mnli examples. Args: filename: a string Yields: dictionaries containing "premise", "hypothesis" and "label" strings """ for idx, line in enumerate(tf.gfile.Open(filename, "rb")): if idx == 0: continue # skip header line = text_encoder.to_unicode_...
python
def _example_generator(filename): """Generate mnli examples. Args: filename: a string Yields: dictionaries containing "premise", "hypothesis" and "label" strings """ for idx, line in enumerate(tf.gfile.Open(filename, "rb")): if idx == 0: continue # skip header line = text_encoder.to_unicode_...
[ "def", "_example_generator", "(", "filename", ")", ":", "for", "idx", ",", "line", "in", "enumerate", "(", "tf", ".", "gfile", ".", "Open", "(", "filename", ",", "\"rb\"", ")", ")", ":", "if", "idx", "==", "0", ":", "continue", "# skip header", "line",...
Generate mnli examples. Args: filename: a string Yields: dictionaries containing "premise", "hypothesis" and "label" strings
[ "Generate", "mnli", "examples", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multinli.py#L62-L79
train
tensorflow/tensor2tensor
tensor2tensor/models/shake_shake.py
shake_shake_skip_connection
def shake_shake_skip_connection(x, output_filters, stride, is_training): """Adds a residual connection to the filter x for the shake-shake model.""" curr_filters = common_layers.shape_list(x)[-1] if curr_filters == output_filters: return x stride_spec = [1, stride, stride, 1] # Skip path 1. path1 = tf.n...
python
def shake_shake_skip_connection(x, output_filters, stride, is_training): """Adds a residual connection to the filter x for the shake-shake model.""" curr_filters = common_layers.shape_list(x)[-1] if curr_filters == output_filters: return x stride_spec = [1, stride, stride, 1] # Skip path 1. path1 = tf.n...
[ "def", "shake_shake_skip_connection", "(", "x", ",", "output_filters", ",", "stride", ",", "is_training", ")", ":", "curr_filters", "=", "common_layers", ".", "shape_list", "(", "x", ")", "[", "-", "1", "]", "if", "curr_filters", "==", "output_filters", ":", ...
Adds a residual connection to the filter x for the shake-shake model.
[ "Adds", "a", "residual", "connection", "to", "the", "filter", "x", "for", "the", "shake", "-", "shake", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/shake_shake.py#L30-L52
train
tensorflow/tensor2tensor
tensor2tensor/models/shake_shake.py
shake_shake_branch
def shake_shake_branch(x, output_filters, stride, rand_forward, rand_backward, hparams): """Building a 2 branching convnet.""" is_training = hparams.mode == tf.estimator.ModeKeys.TRAIN x = tf.nn.relu(x) x = tf.layers.conv2d( x, output_filters, (3, 3), strides=(stride, st...
python
def shake_shake_branch(x, output_filters, stride, rand_forward, rand_backward, hparams): """Building a 2 branching convnet.""" is_training = hparams.mode == tf.estimator.ModeKeys.TRAIN x = tf.nn.relu(x) x = tf.layers.conv2d( x, output_filters, (3, 3), strides=(stride, st...
[ "def", "shake_shake_branch", "(", "x", ",", "output_filters", ",", "stride", ",", "rand_forward", ",", "rand_backward", ",", "hparams", ")", ":", "is_training", "=", "hparams", ".", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", "x", ...
Building a 2 branching convnet.
[ "Building", "a", "2", "branching", "convnet", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/shake_shake.py#L55-L75
train
tensorflow/tensor2tensor
tensor2tensor/models/shake_shake.py
shake_shake_block
def shake_shake_block(x, output_filters, stride, hparams): """Builds a full shake-shake sub layer.""" is_training = hparams.mode == tf.estimator.ModeKeys.TRAIN batch_size = common_layers.shape_list(x)[0] # Generate random numbers for scaling the branches. rand_forward = [ tf.random_uniform( [...
python
def shake_shake_block(x, output_filters, stride, hparams): """Builds a full shake-shake sub layer.""" is_training = hparams.mode == tf.estimator.ModeKeys.TRAIN batch_size = common_layers.shape_list(x)[0] # Generate random numbers for scaling the branches. rand_forward = [ tf.random_uniform( [...
[ "def", "shake_shake_block", "(", "x", ",", "output_filters", ",", "stride", ",", "hparams", ")", ":", "is_training", "=", "hparams", ".", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", "batch_size", "=", "common_layers", ".", "shape_lis...
Builds a full shake-shake sub layer.
[ "Builds", "a", "full", "shake", "-", "shake", "sub", "layer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/shake_shake.py#L78-L119
train
tensorflow/tensor2tensor
tensor2tensor/models/shake_shake.py
shake_shake_layer
def shake_shake_layer(x, output_filters, num_blocks, stride, hparams): """Builds many sub layers into one full layer.""" for block_num in range(num_blocks): curr_stride = stride if (block_num == 0) else 1 with tf.variable_scope("layer_{}".format(block_num)): x = shake_shake_block(x, output_filters, cu...
python
def shake_shake_layer(x, output_filters, num_blocks, stride, hparams): """Builds many sub layers into one full layer.""" for block_num in range(num_blocks): curr_stride = stride if (block_num == 0) else 1 with tf.variable_scope("layer_{}".format(block_num)): x = shake_shake_block(x, output_filters, cu...
[ "def", "shake_shake_layer", "(", "x", ",", "output_filters", ",", "num_blocks", ",", "stride", ",", "hparams", ")", ":", "for", "block_num", "in", "range", "(", "num_blocks", ")", ":", "curr_stride", "=", "stride", "if", "(", "block_num", "==", "0", ")", ...
Builds many sub layers into one full layer.
[ "Builds", "many", "sub", "layers", "into", "one", "full", "layer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/shake_shake.py#L122-L128
train
tensorflow/tensor2tensor
tensor2tensor/models/shake_shake.py
shakeshake_small
def shakeshake_small(): """Parameters for CIFAR-10. Gets to about 96% accuracy@700K steps, 1 GPU.""" hparams = common_hparams.basic_params1() hparams.batch_size = 128 hparams.hidden_size = 32 hparams.layer_prepostprocess_dropout = 0.0 hparams.dropout = 0 hparams.label_smoothing = 0.0 hparams.clip_grad_n...
python
def shakeshake_small(): """Parameters for CIFAR-10. Gets to about 96% accuracy@700K steps, 1 GPU.""" hparams = common_hparams.basic_params1() hparams.batch_size = 128 hparams.hidden_size = 32 hparams.layer_prepostprocess_dropout = 0.0 hparams.dropout = 0 hparams.label_smoothing = 0.0 hparams.clip_grad_n...
[ "def", "shakeshake_small", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "batch_size", "=", "128", "hparams", ".", "hidden_size", "=", "32", "hparams", ".", "layer_prepostprocess_dropout", "=", "0.0", "hparams",...
Parameters for CIFAR-10. Gets to about 96% accuracy@700K steps, 1 GPU.
[ "Parameters", "for", "CIFAR", "-", "10", ".", "Gets", "to", "about", "96%", "accuracy" ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/shake_shake.py#L165-L187
train
tensorflow/tensor2tensor
tensor2tensor/utils/metrics_hook.py
has_metric_plateaued
def has_metric_plateaued(steps, values, num_steps=100, delta=0.1, decrease=True): """Check if metric has plateaued. A metric has plateaued if the value has not increased/decreased (depending on `decrease`) by `delta` for at least `num_steps`. Args: steps: list<int> list of global ...
python
def has_metric_plateaued(steps, values, num_steps=100, delta=0.1, decrease=True): """Check if metric has plateaued. A metric has plateaued if the value has not increased/decreased (depending on `decrease`) by `delta` for at least `num_steps`. Args: steps: list<int> list of global ...
[ "def", "has_metric_plateaued", "(", "steps", ",", "values", ",", "num_steps", "=", "100", ",", "delta", "=", "0.1", ",", "decrease", "=", "True", ")", ":", "assert", "num_steps", ">", "0", "if", "len", "(", "steps", ")", "<", "2", ":", "return", "Fal...
Check if metric has plateaued. A metric has plateaued if the value has not increased/decreased (depending on `decrease`) by `delta` for at least `num_steps`. Args: steps: list<int> list of global steps for values. values: list<float> list of metric values. num_steps: int, number of steps the metric ...
[ "Check", "if", "metric", "has", "plateaued", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics_hook.py#L249-L290
train
tensorflow/tensor2tensor
tensor2tensor/models/video/savp_params.py
next_frame_savp
def next_frame_savp(): """SAVP model hparams.""" hparams = sv2p_params.next_frame_sv2p() hparams.add_hparam("z_dim", 8) hparams.add_hparam("num_discriminator_filters", 32) hparams.add_hparam("use_vae", True) hparams.add_hparam("use_gan", False) hparams.add_hparam("use_spectral_norm", True) hparams.add_h...
python
def next_frame_savp(): """SAVP model hparams.""" hparams = sv2p_params.next_frame_sv2p() hparams.add_hparam("z_dim", 8) hparams.add_hparam("num_discriminator_filters", 32) hparams.add_hparam("use_vae", True) hparams.add_hparam("use_gan", False) hparams.add_hparam("use_spectral_norm", True) hparams.add_h...
[ "def", "next_frame_savp", "(", ")", ":", "hparams", "=", "sv2p_params", ".", "next_frame_sv2p", "(", ")", "hparams", ".", "add_hparam", "(", "\"z_dim\"", ",", "8", ")", "hparams", ".", "add_hparam", "(", "\"num_discriminator_filters\"", ",", "32", ")", "hparam...
SAVP model hparams.
[ "SAVP", "model", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/savp_params.py#L27-L56
train
tensorflow/tensor2tensor
tensor2tensor/models/video/savp_params.py
next_frame_savp_vae
def next_frame_savp_vae(): """SAVP - VAE only model.""" hparams = next_frame_savp() hparams.use_vae = True hparams.use_gan = False hparams.latent_loss_multiplier = 1e-3 hparams.latent_loss_multiplier_schedule = "linear_anneal" return hparams
python
def next_frame_savp_vae(): """SAVP - VAE only model.""" hparams = next_frame_savp() hparams.use_vae = True hparams.use_gan = False hparams.latent_loss_multiplier = 1e-3 hparams.latent_loss_multiplier_schedule = "linear_anneal" return hparams
[ "def", "next_frame_savp_vae", "(", ")", ":", "hparams", "=", "next_frame_savp", "(", ")", "hparams", ".", "use_vae", "=", "True", "hparams", ".", "use_gan", "=", "False", "hparams", ".", "latent_loss_multiplier", "=", "1e-3", "hparams", ".", "latent_loss_multipl...
SAVP - VAE only model.
[ "SAVP", "-", "VAE", "only", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/savp_params.py#L70-L77
train
tensorflow/tensor2tensor
tensor2tensor/models/video/savp_params.py
next_frame_savp_gan
def next_frame_savp_gan(): """SAVP - GAN only model.""" hparams = next_frame_savp() hparams.use_gan = True hparams.use_vae = False hparams.gan_loss_multiplier = 0.001 hparams.optimizer_adam_beta1 = 0.5 hparams.learning_rate_constant = 2e-4 hparams.gan_loss = "cross_entropy" hparams.learning_rate_decay...
python
def next_frame_savp_gan(): """SAVP - GAN only model.""" hparams = next_frame_savp() hparams.use_gan = True hparams.use_vae = False hparams.gan_loss_multiplier = 0.001 hparams.optimizer_adam_beta1 = 0.5 hparams.learning_rate_constant = 2e-4 hparams.gan_loss = "cross_entropy" hparams.learning_rate_decay...
[ "def", "next_frame_savp_gan", "(", ")", ":", "hparams", "=", "next_frame_savp", "(", ")", "hparams", ".", "use_gan", "=", "True", "hparams", ".", "use_vae", "=", "False", "hparams", ".", "gan_loss_multiplier", "=", "0.001", "hparams", ".", "optimizer_adam_beta1"...
SAVP - GAN only model.
[ "SAVP", "-", "GAN", "only", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/savp_params.py#L81-L92
train
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
diet_adam_optimizer_params
def diet_adam_optimizer_params(): """Default hyperparameters for a DietAdamOptimizer. Returns: a hyperparameters object. """ return hparam.HParams( quantize=True, # use 16-bit fixed-point quantization_scale=10.0 / tf.int16.max, optimizer="DietAdam", learning_rate=1.0, learnin...
python
def diet_adam_optimizer_params(): """Default hyperparameters for a DietAdamOptimizer. Returns: a hyperparameters object. """ return hparam.HParams( quantize=True, # use 16-bit fixed-point quantization_scale=10.0 / tf.int16.max, optimizer="DietAdam", learning_rate=1.0, learnin...
[ "def", "diet_adam_optimizer_params", "(", ")", ":", "return", "hparam", ".", "HParams", "(", "quantize", "=", "True", ",", "# use 16-bit fixed-point", "quantization_scale", "=", "10.0", "/", "tf", ".", "int16", ".", "max", ",", "optimizer", "=", "\"DietAdam\"", ...
Default hyperparameters for a DietAdamOptimizer. Returns: a hyperparameters object.
[ "Default", "hyperparameters", "for", "a", "DietAdamOptimizer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L34-L51
train
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
diet_expert
def diet_expert(x, hidden_size, params): """A two-layer feed-forward network with relu activation on hidden layer. Uses diet variables. Recomputes hidden layer on backprop to save activation memory. Args: x: a Tensor with shape [batch, io_size] hidden_size: an integer params: a diet variable HPara...
python
def diet_expert(x, hidden_size, params): """A two-layer feed-forward network with relu activation on hidden layer. Uses diet variables. Recomputes hidden layer on backprop to save activation memory. Args: x: a Tensor with shape [batch, io_size] hidden_size: an integer params: a diet variable HPara...
[ "def", "diet_expert", "(", "x", ",", "hidden_size", ",", "params", ")", ":", "@", "fn_with_diet_vars", "(", "params", ")", "def", "diet_expert_internal", "(", "x", ")", ":", "dim", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", ...
A two-layer feed-forward network with relu activation on hidden layer. Uses diet variables. Recomputes hidden layer on backprop to save activation memory. Args: x: a Tensor with shape [batch, io_size] hidden_size: an integer params: a diet variable HParams object. Returns: a Tensor with shape...
[ "A", "two", "-", "layer", "feed", "-", "forward", "network", "with", "relu", "activation", "on", "hidden", "layer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L54-L77
train
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
_quantize
def _quantize(x, params, randomize=True): """Quantize x according to params, optionally randomizing the rounding.""" if not params.quantize: return x if not randomize: return tf.bitcast( tf.cast(x / params.quantization_scale, tf.int16), tf.float16) abs_x = tf.abs(x) sign_x = tf.sign(x) y =...
python
def _quantize(x, params, randomize=True): """Quantize x according to params, optionally randomizing the rounding.""" if not params.quantize: return x if not randomize: return tf.bitcast( tf.cast(x / params.quantization_scale, tf.int16), tf.float16) abs_x = tf.abs(x) sign_x = tf.sign(x) y =...
[ "def", "_quantize", "(", "x", ",", "params", ",", "randomize", "=", "True", ")", ":", "if", "not", "params", ".", "quantize", ":", "return", "x", "if", "not", "randomize", ":", "return", "tf", ".", "bitcast", "(", "tf", ".", "cast", "(", "x", "/", ...
Quantize x according to params, optionally randomizing the rounding.
[ "Quantize", "x", "according", "to", "params", "optionally", "randomizing", "the", "rounding", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L235-L250
train
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
_dequantize
def _dequantize(q, params): """Dequantize q according to params.""" if not params.quantize: return q return tf.to_float(tf.bitcast(q, tf.int16)) * params.quantization_scale
python
def _dequantize(q, params): """Dequantize q according to params.""" if not params.quantize: return q return tf.to_float(tf.bitcast(q, tf.int16)) * params.quantization_scale
[ "def", "_dequantize", "(", "q", ",", "params", ")", ":", "if", "not", "params", ".", "quantize", ":", "return", "q", "return", "tf", ".", "to_float", "(", "tf", ".", "bitcast", "(", "q", ",", "tf", ".", "int16", ")", ")", "*", "params", ".", "qua...
Dequantize q according to params.
[ "Dequantize", "q", "according", "to", "params", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L253-L257
train
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
make_diet_var_getter
def make_diet_var_getter(params): """Create a custom variable getter for diet variables according to params.""" def diet_var_initializer(shape, dtype, partition_info=None): """Initializer for a diet variable.""" del dtype del partition_info with common_layers.fn_device_dependency("diet_init") as o...
python
def make_diet_var_getter(params): """Create a custom variable getter for diet variables according to params.""" def diet_var_initializer(shape, dtype, partition_info=None): """Initializer for a diet variable.""" del dtype del partition_info with common_layers.fn_device_dependency("diet_init") as o...
[ "def", "make_diet_var_getter", "(", "params", ")", ":", "def", "diet_var_initializer", "(", "shape", ",", "dtype", ",", "partition_info", "=", "None", ")", ":", "\"\"\"Initializer for a diet variable.\"\"\"", "del", "dtype", "del", "partition_info", "with", "common_la...
Create a custom variable getter for diet variables according to params.
[ "Create", "a", "custom", "variable", "getter", "for", "diet", "variables", "according", "to", "params", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L260-L293
train
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
_fn_with_diet_vars
def _fn_with_diet_vars(fn, args, params): """Call function with args; use diet variables according to params.""" vs_ctr = [] def grad_fn(inputs, variables, outputs, output_grads): """Custom gradient function.""" del outputs # recomputing below with common_layers.fn_device_dependency("diet_grad", ...
python
def _fn_with_diet_vars(fn, args, params): """Call function with args; use diet variables according to params.""" vs_ctr = [] def grad_fn(inputs, variables, outputs, output_grads): """Custom gradient function.""" del outputs # recomputing below with common_layers.fn_device_dependency("diet_grad", ...
[ "def", "_fn_with_diet_vars", "(", "fn", ",", "args", ",", "params", ")", ":", "vs_ctr", "=", "[", "]", "def", "grad_fn", "(", "inputs", ",", "variables", ",", "outputs", ",", "output_grads", ")", ":", "\"\"\"Custom gradient function.\"\"\"", "del", "outputs", ...
Call function with args; use diet variables according to params.
[ "Call", "function", "with", "args", ";", "use", "diet", "variables", "according", "to", "params", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L296-L349
train
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
fn_with_diet_vars
def fn_with_diet_vars(params): """Decorator for graph-building function to use diet variables.""" params = copy.copy(params) def dec(fn): def wrapped(*args): return _fn_with_diet_vars(fn, args, params) return wrapped return dec
python
def fn_with_diet_vars(params): """Decorator for graph-building function to use diet variables.""" params = copy.copy(params) def dec(fn): def wrapped(*args): return _fn_with_diet_vars(fn, args, params) return wrapped return dec
[ "def", "fn_with_diet_vars", "(", "params", ")", ":", "params", "=", "copy", ".", "copy", "(", "params", ")", "def", "dec", "(", "fn", ")", ":", "def", "wrapped", "(", "*", "args", ")", ":", "return", "_fn_with_diet_vars", "(", "fn", ",", "args", ",",...
Decorator for graph-building function to use diet variables.
[ "Decorator", "for", "graph", "-", "building", "function", "to", "use", "diet", "variables", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L352-L363
train
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
DietAdamOptimizer.create_slots
def create_slots(self, var): """Create the factorized Adam accumulators for diet variables.""" params = self.params shape = var.get_shape().as_list() if not hasattr(params, "slots"): params.slots = defaultdict(dict) name = var.op.name slots = params.slots[name] if params.factored_se...
python
def create_slots(self, var): """Create the factorized Adam accumulators for diet variables.""" params = self.params shape = var.get_shape().as_list() if not hasattr(params, "slots"): params.slots = defaultdict(dict) name = var.op.name slots = params.slots[name] if params.factored_se...
[ "def", "create_slots", "(", "self", ",", "var", ")", ":", "params", "=", "self", ".", "params", "shape", "=", "var", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "if", "not", "hasattr", "(", "params", ",", "\"slots\"", ")", ":", "params", ...
Create the factorized Adam accumulators for diet variables.
[ "Create", "the", "factorized", "Adam", "accumulators", "for", "diet", "variables", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L144-L175
train
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
DietAdamOptimizer.update_variable
def update_variable(self, var, grad_var): """Update the variable and its slots.""" params = self.params global_step = tf.to_float(self.global_step) + 1 # compute learning rate lrate = params.learning_rate if params.learning_rate_decay_scheme == "noam": lrate *= tf.minimum(global_step * pa...
python
def update_variable(self, var, grad_var): """Update the variable and its slots.""" params = self.params global_step = tf.to_float(self.global_step) + 1 # compute learning rate lrate = params.learning_rate if params.learning_rate_decay_scheme == "noam": lrate *= tf.minimum(global_step * pa...
[ "def", "update_variable", "(", "self", ",", "var", ",", "grad_var", ")", ":", "params", "=", "self", ".", "params", "global_step", "=", "tf", ".", "to_float", "(", "self", ".", "global_step", ")", "+", "1", "# compute learning rate", "lrate", "=", "params"...
Update the variable and its slots.
[ "Update", "the", "variable", "and", "its", "slots", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L177-L225
train
tensorflow/tensor2tensor
tensor2tensor/utils/mtf_model.py
MtfModel.estimator_spec_eval
def estimator_spec_eval( self, features, logits, labels, loss, restore_hook, use_tpu): """Construct EstimatorSpec for EVAL mode.""" hparams = self.hparams problem = hparams.problem if logits.get_shape().ndims == 3: logits = tf.expand_dims(tf.expand_dims(logits, 2), 3) # Support for mult...
python
def estimator_spec_eval( self, features, logits, labels, loss, restore_hook, use_tpu): """Construct EstimatorSpec for EVAL mode.""" hparams = self.hparams problem = hparams.problem if logits.get_shape().ndims == 3: logits = tf.expand_dims(tf.expand_dims(logits, 2), 3) # Support for mult...
[ "def", "estimator_spec_eval", "(", "self", ",", "features", ",", "logits", ",", "labels", ",", "loss", ",", "restore_hook", ",", "use_tpu", ")", ":", "hparams", "=", "self", ".", "hparams", "problem", "=", "hparams", ".", "problem", "if", "logits", ".", ...
Construct EstimatorSpec for EVAL mode.
[ "Construct", "EstimatorSpec", "for", "EVAL", "mode", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/mtf_model.py#L188-L229
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/desc2code.py
generator_samples
def generator_samples(tmp_dir, pb_cst): """Generator for the dataset samples. If not present, download and extract the dataset. Args: tmp_dir: path to the directory where to download the dataset. pb_cst: CodingPbConstants object defining paths Yields: A CodingPbInfo object containing the next cha...
python
def generator_samples(tmp_dir, pb_cst): """Generator for the dataset samples. If not present, download and extract the dataset. Args: tmp_dir: path to the directory where to download the dataset. pb_cst: CodingPbConstants object defining paths Yields: A CodingPbInfo object containing the next cha...
[ "def", "generator_samples", "(", "tmp_dir", ",", "pb_cst", ")", ":", "# Step1: Download dataset (eventually)", "data_zip_path", "=", "generator_utils", ".", "maybe_download_from_drive", "(", "directory", "=", "tmp_dir", ",", "filename", "=", "_DATASET_FILENAME", ",", "u...
Generator for the dataset samples. If not present, download and extract the dataset. Args: tmp_dir: path to the directory where to download the dataset. pb_cst: CodingPbConstants object defining paths Yields: A CodingPbInfo object containing the next challenge informations.
[ "Generator", "for", "the", "dataset", "samples", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/desc2code.py#L240-L308
train
tensorflow/tensor2tensor
tensor2tensor/models/lstm.py
lstm
def lstm(inputs, sequence_length, hparams, train, name, initial_state=None): """Adds a stack of LSTM layers on top of input. Args: inputs: The input `Tensor`, shaped `[batch_size, time_steps, hidden_size]`. sequence_length: Lengths of the actual input sequence, excluding padding; a `Tensor` shaped ...
python
def lstm(inputs, sequence_length, hparams, train, name, initial_state=None): """Adds a stack of LSTM layers on top of input. Args: inputs: The input `Tensor`, shaped `[batch_size, time_steps, hidden_size]`. sequence_length: Lengths of the actual input sequence, excluding padding; a `Tensor` shaped ...
[ "def", "lstm", "(", "inputs", ",", "sequence_length", ",", "hparams", ",", "train", ",", "name", ",", "initial_state", "=", "None", ")", ":", "layers", "=", "[", "_dropout_lstm_cell", "(", "hparams", ",", "train", ")", "for", "_", "in", "range", "(", "...
Adds a stack of LSTM layers on top of input. Args: inputs: The input `Tensor`, shaped `[batch_size, time_steps, hidden_size]`. sequence_length: Lengths of the actual input sequence, excluding padding; a `Tensor` shaped `[batch_size]`. hparams: HParams; hyperparameters. train: bool; `True` whe...
[ "Adds", "a", "stack", "of", "LSTM", "layers", "on", "top", "of", "input", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L38-L67
train
tensorflow/tensor2tensor
tensor2tensor/models/lstm.py
lstm_attention_decoder
def lstm_attention_decoder(inputs, hparams, train, name, initial_state, encoder_outputs, encoder_output_length, decoder_input_length): """Run LSTM cell with attention on inputs of shape [batch x time x size]. Args: inputs: The decoder input `Tensor`, shaped...
python
def lstm_attention_decoder(inputs, hparams, train, name, initial_state, encoder_outputs, encoder_output_length, decoder_input_length): """Run LSTM cell with attention on inputs of shape [batch x time x size]. Args: inputs: The decoder input `Tensor`, shaped...
[ "def", "lstm_attention_decoder", "(", "inputs", ",", "hparams", ",", "train", ",", "name", ",", "initial_state", ",", "encoder_outputs", ",", "encoder_output_length", ",", "decoder_input_length", ")", ":", "layers", "=", "[", "_dropout_lstm_cell", "(", "hparams", ...
Run LSTM cell with attention on inputs of shape [batch x time x size]. Args: inputs: The decoder input `Tensor`, shaped `[batch_size, decoder_steps, hidden_size]`. hparams: HParams; hyperparameters. train: bool; `True` when constructing training graph to enable dropout. name: string; Create v...
[ "Run", "LSTM", "cell", "with", "attention", "on", "inputs", "of", "shape", "[", "batch", "x", "time", "x", "size", "]", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L70-L174
train
tensorflow/tensor2tensor
tensor2tensor/models/lstm.py
lstm_seq2seq_internal
def lstm_seq2seq_internal(inputs, targets, hparams, train): """The basic LSTM seq2seq model, main step used for training.""" with tf.variable_scope("lstm_seq2seq"): if inputs is not None: inputs_length = common_layers.length_from_embedding(inputs) # Flatten inputs. inputs = common_layers.flatt...
python
def lstm_seq2seq_internal(inputs, targets, hparams, train): """The basic LSTM seq2seq model, main step used for training.""" with tf.variable_scope("lstm_seq2seq"): if inputs is not None: inputs_length = common_layers.length_from_embedding(inputs) # Flatten inputs. inputs = common_layers.flatt...
[ "def", "lstm_seq2seq_internal", "(", "inputs", ",", "targets", ",", "hparams", ",", "train", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"lstm_seq2seq\"", ")", ":", "if", "inputs", "is", "not", "None", ":", "inputs_length", "=", "common_layers", "....
The basic LSTM seq2seq model, main step used for training.
[ "The", "basic", "LSTM", "seq2seq", "model", "main", "step", "used", "for", "training", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L177-L203
train
tensorflow/tensor2tensor
tensor2tensor/models/lstm.py
lstm_seq2seq_internal_attention
def lstm_seq2seq_internal_attention(inputs, targets, hparams, train, inputs_length, targets_length): """LSTM seq2seq model with attention, main step used for training.""" with tf.variable_scope("lstm_seq2seq_attention"): # Flatten inputs. inputs = common_layers.flatten4d3...
python
def lstm_seq2seq_internal_attention(inputs, targets, hparams, train, inputs_length, targets_length): """LSTM seq2seq model with attention, main step used for training.""" with tf.variable_scope("lstm_seq2seq_attention"): # Flatten inputs. inputs = common_layers.flatten4d3...
[ "def", "lstm_seq2seq_internal_attention", "(", "inputs", ",", "targets", ",", "hparams", ",", "train", ",", "inputs_length", ",", "targets_length", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"lstm_seq2seq_attention\"", ")", ":", "# Flatten inputs.", "inpu...
LSTM seq2seq model with attention, main step used for training.
[ "LSTM", "seq2seq", "model", "with", "attention", "main", "step", "used", "for", "training", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L206-L225
train
tensorflow/tensor2tensor
tensor2tensor/models/lstm.py
lstm_bid_encoder
def lstm_bid_encoder(inputs, sequence_length, hparams, train, name): """Bidirectional LSTM for encoding inputs that are [batch x time x size].""" with tf.variable_scope(name): cell_fw = tf.nn.rnn_cell.MultiRNNCell( [_dropout_lstm_cell(hparams, train) for _ in range(hparams.num_hidden_layers)])...
python
def lstm_bid_encoder(inputs, sequence_length, hparams, train, name): """Bidirectional LSTM for encoding inputs that are [batch x time x size].""" with tf.variable_scope(name): cell_fw = tf.nn.rnn_cell.MultiRNNCell( [_dropout_lstm_cell(hparams, train) for _ in range(hparams.num_hidden_layers)])...
[ "def", "lstm_bid_encoder", "(", "inputs", ",", "sequence_length", ",", "hparams", ",", "train", ",", "name", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "cell_fw", "=", "tf", ".", "nn", ".", "rnn_cell", ".", "MultiRNNCell", "(",...
Bidirectional LSTM for encoding inputs that are [batch x time x size].
[ "Bidirectional", "LSTM", "for", "encoding", "inputs", "that", "are", "[", "batch", "x", "time", "x", "size", "]", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L228-L273
train
tensorflow/tensor2tensor
tensor2tensor/models/lstm.py
lstm_seq2seq_internal_bid_encoder
def lstm_seq2seq_internal_bid_encoder(inputs, targets, hparams, train): """The basic LSTM seq2seq model with bidirectional encoder.""" with tf.variable_scope("lstm_seq2seq_bid_encoder"): if inputs is not None: inputs_length = common_layers.length_from_embedding(inputs) # Flatten inputs. inputs...
python
def lstm_seq2seq_internal_bid_encoder(inputs, targets, hparams, train): """The basic LSTM seq2seq model with bidirectional encoder.""" with tf.variable_scope("lstm_seq2seq_bid_encoder"): if inputs is not None: inputs_length = common_layers.length_from_embedding(inputs) # Flatten inputs. inputs...
[ "def", "lstm_seq2seq_internal_bid_encoder", "(", "inputs", ",", "targets", ",", "hparams", ",", "train", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"lstm_seq2seq_bid_encoder\"", ")", ":", "if", "inputs", "is", "not", "None", ":", "inputs_length", "=",...
The basic LSTM seq2seq model with bidirectional encoder.
[ "The", "basic", "LSTM", "seq2seq", "model", "with", "bidirectional", "encoder", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L276-L302
train
tensorflow/tensor2tensor
tensor2tensor/models/lstm.py
lstm_seq2seq_internal_attention_bid_encoder
def lstm_seq2seq_internal_attention_bid_encoder(inputs, targets, hparams, train): """LSTM seq2seq model with attention, main step used for training.""" with tf.variable_scope("lstm_seq2seq_attention_bid_encoder"): inputs_length = common_layers.length_from_embeddin...
python
def lstm_seq2seq_internal_attention_bid_encoder(inputs, targets, hparams, train): """LSTM seq2seq model with attention, main step used for training.""" with tf.variable_scope("lstm_seq2seq_attention_bid_encoder"): inputs_length = common_layers.length_from_embeddin...
[ "def", "lstm_seq2seq_internal_attention_bid_encoder", "(", "inputs", ",", "targets", ",", "hparams", ",", "train", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"lstm_seq2seq_attention_bid_encoder\"", ")", ":", "inputs_length", "=", "common_layers", ".", "leng...
LSTM seq2seq model with attention, main step used for training.
[ "LSTM", "seq2seq", "model", "with", "attention", "main", "step", "used", "for", "training", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L305-L325
train
tensorflow/tensor2tensor
tensor2tensor/models/lstm.py
lstm_seq2seq
def lstm_seq2seq(): """hparams for LSTM.""" hparams = common_hparams.basic_params1() hparams.daisy_chain_variables = False hparams.batch_size = 1024 hparams.hidden_size = 128 hparams.num_hidden_layers = 2 hparams.initializer = "uniform_unit_scaling" hparams.initializer_gain = 1.0 hparams.weight_decay ...
python
def lstm_seq2seq(): """hparams for LSTM.""" hparams = common_hparams.basic_params1() hparams.daisy_chain_variables = False hparams.batch_size = 1024 hparams.hidden_size = 128 hparams.num_hidden_layers = 2 hparams.initializer = "uniform_unit_scaling" hparams.initializer_gain = 1.0 hparams.weight_decay ...
[ "def", "lstm_seq2seq", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "daisy_chain_variables", "=", "False", "hparams", ".", "batch_size", "=", "1024", "hparams", ".", "hidden_size", "=", "128", "hparams", ".",...
hparams for LSTM.
[ "hparams", "for", "LSTM", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L410-L420
train
tensorflow/tensor2tensor
tensor2tensor/models/lstm.py
lstm_attention_base
def lstm_attention_base(): """Base attention params.""" hparams = lstm_seq2seq() hparams.add_hparam("attention_layer_size", hparams.hidden_size) hparams.add_hparam("output_attention", True) hparams.add_hparam("num_heads", 1) return hparams
python
def lstm_attention_base(): """Base attention params.""" hparams = lstm_seq2seq() hparams.add_hparam("attention_layer_size", hparams.hidden_size) hparams.add_hparam("output_attention", True) hparams.add_hparam("num_heads", 1) return hparams
[ "def", "lstm_attention_base", "(", ")", ":", "hparams", "=", "lstm_seq2seq", "(", ")", "hparams", ".", "add_hparam", "(", "\"attention_layer_size\"", ",", "hparams", ".", "hidden_size", ")", "hparams", ".", "add_hparam", "(", "\"output_attention\"", ",", "True", ...
Base attention params.
[ "Base", "attention", "params", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L423-L429
train
tensorflow/tensor2tensor
tensor2tensor/models/lstm.py
lstm_asr_v1
def lstm_asr_v1(): """Basic LSTM Params.""" hparams = lstm_bahdanau_attention() hparams.num_hidden_layers = 2 hparams.hidden_size = 256 hparams.batch_size = 36 hparams.max_input_seq_length = 600000 hparams.max_target_seq_length = 350 hparams.max_length = hparams.max_input_seq_length hparams.min_length...
python
def lstm_asr_v1(): """Basic LSTM Params.""" hparams = lstm_bahdanau_attention() hparams.num_hidden_layers = 2 hparams.hidden_size = 256 hparams.batch_size = 36 hparams.max_input_seq_length = 600000 hparams.max_target_seq_length = 350 hparams.max_length = hparams.max_input_seq_length hparams.min_length...
[ "def", "lstm_asr_v1", "(", ")", ":", "hparams", "=", "lstm_bahdanau_attention", "(", ")", "hparams", ".", "num_hidden_layers", "=", "2", "hparams", ".", "hidden_size", "=", "256", "hparams", ".", "batch_size", "=", "36", "hparams", ".", "max_input_seq_length", ...
Basic LSTM Params.
[ "Basic", "LSTM", "Params", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L471-L482
train
tensorflow/tensor2tensor
tensor2tensor/models/lstm.py
lstm_area_attention_base
def lstm_area_attention_base(): """Hparams for LSTM with area attention.""" hparams = lstm_luong_attention() hparams.batch_size = 16384 hparams.num_hidden_layers = 2 hparams.hidden_size = 1024 hparams.num_heads = 4 hparams.dropout = 0.2 hparams.learning_rate = 0.1 hparams.max_area_width = 2 hparams....
python
def lstm_area_attention_base(): """Hparams for LSTM with area attention.""" hparams = lstm_luong_attention() hparams.batch_size = 16384 hparams.num_hidden_layers = 2 hparams.hidden_size = 1024 hparams.num_heads = 4 hparams.dropout = 0.2 hparams.learning_rate = 0.1 hparams.max_area_width = 2 hparams....
[ "def", "lstm_area_attention_base", "(", ")", ":", "hparams", "=", "lstm_luong_attention", "(", ")", "hparams", ".", "batch_size", "=", "16384", "hparams", ".", "num_hidden_layers", "=", "2", "hparams", ".", "hidden_size", "=", "1024", "hparams", ".", "num_heads"...
Hparams for LSTM with area attention.
[ "Hparams", "for", "LSTM", "with", "area", "attention", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L486-L498
train
tensorflow/tensor2tensor
tensor2tensor/bin/t2t_attack.py
create_surrogate_run_config
def create_surrogate_run_config(hp): """Create a run config. Args: hp: model hyperparameters Returns: a run config """ save_ckpt_steps = max(FLAGS.iterations_per_loop, FLAGS.local_eval_frequency) save_ckpt_secs = FLAGS.save_checkpoints_secs or None if save_ckpt_secs: save_ckpt_steps = None ...
python
def create_surrogate_run_config(hp): """Create a run config. Args: hp: model hyperparameters Returns: a run config """ save_ckpt_steps = max(FLAGS.iterations_per_loop, FLAGS.local_eval_frequency) save_ckpt_secs = FLAGS.save_checkpoints_secs or None if save_ckpt_secs: save_ckpt_steps = None ...
[ "def", "create_surrogate_run_config", "(", "hp", ")", ":", "save_ckpt_steps", "=", "max", "(", "FLAGS", ".", "iterations_per_loop", ",", "FLAGS", ".", "local_eval_frequency", ")", "save_ckpt_secs", "=", "FLAGS", ".", "save_checkpoints_secs", "or", "None", "if", "s...
Create a run config. Args: hp: model hyperparameters Returns: a run config
[ "Create", "a", "run", "config", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_attack.py#L83-L131
train
tensorflow/tensor2tensor
tensor2tensor/bin/t2t_attack.py
prepare_data
def prepare_data(problem, hparams, params, config): """Construct input pipeline.""" input_fn = problem.make_estimator_input_fn( tf.estimator.ModeKeys.EVAL, hparams, force_repeat=True) dataset = input_fn(params, config) features, _ = dataset.make_one_shot_iterator().get_next() inputs, labels = features["...
python
def prepare_data(problem, hparams, params, config): """Construct input pipeline.""" input_fn = problem.make_estimator_input_fn( tf.estimator.ModeKeys.EVAL, hparams, force_repeat=True) dataset = input_fn(params, config) features, _ = dataset.make_one_shot_iterator().get_next() inputs, labels = features["...
[ "def", "prepare_data", "(", "problem", ",", "hparams", ",", "params", ",", "config", ")", ":", "input_fn", "=", "problem", ".", "make_estimator_input_fn", "(", "tf", ".", "estimator", ".", "ModeKeys", ".", "EVAL", ",", "hparams", ",", "force_repeat", "=", ...
Construct input pipeline.
[ "Construct", "input", "pipeline", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_attack.py#L134-L145
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/audio_encoder.py
AudioEncoder.encode
def encode(self, s): """Transform a string with a filename into a list of float32. Args: s: path to the file with a waveform. Returns: samples: list of int16s """ # Make sure that the data is a single channel, 16bit, 16kHz wave. # TODO(chorowski): the directory may not be writable,...
python
def encode(self, s): """Transform a string with a filename into a list of float32. Args: s: path to the file with a waveform. Returns: samples: list of int16s """ # Make sure that the data is a single channel, 16bit, 16kHz wave. # TODO(chorowski): the directory may not be writable,...
[ "def", "encode", "(", "self", ",", "s", ")", ":", "# Make sure that the data is a single channel, 16bit, 16kHz wave.", "# TODO(chorowski): the directory may not be writable, this should fallback", "# to a temp path, and provide instructions for installing sox.", "if", "s", ".", "endswith...
Transform a string with a filename into a list of float32. Args: s: path to the file with a waveform. Returns: samples: list of int16s
[ "Transform", "a", "string", "with", "a", "filename", "into", "a", "list", "of", "float32", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/audio_encoder.py#L36-L65
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/audio_encoder.py
AudioEncoder.decode
def decode(self, ids): """Transform a sequence of float32 into a waveform. Args: ids: list of integers to be converted. Returns: Path to the temporary file where the waveform was saved. Raises: ValueError: if the ids are not of the appropriate size. """ _, tmp_file_path = te...
python
def decode(self, ids): """Transform a sequence of float32 into a waveform. Args: ids: list of integers to be converted. Returns: Path to the temporary file where the waveform was saved. Raises: ValueError: if the ids are not of the appropriate size. """ _, tmp_file_path = te...
[ "def", "decode", "(", "self", ",", "ids", ")", ":", "_", ",", "tmp_file_path", "=", "tempfile", ".", "mkstemp", "(", ")", "wavfile", ".", "write", "(", "tmp_file_path", ",", "self", ".", "_sample_rate", ",", "np", ".", "asarray", "(", "ids", ")", ")"...
Transform a sequence of float32 into a waveform. Args: ids: list of integers to be converted. Returns: Path to the temporary file where the waveform was saved. Raises: ValueError: if the ids are not of the appropriate size.
[ "Transform", "a", "sequence", "of", "float32", "into", "a", "waveform", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/audio_encoder.py#L67-L81
train
tensorflow/tensor2tensor
tensor2tensor/insights/graph.py
Graph.new_vertex
def new_vertex(self): """Creates and returns a new vertex. Returns: A new Vertex instance with a unique index. """ vertex = Vertex(len(self.vertices)) self.vertices.append(vertex) return vertex
python
def new_vertex(self): """Creates and returns a new vertex. Returns: A new Vertex instance with a unique index. """ vertex = Vertex(len(self.vertices)) self.vertices.append(vertex) return vertex
[ "def", "new_vertex", "(", "self", ")", ":", "vertex", "=", "Vertex", "(", "len", "(", "self", ".", "vertices", ")", ")", "self", ".", "vertices", ".", "append", "(", "vertex", ")", "return", "vertex" ]
Creates and returns a new vertex. Returns: A new Vertex instance with a unique index.
[ "Creates", "and", "returns", "a", "new", "vertex", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/insights/graph.py#L102-L110
train
tensorflow/tensor2tensor
tensor2tensor/insights/graph.py
Graph.get_vertex
def get_vertex(self, key): """Returns or Creates a Vertex mapped by key. Args: key: A string reference for a vertex. May refer to a new Vertex in which case it will be created. Returns: A the Vertex mapped to by key. """ if key in self.vertex_map: return self.vertex_map[ke...
python
def get_vertex(self, key): """Returns or Creates a Vertex mapped by key. Args: key: A string reference for a vertex. May refer to a new Vertex in which case it will be created. Returns: A the Vertex mapped to by key. """ if key in self.vertex_map: return self.vertex_map[ke...
[ "def", "get_vertex", "(", "self", ",", "key", ")", ":", "if", "key", "in", "self", ".", "vertex_map", ":", "return", "self", ".", "vertex_map", "[", "key", "]", "vertex", "=", "self", ".", "new_vertex", "(", ")", "self", ".", "vertex_map", "[", "key"...
Returns or Creates a Vertex mapped by key. Args: key: A string reference for a vertex. May refer to a new Vertex in which case it will be created. Returns: A the Vertex mapped to by key.
[ "Returns", "or", "Creates", "a", "Vertex", "mapped", "by", "key", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/insights/graph.py#L112-L126
train
tensorflow/tensor2tensor
tensor2tensor/insights/graph.py
Graph.add_edge
def add_edge(self, source, target): """Returns a new edge connecting source and target vertices. Args: source: The source Vertex. target: The target Vertex. Returns: A new Edge linking source to target. """ edge = Edge(len(self.edges)) self.edges.append(edge) source.out_e...
python
def add_edge(self, source, target): """Returns a new edge connecting source and target vertices. Args: source: The source Vertex. target: The target Vertex. Returns: A new Edge linking source to target. """ edge = Edge(len(self.edges)) self.edges.append(edge) source.out_e...
[ "def", "add_edge", "(", "self", ",", "source", ",", "target", ")", ":", "edge", "=", "Edge", "(", "len", "(", "self", ".", "edges", ")", ")", "self", ".", "edges", ".", "append", "(", "edge", ")", "source", ".", "out_edges", ".", "append", "(", "...
Returns a new edge connecting source and target vertices. Args: source: The source Vertex. target: The target Vertex. Returns: A new Edge linking source to target.
[ "Returns", "a", "new", "edge", "connecting", "source", "and", "target", "vertices", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/insights/graph.py#L128-L144
train
tensorflow/tensor2tensor
tensor2tensor/insights/graph.py
Graph.to_dict
def to_dict(self): """Returns a simplified dictionary representing the Graph. Returns: A dictionary that can easily be serialized to JSON. """ return { "node": [v.to_dict() for v in self.vertices], "edge": [e.to_dict() for e in self.edges] }
python
def to_dict(self): """Returns a simplified dictionary representing the Graph. Returns: A dictionary that can easily be serialized to JSON. """ return { "node": [v.to_dict() for v in self.vertices], "edge": [e.to_dict() for e in self.edges] }
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "\"node\"", ":", "[", "v", ".", "to_dict", "(", ")", "for", "v", "in", "self", ".", "vertices", "]", ",", "\"edge\"", ":", "[", "e", ".", "to_dict", "(", ")", "for", "e", "in", "self", "."...
Returns a simplified dictionary representing the Graph. Returns: A dictionary that can easily be serialized to JSON.
[ "Returns", "a", "simplified", "dictionary", "representing", "the", "Graph", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/insights/graph.py#L146-L155
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
attend
def attend(x, source, hparams, name): """Self-attention layer with source as memory antecedent.""" with tf.variable_scope(name): x = tf.squeeze(x, axis=2) if len(source.get_shape()) > 3: source = tf.squeeze(source, axis=2) source = common_attention.add_timing_signal_1d(source) y = common_atten...
python
def attend(x, source, hparams, name): """Self-attention layer with source as memory antecedent.""" with tf.variable_scope(name): x = tf.squeeze(x, axis=2) if len(source.get_shape()) > 3: source = tf.squeeze(source, axis=2) source = common_attention.add_timing_signal_1d(source) y = common_atten...
[ "def", "attend", "(", "x", ",", "source", ",", "hparams", ",", "name", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "x", "=", "tf", ".", "squeeze", "(", "x", ",", "axis", "=", "2", ")", "if", "len", "(", "source", ".", ...
Self-attention layer with source as memory antecedent.
[ "Self", "-", "attention", "layer", "with", "source", "as", "memory", "antecedent", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L62-L76
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
top_k_softmax
def top_k_softmax(x, k): """Calculate softmax(x), select top-k and rescale to sum to 1.""" x = tf.nn.softmax(x) top_x, _ = tf.nn.top_k(x, k=k+1) min_top = tf.reduce_min(top_x, axis=-1, keepdims=True) x = tf.nn.relu((x - min_top) + 1e-12) x /= tf.reduce_sum(x, axis=-1, keepdims=True) return x, tf.reduce_ma...
python
def top_k_softmax(x, k): """Calculate softmax(x), select top-k and rescale to sum to 1.""" x = tf.nn.softmax(x) top_x, _ = tf.nn.top_k(x, k=k+1) min_top = tf.reduce_min(top_x, axis=-1, keepdims=True) x = tf.nn.relu((x - min_top) + 1e-12) x /= tf.reduce_sum(x, axis=-1, keepdims=True) return x, tf.reduce_ma...
[ "def", "top_k_softmax", "(", "x", ",", "k", ")", ":", "x", "=", "tf", ".", "nn", ".", "softmax", "(", "x", ")", "top_x", ",", "_", "=", "tf", ".", "nn", ".", "top_k", "(", "x", ",", "k", "=", "k", "+", "1", ")", "min_top", "=", "tf", ".",...
Calculate softmax(x), select top-k and rescale to sum to 1.
[ "Calculate", "softmax", "(", "x", ")", "select", "top", "-", "k", "and", "rescale", "to", "sum", "to", "1", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L93-L100
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
compress
def compress(x, c, is_2d, hparams, name): """Compress.""" with tf.variable_scope(name): # Run compression by strided convs. cur = x k1 = (3, 3) if is_2d else (3, 1) k2 = (2, 2) if is_2d else (2, 1) cur = residual_conv(cur, hparams.num_compress_steps, k1, hparams, "rc") if c is not None and h...
python
def compress(x, c, is_2d, hparams, name): """Compress.""" with tf.variable_scope(name): # Run compression by strided convs. cur = x k1 = (3, 3) if is_2d else (3, 1) k2 = (2, 2) if is_2d else (2, 1) cur = residual_conv(cur, hparams.num_compress_steps, k1, hparams, "rc") if c is not None and h...
[ "def", "compress", "(", "x", ",", "c", ",", "is_2d", ",", "hparams", ",", "name", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "# Run compression by strided convs.", "cur", "=", "x", "k1", "=", "(", "3", ",", "3", ")", "if", ...
Compress.
[ "Compress", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L115-L132
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
decode_transformer
def decode_transformer(encoder_output, encoder_decoder_attention_bias, targets, hparams, name, task=None, causal=True): """Original Transformer decoder.""" orig_hparams = hparams...
python
def decode_transformer(encoder_output, encoder_decoder_attention_bias, targets, hparams, name, task=None, causal=True): """Original Transformer decoder.""" orig_hparams = hparams...
[ "def", "decode_transformer", "(", "encoder_output", ",", "encoder_decoder_attention_bias", ",", "targets", ",", "hparams", ",", "name", ",", "task", "=", "None", ",", "causal", "=", "True", ")", ":", "orig_hparams", "=", "hparams", "with", "tf", ".", "variable...
Original Transformer decoder.
[ "Original", "Transformer", "decoder", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L145-L208
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
ae_latent_softmax
def ae_latent_softmax(latents_pred, latents_discrete, hparams): """Latent prediction and loss.""" vocab_size = 2 ** hparams.z_size if hparams.num_decode_blocks < 2: latents_logits = tf.layers.dense(latents_pred, vocab_size, name="extra_logits") if hparams.logit_normali...
python
def ae_latent_softmax(latents_pred, latents_discrete, hparams): """Latent prediction and loss.""" vocab_size = 2 ** hparams.z_size if hparams.num_decode_blocks < 2: latents_logits = tf.layers.dense(latents_pred, vocab_size, name="extra_logits") if hparams.logit_normali...
[ "def", "ae_latent_softmax", "(", "latents_pred", ",", "latents_discrete", ",", "hparams", ")", ":", "vocab_size", "=", "2", "**", "hparams", ".", "z_size", "if", "hparams", ".", "num_decode_blocks", "<", "2", ":", "latents_logits", "=", "tf", ".", "layers", ...
Latent prediction and loss.
[ "Latent", "prediction", "and", "loss", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L221-L267
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
ae_latent_sample
def ae_latent_sample(latents_dense, inputs, ed, embed, iters, hparams): """Sample from the latent space in the autoencoder.""" if hparams.num_decode_blocks < 2 and hparams.sampling_temp == 0.0: # TODO(lukaszkaiser): beam-search only works in non-blocked mode for now. tf.logging.info("Running beam-search for...
python
def ae_latent_sample(latents_dense, inputs, ed, embed, iters, hparams): """Sample from the latent space in the autoencoder.""" if hparams.num_decode_blocks < 2 and hparams.sampling_temp == 0.0: # TODO(lukaszkaiser): beam-search only works in non-blocked mode for now. tf.logging.info("Running beam-search for...
[ "def", "ae_latent_sample", "(", "latents_dense", ",", "inputs", ",", "ed", ",", "embed", ",", "iters", ",", "hparams", ")", ":", "if", "hparams", ".", "num_decode_blocks", "<", "2", "and", "hparams", ".", "sampling_temp", "==", "0.0", ":", "# TODO(lukaszkais...
Sample from the latent space in the autoencoder.
[ "Sample", "from", "the", "latent", "space", "in", "the", "autoencoder", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L301-L322
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
ae_transformer_internal
def ae_transformer_internal(inputs, targets, target_space, hparams, cache=None, predict_mask=1.0): """AE Transformer, main step used for training.""" # Summaries break with the...
python
def ae_transformer_internal(inputs, targets, target_space, hparams, cache=None, predict_mask=1.0): """AE Transformer, main step used for training.""" # Summaries break with the...
[ "def", "ae_transformer_internal", "(", "inputs", ",", "targets", ",", "target_space", ",", "hparams", ",", "cache", "=", "None", ",", "predict_mask", "=", "1.0", ")", ":", "# Summaries break with the do_refine cond, turn them off in that case.", "global", "_DO_SUMMARIES",...
AE Transformer, main step used for training.
[ "AE", "Transformer", "main", "step", "used", "for", "training", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L325-L536
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
transformer_ae_small
def transformer_ae_small(): """Set of hyperparameters.""" hparams = transformer.transformer_small() hparams.batch_size = 2048 hparams.learning_rate = 0.2 hparams.learning_rate_warmup_steps = 4000 hparams.num_hidden_layers = 3 hparams.hidden_size = 384 hparams.filter_size = 2048 hparams.add_hparam("com...
python
def transformer_ae_small(): """Set of hyperparameters.""" hparams = transformer.transformer_small() hparams.batch_size = 2048 hparams.learning_rate = 0.2 hparams.learning_rate_warmup_steps = 4000 hparams.num_hidden_layers = 3 hparams.hidden_size = 384 hparams.filter_size = 2048 hparams.add_hparam("com...
[ "def", "transformer_ae_small", "(", ")", ":", "hparams", "=", "transformer", ".", "transformer_small", "(", ")", "hparams", ".", "batch_size", "=", "2048", "hparams", ".", "learning_rate", "=", "0.2", "hparams", ".", "learning_rate_warmup_steps", "=", "4000", "h...
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L760-L830
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
imagetransformer_ae_cifar
def imagetransformer_ae_cifar(): """Hyperparameters for CIFAR-10 experiments.""" hparams = transformer_ae_small() hparams.filter_size = 512 hparams.num_compress_steps = 3 hparams.startup_steps = 10000 hparams.is_2d = 0 hparams.learning_rate_warmup_steps = 8000 hparams.learning_rate = 0.2 hparams.hidde...
python
def imagetransformer_ae_cifar(): """Hyperparameters for CIFAR-10 experiments.""" hparams = transformer_ae_small() hparams.filter_size = 512 hparams.num_compress_steps = 3 hparams.startup_steps = 10000 hparams.is_2d = 0 hparams.learning_rate_warmup_steps = 8000 hparams.learning_rate = 0.2 hparams.hidde...
[ "def", "imagetransformer_ae_cifar", "(", ")", ":", "hparams", "=", "transformer_ae_small", "(", ")", "hparams", ".", "filter_size", "=", "512", "hparams", ".", "num_compress_steps", "=", "3", "hparams", ".", "startup_steps", "=", "10000", "hparams", ".", "is_2d"...
Hyperparameters for CIFAR-10 experiments.
[ "Hyperparameters", "for", "CIFAR", "-", "10", "experiments", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L834-L904
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
imagetransformer_ae_imagenet
def imagetransformer_ae_imagenet(): """For 64x64 ImageNet. ~56M trainable variables.""" hparams = imagetransformer_ae_cifar() hparams.max_length = int(64 * 64 * 3) hparams.img_len = 64 hparams.num_heads = 4 # Heads are expensive on TPUs. # Reduce architecture from 32x32 CIFAR-10 in order to fit in memory. ...
python
def imagetransformer_ae_imagenet(): """For 64x64 ImageNet. ~56M trainable variables.""" hparams = imagetransformer_ae_cifar() hparams.max_length = int(64 * 64 * 3) hparams.img_len = 64 hparams.num_heads = 4 # Heads are expensive on TPUs. # Reduce architecture from 32x32 CIFAR-10 in order to fit in memory. ...
[ "def", "imagetransformer_ae_imagenet", "(", ")", ":", "hparams", "=", "imagetransformer_ae_cifar", "(", ")", "hparams", ".", "max_length", "=", "int", "(", "64", "*", "64", "*", "3", ")", "hparams", ".", "img_len", "=", "64", "hparams", ".", "num_heads", "...
For 64x64 ImageNet. ~56M trainable variables.
[ "For", "64x64", "ImageNet", ".", "~56M", "trainable", "variables", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L907-L916
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
transformer_ae_base
def transformer_ae_base(): """Set of hyperparameters.""" hparams = transformer_ae_small() hparams.batch_size = 2048 hparams.hidden_size = 512 hparams.filter_size = 4096 hparams.num_hidden_layers = 6 return hparams
python
def transformer_ae_base(): """Set of hyperparameters.""" hparams = transformer_ae_small() hparams.batch_size = 2048 hparams.hidden_size = 512 hparams.filter_size = 4096 hparams.num_hidden_layers = 6 return hparams
[ "def", "transformer_ae_base", "(", ")", ":", "hparams", "=", "transformer_ae_small", "(", ")", "hparams", ".", "batch_size", "=", "2048", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "filter_size", "=", "4096", "hparams", ".", "num_hidden_layers", ...
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L920-L927
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
transformer_ae_a3
def transformer_ae_a3(): """Set of hyperparameters.""" hparams = transformer_ae_base() hparams.batch_size = 4096 hparams.layer_prepostprocess_dropout = 0.3 hparams.optimizer = "Adafactor" hparams.learning_rate = 0.25 hparams.learning_rate_warmup_steps = 10000 return hparams
python
def transformer_ae_a3(): """Set of hyperparameters.""" hparams = transformer_ae_base() hparams.batch_size = 4096 hparams.layer_prepostprocess_dropout = 0.3 hparams.optimizer = "Adafactor" hparams.learning_rate = 0.25 hparams.learning_rate_warmup_steps = 10000 return hparams
[ "def", "transformer_ae_a3", "(", ")", ":", "hparams", "=", "transformer_ae_base", "(", ")", "hparams", ".", "batch_size", "=", "4096", "hparams", ".", "layer_prepostprocess_dropout", "=", "0.3", "hparams", ".", "optimizer", "=", "\"Adafactor\"", "hparams", ".", ...
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L931-L939
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
transformer_ae_base_noatt
def transformer_ae_base_noatt(): """Set of hyperparameters.""" hparams = transformer_ae_base() hparams.reshape_method = "slice" hparams.bottleneck_kind = "dvq" hparams.hidden_size = 512 hparams.num_blocks = 1 hparams.num_decode_blocks = 1 hparams.z_size = 12 hparams.do_attend_decompress = False retu...
python
def transformer_ae_base_noatt(): """Set of hyperparameters.""" hparams = transformer_ae_base() hparams.reshape_method = "slice" hparams.bottleneck_kind = "dvq" hparams.hidden_size = 512 hparams.num_blocks = 1 hparams.num_decode_blocks = 1 hparams.z_size = 12 hparams.do_attend_decompress = False retu...
[ "def", "transformer_ae_base_noatt", "(", ")", ":", "hparams", "=", "transformer_ae_base", "(", ")", "hparams", ".", "reshape_method", "=", "\"slice\"", "hparams", ".", "bottleneck_kind", "=", "\"dvq\"", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", ...
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L970-L980
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
transformer_ae_small_noatt
def transformer_ae_small_noatt(): """Set of hyperparameters.""" hparams = transformer_ae_small() hparams.reshape_method = "slice" hparams.bottleneck_kind = "dvq" hparams.hidden_size = 512 hparams.num_blocks = 1 hparams.num_decode_blocks = 1 hparams.z_size = 12 hparams.do_attend_decompress = False re...
python
def transformer_ae_small_noatt(): """Set of hyperparameters.""" hparams = transformer_ae_small() hparams.reshape_method = "slice" hparams.bottleneck_kind = "dvq" hparams.hidden_size = 512 hparams.num_blocks = 1 hparams.num_decode_blocks = 1 hparams.z_size = 12 hparams.do_attend_decompress = False re...
[ "def", "transformer_ae_small_noatt", "(", ")", ":", "hparams", "=", "transformer_ae_small", "(", ")", "hparams", ".", "reshape_method", "=", "\"slice\"", "hparams", ".", "bottleneck_kind", "=", "\"dvq\"", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", ...
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L984-L994
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_sketch.py
transformer_sketch
def transformer_sketch(): """Basic transformer_sketch hparams.""" hparams = transformer.transformer_small() hparams.num_compress_steps = 4 hparams.batch_size = 32 hparams.clip_grad_norm = 2. hparams.sampling_method = "random" return hparams
python
def transformer_sketch(): """Basic transformer_sketch hparams.""" hparams = transformer.transformer_small() hparams.num_compress_steps = 4 hparams.batch_size = 32 hparams.clip_grad_norm = 2. hparams.sampling_method = "random" return hparams
[ "def", "transformer_sketch", "(", ")", ":", "hparams", "=", "transformer", ".", "transformer_small", "(", ")", "hparams", ".", "num_compress_steps", "=", "4", "hparams", ".", "batch_size", "=", "32", "hparams", ".", "clip_grad_norm", "=", "2.", "hparams", ".",...
Basic transformer_sketch hparams.
[ "Basic", "transformer_sketch", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_sketch.py#L55-L62
train
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
layers
def layers(): """Get the layers module good for TF 1 and TF 2 work for now.""" global _cached_layers if _cached_layers is not None: return _cached_layers layers_module = tf.layers try: from tensorflow.python import tf2 # pylint: disable=g-direct-tensorflow-import,g-import-not-at-top if tf2.enable...
python
def layers(): """Get the layers module good for TF 1 and TF 2 work for now.""" global _cached_layers if _cached_layers is not None: return _cached_layers layers_module = tf.layers try: from tensorflow.python import tf2 # pylint: disable=g-direct-tensorflow-import,g-import-not-at-top if tf2.enable...
[ "def", "layers", "(", ")", ":", "global", "_cached_layers", "if", "_cached_layers", "is", "not", "None", ":", "return", "_cached_layers", "layers_module", "=", "tf", ".", "layers", "try", ":", "from", "tensorflow", ".", "python", "import", "tf2", "# pylint: di...
Get the layers module good for TF 1 and TF 2 work for now.
[ "Get", "the", "layers", "module", "good", "for", "TF", "1", "and", "TF", "2", "work", "for", "now", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L42-L56
train
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
dropout_with_broadcast_dims
def dropout_with_broadcast_dims(x, keep_prob, broadcast_dims=None, **kwargs): """Like tf.nn.dropout but takes broadcast_dims instead of noise_shape. Instead of specifying noise_shape, this function takes broadcast_dims - a list of dimension numbers in which noise_shape should be 1. The random keep/drop tensor...
python
def dropout_with_broadcast_dims(x, keep_prob, broadcast_dims=None, **kwargs): """Like tf.nn.dropout but takes broadcast_dims instead of noise_shape. Instead of specifying noise_shape, this function takes broadcast_dims - a list of dimension numbers in which noise_shape should be 1. The random keep/drop tensor...
[ "def", "dropout_with_broadcast_dims", "(", "x", ",", "keep_prob", ",", "broadcast_dims", "=", "None", ",", "*", "*", "kwargs", ")", ":", "assert", "\"noise_shape\"", "not", "in", "kwargs", "if", "broadcast_dims", ":", "shape", "=", "tf", ".", "shape", "(", ...
Like tf.nn.dropout but takes broadcast_dims instead of noise_shape. Instead of specifying noise_shape, this function takes broadcast_dims - a list of dimension numbers in which noise_shape should be 1. The random keep/drop tensor has dimensionality 1 along these dimensions. Args: x: a floating point tens...
[ "Like", "tf", ".", "nn", ".", "dropout", "but", "takes", "broadcast_dims", "instead", "of", "noise_shape", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L103-L130
train
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
saturating_sigmoid
def saturating_sigmoid(x): """Saturating sigmoid: 1.2 * sigmoid(x) - 0.1 cut to [0, 1].""" with tf.name_scope("saturating_sigmoid", values=[x]): y = tf.sigmoid(x) return tf.minimum(1.0, tf.maximum(0.0, 1.2 * y - 0.1))
python
def saturating_sigmoid(x): """Saturating sigmoid: 1.2 * sigmoid(x) - 0.1 cut to [0, 1].""" with tf.name_scope("saturating_sigmoid", values=[x]): y = tf.sigmoid(x) return tf.minimum(1.0, tf.maximum(0.0, 1.2 * y - 0.1))
[ "def", "saturating_sigmoid", "(", "x", ")", ":", "with", "tf", ".", "name_scope", "(", "\"saturating_sigmoid\"", ",", "values", "=", "[", "x", "]", ")", ":", "y", "=", "tf", ".", "sigmoid", "(", "x", ")", "return", "tf", ".", "minimum", "(", "1.0", ...
Saturating sigmoid: 1.2 * sigmoid(x) - 0.1 cut to [0, 1].
[ "Saturating", "sigmoid", ":", "1", ".", "2", "*", "sigmoid", "(", "x", ")", "-", "0", ".", "1", "cut", "to", "[", "0", "1", "]", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L137-L141
train