Unit 7.1 · about 4 h
214 / 324Queries, keys, values and scaled dot-product attention
Attention is the only communication path between positions in a transformer. If the scale, the softmax axis or the stability fix is wrong, every later block inherits the error.
- derive
- implement
You can now
- Derive the \(1/\sqrt{d_k}\) scale from unit-variance query and key components and state the assumption it needs.
- Implement stable scaled dot-product attention from tensor operations, with a row-wise softmax that cannot overflow in
fp32. - Explain attention output as a convex combination of values and predict how a logit shift moves the weights.
Covers
- Query, key and value projections
- Scaled dot-product attention
- Stable row-wise softmax
Study, in this order
5 steps
- Dot-product self-attention through scalingUnderstanding Deep Learning - Transformers
Sections 12.2 to 12.3.2 (pp. 208 to 214): value, query and key computation in equations 12.2 to 12.4, attention weights in 12.5, matrix form in 12.7 and 12.8, and the scaling argument with equation 12.9
- Notebook 12.1: self-attentionUnderstanding Deep Learning - Transformers
The complete notebook, referenced in the margin of the matrix-form derivation
- Queries, keys and valuesD2L - attention and transformer implementation route
Section 11.1: the attention-pooling equation, the nonnegative, convex-combination, single-selection and average-pooling cases, and
show_heatmaps - Dot-product attention and scalingD2L - attention and transformer implementation route
Section 11.3.1 including the variance-\(d\) derivation of the scaled scoring function, then the Scaled Dot Product Attention class with the
(2, 1, 2)query toy and heatmap checkDepth · Skip Additive Attention; it is not a unit topic. Read the batch matrix multiplication part of Section 11.3.2 for shapes only.
- Equivalent-implementation boxPyTorch - scaled dot product attention
The Efficient implementation equivalent code box: default scale \(1/\sqrt{E}\), score-times-scale order, and softmax-then-dropout order
Focus on
- Queries, keys and values are three learned linear maps of the same input. D2L builds them bias-free by default while UDL equations 12.4 and 12.6 carry bias vectors, so the two parameter counts differ by construction.
- Under independent zero-mean unit-variance components, \(q^\top k\) has variance \(d\). The \(1/\sqrt{d}\) factor restores unit variance before the softmax; without it large \(d\) saturates the softmax and gradients vanish.
- Stable softmax subtracts the row max first. Naive
fp32softmax on the UDL Problem 12.4 logits overflows at \(\exp(100)\): that entry becomesinf/inf, which isNaN, and the rest become0. The shifted form returns the correct weights. - UDL lays inputs out as \(D \times N\) columns with softmax per column; D2L uses batch by queries by keys with softmax on the last axis. In both, exactly one axis sums to 1: check which one before reading any heatmap.
Reproduce closed-book
Traps
- Computing softmax as \(\exp(z)/\sum(\exp(z))\) in
fp32. \(\exp(100)\) overflows toinf, so the sum isinf, the large entry becomesNaNand every other entry0. Always subtract the row max, and recheck any code that skips it. - Softmaxing the wrong axis after a transpose. UDL and D2L sum over different axes by layout; a heatmap that sums to 1 along queries instead of keys inverts the routing story.
- Quoting D2L parameter counts for UDL equations or vice versa. The bias terms add \(3D\) parameters; carry them only when the equations you implement include them.
Practice
Deep-ML 490: Build Scaled Dot-Product Attention
Both shown tests (the \(2 \times 2\) identity \(Q/K\) case and the \(1 \times 3\) over \(2 \times 3\) case) plus the prompt mask rule (0 blocks, 1 keeps)
The two shown tests are unmasked and check outputs and weights to 4 decimals. Add your own hand-computed masked case before the masks unit.
Self-test
-
Query and key components are independent with zero mean and unit variance, in dimension \(d\). What are the mean and variance of their dot product, and what scale restores unit variance?
Mean 0 and variance \(d\), since the dot product sums \(d\) independent unit-variance products. Multiply by \(1/\sqrt{d}\) to restore unit variance before the softmax. -
Naive
fp32softmax meets UDL Problem 12.4 logits[-3, 1, 100, 5, -1]. What comes out, what does the max-subtracted form give, and what do the 25 derivatives say?Naive \(\exp\) overflows at \(\exp(100)\), so the denominator isinfand the output is[0, 0, NaN, 0, 0]. Max-subtracted softmax gives \(y_3\) near 1 and the rest near 0. All 25 derivatives are near 0 (largest magnitude about 5.5e-42): a saturated softmax with vanishing gradients. -
A self-attention block takes \(N = 5\) inputs of width \(D = 8\), with queries, keys and values also width 8. How many QKV weights and biases, how many attention weights, and how many weights and biases in a fully connected \(DN\) to \(DN\) map?
QKV: 3 times (64 + 8) = 216. Attention weights: 25. Fully connected: 1600 weights plus 40 biases = 1640. -
Why must attention weights be nonnegative and sum to one, and where does each output lie?
They form a convex combination, so each output is a weighted average of the value vectors and lies in their convex hull. Routing language only makes sense under this constraint.
Completion criterion
Stop when
You derive the scale without notes, reproduce the 490 numbers by hand, and your own implementation matches a softmax-based reference on random small cases.
Mark passed, then open 7.2 Only mark this when you can do it without notes.Leads to
- 7.2 Causal masks, padding masks and fully masked rows Feed masked scores into the same row-wise softmax.
- 7.3 Self-attention, cross-attention and multi-head shapes Reuse single-head attention inside per-head projections.
Resources for this unit
- Understanding Deep Learning - Transformers Use Chapter 12.1-12.11 and the matching notebooks for dot-product self-attention, extension to transformers, transformer layers and vision transformers.
- D2L - attention and transformer implementation route Use queries-keys-values, attention-scoring-functions, multihead-attention, self-attention-and-positional-encoding, transformer and vision-transformer. Implement masked single-head attention, multi-head attention and one pre-normalized block before comparing with PyTorch.
- PyTorch - scaled dot product attention Use the official function documentation as a differential oracle for shapes, masks, dropout and backend behavior after the manual version passes intervention tests.
Also in this section
- Deep-ML candidate - attention problems Use 490 Scaled Dot-Product Attention as the fifth platform admission sample. If the judge catches a seeded masking error, use at most one of 490, 491, 53, 904 or 905 as a changed-prompt drill.
- TrenTorch - attention and block questions Solve the multi-head split, sinusoidal positional encoding, causal mask and pre-norm versus post-norm questions the units name, then carry the same checks into your own block.