Masked multi-head self-attention

Attention probabilities

×

Each row distributes one query position's weight across its own and earlier key positions.

shape
AiA_{i} head i [B batch, 1, 1001]AA all heads [B batch, 12 heads, 1, 1001]
Sources

Contextual evidence from Row-wise softmax

The released implementation subtracts the row maximum for stability, exponentiates, and divides by the row sum on the final axis. Attention calls it after masking.

model.py 20–97 ↗ · openai/gpt-2 @ 9b63575ef427

Excerpt
def softmax(x, axis=-1):
    x = x - tf.reduce_max(x, axis=axis, keepdims=True)
    ex = tf.exp(x)
    return ex / tf.reduce_sum(ex, axis=axis, keepdims=True)

… lines 24–95 omitted …

        w = mask_attn_weights(w)
        w = softmax(w)

Contextual evidence from Attention weights after dropout

The maintained eager attention path normalizes scores, applies training-dependent dropout, and multiplies the resulting weights by values.

modeling_gpt2.py 63–69 ↗ · huggingface/transformers @ 71c6f699ac9b

Excerpt
    attn_weights = nn.functional.softmax(attn_weights, dim=-1)

    # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op otherwise
    attn_weights = attn_weights.type(value.dtype)
    attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)

    attn_output = torch.matmul(attn_weights, value)