Decoder 6 layers › Cross-attention › Dot-product attention
Masked scores
×tensorlogits · 339
Scores at source tokens; −10⁹ at padding.
- shape
- [B batch, 8 heads, T queries, S keys]
Sources
Contextual evidence from Apply padding mask
Scaled scores are the product of queries and keys plus the bias; softmax over keys, dropout on the weights, then the weighted sum of values.
dot-product · tensorflow/tensor2tensor / tensor2tensor/models/common_attention.py
Pinned revision 0c66117d4297 ↗ · lines 310–345
Read code excerpt
def dot_product_attention(q,
k,
v,
bias,
dropout_rate=0.0,
summaries=False,
image_shapes=None,
name=None):
"""dot-product attention.
Args:
q: a Tensor with shape [batch, heads, length_q, depth_k]
k: a Tensor with shape [batch, heads, length_kv, depth_k]
v: a Tensor with shape [batch, heads, length_kv, depth_v]
bias: bias Tensor (see attention_bias())
dropout_rate: a floating point number
summaries: a boolean
image_shapes: optional tuple of integer scalars.
see comments for attention_image_summary()
name: an optional string
Returns:
A Tensor.
"""
with tf.variable_scope(
name, default_name="dot_product_attention", values=[q, k, v]):
# [batch, num_heads, query_length, memory_length]
logits = tf.matmul(q, k, transpose_b=True)
if bias is not None:
logits += bias
weights = tf.nn.softmax(logits, name="attention_weights")
# dropping out the attention links for each of the heads
weights = tf.nn.dropout(weights, 1.0 - dropout_rate)
if summaries and not tf.get_variable_scope().reuse:
attention_image_summary(weights, image_shapes)
return tf.matmul(weights, v)Contextual evidence from Apply padding mask
Padding positions are those whose embedding is all zeros; they get an attention bias of −1e9.
padding · tensorflow/tensor2tensor / tensor2tensor/models/common_attention.py
Pinned revision 0c66117d4297 ↗ · lines 166–205
Read code excerpt
def embedding_to_padding(emb):
"""Input embeddings -> is_padding.
We have hacked symbol_modality to return all-zero embeddings for padding.
Args:
emb: a Tensor with shape [..., depth].
Returns:
a boolean Tensor with shape [...].
"""
emb_sum = tf.reduce_sum(tf.abs(emb), axis=-1)
return tf.equal(emb_sum, 0.0)
… lines 179–193 omitted …
def attention_bias_ignore_padding(memory_padding):
"""Create an bias tensor to be added to attention logits.
Args:
memory_padding: a boolean `Tensor` with shape [batch, memory_length].
Returns:
a `Tensor` with shape [batch, 1, 1, memory_length].
"""
ret = tf.to_float(memory_padding) * -1e9
return tf.expand_dims(tf.expand_dims(ret, 1), 1)