Phase 7 · Transformers/
Lesson 7.2core4 h⚡ live demo

Scaled dot-product and multi-head attention, fully derived

Q, K, V, the √d_k argument, masking and heads — every number computed by hand

This is the single most important equation in modern AI. Everything a language model "knows about context" flows through softmax⁡(QK⊤/dk)V\operatorname{softmax}(\mathbf{QK}^\top/\sqrt{d_k})\mathbf{V}. Deriving it — including why the scaling factor is dk\sqrt{d_k}, how masks make a model autoregressive, and why heads cost 4d24d^2 parameters and O(n2d)O(n^2 d) time — is what lets you read any transformer codebase (7.8 Build GPT from scratch (nanoGPT walkthrough)), reason about inference cost (7.10 Efficient inference: KV cache, GQA, FlashAttention, speculative decoding, quantization) and understand interpretability results about attention heads (8.11 Interpretability: what is happening inside).

You'll be able to

  • Derive scaled dot-product attention from the soft-lookup idea and compute it by hand for a 3-token example
  • Prove that the dot product of unit-variance queries and keys has variance d_k and explain why that motivates the √d_k scaling
  • Implement masking, multi-head attention and the output projection in PyTorch and count their parameters
  • State the time and memory complexity of attention and explain which term dominates for long contexts

Key ideas

  1. Attention(Q,K,V) = softmax(QKᵀ/√d_k)V: scores measure query–key alignment, softmax turns them into weights, and the output is a convex combination of values.
  2. If query and key components have unit variance, q·k has variance d_k; dividing by √d_k keeps the softmax out of its saturated, zero-gradient regime.
  3. Masking sets scores to −∞ before the softmax; the causal mask (j > i) makes a model autoregressive and allows parallel training.
Show 4 more key ideas
  1. Multi-head attention runs h heads on d/h-dimensional projections and concatenates them through W^O; total parameters ≈ 4d² per layer.
  2. Time is O(n²d) for scores and O(nd²) for projections; attention matrices need O(h·n²) memory — the long-context bottleneck.
  3. Attention outputs lie inside the convex hull of the value vectors: attention mixes, it never creates new directions on its own.
  4. In code, attention is two matrix products and a softmax; the heads are a reshape, not a loop.

Suggested path through this lesson