B.7 Pass 5: The Transformer
This is the pass where the course reaches the architecture behind every modern language model. It builds the 2017 transformer from its parts (scaled dot-product attention, masks, multi-head attention, positional encodings) and trains it to add three-digit numbers exactly, then shows why pre-LN trains where post-LN does not. It then applies one architecture to several pretraining objectives: GPT’s next-token prediction, BERT’s masked tokens, and ELECTRA’s replaced-token detection, with LoRA fine-tuning and an evaluation harness that puts every model the course has trained on one report.
Concepts from other sections (40)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- scaled dot-product attention: , a weighted average of values with weights from query-key similarity. Read more: 11.1 Scaled dot-product attention (forward and backward)
- positional encoding: a vector depending only on position, added to the token embedding so attention can see order. Read more: 11.4 Positional encodings: sinusoidal, learned
- pre-LN: with one final LN per stack; trains without warmup. Read more: 11.5 Encoder-decoder Transformer: post-LN and pre-LN, Noam, label smoothing
- post-LN: , the paper’s placement; needs warmup. Read more: 11.5 Encoder-decoder Transformer: post-LN and pre-LN, Noam, label smoothing
- Replaced-token detection: a per-token binary task, deciding whether each token differs from the original text. Read more: 12.3 ELECTRA: replaced-token detection
- LoRA: a frozen Linear plus a trainable low-rank update . Read more: 12.6 LoRA: low-rank adaptation with PiSSA initialization and merging
- RMSNorm: divides a vector by its root mean square plus eps (inside the root) and multiplies by a learned gain; no mean subtraction, no bias. Read more: 13.1 Pre-LN and RMSNorm
- RoPE: rotary position embedding, which rotates queries and keys by position to encode relative position. Read more: 5.3 Model landscape and lifecycle
- Multi-head latent attention (MLA): attention whose keys and values are rebuilt per head from a cached low-rank latent of each token. Read more: 13.6 Multi-Head Latent Attention and Weight Absorption
- sliding window: the causal mask AND a distance bound , at most keys per query. Read more: 11.2 Masks: causal, padding, sliding window, additive
- Mixture of experts (MoE): a layer of many expert MLPs of which a router picks per token. Read more: 13.8 Mixture of Experts
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- Decoder block: two Pre-LN residual steps, attention then MLP. Read more: 13.9 The Llama-Family Model: Config, Weight Loading, and Download
- beam search: keeping the best prefixes by summed log-probability, ranking all extensions together at each step. Read more: 10.4 Beam search, generic over a step function
- Permutation test: a test that compares the observed statistic difference with its distribution over random relabelings of the pooled samples. Read more: 23.12 Run comparison and the regression gate
- IRLS: iteratively reweighted least squares, Newton’s method on the logistic loss, where each step is a weighted least-squares solve with weights . Read more: 13.8 Logistic regression (IRLS), ROC-AUC, calibration (ECE) in Mathematics
- Logistic regression: a model in which the log-odds are linear in the features. Read more: 13.8 Logistic regression (IRLS), ROC-AUC, calibration (ECE) in Mathematics
- ECE: expected calibration error, the count-weighted mean gap between accuracy and confidence over confidence bins. Read more: 13.8 Logistic regression (IRLS), ROC-AUC, calibration (ECE) in Mathematics
- additive mask: the float form, 0 where allowed and where blocked, added to scores before the softmax. Read more: 11.2 Masks: causal, padding, sliding window, additive
- Noam schedule: , linear warmup then inverse-square-root decay. Read more: 11.5 Encoder-decoder Transformer: post-LN and pre-LN, Noam, label smoothing
- label smoothing: training against instead of a one-hot target. Read more: 11.5 Encoder-decoder Transformer: post-LN and pre-LN, Noam, label smoothing
- Masked language modeling (MLM): training an encoder to recover the original tokens at corrupted positions. Read more: 12.2 BERT: the bidirectional encoder and masked language modeling
- PiSSA: initializing the adapter at the top- singular part of and freezing the residual. Read more: 12.6 LoRA: low-rank adaptation with PiSSA initialization and merging
- LayerNorm: per-row normalization by the population mean and variance with inside the square root, then an affine map. Read more: 6.5 Module system and basic layers
- SwiGLU: the gated MLP with silu on the gate (Llama, SmolLM2). Read more: 13.2 Gated MLPs: SwiGLU and GeGLU
- GeGLU: the gated MLP with the tanh-approximated GELU on the gate (Gemma). Read more: 13.2 Gated MLPs: SwiGLU and GeGLU
- interleaved layout: sin at column and cos at column , the pair layout of the paper. Read more: 11.4 Positional encodings: sinusoidal, learned
- Partial rotary: rotating only the first entries of each head. Read more: 13.3 Rotary Position Embeddings
- YaRN: a per-pair ramp between keeping and dividing frequencies, by turns over the trained context, plus a temperature . Read more: 13.4 Context Extension: PI, NTK, YaRN, Llama 3 Scaling, and ALiBi
- Multi-query attention (MQA): all query heads share one key/value head. Read more: 13.5 Grouped-Query Attention with a Cache Hook, Windows, and Sinks
- Grouped-query attention (GQA): query heads share key/value heads, each serving a contiguous group of query heads. Read more: 13.5 Grouped-Query Attention with a Cache Hook, Windows, and Sinks
- Cache hook: the
update(layer, k, v)protocol through which a KV cache receives rotated, unrepeated keys and values. Read more: 13.5 Grouped-Query Attention with a Cache Hook, Windows, and Sinks - Learned sink: a per-head extra logit in every softmax row, dropped afterwards, letting a head attend to nothing. Read more: 13.5 Grouped-Query Attention with a Cache Hook, Windows, and Sinks
- KV cache: per-layer storage of past keys and values, so each decode step processes only the new token. Read more: 21.2 The KV cache, incremental decoding, and generate
- Weight absorption: folding into the query and into the output so decoding never builds per-head keys or values. Read more: 13.6 Multi-Head Latent Attention and Weight Absorption
- Aux-free bias: DeepSeek-V3’s per-expert correction added to choice scores only, moved by a sign rule. Read more: 13.8 Mixture of Experts
- Differential test: a check that two implementations of the same contract agree on generated inputs. Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
- Gradcheck: a comparison of a hand-written gradient against central differences of . Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
- Span corruption: replacing whole spans of the input with sentinels and training the decoder to write the spans back. Read more: 12.4 T5: span corruption and relative position buckets
- Relative position bucket: an index into a learned bias table, exact for small offsets and logarithmic for large ones. Read more: 12.4 T5: span corruption and relative position buckets
The last third of the pass covers what changed between 2017 and a Llama-family model: RMSNorm, gated MLPs, RoPE and context extension, grouped-query and multi-head latent attention, sliding windows and sinks, and mixture of experts. It ends with a Llama-family model that loads SmolLM2-135M exactly as Hugging Face saves it and matches Hugging Face’s logits and greedy continuation token for token. From here on, the engine can serve real weights.
Learning objectives
- Derive scaled dot-product attention’s forward and backward passes and explain each mask and positional encoding.
- Explain why pre-LN trains without warmup where post-LN does not.
- Explain the GPT, BERT, and ELECTRA objectives and how LoRA adapts a model through under 5% of its parameters.
- Count a model’s parameters, FLOPs, and KV-cache bytes.
- Explain each component of the modern decoder block and how a published Llama checkpoint is loaded and verified.
Before you begin
Section titled “Before you begin”This pass needs Pass 4, whose attention, beam search, and sequence metrics the transformer reuses.
In this pass
Section titled “In this pass”The pass opens with the statistics used to compare models, then builds the transformer, its objectives, and the modern block:
- Definite Integrals: Trapezoid and Simpson. Afterwards you can explain the error orders of the trapezoid and Simpson rules.
- Hypothesis tests: paired and two-sample permutation, McNemar, Holm. Afterwards you can explain how paired and two-sample permutation tests, McNemar, and Holm’s correction decide significance.
- Logistic regression (IRLS), ROC-AUC, calibration (ECE). Afterwards you can explain how IRLS fits logistic regression and how ROC-AUC and ECE measure ranking and calibration.
- Probability problem set, part d: hypothesis tests, regression, queueing, balls into bins. Afterwards you can work every problem in the set and explain each answer.
- Scaled dot-product attention (forward and backward). Afterwards you can derive scaled dot-product attention’s forward and backward and explain the 1/sqrt(d) scale.
- Masks: causal, padding, sliding window, additive. Afterwards you can explain how causal, padding, and sliding-window masks combine as additive masks.
- Multi-head attention. Afterwards you can explain how multi-head attention splits, attends, and merges heads.
- Positional encodings: sinusoidal, learned. Afterwards you can explain how sinusoidal and learned positional encodings inject position.
- Encoder-decoder Transformer: post-LN and pre-LN, Noam, label smoothing. Afterwards you can explain why pre-LN trains where post-LN needs warmup, and how the Noam schedule and label smoothing are applied.
- GPT: the decoder-only language model. Afterwards you can explain the decoder-only GPT, its shifted causal LM loss, and how GPT-2 weights are mapped in.
- BERT: the bidirectional encoder and masked language modeling. Afterwards you can explain the BERT encoder and the 80/10/10 MLM masking rule.
- ELECTRA: replaced-token detection. Afterwards you can explain how ELECTRA’s generator and discriminator are trained for replaced-token detection.
- LoRA: low-rank adaptation with PiSSA initialization and merging. Afterwards you can explain how LoRA adds a low-rank update, how PiSSA initializes it from the SVD, and how it merges back.
- Fine-tuning heads and the linear-head export. Afterwards you can explain how fine-tuning heads attach to the backbone and what the linear-head export writes.
- The evaluation harness and the model zoo. Afterwards you can explain how the evaluation harness scores the models in the zoo.
- Counting: parameters, FLOPs, KV bytes, and memory plans. Afterwards you can count a model’s parameters, FLOPs, and KV-cache bytes by hand.
- Pre-LN and RMSNorm. Afterwards you can explain how RMSNorm differs from LayerNorm and why the modern block is pre-LN.
- Gated MLPs: SwiGLU and GeGLU. Afterwards you can explain how SwiGLU and GeGLU gate the MLP and how the hidden size is chosen.
- Rotary Position Embeddings. Afterwards you can explain how RoPE rotates query and key pairs in the half and interleaved layouts, and how partial rotary works.
- Context Extension: PI, NTK, YaRN, Llama 3 Scaling, and ALiBi. Afterwards you can explain how PI, NTK, YaRN, and Llama-3 scaling stretch RoPE to longer contexts.
- Grouped-Query Attention with a Cache Hook, Windows, and Sinks. Afterwards you can explain how MQA and GQA share key-value heads and how the cache hook, window, and learned sinks plug in.
- Multi-Head Latent Attention and Weight Absorption. Afterwards you can explain how multi-head latent attention compresses the KV cache and how weight absorption avoids decompressing it.
- Sliding Windows and Attention Sinks. Afterwards you can explain how a sliding window bounds attention and why StreamingLLM keeps sink tokens.
- Mixture of Experts. Afterwards you can explain how MoE routes tokens to experts, dispatches them in sorted order, and balances load with the Switch aux loss or the aux-free bias.
- The Llama-Family Model: Config, Weight Loading, and Download. Afterwards you can trace how the Llama-family model reads an HF config, loads weights, and matches Hugging Face logits.
- Oracles, golden and differential tests, gradcheck as a test. Afterwards you can explain how oracles, golden and differential tests, and gradcheck verify numerical code.
- What the System Does After Pass 5. Afterwards you can explain why pre-LN trains where post-LN does not, and how the modern decoder loads SmolLM2-135M and matches Hugging Face.
Going deeper
Section titled “Going deeper”One optional section covers the third classic pretraining objective:
- T5: span corruption and relative position buckets. Afterwards you can explain T5’s span corruption and how relative position buckets are computed.
The stages are also in this pass’s manifest, path.tsv. Pass 6 makes this model fast to run without changing a single output token.
Stages
Section titled “Stages”Generated from path.tsv.
| Stage | Read | Done when |
|---|---|---|
| 1 | Definite integrals, trapezoid, Simpson 7.4 Definite Integrals: Trapezoid and Simpson | You can explain the error orders of the trapezoid and Simpson rules (M01.4). |
| 2 | Hypothesis tests: paired and two-sample permutation, McNemar, Holm 13.6 Hypothesis tests: paired and two-sample permutation, McNemar, Holm | You can explain how paired and two-sample permutation tests, McNemar, and Holm’s correction decide significance (M07.5). |
| 3 | Logistic regression (IRLS), ROC-AUC, calibration (ECE) 13.8 Logistic regression (IRLS), ROC-AUC, calibration (ECE) | You can explain how IRLS fits logistic regression and how ROC-AUC and ECE measure ranking and calibration (M07.7). |
| 4 | Solve set: hypothesis tests, regression, queueing and Little’s law, balls into bins 13.12 Probability problem set, part d: hypothesis tests, regression, queueing, balls into bins | You can work every S-M07d problem and explain each answer. |
| 5 | Scaled dot-product attention (forward and backward) 11.1 Scaled dot-product attention (forward and backward) | You can derive scaled dot-product attention’s forward and backward and explain the 1/sqrt(d) scale (L5.1). |
| 6 | Masks: causal, padding, sliding window, additive 11.2 Masks: causal, padding, sliding window, additive | You can explain how causal, padding, and sliding-window masks combine as additive masks (L5.2). |
| 7 | Multi-head attention 11.3 Multi-head attention | You can explain how multi-head attention splits, attends, and merges heads (L5.3). |
| 8 | Positional encodings: sinusoidal, learned 11.4 Positional encodings: sinusoidal, learned | You can explain how sinusoidal and learned positional encodings inject position (L5.4). |
| 9 | Encoder-decoder Transformer: post-LN and pre-LN, Noam, label smoothing 11.5 Encoder-decoder Transformer: post-LN and pre-LN, Noam, label smoothing | You can explain why pre-LN trains where post-LN needs warmup, and how the Noam schedule and label smoothing are applied (L5.5). |
| 10 | GPT decoder-only, causal LM loss, GPT-2 weight loading 12.1 GPT: the decoder-only language model | You can explain the decoder-only GPT, its shifted causal LM loss, and how GPT-2 weights are mapped in (L6.1). |
| 11 | BERT encoder and MLM masking 12.2 BERT: the bidirectional encoder and masked language modeling | You can explain the BERT encoder and the 80/10/10 MLM masking rule (L6.2). |
| 12 | ELECTRA replaced-token detection 12.3 ELECTRA: replaced-token detection | You can explain how ELECTRA’s generator and discriminator are trained for replaced-token detection (L6.3). |
| 13 | LoRA with PiSSA init and merge 12.6 LoRA: low-rank adaptation with PiSSA initialization and merging | You can explain how LoRA adds a low-rank update, how PiSSA initializes it from the SVD, and how it merges back (L6.6). |
| 14 | Fine-tuning heads and the linear-head export 12.5 Fine-tuning heads and the linear-head export | You can explain how fine-tuning heads attach to the backbone and what the linear-head export writes (L6.5). |
| 15 | LM evaluation harness and the model zoo 12.7 The evaluation harness and the model zoo | You can explain how the evaluation harness scores the models in the zoo (L6.7). |
| 16 | Counting: params, FLOPs, KV bytes, memory plans 11.1 Counting: parameters, FLOPs, KV bytes, and memory plans | You can count a model’s parameters, FLOPs, and KV-cache bytes by hand (M05.1). |
| 17 | Pre-LN, RMSNorm 13.1 Pre-LN and RMSNorm | You can explain how RMSNorm differs from LayerNorm and why the modern block is pre-LN (L7.1). |
| 18 | Gated MLPs: SwiGLU, GeGLU 13.2 Gated MLPs: SwiGLU and GeGLU | You can explain how SwiGLU and GeGLU gate the MLP and how the hidden size is chosen (L7.2). |
| 19 | RoPE (half and interleaved layouts, partial rotary) 13.3 Rotary Position Embeddings | You can explain how RoPE rotates query and key pairs in the half and interleaved layouts, and how partial rotary works (L7.3). |
| 20 | Context extension: PI, NTK, YaRN, Llama-3 scaling; ALiBi (optional part) 13.4 Context Extension: PI, NTK, YaRN, Llama 3 Scaling, and ALiBi | You can explain how PI, NTK, YaRN, and Llama-3 scaling stretch RoPE to longer contexts (L7.4). |
| 21 | MQA/GQA attention with cache hook, window, learned sinks 13.5 Grouped-Query Attention with a Cache Hook, Windows, and Sinks | You can explain how MQA and GQA share key-value heads and how the cache hook, window, and learned sinks plug in (L7.5). |
| 22 | Multi-head latent attention (DeepSeek-V2/V3), weight absorption 13.6 Multi-Head Latent Attention and Weight Absorption | You can explain how multi-head latent attention compresses the KV cache and how weight absorption avoids decompressing it (L7.6). |
| 23 | Sliding window, StreamingLLM sinks, learned sinks 13.7 Sliding Windows and Attention Sinks | You can explain how a sliding window bounds attention and why StreamingLLM keeps sink tokens (L7.7). |
| 24 | Mixture of Experts: routing, sorted dispatch, Switch aux loss, aux-free bias 13.8 Mixture of Experts | You can explain how MoE routes tokens to experts, dispatches them in sorted order, and balances load with the Switch aux loss or the aux-free bias (L7.8). |
| 25 | Llama-family model, HF config, weight loading, downloader 13.9 The Llama-Family Model: Config, Weight Loading, and Download | You can trace how the Llama-family model reads an HF config, loads weights, and matches Hugging Face logits (L7.9). |
| 26 | Oracles, golden and differential tests, gradcheck as a test (R5) 3.3 Oracles, golden and differential tests, gradcheck as a test | You can explain how oracles, golden and differential tests, and gradcheck verify numerical code (craft.05). |
| 27 | What the system does after Pass 5 B.7.1 What the System Does After Pass 5 | You can explain why pre-LN trains where post-LN does not, and how the modern decoder loads SmolLM2-135M and matches Hugging Face. |
| 28 | T5 span corruption and relative position buckets 12.4 T5: span corruption and relative position buckets | You can explain T5’s span corruption and how relative position buckets are computed (L6.4). |