CS 460G · Week 13 → Lecture 2 · Fall 2026

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 formulas Vaswani 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

QuestionShort 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:

The recurrence being replaced · slide 5
\mathbf{h}_t = \tanh\!\left(U\mathbf{x}_t + W\mathbf{h}_{t-1}\right)
\hat{\mathbf{y}}_t = \mathrm{softmax}(V\mathbf{h}_t)
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.
Backpropagation through time · slides 3–4
J = \sum_{t=1}^{T} J_t \qquad\Longrightarrow\qquad \frac{\partial J}{\partial W} = \sum_{t=1}^{T} \frac{\partial J_t}{\partial W}
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 — exploding and vanishing gradient
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?”:

CNNRNNTransformer
SeesLocal windows; global dependencies largely ignoredEverything up to now, via one hidden stateAll tokens at once, every layer
OrderBuilt in (kernel slides over the grid)Built in (the sequence is the loop)Not built in — positional encodings required
Parallel over the sequence?YesNo: $h_t$ needs $h_{t-1}$Yes — all scores computed at once
Long-range path lengthGrows with depthGrows with distance (and decays)1 — any token attends to any token directly
CostLinear in lengthLinear 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.

Scaled dot-product attention · slide 31 · Vaswani et al. 2017
\mathrm{Attention}(Q,K,V) = \mathrm{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right)V
$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.
SymbolShapeWhat it isPlain-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$ScoresEvery query compared with every key
$\mathrm{softmax}(\cdot)$$n \times m$WeightsEach 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, what does it refer to
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.

The variance argument · derived for this page
q\cdot k = \sum_{i=1}^{d_k} q_i k_i
\Rightarrow\; \mathrm{Var}(q\cdot k) = d_k\,\mathrm{Var}(q_i k_i) = d_k
\Rightarrow\; \mathrm{std}\!\left(\frac{q\cdot k}{\sqrt{d_k}}\right) \approx 1
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.

…

2.2 Multi-head: several conversations at once

Multi-head attention · slide 33
\mathrm{head}_i = \mathrm{Attention}\!\left(QW_i^{Q},\; KW_i^{K},\; VW_i^{V}\right)
\mathrm{MultiHead}(Q,K,V) =
\mathrm{Concat}\!\left(\mathrm{head}_1,\dots,\mathrm{head}_h\right)W^{O}
$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 — multi-head attention
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.
One decoder block · slide 27
z_1 = \mathrm{LayerNorm}\!\left(x + \mathrm{MaskedMHA}(x,x,x)\right)
z_2 = \mathrm{LN}\!\left(z_1 + \mathrm{CrossMHA}(z_1;\text{enc})\right)
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 — Transformer architecture
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:

Fixed sinusoidal encoding · slide 34
PE_{(pos,\,2i)} = \sin\!\left(\frac{pos}{10000^{\,2i/d_{\text{model}}}}\right)
PE_{(pos,\,2i+1)} = \cos\!\left(\frac{pos}{10000^{\,2i/d_{\text{model}}}}\right)
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:

posd0d1d2d3
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
posd4d5d6d7
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.

The scaling law you should be able to state
\text{scores per layer} = h\,n^{2}
\text{compute} \propto n^{2}d, \qquad \text{memory} \propto n^{2}h
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 lengthScores per headAt n=128At n=1,024At n=4,096
Formula$n^2$16,3841,048,57616,777,216
float16, 8 heads, 1 layer$2hn^2$ bytes0.25 MB16 MB256 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

ThingFormulaOne-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 diagonalPrevents looking at future tokens
Cost$O(n^2)$ per headThe price of global attention

!Exam traps, collected

WrongRight
“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)
Every number on this page, and where it comes from

▦All 50 slides