QUESTION 4 OF 15

Why divide attention logits by the square root of the key dimension?

Reveal the answer and explore the explanation.

04
MediumHigh priorityVisual

Why divide attention logits by the square root of the key dimension?

Answer
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 ↗

Last 30 min revisionHigh-yield interview Q&As