Unit 1 of 7 · about 4 hours · derive, implement
Queries, 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.
You'll be able to
- Derive the 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
Read
In this order, only the parts listed
0 of 5 done
- 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- derivation of the scaled scoring function, then the Scaled Dot Product Attention class with the
(2, 1, 2)query toy and heatmap checkSkip 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 , 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, has variance . The factor restores unit variance before the softmax; without it large saturates the softmax and gradients vanish.
- Stable softmax subtracts the row max first. Naive
fp32softmax on the UDL Problem 12.4 logits overflows at : that entry becomesinf/inf, which isNaN, and the rest become0. The shifted form returns the correct weights. - UDL lays inputs out as 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.
Common mistakes · 3
- Computing softmax as in
fp32. 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 parameters; carry them only when the equations you implement include them.
Try it yourself
Closed-book, before checking anything
Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Query and key components are independent with zero mean and unit variance, in dimension . What are the mean and variance of their dot product, and what scale restores unit variance?Answer
Mean 0 and variance , since the dot product sums independent unit-variance products. Multiply by to restore unit variance before the softmax.
2.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?AnswerNaive overflows at , so the denominator is
infand the output is[0, 0, NaN, 0, 0]. Max-subtracted softmax gives 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.3.A self-attention block takes inputs of width , 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 to map?Answer
QKV: 3 times (64 + 8) = 216. Attention weights: 25. Fully connected: 1600 weights plus 40 biases = 1640.
4.Why must attention weights be nonnegative and sum to one, and where does each output lie?Answer
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.
Practice
- Deep-ML 490: Build Scaled Dot-Product Attention
Both shown tests (the identity case and the over case) plus the prompt mask rule (
0blocks,1keeps)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.
You're done 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.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 2 more in the section
- Understanding Deep Learning - TransformersSimon J. D. Prince · primary
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 routeD2L authors · required
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 attentionPyTorch · reference
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 problemsDeep-ML · optional
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 questionsTrenTorch · support
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.