Foundations to Frontier
Tests
E. Deep Learning › E12 Transformer Architectures

Scaled dot-product and multi-head attention

Scaled dot-product attention computes softmax(QKᵀ/√d_k)V: each query is compared with every key by a dot product, the scores are divided by √d_k, normalised by a softmax and used to average the values. Multi-head attention runs several such attentions in parallel on lower-dimensional projections and concatenates the results, so different heads can attend to different things at the same cost. This page covers the formula, why the scale is needed, masking, multi-head attention, costs and the KV cache. In the exercises you implement both from scratch and verify permutation equivariance and causality. You then show what the scale buys: without it the largest attention weight rises to 0.96 at d = 1024, the softmax's gradient shrinks sixfold, and a one-layer Transformer with d = 128 fails to learn reversal (0.168, chance level, against 0.946).

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Questions, keys and answers

Attention works like a soft lookup:

  • each word makes a query (“what am I looking for?”);
  • every word offers a key (“what do I contain?”) and a value (“what I will pass on”).

A query is compared with every key; the better the match, the more of that word’s value it collects. Dividing the match scores by √d stops them from getting so large that attention snaps onto a single word and stops learning. Multi-head attention runs several of these lookups at once, each looking for something different. Change the dimension in the demo, with and without the scaling.

Transformer lab
Largest weight 0.263. Unscaled dot products have standard deviation √d, so for large d the softmax becomes almost one-hot and its gradients vanish; dividing by √d keeps scores at unit scale.
Why engineers care

Attention is the main compute and memory cost of Transformers. Its scaling, masking and caching decide how fast and how stable a deployed model is.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A query is compared with…
  2. 2. Scores are divided by…
  3. 3. Multi-head attention runs…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Formula: Attention(Q, K, V) = softmax(QKᵀ/√dₖ) V, with Q (n × dₖ), K (m × dₖ), V (m × d_v). Each output row is a weighted average of value rows.
  • Why √dₖ:
    • for independent unit-variance components, q·k has variance dₖ, standard deviation 8 at dₖ = 64;
    • dividing by √dₖ restores unit variance;
    • large scores push the softmax towards one-hot, where its Jacobian diag(a) − aaᵀ is near zero: [[0.25, −0.25], [−0.25, 0.25]] for a = (0.5, 0.5), and all zeros for a = (1, 0).
  • Masking: set disallowed scores to −∞ before the softmax: a causal mask for decoders, key-padding masks for padding.
  • Multi-head:
    • headᵢ = Attention(XW_Qⁱ, XW_Kⁱ, XW_Vⁱ) with dₖ = d/h;
    • MHA(X) = Concat(head₁, …, head_h) W_O;
    • parameters 4d² + 4d whatever h is: 1,050,624 for d = 512.
  • Cost of one layer over L tokens: projections 4Ld², scores and weighted sum 2L²d. At L = d these are in ratio 2 : 1. At L = 8d, attention’s L² terms dominate.
  • KV cache: during decoding, past keys and values are stored, 2 × layers × L × d numbers. A 32-layer, 4096-wide model at 4096 tokens holds 2 GiB in 16-bit.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Std of q·k for d = 64 without scaling:
  2. 2. MHA parameters for d = 512 (with biases):
  3. 3. Softmax Jacobian of a one-hot vector:

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Attention in code

Exercise 1.

  • Multi-head attention with one head equalled plain scaled dot-product attention.
  • Permuting the inputs permuted the outputs (equivariance).
  • With a causal mask, changing the last token left all earlier outputs unchanged.

Practice.

  • F.scaled_dot_product_attention(q, k, v, attn_mask=None, is_causal=True) dispatches to fused kernels (FlashAttention, E12-20) when it can.
  • nn.MultiheadAttention(embed_dim, num_heads, batch_first=True) wraps the projections.
  • Use −∞ (or the dtype’s minimum) for masked scores, and avoid rows that are fully masked, which produce NaNs.
  • Grouped-query attention (several query heads sharing one key–value head) and multi-query attention shrink the KV cache by the group size.
