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
layer_norm_vars
Create Variables for layer norm.
tensor2tensor/layers/common_layers.py
def layer_norm_vars(filters): """Create Variables for layer norm.""" scale = tf.get_variable( "layer_norm_scale", [filters], initializer=tf.ones_initializer()) bias = tf.get_variable( "layer_norm_bias", [filters], initializer=tf.zeros_initializer()) return scale, bias
def layer_norm_vars(filters): """Create Variables for layer norm.""" scale = tf.get_variable( "layer_norm_scale", [filters], initializer=tf.ones_initializer()) bias = tf.get_variable( "layer_norm_bias", [filters], initializer=tf.zeros_initializer()) return scale, bias
[ "Create", "Variables", "for", "layer", "norm", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L651-L657
[ "def", "layer_norm_vars", "(", "filters", ")", ":", "scale", "=", "tf", ".", "get_variable", "(", "\"layer_norm_scale\"", ",", "[", "filters", "]", ",", "initializer", "=", "tf", ".", "ones_initializer", "(", ")", ")", "bias", "=", "tf", ".", "get_variable...
272500b6efe353aeb638d2745ed56e519462ca31
train
layer_norm_compute
Layer norm raw computation.
tensor2tensor/layers/common_layers.py
def layer_norm_compute(x, epsilon, scale, bias, layer_collection=None): """Layer norm raw computation.""" # Save these before they get converted to tensors by the casting below params = (scale, bias) epsilon, scale, bias = [cast_like(t, x) for t in [epsilon, scale, bias]] mean = tf.reduce_mean(x, axis=[-1],...
def layer_norm_compute(x, epsilon, scale, bias, layer_collection=None): """Layer norm raw computation.""" # Save these before they get converted to tensors by the casting below params = (scale, bias) epsilon, scale, bias = [cast_like(t, x) for t in [epsilon, scale, bias]] mean = tf.reduce_mean(x, axis=[-1],...
[ "Layer", "norm", "raw", "computation", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L660-L675
[ "def", "layer_norm_compute", "(", "x", ",", "epsilon", ",", "scale", ",", "bias", ",", "layer_collection", "=", "None", ")", ":", "# Save these before they get converted to tensors by the casting below", "params", "=", "(", "scale", ",", "bias", ")", "epsilon", ",",...
272500b6efe353aeb638d2745ed56e519462ca31
train
layer_norm
Layer normalize the tensor x, averaging over the last dimension.
tensor2tensor/layers/common_layers.py
def layer_norm(x, filters=None, epsilon=1e-6, name=None, reuse=None, layer_collection=None): """Layer normalize the tensor x, averaging over the last dimension.""" if filters is None: filters = shape_list(x)[-1] with tf.variable_scope(...
def layer_norm(x, filters=None, epsilon=1e-6, name=None, reuse=None, layer_collection=None): """Layer normalize the tensor x, averaging over the last dimension.""" if filters is None: filters = shape_list(x)[-1] with tf.variable_scope(...
[ "Layer", "normalize", "the", "tensor", "x", "averaging", "over", "the", "last", "dimension", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L678-L691
[ "def", "layer_norm", "(", "x", ",", "filters", "=", "None", ",", "epsilon", "=", "1e-6", ",", "name", "=", "None", ",", "reuse", "=", "None", ",", "layer_collection", "=", "None", ")", ":", "if", "filters", "is", "None", ":", "filters", "=", "shape_l...
272500b6efe353aeb638d2745ed56e519462ca31
train
group_norm
Group normalization as in https://arxiv.org/abs/1803.08494.
tensor2tensor/layers/common_layers.py
def group_norm(x, filters=None, num_groups=8, epsilon=1e-5): """Group normalization as in https://arxiv.org/abs/1803.08494.""" x_shape = shape_list(x) if filters is None: filters = x_shape[-1] assert len(x_shape) == 4 assert filters % num_groups == 0 # Prepare variables. scale = tf.get_variable( ...
def group_norm(x, filters=None, num_groups=8, epsilon=1e-5): """Group normalization as in https://arxiv.org/abs/1803.08494.""" x_shape = shape_list(x) if filters is None: filters = x_shape[-1] assert len(x_shape) == 4 assert filters % num_groups == 0 # Prepare variables. scale = tf.get_variable( ...
[ "Group", "normalization", "as", "in", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1803", ".", "08494", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L694-L712
[ "def", "group_norm", "(", "x", ",", "filters", "=", "None", ",", "num_groups", "=", "8", ",", "epsilon", "=", "1e-5", ")", ":", "x_shape", "=", "shape_list", "(", "x", ")", "if", "filters", "is", "None", ":", "filters", "=", "x_shape", "[", "-", "1...
272500b6efe353aeb638d2745ed56e519462ca31
train
noam_norm
One version of layer normalization.
tensor2tensor/layers/common_layers.py
def noam_norm(x, epsilon=1.0, name=None): """One version of layer normalization.""" with tf.name_scope(name, default_name="noam_norm", values=[x]): shape = x.get_shape() ndims = len(shape) return (tf.nn.l2_normalize(x, ndims - 1, epsilon=epsilon) * tf.sqrt( to_float(shape[-1])))
def noam_norm(x, epsilon=1.0, name=None): """One version of layer normalization.""" with tf.name_scope(name, default_name="noam_norm", values=[x]): shape = x.get_shape() ndims = len(shape) return (tf.nn.l2_normalize(x, ndims - 1, epsilon=epsilon) * tf.sqrt( to_float(shape[-1])))
[ "One", "version", "of", "layer", "normalization", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L715-L721
[ "def", "noam_norm", "(", "x", ",", "epsilon", "=", "1.0", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ",", "default_name", "=", "\"noam_norm\"", ",", "values", "=", "[", "x", "]", ")", ":", "shape", "=", "x", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
l2_norm
Layer normalization with l2 norm.
tensor2tensor/layers/common_layers.py
def l2_norm(x, filters=None, epsilon=1e-6, name=None, reuse=None): """Layer normalization with l2 norm.""" if filters is None: filters = shape_list(x)[-1] with tf.variable_scope(name, default_name="l2_norm", values=[x], reuse=reuse): scale = tf.get_variable( "l2_norm_scale", [filters], initializer...
def l2_norm(x, filters=None, epsilon=1e-6, name=None, reuse=None): """Layer normalization with l2 norm.""" if filters is None: filters = shape_list(x)[-1] with tf.variable_scope(name, default_name="l2_norm", values=[x], reuse=reuse): scale = tf.get_variable( "l2_norm_scale", [filters], initializer...
[ "Layer", "normalization", "with", "l2", "norm", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L724-L738
[ "def", "l2_norm", "(", "x", ",", "filters", "=", "None", ",", "epsilon", "=", "1e-6", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "if", "filters", "is", "None", ":", "filters", "=", "shape_list", "(", "x", ")", "[", "-", "1", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
apply_spectral_norm
Normalizes x using the spectral norm. The implementation follows Algorithm 1 of https://arxiv.org/abs/1802.05957. If x is not a 2-D Tensor, then it is reshaped such that the number of channels (last-dimension) is the same. Args: x: Tensor with the last dimension equal to the number of filters. Returns:...
tensor2tensor/layers/common_layers.py
def apply_spectral_norm(x): """Normalizes x using the spectral norm. The implementation follows Algorithm 1 of https://arxiv.org/abs/1802.05957. If x is not a 2-D Tensor, then it is reshaped such that the number of channels (last-dimension) is the same. Args: x: Tensor with the last dimension equal to t...
def apply_spectral_norm(x): """Normalizes x using the spectral norm. The implementation follows Algorithm 1 of https://arxiv.org/abs/1802.05957. If x is not a 2-D Tensor, then it is reshaped such that the number of channels (last-dimension) is the same. Args: x: Tensor with the last dimension equal to t...
[ "Normalizes", "x", "using", "the", "spectral", "norm", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L741-L778
[ "def", "apply_spectral_norm", "(", "x", ")", ":", "weights_shape", "=", "shape_list", "(", "x", ")", "other", ",", "num_filters", "=", "tf", ".", "reduce_prod", "(", "weights_shape", "[", ":", "-", "1", "]", ")", ",", "weights_shape", "[", "-", "1", "]...
272500b6efe353aeb638d2745ed56e519462ca31
train
apply_norm
Apply Normalization.
tensor2tensor/layers/common_layers.py
def apply_norm(x, norm_type, depth, epsilon, layer_collection=None): """Apply Normalization.""" if layer_collection is not None: assert norm_type == "layer" if norm_type == "layer": return layer_norm( x, filters=depth, epsilon=epsilon, layer_collection=layer_collection) if norm_type == "group": ...
def apply_norm(x, norm_type, depth, epsilon, layer_collection=None): """Apply Normalization.""" if layer_collection is not None: assert norm_type == "layer" if norm_type == "layer": return layer_norm( x, filters=depth, epsilon=epsilon, layer_collection=layer_collection) if norm_type == "group": ...
[ "Apply", "Normalization", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L781-L799
[ "def", "apply_norm", "(", "x", ",", "norm_type", ",", "depth", ",", "epsilon", ",", "layer_collection", "=", "None", ")", ":", "if", "layer_collection", "is", "not", "None", ":", "assert", "norm_type", "==", "\"layer\"", "if", "norm_type", "==", "\"layer\"",...
272500b6efe353aeb638d2745ed56e519462ca31
train
zero_add
Resnet connection with zero initialization. Another type of resnet connection which returns previous_value + gamma * x. gamma is a trainable scalar and initialized with zero. It is useful when a module is plugged into a trained model and we want to make sure it matches the original model's performance. Args...
tensor2tensor/layers/common_layers.py
def zero_add(previous_value, x, name=None, reuse=None): """Resnet connection with zero initialization. Another type of resnet connection which returns previous_value + gamma * x. gamma is a trainable scalar and initialized with zero. It is useful when a module is plugged into a trained model and we want to mak...
def zero_add(previous_value, x, name=None, reuse=None): """Resnet connection with zero initialization. Another type of resnet connection which returns previous_value + gamma * x. gamma is a trainable scalar and initialized with zero. It is useful when a module is plugged into a trained model and we want to mak...
[ "Resnet", "connection", "with", "zero", "initialization", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L802-L821
[ "def", "zero_add", "(", "previous_value", ",", "x", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"zero_add\"", ",", "reuse", "=", "reuse", ")", ":", "gamma"...
272500b6efe353aeb638d2745ed56e519462ca31
train
layer_prepostprocess
Apply a sequence of functions to the input or output of a layer. The sequence is specified as a string which may contain the following characters: a: add previous_value n: apply normalization d: apply dropout z: zero add For example, if sequence=="dna", then the output is previous_value + no...
tensor2tensor/layers/common_layers.py
def layer_prepostprocess(previous_value, x, sequence, dropout_rate, norm_type, depth, epsilon, default_name, name=None, ...
def layer_prepostprocess(previous_value, x, sequence, dropout_rate, norm_type, depth, epsilon, default_name, name=None, ...
[ "Apply", "a", "sequence", "of", "functions", "to", "the", "input", "or", "output", "of", "a", "layer", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L824-L881
[ "def", "layer_prepostprocess", "(", "previous_value", ",", "x", ",", "sequence", ",", "dropout_rate", ",", "norm_type", ",", "depth", ",", "epsilon", ",", "default_name", ",", "name", "=", "None", ",", "dropout_broadcast_dims", "=", "None", ",", "layer_collectio...
272500b6efe353aeb638d2745ed56e519462ca31
train
layer_preprocess
Apply layer preprocessing. See layer_prepostprocess() for details. A hyperparameters object is passed for convenience. The hyperparameters that may be used are: layer_preprocess_sequence layer_prepostprocess_dropout norm_type hidden_size norm_epsilon Args: layer_input: a Tensor ...
tensor2tensor/layers/common_layers.py
def layer_preprocess(layer_input, hparams, layer_collection=None): """Apply layer preprocessing. See layer_prepostprocess() for details. A hyperparameters object is passed for convenience. The hyperparameters that may be used are: layer_preprocess_sequence layer_prepostprocess_dropout norm_type ...
def layer_preprocess(layer_input, hparams, layer_collection=None): """Apply layer preprocessing. See layer_prepostprocess() for details. A hyperparameters object is passed for convenience. The hyperparameters that may be used are: layer_preprocess_sequence layer_prepostprocess_dropout norm_type ...
[ "Apply", "layer", "preprocessing", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L884-L922
[ "def", "layer_preprocess", "(", "layer_input", ",", "hparams", ",", "layer_collection", "=", "None", ")", ":", "assert", "\"a\"", "not", "in", "hparams", ".", "layer_preprocess_sequence", ",", "(", "\"No residual connections allowed in hparams.layer_preprocess_sequence\"", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
layer_postprocess
Apply layer postprocessing. See layer_prepostprocess() for details. A hyperparameters object is passed for convenience. The hyperparameters that may be used are: layer_postprocess_sequence layer_prepostprocess_dropout norm_type hidden_size norm_epsilon Args: layer_input: a Tensor ...
tensor2tensor/layers/common_layers.py
def layer_postprocess(layer_input, layer_output, hparams): """Apply layer postprocessing. See layer_prepostprocess() for details. A hyperparameters object is passed for convenience. The hyperparameters that may be used are: layer_postprocess_sequence layer_prepostprocess_dropout norm_type hi...
def layer_postprocess(layer_input, layer_output, hparams): """Apply layer postprocessing. See layer_prepostprocess() for details. A hyperparameters object is passed for convenience. The hyperparameters that may be used are: layer_postprocess_sequence layer_prepostprocess_dropout norm_type hi...
[ "Apply", "layer", "postprocessing", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L925-L957
[ "def", "layer_postprocess", "(", "layer_input", ",", "layer_output", ",", "hparams", ")", ":", "return", "layer_prepostprocess", "(", "layer_input", ",", "layer_output", ",", "sequence", "=", "hparams", ".", "layer_postprocess_sequence", ",", "dropout_rate", "=", "h...
272500b6efe353aeb638d2745ed56e519462ca31
train
conv_block_internal
A block of convolutions. Args: conv_fn: convolution function, e.g. conv or separable_conv. inputs: a Tensor filters: an Integer dilation_rates_and_kernel_sizes: a list of tuples (dilation, (k_w, k_h)) first_relu: whether to do a relu at start (defaults to True) use_elu: whether to use ELUs in...
tensor2tensor/layers/common_layers.py
def conv_block_internal(conv_fn, inputs, filters, dilation_rates_and_kernel_sizes, first_relu=True, use_elu=False, separabilities=None, **kwargs): """...
def conv_block_internal(conv_fn, inputs, filters, dilation_rates_and_kernel_sizes, first_relu=True, use_elu=False, separabilities=None, **kwargs): """...
[ "A", "block", "of", "convolutions", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L960-L1028
[ "def", "conv_block_internal", "(", "conv_fn", ",", "inputs", ",", "filters", ",", "dilation_rates_and_kernel_sizes", ",", "first_relu", "=", "True", ",", "use_elu", "=", "False", ",", "separabilities", "=", "None", ",", "*", "*", "kwargs", ")", ":", "name", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
conv_block
A block of standard 2d convolutions.
tensor2tensor/layers/common_layers.py
def conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs): """A block of standard 2d convolutions.""" return conv_block_internal(conv, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)
def conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs): """A block of standard 2d convolutions.""" return conv_block_internal(conv, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)
[ "A", "block", "of", "standard", "2d", "convolutions", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1031-L1034
[ "def", "conv_block", "(", "inputs", ",", "filters", ",", "dilation_rates_and_kernel_sizes", ",", "*", "*", "kwargs", ")", ":", "return", "conv_block_internal", "(", "conv", ",", "inputs", ",", "filters", ",", "dilation_rates_and_kernel_sizes", ",", "*", "*", "kw...
272500b6efe353aeb638d2745ed56e519462ca31
train
conv1d_block
A block of standard 1d convolutions.
tensor2tensor/layers/common_layers.py
def conv1d_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs): """A block of standard 1d convolutions.""" return conv_block_internal(conv1d, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)
def conv1d_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs): """A block of standard 1d convolutions.""" return conv_block_internal(conv1d, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)
[ "A", "block", "of", "standard", "1d", "convolutions", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1037-L1040
[ "def", "conv1d_block", "(", "inputs", ",", "filters", ",", "dilation_rates_and_kernel_sizes", ",", "*", "*", "kwargs", ")", ":", "return", "conv_block_internal", "(", "conv1d", ",", "inputs", ",", "filters", ",", "dilation_rates_and_kernel_sizes", ",", "*", "*", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
separable_conv_block
A block of separable convolutions.
tensor2tensor/layers/common_layers.py
def separable_conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs): """A block of separable convolutions.""" return conv_block_internal(separable_conv, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)
def separable_conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs): """A block of separable convolutions.""" return conv_block_internal(separable_conv, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)
[ "A", "block", "of", "separable", "convolutions", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1043-L1047
[ "def", "separable_conv_block", "(", "inputs", ",", "filters", ",", "dilation_rates_and_kernel_sizes", ",", "*", "*", "kwargs", ")", ":", "return", "conv_block_internal", "(", "separable_conv", ",", "inputs", ",", "filters", ",", "dilation_rates_and_kernel_sizes", ",",...
272500b6efe353aeb638d2745ed56e519462ca31
train
subseparable_conv_block
A block of separable convolutions.
tensor2tensor/layers/common_layers.py
def subseparable_conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs): """A block of separable convolutions.""" return conv_block_internal(subseparable_conv, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)
def subseparable_conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs): """A block of separable convolutions.""" return conv_block_internal(subseparable_conv, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)
[ "A", "block", "of", "separable", "convolutions", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1050-L1054
[ "def", "subseparable_conv_block", "(", "inputs", ",", "filters", ",", "dilation_rates_and_kernel_sizes", ",", "*", "*", "kwargs", ")", ":", "return", "conv_block_internal", "(", "subseparable_conv", ",", "inputs", ",", "filters", ",", "dilation_rates_and_kernel_sizes", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
pool
Pooling (supports "LEFT").
tensor2tensor/layers/common_layers.py
def pool(inputs, window_size, pooling_type, padding, strides=(1, 1)): """Pooling (supports "LEFT").""" with tf.name_scope("pool", values=[inputs]): static_shape = inputs.get_shape() if not static_shape or len(static_shape) != 4: raise ValueError("Inputs to conv must have statically known rank 4.") ...
def pool(inputs, window_size, pooling_type, padding, strides=(1, 1)): """Pooling (supports "LEFT").""" with tf.name_scope("pool", values=[inputs]): static_shape = inputs.get_shape() if not static_shape or len(static_shape) != 4: raise ValueError("Inputs to conv must have statically known rank 4.") ...
[ "Pooling", "(", "supports", "LEFT", ")", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1057-L1080
[ "def", "pool", "(", "inputs", ",", "window_size", ",", "pooling_type", ",", "padding", ",", "strides", "=", "(", "1", ",", "1", ")", ")", ":", "with", "tf", ".", "name_scope", "(", "\"pool\"", ",", "values", "=", "[", "inputs", "]", ")", ":", "stat...
272500b6efe353aeb638d2745ed56e519462ca31
train
conv_block_downsample
Implements a downwards-striding conv block, like Xception exit flow.
tensor2tensor/layers/common_layers.py
def conv_block_downsample(x, kernel, strides, padding, separability=0, name=None, reuse=None): """Implements a downwards-striding conv block, like Xception exit f...
def conv_block_downsample(x, kernel, strides, padding, separability=0, name=None, reuse=None): """Implements a downwards-striding conv block, like Xception exit f...
[ "Implements", "a", "downwards", "-", "striding", "conv", "block", "like", "Xception", "exit", "flow", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1083-L1130
[ "def", "conv_block_downsample", "(", "x", ",", "kernel", ",", "strides", ",", "padding", ",", "separability", "=", "0", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_timing_signal
Create Tensor of sinusoids of different frequencies. Args: length: Length of the Tensor to create, i.e. Number of steps. min_timescale: a float max_timescale: a float num_timescales: an int Returns: Tensor of shape (length, 2*num_timescales)
tensor2tensor/layers/common_layers.py
def get_timing_signal(length, min_timescale=1, max_timescale=1e4, num_timescales=16): """Create Tensor of sinusoids of different frequencies. Args: length: Length of the Tensor to create, i.e. Number of steps. min_timescale: a float max_...
def get_timing_signal(length, min_timescale=1, max_timescale=1e4, num_timescales=16): """Create Tensor of sinusoids of different frequencies. Args: length: Length of the Tensor to create, i.e. Number of steps. min_timescale: a float max_...
[ "Create", "Tensor", "of", "sinusoids", "of", "different", "frequencies", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1133-L1154
[ "def", "get_timing_signal", "(", "length", ",", "min_timescale", "=", "1", ",", "max_timescale", "=", "1e4", ",", "num_timescales", "=", "16", ")", ":", "positions", "=", "to_float", "(", "tf", ".", "range", "(", "length", ")", ")", "log_timescale_increment"...
272500b6efe353aeb638d2745ed56e519462ca31
train
add_timing_signal
Adds a bunch of sinusoids of different frequencies to a Tensor. This allows attention to learn to use absolute and relative positions. The timing signal should be added to some precursor of both the source and the target of the attention. The use of relative position is possible because sin(x+y) and cos(x+y) ...
tensor2tensor/layers/common_layers.py
def add_timing_signal(x, min_timescale=1, max_timescale=1e4, num_timescales=16): """Adds a bunch of sinusoids of different frequencies to a Tensor. This allows attention to learn to use absolute and relative positions. The timing signal should be added to some precursor of both the source and the target of the...
def add_timing_signal(x, min_timescale=1, max_timescale=1e4, num_timescales=16): """Adds a bunch of sinusoids of different frequencies to a Tensor. This allows attention to learn to use absolute and relative positions. The timing signal should be added to some precursor of both the source and the target of the...
[ "Adds", "a", "bunch", "of", "sinusoids", "of", "different", "frequencies", "to", "a", "Tensor", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1157-L1188
[ "def", "add_timing_signal", "(", "x", ",", "min_timescale", "=", "1", ",", "max_timescale", "=", "1e4", ",", "num_timescales", "=", "16", ")", ":", "length", "=", "shape_list", "(", "x", ")", "[", "1", "]", "depth", "=", "shape_list", "(", "x", ")", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
mask_from_embedding
Input embeddings -> padding mask. We have hacked symbol_modality to return all-zero embeddings for padding. Returns a mask with 0.0 in the padding positions and 1.0 elsewhere. Args: emb: a Tensor with shape [batch, width, height, depth]. Returns: a 0.0/1.0 Tensor with shape [batch, width, height, 1].
tensor2tensor/layers/common_layers.py
def mask_from_embedding(emb): """Input embeddings -> padding mask. We have hacked symbol_modality to return all-zero embeddings for padding. Returns a mask with 0.0 in the padding positions and 1.0 elsewhere. Args: emb: a Tensor with shape [batch, width, height, depth]. Returns: a 0.0/1.0 Tensor wit...
def mask_from_embedding(emb): """Input embeddings -> padding mask. We have hacked symbol_modality to return all-zero embeddings for padding. Returns a mask with 0.0 in the padding positions and 1.0 elsewhere. Args: emb: a Tensor with shape [batch, width, height, depth]. Returns: a 0.0/1.0 Tensor wit...
[ "Input", "embeddings", "-", ">", "padding", "mask", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1191-L1202
[ "def", "mask_from_embedding", "(", "emb", ")", ":", "return", "weights_nonzero", "(", "tf", ".", "reduce_sum", "(", "tf", ".", "abs", "(", "emb", ")", ",", "axis", "=", "3", ",", "keepdims", "=", "True", ")", ")" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
length_from_embedding
Compute the length of each sequence in the batch. Args: emb: a sequence embedding Tensor with shape [batch, max_time, 1, depth]. Returns: a Tensor with shape [batch].
tensor2tensor/layers/common_layers.py
def length_from_embedding(emb): """Compute the length of each sequence in the batch. Args: emb: a sequence embedding Tensor with shape [batch, max_time, 1, depth]. Returns: a Tensor with shape [batch]. """ return tf.cast(tf.reduce_sum(mask_from_embedding(emb), [1, 2, 3]), tf.int32)
def length_from_embedding(emb): """Compute the length of each sequence in the batch. Args: emb: a sequence embedding Tensor with shape [batch, max_time, 1, depth]. Returns: a Tensor with shape [batch]. """ return tf.cast(tf.reduce_sum(mask_from_embedding(emb), [1, 2, 3]), tf.int32)
[ "Compute", "the", "length", "of", "each", "sequence", "in", "the", "batch", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1205-L1213
[ "def", "length_from_embedding", "(", "emb", ")", ":", "return", "tf", ".", "cast", "(", "tf", ".", "reduce_sum", "(", "mask_from_embedding", "(", "emb", ")", ",", "[", "1", ",", "2", ",", "3", "]", ")", ",", "tf", ".", "int32", ")" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
relu_density_logit
logit(density(x)). Useful for histograms. Args: x: a Tensor, typically the output of tf.relu reduce_dims: a list of dimensions Returns: a Tensor
tensor2tensor/layers/common_layers.py
def relu_density_logit(x, reduce_dims): """logit(density(x)). Useful for histograms. Args: x: a Tensor, typically the output of tf.relu reduce_dims: a list of dimensions Returns: a Tensor """ frac = tf.reduce_mean(to_float(x > 0.0), reduce_dims) scaled = tf.log(frac + math.exp(-10)) - tf.lo...
def relu_density_logit(x, reduce_dims): """logit(density(x)). Useful for histograms. Args: x: a Tensor, typically the output of tf.relu reduce_dims: a list of dimensions Returns: a Tensor """ frac = tf.reduce_mean(to_float(x > 0.0), reduce_dims) scaled = tf.log(frac + math.exp(-10)) - tf.lo...
[ "logit", "(", "density", "(", "x", "))", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1233-L1247
[ "def", "relu_density_logit", "(", "x", ",", "reduce_dims", ")", ":", "frac", "=", "tf", ".", "reduce_mean", "(", "to_float", "(", "x", ">", "0.0", ")", ",", "reduce_dims", ")", "scaled", "=", "tf", ".", "log", "(", "frac", "+", "math", ".", "exp", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
maybe_zero_out_padding
If necessary, zero out inputs to a conv for padding positions. Args: inputs: a Tensor with shape [batch, length, ...] kernel_size: an integer or pair of integers nonpadding_mask: a Tensor with shape [batch, length] Returns: Tensor of the same shape as inputs.
tensor2tensor/layers/common_layers.py
def maybe_zero_out_padding(inputs, kernel_size, nonpadding_mask): """If necessary, zero out inputs to a conv for padding positions. Args: inputs: a Tensor with shape [batch, length, ...] kernel_size: an integer or pair of integers nonpadding_mask: a Tensor with shape [batch, length] Returns: Ten...
def maybe_zero_out_padding(inputs, kernel_size, nonpadding_mask): """If necessary, zero out inputs to a conv for padding positions. Args: inputs: a Tensor with shape [batch, length, ...] kernel_size: an integer or pair of integers nonpadding_mask: a Tensor with shape [batch, length] Returns: Ten...
[ "If", "necessary", "zero", "out", "inputs", "to", "a", "conv", "for", "padding", "positions", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1250-L1267
[ "def", "maybe_zero_out_padding", "(", "inputs", ",", "kernel_size", ",", "nonpadding_mask", ")", ":", "if", "(", "kernel_size", "!=", "1", "and", "kernel_size", "!=", "(", "1", ",", "1", ")", "and", "nonpadding_mask", "is", "not", "None", ")", ":", "while"...
272500b6efe353aeb638d2745ed56e519462ca31
train
dense_relu_dense
Hidden layer with RELU activation followed by linear projection.
tensor2tensor/layers/common_layers.py
def dense_relu_dense(inputs, filter_size, output_size, output_activation=None, dropout=0.0, dropout_broadcast_dims=None, layer_collection=None, name=None): """Hidden layer...
def dense_relu_dense(inputs, filter_size, output_size, output_activation=None, dropout=0.0, dropout_broadcast_dims=None, layer_collection=None, name=None): """Hidden layer...
[ "Hidden", "layer", "with", "RELU", "activation", "followed", "by", "linear", "projection", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1270-L1300
[ "def", "dense_relu_dense", "(", "inputs", ",", "filter_size", ",", "output_size", ",", "output_activation", "=", "None", ",", "dropout", "=", "0.0", ",", "dropout_broadcast_dims", "=", "None", ",", "layer_collection", "=", "None", ",", "name", "=", "None", ")"...
272500b6efe353aeb638d2745ed56e519462ca31
train
dense_dropconnect
Dense layer with dropconnect.
tensor2tensor/layers/common_layers.py
def dense_dropconnect(inputs, output_size, dropconnect_dropout=0.0, name="dense_dropconnect", **kwargs): """Dense layer with dropconnect.""" if dropconnect_dropout != 0.0: tf.logging.info("Applying dropconnect as the kernel...
def dense_dropconnect(inputs, output_size, dropconnect_dropout=0.0, name="dense_dropconnect", **kwargs): """Dense layer with dropconnect.""" if dropconnect_dropout != 0.0: tf.logging.info("Applying dropconnect as the kernel...
[ "Dense", "layer", "with", "dropconnect", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1303-L1315
[ "def", "dense_dropconnect", "(", "inputs", ",", "output_size", ",", "dropconnect_dropout", "=", "0.0", ",", "name", "=", "\"dense_dropconnect\"", ",", "*", "*", "kwargs", ")", ":", "if", "dropconnect_dropout", "!=", "0.0", ":", "tf", ".", "logging", ".", "in...
272500b6efe353aeb638d2745ed56e519462ca31
train
conv_relu_conv
Hidden layer with RELU activation followed by linear projection. Args: inputs: A tensor. filter_size: An integer. output_size: An integer. first_kernel_size: An integer. second_kernel_size: An integer. padding: A string. nonpadding_mask: A tensor. dropout: A float. name: A string....
tensor2tensor/layers/common_layers.py
def conv_relu_conv(inputs, filter_size, output_size, first_kernel_size=3, second_kernel_size=3, padding="SAME", nonpadding_mask=None, dropout=0.0, name=None, ...
def conv_relu_conv(inputs, filter_size, output_size, first_kernel_size=3, second_kernel_size=3, padding="SAME", nonpadding_mask=None, dropout=0.0, name=None, ...
[ "Hidden", "layer", "with", "RELU", "activation", "followed", "by", "linear", "projection", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1318-L1382
[ "def", "conv_relu_conv", "(", "inputs", ",", "filter_size", ",", "output_size", ",", "first_kernel_size", "=", "3", ",", "second_kernel_size", "=", "3", ",", "padding", "=", "\"SAME\"", ",", "nonpadding_mask", "=", "None", ",", "dropout", "=", "0.0", ",", "n...
272500b6efe353aeb638d2745ed56e519462ca31
train
sepconv_relu_sepconv
Hidden layer with RELU activation followed by linear projection.
tensor2tensor/layers/common_layers.py
def sepconv_relu_sepconv(inputs, filter_size, output_size, first_kernel_size=(1, 1), second_kernel_size=(1, 1), padding="LEFT", nonpadding_mask=None, ...
def sepconv_relu_sepconv(inputs, filter_size, output_size, first_kernel_size=(1, 1), second_kernel_size=(1, 1), padding="LEFT", nonpadding_mask=None, ...
[ "Hidden", "layer", "with", "RELU", "activation", "followed", "by", "linear", "projection", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1385-L1416
[ "def", "sepconv_relu_sepconv", "(", "inputs", ",", "filter_size", ",", "output_size", ",", "first_kernel_size", "=", "(", "1", ",", "1", ")", ",", "second_kernel_size", "=", "(", "1", ",", "1", ")", ",", "padding", "=", "\"LEFT\"", ",", "nonpadding_mask", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
conv_hidden_relu
Hidden layer with RELU activation followed by linear projection.
tensor2tensor/layers/common_layers.py
def conv_hidden_relu(inputs, hidden_size, output_size, kernel_size=(1, 1), second_kernel_size=(1, 1), dropout=0.0, **kwargs): """Hidden layer with RELU activation followed by linear projection...
def conv_hidden_relu(inputs, hidden_size, output_size, kernel_size=(1, 1), second_kernel_size=(1, 1), dropout=0.0, **kwargs): """Hidden layer with RELU activation followed by linear projection...
[ "Hidden", "layer", "with", "RELU", "activation", "followed", "by", "linear", "projection", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1420-L1449
[ "def", "conv_hidden_relu", "(", "inputs", ",", "hidden_size", ",", "output_size", ",", "kernel_size", "=", "(", "1", ",", "1", ")", ",", "second_kernel_size", "=", "(", "1", ",", "1", ")", ",", "dropout", "=", "0.0", ",", "*", "*", "kwargs", ")", ":"...
272500b6efe353aeb638d2745ed56e519462ca31
train
conv_gru
Convolutional GRU in 1 dimension.
tensor2tensor/layers/common_layers.py
def conv_gru(x, kernel_size, filters, padding="SAME", dilation_rate=(1, 1), name=None, reuse=None): """Convolutional GRU in 1 dimension.""" # Let's make a shorthand for conv call first. def do_conv(args, name, bias_start, padding): ...
def conv_gru(x, kernel_size, filters, padding="SAME", dilation_rate=(1, 1), name=None, reuse=None): """Convolutional GRU in 1 dimension.""" # Let's make a shorthand for conv call first. def do_conv(args, name, bias_start, padding): ...
[ "Convolutional", "GRU", "in", "1", "dimension", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1452-L1478
[ "def", "conv_gru", "(", "x", ",", "kernel_size", ",", "filters", ",", "padding", "=", "\"SAME\"", ",", "dilation_rate", "=", "(", "1", ",", "1", ")", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "# Let's make a shorthand for conv call fir...
272500b6efe353aeb638d2745ed56e519462ca31
train
gru_feedfwd
position-wise Feed-fwd GRU gates following the MPNN. Args: a_t: Tensor of shape [batch, length, depth] of current input h_prev: Tensor of shape [batch, length, depth] of prev input filters: an integer specifying number of dimensions of the filters name: A string Returns: h_t: [batch, length, fi...
tensor2tensor/layers/common_layers.py
def gru_feedfwd(a_t, h_prev, filters, name=None): """position-wise Feed-fwd GRU gates following the MPNN. Args: a_t: Tensor of shape [batch, length, depth] of current input h_prev: Tensor of shape [batch, length, depth] of prev input filters: an integer specifying number of dimensions of the filters ...
def gru_feedfwd(a_t, h_prev, filters, name=None): """position-wise Feed-fwd GRU gates following the MPNN. Args: a_t: Tensor of shape [batch, length, depth] of current input h_prev: Tensor of shape [batch, length, depth] of prev input filters: an integer specifying number of dimensions of the filters ...
[ "position", "-", "wise", "Feed", "-", "fwd", "GRU", "gates", "following", "the", "MPNN", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1481-L1510
[ "def", "gru_feedfwd", "(", "a_t", ",", "h_prev", ",", "filters", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"GRU\"", ",", "values", "=", "[", "a_t", ",", "h_prev", "]", ")", ":", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
conv_lstm
Convolutional LSTM in 1 dimension.
tensor2tensor/layers/common_layers.py
def conv_lstm(x, kernel_size, filters, padding="SAME", dilation_rate=(1, 1), name=None, reuse=None): """Convolutional LSTM in 1 dimension.""" with tf.variable_scope( name, default_name="conv_lstm", values=[x], reuse=reuse): ...
def conv_lstm(x, kernel_size, filters, padding="SAME", dilation_rate=(1, 1), name=None, reuse=None): """Convolutional LSTM in 1 dimension.""" with tf.variable_scope( name, default_name="conv_lstm", values=[x], reuse=reuse): ...
[ "Convolutional", "LSTM", "in", "1", "dimension", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1513-L1531
[ "def", "conv_lstm", "(", "x", ",", "kernel_size", ",", "filters", ",", "padding", "=", "\"SAME\"", ",", "dilation_rate", "=", "(", "1", ",", "1", ")", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope",...
272500b6efe353aeb638d2745ed56e519462ca31
train
diagonal_conv_gru
Diagonal Convolutional GRU as in https://arxiv.org/abs/1702.08727.
tensor2tensor/layers/common_layers.py
def diagonal_conv_gru(x, kernel_size, filters, dropout=0.0, name=None, reuse=None): """Diagonal Convolutional GRU as in https://arxiv.org/abs/1702.08727.""" # Let's make a shorthand for conv call first. ...
def diagonal_conv_gru(x, kernel_size, filters, dropout=0.0, name=None, reuse=None): """Diagonal Convolutional GRU as in https://arxiv.org/abs/1702.08727.""" # Let's make a shorthand for conv call first. ...
[ "Diagonal", "Convolutional", "GRU", "as", "in", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1702", ".", "08727", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1534-L1573
[ "def", "diagonal_conv_gru", "(", "x", ",", "kernel_size", ",", "filters", ",", "dropout", "=", "0.0", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "# Let's make a shorthand for conv call first.", "def", "do_conv", "(", "args", ",", "name", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
pad_to_same_length
Pad tensors x and y on axis 1 so that they have the same length.
tensor2tensor/layers/common_layers.py
def pad_to_same_length(x, y, final_length_divisible_by=1, axis=1): """Pad tensors x and y on axis 1 so that they have the same length.""" if axis not in [1, 2]: raise ValueError("Only axis=1 and axis=2 supported for now.") with tf.name_scope("pad_to_same_length", values=[x, y]): x_length = shape_list(x)[a...
def pad_to_same_length(x, y, final_length_divisible_by=1, axis=1): """Pad tensors x and y on axis 1 so that they have the same length.""" if axis not in [1, 2]: raise ValueError("Only axis=1 and axis=2 supported for now.") with tf.name_scope("pad_to_same_length", values=[x, y]): x_length = shape_list(x)[a...
[ "Pad", "tensors", "x", "and", "y", "on", "axis", "1", "so", "that", "they", "have", "the", "same", "length", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1576-L1613
[ "def", "pad_to_same_length", "(", "x", ",", "y", ",", "final_length_divisible_by", "=", "1", ",", "axis", "=", "1", ")", ":", "if", "axis", "not", "in", "[", "1", ",", "2", "]", ":", "raise", "ValueError", "(", "\"Only axis=1 and axis=2 supported for now.\""...
272500b6efe353aeb638d2745ed56e519462ca31
train
pad_with_zeros
Pad labels on the length dimension to match logits length.
tensor2tensor/layers/common_layers.py
def pad_with_zeros(logits, labels): """Pad labels on the length dimension to match logits length.""" with tf.name_scope("pad_with_zeros", values=[logits, labels]): logits, labels = pad_to_same_length(logits, labels) if len(labels.shape) == 3: # 2-d labels. logits, labels = pad_to_same_length(logits, ...
def pad_with_zeros(logits, labels): """Pad labels on the length dimension to match logits length.""" with tf.name_scope("pad_with_zeros", values=[logits, labels]): logits, labels = pad_to_same_length(logits, labels) if len(labels.shape) == 3: # 2-d labels. logits, labels = pad_to_same_length(logits, ...
[ "Pad", "labels", "on", "the", "length", "dimension", "to", "match", "logits", "length", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1616-L1622
[ "def", "pad_with_zeros", "(", "logits", ",", "labels", ")", ":", "with", "tf", ".", "name_scope", "(", "\"pad_with_zeros\"", ",", "values", "=", "[", "logits", ",", "labels", "]", ")", ":", "logits", ",", "labels", "=", "pad_to_same_length", "(", "logits",...
272500b6efe353aeb638d2745ed56e519462ca31
train
weights_prepend_inputs_to_targets
Assign weight 1.0 to only the "targets" portion of the labels. Weight 1.0 is assigned to all nonzero labels past the first zero. See prepend_mode in common_hparams.py Args: labels: A Tensor of int32s. Returns: A Tensor of floats.
tensor2tensor/layers/common_layers.py
def weights_prepend_inputs_to_targets(labels): """Assign weight 1.0 to only the "targets" portion of the labels. Weight 1.0 is assigned to all nonzero labels past the first zero. See prepend_mode in common_hparams.py Args: labels: A Tensor of int32s. Returns: A Tensor of floats. """ past_first_...
def weights_prepend_inputs_to_targets(labels): """Assign weight 1.0 to only the "targets" portion of the labels. Weight 1.0 is assigned to all nonzero labels past the first zero. See prepend_mode in common_hparams.py Args: labels: A Tensor of int32s. Returns: A Tensor of floats. """ past_first_...
[ "Assign", "weight", "1", ".", "0", "to", "only", "the", "targets", "portion", "of", "the", "labels", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1630-L1644
[ "def", "weights_prepend_inputs_to_targets", "(", "labels", ")", ":", "past_first_zero", "=", "tf", ".", "cumsum", "(", "to_float", "(", "tf", ".", "equal", "(", "labels", ",", "0", ")", ")", ",", "axis", "=", "1", ")", "nonzero", "=", "to_float", "(", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
check_nonnegative
Check that the value is nonnegative.
tensor2tensor/layers/common_layers.py
def check_nonnegative(value): """Check that the value is nonnegative.""" if isinstance(value, tf.Tensor): with tf.control_dependencies([tf.assert_greater_equal(value, 0)]): value = tf.identity(value) elif value < 0: raise ValueError("Value must be non-negative.") return value
def check_nonnegative(value): """Check that the value is nonnegative.""" if isinstance(value, tf.Tensor): with tf.control_dependencies([tf.assert_greater_equal(value, 0)]): value = tf.identity(value) elif value < 0: raise ValueError("Value must be non-negative.") return value
[ "Check", "that", "the", "value", "is", "nonnegative", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1647-L1654
[ "def", "check_nonnegative", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "tf", ".", "Tensor", ")", ":", "with", "tf", ".", "control_dependencies", "(", "[", "tf", ".", "assert_greater_equal", "(", "value", ",", "0", ")", "]", ")", ":"...
272500b6efe353aeb638d2745ed56e519462ca31
train
weights_multi_problem
Assign weight 1.0 to only the "targets" portion of the labels. Weight 1.0 is assigned to all labels past the taskid. Args: labels: A Tensor of int32s. taskid: an int32 representing the task id for a problem. Returns: A Tensor of floats. Raises: ValueError: The Task ID must be valid.
tensor2tensor/layers/common_layers.py
def weights_multi_problem(labels, taskid=-1): """Assign weight 1.0 to only the "targets" portion of the labels. Weight 1.0 is assigned to all labels past the taskid. Args: labels: A Tensor of int32s. taskid: an int32 representing the task id for a problem. Returns: A Tensor of floats. Raises: ...
def weights_multi_problem(labels, taskid=-1): """Assign weight 1.0 to only the "targets" portion of the labels. Weight 1.0 is assigned to all labels past the taskid. Args: labels: A Tensor of int32s. taskid: an int32 representing the task id for a problem. Returns: A Tensor of floats. Raises: ...
[ "Assign", "weight", "1", ".", "0", "to", "only", "the", "targets", "portion", "of", "the", "labels", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1657-L1677
[ "def", "weights_multi_problem", "(", "labels", ",", "taskid", "=", "-", "1", ")", ":", "taskid", "=", "check_nonnegative", "(", "taskid", ")", "past_taskid", "=", "tf", ".", "cumsum", "(", "to_float", "(", "tf", ".", "equal", "(", "labels", ",", "taskid"...
272500b6efe353aeb638d2745ed56e519462ca31
train
weights_multi_problem_all
Assign weight 1.0 to only examples from the given task.
tensor2tensor/layers/common_layers.py
def weights_multi_problem_all(labels, taskid=-1): """Assign weight 1.0 to only examples from the given task.""" taskid = check_nonnegative(taskid) weights = to_float(tf.not_equal(labels, 0)) past_taskid = tf.cumsum(to_float(tf.equal(labels, taskid)), axis=1) # Additionally zero out the task id location past...
def weights_multi_problem_all(labels, taskid=-1): """Assign weight 1.0 to only examples from the given task.""" taskid = check_nonnegative(taskid) weights = to_float(tf.not_equal(labels, 0)) past_taskid = tf.cumsum(to_float(tf.equal(labels, taskid)), axis=1) # Additionally zero out the task id location past...
[ "Assign", "weight", "1", ".", "0", "to", "only", "examples", "from", "the", "given", "task", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1680-L1693
[ "def", "weights_multi_problem_all", "(", "labels", ",", "taskid", "=", "-", "1", ")", ":", "taskid", "=", "check_nonnegative", "(", "taskid", ")", "weights", "=", "to_float", "(", "tf", ".", "not_equal", "(", "labels", ",", "0", ")", ")", "past_taskid", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
weights_multi_problem_input
Assign weight 1.0 to only the inputs for the given task.
tensor2tensor/layers/common_layers.py
def weights_multi_problem_input(labels, taskid=-1): """Assign weight 1.0 to only the inputs for the given task.""" taskid = check_nonnegative(taskid) weights_all_tokens = weights_multi_problem_all(labels, taskid) weights_target = weights_multi_problem(labels, taskid) return weights_all_tokens - weights_target
def weights_multi_problem_input(labels, taskid=-1): """Assign weight 1.0 to only the inputs for the given task.""" taskid = check_nonnegative(taskid) weights_all_tokens = weights_multi_problem_all(labels, taskid) weights_target = weights_multi_problem(labels, taskid) return weights_all_tokens - weights_target
[ "Assign", "weight", "1", ".", "0", "to", "only", "the", "inputs", "for", "the", "given", "task", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1696-L1701
[ "def", "weights_multi_problem_input", "(", "labels", ",", "taskid", "=", "-", "1", ")", ":", "taskid", "=", "check_nonnegative", "(", "taskid", ")", "weights_all_tokens", "=", "weights_multi_problem_all", "(", "labels", ",", "taskid", ")", "weights_target", "=", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
weights_concatenated
Assign weight 1.0 to the "target" part of the concatenated labels. The labels look like: source English I love you . ID1 target French Je t'aime . ID1 source English the cat ID1 target French le chat ID1 source English ... We want to assign weight 1.0 to all words in the target text (including the ID1...
tensor2tensor/layers/common_layers.py
def weights_concatenated(labels): """Assign weight 1.0 to the "target" part of the concatenated labels. The labels look like: source English I love you . ID1 target French Je t'aime . ID1 source English the cat ID1 target French le chat ID1 source English ... We want to assign weight 1.0 to all words ...
def weights_concatenated(labels): """Assign weight 1.0 to the "target" part of the concatenated labels. The labels look like: source English I love you . ID1 target French Je t'aime . ID1 source English the cat ID1 target French le chat ID1 source English ... We want to assign weight 1.0 to all words ...
[ "Assign", "weight", "1", ".", "0", "to", "the", "target", "part", "of", "the", "concatenated", "labels", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1709-L1735
[ "def", "weights_concatenated", "(", "labels", ")", ":", "eos_mask", "=", "tf", ".", "to_int32", "(", "tf", ".", "equal", "(", "labels", ",", "1", ")", ")", "sentence_num", "=", "tf", ".", "cumsum", "(", "eos_mask", ",", "axis", "=", "1", ",", "exclus...
272500b6efe353aeb638d2745ed56e519462ca31
train
padded_cross_entropy
Compute cross-entropy assuming 0s are padding. Computes a loss numerator (the sum of losses), and loss denominator (the number of non-padding tokens). Args: logits: a `Tensor` with shape `[batch, timesteps, vocab_size]`. optionally a FactoredTensor. labels: an integer `Tensor` with shape `[batch, ...
tensor2tensor/layers/common_layers.py
def padded_cross_entropy(logits, labels, label_smoothing, weights_fn=weights_nonzero, reduce_sum=True, cutoff=0.0, gaussian=False): """Compute cross-entropy assuming 0s...
def padded_cross_entropy(logits, labels, label_smoothing, weights_fn=weights_nonzero, reduce_sum=True, cutoff=0.0, gaussian=False): """Compute cross-entropy assuming 0s...
[ "Compute", "cross", "-", "entropy", "assuming", "0s", "are", "padding", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1738-L1800
[ "def", "padded_cross_entropy", "(", "logits", ",", "labels", ",", "label_smoothing", ",", "weights_fn", "=", "weights_nonzero", ",", "reduce_sum", "=", "True", ",", "cutoff", "=", "0.0", ",", "gaussian", "=", "False", ")", ":", "if", "isinstance", "(", "logi...
272500b6efe353aeb638d2745ed56e519462ca31
train
padded_cross_entropy_mixture
Compute cross-entropy assuming 0s are padding. Computes a loss numerator (the sum of losses), and loss denominator (the number of non-padding tokens). Computes cross-entropy for each mixture, and returns the corresponding values for the mixture with the highest probability Args: logits: `Tensor` with s...
tensor2tensor/layers/common_layers.py
def padded_cross_entropy_mixture(logits, labels, label_smoothing, num_mixtures, weights_fn=weights_nonzero, reduce_sum=False, ...
def padded_cross_entropy_mixture(logits, labels, label_smoothing, num_mixtures, weights_fn=weights_nonzero, reduce_sum=False, ...
[ "Compute", "cross", "-", "entropy", "assuming", "0s", "are", "padding", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1803-L1897
[ "def", "padded_cross_entropy_mixture", "(", "logits", ",", "labels", ",", "label_smoothing", ",", "num_mixtures", ",", "weights_fn", "=", "weights_nonzero", ",", "reduce_sum", "=", "False", ",", "cutoff", "=", "0.0", ",", "gaussian", "=", "False", ",", "return_b...
272500b6efe353aeb638d2745ed56e519462ca31
train
dml_loss
Discretized mixture of logistics loss. Args: pred: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (one per channel), and three coefficients which linearly parameterize dependen...
tensor2tensor/layers/common_layers.py
def dml_loss(pred, labels, weights_fn=_weights_one_third, reduce_sum=True): """Discretized mixture of logistics loss. Args: pred: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (on...
def dml_loss(pred, labels, weights_fn=_weights_one_third, reduce_sum=True): """Discretized mixture of logistics loss. Args: pred: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (on...
[ "Discretized", "mixture", "of", "logistics", "loss", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1905-L1934
[ "def", "dml_loss", "(", "pred", ",", "labels", ",", "weights_fn", "=", "_weights_one_third", ",", "reduce_sum", "=", "True", ")", ":", "real_labels", "=", "convert_rgb_to_symmetric_real", "(", "labels", ")", "dml_loss_value", "=", "discretized_mix_logistic_loss", "(...
272500b6efe353aeb638d2745ed56e519462ca31
train
split_to_discretized_mix_logistic_params
Splits input tensor into parameters of discretized mixture logistic. Args: inputs: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (one per channel), and three coefficients whic...
tensor2tensor/layers/common_layers.py
def split_to_discretized_mix_logistic_params(inputs): """Splits input tensor into parameters of discretized mixture logistic. Args: inputs: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard devi...
def split_to_discretized_mix_logistic_params(inputs): """Splits input tensor into parameters of discretized mixture logistic. Args: inputs: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard devi...
[ "Splits", "input", "tensor", "into", "parameters", "of", "discretized", "mixture", "logistic", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1937-L1967
[ "def", "split_to_discretized_mix_logistic_params", "(", "inputs", ")", ":", "batch", ",", "height", ",", "width", ",", "output_dim", "=", "shape_list", "(", "inputs", ")", "# pylint: disable=unbalanced-tuple-unpacking", "num_mixtures", "=", "output_dim", "//", "10", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
discretized_mix_logistic_loss
Computes negative log probability for the discretized mixture of logistics. The distribution of a whole pixel is a mixture of 3-dimensional discretized logistic distributions. The 3-D discretized logistic factorizes as 3 1-D discretized logistic distributions, one for each channel. It defines ```none P(X = ...
tensor2tensor/layers/common_layers.py
def discretized_mix_logistic_loss(pred, labels): """Computes negative log probability for the discretized mixture of logistics. The distribution of a whole pixel is a mixture of 3-dimensional discretized logistic distributions. The 3-D discretized logistic factorizes as 3 1-D discretized logistic distributions...
def discretized_mix_logistic_loss(pred, labels): """Computes negative log probability for the discretized mixture of logistics. The distribution of a whole pixel is a mixture of 3-dimensional discretized logistic distributions. The 3-D discretized logistic factorizes as 3 1-D discretized logistic distributions...
[ "Computes", "negative", "log", "probability", "for", "the", "discretized", "mixture", "of", "logistics", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1970-L2051
[ "def", "discretized_mix_logistic_loss", "(", "pred", ",", "labels", ")", ":", "logits", ",", "locs", ",", "log_scales", ",", "coeffs", "=", "split_to_discretized_mix_logistic_params", "(", "pred", ")", "# Tile labels to broadcast compute across the mixture dimension.", "bat...
272500b6efe353aeb638d2745ed56e519462ca31
train
sample_from_discretized_mix_logistic
Sampling from a discretized mixture of logistics. Args: pred: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (one per channel), and three coefficients which linearly parameteri...
tensor2tensor/layers/common_layers.py
def sample_from_discretized_mix_logistic(pred, seed=None): """Sampling from a discretized mixture of logistics. Args: pred: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (one per ...
def sample_from_discretized_mix_logistic(pred, seed=None): """Sampling from a discretized mixture of logistics. Args: pred: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (one per ...
[ "Sampling", "from", "a", "discretized", "mixture", "of", "logistics", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2054-L2100
[ "def", "sample_from_discretized_mix_logistic", "(", "pred", ",", "seed", "=", "None", ")", ":", "logits", ",", "locs", ",", "log_scales", ",", "coeffs", "=", "split_to_discretized_mix_logistic_params", "(", "pred", ")", "# Sample mixture indicator given logits using the g...
272500b6efe353aeb638d2745ed56e519462ca31
train
smoothing_cross_entropy
Cross entropy with label smoothing to limit over-confidence. Args: logits: Tensor of shape [batch_size, ?, ?, ?, vocab_size]. labels: Tensor of shape [batch_size, ?, ?, ?]. vocab_size: Tensor representing the size of the vocabulary. confidence: Used to determine on and off values for label smoothing....
tensor2tensor/layers/common_layers.py
def smoothing_cross_entropy(logits, labels, vocab_size, confidence, gaussian=False): """Cross entropy with label smoothing to limit over-confidence. Args: logits: Tensor of shape [batch_size, ?, ?, ?...
def smoothing_cross_entropy(logits, labels, vocab_size, confidence, gaussian=False): """Cross entropy with label smoothing to limit over-confidence. Args: logits: Tensor of shape [batch_size, ?, ?, ?...
[ "Cross", "entropy", "with", "label", "smoothing", "to", "limit", "over", "-", "confidence", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2103-L2149
[ "def", "smoothing_cross_entropy", "(", "logits", ",", "labels", ",", "vocab_size", ",", "confidence", ",", "gaussian", "=", "False", ")", ":", "with", "tf", ".", "name_scope", "(", "\"smoothing_cross_entropy\"", ",", "values", "=", "[", "logits", ",", "labels"...
272500b6efe353aeb638d2745ed56e519462ca31
train
global_pool_1d
Pool elements across the last dimension. Useful to convert a list of vectors into a single vector so as to get a representation of a set. Args: inputs: A tensor of shape [batch_size, sequence_length, input_dims] containing the sequences of input vectors. pooling_type: the pooling type to use, MAX ...
tensor2tensor/layers/common_layers.py
def global_pool_1d(inputs, pooling_type="MAX", mask=None): """Pool elements across the last dimension. Useful to convert a list of vectors into a single vector so as to get a representation of a set. Args: inputs: A tensor of shape [batch_size, sequence_length, input_dims] containing the sequences o...
def global_pool_1d(inputs, pooling_type="MAX", mask=None): """Pool elements across the last dimension. Useful to convert a list of vectors into a single vector so as to get a representation of a set. Args: inputs: A tensor of shape [batch_size, sequence_length, input_dims] containing the sequences o...
[ "Pool", "elements", "across", "the", "last", "dimension", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2152-L2186
[ "def", "global_pool_1d", "(", "inputs", ",", "pooling_type", "=", "\"MAX\"", ",", "mask", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "\"global_pool\"", ",", "values", "=", "[", "inputs", "]", ")", ":", "if", "mask", "is", "not", "None...
272500b6efe353aeb638d2745ed56e519462ca31
train
running_global_pool_1d
Same global pool, but only for the elements up to the current element. Useful for outputs where the state of future elements is not known. Takes no mask as all elements up to the current element are assumed to exist. Currently only supports maximum. Equivalent to using a lower triangle bias. Args: inputs:...
tensor2tensor/layers/common_layers.py
def running_global_pool_1d(inputs, pooling_type="MAX"): """Same global pool, but only for the elements up to the current element. Useful for outputs where the state of future elements is not known. Takes no mask as all elements up to the current element are assumed to exist. Currently only supports maximum. Eq...
def running_global_pool_1d(inputs, pooling_type="MAX"): """Same global pool, but only for the elements up to the current element. Useful for outputs where the state of future elements is not known. Takes no mask as all elements up to the current element are assumed to exist. Currently only supports maximum. Eq...
[ "Same", "global", "pool", "but", "only", "for", "the", "elements", "up", "to", "the", "current", "element", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2189-L2214
[ "def", "running_global_pool_1d", "(", "inputs", ",", "pooling_type", "=", "\"MAX\"", ")", ":", "del", "pooling_type", "with", "tf", ".", "name_scope", "(", "\"running_global_pool\"", ",", "values", "=", "[", "inputs", "]", ")", ":", "scan_fct", "=", "tf", "....
272500b6efe353aeb638d2745ed56e519462ca31
train
gated_linear_unit_layer
Gated linear unit layer. Paper: Language Modeling with Gated Convolutional Networks. Link: https://arxiv.org/abs/1612.08083 x = Wx * sigmoid(W'x). Args: x: A tensor name: A string Returns: A tensor of the same shape as x.
tensor2tensor/layers/common_layers.py
def gated_linear_unit_layer(x, name=None): """Gated linear unit layer. Paper: Language Modeling with Gated Convolutional Networks. Link: https://arxiv.org/abs/1612.08083 x = Wx * sigmoid(W'x). Args: x: A tensor name: A string Returns: A tensor of the same shape as x. """ with tf.variable_...
def gated_linear_unit_layer(x, name=None): """Gated linear unit layer. Paper: Language Modeling with Gated Convolutional Networks. Link: https://arxiv.org/abs/1612.08083 x = Wx * sigmoid(W'x). Args: x: A tensor name: A string Returns: A tensor of the same shape as x. """ with tf.variable_...
[ "Gated", "linear", "unit", "layer", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2217-L2235
[ "def", "gated_linear_unit_layer", "(", "x", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"glu_layer\"", ",", "values", "=", "[", "x", "]", ")", ":", "depth", "=", "shape_list", "(", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
sru_with_scan
SRU cell as in https://arxiv.org/abs/1709.02755. This implementation uses tf.scan and can incur overhead, see the full SRU function doc for details and an implementation that is sometimes faster. Args: x: A tensor of shape [batch, ..., channels] ; ... is treated as time. num_layers: How many SRU layers;...
tensor2tensor/layers/common_layers.py
def sru_with_scan(x, num_layers=2, activation=None, initial_state=None, name=None, reuse=None): """SRU cell as in https://arxiv.org/abs/1709.02755. This implementation uses tf.scan and can incur overhead, see the full SRU f...
def sru_with_scan(x, num_layers=2, activation=None, initial_state=None, name=None, reuse=None): """SRU cell as in https://arxiv.org/abs/1709.02755. This implementation uses tf.scan and can incur overhead, see the full SRU f...
[ "SRU", "cell", "as", "in", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1709", ".", "02755", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2238-L2298
[ "def", "sru_with_scan", "(", "x", ",", "num_layers", "=", "2", ",", "activation", "=", "None", ",", "initial_state", "=", "None", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "if", "num_layers", "<", "1", ":", "raise", "ValueError", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
sru
SRU cell as in https://arxiv.org/abs/1709.02755. As defined in the paper: (1) x'_t = W x_t (2) f_t = sigmoid(Wf x_t + bf) (3) r_t = sigmoid(Wr x_t + br) (4) c_t = f_t * c_{t-1} + (1 - f_t) * x'_t (5) h_t = r_t * activation(c_t) + (1 - r_t) * x_t This version uses functional ops to be faster on GPUs with...
tensor2tensor/layers/common_layers.py
def sru(x, num_layers=2, activation=None, initial_state=None, name=None, reuse=None): """SRU cell as in https://arxiv.org/abs/1709.02755. As defined in the paper: (1) x'_t = W x_t (2) f_t = sigmoid(Wf x_t + bf) (3) r_t = sigmoid(Wr x_t + br) (4) c_t = f_t * c_{t-1} +...
def sru(x, num_layers=2, activation=None, initial_state=None, name=None, reuse=None): """SRU cell as in https://arxiv.org/abs/1709.02755. As defined in the paper: (1) x'_t = W x_t (2) f_t = sigmoid(Wf x_t + bf) (3) r_t = sigmoid(Wr x_t + br) (4) c_t = f_t * c_{t-1} +...
[ "SRU", "cell", "as", "in", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1709", ".", "02755", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2322-L2386
[ "def", "sru", "(", "x", ",", "num_layers", "=", "2", ",", "activation", "=", "None", ",", "initial_state", "=", "None", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "if", "num_layers", "<", "1", ":", "raise", "ValueError", "(", "\...
272500b6efe353aeb638d2745ed56e519462ca31
train
linear_set_layer
Basic layer type for doing funky things with sets. Applies a linear transformation to each element in the input set. If a context is supplied, it is concatenated with the inputs. e.g. One can use global_pool_1d to get a representation of the set which can then be used as the context for the next layer. ...
tensor2tensor/layers/common_layers.py
def linear_set_layer(layer_size, inputs, context=None, activation_fn=tf.nn.relu, dropout=0.0, name=None): """Basic layer type for doing funky things with sets. Applies a linear transformation to each element in...
def linear_set_layer(layer_size, inputs, context=None, activation_fn=tf.nn.relu, dropout=0.0, name=None): """Basic layer type for doing funky things with sets. Applies a linear transformation to each element in...
[ "Basic", "layer", "type", "for", "doing", "funky", "things", "with", "sets", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2389-L2440
[ "def", "linear_set_layer", "(", "layer_size", ",", "inputs", ",", "context", "=", "None", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ",", "dropout", "=", "0.0", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(",...
272500b6efe353aeb638d2745ed56e519462ca31
train
ravanbakhsh_set_layer
Layer from Deep Sets paper: https://arxiv.org/abs/1611.04500 . More parameter-efficient version of a linear-set-layer with context. Args: layer_size: Dimension to transform the input vectors to. inputs: A tensor of shape [batch_size, sequence_length, vector] containing the sequences of input vectors...
tensor2tensor/layers/common_layers.py
def ravanbakhsh_set_layer(layer_size, inputs, mask=None, sequential=False, activation_fn=tf.nn.tanh, dropout=0.0, name=None): """Layer from Deep Sets paper: https...
def ravanbakhsh_set_layer(layer_size, inputs, mask=None, sequential=False, activation_fn=tf.nn.tanh, dropout=0.0, name=None): """Layer from Deep Sets paper: https...
[ "Layer", "from", "Deep", "Sets", "paper", ":", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1611", ".", "04500", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2443-L2483
[ "def", "ravanbakhsh_set_layer", "(", "layer_size", ",", "inputs", ",", "mask", "=", "None", ",", "sequential", "=", "False", ",", "activation_fn", "=", "tf", ".", "nn", ".", "tanh", ",", "dropout", "=", "0.0", ",", "name", "=", "None", ")", ":", "del",...
272500b6efe353aeb638d2745ed56e519462ca31
train
fn_device_dependency_dict
State container for fn_device_dependency.
tensor2tensor/layers/common_layers.py
def fn_device_dependency_dict(): """State container for fn_device_dependency.""" default_graph = tf.get_default_graph() if not hasattr(default_graph, "dependency_dict"): default_graph.dependency_dict = collections.defaultdict(list) return default_graph.dependency_dict
def fn_device_dependency_dict(): """State container for fn_device_dependency.""" default_graph = tf.get_default_graph() if not hasattr(default_graph, "dependency_dict"): default_graph.dependency_dict = collections.defaultdict(list) return default_graph.dependency_dict
[ "State", "container", "for", "fn_device_dependency", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2486-L2491
[ "def", "fn_device_dependency_dict", "(", ")", ":", "default_graph", "=", "tf", ".", "get_default_graph", "(", ")", "if", "not", "hasattr", "(", "default_graph", ",", "\"dependency_dict\"", ")", ":", "default_graph", ".", "dependency_dict", "=", "collections", ".",...
272500b6efe353aeb638d2745ed56e519462ca31
train
fn_device_dependency
Add control deps for name and device.
tensor2tensor/layers/common_layers.py
def fn_device_dependency(name, device=""): """Add control deps for name and device.""" key = name + "_" + device outs = [] def body(): with tf.control_dependencies(fn_device_dependency_dict()[key]): yield outs assert outs deps = outs if isinstance(outs[0], (list, tuple)): a...
def fn_device_dependency(name, device=""): """Add control deps for name and device.""" key = name + "_" + device outs = [] def body(): with tf.control_dependencies(fn_device_dependency_dict()[key]): yield outs assert outs deps = outs if isinstance(outs[0], (list, tuple)): a...
[ "Add", "control", "deps", "for", "name", "and", "device", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2495-L2515
[ "def", "fn_device_dependency", "(", "name", ",", "device", "=", "\"\"", ")", ":", "key", "=", "name", "+", "\"_\"", "+", "device", "outs", "=", "[", "]", "def", "body", "(", ")", ":", "with", "tf", ".", "control_dependencies", "(", "fn_device_dependency_...
272500b6efe353aeb638d2745ed56e519462ca31
train
underlying_variable_ref
Find the underlying variable ref. Traverses through Identity, ReadVariableOp, and Enter ops. Stops when op type has Variable or VarHandle in name. Args: t: a Tensor Returns: a Tensor that is a variable ref, or None on error.
tensor2tensor/layers/common_layers.py
def underlying_variable_ref(t): """Find the underlying variable ref. Traverses through Identity, ReadVariableOp, and Enter ops. Stops when op type has Variable or VarHandle in name. Args: t: a Tensor Returns: a Tensor that is a variable ref, or None on error. """ while t.op.type in ["Identity",...
def underlying_variable_ref(t): """Find the underlying variable ref. Traverses through Identity, ReadVariableOp, and Enter ops. Stops when op type has Variable or VarHandle in name. Args: t: a Tensor Returns: a Tensor that is a variable ref, or None on error. """ while t.op.type in ["Identity",...
[ "Find", "the", "underlying", "variable", "ref", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2518-L2537
[ "def", "underlying_variable_ref", "(", "t", ")", ":", "while", "t", ".", "op", ".", "type", "in", "[", "\"Identity\"", ",", "\"ReadVariableOp\"", ",", "\"Enter\"", "]", ":", "t", "=", "t", ".", "op", ".", "inputs", "[", "0", "]", "op_type", "=", "t",...
272500b6efe353aeb638d2745ed56e519462ca31
train
underlying_variable
Find the underlying tf.Variable object. Args: t: a Tensor Returns: tf.Variable.
tensor2tensor/layers/common_layers.py
def underlying_variable(t): """Find the underlying tf.Variable object. Args: t: a Tensor Returns: tf.Variable. """ t = underlying_variable_ref(t) assert t is not None # make sure that the graph has a variable index and that it is up-to-date if not hasattr(tf.get_default_graph(), "var_index"): ...
def underlying_variable(t): """Find the underlying tf.Variable object. Args: t: a Tensor Returns: tf.Variable. """ t = underlying_variable_ref(t) assert t is not None # make sure that the graph has a variable index and that it is up-to-date if not hasattr(tf.get_default_graph(), "var_index"): ...
[ "Find", "the", "underlying", "tf", ".", "Variable", "object", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2540-L2557
[ "def", "underlying_variable", "(", "t", ")", ":", "t", "=", "underlying_variable_ref", "(", "t", ")", "assert", "t", "is", "not", "None", "# make sure that the graph has a variable index and that it is up-to-date", "if", "not", "hasattr", "(", "tf", ".", "get_default_...
272500b6efe353aeb638d2745ed56e519462ca31
train
approximate_split
Split approximately equally into num_splits parts. Args: x: a Tensor num_splits: an integer axis: an integer. Returns: a list of num_splits Tensors.
tensor2tensor/layers/common_layers.py
def approximate_split(x, num_splits, axis=0): """Split approximately equally into num_splits parts. Args: x: a Tensor num_splits: an integer axis: an integer. Returns: a list of num_splits Tensors. """ size = shape_list(x)[axis] size_splits = [tf.div(size + i, num_splits) for i in range(nu...
def approximate_split(x, num_splits, axis=0): """Split approximately equally into num_splits parts. Args: x: a Tensor num_splits: an integer axis: an integer. Returns: a list of num_splits Tensors. """ size = shape_list(x)[axis] size_splits = [tf.div(size + i, num_splits) for i in range(nu...
[ "Split", "approximately", "equally", "into", "num_splits", "parts", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2560-L2573
[ "def", "approximate_split", "(", "x", ",", "num_splits", ",", "axis", "=", "0", ")", ":", "size", "=", "shape_list", "(", "x", ")", "[", "axis", "]", "size_splits", "=", "[", "tf", ".", "div", "(", "size", "+", "i", ",", "num_splits", ")", "for", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
smoothing_cross_entropy_factored_grad
Gradient function for smoothing_cross_entropy_factored.
tensor2tensor/layers/common_layers.py
def smoothing_cross_entropy_factored_grad(op, dy): """Gradient function for smoothing_cross_entropy_factored.""" a = op.inputs[0] b = op.inputs[1] labels = op.inputs[2] confidence = op.inputs[3] num_splits = 16 vocab_size = shape_list(b)[0] labels = approximate_split(labels, num_splits) a = approximat...
def smoothing_cross_entropy_factored_grad(op, dy): """Gradient function for smoothing_cross_entropy_factored.""" a = op.inputs[0] b = op.inputs[1] labels = op.inputs[2] confidence = op.inputs[3] num_splits = 16 vocab_size = shape_list(b)[0] labels = approximate_split(labels, num_splits) a = approximat...
[ "Gradient", "function", "for", "smoothing_cross_entropy_factored", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2625-L2653
[ "def", "smoothing_cross_entropy_factored_grad", "(", "op", ",", "dy", ")", ":", "a", "=", "op", ".", "inputs", "[", "0", "]", "b", "=", "op", ".", "inputs", "[", "1", "]", "labels", "=", "op", ".", "inputs", "[", "2", "]", "confidence", "=", "op", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
smoothing_cross_entropy_factored
Memory-efficient computation of smoothing cross-entropy. Avoids realizing the entire logits matrix at once. Args: a: a Tensor with shape [batch, inner_dim] b: a Tensor with shape [vocab_size, inner_dim] labels: an integer Tensor with shape [batch] confidence: a float Returns: A Tensor with ...
tensor2tensor/layers/common_layers.py
def smoothing_cross_entropy_factored(a, b, labels, confidence): """Memory-efficient computation of smoothing cross-entropy. Avoids realizing the entire logits matrix at once. Args: a: a Tensor with shape [batch, inner_dim] b: a Tensor with shape [vocab_size, inner_dim] labels: an integer Tensor with...
def smoothing_cross_entropy_factored(a, b, labels, confidence): """Memory-efficient computation of smoothing cross-entropy. Avoids realizing the entire logits matrix at once. Args: a: a Tensor with shape [batch, inner_dim] b: a Tensor with shape [vocab_size, inner_dim] labels: an integer Tensor with...
[ "Memory", "-", "efficient", "computation", "of", "smoothing", "cross", "-", "entropy", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2661-L2685
[ "def", "smoothing_cross_entropy_factored", "(", "a", ",", "b", ",", "labels", ",", "confidence", ")", ":", "num_splits", "=", "16", "vocab_size", "=", "shape_list", "(", "b", ")", "[", "0", "]", "labels", "=", "approximate_split", "(", "labels", ",", "num_...
272500b6efe353aeb638d2745ed56e519462ca31
train
padded_cross_entropy_factored
Memory-efficient computation of smoothing cross-entropy. Avoids realizing the entire logits matrix at once. Args: factored_logits: a `FactoredTensor` representing a Tensor with shape `[batch, timesteps, vocab_size]`. labels: an integer `Tensor` with shape `[batch, timesteps]`. label_smoothing: ...
tensor2tensor/layers/common_layers.py
def padded_cross_entropy_factored(factored_logits, labels, label_smoothing, weights_fn=weights_nonzero, reduce_sum=True): """Memory-efficient computation of smoothing cross-entropy. ...
def padded_cross_entropy_factored(factored_logits, labels, label_smoothing, weights_fn=weights_nonzero, reduce_sum=True): """Memory-efficient computation of smoothing cross-entropy. ...
[ "Memory", "-", "efficient", "computation", "of", "smoothing", "cross", "-", "entropy", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2688-L2721
[ "def", "padded_cross_entropy_factored", "(", "factored_logits", ",", "labels", ",", "label_smoothing", ",", "weights_fn", "=", "weights_nonzero", ",", "reduce_sum", "=", "True", ")", ":", "a", "=", "factored_logits", ".", "a", "b", "=", "factored_logits", ".", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
fn_with_custom_grad
Decorator to create a subgraph with a custom gradient function. The subgraph created by the decorated function is NOT put in a Defun and so does not suffer from the limitations of the Defun (all subgraph ops on the same device, no summaries). Args: grad_fn: function with signature (inputs, variables...
tensor2tensor/layers/common_layers.py
def fn_with_custom_grad(grad_fn, use_global_vars=False): """Decorator to create a subgraph with a custom gradient function. The subgraph created by the decorated function is NOT put in a Defun and so does not suffer from the limitations of the Defun (all subgraph ops on the same device, no summaries). Args:...
def fn_with_custom_grad(grad_fn, use_global_vars=False): """Decorator to create a subgraph with a custom gradient function. The subgraph created by the decorated function is NOT put in a Defun and so does not suffer from the limitations of the Defun (all subgraph ops on the same device, no summaries). Args:...
[ "Decorator", "to", "create", "a", "subgraph", "with", "a", "custom", "gradient", "function", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2724-L2751
[ "def", "fn_with_custom_grad", "(", "grad_fn", ",", "use_global_vars", "=", "False", ")", ":", "def", "dec", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrapped", "(", "*", "args", ")", ":", "return", "_fn_with_custom_grad...
272500b6efe353aeb638d2745ed56e519462ca31
train
_fn_with_custom_grad
Create a subgraph with a custom gradient. Args: fn: function that takes inputs as arguments and produces 1 or more Tensors. inputs: list<Tensor>, will be passed as fn(*inputs). grad_fn: function with signature (inputs, vars, outputs, output_grads) -> (grad_inputs, grad_vars), all of which are...
tensor2tensor/layers/common_layers.py
def _fn_with_custom_grad(fn, inputs, grad_fn, use_global_vars=False): """Create a subgraph with a custom gradient. Args: fn: function that takes inputs as arguments and produces 1 or more Tensors. inputs: list<Tensor>, will be passed as fn(*inputs). grad_fn: function with signature (inputs, vars,...
def _fn_with_custom_grad(fn, inputs, grad_fn, use_global_vars=False): """Create a subgraph with a custom gradient. Args: fn: function that takes inputs as arguments and produces 1 or more Tensors. inputs: list<Tensor>, will be passed as fn(*inputs). grad_fn: function with signature (inputs, vars,...
[ "Create", "a", "subgraph", "with", "a", "custom", "gradient", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2754-L2817
[ "def", "_fn_with_custom_grad", "(", "fn", ",", "inputs", ",", "grad_fn", ",", "use_global_vars", "=", "False", ")", ":", "vs", "=", "tf", ".", "get_variable_scope", "(", ")", "get_vars_fn", "=", "(", "vs", ".", "global_variables", "if", "use_global_vars", "e...
272500b6efe353aeb638d2745ed56e519462ca31
train
conv_hidden_relu_memory_efficient
LayerNorm, Conv, ReLU, Conv. All convolutions have kernel size 1. returns conv(relu(conv(layer_norm(x)))) Args: x: input Tensor with shape [batch, length, io_size] filter_size: an integer - size of the hidden layer. epsilon: a float (for layer norm) forget: a boolean - forget forwards activatio...
tensor2tensor/layers/common_layers.py
def conv_hidden_relu_memory_efficient(x, filter_size, epsilon=1e-6, forget=True, test_vars=None, name=None): """LayerNorm, Conv,...
def conv_hidden_relu_memory_efficient(x, filter_size, epsilon=1e-6, forget=True, test_vars=None, name=None): """LayerNorm, Conv,...
[ "LayerNorm", "Conv", "ReLU", "Conv", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2823-L2930
[ "def", "conv_hidden_relu_memory_efficient", "(", "x", ",", "filter_size", ",", "epsilon", "=", "1e-6", ",", "forget", "=", "True", ",", "test_vars", "=", "None", ",", "name", "=", "None", ")", ":", "io_size", "=", "x", ".", "get_shape", "(", ")", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
shape_list
Return list of dims, statically where possible.
tensor2tensor/layers/common_layers.py
def shape_list(x): """Return list of dims, statically where possible.""" x = tf.convert_to_tensor(x) # If unknown rank, return dynamic shape if x.get_shape().dims is None: return tf.shape(x) static = x.get_shape().as_list() shape = tf.shape(x) ret = [] for i, dim in enumerate(static): if dim ...
def shape_list(x): """Return list of dims, statically where possible.""" x = tf.convert_to_tensor(x) # If unknown rank, return dynamic shape if x.get_shape().dims is None: return tf.shape(x) static = x.get_shape().as_list() shape = tf.shape(x) ret = [] for i, dim in enumerate(static): if dim ...
[ "Return", "list", "of", "dims", "statically", "where", "possible", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2933-L2949
[ "def", "shape_list", "(", "x", ")", ":", "x", "=", "tf", ".", "convert_to_tensor", "(", "x", ")", "# If unknown rank, return dynamic shape", "if", "x", ".", "get_shape", "(", ")", ".", "dims", "is", "None", ":", "return", "tf", ".", "shape", "(", "x", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
sample_with_temperature
Either argmax or random sampling. Args: logits: a Tensor. temperature: a float 0.0=argmax 1.0=random sampling_keep_top_k: If not -1, only sample from the top k logits. Returns: a Tensor with one fewer dimension than logits.
tensor2tensor/layers/common_layers.py
def sample_with_temperature(logits, temperature, sampling_keep_top_k=-1): """Either argmax or random sampling. Args: logits: a Tensor. temperature: a float 0.0=argmax 1.0=random sampling_keep_top_k: If not -1, only sample from the top k logits. Returns: a Tensor with one fewer dimension than log...
def sample_with_temperature(logits, temperature, sampling_keep_top_k=-1): """Either argmax or random sampling. Args: logits: a Tensor. temperature: a float 0.0=argmax 1.0=random sampling_keep_top_k: If not -1, only sample from the top k logits. Returns: a Tensor with one fewer dimension than log...
[ "Either", "argmax", "or", "random", "sampling", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2959-L2997
[ "def", "sample_with_temperature", "(", "logits", ",", "temperature", ",", "sampling_keep_top_k", "=", "-", "1", ")", ":", "if", "temperature", "==", "0.0", ":", "# TF argmax doesn't handle >5 dimensions, so we reshape here.", "logits_shape", "=", "shape_list", "(", "log...
272500b6efe353aeb638d2745ed56e519462ca31
train
ones_matrix_band_part
Matrix band part of ones. Args: rows: int determining number of rows in output cols: int num_lower: int, maximum distance backward. Negative values indicate unlimited. num_upper: int, maximum distance forward. Negative values indicate unlimited. out_shape: shape to reshape output by. ...
tensor2tensor/layers/common_layers.py
def ones_matrix_band_part(rows, cols, num_lower, num_upper, out_shape=None): """Matrix band part of ones. Args: rows: int determining number of rows in output cols: int num_lower: int, maximum distance backward. Negative values indicate unlimited. num_upper: int, maximum distance forward. Neg...
def ones_matrix_band_part(rows, cols, num_lower, num_upper, out_shape=None): """Matrix band part of ones. Args: rows: int determining number of rows in output cols: int num_lower: int, maximum distance backward. Negative values indicate unlimited. num_upper: int, maximum distance forward. Neg...
[ "Matrix", "band", "part", "of", "ones", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3000-L3034
[ "def", "ones_matrix_band_part", "(", "rows", ",", "cols", ",", "num_lower", ",", "num_upper", ",", "out_shape", "=", "None", ")", ":", "if", "all", "(", "[", "isinstance", "(", "el", ",", "int", ")", "for", "el", "in", "[", "rows", ",", "cols", ",", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
reshape_like_all_dims
Reshapes a to match the shape of b.
tensor2tensor/layers/common_layers.py
def reshape_like_all_dims(a, b): """Reshapes a to match the shape of b.""" ret = tf.reshape(a, tf.shape(b)) if not tf.executing_eagerly(): ret.set_shape(b.get_shape()) return ret
def reshape_like_all_dims(a, b): """Reshapes a to match the shape of b.""" ret = tf.reshape(a, tf.shape(b)) if not tf.executing_eagerly(): ret.set_shape(b.get_shape()) return ret
[ "Reshapes", "a", "to", "match", "the", "shape", "of", "b", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3037-L3042
[ "def", "reshape_like_all_dims", "(", "a", ",", "b", ")", ":", "ret", "=", "tf", ".", "reshape", "(", "a", ",", "tf", ".", "shape", "(", "b", ")", ")", "if", "not", "tf", ".", "executing_eagerly", "(", ")", ":", "ret", ".", "set_shape", "(", "b", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
recompute_grad
Decorator that recomputes the function on the backwards pass. Args: fn: a function that takes Tensors (all as positional arguments) and returns a tuple of Tensors. Returns: A wrapped fn that is identical to fn when called, but its activations will be discarded and recomputed on the backwards pas...
tensor2tensor/layers/common_layers.py
def recompute_grad(fn): """Decorator that recomputes the function on the backwards pass. Args: fn: a function that takes Tensors (all as positional arguments) and returns a tuple of Tensors. Returns: A wrapped fn that is identical to fn when called, but its activations will be discarded and re...
def recompute_grad(fn): """Decorator that recomputes the function on the backwards pass. Args: fn: a function that takes Tensors (all as positional arguments) and returns a tuple of Tensors. Returns: A wrapped fn that is identical to fn when called, but its activations will be discarded and re...
[ "Decorator", "that", "recomputes", "the", "function", "on", "the", "backwards", "pass", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3045-L3062
[ "def", "recompute_grad", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrapped", "(", "*", "args", ")", ":", "return", "_recompute_grad", "(", "fn", ",", "args", ")", "return", "wrapped" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
_recompute_grad
See recompute_grad.
tensor2tensor/layers/common_layers.py
def _recompute_grad(fn, args): """See recompute_grad.""" cached_vs = [] cached_arg_scope = [] def grad_fn(inputs, variables, outputs, output_grads): """Recompute outputs for gradient computation.""" del outputs variables = [underlying_variable_ref(v) for v in variables] # Recompute outputs ...
def _recompute_grad(fn, args): """See recompute_grad.""" cached_vs = [] cached_arg_scope = [] def grad_fn(inputs, variables, outputs, output_grads): """Recompute outputs for gradient computation.""" del outputs variables = [underlying_variable_ref(v) for v in variables] # Recompute outputs ...
[ "See", "recompute_grad", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3065-L3100
[ "def", "_recompute_grad", "(", "fn", ",", "args", ")", ":", "cached_vs", "=", "[", "]", "cached_arg_scope", "=", "[", "]", "def", "grad_fn", "(", "inputs", ",", "variables", ",", "outputs", ",", "output_grads", ")", ":", "\"\"\"Recompute outputs for gradient c...
272500b6efe353aeb638d2745ed56e519462ca31
train
dense
Identical to layers.dense.
tensor2tensor/layers/common_layers.py
def dense(x, units, **kwargs): """Identical to layers.dense.""" layer_collection = kwargs.pop("layer_collection", None) activations = layers().Dense(units, **kwargs)(x) if layer_collection: # We need to find the layer parameters using scope name for the layer, so # check that the layer is named. Otherwi...
def dense(x, units, **kwargs): """Identical to layers.dense.""" layer_collection = kwargs.pop("layer_collection", None) activations = layers().Dense(units, **kwargs)(x) if layer_collection: # We need to find the layer parameters using scope name for the layer, so # check that the layer is named. Otherwi...
[ "Identical", "to", "layers", ".", "dense", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3103-L3141
[ "def", "dense", "(", "x", ",", "units", ",", "*", "*", "kwargs", ")", ":", "layer_collection", "=", "kwargs", ".", "pop", "(", "\"layer_collection\"", ",", "None", ")", "activations", "=", "layers", "(", ")", ".", "Dense", "(", "units", ",", "*", "*"...
272500b6efe353aeb638d2745ed56e519462ca31
train
batch_dense
Multiply a batch of input matrices by a batch of parameter matrices. Each input matrix is multiplied by the corresponding parameter matrix. This is useful in a mixture-of-experts where the batch represents different experts with different inputs. Args: inputs: a Tensor with shape [batch, length, input_un...
tensor2tensor/layers/common_layers.py
def batch_dense(inputs, units, activation=None, kernel_initializer=None, reuse=None, name=None): """Multiply a batch of input matrices by a batch of parameter matrices. Each input matrix is multiplied by the corresponding parameter mat...
def batch_dense(inputs, units, activation=None, kernel_initializer=None, reuse=None, name=None): """Multiply a batch of input matrices by a batch of parameter matrices. Each input matrix is multiplied by the corresponding parameter mat...
[ "Multiply", "a", "batch", "of", "input", "matrices", "by", "a", "batch", "of", "parameter", "matrices", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3144-L3195
[ "def", "batch_dense", "(", "inputs", ",", "units", ",", "activation", "=", "None", ",", "kernel_initializer", "=", "None", ",", "reuse", "=", "None", ",", "name", "=", "None", ")", ":", "inputs_shape", "=", "shape_list", "(", "inputs", ")", "if", "len", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
mix
Mix starting with x2, mixing mixing, going towards x1.
tensor2tensor/layers/common_layers.py
def mix(x1, x2, steps, is_training, min_prob=0.0, max_prob=1.0, mode="lin", simple=False, broadcast_last=False): """Mix starting with x2, mixing mixing, going towards x1.""" with tf.name_scope("mix"): if not is_training: if max_prob >= 1.0: ...
def mix(x1, x2, steps, is_training, min_prob=0.0, max_prob=1.0, mode="lin", simple=False, broadcast_last=False): """Mix starting with x2, mixing mixing, going towards x1.""" with tf.name_scope("mix"): if not is_training: if max_prob >= 1.0: ...
[ "Mix", "starting", "with", "x2", "mixing", "mixing", "going", "towards", "x1", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3198-L3251
[ "def", "mix", "(", "x1", ",", "x2", ",", "steps", ",", "is_training", ",", "min_prob", "=", "0.0", ",", "max_prob", "=", "1.0", ",", "mode", "=", "\"lin\"", ",", "simple", "=", "False", ",", "broadcast_last", "=", "False", ")", ":", "with", "tf", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
brelu
Bipolar ReLU as in https://arxiv.org/abs/1709.04054.
tensor2tensor/layers/common_layers.py
def brelu(x): """Bipolar ReLU as in https://arxiv.org/abs/1709.04054.""" x_shape = shape_list(x) x1, x2 = tf.split(tf.reshape(x, x_shape[:-1] + [-1, 2]), 2, axis=-1) y1 = tf.nn.relu(x1) y2 = -tf.nn.relu(-x2) return tf.reshape(tf.concat([y1, y2], axis=-1), x_shape)
def brelu(x): """Bipolar ReLU as in https://arxiv.org/abs/1709.04054.""" x_shape = shape_list(x) x1, x2 = tf.split(tf.reshape(x, x_shape[:-1] + [-1, 2]), 2, axis=-1) y1 = tf.nn.relu(x1) y2 = -tf.nn.relu(-x2) return tf.reshape(tf.concat([y1, y2], axis=-1), x_shape)
[ "Bipolar", "ReLU", "as", "in", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1709", ".", "04054", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3254-L3260
[ "def", "brelu", "(", "x", ")", ":", "x_shape", "=", "shape_list", "(", "x", ")", "x1", ",", "x2", "=", "tf", ".", "split", "(", "tf", ".", "reshape", "(", "x", ",", "x_shape", "[", ":", "-", "1", "]", "+", "[", "-", "1", ",", "2", "]", ")...
272500b6efe353aeb638d2745ed56e519462ca31
train
belu
Bipolar ELU as in https://arxiv.org/abs/1709.04054.
tensor2tensor/layers/common_layers.py
def belu(x): """Bipolar ELU as in https://arxiv.org/abs/1709.04054.""" x_shape = shape_list(x) x1, x2 = tf.split(tf.reshape(x, x_shape[:-1] + [-1, 2]), 2, axis=-1) y1 = tf.nn.elu(x1) y2 = -tf.nn.elu(-x2) return tf.reshape(tf.concat([y1, y2], axis=-1), x_shape)
def belu(x): """Bipolar ELU as in https://arxiv.org/abs/1709.04054.""" x_shape = shape_list(x) x1, x2 = tf.split(tf.reshape(x, x_shape[:-1] + [-1, 2]), 2, axis=-1) y1 = tf.nn.elu(x1) y2 = -tf.nn.elu(-x2) return tf.reshape(tf.concat([y1, y2], axis=-1), x_shape)
[ "Bipolar", "ELU", "as", "in", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1709", ".", "04054", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3263-L3269
[ "def", "belu", "(", "x", ")", ":", "x_shape", "=", "shape_list", "(", "x", ")", "x1", ",", "x2", "=", "tf", ".", "split", "(", "tf", ".", "reshape", "(", "x", ",", "x_shape", "[", ":", "-", "1", "]", "+", "[", "-", "1", ",", "2", "]", ")"...
272500b6efe353aeb638d2745ed56e519462ca31
train
gelu
Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: x: float Tensor to perform activation. Returns: x with the GELU activation applied.
tensor2tensor/layers/common_layers.py
def gelu(x): """Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: x: float Tensor to perform activation. Returns: x with the GELU activation applied. """ cdf = 0.5 * (1.0 + tf.tanh( (np.sqrt(2 / np.pi) * (x + 0.04471...
def gelu(x): """Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: x: float Tensor to perform activation. Returns: x with the GELU activation applied. """ cdf = 0.5 * (1.0 + tf.tanh( (np.sqrt(2 / np.pi) * (x + 0.04471...
[ "Gaussian", "Error", "Linear", "Unit", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3272-L3286
[ "def", "gelu", "(", "x", ")", ":", "cdf", "=", "0.5", "*", "(", "1.0", "+", "tf", ".", "tanh", "(", "(", "np", ".", "sqrt", "(", "2", "/", "np", ".", "pi", ")", "*", "(", "x", "+", "0.044715", "*", "tf", ".", "pow", "(", "x", ",", "3", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
nac
NAC as in https://arxiv.org/abs/1808.00508.
tensor2tensor/layers/common_layers.py
def nac(x, depth, name=None, reuse=None): """NAC as in https://arxiv.org/abs/1808.00508.""" with tf.variable_scope(name, default_name="nac", values=[x], reuse=reuse): x_shape = shape_list(x) w = tf.get_variable("w", [x_shape[-1], depth]) m = tf.get_variable("m", [x_shape[-1], depth]) w = tf.tanh(w) ...
def nac(x, depth, name=None, reuse=None): """NAC as in https://arxiv.org/abs/1808.00508.""" with tf.variable_scope(name, default_name="nac", values=[x], reuse=reuse): x_shape = shape_list(x) w = tf.get_variable("w", [x_shape[-1], depth]) m = tf.get_variable("m", [x_shape[-1], depth]) w = tf.tanh(w) ...
[ "NAC", "as", "in", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1808", ".", "00508", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3289-L3298
[ "def", "nac", "(", "x", ",", "depth", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"nac\"", ",", "values", "=", "[", "x", "]", ",", "reuse", "=", "reu...
272500b6efe353aeb638d2745ed56e519462ca31
train
nalu
NALU as in https://arxiv.org/abs/1808.00508.
tensor2tensor/layers/common_layers.py
def nalu(x, depth, epsilon=1e-30, name=None, reuse=None): """NALU as in https://arxiv.org/abs/1808.00508.""" with tf.variable_scope(name, default_name="nalu", values=[x], reuse=reuse): x_shape = shape_list(x) x_flat = tf.reshape(x, [-1, x_shape[-1]]) gw = tf.get_variable("w", [x_shape[-1], depth]) g...
def nalu(x, depth, epsilon=1e-30, name=None, reuse=None): """NALU as in https://arxiv.org/abs/1808.00508.""" with tf.variable_scope(name, default_name="nalu", values=[x], reuse=reuse): x_shape = shape_list(x) x_flat = tf.reshape(x, [-1, x_shape[-1]]) gw = tf.get_variable("w", [x_shape[-1], depth]) g...
[ "NALU", "as", "in", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1808", ".", "00508", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3301-L3312
[ "def", "nalu", "(", "x", ",", "depth", ",", "epsilon", "=", "1e-30", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"nalu\"", ",", "values", "=", "[", "x"...
272500b6efe353aeb638d2745ed56e519462ca31
train
argmax_with_score
Argmax along with the value.
tensor2tensor/layers/common_layers.py
def argmax_with_score(logits, axis=None): """Argmax along with the value.""" axis = axis or len(logits.get_shape()) - 1 predictions = tf.argmax(logits, axis=axis) logits_shape = shape_list(logits) prefix_shape, vocab_size = logits_shape[:-1], logits_shape[-1] prefix_size = 1 for d in prefix_shape: pr...
def argmax_with_score(logits, axis=None): """Argmax along with the value.""" axis = axis or len(logits.get_shape()) - 1 predictions = tf.argmax(logits, axis=axis) logits_shape = shape_list(logits) prefix_shape, vocab_size = logits_shape[:-1], logits_shape[-1] prefix_size = 1 for d in prefix_shape: pr...
[ "Argmax", "along", "with", "the", "value", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3315-L3338
[ "def", "argmax_with_score", "(", "logits", ",", "axis", "=", "None", ")", ":", "axis", "=", "axis", "or", "len", "(", "logits", ".", "get_shape", "(", ")", ")", "-", "1", "predictions", "=", "tf", ".", "argmax", "(", "logits", ",", "axis", "=", "ax...
272500b6efe353aeb638d2745ed56e519462ca31
train
top_kth_iterative
Compute the k-th top element of x on the last axis iteratively. This assumes values in x are non-negative, rescale if needed. It is often faster than tf.nn.top_k for small k, especially if k < 30. Note: this does not support back-propagation, it stops gradients! Args: x: a Tensor of non-negative numbers o...
tensor2tensor/layers/common_layers.py
def top_kth_iterative(x, k): """Compute the k-th top element of x on the last axis iteratively. This assumes values in x are non-negative, rescale if needed. It is often faster than tf.nn.top_k for small k, especially if k < 30. Note: this does not support back-propagation, it stops gradients! Args: x: ...
def top_kth_iterative(x, k): """Compute the k-th top element of x on the last axis iteratively. This assumes values in x are non-negative, rescale if needed. It is often faster than tf.nn.top_k for small k, especially if k < 30. Note: this does not support back-propagation, it stops gradients! Args: x: ...
[ "Compute", "the", "k", "-", "th", "top", "element", "of", "x", "on", "the", "last", "axis", "iteratively", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3345-L3375
[ "def", "top_kth_iterative", "(", "x", ",", "k", ")", ":", "# The iterative computation is as follows:", "#", "# cur_x = x", "# for _ in range(k):", "# top_x = maximum of elements of cur_x on the last axis", "# cur_x = cur_x where cur_x < top_x and 0 everywhere else (top elements)", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
top_1_tpu
find max and argmax over the last dimension. Works well on TPU Args: inputs: A tensor with shape [..., depth] Returns: values: a Tensor with shape [...] indices: a Tensor with shape [...]
tensor2tensor/layers/common_layers.py
def top_1_tpu(inputs): """find max and argmax over the last dimension. Works well on TPU Args: inputs: A tensor with shape [..., depth] Returns: values: a Tensor with shape [...] indices: a Tensor with shape [...] """ inputs_max = tf.reduce_max(inputs, axis=-1, keepdims=True) mask = tf.to_i...
def top_1_tpu(inputs): """find max and argmax over the last dimension. Works well on TPU Args: inputs: A tensor with shape [..., depth] Returns: values: a Tensor with shape [...] indices: a Tensor with shape [...] """ inputs_max = tf.reduce_max(inputs, axis=-1, keepdims=True) mask = tf.to_i...
[ "find", "max", "and", "argmax", "over", "the", "last", "dimension", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3378-L3393
[ "def", "top_1_tpu", "(", "inputs", ")", ":", "inputs_max", "=", "tf", ".", "reduce_max", "(", "inputs", ",", "axis", "=", "-", "1", ",", "keepdims", "=", "True", ")", "mask", "=", "tf", ".", "to_int32", "(", "tf", ".", "equal", "(", "inputs_max", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
index_last_dim_with_indices
Use indices to index into the last axis of x. This can be useful for recovering the actual probabilities of a sample from a probability distribution. Args: x: Tensor, n-d. indices: Tensor, (n-1)-d, where the dimension sizes match the first (n-1) dimensions of x. The values of indices will be used ...
tensor2tensor/layers/common_layers.py
def index_last_dim_with_indices(x, indices): """Use indices to index into the last axis of x. This can be useful for recovering the actual probabilities of a sample from a probability distribution. Args: x: Tensor, n-d. indices: Tensor, (n-1)-d, where the dimension sizes match the first (n-1) di...
def index_last_dim_with_indices(x, indices): """Use indices to index into the last axis of x. This can be useful for recovering the actual probabilities of a sample from a probability distribution. Args: x: Tensor, n-d. indices: Tensor, (n-1)-d, where the dimension sizes match the first (n-1) di...
[ "Use", "indices", "to", "index", "into", "the", "last", "axis", "of", "x", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3396-L3429
[ "def", "index_last_dim_with_indices", "(", "x", ",", "indices", ")", ":", "assert", "len", "(", "x", ".", "shape", ")", "==", "len", "(", "indices", ".", "shape", ")", "+", "1", "x_shape", "=", "shape_list", "(", "x", ")", "vocab_size", "=", "x_shape",...
272500b6efe353aeb638d2745ed56e519462ca31
train
should_generate_summaries
Is this an appropriate context to generate summaries. Returns: a boolean
tensor2tensor/layers/common_layers.py
def should_generate_summaries(): """Is this an appropriate context to generate summaries. Returns: a boolean """ name_scope = tf.contrib.framework.get_name_scope() if name_scope and "while/" in name_scope: # Summaries don't work well within tf.while_loop() return False if tf.get_variable_scope(...
def should_generate_summaries(): """Is this an appropriate context to generate summaries. Returns: a boolean """ name_scope = tf.contrib.framework.get_name_scope() if name_scope and "while/" in name_scope: # Summaries don't work well within tf.while_loop() return False if tf.get_variable_scope(...
[ "Is", "this", "an", "appropriate", "context", "to", "generate", "summaries", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3432-L3445
[ "def", "should_generate_summaries", "(", ")", ":", "name_scope", "=", "tf", ".", "contrib", ".", "framework", ".", "get_name_scope", "(", ")", "if", "name_scope", "and", "\"while/\"", "in", "name_scope", ":", "# Summaries don't work well within tf.while_loop()", "retu...
272500b6efe353aeb638d2745ed56e519462ca31
train
reshape_like
Reshapes a to match the shape of b in all but the last dimension.
tensor2tensor/layers/common_layers.py
def reshape_like(a, b): """Reshapes a to match the shape of b in all but the last dimension.""" ret = tf.reshape(a, tf.concat([tf.shape(b)[:-1], tf.shape(a)[-1:]], 0)) if not tf.executing_eagerly(): ret.set_shape(b.get_shape().as_list()[:-1] + a.get_shape().as_list()[-1:]) return ret
def reshape_like(a, b): """Reshapes a to match the shape of b in all but the last dimension.""" ret = tf.reshape(a, tf.concat([tf.shape(b)[:-1], tf.shape(a)[-1:]], 0)) if not tf.executing_eagerly(): ret.set_shape(b.get_shape().as_list()[:-1] + a.get_shape().as_list()[-1:]) return ret
[ "Reshapes", "a", "to", "match", "the", "shape", "of", "b", "in", "all", "but", "the", "last", "dimension", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3448-L3453
[ "def", "reshape_like", "(", "a", ",", "b", ")", ":", "ret", "=", "tf", ".", "reshape", "(", "a", ",", "tf", ".", "concat", "(", "[", "tf", ".", "shape", "(", "b", ")", "[", ":", "-", "1", "]", ",", "tf", ".", "shape", "(", "a", ")", "[", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
summarize_video
Summarize the video using image summaries starting with prefix.
tensor2tensor/layers/common_layers.py
def summarize_video(video, prefix, max_outputs=1): """Summarize the video using image summaries starting with prefix.""" video_shape = shape_list(video) if len(video_shape) != 5: raise ValueError("Assuming videos given as tensors in the format " "[batch, time, height, width, channels] but...
def summarize_video(video, prefix, max_outputs=1): """Summarize the video using image summaries starting with prefix.""" video_shape = shape_list(video) if len(video_shape) != 5: raise ValueError("Assuming videos given as tensors in the format " "[batch, time, height, width, channels] but...
[ "Summarize", "the", "video", "using", "image", "summaries", "starting", "with", "prefix", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3456-L3475
[ "def", "summarize_video", "(", "video", ",", "prefix", ",", "max_outputs", "=", "1", ")", ":", "video_shape", "=", "shape_list", "(", "video", ")", "if", "len", "(", "video_shape", ")", "!=", "5", ":", "raise", "ValueError", "(", "\"Assuming videos given as ...
272500b6efe353aeb638d2745ed56e519462ca31
train
cast_like
Cast x to y's dtype, if necessary.
tensor2tensor/layers/common_layers.py
def cast_like(x, y): """Cast x to y's dtype, if necessary.""" x = tf.convert_to_tensor(x) y = tf.convert_to_tensor(y) if x.dtype.base_dtype == y.dtype.base_dtype: return x cast_x = tf.cast(x, y.dtype) if cast_x.device != x.device: x_name = "(eager Tensor)" try: x_name = x.name except...
def cast_like(x, y): """Cast x to y's dtype, if necessary.""" x = tf.convert_to_tensor(x) y = tf.convert_to_tensor(y) if x.dtype.base_dtype == y.dtype.base_dtype: return x cast_x = tf.cast(x, y.dtype) if cast_x.device != x.device: x_name = "(eager Tensor)" try: x_name = x.name except...
[ "Cast", "x", "to", "y", "s", "dtype", "if", "necessary", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3478-L3495
[ "def", "cast_like", "(", "x", ",", "y", ")", ":", "x", "=", "tf", ".", "convert_to_tensor", "(", "x", ")", "y", "=", "tf", ".", "convert_to_tensor", "(", "y", ")", "if", "x", ".", "dtype", ".", "base_dtype", "==", "y", ".", "dtype", ".", "base_dt...
272500b6efe353aeb638d2745ed56e519462ca31
train
make_even_size
Pad x to be even-sized on axis 1 and 2, but only if necessary.
tensor2tensor/layers/common_layers.py
def make_even_size(x): """Pad x to be even-sized on axis 1 and 2, but only if necessary.""" x_shape = x.get_shape().as_list() assert len(x_shape) > 2, "Only 3+-dimensional tensors supported." shape = [dim if dim is not None else -1 for dim in x_shape] new_shape = x_shape # To make sure constant shapes remain...
def make_even_size(x): """Pad x to be even-sized on axis 1 and 2, but only if necessary.""" x_shape = x.get_shape().as_list() assert len(x_shape) > 2, "Only 3+-dimensional tensors supported." shape = [dim if dim is not None else -1 for dim in x_shape] new_shape = x_shape # To make sure constant shapes remain...
[ "Pad", "x", "to", "be", "even", "-", "sized", "on", "axis", "1", "and", "2", "but", "only", "if", "necessary", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3498-L3521
[ "def", "make_even_size", "(", "x", ")", ":", "x_shape", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "assert", "len", "(", "x_shape", ")", ">", "2", ",", "\"Only 3+-dimensional tensors supported.\"", "shape", "=", "[", "dim", "if", "di...
272500b6efe353aeb638d2745ed56e519462ca31
train
sliced_gan_loss
Loss inspired by the sliced WGAN paper: https://arxiv.org/abs/1804.01947. Puts input1 and input2 through the provided discriminator to get logits. Then, computes num_vecs random projections of the logits, sorts them on the batch dimension and returns the L2 loss between the sorted vectors. See the above-mentio...
tensor2tensor/layers/common_layers.py
def sliced_gan_loss(input1, input2, discriminator, num_vecs, do_random_vecs=True, do_tanh=True, return_logits=False): """Loss inspired by the sliced WGAN paper: https://arxiv.org/abs/1804.01947. ...
def sliced_gan_loss(input1, input2, discriminator, num_vecs, do_random_vecs=True, do_tanh=True, return_logits=False): """Loss inspired by the sliced WGAN paper: https://arxiv.org/abs/1804.01947. ...
[ "Loss", "inspired", "by", "the", "sliced", "WGAN", "paper", ":", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1804", ".", "01947", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3524-L3594
[ "def", "sliced_gan_loss", "(", "input1", ",", "input2", ",", "discriminator", ",", "num_vecs", ",", "do_random_vecs", "=", "True", ",", "do_tanh", "=", "True", ",", "return_logits", "=", "False", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"sliced_...
272500b6efe353aeb638d2745ed56e519462ca31
train
deep_discriminator
Discriminator architecture based on InfoGAN.
tensor2tensor/layers/common_layers.py
def deep_discriminator(x, batch_norm, is_training, filters=64, filter_size=4, stride=2, output_size=1024): """Discriminator architecture based on InfoGAN.""" with tf.variable_sco...
def deep_discriminator(x, batch_norm, is_training, filters=64, filter_size=4, stride=2, output_size=1024): """Discriminator architecture based on InfoGAN.""" with tf.variable_sco...
[ "Discriminator", "architecture", "based", "on", "InfoGAN", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3601-L3637
[ "def", "deep_discriminator", "(", "x", ",", "batch_norm", ",", "is_training", ",", "filters", "=", "64", ",", "filter_size", "=", "4", ",", "stride", "=", "2", ",", "output_size", "=", "1024", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"discri...
272500b6efe353aeb638d2745ed56e519462ca31
train
instance_norm
Instance normalization layer.
tensor2tensor/layers/common_layers.py
def instance_norm(x): """Instance normalization layer.""" with tf.variable_scope("instance_norm"): epsilon = 1e-5 mean, var = tf.nn.moments(x, [1, 2], keep_dims=True) scale = tf.get_variable( "scale", [x.get_shape()[-1]], initializer=tf.truncated_normal_initializer(mean=1.0, stddev=0.02)...
def instance_norm(x): """Instance normalization layer.""" with tf.variable_scope("instance_norm"): epsilon = 1e-5 mean, var = tf.nn.moments(x, [1, 2], keep_dims=True) scale = tf.get_variable( "scale", [x.get_shape()[-1]], initializer=tf.truncated_normal_initializer(mean=1.0, stddev=0.02)...
[ "Instance", "normalization", "layer", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3640-L3652
[ "def", "instance_norm", "(", "x", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"instance_norm\"", ")", ":", "epsilon", "=", "1e-5", "mean", ",", "var", "=", "tf", ".", "nn", ".", "moments", "(", "x", ",", "[", "1", ",", "2", "]", ",", "k...
272500b6efe353aeb638d2745ed56e519462ca31
train
general_conv
Generalized convolution layer.
tensor2tensor/layers/common_layers.py
def general_conv(x, num_filters=64, filter_size=7, stride=1, stddev=0.02, padding="VALID", name="conv", do_norm="instance", do_relu=True, relufactor=0): """Generaliz...
def general_conv(x, num_filters=64, filter_size=7, stride=1, stddev=0.02, padding="VALID", name="conv", do_norm="instance", do_relu=True, relufactor=0): """Generaliz...
[ "Generalized", "convolution", "layer", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3655-L3686
[ "def", "general_conv", "(", "x", ",", "num_filters", "=", "64", ",", "filter_size", "=", "7", ",", "stride", "=", "1", ",", "stddev", "=", "0.02", ",", "padding", "=", "\"VALID\"", ",", "name", "=", "\"conv\"", ",", "do_norm", "=", "\"instance\"", ",",...
272500b6efe353aeb638d2745ed56e519462ca31
train
patch_discriminator
Patch descriminator.
tensor2tensor/layers/common_layers.py
def patch_discriminator(x, filters=64, filter_size=5, n=4, name="patch_discrim"): """Patch descriminator.""" with tf.variable_scope(name): x_shape = shape_list(x) spatial_dims = [x_shape[1] // 4, x_shape[2] // 4] x = tf.random_crop(x, [x_shape[0]] + spatial_dims + [x_shape[3]]) ...
def patch_discriminator(x, filters=64, filter_size=5, n=4, name="patch_discrim"): """Patch descriminator.""" with tf.variable_scope(name): x_shape = shape_list(x) spatial_dims = [x_shape[1] // 4, x_shape[2] // 4] x = tf.random_crop(x, [x_shape[0]] + spatial_dims + [x_shape[3]]) ...
[ "Patch", "descriminator", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3689-L3709
[ "def", "patch_discriminator", "(", "x", ",", "filters", "=", "64", ",", "filter_size", "=", "5", ",", "n", "=", "4", ",", "name", "=", "\"patch_discrim\"", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "x_shape", "=", "shape_lis...
272500b6efe353aeb638d2745ed56e519462ca31
train
mean_with_attention
Mean and attention to reduce spatial dimensions.
tensor2tensor/layers/common_layers.py
def mean_with_attention(x, name, num_heads=4): """Mean and attention to reduce spatial dimensions.""" with tf.variable_scope(name): shape = shape_list(x) m = tf.reduce_mean(x, [1, 2]) a = layers().Dense(num_heads, name="mean_attn")(x) s = tf.reshape(a, [shape[0], -1, num_heads]) s = tf.nn.softma...
def mean_with_attention(x, name, num_heads=4): """Mean and attention to reduce spatial dimensions.""" with tf.variable_scope(name): shape = shape_list(x) m = tf.reduce_mean(x, [1, 2]) a = layers().Dense(num_heads, name="mean_attn")(x) s = tf.reshape(a, [shape[0], -1, num_heads]) s = tf.nn.softma...
[ "Mean", "and", "attention", "to", "reduce", "spatial", "dimensions", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3712-L3724
[ "def", "mean_with_attention", "(", "x", ",", "name", ",", "num_heads", "=", "4", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "shape", "=", "shape_list", "(", "x", ")", "m", "=", "tf", ".", "reduce_mean", "(", "x", ",", "["...
272500b6efe353aeb638d2745ed56e519462ca31
train
single_discriminator
A simple single-layer convolutional discriminator.
tensor2tensor/layers/common_layers.py
def single_discriminator(x, filters=128, kernel_size=8, strides=4, pure_mean=False): """A simple single-layer convolutional discriminator.""" with tf.variable_scope("discriminator"): net = layers().Conv2D( filters, kernel_size, strides=strides, padding="SAME", name="conv1")(x) ...
def single_discriminator(x, filters=128, kernel_size=8, strides=4, pure_mean=False): """A simple single-layer convolutional discriminator.""" with tf.variable_scope("discriminator"): net = layers().Conv2D( filters, kernel_size, strides=strides, padding="SAME", name="conv1")(x) ...
[ "A", "simple", "single", "-", "layer", "convolutional", "discriminator", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3727-L3737
[ "def", "single_discriminator", "(", "x", ",", "filters", "=", "128", ",", "kernel_size", "=", "8", ",", "strides", "=", "4", ",", "pure_mean", "=", "False", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"discriminator\"", ")", ":", "net", "=", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
double_discriminator
A convolutional discriminator with 2 layers and concatenated output.
tensor2tensor/layers/common_layers.py
def double_discriminator(x, filters1=128, filters2=None, kernel_size=8, strides=4, pure_mean=False): """A convolutional discriminator with 2 layers and concatenated output.""" if filters2 is None: filters2 = 4 * filters1 with tf.variable_scope("discriminator"): batch_size = shape_...
def double_discriminator(x, filters1=128, filters2=None, kernel_size=8, strides=4, pure_mean=False): """A convolutional discriminator with 2 layers and concatenated output.""" if filters2 is None: filters2 = 4 * filters1 with tf.variable_scope("discriminator"): batch_size = shape_...
[ "A", "convolutional", "discriminator", "with", "2", "layers", "and", "concatenated", "output", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3740-L3761
[ "def", "double_discriminator", "(", "x", ",", "filters1", "=", "128", ",", "filters2", "=", "None", ",", "kernel_size", "=", "8", ",", "strides", "=", "4", ",", "pure_mean", "=", "False", ")", ":", "if", "filters2", "is", "None", ":", "filters2", "=", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
upscale
Upscaling the image by a factor of f.
tensor2tensor/layers/common_layers.py
def upscale(inputs, f, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR): """Upscaling the image by a factor of f.""" height, width = shape_list(inputs)[1:3] # pylint: disable=unbalanced-tuple-unpacking return tf.image.resize_images(inputs, (height * f, width * f), method)
def upscale(inputs, f, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR): """Upscaling the image by a factor of f.""" height, width = shape_list(inputs)[1:3] # pylint: disable=unbalanced-tuple-unpacking return tf.image.resize_images(inputs, (height * f, width * f), method)
[ "Upscaling", "the", "image", "by", "a", "factor", "of", "f", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3764-L3767
[ "def", "upscale", "(", "inputs", ",", "f", ",", "method", "=", "tf", ".", "image", ".", "ResizeMethod", ".", "NEAREST_NEIGHBOR", ")", ":", "height", ",", "width", "=", "shape_list", "(", "inputs", ")", "[", "1", ":", "3", "]", "# pylint: disable=unbalanc...
272500b6efe353aeb638d2745ed56e519462ca31
train
cyclegan_upsample
Upsamples the given inputs. Args: net: A Tensor of size [batch_size, height, width, filters]. num_outputs: The number of output filters. stride: A list of 2 scalars or a 1x2 Tensor indicating the scale, relative to the inputs, of the output dimensions. For example, if kernel size is [2, 3], t...
tensor2tensor/layers/common_layers.py
def cyclegan_upsample(net, num_outputs, stride, method="conv2d_transpose"): """Upsamples the given inputs. Args: net: A Tensor of size [batch_size, height, width, filters]. num_outputs: The number of output filters. stride: A list of 2 scalars or a 1x2 Tensor indicating the scale, relative to the...
def cyclegan_upsample(net, num_outputs, stride, method="conv2d_transpose"): """Upsamples the given inputs. Args: net: A Tensor of size [batch_size, height, width, filters]. num_outputs: The number of output filters. stride: A list of 2 scalars or a 1x2 Tensor indicating the scale, relative to the...
[ "Upsamples", "the", "given", "inputs", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3788-L3841
[ "def", "cyclegan_upsample", "(", "net", ",", "num_outputs", ",", "stride", ",", "method", "=", "\"conv2d_transpose\"", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"upconv\"", ")", ":", "net_shape", "=", "tf", ".", "shape", "(", "net", ")", "heigh...
272500b6efe353aeb638d2745ed56e519462ca31