Module 9
Attention and transformers
A recurrent network passes information along one step at a time. Attention lets every position look straight at any earlier one. Stack that with the layers you already know and you have a transformer.
Why it matters
The transformer is the architecture behind today's language models, and it is assembled almost entirely from parts built earlier in this course: embeddings, matrix products, softmax, MLPs, and an additive path that keeps gradients alive. The one new part is attention. This module builds a complete transformer small enough to train in a browser tab in about half a minute, and the last two modules of the course open that same model up to see what is going on inside it.
The idea
Looking things up by content
Stack the vectors for a sequence of $T$ positions as the rows of $X \in \mathbb{R}^{T \times d}$. An attention head makes three linear maps of every row: a query (what this position is looking for), a key (what this position offers) and a value (what it hands over if chosen):
$$Q = X W_Q, \qquad K = X W_K, \qquad V = X W_V, \qquad \text{each of shape } T \times d_k .$$The match between position $i$'s query and position $j$'s key is their dot product. A softmax over each row turns the matches into weights, and each position receives the weighted average of the values:
$$A = \operatorname{softmax}\!\left( \frac{Q K^{\top}}{\sqrt{d_k}} \right), \qquad \text{output} = A\, V .$$Row $i$ of $A$ is a probability distribution over positions: where position $i$ is looking. This is scaled dot-product attention. The division by $\sqrt{d_k}$ keeps the dot products, whose spread grows with the dimension, from pushing the softmax into its flat, saturated regions.
No peeking: the causal mask
A model that predicts the next token is trained on every position of a sequence at once, and position $i$'s target is token $i + 1$. If position $i$ could attend to later positions it would simply read the answer. So before the softmax, $-\infty$ is added to every entry above the diagonal of $Q K^{\top}$, which makes those weights exactly zero. Position $i$ sees positions $1$ to $i$ and nothing else.
Several heads, and where their output goes
One head can only look for one kind of thing at a time, so a layer runs several in parallel, each with its own small $W_Q$, $W_K$ and $W_V$ (here two heads with $d_k = 16$). Each head's result is mapped back to $d$ dimensions by its own matrix $W_O$ and added to the vector it started from.
Attention by itself ignores order: shuffle the rows of $X$ and the outputs are shuffled the same way. To give the model positions, a learned position embedding is added to each token's embedding at the input.
The residual stream
A transformer layer is two steps, each of which reads the current vectors and adds something to them:
$$x \leftarrow x + \sum_{\text{heads}} A_h\, V_h\, W_{O,h} \quad \text{(attention, reading } \operatorname{LN}(x)\text{)}, \qquad x \leftarrow x + \operatorname{MLP}\big(\operatorname{LN}(x)\big) .$$$\operatorname{LN}$ is layer normalisation: subtract the mean of a vector's $d$ entries, divide by their standard deviation, then apply a learned scale and shift. In this pre-norm arrangement the normalisation sits on the input of each step, and the running sum $x$ itself is never overwritten. That running sum, one vector per position, is called the residual stream. It is the additive path of module 7 again: every layer reads from it and writes to it, and gradients flow back along it without attenuation.
At the top, one more normalisation and a matrix $W_U$, the unembedding, turn each position's vector into scores for the next token:
$$\text{logits} = \operatorname{LN}_{\text{final}}(x)\; W_U .$$A decoder-only transformer is exactly this: embeddings, a stack of such layers with causal masking, and an unembedding, trained with cross-entropy to predict the next token.
The model in the demo
The task is sorting. The input is five digits, then a separator; the model must continue with the same five digits in ascending order, one at a time:
3 1 4 1 5 | 1 1 3 4 5
The model has two layers, two heads per layer, $d = 32$ and an MLP hidden layer of 64 units: 17,920 parameters in all. It is trained with Adam on batches of 32 random lists, and scored on lists that are held out and never trained on.
Live demo: a transformer that sorts
Train it, try it, look inside
Loss during training
Accuracy on 200 held-out lists during training
Try a list
The model's answer, with its confidence in each digit
Attention patterns for this list
Try this
- Press Train from scratch and watch both charts. Within the first hundred or two steps most digits are right; getting whole lists right takes longer, because all five digits must be. The 600 steps here typically end with about 95% of held-out lists sorted correctly; the pretrained weights had 4,000 steps and reach 99.8%.
- While it trains, keep an eye on the heatmaps. They start as a blur and sharpen as the heads learn what to look for.
- Enter lists that are hard in different ways: all the same digit (7 7 7 7 7), already sorted (0 2 4 6 8), reversed (9 7 5 3 1). Low confidence shows you where the model is unsure.
- Press Load pretrained and compare its heatmaps with the ones your own training run produced. Look along the last five rows: where does each head look while the answer is being written?
- With the pretrained model, change one digit of the list and watch which cells of which heatmap change. That is a first, informal version of the experiments in module 10.
Exercise
Causal masking and one attention head
Write the causal mask and a single attention head in NumPy, for one sequence. The tests check the mask, compare the head with the equations above, and verify the property the mask exists for: changing a later token must not change any earlier output.
Mask. np.triu(a, k=1) keeps the part of an array strictly above the diagonal and zeroes the rest. Apply it to an array filled with -1e9.
Head. Compute Q, K, V; the scores are Q @ K.T / np.sqrt(d_k) with d_k = Q.shape[1]; add the mask; take the softmax of each row; multiply the weights by V.
Check yourself
Why does a transformer need position embeddings?
Attention computes weighted averages over a set of positions and has no notion of their order: permute the input rows and the outputs are permuted the same way. Adding a different learned vector at each position is what lets the model tell “first” from “fifth”.
What would go wrong if the causal mask were left out during training?
Each position is trained to predict the next token, and that token is sitting in the next position of the input. Without the mask the model would learn to attend one step ahead and copy it, reach zero loss, and be useless when the next token is genuinely unknown.
In a pre-norm transformer, what stands between something layer 1 writes into the residual stream and the logits?
Nothing that removes it. Later layers add to the stream but never overwrite it, so layer 1's contribution is still part of the final vector, and reaches the logits through just the final normalisation and $W_U$. That is why it makes sense to decode the stream at an intermediate layer, which is where module 10 begins.
Where this leads
The model now sorts lists, and so far you have only its attention patterns to go on for how. Module 10, coming soon, introduces the basic tools of interpretability and uses them on this same trained model: probes, the logit lens, activation patching and sparse autoencoders.
Sources: A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser and I. Polosukhin, “Attention is all you need”, NeurIPS (2017); J. L. Ba, J. R. Kiros and G. E. Hinton, “Layer normalization”, arXiv:1607.06450 (2016); A. Radford, K. Narasimhan, T. Salimans and I. Sutskever, “Improving language understanding by generative pre-training”, OpenAI (2018); N. Elhage and others, “A mathematical framework for transformer circuits”, Transformer Circuits Thread (2021), for the residual-stream view.