Transformer block › Attention
Row-wise softmax
×no parameterssoftmax(w)
Normalize each query’s masked scores across key positions into attention probabilities. Each row sums to one before attention dropout.
- in
- [B batch, 12 heads, T queries, T keys]
- out
- [B batch, 12 heads, T queries, T keys]
Explanation
, , and index batch, head, query and key; runs over the keys.
The released code subtracts each row’s maximum before exponentiating (model.py 20–23). The shift cancels between numerator and denominator and keeps every exponent at or below zero, so cannot overflow.
Codemodel.py 20–23, 96–97
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) w = mask_attn_weights(w)
w = softmax(w)Sources1
Direct evidence
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)