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

Query, key and value projectionsScaled dot-product attentionStable row-wise softmax
1

Read

In this order, only the parts listed

0 of 5 done

  1. 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

  2. Notebook 12.1: self-attentionUnderstanding Deep Learning - Transformers

    The complete notebook, referenced in the margin of the matrix-form derivation

  3. 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

  4. 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 check

    Skip Additive Attention; it is not a unit topic. Read the batch matrix multiplication part of Section 11.3.2 for shapes only.

  5. Equivalent-implementation boxPyTorch - scaled dot product attention

    The Efficient implementation equivalent code box: default scale , score-times-scale order, and softmax-then-dropout order

2

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 fp32 softmax on the UDL Problem 12.4 logits overflows at : that entry becomes inf/inf, which is NaN, and the rest become 0. 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 to inf, so the sum is inf, the large entry becomes NaN and every other entry 0. 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.
3

Try it yourself

Closed-book, before checking anything

Closed-book, derive the scale from the variance argument. Then hand-compute the Deep-ML 490 first test: scores , weights , output .
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 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. 2.Naive fp32 softmax 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?Answer

    Naive overflows at , so the denominator is inf and 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. 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. 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.

5

Practice

  • Deep-ML 490: Build Scaled Dot-Product Attention

    Both shown tests (the identity case and the over 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.

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.