partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
categorical_case
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...
tensor2tensor/data_generators/multi_problem_v2.py
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): """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 ...
[ "Returns", "the", "outputs", "of", "fns", "[", "i", "]", "with", "probability", "pmf", "[", "i", "]", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L256-L271
[ "def", "categorical_case", "(", "pmf", ",", "fns", ",", "rand", "=", "None", ")", ":", "rand", "=", "tf", ".", "random_uniform", "(", "[", "]", ")", "if", "rand", "is", "None", "else", "rand", "cmf", "=", "tf", ".", "pad", "(", "tf", ".", "cumsum...
272500b6efe353aeb638d2745ed56e519462ca31
train
linear_interpolation
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. ...
tensor2tensor/data_generators/multi_problem_v2.py
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): """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 [...
[ "Multi", "-", "dimensional", "linear", "interpolation", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L274-L294
[ "def", "linear_interpolation", "(", "x", ",", "xp", ",", "fp", ",", "*", "*", "kwargs", ")", ":", "yp", "=", "fp", ".", "reshape", "(", "[", "fp", ".", "shape", "[", "0", "]", ",", "-", "1", "]", ")", ".", "transpose", "(", ")", "y", "=", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
step_interpolation
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...
tensor2tensor/data_generators/multi_problem_v2.py
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): """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...
[ "Multi", "-", "dimensional", "step", "interpolation", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L297-L325
[ "def", "step_interpolation", "(", "x", ",", "xp", ",", "fp", ",", "*", "*", "kwargs", ")", ":", "del", "kwargs", "# Unused.", "xp", "=", "np", ".", "expand_dims", "(", "xp", ",", "-", "1", ")", "lower", ",", "upper", "=", "xp", "[", ":", "-", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
epoch_rates_to_pmf
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...
tensor2tensor/data_generators/multi_problem_v2.py
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): """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...
[ "Create", "a", "probability", "-", "mass", "-", "function", "based", "on", "relative", "epoch", "rates", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L353-L375
[ "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", "."...
272500b6efe353aeb638d2745ed56e519462ca31
train
encode_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 array_like of shape [N, M] where pm...
tensor2tensor/data_generators/multi_problem_v2.py
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): """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...
[ "Encodes", "a", "schedule", "tuple", "into", "a", "string", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L378-L394
[ "def", "encode_schedule", "(", "schedule", ")", ":", "interpolation", ",", "steps", ",", "pmfs", "=", "schedule", "return", "interpolation", "+", "' '", "+", "' '", ".", "join", "(", "'@'", "+", "str", "(", "s", ")", "+", "' '", "+", "' '", ".", "joi...
272500b6efe353aeb638d2745ed56e519462ca31
train
decode_schedule
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.
tensor2tensor/data_generators/multi_problem_v2.py
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): """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( ...
[ "Decodes", "a", "string", "into", "a", "schedule", "tuple", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L397-L410
[ "def", "decode_schedule", "(", "string", ")", ":", "splits", "=", "string", ".", "split", "(", ")", "steps", "=", "[", "int", "(", "x", "[", "1", ":", "]", ")", "for", "x", "in", "splits", "[", "1", ":", "]", "if", "x", "[", "0", "]", "==", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
tuplize
Recursively converts iterables into tuples. Args: nested: A nested structure of items and iterables. Returns: A nested structure of items and tuples.
tensor2tensor/data_generators/multi_problem_v2.py
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): """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...
[ "Recursively", "converts", "iterables", "into", "tuples", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L413-L427
[ "def", "tuplize", "(", "nested", ")", ":", "if", "isinstance", "(", "nested", ",", "str", ")", ":", "return", "nested", "try", ":", "return", "tuple", "(", "map", "(", "tuplize", ",", "nested", ")", ")", "except", "TypeError", ":", "return", "nested" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
MultiProblemV2.filepattern
Returns a list of filepatterns, one for each problem.
tensor2tensor/data_generators/multi_problem_v2.py
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): """Returns a list of filepatterns, one for each problem.""" return [p.filepattern(*args, **kwargs) for p in self.problems]
[ "Returns", "a", "list", "of", "filepatterns", "one", "for", "each", "problem", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L82-L84
[ "def", "filepattern", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "[", "p", ".", "filepattern", "(", "*", "args", ",", "*", "*", "kwargs", ")", "for", "p", "in", "self", ".", "problems", "]" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
MultiProblemV2.generate_data
Generates data for each problem.
tensor2tensor/data_generators/multi_problem_v2.py
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): """Generates data for each problem.""" for p in self.problems: p.generate_data(*args, **kwargs)
[ "Generates", "data", "for", "each", "problem", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L86-L89
[ "def", "generate_data", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "p", "in", "self", ".", "problems", ":", "p", ".", "generate_data", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
MultiProblemV2.dataset
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...
tensor2tensor/data_generators/multi_problem_v2.py
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): """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...
[ "Returns", "a", "dataset", "containing", "examples", "from", "multiple", "problems", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L101-L133
[ "def", "dataset", "(", "self", ",", "mode", ",", "hparams", "=", "None", ",", "global_step", "=", "None", ",", "*", "*", "kwargs", ")", ":", "datasets", "=", "[", "p", ".", "dataset", "(", "mode", ",", "*", "*", "kwargs", ")", "for", "p", "in", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
MultiText2TextProblem.normalize_example
Assumes that example contains both inputs and targets.
tensor2tensor/data_generators/multi_problem_v2.py
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): """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...
[ "Assumes", "that", "example", "contains", "both", "inputs", "and", "targets", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L139-L181
[ "def", "normalize_example", "(", "self", ",", "example", ",", "hparams", ")", ":", "length", "=", "self", ".", "max_length", "(", "hparams", ")", "def", "_to_constant_shape", "(", "tensor", ")", ":", "tensor", "=", "tensor", "[", ":", "length", "]", "ten...
272500b6efe353aeb638d2745ed56e519462ca31
train
MultiText2TextProblem.generate_data_with_shared_vocab
Generates TF-Records for problems using a global vocabulary file.
tensor2tensor/data_generators/multi_problem_v2.py
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): """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...
[ "Generates", "TF", "-", "Records", "for", "problems", "using", "a", "global", "vocabulary", "file", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L183-L197
[ "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", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
lengths_to_area_mask
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]
tensor2tensor/layers/area_attention.py
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): """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...
[ "Generates", "a", "non", "-", "padding", "mask", "for", "areas", "based", "on", "lengths", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L27-L44
[ "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", ","...
272500b6efe353aeb638d2745ed56e519462ca31
train
_pool_one_shape
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...
tensor2tensor/layers/area_attention.py
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): """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. ...
[ "Pools", "for", "an", "area", "in", "features_2d", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L47-L75
[ "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...
272500b6efe353aeb638d2745ed56e519462ca31
train
basic_pool
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 ...
tensor2tensor/layers/area_attention.py
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): """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. ...
[ "Pools", "for", "each", "area", "based", "on", "a", "given", "pooling", "function", "(", "fn", ")", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L78-L128
[ "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...
272500b6efe353aeb638d2745ed56e519462ca31
train
_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...
tensor2tensor/layers/area_attention.py
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): """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...
[ "Computes", "area", "sums", "for", "features", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L131-L196
[ "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\"...
272500b6efe353aeb638d2745ed56e519462ca31
train
compute_area_features
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...
tensor2tensor/layers/area_attention.py
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): """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...
[ "Computes", "features", "for", "each", "area", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L199-L231
[ "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", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
compute_area_key
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 ...
tensor2tensor/layers/area_attention.py
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): """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_...
[ "Computes", "the", "key", "for", "each", "area", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L234-L302
[ "def", "compute_area_key", "(", "features", ",", "max_area_width", ",", "max_area_height", "=", "1", ",", "height", "=", "1", ",", "mode", "=", "\"mean\"", ",", "training", "=", "True", ",", "name", "=", "None", ")", ":", "tf", ".", "logging", ".", "in...
272500b6efe353aeb638d2745ed56e519462ca31
train
dot_product_area_attention
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...
tensor2tensor/layers/area_attention.py
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...
[ "Dot", "-", "product", "area", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L305-L433
[ "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", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
setup_directories
Setup directories.
tensor2tensor/rl/trainer_model_based.py
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): """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....
[ "Setup", "directories", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L68-L82
[ "def", "setup_directories", "(", "base_dir", ",", "subdirs", ")", ":", "base_dir", "=", "os", ".", "path", ".", "expanduser", "(", "base_dir", ")", "tf", ".", "gfile", ".", "MakeDirs", "(", "base_dir", ")", "all_dirs", "=", "{", "}", "for", "subdir", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
make_relative_timing_fn
Make a function that logs the duration since it was made.
tensor2tensor/rl/trainer_model_based.py
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(): """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...
[ "Make", "a", "function", "that", "logs", "the", "duration", "since", "it", "was", "made", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L85-L96
[ "def", "make_relative_timing_fn", "(", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "def", "format_relative_time", "(", ")", ":", "time_delta", "=", "time", ".", "time", "(", ")", "-", "start_time", "return", "str", "(", "datetime", ".", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
train_supervised
Train supervised.
tensor2tensor/rl/trainer_model_based.py
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"): """Train supervised.""" if local_eval_frequency is None: local_eval_frequency = FLAGS.local_eval_frequency...
[ "Train", "supervised", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L125-L138
[ "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"...
272500b6efe353aeb638d2745ed56e519462ca31
train
train_agent
Train the PPO agent in the simulated environment.
tensor2tensor/rl/trainer_model_based.py
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): """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...
[ "Train", "the", "PPO", "agent", "in", "the", "simulated", "environment", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L141-L170
[ "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...
272500b6efe353aeb638d2745ed56e519462ca31
train
train_agent_real_env
Train the PPO agent in the real environment.
tensor2tensor/rl/trainer_model_based.py
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): """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 + "_" )...
[ "Train", "the", "PPO", "agent", "in", "the", "real", "environment", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L173-L196
[ "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...
272500b6efe353aeb638d2745ed56e519462ca31
train
train_world_model
Train the world model on problem_name.
tensor2tensor/rl/trainer_model_based.py
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 ): """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...
[ "Train", "the", "world", "model", "on", "problem_name", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L199-L228
[ "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",...
272500b6efe353aeb638d2745ed56e519462ca31
train
load_metrics
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.
tensor2tensor/rl/trainer_model_based.py
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): """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 = {...
[ "Loads", "metrics", "for", "this", "epoch", "if", "they", "have", "already", "been", "written", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L231-L250
[ "def", "load_metrics", "(", "event_dir", ",", "epoch", ")", ":", "metrics", "=", "{", "}", "for", "filename", "in", "tf", ".", "gfile", ".", "ListDirectory", "(", "event_dir", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "event_dir", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
training_loop
Run the main training loop.
tensor2tensor/rl/trainer_model_based.py
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): """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...
[ "Run", "the", "main", "training", "loop", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L253-L378
[ "def", "training_loop", "(", "hparams", ",", "output_dir", ",", "report_fn", "=", "None", ",", "report_metric", "=", "None", ")", ":", "if", "report_fn", ":", "assert", "report_metric", "is", "not", "None", "# Directories", "subdirectories", "=", "[", "\"data\...
272500b6efe353aeb638d2745ed56e519462ca31
train
conv_layer
Single conv layer with relu, optional pooling, and dropout.
tensor2tensor/models/research/gene_expression.py
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"): """Single conv layer with relu, optional pooling, and dropout.""" with tf.variable_scope(name): ...
[ "Single", "conv", "layer", "with", "relu", "optional", "pooling", "and", "dropout", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/gene_expression.py#L92-L114
[ "def", "conv_layer", "(", "x", ",", "hidden_size", ",", "kernel_size", ",", "stride", ",", "pooling_window", ",", "dropout_rate", ",", "dilation_rate", ",", "name", "=", "\"conv\"", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "out...
272500b6efe353aeb638d2745ed56e519462ca31
train
gene_expression_conv_base
Hparams for GeneExpressionConv model.
tensor2tensor/models/research/gene_expression.py
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 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...
[ "Hparams", "for", "GeneExpressionConv", "model", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/gene_expression.py#L128-L149
[ "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...
272500b6efe353aeb638d2745ed56e519462ca31
train
compress_self_attention_layer
Attend function.
tensor2tensor/layers/latent_layers.py
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): """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, ...
[ "Attend", "function", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L35-L48
[ "def", "compress_self_attention_layer", "(", "x", ",", "hparams", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"compress_self_attention\"", ")", ":", "x", ",", "xshape", ",", "_", "=", "c...
272500b6efe353aeb638d2745ed56e519462ca31
train
compute_nats_and_bits_per_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 ...
tensor2tensor/layers/latent_layers.py
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): """Computes negative ELBO, which is an upper bound on the negative likelihood. Args: data_dim: int-like indicatin...
[ "Computes", "negative", "ELBO", "which", "is", "an", "upper", "bound", "on", "the", "negative", "likelihood", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L51-L77
[ "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", "=", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
multinomial_sample
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...
tensor2tensor/layers/latent_layers.py
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): """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. ...
[ "Multinomial", "sampling", "from", "a", "n", "-", "dimensional", "tensor", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L80-L99
[ "def", "multinomial_sample", "(", "x", ",", "vocab_size", "=", "None", ",", "sampling_method", "=", "\"random\"", ",", "temperature", "=", "1.0", ")", ":", "vocab_size", "=", "vocab_size", "or", "common_layers", ".", "shape_list", "(", "x", ")", "[", "-", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
ae_latent_softmax
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...
tensor2tensor/layers/latent_layers.py
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): """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: ...
[ "Latent", "prediction", "and", "loss", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L102-L130
[ "def", "ae_latent_softmax", "(", "latents_pred", ",", "latents_discrete_hot", ",", "vocab_size", ",", "hparams", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"latent_logits\"", ")", ":", "latents_logits", "=", "tf", ".", "layers", ".", "dense", "(", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
ae_latent_sample_beam
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 ...
tensor2tensor/layers/latent_layers.py
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): """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 *...
[ "Samples", "from", "the", "latent", "space", "in", "the", "autoencoder", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L133-L182
[ "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"...
272500b6efe353aeb638d2745ed56e519462ca31
train
residual_block_layer
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...
tensor2tensor/layers/latent_layers.py
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): """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_...
[ "Residual", "block", "over", "inputs", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L185-L219
[ "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", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
compress_encoder
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...
tensor2tensor/layers/latent_layers.py
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): """Encoder that compresses 2-D inputs by 2**num_compress_steps. Args: inputs: Tensor of shape [batch, height, width, channels]. hparams: ...
[ "Encoder", "that", "compresses", "2", "-", "D", "inputs", "by", "2", "**", "num_compress_steps", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L222-L270
[ "def", "compress_encoder", "(", "inputs", ",", "hparams", ",", "strides", "=", "(", "2", ",", "2", ")", ",", "kernel_size", "=", "(", "3", ",", "3", ")", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
compress_encoder_2d
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...
tensor2tensor/layers/latent_layers.py
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): """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 ...
[ "Encoder", "that", "compresses", "2", "-", "D", "inputs", "by", "2", "**", "num_compress_steps", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L273-L291
[ "def", "compress_encoder_2d", "(", "x", ",", "hparams", ",", "name", "=", "None", ")", ":", "return", "compress_encoder", "(", "x", ",", "hparams", ",", "strides", "=", "(", "2", ",", "2", ")", ",", "kernel_size", "=", "(", "hparams", ".", "kernel_size...
272500b6efe353aeb638d2745ed56e519462ca31
train
compress_encoder_1d
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...
tensor2tensor/layers/latent_layers.py
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): """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...
[ "Encoder", "that", "compresses", "1", "-", "D", "inputs", "by", "2", "**", "num_compress_steps", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L294-L312
[ "def", "compress_encoder_1d", "(", "x", ",", "hparams", ",", "name", "=", "None", ")", ":", "x", "=", "tf", ".", "expand_dims", "(", "x", ",", "axis", "=", "2", ")", "return", "compress_encoder", "(", "x", ",", "hparams", ",", "strides", "=", "(", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
decompress_decoder
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: ...
tensor2tensor/layers/latent_layers.py
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): """Decoder that decompresses 2-D inputs by 2**num_compress_steps. Args: inputs: Tensor of shape [batch, compress_height, compress_width,...
[ "Decoder", "that", "decompresses", "2", "-", "D", "inputs", "by", "2", "**", "num_compress_steps", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L315-L352
[ "def", "decompress_decoder", "(", "inputs", ",", "hparams", ",", "strides", "=", "(", "2", ",", "2", ")", ",", "kernel", "=", "(", "3", ",", "3", ")", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "def...
272500b6efe353aeb638d2745ed56e519462ca31
train
decompress_decoder_2d
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].
tensor2tensor/layers/latent_layers.py
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): """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...
[ "Decoder", "that", "decompresses", "2", "-", "D", "inputs", "by", "2", "**", "num_compress_steps", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L355-L369
[ "def", "decompress_decoder_2d", "(", "x", ",", "hparams", ",", "name", "=", "None", ")", ":", "return", "decompress_decoder", "(", "x", ",", "hparams", ",", "strides", "=", "(", "2", ",", "2", ")", ",", "kernel", "=", "(", "hparams", ".", "kernel_size"...
272500b6efe353aeb638d2745ed56e519462ca31
train
decompress_decoder_1d
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].
tensor2tensor/layers/latent_layers.py
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): """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", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L372-L388
[ "def", "decompress_decoder_1d", "(", "x", ",", "hparams", ",", "name", "=", "None", ")", ":", "x", "=", "tf", ".", "expand_dims", "(", "x", ",", "axis", "=", "2", ")", "output", "=", "decompress_decoder", "(", "x", ",", "hparams", ",", "strides", "="...
272500b6efe353aeb638d2745ed56e519462ca31
train
transformer_text_encoder
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...
tensor2tensor/layers/latent_layers.py
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): """Transformer text encoder over inputs with unmasked full attention. Args: inputs: Tensor of shape [batch, length, 1, hparams.hidden_size]. target_...
[ "Transformer", "text", "encoder", "over", "inputs", "with", "unmasked", "full", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L391-L419
[ "def", "transformer_text_encoder", "(", "inputs", ",", "target_space", ",", "hparams", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"transformer_text_encoder\"", ")", ":", "inputs", "=", "com...
272500b6efe353aeb638d2745ed56e519462ca31
train
transformer_image_decoder
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...
tensor2tensor/layers/latent_layers.py
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): """Transformer image decoder over targets with local attention. Args: targets: Tensor of shape [...
[ "Transformer", "image", "decoder", "over", "targets", "with", "local", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L422-L462
[ "def", "transformer_image_decoder", "(", "targets", ",", "encoder_output", ",", "ed_attention_bias", ",", "hparams", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"transformer_dec\"", ")", ":", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
transformer_latent_decoder
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...
tensor2tensor/layers/latent_layers.py
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): """Transformer decoder over latents using latent_attention_type. Args: x: Tensor of shape [batch,...
[ "Transformer", "decoder", "over", "latents", "using", "latent_attention_type", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L465-L506
[ "def", "transformer_latent_decoder", "(", "x", ",", "encoder_output", ",", "ed_attention_bias", ",", "hparams", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"transformer_latent_dec\"", ")", ":"...
272500b6efe353aeb638d2745ed56e519462ca31
train
bottleneck_layer
Computes latents given inputs (typically, compressed targets).
tensor2tensor/layers/latent_layers.py
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"): """Computes latents given inputs (typically, compressed targets).""" [ latents_dense, latents_discrete, extra_loss, embed_fn, _, ] = hparams.bottleneck(inputs=inputs, ...
[ "Computes", "latents", "given", "inputs", "(", "typically", "compressed", "targets", ")", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L509-L526
[ "def", "bottleneck_layer", "(", "inputs", ",", "hparams", ",", "name", "=", "\"discrete_bottleneck\"", ")", ":", "[", "latents_dense", ",", "latents_discrete", ",", "extra_loss", ",", "embed_fn", ",", "_", ",", "]", "=", "hparams", ".", "bottleneck", "(", "i...
272500b6efe353aeb638d2745ed56e519462ca31
train
latent_prediction_model
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...
tensor2tensor/layers/latent_layers.py
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): """Transformer-based lat...
[ "Transformer", "-", "based", "latent", "prediction", "model", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L529-L573
[ "def", "latent_prediction_model", "(", "inputs", ",", "ed_attention_bias", ",", "latents_discrete", ",", "latents_dense", ",", "hparams", ",", "vocab_size", "=", "None", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",",...
272500b6efe353aeb638d2745ed56e519462ca31
train
transformer_autoencoder
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...
tensor2tensor/layers/latent_layers.py
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): """Auto-encoder using a Transformer decoder and a prior over latent sequences. ...
[ "Auto", "-", "encoder", "using", "a", "Transformer", "decoder", "and", "a", "prior", "over", "latent", "sequences", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L576-L700
[ "def", "transformer_autoencoder", "(", "inputs", ",", "targets", ",", "target_space", ",", "hparams", ",", "cache", "=", "None", ",", "predict_mask", "=", "1.0", ")", ":", "original_targets_shape", "=", "common_layers", ".", "shape_list", "(", "targets", ")", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
iaf_flow
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 ...
tensor2tensor/layers/latent_layers.py
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): """Performs a single IAF flow using scale and normalization transformations. Args: one_hot_assignments: Assignments Tensor with shape [num_samples, ...
[ "Performs", "a", "single", "IAF", "flow", "using", "scale", "and", "normalization", "transformations", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L703-L758
[ "def", "iaf_flow", "(", "one_hot_assignments", ",", "scale_weights", ",", "scale_bias", ",", "num_codes", ",", "summary", "=", "True", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ",", "default_name", "=", "\"iaf\"", ")...
272500b6efe353aeb638d2745ed56e519462ca31
train
_get_lsun
Downloads all lsun files to directory unless they are there.
tensor2tensor/data_generators/image_lsun.py
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): """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))
[ "Downloads", "all", "lsun", "files", "to", "directory", "unless", "they", "are", "there", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_lsun.py#L40-L44
[ "def", "_get_lsun", "(", "directory", ",", "category", ",", "split_name", ")", ":", "generator_utils", ".", "maybe_download", "(", "directory", ",", "_LSUN_DATA_FILENAME", "%", "(", "category", ",", "split_name", ")", ",", "_LSUN_URL", "%", "(", "category", ",...
272500b6efe353aeb638d2745ed56e519462ca31
train
_mixed_precision_is_enabled
Should be the same as in common_attention, avoiding import.
tensor2tensor/utils/optimize.py
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): """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
[ "Should", "be", "the", "same", "as", "in", "common_attention", "avoiding", "import", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L36-L40
[ "def", "_mixed_precision_is_enabled", "(", "hparams", ")", ":", "activation_dtype", "=", "hparams", ".", "activation_dtype", "weight_dtype", "=", "hparams", ".", "weight_dtype", "return", "activation_dtype", "==", "tf", ".", "float16", "and", "weight_dtype", "==", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
optimize
Minimize loss.
tensor2tensor/utils/optimize.py
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): """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...
[ "Minimize", "loss", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L43-L94
[ "def", "optimize", "(", "loss", ",", "learning_rate", ",", "hparams", ",", "use_tpu", "=", "False", ",", "variables", "=", "None", ")", ":", "loss", "=", "weight_decay_and_noise", "(", "loss", ",", "hparams", ",", "learning_rate", ")", "loss", "=", "tf", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
weight_decay_and_noise
Apply weight decay and weight noise.
tensor2tensor/utils/optimize.py
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): """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...
[ "Apply", "weight", "decay", "and", "weight", "noise", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L238-L256
[ "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"...
272500b6efe353aeb638d2745ed56e519462ca31
train
weight_noise
Apply weight noise to vars in var_list.
tensor2tensor/utils/optimize.py
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): """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....
[ "Apply", "weight", "noise", "to", "vars", "in", "var_list", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L259-L278
[ "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...
272500b6efe353aeb638d2745ed56e519462ca31
train
weight_decay
Apply weight decay to vars in var_list.
tensor2tensor/utils/optimize.py
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): """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...
[ "Apply", "weight", "decay", "to", "vars", "in", "var_list", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L281-L298
[ "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", ")", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
log_variable_sizes
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.
tensor2tensor/utils/optimize.py
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): """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...
[ "Log", "the", "sizes", "and", "shapes", "of", "variables", "and", "the", "total", "size", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L301-L327
[ "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", ":"...
272500b6efe353aeb638d2745ed56e519462ca31
train
summarize_variables
Summarize the variables. Args: var_list: a list of variables; defaults to trainable_variables. tag: name scope of the summary; defaults to training_variables/.
tensor2tensor/utils/optimize.py
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): """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...
[ "Summarize", "the", "variables", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L330-L345
[ "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...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_variable_initializer
Get variable initializer from hparams.
tensor2tensor/utils/optimize.py
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): """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) ...
[ "Get", "variable", "initializer", "from", "hparams", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L348-L373
[ "def", "get_variable_initializer", "(", "hparams", ")", ":", "if", "not", "hparams", ".", "initializer", ":", "return", "None", "mlperf_log", ".", "transformer_print", "(", "key", "=", "mlperf_log", ".", "MODEL_HP_INITIALIZER_GAIN", ",", "value", "=", "hparams", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
summarize_tensors
Summarize the tensors. Args: tensor_dict: a dictionary of tensors. tag: name scope of the summary; defaults to tensors/.
tensor2tensor/layers/vqa_layers.py
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): """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...
[ "Summarize", "the", "tensors", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/vqa_layers.py#L33-L45
[ "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...
272500b6efe353aeb638d2745ed56e519462ca31
train
image_embedding
Extract image features from pretrained resnet model.
tensor2tensor/layers/vqa_layers.py
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, batch_norm_scale=True, ...
[ "Extract", "image", "features", "from", "pretrained", "resnet", "model", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/vqa_layers.py#L48-L99
[ "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", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
multihead_attention
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...
tensor2tensor/layers/vqa_layers.py
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, ...
[ "Multihead", "scaled", "-", "dot", "-", "product", "attention", "with", "input", "/", "output", "transformations", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/vqa_layers.py#L102-L347
[ "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", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
_get_timit
Extract TIMIT datasets to directory unless directory/timit exists.
tensor2tensor/data_generators/audio.py
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): """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...
[ "Extract", "TIMIT", "datasets", "to", "directory", "unless", "directory", "/", "timit", "exists", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/audio.py#L44-L53
[ "def", "_get_timit", "(", "directory", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "\"timit\"", ")", ")", ":", "return", "assert", "FLAGS", ".", "timit_paths", "for", "path", "in", "FL...
272500b6efe353aeb638d2745ed56e519462ca31
train
_collect_data
Traverses directory collecting input and target files.
tensor2tensor/data_generators/audio.py
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): """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 ...
[ "Traverses", "directory", "collecting", "input", "and", "target", "files", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/audio.py#L56-L74
[ "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 ...
272500b6efe353aeb638d2745ed56e519462ca31
train
timit_generator
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...
tensor2tensor/data_generators/audio.py
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): """Data generator for TIMIT transcription problem. ...
[ "Data", "generator", "for", "TIMIT", "transcription", "problem", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/audio.py#L98-L162
[ "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"...
272500b6efe353aeb638d2745ed56e519462ca31
train
_build_vocab
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.
tensor2tensor/data_generators/wikitext103.py
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): """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...
[ "Reads", "a", "file", "to", "build", "a", "vocabulary", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikitext103.py#L37-L59
[ "def", "_build_vocab", "(", "filename", ",", "vocab_dir", ",", "vocab_name", ")", ":", "vocab_path", "=", "os", ".", "path", ".", "join", "(", "vocab_dir", ",", "vocab_name", ")", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "vocab_path", ")", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_maybe_download_corpus
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.
tensor2tensor/data_generators/wikitext103.py
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): """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...
[ "Download", "and", "unpack", "the", "corpus", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikitext103.py#L62-L104
[ "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...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_batch_coordinate
Return a flat int32 tensor of shape [1, batch_size*length, 1].
tensor2tensor/models/research/aligned.py
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): """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...
[ "Return", "a", "flat", "int32", "tensor", "of", "shape", "[", "1", "batch_size", "*", "length", "1", "]", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/aligned.py#L228-L235
[ "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", ")",...
272500b6efe353aeb638d2745ed56e519462ca31
train
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
tensor2tensor/models/research/aligned.py
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(): """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...
[ "Set", "of", "hyperparameters", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/aligned.py#L239-L305
[ "def", "aligned_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "batch_size", "=", "5000", "hparams", ".", "max_length", "=", "0", "hparams", ".", "min_length_...
272500b6efe353aeb638d2745ed56e519462ca31
train
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
tensor2tensor/models/research/aligned.py
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(): """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 ...
[ "version", "for", "languagemodel_wiki_scramble8k50", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/aligned.py#L512-L527
[ "def", "aligned_8k_grouped", "(", ")", ":", "hparams", "=", "aligned_grouped", "(", ")", "hparams", ".", "batch_size", "=", "8192", "# hparams.attention_image_summary = False", "hparams", ".", "num_groups", "=", "16", "hparams", ".", "multiplicative_overhead", "=", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_merge_beam_dim
Reshapes first two dimensions in to single dimension. Args: tensor: Tensor to reshape of shape [A, B, ...] Returns: Reshaped tensor of shape [A*B, ...]
tensor2tensor/utils/beam_search.py
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): """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) # ...
[ "Reshapes", "first", "two", "dimensions", "in", "to", "single", "dimension", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L37-L49
[ "def", "_merge_beam_dim", "(", "tensor", ")", ":", "shape", "=", "common_layers", ".", "shape_list", "(", "tensor", ")", "shape", "[", "0", "]", "*=", "shape", "[", "1", "]", "# batch -> batch * beam_size", "shape", ".", "pop", "(", "1", ")", "# Remove bea...
272500b6efe353aeb638d2745ed56e519462ca31
train
_unmerge_beam_dim
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, ...]
tensor2tensor/utils/beam_search.py
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): """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 [...
[ "Reshapes", "first", "dimension", "back", "to", "[", "batch_size", "beam_size", "]", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L52-L65
[ "def", "_unmerge_beam_dim", "(", "tensor", ",", "batch_size", ",", "beam_size", ")", ":", "shape", "=", "common_layers", ".", "shape_list", "(", "tensor", ")", "new_shape", "=", "[", "batch_size", "]", "+", "[", "beam_size", "]", "+", "shape", "[", "1", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_expand_to_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, ...]
tensor2tensor/utils/beam_search.py
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): """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...
[ "Tiles", "a", "given", "tensor", "by", "beam_size", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L68-L82
[ "def", "_expand_to_beam_size", "(", "tensor", ",", "beam_size", ")", ":", "tensor", "=", "tf", ".", "expand_dims", "(", "tensor", ",", "axis", "=", "1", ")", "tile_dims", "=", "[", "1", "]", "*", "tensor", ".", "shape", ".", "ndims", "tile_dims", "[", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_state_shape_invariants
Returns the shape of the tensor but sets middle dims to None.
tensor2tensor/utils/beam_search.py
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): """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)
[ "Returns", "the", "shape", "of", "the", "tensor", "but", "sets", "middle", "dims", "to", "None", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L85-L90
[ "def", "get_state_shape_invariants", "(", "tensor", ")", ":", "shape", "=", "tensor", ".", "shape", ".", "as_list", "(", ")", "for", "i", "in", "range", "(", "1", ",", "len", "(", "shape", ")", "-", "1", ")", ":", "shape", "[", "i", "]", "=", "No...
272500b6efe353aeb638d2745ed56e519462ca31
train
compute_batch_indices
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...
tensor2tensor/utils/beam_search.py
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): """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...
[ "Computes", "the", "i", "th", "coordinate", "that", "contains", "the", "batch", "index", "for", "gathers", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L93-L108
[ "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"...
272500b6efe353aeb638d2745ed56e519462ca31
train
fast_tpu_gather
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. ...
tensor2tensor/utils/beam_search.py
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): """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...
[ "Fast", "gather", "implementation", "for", "models", "running", "on", "TPU", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L111-L165
[ "def", "fast_tpu_gather", "(", "params", ",", "indices", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ")", ":", "dtype", "=", "params", ".", "dtype", "def", "_gather", "(", "params", ",", "indices", ")", ":", "\"\...
272500b6efe353aeb638d2745ed56e519462ca31
train
_create_make_unique
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...
tensor2tensor/utils/beam_search.py
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): """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: ...
[ "Replaces", "the", "lower", "bits", "of", "each", "element", "with", "iota", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L168-L229
[ "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", "=", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
_create_topk_unique
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. [...
tensor2tensor/utils/beam_search.py
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): """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:...
[ "Creates", "the", "top", "k", "values", "in", "sorted", "order", "with", "indices", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L232-L270
[ "def", "_create_topk_unique", "(", "inputs", ",", "k", ")", ":", "height", "=", "inputs", ".", "shape", "[", "0", "]", "width", "=", "inputs", ".", "shape", "[", "1", "]", "neg_inf_r0", "=", "tf", ".", "constant", "(", "-", "np", ".", "inf", ",", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
top_k_with_unique
Finds the values and indices of the k largests entries. Instead of doing sort like tf.nn.top_k, this function finds the max value k times. The running time is proportional to k, which is be faster when k is small. The current implementation supports only inputs of rank 2. In addition, iota is used to replace t...
tensor2tensor/utils/beam_search.py
def top_k_with_unique(inputs, k): """Finds the values and indices of the k largests entries. Instead of doing sort like tf.nn.top_k, this function finds the max value k times. The running time is proportional to k, which is be faster when k is small. The current implementation supports only inputs of rank 2. ...
def top_k_with_unique(inputs, k): """Finds the values and indices of the k largests entries. Instead of doing sort like tf.nn.top_k, this function finds the max value k times. The running time is proportional to k, which is be faster when k is small. The current implementation supports only inputs of rank 2. ...
[ "Finds", "the", "values", "and", "indices", "of", "the", "k", "largests", "entries", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L273-L295
[ "def", "top_k_with_unique", "(", "inputs", ",", "k", ")", ":", "unique_inputs", "=", "_create_make_unique", "(", "tf", ".", "cast", "(", "inputs", ",", "tf", ".", "float32", ")", ")", "top_values", ",", "indices", "=", "_create_topk_unique", "(", "unique_inp...
272500b6efe353aeb638d2745ed56e519462ca31
train
compute_topk_scores_and_seq
Given sequences and scores, will gather the top k=beam size sequences. This function is used to grow alive, and finished. It takes sequences, scores, and flags, and returns the top k from sequences, scores_to_gather, and flags based on the values in scores. This method permits easy introspection using tfdbg. ...
tensor2tensor/utils/beam_search.py
def compute_topk_scores_and_seq(sequences, scores, scores_to_gather, flags, beam_size, batch_size, prefix="default", ...
def compute_topk_scores_and_seq(sequences, scores, scores_to_gather, flags, beam_size, batch_size, prefix="default", ...
[ "Given", "sequences", "and", "scores", "will", "gather", "the", "top", "k", "=", "beam", "size", "sequences", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L298-L393
[ "def", "compute_topk_scores_and_seq", "(", "sequences", ",", "scores", ",", "scores_to_gather", ",", "flags", ",", "beam_size", ",", "batch_size", ",", "prefix", "=", "\"default\"", ",", "states_to_gather", "=", "None", ",", "use_tpu", "=", "False", ",", "use_to...
272500b6efe353aeb638d2745ed56e519462ca31
train
beam_search
Beam search with length penalties. Requires a function that can take the currently decoded symbols and return the logits for the next symbol. The implementation is inspired by https://arxiv.org/abs/1609.08144. When running, the beam search steps can be visualized by using tfdbg to watch the operations gener...
tensor2tensor/utils/beam_search.py
def beam_search(symbols_to_logits_fn, initial_ids, beam_size, decode_length, vocab_size, alpha, states=None, eos_id=EOS_ID, stop_early=True, use_tpu=False, use_...
def beam_search(symbols_to_logits_fn, initial_ids, beam_size, decode_length, vocab_size, alpha, states=None, eos_id=EOS_ID, stop_early=True, use_tpu=False, use_...
[ "Beam", "search", "with", "length", "penalties", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L396-L813
[ "def", "beam_search", "(", "symbols_to_logits_fn", ",", "initial_ids", ",", "beam_size", ",", "decode_length", ",", "vocab_size", ",", "alpha", ",", "states", "=", "None", ",", "eos_id", "=", "EOS_ID", ",", "stop_early", "=", "True", ",", "use_tpu", "=", "Fa...
272500b6efe353aeb638d2745ed56e519462ca31
train
video_augmentation
Augments video with optional hue, saturation and constrast. Args: features: dict, with keys "inputs", "targets". features["inputs"], 4-D Tensor, shape=(THWC) features["targets"], 4-D Tensor, shape=(THWC) hue: bool, apply hue_transform. saturate: bool, apply saturation transfor...
tensor2tensor/data_generators/video_utils.py
def video_augmentation(features, hue=False, saturate=False, contrast=False): """Augments video with optional hue, saturation and constrast. Args: features: dict, with keys "inputs", "targets". features["inputs"], 4-D Tensor, shape=(THWC) features["targets"], 4-D Tensor, shape=(THWC)...
def video_augmentation(features, hue=False, saturate=False, contrast=False): """Augments video with optional hue, saturation and constrast. Args: features: dict, with keys "inputs", "targets". features["inputs"], 4-D Tensor, shape=(THWC) features["targets"], 4-D Tensor, shape=(THWC)...
[ "Augments", "video", "with", "optional", "hue", "saturation", "and", "constrast", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L52-L78
[ "def", "video_augmentation", "(", "features", ",", "hue", "=", "False", ",", "saturate", "=", "False", ",", "contrast", "=", "False", ")", ":", "inputs", ",", "targets", "=", "features", "[", "\"inputs\"", "]", ",", "features", "[", "\"targets\"", "]", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
create_border
Creates a border around each frame to differentiate input and target. Args: video: 5-D NumPy array. color: string, "blue", "red" or "green". border_percent: Percentarge of the frame covered by the border. Returns: video: 5-D NumPy array.
tensor2tensor/data_generators/video_utils.py
def create_border(video, color="blue", border_percent=2): """Creates a border around each frame to differentiate input and target. Args: video: 5-D NumPy array. color: string, "blue", "red" or "green". border_percent: Percentarge of the frame covered by the border. Returns: video: 5-D NumPy array...
def create_border(video, color="blue", border_percent=2): """Creates a border around each frame to differentiate input and target. Args: video: 5-D NumPy array. color: string, "blue", "red" or "green". border_percent: Percentarge of the frame covered by the border. Returns: video: 5-D NumPy array...
[ "Creates", "a", "border", "around", "each", "frame", "to", "differentiate", "input", "and", "target", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L81-L103
[ "def", "create_border", "(", "video", ",", "color", "=", "\"blue\"", ",", "border_percent", "=", "2", ")", ":", "# Do not create border if the video is not in RGB format", "if", "video", ".", "shape", "[", "-", "1", "]", "!=", "3", ":", "return", "video", "col...
272500b6efe353aeb638d2745ed56e519462ca31
train
convert_videos_to_summaries
Converts input, output and target videos into video summaries. Args: input_videos: 5-D NumPy array, (NTHWC) conditioning frames. output_videos: 5-D NumPy array, (NTHWC) model predictions. target_videos: 5-D NumPy array, (NTHWC) target frames. tag: tf summary tag. decode_hparams: HParams. disp...
tensor2tensor/data_generators/video_utils.py
def convert_videos_to_summaries(input_videos, output_videos, target_videos, tag, decode_hparams, display_ground_truth=False): """Converts input, output and target videos into video summaries. Args: input_videos: 5-D NumPy array, (NTHWC) conditioni...
def convert_videos_to_summaries(input_videos, output_videos, target_videos, tag, decode_hparams, display_ground_truth=False): """Converts input, output and target videos into video summaries. Args: input_videos: 5-D NumPy array, (NTHWC) conditioni...
[ "Converts", "input", "output", "and", "target", "videos", "into", "video", "summaries", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L106-L162
[ "def", "convert_videos_to_summaries", "(", "input_videos", ",", "output_videos", ",", "target_videos", ",", "tag", ",", "decode_hparams", ",", "display_ground_truth", "=", "False", ")", ":", "fps", "=", "decode_hparams", ".", "frames_per_second", "border_percent", "="...
272500b6efe353aeb638d2745ed56e519462ca31
train
display_video_hooks
Hooks to display videos at decode time.
tensor2tensor/data_generators/video_utils.py
def display_video_hooks(hook_args): """Hooks to display videos at decode time.""" predictions = hook_args.predictions max_outputs = hook_args.decode_hparams.max_display_outputs max_decodes = hook_args.decode_hparams.max_display_decodes with tf.Graph().as_default(): _, best_decodes = video_metrics.compute...
def display_video_hooks(hook_args): """Hooks to display videos at decode time.""" predictions = hook_args.predictions max_outputs = hook_args.decode_hparams.max_display_outputs max_decodes = hook_args.decode_hparams.max_display_decodes with tf.Graph().as_default(): _, best_decodes = video_metrics.compute...
[ "Hooks", "to", "display", "videos", "at", "decode", "time", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L165-L206
[ "def", "display_video_hooks", "(", "hook_args", ")", ":", "predictions", "=", "hook_args", ".", "predictions", "max_outputs", "=", "hook_args", ".", "decode_hparams", ".", "max_display_outputs", "max_decodes", "=", "hook_args", ".", "decode_hparams", ".", "max_display...
272500b6efe353aeb638d2745ed56e519462ca31
train
summarize_video_metrics
Computes video metrics summaries using the decoder output.
tensor2tensor/data_generators/video_utils.py
def summarize_video_metrics(hook_args): """Computes video metrics summaries using the decoder output.""" problem_name = hook_args.problem.name current_problem = hook_args.problem hparams = hook_args.hparams output_dirs = hook_args.output_dirs predictions = hook_args.predictions frame_shape = [ curre...
def summarize_video_metrics(hook_args): """Computes video metrics summaries using the decoder output.""" problem_name = hook_args.problem.name current_problem = hook_args.problem hparams = hook_args.hparams output_dirs = hook_args.output_dirs predictions = hook_args.predictions frame_shape = [ curre...
[ "Computes", "video", "metrics", "summaries", "using", "the", "decoder", "output", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L209-L235
[ "def", "summarize_video_metrics", "(", "hook_args", ")", ":", "problem_name", "=", "hook_args", ".", "problem", ".", "name", "current_problem", "=", "hook_args", ".", "problem", "hparams", "=", "hook_args", ".", "hparams", "output_dirs", "=", "hook_args", ".", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
debug_video_writer_factory
Creates a VideoWriter for debug videos.
tensor2tensor/data_generators/video_utils.py
def debug_video_writer_factory(output_dir): """Creates a VideoWriter for debug videos.""" if FLAGS.disable_ffmpeg: return common_video.IndividualFrameWriter(output_dir) else: output_path = os.path.join(output_dir, "video.avi") return common_video.WholeVideoWriter( fps=10, output_path=output_pa...
def debug_video_writer_factory(output_dir): """Creates a VideoWriter for debug videos.""" if FLAGS.disable_ffmpeg: return common_video.IndividualFrameWriter(output_dir) else: output_path = os.path.join(output_dir, "video.avi") return common_video.WholeVideoWriter( fps=10, output_path=output_pa...
[ "Creates", "a", "VideoWriter", "for", "debug", "videos", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L238-L246
[ "def", "debug_video_writer_factory", "(", "output_dir", ")", ":", "if", "FLAGS", ".", "disable_ffmpeg", ":", "return", "common_video", ".", "IndividualFrameWriter", "(", "output_dir", ")", "else", ":", "output_path", "=", "os", ".", "path", ".", "join", "(", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
VideoProblem.preprocess_example
Runtime preprocessing, e.g., resize example["frame"].
tensor2tensor/data_generators/video_utils.py
def preprocess_example(self, example, mode, hparams): """Runtime preprocessing, e.g., resize example["frame"].""" if getattr(hparams, "preprocess_resize_frames", None) is not None: example["frame"] = tf.image.resize_images( example["frame"], hparams.preprocess_resize_frames, tf.image.R...
def preprocess_example(self, example, mode, hparams): """Runtime preprocessing, e.g., resize example["frame"].""" if getattr(hparams, "preprocess_resize_frames", None) is not None: example["frame"] = tf.image.resize_images( example["frame"], hparams.preprocess_resize_frames, tf.image.R...
[ "Runtime", "preprocessing", "e", ".", "g", ".", "resize", "example", "[", "frame", "]", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L346-L352
[ "def", "preprocess_example", "(", "self", ",", "example", ",", "mode", ",", "hparams", ")", ":", "if", "getattr", "(", "hparams", ",", "\"preprocess_resize_frames\"", ",", "None", ")", "is", "not", "None", ":", "example", "[", "\"frame\"", "]", "=", "tf", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
VideoProblem.serving_input_fn
For serving/predict, assume that only video frames are provided.
tensor2tensor/data_generators/video_utils.py
def serving_input_fn(self, hparams): """For serving/predict, assume that only video frames are provided.""" video_input_frames = tf.placeholder( dtype=tf.float32, shape=[ None, hparams.video_num_input_frames, self.frame_width, self.frame_height, self.num_channels ...
def serving_input_fn(self, hparams): """For serving/predict, assume that only video frames are provided.""" video_input_frames = tf.placeholder( dtype=tf.float32, shape=[ None, hparams.video_num_input_frames, self.frame_width, self.frame_height, self.num_channels ...
[ "For", "serving", "/", "predict", "assume", "that", "only", "video", "frames", "are", "provided", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L397-L409
[ "def", "serving_input_fn", "(", "self", ",", "hparams", ")", ":", "video_input_frames", "=", "tf", ".", "placeholder", "(", "dtype", "=", "tf", ".", "float32", ",", "shape", "=", "[", "None", ",", "hparams", ".", "video_num_input_frames", ",", "self", ".",...
272500b6efe353aeb638d2745ed56e519462ca31
train
VideoProblem.generate_encoded_samples
Generate samples of the encoded frames with possible extra data. By default this function just encodes the numpy array returned as "frame" from `self.generate_samples` into a PNG image. Override this function to get other encodings on disk. Args: data_dir: final data directory. Typically only us...
tensor2tensor/data_generators/video_utils.py
def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split): """Generate samples of the encoded frames with possible extra data. By default this function just encodes the numpy array returned as "frame" from `self.generate_samples` into a PNG image. Override this function to get other encoding...
def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split): """Generate samples of the encoded frames with possible extra data. By default this function just encodes the numpy array returned as "frame" from `self.generate_samples` into a PNG image. Override this function to get other encoding...
[ "Generate", "samples", "of", "the", "encoded", "frames", "with", "possible", "extra", "data", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L573-L630
[ "def", "generate_encoded_samples", "(", "self", ",", "data_dir", ",", "tmp_dir", ",", "dataset_split", ")", ":", "writer", "=", "None", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ":", "image_t", "=", "tf", ".", "placeholder", "(",...
272500b6efe353aeb638d2745ed56e519462ca31
train
VideoProblem.generate_data
The function generating the data.
tensor2tensor/data_generators/video_utils.py
def generate_data(self, data_dir, tmp_dir, task_id=-1): """The function generating the data.""" filepath_fns = { problem.DatasetSplit.TRAIN: self.training_filepaths, problem.DatasetSplit.EVAL: self.dev_filepaths, problem.DatasetSplit.TEST: self.test_filepaths, } # We set shuffle...
def generate_data(self, data_dir, tmp_dir, task_id=-1): """The function generating the data.""" filepath_fns = { problem.DatasetSplit.TRAIN: self.training_filepaths, problem.DatasetSplit.EVAL: self.dev_filepaths, problem.DatasetSplit.TEST: self.test_filepaths, } # We set shuffle...
[ "The", "function", "generating", "the", "data", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L632-L659
[ "def", "generate_data", "(", "self", ",", "data_dir", ",", "tmp_dir", ",", "task_id", "=", "-", "1", ")", ":", "filepath_fns", "=", "{", "problem", ".", "DatasetSplit", ".", "TRAIN", ":", "self", ".", "training_filepaths", ",", "problem", ".", "DatasetSpli...
272500b6efe353aeb638d2745ed56e519462ca31
train
add_scope
Return a decorator which add a TF name/variable scope to a function. Note that the function returned by the decorator accept an additional 'name' parameter, which can overwrite the name scope given when the function is created. Args: scope (str): name of the scope. If None, the function name is used. ...
tensor2tensor/utils/expert_utils.py
def add_scope(scope=None, scope_fn=None): """Return a decorator which add a TF name/variable scope to a function. Note that the function returned by the decorator accept an additional 'name' parameter, which can overwrite the name scope given when the function is created. Args: scope (str): name of the ...
def add_scope(scope=None, scope_fn=None): """Return a decorator which add a TF name/variable scope to a function. Note that the function returned by the decorator accept an additional 'name' parameter, which can overwrite the name scope given when the function is created. Args: scope (str): name of the ...
[ "Return", "a", "decorator", "which", "add", "a", "TF", "name", "/", "variable", "scope", "to", "a", "function", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L40-L64
[ "def", "add_scope", "(", "scope", "=", "None", ",", "scope_fn", "=", "None", ")", ":", "def", "decorator", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":",...
272500b6efe353aeb638d2745ed56e519462ca31
train
_add_variable_proxy_methods
Proxy methods of underlying variable. This enables our custom getters to still work with, e.g., batch norm. Args: var: Variable to proxy proxy_tensor: Tensor that is identity of var
tensor2tensor/utils/expert_utils.py
def _add_variable_proxy_methods(var, proxy_tensor): """Proxy methods of underlying variable. This enables our custom getters to still work with, e.g., batch norm. Args: var: Variable to proxy proxy_tensor: Tensor that is identity of var """ proxy_tensor.read_value = lambda: tf.identity(proxy_tensor)...
def _add_variable_proxy_methods(var, proxy_tensor): """Proxy methods of underlying variable. This enables our custom getters to still work with, e.g., batch norm. Args: var: Variable to proxy proxy_tensor: Tensor that is identity of var """ proxy_tensor.read_value = lambda: tf.identity(proxy_tensor)...
[ "Proxy", "methods", "of", "underlying", "variable", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L75-L87
[ "def", "_add_variable_proxy_methods", "(", "var", ",", "proxy_tensor", ")", ":", "proxy_tensor", ".", "read_value", "=", "lambda", ":", "tf", ".", "identity", "(", "proxy_tensor", ")", "proxy_tensor", ".", "assign_sub", "=", "var", ".", "assign_sub", "proxy_tens...
272500b6efe353aeb638d2745ed56e519462ca31
train
_rowwise_unsorted_segment_sum
UnsortedSegmentSum on each row. Args: values: a `Tensor` with shape `[batch_size, k]`. indices: an integer `Tensor` with shape `[batch_size, k]`. n: an integer. Returns: A `Tensor` with the same type as `values` and shape `[batch_size, n]`.
tensor2tensor/utils/expert_utils.py
def _rowwise_unsorted_segment_sum(values, indices, n): """UnsortedSegmentSum on each row. Args: values: a `Tensor` with shape `[batch_size, k]`. indices: an integer `Tensor` with shape `[batch_size, k]`. n: an integer. Returns: A `Tensor` with the same type as `values` and shape `[batch_size, n]`...
def _rowwise_unsorted_segment_sum(values, indices, n): """UnsortedSegmentSum on each row. Args: values: a `Tensor` with shape `[batch_size, k]`. indices: an integer `Tensor` with shape `[batch_size, k]`. n: an integer. Returns: A `Tensor` with the same type as `values` and shape `[batch_size, n]`...
[ "UnsortedSegmentSum", "on", "each", "row", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L267-L281
[ "def", "_rowwise_unsorted_segment_sum", "(", "values", ",", "indices", ",", "n", ")", ":", "batch", ",", "k", "=", "tf", ".", "unstack", "(", "tf", ".", "shape", "(", "indices", ")", ",", "num", "=", "2", ")", "indices_flat", "=", "tf", ".", "reshape...
272500b6efe353aeb638d2745ed56e519462ca31
train
_prob_in_top_k
Helper function to NoisyTopKGating. Computes the probability that value is in top k, given different random noise. This gives us a way of backpropagating from a loss that balances the number of times each expert is in the top k experts per example. In the case of no noise, pass in None for noise_stddev, and ...
tensor2tensor/utils/expert_utils.py
def _prob_in_top_k( clean_values, noisy_values, noise_stddev, noisy_top_values, k): """Helper function to NoisyTopKGating. Computes the probability that value is in top k, given different random noise. This gives us a way of backpropagating from a loss that balances the number of times each expert is in t...
def _prob_in_top_k( clean_values, noisy_values, noise_stddev, noisy_top_values, k): """Helper function to NoisyTopKGating. Computes the probability that value is in top k, given different random noise. This gives us a way of backpropagating from a loss that balances the number of times each expert is in t...
[ "Helper", "function", "to", "NoisyTopKGating", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L303-L348
[ "def", "_prob_in_top_k", "(", "clean_values", ",", "noisy_values", ",", "noise_stddev", ",", "noisy_top_values", ",", "k", ")", ":", "batch", "=", "tf", ".", "shape", "(", "clean_values", ")", "[", "0", "]", "m", "=", "tf", ".", "shape", "(", "noisy_top_...
272500b6efe353aeb638d2745ed56e519462ca31
train
cv_squared
The squared coefficient of variation of a sample. Useful as a loss to encourage a positive distribution to be more uniform. Epsilons added for numerical stability. Returns 0 for an empty Tensor. Args: x: a `Tensor`. Returns: a `Scalar`.
tensor2tensor/utils/expert_utils.py
def cv_squared(x): """The squared coefficient of variation of a sample. Useful as a loss to encourage a positive distribution to be more uniform. Epsilons added for numerical stability. Returns 0 for an empty Tensor. Args: x: a `Tensor`. Returns: a `Scalar`. """ epsilon = 1e-10 float_size =...
def cv_squared(x): """The squared coefficient of variation of a sample. Useful as a loss to encourage a positive distribution to be more uniform. Epsilons added for numerical stability. Returns 0 for an empty Tensor. Args: x: a `Tensor`. Returns: a `Scalar`. """ epsilon = 1e-10 float_size =...
[ "The", "squared", "coefficient", "of", "variation", "of", "a", "sample", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L351-L368
[ "def", "cv_squared", "(", "x", ")", ":", "epsilon", "=", "1e-10", "float_size", "=", "tf", ".", "to_float", "(", "tf", ".", "size", "(", "x", ")", ")", "+", "epsilon", "mean", "=", "tf", ".", "reduce_sum", "(", "x", ")", "/", "float_size", "varianc...
272500b6efe353aeb638d2745ed56e519462ca31
train
update_hparams_for_vq_gating
VQ Gating hparams.
tensor2tensor/utils/expert_utils.py
def update_hparams_for_vq_gating(hparams): """VQ Gating hparams.""" hparams.add_hparam("z_size", 4) hparams.add_hparam("noise_dev", 0.5) # Bottleneck kinds supported: dense, vae, dvq. hparams.add_hparam("bottleneck_kind", "dvq") hparams.add_hparam("num_blocks", 1) hparams.add_hparam("num_residuals", 1) ...
def update_hparams_for_vq_gating(hparams): """VQ Gating hparams.""" hparams.add_hparam("z_size", 4) hparams.add_hparam("noise_dev", 0.5) # Bottleneck kinds supported: dense, vae, dvq. hparams.add_hparam("bottleneck_kind", "dvq") hparams.add_hparam("num_blocks", 1) hparams.add_hparam("num_residuals", 1) ...
[ "VQ", "Gating", "hparams", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L384-L402
[ "def", "update_hparams_for_vq_gating", "(", "hparams", ")", ":", "hparams", ".", "add_hparam", "(", "\"z_size\"", ",", "4", ")", "hparams", ".", "add_hparam", "(", "\"noise_dev\"", ",", "0.5", ")", "# Bottleneck kinds supported: dense, vae, dvq.", "hparams", ".", "a...
272500b6efe353aeb638d2745ed56e519462ca31
train
_my_top_k
GPU-compatible version of top-k that works for very small constant k. Calls argmax repeatedly. tf.nn.top_k is implemented for GPU, but the gradient, sparse_to_dense, seems not to be, so if we use tf.nn.top_k, then both the top_k and its gradient go on cpu. Once this is not an issue, this function becomes o...
tensor2tensor/utils/expert_utils.py
def _my_top_k(x, k): """GPU-compatible version of top-k that works for very small constant k. Calls argmax repeatedly. tf.nn.top_k is implemented for GPU, but the gradient, sparse_to_dense, seems not to be, so if we use tf.nn.top_k, then both the top_k and its gradient go on cpu. Once this is not an issue,...
def _my_top_k(x, k): """GPU-compatible version of top-k that works for very small constant k. Calls argmax repeatedly. tf.nn.top_k is implemented for GPU, but the gradient, sparse_to_dense, seems not to be, so if we use tf.nn.top_k, then both the top_k and its gradient go on cpu. Once this is not an issue,...
[ "GPU", "-", "compatible", "version", "of", "top", "-", "k", "that", "works", "for", "very", "small", "constant", "k", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L405-L434
[ "def", "_my_top_k", "(", "x", ",", "k", ")", ":", "if", "k", ">", "10", ":", "return", "tf", ".", "nn", ".", "top_k", "(", "x", ",", "k", ")", "values", "=", "[", "]", "indices", "=", "[", "]", "depth", "=", "tf", ".", "shape", "(", "x", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
vq_gating
VQ gating. Args: x: input Tensor with shape [batch_size, input_size] num_experts: an integer k: an integer - number of experts per example bneck: a bottleneck object hparams: optional hparams name: an optional string Returns: gates: a Tensor with shape [batch_size, num_experts] loa...
tensor2tensor/utils/expert_utils.py
def vq_gating(x, num_experts, k, bneck, hparams=None, name="vq_gating"): """VQ gating. Args: x: input Tensor with shape [batch_size, input_size] num_experts: an integer k: an integer - number of experts per example bneck: a bottl...
def vq_gating(x, num_experts, k, bneck, hparams=None, name="vq_gating"): """VQ gating. Args: x: input Tensor with shape [batch_size, input_size] num_experts: an integer k: an integer - number of experts per example bneck: a bottl...
[ "VQ", "gating", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L437-L511
[ "def", "vq_gating", "(", "x", ",", "num_experts", ",", "k", ",", "bneck", ",", "hparams", "=", "None", ",", "name", "=", "\"vq_gating\"", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "reuse", "=", "tf", ".", "AUTO_REUSE", ")", ":"...
272500b6efe353aeb638d2745ed56e519462ca31
train
noisy_top_k_gating
Noisy top-k gating. See paper: https://arxiv.org/abs/1701.06538. Args: x: input Tensor with shape [batch_size, input_size] num_experts: an integer train: a boolean - we only add noise at training time. k: an integer - number of experts per example initializer: an initializer noisy_gating: ...
tensor2tensor/utils/expert_utils.py
def noisy_top_k_gating(x, num_experts, train, k=2, initializer=tf.zeros_initializer(), noisy_gating=True, noise_epsilon=1e-2, name=None): """Noisy top-k gati...
def noisy_top_k_gating(x, num_experts, train, k=2, initializer=tf.zeros_initializer(), noisy_gating=True, noise_epsilon=1e-2, name=None): """Noisy top-k gati...
[ "Noisy", "top", "-", "k", "gating", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L514-L579
[ "def", "noisy_top_k_gating", "(", "x", ",", "num_experts", ",", "train", ",", "k", "=", "2", ",", "initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ",", "noisy_gating", "=", "True", ",", "noise_epsilon", "=", "1e-2", ",", "name", "=", "None",...
272500b6efe353aeb638d2745ed56e519462ca31
train
map_ids
Apply a function to each coordinate ids of a multidimensional tensor. This allows to process each sequence of a batch independently. This is similar to tf.map_fn but with tensor where the batch dim has been flatten. Warning: The indices ids have to be contiguous and ordered in memory as the output vector for ...
tensor2tensor/utils/expert_utils.py
def map_ids(x, indices, map_fn): """Apply a function to each coordinate ids of a multidimensional tensor. This allows to process each sequence of a batch independently. This is similar to tf.map_fn but with tensor where the batch dim has been flatten. Warning: The indices ids have to be contiguous and ordered...
def map_ids(x, indices, map_fn): """Apply a function to each coordinate ids of a multidimensional tensor. This allows to process each sequence of a batch independently. This is similar to tf.map_fn but with tensor where the batch dim has been flatten. Warning: The indices ids have to be contiguous and ordered...
[ "Apply", "a", "function", "to", "each", "coordinate", "ids", "of", "a", "multidimensional", "tensor", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L665-L730
[ "def", "map_ids", "(", "x", ",", "indices", ",", "map_fn", ")", ":", "indices", "=", "tf", ".", "reshape", "(", "indices", ",", "[", "-", "1", "]", ")", "t_i", "=", "tf", ".", "constant", "(", "0", ")", "# batch_coordinates start at 0", "t_batch_size",...
272500b6efe353aeb638d2745ed56e519462ca31
train
ffn_expert_fn
Returns a function that creates a feed-forward network. Use this function to create the expert_fn argument to distributed_moe. Args: input_size: an integer hidden_sizes: a list of integers output_size: an integer hidden_activation: a unary function. Returns: a unary function
tensor2tensor/utils/expert_utils.py
def ffn_expert_fn(input_size, hidden_sizes, output_size, hidden_activation=tf.nn.relu): """Returns a function that creates a feed-forward network. Use this function to create the expert_fn argument to distributed_moe. Args: input_size: an integer hid...
def ffn_expert_fn(input_size, hidden_sizes, output_size, hidden_activation=tf.nn.relu): """Returns a function that creates a feed-forward network. Use this function to create the expert_fn argument to distributed_moe. Args: input_size: an integer hid...
[ "Returns", "a", "function", "that", "creates", "a", "feed", "-", "forward", "network", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L956-L983
[ "def", "ffn_expert_fn", "(", "input_size", ",", "hidden_sizes", ",", "output_size", ",", "hidden_activation", "=", "tf", ".", "nn", ".", "relu", ")", ":", "def", "my_fn", "(", "x", ")", ":", "layer_sizes", "=", "[", "input_size", "]", "+", "hidden_sizes", ...
272500b6efe353aeb638d2745ed56e519462ca31