q, k, v = (proj(x).view(B, L, h, d // h).transpose(1, 2) for proj in (Wq, Wk, Wv))
o = F.scaled_dot_product_attention(q, k, v, is_causal=True)          # (B, h, L, d/h)
y = Wo(o.transpose(1, 2).reshape(B, L, d))
🐍 Exercise 1: attention from scratch
Implement scaled dot-product attention with masks and multi-head attention; check equivariance and causality.
📝 Quick check (Level 2)
0/3 answered
  1. 1. PyTorch's fused attention function:
  2. 2. A fully masked row gives…
  3. 3. Grouped-query attention shrinks…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Equivariance. Without masks or positional information, self-attention is permutation-equivariant: permuting the inputs permutes the outputs identically. The model sees a set, not a sequence (E12-3).

Why several heads.

  • One softmax produces one weighted average per query, so a single head must compromise between, say, the previous word and the subject of the sentence.
  • h heads of size d/h cost the same as one head of size d, but give h separate distributions.
  • Studies of trained models find heads specialising (positional, syntactic, rare-word heads). Many can be pruned with little loss (Michel et al., 2019; Voita et al., 2019).

Scaling and saturation.

  • If scores have standard deviation σ, the softmax’s largest weight grows with σ and its Jacobian shrinks.
  • Without the 1/√d factor, σ = √d, so wide models start with near-hard attention and tiny gradients through the softmax.
  • The factor keeps σ ≈ 1 at initialisation, independent of width. Exercise 2 measures both effects.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Unmasked self-attention without positions treats its input as…
  2. 2. h heads of size d/h cost…
  3. 3. Many trained heads can be…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

What does the √d scale buy?

History.

  • Luong et al.’s dot score (2015) was unscaled.
  • Vaswani et al. (2017) added 1/√dₖ, noting that for large dₖ the dot products “grow large in magnitude”, pushing the softmax into small-gradient regions. They also introduced multi-head attention.
  • Later variants include multi-query attention (Shazeer, 2019) and grouped-query attention (Ainslie et al., 2023).

Exercise 2.

  • (a) Saturation: for random unit-variance queries and 16 keys, the mean largest attention weight and the norm of the softmax Jacobian, with and without scaling, averaged over 300 draws.
  • (b) Training: the one-layer Transformer of E12-1 with d = 128 (sinusoidal positions), trained for 150 steps of batch 8 to reverse 12 tokens.
d largest weight, scaled largest weight, unscaled Jacobian norm, scaled Jacobian norm, unscaled
4 0.236 0.425 0.295 0.317
64 0.250 0.845 0.304 0.173
256 0.235 0.914 0.305 0.111
1024 0.246 0.962 0.305 0.051

Reversal accuracy at d = 128: scaled 0.946, unscaled 0.168, which is chance (1/6). Second seed: 0.938 and 0.163.

  • With scaling, attention statistics do not depend on width: the largest weight stays near 0.24 and the Jacobian norm near 0.30.
  • Without it, the softmax saturates as d grows. At d = 1024 one key takes 96% of the weight, and the gradient through the softmax is 6 times smaller.
  • This decides learning. At d = 32 both versions learned reversal, but at d = 128 the unscaled layer learned nothing while the scaled one reached 0.95. In a longer run (300 steps of batch 32) the scaled layer reached 1.000 and the unscaled 0.276.
🐍 Exercise 2 (research): what does the √d scale buy?
Measure softmax saturation with and without scaling across widths, and train a one-layer Transformer both ways.

Attention in AI, robotics and aerospace

  • Sensor fusion: cross-attention lets a query from one sensor (camera) gather features from another (lidar, radar).
  • Memory budgets: KV cache size limits context length on embedded accelerators; grouped-query attention and quantised caches help.
  • Numerical care: mixed-precision attention needs scaling and stable softmax to avoid overflow, especially on low-precision hardware.

References

  1. A. Vaswani et al. (2017). “Attention is all you need.” Proc. NeurIPS.
  2. P. Michel, O. Levy, G. Neubig (2019). “Are sixteen heads really better than one?” Proc. NeurIPS.
  3. N. Shazeer (2019). “Fast transformer decoding: one write-head is all you need.” arXiv:1911.02150.
  4. J. Ainslie et al. (2023). “GQA: training generalized multi-query transformer models from multi-head checkpoints.” Proc. EMNLP.