Masked multi-head self-attention

Query–key products

×

Score every key for every query within each head.

Why

Dot products. Two attention functions were in common use: additive attention, which scores a query against a key with a feed-forward network of one hidden layer, and dot-product attention. The authors say the two are similar in theoretical complexity, and that dot-product attention is much faster and more space-efficient in practice, since it runs as highly optimized matrix multiplication. Transformer paper §3.2.1, p. 4

S=Q~KT{\htmlData{light=scores similarity}{S}}={\htmlData{light=queries prepare}{\tilde {\htmlClass{vl-stream-q}{Q}}}}{\htmlData{light=keys prepare}{{\htmlClass{vl-stream-k}{K^{\mathsf T}}}}}
in
Q~\tilde Q [B batch, 8 heads, T target positions, 64 d_k]KK [B batch, 8 heads, T target positions, 64 d_k]
out
SS [B batch, 8 heads, T queries, T keys]
Sources

In codedot_product_attention(q, k, v, bias, …) · tf.matmul(q, k, transpose_b=True) · 337

Open pinned code ↗

Direct evidence

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.

common_attention.py 310–345 ↗ · tensorflow/tensor2tensor @ 0c66117d4297

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)