Masked multi-head self-attention

Reference code openai/gpt-2 @ 9b63575, huggingface/transformers @ 71c6f69, configuration openai-community/gpt2 @ 607a30d · checkpoint tensors not independently counted · How to read

Transformer block › Attention

Attention probabilities

×

tensorw · 97

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.

openai · openai/gpt-2 / src/model.py
Pinned revision 9b63575ef427 ↗ · lines 20–97

Read code 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.

transformers · huggingface/transformers / src/transformers/models/gpt2/modeling_gpt2.py
Pinned revision 71c6f699ac9b ↗ · lines 63–69

Read code 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)