Skip to content

4.4 Attention

ready≈ 13 hoursNeeds: 4.2, 0.2Unlocks: 4.5, 5.2
  1. 1 Learn
  2. 2 Bridge & derive
  3. 3 Explore (Attention calculator)
  4. 4 Do
  5. 5 Check

A soft lookup. An RNN squeezes everything it has read into one state vector. Attention instead lets each position look back at all the others and take a weighted average of what it finds. Each token is projected three ways: a query q\mathbf{q} (what it is looking for), a key k\mathbf{k} (what it can be found by) and a value v\mathbf{v} (what it passes on). Token ii gives token jj the weight softmax⁡j(qi⋅kj/d)\operatorname{softmax}_j(\mathbf{q}_i\cdot\mathbf{k}_j/\sqrt{d}) and outputs ∑jaijvj\sum_j a_{ij}\mathbf{v}_j. In matrix form that is softmax⁡(QK⊤/d) V\operatorname{softmax}(\mathbf{Q}\mathbf{K}^\top/\sqrt d)\,\mathbf{V} (UDL §12.2).

Why divide by d\sqrt d. If the components of q\mathbf{q} and k\mathbf{k} are independent with mean 0 and variance 1, their dot product has variance dd. With d=64d = 64 the scores spread over a range of about ±16, the softmax puts almost all its weight on one key, and its gradient nearly vanishes. Dividing by d\sqrt d restores unit variance (Vaswani et al. 2017, §3.2.1).

The causal mask. A language model predicts token t+1t+1 from tokens up to tt, and during training it does so at every position at once. So position ii must not see j>ij > i: those scores are set to −∞-\infty before the softmax, which makes their weights exactly zero. One matrix product then trains all TT predictions in parallel, the advantage over an RNN (Karpathy, Let’s build GPT).

No built-in order. Without the mask, permuting the input tokens just permutes the outputs: attention treats its input as a set. Word order has to be added through position information, the subject of 4.5 (UDL §12.3).

Backward pass of attention through the softmaxstep 1 of 5
  1. S=QK⊤/d,A=softmax⁡rows(S),O=AV\mathbf{S} = \mathbf{Q}\mathbf{K}^\top/\sqrt d,\quad \mathbf{A} = \operatorname{softmax}_{\text{rows}}(\mathbf{S}),\quad \mathbf{O} = \mathbf{A}\mathbf{V}

★ Attention calculator

Exactly what attention computes

Static view on small screens. Open this page on a laptop to interact.

Step 1. Inputs. Each token is a vector (one row of X). Here they are random 4-D embeddings (the two "the" tokens share one); in a trained model they come from the embedding table and earlier layers.

X (tokens × 4)
x₁x₂x₃x₄
1.550.380.980.50
-1.690.200.610.98
-0.74-0.250.570.33
-1.560.231.29-1.22
1.550.380.980.50
-0.32-0.82-0.39-0.73
the65%cat22%sat13%on0%the0%mat0%
query: on (4) (click a row to choose) largest weight 65% entropy 0.89 nats (uniform over 4 keys: 1.39)

Every number is computed live from random weights. Raise the query sharpness or switch off ÷√d: the scores grow, the softmax saturates and each query puts nearly all its weight on one key, which also starves the other keys of gradient. Switch off the causal mask and early tokens can see later ones, which a model predicting the next token must never do. The two occurrences of "the" have identical rows of X, so without positional information they always get identical queries, keys and attention patterns (up to the mask).

The six tokens “the cat sat on the mat” pass through attention one stage at a time: inputs X; queries, keys and values; the score matrix Q·Kᵀ; scaling by √d; the causal mask; the softmax; and the output A·V. Each stage shows its matrices as tables with coloured cells. A strip below draws arcs from the selected query token to every key, with thickness and percentage equal to its attention weight. Toggles switch the mask and the scaling, and a slider scales the queries. Keyboard: Tab to the stage buttons and press Enter; click a token in a row header to choose the query.
Scaled dot-product attention stubs/m4_4_attention.py

Loading starter file…

Prefer your own editor? Edit exercises/stubs/m4_4_attention.py and run mlc check 4.4. The tests are identical; import the results on the progress page.

Hints · attention 0/3 revealed
Hints · attention_backward 0/3 revealed
1. What do the query and key of a token do?
2. Why divide the scores by √d?
3. Where is the causal mask applied?
4. Without a mask and without position information, permuting the input tokens…
  • not yet: All tests pass (0/?)
  • not yet: Checkpoint quiz ≥ 80%
Finish the items above first.
Learner log: time spent and points of confusion

Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.