“The animal didn’t cross the street because it was too tired.” Which word does “it” mean? Two attention layers answer without reading word by word. In this toy, layer 2 sends 0.67 of the attention from “it” to “animal” and 0.03 to “street”. Change “tired” to “wide” and the two weights swap.
Switch the last word between “tired” and “wide”, then turn layer 1 off. Watch where “it” looks in each layer. Then we build every part from zero: queries and keys, the scaling, many heads, positions, the block, the masked decoder, and what it all costs.
You need a little Python, matrix multiplication and what a probability is. Lecture 4 helps. We build the rest from zero.
Lecture 5, "Transformers", of Stanford CS224N, Natural Language Processing with Deep Learning (Winter 2026, Diyi Yang and Yejin Choi). Its readings include Vaswani et al., "Attention Is All You Need" (2017), Layer Normalization (Ba, Kiros and Hinton, 2016), the Image Transformer and the Music Transformer. Before: Lecture 4, Language Models and RNNs. Next: Lecture 6, Practical Tips.
Illustrative toy, computed live in your browser: 8 hand-made features per word (yellow labels) and hand-picked weights, not a trained model. Each layer runs scaled dot-product attention, softmax(QKT/√8)V, with a residual add between the layers.
Chapter 0
Count the steps an RNN must take one after another, and the steps a word's meaning must travel
Lecture 4 ended with an RNN that reads one word at a time. Its hidden state at step t needs the state at step t − 1. So a 512-word text costs 512 steps, run one after another. A GPU with thousands of cores waits for each step to finish.
There is a second cost. For word 1 to change how the model reads word 512, its signal must pass through 511 updates of the hidden state. Lecture 4 showed what happens to a learning signal that crosses many steps: it shrinks. Attention helped, but it sat on top of the RNN, so the steps stayed.
Top: the RNN passes its state along a chain. Bottom: attention links every word to every word at once. Press Play, then make the sequence longer.
Illustrative: one time unit per serial step. Real speed also depends on the hardware and on how much work each step does (Chapter 7).
In 2017 Ashish Vaswani and seven co-authors proposed a model "based solely on attention mechanisms, dispensing with recurrence and convolutions entirely". They called it the Transformer. Every word looks at every other word in one step. For n = 512 words that is 1 step instead of 512, and a path of length 1 instead of 511.
The price is the number of pairs. Attention scores every pair of words: 512 × 512 = 262,144 scores per layer. Chapter 7 weighs that cost.
Symptom: an RNN trains slowly on long texts, even on a large GPU.
Measure: count the serial steps per sequence. An RNN needs n; nothing inside one layer can start step t before step t − 1 ends.
Fix: compute every position at once from the layer below (Chapter 1).
Chapter 1
Let each word ask a question, score every word's answer, and blend what the best answers carry
Think of a soft dictionary. A normal dictionary matches your question to one key and returns its value. Attention scores your question against every key and returns a blend of all the values.
Each word starts as a vector xi, its embedding. Three learned matrices turn it into three new vectors. The query qi = xiWQ is what word i looks for. The key kj = xjWK is the label word j shows. The value vj = xjWV is what word j hands over.
The same three matrices serve every position. All three vectors come from the same sentence, so this is self-attention.
Pick the word that asks. Press Step to go from dot-product scores to softmax weights to the blended output.
Illustrative toy: the 4-number vectors of the Code Lab below, with WQ = WK = WV = the identity, so q = k = v = x. Trained matrices are not the identity.
How much does word i attend to word j? Score the pair by the dot product of qi and kj. Turn word i's scores into weights αij with a softmax. Then add up the values, each times its weight:
o-i equals the sum over j of alpha-i-j times v-j, where alpha-i-j equals e to the q-i dot k-j, divided by the sum over m of e to the q-i dot k-m.
Take word i's query q-i. Dot it with every key k-j to get one score per word. Apply e to the power of each score and divide by their total: those are the weights alpha-i-j. Multiply each value v-j by its weight and add. The sum is o-i.
From the device: "I" = (1, 0, 1, 0), "love" = (0, 1, 0, 1), "dogs" = (1, 1, 0, 0). The scores of "I" are 2, 0 and 1. The softmax gives 0.665, 0.090 and 0.245. So oI = 0.665 × (1, 0, 1, 0) + 0.090 × (0, 1, 0, 1) + 0.245 × (1, 1, 0, 0) = (0.910, 0.335, 0.665, 0.090).
No position waits for another, so the layer is a few matrix products. Stack the queries as the rows of Q and the keys as the rows of K. One product, QKT, gives every score. In the Code Lab, you write the softmax.
Symptom: a word's attention weights do not add to 1.
Measure: sum each row. Raw scores for "I" sum to 3.
Fix: softmax each row over the keys (axis 1). Subtract the row's largest score first, so exp cannot overflow.
Chapter 2
See dot products grow with the vector length, watch the softmax lock onto one word, and undo it with one division
Call the length of each query and key vector dk. In the base Transformer it is 64. A dot product adds dk products. Say each entry of q and k is random, with mean 0 and variance 1. Then each product has variance 1, and the sum has variance dk (the paper's footnote 4).
So longer vectors give bigger scores: about ±22.6 at dk = 512. The softmax then gives almost all the weight to the largest. That is a hard lookup with a gradient near zero, so training cannot move it.
Dots are the scores of 8 random keys. Bars are their softmax weights. Raise dk with scaling off, then switch it on.
Illustrative: entries drawn at random with mean 0 and variance 1, as in the paper's footnote. "Gradient" is the largest p(1 − p), how much a score can still move its own weight.
The fix divides every score by the standard deviation, √dk. With all queries as rows of Q, keys as rows of K and values as rows of V, the whole layer is one line:
Attention of Q, K, V equals softmax of Q K-transpose over root d-k, times V.
Multiply Q by K-transpose to get every score at once. Divide each score by root d-k. Softmax each row into weights. Multiply the weights by V: each row of the result blends the values for one word.
With made-up numbers, dk = 4: q = (1, 0, −1, 2) and keys (2, 1, 0, 1), (0, −1, 1, 0), (1, 0, −1, 3). The raw scores are 4, −1 and 8, and their softmax is 0.018, 0.000, 0.982. Divided by √4 = 2 they are 2, −0.5 and 4, and the softmax is 0.118, 0.010, 0.872. Key 1 keeps 12% of the weight instead of 2%.
The gradient tells the same story. A weight p moves with its own score at rate p(1 − p). For key 1 that rate is 0.018 unscaled and 0.104 scaled, almost six times more signal. The paper notes that an older method, additive attention, beat unscaled dot products at large dk. The division fixes that and keeps the speed of a matrix product.
Symptom: attention maps are one-hot from the start of training, and they barely change.
Measure: the standard deviation of the scores before the softmax. Unscaled, it grows as √dk: 8 at dk = 64.
Fix: divide by √dk. Dividing by dk goes too far: the weights flatten toward 1/n and no key can win.
Chapter 3
Split the vector into slices, give each slice its own attention, and glue the results back together
In "the cat sat on the mat because it was tired", "it" should find "cat", "on" should find "mat", and every word gains from knowing its neighbour. One softmax row gives one blend. If one head must serve all these links, it averages them. The paper puts it this way: "With a single attention head, averaging inhibits this."
So the Transformer runs h attentions side by side. Each head has its own WQ, WK and WV. They shrink the word vector of dmodel numbers to dk = dmodel/h numbers. In the base model dmodel = 512 and h = 8, so each head works in 64 dimensions.
Each grid is one head: row = the word that asks, column = the word it looks at. Pick a head. Then change h and watch the slices.
Illustrative patterns, hand-made. Clark et al. (2019) found heads like these in trained BERT: previous token, coreference, a preposition's object, a fixed token ([CLS] or [SEP]). The slice bar uses the base model's dmodel = 512.
Each head returns an [n × dk] matrix. Place the h results side by side to get [n × dmodel] again, then mix them with one more matrix:
Multi-head of X equals concat of head-one through head-h, times W-O, where head-i equals attention of X W-i-Q, X W-i-K, X W-i-V.
For each head i, project X with that head's three matrices and run attention. Put the h outputs side by side. Multiply by W-O to mix the heads back into one d-model vector per word.
The base model: dmodel = 512, h = 8, so dk = 64. Each head's three matrices hold 3 × 512 × 64 = 98,304 weights; eight heads hold 786,432. WO adds 512 × 512 = 262,144. Total 1,048,576, the same as one head with dk = 512. With biases it is 1,050,624.
Heads cost nothing extra in weights. Do they help? Table 3 of the paper tried it on its development set: one head with dk = 512 scored 24.9 BLEU, eight heads 25.8. Too many also hurts: 32 heads of 16 dimensions scored 25.4.
Symptom: a reshape error, or heads that silently mix numbers from different words.
Measure: check that dmodel/h is a whole number. The split must be [batch, n, h, dk], then a transpose to [batch, h, n, dk].
Fix: choose h that divides dmodel, and reshape before you transpose (Field guide code).
Chapter 4
Shuffle a sentence and see attention not notice, then add a fixed wave pattern for each position
"Dog bites man" and "man bites dog" hold the same three words. Look again at Chapter 1: a word's output depends on the queries, keys and values, and none of them knows its position. Shuffle the words and each word gets the same output, only in a new row. Self-attention treats a sentence as a set.
Purple bars are the attention output for "dog" in each sentence. With positions off they match exactly. Switch positions on.
Illustrative toy: 4-number word vectors we made up, identity projections, scaled dot-product attention. Positions use the formula below with d = 4.
The fix adds a vector that depends only on the position to each word vector. Call the position pos, the length of each vector dmodel, and the pair index i, which runs over pairs of entries. The paper uses fixed waves:
P-E of pos, two-i equals sine of pos over ten thousand to the two-i over d-model; P-E of pos, two-i-plus-one equals cosine of the same.
For each pair i, divide the position pos by ten thousand to the two-i over d-model. Take the sine of that angle for the even entry and the cosine for the odd entry. Add the finished vector to the word vector at that position.
With dmodel = 32, position 1: pair 0 divides by 1, so its entries are sin 1 = 0.841 and cos 1 = 0.540. Pair 1 divides by 100002/32 = 1.778, giving sin 0.562 = 0.533 and cos 0.562 = 0.846.
Think of a clock with many hands. The first pair turns fast, the last pair barely moves, and together they mark every position. Each pair is a point on a circle, so moving k positions turns every pair by a fixed angle. That is why the paper expected the model to learn relative offsets: PE(pos + k) is a linear function of PE(pos). As a check, with dmodel = 32 the dot product PE(pos) · PE(pos + 1) is 15.31 at every position.
The paper also tried learned position vectors and got nearly identical results (Table 3, row E). It kept the sines because they might extend to longer sentences than training saw. Later models often use learned or rotary positions (Positional encoding covers them).
Symptom: the model translates "dog bites man" and "man bites dog" the same way.
Measure: shuffle a test sentence and compare each word's output. If only the row order changes, the model has no positions.
Fix: add PE (or learned position vectors) to the embeddings before the first layer.
Chapter 5
Wrap attention and a small per-word network in residual adds and layer norm, then stack six
Attention only mixes: each output is a weighted average of values. The block adds a feed-forward network (FFN): two layers with a ReLU, applied to each word on its own, with the same weights at every position:
An encoder layer has two sub-layers: multi-head self-attention, then the FFN. The same wrapper goes around each. Add the sub-layer's input to its output, a residual connection, then normalise:
y equals layer-norm of x plus sub-layer of x.
Run the sub-layer on x. Add x back to its output. Normalise each word's vector. The result y goes on to the next sub-layer.
With made-up numbers: x = (1, −1, 0, 2) and Sublayer(x) = (1, 5, 6, 6). Their sum is (2, 4, 6, 8). Layer norm turns it into (−1.34, −0.45, 0.45, 1.34), worked below.
Why the residual? Backpropagation (Lecture 3) multiplies the gradient by each layer's derivative. The derivative of x + Sublayer(x) is the identity plus the sub-layer's part. So a path with factor 1 always reaches the bottom.
Each bar is the gradient size at one layer, top on the right, on a log scale. Add layers, then turn the residual off.
Illustrative toy: 16 numbers per layer, x → tanh(Wx) with fixed random W of gain 0.8, no attention. The identity path is the same in a real Transformer.
Layer normalisation (Ba, Kiros and Hinton, 2016) works on one word's vector at a time. Call the entries of that vector z, their mean μ and their variance σ². The learned vectors γ and β set the final scale and shift:
Layer-norm of z equals gamma times, z minus mu over the root of sigma-squared plus epsilon, plus beta.
Find the mean mu and variance sigma-squared of the word's entries. Subtract mu from each entry and divide by the standard deviation. Multiply by gamma and add beta.
z = (2, 4, 6, 8): μ = 5 and σ² = (9 + 1 + 1 + 9)/4 = 5, so the standard deviation is 2.236. With γ = 1 and β = 0 the output is (−3, −1, 1, 3)/2.236 = (−1.34, −0.45, 0.45, 1.34).
The worked count for one base encoder layer: 1,050,624 attention weights, 2,099,712 FFN weights and 2,048 in its two norms. That is 3,152,384 in all, and the encoder stacks N = 6 layers.
Symptom: a deep stack trains no better than a shallow one, or the loss sits still at the start.
Measure: the gradient size per layer. Without residuals, the lower layers get almost nothing.
Fix: a residual add around every sub-layer. Many later models use pre-norm, x + Sublayer(LayerNorm(x)), which trains more easily when deep.
Chapter 6
Block every look ahead with minus infinity, train all positions at once, and let queries from the decoder read the source
The decoder writes the translation one word at a time. In training we know the whole target sentence, so we feed it all at once. This is teacher forcing, as in Lecture 4. But then position 2 could look at word 3, the word it must predict. It would copy, not learn.
So the decoder's self-attention adds a causal mask M before the softmax. Entry Mij is 0 when j ≤ i, a word at or before position i. It is −∞ when j > i, a future word:
Masked attention of Q, K, V equals softmax of Q K-transpose over root d-k, plus M, times V.
Compute the scaled scores as in Chapter 2. Set every score from position i to a later position j to minus infinity by adding M. Softmax each row: the future gets exactly zero weight. Blend the values.
The Code Lab's scores for "Le chat dort": row "chat" is (1.5, 2.8, 0.9). The mask turns it into (1.5, 2.8, −∞), and the softmax gives 0.21, 0.79 and 0. The mask leaves row "dort" alone: (0.3, 1.8, 2.1) gives 0.09, 0.39 and 0.52.
Press Step to fill one row per target word. Then turn the mask off: red cells are looks into the future.
Illustrative: the made-up scores from the worked example and the Code Lab below.
Each decoder layer has a third sub-layer between the two: cross-attention. Its queries come from the decoder; its keys and values come from the encoder's output. So each target position asks which source words matter now, the job attention did for the RNN translator in Lecture 4. The decoder stacks N = 6 such layers, and a final linear layer and softmax give next-word probabilities.
At generation time there is no target to feed. The decoder writes word 1, feeds it back, writes word 2, and so on: one pass per word, as slow as an RNN here. Code usually keeps each earlier word's keys and values, a KV cache, so each step computes only the newest word's.
Symptom: the training loss falls fast and low, but generation writes nonsense.
Measure: look at one row of decoder attention. Any weight on a later position is a leak.
Fix: add the causal mask (strictly above the diagonal, so each word still sees itself).
Chapter 7
Compare the work per layer of attention and recurrence, and find the length where attention gets expensive
Attention scores every pair of the n words, and each score is a dot product of d numbers. An RNN does a d × d matrix product at each of its n steps. Call the sequence length n and the vector length d. Table 1 of the paper compares the work per layer:
The work of attention grows like n-squared times d; the work of an RNN grows like n times d-squared.
Divide the two: attention over RNN is n over d. While the sequence is shorter than the vector, n below d, attention does less work. Past that it does more, and the gap grows with n.
With d = 512: at n = 512 the two are equal. At n = 4,096 attention does 8 times the work. One head's score table then holds 16.8 million numbers, 33.6 MB in 16-bit floats, in every layer.
Bars use a log scale: each grid line is 10 times the last. Drag the length and find where attention's bar passes the RNN's.
Orders of growth from Table 1 of the paper, with constant factors left out. Memory is one head's n × n score table in 16-bit floats.
The paper notes that for sentences, n is usually smaller than d. So for translation the trade was cheap: same or less work, 1 serial step instead of n, and a path of length 1. For books or long chats, n² dominates. FlashAttention (lesson) computes the same result without storing the table. The paper itself suggests attending only to a nearby window, as the Image Transformer does (Chapter 9).
Symptom: doubling the context length runs out of GPU memory, though the weights did not change.
Measure: the score tables grow as n²: twice the length is four times the memory.
Fix: a memory-saving exact kernel, a local window, or a linear-time variant (Linear attention).
Chapter 8
Set the depth, width and heads, follow one sentence's shapes through the stack, and count every weight
Here is the whole model as the paper built it for translation. Source words go through an embedding, the model adds positions, and N encoder layers run. Target words, shifted right by one, go through N decoder layers with masked self-attention, cross-attention and an FFN. A linear layer and softmax score every word piece of the vocabulary.
Start from the base model. Change one setting at a time and watch the stack, the shapes and the count. Then turn weight sharing off.
We count from the paper's shapes, with biases, layer norms, post-norm layers and a shared vocabulary of 37,000 word pieces (the paper says "about 37000"). Paper totals from Table 3. Heads change dk, not the count.
What to look at. The base model counts to 63.1 million; the paper says 65 million. The vocabulary is only "about 37000", and the paper does not list every bias, so expect a small gap. The big model counts to 214.2 million against the paper's 213. Turn sharing off and the base model jumps to 101.0 million. The paper shares one matrix between the two embeddings and the output layer, and multiplies the embeddings by √dmodel.
Next, set h from 1 to 32. The count does not move, because each head gets dmodel/h dimensions. Then set N to 12: the encoder and decoder grow, the embedding does not.
The paper's results, from Table 2. On WMT 2014 English to German (about 4.5 million sentence pairs), the base model scored 27.3 BLEU after 12 hours on 8 P100 GPUs, already above every earlier published result, ensembles included. The big model scored 28.4 after 3.5 days, more than 2 BLEU above the best of them. On English to French, Table 2 lists 41.8 for the big model (the text of the same version says 41.0).
Training used Adam with β1 = 0.9, β2 = 0.98 and ε = 10−9. The learning rate rose for 4,000 warm-up steps, then fell as one over the square root of the step. Dropout was 0.1 for the base model, and label smoothing 0.1, which the paper says "hurts perplexity" but improves BLEU.
Chapter 9
Cut an image into patches, count the tokens and the pairs, and see what images and music changed
Nothing in attention knows it reads words. It takes a set of vectors, plus positions. Two of the lecture's readings carried that to other data.
The Image Transformer (Parmar et al., 2018) generates images one pixel channel at a time. A 32 × 32 colour image is 32 × 32 × 3 = 3,072 tokens, so full attention needs 9.4 million scores. The paper restricts each position to a local neighbourhood, the limit Vaswani et al. had suggested for long inputs.
The grid shows the patches. Each patch becomes one token. Make the patches smaller and watch the count of pairs.
The page draws the image, 224 × 224 pixels, the input size the Vision Transformer used. Counts are exact; patch side 1 means one token per pixel (colour channels kept together).
The worked number: 16 × 16 patches of a 224 × 224 image give 14 × 14 = 196 tokens. Each holds 16 × 16 × 3 = 768 numbers, and there are 38,416 scores per head. One token per pixel would be 50,176 tokens and 2.5 billion scores. The Vision Transformer (Dosovitskiy et al., 2021) uses the 16-pixel patches with a plain encoder (Vision Transformer).
The Music Transformer (Huang et al., 2019) reads music as a sequence of note events. In music the gap between notes matters more than where they sit. So it scores pairs with relative positions: a term that depends on the offset i − j.
Symptom: a Transformer on raw pixels runs out of memory on a small image.
Measure: count the tokens. Pixels of a 224 × 224 image are 50,176 tokens, and n² is 2.5 billion.
Fix: bigger tokens (patches) or a local window.
Chapter 10
Keep the parts, the numbers, the code, and where the course goes next
Self-attention lets each word score every word with a query and a key, and blend their values. Dividing by √dk keeps the softmax soft. Heads run several attentions in slices of the same width. Attention sees a set, so we add positions.
A block wraps attention and an FFN in residual adds and layer norm, and the blocks stack. The decoder masks the future and reads the encoder through cross-attention. All of it runs in parallel, at a cost of n² scores per layer.
| Layer type | Work per layer | Serial steps | Longest path |
|---|---|---|---|
| Self-attention | n² · d | 1 | 1 |
| Recurrent (RNN, LSTM) | n · d² | n | n |
| Convolution, width k | k · n · d² | 1 | logk n |
| Number | Value | Where |
|---|---|---|
| Weights of "I" over I, love, dogs | 0.665, 0.090, 0.245 | Chapter 1 |
| Softmax of 4, −1, 8: raw vs ÷2 | 0.982 vs 0.872 on the top key | Chapter 2 |
| Multi-head attention weights, dmodel 512 | 1,048,576 (+2,048 biases) | Chapter 3 |
| Dev BLEU: 1 head vs 8 heads | 24.9 vs 25.8 | Table 3, row A |
| One encoder layer, base | 3,152,384 weights | Chapter 5 |
| Masked row "chat" | 0.21, 0.79, 0 | Chapter 6 |
| Base / big, counted here | 63.1 M / 214.2 M (paper 65 M / 213 M) | Chapter 8 |
| EN-DE BLEU, base / big | 27.3 / 28.4 | Table 2 |
| ViT tokens of a 224 × 224 image | 196 | Chapter 9 |
The core as code: multi-head self-attention with an optional causal mask, and one post-norm encoder layer, in PyTorch.
python import math, torch, torch.nn as nn, torch.nn.functional as F class MultiHeadAttention(nn.Module): def __init__(self, d=512, h=8): super().__init__() assert d % h == 0 # each head gets d // h numbers self.h, self.dk = h, d // h self.qkv = nn.Linear(d, 3 * d) # W^Q, W^K, W^V for all heads at once self.out = nn.Linear(d, d) # W^O def forward(self, x, causal=False): # x: [B, n, d] B, n, d = x.shape q, k, v = self.qkv(x).split(d, dim=-1) # each [B, n, d] q, k, v = (t.view(B, n, self.h, self.dk).transpose(1, 2) for t in (q, k, v)) # [B, h, n, dk] s = q @ k.transpose(-2, -1) / math.sqrt(self.dk) # scores [B, h, n, n] if causal: # -inf strictly above the diagonal s = s.masked_fill(torch.ones(n, n, dtype=torch.bool, device=x.device).triu(1), float('-inf')) a = F.softmax(s, dim=-1) # each row adds to 1 o = (a @ v).transpose(1, 2).reshape(B, n, d) # concat the heads return self.out(o) class EncoderLayer(nn.Module): def __init__(self, d=512, h=8, dff=2048, p=0.1): super().__init__() self.att, self.drop = MultiHeadAttention(d, h), nn.Dropout(p) self.ff = nn.Sequential(nn.Linear(d, dff), nn.ReLU(), nn.Linear(dff, d)) self.n1, self.n2 = nn.LayerNorm(d), nn.LayerNorm(d) def forward(self, x): # post-norm, as in the paper x = self.n1(x + self.drop(self.att(x))) # LayerNorm(x + Sublayer(x)) return self.n2(x + self.drop(self.ff(x)))
Where the course goes next. Lecture 6 covers final projects and practical methods. Lecture 7 pretrains Transformers on huge amounts of text. Most large language models today keep only the decoder half, with the causal mask and no cross-attention.
Now teach it: press Present or Teach. Explain how a query finds a key, why we divide the scores by √dk, and what the mask stops. Then go back to the hero, turn layer 1 off, and say why "it" no longer finds its noun.