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
random_shift
Apply random horizontal and vertical shift to images. This is the default data-augmentation strategy used on CIFAR in Glow. Args: image: a 3-D Tensor wsr: Width shift range, as a float fraction of the width. hsr: Height shift range, as a float fraction of the width. Returns: images: images trans...
tensor2tensor/data_generators/image_utils.py
def random_shift(image, wsr=0.1, hsr=0.1): """Apply random horizontal and vertical shift to images. This is the default data-augmentation strategy used on CIFAR in Glow. Args: image: a 3-D Tensor wsr: Width shift range, as a float fraction of the width. hsr: Height shift range, as a float fraction o...
def random_shift(image, wsr=0.1, hsr=0.1): """Apply random horizontal and vertical shift to images. This is the default data-augmentation strategy used on CIFAR in Glow. Args: image: a 3-D Tensor wsr: Width shift range, as a float fraction of the width. hsr: Height shift range, as a float fraction o...
[ "Apply", "random", "horizontal", "and", "vertical", "shift", "to", "images", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_utils.py#L408-L425
[ "def", "random_shift", "(", "image", ",", "wsr", "=", "0.1", ",", "hsr", "=", "0.1", ")", ":", "height", ",", "width", ",", "_", "=", "common_layers", ".", "shape_list", "(", "image", ")", "width_range", ",", "height_range", "=", "wsr", "*", "width", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_standardized_layers
Get the common attention and feed-forward layers. The returned layer functions will have the following signature: y, extra_loss = fct(x) extra_loss is set to 0.0 if the layer doesn't have extra loss. If dp is provided, the layers will be distributed within the devices. If moe wants to be used, both dp an...
tensor2tensor/layers/common_attention.py
def get_standardized_layers(hparams, dp=None): """Get the common attention and feed-forward layers. The returned layer functions will have the following signature: y, extra_loss = fct(x) extra_loss is set to 0.0 if the layer doesn't have extra loss. If dp is provided, the layers will be distributed withi...
def get_standardized_layers(hparams, dp=None): """Get the common attention and feed-forward layers. The returned layer functions will have the following signature: y, extra_loss = fct(x) extra_loss is set to 0.0 if the layer doesn't have extra loss. If dp is provided, the layers will be distributed withi...
[ "Get", "the", "common", "attention", "and", "feed", "-", "forward", "layers", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L91-L299
[ "def", "get_standardized_layers", "(", "hparams", ",", "dp", "=", "None", ")", ":", "def", "partial", "(", "fct", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Same as functools.partial but with functools.wraps.\"\"\"", "return", "functools", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
add_standard_attention_hparams
Adds the hparams used by get_standardized_layers.
tensor2tensor/layers/common_attention.py
def add_standard_attention_hparams(hparams): """Adds the hparams used by get_standardized_layers.""" # All hyperparameters ending in "dropout" are automatically set to 0.0 # when not in training mode. # hparams used and which should have been defined outside (in # common_hparams): # Global flags # hparam...
def add_standard_attention_hparams(hparams): """Adds the hparams used by get_standardized_layers.""" # All hyperparameters ending in "dropout" are automatically set to 0.0 # when not in training mode. # hparams used and which should have been defined outside (in # common_hparams): # Global flags # hparam...
[ "Adds", "the", "hparams", "used", "by", "get_standardized_layers", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L302-L344
[ "def", "add_standard_attention_hparams", "(", "hparams", ")", ":", "# All hyperparameters ending in \"dropout\" are automatically set to 0.0", "# when not in training mode.", "# hparams used and which should have been defined outside (in", "# common_hparams):", "# Global flags", "# hparams.mod...
272500b6efe353aeb638d2745ed56e519462ca31
train
encoder_decoder_attention_loss
Computes encdec attention loss between expected and actual attentions. Args: expected_attention_logits: Tensor storing the expected encoder-decoder attention logits with shape [batch_size, target_length, input_length]. actual_attentions: Dictionary with actual attention logits for different atten...
tensor2tensor/layers/common_attention.py
def encoder_decoder_attention_loss(expected_attention_logits, actual_attentions, loss_type="kl_divergence", loss_multiplier=1.0): """Computes encdec attention loss between expected and actual attentions. Args: ...
def encoder_decoder_attention_loss(expected_attention_logits, actual_attentions, loss_type="kl_divergence", loss_multiplier=1.0): """Computes encdec attention loss between expected and actual attentions. Args: ...
[ "Computes", "encdec", "attention", "loss", "between", "expected", "and", "actual", "attentions", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L347-L402
[ "def", "encoder_decoder_attention_loss", "(", "expected_attention_logits", ",", "actual_attentions", ",", "loss_type", "=", "\"kl_divergence\"", ",", "loss_multiplier", "=", "1.0", ")", ":", "def", "combine_attentions", "(", "attention_list", ")", ":", "\"\"\"Combine diff...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_timing_signal_1d
Gets a bunch of sinusoids of different frequencies. Each channel of the input Tensor is incremented by a sinusoid of a different frequency and phase. This allows attention to learn to use absolute and relative positions. Timing signals should be added to some precursors of both the query and the memory inpu...
tensor2tensor/layers/common_attention.py
def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4, start_index=0): """Gets a bunch of sinusoids of different frequencies. Each channel of the input Tensor is incremented by a sinusoid...
def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4, start_index=0): """Gets a bunch of sinusoids of different frequencies. Each channel of the input Tensor is incremented by a sinusoid...
[ "Gets", "a", "bunch", "of", "sinusoids", "of", "different", "frequencies", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L406-L452
[ "def", "get_timing_signal_1d", "(", "length", ",", "channels", ",", "min_timescale", "=", "1.0", ",", "max_timescale", "=", "1.0e4", ",", "start_index", "=", "0", ")", ":", "position", "=", "tf", ".", "to_float", "(", "tf", ".", "range", "(", "length", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
add_timing_signal_1d
Adds a bunch of sinusoids of different frequencies to a Tensor. Each channel of the input Tensor is incremented by a sinusoid of a different frequency and phase. This allows attention to learn to use absolute and relative positions. Timing signals should be added to some precursors of both the query and the ...
tensor2tensor/layers/common_attention.py
def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, start_index=0): """Adds a bunch of sinusoids of different frequencies to a Tensor. Each channel of the input Tensor is incremented by a sinusoid of a different frequency ...
def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, start_index=0): """Adds a bunch of sinusoids of different frequencies to a Tensor. Each channel of the input Tensor is incremented by a sinusoid of a different frequency ...
[ "Adds", "a", "bunch", "of", "sinusoids", "of", "different", "frequencies", "to", "a", "Tensor", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L456-L492
[ "def", "add_timing_signal_1d", "(", "x", ",", "min_timescale", "=", "1.0", ",", "max_timescale", "=", "1.0e4", ",", "start_index", "=", "0", ")", ":", "length", "=", "common_layers", ".", "shape_list", "(", "x", ")", "[", "1", "]", "channels", "=", "comm...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_layer_timing_signal_learned_1d
get n-dimensional embedding as the layer (vertical) timing signal. Adds embeddings to represent the position of the layer in the tower. Args: channels: dimension of the timing signal layer: layer num num_layers: total number of layers Returns: a Tensor of timing signals [1, 1, channels].
tensor2tensor/layers/common_attention.py
def get_layer_timing_signal_learned_1d(channels, layer, num_layers): """get n-dimensional embedding as the layer (vertical) timing signal. Adds embeddings to represent the position of the layer in the tower. Args: channels: dimension of the timing signal layer: layer num num_layers: total number of ...
def get_layer_timing_signal_learned_1d(channels, layer, num_layers): """get n-dimensional embedding as the layer (vertical) timing signal. Adds embeddings to represent the position of the layer in the tower. Args: channels: dimension of the timing signal layer: layer num num_layers: total number of ...
[ "get", "n", "-", "dimensional", "embedding", "as", "the", "layer", "(", "vertical", ")", "timing", "signal", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L496-L516
[ "def", "get_layer_timing_signal_learned_1d", "(", "channels", ",", "layer", ",", "num_layers", ")", ":", "shape", "=", "[", "num_layers", ",", "1", ",", "1", ",", "channels", "]", "layer_embedding", "=", "(", "tf", ".", "get_variable", "(", "\"layer_embedding\...
272500b6efe353aeb638d2745ed56e519462ca31
train
add_layer_timing_signal_learned_1d
Add n-dimensional embedding as the layer (vertical) timing signal. Adds embeddings to represent the position of the layer in the tower. Args: x: a tensor with shape [batch, length, depth] layer: layer num num_layers: total number of layers Returns: a Tensor the same shape as x.
tensor2tensor/layers/common_attention.py
def add_layer_timing_signal_learned_1d(x, layer, num_layers): """Add n-dimensional embedding as the layer (vertical) timing signal. Adds embeddings to represent the position of the layer in the tower. Args: x: a tensor with shape [batch, length, depth] layer: layer num num_layers: total number of la...
def add_layer_timing_signal_learned_1d(x, layer, num_layers): """Add n-dimensional embedding as the layer (vertical) timing signal. Adds embeddings to represent the position of the layer in the tower. Args: x: a tensor with shape [batch, length, depth] layer: layer num num_layers: total number of la...
[ "Add", "n", "-", "dimensional", "embedding", "as", "the", "layer", "(", "vertical", ")", "timing", "signal", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L520-L536
[ "def", "add_layer_timing_signal_learned_1d", "(", "x", ",", "layer", ",", "num_layers", ")", ":", "channels", "=", "common_layers", ".", "shape_list", "(", "x", ")", "[", "-", "1", "]", "signal", "=", "get_layer_timing_signal_learned_1d", "(", "channels", ",", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_layer_timing_signal_sinusoid_1d
Add sinusoids of different frequencies as layer (vertical) timing signal. Args: channels: dimension of the timing signal layer: layer num num_layers: total number of layers Returns: a Tensor of timing signals [1, 1, channels].
tensor2tensor/layers/common_attention.py
def get_layer_timing_signal_sinusoid_1d(channels, layer, num_layers): """Add sinusoids of different frequencies as layer (vertical) timing signal. Args: channels: dimension of the timing signal layer: layer num num_layers: total number of layers Returns: a Tensor of timing signals [1, 1, channel...
def get_layer_timing_signal_sinusoid_1d(channels, layer, num_layers): """Add sinusoids of different frequencies as layer (vertical) timing signal. Args: channels: dimension of the timing signal layer: layer num num_layers: total number of layers Returns: a Tensor of timing signals [1, 1, channel...
[ "Add", "sinusoids", "of", "different", "frequencies", "as", "layer", "(", "vertical", ")", "timing", "signal", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L540-L555
[ "def", "get_layer_timing_signal_sinusoid_1d", "(", "channels", ",", "layer", ",", "num_layers", ")", ":", "signal", "=", "get_timing_signal_1d", "(", "num_layers", ",", "channels", ")", "layer_signal", "=", "tf", ".", "expand_dims", "(", "signal", "[", ":", ",",...
272500b6efe353aeb638d2745ed56e519462ca31
train
add_layer_timing_signal_sinusoid_1d
Add sinusoids of different frequencies as layer (vertical) timing signal. Args: x: a Tensor with shape [batch, length, channels] layer: layer num num_layers: total number of layers Returns: a Tensor the same shape as x.
tensor2tensor/layers/common_attention.py
def add_layer_timing_signal_sinusoid_1d(x, layer, num_layers): """Add sinusoids of different frequencies as layer (vertical) timing signal. Args: x: a Tensor with shape [batch, length, channels] layer: layer num num_layers: total number of layers Returns: a Tensor the same shape as x. """ c...
def add_layer_timing_signal_sinusoid_1d(x, layer, num_layers): """Add sinusoids of different frequencies as layer (vertical) timing signal. Args: x: a Tensor with shape [batch, length, channels] layer: layer num num_layers: total number of layers Returns: a Tensor the same shape as x. """ c...
[ "Add", "sinusoids", "of", "different", "frequencies", "as", "layer", "(", "vertical", ")", "timing", "signal", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L559-L574
[ "def", "add_layer_timing_signal_sinusoid_1d", "(", "x", ",", "layer", ",", "num_layers", ")", ":", "channels", "=", "common_layers", ".", "shape_list", "(", "x", ")", "[", "-", "1", "]", "signal", "=", "get_layer_timing_signal_sinusoid_1d", "(", "channels", ",",...
272500b6efe353aeb638d2745ed56e519462ca31
train
add_timing_signal_1d_given_position
Adds sinusoids of diff frequencies to a Tensor, with timing position given. Args: x: a Tensor with shape [batch, length, channels] position: a Tensor with shape [batch, length] min_timescale: a float max_timescale: a float Returns: a Tensor the same shape as x.
tensor2tensor/layers/common_attention.py
def add_timing_signal_1d_given_position(x, position, min_timescale=1.0, max_timescale=1.0e4): """Adds sinusoids of diff frequencies to a Tensor, with timing position given. Args: x: a Tensor ...
def add_timing_signal_1d_given_position(x, position, min_timescale=1.0, max_timescale=1.0e4): """Adds sinusoids of diff frequencies to a Tensor, with timing position given. Args: x: a Tensor ...
[ "Adds", "sinusoids", "of", "diff", "frequencies", "to", "a", "Tensor", "with", "timing", "position", "given", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L578-L606
[ "def", "add_timing_signal_1d_given_position", "(", "x", ",", "position", ",", "min_timescale", "=", "1.0", ",", "max_timescale", "=", "1.0e4", ")", ":", "channels", "=", "common_layers", ".", "shape_list", "(", "x", ")", "[", "2", "]", "num_timescales", "=", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
add_timing_signal_nd
Adds a bunch of sinusoids of different frequencies to a Tensor. Each channel of the input Tensor is incremented by a sinusoid of a different frequency and phase in one of the positional dimensions. This allows attention to learn to use absolute and relative positions. Timing signals should be added to some pr...
tensor2tensor/layers/common_attention.py
def add_timing_signal_nd(x, min_timescale=1.0, max_timescale=1.0e4): """Adds a bunch of sinusoids of different frequencies to a Tensor. Each channel of the input Tensor is incremented by a sinusoid of a different frequency and phase in one of the positional dimensions. This allows attention to learn to use ab...
def add_timing_signal_nd(x, min_timescale=1.0, max_timescale=1.0e4): """Adds a bunch of sinusoids of different frequencies to a Tensor. Each channel of the input Tensor is incremented by a sinusoid of a different frequency and phase in one of the positional dimensions. This allows attention to learn to use ab...
[ "Adds", "a", "bunch", "of", "sinusoids", "of", "different", "frequencies", "to", "a", "Tensor", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L610-L663
[ "def", "add_timing_signal_nd", "(", "x", ",", "min_timescale", "=", "1.0", ",", "max_timescale", "=", "1.0e4", ")", ":", "num_dims", "=", "len", "(", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", ")", "-", "2", "channels", "=", "common_lay...
272500b6efe353aeb638d2745ed56e519462ca31
train
add_positional_embedding
Adds positional embedding. Args: x: Tensor with shape [batch, length, depth]. max_length: int representing static maximum size of any dimension. name: str representing name of the embedding tf.Variable. positions: Tensor with shape [batch, length]. Returns: Tensor of same shape as x.
tensor2tensor/layers/common_attention.py
def add_positional_embedding(x, max_length, name=None, positions=None): """Adds positional embedding. Args: x: Tensor with shape [batch, length, depth]. max_length: int representing static maximum size of any dimension. name: str representing name of the embedding tf.Variable. positions: Tensor wit...
def add_positional_embedding(x, max_length, name=None, positions=None): """Adds positional embedding. Args: x: Tensor with shape [batch, length, depth]. max_length: int representing static maximum size of any dimension. name: str representing name of the embedding tf.Variable. positions: Tensor wit...
[ "Adds", "positional", "embedding", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L666-L689
[ "def", "add_positional_embedding", "(", "x", ",", "max_length", ",", "name", "=", "None", ",", "positions", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "\"add_positional_embedding\"", ")", ":", "_", ",", "length", ",", "depth", "=", "commo...
272500b6efe353aeb638d2745ed56e519462ca31
train
add_positional_embedding_nd
Adds n-dimensional positional embedding. The embeddings add to all positional dimensions of the tensor. Args: x: Tensor with shape [batch, p1 ... pn, depth]. It has n positional dimensions, i.e., 1 for text, 2 for images, 3 for video, etc. max_length: int representing static maximum size of any dime...
tensor2tensor/layers/common_attention.py
def add_positional_embedding_nd(x, max_length, name=None): """Adds n-dimensional positional embedding. The embeddings add to all positional dimensions of the tensor. Args: x: Tensor with shape [batch, p1 ... pn, depth]. It has n positional dimensions, i.e., 1 for text, 2 for images, 3 for video, etc. ...
def add_positional_embedding_nd(x, max_length, name=None): """Adds n-dimensional positional embedding. The embeddings add to all positional dimensions of the tensor. Args: x: Tensor with shape [batch, p1 ... pn, depth]. It has n positional dimensions, i.e., 1 for text, 2 for images, 3 for video, etc. ...
[ "Adds", "n", "-", "dimensional", "positional", "embedding", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L692-L725
[ "def", "add_positional_embedding_nd", "(", "x", ",", "max_length", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "\"add_positional_embedding_nd\"", ")", ":", "x_shape", "=", "common_layers", ".", "shape_list", "(", "x", ")", "num_di...
272500b6efe353aeb638d2745ed56e519462ca31
train
make_edge_vectors
Gets edge vectors for the edge types in the adjacency matrix. Args: adjacency_matrix: A [batch, num_nodes, num_nodes] tensor of ints. num_edge_types: Number of different edge types depth: Number of channels name: a string Returns: A [batch, num_nodes, num_nodes, depth] vector of tensors
tensor2tensor/layers/common_attention.py
def make_edge_vectors(adjacency_matrix, num_edge_types, depth, name=None): """Gets edge vectors for the edge types in the adjacency matrix. Args: adjacency_matrix: A [batch, num_nodes, num_nodes] tensor of ints. num_edge_types: Number of different edge types depth: Number of channels name: a string...
def make_edge_vectors(adjacency_matrix, num_edge_types, depth, name=None): """Gets edge vectors for the edge types in the adjacency matrix. Args: adjacency_matrix: A [batch, num_nodes, num_nodes] tensor of ints. num_edge_types: Number of different edge types depth: Number of channels name: a string...
[ "Gets", "edge", "vectors", "for", "the", "edge", "types", "in", "the", "adjacency", "matrix", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L728-L759
[ "def", "make_edge_vectors", "(", "adjacency_matrix", ",", "num_edge_types", ",", "depth", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"edge_vectors\"", ")", ":", "att_adj_vectors_shape", "=", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
padding_to_length
Calculate the length of mask based on padding. Args: padding: a Tensor with shape [..., length]. Returns: a Tensor with shape [...].
tensor2tensor/layers/common_attention.py
def padding_to_length(padding): """Calculate the length of mask based on padding. Args: padding: a Tensor with shape [..., length]. Returns: a Tensor with shape [...]. """ non_padding = 1.0 - padding return tf.to_int32(tf.reduce_sum(non_padding, axis=-1))
def padding_to_length(padding): """Calculate the length of mask based on padding. Args: padding: a Tensor with shape [..., length]. Returns: a Tensor with shape [...]. """ non_padding = 1.0 - padding return tf.to_int32(tf.reduce_sum(non_padding, axis=-1))
[ "Calculate", "the", "length", "of", "mask", "based", "on", "padding", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L860-L869
[ "def", "padding_to_length", "(", "padding", ")", ":", "non_padding", "=", "1.0", "-", "padding", "return", "tf", ".", "to_int32", "(", "tf", ".", "reduce_sum", "(", "non_padding", ",", "axis", "=", "-", "1", ")", ")" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
attention_bias_local
Create an bias tensor to be added to attention logits. A position may attend to positions at most max_distance from it, forward and backwards. This does not actually save any computation. Args: length: int max_backward: int, maximum distance backward to attend. Negative values indicate unlimite...
tensor2tensor/layers/common_attention.py
def attention_bias_local(length, max_backward, max_forward): """Create an bias tensor to be added to attention logits. A position may attend to positions at most max_distance from it, forward and backwards. This does not actually save any computation. Args: length: int max_backward: int, maximum di...
def attention_bias_local(length, max_backward, max_forward): """Create an bias tensor to be added to attention logits. A position may attend to positions at most max_distance from it, forward and backwards. This does not actually save any computation. Args: length: int max_backward: int, maximum di...
[ "Create", "an", "bias", "tensor", "to", "be", "added", "to", "attention", "logits", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L873-L897
[ "def", "attention_bias_local", "(", "length", ",", "max_backward", ",", "max_forward", ")", ":", "band", "=", "common_layers", ".", "ones_matrix_band_part", "(", "length", ",", "length", ",", "max_backward", ",", "max_forward", ",", "out_shape", "=", "[", "1", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
attention_bias_same_segment
Create an bias tensor to be added to attention logits. Positions with the same segment_ids can see each other. Args: query_segment_id: a float `Tensor` with shape [batch, query_length]. memory_segment_id: a float `Tensor` with shape [batch, memory_length]. Returns: a `Tensor` with shape [batch, 1, ...
tensor2tensor/layers/common_attention.py
def attention_bias_same_segment(query_segment_id, memory_segment_id): """Create an bias tensor to be added to attention logits. Positions with the same segment_ids can see each other. Args: query_segment_id: a float `Tensor` with shape [batch, query_length]. memory_segment_id: a float `Tensor` with shap...
def attention_bias_same_segment(query_segment_id, memory_segment_id): """Create an bias tensor to be added to attention logits. Positions with the same segment_ids can see each other. Args: query_segment_id: a float `Tensor` with shape [batch, query_length]. memory_segment_id: a float `Tensor` with shap...
[ "Create", "an", "bias", "tensor", "to", "be", "added", "to", "attention", "logits", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L916-L933
[ "def", "attention_bias_same_segment", "(", "query_segment_id", ",", "memory_segment_id", ")", ":", "ret", "=", "(", "tf", ".", "to_float", "(", "tf", ".", "not_equal", "(", "tf", ".", "expand_dims", "(", "query_segment_id", ",", "2", ")", ",", "tf", ".", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
attention_bias_ignore_padding
Create an bias tensor to be added to attention logits. Args: memory_padding: a float `Tensor` with shape [batch, memory_length]. Returns: a `Tensor` with shape [batch, 1, 1, memory_length].
tensor2tensor/layers/common_attention.py
def attention_bias_ignore_padding(memory_padding): """Create an bias tensor to be added to attention logits. Args: memory_padding: a float `Tensor` with shape [batch, memory_length]. Returns: a `Tensor` with shape [batch, 1, 1, memory_length]. """ ret = memory_padding * large_compatible_negative(mem...
def attention_bias_ignore_padding(memory_padding): """Create an bias tensor to be added to attention logits. Args: memory_padding: a float `Tensor` with shape [batch, memory_length]. Returns: a `Tensor` with shape [batch, 1, 1, memory_length]. """ ret = memory_padding * large_compatible_negative(mem...
[ "Create", "an", "bias", "tensor", "to", "be", "added", "to", "attention", "logits", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L937-L947
[ "def", "attention_bias_ignore_padding", "(", "memory_padding", ")", ":", "ret", "=", "memory_padding", "*", "large_compatible_negative", "(", "memory_padding", ".", "dtype", ")", "return", "tf", ".", "expand_dims", "(", "tf", ".", "expand_dims", "(", "ret", ",", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
attention_bias_to_padding
Inverse of attention_bias_ignore_padding(). Args: attention_bias: a `Tensor` with shape [batch, 1, 1, memory_length], as returned by attention_bias_ignore_padding(). cast_fn: function used to cast to output type. Returns: a Tensor with shape [batch, memory_length] with 1.0 in padding positions ...
tensor2tensor/layers/common_attention.py
def attention_bias_to_padding(attention_bias, cast_fn=tf.to_float): """Inverse of attention_bias_ignore_padding(). Args: attention_bias: a `Tensor` with shape [batch, 1, 1, memory_length], as returned by attention_bias_ignore_padding(). cast_fn: function used to cast to output type. Returns: a...
def attention_bias_to_padding(attention_bias, cast_fn=tf.to_float): """Inverse of attention_bias_ignore_padding(). Args: attention_bias: a `Tensor` with shape [batch, 1, 1, memory_length], as returned by attention_bias_ignore_padding(). cast_fn: function used to cast to output type. Returns: a...
[ "Inverse", "of", "attention_bias_ignore_padding", "()", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L951-L965
[ "def", "attention_bias_to_padding", "(", "attention_bias", ",", "cast_fn", "=", "tf", ".", "to_float", ")", ":", "# `attention_bias` is a large negative number in padding positions and 0.0", "# elsewhere.", "return", "tf", ".", "squeeze", "(", "cast_fn", "(", "tf", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
attention_bias_prepend_inputs_full_attention
Create a bias tensor for prepend_mode="prepend_inputs_full_attention". See prepend_inputs in common_hparams.py. Produces a bias tensor to be used in self-attention. This bias tensor allows for full connectivity in the "inputs" part of the sequence and masked connectivity in the targets part. Args: pad...
tensor2tensor/layers/common_attention.py
def attention_bias_prepend_inputs_full_attention(padding): """Create a bias tensor for prepend_mode="prepend_inputs_full_attention". See prepend_inputs in common_hparams.py. Produces a bias tensor to be used in self-attention. This bias tensor allows for full connectivity in the "inputs" part of the sequen...
def attention_bias_prepend_inputs_full_attention(padding): """Create a bias tensor for prepend_mode="prepend_inputs_full_attention". See prepend_inputs in common_hparams.py. Produces a bias tensor to be used in self-attention. This bias tensor allows for full connectivity in the "inputs" part of the sequen...
[ "Create", "a", "bias", "tensor", "for", "prepend_mode", "=", "prepend_inputs_full_attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L969-L999
[ "def", "attention_bias_prepend_inputs_full_attention", "(", "padding", ")", ":", "# Everything past the first padding position is part of the target.", "# This Tensor has zeros for the source portion and separator,", "# and ones for the target portion.", "in_target", "=", "tf", ".", "cumsu...
272500b6efe353aeb638d2745ed56e519462ca31
train
attention_bias_proximal
Bias for self-attention to encourage attention to close positions. Args: length: an integer scalar. Returns: a Tensor with shape [1, 1, length, length]
tensor2tensor/layers/common_attention.py
def attention_bias_proximal(length): """Bias for self-attention to encourage attention to close positions. Args: length: an integer scalar. Returns: a Tensor with shape [1, 1, length, length] """ r = tf.to_float(tf.range(length)) diff = tf.expand_dims(r, 0) - tf.expand_dims(r, 1) return tf.expan...
def attention_bias_proximal(length): """Bias for self-attention to encourage attention to close positions. Args: length: an integer scalar. Returns: a Tensor with shape [1, 1, length, length] """ r = tf.to_float(tf.range(length)) diff = tf.expand_dims(r, 0) - tf.expand_dims(r, 1) return tf.expan...
[ "Bias", "for", "self", "-", "attention", "to", "encourage", "attention", "to", "close", "positions", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1003-L1014
[ "def", "attention_bias_proximal", "(", "length", ")", ":", "r", "=", "tf", ".", "to_float", "(", "tf", ".", "range", "(", "length", ")", ")", "diff", "=", "tf", ".", "expand_dims", "(", "r", ",", "0", ")", "-", "tf", ".", "expand_dims", "(", "r", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
attention_bias_batch
Generate a mask to prevent the batch to attend to each others. Args: batch_coordinates_q: Int-like Tensor of shape [length_q, 1] containing the coordinates of the batches batch_coordinates_k: Int-like Tensor of shape [length_k, 1] containing the coordinates of the batches. If None, do self-attent...
tensor2tensor/layers/common_attention.py
def attention_bias_batch(batch_coordinates_q, batch_coordinates_k=None, condition_fn=None): """Generate a mask to prevent the batch to attend to each others. Args: batch_coordinates_q: Int-like Tensor of shape [length_q, 1] containing the coordinates of t...
def attention_bias_batch(batch_coordinates_q, batch_coordinates_k=None, condition_fn=None): """Generate a mask to prevent the batch to attend to each others. Args: batch_coordinates_q: Int-like Tensor of shape [length_q, 1] containing the coordinates of t...
[ "Generate", "a", "mask", "to", "prevent", "the", "batch", "to", "attend", "to", "each", "others", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1018-L1049
[ "def", "attention_bias_batch", "(", "batch_coordinates_q", ",", "batch_coordinates_k", "=", "None", ",", "condition_fn", "=", "None", ")", ":", "if", "batch_coordinates_k", "is", "None", ":", "batch_coordinates_k", "=", "batch_coordinates_q", "# Convert to float first bec...
272500b6efe353aeb638d2745ed56e519462ca31
train
split_last_dimension
Reshape x so that the last dimension becomes two dimensions. The first of these two dimensions is n. Args: x: a Tensor with shape [..., m] n: an integer. Returns: a Tensor with shape [..., n, m/n]
tensor2tensor/layers/common_attention.py
def split_last_dimension(x, n): """Reshape x so that the last dimension becomes two dimensions. The first of these two dimensions is n. Args: x: a Tensor with shape [..., m] n: an integer. Returns: a Tensor with shape [..., n, m/n] """ x_shape = common_layers.shape_list(x) m = x_shape[-1] ...
def split_last_dimension(x, n): """Reshape x so that the last dimension becomes two dimensions. The first of these two dimensions is n. Args: x: a Tensor with shape [..., m] n: an integer. Returns: a Tensor with shape [..., n, m/n] """ x_shape = common_layers.shape_list(x) m = x_shape[-1] ...
[ "Reshape", "x", "so", "that", "the", "last", "dimension", "becomes", "two", "dimensions", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1069-L1085
[ "def", "split_last_dimension", "(", "x", ",", "n", ")", ":", "x_shape", "=", "common_layers", ".", "shape_list", "(", "x", ")", "m", "=", "x_shape", "[", "-", "1", "]", "if", "isinstance", "(", "m", ",", "int", ")", "and", "isinstance", "(", "n", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
combine_last_two_dimensions
Reshape x so that the last two dimension become one. Args: x: a Tensor with shape [..., a, b] Returns: a Tensor with shape [..., ab]
tensor2tensor/layers/common_attention.py
def combine_last_two_dimensions(x): """Reshape x so that the last two dimension become one. Args: x: a Tensor with shape [..., a, b] Returns: a Tensor with shape [..., ab] """ x_shape = common_layers.shape_list(x) a, b = x_shape[-2:] return tf.reshape(x, x_shape[:-2] + [a * b])
def combine_last_two_dimensions(x): """Reshape x so that the last two dimension become one. Args: x: a Tensor with shape [..., a, b] Returns: a Tensor with shape [..., ab] """ x_shape = common_layers.shape_list(x) a, b = x_shape[-2:] return tf.reshape(x, x_shape[:-2] + [a * b])
[ "Reshape", "x", "so", "that", "the", "last", "two", "dimension", "become", "one", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1089-L1100
[ "def", "combine_last_two_dimensions", "(", "x", ")", ":", "x_shape", "=", "common_layers", ".", "shape_list", "(", "x", ")", "a", ",", "b", "=", "x_shape", "[", "-", "2", ":", "]", "return", "tf", ".", "reshape", "(", "x", ",", "x_shape", "[", ":", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
combine_first_two_dimensions
Reshape x so that the first two dimension become one. Args: x: a Tensor with shape [a, b, ...] Returns: a Tensor with shape [ab, ...]
tensor2tensor/layers/common_attention.py
def combine_first_two_dimensions(x): """Reshape x so that the first two dimension become one. Args: x: a Tensor with shape [a, b, ...] Returns: a Tensor with shape [ab, ...] """ ret = tf.reshape(x, tf.concat([[-1], common_layers.shape_list(x)[2:]], 0)) old_shape = x.get_shape().dims a, b = old_s...
def combine_first_two_dimensions(x): """Reshape x so that the first two dimension become one. Args: x: a Tensor with shape [a, b, ...] Returns: a Tensor with shape [ab, ...] """ ret = tf.reshape(x, tf.concat([[-1], common_layers.shape_list(x)[2:]], 0)) old_shape = x.get_shape().dims a, b = old_s...
[ "Reshape", "x", "so", "that", "the", "first", "two", "dimension", "become", "one", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1104-L1118
[ "def", "combine_first_two_dimensions", "(", "x", ")", ":", "ret", "=", "tf", ".", "reshape", "(", "x", ",", "tf", ".", "concat", "(", "[", "[", "-", "1", "]", ",", "common_layers", ".", "shape_list", "(", "x", ")", "[", "2", ":", "]", "]", ",", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
attention_image_summary
Compute color image summary. Args: attn: a Tensor with shape [batch, num_heads, query_length, memory_length] image_shapes: optional tuple of integer scalars. If the query positions and memory positions represent the pixels of flattened images, then pass in their dimensions: (query_rows, q...
tensor2tensor/layers/common_attention.py
def attention_image_summary(attn, image_shapes=None): """Compute color image summary. Args: attn: a Tensor with shape [batch, num_heads, query_length, memory_length] image_shapes: optional tuple of integer scalars. If the query positions and memory positions represent the pixels of flattened im...
def attention_image_summary(attn, image_shapes=None): """Compute color image summary. Args: attn: a Tensor with shape [batch, num_heads, query_length, memory_length] image_shapes: optional tuple of integer scalars. If the query positions and memory positions represent the pixels of flattened im...
[ "Compute", "color", "image", "summary", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1176-L1217
[ "def", "attention_image_summary", "(", "attn", ",", "image_shapes", "=", "None", ")", ":", "attn", "=", "tf", ".", "cast", "(", "attn", ",", "tf", ".", "float32", ")", "num_heads", "=", "common_layers", ".", "shape_list", "(", "attn", ")", "[", "1", "]...
272500b6efe353aeb638d2745ed56e519462ca31
train
grouped_attention_multihead
Multi-head dot-product attention with sparsity. For each attention head, the queries are partitioned into groups. For each group, only a subset of the key-value pairs are considered. The choices of groups are selected based on trained predictors of the total attention given the group inclusion. memory_targ...
tensor2tensor/layers/common_attention.py
def grouped_attention_multihead(query_antecedent, memory_antecedent, total_key_depth, total_value_depth, output_depth, num_heads, ...
def grouped_attention_multihead(query_antecedent, memory_antecedent, total_key_depth, total_value_depth, output_depth, num_heads, ...
[ "Multi", "-", "head", "dot", "-", "product", "attention", "with", "sparsity", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1220-L1472
[ "def", "grouped_attention_multihead", "(", "query_antecedent", ",", "memory_antecedent", ",", "total_key_depth", ",", "total_value_depth", ",", "output_depth", ",", "num_heads", ",", "num_groups", ",", "memory_target_density", "=", "2.0", ",", "multiplicative_overhead", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
harden_attention_weights
Make attention weights non-0 only on the top-hard_attention_k ones.
tensor2tensor/layers/common_attention.py
def harden_attention_weights(weights, hard_attention_k): """Make attention weights non-0 only on the top-hard_attention_k ones.""" # Subtract the top-kth weight and zero-out all lower ones. # Note that currently in case of numerical ties it will retain more # than k elements. In the future, we may want to avoid...
def harden_attention_weights(weights, hard_attention_k): """Make attention weights non-0 only on the top-hard_attention_k ones.""" # Subtract the top-kth weight and zero-out all lower ones. # Note that currently in case of numerical ties it will retain more # than k elements. In the future, we may want to avoid...
[ "Make", "attention", "weights", "non", "-", "0", "only", "on", "the", "top", "-", "hard_attention_k", "ones", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1475-L1486
[ "def", "harden_attention_weights", "(", "weights", ",", "hard_attention_k", ")", ":", "# Subtract the top-kth weight and zero-out all lower ones.", "# Note that currently in case of numerical ties it will retain more", "# than k elements. In the future, we may want to avoid this.", "weights", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
dot_product_attention
Dot-product attention. Args: q: Tensor with shape [..., length_q, depth_k]. k: Tensor with shape [..., length_kv, depth_k]. Leading dimensions must match with q. v: Tensor with shape [..., length_kv, depth_v] Leading dimensions must match with q. bias: bias Tensor (see attention_bias()) ...
tensor2tensor/layers/common_attention.py
def dot_product_attention(q, k, v, bias, dropout_rate=0.0, image_shapes=None, name=None, make_image_summary=True, ...
def dot_product_attention(q, k, v, bias, dropout_rate=0.0, image_shapes=None, name=None, make_image_summary=True, ...
[ "Dot", "-", "product", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1489-L1549
[ "def", "dot_product_attention", "(", "q", ",", "k", ",", "v", ",", "bias", ",", "dropout_rate", "=", "0.0", ",", "image_shapes", "=", "None", ",", "name", "=", "None", ",", "make_image_summary", "=", "True", ",", "save_weights_to", "=", "None", ",", "dro...
272500b6efe353aeb638d2745ed56e519462ca31
train
_generate_relative_positions_matrix
Generates matrix of relative positions between inputs.
tensor2tensor/layers/common_attention.py
def _generate_relative_positions_matrix(length_q, length_k, max_relative_position, cache=False): """Generates matrix of relative positions between inputs.""" if not cache: if length_q == length_k: range_vec_q = range_vec_k = t...
def _generate_relative_positions_matrix(length_q, length_k, max_relative_position, cache=False): """Generates matrix of relative positions between inputs.""" if not cache: if length_q == length_k: range_vec_q = range_vec_k = t...
[ "Generates", "matrix", "of", "relative", "positions", "between", "inputs", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1552-L1570
[ "def", "_generate_relative_positions_matrix", "(", "length_q", ",", "length_k", ",", "max_relative_position", ",", "cache", "=", "False", ")", ":", "if", "not", "cache", ":", "if", "length_q", "==", "length_k", ":", "range_vec_q", "=", "range_vec_k", "=", "tf", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_generate_relative_positions_embeddings
Generates tensor of size [1 if cache else length_q, length_k, depth].
tensor2tensor/layers/common_attention.py
def _generate_relative_positions_embeddings(length_q, length_k, depth, max_relative_position, name, cache=False): """Generates tensor of size [1 if cache else length_q, length_k, depth].""" with tf.variable_scope(name): rela...
def _generate_relative_positions_embeddings(length_q, length_k, depth, max_relative_position, name, cache=False): """Generates tensor of size [1 if cache else length_q, length_k, depth].""" with tf.variable_scope(name): rela...
[ "Generates", "tensor", "of", "size", "[", "1", "if", "cache", "else", "length_q", "length_k", "depth", "]", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1573-L1584
[ "def", "_generate_relative_positions_embeddings", "(", "length_q", ",", "length_k", ",", "depth", ",", "max_relative_position", ",", "name", ",", "cache", "=", "False", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "relative_positions_matri...
272500b6efe353aeb638d2745ed56e519462ca31
train
_relative_attention_inner
Relative position-aware dot-product attention inner calculation. This batches matrix multiply calculations to avoid unnecessary broadcasting. Args: x: Tensor with shape [batch_size, heads, length or 1, length or depth]. y: Tensor with shape [batch_size, heads, length or 1, depth]. z: Tensor with shape...
tensor2tensor/layers/common_attention.py
def _relative_attention_inner(x, y, z, transpose): """Relative position-aware dot-product attention inner calculation. This batches matrix multiply calculations to avoid unnecessary broadcasting. Args: x: Tensor with shape [batch_size, heads, length or 1, length or depth]. y: Tensor with shape [batch_si...
def _relative_attention_inner(x, y, z, transpose): """Relative position-aware dot-product attention inner calculation. This batches matrix multiply calculations to avoid unnecessary broadcasting. Args: x: Tensor with shape [batch_size, heads, length or 1, length or depth]. y: Tensor with shape [batch_si...
[ "Relative", "position", "-", "aware", "dot", "-", "product", "attention", "inner", "calculation", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1587-L1618
[ "def", "_relative_attention_inner", "(", "x", ",", "y", ",", "z", ",", "transpose", ")", ":", "batch_size", "=", "tf", ".", "shape", "(", "x", ")", "[", "0", "]", "heads", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "1", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
dot_product_attention_relative
Calculate relative position-aware dot-product self-attention. The attention calculation is augmented with learned representations for the relative position between each element in q and each element in k and v. Args: q: a Tensor with shape [batch, heads, length, depth]. k: a Tensor with shape [batch, he...
tensor2tensor/layers/common_attention.py
def dot_product_attention_relative(q, k, v, bias, max_relative_position, dropout_rate=0.0, image_shapes=None, ...
def dot_product_attention_relative(q, k, v, bias, max_relative_position, dropout_rate=0.0, image_shapes=None, ...
[ "Calculate", "relative", "position", "-", "aware", "dot", "-", "product", "self", "-", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1621-L1702
[ "def", "dot_product_attention_relative", "(", "q", ",", "k", ",", "v", ",", "bias", ",", "max_relative_position", ",", "dropout_rate", "=", "0.0", ",", "image_shapes", "=", "None", ",", "save_weights_to", "=", "None", ",", "name", "=", "None", ",", "make_ima...
272500b6efe353aeb638d2745ed56e519462ca31
train
_relative_position_to_absolute_position_masked
Helper to dot_product_self_attention_relative_v2. Rearrange an attention logits or weights Tensor. The dimensions of the input represent: [batch, heads, query_position, memory_position - query_position + length - 1] The dimensions of the output represent: [batch, heads, query_position, memory_position] ...
tensor2tensor/layers/common_attention.py
def _relative_position_to_absolute_position_masked(x): """Helper to dot_product_self_attention_relative_v2. Rearrange an attention logits or weights Tensor. The dimensions of the input represent: [batch, heads, query_position, memory_position - query_position + length - 1] The dimensions of the output repr...
def _relative_position_to_absolute_position_masked(x): """Helper to dot_product_self_attention_relative_v2. Rearrange an attention logits or weights Tensor. The dimensions of the input represent: [batch, heads, query_position, memory_position - query_position + length - 1] The dimensions of the output repr...
[ "Helper", "to", "dot_product_self_attention_relative_v2", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1705-L1729
[ "def", "_relative_position_to_absolute_position_masked", "(", "x", ")", ":", "batch", ",", "heads", ",", "length", ",", "_", "=", "common_layers", ".", "shape_list", "(", "x", ")", "x", "=", "tf", ".", "pad", "(", "x", ",", "[", "[", "0", ",", "0", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
dot_product_self_attention_relative_v2
Calculate relative position-aware dot-product self-attention. Only works for masked self-attention (no looking forward). The attention calculation is augmented with learned representations for the relative position between each element in q and each element in k and v. Args: q: a Tensor with shape [batch...
tensor2tensor/layers/common_attention.py
def dot_product_self_attention_relative_v2(q, k, v, bias, max_relative_position=None, dropout_rate=0.0, ...
def dot_product_self_attention_relative_v2(q, k, v, bias, max_relative_position=None, dropout_rate=0.0, ...
[ "Calculate", "relative", "position", "-", "aware", "dot", "-", "product", "self", "-", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1809-L1899
[ "def", "dot_product_self_attention_relative_v2", "(", "q", ",", "k", ",", "v", ",", "bias", ",", "max_relative_position", "=", "None", ",", "dropout_rate", "=", "0.0", ",", "image_shapes", "=", "None", ",", "name", "=", "None", ",", "make_image_summary", "=", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_absolute_position_to_relative_position_unmasked
Helper function for dot_product_unmasked_self_attention_relative_v2. Rearrange an attention logits or weights Tensor. The dimensions of the input represent: [batch, heads, query_position, memory_position] The dimensions of the output represent: [batch, heads, query_position, memory_position - query_positio...
tensor2tensor/layers/common_attention.py
def _absolute_position_to_relative_position_unmasked(x): """Helper function for dot_product_unmasked_self_attention_relative_v2. Rearrange an attention logits or weights Tensor. The dimensions of the input represent: [batch, heads, query_position, memory_position] The dimensions of the output represent: ...
def _absolute_position_to_relative_position_unmasked(x): """Helper function for dot_product_unmasked_self_attention_relative_v2. Rearrange an attention logits or weights Tensor. The dimensions of the input represent: [batch, heads, query_position, memory_position] The dimensions of the output represent: ...
[ "Helper", "function", "for", "dot_product_unmasked_self_attention_relative_v2", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1902-L1930
[ "def", "_absolute_position_to_relative_position_unmasked", "(", "x", ")", ":", "batch", ",", "heads", ",", "length", ",", "_", "=", "common_layers", ".", "shape_list", "(", "x", ")", "# padd along column", "x", "=", "tf", ".", "pad", "(", "x", ",", "[", "[...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_relative_embeddings_left_right
Instantiate or retrieve relative embeddings, sliced according to length. Use for unmasked case where the relative attention looks both left and right. Args: max_relative_position: an Integer for the number of entries in the relative embedding, which corresponds to the max relative distance that is ...
tensor2tensor/layers/common_attention.py
def get_relative_embeddings_left_right(max_relative_position, length, depth, num_heads, heads_share_relative_embedding, name): """Instantiate or retrieve relative embeddings, sliced according to length...
def get_relative_embeddings_left_right(max_relative_position, length, depth, num_heads, heads_share_relative_embedding, name): """Instantiate or retrieve relative embeddings, sliced according to length...
[ "Instantiate", "or", "retrieve", "relative", "embeddings", "sliced", "according", "to", "length", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1933-L1982
[ "def", "get_relative_embeddings_left_right", "(", "max_relative_position", ",", "length", ",", "depth", ",", "num_heads", ",", "heads_share_relative_embedding", ",", "name", ")", ":", "initializer_stddev", "=", "depth", "**", "-", "0.5", "max_relative_position_unmasked", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
dot_product_unmasked_self_attention_relative_v2
Calculate relative position-aware dot-product self-attention. The attention calculation is augmented with learned representations for the relative position between each element in q and each element in k and v. Args: q: a Tensor with shape [batch, heads, length, depth]. k: a Tensor with shape [batch, he...
tensor2tensor/layers/common_attention.py
def dot_product_unmasked_self_attention_relative_v2( q, k, v, bias, max_relative_position=None, dropout_rate=0.0, image_shapes=None, name=None, make_image_summary=True, dropout_broadcast_dims=None, heads_share_relative_embedding=False, add_relative_to_values=False): """Calculate relative position-awar...
def dot_product_unmasked_self_attention_relative_v2( q, k, v, bias, max_relative_position=None, dropout_rate=0.0, image_shapes=None, name=None, make_image_summary=True, dropout_broadcast_dims=None, heads_share_relative_embedding=False, add_relative_to_values=False): """Calculate relative position-awar...
[ "Calculate", "relative", "position", "-", "aware", "dot", "-", "product", "self", "-", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1985-L2074
[ "def", "dot_product_unmasked_self_attention_relative_v2", "(", "q", ",", "k", ",", "v", ",", "bias", ",", "max_relative_position", "=", "None", ",", "dropout_rate", "=", "0.0", ",", "image_shapes", "=", "None", ",", "name", "=", "None", ",", "make_image_summary"...
272500b6efe353aeb638d2745ed56e519462ca31
train
_matmul_with_relative_keys_2d
Helper function for dot_product_unmasked_self_attention_relative_2d.
tensor2tensor/layers/common_attention.py
def _matmul_with_relative_keys_2d(x, y, heads_share_relative_embedding): """Helper function for dot_product_unmasked_self_attention_relative_2d.""" if heads_share_relative_embedding: ret = tf.einsum("bhxyd,md->bhxym", x, y) else: ret = tf.einsum("bhxyd,hmd->bhxym", x, y) return ret
def _matmul_with_relative_keys_2d(x, y, heads_share_relative_embedding): """Helper function for dot_product_unmasked_self_attention_relative_2d.""" if heads_share_relative_embedding: ret = tf.einsum("bhxyd,md->bhxym", x, y) else: ret = tf.einsum("bhxyd,hmd->bhxym", x, y) return ret
[ "Helper", "function", "for", "dot_product_unmasked_self_attention_relative_2d", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2077-L2083
[ "def", "_matmul_with_relative_keys_2d", "(", "x", ",", "y", ",", "heads_share_relative_embedding", ")", ":", "if", "heads_share_relative_embedding", ":", "ret", "=", "tf", ".", "einsum", "(", "\"bhxyd,md->bhxym\"", ",", "x", ",", "y", ")", "else", ":", "ret", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
dot_product_unmasked_self_attention_relative_2d
Calculate relative position unmasked dot-product self-attention 2d. The attention calculation is augmented with learned representations for the relative position between each element in q and each element in k and v in height and width dimensions. for query index (i,j) and key index (l, m), the logit is q_i k...
tensor2tensor/layers/common_attention.py
def dot_product_unmasked_self_attention_relative_2d( q, k, v, bias, max_relative_position=None, dropout_rate=0.0, image_shapes=None, name=None, make_image_summary=True, dropout_broadcast_dims=None, heads_share_relative_embedding=False, add_relative_to_values=False): """Calculate relative position unma...
def dot_product_unmasked_self_attention_relative_2d( q, k, v, bias, max_relative_position=None, dropout_rate=0.0, image_shapes=None, name=None, make_image_summary=True, dropout_broadcast_dims=None, heads_share_relative_embedding=False, add_relative_to_values=False): """Calculate relative position unma...
[ "Calculate", "relative", "position", "unmasked", "dot", "-", "product", "self", "-", "attention", "2d", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2086-L2225
[ "def", "dot_product_unmasked_self_attention_relative_2d", "(", "q", ",", "k", ",", "v", ",", "bias", ",", "max_relative_position", "=", "None", ",", "dropout_rate", "=", "0.0", ",", "image_shapes", "=", "None", ",", "name", "=", "None", ",", "make_image_summary"...
272500b6efe353aeb638d2745ed56e519462ca31
train
_split_along_width
Helper function for local 2d attention. Takes a tensor of [batch, heads, num_h_blocks, num_w_blocks, height, width, depth] and returns two tensors which contain every alternate position along the width Args: x_left_right_blocks: A [batch, num_h_blocks, num_w_blocks, height, wi...
tensor2tensor/layers/common_attention.py
def _split_along_width(x_left_right_blocks): """Helper function for local 2d attention. Takes a tensor of [batch, heads, num_h_blocks, num_w_blocks, height, width, depth] and returns two tensors which contain every alternate position along the width Args: x_left_right_blocks: A [batch, num_h_blocks, nu...
def _split_along_width(x_left_right_blocks): """Helper function for local 2d attention. Takes a tensor of [batch, heads, num_h_blocks, num_w_blocks, height, width, depth] and returns two tensors which contain every alternate position along the width Args: x_left_right_blocks: A [batch, num_h_blocks, nu...
[ "Helper", "function", "for", "local", "2d", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2228-L2265
[ "def", "_split_along_width", "(", "x_left_right_blocks", ")", ":", "(", "_", ",", "x_num_h_blocks", ",", "x_num_outer_w_blocks", ",", "x_memory_flange_h", ",", "x_memory_flange_w", ",", "depth", ")", "=", "common_layers", ".", "shape_list", "(", "x_left_right_blocks",...
272500b6efe353aeb638d2745ed56e519462ca31
train
_get_left_right_blocks
Helper function. Assumes that memory_flange is half of query sizes. This function splits the tensor of width 'n' into two halves, where the first half gets the width indices 0, 2, 4.. and the second half gets the width indices 3, 5, ... We also fuse two blocks along the h dimension. Args: x: a 6-d tensor....
tensor2tensor/layers/common_attention.py
def _get_left_right_blocks(x): """Helper function. Assumes that memory_flange is half of query sizes. This function splits the tensor of width 'n' into two halves, where the first half gets the width indices 0, 2, 4.. and the second half gets the width indices 3, 5, ... We also fuse two blocks along the h dime...
def _get_left_right_blocks(x): """Helper function. Assumes that memory_flange is half of query sizes. This function splits the tensor of width 'n' into two halves, where the first half gets the width indices 0, 2, 4.. and the second half gets the width indices 3, 5, ... We also fuse two blocks along the h dime...
[ "Helper", "function", ".", "Assumes", "that", "memory_flange", "is", "half", "of", "query", "sizes", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2268-L2303
[ "def", "_get_left_right_blocks", "(", "x", ")", ":", "(", "_", ",", "x_num_outer_h_blocks", ",", "x_num_outer_w_blocks", ",", "x_memory_flange_h", ",", "x_memory_flange_w", ",", "depth", ")", "=", "common_layers", ".", "shape_list", "(", "x", ")", "x_left_right_bl...
272500b6efe353aeb638d2745ed56e519462ca31
train
_extract_blocks
Helper function for local 2d attention. Args: x: a [batch, height, width, depth] tensor block_h: An integer. block height block_w: An inteter. block width returns: a [batch, num_heads, height/block_h, width/block_w, depth] tensor
tensor2tensor/layers/common_attention.py
def _extract_blocks(x, block_h, block_w): """Helper function for local 2d attention. Args: x: a [batch, height, width, depth] tensor block_h: An integer. block height block_w: An inteter. block width returns: a [batch, num_heads, height/block_h, width/block_w, depth] tensor """ (_, height, w...
def _extract_blocks(x, block_h, block_w): """Helper function for local 2d attention. Args: x: a [batch, height, width, depth] tensor block_h: An integer. block height block_w: An inteter. block width returns: a [batch, num_heads, height/block_h, width/block_w, depth] tensor """ (_, height, w...
[ "Helper", "function", "for", "local", "2d", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2307-L2323
[ "def", "_extract_blocks", "(", "x", ",", "block_h", ",", "block_w", ")", ":", "(", "_", ",", "height", ",", "width", ",", "depth", ")", "=", "common_layers", ".", "shape_list", "(", "x", ")", "assert", "height", "%", "block_h", "==", "0", "assert", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_2d_local_memory
Stitches together the local 2d memory blocks. Args: x: a [batch, height, width, depth tensor] query_shape: 2-d integer list of query shape memory_flange: 2-d integer list of memory flanges Returns: x: A [batch, num_h_blocks, num_w_blocks, query_shape[0]+2*memory_flange[0],query_shape[1]+...
tensor2tensor/layers/common_attention.py
def get_2d_local_memory(x, query_shape, memory_flange): """Stitches together the local 2d memory blocks. Args: x: a [batch, height, width, depth tensor] query_shape: 2-d integer list of query shape memory_flange: 2-d integer list of memory flanges Returns: x: A [batch, num_h_blocks, num_w_blocks...
def get_2d_local_memory(x, query_shape, memory_flange): """Stitches together the local 2d memory blocks. Args: x: a [batch, height, width, depth tensor] query_shape: 2-d integer list of query shape memory_flange: 2-d integer list of memory flanges Returns: x: A [batch, num_h_blocks, num_w_blocks...
[ "Stitches", "together", "the", "local", "2d", "memory", "blocks", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2326-L2404
[ "def", "get_2d_local_memory", "(", "x", ",", "query_shape", ",", "memory_flange", ")", ":", "(", "_", ",", "height", ",", "width", ",", "depth_x", ")", "=", "common_layers", ".", "shape_list", "(", "x", ")", "x_center_blocks", "=", "_extract_blocks", "(", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_2d_local_memory_v2
Gathering memory blocks around query blocks. flange is half of query . Only works if memory flanges are half of query sizes. Args: x: a [batch, height, width, depth tensor] query_shape: 2-d integer list of query shape memory_flange: 2-d integer list of memory flanges Returns: x: A [batch, num...
tensor2tensor/layers/common_attention.py
def get_2d_local_memory_v2(x, query_shape, memory_flange): """Gathering memory blocks around query blocks. flange is half of query . Only works if memory flanges are half of query sizes. Args: x: a [batch, height, width, depth tensor] query_shape: 2-d integer list of query shape memory_flange: 2-d...
def get_2d_local_memory_v2(x, query_shape, memory_flange): """Gathering memory blocks around query blocks. flange is half of query . Only works if memory flanges are half of query sizes. Args: x: a [batch, height, width, depth tensor] query_shape: 2-d integer list of query shape memory_flange: 2-d...
[ "Gathering", "memory", "blocks", "around", "query", "blocks", ".", "flange", "is", "half", "of", "query", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2407-L2445
[ "def", "get_2d_local_memory_v2", "(", "x", ",", "query_shape", ",", "memory_flange", ")", ":", "(", "_", ",", "height", ",", "width", ",", "depth_x", ")", "=", "common_layers", ".", "shape_list", "(", "x", ")", "# add extra padding to x so that we can extract the ...
272500b6efe353aeb638d2745ed56e519462ca31
train
dot_product_unmasked_attention_local_2d_tpu
Calculate unmasked dot-product local self-attention 2d on tpu. Args: q: a Tensor with shape [batch, heads, height, width, depth]. k: a Tensor with shape [batch, heads, height, width, depth]. v: a Tensor with shape [batch, heads, height, width, depth]. bias: bias Tensor. max_relative_position: an ...
tensor2tensor/layers/common_attention.py
def dot_product_unmasked_attention_local_2d_tpu( q, k, v, bias, max_relative_position=None, query_shape=(8, 8), dropout_rate=0.0, image_shapes=None, name=None, make_image_summary=False, dropout_broadcast_dims=None): """Calculate unmasked dot-product local self-attention 2d on tpu. Args: q: a Tensor...
def dot_product_unmasked_attention_local_2d_tpu( q, k, v, bias, max_relative_position=None, query_shape=(8, 8), dropout_rate=0.0, image_shapes=None, name=None, make_image_summary=False, dropout_broadcast_dims=None): """Calculate unmasked dot-product local self-attention 2d on tpu. Args: q: a Tensor...
[ "Calculate", "unmasked", "dot", "-", "product", "local", "self", "-", "attention", "2d", "on", "tpu", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2448-L2537
[ "def", "dot_product_unmasked_attention_local_2d_tpu", "(", "q", ",", "k", ",", "v", ",", "bias", ",", "max_relative_position", "=", "None", ",", "query_shape", "=", "(", "8", ",", "8", ")", ",", "dropout_rate", "=", "0.0", ",", "image_shapes", "=", "None", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
dot_product_unmasked_attention_local_2d_tpu_simple
Calculate simple unmasked dot-product local self-attention 2d on tpu. The query, key, and value blocks are the same. We do not do a second linear transformation after computing the values Args: x: a Tensor with shape [batch, height, width, depth]. bias: bias Tensor. total_key_depth: the dimensions o...
tensor2tensor/layers/common_attention.py
def dot_product_unmasked_attention_local_2d_tpu_simple( x, bias, total_key_depth, total_value_depth, num_heads, query_shape=(8, 8), dropout_rate=0.0, image_shapes=None, make_image_summary=False, dropout_broadcast_dims=None): """Calculate simple unmasked dot-product local self-attention 2d on tpu. ...
def dot_product_unmasked_attention_local_2d_tpu_simple( x, bias, total_key_depth, total_value_depth, num_heads, query_shape=(8, 8), dropout_rate=0.0, image_shapes=None, make_image_summary=False, dropout_broadcast_dims=None): """Calculate simple unmasked dot-product local self-attention 2d on tpu. ...
[ "Calculate", "simple", "unmasked", "dot", "-", "product", "local", "self", "-", "attention", "2d", "on", "tpu", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2540-L2615
[ "def", "dot_product_unmasked_attention_local_2d_tpu_simple", "(", "x", ",", "bias", ",", "total_key_depth", ",", "total_value_depth", ",", "num_heads", ",", "query_shape", "=", "(", "8", ",", "8", ")", ",", "dropout_rate", "=", "0.0", ",", "image_shapes", "=", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
masked_within_block_local_attention_1d
Attention to the source and a neighborhood to the left within a block. The sequence is divided into blocks of length block_length. Attention for a given query position can only see memory positions less than or equal to the query position in the corresponding block. Args: q: a Tensor with shape [batch, he...
tensor2tensor/layers/common_attention.py
def masked_within_block_local_attention_1d(q, k, v, block_length=64, name=None): """Attention to the source and a neighborhood to the left within a block. The sequence is divided into blocks of length block_length. Attention for a given query position can only see memory positions less than or equal to the que...
def masked_within_block_local_attention_1d(q, k, v, block_length=64, name=None): """Attention to the source and a neighborhood to the left within a block. The sequence is divided into blocks of length block_length. Attention for a given query position can only see memory positions less than or equal to the que...
[ "Attention", "to", "the", "source", "and", "a", "neighborhood", "to", "the", "left", "within", "a", "block", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2618-L2671
[ "def", "masked_within_block_local_attention_1d", "(", "q", ",", "k", ",", "v", ",", "block_length", "=", "64", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"within_local_attention_1d\"", ",",...
272500b6efe353aeb638d2745ed56e519462ca31
train
_relative_position_to_absolute_position_unmasked
Converts tensor from relative to aboslute indexing for local attention. Args: x: a Tensor of shape [batch (or batch*num_blocks), heads, length, 2 * length - 1] Returns: A Tensor of shape [batch (or batch*num_blocks), heads, length, length-1]
tensor2tensor/layers/common_attention.py
def _relative_position_to_absolute_position_unmasked(x): """Converts tensor from relative to aboslute indexing for local attention. Args: x: a Tensor of shape [batch (or batch*num_blocks), heads, length, 2 * length - 1] Returns: A Tensor of shape [batch (or batch*num_blocks), h...
def _relative_position_to_absolute_position_unmasked(x): """Converts tensor from relative to aboslute indexing for local attention. Args: x: a Tensor of shape [batch (or batch*num_blocks), heads, length, 2 * length - 1] Returns: A Tensor of shape [batch (or batch*num_blocks), h...
[ "Converts", "tensor", "from", "relative", "to", "aboslute", "indexing", "for", "local", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2674-L2701
[ "def", "_relative_position_to_absolute_position_unmasked", "(", "x", ")", ":", "x_shape", "=", "common_layers", ".", "shape_list", "(", "x", ")", "batch", "=", "x_shape", "[", "0", "]", "heads", "=", "x_shape", "[", "1", "]", "length", "=", "x_shape", "[", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
masked_local_attention_1d
Attention to the source position and a neighborhood to the left of it. The sequence is divided into blocks of length block_length. Attention for a given query position can only see memory positions less than or equal to the query position, in the corresponding block and the previous block. Args: q: a Tens...
tensor2tensor/layers/common_attention.py
def masked_local_attention_1d(q, k, v, block_length=128, make_image_summary=False, dropout_rate=0., name=None): """Attention to the source...
def masked_local_attention_1d(q, k, v, block_length=128, make_image_summary=False, dropout_rate=0., name=None): """Attention to the source...
[ "Attention", "to", "the", "source", "position", "and", "a", "neighborhood", "to", "the", "left", "of", "it", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2704-L2812
[ "def", "masked_local_attention_1d", "(", "q", ",", "k", ",", "v", ",", "block_length", "=", "128", ",", "make_image_summary", "=", "False", ",", "dropout_rate", "=", "0.", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "nam...
272500b6efe353aeb638d2745ed56e519462ca31
train
_make_local_block
Helper function to create a local version of the keys or values for 1d.
tensor2tensor/layers/common_attention.py
def _make_local_block(x, depth, batch, heads, num_blocks, block_length): """Helper function to create a local version of the keys or values for 1d.""" prev_block = tf.slice(x, [0, 0, 0, 0, 0], [-1, -1, num_blocks - 1, -1, -1]) cur_block = tf.slice(x, [0, 0, 1, 0, 0], [-1, -1, -1, -1, -1]) ...
def _make_local_block(x, depth, batch, heads, num_blocks, block_length): """Helper function to create a local version of the keys or values for 1d.""" prev_block = tf.slice(x, [0, 0, 0, 0, 0], [-1, -1, num_blocks - 1, -1, -1]) cur_block = tf.slice(x, [0, 0, 1, 0, 0], [-1, -1, -1, -1, -1]) ...
[ "Helper", "function", "to", "create", "a", "local", "version", "of", "the", "keys", "or", "values", "for", "1d", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2815-L2822
[ "def", "_make_local_block", "(", "x", ",", "depth", ",", "batch", ",", "heads", ",", "num_blocks", ",", "block_length", ")", ":", "prev_block", "=", "tf", ".", "slice", "(", "x", ",", "[", "0", ",", "0", ",", "0", ",", "0", ",", "0", "]", ",", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
masked_relative_local_attention_1d
Masked local 1d attention with relative positions. The sequence is divided into blocks of length block_size. Attention for a given query position can only see memory positions less than or equal to the query position, in the corresponding block and the previous block. If mask_right is True, then a target po...
tensor2tensor/layers/common_attention.py
def masked_relative_local_attention_1d(q, k, v, block_length=128, make_image_summary=False, dropout_rate=0., ...
def masked_relative_local_attention_1d(q, k, v, block_length=128, make_image_summary=False, dropout_rate=0., ...
[ "Masked", "local", "1d", "attention", "with", "relative", "positions", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2825-L3033
[ "def", "masked_relative_local_attention_1d", "(", "q", ",", "k", ",", "v", ",", "block_length", "=", "128", ",", "make_image_summary", "=", "False", ",", "dropout_rate", "=", "0.", ",", "heads_share_relative_embedding", "=", "False", ",", "add_relative_to_values", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
local_attention_1d
Strided block local self-attention. The sequence is divided into blocks of length block_length. Attention for a given query position can see all memory positions in the corresponding block and filter_width many positions to the left and right of the block. Args: q: a Tensor with shape [batch, heads, lengt...
tensor2tensor/layers/common_attention.py
def local_attention_1d(q, k, v, block_length=128, filter_width=100, name=None): """Strided block local self-attention. The sequence is divided into blocks of length block_length. Attention for a given query position can see all memory positions in the corresponding block and filter_width many positions to the ...
def local_attention_1d(q, k, v, block_length=128, filter_width=100, name=None): """Strided block local self-attention. The sequence is divided into blocks of length block_length. Attention for a given query position can see all memory positions in the corresponding block and filter_width many positions to the ...
[ "Strided", "block", "local", "self", "-", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3052-L3154
[ "def", "local_attention_1d", "(", "q", ",", "k", ",", "v", ",", "block_length", "=", "128", ",", "filter_width", "=", "100", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"local_self_att...
272500b6efe353aeb638d2745ed56e519462ca31
train
reshape_by_blocks
Reshapes input by splitting its length over blocks of memory_block_size. Args: x: a Tensor with shape [batch, heads, length, depth] x_shape: tf.TensorShape of x. memory_block_size: Integer which divides length. Returns: Tensor with shape [batch, heads, length // memory_block_size, memory_block...
tensor2tensor/layers/common_attention.py
def reshape_by_blocks(x, x_shape, memory_block_size): """Reshapes input by splitting its length over blocks of memory_block_size. Args: x: a Tensor with shape [batch, heads, length, depth] x_shape: tf.TensorShape of x. memory_block_size: Integer which divides length. Returns: Tensor with shape ...
def reshape_by_blocks(x, x_shape, memory_block_size): """Reshapes input by splitting its length over blocks of memory_block_size. Args: x: a Tensor with shape [batch, heads, length, depth] x_shape: tf.TensorShape of x. memory_block_size: Integer which divides length. Returns: Tensor with shape ...
[ "Reshapes", "input", "by", "splitting", "its", "length", "over", "blocks", "of", "memory_block_size", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3157-L3173
[ "def", "reshape_by_blocks", "(", "x", ",", "x_shape", ",", "memory_block_size", ")", ":", "x", "=", "tf", ".", "reshape", "(", "x", ",", "[", "x_shape", "[", "0", "]", ",", "x_shape", "[", "1", "]", ",", "x_shape", "[", "2", "]", "//", "memory_bloc...
272500b6efe353aeb638d2745ed56e519462ca31
train
dilated_self_attention_1d
Dilated self-attention. Args: q: a Tensor with shape [batch, heads, length, depth] k: a Tensor with shape [batch, heads, length, depth] v: a Tensor with shape [batch, heads, length, depth] query_block_size: an integer indicating size of query block memory_block_size: an integer indicating the siz...
tensor2tensor/layers/common_attention.py
def dilated_self_attention_1d(q, k, v, query_block_size=128, memory_block_size=128, gap_size=2, num_memory_blocks=2, ...
def dilated_self_attention_1d(q, k, v, query_block_size=128, memory_block_size=128, gap_size=2, num_memory_blocks=2, ...
[ "Dilated", "self", "-", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3176-L3293
[ "def", "dilated_self_attention_1d", "(", "q", ",", "k", ",", "v", ",", "query_block_size", "=", "128", ",", "memory_block_size", "=", "128", ",", "gap_size", "=", "2", ",", "num_memory_blocks", "=", "2", ",", "name", "=", "None", ")", ":", "with", "tf", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
gather_dilated_memory_blocks
Gathers blocks with gaps in between. Args: x: Tensor of shape [length, batch, heads, depth] num_memory_blocks: how many memory blocks to look in "direction". Each will be separated by gap_size. gap_size: an integer indicating the gap size query_block_size: an integer indicating size of query bl...
tensor2tensor/layers/common_attention.py
def gather_dilated_memory_blocks(x, num_memory_blocks, gap_size, query_block_size, memory_block_size, gather_indices, dire...
def gather_dilated_memory_blocks(x, num_memory_blocks, gap_size, query_block_size, memory_block_size, gather_indices, dire...
[ "Gathers", "blocks", "with", "gaps", "in", "between", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3296-L3339
[ "def", "gather_dilated_memory_blocks", "(", "x", ",", "num_memory_blocks", ",", "gap_size", ",", "query_block_size", ",", "memory_block_size", ",", "gather_indices", ",", "direction", "=", "\"left\"", ")", ":", "gathered_blocks", "=", "[", "]", "# gathering memory blo...
272500b6efe353aeb638d2745ed56e519462ca31
train
masked_dilated_self_attention_1d
Dilated self-attention. TODO(avaswani): Try it and write a paper on it. Args: q: a Tensor with shape [batch, heads, length, depth] k: a Tensor with shape [batch, heads, length, depth] v: a Tensor with shape [batch, heads, length, depth] query_block_size: an integer memory_block_size: an integer i...
tensor2tensor/layers/common_attention.py
def masked_dilated_self_attention_1d(q, k, v, query_block_size=64, memory_block_size=64, gap_size=2, ...
def masked_dilated_self_attention_1d(q, k, v, query_block_size=64, memory_block_size=64, gap_size=2, ...
[ "Dilated", "self", "-", "attention", ".", "TODO", "(", "avaswani", ")", ":", "Try", "it", "and", "write", "a", "paper", "on", "it", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3342-L3452
[ "def", "masked_dilated_self_attention_1d", "(", "q", ",", "k", ",", "v", ",", "query_block_size", "=", "64", ",", "memory_block_size", "=", "64", ",", "gap_size", "=", "2", ",", "num_memory_blocks", "=", "2", ",", "name", "=", "None", ")", ":", "with", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
local_attention_2d
Strided block local self-attention. The 2-D sequence is divided into 2-D blocks of shape query_shape. Attention for a given query position can only see memory positions less than or equal to the query position. The memory positions are the corresponding block with memory_flange many positions to add to the hei...
tensor2tensor/layers/common_attention.py
def local_attention_2d(q, k, v, query_shape=(8, 16), memory_flange=(8, 16), name=None): """Strided block local self-attention. The 2-D sequence is divided into 2-D blocks of shape query_shape. Attenti...
def local_attention_2d(q, k, v, query_shape=(8, 16), memory_flange=(8, 16), name=None): """Strided block local self-attention. The 2-D sequence is divided into 2-D blocks of shape query_shape. Attenti...
[ "Strided", "block", "local", "self", "-", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3455-L3523
[ "def", "local_attention_2d", "(", "q", ",", "k", ",", "v", ",", "query_shape", "=", "(", "8", ",", "16", ")", ",", "memory_flange", "=", "(", "8", ",", "16", ")", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name...
272500b6efe353aeb638d2745ed56e519462ca31
train
pad_to_multiple_2d
Making sure x is a multiple of shape. Args: x: a [batch, heads, h, w, depth] or [batch, h, w, depth] tensor block_shape: a 2-d list of integer shapes Returns: padded_x: a [batch, heads, h, w, depth] or [batch, h, w, depth] tensor
tensor2tensor/layers/common_attention.py
def pad_to_multiple_2d(x, block_shape): """Making sure x is a multiple of shape. Args: x: a [batch, heads, h, w, depth] or [batch, h, w, depth] tensor block_shape: a 2-d list of integer shapes Returns: padded_x: a [batch, heads, h, w, depth] or [batch, h, w, depth] tensor """ old_shape = x.get_s...
def pad_to_multiple_2d(x, block_shape): """Making sure x is a multiple of shape. Args: x: a [batch, heads, h, w, depth] or [batch, h, w, depth] tensor block_shape: a 2-d list of integer shapes Returns: padded_x: a [batch, heads, h, w, depth] or [batch, h, w, depth] tensor """ old_shape = x.get_s...
[ "Making", "sure", "x", "is", "a", "multiple", "of", "shape", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3526-L3551
[ "def", "pad_to_multiple_2d", "(", "x", ",", "block_shape", ")", ":", "old_shape", "=", "x", ".", "get_shape", "(", ")", ".", "dims", "last", "=", "old_shape", "[", "-", "1", "]", "if", "len", "(", "old_shape", ")", "==", "4", ":", "height_padding", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
reshape_range
Reshapes a tensor between dimensions i and j.
tensor2tensor/layers/common_attention.py
def reshape_range(tensor, i, j, shape): """Reshapes a tensor between dimensions i and j.""" t_shape = common_layers.shape_list(tensor) target_shape = t_shape[:i] + shape + t_shape[j:] return tf.reshape(tensor, target_shape)
def reshape_range(tensor, i, j, shape): """Reshapes a tensor between dimensions i and j.""" t_shape = common_layers.shape_list(tensor) target_shape = t_shape[:i] + shape + t_shape[j:] return tf.reshape(tensor, target_shape)
[ "Reshapes", "a", "tensor", "between", "dimensions", "i", "and", "j", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3554-L3558
[ "def", "reshape_range", "(", "tensor", ",", "i", ",", "j", ",", "shape", ")", ":", "t_shape", "=", "common_layers", ".", "shape_list", "(", "tensor", ")", "target_shape", "=", "t_shape", "[", ":", "i", "]", "+", "shape", "+", "t_shape", "[", "j", ":"...
272500b6efe353aeb638d2745ed56e519462ca31
train
gather_blocks_2d
Gathers flattened blocks from x.
tensor2tensor/layers/common_attention.py
def gather_blocks_2d(x, indices): """Gathers flattened blocks from x.""" x_shape = common_layers.shape_list(x) x = reshape_range(x, 2, 4, [tf.reduce_prod(x_shape[2:4])]) # [length, batch, heads, dim] x_t = tf.transpose(x, [2, 0, 1, 3]) x_new = tf.gather(x_t, indices) # returns [batch, heads, num_blocks, b...
def gather_blocks_2d(x, indices): """Gathers flattened blocks from x.""" x_shape = common_layers.shape_list(x) x = reshape_range(x, 2, 4, [tf.reduce_prod(x_shape[2:4])]) # [length, batch, heads, dim] x_t = tf.transpose(x, [2, 0, 1, 3]) x_new = tf.gather(x_t, indices) # returns [batch, heads, num_blocks, b...
[ "Gathers", "flattened", "blocks", "from", "x", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3561-L3569
[ "def", "gather_blocks_2d", "(", "x", ",", "indices", ")", ":", "x_shape", "=", "common_layers", ".", "shape_list", "(", "x", ")", "x", "=", "reshape_range", "(", "x", ",", "2", ",", "4", ",", "[", "tf", ".", "reduce_prod", "(", "x_shape", "[", "2", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
scatter_blocks_2d
scatters blocks from x into shape with indices.
tensor2tensor/layers/common_attention.py
def scatter_blocks_2d(x, indices, shape): """scatters blocks from x into shape with indices.""" x_shape = common_layers.shape_list(x) # [length, batch, heads, dim] x_t = tf.transpose( tf.reshape(x, [x_shape[0], x_shape[1], -1, x_shape[-1]]), [2, 0, 1, 3]) x_t_shape = common_layers.shape_list(x_t) indi...
def scatter_blocks_2d(x, indices, shape): """scatters blocks from x into shape with indices.""" x_shape = common_layers.shape_list(x) # [length, batch, heads, dim] x_t = tf.transpose( tf.reshape(x, [x_shape[0], x_shape[1], -1, x_shape[-1]]), [2, 0, 1, 3]) x_t_shape = common_layers.shape_list(x_t) indi...
[ "scatters", "blocks", "from", "x", "into", "shape", "with", "indices", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3572-L3582
[ "def", "scatter_blocks_2d", "(", "x", ",", "indices", ",", "shape", ")", ":", "x_shape", "=", "common_layers", ".", "shape_list", "(", "x", ")", "# [length, batch, heads, dim]", "x_t", "=", "tf", ".", "transpose", "(", "tf", ".", "reshape", "(", "x", ",", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
gather_indices_2d
Getting gather indices.
tensor2tensor/layers/common_attention.py
def gather_indices_2d(x, block_shape, block_stride): """Getting gather indices.""" # making an identity matrix kernel kernel = tf.eye(block_shape[0] * block_shape[1]) kernel = reshape_range(kernel, 0, 1, [block_shape[0], block_shape[1], 1]) # making indices [1, h, w, 1] to appy convs x_shape = common_layers...
def gather_indices_2d(x, block_shape, block_stride): """Getting gather indices.""" # making an identity matrix kernel kernel = tf.eye(block_shape[0] * block_shape[1]) kernel = reshape_range(kernel, 0, 1, [block_shape[0], block_shape[1], 1]) # making indices [1, h, w, 1] to appy convs x_shape = common_layers...
[ "Getting", "gather", "indices", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3585-L3606
[ "def", "gather_indices_2d", "(", "x", ",", "block_shape", ",", "block_stride", ")", ":", "# making an identity matrix kernel", "kernel", "=", "tf", ".", "eye", "(", "block_shape", "[", "0", "]", "*", "block_shape", "[", "1", "]", ")", "kernel", "=", "reshape...
272500b6efe353aeb638d2745ed56e519462ca31
train
make_2d_block_raster_mask
Creates a mask for 2d block raster scan. The query mask can look to the left, top left, top, and top right, but not to the right. Inside the query, we have the standard raster scan masking. Args: query_shape: A tuple of ints (query_height, query_width) memory_flange: A tuple of ints (memory_flang...
tensor2tensor/layers/common_attention.py
def make_2d_block_raster_mask(query_shape, memory_flange): """Creates a mask for 2d block raster scan. The query mask can look to the left, top left, top, and top right, but not to the right. Inside the query, we have the standard raster scan masking. Args: query_shape: A tuple of ints (query_height, que...
def make_2d_block_raster_mask(query_shape, memory_flange): """Creates a mask for 2d block raster scan. The query mask can look to the left, top left, top, and top right, but not to the right. Inside the query, we have the standard raster scan masking. Args: query_shape: A tuple of ints (query_height, que...
[ "Creates", "a", "mask", "for", "2d", "block", "raster", "scan", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3609-L3646
[ "def", "make_2d_block_raster_mask", "(", "query_shape", ",", "memory_flange", ")", ":", "# mask inside the query block", "query_triangle", "=", "common_layers", ".", "ones_matrix_band_part", "(", "np", ".", "prod", "(", "query_shape", ")", ",", "np", ".", "prod", "(...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_memory_region
Get the memory regions that surround a 2d query. The memory regions will be the left and top right. Args: x: A tensor with shape [batch, heads, height, width, depth] query_block_shape: a 2-d tuple of integers memory_flange: a 2-d tuple of integers q_indices: a tensor of indices for each of the c...
tensor2tensor/layers/common_attention.py
def get_memory_region(x, query_block_shape, memory_flange, q_indices): """Get the memory regions that surround a 2d query. The memory regions will be the left and top right. Args: x: A tensor with shape [batch, heads, height, width, depth] query_block_shape: a 2-d tuple of integers memory_flange: ...
def get_memory_region(x, query_block_shape, memory_flange, q_indices): """Get the memory regions that surround a 2d query. The memory regions will be the left and top right. Args: x: A tensor with shape [batch, heads, height, width, depth] query_block_shape: a 2-d tuple of integers memory_flange: ...
[ "Get", "the", "memory", "regions", "that", "surround", "a", "2d", "query", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3649-L3700
[ "def", "get_memory_region", "(", "x", ",", "query_block_shape", ",", "memory_flange", ",", "q_indices", ")", ":", "# Padding x to be multiple of query_shape and then", "# extracting the memory blocks from the same regions as the query blocks", "x_query_padded", "=", "pad_to_multiple_...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_shifted_center_blocks
Get right shifted blocks for masked local attention 2d. Args: x: A tensor with shape [batch, heads, height, width, depth] indices: The indices to gather blocks Returns: x_shifted: a tensor of extracted blocks, each block right shifted along length.
tensor2tensor/layers/common_attention.py
def get_shifted_center_blocks(x, indices): """Get right shifted blocks for masked local attention 2d. Args: x: A tensor with shape [batch, heads, height, width, depth] indices: The indices to gather blocks Returns: x_shifted: a tensor of extracted blocks, each block right shifted along length....
def get_shifted_center_blocks(x, indices): """Get right shifted blocks for masked local attention 2d. Args: x: A tensor with shape [batch, heads, height, width, depth] indices: The indices to gather blocks Returns: x_shifted: a tensor of extracted blocks, each block right shifted along length....
[ "Get", "right", "shifted", "blocks", "for", "masked", "local", "attention", "2d", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3703-L3724
[ "def", "get_shifted_center_blocks", "(", "x", ",", "indices", ")", ":", "center_x", "=", "gather_blocks_2d", "(", "x", ",", "indices", ")", "# Shift right along the length dimension", "def", "shift_right_2d_blocks", "(", "x", ")", ":", "\"\"\"Shift the second to last di...
272500b6efe353aeb638d2745ed56e519462ca31
train
right_shift_blockwise
Right shifts once in every block. Args: x: a tensor of shape [batch, height, width, depth] query_shape: A 2d tuple of ints name: a string Returns: output: a tensor of the same shape as x
tensor2tensor/layers/common_attention.py
def right_shift_blockwise(x, query_shape, name=None): """Right shifts once in every block. Args: x: a tensor of shape [batch, height, width, depth] query_shape: A 2d tuple of ints name: a string Returns: output: a tensor of the same shape as x """ with tf.variable_scope( name, default_...
def right_shift_blockwise(x, query_shape, name=None): """Right shifts once in every block. Args: x: a tensor of shape [batch, height, width, depth] query_shape: A 2d tuple of ints name: a string Returns: output: a tensor of the same shape as x """ with tf.variable_scope( name, default_...
[ "Right", "shifts", "once", "in", "every", "block", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3727-L3757
[ "def", "right_shift_blockwise", "(", "x", ",", "query_shape", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"right_shift_blockwise\"", ",", "values", "=", "[", "x", "]", ")", ":", "x_list_...
272500b6efe353aeb638d2745ed56e519462ca31
train
masked_local_attention_2d
Strided block local self-attention. Each position in a query block can attend to all the generated queries in the query block, which are generated in raster scan, and positions that are generated to the left and top. The shapes are specified by query shape and memory flange. Note that if you're using this func...
tensor2tensor/layers/common_attention.py
def masked_local_attention_2d(q, k, v, query_shape=(8, 16), memory_flange=(8, 16), name=None): """Strided block local self-attention. Each position in a query block ...
def masked_local_attention_2d(q, k, v, query_shape=(8, 16), memory_flange=(8, 16), name=None): """Strided block local self-attention. Each position in a query block ...
[ "Strided", "block", "local", "self", "-", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3760-L3850
[ "def", "masked_local_attention_2d", "(", "q", ",", "k", ",", "v", ",", "query_shape", "=", "(", "8", ",", "16", ")", ",", "memory_flange", "=", "(", "8", ",", "16", ")", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
compute_attention_component
Computes attention compoenent (query, key or value). Args: antecedent: a Tensor with shape [batch, length, channels] total_depth: an integer filter_width: An integer specifying how wide you want the attention component to be. padding: One of "VALID", "SAME" or "LEFT". Default is VALID: No paddi...
tensor2tensor/layers/common_attention.py
def compute_attention_component(antecedent, total_depth, filter_width=1, padding="VALID", name="c", vars_3d_num_heads=0, layer_c...
def compute_attention_component(antecedent, total_depth, filter_width=1, padding="VALID", name="c", vars_3d_num_heads=0, layer_c...
[ "Computes", "attention", "compoenent", "(", "query", "key", "or", "value", ")", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3853-L3903
[ "def", "compute_attention_component", "(", "antecedent", ",", "total_depth", ",", "filter_width", "=", "1", ",", "padding", "=", "\"VALID\"", ",", "name", "=", "\"c\"", ",", "vars_3d_num_heads", "=", "0", ",", "layer_collection", "=", "None", ")", ":", "if", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
compute_qkv
Computes query, key and value. Args: query_antecedent: a Tensor with shape [batch, length_q, channels] memory_antecedent: a Tensor with shape [batch, length_m, channels] total_key_depth: an integer total_value_depth: an integer q_filter_width: An integer specifying how wide you want the query to ...
tensor2tensor/layers/common_attention.py
def compute_qkv(query_antecedent, memory_antecedent, total_key_depth, total_value_depth, q_filter_width=1, kv_filter_width=1, q_padding="VALID", kv_padding="VALID", vars_3d_num_heads=0, ...
def compute_qkv(query_antecedent, memory_antecedent, total_key_depth, total_value_depth, q_filter_width=1, kv_filter_width=1, q_padding="VALID", kv_padding="VALID", vars_3d_num_heads=0, ...
[ "Computes", "query", "key", "and", "value", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3906-L3961
[ "def", "compute_qkv", "(", "query_antecedent", ",", "memory_antecedent", ",", "total_key_depth", ",", "total_value_depth", ",", "q_filter_width", "=", "1", ",", "kv_filter_width", "=", "1", ",", "q_padding", "=", "\"VALID\"", ",", "kv_padding", "=", "\"VALID\"", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
multihead_attention
Multihead scaled-dot-product attention with input/output transformations. Args: query_antecedent: a Tensor with shape [batch, length_q, channels] memory_antecedent: a Tensor with shape [batch, length_m, channels] or None bias: bias Tensor (see attention_bias()) total_key_depth: an integer total_v...
tensor2tensor/layers/common_attention.py
def multihead_attention(query_antecedent, memory_antecedent, bias, total_key_depth, total_value_depth, output_depth, num_heads, dropout_rate, ...
def multihead_attention(query_antecedent, memory_antecedent, bias, total_key_depth, total_value_depth, output_depth, num_heads, dropout_rate, ...
[ "Multihead", "scaled", "-", "dot", "-", "product", "attention", "with", "input", "/", "output", "transformations", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3964-L4299
[ "def", "multihead_attention", "(", "query_antecedent", ",", "memory_antecedent", ",", "bias", ",", "total_key_depth", ",", "total_value_depth", ",", "output_depth", ",", "num_heads", ",", "dropout_rate", ",", "attention_type", "=", "\"dot_product\"", ",", "max_relative_...
272500b6efe353aeb638d2745ed56e519462ca31
train
multihead_attention_2d
2d Multihead scaled-dot-product attention with inp/output transformations. Args: query_antecedent: a Tensor with shape [batch, h, w, depth_k] memory_antecedent: a Tensor with shape [batch, h, w, depth_k] total_key_depth: an integer total_value_depth: an integer output_depth: an integer num_he...
tensor2tensor/layers/common_attention.py
def multihead_attention_2d(query_antecedent, memory_antecedent, total_key_depth, total_value_depth, output_depth, num_heads, attention_type="local_attention_2...
def multihead_attention_2d(query_antecedent, memory_antecedent, total_key_depth, total_value_depth, output_depth, num_heads, attention_type="local_attention_2...
[ "2d", "Multihead", "scaled", "-", "dot", "-", "product", "attention", "with", "inp", "/", "output", "transformations", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L4302-L4365
[ "def", "multihead_attention_2d", "(", "query_antecedent", ",", "memory_antecedent", ",", "total_key_depth", ",", "total_value_depth", ",", "output_depth", ",", "num_heads", ",", "attention_type", "=", "\"local_attention_2d\"", ",", "query_shape", "=", "(", "8", ",", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
ffn_self_attention_layer
Self-attention feedforward layer. We use self-attention to do feedforward computations. We apply this function positionwise where for each position, we linearly transform the output to have depth filter_depth, and break up the result depth-wise into num_parts contiguous parts. The parts self-attend, we concate...
tensor2tensor/layers/common_attention.py
def ffn_self_attention_layer(x, filter_depth, output_depth, num_parts, dropout_rate, share_kv=False, name=None): """Self-attention feedforward l...
def ffn_self_attention_layer(x, filter_depth, output_depth, num_parts, dropout_rate, share_kv=False, name=None): """Self-attention feedforward l...
[ "Self", "-", "attention", "feedforward", "layer", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L4368-L4430
[ "def", "ffn_self_attention_layer", "(", "x", ",", "filter_depth", ",", "output_depth", ",", "num_parts", ",", "dropout_rate", ",", "share_kv", "=", "False", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_n...
272500b6efe353aeb638d2745ed56e519462ca31
train
parameter_attention
Attention over parameters. We use the same multi-headed attention as in the other layers, but the memory keys and values are model parameters. There are no linear transformation on the keys or values. We are also a bit more careful about memory usage, since the number of memory positions may be very large. ...
tensor2tensor/layers/common_attention.py
def parameter_attention(x, total_key_depth, total_value_depth, output_depth, memory_rows, num_heads, dropout_rate, name=None): """Attention over param...
def parameter_attention(x, total_key_depth, total_value_depth, output_depth, memory_rows, num_heads, dropout_rate, name=None): """Attention over param...
[ "Attention", "over", "parameters", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L4433-L4502
[ "def", "parameter_attention", "(", "x", ",", "total_key_depth", ",", "total_value_depth", ",", "output_depth", ",", "memory_rows", ",", "num_heads", ",", "dropout_rate", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",",...
272500b6efe353aeb638d2745ed56e519462ca31
train
coordinate_tensor
Return a tensor with given shape containing coordinate along given axis. Args: shape: a Tensor representing the shape of the output Tensor axis: an integer Returns: A tensor with shape shape and type tf.int32, where each elements its coordinate along the given axis.
tensor2tensor/layers/common_attention.py
def coordinate_tensor(shape, axis): """Return a tensor with given shape containing coordinate along given axis. Args: shape: a Tensor representing the shape of the output Tensor axis: an integer Returns: A tensor with shape shape and type tf.int32, where each elements its coordinate along the gi...
def coordinate_tensor(shape, axis): """Return a tensor with given shape containing coordinate along given axis. Args: shape: a Tensor representing the shape of the output Tensor axis: an integer Returns: A tensor with shape shape and type tf.int32, where each elements its coordinate along the gi...
[ "Return", "a", "tensor", "with", "given", "shape", "containing", "coordinate", "along", "given", "axis", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L4506-L4523
[ "def", "coordinate_tensor", "(", "shape", ",", "axis", ")", ":", "if", "axis", "<", "0", ":", "axis", "=", "tf", ".", "size", "(", "shape", ")", "+", "axis", "# Convert to positive for the one_hot indice", "r", "=", "tf", ".", "range", "(", "shape", "[",...
272500b6efe353aeb638d2745ed56e519462ca31
train
self_attention_expert
Implementing attention that runs inside each expert. Args: x: A tensor of shape[batch, depth]. Contains representations from different positions, which are lexicographically ordered. batch_coordinate: A tensor of shape [batch, 1] containing the batch coordinate of each element in x. This is neede...
tensor2tensor/layers/common_attention.py
def self_attention_expert(x, batch_coordinate, mask_right=True, split_batch=False, attention_num_head=1, attention_kq_size=None, attention_v_size=None): """Implem...
def self_attention_expert(x, batch_coordinate, mask_right=True, split_batch=False, attention_num_head=1, attention_kq_size=None, attention_v_size=None): """Implem...
[ "Implementing", "attention", "that", "runs", "inside", "each", "expert", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L4526-L4632
[ "def", "self_attention_expert", "(", "x", ",", "batch_coordinate", ",", "mask_right", "=", "True", ",", "split_batch", "=", "False", ",", "attention_num_head", "=", "1", ",", "attention_kq_size", "=", "None", ",", "attention_v_size", "=", "None", ")", ":", "de...
272500b6efe353aeb638d2745ed56e519462ca31
train
local_expert_attention
Attention using a mixture of experts. Positions sent to the same expert can attend to each other. The mixture of experts is "local" in that it is replicated on each datashard. local_moe flatten all batches so to avoid problems with padding (ex: all padding going to the same expert, self attention ...
tensor2tensor/layers/common_attention.py
def local_expert_attention(x, k, loss_coef, attention_num_experts, train=True, batch_coordinate=None, **kwargs): """Attention using a mixture of experts. ...
def local_expert_attention(x, k, loss_coef, attention_num_experts, train=True, batch_coordinate=None, **kwargs): """Attention using a mixture of experts. ...
[ "Attention", "using", "a", "mixture", "of", "experts", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L4635-L4681
[ "def", "local_expert_attention", "(", "x", ",", "k", ",", "loss_coef", ",", "attention_num_experts", ",", "train", "=", "True", ",", "batch_coordinate", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "batch_coordinate", "is", "None", ":", "batch_coord...
272500b6efe353aeb638d2745ed56e519462ca31
train
expert_dot_product
Perform dot product on a subset of the sequence. Can add a mask to the attention to prevent sequences to attend to each other and to prevent attention to the future. Args: q (tf.Tensor): Queries of shape [length_expert_q, depth_k] k (tf.Tensor): Keys of shape [length_expert_k, depth_k] v (tf.Tensor)...
tensor2tensor/layers/common_attention.py
def expert_dot_product(q, k, v, info_q, info_k): """Perform dot product on a subset of the sequence. Can add a mask to the attention to prevent sequences to attend to each other and to prevent attention to the future. Args: q (tf.Tensor): Queries of shape [length_expert_q, depth_k] k (tf.Tensor): Keys...
def expert_dot_product(q, k, v, info_q, info_k): """Perform dot product on a subset of the sequence. Can add a mask to the attention to prevent sequences to attend to each other and to prevent attention to the future. Args: q (tf.Tensor): Queries of shape [length_expert_q, depth_k] k (tf.Tensor): Keys...
[ "Perform", "dot", "product", "on", "a", "subset", "of", "the", "sequence", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L4685-L4746
[ "def", "expert_dot_product", "(", "q", ",", "k", ",", "v", ",", "info_q", ",", "info_k", ")", ":", "length_q", "=", "common_layers", ".", "shape_list", "(", "q", ")", "[", "0", "]", "length_k", "=", "common_layers", ".", "shape_list", "(", "k", ")", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
dot_product_single_head
Perform a dot product attention on a single sequence on a single head. This function dispatch the q, k, v and loop over the buckets to compute the attention dot product on each subsequences. Args: q (tf.Tensor): [length_q, depth_q] k (tf.Tensor): [length_k, depth_q] v (tf.Tensor): [length_k, depth_v...
tensor2tensor/layers/common_attention.py
def dot_product_single_head(q, k, v, gates_q, gates_k, bi): """Perform a dot product attention on a single sequence on a single head. This function dispatch the q, k, v and loop over the buckets to compute the attention dot product on each subsequences. Args: q (tf.Tensor): [length_q, depth_q] k (tf.T...
def dot_product_single_head(q, k, v, gates_q, gates_k, bi): """Perform a dot product attention on a single sequence on a single head. This function dispatch the q, k, v and loop over the buckets to compute the attention dot product on each subsequences. Args: q (tf.Tensor): [length_q, depth_q] k (tf.T...
[ "Perform", "a", "dot", "product", "attention", "on", "a", "single", "sequence", "on", "a", "single", "head", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L4750-L4808
[ "def", "dot_product_single_head", "(", "q", ",", "k", ",", "v", ",", "gates_q", ",", "gates_k", ",", "bi", ")", ":", "nb_buckets", "=", "gates_q", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "-", "1", "]", "q_dispatcher", "=", "expert_...
272500b6efe353aeb638d2745ed56e519462ca31
train
map_fn_switch
Construct the graph with either tf.map_fn or a python for loop. This function is mainly for for benchmarking purpose. tf.map_fn is dynamic but is much slower than creating a static graph with for loop. However, having a for loop make the graph much longer to build and can consume too much RAM on distributed s...
tensor2tensor/layers/common_attention.py
def map_fn_switch(fn, elems, use_map_fn=True, **kwargs): """Construct the graph with either tf.map_fn or a python for loop. This function is mainly for for benchmarking purpose. tf.map_fn is dynamic but is much slower than creating a static graph with for loop. However, having a for loop make the graph much l...
def map_fn_switch(fn, elems, use_map_fn=True, **kwargs): """Construct the graph with either tf.map_fn or a python for loop. This function is mainly for for benchmarking purpose. tf.map_fn is dynamic but is much slower than creating a static graph with for loop. However, having a for loop make the graph much l...
[ "Construct", "the", "graph", "with", "either", "tf", ".", "map_fn", "or", "a", "python", "for", "loop", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L4811-L4836
[ "def", "map_fn_switch", "(", "fn", ",", "elems", ",", "use_map_fn", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "use_map_fn", ":", "return", "tf", ".", "map_fn", "(", "fn", ",", "elems", ",", "*", "*", "kwargs", ")", "elems_unpacked", "=", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
sparse_dot_product_attention
Sparse multihead self attention. Perform an approximation of the full multihead attention by dispatching the tokens using their keys/values. Thus the attention matrix are only computed each times on a subset of the tokens. Notes: * The function don't perform scaling here (multihead_attention does the /sq...
tensor2tensor/layers/common_attention.py
def sparse_dot_product_attention(q, k, v, bi, use_map_fn, experts_params): """Sparse multihead self attention. Perform an approximation of the full multihead attention by dispatching the tokens using their keys/values. Thus the attention matrix are only computed each times on a subset of the tokens. Notes: ...
def sparse_dot_product_attention(q, k, v, bi, use_map_fn, experts_params): """Sparse multihead self attention. Perform an approximation of the full multihead attention by dispatching the tokens using their keys/values. Thus the attention matrix are only computed each times on a subset of the tokens. Notes: ...
[ "Sparse", "multihead", "self", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L4840-L4933
[ "def", "sparse_dot_product_attention", "(", "q", ",", "k", ",", "v", ",", "bi", ",", "use_map_fn", ",", "experts_params", ")", ":", "batch_size", ",", "nb_heads", ",", "_", ",", "depth", "=", "common_layers", ".", "shape_list", "(", "q", ")", "@", "exper...
272500b6efe353aeb638d2745ed56e519462ca31
train
dot_product_batched_head
Perform a dot product attention on a single sequence on a single head. This function dispatch the q, k, v and loop over the buckets to compute the attention dot product on each subsequences. Args: q (tf.Tensor): [batch*heads, length_q, depth_q] k (tf.Tensor): [batch*heads, length_k, depth_q] v (tf.T...
tensor2tensor/layers/common_attention.py
def dot_product_batched_head(q, k, v, gates_q, gates_k, mask_right=False): """Perform a dot product attention on a single sequence on a single head. This function dispatch the q, k, v and loop over the buckets to compute the attention dot product on each subsequences. Args: q (tf.Tensor): [batch*heads, le...
def dot_product_batched_head(q, k, v, gates_q, gates_k, mask_right=False): """Perform a dot product attention on a single sequence on a single head. This function dispatch the q, k, v and loop over the buckets to compute the attention dot product on each subsequences. Args: q (tf.Tensor): [batch*heads, le...
[ "Perform", "a", "dot", "product", "attention", "on", "a", "single", "sequence", "on", "a", "single", "head", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L4937-L5005
[ "def", "dot_product_batched_head", "(", "q", ",", "k", ",", "v", ",", "gates_q", ",", "gates_k", ",", "mask_right", "=", "False", ")", ":", "nb_buckets", "=", "common_layers", ".", "shape_list", "(", "gates_q", ")", "[", "-", "1", "]", "@", "expert_utils...
272500b6efe353aeb638d2745ed56e519462ca31
train
sparse_dot_product_attention_truncated
Sparse multihead self attention. Perform an approximation of the full multihead attention by dispatching the tokens using their keys/values. Thus the attention matrix are only computed each times on a subset of the tokens. Notes: * The function don't perform scaling here (multihead_attention does the /sq...
tensor2tensor/layers/common_attention.py
def sparse_dot_product_attention_truncated( q, k, v, bi, # Unused experts_params, use_map_fn=False, # Unused mask_right=False, ): # pylint: disable=unused-argument """Sparse multihead self attention. Perform an approximation of the full multihead attention by dispatching the tokens...
def sparse_dot_product_attention_truncated( q, k, v, bi, # Unused experts_params, use_map_fn=False, # Unused mask_right=False, ): # pylint: disable=unused-argument """Sparse multihead self attention. Perform an approximation of the full multihead attention by dispatching the tokens...
[ "Sparse", "multihead", "self", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L5009-L5112
[ "def", "sparse_dot_product_attention_truncated", "(", "q", ",", "k", ",", "v", ",", "bi", ",", "# Unused", "experts_params", ",", "use_map_fn", "=", "False", ",", "# Unused", "mask_right", "=", "False", ",", ")", ":", "# pylint: disable=unused-argument", "# Curren...
272500b6efe353aeb638d2745ed56e519462ca31
train
deconv_elems_1d
Increase the length and change the dimensionality. Expand/project each positions of dim depth of the input into factor*tokens of dim out_depth Args: x (tf.Tensor): shape [batch_size, length, depth] factor (int): Multiplicative factor of each tokens. out_depth (int): Output depth (if None, keep depth...
tensor2tensor/layers/common_attention.py
def deconv_elems_1d(x, factor, out_depth=None): """Increase the length and change the dimensionality. Expand/project each positions of dim depth of the input into factor*tokens of dim out_depth Args: x (tf.Tensor): shape [batch_size, length, depth] factor (int): Multiplicative factor of each tokens. ...
def deconv_elems_1d(x, factor, out_depth=None): """Increase the length and change the dimensionality. Expand/project each positions of dim depth of the input into factor*tokens of dim out_depth Args: x (tf.Tensor): shape [batch_size, length, depth] factor (int): Multiplicative factor of each tokens. ...
[ "Increase", "the", "length", "and", "change", "the", "dimensionality", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L5116-L5140
[ "def", "deconv_elems_1d", "(", "x", ",", "factor", ",", "out_depth", "=", "None", ")", ":", "out_depth", "=", "out_depth", "or", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "-", "1", "]", "x", "=", "tf", ".", "expand_dims", "(",...
272500b6efe353aeb638d2745ed56e519462ca31
train
conv_elems_1d
Decrease the length and change the dimensionality. Merge/restore/compress factors positions of dim depth of the input into a single position of dim out_depth. This is basically just a strided convolution without overlap between each strides. The original length has to be divided by factor. Args: x (tf.T...
tensor2tensor/layers/common_attention.py
def conv_elems_1d(x, factor, out_depth=None): """Decrease the length and change the dimensionality. Merge/restore/compress factors positions of dim depth of the input into a single position of dim out_depth. This is basically just a strided convolution without overlap between each strides. The original lengt...
def conv_elems_1d(x, factor, out_depth=None): """Decrease the length and change the dimensionality. Merge/restore/compress factors positions of dim depth of the input into a single position of dim out_depth. This is basically just a strided convolution without overlap between each strides. The original lengt...
[ "Decrease", "the", "length", "and", "change", "the", "dimensionality", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L5144-L5172
[ "def", "conv_elems_1d", "(", "x", ",", "factor", ",", "out_depth", "=", "None", ")", ":", "out_depth", "=", "out_depth", "or", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "-", "1", "]", "# with tf.control_dependencies( # Dynamic assertio...
272500b6efe353aeb638d2745ed56e519462ca31
train
local_reduction_attention
Reduce the length dimension using self attention. Args: x (tf.Tensor): float32 of shape [batch, length, depth] block_length (int): Block length for local attention (Compression factor) multihead_params (dict): parameters for multihead attention Returns: tf.Tensor: Compressed tensor of shape [batch...
tensor2tensor/layers/common_attention.py
def local_reduction_attention(x, block_length, multihead_params): """Reduce the length dimension using self attention. Args: x (tf.Tensor): float32 of shape [batch, length, depth] block_length (int): Block length for local attention (Compression factor) multihead_params (dict): parameters for multihead...
def local_reduction_attention(x, block_length, multihead_params): """Reduce the length dimension using self attention. Args: x (tf.Tensor): float32 of shape [batch, length, depth] block_length (int): Block length for local attention (Compression factor) multihead_params (dict): parameters for multihead...
[ "Reduce", "the", "length", "dimension", "using", "self", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L5176-L5255
[ "def", "local_reduction_attention", "(", "x", ",", "block_length", ",", "multihead_params", ")", ":", "@", "expert_utils", ".", "add_name_scope", "(", ")", "def", "dot_product_self_local_attention_flattened", "(", "q", ",", "k", ",", "v", ")", ":", "\"\"\"Strided ...
272500b6efe353aeb638d2745ed56e519462ca31
train
multihead_self_attention_reduced
Reduce the length dimension by compressing with conv. Args: x (tf.Tensor): float32 of shape [batch, length, depth] memory_antecedent (tf.Tensor): Unsupported for now bias (tf.Tensor): Ignored factor (int): compression factor for the memory sequence multihead_params (dict): parameters for multihea...
tensor2tensor/layers/common_attention.py
def multihead_self_attention_reduced( x, memory_antecedent=None, bias=None, factor=None, multihead_params=None, nonlinearity="none", reduction_type="conv", add_mask=True, ): """Reduce the length dimension by compressing with conv. Args: x (tf.Tensor): float32 of shape [batch, le...
def multihead_self_attention_reduced( x, memory_antecedent=None, bias=None, factor=None, multihead_params=None, nonlinearity="none", reduction_type="conv", add_mask=True, ): """Reduce the length dimension by compressing with conv. Args: x (tf.Tensor): float32 of shape [batch, le...
[ "Reduce", "the", "length", "dimension", "by", "compressing", "with", "conv", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L5259-L5350
[ "def", "multihead_self_attention_reduced", "(", "x", ",", "memory_antecedent", "=", "None", ",", "bias", "=", "None", ",", "factor", "=", "None", ",", "multihead_params", "=", "None", ",", "nonlinearity", "=", "\"none\"", ",", "reduction_type", "=", "\"conv\"", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
scaled_dot_product_attention_simple
Scaled dot-product attention. One head. One spatial dimension. Args: q: a Tensor with shape [batch, length_q, depth_k] k: a Tensor with shape [batch, length_kv, depth_k] v: a Tensor with shape [batch, length_kv, depth_v] bias: optional Tensor broadcastable to [batch, length_q, length_kv] name: an...
tensor2tensor/layers/common_attention.py
def scaled_dot_product_attention_simple(q, k, v, bias, name=None): """Scaled dot-product attention. One head. One spatial dimension. Args: q: a Tensor with shape [batch, length_q, depth_k] k: a Tensor with shape [batch, length_kv, depth_k] v: a Tensor with shape [batch, length_kv, depth_v] bias: op...
def scaled_dot_product_attention_simple(q, k, v, bias, name=None): """Scaled dot-product attention. One head. One spatial dimension. Args: q: a Tensor with shape [batch, length_q, depth_k] k: a Tensor with shape [batch, length_kv, depth_k] v: a Tensor with shape [batch, length_kv, depth_v] bias: op...
[ "Scaled", "dot", "-", "product", "attention", ".", "One", "head", ".", "One", "spatial", "dimension", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L5353-L5376
[ "def", "scaled_dot_product_attention_simple", "(", "q", ",", "k", ",", "v", ",", "bias", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"scaled_dot_product_attention_simple\"", ")", ":", "scala...
272500b6efe353aeb638d2745ed56e519462ca31
train
multihead_self_attention_memory_efficient
Multihead scaled-dot-product self-attention. Includes layer norm. Returns multihead-self-attention(layer_norm(x)) Computes one attention head at a time to avoid exhausting memory. If forget=True, then forget all forwards activations and recompute on the backwards pass. Args: x: a Tensor with shape ...
tensor2tensor/layers/common_attention.py
def multihead_self_attention_memory_efficient(x, bias, num_heads, head_size=None, epsilon=1e-6, ...
def multihead_self_attention_memory_efficient(x, bias, num_heads, head_size=None, epsilon=1e-6, ...
[ "Multihead", "scaled", "-", "dot", "-", "product", "self", "-", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L5382-L5501
[ "def", "multihead_self_attention_memory_efficient", "(", "x", ",", "bias", ",", "num_heads", ",", "head_size", "=", "None", ",", "epsilon", "=", "1e-6", ",", "forget", "=", "True", ",", "test_vars", "=", "None", ",", "name", "=", "None", ")", ":", "io_size...
272500b6efe353aeb638d2745ed56e519462ca31
train
LshGating._idx_to_bits
Convert an group index to its bit representation.
tensor2tensor/layers/common_attention.py
def _idx_to_bits(self, i): """Convert an group index to its bit representation.""" bits = bin(i)[2:].zfill(self.nb_hyperplanes) # Pad the bits str with 0 return [-1.0 if b == "0" else 1.0 for b in bits]
def _idx_to_bits(self, i): """Convert an group index to its bit representation.""" bits = bin(i)[2:].zfill(self.nb_hyperplanes) # Pad the bits str with 0 return [-1.0 if b == "0" else 1.0 for b in bits]
[ "Convert", "an", "group", "index", "to", "its", "bit", "representation", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L803-L806
[ "def", "_idx_to_bits", "(", "self", ",", "i", ")", ":", "bits", "=", "bin", "(", "i", ")", "[", "2", ":", "]", ".", "zfill", "(", "self", ".", "nb_hyperplanes", ")", "# Pad the bits str with 0", "return", "[", "-", "1.0", "if", "b", "==", "\"0\"", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
LshGating.get_gates
Return the bucket id of the given tensor. Args: x (tf.Tensor): float32 of shape [length, depth] Returns: tf.Tensor: One-hot vector int64 of shape [heads, length, nb_buckets] containing the id of the bucket
tensor2tensor/layers/common_attention.py
def get_gates(self, x): """Return the bucket id of the given tensor. Args: x (tf.Tensor): float32 of shape [length, depth] Returns: tf.Tensor: One-hot vector int64 of shape [heads, length, nb_buckets] containing the id of the bucket """ # The balance loss don't propagate to th...
def get_gates(self, x): """Return the bucket id of the given tensor. Args: x (tf.Tensor): float32 of shape [length, depth] Returns: tf.Tensor: One-hot vector int64 of shape [heads, length, nb_buckets] containing the id of the bucket """ # The balance loss don't propagate to th...
[ "Return", "the", "bucket", "id", "of", "the", "given", "tensor", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L809-L839
[ "def", "get_gates", "(", "self", ",", "x", ")", ":", "# The balance loss don't propagate to the rest of the network", "x", "=", "tf", ".", "stop_gradient", "(", "x", ")", "# [length, depth] * [depth, nb_vectors * replicat]", "x", "=", "tf", ".", "matmul", "(", "x", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
van_image_enc_2d
The image encoder for the VAN. Similar architecture as Ruben's paper (http://proceedings.mlr.press/v70/villegas17a/villegas17a.pdf). Args: x: The image to encode. first_depth: The depth of the first layer. Depth is increased in subsequent layers. reuse: To reuse in variable scope or not. h...
tensor2tensor/models/video/epva.py
def van_image_enc_2d(x, first_depth, reuse=False, hparams=None): """The image encoder for the VAN. Similar architecture as Ruben's paper (http://proceedings.mlr.press/v70/villegas17a/villegas17a.pdf). Args: x: The image to encode. first_depth: The depth of the first layer. Depth is increased in subseq...
def van_image_enc_2d(x, first_depth, reuse=False, hparams=None): """The image encoder for the VAN. Similar architecture as Ruben's paper (http://proceedings.mlr.press/v70/villegas17a/villegas17a.pdf). Args: x: The image to encode. first_depth: The depth of the first layer. Depth is increased in subseq...
[ "The", "image", "encoder", "for", "the", "VAN", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L53-L124
[ "def", "van_image_enc_2d", "(", "x", ",", "first_depth", ",", "reuse", "=", "False", ",", "hparams", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "'van_image_enc'", ",", "reuse", "=", "reuse", ")", ":", "enc_history", "=", "[", "x", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
van_enc_2d
The higher level structure encoder for the VAN. The high level structure is a vector instead of an image. Args: x: The higher level structure to encode. first_depth: The depth of the first layer. Depth is increased in subsequent layers. reuse: To reuse in variable scope or not. Returns: T...
tensor2tensor/models/video/epva.py
def van_enc_2d(x, first_depth, reuse=False): """The higher level structure encoder for the VAN. The high level structure is a vector instead of an image. Args: x: The higher level structure to encode. first_depth: The depth of the first layer. Depth is increased in subsequent layers. reuse: To...
def van_enc_2d(x, first_depth, reuse=False): """The higher level structure encoder for the VAN. The high level structure is a vector instead of an image. Args: x: The higher level structure to encode. first_depth: The depth of the first layer. Depth is increased in subsequent layers. reuse: To...
[ "The", "higher", "level", "structure", "encoder", "for", "the", "VAN", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L127-L182
[ "def", "van_enc_2d", "(", "x", ",", "first_depth", ",", "reuse", "=", "False", ")", ":", "with", "tf", ".", "variable_scope", "(", "'van_enc'", ",", "reuse", "=", "reuse", ")", ":", "a", "=", "4", "# depends on the inputs size", "b", "=", "4", "# a, b = ...
272500b6efe353aeb638d2745ed56e519462ca31
train
van_dec_2d
The VAN decoder. Args: x: The analogy information to decode. skip_connections: The encoder layers which can be used as skip connections. output_shape: The shape of the desired output image. first_depth: The depth of the first layer of the van image encoder. hparams: The python hparams. Returns...
tensor2tensor/models/video/epva.py
def van_dec_2d(x, skip_connections, output_shape, first_depth, hparams=None): """The VAN decoder. Args: x: The analogy information to decode. skip_connections: The encoder layers which can be used as skip connections. output_shape: The shape of the desired output image. first_depth: The depth of th...
def van_dec_2d(x, skip_connections, output_shape, first_depth, hparams=None): """The VAN decoder. Args: x: The analogy information to decode. skip_connections: The encoder layers which can be used as skip connections. output_shape: The shape of the desired output image. first_depth: The depth of th...
[ "The", "VAN", "decoder", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L185-L249
[ "def", "van_dec_2d", "(", "x", ",", "skip_connections", ",", "output_shape", ",", "first_depth", ",", "hparams", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "'van_dec'", ")", ":", "dec", "=", "tf", ".", "layers", ".", "conv2d_transpose...
272500b6efe353aeb638d2745ed56e519462ca31
train
analogy_computation_2d
Implements the deep analogy computation.
tensor2tensor/models/video/epva.py
def analogy_computation_2d(f_first_enc, f_first_frame, f_current_enc, first_depth): """Implements the deep analogy computation.""" with tf.variable_scope('analogy_computation'): frame_enc_diff = f_first_frame - f_first_enc fr...
def analogy_computation_2d(f_first_enc, f_first_frame, f_current_enc, first_depth): """Implements the deep analogy computation.""" with tf.variable_scope('analogy_computation'): frame_enc_diff = f_first_frame - f_first_enc fr...
[ "Implements", "the", "deep", "analogy", "computation", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L252-L298
[ "def", "analogy_computation_2d", "(", "f_first_enc", ",", "f_first_frame", ",", "f_current_enc", ",", "first_depth", ")", ":", "with", "tf", ".", "variable_scope", "(", "'analogy_computation'", ")", ":", "frame_enc_diff", "=", "f_first_frame", "-", "f_first_enc", "f...
272500b6efe353aeb638d2745ed56e519462ca31
train
van
Implements a VAN. Args: first_enc: The first encoding. first_frame: The first ground truth frame. current_enc: The encoding of the frame to generate. gt_image: The ground truth image, only used for regularization. reuse: To reuse in variable scope or not. scope_prefix: The prefix before the s...
tensor2tensor/models/video/epva.py
def van(first_enc, first_frame, current_enc, gt_image, reuse=False, scope_prefix='', hparams=None): """Implements a VAN. Args: first_enc: The first encoding. first_frame: The first ground truth frame. current_enc: The encoding of the frame to generate. ...
def van(first_enc, first_frame, current_enc, gt_image, reuse=False, scope_prefix='', hparams=None): """Implements a VAN. Args: first_enc: The first encoding. first_frame: The first ground truth frame. current_enc: The encoding of the frame to generate. ...
[ "Implements", "a", "VAN", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L301-L346
[ "def", "van", "(", "first_enc", ",", "first_frame", ",", "current_enc", ",", "gt_image", ",", "reuse", "=", "False", ",", "scope_prefix", "=", "''", ",", "hparams", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope_prefix", "+", "'v...
272500b6efe353aeb638d2745ed56e519462ca31
train
encoder_vgg
VGG network to use as encoder without the top few layers. Can be pretrained. Args: x: The image to encode. In the range 0 to 1. enc_final_size: The desired size of the encoding. reuse: To reuse in variable scope or not. scope_prefix: The prefix before the scope name. hparams: The python hparam...
tensor2tensor/models/video/epva.py
def encoder_vgg(x, enc_final_size, reuse=False, scope_prefix='', hparams=None, is_training=True): """VGG network to use as encoder without the top few layers. Can be pretrained. Args: x: The image to encode. In the range 0 to 1. enc_final_size: The desired size of the encoding. reuse...
def encoder_vgg(x, enc_final_size, reuse=False, scope_prefix='', hparams=None, is_training=True): """VGG network to use as encoder without the top few layers. Can be pretrained. Args: x: The image to encode. In the range 0 to 1. enc_final_size: The desired size of the encoding. reuse...
[ "VGG", "network", "to", "use", "as", "encoder", "without", "the", "top", "few", "layers", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L349-L401
[ "def", "encoder_vgg", "(", "x", ",", "enc_final_size", ",", "reuse", "=", "False", ",", "scope_prefix", "=", "''", ",", "hparams", "=", "None", ",", "is_training", "=", "True", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope_prefix", "+", "'en...
272500b6efe353aeb638d2745ed56e519462ca31
train
predictor
LSTM predictor network.
tensor2tensor/models/video/epva.py
def predictor(enc_flat, action, lstm_states, pred_depth, reuse=False, scope_prefix='', hparams=None): """LSTM predictor network.""" with tf.variable_scope(scope_prefix + 'predict', reuse=reuse): enc_final_size = enc_flat.get_sh...
def predictor(enc_flat, action, lstm_states, pred_depth, reuse=False, scope_prefix='', hparams=None): """LSTM predictor network.""" with tf.variable_scope(scope_prefix + 'predict', reuse=reuse): enc_final_size = enc_flat.get_sh...
[ "LSTM", "predictor", "network", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L404-L492
[ "def", "predictor", "(", "enc_flat", ",", "action", ",", "lstm_states", ",", "pred_depth", ",", "reuse", "=", "False", ",", "scope_prefix", "=", "''", ",", "hparams", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope_prefix", "+", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
construct_model
Constructs the tensorflow graph of the hierarchical model.
tensor2tensor/models/video/epva.py
def construct_model(images, actions=None, context_frames=2, hparams=None, is_training=True): """Constructs the tensorflow graph of the hierarchical model.""" pred_depth = 20 enc_out_all, pred_out_all, van_out_all, van_on_enc_all = [...
def construct_model(images, actions=None, context_frames=2, hparams=None, is_training=True): """Constructs the tensorflow graph of the hierarchical model.""" pred_depth = 20 enc_out_all, pred_out_all, van_out_all, van_on_enc_all = [...
[ "Constructs", "the", "tensorflow", "graph", "of", "the", "hierarchical", "model", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L495-L569
[ "def", "construct_model", "(", "images", ",", "actions", "=", "None", ",", "context_frames", "=", "2", ",", "hparams", "=", "None", ",", "is_training", "=", "True", ")", ":", "pred_depth", "=", "20", "enc_out_all", ",", "pred_out_all", ",", "van_out_all", ...
272500b6efe353aeb638d2745ed56e519462ca31