6.2 — Scaled dot-product attention
Goal: Specialise the soft-lookup formula to use the scaled dot product as similarity, derive the batched form Attn(Q, K, V) = softmax(QKᵀ/√d_k) V, and understand why the √d_k scaling is the difference between training and not training.
1. Why this session exists
6.1 left us with the general attention formula
with the similarity function left unspecified. This session picks the function that every Transformer uses — the scaled dot product — and writes the operation in batched matrix form. Picking the similarity is not arbitrary: the choice has a direct consequence on whether the network trains at all, and the scaling factor is the single most important hyperparameter-free piece of the design.[1, 2, 4, 5]
2. The dot product as a similarity
For two vectors , the natural geometric similarity is the inner product
It is large and positive when and point in similar directions, near zero when they are orthogonal, and negative when they oppose. As a similarity score for attention, it has three structural virtues:
- Computable in a single GEMM. With all queries packed into and all keys into , every pairwise score is one matrix product:
This is the workhorse operation GPUs are tuned for.
-
Bilinear in the parameters. Because the score is linear in and in , the gradient through it has a simple form. We will see in 6.3 that and are produced from input embeddings by separate learnable linear maps; the dot product makes the whole thing differentiable in clean closed form.
-
Statistically well-behaved at standard initialisation. If and have i.i.d. zero-mean unit-variance coordinates, the dot product has a controlled distribution — variance , mean . This is the property that the scaling exploits.
Other choices exist — additive attention (Bahdanau et al., 2014)[3] uses ; bilinear attention uses — and the original "neural attention" paper (Bahdanau et al., 2014) used additive. Attention Is All You Need picked the dot product and added the scaling for the reason in §4 below; this is the choice the entire LLM family has inherited.
3. The batched form
For a query matrix (one query per row), a key matrix , and a value matrix , the scaled dot-product attention is:
The softmax is applied row-wise: each of the rows of is independently normalised over its entries.
3.1 Shapes, slowly
Let us trace the shapes:
| Quantity | Shape | What it is | | --- | --- | --- | | | | Queries (one per row) | | | | Keys (one per row) | | | | Values (one per row) | | | | Pairwise similarity matrix; row is "query vs all keys" | | | | Scaled scores | | | | Attention weights; each row sums to 1 | | | | Output (one row per query) |
A typical self-attention layer in a decoder-only LLM has (queries, keys, values all come from the same sequence of length ) and where is the hidden size and is the number of heads (6.4). For a small Transformer with , that's , so , the score matrix is , and the output is .
3.2 Row-wise softmax: each query is independent
The softmax in attention is applied across keys for each query: row of becomes a probability distribution over the keys that query might attend to.
Concretely, with , the attention weight matrix has entries
Different queries can attend to different distributions over keys; the rows do not interact. This is what makes attention "per-token" in its mixing.
3.3 The compute and memory bill
Compute:
- : FLOPs.
- Softmax: .
- : .
Total: . For self-attention with and , the per-head cost is , and the total over heads is .
Memory: the score matrix has entries. For self-attention this is , the quadratic memory cost that motivates long-context variants in 6.13.
4. Why ? The variance argument
The scaling factor is the single design choice that makes scaled dot-product attention trainable. Here is the argument from Attention Is All You Need §3.2.1.
Suppose query and key vectors are each composed of i.i.d. random coordinates with mean 0 and variance 1 — a reasonable model for vectors right after initialisation, where the matrices have small variance and inputs are standardised. Then:
(In the variance step we used independence of and and the variance-of-product formula for zero-mean factors.) So the standard deviation of scales as .
For , the scores have std . The softmax of such scores is already badly saturated — one entry is multiple standard deviations larger than the others, the corresponding , the rest . Two consequences:
(a) Vanishing gradients. Saturated softmax has everywhere except the "winner." Backprop through the softmax sends essentially zero gradient to the keys that lost. The other keys cannot move toward better matches.
(b) Hard match before training begins. With softmax saturated at initialisation, every query in every layer locks onto a single key from step zero. The network looks like it is making decisions, but the decisions are essentially random and the gradients to fix them are vanishingly small.
The fix: divide the scores by before the softmax. This rescales to have unit variance, putting the softmax in its non-saturated regime regardless of . With variance 1, exponential differences between scores are bounded by a constant, the softmax output is informative for every query, and gradients flow to every key.
5. A small worked example
Take three keys and three values in :
And one query , so as a row.
Step 1 — scores. .
Step 2 — scale. Divide by : .
Step 3 — softmax. Exponentials: . Sum: . Normalised: .
Step 4 — weighted values. Output .
The query aligns best with keys 1 and 3 (both have score 1) and roughly evenly splits attention between them, lightly attending to key 2. The output mixes the values of the chosen keys.
5.1 Without the scaling
If we omitted the scale (scores directly into softmax), the exponentials would be , sum , weights — slightly more concentrated, but for the effect is small. At , with typical post-init magnitudes, the score gap would be many standard deviations and the softmax would be near-degenerate. The scaling matters more the larger gets.
6. Reading the formula in one phrase
The whole operation in plain language:
"Each query produces a probability distribution over keys (by softmax of scaled dot-product similarities). The output is the values, averaged under that distribution."
Every architectural choice in the rest of Chapter 6 is a refinement of this single sentence. Self-attention (6.3) specifies where come from. Multi-head (6.4) specifies how many copies of this operation run in parallel. Causal mask (6.5) specifies which keys each query may attend to. Positional info (6.6, 6.7) specifies how order is injected. FFN (6.8) is the per-position non-linearity that pairs with attention to build a complete block.
(a) Verify the shape rules of §3.1: given , , , confirm by index notation that .
(b) Show that for fixed , the operation is not linear in (the softmax breaks linearity). Identify exactly which step introduces non-linearity.
(c) Re-derive the variance argument of §4 if and have variance (not ) per coordinate. What is ? What scaling factor should be used in place of to recover unit variance?
(d) For the example of §5, change the query to and recompute the attention weights and output. Which value gets the largest weight? Does the answer match your geometric intuition about the keys?
(e) Compute the total FLOPs and the score-matrix memory for a self-attention layer with . Compare with a single attention head () of the same total . Which one is cheaper in compute? Which uses less score-matrix memory?
References
- [1]
Prince, S. J. D. (2023). Understanding Deep Learning, §12 (Sequence-to-Sequence Models) and §13 (Transformers). MIT Press. — Attention as soft lookup (6.1), scaled dot-product attention (6.2), multi-head attention (6.4).
↩ - [2]
Vaswani, A., Shazeer, N., Parmar, N., et al. (2017). "Attention is all you need". NeurIPS. arXiv:1706.03762 — The Transformer paper. Scaled dot-product attention (6.2), multi-head attention (6.4), encoder–decoder cross-attention (6.3), sinusoidal positional encoding (Appendix 6.A), the FFN sub-layer (6.8), post-LN block diagram (6.10), full architecture read (6.11).
↩ - [3]
Bahdanau, D., Cho, K., & Bengio, Y. (2014). "Neural machine translation by jointly learning to align and translate". arXiv:1409.0473 — First "neural attention" paper; additive attention as a precursor to scaled dot-product (6.1, 6.2).
↩ - [4]
Luong, M.-T., Pham, H., & Manning, C. D. (2015). "Effective approaches to attention-based neural machine translation". EMNLP. arXiv:1508.04025 — Dot-product attention variants (6.2).
↩ - [5]
3Blue1Brown. "But what is a GPT? Visual intro to Transformers" and "Attention in transformers, step-by-step". 3blue1brown.com — Visual introduction to attention (6.1, 6.2).
↩ - [6]
Dettmers, T., Lewis, M., Belkada, Y., & Zettlemoyer, L. (2022). "LLM.int8(): 8-bit matrix multiplication for transformers at scale". arXiv:2208.07339 — Outlier-aware quantisation; structural activation outliers (7.4 §6.2; full treatment Cap 10.6).
↩ - [7]
Wang, P., Li, L., Shao, Z., et al. (2024). "Math-Shepherd: Verify and reinforce LLMs step-by-step without human annotations". arXiv:2312.08935 — Outcome-conditioned synthetic PRM labels (9.12 §6.2).
↩ - [8]
Snell, C., Lee, J., Xu, K., & Kumar, A. (2024). "Scaling LLM test-time compute optimally can be more effective than scaling model parameters". arXiv:2408.03314 — Inference-time scaling laws (9.15 §6.2).
↩