Transformers — attention, and the end of recurrence
Last week the recurrence was the story: $h_t$ depends on $h_{t-1}$, so the model must walk the
sequence one step at a time. This lecture throws that away. Every token looks at every other token at
once, the weights come from the data instead of from a fixed position, and the whole sequence is
parallel — at the price of $n^2$ comparisons and the need to inject order by hand. Every formula below
is real LaTeX, rendered in your browser, not a screenshot.
50 slides4 interactive widgets24 display formulasVaswani et al. 2017
Coming from W13L1? This page assumes the gating material (LSTM/GRU) and, before that, the plain
recurrence. If “hidden state” and “vanishing gradient” are not yet solid, read
the W13L1 page or
the W12L3 RNN page first.
The sequel to this page is W13L3 — Vision Transformers.
3
matrices: Q, K, V
n²
scores for n tokens
0
recurrences
√dk
the scaling that saves softmax
One sentence that governs the lecture. Attention is a learned, content-based lookup: every
token poses a question (its query), every token advertises what it holds (its key), and the
output is a weighted average of what the tokens actually carry (their values), with weights
from $\mathrm{softmax}(QK^\top/\sqrt{d_k})$. Because the weights come from the data and not from a
position, the operation is permutation-invariant — so order has to be added back by hand — and
because all pairs are compared at once, it is parallel over the sequence, at the price of
$n^2$ scores and the memory to store them.
0Orientation in 60 seconds
Question
Short answer
What is wrong with the RNN we just built?
It is sequential (step $t$ waits for $t-1$) and its gradient is a long product of the same $W$. Long sequences are slow and hard to learn.
What replaces the recurrence?
Self-attention: every token is compared with every other token in one matrix multiply. No loop, no hidden state carried forward.
How does a token “decide” what to look at?
Its query $q$ is dotted with every key $k$. The scores go through a softmax, and the output is that softmax applied to the values $v$.
Why divide by $\sqrt{d_k}$?
A dot product of $d_k$ random components has standard deviation $\sqrt{d_k}$. Without the division the scores grow with $d_k$, the softmax saturates, and the gradient dies.
If attention ignores order, how does the model know word order?
Positional encoding — a fixed sin/cos vector (or a learned one) added to every input embedding.
What does the full model look like?
An encoder stack ($N$ × [multi-head self-attention + feed-forward, each with add & norm]) and a decoder stack that adds masked self-attention and cross-attention over the encoder.
What does it cost?
Memory and compute grow as $O(n^2)$ in sequence length, because you materialise an $n\times n$ score matrix per head.
1Why the field left recurrence
The deck spends its first third on the recap, because the Transformer is defined by what it removes.
An RNN carries a hidden state forward:
Three shared matrices — $U$ (input→hidden), $W$ (hidden→hidden), $V$ (hidden→output) — reused at every step. Training is backpropagation through time: the loss is summed over the sequence and so are the gradients.
Each $\partial J_t/\partial W$ contains a product of $t$ Jacobians $\partial h_k/\partial h_{k-1}$ — the same $W$ multiplied $t$ times. That product is the vanishing/exploding gradient from W13L1.
Slide 5. “In RNN, W is multiplied repeatedly along with an input sequence.” The deck’s whole motivation for the rest of the lecture. tap to open full size
1.1 The comparison that ends the argument
Slides 43–46 put the three families side by side. This is the table to memorise, because it is the
answer to “why Transformers?”:
CNN
RNN
Transformer
Sees
Local windows; global dependencies largely ignored
Everything up to now, via one hidden state
All tokens at once, every layer
Order
Built in (kernel slides over the grid)
Built in (the sequence is the loop)
Not built in — positional encodings required
Parallel over the sequence?
Yes
No: $h_t$ needs $h_{t-1}$
Yes — all scores computed at once
Long-range path length
Grows with depth
Grows with distance (and decays)
1 — any token attends to any token directly
Cost
Linear in length
Linear in length, but sequential
$O(n^2)$ memory & compute for the scores
The exam sentence
A Transformer is not better because it is deeper or bigger. It is better on long sequences for two
structural reasons: the path between two tokens is one hop (not $|i-j|$), and the computation is
parallel across positions, so it actually uses a GPU. The bill arrives as $O(n^2)$.
2Attention — the one operation that matters
Slide 30 states it as a function: “maps a query and a set of key-value pairs to an output; query, key,
value all are vectors.” The retrieval analogy is exact — you ask a question, every item has a label,
and you get back a blend of the items weighted by how well their labels match your question.
$Q$ is $n\times d_k$, $K$ is $m\times d_k$, $V$ is $m\times d_v$. The product $QK^\top$ is $n\times m$ —
one score for every (query, key) pair. Softmax is applied row-wise, so each query's weights sum to 1.
Symbol
Shape
What it is
Plain-English
$Q$
$n \times d_k$
Queries
“What am I looking for?” — one per output token
$K$
$m \times d_k$
Keys
“What do I contain?” — one per input token
$V$
$m \times d_v$
Values
“What do I actually hand over if you pick me?”
$QK^\top$
$n \times m$
Scores
Every query compared with every key
$\mathrm{softmax}(\cdot)$
$n \times m$
Weights
Each row is a probability distribution over the inputs
In self-attention the queries, keys and values all come from the same sequence — the sentence looks
at itself. Slide 29 makes the point with a pronoun: in “The animal didn’t cross the street because
it was too tired”, resolving “it” means the query for it must score highly against the key for
animal, not street.
Slide 29. Self-attention in one sentence and one question: what does “it” refer to — the street or the animal? The attention weights are the answer, learned from data. tap to open full size
2.1 Why the $\sqrt{d_k}$ is there — and it is not cosmetic
If $q$ and $k$ have $d_k$ independent components with zero mean and unit variance, their dot product has
variance $d_k$, so its standard deviation is $\sqrt{d_k}$. Feed scores that grow with $d_k$ into a softmax
and it saturates: one weight ≈ 1, the rest ≈ 0, and the gradient through it ≈ 0. Dividing by $\sqrt{d_k}$
puts the scores back on a scale where softmax stays soft. Widget 2 measures this on random vectors.
Unit variance is the target: it keeps the softmax input in a range where the exponential does not saturate. Same reason weight initialisation divides by fan-in.
🎛️ Widget 1 — one query, four keys: watch the softmax
Four tokens, each with a key $k_i$ and a value $v_i$. Slide the query and the head size.
Output $=\sum_i w_i v_i$ with $w=\mathrm{softmax}(qk_i/\sqrt{d_k})$. At $d_k = 1$ there is no scaling.
…
📐 Widget 2 — measure the score spread yourself
Draw 4000 random $(q,k)$ pairs in $d$ dimensions, both $\mathcal{N}(0,1)$. The bar shows the
measured standard deviation of the raw dot product against $\sqrt{d}$ — no scaling, no data, just noise.
$h$ independent projections, computed in parallel, concatenated and projected back down.
Each head works in a low dimension $d_k = d_{\text{model}}/h$, so the total cost is roughly that of one
full-width head.
The deck's reason: “allows the model to jointly attend to information from different representation
subspaces at different positions.” In practice one head may track syntax (subject–verb), another
coreference (it → animal), another local collocations — you do not assign those roles, the training does.
Slide 33. The wiring: three linear projections, $h$ scaled-dot-product attention blocks in parallel, concat, one more linear layer. tap to open full size
3The architecture
Slide 23 gives the two halves in the deck's own words: the encoder “maps input sequence to a
sequence of continuous representations”; the decoder “receives encoder output as well as decoder
output at previous time step and generates a new output sequence”; and it is auto-regressive — it
“consumes previously generated symbols as additional input”.
One encoder block · slides 24–26
z = \mathrm{LN}\!\left(x + \mathrm{MHA}(x,x,x)\right)
y = \mathrm{LayerNorm}\!\left(z + \mathrm{FFN}(z)\right)
Two sublayers, each wrapped in a residual connection and a layer norm. The FFN is
position-wise: the same small MLP applied to each token independently (in the paper, $d\to 2048\to d$ with ReLU).
$N$ identical blocks are stacked.
y = \mathrm{LayerNorm}\!\left(z_2 + \mathrm{FFN}(z_2)\right)
The decoder has three sublayers, not two: masked self-attention (so position $t$ cannot
see $t{+}1$), cross-attention whose queries come from the decoder but whose keys and values come from the encoder,
then the feed-forward.
The mask is the whole trick of generation
In the decoder, self-attention must be causal: the score matrix has $-\infty$ above the diagonal
before the softmax, so after it those weights are exactly 0. Without the mask, the model would read the
answer it is supposed to predict — it would score perfectly on the training set and be useless at
inference.
Slide 22. The figure from the 2017 paper: encoder on the left, decoder on the right, the “N×” bracket around each stack, and the arrow carrying encoder output into every decoder block. tap to open full size
🧮 Widget 3 — shapes and the $n^2$ bill
Set the sequence length, model width and head count. Everything below follows from
$d_k=d_{\text{model}}/h$ and the fact that each head stores an $n\times n$ score matrix.
…
4Positional encoding — putting order back
Attention is permutation-invariant: shuffle the tokens and each output is just shuffled with them. That
is a feature for sets and a bug for language. The fix is to add a position vector to each input
embedding — same dimension, so the sum is still one vector per token:
Dimension $2i$ gets a sine, $2i+1$ the matching cosine — the same frequency as a pair, so
each pair is a point on a circle whose phase advances with position. Low dimensions oscillate fast, high
dimensions slowly: a binary-counter of position written in continuous form.
Analogy
Think of the clock hands in a clock shop: the second hand spins, the minute hand crawls, the hour hand
barely moves. Any instant is uniquely described by the combination of hand positions — and if you
advance time by a fixed amount, every hand advances by a fixed amount too. That second property is why the
model can learn relative offsets: $PE(pos+k)$ is a fixed linear function of $PE(pos)$.
🌈 Widget 4 — the encoding, position by position
The grid is $PE$ for 64 positions × 16 dimensions (computed exactly from the formula above).
Drag the marker to read one row as a vector.
…
The deck then walks the encoding through the token sequence “Transformer can learn long range
dependencies” (6 tokens, model dimension 8, slides 35–42), adding the embedding and the encoding element by
element. The eight numbers for positions 0–5, computed from the formula:
pos
d0
d1
d2
d3
0
+0.00
+1.00
+0.00
+1.00
1
+0.84
+0.54
+0.10
+1.00
2
+0.91
-0.42
+0.20
+0.98
3
+0.14
-0.99
+0.30
+0.96
4
-0.76
-0.65
+0.39
+0.92
5
-0.96
+0.28
+0.48
+0.88
pos
d4
d5
d6
d7
0
+0.00
+1.00
+0.00
+1.00
1
+0.01
+1.00
+0.00
+1.00
2
+0.02
+1.00
+0.00
+1.00
3
+0.03
+1.00
+0.00
+1.00
4
+0.04
+1.00
+0.00
+1.00
5
+0.05
+1.00
+0.00
+1.00
Read the table, not just the formula
Column $d_0/d_1$ cycles fastest (period $2\pi \approx 6.3$ positions); $d_6/d_7$ barely moves across six
tokens. That is why the low dimensions encode fine position and the high dimensions encode coarse
position — and why the encoding can be extrapolated to sequences longer than the ones seen in training.
A learned encoding cannot do that; the deck notes both options are allowed.
5What it costs, and why that became the next research problem
Every strength in Part 1 has a bill attached, and the deck says it plainly on slide 46: “Can be memory
intensive — calculate and store attention scores.” Two tokens per pair gives $n(n+1)/2$ pairs (with the
causal mask) and $n^2$ entries per head, per layer.
Double the sequence length and the score matrices grow 4×; double the width and the
feed-forward layers grow 4× too. This is why long context is expensive and why later work (sparse attention,
linear attention, Swin's windows) attacks exactly this term.
Sequence length
Scores per head
At n=128
At n=1,024
At n=4,096
Formula
$n^2$
16,384
1,048,576
16,777,216
float16, 8 heads, 1 layer
$2hn^2$ bytes
0.25 MB
16 MB
256 MB
6Code and readings
Slide 47 links two implementations; slide 48 lists the four readings. Both are worth one pass:
And the punchline the deck drops on slide 16“ChatGPT is based on the Transformer architecture!” The GPT family is the decoder half of this
figure, stacked, with the cross-attention removed (there is no encoder), trained to predict the next token.
Everything on this page — $QK^\top/\sqrt{d_k}$, multi-head, positional encodings, causal masking — is inside it.
✓Cheat sheet
Thing
Formula
One-line reading
RNN step (replaced)
$h_t=\tanh(Ux_t+Wh_{t-1})$
Sequential; gradient is $W$ multiplied $t$ times
Scaled dot-product attention
$\mathrm{softmax}(QK^\top/\sqrt{d_k})V$
Row-wise softmax over key scores, then weighted average of values
Why $\sqrt{d_k}$
$\mathrm{Var}(q\cdot k)=d_k$
Keeps softmax inputs at unit scale; otherwise it saturates
Head dimension
$d_k=d_{\text{model}}/h$
Heads split the width, not multiply the cost
Multi-head
$\mathrm{Concat}(\text{head}_i)W^O$
Different subspaces, then one projection back
Sublayer
$\mathrm{LN}(x+\mathrm{Sublayer}(x))$
Residual first, then layer norm
Positional encoding
$\sin/\cos\!\left(pos/10000^{2i/d}\right)$
Added to embeddings; low dims fast, high dims slow
Decoder masking
$-\infty$ above the diagonal
Prevents looking at future tokens
Cost
$O(n^2)$ per head
The price of global attention
!Exam traps, collected
Wrong
Right
“Attention learns the weights from position.”
Attention is content-based and permutation-invariant. Position enters only through the added encoding.
“The softmax is over the whole matrix.”
It is row-wise: each query's weights sum to 1 over the keys.
“$\sqrt{d_k}$ is a learning rate.”
It is a fixed variance correction, not a hyperparameter.
“More heads = more compute.”
With $d_k=d/h$ the cost is roughly constant; heads partition the width.
“The decoder is just an encoder with an extra layer.”
It has three sublayers: masked self-attention, cross-attention (Q from decoder, K/V from encoder), FFN.
“Positional encoding is concatenated.”
It is added, element-wise, which is why it must have the same dimension.
“Transformers have no inductive bias.”
They have almost none — that is why they need more data, and why ViT (next lecture) needs large-scale pretraining.
Reading map for the deck (what each block of slides is doing)
1–11 — recap of RNN/LSTM/GRU and their applications; the setup for “what is still wrong”.
12–16 — outline, objectives, and the motivation slide (ChatGPT, the 2017 paper).
17–21 — what the Transformer is: non-vision, sequence data, no recurrence, no convolution, parallel.
22–27 — the architecture: encoder/decoder/auto-regressive, then each block's sublayers.
28–33 — attention: the idea, self-attention, Q/K/V, scaled dot-product, multi-head.
34–42 — positional encoding, worked through on a 6-token, 8-dimension example.
43–46 — the three-way comparison with CNNs and RNNs, ending on the memory cost.
47–50 — implementations, readings, admin, and the hand-off to W13L3 (vision).
Every number on this page, and where it comes from
Attention, multi-head and positional-encoding formulas — deck slides 31, 33, 34 (Vaswani et al., NeurIPS 2017).
The $d\to2048\to d$ feed-forward width, $d_{\text{model}}=512$, $h=8$ — the paper's “base” configuration, used as widget defaults.
The variance argument $\mathrm{Var}(q\cdot k)=d_k$ — derived on this page; Widget 2 measures it by Monte Carlo (4000 draws) rather than quoting it.
The score-count table ($n^2$ at 128/1024/4096, and bytes at float16 × 8 heads) — computed here with $2hn^2$ bytes.
The 6×8 positional-encoding table — computed here from the slide-34 formula for the deck's own example (6 tokens, model dimension 8).
Not on the slides: the loss is only drawn as $y\to E$ (slide 3); $J=\sum_t J_t$ is the standard BPTT statement, added here.