4.4 Attention
1. Learn
Section titled “1. Learn”- Understanding Deep Learning (Prince)§12.1–12.3 Processing text data, Dot-product self-attention, Extensions (pp. 207–215)
- Karpathy, Let's build GPT: from scratch, in code, spelled out00:42:13–01:19:11 (averaging past context, the matrix-multiply trick, softmax, self-attention, and notes 1–6 including why to divide by √head_size)
2. Bridge
Section titled “2. Bridge”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 (what it is looking for), a key (what it can be found by) and a value (what it passes on). Token gives token the weight and outputs . In matrix form that is (UDL §12.2).
Why divide by . If the components of and are independent with mean 0 and variance 1, their dot product has variance . With 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 restores unit variance (Vaswani et al. 2017, §3.2.1).
The causal mask. A language model predicts token from tokens up to , and during training it does so at every position at once. So position must not see : those scores are set to before the softmax, which makes their weights exactly zero. One matrix product then trains all 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).
3. Explore
Section titled “3. Explore”stubs/m4_4_attention.pyLoading 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.
5. Check
Section titled “5. Check”- not yet: All tests pass (0/?)
- not yet: Checkpoint quiz ≥ 80%
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.