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/layers/transformer_memory.py
TransformerMemory.read
def read(self, x): """Read from the memory. An external component can use the results via a simple MLP, e.g., fn(x W_x + retrieved_mem W_m). Args: x: a tensor in the shape of [batch_size, length, depth]. Returns: access_logits: the logits for accessing the memory in shape of ...
python
def read(self, x): """Read from the memory. An external component can use the results via a simple MLP, e.g., fn(x W_x + retrieved_mem W_m). Args: x: a tensor in the shape of [batch_size, length, depth]. Returns: access_logits: the logits for accessing the memory in shape of ...
[ "def", "read", "(", "self", ",", "x", ")", ":", "access_logits", "=", "self", ".", "_address_content", "(", "x", ")", "weights", "=", "tf", ".", "nn", ".", "softmax", "(", "access_logits", ")", "retrieved_mem", "=", "tf", ".", "reduce_sum", "(", "tf", ...
Read from the memory. An external component can use the results via a simple MLP, e.g., fn(x W_x + retrieved_mem W_m). Args: x: a tensor in the shape of [batch_size, length, depth]. Returns: access_logits: the logits for accessing the memory in shape of [batch_size, length, memor...
[ "Read", "from", "the", "memory", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L251-L270
train
tensorflow/tensor2tensor
tensor2tensor/layers/transformer_memory.py
TransformerMemory.write
def write(self, x, access_logits): """Write to the memory based on a combination of similarity and least used. Based on arXiv:1607.00036v2 [cs.LG]. Args: x: a tensor in the shape of [batch_size, length, depth]. access_logits: the logits for accessing the memory. Returns: the update o...
python
def write(self, x, access_logits): """Write to the memory based on a combination of similarity and least used. Based on arXiv:1607.00036v2 [cs.LG]. Args: x: a tensor in the shape of [batch_size, length, depth]. access_logits: the logits for accessing the memory. Returns: the update o...
[ "def", "write", "(", "self", ",", "x", ",", "access_logits", ")", ":", "gamma", "=", "tf", ".", "layers", ".", "dense", "(", "x", ",", "1", ",", "activation", "=", "tf", ".", "sigmoid", ",", "name", "=", "\"gamma\"", ")", "write_logits", "=", "acce...
Write to the memory based on a combination of similarity and least used. Based on arXiv:1607.00036v2 [cs.LG]. Args: x: a tensor in the shape of [batch_size, length, depth]. access_logits: the logits for accessing the memory. Returns: the update op.
[ "Write", "to", "the", "memory", "based", "on", "a", "combination", "of", "similarity", "and", "least", "used", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L272-L303
train
tensorflow/tensor2tensor
tensor2tensor/layers/transformer_memory.py
TransformerMemory.reset
def reset(self, entries_to_reset): """Reset the entries in the memory. Args: entries_to_reset: a 1D tensor. Returns: the reset op. """ num_updates = tf.size(entries_to_reset) update_vals = tf.scatter_update( self.mem_vals, entries_to_reset, tf.tile(tf.expand_dims( ...
python
def reset(self, entries_to_reset): """Reset the entries in the memory. Args: entries_to_reset: a 1D tensor. Returns: the reset op. """ num_updates = tf.size(entries_to_reset) update_vals = tf.scatter_update( self.mem_vals, entries_to_reset, tf.tile(tf.expand_dims( ...
[ "def", "reset", "(", "self", ",", "entries_to_reset", ")", ":", "num_updates", "=", "tf", ".", "size", "(", "entries_to_reset", ")", "update_vals", "=", "tf", ".", "scatter_update", "(", "self", ".", "mem_vals", ",", "entries_to_reset", ",", "tf", ".", "ti...
Reset the entries in the memory. Args: entries_to_reset: a 1D tensor. Returns: the reset op.
[ "Reset", "the", "entries", "in", "the", "memory", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L317-L337
train
tensorflow/tensor2tensor
tensor2tensor/layers/transformer_memory.py
TransformerMemory.pre_attention
def pre_attention(self, segment_number, query_antecedent, memory_antecedent, bias): """Called prior to self-attention, to incorporate memory items. Args: segment_number: an integer Tensor with shape [batch] query_antecedent: a Tensor with shape [batch, length_q, channels] ...
python
def pre_attention(self, segment_number, query_antecedent, memory_antecedent, bias): """Called prior to self-attention, to incorporate memory items. Args: segment_number: an integer Tensor with shape [batch] query_antecedent: a Tensor with shape [batch, length_q, channels] ...
[ "def", "pre_attention", "(", "self", ",", "segment_number", ",", "query_antecedent", ",", "memory_antecedent", ",", "bias", ")", ":", "with", "tf", ".", "variable_scope", "(", "self", ".", "name", "+", "\"/pre_attention\"", ",", "reuse", "=", "tf", ".", "AUT...
Called prior to self-attention, to incorporate memory items. Args: segment_number: an integer Tensor with shape [batch] query_antecedent: a Tensor with shape [batch, length_q, channels] memory_antecedent: must be None. Attention normally allows this to be a Tensor with shape [batch, lengt...
[ "Called", "prior", "to", "self", "-", "attention", "to", "incorporate", "memory", "items", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L339-L371
train
tensorflow/tensor2tensor
tensor2tensor/layers/transformer_memory.py
TransformerMemory.post_attention
def post_attention(self, token, x): """Called after self-attention. The memory can be updated here. Args: token: Data returned by pre_attention, which can be used to carry over state related to the current memory operation. x: a Tensor of data after self-attention and feed-forward Retur...
python
def post_attention(self, token, x): """Called after self-attention. The memory can be updated here. Args: token: Data returned by pre_attention, which can be used to carry over state related to the current memory operation. x: a Tensor of data after self-attention and feed-forward Retur...
[ "def", "post_attention", "(", "self", ",", "token", ",", "x", ")", ":", "with", "tf", ".", "variable_scope", "(", "self", ".", "name", "+", "\"/post_attention\"", ",", "reuse", "=", "tf", ".", "AUTO_REUSE", ")", ":", "depth", "=", "common_layers", ".", ...
Called after self-attention. The memory can be updated here. Args: token: Data returned by pre_attention, which can be used to carry over state related to the current memory operation. x: a Tensor of data after self-attention and feed-forward Returns: a (possibly modified) version of ...
[ "Called", "after", "self", "-", "attention", ".", "The", "memory", "can", "be", "updated", "here", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L373-L393
train
tensorflow/tensor2tensor
tensor2tensor/rl/ppo_learner.py
_define_train
def _define_train( train_env, ppo_hparams, eval_env_fn=None, sampling_temp=1.0, **collect_kwargs ): """Define the training setup.""" memory, collect_summary, train_initialization = ( _define_collect( train_env, ppo_hparams, "ppo_train", eval_phase=Fa...
python
def _define_train( train_env, ppo_hparams, eval_env_fn=None, sampling_temp=1.0, **collect_kwargs ): """Define the training setup.""" memory, collect_summary, train_initialization = ( _define_collect( train_env, ppo_hparams, "ppo_train", eval_phase=Fa...
[ "def", "_define_train", "(", "train_env", ",", "ppo_hparams", ",", "eval_env_fn", "=", "None", ",", "sampling_temp", "=", "1.0", ",", "*", "*", "collect_kwargs", ")", ":", "memory", ",", "collect_summary", ",", "train_initialization", "=", "(", "_define_collect"...
Define the training setup.
[ "Define", "the", "training", "setup", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/ppo_learner.py#L151-L186
train
tensorflow/tensor2tensor
tensor2tensor/rl/ppo_learner.py
_run_train
def _run_train(ppo_hparams, event_dir, model_dir, restarter, train_summary_op, eval_summary_op, initializers, report_fn=None, model_save_fn=None): """Train.""" summary_writer = tf.summary.FileWrit...
python
def _run_train(ppo_hparams, event_dir, model_dir, restarter, train_summary_op, eval_summary_op, initializers, report_fn=None, model_save_fn=None): """Train.""" summary_writer = tf.summary.FileWrit...
[ "def", "_run_train", "(", "ppo_hparams", ",", "event_dir", ",", "model_dir", ",", "restarter", ",", "train_summary_op", ",", "eval_summary_op", ",", "initializers", ",", "report_fn", "=", "None", ",", "model_save_fn", "=", "None", ")", ":", "summary_writer", "="...
Train.
[ "Train", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/ppo_learner.py#L189-L251
train
tensorflow/tensor2tensor
tensor2tensor/rl/ppo_learner.py
_rollout_metadata
def _rollout_metadata(batch_env): """Metadata for rollouts.""" batch_env_shape = batch_env.observ.get_shape().as_list() batch_size = [batch_env_shape[0]] shapes_types_names = [ # TODO(piotrmilos): possibly retrieve the observation type for batch_env (batch_size + batch_env_shape[1:], batch_env.obser...
python
def _rollout_metadata(batch_env): """Metadata for rollouts.""" batch_env_shape = batch_env.observ.get_shape().as_list() batch_size = [batch_env_shape[0]] shapes_types_names = [ # TODO(piotrmilos): possibly retrieve the observation type for batch_env (batch_size + batch_env_shape[1:], batch_env.obser...
[ "def", "_rollout_metadata", "(", "batch_env", ")", ":", "batch_env_shape", "=", "batch_env", ".", "observ", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "batch_size", "=", "[", "batch_env_shape", "[", "0", "]", "]", "shapes_types_names", "=", "[", ...
Metadata for rollouts.
[ "Metadata", "for", "rollouts", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/ppo_learner.py#L254-L268
train
tensorflow/tensor2tensor
tensor2tensor/rl/ppo_learner.py
_define_collect
def _define_collect(batch_env, ppo_hparams, scope, frame_stack_size, eval_phase, sampling_temp, force_beginning_resets): """Collect trajectories. Args: batch_env: Batch environment. ppo_hparams: PPO hparams, defined in tensor2tensor.models.research.rl. scope: var scope. frame_st...
python
def _define_collect(batch_env, ppo_hparams, scope, frame_stack_size, eval_phase, sampling_temp, force_beginning_resets): """Collect trajectories. Args: batch_env: Batch environment. ppo_hparams: PPO hparams, defined in tensor2tensor.models.research.rl. scope: var scope. frame_st...
[ "def", "_define_collect", "(", "batch_env", ",", "ppo_hparams", ",", "scope", ",", "frame_stack_size", ",", "eval_phase", ",", "sampling_temp", ",", "force_beginning_resets", ")", ":", "epoch_length", "=", "ppo_hparams", ".", "epoch_length", "to_initialize", "=", "[...
Collect trajectories. Args: batch_env: Batch environment. ppo_hparams: PPO hparams, defined in tensor2tensor.models.research.rl. scope: var scope. frame_stack_size: Number of last observations to feed into the policy. eval_phase: TODO(koz4k): Write docstring. sampling_temp: Sampling temperatu...
[ "Collect", "trajectories", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/ppo_learner.py#L310-L515
train
tensorflow/tensor2tensor
tensor2tensor/models/vanilla_gan.py
deconv2d
def deconv2d( input_, output_shape, k_h, k_w, d_h, d_w, stddev=0.02, name="deconv2d"): """Deconvolution layer.""" with tf.variable_scope(name): w = tf.get_variable( "w", [k_h, k_w, output_shape[-1], input_.get_shape()[-1]], initializer=tf.random_normal_initializer(stddev=stddev)) deconv ...
python
def deconv2d( input_, output_shape, k_h, k_w, d_h, d_w, stddev=0.02, name="deconv2d"): """Deconvolution layer.""" with tf.variable_scope(name): w = tf.get_variable( "w", [k_h, k_w, output_shape[-1], input_.get_shape()[-1]], initializer=tf.random_normal_initializer(stddev=stddev)) deconv ...
[ "def", "deconv2d", "(", "input_", ",", "output_shape", ",", "k_h", ",", "k_w", ",", "d_h", ",", "d_w", ",", "stddev", "=", "0.02", ",", "name", "=", "\"deconv2d\"", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "w", "=", "tf...
Deconvolution layer.
[ "Deconvolution", "layer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/vanilla_gan.py#L37-L48
train
tensorflow/tensor2tensor
tensor2tensor/models/vanilla_gan.py
sliced_gan
def sliced_gan(): """Basic parameters for a vanilla_gan.""" hparams = common_hparams.basic_params1() hparams.optimizer = "adam" hparams.learning_rate_constant = 0.0002 hparams.learning_rate_warmup_steps = 500 hparams.learning_rate_schedule = "constant * linear_warmup" hparams.label_smoothing = 0.0 hpara...
python
def sliced_gan(): """Basic parameters for a vanilla_gan.""" hparams = common_hparams.basic_params1() hparams.optimizer = "adam" hparams.learning_rate_constant = 0.0002 hparams.learning_rate_warmup_steps = 500 hparams.learning_rate_schedule = "constant * linear_warmup" hparams.label_smoothing = 0.0 hpara...
[ "def", "sliced_gan", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "optimizer", "=", "\"adam\"", "hparams", ".", "learning_rate_constant", "=", "0.0002", "hparams", ".", "learning_rate_warmup_steps", "=", "500", ...
Basic parameters for a vanilla_gan.
[ "Basic", "parameters", "for", "a", "vanilla_gan", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/vanilla_gan.py#L199-L217
train
tensorflow/tensor2tensor
tensor2tensor/models/vanilla_gan.py
AbstractGAN.discriminator
def discriminator(self, x, is_training, reuse=False): """Discriminator architecture based on InfoGAN. Args: x: input images, shape [bs, h, w, channels] is_training: boolean, are we in train or eval model. reuse: boolean, should params be re-used. Returns: out_logit: the output logi...
python
def discriminator(self, x, is_training, reuse=False): """Discriminator architecture based on InfoGAN. Args: x: input images, shape [bs, h, w, channels] is_training: boolean, are we in train or eval model. reuse: boolean, should params be re-used. Returns: out_logit: the output logi...
[ "def", "discriminator", "(", "self", ",", "x", ",", "is_training", ",", "reuse", "=", "False", ")", ":", "hparams", "=", "self", ".", "hparams", "with", "tf", ".", "variable_scope", "(", "\"discriminator\"", ",", "reuse", "=", "reuse", ",", "initializer", ...
Discriminator architecture based on InfoGAN. Args: x: input images, shape [bs, h, w, channels] is_training: boolean, are we in train or eval model. reuse: boolean, should params be re-used. Returns: out_logit: the output logits (before sigmoid).
[ "Discriminator", "architecture", "based", "on", "InfoGAN", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/vanilla_gan.py#L58-L93
train
tensorflow/tensor2tensor
tensor2tensor/models/vanilla_gan.py
AbstractGAN.generator
def generator(self, z, is_training, out_shape): """Generator outputting image in [0, 1].""" hparams = self.hparams height, width, c_dim = out_shape batch_size = hparams.batch_size with tf.variable_scope( "generator", initializer=tf.random_normal_initializer(stddev=0.02)): net =...
python
def generator(self, z, is_training, out_shape): """Generator outputting image in [0, 1].""" hparams = self.hparams height, width, c_dim = out_shape batch_size = hparams.batch_size with tf.variable_scope( "generator", initializer=tf.random_normal_initializer(stddev=0.02)): net =...
[ "def", "generator", "(", "self", ",", "z", ",", "is_training", ",", "out_shape", ")", ":", "hparams", "=", "self", ".", "hparams", "height", ",", "width", ",", "c_dim", "=", "out_shape", "batch_size", "=", "hparams", ".", "batch_size", "with", "tf", ".",...
Generator outputting image in [0, 1].
[ "Generator", "outputting", "image", "in", "[", "0", "1", "]", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/vanilla_gan.py#L95-L121
train
tensorflow/tensor2tensor
tensor2tensor/models/vanilla_gan.py
AbstractGAN.body
def body(self, features): """Body of the model. Args: features: a dictionary with the tensors. Returns: A pair (predictions, losses) where predictions is the generated image and losses is a dictionary of losses (that get added for the final loss). """ features["targets"] = featur...
python
def body(self, features): """Body of the model. Args: features: a dictionary with the tensors. Returns: A pair (predictions, losses) where predictions is the generated image and losses is a dictionary of losses (that get added for the final loss). """ features["targets"] = featur...
[ "def", "body", "(", "self", ",", "features", ")", ":", "features", "[", "\"targets\"", "]", "=", "features", "[", "\"inputs\"", "]", "is_training", "=", "self", ".", "hparams", ".", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", "...
Body of the model. Args: features: a dictionary with the tensors. Returns: A pair (predictions, losses) where predictions is the generated image and losses is a dictionary of losses (that get added for the final loss).
[ "Body", "of", "the", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/vanilla_gan.py#L127-L160
train
tensorflow/tensor2tensor
tensor2tensor/trax/inputs.py
inputs
def inputs(num_devices, dataset_name, data_dir=None, input_name=None, num_chunks=0, append_targets=False): """Make Inputs for built-in datasets. Args: num_devices: how many devices to build the inputs for. dataset_name: a TFDS or T2T dataset name. If it's a T2T dataset name, prefix with "t...
python
def inputs(num_devices, dataset_name, data_dir=None, input_name=None, num_chunks=0, append_targets=False): """Make Inputs for built-in datasets. Args: num_devices: how many devices to build the inputs for. dataset_name: a TFDS or T2T dataset name. If it's a T2T dataset name, prefix with "t...
[ "def", "inputs", "(", "num_devices", ",", "dataset_name", ",", "data_dir", "=", "None", ",", "input_name", "=", "None", ",", "num_chunks", "=", "0", ",", "append_targets", "=", "False", ")", ":", "assert", "data_dir", ",", "\"Must provide a data directory\"", ...
Make Inputs for built-in datasets. Args: num_devices: how many devices to build the inputs for. dataset_name: a TFDS or T2T dataset name. If it's a T2T dataset name, prefix with "t2t_". data_dir: data directory. input_name: optional, name of the inputs from the dictionary. num_chunks: optio...
[ "Make", "Inputs", "for", "built", "-", "in", "datasets", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/inputs.py#L58-L95
train
tensorflow/tensor2tensor
tensor2tensor/trax/inputs.py
random_inputs
def random_inputs( num_devices, input_shape=gin.REQUIRED, input_dtype=np.int32, input_range=(0, 255), output_shape=gin.REQUIRED, output_dtype=np.int32, output_range=(0, 9)): """Make random Inputs for debugging. Args: num_devices: how many devices to build the inputs for. input_shape: the shape ...
python
def random_inputs( num_devices, input_shape=gin.REQUIRED, input_dtype=np.int32, input_range=(0, 255), output_shape=gin.REQUIRED, output_dtype=np.int32, output_range=(0, 9)): """Make random Inputs for debugging. Args: num_devices: how many devices to build the inputs for. input_shape: the shape ...
[ "def", "random_inputs", "(", "num_devices", ",", "input_shape", "=", "gin", ".", "REQUIRED", ",", "input_dtype", "=", "np", ".", "int32", ",", "input_range", "=", "(", "0", ",", "255", ")", ",", "output_shape", "=", "gin", ".", "REQUIRED", ",", "output_d...
Make random Inputs for debugging. Args: num_devices: how many devices to build the inputs for. input_shape: the shape of inputs (including batch dimension). input_dtype: the type of the inputs (int32 by default). input_range: the range of inputs (defaults to (0, 255)). output_shape: the shape of ...
[ "Make", "random", "Inputs", "for", "debugging", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/inputs.py#L99-L143
train
tensorflow/tensor2tensor
tensor2tensor/trax/inputs.py
dataset_to_stream
def dataset_to_stream(dataset, input_name, num_chunks=0, append_targets=False): """Takes a tf.Dataset and creates a numpy stream of ready batches.""" for example in tfds.as_numpy(dataset): inp, out = example[0][input_name], example[1] if len(out.shape) > 1 and out.shape[-1] == 1: out = np.squeeze(out,...
python
def dataset_to_stream(dataset, input_name, num_chunks=0, append_targets=False): """Takes a tf.Dataset and creates a numpy stream of ready batches.""" for example in tfds.as_numpy(dataset): inp, out = example[0][input_name], example[1] if len(out.shape) > 1 and out.shape[-1] == 1: out = np.squeeze(out,...
[ "def", "dataset_to_stream", "(", "dataset", ",", "input_name", ",", "num_chunks", "=", "0", ",", "append_targets", "=", "False", ")", ":", "for", "example", "in", "tfds", ".", "as_numpy", "(", "dataset", ")", ":", "inp", ",", "out", "=", "example", "[", ...
Takes a tf.Dataset and creates a numpy stream of ready batches.
[ "Takes", "a", "tf", ".", "Dataset", "and", "creates", "a", "numpy", "stream", "of", "ready", "batches", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/inputs.py#L146-L157
train
tensorflow/tensor2tensor
tensor2tensor/trax/inputs.py
_train_and_eval_dataset_v1
def _train_and_eval_dataset_v1(problem_name, data_dir): """Return train and evaluation datasets, feature info and supervised keys.""" assert not tf.executing_eagerly(), "tf.eager mode must be turned off." problem = t2t_problems.problem(problem_name) train_dataset = problem.dataset(tf.estimator.ModeKeys.TRAIN, d...
python
def _train_and_eval_dataset_v1(problem_name, data_dir): """Return train and evaluation datasets, feature info and supervised keys.""" assert not tf.executing_eagerly(), "tf.eager mode must be turned off." problem = t2t_problems.problem(problem_name) train_dataset = problem.dataset(tf.estimator.ModeKeys.TRAIN, d...
[ "def", "_train_and_eval_dataset_v1", "(", "problem_name", ",", "data_dir", ")", ":", "assert", "not", "tf", ".", "executing_eagerly", "(", ")", ",", "\"tf.eager mode must be turned off.\"", "problem", "=", "t2t_problems", ".", "problem", "(", "problem_name", ")", "t...
Return train and evaluation datasets, feature info and supervised keys.
[ "Return", "train", "and", "evaluation", "datasets", "feature", "info", "and", "supervised", "keys", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/inputs.py#L229-L257
train
tensorflow/tensor2tensor
tensor2tensor/trax/inputs.py
batch_fun
def batch_fun(dataset, training, shapes, target_names, num_devices, batch_size_per_device=32, batch_size=None, eval_batch_size=32, bucket_length=32, buckets=None, batch_shuffle_size=128, max_eval_length=None): """Batching function.""" del target_names # Batch size is batc...
python
def batch_fun(dataset, training, shapes, target_names, num_devices, batch_size_per_device=32, batch_size=None, eval_batch_size=32, bucket_length=32, buckets=None, batch_shuffle_size=128, max_eval_length=None): """Batching function.""" del target_names # Batch size is batc...
[ "def", "batch_fun", "(", "dataset", ",", "training", ",", "shapes", ",", "target_names", ",", "num_devices", ",", "batch_size_per_device", "=", "32", ",", "batch_size", "=", "None", ",", "eval_batch_size", "=", "32", ",", "bucket_length", "=", "32", ",", "bu...
Batching function.
[ "Batching", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/inputs.py#L262-L316
train
tensorflow/tensor2tensor
tensor2tensor/trax/inputs.py
lm1b_preprocess
def lm1b_preprocess(dataset, training, max_target_length=-1, max_eval_target_length=-1): """Preprocessing for LM1B: filter out targets exceeding maximum length.""" def target_right_length(_, target): return tf.less(tf.shape(target)[0], max_target_length + 1) def eval_target_right_length(...
python
def lm1b_preprocess(dataset, training, max_target_length=-1, max_eval_target_length=-1): """Preprocessing for LM1B: filter out targets exceeding maximum length.""" def target_right_length(_, target): return tf.less(tf.shape(target)[0], max_target_length + 1) def eval_target_right_length(...
[ "def", "lm1b_preprocess", "(", "dataset", ",", "training", ",", "max_target_length", "=", "-", "1", ",", "max_eval_target_length", "=", "-", "1", ")", ":", "def", "target_right_length", "(", "_", ",", "target", ")", ":", "return", "tf", ".", "less", "(", ...
Preprocessing for LM1B: filter out targets exceeding maximum length.
[ "Preprocessing", "for", "LM1B", ":", "filter", "out", "targets", "exceeding", "maximum", "length", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/inputs.py#L337-L353
train
tensorflow/tensor2tensor
tensor2tensor/trax/inputs.py
shuffle_and_batch_data
def shuffle_and_batch_data(dataset, target_names, features_info, training, num_devices, shuffle_buffer_size=1024, preprocess_fun=no_preprocess): """Shuffle ...
python
def shuffle_and_batch_data(dataset, target_names, features_info, training, num_devices, shuffle_buffer_size=1024, preprocess_fun=no_preprocess): """Shuffle ...
[ "def", "shuffle_and_batch_data", "(", "dataset", ",", "target_names", ",", "features_info", ",", "training", ",", "num_devices", ",", "shuffle_buffer_size", "=", "1024", ",", "preprocess_fun", "=", "no_preprocess", ")", ":", "def", "append_targets", "(", "example", ...
Shuffle and batch the given dataset.
[ "Shuffle", "and", "batch", "the", "given", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/inputs.py#L357-L385
train
tensorflow/tensor2tensor
tensor2tensor/trax/inputs.py
_train_and_eval_batches
def _train_and_eval_batches(dataset, data_dir, input_name, num_devices): """Return train and eval batches with input name and shape.""" (train_data, eval_data, features_info, keys) = train_and_eval_dataset( dataset, data_dir) input_names, target_names = keys[0], keys[1] train_batches = shuffle_and_batch_d...
python
def _train_and_eval_batches(dataset, data_dir, input_name, num_devices): """Return train and eval batches with input name and shape.""" (train_data, eval_data, features_info, keys) = train_and_eval_dataset( dataset, data_dir) input_names, target_names = keys[0], keys[1] train_batches = shuffle_and_batch_d...
[ "def", "_train_and_eval_batches", "(", "dataset", ",", "data_dir", ",", "input_name", ",", "num_devices", ")", ":", "(", "train_data", ",", "eval_data", ",", "features_info", ",", "keys", ")", "=", "train_and_eval_dataset", "(", "dataset", ",", "data_dir", ")", ...
Return train and eval batches with input name and shape.
[ "Return", "train", "and", "eval", "batches", "with", "input", "name", "and", "shape", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/inputs.py#L388-L405
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem_v2.py
get_multi_dataset
def get_multi_dataset(datasets, pmf=None): """Returns a Dataset that samples records from one or more Datasets. Args: datasets: A list of one or more Dataset objects to sample from. pmf: A tensor of shape [len(datasets)], the probabilities to sample each dataset with. This tensor is often constructed...
python
def get_multi_dataset(datasets, pmf=None): """Returns a Dataset that samples records from one or more Datasets. Args: datasets: A list of one or more Dataset objects to sample from. pmf: A tensor of shape [len(datasets)], the probabilities to sample each dataset with. This tensor is often constructed...
[ "def", "get_multi_dataset", "(", "datasets", ",", "pmf", "=", "None", ")", ":", "pmf", "=", "tf", ".", "fill", "(", "[", "len", "(", "datasets", ")", "]", ",", "1.0", "/", "len", "(", "datasets", ")", ")", "if", "pmf", "is", "None", "else", "pmf"...
Returns a Dataset that samples records from one or more Datasets. Args: datasets: A list of one or more Dataset objects to sample from. pmf: A tensor of shape [len(datasets)], the probabilities to sample each dataset with. This tensor is often constructed with the global_step. If this is None, we...
[ "Returns", "a", "Dataset", "that", "samples", "records", "from", "one", "or", "more", "Datasets", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L205-L223
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem_v2.py
get_schedule_distribution
def get_schedule_distribution(schedule, global_step=None): """Computes the pmf of a schedule given the global_step. Args: schedule: A schedule tuple, see encode_schedule for details. global_step: A scalar tensor, the step to query the schedule. Returns: A 1-D tensor of probs, the sampling distributi...
python
def get_schedule_distribution(schedule, global_step=None): """Computes the pmf of a schedule given the global_step. Args: schedule: A schedule tuple, see encode_schedule for details. global_step: A scalar tensor, the step to query the schedule. Returns: A 1-D tensor of probs, the sampling distributi...
[ "def", "get_schedule_distribution", "(", "schedule", ",", "global_step", "=", "None", ")", ":", "interpolation", ",", "steps", ",", "pmfs", "=", "schedule", "if", "len", "(", "pmfs", ")", "==", "1", ":", "# py_func doesn't seem to work on TPU - at least get the cons...
Computes the pmf of a schedule given the global_step. Args: schedule: A schedule tuple, see encode_schedule for details. global_step: A scalar tensor, the step to query the schedule. Returns: A 1-D tensor of probs, the sampling distribution of the global_step.
[ "Computes", "the", "pmf", "of", "a", "schedule", "given", "the", "global_step", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L226-L253
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem_v2.py
categorical_case
def categorical_case(pmf, fns, rand=None): """Returns the outputs of fns[i] with probability pmf[i]. Args: pmf: A 1-D tensor of probabilities, the probability mass function. fns: A list of callables that return tensors, same length as pmf. rand: An optional scalar between 0.0 and 1.0, the output of an ...
python
def categorical_case(pmf, fns, rand=None): """Returns the outputs of fns[i] with probability pmf[i]. Args: pmf: A 1-D tensor of probabilities, the probability mass function. fns: A list of callables that return tensors, same length as pmf. rand: An optional scalar between 0.0 and 1.0, the output of an ...
[ "def", "categorical_case", "(", "pmf", ",", "fns", ",", "rand", "=", "None", ")", ":", "rand", "=", "tf", ".", "random_uniform", "(", "[", "]", ")", "if", "rand", "is", "None", "else", "rand", "cmf", "=", "tf", ".", "pad", "(", "tf", ".", "cumsum...
Returns the outputs of fns[i] with probability pmf[i]. Args: pmf: A 1-D tensor of probabilities, the probability mass function. fns: A list of callables that return tensors, same length as pmf. rand: An optional scalar between 0.0 and 1.0, the output of an RNG. Returns: A tensor, the output of fns...
[ "Returns", "the", "outputs", "of", "fns", "[", "i", "]", "with", "probability", "pmf", "[", "i", "]", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L256-L271
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem_v2.py
linear_interpolation
def linear_interpolation(x, xp, fp, **kwargs): """Multi-dimensional linear interpolation. Returns the multi-dimensional piecewise linear interpolant to a function with given discrete data points (xp, fp), evaluated at x. Note that *N and *M indicate zero or more dimensions. Args: x: An array of shape [...
python
def linear_interpolation(x, xp, fp, **kwargs): """Multi-dimensional linear interpolation. Returns the multi-dimensional piecewise linear interpolant to a function with given discrete data points (xp, fp), evaluated at x. Note that *N and *M indicate zero or more dimensions. Args: x: An array of shape [...
[ "def", "linear_interpolation", "(", "x", ",", "xp", ",", "fp", ",", "*", "*", "kwargs", ")", ":", "yp", "=", "fp", ".", "reshape", "(", "[", "fp", ".", "shape", "[", "0", "]", ",", "-", "1", "]", ")", ".", "transpose", "(", ")", "y", "=", "...
Multi-dimensional linear interpolation. Returns the multi-dimensional piecewise linear interpolant to a function with given discrete data points (xp, fp), evaluated at x. Note that *N and *M indicate zero or more dimensions. Args: x: An array of shape [*N], the x-coordinates of the interpolated values. ...
[ "Multi", "-", "dimensional", "linear", "interpolation", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L274-L294
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem_v2.py
step_interpolation
def step_interpolation(x, xp, fp, **kwargs): """Multi-dimensional step interpolation. Returns the multi-dimensional step interpolant to a function with given discrete data points (xp, fp), evaluated at x. Note that *N and *M indicate zero or more dimensions. Args: x: An array of shape [*N], the x-coord...
python
def step_interpolation(x, xp, fp, **kwargs): """Multi-dimensional step interpolation. Returns the multi-dimensional step interpolant to a function with given discrete data points (xp, fp), evaluated at x. Note that *N and *M indicate zero or more dimensions. Args: x: An array of shape [*N], the x-coord...
[ "def", "step_interpolation", "(", "x", ",", "xp", ",", "fp", ",", "*", "*", "kwargs", ")", ":", "del", "kwargs", "# Unused.", "xp", "=", "np", ".", "expand_dims", "(", "xp", ",", "-", "1", ")", "lower", ",", "upper", "=", "xp", "[", ":", "-", "...
Multi-dimensional step interpolation. Returns the multi-dimensional step interpolant to a function with given discrete data points (xp, fp), evaluated at x. Note that *N and *M indicate zero or more dimensions. Args: x: An array of shape [*N], the x-coordinates of the interpolated values. xp: An np.a...
[ "Multi", "-", "dimensional", "step", "interpolation", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L297-L325
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem_v2.py
epoch_rates_to_pmf
def epoch_rates_to_pmf(problems, epoch_rates=None): """Create a probability-mass-function based on relative epoch rates. if epoch_rates=None, then we use uniform epoch rates [1.0] * len(problems) i.e. it takes each problem the same time to go through one epoch. If epoch_rates is given, then these are the rela...
python
def epoch_rates_to_pmf(problems, epoch_rates=None): """Create a probability-mass-function based on relative epoch rates. if epoch_rates=None, then we use uniform epoch rates [1.0] * len(problems) i.e. it takes each problem the same time to go through one epoch. If epoch_rates is given, then these are the rela...
[ "def", "epoch_rates_to_pmf", "(", "problems", ",", "epoch_rates", "=", "None", ")", ":", "if", "epoch_rates", "is", "None", ":", "epoch_rates", "=", "[", "1.0", "]", "*", "len", "(", "problems", ")", "example_rates", "=", "[", "epoch_rate", "*", "p", "."...
Create a probability-mass-function based on relative epoch rates. if epoch_rates=None, then we use uniform epoch rates [1.0] * len(problems) i.e. it takes each problem the same time to go through one epoch. If epoch_rates is given, then these are the relative numbers of epochs of each problem to go through in...
[ "Create", "a", "probability", "-", "mass", "-", "function", "based", "on", "relative", "epoch", "rates", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L353-L375
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem_v2.py
encode_schedule
def encode_schedule(schedule): """Encodes a schedule tuple into a string. Args: schedule: A tuple containing (interpolation, steps, pmfs), where interpolation is a string specifying the interpolation strategy, steps is an int array_like of shape [N] specifying the global steps, and pmfs is an...
python
def encode_schedule(schedule): """Encodes a schedule tuple into a string. Args: schedule: A tuple containing (interpolation, steps, pmfs), where interpolation is a string specifying the interpolation strategy, steps is an int array_like of shape [N] specifying the global steps, and pmfs is an...
[ "def", "encode_schedule", "(", "schedule", ")", ":", "interpolation", ",", "steps", ",", "pmfs", "=", "schedule", "return", "interpolation", "+", "' '", "+", "' '", ".", "join", "(", "'@'", "+", "str", "(", "s", ")", "+", "' '", "+", "' '", ".", "joi...
Encodes a schedule tuple into a string. Args: schedule: A tuple containing (interpolation, steps, pmfs), where interpolation is a string specifying the interpolation strategy, steps is an int array_like of shape [N] specifying the global steps, and pmfs is an array_like of shape [N, M] where pm...
[ "Encodes", "a", "schedule", "tuple", "into", "a", "string", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L378-L394
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem_v2.py
decode_schedule
def decode_schedule(string): """Decodes a string into a schedule tuple. Args: string: The string encoding of a schedule tuple. Returns: A schedule tuple, see encode_schedule for details. """ splits = string.split() steps = [int(x[1:]) for x in splits[1:] if x[0] == '@'] pmfs = np.reshape( ...
python
def decode_schedule(string): """Decodes a string into a schedule tuple. Args: string: The string encoding of a schedule tuple. Returns: A schedule tuple, see encode_schedule for details. """ splits = string.split() steps = [int(x[1:]) for x in splits[1:] if x[0] == '@'] pmfs = np.reshape( ...
[ "def", "decode_schedule", "(", "string", ")", ":", "splits", "=", "string", ".", "split", "(", ")", "steps", "=", "[", "int", "(", "x", "[", "1", ":", "]", ")", "for", "x", "in", "splits", "[", "1", ":", "]", "if", "x", "[", "0", "]", "==", ...
Decodes a string into a schedule tuple. Args: string: The string encoding of a schedule tuple. Returns: A schedule tuple, see encode_schedule for details.
[ "Decodes", "a", "string", "into", "a", "schedule", "tuple", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L397-L410
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem_v2.py
tuplize
def tuplize(nested): """Recursively converts iterables into tuples. Args: nested: A nested structure of items and iterables. Returns: A nested structure of items and tuples. """ if isinstance(nested, str): return nested try: return tuple(map(tuplize, nested)) except TypeError: return...
python
def tuplize(nested): """Recursively converts iterables into tuples. Args: nested: A nested structure of items and iterables. Returns: A nested structure of items and tuples. """ if isinstance(nested, str): return nested try: return tuple(map(tuplize, nested)) except TypeError: return...
[ "def", "tuplize", "(", "nested", ")", ":", "if", "isinstance", "(", "nested", ",", "str", ")", ":", "return", "nested", "try", ":", "return", "tuple", "(", "map", "(", "tuplize", ",", "nested", ")", ")", "except", "TypeError", ":", "return", "nested" ]
Recursively converts iterables into tuples. Args: nested: A nested structure of items and iterables. Returns: A nested structure of items and tuples.
[ "Recursively", "converts", "iterables", "into", "tuples", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L413-L427
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem_v2.py
MultiProblemV2.filepattern
def filepattern(self, *args, **kwargs): """Returns a list of filepatterns, one for each problem.""" return [p.filepattern(*args, **kwargs) for p in self.problems]
python
def filepattern(self, *args, **kwargs): """Returns a list of filepatterns, one for each problem.""" return [p.filepattern(*args, **kwargs) for p in self.problems]
[ "def", "filepattern", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "[", "p", ".", "filepattern", "(", "*", "args", ",", "*", "*", "kwargs", ")", "for", "p", "in", "self", ".", "problems", "]" ]
Returns a list of filepatterns, one for each problem.
[ "Returns", "a", "list", "of", "filepatterns", "one", "for", "each", "problem", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L82-L84
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem_v2.py
MultiProblemV2.generate_data
def generate_data(self, *args, **kwargs): """Generates data for each problem.""" for p in self.problems: p.generate_data(*args, **kwargs)
python
def generate_data(self, *args, **kwargs): """Generates data for each problem.""" for p in self.problems: p.generate_data(*args, **kwargs)
[ "def", "generate_data", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "p", "in", "self", ".", "problems", ":", "p", ".", "generate_data", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Generates data for each problem.
[ "Generates", "data", "for", "each", "problem", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L86-L89
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem_v2.py
MultiProblemV2.dataset
def dataset(self, mode, hparams=None, global_step=None, **kwargs): """Returns a dataset containing examples from multiple problems. Args: mode: A member of problem.DatasetSplit. hparams: A tf.HParams object, the model hparams. global_step: A scalar tensor used to compute the sampling distribu...
python
def dataset(self, mode, hparams=None, global_step=None, **kwargs): """Returns a dataset containing examples from multiple problems. Args: mode: A member of problem.DatasetSplit. hparams: A tf.HParams object, the model hparams. global_step: A scalar tensor used to compute the sampling distribu...
[ "def", "dataset", "(", "self", ",", "mode", ",", "hparams", "=", "None", ",", "global_step", "=", "None", ",", "*", "*", "kwargs", ")", ":", "datasets", "=", "[", "p", ".", "dataset", "(", "mode", ",", "*", "*", "kwargs", ")", "for", "p", "in", ...
Returns a dataset containing examples from multiple problems. Args: mode: A member of problem.DatasetSplit. hparams: A tf.HParams object, the model hparams. global_step: A scalar tensor used to compute the sampling distribution. If global_step is None, we call tf.train.get_or_create_globa...
[ "Returns", "a", "dataset", "containing", "examples", "from", "multiple", "problems", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L101-L133
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem_v2.py
MultiText2TextProblem.normalize_example
def normalize_example(self, example, hparams): """Assumes that example contains both inputs and targets.""" length = self.max_length(hparams) def _to_constant_shape(tensor): tensor = tensor[:length] tensor = tf.pad(tensor, [(0, length - tf.shape(tensor)[0])]) return tf.reshape(tensor, [le...
python
def normalize_example(self, example, hparams): """Assumes that example contains both inputs and targets.""" length = self.max_length(hparams) def _to_constant_shape(tensor): tensor = tensor[:length] tensor = tf.pad(tensor, [(0, length - tf.shape(tensor)[0])]) return tf.reshape(tensor, [le...
[ "def", "normalize_example", "(", "self", ",", "example", ",", "hparams", ")", ":", "length", "=", "self", ".", "max_length", "(", "hparams", ")", "def", "_to_constant_shape", "(", "tensor", ")", ":", "tensor", "=", "tensor", "[", ":", "length", "]", "ten...
Assumes that example contains both inputs and targets.
[ "Assumes", "that", "example", "contains", "both", "inputs", "and", "targets", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L139-L181
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem_v2.py
MultiText2TextProblem.generate_data_with_shared_vocab
def generate_data_with_shared_vocab(self, data_dir, tmp_dir, task_id=-1): """Generates TF-Records for problems using a global vocabulary file.""" global_vocab_filename = os.path.join(data_dir, self.vocab_filename) if not tf.gfile.Exists(global_vocab_filename): raise ValueError( 'Global vocab...
python
def generate_data_with_shared_vocab(self, data_dir, tmp_dir, task_id=-1): """Generates TF-Records for problems using a global vocabulary file.""" global_vocab_filename = os.path.join(data_dir, self.vocab_filename) if not tf.gfile.Exists(global_vocab_filename): raise ValueError( 'Global vocab...
[ "def", "generate_data_with_shared_vocab", "(", "self", ",", "data_dir", ",", "tmp_dir", ",", "task_id", "=", "-", "1", ")", ":", "global_vocab_filename", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "self", ".", "vocab_filename", ")", "if", "...
Generates TF-Records for problems using a global vocabulary file.
[ "Generates", "TF", "-", "Records", "for", "problems", "using", "a", "global", "vocabulary", "file", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L183-L197
train
tensorflow/tensor2tensor
tensor2tensor/layers/area_attention.py
lengths_to_area_mask
def lengths_to_area_mask(feature_length, length, max_area_size): """Generates a non-padding mask for areas based on lengths. Args: feature_length: a tensor of [batch_size] length: the length of the batch max_area_size: the maximum area size considered Returns: mask: a tensor in shape of [batch_si...
python
def lengths_to_area_mask(feature_length, length, max_area_size): """Generates a non-padding mask for areas based on lengths. Args: feature_length: a tensor of [batch_size] length: the length of the batch max_area_size: the maximum area size considered Returns: mask: a tensor in shape of [batch_si...
[ "def", "lengths_to_area_mask", "(", "feature_length", ",", "length", ",", "max_area_size", ")", ":", "paddings", "=", "tf", ".", "cast", "(", "tf", ".", "expand_dims", "(", "tf", ".", "logical_not", "(", "tf", ".", "sequence_mask", "(", "feature_length", ","...
Generates a non-padding mask for areas based on lengths. Args: feature_length: a tensor of [batch_size] length: the length of the batch max_area_size: the maximum area size considered Returns: mask: a tensor in shape of [batch_size, num_areas]
[ "Generates", "a", "non", "-", "padding", "mask", "for", "areas", "based", "on", "lengths", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L27-L44
train
tensorflow/tensor2tensor
tensor2tensor/layers/area_attention.py
_pool_one_shape
def _pool_one_shape(features_2d, area_width, area_height, batch_size, width, height, depth, fn=tf.reduce_max, name=None): """Pools for an area in features_2d. Args: features_2d: a Tensor in a shape of [batch_size, height, width, depth]. area_width: the max width allowed for an area. ...
python
def _pool_one_shape(features_2d, area_width, area_height, batch_size, width, height, depth, fn=tf.reduce_max, name=None): """Pools for an area in features_2d. Args: features_2d: a Tensor in a shape of [batch_size, height, width, depth]. area_width: the max width allowed for an area. ...
[ "def", "_pool_one_shape", "(", "features_2d", ",", "area_width", ",", "area_height", ",", "batch_size", ",", "width", ",", "height", ",", "depth", ",", "fn", "=", "tf", ".", "reduce_max", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope...
Pools for an area in features_2d. Args: features_2d: a Tensor in a shape of [batch_size, height, width, depth]. area_width: the max width allowed for an area. area_height: the max height allowed for an area. batch_size: the batch size. width: the width of the memory. height: the height of the...
[ "Pools", "for", "an", "area", "in", "features_2d", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L47-L75
train
tensorflow/tensor2tensor
tensor2tensor/layers/area_attention.py
basic_pool
def basic_pool(features, max_area_width, max_area_height=1, height=1, fn=tf.reduce_max, name=None): """Pools for each area based on a given pooling function (fn). Args: features: a Tensor in a shape of [batch_size, height * width, depth]. max_area_width: the max width allowed for an area. ...
python
def basic_pool(features, max_area_width, max_area_height=1, height=1, fn=tf.reduce_max, name=None): """Pools for each area based on a given pooling function (fn). Args: features: a Tensor in a shape of [batch_size, height * width, depth]. max_area_width: the max width allowed for an area. ...
[ "def", "basic_pool", "(", "features", ",", "max_area_width", ",", "max_area_height", "=", "1", ",", "height", "=", "1", ",", "fn", "=", "tf", ".", "reduce_max", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ",", "d...
Pools for each area based on a given pooling function (fn). Args: features: a Tensor in a shape of [batch_size, height * width, depth]. max_area_width: the max width allowed for an area. max_area_height: the max height allowed for an area. height: the height of the image. fn: the TF function for ...
[ "Pools", "for", "each", "area", "based", "on", "a", "given", "pooling", "function", "(", "fn", ")", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L78-L128
train
tensorflow/tensor2tensor
tensor2tensor/layers/area_attention.py
_compute_sum_image
def _compute_sum_image(features, max_area_width, max_area_height=1, height=1, name=None): """Computes area sums for features. Args: features: a Tensor in a shape of [batch_size, height * width, depth]. max_area_width: the max width allowed for an area. max_area_height: the max he...
python
def _compute_sum_image(features, max_area_width, max_area_height=1, height=1, name=None): """Computes area sums for features. Args: features: a Tensor in a shape of [batch_size, height * width, depth]. max_area_width: the max width allowed for an area. max_area_height: the max he...
[ "def", "_compute_sum_image", "(", "features", ",", "max_area_width", ",", "max_area_height", "=", "1", ",", "height", "=", "1", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ",", "default_name", "=", "\"compute_sum_image\"...
Computes area sums for features. Args: features: a Tensor in a shape of [batch_size, height * width, depth]. max_area_width: the max width allowed for an area. max_area_height: the max height allowed for an area. height: the height of the image. name: the namescope. Returns: sum_image: A Te...
[ "Computes", "area", "sums", "for", "features", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L131-L196
train
tensorflow/tensor2tensor
tensor2tensor/layers/area_attention.py
compute_area_features
def compute_area_features(features, max_area_width, max_area_height=1, height=1, epsilon=1e-6): """Computes features for each area. Args: features: a Tensor in a shape of [batch_size, height * width, depth]. max_area_width: the max width allowed for an area. max_area_height: t...
python
def compute_area_features(features, max_area_width, max_area_height=1, height=1, epsilon=1e-6): """Computes features for each area. Args: features: a Tensor in a shape of [batch_size, height * width, depth]. max_area_width: the max width allowed for an area. max_area_height: t...
[ "def", "compute_area_features", "(", "features", ",", "max_area_width", ",", "max_area_height", "=", "1", ",", "height", "=", "1", ",", "epsilon", "=", "1e-6", ")", ":", "with", "tf", ".", "name_scope", "(", "\"compute_area_features\"", ")", ":", "tf", ".", ...
Computes features for each area. Args: features: a Tensor in a shape of [batch_size, height * width, depth]. max_area_width: the max width allowed for an area. max_area_height: the max height allowed for an area. height: the height of the image. epsilon: the epsilon added to the variance for comp...
[ "Computes", "features", "for", "each", "area", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L199-L231
train
tensorflow/tensor2tensor
tensor2tensor/layers/area_attention.py
compute_area_key
def compute_area_key(features, max_area_width, max_area_height=1, height=1, mode="mean", training=True, name=None): """Computes the key for each area. Args: features: a Tensor in a shape of [batch_size, height * width, depth]. max_area_width: the max width allowed for an area. max_...
python
def compute_area_key(features, max_area_width, max_area_height=1, height=1, mode="mean", training=True, name=None): """Computes the key for each area. Args: features: a Tensor in a shape of [batch_size, height * width, depth]. max_area_width: the max width allowed for an area. max_...
[ "def", "compute_area_key", "(", "features", ",", "max_area_width", ",", "max_area_height", "=", "1", ",", "height", "=", "1", ",", "mode", "=", "\"mean\"", ",", "training", "=", "True", ",", "name", "=", "None", ")", ":", "tf", ".", "logging", ".", "in...
Computes the key for each area. Args: features: a Tensor in a shape of [batch_size, height * width, depth]. max_area_width: the max width allowed for an area. max_area_height: the max height allowed for an area. height: the height of the image. mode: whether to combine different area features or ...
[ "Computes", "the", "key", "for", "each", "area", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L234-L302
train
tensorflow/tensor2tensor
tensor2tensor/layers/area_attention.py
dot_product_area_attention
def dot_product_area_attention(q, k, v, bias, dropout_rate=0.0, image_shapes=None, name=None, attention...
python
def dot_product_area_attention(q, k, v, bias, dropout_rate=0.0, image_shapes=None, name=None, attention...
[ "def", "dot_product_area_attention", "(", "q", ",", "k", ",", "v", ",", "bias", ",", "dropout_rate", "=", "0.0", ",", "image_shapes", "=", "None", ",", "name", "=", "None", ",", "attention_image_summary", "=", "None", ",", "save_weights_to", "=", "None", "...
Dot-product area attention. Args: q: Tensor with shape [..., length_q, depth_k]. k: Tensor with shape [..., length_kv, depth_k]. Leading dimensions must match with q. v: Tensor with shape [..., length_kv, depth_v] Leading dimensions must match with q. bias: bias Tensor (see attention_bias...
[ "Dot", "-", "product", "area", "attention", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L305-L433
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based.py
setup_directories
def setup_directories(base_dir, subdirs): """Setup directories.""" base_dir = os.path.expanduser(base_dir) tf.gfile.MakeDirs(base_dir) all_dirs = {} for subdir in subdirs: if isinstance(subdir, six.string_types): subdir_tuple = (subdir,) else: subdir_tuple = subdir dir_name = os.path....
python
def setup_directories(base_dir, subdirs): """Setup directories.""" base_dir = os.path.expanduser(base_dir) tf.gfile.MakeDirs(base_dir) all_dirs = {} for subdir in subdirs: if isinstance(subdir, six.string_types): subdir_tuple = (subdir,) else: subdir_tuple = subdir dir_name = os.path....
[ "def", "setup_directories", "(", "base_dir", ",", "subdirs", ")", ":", "base_dir", "=", "os", ".", "path", ".", "expanduser", "(", "base_dir", ")", "tf", ".", "gfile", ".", "MakeDirs", "(", "base_dir", ")", "all_dirs", "=", "{", "}", "for", "subdir", "...
Setup directories.
[ "Setup", "directories", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L68-L82
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based.py
make_relative_timing_fn
def make_relative_timing_fn(): """Make a function that logs the duration since it was made.""" start_time = time.time() def format_relative_time(): time_delta = time.time() - start_time return str(datetime.timedelta(seconds=time_delta)) def log_relative_time(): tf.logging.info("Timing: %s", format...
python
def make_relative_timing_fn(): """Make a function that logs the duration since it was made.""" start_time = time.time() def format_relative_time(): time_delta = time.time() - start_time return str(datetime.timedelta(seconds=time_delta)) def log_relative_time(): tf.logging.info("Timing: %s", format...
[ "def", "make_relative_timing_fn", "(", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "def", "format_relative_time", "(", ")", ":", "time_delta", "=", "time", ".", "time", "(", ")", "-", "start_time", "return", "str", "(", "datetime", ".", "...
Make a function that logs the duration since it was made.
[ "Make", "a", "function", "that", "logs", "the", "duration", "since", "it", "was", "made", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L85-L96
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based.py
train_supervised
def train_supervised(problem, model_name, hparams, data_dir, output_dir, train_steps, eval_steps, local_eval_frequency=None, schedule="continuous_train_and_eval"): """Train supervised.""" if local_eval_frequency is None: local_eval_frequency = FLAGS.local_eval_frequency...
python
def train_supervised(problem, model_name, hparams, data_dir, output_dir, train_steps, eval_steps, local_eval_frequency=None, schedule="continuous_train_and_eval"): """Train supervised.""" if local_eval_frequency is None: local_eval_frequency = FLAGS.local_eval_frequency...
[ "def", "train_supervised", "(", "problem", ",", "model_name", ",", "hparams", ",", "data_dir", ",", "output_dir", ",", "train_steps", ",", "eval_steps", ",", "local_eval_frequency", "=", "None", ",", "schedule", "=", "\"continuous_train_and_eval\"", ")", ":", "if"...
Train supervised.
[ "Train", "supervised", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L125-L138
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based.py
train_agent
def train_agent(real_env, learner, world_model_dir, hparams, epoch): """Train the PPO agent in the simulated environment.""" initial_frame_chooser = rl_utils.make_initial_frame_chooser( real_env, hparams.frame_stack_size, hparams.simulation_random_starts, hparams.simulation_flip_first_random_for_beginni...
python
def train_agent(real_env, learner, world_model_dir, hparams, epoch): """Train the PPO agent in the simulated environment.""" initial_frame_chooser = rl_utils.make_initial_frame_chooser( real_env, hparams.frame_stack_size, hparams.simulation_random_starts, hparams.simulation_flip_first_random_for_beginni...
[ "def", "train_agent", "(", "real_env", ",", "learner", ",", "world_model_dir", ",", "hparams", ",", "epoch", ")", ":", "initial_frame_chooser", "=", "rl_utils", ".", "make_initial_frame_chooser", "(", "real_env", ",", "hparams", ".", "frame_stack_size", ",", "hpar...
Train the PPO agent in the simulated environment.
[ "Train", "the", "PPO", "agent", "in", "the", "simulated", "environment", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L141-L170
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based.py
train_agent_real_env
def train_agent_real_env(env, learner, hparams, epoch): """Train the PPO agent in the real environment.""" base_algo_str = hparams.base_algo train_hparams = trainer_lib.create_hparams(hparams.base_algo_params) rl_utils.update_hparams_from_hparams( train_hparams, hparams, "real_" + base_algo_str + "_" )...
python
def train_agent_real_env(env, learner, hparams, epoch): """Train the PPO agent in the real environment.""" base_algo_str = hparams.base_algo train_hparams = trainer_lib.create_hparams(hparams.base_algo_params) rl_utils.update_hparams_from_hparams( train_hparams, hparams, "real_" + base_algo_str + "_" )...
[ "def", "train_agent_real_env", "(", "env", ",", "learner", ",", "hparams", ",", "epoch", ")", ":", "base_algo_str", "=", "hparams", ".", "base_algo", "train_hparams", "=", "trainer_lib", ".", "create_hparams", "(", "hparams", ".", "base_algo_params", ")", "rl_ut...
Train the PPO agent in the real environment.
[ "Train", "the", "PPO", "agent", "in", "the", "real", "environment", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L173-L196
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based.py
train_world_model
def train_world_model( env, data_dir, output_dir, hparams, world_model_steps_num, epoch ): """Train the world model on problem_name.""" world_model_steps_num += world_model_step_increment( hparams, is_initial_epoch=(epoch == 0) ) model_hparams = trainer_lib.create_hparams(hparams.generative_model_para...
python
def train_world_model( env, data_dir, output_dir, hparams, world_model_steps_num, epoch ): """Train the world model on problem_name.""" world_model_steps_num += world_model_step_increment( hparams, is_initial_epoch=(epoch == 0) ) model_hparams = trainer_lib.create_hparams(hparams.generative_model_para...
[ "def", "train_world_model", "(", "env", ",", "data_dir", ",", "output_dir", ",", "hparams", ",", "world_model_steps_num", ",", "epoch", ")", ":", "world_model_steps_num", "+=", "world_model_step_increment", "(", "hparams", ",", "is_initial_epoch", "=", "(", "epoch",...
Train the world model on problem_name.
[ "Train", "the", "world", "model", "on", "problem_name", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L199-L228
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based.py
load_metrics
def load_metrics(event_dir, epoch): """Loads metrics for this epoch if they have already been written. This reads the entire event file but it's small with just per-epoch metrics. Args: event_dir: TODO(koz4k): Document this. epoch: TODO(koz4k): Document this. Returns: metrics. """ metrics = {...
python
def load_metrics(event_dir, epoch): """Loads metrics for this epoch if they have already been written. This reads the entire event file but it's small with just per-epoch metrics. Args: event_dir: TODO(koz4k): Document this. epoch: TODO(koz4k): Document this. Returns: metrics. """ metrics = {...
[ "def", "load_metrics", "(", "event_dir", ",", "epoch", ")", ":", "metrics", "=", "{", "}", "for", "filename", "in", "tf", ".", "gfile", ".", "ListDirectory", "(", "event_dir", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "event_dir", "...
Loads metrics for this epoch if they have already been written. This reads the entire event file but it's small with just per-epoch metrics. Args: event_dir: TODO(koz4k): Document this. epoch: TODO(koz4k): Document this. Returns: metrics.
[ "Loads", "metrics", "for", "this", "epoch", "if", "they", "have", "already", "been", "written", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L231-L250
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based.py
training_loop
def training_loop(hparams, output_dir, report_fn=None, report_metric=None): """Run the main training loop.""" if report_fn: assert report_metric is not None # Directories subdirectories = [ "data", "tmp", "world_model", ("world_model", "debug_videos"), "policy", "eval_metrics" ] directories...
python
def training_loop(hparams, output_dir, report_fn=None, report_metric=None): """Run the main training loop.""" if report_fn: assert report_metric is not None # Directories subdirectories = [ "data", "tmp", "world_model", ("world_model", "debug_videos"), "policy", "eval_metrics" ] directories...
[ "def", "training_loop", "(", "hparams", ",", "output_dir", ",", "report_fn", "=", "None", ",", "report_metric", "=", "None", ")", ":", "if", "report_fn", ":", "assert", "report_metric", "is", "not", "None", "# Directories", "subdirectories", "=", "[", "\"data\...
Run the main training loop.
[ "Run", "the", "main", "training", "loop", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L253-L378
train
tensorflow/tensor2tensor
tensor2tensor/models/research/gene_expression.py
conv_layer
def conv_layer(x, hidden_size, kernel_size, stride, pooling_window, dropout_rate, dilation_rate, name="conv"): """Single conv layer with relu, optional pooling, and dropout.""" with tf.variable_scope(name): ...
python
def conv_layer(x, hidden_size, kernel_size, stride, pooling_window, dropout_rate, dilation_rate, name="conv"): """Single conv layer with relu, optional pooling, and dropout.""" with tf.variable_scope(name): ...
[ "def", "conv_layer", "(", "x", ",", "hidden_size", ",", "kernel_size", ",", "stride", ",", "pooling_window", ",", "dropout_rate", ",", "dilation_rate", ",", "name", "=", "\"conv\"", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "out...
Single conv layer with relu, optional pooling, and dropout.
[ "Single", "conv", "layer", "with", "relu", "optional", "pooling", "and", "dropout", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/gene_expression.py#L92-L114
train
tensorflow/tensor2tensor
tensor2tensor/models/research/gene_expression.py
gene_expression_conv_base
def gene_expression_conv_base(): """Hparams for GeneExpressionConv model.""" hparams = common_hparams.basic_params1() batch_size = 10 output_length = 2048 inputs_per_output = 128 chunk_size = 4 input_length = output_length * inputs_per_output // chunk_size hparams.batch_size = input_length * batch_size...
python
def gene_expression_conv_base(): """Hparams for GeneExpressionConv model.""" hparams = common_hparams.basic_params1() batch_size = 10 output_length = 2048 inputs_per_output = 128 chunk_size = 4 input_length = output_length * inputs_per_output // chunk_size hparams.batch_size = input_length * batch_size...
[ "def", "gene_expression_conv_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "batch_size", "=", "10", "output_length", "=", "2048", "inputs_per_output", "=", "128", "chunk_size", "=", "4", "input_length", "=", "output_length...
Hparams for GeneExpressionConv model.
[ "Hparams", "for", "GeneExpressionConv", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/gene_expression.py#L128-L149
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
compress_self_attention_layer
def compress_self_attention_layer(x, hparams, name=None): """Attend function.""" with tf.variable_scope(name, default_name="compress_self_attention"): x, xshape, _ = cia.maybe_reshape_4d_to_3d(x) y = common_attention.multihead_attention( common_layers.layer_preprocess(x, hparams), None, ...
python
def compress_self_attention_layer(x, hparams, name=None): """Attend function.""" with tf.variable_scope(name, default_name="compress_self_attention"): x, xshape, _ = cia.maybe_reshape_4d_to_3d(x) y = common_attention.multihead_attention( common_layers.layer_preprocess(x, hparams), None, ...
[ "def", "compress_self_attention_layer", "(", "x", ",", "hparams", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"compress_self_attention\"", ")", ":", "x", ",", "xshape", ",", "_", "=", "c...
Attend function.
[ "Attend", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L35-L48
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
compute_nats_and_bits_per_dim
def compute_nats_and_bits_per_dim(data_dim, latent_dim, average_reconstruction, average_prior): """Computes negative ELBO, which is an upper bound on the negative likelihood. Args: data_dim: int-like indicatin...
python
def compute_nats_and_bits_per_dim(data_dim, latent_dim, average_reconstruction, average_prior): """Computes negative ELBO, which is an upper bound on the negative likelihood. Args: data_dim: int-like indicatin...
[ "def", "compute_nats_and_bits_per_dim", "(", "data_dim", ",", "latent_dim", ",", "average_reconstruction", ",", "average_prior", ")", ":", "with", "tf", ".", "name_scope", "(", "None", ",", "default_name", "=", "\"compute_nats_per_dim\"", ")", ":", "data_dim", "=", ...
Computes negative ELBO, which is an upper bound on the negative likelihood. Args: data_dim: int-like indicating data dimensionality. latent_dim: int-like indicating latent dimensionality. average_reconstruction: Scalar Tensor indicating the reconstruction cost averaged over all data dimensions and ...
[ "Computes", "negative", "ELBO", "which", "is", "an", "upper", "bound", "on", "the", "negative", "likelihood", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L51-L77
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
multinomial_sample
def multinomial_sample(x, vocab_size=None, sampling_method="random", temperature=1.0): """Multinomial sampling from a n-dimensional tensor. Args: x: Tensor of shape [..., vocab_size]. Parameterizes logits of multinomial. vocab_size: Number of classes in multinomial distribution. ...
python
def multinomial_sample(x, vocab_size=None, sampling_method="random", temperature=1.0): """Multinomial sampling from a n-dimensional tensor. Args: x: Tensor of shape [..., vocab_size]. Parameterizes logits of multinomial. vocab_size: Number of classes in multinomial distribution. ...
[ "def", "multinomial_sample", "(", "x", ",", "vocab_size", "=", "None", ",", "sampling_method", "=", "\"random\"", ",", "temperature", "=", "1.0", ")", ":", "vocab_size", "=", "vocab_size", "or", "common_layers", ".", "shape_list", "(", "x", ")", "[", "-", ...
Multinomial sampling from a n-dimensional tensor. Args: x: Tensor of shape [..., vocab_size]. Parameterizes logits of multinomial. vocab_size: Number of classes in multinomial distribution. sampling_method: String, "random" or otherwise deterministic. temperature: Positive float. Returns: Tens...
[ "Multinomial", "sampling", "from", "a", "n", "-", "dimensional", "tensor", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L80-L99
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
ae_latent_softmax
def ae_latent_softmax(latents_pred, latents_discrete_hot, vocab_size, hparams): """Latent prediction and loss. Args: latents_pred: Tensor of shape [..., depth]. latents_discrete_hot: Tensor of shape [..., vocab_size]. vocab_size: an int representing the vocab size. hparams: HParams. Returns: ...
python
def ae_latent_softmax(latents_pred, latents_discrete_hot, vocab_size, hparams): """Latent prediction and loss. Args: latents_pred: Tensor of shape [..., depth]. latents_discrete_hot: Tensor of shape [..., vocab_size]. vocab_size: an int representing the vocab size. hparams: HParams. Returns: ...
[ "def", "ae_latent_softmax", "(", "latents_pred", ",", "latents_discrete_hot", ",", "vocab_size", ",", "hparams", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"latent_logits\"", ")", ":", "latents_logits", "=", "tf", ".", "layers", ".", "dense", "(", "...
Latent prediction and loss. Args: latents_pred: Tensor of shape [..., depth]. latents_discrete_hot: Tensor of shape [..., vocab_size]. vocab_size: an int representing the vocab size. hparams: HParams. Returns: sample: Tensor of shape [...], a sample from a multinomial distribution. loss: T...
[ "Latent", "prediction", "and", "loss", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L102-L130
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
ae_latent_sample_beam
def ae_latent_sample_beam(latents_dense_in, inputs, ed, embed, hparams): """Samples from the latent space in the autoencoder. Args: latents_dense_in: Tensor of shape [batch, length_q, ...]. Only the shape of its first two dimensions are used. length_q is the latent length, which is height * width *...
python
def ae_latent_sample_beam(latents_dense_in, inputs, ed, embed, hparams): """Samples from the latent space in the autoencoder. Args: latents_dense_in: Tensor of shape [batch, length_q, ...]. Only the shape of its first two dimensions are used. length_q is the latent length, which is height * width *...
[ "def", "ae_latent_sample_beam", "(", "latents_dense_in", ",", "inputs", ",", "ed", ",", "embed", ",", "hparams", ")", ":", "def", "symbols_to_logits_fn", "(", "ids", ")", ":", "\"\"\"Go from ids to logits.\"\"\"", "ids", "=", "tf", ".", "expand_dims", "(", "ids"...
Samples from the latent space in the autoencoder. Args: latents_dense_in: Tensor of shape [batch, length_q, ...]. Only the shape of its first two dimensions are used. length_q is the latent length, which is height * width * hparams.num_latents / (2**hparams.num_compress_steps). inputs: Tensor of ...
[ "Samples", "from", "the", "latent", "space", "in", "the", "autoencoder", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L133-L182
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
residual_block_layer
def residual_block_layer(inputs, hparams): """Residual block over inputs. Runs a residual block consisting of conv: kernel_size x kernel_size conv: 1x1 dropout, add and normalize according to hparams.layer_postprocess_sequence. Args: inputs: Tensor of shape [batch, height, width, hparams.hidden_...
python
def residual_block_layer(inputs, hparams): """Residual block over inputs. Runs a residual block consisting of conv: kernel_size x kernel_size conv: 1x1 dropout, add and normalize according to hparams.layer_postprocess_sequence. Args: inputs: Tensor of shape [batch, height, width, hparams.hidden_...
[ "def", "residual_block_layer", "(", "inputs", ",", "hparams", ")", ":", "kernel", "=", "(", "hparams", ".", "res_kernel_size", ",", "hparams", ".", "res_kernel_size", ")", "x", "=", "inputs", "for", "i", "in", "range", "(", "hparams", ".", "num_res_layers", ...
Residual block over inputs. Runs a residual block consisting of conv: kernel_size x kernel_size conv: 1x1 dropout, add and normalize according to hparams.layer_postprocess_sequence. Args: inputs: Tensor of shape [batch, height, width, hparams.hidden_size]. hparams: HParams. Returns: Ten...
[ "Residual", "block", "over", "inputs", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L185-L219
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
compress_encoder
def compress_encoder(inputs, hparams, strides=(2, 2), kernel_size=(3, 3), name=None): """Encoder that compresses 2-D inputs by 2**num_compress_steps. Args: inputs: Tensor of shape [batch, height, width, channels]. hparams: ...
python
def compress_encoder(inputs, hparams, strides=(2, 2), kernel_size=(3, 3), name=None): """Encoder that compresses 2-D inputs by 2**num_compress_steps. Args: inputs: Tensor of shape [batch, height, width, channels]. hparams: ...
[ "def", "compress_encoder", "(", "inputs", ",", "hparams", ",", "strides", "=", "(", "2", ",", "2", ")", ",", "kernel_size", "=", "(", "3", ",", "3", ")", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "...
Encoder that compresses 2-D inputs by 2**num_compress_steps. Args: inputs: Tensor of shape [batch, height, width, channels]. hparams: HParams. strides: Tuple, strides for conv block. kernel_size: Tuple, kernel window size for conv block. name: string, variable scope. Returns: Tensor of sha...
[ "Encoder", "that", "compresses", "2", "-", "D", "inputs", "by", "2", "**", "num_compress_steps", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L222-L270
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
compress_encoder_2d
def compress_encoder_2d(x, hparams, name=None): """Encoder that compresses 2-D inputs by 2**num_compress_steps. Args: x: Tensor of shape [batch, height, width, channels]. hparams: HParams. name: string, variable scope. Returns: Tensor of shape [batch, latent_length, hparams.hidden_size], where ...
python
def compress_encoder_2d(x, hparams, name=None): """Encoder that compresses 2-D inputs by 2**num_compress_steps. Args: x: Tensor of shape [batch, height, width, channels]. hparams: HParams. name: string, variable scope. Returns: Tensor of shape [batch, latent_length, hparams.hidden_size], where ...
[ "def", "compress_encoder_2d", "(", "x", ",", "hparams", ",", "name", "=", "None", ")", ":", "return", "compress_encoder", "(", "x", ",", "hparams", ",", "strides", "=", "(", "2", ",", "2", ")", ",", "kernel_size", "=", "(", "hparams", ".", "kernel_size...
Encoder that compresses 2-D inputs by 2**num_compress_steps. Args: x: Tensor of shape [batch, height, width, channels]. hparams: HParams. name: string, variable scope. Returns: Tensor of shape [batch, latent_length, hparams.hidden_size], where latent_length is hparams.num_latents * (he...
[ "Encoder", "that", "compresses", "2", "-", "D", "inputs", "by", "2", "**", "num_compress_steps", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L273-L291
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
compress_encoder_1d
def compress_encoder_1d(x, hparams, name=None): """Encoder that compresses 1-D inputs by 2**num_compress_steps. Args: x: Tensor of shape [batch, length, channels]. hparams: HParams. name: string, variable scope. Returns: Tensor of shape [batch, latent_length, hparams.hidden_size], where la...
python
def compress_encoder_1d(x, hparams, name=None): """Encoder that compresses 1-D inputs by 2**num_compress_steps. Args: x: Tensor of shape [batch, length, channels]. hparams: HParams. name: string, variable scope. Returns: Tensor of shape [batch, latent_length, hparams.hidden_size], where la...
[ "def", "compress_encoder_1d", "(", "x", ",", "hparams", ",", "name", "=", "None", ")", ":", "x", "=", "tf", ".", "expand_dims", "(", "x", ",", "axis", "=", "2", ")", "return", "compress_encoder", "(", "x", ",", "hparams", ",", "strides", "=", "(", ...
Encoder that compresses 1-D inputs by 2**num_compress_steps. Args: x: Tensor of shape [batch, length, channels]. hparams: HParams. name: string, variable scope. Returns: Tensor of shape [batch, latent_length, hparams.hidden_size], where latent_length is hparams.num_latents * length / 2...
[ "Encoder", "that", "compresses", "1", "-", "D", "inputs", "by", "2", "**", "num_compress_steps", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L294-L312
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
decompress_decoder
def decompress_decoder(inputs, hparams, strides=(2, 2), kernel=(3, 3), name=None): """Decoder that decompresses 2-D inputs by 2**num_compress_steps. Args: inputs: Tensor of shape [batch, compress_height, compress_width,...
python
def decompress_decoder(inputs, hparams, strides=(2, 2), kernel=(3, 3), name=None): """Decoder that decompresses 2-D inputs by 2**num_compress_steps. Args: inputs: Tensor of shape [batch, compress_height, compress_width,...
[ "def", "decompress_decoder", "(", "inputs", ",", "hparams", ",", "strides", "=", "(", "2", ",", "2", ")", ",", "kernel", "=", "(", "3", ",", "3", ")", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "def...
Decoder that decompresses 2-D inputs by 2**num_compress_steps. Args: inputs: Tensor of shape [batch, compress_height, compress_width, channels]. hparams: HParams. strides: Tuple, strides for conv block. kernel: Tuple, kernel window size for conv block. name: string, variable scope. Returns: ...
[ "Decoder", "that", "decompresses", "2", "-", "D", "inputs", "by", "2", "**", "num_compress_steps", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L315-L352
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
decompress_decoder_2d
def decompress_decoder_2d(x, hparams, name=None): """Decoder that decompresses 2-D inputs by 2**num_compress_steps. Args: x: Tensor of shape [batch, compress_height, compress_width, channels]. hparams: HParams. name: string, variable scope. Returns: Tensor of shape [batch, height, width, hparams...
python
def decompress_decoder_2d(x, hparams, name=None): """Decoder that decompresses 2-D inputs by 2**num_compress_steps. Args: x: Tensor of shape [batch, compress_height, compress_width, channels]. hparams: HParams. name: string, variable scope. Returns: Tensor of shape [batch, height, width, hparams...
[ "def", "decompress_decoder_2d", "(", "x", ",", "hparams", ",", "name", "=", "None", ")", ":", "return", "decompress_decoder", "(", "x", ",", "hparams", ",", "strides", "=", "(", "2", ",", "2", ")", ",", "kernel", "=", "(", "hparams", ".", "kernel_size"...
Decoder that decompresses 2-D inputs by 2**num_compress_steps. Args: x: Tensor of shape [batch, compress_height, compress_width, channels]. hparams: HParams. name: string, variable scope. Returns: Tensor of shape [batch, height, width, hparams.hidden_size].
[ "Decoder", "that", "decompresses", "2", "-", "D", "inputs", "by", "2", "**", "num_compress_steps", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L355-L369
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
decompress_decoder_1d
def decompress_decoder_1d(x, hparams, name=None): """Decoder that decompresses 1-D inputs by 2**num_compress_steps. Args: x: Tensor of shape [batch, compress_length, channels]. hparams: HParams. name: string, variable scope. Returns: Tensor of shape [batch, length, hparams.hidden_size]. """ ...
python
def decompress_decoder_1d(x, hparams, name=None): """Decoder that decompresses 1-D inputs by 2**num_compress_steps. Args: x: Tensor of shape [batch, compress_length, channels]. hparams: HParams. name: string, variable scope. Returns: Tensor of shape [batch, length, hparams.hidden_size]. """ ...
[ "def", "decompress_decoder_1d", "(", "x", ",", "hparams", ",", "name", "=", "None", ")", ":", "x", "=", "tf", ".", "expand_dims", "(", "x", ",", "axis", "=", "2", ")", "output", "=", "decompress_decoder", "(", "x", ",", "hparams", ",", "strides", "="...
Decoder that decompresses 1-D inputs by 2**num_compress_steps. Args: x: Tensor of shape [batch, compress_length, channels]. hparams: HParams. name: string, variable scope. Returns: Tensor of shape [batch, length, hparams.hidden_size].
[ "Decoder", "that", "decompresses", "1", "-", "D", "inputs", "by", "2", "**", "num_compress_steps", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L372-L388
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
transformer_text_encoder
def transformer_text_encoder(inputs, target_space, hparams, name=None): """Transformer text encoder over inputs with unmasked full attention. Args: inputs: Tensor of shape [batch, length, 1, hparams.hidden_size]. target_...
python
def transformer_text_encoder(inputs, target_space, hparams, name=None): """Transformer text encoder over inputs with unmasked full attention. Args: inputs: Tensor of shape [batch, length, 1, hparams.hidden_size]. target_...
[ "def", "transformer_text_encoder", "(", "inputs", ",", "target_space", ",", "hparams", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"transformer_text_encoder\"", ")", ":", "inputs", "=", "com...
Transformer text encoder over inputs with unmasked full attention. Args: inputs: Tensor of shape [batch, length, 1, hparams.hidden_size]. target_space: int. Used for encoding inputs under a target space id. hparams: HParams. name: string, variable scope. Returns: encoder_output: Tensor of shap...
[ "Transformer", "text", "encoder", "over", "inputs", "with", "unmasked", "full", "attention", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L391-L419
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
transformer_image_decoder
def transformer_image_decoder(targets, encoder_output, ed_attention_bias, hparams, name=None): """Transformer image decoder over targets with local attention. Args: targets: Tensor of shape [...
python
def transformer_image_decoder(targets, encoder_output, ed_attention_bias, hparams, name=None): """Transformer image decoder over targets with local attention. Args: targets: Tensor of shape [...
[ "def", "transformer_image_decoder", "(", "targets", ",", "encoder_output", ",", "ed_attention_bias", ",", "hparams", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"transformer_dec\"", ")", ":", ...
Transformer image decoder over targets with local attention. Args: targets: Tensor of shape [batch, ...], and whose size is batch * height * width * hparams.num_channels * hparams.hidden_size. encoder_output: Tensor of shape [batch, length_kv, hparams.hidden_size]. ed_attention_bias: Tensor which b...
[ "Transformer", "image", "decoder", "over", "targets", "with", "local", "attention", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L422-L462
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
transformer_latent_decoder
def transformer_latent_decoder(x, encoder_output, ed_attention_bias, hparams, name=None): """Transformer decoder over latents using latent_attention_type. Args: x: Tensor of shape [batch,...
python
def transformer_latent_decoder(x, encoder_output, ed_attention_bias, hparams, name=None): """Transformer decoder over latents using latent_attention_type. Args: x: Tensor of shape [batch,...
[ "def", "transformer_latent_decoder", "(", "x", ",", "encoder_output", ",", "ed_attention_bias", ",", "hparams", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"transformer_latent_dec\"", ")", ":"...
Transformer decoder over latents using latent_attention_type. Args: x: Tensor of shape [batch, length_q, hparams.hidden_size]. length_q is the latent length, which is height * width * hparams.num_latents / (2**hparams.num_compress_steps). encoder_output: Tensor of shape [batch, length_kv, hparams...
[ "Transformer", "decoder", "over", "latents", "using", "latent_attention_type", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L465-L506
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
bottleneck_layer
def bottleneck_layer(inputs, hparams, name="discrete_bottleneck"): """Computes latents given inputs (typically, compressed targets).""" [ latents_dense, latents_discrete, extra_loss, embed_fn, _, ] = hparams.bottleneck(inputs=inputs, ...
python
def bottleneck_layer(inputs, hparams, name="discrete_bottleneck"): """Computes latents given inputs (typically, compressed targets).""" [ latents_dense, latents_discrete, extra_loss, embed_fn, _, ] = hparams.bottleneck(inputs=inputs, ...
[ "def", "bottleneck_layer", "(", "inputs", ",", "hparams", ",", "name", "=", "\"discrete_bottleneck\"", ")", ":", "[", "latents_dense", ",", "latents_discrete", ",", "extra_loss", ",", "embed_fn", ",", "_", ",", "]", "=", "hparams", ".", "bottleneck", "(", "i...
Computes latents given inputs (typically, compressed targets).
[ "Computes", "latents", "given", "inputs", "(", "typically", "compressed", "targets", ")", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L509-L526
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
latent_prediction_model
def latent_prediction_model(inputs, ed_attention_bias, latents_discrete, latents_dense, hparams, vocab_size=None, name=None): """Transformer-based lat...
python
def latent_prediction_model(inputs, ed_attention_bias, latents_discrete, latents_dense, hparams, vocab_size=None, name=None): """Transformer-based lat...
[ "def", "latent_prediction_model", "(", "inputs", ",", "ed_attention_bias", ",", "latents_discrete", ",", "latents_dense", ",", "hparams", ",", "vocab_size", "=", "None", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",",...
Transformer-based latent prediction model. It is an autoregressive decoder over latents_discrete given inputs. Args: inputs: Tensor of shape [batch, length_kv, hparams.hidden_size]. Inputs to attend to for the decoder on latents. ed_attention_bias: Tensor which broadcasts with shape [batch, hp...
[ "Transformer", "-", "based", "latent", "prediction", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L529-L573
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
transformer_autoencoder
def transformer_autoencoder(inputs, targets, target_space, hparams, cache=None, predict_mask=1.0): """Auto-encoder using a Transformer decoder and a prior over latent sequences. ...
python
def transformer_autoencoder(inputs, targets, target_space, hparams, cache=None, predict_mask=1.0): """Auto-encoder using a Transformer decoder and a prior over latent sequences. ...
[ "def", "transformer_autoencoder", "(", "inputs", ",", "targets", ",", "target_space", ",", "hparams", ",", "cache", "=", "None", ",", "predict_mask", "=", "1.0", ")", ":", "original_targets_shape", "=", "common_layers", ".", "shape_list", "(", "targets", ")", ...
Auto-encoder using a Transformer decoder and a prior over latent sequences. Args: inputs: Tensor of shape [batch, length, 1, hparams.hidden_size] or None. targets: Tensor of shape [batch, ..., channels]. Ellipses may be 1 or 2 dimensions denoting sequence length. target_space: int. Used for encodin...
[ "Auto", "-", "encoder", "using", "a", "Transformer", "decoder", "and", "a", "prior", "over", "latent", "sequences", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L576-L700
train
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
iaf_flow
def iaf_flow(one_hot_assignments, scale_weights, scale_bias, num_codes, summary=True, name=None): """Performs a single IAF flow using scale and normalization transformations. Args: one_hot_assignments: Assignments Tensor with shape [num_samples, ...
python
def iaf_flow(one_hot_assignments, scale_weights, scale_bias, num_codes, summary=True, name=None): """Performs a single IAF flow using scale and normalization transformations. Args: one_hot_assignments: Assignments Tensor with shape [num_samples, ...
[ "def", "iaf_flow", "(", "one_hot_assignments", ",", "scale_weights", ",", "scale_bias", ",", "num_codes", ",", "summary", "=", "True", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ",", "default_name", "=", "\"iaf\"", ")...
Performs a single IAF flow using scale and normalization transformations. Args: one_hot_assignments: Assignments Tensor with shape [num_samples, batch_size, latent_size, num_codes]. scale_weights: Tensor corresponding to lower triangular matrix used to autoregressively generate scale matrix from ...
[ "Performs", "a", "single", "IAF", "flow", "using", "scale", "and", "normalization", "transformations", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L703-L758
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/image_lsun.py
_get_lsun
def _get_lsun(directory, category, split_name): """Downloads all lsun files to directory unless they are there.""" generator_utils.maybe_download(directory, _LSUN_DATA_FILENAME % (category, split_name), _LSUN_URL % (category, split_name))
python
def _get_lsun(directory, category, split_name): """Downloads all lsun files to directory unless they are there.""" generator_utils.maybe_download(directory, _LSUN_DATA_FILENAME % (category, split_name), _LSUN_URL % (category, split_name))
[ "def", "_get_lsun", "(", "directory", ",", "category", ",", "split_name", ")", ":", "generator_utils", ".", "maybe_download", "(", "directory", ",", "_LSUN_DATA_FILENAME", "%", "(", "category", ",", "split_name", ")", ",", "_LSUN_URL", "%", "(", "category", ",...
Downloads all lsun files to directory unless they are there.
[ "Downloads", "all", "lsun", "files", "to", "directory", "unless", "they", "are", "there", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_lsun.py#L40-L44
train
tensorflow/tensor2tensor
tensor2tensor/utils/optimize.py
_mixed_precision_is_enabled
def _mixed_precision_is_enabled(hparams): """Should be the same as in common_attention, avoiding import.""" activation_dtype = hparams.activation_dtype weight_dtype = hparams.weight_dtype return activation_dtype == tf.float16 and weight_dtype == tf.float32
python
def _mixed_precision_is_enabled(hparams): """Should be the same as in common_attention, avoiding import.""" activation_dtype = hparams.activation_dtype weight_dtype = hparams.weight_dtype return activation_dtype == tf.float16 and weight_dtype == tf.float32
[ "def", "_mixed_precision_is_enabled", "(", "hparams", ")", ":", "activation_dtype", "=", "hparams", ".", "activation_dtype", "weight_dtype", "=", "hparams", ".", "weight_dtype", "return", "activation_dtype", "==", "tf", ".", "float16", "and", "weight_dtype", "==", "...
Should be the same as in common_attention, avoiding import.
[ "Should", "be", "the", "same", "as", "in", "common_attention", "avoiding", "import", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L36-L40
train
tensorflow/tensor2tensor
tensor2tensor/utils/optimize.py
optimize
def optimize(loss, learning_rate, hparams, use_tpu=False, variables=None): """Minimize loss.""" loss = weight_decay_and_noise(loss, hparams, learning_rate) loss = tf.identity(loss, name="total_loss") if variables is None: variables = tf.trainable_variables() # Print trainable variables. log_variable_siz...
python
def optimize(loss, learning_rate, hparams, use_tpu=False, variables=None): """Minimize loss.""" loss = weight_decay_and_noise(loss, hparams, learning_rate) loss = tf.identity(loss, name="total_loss") if variables is None: variables = tf.trainable_variables() # Print trainable variables. log_variable_siz...
[ "def", "optimize", "(", "loss", ",", "learning_rate", ",", "hparams", ",", "use_tpu", "=", "False", ",", "variables", "=", "None", ")", ":", "loss", "=", "weight_decay_and_noise", "(", "loss", ",", "hparams", ",", "learning_rate", ")", "loss", "=", "tf", ...
Minimize loss.
[ "Minimize", "loss", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L43-L94
train
tensorflow/tensor2tensor
tensor2tensor/utils/optimize.py
weight_decay_and_noise
def weight_decay_and_noise(loss, hparams, learning_rate, var_list=None): """Apply weight decay and weight noise.""" if var_list is None: var_list = tf.trainable_variables() decay_vars = [v for v in var_list] noise_vars = [v for v in var_list if "/body/" in v.name] weight_decay_loss = weight_decay(hparam...
python
def weight_decay_and_noise(loss, hparams, learning_rate, var_list=None): """Apply weight decay and weight noise.""" if var_list is None: var_list = tf.trainable_variables() decay_vars = [v for v in var_list] noise_vars = [v for v in var_list if "/body/" in v.name] weight_decay_loss = weight_decay(hparam...
[ "def", "weight_decay_and_noise", "(", "loss", ",", "hparams", ",", "learning_rate", ",", "var_list", "=", "None", ")", ":", "if", "var_list", "is", "None", ":", "var_list", "=", "tf", ".", "trainable_variables", "(", ")", "decay_vars", "=", "[", "v", "for"...
Apply weight decay and weight noise.
[ "Apply", "weight", "decay", "and", "weight", "noise", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L238-L256
train
tensorflow/tensor2tensor
tensor2tensor/utils/optimize.py
weight_noise
def weight_noise(noise_rate, learning_rate, var_list): """Apply weight noise to vars in var_list.""" if not noise_rate: return [tf.no_op()] tf.logging.info("Applying weight noise scaled by learning rate, " "noise_rate: %0.5f", noise_rate) noise_ops = [] for v in var_list: with tf....
python
def weight_noise(noise_rate, learning_rate, var_list): """Apply weight noise to vars in var_list.""" if not noise_rate: return [tf.no_op()] tf.logging.info("Applying weight noise scaled by learning rate, " "noise_rate: %0.5f", noise_rate) noise_ops = [] for v in var_list: with tf....
[ "def", "weight_noise", "(", "noise_rate", ",", "learning_rate", ",", "var_list", ")", ":", "if", "not", "noise_rate", ":", "return", "[", "tf", ".", "no_op", "(", ")", "]", "tf", ".", "logging", ".", "info", "(", "\"Applying weight noise scaled by learning rat...
Apply weight noise to vars in var_list.
[ "Apply", "weight", "noise", "to", "vars", "in", "var_list", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L259-L278
train
tensorflow/tensor2tensor
tensor2tensor/utils/optimize.py
weight_decay
def weight_decay(decay_rate, var_list, skip_biases=True): """Apply weight decay to vars in var_list.""" if not decay_rate: return 0. tf.logging.info("Applying weight decay, decay_rate: %0.5f", decay_rate) weight_decays = [] for v in var_list: # Weight decay. # This is a heuristic way to detect b...
python
def weight_decay(decay_rate, var_list, skip_biases=True): """Apply weight decay to vars in var_list.""" if not decay_rate: return 0. tf.logging.info("Applying weight decay, decay_rate: %0.5f", decay_rate) weight_decays = [] for v in var_list: # Weight decay. # This is a heuristic way to detect b...
[ "def", "weight_decay", "(", "decay_rate", ",", "var_list", ",", "skip_biases", "=", "True", ")", ":", "if", "not", "decay_rate", ":", "return", "0.", "tf", ".", "logging", ".", "info", "(", "\"Applying weight decay, decay_rate: %0.5f\"", ",", "decay_rate", ")", ...
Apply weight decay to vars in var_list.
[ "Apply", "weight", "decay", "to", "vars", "in", "var_list", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L281-L298
train
tensorflow/tensor2tensor
tensor2tensor/utils/optimize.py
log_variable_sizes
def log_variable_sizes(var_list=None, tag=None, verbose=False): """Log the sizes and shapes of variables, and the total size. Args: var_list: a list of variables; defaults to trainable_variables tag: a string; defaults to "Trainable Variables" verbose: bool, if True, log every weight; otherwise, log to...
python
def log_variable_sizes(var_list=None, tag=None, verbose=False): """Log the sizes and shapes of variables, and the total size. Args: var_list: a list of variables; defaults to trainable_variables tag: a string; defaults to "Trainable Variables" verbose: bool, if True, log every weight; otherwise, log to...
[ "def", "log_variable_sizes", "(", "var_list", "=", "None", ",", "tag", "=", "None", ",", "verbose", "=", "False", ")", ":", "if", "var_list", "is", "None", ":", "var_list", "=", "tf", ".", "trainable_variables", "(", ")", "if", "tag", "is", "None", ":"...
Log the sizes and shapes of variables, and the total size. Args: var_list: a list of variables; defaults to trainable_variables tag: a string; defaults to "Trainable Variables" verbose: bool, if True, log every weight; otherwise, log total size only.
[ "Log", "the", "sizes", "and", "shapes", "of", "variables", "and", "the", "total", "size", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L301-L327
train
tensorflow/tensor2tensor
tensor2tensor/utils/optimize.py
summarize_variables
def summarize_variables(var_list=None, tag=None): """Summarize the variables. Args: var_list: a list of variables; defaults to trainable_variables. tag: name scope of the summary; defaults to training_variables/. """ if var_list is None: var_list = tf.trainable_variables() if tag is None: tag...
python
def summarize_variables(var_list=None, tag=None): """Summarize the variables. Args: var_list: a list of variables; defaults to trainable_variables. tag: name scope of the summary; defaults to training_variables/. """ if var_list is None: var_list = tf.trainable_variables() if tag is None: tag...
[ "def", "summarize_variables", "(", "var_list", "=", "None", ",", "tag", "=", "None", ")", ":", "if", "var_list", "is", "None", ":", "var_list", "=", "tf", ".", "trainable_variables", "(", ")", "if", "tag", "is", "None", ":", "tag", "=", "\"training_varia...
Summarize the variables. Args: var_list: a list of variables; defaults to trainable_variables. tag: name scope of the summary; defaults to training_variables/.
[ "Summarize", "the", "variables", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L330-L345
train
tensorflow/tensor2tensor
tensor2tensor/utils/optimize.py
get_variable_initializer
def get_variable_initializer(hparams): """Get variable initializer from hparams.""" if not hparams.initializer: return None mlperf_log.transformer_print(key=mlperf_log.MODEL_HP_INITIALIZER_GAIN, value=hparams.initializer_gain, hparams=hparams) ...
python
def get_variable_initializer(hparams): """Get variable initializer from hparams.""" if not hparams.initializer: return None mlperf_log.transformer_print(key=mlperf_log.MODEL_HP_INITIALIZER_GAIN, value=hparams.initializer_gain, hparams=hparams) ...
[ "def", "get_variable_initializer", "(", "hparams", ")", ":", "if", "not", "hparams", ".", "initializer", ":", "return", "None", "mlperf_log", ".", "transformer_print", "(", "key", "=", "mlperf_log", ".", "MODEL_HP_INITIALIZER_GAIN", ",", "value", "=", "hparams", ...
Get variable initializer from hparams.
[ "Get", "variable", "initializer", "from", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L348-L373
train
tensorflow/tensor2tensor
tensor2tensor/layers/vqa_layers.py
summarize_tensors
def summarize_tensors(tensor_dict, tag=None): """Summarize the tensors. Args: tensor_dict: a dictionary of tensors. tag: name scope of the summary; defaults to tensors/. """ if tag is None: tag = "tensors/" for t_name in list(tensor_dict): t = tensor_dict[t_name] tf.summary.histogram(tag...
python
def summarize_tensors(tensor_dict, tag=None): """Summarize the tensors. Args: tensor_dict: a dictionary of tensors. tag: name scope of the summary; defaults to tensors/. """ if tag is None: tag = "tensors/" for t_name in list(tensor_dict): t = tensor_dict[t_name] tf.summary.histogram(tag...
[ "def", "summarize_tensors", "(", "tensor_dict", ",", "tag", "=", "None", ")", ":", "if", "tag", "is", "None", ":", "tag", "=", "\"tensors/\"", "for", "t_name", "in", "list", "(", "tensor_dict", ")", ":", "t", "=", "tensor_dict", "[", "t_name", "]", "tf...
Summarize the tensors. Args: tensor_dict: a dictionary of tensors. tag: name scope of the summary; defaults to tensors/.
[ "Summarize", "the", "tensors", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/vqa_layers.py#L33-L45
train
tensorflow/tensor2tensor
tensor2tensor/layers/vqa_layers.py
image_embedding
def image_embedding(images, model_fn=resnet_v1_152, trainable=True, is_training=True, weight_decay=0.0001, batch_norm_decay=0.997, batch_norm_epsilon=1e-5, batch_norm_scale=True, ...
python
def image_embedding(images, model_fn=resnet_v1_152, trainable=True, is_training=True, weight_decay=0.0001, batch_norm_decay=0.997, batch_norm_epsilon=1e-5, batch_norm_scale=True, ...
[ "def", "image_embedding", "(", "images", ",", "model_fn", "=", "resnet_v1_152", ",", "trainable", "=", "True", ",", "is_training", "=", "True", ",", "weight_decay", "=", "0.0001", ",", "batch_norm_decay", "=", "0.997", ",", "batch_norm_epsilon", "=", "1e-5", "...
Extract image features from pretrained resnet model.
[ "Extract", "image", "features", "from", "pretrained", "resnet", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/vqa_layers.py#L48-L99
train
tensorflow/tensor2tensor
tensor2tensor/layers/vqa_layers.py
multihead_attention
def multihead_attention(query_antecedent, memory_antecedent, bias, total_key_depth, total_value_depth, output_depth, num_heads, dropout_rate, ...
python
def multihead_attention(query_antecedent, memory_antecedent, bias, total_key_depth, total_value_depth, output_depth, num_heads, dropout_rate, ...
[ "def", "multihead_attention", "(", "query_antecedent", ",", "memory_antecedent", ",", "bias", ",", "total_key_depth", ",", "total_value_depth", ",", "output_depth", ",", "num_heads", ",", "dropout_rate", ",", "shared_rel", "=", "False", ",", "max_relative_position", "...
Multihead scaled-dot-product attention with input/output transformations. Args: query_antecedent: a Tensor with shape [batch, length_q, channels] memory_antecedent: a Tensor with shape [batch, length_m, channels] or None bias: bias Tensor (see attention_bias()) total_key_depth: an integer total_v...
[ "Multihead", "scaled", "-", "dot", "-", "product", "attention", "with", "input", "/", "output", "transformations", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/vqa_layers.py#L102-L347
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/audio.py
_get_timit
def _get_timit(directory): """Extract TIMIT datasets to directory unless directory/timit exists.""" if os.path.exists(os.path.join(directory, "timit")): return assert FLAGS.timit_paths for path in FLAGS.timit_paths.split(","): with tf.gfile.GFile(path) as f: with tarfile.open(fileobj=f, mode="r:g...
python
def _get_timit(directory): """Extract TIMIT datasets to directory unless directory/timit exists.""" if os.path.exists(os.path.join(directory, "timit")): return assert FLAGS.timit_paths for path in FLAGS.timit_paths.split(","): with tf.gfile.GFile(path) as f: with tarfile.open(fileobj=f, mode="r:g...
[ "def", "_get_timit", "(", "directory", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "\"timit\"", ")", ")", ":", "return", "assert", "FLAGS", ".", "timit_paths", "for", "path", "in", "FL...
Extract TIMIT datasets to directory unless directory/timit exists.
[ "Extract", "TIMIT", "datasets", "to", "directory", "unless", "directory", "/", "timit", "exists", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/audio.py#L44-L53
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/audio.py
_collect_data
def _collect_data(directory, input_ext, target_ext): """Traverses directory collecting input and target files.""" # Directory from string to tuple pair of strings # key: the filepath to a datafile including the datafile's basename. Example, # if the datafile was "/path/to/datafile.wav" then the key would be ...
python
def _collect_data(directory, input_ext, target_ext): """Traverses directory collecting input and target files.""" # Directory from string to tuple pair of strings # key: the filepath to a datafile including the datafile's basename. Example, # if the datafile was "/path/to/datafile.wav" then the key would be ...
[ "def", "_collect_data", "(", "directory", ",", "input_ext", ",", "target_ext", ")", ":", "# Directory from string to tuple pair of strings", "# key: the filepath to a datafile including the datafile's basename. Example,", "# if the datafile was \"/path/to/datafile.wav\" then the key would ...
Traverses directory collecting input and target files.
[ "Traverses", "directory", "collecting", "input", "and", "target", "files", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/audio.py#L56-L74
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/audio.py
timit_generator
def timit_generator(data_dir, tmp_dir, training, how_many, start_from=0, eos_list=None, vocab_filename=None, vocab_size=0): """Data generator for TIMIT transcription problem. ...
python
def timit_generator(data_dir, tmp_dir, training, how_many, start_from=0, eos_list=None, vocab_filename=None, vocab_size=0): """Data generator for TIMIT transcription problem. ...
[ "def", "timit_generator", "(", "data_dir", ",", "tmp_dir", ",", "training", ",", "how_many", ",", "start_from", "=", "0", ",", "eos_list", "=", "None", ",", "vocab_filename", "=", "None", ",", "vocab_size", "=", "0", ")", ":", "del", "data_dir", "eos_list"...
Data generator for TIMIT transcription problem. Args: data_dir: path to the data directory. tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. how_many: how many inputs and labels to generate. start_from: from which input to s...
[ "Data", "generator", "for", "TIMIT", "transcription", "problem", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/audio.py#L98-L162
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikitext103.py
_build_vocab
def _build_vocab(filename, vocab_dir, vocab_name): """Reads a file to build a vocabulary. Args: filename: file to read list of words from. vocab_dir: directory where to save the vocabulary. vocab_name: vocab file name. Returns: text encoder. """ vocab_path = os.path.join(vocab_dir, vocab_nam...
python
def _build_vocab(filename, vocab_dir, vocab_name): """Reads a file to build a vocabulary. Args: filename: file to read list of words from. vocab_dir: directory where to save the vocabulary. vocab_name: vocab file name. Returns: text encoder. """ vocab_path = os.path.join(vocab_dir, vocab_nam...
[ "def", "_build_vocab", "(", "filename", ",", "vocab_dir", ",", "vocab_name", ")", ":", "vocab_path", "=", "os", ".", "path", ".", "join", "(", "vocab_dir", ",", "vocab_name", ")", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "vocab_path", ")", ...
Reads a file to build a vocabulary. Args: filename: file to read list of words from. vocab_dir: directory where to save the vocabulary. vocab_name: vocab file name. Returns: text encoder.
[ "Reads", "a", "file", "to", "build", "a", "vocabulary", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikitext103.py#L37-L59
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikitext103.py
_maybe_download_corpus
def _maybe_download_corpus(tmp_dir, vocab_type): """Download and unpack the corpus. Args: tmp_dir: directory containing dataset. vocab_type: which vocabulary are we using. Returns: The list of names of files. """ if vocab_type == text_problems.VocabType.CHARACTER: dataset_url = ("https://s3...
python
def _maybe_download_corpus(tmp_dir, vocab_type): """Download and unpack the corpus. Args: tmp_dir: directory containing dataset. vocab_type: which vocabulary are we using. Returns: The list of names of files. """ if vocab_type == text_problems.VocabType.CHARACTER: dataset_url = ("https://s3...
[ "def", "_maybe_download_corpus", "(", "tmp_dir", ",", "vocab_type", ")", ":", "if", "vocab_type", "==", "text_problems", ".", "VocabType", ".", "CHARACTER", ":", "dataset_url", "=", "(", "\"https://s3.amazonaws.com/research.metamind.io/wikitext\"", "\"/wikitext-103-raw-v1.z...
Download and unpack the corpus. Args: tmp_dir: directory containing dataset. vocab_type: which vocabulary are we using. Returns: The list of names of files.
[ "Download", "and", "unpack", "the", "corpus", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikitext103.py#L62-L104
train
tensorflow/tensor2tensor
tensor2tensor/models/research/aligned.py
get_batch_coordinate
def get_batch_coordinate(x): """Return a flat int32 tensor of shape [1, batch_size*length, 1].""" # Compute the batch coordinate before flattening all batches batch_coordinate = tf.expand_dims( common_attention.coordinate_tensor( common_layers.shape_list(x)[:-1], axis=0), axis=-1) return b...
python
def get_batch_coordinate(x): """Return a flat int32 tensor of shape [1, batch_size*length, 1].""" # Compute the batch coordinate before flattening all batches batch_coordinate = tf.expand_dims( common_attention.coordinate_tensor( common_layers.shape_list(x)[:-1], axis=0), axis=-1) return b...
[ "def", "get_batch_coordinate", "(", "x", ")", ":", "# Compute the batch coordinate before flattening all batches", "batch_coordinate", "=", "tf", ".", "expand_dims", "(", "common_attention", ".", "coordinate_tensor", "(", "common_layers", ".", "shape_list", "(", "x", ")",...
Return a flat int32 tensor of shape [1, batch_size*length, 1].
[ "Return", "a", "flat", "int32", "tensor", "of", "shape", "[", "1", "batch_size", "*", "length", "1", "]", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/aligned.py#L228-L235
train
tensorflow/tensor2tensor
tensor2tensor/models/research/aligned.py
aligned_base
def aligned_base(): """Set of hyperparameters. languagemodel_wiki_scramble1k50, 1gpu, 7k steps (10min): log(ppl)_eval = 2.60 12.0 steps/sec on P100 8gpu (8x batch), 7k steps: log(ppl)_eval = 2.00 Returns: a hparams object """ hparams = common_hparams.basic_params1() hparams.hidden_size = 512 hpa...
python
def aligned_base(): """Set of hyperparameters. languagemodel_wiki_scramble1k50, 1gpu, 7k steps (10min): log(ppl)_eval = 2.60 12.0 steps/sec on P100 8gpu (8x batch), 7k steps: log(ppl)_eval = 2.00 Returns: a hparams object """ hparams = common_hparams.basic_params1() hparams.hidden_size = 512 hpa...
[ "def", "aligned_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "batch_size", "=", "5000", "hparams", ".", "max_length", "=", "0", "hparams", ".", "min_length_...
Set of hyperparameters. languagemodel_wiki_scramble1k50, 1gpu, 7k steps (10min): log(ppl)_eval = 2.60 12.0 steps/sec on P100 8gpu (8x batch), 7k steps: log(ppl)_eval = 2.00 Returns: a hparams object
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/aligned.py#L239-L305
train
tensorflow/tensor2tensor
tensor2tensor/models/research/aligned.py
aligned_8k_grouped
def aligned_8k_grouped(): """version for languagemodel_wiki_scramble8k50. languagemodel_wiki_scramble1k50, 1gpu, 7k steps: log(ppl)_eval = 2.92 3.3 steps/sec on P100 8gpu (8x batch), 7k steps: log(ppl)_eval = 2.15 Returns: a hparams object """ hparams = aligned_grouped() hparams.batch_size = 8192 ...
python
def aligned_8k_grouped(): """version for languagemodel_wiki_scramble8k50. languagemodel_wiki_scramble1k50, 1gpu, 7k steps: log(ppl)_eval = 2.92 3.3 steps/sec on P100 8gpu (8x batch), 7k steps: log(ppl)_eval = 2.15 Returns: a hparams object """ hparams = aligned_grouped() hparams.batch_size = 8192 ...
[ "def", "aligned_8k_grouped", "(", ")", ":", "hparams", "=", "aligned_grouped", "(", ")", "hparams", ".", "batch_size", "=", "8192", "# hparams.attention_image_summary = False", "hparams", ".", "num_groups", "=", "16", "hparams", ".", "multiplicative_overhead", "=", ...
version for languagemodel_wiki_scramble8k50. languagemodel_wiki_scramble1k50, 1gpu, 7k steps: log(ppl)_eval = 2.92 3.3 steps/sec on P100 8gpu (8x batch), 7k steps: log(ppl)_eval = 2.15 Returns: a hparams object
[ "version", "for", "languagemodel_wiki_scramble8k50", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/aligned.py#L512-L527
train
tensorflow/tensor2tensor
tensor2tensor/utils/beam_search.py
_merge_beam_dim
def _merge_beam_dim(tensor): """Reshapes first two dimensions in to single dimension. Args: tensor: Tensor to reshape of shape [A, B, ...] Returns: Reshaped tensor of shape [A*B, ...] """ shape = common_layers.shape_list(tensor) shape[0] *= shape[1] # batch -> batch * beam_size shape.pop(1) # ...
python
def _merge_beam_dim(tensor): """Reshapes first two dimensions in to single dimension. Args: tensor: Tensor to reshape of shape [A, B, ...] Returns: Reshaped tensor of shape [A*B, ...] """ shape = common_layers.shape_list(tensor) shape[0] *= shape[1] # batch -> batch * beam_size shape.pop(1) # ...
[ "def", "_merge_beam_dim", "(", "tensor", ")", ":", "shape", "=", "common_layers", ".", "shape_list", "(", "tensor", ")", "shape", "[", "0", "]", "*=", "shape", "[", "1", "]", "# batch -> batch * beam_size", "shape", ".", "pop", "(", "1", ")", "# Remove bea...
Reshapes first two dimensions in to single dimension. Args: tensor: Tensor to reshape of shape [A, B, ...] Returns: Reshaped tensor of shape [A*B, ...]
[ "Reshapes", "first", "two", "dimensions", "in", "to", "single", "dimension", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L37-L49
train
tensorflow/tensor2tensor
tensor2tensor/utils/beam_search.py
_unmerge_beam_dim
def _unmerge_beam_dim(tensor, batch_size, beam_size): """Reshapes first dimension back to [batch_size, beam_size]. Args: tensor: Tensor to reshape of shape [batch_size*beam_size, ...] batch_size: Tensor, original batch size. beam_size: int, original beam size. Returns: Reshaped tensor of shape [...
python
def _unmerge_beam_dim(tensor, batch_size, beam_size): """Reshapes first dimension back to [batch_size, beam_size]. Args: tensor: Tensor to reshape of shape [batch_size*beam_size, ...] batch_size: Tensor, original batch size. beam_size: int, original beam size. Returns: Reshaped tensor of shape [...
[ "def", "_unmerge_beam_dim", "(", "tensor", ",", "batch_size", ",", "beam_size", ")", ":", "shape", "=", "common_layers", ".", "shape_list", "(", "tensor", ")", "new_shape", "=", "[", "batch_size", "]", "+", "[", "beam_size", "]", "+", "shape", "[", "1", ...
Reshapes first dimension back to [batch_size, beam_size]. Args: tensor: Tensor to reshape of shape [batch_size*beam_size, ...] batch_size: Tensor, original batch size. beam_size: int, original beam size. Returns: Reshaped tensor of shape [batch_size, beam_size, ...]
[ "Reshapes", "first", "dimension", "back", "to", "[", "batch_size", "beam_size", "]", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L52-L65
train
tensorflow/tensor2tensor
tensor2tensor/utils/beam_search.py
_expand_to_beam_size
def _expand_to_beam_size(tensor, beam_size): """Tiles a given tensor by beam_size. Args: tensor: tensor to tile [batch_size, ...] beam_size: How much to tile the tensor by. Returns: Tiled tensor [batch_size, beam_size, ...] """ tensor = tf.expand_dims(tensor, axis=1) tile_dims = [1] * tensor.s...
python
def _expand_to_beam_size(tensor, beam_size): """Tiles a given tensor by beam_size. Args: tensor: tensor to tile [batch_size, ...] beam_size: How much to tile the tensor by. Returns: Tiled tensor [batch_size, beam_size, ...] """ tensor = tf.expand_dims(tensor, axis=1) tile_dims = [1] * tensor.s...
[ "def", "_expand_to_beam_size", "(", "tensor", ",", "beam_size", ")", ":", "tensor", "=", "tf", ".", "expand_dims", "(", "tensor", ",", "axis", "=", "1", ")", "tile_dims", "=", "[", "1", "]", "*", "tensor", ".", "shape", ".", "ndims", "tile_dims", "[", ...
Tiles a given tensor by beam_size. Args: tensor: tensor to tile [batch_size, ...] beam_size: How much to tile the tensor by. Returns: Tiled tensor [batch_size, beam_size, ...]
[ "Tiles", "a", "given", "tensor", "by", "beam_size", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L68-L82
train
tensorflow/tensor2tensor
tensor2tensor/utils/beam_search.py
get_state_shape_invariants
def get_state_shape_invariants(tensor): """Returns the shape of the tensor but sets middle dims to None.""" shape = tensor.shape.as_list() for i in range(1, len(shape) - 1): shape[i] = None return tf.TensorShape(shape)
python
def get_state_shape_invariants(tensor): """Returns the shape of the tensor but sets middle dims to None.""" shape = tensor.shape.as_list() for i in range(1, len(shape) - 1): shape[i] = None return tf.TensorShape(shape)
[ "def", "get_state_shape_invariants", "(", "tensor", ")", ":", "shape", "=", "tensor", ".", "shape", ".", "as_list", "(", ")", "for", "i", "in", "range", "(", "1", ",", "len", "(", "shape", ")", "-", "1", ")", ":", "shape", "[", "i", "]", "=", "No...
Returns the shape of the tensor but sets middle dims to None.
[ "Returns", "the", "shape", "of", "the", "tensor", "but", "sets", "middle", "dims", "to", "None", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L85-L90
train
tensorflow/tensor2tensor
tensor2tensor/utils/beam_search.py
compute_batch_indices
def compute_batch_indices(batch_size, beam_size): """Computes the i'th coordinate that contains the batch index for gathers. Batch pos is a tensor like [[0,0,0,0,],[1,1,1,1],..]. It says which batch the beam item is in. This will create the i of the i,j coordinate needed for the gather. Args: batch_size...
python
def compute_batch_indices(batch_size, beam_size): """Computes the i'th coordinate that contains the batch index for gathers. Batch pos is a tensor like [[0,0,0,0,],[1,1,1,1],..]. It says which batch the beam item is in. This will create the i of the i,j coordinate needed for the gather. Args: batch_size...
[ "def", "compute_batch_indices", "(", "batch_size", ",", "beam_size", ")", ":", "batch_pos", "=", "tf", ".", "range", "(", "batch_size", "*", "beam_size", ")", "//", "beam_size", "batch_pos", "=", "tf", ".", "reshape", "(", "batch_pos", ",", "[", "batch_size"...
Computes the i'th coordinate that contains the batch index for gathers. Batch pos is a tensor like [[0,0,0,0,],[1,1,1,1],..]. It says which batch the beam item is in. This will create the i of the i,j coordinate needed for the gather. Args: batch_size: Batch size beam_size: Size of the beam. Returns...
[ "Computes", "the", "i", "th", "coordinate", "that", "contains", "the", "batch", "index", "for", "gathers", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L93-L108
train
tensorflow/tensor2tensor
tensor2tensor/utils/beam_search.py
fast_tpu_gather
def fast_tpu_gather(params, indices, name=None): """Fast gather implementation for models running on TPU. This function use one_hot and batch matmul to do gather, which is faster than gather_nd on TPU. For params that have dtype of int32 (sequences to gather from), batch_gather is used to keep accuracy. Arg...
python
def fast_tpu_gather(params, indices, name=None): """Fast gather implementation for models running on TPU. This function use one_hot and batch matmul to do gather, which is faster than gather_nd on TPU. For params that have dtype of int32 (sequences to gather from), batch_gather is used to keep accuracy. Arg...
[ "def", "fast_tpu_gather", "(", "params", ",", "indices", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ")", ":", "dtype", "=", "params", ".", "dtype", "def", "_gather", "(", "params", ",", "indices", ")", ":", "\"\...
Fast gather implementation for models running on TPU. This function use one_hot and batch matmul to do gather, which is faster than gather_nd on TPU. For params that have dtype of int32 (sequences to gather from), batch_gather is used to keep accuracy. Args: params: A tensor from which to gather values. ...
[ "Fast", "gather", "implementation", "for", "models", "running", "on", "TPU", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L111-L165
train
tensorflow/tensor2tensor
tensor2tensor/utils/beam_search.py
_create_make_unique
def _create_make_unique(inputs): """Replaces the lower bits of each element with iota. The iota is used to derive the index, and also serves the purpose to make each element unique to break ties. Args: inputs: A tensor with rank of 2 and dtype of tf.float32. [batch_size, original_size]. Returns: ...
python
def _create_make_unique(inputs): """Replaces the lower bits of each element with iota. The iota is used to derive the index, and also serves the purpose to make each element unique to break ties. Args: inputs: A tensor with rank of 2 and dtype of tf.float32. [batch_size, original_size]. Returns: ...
[ "def", "_create_make_unique", "(", "inputs", ")", ":", "if", "inputs", ".", "shape", ".", "ndims", "!=", "2", ":", "raise", "ValueError", "(", "\"Input of top_k_with_unique must be rank-2 \"", "\"but got: %s\"", "%", "inputs", ".", "shape", ")", "height", "=", "...
Replaces the lower bits of each element with iota. The iota is used to derive the index, and also serves the purpose to make each element unique to break ties. Args: inputs: A tensor with rank of 2 and dtype of tf.float32. [batch_size, original_size]. Returns: A tensor after element wise transf...
[ "Replaces", "the", "lower", "bits", "of", "each", "element", "with", "iota", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L168-L229
train
tensorflow/tensor2tensor
tensor2tensor/utils/beam_search.py
_create_topk_unique
def _create_topk_unique(inputs, k): """Creates the top k values in sorted order with indices. Args: inputs: A tensor with rank of 2. [batch_size, original_size]. k: An integer, number of top elements to select. Returns: topk_r2: A tensor, the k largest elements. [batch_size, k]. topk_indices_r2:...
python
def _create_topk_unique(inputs, k): """Creates the top k values in sorted order with indices. Args: inputs: A tensor with rank of 2. [batch_size, original_size]. k: An integer, number of top elements to select. Returns: topk_r2: A tensor, the k largest elements. [batch_size, k]. topk_indices_r2:...
[ "def", "_create_topk_unique", "(", "inputs", ",", "k", ")", ":", "height", "=", "inputs", ".", "shape", "[", "0", "]", "width", "=", "inputs", ".", "shape", "[", "1", "]", "neg_inf_r0", "=", "tf", ".", "constant", "(", "-", "np", ".", "inf", ",", ...
Creates the top k values in sorted order with indices. Args: inputs: A tensor with rank of 2. [batch_size, original_size]. k: An integer, number of top elements to select. Returns: topk_r2: A tensor, the k largest elements. [batch_size, k]. topk_indices_r2: A tensor, indices of the top k values. [...
[ "Creates", "the", "top", "k", "values", "in", "sorted", "order", "with", "indices", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L232-L270
train