Why divide attention logits by the square root of the key dimension?
Reveal the answer and explore the explanation.
04MediumHigh priorityVisualWhy divide attention logits by the square root of the key dimension?
Answer
MediumHigh priorityVisual
Why divide attention logits by the square root of the key dimension?
Answer
Softmax of query-key dot products divided by square root of key dimension, applied to values.
Deeper understanding
The standard operation is softmax(QKᵀ/√dₖ + mask)V. If independent query and key coordinates have unit variance, their dot product variance grows with dₖ. Scaling helps prevent overly large logits and saturated softmax.
Practical example
Compute contextual output while preventing large logits from saturating softmax.
PythonRelated concept example
import torch
q, k, v = [torch.randn(4, 8) for _ in range(3)]
weights = (q @ k.T / 8**.5).softmax(dim=-1)
out = weights @ v
print(out.shape)A single unmasked attention head with four tokens.
Reference: Further reading ↗