Maps to: CMU 11-711 Spring 2026, Lecture 5 (01/27), slides
anlp-s2026-05-attention-transformers.pdf; course demo code05_transformers/(transformer.ipynb, following The Annotated Transformer and minGPT). Readings: A. Vaswani et al., Attention Is All You Need (NeurIPS 2017); A. Rush et al., The Annotated Transformer (2018); additional: Zhang & Sennrich, Root Mean Square Layer Normalization (2019); Xiong et al., On Layer Normalization in the Transformer Architecture (2020); Su et al., RoFormer: Enhanced Transformer with Rotary Position Embedding (2021); Ainslie et al., GQA: Training Generalized Multi-Query Transformer Models (2023). Sources: the public slides (adapted from Graham Neubig’s Fall 2024 course; the RoPE slides credit Tatsu Hashimoto’s CS336), the readings, and the papers cited in each section. Every number labelled “measured” comes fromcode/lecture05/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14, one CPU thread). Code:code/lecture05/— every demo runs in under 90 seconds. Reading time: ~120 minutes for the prose; ~45 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Compute attention by hand in the query–key–value framework, and explain why the scores are scaled by .
- Distinguish cross-attention from self-attention, and encoder–decoder from decoder-only Transformers.
- Explain the five core concepts of a Transformer layer: positional encodings, scaled dot-product self-attention, multi-head attention, residual connections with layer normalization, and feed-forward layers; and the causal mask that turns it into a language model.
- Compare positional schemes (learned, sinusoidal, relative, rotary) by what they guarantee and how they cope with shifted and longer inputs.
- Name the modern improvements — SiLU/SwiGLU, pre-norm, RMSNorm, RoPE, grouped-query attention — and what each fixes.
- Derive the Adam optimizer from momentum and RMSProp, and explain why post-norm Transformers need warmup.
- Compare Transformers with RNNs in parallelism, compute ( vs ), memory and long-range dependencies.
0.2 Prerequisites and scope
- Prerequisites: Lecture 4 (attention in encoder–decoders, vanishing gradients, residual/additive connections); Lecture 3 (language modeling, training practice); Lecture 2 (embeddings, backpropagation).
- Scope: the Transformer architecture and how it is trained; the modern decoder-only variant used by today’s LLMs.
- Not in scope: pretraining at scale (Lecture 6), mixture of experts (Lecture 21), efficient long-context attention (Lecture 22).
0.3 Section → code map
| Section | Idea | Demo in code/lecture05/ |
|---|---|---|
| §2 | attention by hand; scaling by | 01_attention.py Parts A–B |
| §3.3–3.5 | matrix-form self-attention; permutation equivariance; masking; multi-head | 01_attention.py Parts C–F (+ transformer.py) |
| §3.2 | sinusoidal and rotary positions; positions in a classifier; shifted and longer inputs | 02_positions.py |
| §3.8, §4.6 | Transformers vs feed-forward / GRU / LSTM; what heads attend to; generation | 03_transformer_lm.py |
| §4.3, §5.1 | pre- vs post-norm and warmup; Adam from scratch; optimizers | 04_training_details.py |
| §4.5, §5.2 | grouped-query attention and the KV cache; complexity vs RNNs | 05_complexity.py |
0.4 Notation
| Symbol | Meaning |
|---|---|
| sequence length; model width; number of heads; per-head size | |
| the output of layer (one row per position) | |
| queries, keys, values; their projections | |
| attention weight of position (query) on position (key) | |
| positional information for position | |
| gain and bias of a normalization layer |
1. Recap, and the plan
A sequence model maps to hidden states , and a language model reads the next-token distribution off each state, . There are three ways to build it. Recurrence conditions each representation on an encoding of the history (Lecture 4). Convolution conditions it on a local context (Lecture 3’s window). Attention conditions it on a weighted average of all tokens. Lecture 4 used attention as an add-on to an RNN encoder–decoder. Today it becomes the whole model.
The Transformer is a sequence model based on attention. Roadmap: attention (§2), the Transformer architecture (§3), the improved Transformer used by today’s LLMs (§4), and two additional topics, the Adam optimizer and Transformers vs RNNs (§5).
2. Attention
2.1 The basic idea, and its two forms
Bahdanau et al. (2015): encode each token in the sequence into a vector, and when decoding, take a linear combination of these vectors weighted by attention weights. There are two forms:
- Cross-attention (交叉注意力): each element of one sequence attends to the elements of another sequence. In translation, each Japanese output word (kono, eiga, ga, kirai) attends to the English input words (this, is, an, example). This is Lecture 4.
- Self-attention (自注意力) (Cheng et al., 2016; Vaswani et al., 2017): each element of a sequence attends to the elements of the same sequence. “this is an example” attends to itself. Each word builds its new representation from the other words of its own sentence.
2.2 Calculating attention
- Take a query vector (e.g. the decoder state while producing “hate”) and the key vectors (e.g. all encoder states).
- For each query–key pair, compute a score .
- Normalize the scores with a softmax so that the weights sum to one.
- Combine the value vectors (usually the encoder states, like the keys) as a weighted sum. Use the result anywhere in the model.
The slide’s example (demo 01 Part A): scores for “kono eiga ga kirai” give weights . With toy two-dimensional values, the context vector is : mostly the value of “kono”.
2.3 The query–key–value framework
In general all three roles are learned projections of hidden states:
is a compatibility (score) function, e.g. . In cross-attention, keys and values come from the encoder states and the query from the decoder state. In self-attention, all three come from the same sequence’s states.
Why separate keys and values? The key answers “should I be looked at?”, and the value answers “what do I contribute if I am?”. Separating them lets a token be found by one property and pass on another.
2.4 Score functions, and why we scale
- Dot product (Luong et al., 2015): .
- Scaled dot product (Vaswani et al., 2017): , i.e. .
Problem: the scale of the dot product grows as the dimensions get larger. If the entries of and are independent with mean 0 and variance 1, then has variance , so its standard deviation is . Large scores push the softmax toward a one-hot vector, where its gradient is nearly zero. Fix: divide by , which restores unit variance. Measured over 16 keys (demo 01 Part B):
| std of | max weight | entropy | gradient | max weight (scaled) | entropy (scaled) | gradient (scaled) | |
|---|---|---|---|---|---|---|---|
| 4 | 2.0 | 0.43 | 1.76 | 2.9e−1 | 0.24 | 2.38 | 2.8e−1 |
| 64 | 8.0 | 0.84 | 0.41 | 1.5e−1 | 0.25 | 2.36 | 2.8e−1 |
| 1024 | 32.0 | 0.96 | 0.10 | 4.3e−2 | 0.24 | 2.36 | 2.9e−1 |
(uniform attention over 16 keys has entropy .) Unscaled, a 1024-dimensional model starts with nearly one-hot attention and gradients 7× smaller. Scaled, the statistics are the same at every size.
3. The Transformer architecture
3.1 “Attention is all you need”
Vaswani et al. (2017) built a sequence-to-sequence model entirely on attention, with no recurrence. It gave strong machine-translation results, and it was fast: everything is matrix multiplication, which parallel hardware does well. Two families descend from it:
- Encoder–decoder (T5, mBART): an encoder stack reads the input with self-attention; a decoder stack generates the output with masked self-attention plus cross-attention to the encoder;
- Decoder-only (GPT, LLaMA): a single stack of masked self-attention layers, a pure language model. Conditional tasks become “continue this prompt” (Lecture 3, §2.2).
(Encoder-only models such as BERT, trained to fill in masked words, appear in Lecture 6.)
The basic idea is to stack identical Transformer layers () on top of embedded inputs. Five concepts make up the layer and the input embedding: positional encodings, scaled dot-product self-attention, multi-head attention, residual + layer normalization, and feed-forward layers.
3.2 Inputs, embeddings and positional encodings
Inputs are generally split into subwords (“the book _s were improv _ed”, Lecture 2), and each is looked up in an embedding table, as in every previous model.
Why positions? A Transformer is purely attentional, and attention treats its inputs as a set: it is permutation equivariant, . Shuffle the input and the outputs are shuffled the same way. Demo 01 Part D checks it exactly (max difference ). In “A big dog and a very big cat” vs “A big cat and a very big dog”, the word “dog” gets the same output vector in both, and the pooled sentence vectors are identical (). Without positional information a Transformer is a bag of words. Positional encodings add information about each token’s position, e.g. for the second word and for the seventh.
Learned (absolute) positional embeddings. Create a learnable table : position gets its own learned vector. Advantage: flexibility. Disadvantage: cannot extrapolate to sequences longer than (rows beyond the trained lengths are never trained).
Sinusoidal encodings (Vaswani et al., 2017). Fixed vectors with frequencies falling geometrically across dimensions:
Motivation: it may be easy to learn relative positions, since is a linear function of . Each (sin, cos) pair is rotated by the angle , a fixed matrix for all . Demo 02 Part A builds and checks for all (error ). The similarity falls smoothly with distance: 0.97 at , 0.66 at 10, 0.49 at 50.
Relative positional encodings (Shaw et al., 2018). Instead of adding absolute positions to the inputs, encode the relative position inside attention, e.g. , with a learned vector for each clipped distance : “token 0 and token 2 are tokens apart”.
Rotary positional embeddings (RoPE) (Su et al., 2021). Goal: make the dot product of a query and a key depend on their positions only through their difference, . Idea: use rotations. In 2-D, satisfies . The dot product depends only on the difference of the angles. RoPE rotates each pair of dimensions of every query and key by the angle , with (small : high frequency; large : low frequency). Then . Demo 02 Part B checks that a rotated query–key score at a fixed distance is identical at positions 0, 3, 17, 100 and 500 (spread ). RoPE is applied inside attention, to and only, and adds no parameters.
What positions buy, measured. A 2-layer Transformer classifier on Cinema World (demo 02 Part C; 2,000 labelled reviews):
| positions | dev | contrast | adjective-swapped twins both right (of 125) |
|---|---|---|---|
| none | 80.2% | 58.4% | 0 |
| learned | 82.3% | 73.6% | 64 |
| sinusoidal | 82.6% | 68.0% | 48 |
| rotary | 83.2% | 78.4% | 65 |
Without positions it is a bag of words again: 0 twins, exactly like every bag model of Lectures 1–2. With positions it can tell the twins apart. But note what it does not do: with 2,000 labelled examples and no pretraining it stays well below Lecture 4’s GRU (94.2% dev, ≈118 twins). A likely reason: the Transformer must learn word order from position signals, while a recurrence has order built in. Transformers win through scale and parallelism (§5.2), and through pretraining on huge corpora (Lecture 6), not through sample efficiency on tiny labelled sets.
Shifted and longer inputs. Train Errand World language models on single sentences (at most 25 input positions). Then score a test sentence twice: alone, and placed right after another sentence. The second placement occupies positions 7–45, so it is both shifted (it starts mid-sequence) and partly beyond the trained positions. Both columns score the same tokens (demo 02 Part D; NLL per token, alone → after):
| positions | tokens at trained positions (4,401) | tokens beyond position 24 (845) |
|---|---|---|
| learned | 0.708 → 3.046 | 0.374 → 1.645 |
| sinusoidal | 0.709 → 2.036 | 0.368 → 1.266 |
| none | 0.714 → 1.086 | 0.365 → 0.869 |
| rotary | 0.716 → 0.947 | 0.366 → 0.600 |
Every model also faces an unusual sentence boundary (no </s> between the sentences), so compare the rows. The striking result is in the first column. Learned and sinusoidal positions fail badly even at positions they were trained on. In training every sentence started at position 1, so an absolute scheme ties a token’s role to its absolute position: “a sentence-initial word at position 10” is out of distribution. RoPE’s scores depend only on distances between tokens, so a shifted sentence looks almost the same to it. It is the most robust in both columns, though not unaffected. (A first version of this experiment reported only the overall gap and called it pure “length extrapolation”. Splitting the tokens by position showed that the shift is the bigger effect.) Notice the “none” row too. A causal language model with no positional encoding still works reasonably, because attention under a causal mask can infer position by itself, e.g. by how many tokens it can see (Haviv et al., 2022). Making models work on inputs longer than they were trained on is a central problem for LLMs (Lecture 22).
3.3 Scaled dot-product self-attention
All queries at once, as matrices: with , , ,
is a matrix of scores (one row per query). The softmax normalizes each row. The output is : one new vector per position. In a Transformer layer, all three come from the previous layer’s output :
Demo 01 Part C prints the weight matrix for “I hate this movie” (random weights; each row sums to 1) and checks that our implementation equals PyTorch’s scaled_dot_product_attention ().
3.4 Multi-head attention
Intuition: information from different parts of a sentence can be useful to disambiguate in different ways. In “I run a small business”, nearby context (syntax) disambiguates “run”. In “I run a mile in 10 minutes”, the clue is farther away (semantics). “The robber made a run for it” and “The stocking had a run” need yet other cues. One attention distribution per position must average all of these; several heads can each specialize.
typically with , so heads cost about the same as one full-width head. In code (the slide’s minGPT excerpt; transformer.MultiHeadAttention): (1) apply the three projections; (2) reshape to get heads; (3) run attention on all heads in parallel; (4) “concatenate” by reshaping back and apply . Demo 01 Part F checks the module against torch.nn.MultiheadAttention with the same weights ().
What do heads do? Vaswani et al. showed heads that track syntactic relations, and tools such as BertViz visualize them. In our Errand World model (demo 03 Part B), predicting the item in “for tennis class , which met on monday , he wanted to buy his own ___”, 5 of the 8 heads put their largest weight on “tennis”, 14 tokens back (up to 0.95). Others look at “his”, “buy” or “monday”. The model’s top prediction is racquet (0.80; truth 0.70).
3.5 Masking for language-model training
To train a language model, mask the attention from future timesteps, so the model cannot cheat when predicting the next token. Position may attend to positions only: a lower-triangular causal mask, implemented by setting the scores of masked pairs to before the softmax. Demo 01 Part E: with the mask, editing the last token of a 6-token input changes only the last output; without it, every position changes. In an encoder–decoder, the decoder uses the causal mask on its own tokens (when predicting “this” in “I hate this movie ”, it sees only “I hate”) and attends freely to the encoder.
3.6 Residual connections and layer normalization
Reminder: gradients and instability. In RNNs, backpropagation through many steps makes gradients vanish or explode (Lecture 4). The same happens through many layers of a deep Transformer. Two components address it.
Layer normalization (层归一化) (Ba et al., 2016) normalizes each position’s vector to a consistent range, preventing large variation in the scale of outputs:
Residual connections (残差连接) add the input back to the output: . They prevent vanishing gradients, because contains an identity term, the same idea as Lecture 4’s additive connection. They also let learn the difference from the input rather than recompute everything. The original Transformer combines the two as “Add & Norm”: .
3.7 Feed-forward layers
After attention has mixed information across positions, a position-wise feed-forward network extracts features from each attended output on its own:
with a nonlinearity (ReLU in the original) and a hidden width usually . Attention decides what to read; the FFN decides what to do with it. Most of a Transformer’s parameters live in its FFNs.
3.8 Putting it together, and how it compares
The original (post-norm) layer is
stacked times on top of embeddings plus positional encodings, with a final linear layer and softmax over the vocabulary. transformer.TransformerLM implements it. On Errand World (demo 03; 2,000 sentences, 2 layers, , 4 heads, early stopping; floor 0.754):
| model | params | test NLL | long 8 | long 14 | long 20 | agreement |
|---|---|---|---|---|---|---|
| feed-forward, window 16 (L3) | 86,755 | 0.817 | 0.92 | 0.85 | 0.14 | 0.99 |
| GRU (L4) | 83,299 | 0.801 | 0.75 | 0.70 | 0.70 | 0.98 |
| LSTM (L4) | 104,035 | 0.785 | 0.95 | 0.94 | 0.93 | 0.99 |
| Transformer, original 2017 | 115,584 | 0.777 | 0.99 | 0.98 | 0.98 | 1.00 |
| Transformer, LLaMA-style | 115,136 | 0.780 | 0.98 | 0.98 | 0.98 | 0.99 |
The Transformers are the closest to the floor and solve the 20-token dependency almost perfectly. With direct attention to every earlier token, distance no longer matters: there is no recurrence to forget through and no window to fall outside of. Of 1,000 generated sentences, 946 (original) and 912 (LLaMA-style) are valid sentences of the language, vs 888 for the GRU.
4. The improved Transformer
Since 2017, a handful of changes have become standard. Comparing the original with LLaMA:
| Vaswani et al. (2017) | LLaMA | LLaMA 2 | |
|---|---|---|---|
| norm position | post | pre | pre |
| norm type | LayerNorm | RMSNorm | RMSNorm |
| FFN / activation | ReLU | SwiGLU | SwiGLU |
| positional encoding | sinusoidal | RoPE | RoPE |
| attention | multi-head | multi-head | grouped-query (largest models) |
4.1 SiLU / Swish and SwiGLU
Activations beyond ReLU: the sigmoid ; ReLU ; SiLU / Swish (Hendrycks & Gimpel, 2016; Ramachandran et al., 2017), which is unbounded above, bounded below, non-monotonic (it dips slightly below 0 for negative inputs) and smooth. The SwiGLU feed-forward layer (Shazeer, 2020) adds a gate:
acts as a learned, input-dependent multiplier on each hidden unit. With three matrices instead of two, the hidden width is usually reduced to about to keep the parameter count equal (as FeedForward does).
4.2 Relative and rotary positions
See §3.2. RoPE is now the default in most open LLMs: relative by construction, parameter-free, and the most robust of the four schemes to shifted and longer inputs in demo 02.
4.3 Pre-layer-norm
Where should LayerNorm go: before or after each sublayer?
In pre-LN the residual stream is never normalized, so there is a clean identity path from the output back to the input through every layer. Pre-layer-norm is better for gradient propagation (Xiong et al., 2020). Their analysis shows that post-LN produces large gradients at initialization, and needs a learning-rate warmup to avoid diverging. Measured in an 8-layer model (demo 04 Part C): at initialization the post-LN layers’ gradients are 1.5–1.7× larger than the pre-LN ones (uniformly across layers in our toy model). And at learning rate 0.01:
| model | warmup | dev NLL after epoch 1 | after epoch 8 |
|---|---|---|---|
| post-LN | none | 4.087 | 4.058 (never leaves the unigram level) |
| post-LN | 200 steps | 2.040 | 0.765 |
| pre-LN | none | 0.977 | 0.791 |
| pre-LN | 200 steps | 2.161 | 0.768 |
The post-LN model without warmup is ruined by its first large updates and never recovers; warmup rescues it; the pre-LN model trains fine without warmup. Pre-norm is one reason modern Transformers are easier to train, and deeper ones especially (Lecture 3 found warmup irrelevant for a shallow feed-forward model).
4.4 RMSNorm
RMSNorm (Zhang & Sennrich, 2019) simplifies LayerNorm by removing the mean subtraction and the bias:
It is cheaper and works as well in practice: rescaling, not re-centering, is what keeps activations in range. (transformer.RMSNorm matches PyTorch’s nn.RMSNorm.)
4.5 Grouped-query attention
During generation, a model stores the keys and values of all past tokens so they are not recomputed at every step: the KV cache. Its size grows with layers × heads × head size × tokens. Grouped-query attention (GQA; Ainslie et al., 2023) shares each key/value head among a group of query heads. Multi-query attention (MQA; Shazeer, 2019) is the extreme of one K/V head. This saves memory and so speeds up inference. At LLaMA-2-70B-like sizes (80 layers, 64 query heads of 128 dimensions, fp16; demo 05 Part D):
| attention | KV cache per token | 4,096-token context | batch of 16 contexts |
|---|---|---|---|
| multi-head (64 K/V heads) | 2.62 MB | 10.74 GB | 171.8 GB |
| grouped-query (8 K/V heads) | 328 KB | 1.34 GB | 21.5 GB |
| multi-query (1 K/V head) | 41 KB | 168 MB | 2.7 GB |
Quality on Errand World: 8, 2 and 1 K/V heads reach 0.780, 0.780 and 0.776, no measurable difference at this scale. Large models report a small loss for MQA, which GQA mostly recovers (Ainslie et al., 2023).
4.6 How important is it?
The slides show a figure from Gu & Dao (2023). “Transformer” (Vaswani et al.) vs “Transformer++” (essentially LLaMA 2’s recipe) on the same data, as a scaling curve: the stronger architecture is roughly 10× more compute-efficient, reaching the same loss with about a tenth of the compute. At our toy scale (2 layers, 2,000 sentences) the two are indistinguishable (0.777 vs 0.780). Architectural improvements of this kind show up as better scaling, which needs scale to see (Lecture 7).
5. Additional topics
5.1 The Adam optimizer
Adam (Kingma & Ba, 2015) is the standard optimizer in NLP and beyond. Each parameter gets an adaptive learning rate. It combines two ideas.
Momentum: update with a running average of gradients instead of the latest one,
is a running estimate of (one number per parameter). Intuition: noisy components of the gradient average out, so it reduces oscillations, while consistent directions accumulate.
RMSProp: divide each parameter’s step by a running estimate of its gradient’s magnitude,
estimates per parameter and normalizes the update magnitude: where squared gradients are large, the step gets smaller; where they are small, larger.
Adam = both + bias correction. Because , the early averages are biased toward zero. Correct by and ; then
Typical values: , , . Our 10-line ScratchAdam (demo 04 Part A) tracks torch.optim.Adam to over 50 steps of a 115k-parameter Transformer. Each optimizer at its best of three learning rates, after 5 epochs (Part B):
| optimizer | best learning rate | dev NLL after epoch 1 | after epoch 5 |
|---|---|---|---|
| SGD | 1.0* | 1.173 | 0.926 |
| SGD + momentum 0.9 | 0.1* | 1.272 | 0.858 |
| RMSProp | 0.001 | 1.070 | 0.806 |
| Adam | 0.003 | 1.127 | 0.781 |
(* at the edge of its grid, so a lower bound.) Note the cost: Adam stores two extra numbers per parameter, which matters for memory at scale (Lecture 20).
5.2 Transformers vs RNNs
Parallel training. A Transformer computes next-token probabilities for all positions at once with matrix multiplications: , , … in a single pass. There is no sequential hidden state as in an RNN, and modern hardware is optimized for exactly these parallel matrix operations, so training is easy to parallelize.
Compute. Per layer, an RNN does work at each of steps: . Self-attention computes with : , plus for the projections. The key difference is (RNNs) vs (Transformers). Multiply-adds per layer at (demo 05 Part A):
| Elman RNN | attention projections | attention mixing | mixing share | |
|---|---|---|---|---|
| 128 | 6.7e7 | 1.3e8 | 1.7e7 | 11% |
| 1,024 | 5.4e8 | 1.1e9 | 1.1e9 | 50% |
| 8,192 | 4.3e9 | 8.6e9 | 6.9e10 | 89% |
| 32,768 | 1.7e10 | 3.4e10 | 1.1e12 | 97% |
The quadratic term takes over beyond . Measured on one CPU thread (Part B; times vary), an attention layer goes from 0.1 ms to 29.9 ms as grows 32× (64 → 2,048), roughly quadratic, while a GRU layer goes from 0.6 to 18.2 ms, linear. But the GRU’s 2,048 steps must run one after another, while all 2,048 attention positions can run at once on parallel hardware.
Memory. Attention stores a matrix per head (Part C, fp16): 8.4 MB per head at , but 137 GB for one layer’s 64 heads at . That is why long-context models use attention that never materializes the matrix (FlashAttention, Lecture 22).
Long-range dependencies are handled by attention: any two tokens are one step apart (the 0.98 on the 20-token probe, §3.8).
| RNN | Transformer | |
|---|---|---|
| compute per layer | ||
| sequential steps per layer | 1 | |
| memory for mixing | state | attention matrix (per head) |
| path between distant tokens | steps (vanishing gradients) | 1 attention step |
| generation cost per new token | with a KV cache |
6. Summary
- Attention: scores between a query and keys, softmax into weights, weighted sum of values. With learned projections , , . Scale by , or at the softmax starts nearly one-hot (0.96) with 7× smaller gradients.
- Self-attention attends within one sequence; cross-attention between sequences. Transformers are encoder–decoder (T5) or decoder-only (GPT, LLaMA).
- Five core concepts: positional encodings (attention is permutation-equivariant without them; 0 twins), scaled dot-product self-attention , multi-head attention (5 of 8 heads read “tennis” 14 tokens back), residual + layer norm, and position-wise feed-forward layers. The causal mask makes it a language model.
- Positions: learned and sinusoidal are absolute (a sentence shifted to start mid-sequence breaks them even at trained positions: 0.71 → 3.05 and → 2.04), relative, and RoPE (scores depend only on distance; most robust to shifts and longer inputs: 0.72 → 0.95).
- On Errand World, Transformers come closest to the entropy (0.777–0.780 vs LSTM 0.785, GRU 0.801) and solve the 20-token dependency (0.98). On 2,000 labelled reviews, though, a small Transformer classifier is less sample-efficient than a GRU (≈83% vs 94%).
- The modern block: pre-norm (trains at lr 0.01 without warmup where post-norm never leaves 4.06), RMSNorm, SwiGLU, RoPE, grouped-query attention (KV cache 10.7 GB → 1.3 GB at 70B-like sizes).
- Adam = momentum + RMSProp + bias correction (best of four optimizers here: 0.781 vs SGD 0.926).
- Transformers vs RNNs: parallel across positions vs sequential; vs compute; an attention matrix; one-step paths between any two tokens.
Common pitfalls
- Forgetting the : wide heads start with saturated softmaxes and tiny gradients.
- Forgetting positions: an attention model without them treats text as a bag of words.
- Forgetting or misplacing the causal mask: a language model that can see the next token trains to a deceptively low loss and generates nonsense.
- Not masking padding keys: padded positions then receive attention weight (
MultiHeadAttentiontakes a padding mask; the classifier uses it). - Training a deep post-norm Transformer without warmup: the first large steps can ruin it (4.06 for 8 epochs).
- Assuming absolute position embeddings handle shifted or longer inputs: a sentence starting at position 10 instead of 1 raised a learned-position model’s NLL from 0.71 to 3.05 on the same tokens.
- Expecting a Transformer to beat a GRU on tiny labelled data: without pretraining, recurrence’s built-in order bias can win.
- Reading attention maps as explanations: as in Lecture 4, they show where information was read, not why the output was chosen.
Exercises
-
Attention by hand. Query ; keys , , ; values , , ; , scaled dot product. Compute the weights and the output.
Answer
Scores $q \cdot k / \sqrt{2}$: 0.707, 0, −0.707. Exponentials 2.028, 1, 0.493 (sum 3.521). Weights 0.576, 0.284, 0.140. Output $0.576(1,2) + 0.284(3,4) + 0.140(5,6) = (2.13, 3.13)$. -
Why . If are independent with mean 0 and variance 1, show that . What is the standard deviation of the scaled score?
Answer
Each term $q_i k_i$ has mean 0 and variance $\mathbb{E}[q_i^2]\mathbb{E}[k_i^2] = 1$; the $d_k$ terms are independent, so the variances add to $d_k$. Dividing by $\sqrt{d_k}$ divides the variance by $d_k$: standard deviation 1 at every $d_k$ (demo 01 Part B: max weight ≈ 0.24–0.25 for all sizes). -
Counting parameters. For a pre-norm LLaMA-style block with , 32 heads, SwiGLU hidden width 11,008 and RMSNorm, count the parameters (no biases). What fraction are in the FFN?
Answer
Attention: $W_Q, W_K, W_V, W_O$ = $4 \times 4096^2 = 67.1$M. SwiGLU: $3 \times 4096 \times 11008 = 135.3$M. Two RMSNorm gains: 8,192. Total ≈ 202.4M per block; the FFN is ≈ 67%. (LLaMA-7B has 32 such blocks ≈ 6.5B, plus 2 × 32,000 × 4096 ≈ 0.26B for embeddings and output.) -
RoPE in 2-D. With the 2-D rotation matrix, show . Why does this make attention depend on relative position only?
Answer
$(R_{t\theta} q)^\top R_{t'\theta} k = q^\top R_{t\theta}^\top R_{t'\theta} k = q^\top R_{-t\theta} R_{t'\theta} k = q^\top R_{(t'-t)\theta} k$, using $R^\top_\phi = R_{-\phi}$ and $R_\alpha R_\beta = R_{\alpha+\beta}$. The score is a function of $q$, $k$ and $t' - t$ only, so the same query–key pair scores the same at any absolute offset. -
Sinusoidal shift. For one frequency , show that is a fixed linear function of , and write the matrix.
Answer
$\sin(\omega t + \omega k) = \sin\omega t \cos\omega k + \cos\omega t \sin\omega k$; $\cos(\omega t + \omega k) = \cos\omega t\cos\omega k - \sin\omega t \sin\omega k$. So $\begin{pmatrix}\sin\omega(t+k)\\ \cos\omega(t+k)\end{pmatrix} = \begin{pmatrix}\cos\omega k & \sin\omega k\\ -\sin\omega k & \cos\omega k\end{pmatrix}\begin{pmatrix}\sin\omega t\\ \cos\omega t\end{pmatrix}$, independent of $t$ (demo 02 Part A builds exactly this block for every frequency). -
Adam’s first step. At with gradient , compute , and the update. What does this say about Adam’s first step size, whatever the gradient’s scale?
Answer
$m_1 = (1-\beta_1) g$, $\hat m_1 = g$; $v_1 = (1-\beta_2) g^2$, $\hat v_1 = g^2$. Update $= -\eta\, g / (\lvert g\rvert + \epsilon) \approx -\eta\,\operatorname{sign}(g)$. Every parameter moves by about $\eta$ on the first step regardless of its gradient's magnitude: which is also why a warmup of $\eta$ can matter early in training. -
KV cache. A model has 32 layers, 32 query heads of size 128 and 8 K/V heads, fp16. How many bytes does its KV cache need per token, and for a 128k-token context? What would full multi-head attention need?
Answer
Per token: $2 \text{ (K,V)} \times 32 \times 8 \times 128 \times 2$ bytes = 131,072 B = 128 KiB; × 131,072 tokens = 16 GiB. With 32 K/V heads: 4× more, 512 KiB per token, 64 GiB. -
Complexity crossover. For , at what sequence length does the attention term equal the projection term (ignoring constant factors)? For a 128k context, which dominates, and by how much?
Answer
$T^2 d = T d^2 \Rightarrow T = d = 4096$ (with the constants 2 and 4 used in demo 05, $T = 2d = 8192$). At $T = 131{,}072$, $T^2 d / (T d^2) = T/d = 32$: attention mixing dominates ~32× (≈16× with the constants).
Related assignment (concepts only)
- Assignment 1 — Build your own LLaMa (released this week). It asks you to implement exactly the modern block of §4 — RMSNorm, rotary embeddings, (grouped-query) causal self-attention, SwiGLU feed-forward, pre-norm residuals — and to load and train it. Every component exists here in
transformer.pyas a teaching version on toy data; these notes do not provide assignment code.
Further reading
- A. Vaswani et al., “Attention Is All You Need”, NeurIPS 2017 (course reading).
- A. Rush et al., “The Annotated Transformer”, 2018 (course reading); A. Karpathy, minGPT / nanoGPT.
- J. Ba, J. Kiros, G. Hinton, “Layer Normalization”, 2016; B. Zhang, R. Sennrich, “Root Mean Square Layer Normalization”, NeurIPS 2019.
- R. Xiong et al., “On Layer Normalization in the Transformer Architecture”, ICML 2020 — pre- vs post-norm and warmup.
- P. Shaw, J. Uszkoreit, A. Vaswani, “Self-Attention with Relative Position Representations”, NAACL 2018; J. Su et al., “RoFormer: Enhanced Transformer with Rotary Position Embedding”, 2021.
- A. Haviv, O. Ram, O. Press, P. Izsak, O. Levy, “Transformer Language Models without Positional Encodings Still Learn Positional Information”, Findings of EMNLP 2022.
- N. Shazeer, “GLU Variants Improve Transformer”, 2020; “Fast Transformer Decoding: One Write-Head is All You Need” (MQA), 2019; J. Ainslie et al., “GQA”, EMNLP 2023.
- D. P. Kingma, J. Ba, “Adam: A Method for Stochastic Optimization”, ICLR 2015.
- H. Touvron et al., “LLaMA” and “Llama 2”, 2023 — the modern recipe.
- A. Gu, T. Dao, “Mamba: Linear-Time Sequence Modeling with Selective State Spaces”, 2023 — source of the Transformer vs Transformer++ scaling figure.
Preview of Lecture 6 — Pretraining
We now have the architecture behind every modern LLM. What turns it into a useful model is pretraining: next-token prediction on enormous amounts of text. Lecture 2 previewed the idea with word vectors from unlabeled reviews. Next we see why predicting the next token teaches general skills (GPT-2’s “language models are unsupervised multitask learners”), how pretraining corpora are built — extraction, language identification, quality filtering, deduplication, mixing (FineWeb, Dolma) — what masked (BERT) vs causal (GPT) objectives learn, and how to account for the compute a pretraining run costs.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| attention / attention weight / score | 注意力 / 注意力权重 / 得分 |
| self-attention / cross-attention | 自注意力 / 交叉注意力 |
| query / key / value | 查询 / 键 / 值 |
| compatibility (score) function | 兼容性(打分)函数 |
| dot product / scaled dot product | 点积 / 缩放点积 |
| Transformer / Transformer layer (block) | Transformer / Transformer 层(块) |
| encoder–decoder / decoder-only / encoder-only | 编码器–解码器 / 仅解码器 / 仅编码器 |
| positional encoding / positional embedding | 位置编码 / 位置嵌入 |
| learned / sinusoidal / relative / rotary (RoPE) | 可学习的 / 正弦 / 相对 / 旋转位置编码 |
| permutation equivariance | 置换等变性 |
| length extrapolation | 长度外推 |
| multi-head attention / head | 多头注意力 / 头 |
| causal mask / masking | 因果掩码 / 掩码 |
| residual connection | 残差连接 |
| layer normalization (LayerNorm) / RMSNorm | 层归一化 / 均方根归一化 |
| pre-norm (pre-LN) / post-norm (post-LN) | 前置归一化 / 后置归一化 |
| feed-forward network (FFN) / position-wise | 前馈网络 / 逐位置的 |
| activation: ReLU / SiLU (Swish) / SwiGLU | 激活:修正线性单元 / SiLU(Swish)/ SwiGLU 门控单元 |
| gate | 门 |
| grouped-query attention (GQA) / multi-query attention (MQA) | 分组查询注意力 / 多查询注意力 |
| KV cache | 键值缓存 |
| optimizer / Adam / momentum / RMSProp | 优化器 / Adam / 动量 / RMSProp |
| bias correction / adaptive learning rate | 偏差修正 / 自适应学习率 |
| warmup | 预热 |
| parallelization / sequential | 并行化 / 串行 |
| computational complexity / quadratic | 计算复杂度 / 二次的 |
| compute efficiency / scaling curve | 计算效率 / 扩展曲线 |