Before chapter 1
About this draft
This is a book being written while the project it describes is being built. A reader who knows Python but not machine learning follows one real project, from raw GitHub files to a small working model that writes Python code, and understands every part because every part is built by hand, measured, and broken on purpose.
How far it has got. Every part is drafted: the preface, all 26 chapters (one per stage of the 25-stage curriculum, plus the choice of domain) and three appendices. The project they describe is finished. They are first drafts: the measurements and findings are in, but some sections still read like engineering notes and will be rewritten for readers in a revision pass.
What makes it different.
- Everything is measured. Every claim comes with a number from a real run on one RTX 4060 Laptop GPU with 8 GB of memory. A change either helped by a measured amount or it did not.
- The mistakes stay in. Wrong tests, datasets that turned out to hold no data, a leak that put 40% of the exam into the textbook. Each chapter shows what went wrong and how it was caught.
- Every component gets broken on purpose. Each chapter removes the thing it just built and records the damage. That is where the understanding lands.
- Honest about scale. A 125M-parameter model will not reason or know facts. The book is about understanding the pipeline, not beating benchmarks.
Code. Every number traces to code and results in the
companion repository. Paths
like stages/04_attention/run.py in the text refer to files there.
Interactive figures for chapters 1 to 4 (the data pipeline, the tokenizer training loop, a step-by-step BPE lab) are on one page: the build map.
Preface
Why one laptop, why code
This book follows one project from an empty folder to a language model that writes Python. It ran from 14 October to 14 November 2026 on a single laptop GPU, an NVIDIA RTX 4060 with 8 GB of memory. Every component of the model was written by hand, measured, and then broken on purpose to see what it had been doing.
The model at the end is small. It has 92 million parameters and read 1.8 billion tokens of training data in about 20 hours. Given 164 standard programming problems (HumanEval), it solves 5 on its first attempt: 3.05%. That number was predicted before any training started, and the book is built around why it is the right result to aim for, not a disappointing one.
Why build it at all
There are good, free language models you can download. Building one from scratch is not the fastest way to get a working model. It is the fastest way to understand one.
Reading about attention, you learn that it "lets tokens look at each other". Building it, you find that a 4-layer model trained for about 3 minutes grows a head that puts 68% of its attention on the previous token, and two heads that park weight on the first position for no use at all (chapter 6). Reading about training, you learn that warmup "stabilises early training". Taking warmup away at a high learning rate, you find that the loss does not explode. It stalls at the level of a model that only knows how often each token appears, and after 2,000 steps it is at 4.78 where the warmed-up run reached 2.95 (chapter 10). The second kind of knowing is the one that lasts, and you only get it by doing the work.
So every chapter follows one rule: build it, check it against a reference,
then break it. The tokenizer is checked against OpenAI's tiktoken. The GPT
model loads OpenAI's real GPT-2 weights and must produce the same outputs as
Hugging Face's implementation. LoRA is checked against the peft library. Then
each piece is removed or damaged, and the damage is measured. That
measurement is where the understanding lands.
Why one laptop
The constraint is the teacher. With 7,797 MB of usable GPU memory (an "8 GB" card has less than 8 GB, chapter 1), nothing fits by default. The 92M model does not fit at the batch size it wants, so the book has to explain exactly where every byte goes, and then use gradient accumulation, mixed precision and activation checkpointing to make it fit. Each of those is a chapter's worth of understanding that a large cloud GPU lets you skip.
The constraint also keeps the book honest about scale. The arithmetic in chapter 2 says that on this hardware the largest sensible model is about 125 million parameters, and that a model this size will not know facts, will not reason over several steps, and will not follow general instructions. It will learn grammar, syntax and local structure, and learn them properly. Saying so up front means no chapter has to pretend.
Everything here was run on the one machine. The book never says "this should help". A change either helped by a measured amount or it did not, and the number is printed next to the claim.
Why Python code
The choice of what the model learns came before any data was downloaded, and it was decided by one property: can a machine check the output?
Stories, essays and translation have no automatic checker. Judging them needs a person or a much larger model acting as judge, and at 100 million parameters the differences between versions are small enough that such a judge mostly measures noise. Python has a perfect checker: run the unit tests. That one fact turns the later chapters into real experiments. Reinforcement learning (chapter 22) gets its reward from tests passing. Evaluation (chapter 24) counts problems solved. When the model gets better or worse, the number says so without anyone's opinion. About 15% of the training data is high-quality English, so comments and docstrings read like language.
The mistakes stay in
A lab journal was kept the whole way through, written the same day things happened: 116 entries, of which 18 are mistakes we made and caught and 12 are traps that would have caught anyone. The obvious Python dataset turned out to contain no Python, only file names and hashes (chapter 2). A training/test split that looked careful still had 43% of test files mostly copied into the training set, through forked repositories (chapter 4). One of our own tests was wrong: it failed on correct code, and the fix belonged in the test (chapter 3). A plot overwrote another chapter's figure.
These are in the book on purpose. They are what a reader will meet in their own work, and how each one was caught is as useful as the thing it broke.
How to read this book
Each chapter asks one question (what problem does this part solve, and what breaks without it?), shows a picture of the mechanism, explains it in plain words with small numbers, then gives the math with tensor shapes, the code, the measurement, what surprised us, what we got wrong, and what happened when we broke it.
You need to be comfortable with Python and with high-school algebra. You do not need to have trained a model before. New terms are defined where they first appear and collected in Appendix A. Every result in the book is in one table in Appendix B, and Appendix C lists the commands that rebuild all of it from a clean machine.
All the code is in the companion repository,
github.com/karanjakhar/llm-from-scratch.
Paths like stages/04_attention/run.py in the text refer to files there.
Chapter 1
What a language model actually computes
Before any code: what is the thing we are building, and what does the hardware let us build?
1. What a language model actually is
Strip away the hype. A language model is a function that takes a sequence of tokens and returns a probability distribution over which token comes next.
input: [15496, 11, 616, 1438, 318] # "Hello, my name is"
output: a vector of length vocab_size, summing to 1
→ P(next = " John") = 0.031
→ P(next = " a") = 0.027
→ P(next = " not") = 0.019
... one number for every token in the vocabulary
That is the whole contract. Everything else — chat, reasoning, code, agents — is built on top of repeatedly sampling from that distribution and feeding the result back in.
The autoregressive factorization
Why next-token prediction is enough to model any text. The probability of a whole sequence factorizes by the chain rule of probability:
P(x₁, x₂, ..., x_n) = P(x₁) · P(x₂|x₁) · P(x₃|x₁,x₂) · ... · P(x_n|x₁...x_{n-1})
= Π_t P(x_t | x_<t)
No approximation. This is exact. So a model that is good at every conditional
P(x_t | x_<t) is a complete model of the text distribution. Learning to
predict the next token is not a proxy task — it is the whole task.
Training is one trick: shift the labels
Given a sequence of T tokens, the inputs are positions 0..T-2 and the targets
are positions 1..T-1. Same array, offset by one:
tokens: [ the, cat, sat, on, the, mat ]
inputs: [ the, cat, sat, on, the ]
targets: [ cat, sat, on, the, mat ]
The model produces a prediction at every position in parallel, and we compute cross-entropy loss at every position. One forward pass gives T-1 training signals. This is why transformers train so efficiently — and the causal mask (Stage 04) is what makes it legal, by stopping position 2 from peeking at position 3's answer.
The train/inference asymmetry
This asymmetry causes most of the engineering in this repo:
| Training | Inference (decode) | |
|---|---|---|
| Sequence processing | all T positions at once | one token at a time |
| Bottleneck | compute (matmul FLOPs) | memory bandwidth |
| Needs activations stored | yes, for backward | no |
| Parallelism | across sequence + batch | across batch only |
Training is embarrassingly parallel over positions. Generation is inherently serial — token t+1 cannot start before token t exists. That single fact is why the KV cache (Stage 07), speculative decoding (Stage 15), and continuous batching (Stage 23) all exist.
2. Where the VRAM goes
8 GB is the binding constraint on this project, so this arithmetic is not optional. There are four consumers of GPU memory during training.
Let N = number of parameters, in bf16 mixed precision with AdamW (the
standard setup):
| Consumer | Bytes per parameter | Why |
|---|---|---|
| Parameters | 2 (bf16) or 4 (fp32 master) | the weights themselves |
| Gradients | 2-4 | one per parameter |
| AdamW state | 8 | two fp32 buffers: momentum + variance |
| Total, fixed | ~12-16 | independent of batch size |
Plus activations, which scale with batch size and sequence length and are the part you actually control at runtime.
Worked example: a 50M parameter model
parameters 50M × 2 bytes (bf16) = 100 MB
gradients 50M × 2 bytes = 100 MB
AdamW m,v 50M × 8 bytes (fp32) = 400 MB
fp32 master 50M × 4 bytes = 200 MB
--------
fixed cost ≈ 800 MB
800 MB out of 7797 MB usable. Comfortable. The remaining ~7 GB is activations, CUDA context (~500 MB), and fragmentation.
A rough activation estimate per layer, per sequence, is
~ s · (several × d_model + n_head · s) elements — the n_head · s² attention
matrix term is the one that explodes. With FlashAttention/SDPA that term
disappears, which is why Stage 09 matters so much on 8 GB.
The scaling reality
| Params | Fixed cost (bf16 + AdamW) | Fits in 8 GB? |
|---|---|---|
| 10M | ~160 MB | easily |
| 125M (GPT-2 small) | ~2.0 GB | yes, with modest batch |
| 350M | ~5.6 GB | tight, needs checkpointing + small batch |
| 1B | ~16 GB | no — needs LoRA or offload |
| 7B | ~112 GB | no — inference only, quantized |
Rule of thumb: full fine-tuning needs ~16 bytes/param; inference in bf16 needs ~2 bytes/param; inference in int4 needs ~0.5 bytes/param. That one line explains why a 7B model you can chat with locally cannot be trained locally.
Why this is the Stage 00 exercise
The ablation for this stage is: compute a budget that omits the AdamW states (a very common mistake — it is 8 of the ~16 bytes), predict that a model will fit, then watch it OOM. Being wrong on purpose, once, in a controlled way, is cheaper than being confused about it for months.
3. PyTorch essentials actually used in this repo
Not a tutorial — a checklist of what shows up constantly.
Shape convention. Every tensor in this project is commented with its shape. The standard names:
B— batch sizeT— time / sequence length (number of tokens)C— channels /d_model/ embedding dimensionnh— number of heads,hs— head size (C / nh)V— vocabulary size
Broadcasting. PyTorch aligns shapes from the right and stretches dims of
size 1. (B,1,T,T) + (1,nh,T,T) works and gives (B,nh,T,T). Most attention
bugs are silent broadcasting that produces the right shape with the wrong math.
This is why shape comments are mandatory.
view vs reshape vs transpose. transpose makes a tensor
non-contiguous; view then fails and you need .contiguous() or .reshape().
Multi-head attention is three of these in a row and it is where everyone's
first implementation breaks.
Autograd. Every op on a tensor with requires_grad=True records itself in a
graph. loss.backward() walks it backwards accumulating .grad. Gradients
accumulate — they are not reset — which is a bug source (zero_grad()) and a
feature (gradient accumulation, Stage 08).
@torch.no_grad() for evaluation and generation: skips graph construction,
saving memory and time.
nn.Module. Holds parameters, supports .to(device), .train()/.eval(),
state_dict(). We subclass it constantly and use almost nothing else from it.
4. Environment
cd llm-from-scratch # wherever you cloned the repo
uv sync # creates .venv from pyproject.toml
uv run python stages/00_setup/verify_env.py # checks CUDA, prints memory budget
verify_env.py prints the actual measured memory cost of a toy model and
compares it to the formula above. If the prediction and the measurement
disagree by more than ~15%, something in the mental model is wrong and that is
worth chasing before Stage 01.
5. Checklist before moving on
- [ ] Can state what a language model outputs, exactly, including the shape.
- [ ] Can explain why next-token prediction models the full joint distribution.
- [ ] Can explain the label shift and why one forward pass gives T-1 signals.
- [ ] Can name the four consumers of training memory and the bytes each costs.
- [ ] Can predict, within 15%, the fixed memory cost of an N-parameter model.
- [ ] Ran
verify_env.py; prediction matched measurement. - [ ] Know why
transposethenviewfails.
6. What we found
Measured on the RTX 4060 Laptop, 2026-10-14. Full entries in docs/JOURNAL.md.
The 16-bytes-per-parameter rule held to 8.5%. A 12.58M-parameter model in fp32 with AdamW:
| predicted | measured | |
|---|---|---|
| weights | 48.0 MB (4 B/param) | 48.0 MB |
| gradients (+ activations) | 48.0 MB | 64.3 MB |
| AdamW state | 96.0 MB (8 B/param) | 96.0 MB |
| total | 192.0 MB | 208.3 MB |
The 16 MB difference is activations held for the backward pass, which the rule leaves out on purpose. AdamW's two buffers are the largest slice. A budget that forgets them predicts 96 MB, off by more than 2×.
An "8 GB" GPU gives PyTorch 7,797 MB. About 390 MB is reserved before any tensor exists. Budget against what the runtime reports.
What that means for the project. At 16 bytes per parameter plus activations, ~125M parameters is the largest model this GPU can train comfortably. That one number sets the scale of everything that follows.
Further reading
- Karpathy, "Let's build GPT: from scratch" — the canonical video walkthrough.
- The Illustrated Transformer (Jay Alammar) — for the pictures.
- PyTorch autograd mechanics docs — read once, properly.
Chapter 2
Choosing what to teach it
A project-level decision, not a stage. It has to be made before Stage 02 (data pipeline) because it determines the corpus, and before Stage 01's final run because it determines what the tokenizer is trained on.
tinyshakespeare is a test fixture, not a training target. It is 1.1 MB — useful for asserting that code works, useless as a model.
1. The constraint, stated honestly
From the compute arithmetic (C ≈ 6ND, Chinchilla D ≈ 20N) on an RTX 4060
Laptop at a realistic 15-25% MFU:
| Params | tok/s | Chinchilla tokens | Wall-clock | Tokenized size |
|---|---|---|---|---|
| 10M | 145-240k | 0.2B | ~0.3 h | 0.4 GB |
| 30M | 48-80k | 0.6B | 2-3.5 h | 1.2 GB |
| 50M | 29-48k | 1.0B | 6-10 h | 2.0 GB |
| 125M | 12-19k | 2.5B | 36-60 h | 5.0 GB |
| 350M | 4-7k | 7.0B | 280-470 h | 14 GB |
The realistic ceiling for this project is ~125M parameters. Stage 09 measures the actual throughput and replaces these estimates.
What that buys, and what it does not
This is the part most "train your own LLM" tutorials lie about. At 125M parameters:
- No world knowledge. It will confidently invent facts. Knowledge scales terribly with parameters; 125M holds almost none.
- No multi-step reasoning. Chain-of-thought is an emergent-at-scale behaviour. It will not appear here.
- No general instruction following. It can learn one narrow task format well.
- Grammar, syntax, and local structure: genuinely good. This is what small models do learn, and learn properly.
So the only domains where the output is useful rather than cute are narrow, highly structured, and ideally machine-verifiable. That last property is worth a lot here — see §3.
2. The options
Ranked by how well they fit both the hardware and the curriculum.
Option A — Python code ★ recommended
Pretrain on Python source, SFT on docstring→function, then RL against unit tests.
Data. codeparrot/codeparrot-clean — 477k Python files, 5.0 GB of actual
source, ungated, with a per-file license column to filter on. Verified
sizes and the alternatives are in docs/datasets.md.
Two traps that cost real time if you trust the obvious choices:
HuggingFaceTB/python-edu ships metadata only (blob ids, not code), and
every bigcode/* corpus is gated. Details in docs/datasets.md.
Honest expected quality at 125M. Syntactically valid code, plausible single functions, correct short completions. HumanEval pass@1 in the low single digits — CodeParrot-small (110M) landed around 3-4%. It is a usable autocomplete for boilerplate and a bad programmer. That is a real, honest number that then improves measurably across Stages 16-21, which is the point.
Why it wins on curriculum fit — this is the decisive argument:
| Stage | What code gives it |
|---|---|
| 01 Tokenizer | Indentation, identifiers, and digit grouping genuinely matter. The regex ablation becomes consequential rather than academic. |
| 16 SFT | Natural instruction data for free: docstring → body. No annotation needed. |
| 20 GRPO / RLVR | A real verifier. Run the unit tests, reward = pass/fail. This is precisely how R1-style code RL works. Every other domain needs a learned reward model or a judge. |
| 22 Evaluation | HumanEval / MBPP pass@k are objective. No LLM-as-judge hand-waving. |
Code is the only option that makes Stage 20 a real experiment instead of a toy.
Risks. Repetitive data means it can look better than it is. Need a held-out set that is genuinely not in training — code is heavily duplicated across GitHub, so Stage 02's dedup work actually matters.
Option B — Text → SQL ★ strong, narrower, higher quality-per-param
Pretrain on a code/SQL mix, SFT on (schema + question → query).
Data. Spider, WikiSQL, BIRD, b-mc2/sql-create-context (~78k synthetic
pairs). Small datasets, so pretraining still needs a broader code corpus
underneath.
Honest expected quality. The best quality-per-parameter of any option here. Fine-tuned encoder-decoder models in the 60-220M range historically reached roughly 40-60% execution accuracy on Spider. A 50M decoder-only model, trained properly, lands in usable territory. You would have a thing you could actually point at a database.
Verifiable: execute the query, compare result sets. So Stage 20 works here too.
Downside. Very narrow. Less interesting as a pretraining exercise because the task data is small and the domain is thin — you would spend Stages 02-11 on general code anyway, then specialize. Effectively Option A with a different stage 16+.
Option C — Python code + a small English slice ★ what I would actually pick
Option A, plus ~15-20% high-quality English (HuggingFaceFW/fineweb-edu
sample) in the pretraining mix.
Data. codeparrot/codeparrot-clean for code + a streamed slice of
HuggingFaceFW/fineweb-edu sample-10BT for English. SFT pairs come free
from code-search-net/code_search_net (412k docstring/function pairs).
Eval is HumanEval + MBPP. All ungated, under 10 GB total — see
docs/datasets.md.
Why the mix. A pure-code model cannot read a docstring or an instruction — it has never seen prose. Adding a slice of English costs little and makes Stages 16-20 possible, because the model can condition on a natural-language request. Every real code model is trained this way for exactly this reason.
Cost. Slightly worse pure-code perplexity in exchange for a model that can be instructed. Worth it, and the ratio is itself a measurable Stage 10/11 ablation: train 100% code vs 85/15 and compare both code perplexity and instruction-following after SFT.
Option D — Narrow structured generation
Same shape as SQL — tiny, verifiable, genuinely works small:
- NL → shell command (tldr pages, nl2bash). Verifiable by parsing/dry-run.
- Regex generation. Verifiable by running against test strings.
- Commit message from diff. You have git history as data. Useful daily.
- SMILES / molecule generation. Small vocab, real scientific use, chemical validity is checkable with RDKit.
All are good, all are too small to pretrain on. They are Stage-16 fine-tuning targets sitting on top of Option A or C. Keep one as a side deliverable; do not make it the pretraining domain.
Option E — A low-resource language
Genuinely useful: there is no good 100M-parameter Hindi/Punjabi/Marathi model, and tokenizer fairness (Stage 01 §2) stops being an abstract point and becomes the main event.
Why I am not recommending it as the primary. Evaluation is the problem. You would need to judge fluency by reading samples, which is slow and subjective, and there is no verifier — so Stages 18-22 lose their teeth. Also needs native fluency in the target language to assess at all.
Good as a second capstone after the pipeline works, if a language you read fluently is of interest.
Option F — TinyStories
Not useful, but worth knowing why it exists: it is the proven existence result that 10-30M parameters can produce genuinely coherent text when the data distribution is narrow enough (toddler-level vocabulary, simple plots).
Use it as the Stage 08 smoke test, not the target. A 10M model trains in 20 minutes and produces readable stories — which means when your training loop is broken, you find out in 20 minutes instead of 10 hours. Keep it for that.
Option G — Domain prose: medical / legal / ArXiv
Avoid. At 125M you get fluent, domain-flavoured, confidently wrong text. The worst failure mode: output that reads authoritative in a domain where being wrong matters. No verifier, no honest eval, real potential to mislead.
3. The decisive criterion: is it verifiable?
Half this curriculum (Stages 18, 19, 20, 22) is about optimizing against a reward and measuring whether it worked. With a verifiable domain:
- Stage 20 GRPO reward = do the unit tests pass. Objective, free, no annotation, no reward model to train, no judge to debias.
- Stage 22 eval = pass@k. A number, reproducible, comparable to published results.
With an unverifiable domain (prose, stories, a language), both stages become "ask an LLM whether this is good", which at 125M is measuring noise.
This single property is why code wins, more than any argument about usefulness.
4. Decision
Option C: Python code + ~15% high-quality English. Chosen 2026-10-14.
Run as two models:
| Workhorse | Capstone | |
|---|---|---|
| Params | ~30-50M | ~125M |
| Tokens | 0.6-1.0B | 2.5B |
| Runtime | 2-10 h | 36-60 h |
| Purpose | learn every stage on it; iterate in an evening | one long run once the pipeline is proven |
Do not start with the 125M run. Every stage from 02 to 11 gets debugged on the workhorse, where a mistake costs an afternoon rather than two days. Stage 11 is where the capstone run happens, with a known-good pipeline.
Then the post-training stages have real jobs:
- 16 SFT — docstring → function
- 17 LoRA — same task, 1% of the trainable parameters, compare
- 18 Reward model — preference pairs over code completions
- 19 DPO — align toward the style you prefer
- 20 GRPO — reward = unit tests pass. The stage this whole choice is for.
- 22 Eval — HumanEval / MBPP pass@k, tracked across every checkpoint
End state: a ~125M Python code model, trained from a tokenizer you wrote, measurably improved by each post-training technique, with honest numbers at every step. Not useful as a product. A completely understood pipeline, which is the actual goal.
5. Consequences for earlier stages
Decided here, consumed later:
- Stage 01 — retrain the tokenizer on the code+English mix, not Shakespeare. Vocab 8192 may be too small for code (identifiers and indentation eat slots); measure 8192 vs 16384 on bytes/token. Consider splitting digits individually (Llama 1/2 and Qwen2 style), since generated code contains numeric literals.
- Stage 02 — dedup is now load-bearing (GitHub duplication is severe), and the train/val split must be by repository, not by file, or held-out perplexity is meaningless.
- Stage 10 — the code/English mixture ratio becomes an extra ablation axis.
Domain decision: Python code + ~15% high-quality English. See
docs/domain_choice.md for why.
Everything below was checked against the HuggingFace API on 2026-10-14.
Numbers come from datasets-server.huggingface.co, not from memory. Re-verify
before a long download; dataset repos get gated, renamed, and restructured.
The plan
| Role | Dataset | Config | Rows | Raw text | Download | Gated |
|---|---|---|---|---|---|---|
| Pretrain — code | codeparrot/codeparrot-clean |
default/train |
477,028 files | 5.0 GB | 1.8 GB parquet | no |
| Pretrain — English | HuggingFaceFW/fineweb-edu |
sample-10BT |
9,672,101 docs | 28.5 GB | streamed slice | no |
| SFT — docstring→code | code-search-net/code_search_net |
python |
412,178 pairs | 1.26 GB | small | no |
| Eval — code | openai/openai_humaneval |
openai_humaneval |
164 problems | tiny | no | |
| Eval — code | google-research-datasets/mbpp |
full / sanitized |
974 / 427 | tiny | no | |
| Smoke test | roneneldan/TinyStories |
— | ~2.1M stories | ~2 GB | no |
Total download for the full pipeline: under 10 GB, against 98 GB free. Nothing requires a token or an access request.
Token budget
5.0 GB of Python at roughly 2.8 bytes/token (our 8192 vocab; measure it in Stage 01) ≈ 1.8B tokens of code. Add ~0.3B tokens of English for the 85/15 mix ≈ 2.1B tokens total, which is Chinchilla-optimal for about 105M parameters. That lines up with the 125M ceiling from the compute table, with one caveat: hitting 2.5B tokens means ~1.2 epochs over the code. Repeating data up to ~4 epochs costs very little, so this is fine — but it is a real constraint to state rather than discover.
Traps found while verifying — read before downloading anything
HuggingFaceTB/python-edu ships no code
This is the obvious first choice (it is the Python half of the SmolLM corpus,
quality-scored, deduplicated) and it does not contain source code. First
trap: it is not its own repo — it is a config of
HuggingFaceTB/smollm-corpus. Second and worse, its schema is:
blob_id, repo_name, path, length_bytes, score, int_score
Metadata only. To get the actual code you fetch every file from Software
Heritage's S3 bucket by blob_id, which needs AWS credentials and 477k+ S3
requests. Technically possible, a bad first step for this project.
Same structure applies to fineweb-edu-dedup and cosmopedia-v2 configs —
check the schema, not the dataset card's prose.
bigcode/* is gated
bigcode/starcoderdata, bigcode/the-stack-v2, and even
bigcode/the-stack-smol all report gated: auto — they need terms accepted
and an HF token. They are better-filtered than codeparrot-clean and are the
right upgrade later, but they are not a zero-friction start.
bigcode/humanevalpack is not gated, so it is available for eval.
Licensing
codeparrot-clean carries a license column per file. Filter to permissive
licenses (apache-2.0, mit, bsd-*) in Stage 02 rather than training on
everything. Cheap to do, and it is the difference between a project you can
publish and one you cannot. The autogenerated column is also worth filtering
on — generated code is highly repetitive and inflates apparent quality.
Scale-up path, if 5 GB turns out to be the binding constraint
codeparrot/github-code-clean— ungated, multi-language, far larger. Filter tolanguage == "Python".bigcode/the-stack-v2— accept the terms, get a token. Best filtering and dedup available, and what real code models actually use.- More
fineweb-edu.sample-10BTalone holds 10B tokens; we use ~3% of it.
Reproducibility
Every download gets pinned in Stage 02's prepare.py: dataset id, config,
revision hash, and the filter predicates. "I trained on codeparrot-clean" is
not reproducible. The revision hash is.
Chapter 3
Cutting text into tokens
The model never sees text. It sees integers. The tokenizer is the layer that decides which integers, and that choice silently shapes everything downstream: vocabulary size, embedding table size, effective context length, arithmetic ability, and multilingual fairness.
It is also the one component that is not learned by gradient descent. It is trained by a separate counting algorithm, frozen, and then everything else is built on top of it. Change the tokenizer and every checkpoint you own becomes garbage.
1. The design space
We need a map from text → list of integers. Three obvious options, all of which fail, which is why BPE exists.
Option A: characters
"tokenization" → ['t','o','k','e','n','i','z','a','t','i','o','n'] # 12 tokens
- Vocab: tiny (~128 for ASCII, ~150k for all of Unicode).
- Problem: sequences get very long. Attention is O(T²), so 4x longer sequences cost 16x more attention compute. Your context window, measured in actual text, collapses.
- Problem: the model must spend its early layers rediscovering that "t-h-e" is a unit. Wasted capacity.
Option B: words
"tokenization is hard" → ['tokenization', 'is', 'hard'] # 3 tokens
- Vocab: huge (English alone has >1M word forms) and open-ended.
- Problem: any word not in the vocab becomes
<UNK>and its meaning is gone forever. Typos, names, new words, code identifiers — all destroyed. - Problem: the embedding table becomes most of the model. 1M words × 768 dims = 768M parameters of embedding alone.
- Problem: no morphology. "run", "running", "runner" are unrelated ids.
Option C: sub-words — the actual answer
Common things get one token; rare things get decomposed into pieces.
"tokenization" → ['token', 'ization'] # 2 tokens
"Jakhar" → ['Jak', 'har'] # rare name, still representable
- Vocab: controllable (8k-200k), chosen as a hyperparameter.
- No
<UNK>ever, if the base alphabet covers all bytes. - Frequent words stay single tokens, so sequences stay short.
- Morphology emerges for free from the merge statistics.
BPE is the algorithm that finds a good sub-word vocabulary automatically, from data.
2. Bytes as the foundation
Before BPE: what is the base alphabet?
If the base alphabet is "characters", Unicode has ~150,000 code points and you
cannot include them all. Any you exclude becomes <UNK>.
Instead, work on UTF-8 bytes. Every possible string encodes to a sequence of bytes, and there are exactly 256 byte values. So:
- Base vocab = 256. Fixed, small, complete.
- Zero possibility of
<UNK>. Any text, any language, any emoji, any binary garbage, round-trips exactly.
"héllo 🌍".encode("utf-8")
# b'h\xc3\xa9llo \xf0\x9f\x8c\x8d'
# → [104, 195, 169, 108, 108, 111, 32, 240, 159, 140, 141] 11 bytes, 7 chars
Note that non-ASCII characters cost multiple bytes. "é" is 2 bytes, "🌍" is 4. This is the root of why non-English text costs more tokens, and why non-English users get less effective context for the same price. A real fairness issue, visible right here at the byte layer.
GPT-2's byte↔unicode trick
A detail that confuses everyone reading GPT-2's tokenizer code. GPT-2 wanted the
vocabulary to be printable/debuggable, but bytes 0-32 and 127-160 are control
characters and whitespace that break when printed or stored in a JSON vocab
file. So GPT-2 maps those "unprintable" byte values to unused printable Unicode
code points (shifting by 256), producing the famous Ġ for a space (byte 32 →
U+0120).
It is a cosmetic encoding for the vocab file, not part of the algorithm.
Ġthe just means " the". We will implement it so GPT-2 vocab files are
readable, and clearly mark it as cosmetic.
3. BPE: the algorithm
Byte Pair Encoding was a 1994 compression algorithm, repurposed for tokenization in 2015 (Sennrich et al.) and used by GPT-2 onward.
Training. Repeat until the vocabulary reaches the target size:
- Count every adjacent pair of symbols in the corpus.
- Find the most frequent pair.
- Mint a new symbol for it. Replace every occurrence.
- Record the merge in an ordered list.
Worked example, by hand
Corpus (tiny, for clarity): "low low low lower lowest"
Start as bytes — here shown as characters since it is all ASCII. _ is a space.
l o w _ l o w _ l o w _ l o w e r _ l o w e s t
Pair counts:
(l,o): 5 (o,w): 5 (w,_): 3 (_,l): 4 (w,e): 2 (e,r): 1 ...
(l,o) and (o,w) tie at 5. Break the tie deterministically (first seen).
Merge 1: (l,o) → lo, new id 256.
lo w _ lo w _ lo w _ lo w e r _ lo w e s t
Merge 2: (lo,w) → low, count 5, new id 257.
low _ low _ low _ low e r _ low e s t
Merge 3: (low,_) → low_? count 3. Or (_,low) count 4 — pick that,
new id 258.
low _low _low _lowe r _lowe s t ... and so on
After 3 merges, "low" is a single token instead of 3. The vocabulary learned
that "low" is a unit purely from counting, with no linguistic knowledge.
Requested vocab size is an upper bound, not a promise
BPE cannot invent merges the corpus does not contain. Once every distinct pre-token chunk has collapsed into a single id, there are no adjacent pairs left and training stops early. A corpus with 30 distinct words supports only about 130 merges no matter how many times those words repeat.
Practical consequence: size the model's embedding table from the tokenizer
that actually came out, not from the vocab size you asked for. Ask for 8192
on a small corpus and you may get 3400. Hard-coding 8192 into the model config
then produces an embedding table with thousands of rows that receive no
gradient — dead parameters, and a silent bug. test_bpe.py asserts this
behaviour explicitly.
What the trained tokenizer consists of
Two artifacts, and that is all:
merges— an ordered list of pairs. Order is the whole point: it is the priority ranking used at encode time.vocab— id → bytes. Derivable from merges, but cached for decoding.
Encoding new text
Given the merge list, encode text by applying merges in training order:
tokens = list(text.encode("utf-8"))
while len(tokens) >= 2:
# find the adjacent pair with the lowest merge rank (= learned earliest)
pair = min(all_adjacent_pairs(tokens), key=lambda p: ranks.get(p, inf))
if pair not in ranks:
break # no mergeable pair left
tokens = merge(tokens, pair, ranks[pair])
Lowest rank first is not an arbitrary choice. It reproduces exactly the state the training corpus was in, so encoding is consistent with training. Applying merges greedily in a different order gives a different (worse, inconsistent) tokenization.
Naive cost is O(n² ) per chunk in the worst case. Real implementations
(tiktoken in Rust, tokenizers in Rust) use a linked list with a priority
queue. We write the slow clear version first, measure it, then optimize — the
speed difference is itself a lesson about why these libraries are not in Python.
Decoding
Trivial: look up each id's bytes, concatenate, .decode("utf-8").
One trap: a single token's bytes may be an incomplete UTF-8 sequence (half
of an emoji). Decoding one token at a time therefore crashes or produces
replacement characters. This is why streaming generation must buffer bytes
until they form valid UTF-8, and why errors="replace" appears in every
decoder. Stage 07 hits this for real.
4. Regex pre-tokenization — the non-obvious part
Run naive BPE on raw text and you get merges like " the", "the.",
" the ", "dog." — tokens that span word and punctuation boundaries.
This wastes vocabulary on near-duplicates and makes the tokenization of a word
depend on its punctuation context.
GPT-2's fix: split text into chunks with a regex first, run BPE independently inside each chunk, and never allow a merge to cross a chunk boundary.
GPT-2's pattern:
's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
Read it piece by piece:
's|'t|'re|'ve|'m|'ll|'d— English contractions get their own tokens.?\p{L}+— an optional leading space plus letters. This is why GPT tokens start with a space:" the"is one token, and leading-space-attached is the canonical form.?\p{N}+— optional space plus digits.?[^\s\p{L}\p{N}]+— optional space plus punctuation, grouped.\s+(?!\S)— trailing whitespace, and\s+— any other whitespace run.
Note \p{N}+ groups all consecutive digits into one chunk, so GPT-2 can
produce a single token for "2024" and a different one for "202". This is
precisely why early LLMs were bad at arithmetic: the digit "5" has a different
id depending on which numbers it appeared inside during training. GPT-4's
pattern, which Llama 3 also uses, caps digit runs at 3 (\p{N}{1,3}). Llama 1
and 2 (SentencePiece with split_digits) and Qwen2 go further and split
every digit separately, which makes digit tokens consistent and is reported
to help arithmetic. A regex choice changes the model's math ability. That is
how deep tokenizer effects run.
The ablation for this stage is to train BPE with and without the regex and inspect the merge lists side by side.
5. Special tokens
Tokens that are not learned from text but injected for control:
| Token | Purpose | Stage |
|---|---|---|
| `< | endoftext | >` |
| `< | pad | >` |
| `< | im_start | >, < |
Two rules, both learned the hard way by the field:
- Reserve ids for tokens you do not need yet. Adding a token later means resizing the embedding table and invalidating checkpoints. Leave a gap.
- Special tokens must never be producible from user text. If a user can
type the literal string
<|im_end|>and have it tokenize to the control token, they can forge a conversation turn. The encoder must have a mode that treats specials as plain text. This is a real prompt-injection surface.
6. Quality metric: compression ratio
How do you know a tokenizer is good? Measure bytes per token on held-out text of the kind you care about:
compression = total_bytes / total_tokens
Higher is better: more text per token means more content in the same context window and fewer FLOPs per character. Reference points:
| Tokenizer | Vocab | ~bytes/token on English |
|---|---|---|
| raw bytes | 256 | 1.0 |
| GPT-2 | 50,257 | ~4.0 |
GPT-4 (cl100k_base) |
100,277 | ~4.4 |
| Llama 3 | 128,256 | ~4.3 |
Returns diminish: doubling the vocab from 50k to 100k buys ~10% compression while adding 50k × d_model embedding parameters. The tradeoff:
- Bigger vocab → shorter sequences (cheaper attention), bigger embedding and output layers, rarer tokens get less training signal each.
- Smaller vocab → longer sequences (costlier attention), compact model, every token well-trained.
Our choice: 8192. At 10-50M parameters, a 50k vocab would make the
embedding table larger than the whole transformer. 8192 × 384 dims ≈ 3.1M
params, which is reasonable. Recorded in CLAUDE.md → Decisions.
7. Why tokenizers cause famous LLM failures
Not trivia — each one is diagnostic of what the model can and cannot see.
"How many r's in strawberry?" The model sees ['str','aw','berry']. It
never sees letters. Asking it to count characters is asking it to count
something that was destroyed before layer 1. The surprise is that it often
gets it right at all, having memorized spellings from text about spelling.
Reversing a string — same cause. Character-level operations on a sub-word-level representation.
Arithmetic — inconsistent digit grouping, as in §4.
Non-English cost — more bytes per character, so more tokens per sentence, so less context and higher price for the same content.
Trailing whitespace weirdness — "Hello" vs "Hello " tokenize
differently, and since tokens carry leading spaces, a trailing space puts the
model in a state it rarely saw in training. This is why API docs warn against
trailing spaces in prompts.
SolidGoldMagikarp — glitch tokens. Strings frequent enough in the tokenizer's training corpus to earn a token, but near-absent from the LM's training corpus. Their embeddings stayed near initialization, so the model behaves erratically when it meets them. A direct consequence of training the tokenizer and the model on different data.
8. Build order for this stage
bpe.py—train(),encode(),decode()in pure Python, no regex. Get round-tripping exact first.- Add regex pre-tokenization. Diff the merge lists against step 1. This is the ablation.
- Add special-token handling, with the "treat as plain text" safe mode.
- Save/load the tokenizer to JSON.
- Train on a real corpus at vocab 8192. Measure bytes/token on held-out text.
- Compare compression and speed against
tiktokengpt2. Explain both gaps. - Promote the clean version to
llmfs/tokenizer/.
Acceptance criteria
- [ ]
decode(encode(s)) == sfor 1000 random held-out strings, including emoji, CJK, and control characters. - [ ] Never emits
<UNK>; vocab covers all 256 bytes. - [ ] Encoding is deterministic and rank-ordered (verify a known case by hand).
- [ ] Compression ratio measured and recorded in
PROGRESS.md. - [ ] Merge list with regex vs without compared, with the difference explained.
- [ ] Specials cannot be forged from user text in safe mode (test asserts it).
9. The production tokenizer — measured on the real corpus
Trained by stages/01_tokenizer/train_production.py on 36 MB of permissive
Python + fineweb-edu English (train split only), then measured on held-out code
and English from validation repositories the tokenizer never saw. Every
variant used GPT-2's pattern with only the digit rule changed. Each was trained
once to 16,384, with smaller vocabs read off as merge prefixes (~1 h per
variant, 3 in parallel).
Held-out bytes per token (higher = more text per token):
| digit rule | vocab | code | English |
|---|---|---|---|
grouped \p{N}+ (GPT-2) |
2,048 | 2.762 | 2.567 |
| 4,096 | 3.099 | 2.942 | |
| 8,192 | 3.381 | 3.369 | |
| 16,384 | 3.586 | 3.796 | |
cap3 \p{N}{1,3} (GPT-4, Llama 3) |
8,192 | 3.376 | 3.365 |
| 16,384 | 3.580 | 3.789 | |
split \p{N} (Llama 1/2, Qwen2) |
8,192 | 3.337 | 3.327 |
| 16,384 | 3.529 | 3.734 | |
| GPT-2's tokenizer | 50,257 | 2.222 | 4.570 |
GPT-4's cl100k_base |
100,277 | 4.244 | 4.688 |
What the table says
Our 8k tokenizer beats GPT-2's 50k tokenizer on code by 52%. GPT-2 was trained on web text and never learned merges for runs of spaces, so every space of Python indentation costs it a whole token. Vocabulary size is not the main thing here. The training distribution is. This is the reason Codex added dedicated whitespace tokens. On English, GPT-2 still wins easily, as it should with 6× the vocab trained on English.
Vocab returns diminish fast. Each doubling buys less on code: +12.2% (2k→4k), +9.1% (4k→8k), +6.1% (8k→16k).
The digit rule is nearly free. Splitting every digit costs 1.3% on code versus grouping; capping at 3 costs 0.15%.
Decision: split_8192
- Vocab 8,192. Going to 16,384 buys 6.1% on code at the cost of 4.2M more embedding parameters (d=512), about 17% of a 50M workhorse once the table is tied to the output head. Both models must share one tokenizer, and the workhorse is where every stage gets debugged.
- Split digits. It costs 1.3% compression, and in exchange every digit
always has the same id.
range(100)becomesrange,(,1,0,0, so the model sees the 1 and the 0s as the same tokens wherever they appear. For a small model that has to learn what numeric literals mean, consistency is worth more than 1.3%. - Cheap to reverse. Switching tokenizers means re-running
stages/02_data/prepare.py(minutes), not retraining anything. Any model trained before a switch is invalidated, though. Revisit only with evidence, e.g. a Stage 10 ablation.
Final layout: ids 0-255 bytes, 256-8191 merges, 8192 <|endoftext|>,
8193 <|pad|>, 8194 <|im_start|>, 8195 <|im_end|> → 8,196 embedding rows.
Speed
The fast cached encoder in llmfs/tokenizer runs at 8.1 MB/s on one core
vs 0.66 MB/s for the stage-01 encoder (12×), with a 98.2% chunk-cache hit
rate starting cold, and produces identical ids (tested on real GitHub files).
10. What we found while building it
Things the theory above does not tell you, found by building and testing.
Dated entries with full detail in docs/JOURNAL.md.
| Finding | Kind | Number |
|---|---|---|
| A requested vocab size is an upper bound: BPE stops when no pairs remain | mistake (test assumed otherwise) | stopped at 127 of 256 merges on a repetitive corpus |
| All-whitespace tokens legitimately contain inner spaces; our first "no boundary-spanning tokens" test was wrong | mistake | — |
| Counting each unique chunk once, weighted by frequency, gives identical merges far faster | result | test suite 8.8 s → 3.25 s; 20 MB of Python = 4.9M chunks, 110k unique |
| Merge lists are prefixes: the first k merges of a long run are the k-merge tokenizer | result | one 16k run gives 2k/4k/8k/16k |
| Pure Python is much slower than tiktoken | result | 0.53 vs 14.4 MB/s (27×) |
| A chunk cache recovers most of it | result | 8.14 vs 0.66 MB/s (12×), 98.2% hits |
| A tokenizer trained on English charges other languages more | surprise | 你好 = 6 raw-byte tokens on the Shakespeare tokenizer |
| GPT-2's 50k tokenizer is worse at Python than our 8k one | surprise | 2.222 vs 3.381 bytes/token (indentation) |
| Llama 3 does not split digits (an earlier draft of §4 said it did) | mistake (corrected) | uses \p{N}{1,3} |
| Saved tokenizers lacked special tokens until an assert in Stage 02 caught it | mistake | — |
The habit this chapter teaches: test the claim, then the code. Two of the three test failures here were wrong tests, not wrong code.
Further reading
- Sennrich et al. 2015, "Neural Machine Translation of Rare Words with Subword Units" — the original BPE-for-NLP paper.
- Karpathy,
minbpe— the reference minimal implementation. Read after writing your own. tiktokensource — see what the production version does differently.
Chapter 4
The data is most of the model
At 125M parameters, the data is most of the model. Architecture tweaks move loss by a few percent. Data choices move it by a lot more. This stage turns ~3 GB of compressed GitHub JSON and one fineweb-edu parquet file into flat binary token arrays that the training loop can sample from without ever starving the GPU.
What this stage builds, in order:
download (pinned revisions)
→ stream documents
→ filter (license)
→ split train/val by REPOSITORY hash
→ tokenize in parallel, append <|endoftext|> after each document
→ write uint16 memmaps: train_code.bin train_en.bin val_code.bin val_en.bin
→ manifest.json (everything needed to reproduce the bins exactly)
then
→ a batch sampler that mixes code/English at a runtime ratio
1. Why data quality dominates
The canonical evidence is about code specifically:
| Model | Params | Training data | HumanEval pass@1 |
|---|---|---|---|
| CodeParrot | 1.5B | ~raw GitHub Python | ~4% |
| phi-1 | 1.3B | ~7B tokens, heavily filtered "textbook-quality" code + synthetic exercises | ~50% |
Same parameter count, more than a 10x gap, and the difference is almost entirely data selection. A small model has no spare capacity to spend memorizing boilerplate, license headers, and auto-generated tables. Every token of junk is a token of capacity not spent on code structure.
We are closer to the CodeParrot end of that table, on purpose, and that
should be said plainly. codeparrot-clean has light heuristic filtering. The
quality-scored alternative (python-edu) ships metadata only and needs ~500k
S3 fetches (see docs/datasets.md). Getting the pipeline right on accessible
data first, and treating better-filtered data as a later, measurable upgrade,
is the deliberate tradeoff.
2. What is actually in the corpus — measured, not assumed
Profile of shard 1 of codeparrot/codeparrot-clean (revision 35a59fb):
rows 100,000 files
text 1.02 GB uncompressed (4.1x gzip ratio)
file size median 4.6 KB, mean 10.2 KB, max 948 KB
distinct repos 47,232 files/repo: median 1, max 110
autogenerated False for all 100,000
line_max ≤ 999 for all (p50 89, p99 354)
alpha_frac ≥ 0.25 for all (p1 0.43, p50 0.61)
Extrapolated: 54 shards ≈ 5.4M files, ~53 GB of Python.
Three of those numbers changed the plan.
Upstream filtering already happened. CodeParrot's cleaning removed
auto-generated files, files with very long lines (line_max ≥ 1000, usually
minified or data blobs), and files with low alphabetic fraction (alpha_frac ≤ 0.25, usually embedded data or base64). Re-applying those filters would be a
no-op, so we do not. The lesson generalizes: profile before filtering.
Filters copied from a blog post onto data that was already cleaned do nothing,
and filters copied onto data with a different distribution do damage.
Repos are scattered across shards. 47k repos in 100k files means files from one repository land in many shards. A train/val split by shard would therefore leak whole repositories into both sides. §5 deals with this.
Licenses split ~58/42. By bytes:
| License | Share | Kind |
|---|---|---|
| apache-2.0 | 23.1% | permissive |
| gpl-3.0 | 18.2% | copyleft |
| mit | 16.4% | permissive |
| bsd-3-clause | 16.0% | permissive |
| gpl-2.0 | 11.6% | copyleft |
| agpl-3.0 | 8.1% | copyleft |
| lgpl / mpl / epl | ~5.4% | weak copyleft |
| bsd-2 / unlicense / isc / cc0 | ~2.2% | permissive |
3. Filtering: license
We keep permissive licenses only — apache-2.0, mit, bsd-2/3-clause, unlicense, isc, cc0-1.0. That is 57.7% of bytes.
Whether training on copyleft code creates obligations for the model is a genuinely unsettled legal question. Permissive-only is the conservative choice, it is what makes the trained weights publishable without an asterisk, and at ~53 GB available against ~6 GB needed, it costs us nothing we would have used.
What breaks without it: nothing technical. The model is not worse. This is a filter for the project's integrity, not its loss curve, and it is worth knowing which kind of filter you are writing.
4. Deduplication
Why duplicates hurt more than they seem to
GitHub is full of copies: forks, vendored libraries, copy-pasted utilities,
setup.py templates, Django migrations. A file that appears 50 times gets 50x
the gradient weight of a file that appears once, and the model memorizes it.
At small scale that is capacity wasted on recall. Worse, duplicates that
straddle the train/val split make validation loss measure memorization
instead of generalization.
Exact dedup — upstream did it, we verify it
Exact duplicates are cheap to find: hash the content, keep the first copy.
CodeParrot did this across the full dataset (the hash column; copies says
how many copies existed before). We re-hash with our own function across every
shard we use and report the duplicate rate, because "the dataset card says it
is deduplicated" is a claim, and claims get checked.
Near-duplicate dedup — built, because the leakage number said so
A fork that renamed one variable has a different hash. Exact dedup misses it.
The standard tool is MinHash + LSH (llmfs/data/dedup.py):
- Shingles. Represent each file as the set of its word 5-grams, where a
"word" is a
\w+run. Ignoring whitespace and punctuation means a fork run through a formatter still matches its original. - Jaccard similarity
|A ∩ B| / |A ∪ B|between two shingle sets measures overlap, from 0 to 1. - MinHash. Apply P = 120 independent hash functions to every shingle and
keep the minimum for each. For any single function,
P(min_A == min_B) = Jaccard(A, B)exactly, so the fraction of the 120 positions that agree is an unbiased estimate of Jaccard, with standard deviation at mostsqrt(0.25/120) ≈ 0.046. - LSH banding. Cut the 120 values into 20 bands of 6. Two files become
candidates if any band matches exactly. The probability of that is
1 - (1 - J^6)^20, an S-curve: ~27% at J = 0.5, ~92% at J = 0.7, ~100% at J = 0.9. Each file is compared with a handful of candidates instead of all 700k others, which avoids the O(n²) blowup. - Verify each candidate pair by its estimated Jaccard ≥ 0.7, union-find the matches into clusters, and keep one file per cluster.
Which copy survives matters. When a cluster spans train and val, the train copy is kept and every val copy is dropped. Dropping the train copy instead would leave the val file in place with its near-twin gone from train. That looks equivalent, but it keeps a val set chosen by "which repos happened to be forked", so the train copy wins.
Two implementation details that silently break this if missed:
- No
hash(). Python's built-inhashis salted per process. Signatures are computed in 18 worker processes, so withhashevery worker's signatures would be incomparable with every other's and nothing would ever match. The module useszlib.crc32and a multiply-add-shift hash family; a test computes signatures in spawned processes and asserts they are identical. - Jaccard is over sets. A shingle repeated 40 times counts once; the
np.uniqueis part of the definition, not an optimization.
What it found (12 shards, 729,865 permissive files, 149 s)
| near-duplicate train files dropped | 205,241 / 726,664 (28.2%) |
| val files dropped | 1,264 / 3,201 (39.5%) |
| …of which had a near-copy in train | 1,258 |
| clusters containing duplicates | 87,331 |
More than a quarter of "deduplicated" GitHub Python is near-duplicate, and almost every dropped val file was a near-copy of something in train. Without this step, ~40% of the code validation set would have been memorization tests.
5. The train/val split — by repository, by hash
Why "by file" is wrong for code
Files in the same repository share imports, helper functions, naming
conventions, license headers, and sometimes whole copied blocks. If
utils.py from repo X is in train and helpers.py from repo X is in val, the
model is graded on text it has effectively seen. Validation loss comes out
optimistic, and the gap between validation loss and real-world quality is
exactly what validation exists to measure.
The fix: assign whole repositories to one side.
Why by hash, not by random draw
def split_of(repo_name: str) -> str:
h = int.from_bytes(hashlib.blake2b(repo_name.encode(), digest_size=8).digest())
return "val" if (h % 10_000) < VAL_PER_10K else "train"
- Deterministic. Same repo, same side, every run, on every machine. No random state to save or forget.
- Streamable. The decision needs one record, not a global shuffle of 5M files. Shard order does not matter, which is required because repos are scattered across shards (§2).
- Stable under growth. Add 10 more shards later and every existing repo stays on the side it was already on. A random split would reshuffle and silently put old val repos into train.
For English documents (no repo), the same function hashes the document id.
Val sizing
0.5% of repositories go to val. Validation loss needs only ~10M tokens to be stable to two decimal places, and every val token is a token not trained on.
The ablation for this stage: what do the split and the dedup each buy?
Measured in run.py leakage, without training anything. For every val file,
take each non-trivial line (stripped, ≥ 20 chars) and check whether it appears
verbatim anywhere in train. Two views of that number:
- All lines. Inflated by boilerplate (license headers, common imports) that is in train under any split. That makes it a ceiling, not a clean signal.
- Rare lines: lines found in ≤ 5 files across the whole corpus. Those are not boilerplate. A rare line on both sides of the split is a copy.
Results on shards 1-2 (~119k permissive files):
| split | near-dedup | val lines in train | rare lines in train | val files >50% leaked |
|---|---|---|---|---|
| file-level | no | 56.3% | 43.9% | 48.6% |
| repo-level | no | 47.6% | 34.4% | 43.3% |
| file-level | yes | 29.6% | 21.7% | 27.4% |
| repo-level | yes | 15.1% | 8.1% | 13.8% |
What the table shows:
- The repo split alone was not enough. Before near-dedup, 43% of val files had most of their lines in train, mostly through forks under other repo names, which a repo split cannot see.
- Near-dedup alone is not enough either. With dedup but a file-level split, rare-line leakage is still 21.7%. Same-repo files share helpers and copied blocks that are not near-duplicates as whole files.
- They are complementary. The file-vs-repo gap grows after dedup (+9.5 → +13.6 rare-line points). Once cross-repo copies are gone, within-repo sharing is the main leak, and only the repo split catches it.
- The residual 8.1% is real and known. These are probably partial copies, e.g. one vendored function inside an otherwise original file, which whole-file Jaccard cannot detect. Closing it would need line- or function-level dedup. We note it rather than chase it: val loss will be slightly optimistic, and Stage 22's HumanEval/MBPP numbers do not depend on this split at all.
The curriculum originally listed "document-level vs token-level shuffling" as this stage's ablation. That needs a training loop to observe, so it moves to Stage 08. The leakage ablation measures something real now.
6. Tokenize once, store as uint16
Tokenizing on the fly during training wastes CPU every epoch and, with a pure-Python tokenizer, would starve the GPU outright. So tokenize everything once and store the ids on disk.
Why uint16: our vocab is 8192 + 4 specials, well under the 65,535 a
uint16 can hold. That is 2 bytes per token instead of 8 for int64:
2.5B tokens × 2 bytes = 5 GB (uint16)
2.5B tokens × 8 bytes = 20 GB (int64 — PyTorch's default index dtype)
The cast to int64 happens per batch on the fly, a few KB at a time.
Why np.memmap: the file is mapped into the address space and the OS pages
it in on demand. A 5 GB array costs essentially no RAM until touched, and
repeated reads hit the OS page cache. No custom loader, no sharding logic.
Parallelism: documents are tokenized in a multiprocessing.Pool with
imap (ordered), so the output is byte-identical regardless of worker count.
Each worker loads the tokenizer once and keeps its own chunk-encoding cache
(§8).
7. Packing: concatenate, separate with <|endoftext|>
Documents vary from 100 bytes to 900 KB. The model sees fixed windows of
T tokens. Two ways to bridge that:
Padding: one document per row, pad to T. With median file ~1.5k tokens
and T = 1024, short files waste most of the row and long files get truncated.
Measured waste on real corpora is commonly 30-60% of compute.
Packing: concatenate every document into one flat stream with an
<|endoftext|> token after each, and cut windows from the stream anywhere.
Zero padding, zero waste.
... def foo():\n return 1\n<|endoftext|>import os\nfrom pathlib ...
^ document boundary
The cost of packing: a window can straddle a boundary, so the model attends
from tokens of document B back into the end of document A. It learns that
<|endoftext|> means "what came before is irrelevant", and at pretraining
scale the measured harm is small, which is why GPT-2 and GPT-3 did exactly
this. The fix when it matters is document masking: a block-diagonal
attention mask so attention cannot cross a boundary. Long-context training and
SFT packing (Stage 16) use it. Here it is not worth the complexity.
8. Making our tokenizer fast enough
Stage 01's encoder runs at 0.53 MB/s. The corpus is ~7.5 GB:
7.5 GB / 0.53 MB/s ≈ 4 hours, on one core
Two changes, both in llmfs/tokenizer/:
- Chunk cache. Pre-tokenized chunks follow a Zipf distribution. In 20 MB of
real Python there are 4.9M chunks but only 110k unique ones:
" "," self"," ="," return"repeat endlessly. Cachechunk → idsand the expensive merge loop runs only on chunks never seen before. - Processes. 20 CPU threads available, tokenization is embarrassingly parallel across documents.
The output must be identical to Stage 01's encoder. A test asserts it, on real files. A faster tokenizer that produces different ids is a different tokenizer.
9. Mixing code and English at runtime, not at write time
We write code and English into separate binaries and mix them in the sampler:
source = "code" if rng.random() < 0.85 else "en"
Baking the 85/15 mix into one file would mean re-tokenizing the corpus to try 100/0 or 70/30. Stage 10 runs exactly that ablation. With separate files it is a command-line flag.
Mixing is per sequence, by token count: each training window is 100% one source. 85% of windows are code, so 85% of training tokens are code.
Separate val files too — val_code.bin and val_en.bin — because a single
mixed val loss hides the tradeoff Stage 10 is trying to see: more English may
cost code loss while buying instruction-following.
10. Sampling windows from the stream
The simple sampler: random offsets
ix = torch.randint(len(data) - T - 1, (B,))
x = stack([data[i : i+T ] for i in ix]) # (B, T) inputs
y = stack([data[i+1 : i+T+1] for i in ix]) # (B, T) targets, shifted by one
Valid because every offset is an equally good place to start predicting. No epoch bookkeeping, trivially resumable. nanoGPT does exactly this.
Why it is wrong for us specifically: coverage
With replacement, a given token is missed by every one of S windows with
probability (1 - T/N)^S ≈ e^(-S·T/N) = e^(-epochs). After one epoch's worth
of samples:
never seen: e^-1 ≈ 37%
seen once: e^-1 ≈ 37%
seen twice+: 1 - 2e^-1 ≈ 26%
37% of the data is never trained on in the first epoch. When data is
plentiful that is irrelevant. We have ~2.1B tokens for a model that wants
~2.5B, so ~1.2 epochs (see docs/datasets.md), and wasting a third of the data
while double-counting a quarter is a real cost.
The sampler we use: shuffled non-overlapping windows
Cut the stream into ⌊(N-1)/T⌋ non-overlapping windows, shuffle their order
once per epoch with a seeded permutation, and walk it. Every token is seen
exactly once per epoch. Resuming needs (epoch, position), two integers.
Both samplers are implemented. A test checks the coverage property: one epoch of the shuffled sampler covers 100% of windows exactly once, and one epoch's worth of random sampling covers ~63%.
11. Not starving the GPU
The workhorse model needs ~30-80k tokens/s (Stage 00 compute table). The loader has to beat that comfortably, or every optimization in Stage 09 is wasted waiting on data.
A batch from a memmap is a few hundred KB of contiguous reads, an int64 cast,
then a host-to-device copy. Two details matter:
- Pinned memory (
.pin_memory()) lets the copy use DMA, and non_blocking=Truelets that copy overlap with GPU compute instead of stalling the Python thread.
run.py measures loader throughput in tokens/s with and without these, against
the model's requirement. If the loader is 100x faster than needed, a
multi-worker DataLoader is unnecessary complexity, and we will not add one.
12. Reproducibility: the manifest
"Trained on codeparrot-clean" does not reproduce anything. manifest.json
records:
- dataset ids and revision hashes, and exactly which shard files
- filter predicates (license allowlist) and the val fraction
- the tokenizer file and its SHA-256
- per-binary token counts and document counts
- the exact-duplicate rate found
With the manifest and the same code, the binaries reproduce byte for byte.
13. Build order
download.py— fetch pinned shards + one fineweb-edu parquet.llmfs/data/corpus.py— stream documents, license filter, repo-hash split.- Production tokenizer (Stage 01 domain work,
stages/01_tokenizer/train_production.py) — train on a train-split-only sample; compare vocab 8192 vs 16384, digits grouped vs split; pick one. llmfs/tokenizer/— fast cached encoder, proven identical to Stage 01.prepare.py— parallel tokenize → four.binfiles +manifest.json.llmfs/data/loader.py— random and shuffled samplers, code/English mixing.run.py— leakage ablation, dedup rate, loader throughput.
Acceptance criteria — results on the real corpus (2026-10-25)
- [x] No repository appears in both train and val: guaranteed by construction
(
split_ofhashesrepo_name) and asserted intest_data.py. - [x] Every document ends with exactly one
<|endoftext|>: EOT count equals document count in all four bins (521,423 / 720,855 / 1,937 / 3,656), and every bin ends in EOT. - [x]
decode(bin)reproduces source exactly: first 200 documents oftrain_code,val_codeandval_enbyte-identical. The firstval_enattempt "failed" at document 174, which turned out to be a verbatim copy of atrain_enarticle that the shared deduper had correctly removed. The check was wrong, not the bin. - [x] Fast tokenizer identical to Stage 01 on real files (test, now unskipped).
- [~] Reproducible bins: worker-count invariance is tested at small scale and
the document stream is deterministic by construction. A full second
prepare.pyrun comparing SHA-256s has not been done. - [x] Shuffled sampler covers every window exactly once per epoch (test).
- [x] Loader throughput ≥ 10× the requirement: 56-140M tokens/s, i.e.
700-1,750× the workhorse's ~80k tok/s. The CPU-only row ran first
against a colder page cache, so the rows are not cleanly comparable with
each other, but all clear the bar by two orders of magnitude. No
multi-worker
DataLoaderneeded. - [x] Leakage measured and logged (§5).
What came out
| bin | documents | tokens | bytes/token | near-dups dropped | exact dups dropped |
|---|---|---|---|---|---|
train_code |
521,423 | 1,330.1M | 3.267 | 205,241 | 0 |
train_en |
720,855 | 1,016.9M | 3.390 | — | 1,476 |
val_code |
1,937 | 4.9M | 3.214 | 1,264 | 0 |
val_en |
3,656 | 5.2M | 3.379 | — | 13 |
| total | 2,357M | 4.4 GB on disk |
Tokenization took ~4.5 minutes at ~36 MB/s across 18 workers, about 4× below the workers' combined capacity. The suspected bottleneck is the single main process reading and JSON-parsing the gzipped shards; it has not been profiled.
Token budget
- Workhorse (~50M params, ~1B tokens at 85/15): needs ~0.85B code tokens. We have 1.33B. Covered with room to spare.
- Capstone (~125M params, ~2.5B tokens at 85/15): needs ~2.1B code tokens.
We have 1.33B, which would mean ~1.6 epochs. Before Stage 11, download ~8 more
shards (~110M code tokens each after dedup; the dedup rate will rise as the
corpus grows), re-run
dedup.pyover all of them, and re-runprepare.py. Not needed until then.
14. What we found
The full story is spread through §2-§5 and the acceptance results above. In one
place, with the dated detail in docs/JOURNAL.md:
| Finding | Kind | Number |
|---|---|---|
| The reported dataset size was a partial conversion | mistake (corrected) | 477k files / 5 GB reported; real: 54 shards, 12.8 GB gz, ~5.4M files |
| Upstream had already applied the filters we planned | surprise | autogenerated False in 100,000 / 100,000 files |
| Repositories are scattered across shards | surprise | 47,232 repos in 100,000 files |
| Permissive licenses are a bit over half the bytes | result | 57.7% |
| A repo-level split alone leaves heavy leakage | surprise | 34.4% of rare val lines in train; 43.3% of val files mostly copied |
| Near-dedup removes over a quarter of the training code | result | 28.2% of train, 39.5% of val, in 149 s |
| Near-dedup and the repo split catch different leaks | surprise | file-vs-repo gap grew +9.5 → +13.6 pts after dedup |
| Leakage after both defenses | result | 8.1% rare lines (residual: partial copies, believed) |
Python's hash() would have silently broken cross-process dedup |
trap (prevented) | — |
fork() after importing torch risks deadlock |
trap | switched pools to spawn |
| fineweb-edu contains exact duplicate articles | surprise | 1,476 train, 13 val |
| A failed decode check turned out to be a correct dedup | mistake (in the check) | doc 174 of val_en |
| The corpus | result | 2.36B tokens, 4.4 GB, ~4.5 min |
| The loader is far faster than the model needs | result | 56-140M tokens/s vs ~80k needed |
The habit this chapter teaches: profile the data, then measure the thing you care about (here, leakage) directly. Every major decision in this stage came from a measurement, and two of them reversed the plan.
Chapter 5
Turning ids into vectors and position
The tokenizer from Stage 01 turns text into a list of integers, like
[1017, 279, 8192, ...]. A neural network cannot do much with those numbers as
they are. Token 1017 is not "bigger" than token 279 in any meaningful way. The
numbers are only names. This stage answers two questions:
- How does a name become something a network can compute with? We swap each id for a learned vector (an embedding).
- How does the model know what order the tokens came in? Attention, the core of the transformer, has no idea of order. We look at three ways to add it: learned positions (GPT-2), sinusoids (the original 2017 transformer), and rotations (RoPE, used by Llama and almost every modern model).
text ──tokenizer──▶ ids (B, T) ──embedding──▶ vectors (B, T, C) ──+ position──▶ transformer
[1017, 279, ...] one row per token which slot is this?
B = batch size, T = sequence length (tokens per row), C = model width
(numbers per token vector). These letters are used on every tensor line in the
code.
1. From ids to vectors: the lookup table
The picture
An embedding is a table with one row per token in the vocabulary. To embed token 3, you read row 3. That is all it does when the model runs.
C = 4 numbers per token
┌──────────────────────────┐
id 0 │ 0.12 -0.40 0.03 0.88 │
id 1 │-0.71 0.05 0.62 -0.10 │
id 2 │ 0.33 0.91 -0.27 0.04 │
id 3 ──▶ │-0.05 -0.66 0.48 0.19 │ ──▶ vector for token 3
... │ ... │
id 8195 │ 0.21 -0.13 -0.94 0.50 │
└──────────────────────────┘
V = 8,196 rows (our tokenizer)
The numbers start random. Training moves them until tokens used in similar
ways end up with similar rows. Nobody tells the model that " self" and
" cls" are related. Gradient descent finds that it lowers the loss to put
them near each other.
The formal version: a one-hot matrix multiply
Write token i as a one-hot vector: length V, all zeros except a 1 at
position i. Multiplying it by the table W (shape V × C) picks out row i:
one_hot(3) = [0, 0, 0, 1, 0, ..., 0] (1, V)
one_hot(3) @ W = W[3] (1, V) @ (V, C) → (1, C)
So an embedding layer is a linear layer with no bias, applied to one-hot
inputs. Libraries implement it as indexing (W[ids]) because building a
V-wide vector of zeros for every token wastes memory: 8,196 floats to select
one row.
Seeing it as a matmul tells us how it learns. The gradient of a matmul with
respect to W is one_hot.T @ grad_out. Every row of one_hot.T is zero
except the rows of tokens that appeared. So only the rows of tokens in the
batch get a gradient. A token that never appears in training keeps its random
initial vector forever. That is one more reason the tokenizer should not have
learned tokens that the training data never uses.
Size
Our tokenizer has V = 8,196 rows. The cost in parameters is V × C:
width C |
embedding params | share of a 40M model |
|---|---|---|
| 256 | 2.10M | 5% |
| 512 | 4.20M | 10% |
| 768 | 6.29M | 16% |
GPT-2's vocabulary is 50,257. At C = 768 its table alone is 38.6M
parameters, almost a third of the 124M model. A small vocabulary keeps more of
our budget in the layers that do the thinking. That was part of the Stage 01
decision.
2. Weight tying: the same table on the way out
At the end of the model, the last vector for each position has to become a
score for every token in the vocabulary (the logits). That is another
C × V matrix, the output head or unembedding:
hidden (B, T, C) @ W_out (C, V) → logits (B, T, V)
W_out has the same shape as the embedding table, transposed. Weight
tying uses the same matrix for both: W_out = W_emb.T.
Why this makes sense: the input table says "token i looks like this vector",
and the output head scores token i by how close the final hidden vector is to
row i (a dot product). Both ask "what does token i look like in this
space?" Tying forces one answer to both questions.
What it buys:
- Parameters. One table instead of two: 4.2M saved at
C = 512. - Rare tokens. A token that is rarely the input is still trained every
time it is a candidate output, which is every step. Every row of the output
head gets a gradient on every step, because softmax touches all
Vscores. Tying passes that signal to the input side.
Who uses it: GPT-2 ties. Llama 1 and 2 do not. Recent small models (Llama 3.2 1B and 3B, Qwen2.5 0.5B and 1.5B, Gemma) tie, because at small sizes the table is a big share of the parameters. We tie, and measure the difference in §8.
3. Why position is needed at all
Attention sees a set, not a sequence
Stage 04 builds attention properly. For this stage, one fact is enough: in attention, each token's output is a weighted average of all tokens' vectors. The weights come from dot products between token vectors. Nothing in that calculation looks at where a token is.
So if you shuffle the input tokens, the outputs come back shuffled the same way
and are otherwise identical. In maths: for any permutation matrix P,
Attention(P·X) = P·Attention(X). This is called permutation
equivariance. We test it exactly in test_embeddings.py.
What that means in practice. These two lines contain exactly the same tokens:
a = b - c
c = b - a
Without position information, attention cannot tell them apart. To it, both
are the bag {a, =, b, -, c}. For code, where x = y and y = x do opposite
things, that is fatal.
A loophole: the causal mask
A language model uses a causal mask: token t may only look at tokens
0..t, never at the future. The mask breaks the symmetry above. Token 0 sees 1
token, token 9 sees 10. A model can, in principle, work out roughly where it is
by how "diluted" its average is. Haviv et al. (2022) showed causal language
models with no position information ("NoPE") still learn something about
order this way. So the honest prediction for our ablation is not "no position →
cannot learn", but:
- No mask, no position: cannot see order at all (proved by the test).
- Causal mask, no position: sees order weakly and indirectly. Should train, but worse. §8 measures how much worse.
4. Scheme 1: learned absolute positions (GPT-2)
The simplest idea: a second lookup table, indexed by position instead of token id. Slot 0 gets row 0, slot 1 gets row 1, and so on. Add it to the token vector:
x = tok_emb[ids] + pos_emb[0..T-1]
(B, T, C) (T, C) ── broadcast over the batch
GPT-2 does exactly this with 1,024 position rows.
Strengths. Nothing to design. The model learns whatever position signal is useful.
What breaks.
- No position beyond the table. GPT-2 has rows 0..1023. Position 1024 has no row, so the model cannot even run on longer input.
- Late positions train less. Every training window uses position 0, but only windows of full length reach position 1023. With document packing (Stage 02) every window is full, so this costs us little. It matters for models trained on short, padded examples.
- Nothing ties positions together. Row 500 and row 501 are learned separately. The model has to discover that they are neighbours.
- Absolute, not relative. "The token 3 places back" is what matters for
most grammar and code (
def f(→)), but the model only gets "I am at 517, that token is at 514". It has to learn to subtract.
5. Scheme 2: sinusoidal positions (the 2017 transformer)
The picture: a row of clocks
Picture C/2 clocks, each with one hand, all ticking at different speeds. The
fastest clock's hand goes round once every ~6 positions. The slowest takes
about 63,000 positions per turn. To encode position p, write down where every
hand points: its sin and cos.
pair 0 (fast) ◷ ◶ ◵ ◴ ◷ ◶ ◵ ◴ ... changes every token: fine detail
pair 1 ◷ ◷ ◶ ◶ ◵ ◵ ◴ ◴ ...
...
pair C/2-1 (slow) ◷ ◷ ◷ ◷ ◷ ◷ ◷ ◷ ... barely moves: coarse "which region"
This works like the hands of a real clock. The second hand tells you the second, the hour hand tells you roughly the time of day. Together they name every moment uniquely.
The formula
For position p and pair index i = 0 .. C/2 - 1:
ω_i = 1 / 10000^(2i / C) # angular speed of clock i
PE[p, 2i] = sin(p · ω_i)
PE[p, 2i+1] = cos(p · ω_i)
ω_0 = 1 radian per token (one turn per 2π ≈ 6.3 tokens). The slowest,
ω_{C/2-1} ≈ 1/10000, takes ≈ 62,800 tokens per turn. No parameters. PE is
added to the token embedding exactly like the learned table.
Why sines and cosines and not just p
- Bounded. Every value is in [-1, 1], whatever
pis. Feeding in a rawpof 50,000 would swamp the token vectors. - Moving by
kis a fixed rotation. Turning a clock hand byk·ωis a 2×2 rotation, the same one at every starting point. SoPE[p + k] = R_k · PE[p], whereR_kdepends only onk. In principle a layer can learn "lookkback" once and use it everywhere. - Similarity depends only on distance.
PE[p] · PE[q] = Σ_i cos((p - q)·ω_i). Only the gapp - qappears. We plot this in §7.
What still breaks. The position is added to the token vector, so the two are mixed together before attention sees them. They must also be the same size: a sinusoid vector has length √(C/2) whatever happens, so the 2017 paper multiplies token vectors by √C first. Forget that, and position drowns the token. We forgot it, and §8 shows the cost. The model has to untangle "what" from "where" itself. And past the training length, attention meets combinations of clock positions it never saw in training. Sinusoids can compute any position, but the model has not learned what to do there.
6. Scheme 3: RoPE, rotary position embedding (Llama and most models since)
The idea in one sentence
Do not add position to the token vector. Instead, rotate the query and key vectors by an angle proportional to their position, right before the attention dot product. Then the dot product sees only the difference in angles, which is the distance between the tokens.
The picture in 2D
Take a query q at position m and a key k at position n. Each is a 2D
arrow. Rotate q by m·θ and k by n·θ:
q rotated by m·θ
↗
/ angle between them = (m - n)·θ + (original angle)
/ ↗ k rotated by n·θ
/ /
o───────
The dot product of two arrows depends only on their lengths and the angle
between them. Rotating both by the same extra amount changes nothing. So if
both tokens move 100 places to the right, the score is the same. Only
m - n matters.
Worked example (small numbers)
Let q = k = (1, 0) and θ = 0.5 radians per token.
| q at | k at | q angle | k angle | score = cos(difference) |
|---|---|---|---|---|
| m = 3 | n = 1 | 1.5 | 0.5 | cos(1.0) = 0.540 |
| m = 10 | n = 8 | 5.0 | 4.0 | cos(1.0) = 0.540 |
| m = 3 | n = 3 | 1.5 | 1.5 | cos(0.0) = 1.000 |
Same gap of 2, same score. That is the whole trick.
More than two dimensions
A head of size d (say 64) is split into d/2 pairs. Each pair is its own 2D
plane, rotated at its own speed, using the same clock speeds as sinusoids:
θ_i = base^(-2i/d), i = 0 .. d/2 - 1, base = 10000
For pair i at position m, with angle a = m·θ_i:
[x'_{2i} ] [cos a -sin a] [x_{2i} ]
[x'_{2i+1}] = [sin a cos a] [x_{2i+1}]
Applied to q and k only, never to v. It has no parameters.
The complex-number view
A 2D pair (x, y) can be written as one complex number x + iy. Rotating by
angle a is multiplying by e^{ia}. So RoPE is:
q̃_m = q · e^{i m θ} k̃_n = k · e^{i n θ}
score = Re( q̃_m · conj(k̃_n) ) = Re( q · conj(k) · e^{i (m - n) θ} )
m and n only appear as m - n. This is the proof in one line, and Meta's
reference Llama code implements RoPE this way, with torch.view_as_complex.
Two layouts, one idea (a trap)
There are two common ways to choose which dimensions form a pair:
- Interleaved: pairs are
(0,1), (2,3), (4,5), .... This is the paper and Meta's complex-number code. - Half-split: pairs are
(0, d/2), (1, d/2+1), .... This is HuggingFace'srotate_half.
Both are correct RoPE. They are not interchangeable: loading weights trained
with one layout into code using the other gives a broken model with no error
message. The two differ only by a fixed shuffle of dimensions, and we test that
claim exactly. We build both and check the half-split one against HuggingFace's
apply_rotary_pos_emb.
Why RoPE won
- Relative by construction. The model does not have to learn subtraction.
- Position stays out of the residual stream. Nothing is added to the token vector, so "what" and "where" are not mixed. Position only affects who attends to whom.
- No parameters, and no table to run out of. Any position can be computed.
What it does not fix (honest version)
RoPE is often said to "extrapolate", meaning it handles sequences longer than training. That is only partly true. The slow pairs turn so little during training that, beyond the training length, they reach angles the model has never seen, and quality drops. That is why long-context models use RoPE plus a fix: position interpolation, NTK scaling, YaRN. Stage 14 covers those. What RoPE does give: no hard wall (unlike a learned table), and graceful rather than total failure. §8 measures it on our model.
7. Pictures from the real code
Both figures are produced by stages/03_embeddings/run.py plots.
Sinusoidal table (docs/visuals/03_sinusoidal.png): rows are positions,
columns are dimensions. The left columns (fast clocks) flicker, the right ones
(slow clocks) barely change. Beside it, the dot product PE[p] · PE[q] as a
heatmap: constant along every diagonal, because it depends only on p - q.

RoPE scores (docs/visuals/03_rope_offset.png): one fixed random q and
k (head size 64), placed at every pair of positions (m, n) from 0 to 127.
The score heatmap has stripes along the diagonals. Beside it, score against
offset m - n for three different starting positions. The three curves lie
exactly on top of each other.

8. Experiment: break position on purpose
Setup
A tiny causal language model, identical in every run except how it gets position:
- 4 layers, width 256, 4 heads of 64, MLP 4× wide, context 256 tokens.
- Our tokenizer (8,196 rows), our data: 85% code, 15% English, shuffled windows.
- 4,000 steps × 32 windows × 256 tokens = 32.8M tokens, AdamW (peak lr 1e-3, warmup then cosine), bf16. About 130-145 s per run on the RTX 4060 Laptop.
- 3 seeds per variant. A seed changes both the initial weights and the batch order; all variants with the same seed see identical batches.
Attention and the block are built properly in Stages 04-05. Here they are a
compact preview (stages/03_embeddings/tiny_lm.py), using PyTorch's built-in
attention kernel, because attention is not what this stage measures.
Variants:
| run | position scheme | tied head |
|---|---|---|
none |
nothing (relies on the causal mask) | yes |
learned |
GPT-2 table, 256 rows | yes |
sinusoidal |
fixed clocks, added | yes |
sinusoidal_scaled |
fixed clocks, added, token vectors × √C first | yes |
rope |
rotation of q, k | yes |
rope_untied |
rotation of q, k | no (separate head) |
Measured: validation loss on held-out code at the end, and loss per position
on windows twice the training length (512), to see what happens past the
edge. sinusoidal_scaled was not in the original plan. It was added after
the first sweep, for the reason in the results below.
Results
Mean ± standard deviation over 3 seeds, held-out code, 512 windows of 256 tokens (131k tokens). Lower is better. A loss of 2.52 means the model gives the correct next token, on average, probability e^-2.52 ≈ 8%; uniform guessing over 8,196 tokens would be ln(8196) = 9.01.
| run | params | val loss (T = 256) | positions 0-255 of a 512 window | positions 256-511 | jump past the edge |
|---|---|---|---|---|---|
none |
5,257,728 | 3.350 ± 0.013 | 3.302 | 3.508 | +0.21 |
learned |
5,323,264 | 2.689 ± 0.012 | cannot run | cannot run | — |
sinusoidal (as first written) |
5,257,728 | 4.723 ± 0.080 | 4.677 | 7.790 | +3.11 |
sinusoidal_scaled |
5,257,728 | 2.633 ± 0.001 | 2.614 | 4.939 | +2.32 |
rope |
5,257,728 | 2.523 ± 0.010 | 2.509 | 3.291 | +0.78 |
rope_untied |
7,355,904 | 2.598 ± 0.009 | 2.580 | 3.191 | +0.61 |
Source: results/03_embeddings/ablation.json. Figure:
docs/visuals/03_ablation.png (training curves, and loss at every position of
a 512-token window).

Seed noise is about ±0.01. Every gap discussed below is at least 5× that (the smallest, scaled sinusoids vs learned, is 0.056).
What the numbers say
1. Position matters a lot, and the causal mask is a poor substitute. No position at all: 3.350. Any working scheme: 2.52-2.69. The gap (0.83 for RoPE) is the largest effect in the table. The NoPE model is not hopeless: it beats broken sinusoids by 1.4 and trains steadily, so the causal mask does leak some order, as §3 predicted. But at this size and training length it is far behind.
2. Sinusoids as first written were worse than no position at all (4.723 vs
3.350). This was a bug in our setup, not in the idea. The sinusoid vector for a
position has length √(C/2) = 11.3. Our token vectors start with length 0.32
(256 numbers of size ~0.02). Added together, position outweighs the token
35 to 1. The model sees mostly where and barely what, and it has to
spend training growing the token vectors to compete. The 2017 paper multiplies
token embeddings by √C before adding the sinusoids. We had left that out. With
it (sinusoidal_scaled), loss drops to 2.633, better than learned positions.
The learned table never had this problem: it starts at the same 0.02 scale as
the tokens.
3. RoPE wins inside the training length: 2.523, which is 0.11 better than scaled sinusoids and 0.17 better than learned positions, with no position parameters at all. The learned table spends 65,536 parameters (256 × 256) and does worse.
4. Tying the head helps at this size. Untying adds 2.10M parameters (+40%) and makes the loss worse, 2.598 vs 2.523. The tied table gets a training signal from both ends of the model on every step. Untied, the input table only learns from the tokens that appear in each batch.
5. Nobody extrapolates well. Past position 255, every scheme gets worse. In detail:
- Learned: cannot run at all. The hard wall.
- Sinusoidal (scaled): breaks immediately. Loss 2.44 at positions 250-255, 3.56 at 256-271, 5.28 at the end of the window. The model has never seen these position vectors added to a token, and they disturb every layer.
- RoPE: fine for about 40 tokens past the edge (2.23 at positions 256-271, no worse than inside), then climbs to 3.89 at the end. Why the delay: RoPE only sees distances. A token at position 270 mostly attends to nearby tokens, at distances it has seen thousands of times. Only its attention to the very first tokens uses distances above 255, which it never saw. As the position grows, more of what it attends to is at unseen distances.
- None: degrades least (+0.21), because there is no position signal to go out of range. Only the causal mask's "how many tokens can I see" changes. It is still worse in absolute terms than RoPE at every position below ~400.
So "RoPE extrapolates" is true only in the weak sense of §6: no wall, and a gradual slope instead of a cliff. Stage 14 covers the fixes real long-context models use.
6. Early positions are hard for everyone. In the RoPE model, loss at position 0 is 5.32 and at position 255 it is 2.15. The first token of a window has no context. Every later token has more to go on. This is why validation loss always depends on the context length it was measured at.
The ablation the curriculum asked for
"Train with no positional info; show it cannot learn word order." Measured
answer: with a causal mask, it can learn some order, but it pays 0.83 nats of
loss for not being told. Without a mask, it provably cannot see order at all
(test_attention_without_position_is_permutation_equivariant).
9. Build order
stages/03_embeddings/embeddings.py: token embedding (as indexing and as one-hot matmul), learned positions, sinusoidal table, RoPE (interleaved, half-split, complex), tied output head.stages/03_embeddings/test_embeddings.py: acceptance criteria below.stages/03_embeddings/tiny_lm.py: the preview model with a switchable position scheme.stages/03_embeddings/run.py:plotsandablation.
Acceptance criteria
- Indexing, one-hot matmul and
nn.Embeddinggive identical outputs and identical gradients. Rows of unused tokens get exactly zero gradient. - Attention without a mask and without position is permutation-equivariant (exact, up to float error). Adding any position scheme breaks it.
- Sinusoidal: values in [-1, 1];
PE[p] · PE[q]depends only onp - q;PE[p + k] = R_k · PE[p]for a fixed rotation. - RoPE: preserves vector length; score depends only on
m - n(to 1e-5); interleaved equals the complex-number version; half-split equals HuggingFaceapply_rotary_pos_emb; the two layouts differ only by a dimension shuffle. - Tied head: output weight is the embedding tensor (same storage), and the
parameter count drops by exactly
V × C.
10. What we found
Dated entries in docs/JOURNAL.md (2026-10-29). The short version:
| What | Number | Lesson |
|---|---|---|
| Any position vs none | 2.52-2.69 vs 3.35 val loss | The causal mask leaks some order, but nowhere near enough. |
| Sinusoids, no √C scaling | 4.72, worse than no position | A position signal 35× louder than the token drowns it. Check the size of everything you add together. |
| Sinusoids, with √C | 2.63, beats learned (2.69) | A one-line detail from the 2017 paper was worth 2.1 nats. |
| RoPE | 2.52, best, zero parameters | Relative position inside attention beats absolute position added to the input. |
| Untied head | +2.1M params, loss 2.60 vs 2.52 | At small sizes, tying is free quality. |
| Past training length | RoPE OK for ~40 tokens, then +0.8 | "Extrapolates" means "no wall", not "works". |
| float32 RoPE angles | score drift 1.4e-5 at position 127 | The angle equals the position in radians; float32 rounds it. Harmless at 256 tokens, real at 100k. |
| Seed noise | ±0.01 | Three seeds made every claim above checkable. One seed would not have. |
The habit this chapter teaches: when two things are added, check that they are the same size. The sinusoid bug produced no error, no NaN and no crash. The loss went down every step. It went down to the wrong place, and only the comparison against other variants showed it. Stage 05 (residual streams and normalization) returns to this: almost every "it trains but badly" bug in a transformer is a scale bug.
Chapter 6
Attention, from one head up
After Stage 03, every token is a vector that knows what it is and where it is. But each vector still knows nothing about its neighbours. In
total = price * qty
return total
the vector for the second total has no idea that total was just assigned,
or what from. To predict what comes after return total, it needs
information from earlier tokens. Attention is how a token gathers
information from other tokens. It is the only place in a transformer where
tokens talk to each other. Everything else (the MLP, the norms) works on one
token at a time.
This stage builds attention from one head to many, checks it against
PyTorch's own F.scaled_dot_product_attention, measures what it costs, and
breaks the √d scaling on purpose.
Shape letters, as in Stage 03: B batch, T tokens, C model width,
H heads, d = C / H head size.
1. The idea: a dictionary lookup that is allowed to be fuzzy
A Python dict, the strict version
memory = {"price": 9.99, "qty": 3, "total": 29.97}
memory["qty"] # → 3
You bring a key, it is compared with every stored key, exactly one matches, you get its value. Exact match, one answer, nothing in between.
Attention, the soft version
Attention does the same three things with vectors, and allows partial matches:
- Each token asks a question: its query
q. - Each token advertises what it has: its key
k. - Each token offers some content: its value
v.
A token compares its query with every key (a dot product: large when the two vectors point the same way). The scores become weights that add up to 1. The result is a weighted average of all the values. A strong match gets most of the weight, a weak match a little, never exactly zero.
query of "return total"
│
compare with every key (dot product)
┌─────────────┼─────────────────┬───────────────┐
▼ ▼ ▼ ▼
key "total" key "=" key "price" key "qty"
score 4.0 score 0.1 score 1.2 score 0.9
└─────────────┴──────┬──────────┴───────────────┘
softmax: scores → weights summing to 1
│
0.80·v_total + 0.05·v_= + 0.09·v_price + 0.06·v_qty
│
new vector for "return total"
(Illustration: the scores are invented to show the flow.)
Why soft instead of exact? Because it has a gradient. A hard lookup either picks an entry or does not, and you cannot nudge it a little. A weighted average changes smoothly when the scores change, so training can adjust the queries and keys bit by bit until the right tokens get the weight.
Where do q, k and v come from? Three learned matrices, applied to each
token's vector:
q = x @ W_q k = x @ W_k v = x @ W_v each (C,) @ (C, d) → (d,)
The same token produces three different vectors for three different jobs: what am I looking for, what do I match on, what do I hand over if picked.
Worked example (small numbers, computed)
One query, three tokens, head size d = 2:
q = [2, 0]
k1 = [2, 0] v1 = [10, 0]
k2 = [0, 2] v2 = [ 0, 10]
k3 = [1, 1] v3 = [ 5, 5]
| step | token 1 | token 2 | token 3 |
|---|---|---|---|
score q · k |
4.0 | 0.0 | 2.0 |
divide by √d = 1.414 |
2.828 | 0.000 | 1.414 |
| softmax (weights) | 0.768 | 0.045 | 0.187 |
Output = 0.768·v1 + 0.045·v2 + 0.187·v3 = [8.61, 1.39]. Mostly token 1,
some token 3 (a partial match), a trace of token 2 (no match, still not zero).
2. The formula
For all tokens at once, stack the queries, keys and values into matrices:
Q = X W_q (T, C) @ (C, d) → (T, d)
K = X W_k (T, d)
V = X W_v (T, d)
scores = Q Kᵀ / √d (T, d) @ (d, T) → (T, T)
weights = softmax(scores, each row) (T, T), every row sums to 1
out = weights V (T, T) @ (T, d) → (T, d)
scores[i, j] is "how much token i's question matches token j's key". Row
i of weights is token i's attention: how it splits its attention across
all tokens. That (T, T) matrix is the attention map, and §8 shows real
ones.
Two pieces need explaining: the √d, and how to stop tokens from looking at
the future.
3. Why divide by √d
The problem: dot products grow with the length of the vectors
A dot product is a sum of d products: q·k = q₁k₁ + q₂k₂ + ... + q_d k_d.
If each qᵢ and kᵢ is a random number with mean 0 and variance 1, each
product also has mean 0 and variance 1. Adding d independent ones gives
variance d, so the typical size (standard deviation) is √d.
head size d |
typical size of q·k |
|---|---|
| 4 | 2 |
| 64 | 8 |
| 512 | 22.6 |
Why large scores are bad: softmax saturates
Softmax turns differences between scores into ratios: a score larger by 1 gets e ≈ 2.7× the weight, larger by 10 gets e¹⁰ ≈ 22,000×. When scores are spread over ±20, the largest one takes almost all the weight. With 8 random keys and a random query (computed):
d |
max weight, no scaling | max weight, divide by √d |
|---|---|---|
| 4 | 0.43 | 0.31 |
| 64 | 0.81 | 0.27 |
| 512 | 1.000 | 0.41 |
A weight of 1.000 means the soft lookup has become a hard one. And a hard
lookup has no gradient, which was the whole point of making it soft. The
softmax's slope is p(1 - p), which is 0 at p = 1 and at p = 0. Every
weight is now either 0 or 1, so almost no gradient flows back to the queries
and keys. They stop learning.
The fix
Divide the scores by √d. Variance d divided by (√d)² = d gives variance
1, whatever the head size. One line, and the softmax starts in its useful
range at any width.
This argument assumes q and k have entries of size about 1. With small
initial weights they are smaller, so the scaling matters less at the start
and more as training grows the weights. §9 measures both: the clean
random-vector case, and a real model trained with and without the scaling.
4. The causal mask: no peeking
A language model predicts token t + 1 from tokens 0..t. In training, all
positions are computed in parallel from one sequence. If position 5 could
attend to position 6, it could read the answer it is being asked to predict.
The loss would drop to near zero and the model would learn nothing usable.
The fix: before the softmax, set every score where j > i (the key is in the
future) to -∞.
scores (T = 4) after mask softmax rows
[ s00 s01 s02 s03 ] [ s00 -∞ -∞ -∞ ] [ 1 0 0 0 ]
[ s10 s11 s12 s13 ] ──▶ [ s10 s11 -∞ -∞ ] ──▶ [ .4 .6 0 0 ]
[ s20 s21 s22 s23 ] [ s20 s21 s22 -∞ ] [ .2 .5 .3 0 ]
[ s30 s31 s32 s33 ] [ s30 s31 s32 s33 ] [ .1 .3 .4 .2 ]
(weights illustrative)
Why -∞ and not 0? Softmax computes e^score. e^0 = 1, which is a real
weight. e^(-∞) = 0 exactly, so a future token gets exactly zero weight and
the remaining weights still add up to 1.
Why mask before the softmax and not zero the weights after? Zeroing after leaves rows that sum to less than 1. Re-normalizing fixes that, but it is two steps where one would do.
The trap. If a row is masked everywhere (this happens with padding,
not with a plain causal mask, because every token can see itself), softmax
computes 0 / 0 and returns NaN. One NaN spreads through every later layer.
Our causal-only setup cannot hit it; Stage 16 (SFT with padding) can.
5. Many heads instead of one
One head computes one attention pattern per token. But a token often needs
several kinds of information at once: the previous token (for syntax), the
matching ( (for brackets), the definition of a variable (for meaning).
Multi-head attention runs H smaller attentions side by side, each with
its own W_q, W_k, W_v of width d = C / H, and joins their outputs:
x (B, T, C)
│ one big matmul makes Q, K, V for all heads at once
▼
q, k, v (B, T, C) each
│ split C into H heads of size d: view → (B, T, H, d)
│ move heads next to batch: transpose(1, 2) → (B, H, T, d)
▼
attention inside each head (independently) (B, H, T, T) weights
▼
out (B, H, T, d)
│ move heads back: transpose(1, 2) → (B, T, H, d)
│ glue the heads side by side: reshape → (B, T, C)
▼
output projection W_o (C, C) ── mixes what the heads found
▼
(B, T, C)
The view + transpose part is where most attention bugs live, because a
wrong reshape gives the right shape and wrong contents. No error is
raised. The test that compares against PyTorch catches it.
Cost compared with one big head: the same. W_q, W_k, W_v, W_o are four
C × C matrices either way (4C² parameters, 262,144 at C = 256). Heads
split the width, they do not add to it. What changes is that there are H
attention maps instead of one, each looking in a d-dimensional slice.
6. What attention costs: the T × T matrix
The scores matrix has one entry per pair of tokens: T × T per head. It is
the reason long context is expensive.
T |
entries per head | bytes per layer at B = 1, H = 8, fp32 |
|---|---|---|
| 1,024 | 1.0M | 32 MB |
| 4,096 | 16.8M | 512 MB |
| 16,384 | 268M | 8.6 GB, more than our whole GPU |
Double the context, four times the memory and compute. A naive
implementation also keeps the (T, T) weights for the backward pass.
FlashAttention (Stage 09) computes the same result in tiles without ever
storing the full matrix, so memory grows with T instead of T². PyTorch's
F.scaled_dot_product_attention uses it when it can. §9 measures our
naive version against it on the 4060.
7. Checking ourselves against PyTorch
The rule for this project: write it, then match the library. Our attention
must equal F.scaled_dot_product_attention to 1e-5, in outputs and
gradients, with and without the causal mask. The multi-head module, with its
weights copied in, must equal nn.MultiheadAttention.
8. Reading attention maps
A trained model's attention weights can be plotted: rows are the token doing the looking, columns the tokens looked at. Some heads do recognisable jobs. The best-known is the previous-token head, which puts most of its weight on the token just before. It shows as a bright line one step below the diagonal.
A warning before reading too much into maps: a weight says where a head looked, not what it used. If the value vectors at that spot are near zero, a large weight contributes nothing. Maps are a hint, not an explanation.
§9 shows maps from our trained tiny model on real Python, and counts how many heads are previous-token heads.
9. Experiments
All produced by stages/04_attention/run.py.
9a. Saturation with random vectors (run.py variance)
Random q, k, v with unit-variance entries, 256 keys, d from 16 to 1024:
the size of the scores, the largest softmax weight, the entropy of the
weights (in nats; spreading evenly over 256 keys gives ln 256 = 5.55, all weight
on one key gives 0), and the gradient at two places: at the scores (where
softmax's slope lives) and at the query. 512 queries per row.
d |
score std, scaled / unscaled | max weight, scaled / unscaled | entropy, unscaled | score gradient, scaled / unscaled | queries with ~no score gradient, unscaled | gradient at q, scaled / unscaled |
|---|---|---|---|---|---|---|
| 16 | 1.00 / 4.00 | 0.046 / 0.494 | 1.90 | 0.356 / 0.829 | 0% | 0.38 / 3.7 |
| 64 | 1.00 / 7.98 | 0.042 / 0.740 | 0.78 | 0.744 / 1.23 | 2% | 0.78 / 13.2 |
| 256 | 1.00 / 16.03 | 0.043 / 0.881 | 0.33 | 1.50 / 0.328 | 14% | 1.58 / 33.9 |
| 1024 | 1.00 / 32.04 | 0.043 / 0.940 | 0.15 | 2.99 / 0.022 | 41% | 3.1 / 63.1 |
"~no gradient" = score-gradient norm below 1e-3. Source:
results/04_attention/variance.json, figure docs/visuals/04_sqrt_d.png.

What it shows:
- Scaled scores have std 1.00 at every
d. The fix does exactly what §3 says. Unscaled std is√d: 4, 8, 16, 32. - Unscaled softmax saturates as
dgrows. Atd = 1024the top key gets 94% of the weight on average, and entropy is 0.15 nats: the "soft" lookup is choosing about one key. - The gradient at the scores collapses: from 1.23 at
d = 64to 0.022 atd = 1024, and 41% of queries get essentially none. That is the vanishing gradient the curriculum predicted. - But the gradient at
qdoes not vanish. It grows (63 vs 3.1). The gradient atqis the score gradient multiplied byk, and unscaled,kenters at full size√dinstead of√d / √d. The two effects partly cancel, and in this setup thekfactor wins. So "gradients vanish" is true at the softmax, and misleading if you measure at the weights. What is really broken is that the gradient is concentrated on a few queries (the ones not yet saturated) while 41% contribute nothing. §9c checks a real model.
9b. The cost of T × T (run.py cost)
Our attention vs PyTorch's fused kernel, B = 1, H = 8, d = 64, causal,
forward + backward, on the RTX 4060 Laptop: peak memory and time per call as
T grows.
T |
ours: peak MB | ours: ms | fused: peak MB | fused: ms |
|---|---|---|---|---|
| 256 | 4.3 | 0.40 | 2.0 | 0.14 |
| 1,024 | 66 | 1.5 | 8.1 | 0.31 |
| 2,048 | 262 | 8.8 | 16.1 | 0.92 |
| 4,096 | 1,044 | 36 | 32.3 | 2.9 |
| 8,192 | 4,168 | 148 | 64.5 | 10.7 |
| 16,384 | out of memory | — | 129 | 41 |
Source: results/04_attention/cost.json, figure docs/visuals/04_cost.png.

- Ours grows 4× per doubling of
T(262 → 1,044 → 4,168 MB): theT²from §6, measured. The fused kernel grows 2× per doubling: linear inT. - Ours keeps about four
T × Tmatrices alive, not one. AtT = 1,024one bf16T × Tmatrix across 8 heads is 16.8 MB, and we peak at 66 MB: the scores, the masked scores, the softmax weights kept for backward, and their gradient. The §6 table counted one copy, so a naive implementation is about 4× worse than that table suggests. - At 16,384 tokens, one attention call would need about 17 GB. Ours cannot run at all. The fused kernel takes 129 MB and 41 ms. That is the whole case for FlashAttention (Stage 09).
- At
T = 8,192the fused kernel is also 14× faster. Memory traffic, not arithmetic, is what the naive version wastes time on.
9c. Training without √d (run.py ablation)
The Stage 03 tiny model (4 layers, C = 256, learned positions, tied head,
32.8M tokens), now using our attention. Four variants, 2 seeds each:
| run | heads × head size | scaling |
|---|---|---|
d64 |
4 × 64 | ÷√d |
d64_noscale |
4 × 64 | none |
d256 |
1 × 256 | ÷√d |
d256_noscale |
1 × 256 | none |
Measured: held-out code loss, and the attention of the trained model on 128 held-out windows (entropy and top weight, rows 32+ only, so early rows with few choices do not dominate).
| run | val loss (3 seeds) | attention entropy | top weight | score std at init | ‖∇W_qkv‖ at end (seed 0) |
|---|---|---|---|---|---|
d64 |
2.689 ± 0.012 | 2.75 | 0.31 | 0.10 | 0.56 |
d64_noscale |
2.652 ± 0.006 | 2.16 | 0.42 | 0.81 | 0.63 |
d256 |
2.705 ± 0.003 | 2.78 | 0.29 | 0.10 | 0.51 |
d256_noscale |
3.655 ± 0.018 | 0.92 | 0.78 | 1.61 | 0.97 |
Source: results/04_attention/ablation.json.
Cross-check first. d64 is the Stage 03 learned model with our attention
swapped in for PyTorch's. Stage 03 seed 0 scored 2.6849, this one 2.6856. Our
attention trains the same as PyTorch's.
At d = 256, dropping √d is a disaster: +0.95 loss, more than
removing position entirely cost in Stage 03 (+0.66 against learned positions). The trained model's
attention is saturated: the top key gets 78% of the weight, and entropy 0.92
nats means each token effectively reads from e^0.92 ≈ 2.5 tokens. The
scaled model spreads over e^2.78 ≈ 16.
At d = 64, dropping √d helped, slightly but on all 3 seeds (2.652 vs
2.689). This was not expected. The reason is the starting point. Our weights
start small (std 0.02), so queries and keys start small too: measured score
std at initialisation is 0.81 unscaled and only 0.10 scaled. With scores
that small, softmax is almost uniform, so the scaled model starts out unable to
focus, and spends early training growing its weights. Unscaled, it starts with
scores in a healthy range. At d = 256 the unscaled start is 1.61, still fine,
but the scores keep growing as training grows the weights, and by the end the
softmax has saturated.
The weight gradients did not vanish. In d256_noscale the gradient
reaching W_q, W_k, W_v is larger at the end (0.97 vs 0.51), consistent with
§9a: the vanishing happens at the softmax, and the k factor hides it at the
weights. So we can say what broke (attention collapsed onto ~2.5 tokens and
loss rose by 0.95). We have not shown exactly why a saturated model then
learns worse; "gradients vanish" is the textbook story, and our measurement
does not support it in that form.
Lesson. √d is not a magic constant. It keeps the scores' scale fixed as
d changes, so one learning rate and one initialisation work for any head
size. At our small d = 64 and small init, it was not needed, and even cost a
little. At d = 256 it was the difference between a working model and a
broken one. Real models use d = 64-128 with much larger widths, and train for
far longer than our 32.8M tokens, which gives the scores more time to grow.
9d. Attention maps (run.py maps)
The trained d64 model (seed 0) on a hand-written Python snippet
(run.py SNIPPET, 42 tokens), plus statistics for every head over 64
held-out windows. Figures: docs/visuals/04_attention_maps.png (all 16
heads), docs/visuals/04_attention_heads.png (two heads, labelled). Source:
results/04_attention/heads.json.


What we found among the 16 heads:
- One clear previous-token head: layer 2, head 2. 68% of its weight on the token just before, on held-out code. Its map is a bright line one step below the diagonal. A model of 5M parameters, trained for about 3 minutes, grew it without being told to.
- Two "attention sink" heads: layer 3, heads 0 and 1 put 24% and 37% of their weight on the first token of the window. Our windows start at a random point in the data, so that first token means nothing in particular. This is a known effect (Xiao et al., 2023): softmax must put weight somewhere, and a head that has nothing useful to read parks it on a spot every token can see. This is why a weight is not evidence of use (§8).
- Column heads: layer 1, head 0 shows vertical stripes: many later tokens all look at the same few earlier tokens.
- Diffuse heads in layer 0 (entropy 3.4-4.2 nats): weight spread thinly over everything, close to an average of recent tokens.
- The snippet also shows our tokenizer at work:
taxis two tokens (·t,ax) andqtyis two (q,ty).
10. Build order and acceptance criteria
stages/04_attention/attention.py:attention()(functional core),SingleHeadAttention,MultiHeadAttention.stages/04_attention/test_attention.py.stages/04_attention/tiny_lm.py: the Stage 03 preview model with our attention in place of PyTorch's.stages/04_attention/run.py:variance,cost,ablation,maps.
Acceptance criteria (as tests):
- Our attention equals
F.scaled_dot_product_attentionwithin 1e-5, causal and not, outputs and gradients. MultiHeadAttentionwith copied weights equalsnn.MultiheadAttention.- Multi-head with
H = 1equals single-head with the same weights. - Causality: changing a future token changes no earlier output, exactly.
- Every row of weights sums to 1; masked weights are exactly 0.
- Unscaled scores of unit-variance vectors have variance ≈
d; scaled ≈ 1.
11. What we found
Dated entries in docs/JOURNAL.md (2026-10-30). The short version:
| What | Number | Lesson |
|---|---|---|
| Our attention vs PyTorch | equal to 1e-5, outputs and gradients; same training loss (2.6856 vs 2.6849) | Match the reference twice: numerically, and in a real run. |
| Wrong reshape | right shape, wrong answer, no error | Only a reference comparison catches it. |
| √d at random vectors | score gradient 0.022 at d = 1024, 41% of queries dead | Saturation is real and gets worse with d. |
Gradient at q without √d |
larger, 63 vs 3.1 | "Gradients vanish" depends on where you measure. |
| No √d, d = 256, real model | loss +0.95, attention on ~2.5 tokens | The ablation the curriculum predicted. |
| No √d, d = 64, real model | loss −0.04, on all seeds | Small init made scaled scores start too flat (std 0.10). |
| Memory, naive vs fused | 4× vs 2× per doubling; OOM at 16k vs 129 MB | T² is real; ~4 copies of the matrix are alive, not 1. |
| Trained heads | one previous-token head (68%), two sinks (24%, 37%) | Structure appears on its own. Weight ≠ use. |
The habit this chapter teaches: a textbook reason is a prediction, not a
fact. "Without √d, gradients vanish" turned out to be right at the softmax,
wrong at the weights, harmless at d = 64, and devastating at d = 256. Each
part was only visible because we measured instead of assuming.
Chapter 7
The transformer block
Stage 04 built attention: the one place where tokens exchange information. A language model is not one attention layer, though. It is the same unit, the block, stacked 12, 24 or 96 times. GPT-2 small has 12 blocks; Llama 3 8B has 32.
The tiny model in Stages 03 and 04 already had blocks in it. We used them as a preview and did not explain them. This stage takes the block apart:
- the residual connection, which makes deep stacks trainable at all;
- the normalisation (LayerNorm, then RMSNorm), which keeps the numbers in a sane range;
- where the normalisation goes (pre-norm or post-norm), which decides whether 24 layers train;
- the MLP, which holds two thirds of the block's parameters;
- the activation function inside it (ReLU → GELU → SwiGLU);
- dropout, and why big pretraining runs switch it off.
Then we check our block against Hugging Face's GPT-2 block number for number, and break each piece on purpose.
Shape letters as before: B batch, T tokens, C model width, H heads.
1. The picture
One block, GPT-2 style:
x (B, T, C) ← the residual stream coming in
│
┌───────┤
│ ▼
│ LayerNorm
│ ▼
│ attention tokens talk to each other (Stage 04)
│ ▼
└──────(+) add, do not replace
│
┌───────┤
│ ▼
│ LayerNorm
│ ▼
│ MLP each token works alone: C → 4C → C
│ ▼
└──────(+)
│
▼
x (B, T, C) ← same shape out, so blocks stack
Two sublayers, each wrapped the same way: normalise, transform, add back.
The input and output have the same shape, (B, T, C), which is the only reason
blocks can be stacked like bricks.
The two sublayers have different jobs. Attention moves information between tokens. The MLP processes each token on its own, with no view of the others. A useful rough picture: attention gathers what a token needs from the context, the MLP thinks about what it gathered.
2. The residual connection: add, do not replace
The idea
Without a residual, a layer replaces its input: x ← f(x). With one, it
adds to its input: x ← x + f(x).
That small change has a big consequence. Each block no longer has to produce a complete new representation. It only has to produce a correction, an edit to what is already there. A block that has nothing useful to say can output close to zero and pass its input through untouched.
This gives the model a different shape. Think of one long vector per token, the residual stream, running from the embedding at the bottom to the output head at the top. Every block reads the stream, computes something, and writes its result back by adding it. Nothing is ever overwritten.
embedding ──► (+) ──► (+) ──► (+) ──► (+) ──► ... ──► final norm ──► head
▲ ▲ ▲ ▲
attn₁ mlp₁ attn₂ mlp₂ each reads the stream,
adds its contribution
Why it matters: the gradient needs a road
Training pushes a gradient backwards from the loss to every weight. Without residuals, the gradient arriving at layer 1 has passed through every layer above it, and each layer multiplies it by its own derivative.
Suppose each layer, on average, shrinks the gradient to 0.8 of its size.
Through 24 layers: 0.8^24 = 0.0047. Layer 1 receives half a percent of the
signal layer 24 got, and learns about 200× slower. If each layer instead grows
it by 1.2: 1.2^24 = 79. The gradient explodes. Getting exactly 1.0 from every
layer, all the time, is not something you can arrange.
With a residual, the derivative of x + f(x) with respect to x is
1 + f'(x). The 1 is a direct path: the gradient from the top reaches
every layer unchanged, plus whatever extra the layers add. The product of
(1 + small) terms does not collapse towards zero the way a product of
small terms does.
no residual: ∂loss/∂x₁ = f'₂₄ · f'₂₃ · ... · f'₁ product of 24 factors
residual: ∂loss/∂x₁ = (1 + f'₂₄)(1 + f'₂₃) ... (1 + f'₁)
= 1 + (sum of single terms) + (pairs) + ...
▲
this 1 is the highway
(Here f' is really a matrix, a Jacobian, and the 1 is the identity matrix.
The argument is the same.)
What breaks without it: deep stacks, we expected; a 4-layer network should survive. That prediction turned out wrong. Without residuals, both our 4-layer and 24-layer models learned nothing about context (§10c), and the reason was not the one above, at least not first (§10a).
3. Normalisation: keep the numbers in range
The problem
The residual stream is a running sum. Every block adds something to it, so its
size tends to grow as it goes up the stack. And each sublayer would like its
input at a predictable scale: attention scores, for example, depend on the size
of q and k (Stage 04 §3). An input that is 10× larger at layer 20 than at
layer 1 means each layer sees numbers of a different size.
The fix is to normalise each token's vector before a sublayer reads it: rescale it to a standard size, every time.
LayerNorm (GPT-2, the original transformer)
For one token's vector x of length C:
- subtract the mean of its
Cnumbers, so they centre on 0; - divide by their standard deviation, so they have spread 1;
- multiply by a learned vector
γ(gain) and add a learnedβ(bias), so the model can undo the scaling where it wants to.
LayerNorm(x) = γ · (x − mean(x)) / sqrt(var(x) + ε) + β x: (C,), γ, β: (C,)
ε (1e-5 in GPT-2) stops a division by zero when every entry is equal.
Worked example, C = 4, γ = 1, β = 0:
x = [2, 4, 6, 8]
mean = 5, var = 5, std = 2.236
x − mean = [−3, −1, 1, 3]
÷ std = [−1.342, −0.447, 0.447, 1.342]
Add 100 to every entry, [102, 104, 106, 108], and LayerNorm gives exactly the
same answer. Multiply by 10, same answer. LayerNorm ignores where the vector
sits and how large it is; it keeps only its shape.
Note the direction: LayerNorm normalises across the C features of one
token, never across tokens or across the batch. Each token is normalised on
its own, which is why it works the same at training and inference and for any
batch size. (BatchNorm, common in vision, normalises across the batch. It is a
poor fit for language models, where batch statistics would mix tokens from
unrelated sequences.)
RMSNorm (Llama, Mistral, Qwen, nearly everything since 2023)
RMSNorm drops step 1 and the β. It divides by the root-mean-square and
nothing else:
RMSNorm(x) = γ · x / sqrt(mean(x²) + ε)
Same example:
x = [2, 4, 6, 8]
mean(x²) = (4 + 16 + 36 + 64) / 4 = 30, rms = 5.477
x ÷ rms = [0.365, 0.730, 1.095, 1.461]
The output is not centred: its entries are all positive, because the input's
were. RMSNorm fixes the size of the vector and leaves its offset alone. Add
100 to every entry and RMSNorm's answer changes, to
[0.971, 0.990, 1.009, 1.028]: nearly constant, because the offset of 100 now
dominates the vector.
Why RMSNorm won. Zhang and Sennrich (2019) found that the re-centring step
contributes little: models trained with RMSNorm match LayerNorm quality, and
the operation is cheaper (one reduction instead of two, no β). The cost
difference is real but small next to a matmul, and a fused LayerNorm kernel
narrows it further. We measure both the quality and the speed (§10d, §10e)
rather than repeat the claim.
What breaks without normalisation at all: the stream's scale drifts with depth, and the learning rate that suits layer 1 does not suit layer 20. We do not run that ablation separately; the post-norm experiment below shows what mis-placed normalisation does, which is the more interesting failure.
4. Pre-norm vs post-norm: where the norm goes
There are two ways to combine a norm with a residual.
post-norm (2017 paper, BERT) pre-norm (GPT-2, Llama, everything modern)
x ──┬──► f ──► (+) ──► Norm ──► out x ──┬──► Norm ──► f ──► (+) ──► out
└────────────┘ └──────────────────┘
out = Norm(x + f(x)) out = x + f(Norm(x))
They look like a minor rearrangement. They are not.
In post-norm, the norm sits on the highway. Every layer's output passes
through a normalisation before it reaches the next layer, and so does every
gradient on the way back. The clean 1 of §2 becomes "1, then rescaled by a
LayerNorm", 24 times over. The direct path from the loss to layer 1 exists, but
it is no longer clean.
In pre-norm, the highway is untouched. The norm sits on the side road that
feeds f. The stream itself is never normalised between blocks, so the
gradient at the top reaches the bottom through nothing but additions.
Xiong et al. (2020) analysed this at initialisation and found that in post-norm, the gradients of the last layers are large, which is why post-norm models need a careful learning-rate warmup and diverge without one. In pre-norm the gradient is well-behaved at every depth, and warmup matters much less.
The prediction for our experiment (§10b): at 4 layers, both train. At 24 layers with the same learning rate, pre-norm trains and post-norm struggles or diverges. We also measure the gradient reaching each layer at initialisation (§10a), which is where the difference starts.
What pre-norm costs. Two things, both honest:
- Because the stream is never normalised, the model needs one extra norm at
the very end, before the output head (
ln_fin GPT-2). Forget it and the head reads an un-normalised, depth-dependent scale. - The stream keeps growing with depth, so a late block's contribution is a smaller fraction of the total than an early block's. Some argue that deep pre-norm models make poor use of their last layers for this reason. It is a known trade-off, accepted because the alternative does not train.
5. The MLP: where most of the parameters live
The MLP (also called the FFN, feed-forward network) is two linear layers with a nonlinearity between them, applied to each token separately:
MLP(x) = W₂ · act(W₁ · x + b₁) + b₂
x: (B, T, C)
W₁: C → 4C (B, T, C) → (B, T, 4C) expand
act (B, T, 4C) bend
W₂: 4C → C (B, T, 4C) → (B, T, C) project back
Every token goes through the same weights, independently. No token sees any other inside the MLP; that is attention's job.
Size. Attention has four C × C matrices (q, k, v, output): 4C².
The MLP has C × 4C plus 4C × C: 8C². Two thirds of a block's weights
are in the MLP. At our C = 256: 262,144 in attention, 524,288 in the MLP.
Why 4×? It is the ratio the 2017 paper used, and nobody has found a reason to move far from it for dense models. There is no derivation behind it; it is a convention that works.
What the MLP is for, roughly. One interpretation (Geva et al., 2021) reads
each of the 4C hidden units as a pattern detector: a row of W₁ is a
"key" that fires on some pattern in the token's vector, and the matching column
of W₂ is the "value" written into the stream when it fires. Under this view
the MLP is a large key-value memory, and it is where much of a model's stored
knowledge seems to live. Treat this as a useful picture, not a proof.
What breaks without it: the block becomes attention only. Attention mixes existing vectors with weights that sum to 1; on its own it has very little capacity to transform what a token carries. We measure the damage (§10d).
6. Activation functions: ReLU → GELU → SwiGLU
Without a nonlinearity between W₁ and W₂, the two would collapse into one
matrix (W₂ W₁), and the MLP would be a single linear map. The activation is
what lets it compute something a matrix cannot.
Values at a few points (computed with PyTorch):
| x | −3 | −2 | −1 | −0.5 | 0 | 0.5 | 1 | 2 | 3 |
|---|---|---|---|---|---|---|---|---|---|
| ReLU | 0 | 0 | 0 | 0 | 0 | 0.50 | 1.00 | 2.00 | 3.00 |
| GELU | −0.004 | −0.046 | −0.159 | −0.154 | 0 | 0.346 | 0.841 | 1.954 | 2.996 |
| SiLU | −0.142 | −0.238 | −0.269 | −0.189 | 0 | 0.311 | 0.731 | 1.762 | 2.858 |
ReLU GELU SiLU
│ ╱ │ ╱ │ ╱
│ ╱ │ ╱ │ ╱
│ ╱ │ ╱ │ ╱
────┼╱───── ──────┼╱────── ─╮────┼╱──────
│ ╰─╯│ ╰──╯│
hard corner at 0 small dip below 0 deeper dip below 0
ReLU, max(0, x). Cheap and simple. Its weakness: for negative inputs the
gradient is exactly 0, so a unit pushed into the negative region for every
input stops learning for good (a "dead" unit).
GELU, x · Φ(x), where Φ is the normal distribution's cumulative
function. A smooth ReLU: almost 0 for very negative x, almost x for very
positive, and a gentle curve in between with a small negative dip. The
gradient is never exactly 0, so units do not die. GPT-2 uses it. GPT-2's
version is a tanh approximation (0.5x(1 + tanh(√(2/π)(x + 0.044715x³))),
called gelu_new in Hugging Face). It differs from the exact GELU by at most
about 0.0004 at the points above, but matching GPT-2's weights number for
number (§9) needs the same one.
SwiGLU (Shazeer, 2020; Llama and most models since). It changes the MLP's shape, not only the function. Instead of one expansion it makes two, and multiplies them:
SwiGLU-MLP(x) = W₂ · ( silu(W_gate · x) ⊙ (W_up · x) )
W_gate: C → h W_up: C → h W₂: h → C ⊙ is elementwise multiply
silu(z) = z · sigmoid(z)
The idea is a gate: W_up · x is the content, and silu(W_gate · x)
decides, unit by unit, how much of it gets through. The gate depends on the
input, so the MLP can switch units on and off per token.
Three matrices instead of two would mean 50% more parameters at the same
hidden size. To compare fairly, SwiGLU shrinks the hidden size to
h = (2/3) · 4C = 8C/3, which brings it back to ≈ 8C². At C = 256:
h = 682, parameters 3 · 256 · 682 = 523,776 versus 524,288 for the GELU MLP.
Within 0.1%.
Why does gating help? Honestly, nobody has a crisp answer. Shazeer's paper reported it worked better and wrote: "We offer no explanation as to why these architectures seem to work; we attribute their success, as all else, to divine benevolence." We measure whether it helps at our scale (§10d).
7. Dropout, and why it is usually 0 now
Dropout zeroes a random fraction p of activations during training (and
scales the survivors by 1/(1 − p) so the expected value is unchanged). At
inference it does nothing. Each step trains a slightly different sub-network,
which stops the model leaning too hard on any one unit.
Its purpose is to fight overfitting: memorising the training data instead of learning what generalises. That happens when a model sees the same examples many times.
Big pretraining runs see most of their data once. There is nothing to
memorise yet, so there is no overfitting for dropout to fight, and it only adds
noise to every step. GPT-2 (2019) used p = 0.1; Llama, and most large models
since, use 0. Our runs see each token at most about once, so the prediction is
that dropout makes our loss worse (§10d). It comes back in later stages
where data is small and repeated (SFT, Stage 16).
In a GPT-2 block, dropout sits in three places: on the attention weights, on
the attention output before the residual add, and on the MLP output before its
residual add. Our Block puts it on the two sublayer outputs, and leaves the
attention weights alone (our Stage 04 attention has no dropout); at p = 0
the two are identical.
8. One block, by the numbers
For C = 256, H = 4 (our test model), GELU MLP, LayerNorm, with biases:
| part | shapes | parameters |
|---|---|---|
ln1 |
γ, β: (C,) | 512 |
attention qkv |
(C, 3C) + bias 3C | 197,376 |
attention proj |
(C, C) + bias C | 65,792 |
ln2 |
γ, β | 512 |
MLP fc |
(C, 4C) + bias 4C | 263,168 |
MLP proj |
(4C, C) + bias C | 262,400 |
| block total | 789,760 |
The rule of thumb is 12C² per block (786,432 here); biases and norms add the
last 0.4%. A test asserts this count.
9. Checking ourselves against a reference
Two oracles, both from Hugging Face transformers and used only for
comparison:
GPT2Block. Copy its weights into our pre-norm, LayerNorm, GELU-tanh block and compare outputs. One trap: GPT-2's linear layers are aConv1Dclass that stores weights as(in, out), whilenn.Linearstores(out, in). Copying without a transpose gives the right shapes for square matrices and the wrong answer. Same lesson as the wrong reshape in Stage 04.LlamaMLPfor SwiGLU andnn.RMSNorm/LlamaRMSNormfor RMSNorm.
Plus nn.LayerNorm and F.gelu for the hand-written pieces.
10. Experiments
All training runs use the Stage 04 recipe so numbers are comparable:
C = 256, 4 heads of 64, learned positions, tied head, T = 256, B = 32,
4,000 steps (32.8M tokens, 85% code / 15% English), AdamW (β = 0.9, 0.95,
weight decay 0.1), peak learning rate 1e-3 with 100 warmup steps and cosine
decay to 10%, gradient clipping at 1.0, bf16 autocast. Metric: loss on 512
held-out code windows. The baseline is pre-norm, LayerNorm, GELU, no dropout,
4 layers: the Stage 04 d64 model.
10a. Gradients at initialisation (run.py grads)
Before training anything: three untrained 24-layer models (pre-norm,
post-norm, pre-norm with both residual adds removed), one real batch each
(B = 8, T = 256, fp32), averaged over 5 seeds. Three measurements per layer:
- the gradient norm reaching each block's weights;
- the size (rms) of the residual stream after each block;
- the mean cosine similarity between different positions of the same
sequence after each block. Near 0 means the tokens' vectors still differ.
Near 1 means every position carries the same vector, and the model can no
longer tell
forfromreturn.

| model (24 layers, untrained) | grad, block 1 | grad, block 24 | stream rms after block 24 | position cosine after block 24 |
|---|---|---|---|---|
| pre-norm | 2.21 | 0.38 | 0.67 | 0.69 |
| post-norm | 1.32 | 0.12 | 1.00 | 0.03 |
| pre-norm, no residual | 3.65 | 2.63 | 0.11 | 1.000 |
Source: results/05_block/grads.json.
The gradients did not vanish, in any of the three. §2 predicted that
without residuals the gradient reaching block 1 would shrink like 0.8^24.
Measured, the no-residual model has the largest gradients of the three,
and they are nearly the same at the bottom as at the top (3.65 vs 2.63). The
reason is the norm in front of every sublayer. LayerNorm's output size does
not depend on its input's size, and on the way back it divides the gradient by
the input's rms. Whenever a layer shrinks the signal, the next norm scales it
back up, in both directions. So the "product of small factors" never forms.
What did break is the last column. Without residuals, the positions' vectors become almost the same after one block (cosine 0.75), 0.989 by block 8, and 1.000 (to three places) from block 12 on. Each token's identity is gone. The cause is attention itself: at initialisation the scores are near zero, so each head takes close to a plain average of the tokens before it, and averages of overlapping sets are similar to each other. With a residual, the token's own vector rides along on the highway past every average. Without one, the average replaces it, 24 times. This is called rank collapse (Dong et al., 2021: attention without skip connections loses rank doubly exponentially with depth).
So the large gradients of the no-residual model are large and useless: they are the same for every position, because every position looks the same. The only thing such a model can learn is which tokens are common overall. §10c shows whether training rescues it.
Post-norm starts out calm. From block 2 on, every post-norm block gets the
almost the same gradient (0.119 to 0.122), and the tokens stay distinct (cosine 0.03). That
is the opposite of the "post-norm gradients misbehave at init" story in §4. The
reason is our small initialisation (std 0.02): each sublayer's output is tiny
next to the normalised stream (rms 1), so Norm(x + f(x)) ≈ x and the model
starts as a near-identity chain. Xiong et al. analysed a larger init, where
f(x) is as large as x. Whether post-norm stays calm once training grows
the weights is what §10b measures.
Pre-norm's lower blocks get the biggest gradients (2.21 at block 1, 0.38 at
block 24). The same LayerNorm effect: the stream starts tiny (the embedding's
rms is 0.028) and grows to 0.67, and the norm in front of each sublayer divides
the gradient by the size of the stream at that depth. Pre-norm's stream also
becomes more alike across positions (cosine 0.69 at the top). Each block adds
a similar averaged vector to every position, and the token's own embedding
(rms 0.028) is small next to those additions. It does not collapse to 1,
because the embedding is still in the sum. Stage 06's initialisation choices
(including scaling each block's output by 1/√(2·n_layer)) are partly about
this.
10b. Pre-norm vs post-norm at depth (run.py depth, run.py diagnose)
One seed per variant (a 24-layer run takes ~18 minutes; the failures are far larger than seed noise, which is ±0.012 at 4 layers). First, the plain comparison, with our usual small embeddings:
| 4 layers | 24 layers | |
|---|---|---|
| pre-norm | 2.685 | 2.567 |
| post-norm | 6.856 | 6.857 |
| pre-norm, no residual (§10c) | 6.856 | 6.856 |
Source: results/05_block/depth.json.
Post-norm failed at 4 layers as well as 24, and it did not diverge. No loss went to infinity. Every failed run reached about 6.9 by step 50 and sat there for the remaining 3,950 steps.
That number has a meaning. If a model ignores its input entirely, the best it can do is predict how common each token is in general. The cross-entropy of those plain token frequencies (from the 85/15 training mix) on the same 512 validation windows is 6.860. The failed models are at 6.856. They have learned the token frequencies and nothing else: not the previous token, not even the current one.
Why they get stuck there. The frequency answer is the same whatever the input is, a constant function. Once the top of the network outputs a near-constant, its derivative with respect to its input is close to zero, and that cuts the gradient to every block below. The gradient reaching block 1 in post-norm fell from 1.1 at step 0 to 2.7e-9 by step 1000 (4 layers) and 1.2e-12 (24 layers). The blocks that would have to learn to use context get no signal to learn from. The trap closes itself.
Why post-norm walks into it: the edits outgrow the highway. run.py diagnose logged, every 25 steps, the size of each sublayer's edit next to
the residual path it is added to, rms(f(x)) / rms(x).

- Post-norm (orange): edits start at 0.02-0.11 of the residual and grow to
2-24× by step 500. In post-norm every gradient passes through
Norm(x + f(x)), which divides it by the size ofx + f(x). When the edit dwarfsx, the path back to earlier layers shrinks by that factor at every sublayer. That is the clean1of §2 being crushed. - Pre-norm (blue): edits are even larger (up to 16× at block 1) and it does not matter, because no norm sits on the residual path. The gradient goes around the edits, not through them.
- Post-norm with the token embedding multiplied by
√C(green): the 2017 paper did this. Our embeddings start at rms 0.028; times√256 = 16they start at about 0.32. Both post-norm runs touch the frequency plateau near step 50 (edits 2.4×, block-1 gradient down to 6e-3). The√Crun climbs out by step 100: its edits shrink back to 0.3-0.6× and the gradient recovers. The small-embedding run never does.
So in our setup, the immediate cause of post-norm's failure was our small
embeddings. Stage 03 met √C as a way to balance token and position vectors;
it turns out to have been holding up post-norm too.
The fair depth test therefore uses the 2017 recipe (√C embeddings) for
both:
| (√C embeddings) | 4 layers | 24 layers |
|---|---|---|
| pre-norm | 2.685 | 2.469 |
| post-norm | 2.693 | 6.700 |
| post-norm, no warmup | 6.856 |

This is the result the curriculum predicted. At 4 layers post-norm trains as well as pre-norm (2.693 vs 2.685). At 24 layers it fails (6.700, barely below the frequency floor; the gradient at block 1 was 8e-12 from step 500 on), while pre-norm trains to 2.469. Without warmup, post-norm does not even leave the floor. Each extra post-norm sublayer is one more place where the gradient can be divided down; 48 of them are too many.
Two more measurements:
- A lower learning rate only slows the slide. Post-norm, 4 layers, small embeddings: lr 3e-4 → 3.822, lr 1e-4 → 4.698. Both escape the plateau but learn far more slowly than pre-norm at 1e-3 (2.685). This is post-norm's reputation: it can be trained, with care, and the care costs.
√Calso helped pre-norm at depth: 2.469 vs 2.567 at 24 layers (one seed each), and made no difference at 4 layers (2.685 vs 2.685). This fits §10a: in a deep pre-norm stack, a tiny embedding is swamped by 48 additions, and the positions start out too alike. Stage 06 revisits initialisation.
10c. Remove the residual (run.py depth)
No residual, pre-norm: 6.856 at 4 layers, 6.856 at 24. Both are at the frequency floor, the same as failed post-norm. The gradient to block 1 by step 1000 was 5e-10 (4 layers) and 3.8e-19 (24 layers).
Put this next to §10a. At initialisation, the gradients were healthy (3.65 at block 1) and the tokens were already indistinguishable (cosine 1.000). Once training starts, the model takes the only thing it can learn from inputs that all look the same, the token frequencies, and that constant answer cuts the gradient to zero. So the textbook story, "vanishing gradients", does happen, but second: rank collapse comes first and causes it.
Removing the residual cost more than anything else in this book so far: +4.17 loss. For comparison, removing position information entirely in Stage 03 cost +0.66.
10d. Norm, activation, MLP and dropout (run.py sweep)
Back to 4 layers and three seeds, changing one thing at a time from the baseline (pre-norm, LayerNorm, GELU, no dropout).

| variant | params | val loss (3 seeds) | vs baseline |
|---|---|---|---|
| baseline | 5,323,264 | 2.689 ± 0.012 | |
| RMSNorm | 5,320,960 | 2.712 ± 0.027 | +0.023 |
| ReLU | 5,323,264 | 2.714 ± 0.002 | +0.025 |
| SwiGLU | 5,316,096 | 2.651 ± 0.012 | −0.038 |
| no MLP | 3,220,992 | 2.959 ± 0.028 | +0.270 |
| no MLP, 12 layers (parameter-matched) | 5,334,528 | 2.909 ± 0.022 | +0.220 |
| dropout 0.1 | 5,323,264 | 2.775 ± 0.024 | +0.086 |
Source: results/05_block/sweep.json.
Cross-check. The baseline is the Stage 04 d64 model rebuilt from this
stage's parts, including our own LayerNorm in place of nn.LayerNorm.
Stage 04: 2.689 ± 0.012. Here: 2.689 ± 0.012.
SwiGLU is the clear win: −0.038 on every seed, with 7,168 fewer
parameters (no MLP biases, and h = 682 instead of 1,024). Of the "modern"
changes, this is the one that pays at our scale.
RMSNorm: no measurable difference. +0.023 with a seed spread of ±0.027. We read this as a tie, which is what Zhang and Sennrich reported. RMSNorm is adopted for its cost (§10e), not for quality.
ReLU is a little worse than GELU (+0.025), consistently (spread ±0.002).
The MLP is not optional. Without it, +0.270. Is that only because the model lost 2.1M parameters? The 12-layer attention-only model has the same non-embedding parameter count as the baseline (3.17M vs 3.16M), and is still +0.220 worse, and slower (350 s vs 250 s per run). Attention averages vectors that already exist; the MLP transforms each one. Spending the same parameters on more attention does not replace that.
Dropout hurts, as predicted: +0.086. It hurts training loss too (3.03 vs 2.86 at the last step), so this is not a trade of training fit for generalisation; it is just noise. Each token was seen once, there was nothing to overfit.
10e. Is RMSNorm faster? (run.py speed)
Forward + backward of one norm over 8,192 rows (8 × 1024 tokens), bf16, in
milliseconds. A C × C linear layer on the same input is shown for scale.
| C | LayerNorm (ours) | RMSNorm (ours) | nn.LayerNorm |
nn.RMSNorm |
LN (ours, compiled) | RMS (ours, compiled) | Linear C×C |
|---|---|---|---|---|---|---|---|
| 256 | 1.18 | 0.60 | 0.42 | 0.30 | 0.22 | 0.18 | 0.54 |
| 768 | 3.22 | 1.73 | 0.68 | 0.59 | 0.67 | 0.51 | 3.38 |
| 2048 | 9.52 | 5.23 | 1.89 | 1.89 | 1.91 | 1.73 | 14.73 |
| 4096 | 18.20 | 10.55 | 3.92 | 3.91 | 3.62 | 3.53 | 36.82 |
Source: results/05_block/speed.json.
- Written out in plain PyTorch, RMSNorm is ~1.8× faster than LayerNorm: fewer operations, and each one is a separate pass over memory. That showed in training: the RMSNorm runs took 228 s against 250 s, 9% of the whole run, because our hand-written norms are slow.
- As fused kernels, the gap mostly closes: 28% at
C = 256, nothing atC ≥ 2048. A norm reads and writes each number once either way; at that point memory traffic, not arithmetic, sets the time. - Either norm is small next to the matmuls at real widths: at
C = 4096, 3.9 ms against 36.8 ms for oneC × Cmatmul, and a block has the equivalent of twelve.
So "RMSNorm is cheaper" is true, and matters most where norms are not fused. Large models adopted it because it is never worse and sometimes cheaper, not because it is a big speed-up.
11. Build order and acceptance criteria
stages/05_block/block.py:LayerNorm,RMSNorm,gelu_tanh,MLP,SwiGLU,Block(configurable: norm, activation, pre/post, residual, dropout).stages/05_block/test_block.py.stages/05_block/model.py: the Stage 04 tiny model with ourBlock.stages/05_block/run.py:grads,depth,diagnose,sweep,speed,plot,summary.
Acceptance criteria (as tests):
- Our
LayerNormequalsnn.LayerNorm; ourRMSNormequalsnn.RMSNorm; outputs and gradients, to 1e-5. - LayerNorm output has mean 0 and variance 1 per token; RMSNorm output has mean square 1.
gelu_tanhequalsF.gelu(approximate="tanh").- Our pre-norm GELU block with GPT-2 weights copied in equals HF
GPT2Block. - Our
SwiGLUequals HFLlamaMLP; its parameter count is within 1% of the GELU MLP's. - A block whose two output projections are zero is the identity (the residual passes the input through).
- The block is causal: changing a future token changes no earlier output.
- Block parameter count equals the table in §8.
12. What we found
Dated entries in docs/JOURNAL.md (2026-11-06). The short version:
| What | Number | Lesson |
|---|---|---|
Our block vs HF GPT2Block |
equal to 1e-5 | Needs Conv1D transposed, the tanh GELU, and a mask the block does not build itself. |
| Our LayerNorm in a real run | 2.689 ± 0.012, = Stage 04 exactly | Hand-written pieces must match in training too. |
| No residual, untrained, 24 layers | gradients flat (3.65 → 2.63); position cosine 1.000 by block 12 | The tokens merge before any gradient vanishes. |
| No residual, trained | 6.856 at 4 and 24 layers = token-frequency loss 6.860 | Rank collapse leads to a constant answer, and the gradient dies after it. |
| Post-norm, small embeddings | 6.856 at 4 and 24 layers | Edits grew to 2-24× the residual; gradient to block 1 fell to 1e-9. |
Post-norm, √C embeddings |
2.693 at 4 layers, 6.700 at 24 | The curriculum's claim, once the 2017 recipe is complete. |
| Pre-norm at 24 layers | 2.567 (2.469 with √C) |
The design that does not care how big the edits get. |
| SwiGLU | −0.038, fewer parameters | The modern change that pays at our scale. |
| RMSNorm | +0.023 ± 0.027 (a tie); 1.8× faster unfused, equal fused at C ≥ 2048 | Adopted for cost, not quality. |
| No MLP (parameter-matched) | +0.220 | Attention cannot stand in for the MLP. |
| Dropout 0.1 | +0.086, train loss worse too | Nothing to overfit on single-pass data. |
| Tied model, targets = inputs | 8.46 vs 9.07 at step 0 | A copy-input bug looks like learning in a tied model. |
The habit this chapter teaches: know the number that means "learned nothing". For our data it is 6.86, the loss of predicting token frequencies. Three different broken models landed on it to three decimal places. A run that plateaus there is not slow; it is broken, and the fix is in the architecture, not in more steps.
The second habit: a recipe is a bundle. Post-norm worked in 2017 inside a
recipe that also scaled embeddings by √C and used warmup. Take one part away
and another stops working, silently. Pre-norm is popular partly because it
does not depend on the rest of the recipe being right.
Chapter 8
Assembling GPT
Stages 03 to 05 built the parts: token and position embeddings, attention, the block. This stage puts them together into one complete model, the GPT class, and proves it is right in the strongest way available to us: we load OpenAI's real GPT-2 weights into our own code and check that it produces the same numbers Hugging Face's GPT-2 does.
Once that check passes, every later stage can trust the model. A bug found in Stage 11 after 40 hours of training will not be "is the model even wired correctly?", because this stage answered that.
Five things are new here:
- the whole forward pass, from token ids to a loss;
- the shift between inputs and targets, which is the entire trick that turns "a network" into "a language model";
- counting parameters by hand, per component, and matching the count;
- initialisation: why every weight starts at std 0.02, and why some start smaller;
- loading someone else's weights, which is where naming and layout bugs live.
Shape letters as before: B batch, T tokens, C model width, H heads,
L layers (blocks), V vocabulary size.
1. The picture
token ids (B, T) e.g. [[ 563, 1029, 40, 8192, ...]]
│
▼
wte[ids] (B, T, C) token embedding: one row per id (Stage 03)
+
wpe[0..T-1] (T, C) learned position embedding, broadcast (Stage 03)
│
▼
┌─────────┐
│ block 1 │ LayerNorm → attention → add (Stage 04-05)
│ block 2 │ LayerNorm → MLP → add
│ ... │
│ block L │
└─────────┘
│ (B, T, C) the residual stream
▼
ln_f one last LayerNorm (pre-norm needs it, Stage 05 §4)
│
▼
lm_head (B, T, V) logits: one score per vocabulary entry, per position
│ (weights tied to wte: the same table, read backwards)
▼
cross-entropy against the ids shifted left by one → one number, the loss
Every piece except the last line has been built and tested already. This stage adds the outer frame and the loss, and names everything the way GPT-2 does so real weights drop in.
2. The shift: the whole autoregressive trick
A language model is trained to answer one question at every position: given the tokens so far, what comes next?
Take a 5-token window from the data:
data: def add ( a ,
position: 0 1 2 3 4
We feed the first four tokens as input and ask for the last four as targets:
input: def add ( a ids[:, :-1] (B, T)
target: add ( a , ids[:, 1:] (B, T)
At position 0 the model sees def and must predict add. At position 1 it
sees def add and must predict (. And so on. One window of T+1 tokens
gives T separate training examples, all computed in one forward pass.
Two things make this work, and both are required:
- The shift. Target at position
tis the token att+1. - The causal mask (Stage 04 §4). Position
tcannot see positions aftert. Without it, position 0 could look at position 1, which is its target.
What breaks without the shift? If target = input, position t is asked to
predict the token it is already looking at. The model learns to copy its input,
which is trivially easy: the loss heads towards zero. Then you try to generate
text, and it has never learned to predict anything new. We do this on purpose
in §8c and measure it.
What breaks without the mask, keeping the shift? Position t attends to
t+1 and copies it. Same disaster, different route. Stage 04 already showed
this as a test.
The loss is the average of the B × T per-position cross-entropies:
logits (B, T, V) ─flatten→ (B·T, V)
targets (B, T) ─flatten→ (B·T,)
loss = mean over B·T of −log softmax(logits)[target]
At initialisation every logit is near zero, so softmax is close to uniform
and the loss is ln V. For our 8,196-token vocabulary that is 9.01; for
GPT-2's 50,257 it is 10.82. A first-step loss far from ln V means
something is wrong before training even started. (Stage 05 found one such
thing: a tied head nudges the loss down to 8.46 if you accidentally feed the
inputs as targets.)
3. Counting parameters by hand
A parameter count you cannot reproduce on paper is a number you do not
understand. Here is GPT-2 small: V = 50,257, C = 768, L = 12,
T_max = 1,024.
| Part | Formula | GPT-2 small |
|---|---|---|
token embedding wte |
V·C |
38,597,376 |
position embedding wpe |
T_max·C |
786,432 |
| per block: 2 LayerNorms | 2 · 2C |
3,072 |
per block: attention c_attn (q, k, v) |
C·3C + 3C |
1,771,776 |
per block: attention c_proj |
C·C + C |
590,592 |
per block: MLP c_fc |
C·4C + 4C |
2,362,368 |
per block: MLP c_proj |
4C·C + C |
2,360,064 |
| one block | 12C² + 13C |
7,087,872 |
| all 12 blocks | L(12C² + 13C) |
85,054,464 |
final LayerNorm ln_f |
2C |
1,536 |
output head lm_head |
tied: 0 | 0 |
| total | 124,439,808 |
This is the "124M" in GPT-2 124M.
Three things to notice:
- The
12C²rule. Attention has fourC×Cmatrices (q, k, v, out); the MLP has twoC×4Cmatrices, which is eight. Four plus eight is twelve. Every bias and norm together is13C, which is 0.14% of a block atC = 768. - The embedding is 31% of GPT-2 small. 38.6M of 124.4M parameters are the
token table. At small sizes the vocabulary dominates. This is why our 8,196
vocabulary was worth choosing carefully (Stage 01 §9): with GPT-2's 50,257,
a 30M-parameter model would spend 13M of it on the table at
C = 256. - Tying saves
V·C. An untied head would add another 38.6M, a 31% increase, for a matrix that holds the same kind of information aswte(Stage 03 §2).
Non-embedding parameters. Scaling-law papers (Stage 10) count parameters without the embeddings, because the table costs memory but almost no compute per token (a lookup is not a matmul). GPT-2 small has 85.1M non-embedding parameters. Keep both numbers in mind: memory sees all 124M, FLOPs mostly see 85M.
Our own Stage 05 model, V = 8,196, C = 256, L = 4, T_max = 256:
wte 8196·256 = 2,098,176
wpe 256·256 = 65,536
blocks 4·(12·256² + 13·256) = 3,159,040
ln_f 2·256 = 512
total = 5,323,264
The training runs in Stage 05 reported exactly 5,323,264. The test in this
stage checks the formula against sum(p.numel()) for several shapes, so the
two can never drift apart.
4. Initialisation
Before training, every weight needs a starting value. "Random" is not enough; the size of the random numbers decides whether training starts at all.
4a. Why std 0.02
GPT-2 draws every linear and embedding weight from a normal distribution with standard deviation 0.02, and sets biases to zero and LayerNorm gains to one.
Where does 0.02 come from? A common rule (Xavier/Glorot) says a C → C matmul
keeps its input's size if weights have std 1/√C. At C = 768 that is
0.036; at C = 1,600 (GPT-2 XL) it is 0.025. So 0.02 is "a bit smaller
than Xavier for every GPT-2 size", fixed once instead of recomputed per width.
It is a convention that works, not a law.
Why it matters: the LayerNorm before each sublayer rescales the input to size 1 anyway (Stage 05 §3), so the exact weight size mostly decides how large each block's edit to the residual stream is. Small edits on a stream of size ~0.03 (the embedding) keep every block close to the identity at the start, which is the calm starting point Stage 05 measured for pre-norm.
4b. The residual-scaled init: std = 0.02 / √(2L)
Each block adds two things to the residual stream: the attention output and the
MLP output. After L blocks, 2L random contributions have been summed.
Sums of independent random numbers grow: the variance adds up, so the
standard deviation grows like √(number of terms). With 2L additions of
size s each:
rms(stream after L blocks) ≈ √( rms(embed)² + 2L · s² )
At L = 12, that is 24 additions, a √24 ≈ 4.9× growth in the part of the
stream that came from the blocks. At L = 48 (GPT-2 XL), √96 ≈ 9.8×.
GPT-2's fix: scale the init of the two layers that write into the residual
stream (attention's c_proj and the MLP's c_proj) by 1/√(2L). Then the
total added variance is 2L · (s/√(2L))² = s², the same as one layer's
worth, whatever the depth.
std(c_proj) = 0.02 / √(2L)
L = 4 → 0.0071
L = 12 → 0.0041
L = 48 → 0.0020
Why only those two? They are the last matmul before the +. Every other
weight's output goes through a norm or a nonlinearity before reaching the
stream, so its size is partly corrected on the way.
What breaks without it? In theory, a deep pre-norm network starts with a residual stream dominated by noise from the blocks rather than the token embedding, and the later blocks each see a slightly bigger stream, so their relative edits are smaller (pre-norm divides by the stream size on the way back, Stage 05 §4). In practice, for 12 layers at our scale, we predict the effect is small: Stage 05 trained 24 pre-norm layers without it. §8b measures both the starting stream and the final loss.
4c. What we do not do
The 2017 paper multiplied token embeddings by √C (Stage 05 §10c). GPT-2 does
not, and we do not either: with pre-norm, Stage 05 measured that it made no
difference (2.6852 → 2.6850 at 4 layers), and post-norm was the only design
that needed it.
5. Names, so real weights fit
Loading weights means matching every one of our tensors to one of theirs, by name and by shape. The simplest way to make that boring and safe is to use GPT-2's names in our own module:
transformer.wte.weight (V, C) token embedding
transformer.wpe.weight (T_max, C) position embedding
transformer.h.{i}.ln_1.weight/bias (C,)
transformer.h.{i}.attn.c_attn.* (C, 3C) q, k, v together
transformer.h.{i}.attn.c_proj.* (C, C)
transformer.h.{i}.ln_2.weight/bias (C,)
transformer.h.{i}.mlp.c_fc.* (C, 4C)
transformer.h.{i}.mlp.c_proj.* (4C, C)
transformer.ln_f.weight/bias (C,)
lm_head.weight (V, C) = wte.weight (tied)
Hugging Face's file stores names without the transformer. prefix. Three
traps, two of which Stage 05 already met:
Conv1Dstores weights transposed. GPT-2's original code used a "1-D convolution" that is a linear layer storing its weight as(in, out). PyTorch'snn.Linearstores(out, in). Everyc_attn,c_projandc_fcweight needs.T. The squarec_projin attention is the dangerous one:(768, 768)transposed has the same shape, so a missing.Traises no error and gives wrong numbers.- The mask is stored as a weight. Older checkpoints carry
attn.biasandattn.masked_bias: not biases, but the causal mask saved as a buffer. They are not parameters and must be skipped. - The head is tied. The file has no separate
lm_head.weight, or has one equal towte. Copyingwteand pointing the head at it is enough.
The loader in this stage refuses to finish if any of our parameters was not filled, or any of theirs was not used. Silent partial loads are the classic bug: a model with one block left at random init still produces plausible- looking logits.
6. What "the same numbers" means
Our model and Hugging Face's are different code doing the same arithmetic in a different order. In float32 they will not match bit for bit. Each matmul rounds differently; 12 blocks of that compounds.
The test therefore asks for agreement within a tolerance, on real text:
- max absolute difference of the logits below
1e-3(logits are of size ~100 for GPT-2, so this is a relative error near1e-5); - the same loss to 4 decimal places;
- the same argmax at every position.
A wrong transpose or a missing layer gives differences of size 1 to 100, not
1e-4. The gap between "rounding" and "bug" is several orders of magnitude,
which is what makes this test useful.
7. Build order and acceptance criteria
stages/06_gpt/gpt.py holds the explicit version. llmfs/model/gpt.py holds
the same model in the form every later stage imports.
GPTConfigdataclass:vocab_size, block_size, n_layer, n_head, n_embd, tie, scaled_init, flash.GPTwith GPT-2's module names, our LayerNorm and attention.count_params_by_hand(cfg)from the table in §3.GPT.from_pretrained("gpt2")reading the safetensors file directly.
Acceptance criteria (as tests in stages/06_gpt/test_gpt.py):
- hand count = actual count, for GPT-2 small and five other shapes, tied and untied;
- GPT-2 small with real weights: logits match HF
GPT2LMHeadModelwithin1e-3, loss to 4 decimals, identical argmax; - the loader fails loudly on a missing or extra tensor;
- initial loss within 0.1 of
ln Vwith random targets; c_projweights have std0.02/√(2L)whenscaled_initis on;- the manual attention path and the
flash(SDPA) path agree to1e-5; - causality: changing token
t+1does not change logits att.
8. Experiments
8a. GPT-2 reproduced
GPT.from_pretrained("gpt2") builds our class, reads OpenAI's safetensors
file and copies 148 tensors in (four transposed per block, the mask buffers
skipped). On the test sentence in test_gpt.py (CPU, float32), our logits
match Hugging Face's GPT2LMHeadModel within 1e-3, with the same argmax at
every position and the same loss to 1e-4.
Then we ran both on 200 windows of our own validation code (about 650 GPT-2 tokens each), on the GPU. The largest logit difference was 0.055. That is 50 times the test tolerance, so it looked like a bug.
It is not one. The same windows in float64 differ by 2e-11: the two implementations compute the same function. In float32 our model is 0.015 away from its own float64 answer on the worst window, and so is Hugging Face's. The cause is what GPT-2 keeps in its residual stream:
max |value| in the residual stream, worst window, per block
embed 1 2 3 4 5 6 ... 11 12 after ln_f
4.5 114 604 2479 2650 2796 2893 ... 3021 3023 405
From block 3 on, a few dimensions hold values near 3,000, while typical
values are around 1. Float32 keeps about 7 significant digits, so a number
near 3,000 is stored to about 3e-4. Every matmul that reads the stream
inherits that, and 12 blocks of different summation orders add it up. These
are massive activations (Sun et al. 2024): a handful of fixed dimensions
that trained transformers use as large constant offsets. They come back in
Stage 21, where they are why naive int8 quantization of activations fails.
The lesson for the test: a tolerance that holds on short text can fail on long
real text for a reason that is not a bug. The check that separates the two is
float64. Agreement to 1e-11 there means the arithmetic is identical.
GPT-2's score on our data. Loss per token cannot be compared across tokenizers (GPT-2's 50,257 tokens are not ours), but bits per byte can: total loss in bits divided by the bytes of text predicted. On the same 200 decoded windows:
| GPT-2 124M (WebText) | bytes per token, ours | |
|---|---|---|
| our val code | 1.394 bits/byte | 3.13 |
| our val English (FineWeb-Edu) | 1.064 bits/byte | 3.35 |
GPT-2 finds our English much easier than our code: WebText had little code. §8d compares our own small model on identical text.
8b. Residual-scaled init
At initialisation, one real batch, size of the residual stream (rms) after each block:
embed block 1 block 4 block 8 block 12 block 48
L=12, plain 0.028 0.117 0.256 0.383 0.474 -
L=12, scaled 0.028 0.036 0.055 0.074 0.090 -
L=48, plain 0.028 0.115 0.251 0.374 0.467 0.933
L=48, scaled 0.028 0.030 0.037 0.043 0.049 0.089
With plain std 0.02 everywhere, the blocks' contributions swamp the token
embedding immediately: after one block the stream is 4× its starting size, and
after 12 blocks 17×. The token's own identity is a small fraction of what the
upper blocks see. With the 1/√(2L) scaling, the stream grows 3.2× over 12
blocks and also 3.2× over 48: the depth-independence the derivation in §4b
promised. (It is not the "one layer's worth" growth exactly, because attention
outputs are not independent of each other, but the scaling with L is gone.)
After training, 12 layers, 4,000 steps, two seeds each:
| init | seed 0 | seed 1 | mean |
|---|---|---|---|
| plain std 0.02 | 2.5927 | 2.5698 | 2.581 |
scaled 0.02/√24 |
2.5632 | 2.5734 | 2.568 |
A 0.013 advantage for the scaled init, about the size of the seed-to-seed spread (0.010-0.023). As predicted in §4b: at 12 layers, pre-norm absorbs the difference. The scaled runs were ahead early (step 100: 5.86/5.89 vs 6.05/6.05) and the gap closed. We keep the scaled init because it costs nothing and its benefit grows with depth, not because we measured a big win.

8c. No shift
Same 4-layer model, 1,000 steps, with target = input instead of the next
token:
| train loss at step 1000 | next-token val loss | copy-task val loss | |
|---|---|---|---|
| no shift | 0.0001 | 21.86 | 0.0003 |
| with shift (normal) | 4.31 | 4.09 | - |
Without the shift, the loss collapses to zero by step 700: copying the token
you can see is trivial. On the real task, predicting the next token, the
same model scores 21.86, far worse than guessing uniformly (9.01). It is
confidently wrong: it puts nearly all its probability on the current token,
which is almost never the next one. Its greedy output from def add(a, b):
is the last token of the prompt (an indent) repeated forever. The normal model
at the same 1,000 steps already writes def get_to_to_to...: bad, but
next-token bad.
The starting loss of the no-shift run was 7.90, not 9.01: Stage 05's tied-head effect again (an untied model's logit for its own input token is not favoured; a tied one's is).

8d. Tied vs untied head
The 4-layer model, C = 256, with and without a separate output matrix:
| params | val loss, 4,000 steps | val loss, 12,000 steps | |
|---|---|---|---|
| tied | 5,323,264 | 2.6814 | 2.3577 |
| untied | 7,421,440 (+39%) | 2.7576 (+0.076) | 2.3608 (+0.003) |
The untied head adds V·C = 2,098,176 parameters, 39% more, and at 4,000
steps it is clearly worse: +0.076, the same gap Stage 03 measured (2.523
vs 2.598, +0.075). Stage 03 left open whether that gap was a lasting cost or
slow learning. At three times the training, it shrinks to 0.003, inside
seed noise. So it is slow learning: an untied output matrix starts random and
must learn, from scratch, a table that a tied model gets for free from its
input embeddings. Given enough steps, it catches up, but no further. Tying is
the right default for small models on a budget: same final quality, 2.1M
fewer parameters, and much faster early progress.
Ours vs GPT-2 on the same text. Bits per byte on identical 256-token
windows (run.py bpb):
| bits per byte, 256-token windows | GPT-2 124M | ours, 5.3M, 12k steps |
|---|---|---|
| our val code | 1.522 | 1.066 |
| our val English | 1.122 | 1.774 |
Our model has 23× fewer parameters and was trained for 12 minutes, and it spends 30% fewer bits on our code than GPT-2. On English, GPT-2 is far ahead. Neither result is surprising once said out loud: GPT-2 saw 40 GB of web text and very little Python; ours saw ~100M tokens drawn 85% from this code distribution (the val split is held out, but from the same sources). Specialisation beats size on the specialist's home ground. It is also a warning for later stages: a small in-domain model can look strong on in-domain loss and still know almost nothing. (These windows are shorter than §8a's, so GPT-2's numbers here are higher: less context per prediction.)
9. What we found
| Question | Answer, measured |
|---|---|
| Does our GPT equal GPT-2? | Yes. Logits match HF within 1e-3 on short text; on long real text the fp32 gap reaches 0.055, and float64 shows it is rounding (2e-11) |
| Why the fp32 gap? | GPT-2's residual stream holds values near 3,000 from block 3 on: massive activations |
| Does the hand count hold? | 124,439,808 for GPT-2 small; equal to numel() for 10 shapes, tied and untied |
| What does the scaled init change? | At init, stream growth over depth goes from 17× (12 layers) / 33× (48) to 3.2× at both. After training, 12 layers: −0.013, within seed noise |
| What happens without the shift? | Train loss → 0.0001; next-token loss 21.86, worse than uniform (9.01); greedy output repeats the last token |
| Tied vs untied? | Untied: +39% parameters, +0.076 worse at 4k steps, +0.003 at 12k. The Stage 03 penalty is slow learning, not a lasting cost |
| Ours vs GPT-2? | On our code, our 5M model needs 1.07 bits/byte, GPT-2 124M 1.52. On English, GPT-2 wins 1.12 to 1.77 |
Two habits from this stage:
- When implementations disagree, go to float64 before going bug-hunting. The difference between "rounding" and "bug" is many orders of magnitude, but only once rounding is taken out of the picture.
- Quote numbers from results files, not memory. The first draft of §4c misquoted a Stage 05 result by 25× (journal).
Chapter 9
Making it talk: generation and decoding
Until now our models have only ever been scored: give it text, measure how surprised it is. A language model is only useful once it writes. This stage turns the model's output, a score for every vocabulary entry, into text. It also makes that fast, using the KV cache.
What is in this stage:
- the autoregressive loop: predict one token, append it, repeat;
- greedy decoding and why it goes wrong;
- temperature, top-k, top-p and the repetition penalty: the knobs on every LLM API;
- the KV cache: why the simple loop redoes almost all its work, how to stop that, and what it costs in memory;
- prefill vs decode, the two phases that Stage 23 builds on.
Shape letters: B batch, T tokens, C width, H heads, d = C/H, L
layers, V vocabulary.
1. The loop
The model gives, at every position, a score (a logit) for every possible next token. To write, we only need the scores at the last position:
prompt ids [def, ␣add, (, a] (1, 4)
model → logits (1, 4, V)
take last → logits[:, -1] (1, V) "what follows 'a'?"
pick a token → "," how? §2-§5
append → [def, ␣add, (, a, ,] (1, 5)
model again → logits (1, 5, V) ...
One token per step, each step feeding on everything written so far. That is what autoregressive means: the output becomes the next input.
When does it stop? Three reasons, checked every step:
- the model picks the end-of-text token (id 8192 for us);
- a length limit is reached (
max_new_tokens, or the position table runs out: our models have learned positions only up toblock_size); - a stop string appears (for code: a blank line followed by
def, which means the function is finished).
2. Greedy: always take the top score
The obvious choice: pick argmax(logits), the single most likely token. It is
deterministic and needs no random numbers.
It is also bad, in a specific way. A model trained on lots of text knows that
after return x a newline is likely, after the newline return is likely
again... The most likely next token, chosen again and again, falls into
loops:
def get_to_to_to_to_to_to_to_to_to_to_to_to_to_to ...
That line is real. It is the greedy output of our 1,000-step Stage 06 model.
Why loops? Once a phrase has appeared, the model's own context makes it more likely to appear again: repeating what is in the context is one of the first patterns a language model learns (Stage 04 found a "previous-token" head early). Greedy has no way to step off the loop, because there is no randomness to step off with.
There is a deeper reason too. The single most likely sequence is not a typical sequence. Human text is full of slightly surprising words. Always choosing the least surprising one gives text that is flat and repetitive, and nothing like the text the model was trained on.
3. Sampling, and temperature
Instead of taking the top token, draw one at random, with each token's chance equal to its softmax probability:
p = softmax(logits) (V,) sums to 1
next = random choice with probabilities p
Now a token with probability 0.3 is chosen 30% of the time. The output looks like the training data, surprises included.
Temperature controls how adventurous the draw is. Divide every logit by a
number τ before the softmax:
p = softmax(logits / τ)
A worked example with three tokens, logits [2.0, 1.0, 0.0]:
| τ | logits / τ | probabilities |
|---|---|---|
| 0.1 | [20, 10, 0] | [1.0000, 0.0000, 0.0000] |
| 0.5 | [4, 2, 0] | [0.867, 0.117, 0.016] |
| 1.0 | [2, 1, 0] | [0.665, 0.245, 0.090] |
| 2.0 | [1, 0.5, 0] | [0.506, 0.307, 0.186] |
- τ → 0: the top token takes all the probability. This is greedy.
- τ = 1: the model's own distribution, unchanged.
- τ → ∞: every token equally likely. Pure noise.
Why dividing works: softmax depends only on differences between logits. Dividing by τ shrinks (τ > 1) or stretches (τ < 1) every difference by the same factor.
What breaks at each end? Low temperature brings back greedy's loops. High temperature samples tokens the model thinks are nearly impossible. One bad token derails everything after it, because each step feeds on the last. §8c catalogues both on our model.
4. Top-k and top-p: cut off the tail
Even at τ = 1 there is a problem. A vocabulary of 8,196 tokens has thousands of tokens that each get a tiny probability, say 0.00005. Individually they almost never get picked. Together they can hold 5-10% of the probability, so roughly every 15th token is drawn from "things the model thinks are nonsense".
The fix is to delete the tail before drawing.
Top-k: keep the k highest-scoring tokens, set the rest to -∞, then
softmax.
logits [5.1, 4.9, 2.0, 1.1, 0.3, ...] k = 2
kept [5.1, 4.9, -∞, -∞, -∞, ...] → only two tokens can be drawn
The weakness: a fixed k is wrong in both directions. After import there
may be 200 sensible next tokens; after for i in ran there is one (ge).
k = 40 cuts off good options in the first case and lets 39 bad ones in the
second.
Top-p (nucleus sampling), Holtzman et al. 2019: sort tokens by
probability, keep the smallest set whose probabilities add up to at least
p, drop the rest.
sorted probs 0.62 0.21 0.09 0.04 0.02 ... p = 0.9
running sum 0.62 0.83 0.92 ...
kept ✓ ✓ ✓ (0.92 ≥ 0.9, stop) → 3 tokens
When the model is confident, the nucleus is one or two tokens. When it is unsure, the nucleus is wide. The cut adapts to the situation, which top-k cannot do.
An implementation detail that is easy to get wrong: the token that crosses
the threshold must be kept. Otherwise a single token with probability 0.95
would be dropped at p = 0.9, leaving nothing. The test checks this case.
5. The repetition penalty
A blunt instrument against loops (Keskar et al. 2019, the CTRL paper): for every token already in the context, make its logit less attractive:
logit > 0 → logit / penalty
logit < 0 → logit · penalty penalty ≈ 1.1 – 1.3
The two cases exist because dividing a negative logit by 1.2 would move it up, making it more likely. Multiplying moves it down.
For code this needs care. Code is supposed to repeat: variable names,
self, indentation, closing brackets. A strong repetition penalty makes a
model avoid writing x a second time in x = x + 1. We measure it rather
than assume it helps.
6. The KV cache
6a. The waste in the simple loop
Each step of the loop in §1 runs the model on the whole sequence so far, then throws away everything except the last position's logits. To write token 500, it recomputes attention, MLPs and everything else for tokens 1-499, exactly as it did one step earlier.
Count the work. Writing N tokens one step at a time processes
1 + 2 + ... + N ≈ N²/2 token-positions in total, where only N were needed.
At N = 512 that is 256× more positions than necessary.
6b. What actually changes between steps
Look at what a new token needs. In each layer, its query q must be compared
with the keys k of every earlier token, and it averages their
values v (Stage 04 §2). The earlier tokens' keys and values do not
change when a new token arrives. The causal mask guarantees it: no token
can look forward, so nothing about token 3 depends on token 500.
So we can compute each token's k and v once, store them, and reuse
them forever. That store is the KV cache.
step t (one new token):
x_t (B, 1, C)
q_t, k_t, v_t = c_attn(x_t) only the new token's three vectors
cache.k[:, :, t] = k_t append
cache.v[:, :, t] = v_t
attend q_t over cache.k[:, :, :t+1] (B, H, 1, d) vs (B, H, t+1, d)
→ one row of attention, not a T×T matrix
The queries are not cached: each query is used once, by its own token, at the step it is made.
6c. Prefill and decode
Generation now has two phases:
- Prefill. Run the whole prompt at once (an ordinary forward pass over
Ttokens), filling the cache. Many tokens at a time keeps the GPU busy: this phase is limited by compute. - Decode. One token per step. Each step does very little arithmetic
(
Btokens, notB·T), but must read every weight and the whole cache from GPU memory. This phase is limited by memory bandwidth, not arithmetic.
That split is the central fact of LLM serving (Stage 23). Time to first token is mostly prefill; time per output token is mostly decode.
6d. What the cache costs
Per token, the cache holds one k and one v vector of width C per layer:
bytes per token = 2 (k and v) · L · C · bytes per number
| Model | L | C | per token (bf16) | 1,024 tokens | 32k tokens |
|---|---|---|---|---|---|
| ours, Stage 05 | 4 | 256 | 4 KB | 4 MB | 128 MB |
| workhorse | 8 | 512 | 16 KB | 16 MB | 512 MB |
| GPT-2 small / capstone | 12 | 768 | 36 KB | 36 MB | 1.1 GB |
| Llama 2 7B (MHA) | 32 | 4096 | 512 KB | 512 MB | 16 GB |
For a 7B model at long context, the cache is bigger than the weights. That is why Stage 12's GQA and Stage 14's MLA exist: both shrink this number.
6e. A subtle trap: the outputs must be identical
A KV-cache decoder is the same mathematics as the simple loop, reorganised. At a fixed random seed it must produce the same tokens. If it does not, the cache has a bug. The most common ones:
- the new token gets position 0 instead of position
t(positions must come from the cache length, not from the new chunk's length); - the causal mask during a multi-token prefill after a cache already exists (each new query must see the old keys plus the new ones up to itself);
- writing into the cache at the wrong offset.
Floating point is the honest caveat. Computing attention for one query
against t keys sums numbers in a different order than computing it as one
row of a T×T matrix, so the logits differ at the 1e-6 level. With greedy
decoding that almost never changes a token. With sampling it can, if a random
draw lands right on a boundary. The test compares logits within a tolerance,
and the experiment compares sampled tokens at a fixed seed.
7. Build order and acceptance criteria
stages/07_generation/sample.py (the explicit version), with the cache in
llmfs/model/gpt.py (KVCache, forward(..., cache=...)).
apply_temperature,top_k_filter,top_p_filter,apply_repetition_penalty,sample_next;generate_naive(model, ids, n): the loop of §1;generate_cached(model, ids, n): prefill then decode with the cache.
Acceptance criteria (test_sample.py):
- temperature matches the worked table in §3;
- top-k keeps exactly k tokens; top-p keeps the crossing token, and a single 0.95 token survives p = 0.9;
- repetition penalty moves negative and positive logits both down;
- cached logits equal full-recompute logits within 1e-4 at every step;
- cached and naive generation give identical tokens greedily, and at a fixed seed with sampling;
- generation stops on end-of-text.
8. Experiments
8a. KV-cache speedup
Randomly initialised models (speed does not depend on training), batch 1,
fp32, a 16-token prompt, greedy decoding to the total length shown. The
naive loop already uses last_only (it only computes the output head for the
last position), so the comparison isolates the cache.
| model | length 128 | 256 | 512 | 1,024 | cached tokens/s |
|---|---|---|---|---|---|
| 4 layers, C=256 (5M) | 0.94× | 0.90× | 1.27× | 2.28× | ~1,420 at every length |
| 8 layers, C=512 (30M) | 1.27× | 1.96× | 3.32× | 5.51× | ~750 → 655 |
| 12 layers, C=768 (92M) | 1.97× | 2.85× | 4.47× | 7.23× | ~427 → 306 |
At every one of the 36 settings, the cached decoder produced exactly the same tokens as the naive loop, greedy and sampled at a fixed seed.
The curriculum's expectation of "5-20× at length 512" is not met: we see 1.3×
to 4.5×. The reason is in the last column. For the 4-layer model, cached
decoding runs at ~1,420 tokens/s whatever the length: 0.7 ms per token, a
fixed cost. That is the cost of launching dozens of small GPU kernels from Python
for one token, not of doing arithmetic. The naive loop, meanwhile, recomputes
up to 1,024 positions per step, but a GPU processes 1,024 positions of a
5M-parameter model almost as fast as one: it was idle anyway. So the
"wasted" N²/2 work of §6a is real, but at this size it is nearly free,
and the cache saves something that was barely costing anything.
The speedup grows with the model (more arithmetic per position, so recomputation hurts more) and with length (more positions to recompute). The 92M model at length 1,024 gets 7.2×. For a 7B model the cached step is dominated by reading the weights, and the cache's advantage is the 10-100× of the textbook. Stage 09 (fused kernels) and Stage 23 (batching several requests per step) attack the fixed per-step overhead that dominates here.
8b. Cache memory, measured
Extra GPU memory during cached generation (fp32 cache), against the formula
2 · L · C · 4 bytes · tokens from §6d:
| model | tokens | formula | measured peak extra |
|---|---|---|---|
| 4L, C=256 | 1,024 | 8.39 MB | 8.70 MB |
| 8L, C=512 | 1,024 | 33.55 MB | 34.18 MB |
| 12L, C=768 | 1,024 | 75.50 MB | 76.43 MB |
The formula accounts for all but 0.3-0.9 MB, which is the logits and the temporaries of one decode step.
8c. Temperature 0.1 / 1.0 / 2.0, and the other knobs
The Stage 06 4-layer model (12k steps), four prompts × five seeds, 200 tokens each. Two numbers per setting: distinct-2, the fraction of adjacent token pairs that are unique (1.0 = never repeats a pair, low = loops), and the mean log-probability the model itself assigns to what it wrote (close to 0 = very predictable to itself; −9 = uniform guessing).
| setting | distinct-2 | mean log-prob | parses as Python |
|---|---|---|---|
| greedy | 0.07 | −0.24 | 25% |
| τ = 0.1 | 0.08 | −0.28 | 20% |
| τ = 0.7 | 0.32 | −0.95 | 5% |
| τ = 1.0 | 0.79 | −3.19 | 0% |
| τ = 1.5 | 1.00 | −7.83 | 0% |
| τ = 2.0 | 1.00 | −9.51 | 0% |
| τ = 1.0, top-k 40 | 0.53 | −1.56 | 0% |
| τ = 1.0, top-p 0.9 | 0.65 | −2.34 | 0% |
| τ = 0.7, repetition 1.3 | 0.94 | −2.84 | 0% |
| greedy, repetition 1.3 | 0.54 | −0.84 | 0% |
What each end looks like, from def is_prime(n)::
greedy: def is_prime(n):
return n
def is_prime(n):
return n
... (the same three lines until the budget runs out)
τ = 2.0: self. supported future()Reader elementFilesXRowEndallements function
defabspathety kwargsStream txNoPoonent OutLoader records...
- Low temperature loops. Greedy and τ = 0.1 are almost identical: at τ = 0.1 the top token takes nearly all the probability (§3's table). Distinct-2 of 0.07 means 93% of token pairs are repeats. The mean log-prob of −0.24 says the model finds its own loop extremely likely: each repetition makes the next one more likely, the trap of §2.
- High temperature is noise. At τ = 2.0 the mean log-prob is −9.5, worse than uniform guessing over the vocabulary (−9.01): the model is mostly drawing from the tail of near-impossible tokens. Every pair is new, and none of it is code.
- "Parses" is a trap metric. The greedy loop parses 25% of the time,
higher than any sampled setting, because
def is_prime(n): return nrepeated is valid Python. Validity is not quality. - Truncation works as advertised: top-k 40 and top-p 0.9 at τ = 1.0 cut the mean surprise from −3.19 to −1.56 and −2.34 while keeping most of the variety.
- The repetition penalty breaks loops and makes things up. Greedy with
penalty 1.3 escapes the
is_primeloop and writes a plausible-looking test class, but every reused name is now penalised, so it invents new ones.
A 5M model does not write working code at any setting, so this measures the knobs, not the model. The same table is worth repeating on the Stage 11 models (Stage 22 uses greedy for pass@1 and τ = 0.8 for pass@10).

9. What we found
| Question | Answer, measured |
|---|---|
| Is the cached decoder exact? | Same tokens as the naive loop in all 36 settings, greedy and sampled |
| KV-cache speedup at length 512? | 1.27× (5M), 3.32× (30M), 4.47× (92M); 7.2× for 92M at 1,024 |
| Why below the 5-20× expectation? | Batch-1 decoding of small models is bound by a fixed per-step overhead (~0.7 ms of kernel launches and Python), not by arithmetic |
| Does the cache cost what §6d says? | Within 0.3-0.9 MB of 2·L·C·bytes·T |
| Low temperature? | Loops: distinct-2 0.07, log-prob −0.24 |
| High temperature? | Noise: log-prob −9.5, worse than uniform |
| Does "parses as Python" measure quality? | No: the greedy loop parses most often |
One habit from this stage: measure where the time goes before believing a speedup estimate. Counting FLOPs predicted a large win; the GPU was not limited by FLOPs.
Chapter 10
The training loop
Every stage so far trained small models with a short loop copied from stage to stage. It worked, but it was never explained. This stage opens it up. The training loop is where most silent bugs in deep learning live: a model with a broken loop still produces a falling loss curve, just a worse one, and nothing crashes to tell you.
What is in this stage:
- the optimizer, built up from SGD to Adam to AdamW, written by hand and checked against PyTorch's;
- what Adam's two state tensors are;
- the learning-rate schedule: warmup, then cosine decay, and why each part exists;
- gradient clipping;
- gradient accumulation: a large batch on 8 GB;
- the two mandatory sanity checks: the loss at step 0, and overfitting one batch;
- a 10M-parameter model on TinyStories, the fast smoke test that makes a broken loop obvious in 20 minutes;
- the ablations: no warmup, no clipping, and three ways of choosing which windows of data to train on.
The loop built here, llmfs/train/trainer.py, is the one every later stage
uses, including the 125M capstone run.
1. The loop in one picture
┌──────────────────────────────────────────────────────────┐
│ for step in range(steps): │
│ lr = schedule(step) §4 │
│ for micro in range(accum): §6 │
│ x, y = next batch (B, T) each │
│ loss = model(x, y) / accum forward │
│ loss.backward() grads add up │
│ clip grads to norm 1.0 §5 │
│ optimizer.step() §2-§3 │
│ zero grads │
│ every N steps: eval, log, checkpoint │
└──────────────────────────────────────────────────────────┘
Each line is a decision. Each one, done wrong, gives a model that still trains, only worse.
2. From SGD to Adam
2a. SGD: walk downhill
The gradient g of the loss with respect to a weight θ says which direction
increases the loss, and how steeply. Stochastic gradient descent steps the
other way:
θ ← θ − lr · g
"Stochastic" because g is computed on one batch, not the whole dataset, so
it is a noisy estimate of the true direction.
Two problems with plain SGD on a transformer:
- One learning rate for very different weights. An embedding row for a rare token gets a gradient once every thousand batches; a LayerNorm gain gets one every step. Gradient sizes across a transformer's weights differ by factors of 100 or more. A learning rate small enough for the big ones barely moves the small ones.
- Noise. Each batch's gradient points in a slightly different direction. Steps zigzag.
2b. Momentum: average the direction
Keep a running average of recent gradients, and step along that:
m ← β₁ · m + (1 − β₁) · g β₁ = 0.9: roughly the last 10 steps
θ ← θ − lr · m
The zigzags cancel in the average; the consistent direction adds up. This is
Adam's first state tensor, m: one number per weight, the same shape as
the weights.
2c. Adam: a learning rate per weight
Also keep a running average of the squared gradient:
v ← β₂ · v + (1 − β₂) · g² β₂ = 0.95 for us (0.999 in the paper)
√v is the typical size of this weight's gradient. Dividing by it puts every
weight's step on the same scale:
θ ← θ − lr · m / (√v + ε)
A weight whose gradients are always tiny gets the same size of step as one
whose gradients are large. That fixes problem 1. v is Adam's second state
tensor. Together m and v are why Adam costs 8 extra bytes per parameter
in fp32 (Stage 00 measured 96 MB of optimizer state for a 12.6M model).
Bias correction. m and v start at zero, so for the first few steps
they are too small: after one step, m = 0.1 · g. Adam divides by
1 − β^t to undo that:
m̂ = m / (1 − β₁ᵗ) v̂ = v / (1 − β₂ᵗ)
θ ← θ − lr · m̂ / (√v̂ + ε)
At step 1, m̂ = g and v̂ = g², so the update is lr · g/|g| = ± lr for
every weight. Every weight moves by the full learning rate, whatever its
gradient. Keep that in mind for §4.
Why β₂ = 0.95 rather than the paper's 0.999? A longer average (0.999 ≈ the
last 1,000 steps) reacts slowly when gradients suddenly grow, so the step
m/√v can briefly become very large. That is a known source of loss spikes in
large language models. 0.95 (the last ~20 steps) is the GPT-3 / Llama choice.
2d. AdamW: weight decay, done right
Weight decay pulls every weight slightly towards zero each step. It stops weights from growing without limit and acts as a mild regulariser.
The old way to do it was to add an L2 penalty ½ · wd · θ² to the loss. Its
gradient is wd · θ, which joins g... and then goes through Adam's division
by √v. So a weight with large gradients gets less decay, and one with small
gradients gets more. The decay strength now depends on the gradient
history, which nobody asked for.
AdamW (Loshchilov & Hutter, 2019) decouples the decay. It shrinks the weight directly, outside Adam's normalisation:
θ ← θ − lr · wd · θ decay: the same fraction for every weight
θ ← θ − lr · m̂ / (√v̂ + ε) Adam step
Which weights get decay? Matrices (linear weights, embeddings) do; biases and
LayerNorm gains do not. A LayerNorm gain of 1 is a meaningful value; pulling
it towards 0 shrinks the signal at every layer. Biases are few and cheap. Our
loop puts every tensor with dim ≥ 2 in the decay group and the rest in a
no-decay group.
§8a checks our hand-written AdamW against torch.optim.AdamW, step by step,
and shows how far L2-in-the-loss drifts from it.
3. What the numbers are
Our settings, kept from Stage 03 onwards and now explained:
| Setting | Value | Why |
|---|---|---|
| β₁ | 0.9 | momentum over ~10 steps |
| β₂ | 0.95 | second moment over ~20 steps: reacts fast to gradient growth (§2c) |
| ε | 1e-8 | avoids divide-by-zero; small next to any real √v |
| weight decay | 0.1 | GPT-3 / Llama value |
| peak lr | 1e-3 (small models), 6e-4 (124M) | smaller models tolerate larger steps |
| warmup | 100-2,000 steps | §4 |
| min lr | 10% of peak | §4 |
| clip | 1.0 | §5 |
4. The learning-rate schedule
lr
│ ╭──────╮
│ ╱ ╲___
│ ╱ ╲___
│ ╱ ╲____
│ ╱ ╲______ ← 10% of peak
│ ╱
└─┴──────────────────────────────────── step
warmup cosine decay
Warmup: start small, grow linearly to the peak. Three reasons:
- Step 1 moves every weight by ±lr (§2c). At lr = 1e-3, every weight, most of which have std 0.02, moves 5% of its typical size in the same step, regardless of how informative its gradient was.
vis a poor estimate early. With β₂ = 0.95 it averages about 20 steps; for the first few it is based on one or two noisy gradients. A weight that happened to get a small gradient early gets a huge effective stepm/√vlater.- The early landscape is the steepest. At init the loss is 9 and falling fast; gradients are large and change direction quickly.
Warmup lets v fill up and the model leave the steep region before full-size
steps begin. What breaks without it: the loss jumps in the first hundred
steps, sometimes recovers, sometimes settles on a worse path. §8d measures it.
Cosine decay: end small. Near the end of training, the model is near a good point, and large steps jump around it rather than settling in. Lowering the learning rate lets it settle. The cosine shape spends a long time near the peak (fast progress) and then drops smoothly:
lr(t) = min + (peak − min) · ½ (1 + cos(π · progress))
Most of the final loss improvement in a run comes from this decay. We stop at 10% of peak rather than 0, which is the Chinchilla convention.
5. Gradient clipping
Sometimes one batch produces a gradient much larger than usual: an unusual
document, a rare token, a sharp spot in the loss landscape. Adam's
normalisation absorbs some of it, but v adapts over ~20 steps, so one huge
gradient still gives one huge step.
Clipping by global norm caps the size of the whole gradient, all parameters together, viewed as one long vector:
norm = √( Σ over every parameter of Σ g² )
if norm > 1.0: g ← g · (1.0 / norm) same direction, capped length
It keeps the direction and limits the length. In a healthy run the norm sits below 1 most of the time, and clipping only acts on the rare spikes. If the norm is above the threshold on most steps, the threshold is effectively a second learning rate, which is worth knowing. We log the norm every step so we can see which case we are in.
6. Gradient accumulation: a big batch on a small GPU
The batch size that trains well (hundreds of thousands of tokens per step for
a 125M model) does not fit in 8 GB. Activations for B = 32, T = 1024 in a
125M model are several GB on their own.
But a gradient is an average over the examples in the batch, and averages
can be computed in pieces. Run 4 micro-batches of 8, call .backward() on
each, and PyTorch adds the gradients into .grad. Divide each
micro-batch's loss by 4 first, and the sum of four quarter-gradients is the
average over all 32:
∇ (L₁ + L₂ + L₃ + L₄)/4 = (∇L₁ + ∇L₂ + ∇L₃ + ∇L₄)/4
That is the same gradient a batch of 32 gives, with only 8 sequences' worth of activations in memory at once. It costs time, not quality: four forward and backward passes for one optimizer step.
The trap: forgetting to divide by the number of micro-batches. Then the gradient is 4× too large, which is like a 4× learning rate. Clipping hides most of it, so the run still trains. §8a tests that accumulated gradients equal one big batch to float precision.
7. Sanity checks before trusting a run
Check 1: the loss at step 0 should be ln V (9.01 for us) with random
targets (Stage 06 §2). Too high: the init is too big, logits are not near
zero. Too low: something leaks information about the target.
Check 2: overfit one batch. Take a single batch and train on it, over and
over. A model with millions of parameters can memorise 8 sequences, so the
loss must go to almost zero. If it does not, something between the data and
the weights is broken: the shift, the mask, the optimizer, the learning rate,
zero_grad. This test takes seconds and catches most loop bugs. It is the
first thing to run on any new training code.
Check 3: the smoke test. A small model on easy data, where the output can be judged by eye. That is TinyStories (§8c): short children's stories with a vocabulary a 3-year-old knows. A working 10M model writes grammatical little stories after ~20 minutes. A broken loop writes word salad, and you see it before wasting a day on code data.
Reading a loss curve
| Shape | Usual cause |
|---|---|
flat at ln V |
no learning: lr 0, frozen params, detached graph |
| drops fast, then flat high | lr too low, or the model learned only unigram statistics (Stage 05 found 6.86) |
| jagged, loss jumps up then recovers | lr too high, no warmup, no clipping |
| goes to NaN | overflow (fp16 without loss scaling), lr far too high, log of zero |
| train falls, val rises | overfitting: too many epochs on too little data |
| sudden drop at a batch boundary | data order: one source after another, not mixed |
8. Experiments
8a. AdamW by hand, and gradient accumulation
Correctness. Our AdamW (stages/08_training/optim.py) against
torch.optim.AdamW, 25 steps on a small GPT, same data:
- in float32 the weights drift apart to 2e-4;
- in float64, 4e-13.
The float32 gap is the same story as Stage 06 §8a: identical arithmetic in a
different order rounds differently, and training amplifies small
differences. Adam is especially sensitive, because it divides by √v:
a weight whose gradient is near zero gets a step of size ±lr from a
tiny, rounding-dominated gradient. The test runs in float64.
Gradient accumulation: four micro-batches of 2 with the loss divided by 4
give the same gradients as one batch of 8 to 1e-6. Without the division, the
gradient is exactly 4.0× too large (test_accumulation_without_divide_is_4x).
Five optimizers, same model and data. The 4-layer model, 1,500 steps, B=32, T=256, all with the same warmup + cosine schedule and clipping, using our hand-written versions:
| optimizer | val loss | weight norm (matrices) |
|---|---|---|
| SGD, lr 0.1 | 5.615 | 41.6 |
| SGD + momentum 0.9 | 4.310 | 48.5 |
| Adam, no decay | 3.609 | 103.7 |
| AdamW, decay 0.1 | 3.614 | 98.7 |
| Adam + L2 in the loss, 0.1 | 6.695 | 1.4 |
- Momentum is worth 1.3 nats here: plain SGD zigzags.
- Adam is worth another 0.7 over momentum, from per-weight step sizes. SGD at lr 0.1 moves the big-gradient weights reasonably and barely moves the rest (§2a, problem 1).
- AdamW vs Adam at 1,500 steps: the same loss within 0.006. Decoupled decay of 0.1 shrinks the weights by 5% over this short run, with no effect on loss yet. Its job is long-run regularisation, not early speed.
- L2 in the loss at the same 0.1 is a disaster: val loss 6.69, close to
the unigram floor of 6.86 (Stage 05), and the weights collapse to a norm of
1.4. The penalty's gradient
0.1·θis the same sign for a weight step after step, so Adam's normalisation turns it into a steady step of aboutlrtowards zero for every weight, a far stronger pull than intended. Coupled L2 needs a coefficient hundreds of times smaller with Adam. AdamW's decoupling is not a refinement; at the same number it is a different algorithm.
8b. Overfitting one batch
One batch of 8 sequences × 256 tokens, the 4-layer model, lr 1e-3, trained on repeatedly:
step 0: 9.029 (ln V = 9.01: initialisation is right)
step 50: 2.985
step 72: < 1.0
step 96: < 0.1
step 129: < 0.01
step 399: 0.0003
5.3M parameters memorise 2,048 tokens in about 130 steps. The loop, the shift, the mask and the optimizer are wired correctly. This check takes 10 seconds, and it is the first thing to run on any new training code.
It also produced the only true loss spike of this stage, unasked:
step 255 256 257 258 259 260 261 262 270 290
loss 0.00038 0.00037 0.00036 0.00036 0.00579 0.57919 0.44423 0.58706 0.06283 0.00674
A 1,600× jump in two steps, and 30 steps to recover. Nothing in the data
changed: it is the same batch every step. The cause is Adam itself (§2c).
As the loss approaches zero, the gradients become tiny and noisy, and so does
v, the running average of their squares. The step is m/√v: a tiny
gradient divided by the root of a tiny average is not a tiny step. It is
about ±lr for every weight, in directions set by noise. Constant lr 1e-3,
no clipping and no schedule here, so nothing damps it. This is the mechanism
behind many late-training spikes in real runs, where some weights' gradients
become small. It is one reason for the cosine decay, and for ε not being
vanishingly small in some recipes.
8c. The TinyStories smoke test
10,103,040 parameters (6 layers, C=320, 5 heads), our code tokenizer, 2 of 4 TinyStories train shards (313M tokens), 6,000 steps of 32 × 256 tokens: 49M tokens, 11.5 minutes on the 4060. Validation loss 1.510.
The same prompt, "Once upon a time", sampled (τ = 0.8, top-p 0.95) during training:
step 0 Once upon a timelanrain supported futureorationReader elementFilesXRow ...
(random weights: a random walk through the vocabulary, mostly code tokens)
step 200 Once upon a time, there was a girl named Lily loved to playing in her
pill and wanted to turned toys to playing and named Lily. Lily.
(the genre's opening, names, quotes; grammar broken)
step 1000 Once upon a time, there was a little dog. The dog wanted to keep the dog
all of the way back. The dog told the dog, and the dog could sat away.
(grammatical sentences, no tracking of who is who)
step 6000 Once upon a time, there was a little boy named Timmy. Timmy loved to play
with his toys all day long. One day, Timmy's mom took him to the zoo to
see all the animals. Timmy was very happy because he loved his toy ball.
They walked to the zoo, and Timmy saw many animals. The zookeeper said,
"Let's go and play with the animals. It's fun!"
By the end: grammatical, a named character carried across sentences, dialogue with correct quoting, a plausible story arc. Also visibly 10M parameters: the zoo visit is motivated by a toy ball, and other samples loop ("She felt the sun on her face. She felt the sun on her face."). This is what "coherent" means at this scale, and it is enough: a broken loop could not produce step 6000's text. The loop is ready for code.
Each sample above is a free diagnostic. Word salad after 1,000 steps would point at the data or the shift; a sample that never changes would point at the learning rate; garbage after a resume would point at the checkpoint (Stage 11).
8d. No warmup, no clipping
At our usual lr of 1e-3, the 4-layer model trains fine without either rail, which would make a dull ablation. So this one uses a 6-layer, C=384 model (14M) at lr 3e-3, 2,000 steps on code, where the rails have something to do:
| variant | val loss | max grad norm | steps with grad norm > 1 |
|---|---|---|---|
| warmup 200 + clip 1.0 | 2.946 | 7.0 (step 0) | 7% |
| no clipping | 3.028 (+0.08) | 7.0 (step 0) | 5% |
| no warmup | 4.781 (+1.84) | 17.6 | 67% |
| neither | 5.057 (+2.11) | 32.6 | 80% |
The loss at the first steps tells the story:
step 0 10 20 30 50 100 200 500 1000
baseline 9.10 8.26 7.55 6.80 5.97 5.59 4.97 4.55 3.68
no warmup 9.10 7.11 7.00 6.99 6.52 6.31 5.50 5.47 5.21
No warmup does not cause a spike. It causes a stall. With the full
3e-3 from step 0, every weight moves ±lr on the first step (§2c). The loss
drops to 7.0 within 10 steps, faster than the warmed-up run, and then sits
there for 30 more steps: 7.0 is close to the unigram plateau (6.86, Stage
05), the loss of predicting each token by its overall frequency. The early
oversized steps have pushed the model into a state that knows token
frequencies and nothing else, and it climbs out slowly. After 2,000 steps it is
still 1.8 nats behind, and its gradient norm is above 1 on two thirds of the
steps: it never settles.
No clipping costs a little here (+0.08), because with warmup the gradient norm exceeds 1 on only 7% of steps, mostly at the very start. Clipping is insurance against rare events, and this run had few. Remove warmup and clipping and the two failures compound: gradient norms reach 32.6 around step 1,000 and the run ends at 5.06.
What we expected and did not see: a classic loss spike (a jump up that recovers). At this scale, the failure mode of missing warmup is getting stuck early, not blowing up. Spikes need longer, larger runs; Stage 11 watches for them.
8e. Which windows to train on
The curriculum listed this for Stage 02, which deferred it here because it needs a loop to observe. Three ways to pick the next training window from a 2.2B-token file:
- sequential: windows in file order. Files from the same repository, topic or source sit next to each other, so consecutive batches are similar.
- random offsets (nanoGPT): any start, with replacement. Stage 02 §10 showed one epoch's worth of draws leaves ~37% of tokens unseen.
- shuffled windows (ours): every non-overlapping window once per epoch, in random order.
The 4-layer model, 4,000 steps of 32 × 256 tokens (85/15 code/English):
| sampler | val code | val English | batch-to-batch train loss std (last 1k steps) |
|---|---|---|---|
| sequential | 3.937 | 5.253 | 0.74 |
| random offsets | 2.695 | 4.539 | 0.16 |
| shuffled windows | 2.683 | 4.516 | 0.16 |
Sequential is a disaster: +1.25 nats. With windows in file order, the 32 rows of a batch are 32 consecutive windows: 8,192 tokens of one or two files. Each step's gradient points at whatever one repository looks like, the next step's at the next repository. The train loss jumps around 4.6× more from step to step, and the model spends its updates chasing the latest file instead of the average. This is the reason every pipeline shuffles, and it is a failure that a falling loss curve does not reveal on its own: sequential's curve falls too, just slowly.
Random vs shuffled: a tie (0.012). Stage 02 §10 showed random offsets leave 37% of the data unseen after one epoch's worth of draws. These runs draw 128k windows out of 5.2M: 2.5% of an epoch. At that fraction, random draws almost never repeat, and both samplers are effectively fresh data. The difference Stage 02 predicted can only show up near and beyond one epoch, which is Stage 10 and 11 territory. We keep the shuffled sampler because it is exactly as good here and strictly better there, and its state is two integers.

9. What we found
| Question | Answer, measured |
|---|---|
| Does our AdamW equal PyTorch's? | 4e-13 in float64; 2e-4 in float32 after 25 steps (rounding, amplified by Adam's division) |
| Is accumulation exact? | Equal gradients to 1e-6; forgetting the ÷4 makes them exactly 4.0× too big |
| What does each optimizer step buy? | SGD 5.61 → momentum 4.31 → Adam 3.61 (1,500 steps) |
| AdamW vs Adam + L2 at 0.1? | 3.61 vs 6.69: coupled L2 crushes the weights (norm 98.7 → 1.4) |
| Overfit one batch? | < 0.01 by step 129 |
| TinyStories smoke test? | 10.1M params, 11.5 min, val 1.510, coherent short stories |
| No warmup at lr 3e-3? | +1.84: an early stall at the unigram plateau (~7.0), not a spike |
| No clipping? | +0.08: clipping acted on only 7% of steps |
| Sequential data order? | +1.25, with 4.6× noisier batches |
| Random vs shuffled windows? | Tie (2.695 vs 2.683) at 2.5% of an epoch |
Two habits from this stage:
- Run the one-batch overfit test before anything else. Ten seconds, and it exercises every piece of the loop.
- An ablation that changes nothing at the default settings is not a negative result yet. Warmup and clipping looked unnecessary at lr 1e-3; at 3e-3 one of them was worth 1.8 nats. Test rails where they bear load.
Chapter 11
Making it fast on 8 GB
Stage 08 gave us a training loop that is correct. This stage makes it fast. Speed is not a luxury here: the capstone run in Stage 11 has a budget of about two days on one laptop GPU. A loop running at a third of the possible speed turns two days into six.
The rule for this stage: one change at a time, measured. We take one model and one batch shape, and stack the optimisations one by one. Each row of the final table records throughput (tokens per second) and peak memory, so every speedup can be attributed to exactly one change.
What is in this stage:
- number formats: fp32, TF32, fp16, bf16, and why bf16 needs no loss scaling;
torch.autocast: which operations run in low precision and which do not;- fused attention (FlashAttention / SDPA): the tiling trick that never
stores the
T×Tmatrix; torch.compileand kernel fusion;- activation checkpointing: trading compute for memory;
- fused AdamW;
- MFU, the honest efficiency number;
- profiling: where the time actually goes.
1. Where the time goes: two kinds of work
A GPU does two things: arithmetic, and moving numbers between its memory and its compute units. Every operation is limited by one of them.
- Matrix multiplies do
2·m·n·karithmetic operations onm·k + k·nnumbers. For big matrices that is hundreds of operations per number moved. They are limited by arithmetic ("compute-bound"). - Elementwise operations (add, GELU, LayerNorm, softmax, dropout) do one or a few operations per number. They read a tensor, do almost nothing, and write it back. They are limited by memory bandwidth ("memory-bound").
A transformer's FLOPs are almost all in the matmuls. But a naive implementation spends a surprising share of its time in elementwise operations, each one a separate trip to memory. Most of this stage is about cutting those trips: fewer bytes per number (bf16), fewer separate kernels (fusion), and never writing big intermediate tensors (fused attention).
Counting FLOPs for training
For a transformer with N non-embedding parameters, the forward pass costs
about 2N FLOPs per token (one multiply and one add per weight), and the
backward pass about twice that. So training costs about 6N FLOPs per
token. Attention adds a term that grows with T:
FLOPs per token ≈ 6N + 12 · L · T · C
(forward QKᵀ and AV are 2·T·C each per layer, ×3 for the backward pass.)
We use this to compute MFU in §7. Stage 10 uses the same formula as C ≈ 6ND.
2. Number formats
Every number on the GPU has a format. Fewer bits means less memory, less bandwidth, and, on tensor cores, much faster matmuls.
sign exponent mantissa range precision
fp32 1 8 23 ~1e-38..3e38 ~7 digits
tf32 1 8 10 same as fp32 ~3 digits (matmul inputs only)
bf16 1 8 7 same as fp32 ~2-3 digits
fp16 1 5 10 ~6e-5..65504 ~3 digits
The exponent decides the range (how big and how small a number can be). The mantissa decides the precision (how many digits are kept).
TF32 is not a storage format. It is a mode in which the tensor cores read
fp32 inputs but use only 10 mantissa bits for the multiply. One line of code
turns it on (torch.backends.cuda.matmul.allow_tf32 = True), and matmuls get
faster with no other change.
fp16 vs bf16. Both are 16 bits. fp16 keeps more precision but has a tiny
range: anything below about 6e-5 becomes zero, and anything above 65,504
overflows. Gradients in a deep network are often smaller than 6e-5. In fp16
they quietly round to zero and that part of the network stops learning. The
fix, loss scaling, multiplies the loss by, say, 1024 before the backward
pass, so the gradients are 1024× larger and stay in range, then divides them
again before the optimizer step. It works, but it needs a scaler that watches
for overflow and adjusts.
bf16 ("brain float") keeps fp32's 8-bit exponent and so fp32's whole
range, and drops precision instead. Small gradients stay representable. No
loss scaling is needed. The cost is precision: bf16 has about 3 significant
digits, so 1 + 0.001 = 1 in bf16. That is why weights and optimizer states
stay in fp32 even when the compute is bf16: thousands of tiny updates would
round away.
What autocast actually does
torch.autocast("cuda", dtype=torch.bfloat16) does not convert the model. It
intercepts each operation:
- matmuls and convolutions run in bf16: the big win;
- reductions and numerically delicate ops (softmax, log-softmax, cross-entropy, LayerNorm's statistics, sums) run in fp32;
- the weights stay fp32 in memory, and are cast to bf16 copies on the fly for each matmul.
Our model's loss computes cross_entropy(logits.float(), ...): the .float()
is belt-and-braces, so the log-softmax over 8,196 entries never runs in bf16.
3. Fused attention: never store the T×T matrix
Stage 04 measured the cost of naive attention: four T×T tensors per head
alive at once, out of memory at T = 16k. FlashAttention (Dao et al. 2022)
computes exactly the same output without ever storing the T×T matrix.
The trick is the softmax. Softmax over a row needs the row's maximum and its sum of exponentials, which seems to need the whole row at once. It does not: both can be computed in pieces and corrected as more pieces arrive.
process keys in blocks of, say, 64:
running max m, running sum s, running output o
for each block:
scores = q · kᵀ_block (small: 64 numbers per query)
m_new = max(m, max(scores))
rescale old s and o by exp(m − m_new) fix what was computed with the old max
s = s + Σ exp(scores − m_new)
o = o + exp(scores − m_new) · v_block
output = o / s
Each block of keys is loaded into the GPU's small, very fast on-chip memory
once, used, and discarded. The full T×T matrix never exists. Memory goes
from O(T²) to O(T); the arithmetic is the same (a little more, for the
rescaling); the time drops because the slow round trips to main memory are
gone. The backward pass recomputes the blocks instead of storing them.
PyTorch exposes this as F.scaled_dot_product_attention, which picks a
FlashAttention or memory-efficient kernel when it can. Stage 04 checked it
equals our hand-written attention to 1e-5. Our model's flash=True switch
uses it.
4. torch.compile and kernel fusion
Each PyTorch operation in eager mode is a separate GPU kernel. x + y reads
x and y from memory and writes the result. Then gelu reads that result
and writes another. A chain of five elementwise operations means five round
trips to memory, with almost no arithmetic in between.
torch.compile(model) traces the Python code into a graph, then fuses
chains of elementwise operations into single kernels that read once, do all
the arithmetic in registers, and write once. It also picks matmul
configurations and removes Python overhead.
The costs: the first steps are slow (compilation takes tens of seconds to minutes), errors become harder to read, and anything that changes shape each step (like our KV-cache decoding) triggers recompilation. We compile the training step only.
5. Activation checkpointing: trade compute for memory
The backward pass needs the forward pass's intermediate tensors (the
activations). They are stored during the forward pass and consumed during
the backward. For a transformer, activation memory grows with
B × T × C × L and is usually larger than the weights.
Activation checkpointing stores only each block's input, throws away everything inside the block, and recomputes the block's forward pass during the backward pass when its activations are needed.
- Memory: from "every intermediate of every block" to "one tensor per block, plus one block's intermediates at a time".
- Cost: one extra forward pass per block, so roughly 1 + 1/3 ≈ +33% compute (forward is ~1/3 of forward+backward).
It does not make a fixed batch faster. It makes a larger batch fit, and a larger batch often uses the GPU better. We measure whether that trade pays on 8 GB.
6. Fused AdamW
The optimizer step touches every parameter, its gradient, and its two state
tensors: four tensors per parameter, read and written, with a few operations
each. Pure memory traffic. The default implementation runs a loop of small
kernels per parameter tensor; fused=True does the whole update for all
parameters in a few large kernels. For small models with many tensors this is
a visible saving; for big ones it is a few percent.
7. MFU: the honest number
Tokens per second depends on the model: a 10M model runs faster than a 125M one on the same GPU, so "100k tokens/s" says nothing on its own. Model FLOPs Utilization (Chowdhery et al., PaLM 2022) asks: what fraction of the GPU's peak arithmetic is spent on useful model FLOPs?
MFU = (tokens/s × FLOPs per token) / peak FLOPs/s
"Useful" means the 6N + 12LTC count from §1. Recomputation for activation
checkpointing does not count, which is the point: MFU rewards speed, not
busy-work.
Which peak? The datasheet number for a laptop GPU depends on clocks and power limits the datasheet does not know. We measure our own peak: the best bf16 throughput of a large square matmul on this GPU, with this driver. It is an achievable ceiling rather than a theoretical one, so our MFU is honest in a conservative direction: published MFU numbers use the datasheet peak and would look lower.
Good large-scale training runs reach 40-60% MFU. Small models on one GPU do worse, because their matmuls are too small to fill the GPU.
8. Build order and acceptance criteria
stages/09_efficiency/bench.py builds the model once per configuration and
times training steps after warm-up. Configurations, stacked in order:
- fp32, hand-written attention, unfused AdamW: the baseline;
-
- TF32 matmuls;
-
- bf16 autocast;
-
- fused attention (SDPA);
-
- fused AdamW;
-
torch.compile;
-
- activation checkpointing, then double the batch.
Acceptance criteria:
- every row reports tokens/s, peak MB and MFU;
- loss after 50 steps from the same seed agrees across rows to within the precision change (fp32 vs bf16 differs; SDPA vs manual must not);
- the stack reaches ≥ 3× the baseline (curriculum target 3-5×);
- a profiler trace of one step names the top kernels.
9. Experiments
9a. Our peak
A 4,096 × 4,096 matmul, repeated, on this laptop GPU:
| format | TFLOP/s |
|---|---|
| fp32 | 5.48 |
| TF32 | 10.43 |
| bf16 | 23.63 |
| fp16 | 24.76 |
bf16 tensor cores do 4.3× the arithmetic of plain fp32 on this chip. That ratio is the ceiling on what mixed precision alone can buy. MFU below is computed against our measured 23.63, which is achievable rather than theoretical.
9b. The stack
8 layers, C=512 (30M), T=512, B=8 unless noted, 30 timed steps after warm-up:
| change (cumulative) | tokens/s | speedup | MFU | peak MB |
|---|---|---|---|---|
| fp32 baseline (our attention, per-tensor AdamW) | 14,271 | 1.00× | 12% | 3,204 |
| + TF32 matmuls | 18,536 | 1.30× | 16% | 3,204 |
| + bf16 autocast | 23,142 | 1.62× | 20% | 2,995 |
| + fused attention (SDPA) | 34,490 | 2.42× | 30% | 2,228 |
| + fused AdamW | 35,098 | 2.46× | 30% | 2,228 |
+ torch.compile |
73,656 | 5.16× | 63% | 1,221 |
| + activation checkpointing | 60,955 | 4.27× | 52% | 718 |
| + batch 8 → 32 (with checkpointing) | 60,846 | 4.26× | 52% | 1,641 |
| compile, no checkpointing, B=16 | 70,579 | 4.95× | 60% | 2,006 |
5.16× total, above the curriculum's 3-5× target. Reading the rows:
- TF32 and bf16 give 1.3× and another 1.25×, far less than the 4.3× peak ratio. The matmuls got faster; everything else did not.
- Fused attention is the largest single step before compile: 1.5×, and
25% less memory, from never storing the
T×Tmatrices (Stage 04's four of them per head). - Fused AdamW: +2%. Small model, few tensors; it matters more with many.
torch.compiledoubles throughput and halves memory. §9c explains why.- Activation checkpointing costs 17% of throughput (the textbook says ~30%; compile makes the recomputed forward cheap) and cuts memory 41%. Spending that memory on a 4× bigger batch buys nothing: B=8 at T=512 is already 4,096 tokens per step, enough to fill the GPU. On 8 GB, at these sizes, checkpointing is a tool for fitting a model, not for speed.
Losses after 40 steps from the same seed: 6.61-6.65 for every row. bf16 and fp32 agree to the run-to-run noise of bf16 kernels at this point (±0.03); none of the optimisations changes what is computed beyond rounding.

9c. Where the time goes
PyTorch profiler, 3 steps, kernel time grouped by kind:
| fp32 baseline | bf16 + fused attention + fused AdamW (before compile) | |
|---|---|---|
| matmul | 55% | 29% |
| other elementwise | 36% | 45% |
| dtype casts / copies | 2% | 14% |
| fused attention | — | 4% |
| softmax | 6% | 3% |
| optimizer | — | 3% |
| LayerNorm, reductions | 2% | 2% |
This is the explanation for the whole stack. In fp32 the matmuls dominate, as the FLOP count says they should. Make the matmuls 2-4× faster with bf16, and they drop to 29% of the time: the GPU now spends most of its time on cheap elementwise operations. Two culprits stand out in the kernel list:
- our hand-written tanh-GELU (Stage 05):
0.5·x·(1 + tanh(√(2/π)(x + 0.044715·x³)))written out is seven or eight separate elementwise kernels (power, multiplies, adds, tanh), each a full read and write of a(B, T, 4C)tensor; - autocast's casts (14%): every fp32 weight is copied to bf16 on every forward pass.
That is the memory-bound work of §1, and it is exactly what torch.compile
fuses: the GELU becomes one kernel, the casts merge into their consumers.
Hence 2× from a single line, where a FLOP count would predict almost nothing.
9d. The Stage 11 shapes
The full stack (compile, bf16, SDPA, fused AdamW) at T = 1,024:
| model | batch | tokens/s | MFU | peak MB |
|---|---|---|---|---|
| workhorse, 8L, C=512 (30M) | 16 | 70,200 | 67% | 3,569 |
| capstone, 12L, C=768 (92M) | 8 | 25,389 | 71% | 4,298 |
| capstone | 16 | out of memory | ||
| capstone + checkpointing | 16 | 21,780 | 61% | 2,828 |
The capstone at 25.4k tokens/s means 1.8B tokens takes about 20 hours. B=8 per micro-batch with gradient accumulation is the configuration.
10. What we found
| Question | Answer, measured |
|---|---|
| Our achievable bf16 peak | 23.6 TFLOP/s (fp32 5.5, TF32 10.4) |
| Total speedup, one change at a time | 5.16×: 14.3k → 73.7k tokens/s; MFU 12% → 63% |
| Biggest single step | torch.compile, 2.1×, plus half the memory |
| Why compile matters so much | After bf16, elementwise ops (45%) and dtype casts (14%) outweigh matmuls (29%) |
| Activation checkpointing | −17% throughput, −41% memory; a bigger batch does not win it back |
| Capstone throughput | 25.4k tokens/s at 71% MFU: ~20 h for 1.8B tokens |
One habit from this stage: profile before optimising. The FLOP count said "matmuls"; the profiler said "elementwise and casts". Only the second one predicted that a compiler would double the speed.
Chapter 12
How big, how long: scaling laws
We have a correct model (Stage 06), a correct loop (Stage 08) and a fast one (Stage 09). Stage 11 will spend about two days of GPU time on one training run. Before spending it, we need to answer a question that sounds simple: for a fixed amount of compute, how big should the model be, and how many tokens should it see?
A bigger model learns more from each token but costs more per token. With a fixed budget, every parameter added means fewer tokens. Somewhere between "a huge model that sees almost nothing" and "a tiny model that sees everything" is a best size. Scaling laws are the measured answer to where.
What is in this stage:
- the compute formula
C ≈ 6ND; - the Kaplan (2020) and Chinchilla (2022) results, and why they disagreed;
- the ~20 tokens per parameter rule, and why most small models are undertrained;
- the IsoFLOP method, run for real on our GPU;
- width vs depth;
- why inference cost moves the optimum (over-training small models on purpose);
- the domain questions for our project: 100% code vs 85/15 code/English, and what repeating data costs.
1. C ≈ 6ND
Stage 09 §1 counted the training cost: about 6N FLOPs per token for a model
with N non-embedding parameters (2 forward, 4 backward). A run over D
tokens therefore costs
C ≈ 6 · N · D FLOPs
Worked example: GPT-2 small's 85M non-embedding parameters on 2.5B tokens is
6 × 85e6 × 2.5e9 = 1.3e18 FLOPs. At 20 TFLOP/s sustained, that is 64,000
seconds, about 18 hours.
This formula is the budget. Every choice in this stage is a way of spending
a fixed C between N and D.
2. Two answers to the same question
Kaplan et al. (OpenAI, 2020) trained many models and fitted power laws:
loss falls smoothly as a power of N, of D, and of C. Their recommendation:
when compute grows 10×, grow the model about 5.5× and the data only about
1.8×. Models should be big, and trained on relatively few tokens. GPT-3 (175B
parameters, 300B tokens, under 2 tokens per parameter) followed this advice.
Hoffmann et al. (DeepMind, "Chinchilla", 2022) redid the experiment and
got a different answer: grow N and D equally. When compute grows 10×,
grow both by about √10 ≈ 3.2×. The best model for a budget sees about 20
tokens per parameter. They proved it by training Chinchilla, 70B parameters
on 1.4T tokens, with the same compute as the 280B-parameter Gopher. Chinchilla
beat Gopher on almost everything.
Why did the two disagree? Mostly the learning-rate schedule. Kaplan used one cosine schedule length for all runs and read losses off the middle of training. A model stopped before its schedule finished has not had its learning rate decayed (Stage 08 §4), so its loss is worse than it would be in a run of that length. That penalised long training, i.e. many tokens, and made big-model, few-token runs look better than they were. Chinchilla tuned the schedule to each run's length.
The lesson for us is practical: every run in a scaling study must have its schedule set to its own length. Our IsoFLOP runs do.
3. The IsoFLOP method
Chinchilla's cleanest approach is the IsoFLOP curve:
- Fix a compute budget
C. - Pick several model sizes
N₁ < N₂ < ... < N₅. - For each, set
D = C / (6N)and train with a full schedule. - Plot final loss against
N. The curve is U-shaped: too small a model cannot learn enough; too big a model sees too few tokens. - The bottom of the U is the best size for that budget.
Repeat at a few budgets and the bottoms trace out the compute-optimal
frontier: how N_opt grows with C.
loss
│ ╲ ╱
│ ╲ ╱
│ ╲ ╱
│ ╲ ● ╱ one compute budget
│ ╲__________╱
│ ↑
│ N_opt
└──────────────────────────── N (log scale)
We can afford this at small scale: budgets around 1e16 FLOPs, models from
~4M to ~60M non-embedding parameters, each run 10-30 minutes on the 4060.
4. Width vs depth
For a fixed N, should the model be wide and shallow, or narrow and deep?
N ≈ 12·L·C² lets many (L, C) pairs give the same N.
Kaplan found that loss depends mostly on N, and only weakly on the shape,
over a wide range of aspect ratios (C/L from ~20 to ~200). Outside that
range, things go wrong:
- too shallow: few layers means few rounds of tokens exchanging information. Multi-step patterns need depth.
- too narrow: tiny head size, and the per-token vector cannot hold much.
- too deep for the width: on our GPU, also slow. Each layer is a sequence of small matmuls, and small matmuls use the GPU poorly (Stage 09).
For the speed reason, at small scale we keep C/L around 64 (GPT-2 small is
768/12 = 64) and head size 64.
5. Why inference changes the answer
Chinchilla minimises training compute for a given loss. But a model that
is going to be used a lot also costs compute every time it runs, and
inference cost scales with N, not D.
A model 2× smaller than Chinchilla-optimal, trained on 4× more tokens, can reach the same loss for somewhat more training compute and is then half the price to run, forever. That is why Llama 1 7B saw 1T tokens (~140 per parameter), and Llama 3 8B saw 15T (~1,900 per parameter). They are deliberately "over-trained" by Chinchilla's standard.
The cost of over-training is diminishing returns: each doubling of D gives a
smaller loss drop. §8c measures one model trained to 10× its Chinchilla
token count.
6. Our two domain questions
Mix ratio. Our data is 85% Python and 15% English (Stage 02). Does the English cost code performance at a fixed budget, or help it? Code loss is the number that matters for HumanEval. English might help (natural-language docstrings and comments are part of code) or might just take budget away. §8d trains both at the same compute.
Repeating data. We have about 2.36B tokens. A 92M-parameter model at 20 tokens per parameter wants 1.8B; at our planned 2.5B, that is about 1.06 epochs. How much does seeing data a second time cost? Muennighoff et al. (2023) found that up to ~4 epochs, repeated data is worth almost as much as fresh data. §8e measures it at our scale: the same budget, on fresh data vs a quarter of the data repeated four times.
7. Build order and acceptance criteria
stages/10_scaling/run.py uses llmfs.train.trainer unchanged (with the
Stage 09 settings). Per run: model shape, N, D, C, final val loss on
code and English, wall time.
- IsoFLOP at two budgets, five sizes each, every schedule set to its own length;
- a fitted parabola in
log Nper budget, its minimum reported with tokens-per-parameter; - the measured optimum compared with Chinchilla's 20 tokens per parameter;
- an over-trained run: one size, 10× its optimal tokens;
- mix 100/0 vs 85/15 at one size and budget;
- fresh vs 4-epoch data at one size and budget;
- the capstone config chosen from these numbers, with the reasoning written down.
8. Experiments
Every run: GPT with QK-norm (§8f), T=512, 16 sequences per step, AdamW,
warmup then cosine set to the run's own length, lr scaled mildly with width
(1.1e-3 at C=192 down to 6.5e-4 at C=640). Compute per token counted
honestly as 6N + 6CV + 12LTC (Stage 09 §1), so small models, whose output
head and attention are a large share of their FLOPs, are not flattered.
8a. IsoFLOP curves
| model | params (total) | 3e15 FLOPs: tokens/param, val code |
1e16: tokens/param, val code |
|---|---|---|---|
| 2 layers, C=128 | 1.5M | 194, 2.480 | — |
| 3 layers, C=192 | 3.0M | 48, 2.329 | 158, 2.184 |
| 4 layers, C=256 | 5.4M | 15, 2.279 | 49, 2.065 |
| 6 layers, C=384 | 14.0M | 2.2, 2.481 | 7.4, 2.055 |
| 8 layers, C=512 | 29.7M | 0.5, 3.667 | 1.7, 2.241 |
| 10 layers, C=640 | 54.8M | — | 0.5, 2.622 |
Both budgets give the U of §3: too small a model saturates (the 1.5M model at 194 tokens per parameter), too big a model barely starts (the 30M model at half a token per parameter is still at 3.67). Each run is 4-20 minutes; the two sweeps together took about 3 hours.
8b. The frontier and the capstone choice
A parabola in log N through each budget's points, its minimum, and
Chinchilla's prediction N = √(C/120) (which is D = 20N with C = 6ND):
| budget | fitted optimal N | tokens per parameter | Chinchilla's N |
|---|---|---|---|
3e15 |
4.2M | 28 | 5.0M |
1e16 |
8.6M | 22.5 | 9.1M |
At our scale, on our data, with our tokenizer, the Chinchilla rule holds to within 15%. The optimum grows with compute (3.3× more compute, 2.0× larger model; Chinchilla says √3.3 = 1.8×), and the tokens-per-parameter ratio lands at 22-28 against Chinchilla's 20. Two budgets and five points each is a thin basis for a law, and the fitted minima are sensitive to single runs (the v1 sweep's diverged runs would have moved them a lot). What it does support is the order of magnitude: on this data, a model should see a few tens of tokens per parameter.
For the capstone (Stage 11), the frontier says: at 92M parameters, about 1.8-2.3B tokens. That is what 20 hours of the 4060 buys at 25.4k tokens/s (Stage 09), and it is what our data supports (§8e: 1.15 epochs of code). The capstone is planned at 1.8B tokens, 20 per parameter, on the compute-optimal line rather than past it.
8c. Ten times past optimal
The 3-layer, 3.0M model, trained to 1×, 2×, 5× and 10× its Chinchilla token count (20 per parameter = 60M tokens):
| tokens | ×optimal | val code | gain over previous |
|---|---|---|---|
| 60M | 1 | 2.534 | — |
| 120M | 2 | 2.365 | −0.169 |
| 301M | 5 | 2.228 | −0.137 (for 2.5×) |
| 601M | 10 | 2.178 | −0.050 (for 2×) |
Training 10× longer improves the loss by 0.36 nats, but the last doubling
of compute buys only 0.05. Compare the IsoFLOP table: the 10× run used
1.25e16 FLOPs (20.9M × 601M) and reached 2.178; the best model at 1e16,
with 20% less compute, reached 2.055. Spending the compute on a bigger
model would have been far better for loss. Over-training is worth it only
when the model's size is fixed by something else, such as inference cost
(§5) or, for us, GPU memory.
8d. Code only vs 85/15
The 4-layer model, 5.4M parameters, 108M tokens (20 per parameter), same compute, three mixes:
| mix | val code | val English |
|---|---|---|
| 100% code | 2.182 | 5.308 |
| 85% code / 15% English (ours) | 2.204 (+0.022) | 4.046 |
| 70% / 30% | 2.260 (+0.079) | 3.844 |
Taking 15% of the budget away from code costs 0.022 nats of code loss and buys 1.26 nats of English. At 30% the code cost is 3.6× larger. The 85/15 choice from Stage 02 holds up: the English is nearly free for code and transforms the model's English (5.31 is barely above unigram-level English; 4.05 writes sentences). Whether that English helps follow instructions after SFT (the curriculum's second question) is for Stage 16.
8e. Fresh vs repeated data
Same model and budget (108M tokens, code only), with fewer unique tokens seen more times:
| unique code tokens | epochs | val code | cost |
|---|---|---|---|
| 108M | 1 | 2.176 | — |
| 27M | 4 | 2.288 | +0.112 |
| 6.7M | 16 | 2.803 | +0.627 |
Four epochs cost 0.11 nats, 5% of the loss; sixteen cost 0.63. This is a larger penalty than Muennighoff et al. (2023) report for 4 epochs ("almost as good as fresh"), and there is a confound we did not remove: the repeated slice is the first 27M (or 6.7M) tokens of the file, a contiguous run of repositories, so it is less varied as well as smaller. Part of the cost is diversity, not repetition. The Stage 11 capstone sees 1.15 epochs of code: far closer to the fresh-data end, where we expect the cost to be small, but we did not measure 1.15 epochs directly.
8f. The sweep that diverged, and QK-norm
The first IsoFLOP sweep used the plain GPT-2 recipe that had trained cleanly
in every stage so far. The 4-layer, C=256 model failed in all four of its
long runs: gradient norms climbed into the tens and thousands after about
6,000 steps, and the 100% code run ended at a code loss of 3.52, worse
than the same model reaches in 2,000 steps. A probe on one fixed batch every
250 steps found the cause. The largest attention score q·k/√d in block 1:
step 0 1000 3000 5000 6000 6500 7000 8000 12000
max score 0.6 35 62 70 218 575 14,207 262,641 1,998,983
grad norm 3.9 1.06 1.59 1.16 1.52 2.30 3.40 18.7 32.5
The score grew slowly for 5,000 steps, then ran away: a score of 14,000 makes the softmax exactly one-hot, and the gradient through a saturated softmax is large and erratic (Stage 04 §3). The largest gradient in the network sat in that block's LayerNorm. The attention score moved 1,000 steps before the gradient norm did, and 6,000 steps before the loss. This is the attention-logit-growth instability (Dehghani et al. 2023; Wortsman et al. 2023), usually discussed for billion-parameter runs, here in a 5M model, by running it 3-4× longer than any earlier stage did.
The same run, 13,000 steps, one change at a time:
| variant | code val | max grad norm | max attention score |
|---|---|---|---|
| as in the sweep (lr 1e-3) | 2.656 | 269 | 2,191,156 |
| lr 5e-4 | 2.431 | 3.9 | 117 |
| QK-norm, lr 1e-3 | 2.280 | 3.8 | 37 |
| B=32, T=256 (Stage 06's shape) | 2.476 | 3.8 | 78 |
QK-norm (normalise each head's q and k to rms 1 times a learned gain,
Stage 12 §5) bounds the score by construction and keeps the higher learning
rate, which is worth another 0.15 nats over simply halving it. Every run in
§8a-e uses QK-norm. The diverged first sweep is kept in
results/10_scaling/v1_no_qknorm/.
9. What we found
| Question | Answer, measured |
|---|---|
| Does the plain GPT-2 recipe survive long runs? | No: the 4L/256 model diverged in all 4 long runs. Attention scores grew to 2M; QK-norm fixed it and was 0.15 better than halving lr |
Compute-optimal size, 3e15 FLOPs |
4.2M parameters, 28 tokens/param (Chinchilla: 5.0M) |
Compute-optimal size, 1e16 FLOPs |
8.6M parameters, 22.5 tokens/param (Chinchilla: 9.1M) |
| 10× past optimal? | −0.36 nats in total; the last doubling only −0.05. A bigger model with less compute did better |
| Code-only vs 85/15? | 85/15 costs 0.022 code nats and gains 1.26 English nats |
| Repeated data? | 4 epochs +0.11, 16 epochs +0.63 (with a diversity confound) |
| Capstone | 92M parameters, 1.8B tokens (20/param): on the line, and what 20 GPU-hours buy |
Two habits from this stage:
- Log the leading indicator, not just the loss. The attention-score maximum moved 6,000 steps before the loss did. A scaling sweep is many long runs, and every one of them can fail quietly.
- Rerun the whole sweep when the recipe changes. Patching only the failed points would mix two recipes in one curve.
Chapter 13
The real pretraining run
Everything so far has been a rehearsal: runs of minutes, models of a few million parameters. This stage is the performance: the model every later stage fine-tunes, aligns, quantizes and serves. It is trained once, for roughly a day, on the 2.36B-token code + English corpus from Stage 02.
A long run fails in ways a short one cannot. The power goes out at hour 19. The loss spikes at hour 7 and you need to know whether to wait or restart. The resumed run quietly re-reads data it already saw. This stage is mostly about those failures, and the habits that survive them.
What is in this stage:
- two models: the ~30M workhorse, trained first and used to find every bug, and the capstone base model;
- checkpointing and resuming that is actually correct: model, optimizer, data position and random state;
- evaluation during training, and why validation loss alone is not enough;
- logging, and how to read a long loss curve;
- loss spikes and what to do about them;
- determinism and seeds;
- the ablation: stop the run, resume it, and prove the curve is continuous.
1. Why two models
The project rule (CLAUDE.md): never debug on the capstone. A bug found after 20 hours costs 20 hours. The same bug found on a 2-hour run costs 2.
The workhorse uses exactly the same code path, config format, tokenizer, data and loop as the capstone; only the size differs. Anything that breaks on the capstone and not the workhorse is about scale (memory, numerics), which narrows the search a lot.
2. What a checkpoint must hold
A checkpoint that holds only the model's weights lets you use the model. To continue training it, you need everything that affects the next step:
| Piece | Why | What breaks if it is missing |
|---|---|---|
| model weights | obviously | nothing to resume |
optimizer state (Adam's m and v) |
Adam's step size per weight depends on them (Stage 08 §2) | resumed run behaves like step 1 of a new one: every weight jumps ±lr, a visible loss spike |
| step number | the learning-rate schedule is a function of it | warmup reruns, or the cosine restarts at the peak |
| data position (sampler epoch, position, RNG) | which windows come next | the model re-reads data it already saw, or skips some |
| random number state (torch CPU and CUDA) | dropout masks, sampling | runs are not reproducible across a resume |
| config | to rebuild the same model | a silent shape or setting mismatch |
The data position is the one people forget. A resumed run that restarts the sampler at epoch 0 will feed the model the first hours of data again. The loss on it drops slightly (it has seen it), which looks like good progress and is not.
Our trainer (llmfs/train/trainer.py, Stage 08) saves all six. Our sampler
(Stage 02) was designed for this: its epoch permutation is a pure function of
(seed, epoch), so its whole state is two integers.
Saving safely. Write the checkpoint to a temporary file, then rename it
over the old one. A rename is atomic on Linux; a crash halfway through
torch.save then leaves the previous checkpoint intact instead of a
half-written file.
3. Evaluating during training
Every few hundred steps the trainer computes loss on fixed validation windows: the same windows every time, so the numbers are comparable along the run.
Validation loss answers "is the model still improving on data it has not seen?" It does not answer "is the model any good at what we want?" Two models with the same loss can differ in what they get right. For us the real target is writing working Python (Stage 22's HumanEval). So the run also logs:
- separate code and English val loss: the mix ratio means one can improve while the other stalls;
- samples from fixed prompts at fixed seeds, every few thousand steps: the fastest way to see that something is off (repetition, broken indentation);
- gradient norm every step: spikes show up here first.
4. Reading a long loss curve
Over a long run, the train loss falls roughly as a power law: fast at first, then slower and slower. On a log-log plot that is close to a straight line. Three things to watch for:
- The end-of-schedule drop. As the cosine schedule brings the learning rate down, loss falls faster again. This is not the model "suddenly learning": smaller steps let it settle into the minimum it was circling around (Stage 08 §4).
- Spikes. A sudden jump in loss, usually with a jump in gradient norm. Most recover within a few hundred steps. One that does not recover, or that grows, means the run has diverged.
- Train/val gap. With ~1 epoch of data, train and val loss should track each other closely. A growing gap means repeated data is being memorised, or the val set differs in kind from train.
Loss spikes: what to do
From the big-model literature (PaLM, OPT, BLOOM logbooks):
- Wait a few hundred steps. Most spikes recover.
- If not: roll back to a checkpoint before the spike and skip the batches around it. Many spikes are caused by specific bad data.
- If spikes keep coming: lower the learning rate, or check the numerics (bf16 overflow in attention logits, which QK-norm fixes; Stage 12).
Our safety rails (warmup, clipping, β₂ = 0.95, bf16, pre-norm) are each a lesson from these logbooks. At our scale, spikes should be rare.
5. Determinism
Same seed, same code, same data should give the same run. In practice, GPU
training is not bitwise deterministic by default: some kernels (atomic
adds in backward passes) sum in a different order each time, and floating
point addition is not associative. Two runs from the same seed drift apart at
the 1e-6 level after the first step, and the gap grows.
That is acceptable. What matters is statistical reproducibility: the same final loss to within the seed-to-seed spread. Stage 05 measured that spread as about ±0.01-0.03 for our small models. What is not acceptable is a resume that changes the curve by more than that spread. §8b tests exactly that.
6. The plan
From Stage 09's throughput and Stage 10's measurements, with one GPU:
| workhorse | capstone | |
|---|---|---|
| shape | 8 layers, C=512, 8 heads | 12 layers, C=768, 12 heads (GPT-2 small's body) |
| parameters | 30M (25.2M non-embedding) | 92M (85.1M non-embedding) |
| context | 1,024 | 1,024 |
| tokens per step | 16 × 1,024 × 2 = 32,768 | 8 × 1,024 × 8 = 65,536 |
| steps | 18,000 | 27,500 |
| tokens | 590M (~20 per parameter) | 1.80B (~20 per parameter) |
| peak lr, warmup | 1e-3, 500 | 6e-4, 1,000 |
| attention | QK-norm (Stage 10 §8f) | QK-norm |
| expected time | ~2.4 h at 70k tokens/s | ~20 h at 25.4k tokens/s |
| data | 85% code / 15% English, shuffled windows | same |
Why these numbers:
- The capstone's size is set by the hardware. 12 layers × 768 is the largest GPT-2-family shape that trains at a useful speed in 8 GB (B=16 does not fit, Stage 09 §9d). Its 92M parameters (vs GPT-2's 124M) are the same body with our 8,196-entry table instead of 50,257.
- ~20 tokens per parameter is Chinchilla's rule. Our own sweep (Stage 10)
is far too small to extrapolate a frontier to
1e18FLOPs; at1e16it put the optimum at fewer tokens per parameter, which would argue for a larger model we cannot fit. A 20 h run is the time budget; 1.8B tokens is what that budget buys at this size. - 1.8B tokens at 85/15 is 1.15 epochs of our code and 0.27 of the English. Stage 10 §8e measured 4 epochs costing 0.11 nats (with a diversity confound); 1.15 epochs is much closer to fresh data, though not measured.
- QK-norm because the plain recipe diverged in Stage 10 at long run lengths; the capstone is the longest run in the project.
7. Acceptance criteria
- workhorse run completes; its val loss and samples are logged;
- resume test: a run stopped at step
s, resumed, gives a curve that overlays the uninterrupted run within the seed spread, with no spike ats; - a run resumed without optimizer state, as a control, does show the spike;
- capstone run completes, with log, config, checkpoints and samples;
- the capstone's val loss is better than the workhorse's by an amount consistent with Stage 10's fits.
8. Experiments
8a. The workhorse
29,941,760 parameters, 18,000 steps × 32,768 tokens = 590M tokens in 2 h 18 min (71k tokens/s, as Stage 09 predicted).
step 0 3,000 6,000 9,000 12,000 15,000 18,000
val code 9.06 1.994 1.809 1.714 1.636 1.583 1.554
val Eng. 9.08 3.877 3.645 3.514 3.411 3.333 3.293
Gradient norm: 7.7 at step 0, then never above 1.49 after step 1,000. No spikes, no instability: QK-norm and the warmup did their jobs. The last third of the run (cosine decay) still bought 0.08 nats of code loss.
For scale: the Stage 06 model (5M, 98M tokens) ended at 2.358 code loss on 256-token windows; the workhorse is 0.8 nats better with 6× the parameters and 6× the data.
What it writes from import os\nimport json\n\n\ndef load_config(path):
at τ = 0.8:
def load_config(path):
try:
config = load(path)
except Exception as e:
raise e
import pprint
import requests
from requests.utils import parse_qs
from requests.exceptions import HTTPError
Real Python idioms, real library names, a plausible try/except, and then it
wanders off into a new file. Greedy decoding loops (def fibonacci(n): return (n - 1) * (n - 1) repeated, Stage 07's failure mode). One detail
matters for the benchmarks later: given a class indented with four spaces,
it continues with tabs, because both are common in its training data.
Mixed indentation is a syntax error in Python 3, and it will cost pass rate
in Stage 16 and 22.
8b. Resume, and resume done wrong
The 4-layer model, 1,200 steps, three ways: uninterrupted; stopped after
step 600 (process exits) and resumed from the checkpoint; and resumed with
everything restored except Adam's m and v.
The first attempt crashed. Resuming raised RNG state must be a torch.ByteTensor: the trainer loads checkpoints with map_location="cuda",
which also moved the saved CPU random-number state onto the GPU. One line
fixed it (.cpu() on restore). This is exactly why the resume test runs
before the capstone: the same bug at hour 12 of a 20-hour run would have
been a crashed restart and an evening lost.
After the fix:
step 580 600 610 620 640 660 final val
uninterrupted 4.151 4.667 4.615 4.437 4.358 4.435 3.9158
resumed 4.151 4.667 4.615 4.437 4.358 4.435 3.9158
resumed, no Adam 4.151 4.667 4.672 4.500 4.397 4.477 3.9323
The resumed run is bit-identical to the uninterrupted one: every logged loss, gradient norm and the final validation loss agree to all printed digits. Model, optimizer, sampler position and both random-number generators are restored exactly, and this short uncompiled run is deterministic.
Losing Adam's state shows as a step: +0.057 at step 610, still +0.04 fifty steps later, +0.017 at the end. Not a dramatic spike, because the learning rate at step 600 of a cosine schedule is already halfway down; but a permanent mark on the curve, from one forgotten dictionary entry. Forgetting the sampler position instead would leave no mark on the loss at all, and silently show the model data it had already seen.
8c. The capstone base model
92,138,496 parameters, 27,500 steps × 65,536 tokens = 1.80B tokens (19.6 per parameter). The run was paused by the owner at step 10,500 on 2026-11-08 and resumed from the checkpoint five days later; training time was about 20.4 GPU-hours in total (7.7 h before the pause, 12.7 h after, ~2.7 s per step).
step 3,000 6,000 9,000 12,000 15,000 18,000 21,000 24,000 27,500
val code 1.752 1.584 1.503 1.440 1.393 1.364 1.330 1.310 1.295
val Eng. 3.573 3.338 3.217 3.126 3.065 3.003 2.956 2.919 2.898
| workhorse (30M, 590M tokens) | capstone (92M, 1.80B tokens) | |
|---|---|---|
| val code | 1.554 | 1.295 (−0.26) |
| val English | 3.293 | 2.898 (−0.40) |
| GPU time | 2.3 h | ~20.4 h |
| max grad norm after step 1,000 | 1.49 | 1.03 |
The resume across the pause was continuous: step 10,500's loss and gradient norm equal the pre-pause log's exactly, and later steps agree to within 0.0003 (journal). Not bitwise, because this run is compiled and bf16 (§5); the Stage-11 resume test, uncompiled, was.
No spike in 27,500 steps. The gradient norm stayed below 1.03 after warm-up; QK-norm and the recipe from Stages 08-10 held at 3× the workhorse's length. The loss never stopped falling: the last 3,500 steps (cosine tail) bought 0.015 on code. Per token seen, the capstone is behind the workhorse until about 120M tokens (twice the batch, 60% of the learning rate, and three times the parameters to move), then ahead for the rest of the run: a bigger model is slower to start and better at the end, Stage 10's picture again.
What it writes. From import os\nimport json\n\n\ndef load_config(path):,
greedy, the capstone now writes a correct body before it starts repeating
itself:
def load_config(path):
config = json.load(open(path))
return config
At τ = 0.8 it writes plausible, idiomatic code that wanders (nested
functions, json.load(config_file), a loop over the result). The English is
grammatical at the sentence level and meaningless beyond it ("Higgins stands
for the manuscript"). Greedy decoding still loops on every prompt, and the
tab/space mixing seen in the workhorse is still there. 92M parameters and
1.8B tokens buy local fluency, not intent.

9. What we found
| Question | Answer, measured |
|---|---|
| Does the resume path work? | Yes: bit-identical (uncompiled test) and continuous to 1e-4 (compiled capstone, across a 5-day pause) |
| What does dropping Adam's state cost? | A visible step: +0.057 at once, +0.017 at the end of a short run |
| Workhorse | 30M, 590M tokens, 2.3 h: val code 1.554, English 3.293 |
| Capstone | 92M, 1.80B tokens, ~20.4 h: val code 1.295, English 2.898 |
| Instabilities | None: grad norm ≤ 1.03 after warm-up across 27,500 steps |
| Bugs found by the workhorse first | The RNG-restore device bug (resume test) |
One habit from this stage: run the resume test before the long run, and keep the long run's log honest. The resume test found a real bug in a minute; the pause found that a log can run past its checkpoint, and those lines have to go before resuming.
Chapter 14
Modern architecture: from GPT-2 to Llama
GPT-2 is from 2019. Almost every open model since 2023 (Llama 2 and 3, Mistral, Qwen, Gemma) uses the same handful of changes on top of it. This stage makes each change on our own model, one at a time, and measures what each one buys. They usually arrive as a bundle. Taken apart, each one gets its own number.
| Change | GPT-2 | Llama | Covered in |
|---|---|---|---|
| normalisation | LayerNorm | RMSNorm | Stage 05 §3 |
| positions | learned table | RoPE | Stage 03 §4 |
| MLP | GELU, 4C | SwiGLU, ≈8C/3 | Stage 05 §6 |
| biases | everywhere | none | §6 here |
| attention heads | MHA | GQA | §2 here |
| (optional) | QK-norm, sliding window | §4-§5 here |
The new ideas in this stage are the ones about attention's memory: GQA and MQA, sliding windows, RoPE scaling for longer context, QK-norm and attention sinks. The older ones were explained in Stages 03 and 05 and are only combined here.
The model is llmfs/model/llama.py. Every change is a config field, and with
all of them switched on it matches Hugging Face's LlamaForCausalLM to 1e-4
with copied weights (test_llama.py).
1. The upgraded block
x (B, T, C)
│
┌──────┤
│ ▼
│ RMSNorm was LayerNorm
│ ▼
│ q = x Wq (H heads)
│ k = x Wk (Hk heads) ← fewer was H heads
│ v = x Wv (Hk heads) ← fewer
│ rotate q, k by position (RoPE) was: add a position vector at the bottom
│ attention, each group of H/Hk query heads sharing one k, v
│ ▼
│ o_proj (no bias)
└─────(+)
│
┌──────┤
│ ▼
│ RMSNorm
│ ▼
│ SwiGLU: down( silu(gate x) ⊙ up x ) was: proj(gelu(fc x))
└─────(+)
2. GQA and MQA: sharing keys and values
2a. The problem: the cache
Stage 07 §6d measured the KV cache: for every token, every layer stores a key
and a value vector of size C. For a 7B model at 32k tokens, that is 16 GB,
more than the weights. During decoding, every step reads the whole cache from
memory (Stage 07 §6c), so the cache's size also sets the decode speed.
2b. The idea: fewer key/value heads
In multi-head attention (MHA), each of the H heads has its own query, key
and value projections. Multi-query attention (MQA, Shazeer 2019) keeps
H query heads but gives them one shared key head and value head.
Grouped-query attention (GQA, Ainslie et al. 2023) sits between: Hk key/
value heads, each shared by a group of H/Hk query heads.
MHA H=8, Hk=8: q q q q q q q q each q has its own k, v
k k k k k k k k
GQA H=8, Hk=2: q q q q | q q q q each group of 4 shares one k, v
k | k
MQA H=8, Hk=1: q q q q q q q q all 8 share one k, v
k
The cache shrinks by H/Hk. Llama 2 70B uses H = 64, Hk = 8: an 8× smaller
cache. Llama 3 8B uses H = 32, Hk = 8.
2c. The cost
Each query head still asks its own question (its own q), but heads in a
group must look at the same keys and read the same values. They can
weight positions differently, but they all choose among the same summaries of
the past. With Hk = 1, every head reads the same v vectors. That is less
expressive, and quality drops. The question GQA answers is how few kv heads
you can get away with. Ainslie et al. found that 8 groups recovers almost all
of MHA's quality at large scale.
Parameters shrink a little too: Wk and Wv go from C × C to C × Hk·d.
At matched parameter count, the savings can go back into the MLP. §9b compares
both ways: at the same architecture, and parameter-matched.
2d. The implementation detail
The cache stores Hk heads. At attention time, each kv head is
repeated H/Hk times so the shapes line up with the queries:
k: (B, Hk, T, d) → repeat_interleave(H/Hk, dim=1) → (B, H, T, d)
repeat_interleave, not repeat: heads 0-3 must share kv head 0, heads 4-7
kv head 1. repeat would give heads 0, 2, 4, 6 kv head 0, which is a
different (also valid, but HF-incompatible) grouping. A test against HF's
Llama catches the difference.
3. RoPE and longer context
RoPE (Stage 03 §4) rotates each pair of dimensions in q and k by an angle
proportional to the position, at a different speed per pair: the fastest pair
turns by 1 radian per token, the slowest by 1/10000 per token (θ = 10000).
A model trained on length 512 has seen rotations up to angle 512 × speed in
each pair. Beyond that, the slow pairs reach angles never seen in training,
and quality collapses (Stage 03 §10 measured it for learned and sinusoidal
positions).
Two families of fixes, both one-line changes to the angles:
- Position interpolation (Chen et al. 2023): divide every position by
s. Position 2,048 now looks like 512. But the fast pairs, which tell neighbours apart, are now squashed bystoo: adjacent tokens looks×closer than in training. - NTK-aware scaling (bloc97, 2023): increase the base
θinstead,θ' = θ · s^(d/(d−2)). That stretches the slow pairs by almost exactlysand leaves the fast pairs almost untouched. Neighbours still look like neighbours, and long distances map into the trained range.
Llama 3 raised θ to 500,000 at training time, which builds the stretch in
from the start. (test_ntk_scaling_keeps_fast_clocks checks the two
properties.) §9d measures loss past the training length with and without
NTK scaling, with no fine-tuning.
4. Sliding-window attention
Full causal attention lets token t see all t earlier tokens: compute and
cache grow with T. Sliding-window attention (Longformer; used in Mistral
7B with window 4,096) lets each token see only the last W tokens.
full window W = 3
1 . . . . . 1 . . . . .
1 1 . . . . 1 1 . . . .
1 1 1 . . . 1 1 1 . . .
1 1 1 1 . . . 1 1 1 . .
1 1 1 1 1 . . . 1 1 1 .
1 1 1 1 1 1 . . . 1 1 1
The cache only needs the last W tokens: bounded memory, however long the
text. Information still travels further than W, layer by layer: after L
layers, a token can be influenced by one L·W back, the way a stack of
small convolutions has a large receptive field.
For code, what is lost is the direct look-up of something far away (an import at the top of the file, a function defined 2,000 tokens earlier). §9c measures the loss for a window of 64 and 128 at training length 512.
5. QK-norm and attention sinks
QK-norm (Dehghani et al. 2023, used in OLMo 2, Gemma 3): apply an RMSNorm
to each head's q and k before the dot product. Without it, q · k can
grow without limit as weights grow, the softmax saturates, and the gradients
through it vanish or explode (Stage 04 §3 showed what a saturated softmax does
to gradients). This is a known cause of loss spikes in large runs. With
QK-norm, each q and k has rms 1 (times a learned gain), so scores stay in
a controlled range. At our scale it should matter little for loss; it is a
stability measure.
Attention sinks (Xiao et al. 2023). Stage 04 found heads that put most of their attention on the first token, whatever it is. Softmax must give out a total weight of 1; a head with nothing useful to read puts the weight on a token whose value vector does little, and the first token, visible to everyone, becomes that dumping ground. It matters for sliding windows and streaming: if the first token falls out of the window, those heads lose their sink and quality drops sharply. StreamingLLM's fix keeps the first few tokens in the cache forever. We measure how much attention our trained model sends to position 0 (§9e).
6. No biases
Llama has no biases in any linear layer, and RMSNorm has no shift. The argument: with pre-norm and enough width, biases add parameters and memory traffic and buy nothing measurable; the norms already centre (or do not need to centre) the signal. §9a measures it as its own step.
7. Parameter counts
Per block, with C width, d head size, Hk kv heads, Hd MLP hidden size:
attention: C·C (q) + 2·C·(Hk·d) (k, v) + C·C (o)
SwiGLU: 3·C·Hd
norms: 2·C (RMSNorm: gain only)
SwiGLU with Hd = 8C/3 has 3 · C · 8C/3 = 8C², the same as GELU's
2 · C · 4C. We round Hd up to a multiple of 64 for GPU-friendly shapes,
as Llama does (multiple_of), which adds a fraction of a percent.
8. Build order and acceptance criteria
llmfs/model/llama.pywith the switches in the module docstring;test_llama.py:- all switches on: logits match HF
LlamaForCausalLMwithin 1e-4, for MHA, GQA and MQA; - KV-cache decoding matches full recompute, for every switch combination, including multi-token chunks after the cache is filled;
- the sliding window really hides tokens outside it;
- GQA's cache and parameter savings match the formulas;
- NTK scaling leaves the fastest pair alone and slows the slowest by
s.
- all switches on: logits match HF
run.py ladder: GPT-2 baseline, then each change added in turn;run.py gqa:Hk∈ {8, 4, 2, 1} atH = 8, plus a parameter-matched MQA; KV bytes per token next to loss;run.py window,run.py rope_scale,run.py sinks.
9. Experiments
Every run: 6 layers, C=384, 8 query heads of 48, T=512, B=16, 4,000 steps (33M tokens of the 85/15 mix), lr 1e-3, same seed and data order.
9a. The ladder: one change at a time
Two seeds per row; each row adds one change to the row above.
| change | val code (seed 0 / 1) | mean | Δ | params |
|---|---|---|---|---|
| GPT-2 style (LayerNorm, learned positions, GELU, biases, MHA) | 2.510 / 2.526 | 2.518 | — | 13.99M |
| + RMSNorm | 2.556 / 2.546 | 2.551 | +0.033 | 13.99M |
| + RoPE | 2.320 / 2.321 | 2.321 | −0.230 | 13.79M |
| + SwiGLU | 2.297 / 2.294 | 2.295 | −0.026 | 13.79M |
| + no biases | 2.305 / 2.303 | 2.304 | +0.009 | 13.77M |
| + GQA, 2 kv heads | 2.319 / 2.340 | 2.329 | +0.026 | 12.44M |
| + QK-norm | 2.271 / 2.277 | 2.274 | −0.055 | 12.44M |
From GPT-2 to the full Llama-style block: 2.518 → 2.274, −0.244, with 11% fewer parameters and a 4× smaller KV cache. Almost all of it comes from two rows:
- RoPE is worth 0.23 nats, by far the largest change. Stage 03 measured RoPE vs learned positions at 0.17 on a smaller model; here the gap is larger. Learned positions must learn every position's vector separately from data; RoPE gives relative position for free.
- QK-norm is worth 0.055 at this learning rate, more than SwiGLU. Stage 10 showed why: it lets a high learning rate train without attention scores running away.
- RMSNorm costs 0.03, the same small, consistent penalty as Stage 05 (+0.023). Its case is speed (Stage 05 §10e), not quality.
- No biases: +0.009, inside the seed spread. Llama's claim, "biases buy nothing", holds.
- SwiGLU: −0.026, close to Stage 05's −0.038.
The seed spread is 0.001-0.022 per row. Anything under ~0.02 is a tie.
9b. MHA → GQA → MQA
Same Llama block (RMSNorm, RoPE, SwiGLU, no bias, no QK-norm), one seed, varying the number of key/value heads for 8 query heads:
| kv heads | KV cache per token | params | val code | Δ vs MHA |
|---|---|---|---|---|
| 8 (MHA) | 9,216 B | 13.77M | 2.306 | — |
| 4 | 4,608 B | 12.88M | 2.305 | −0.002 |
| 2 | 2,304 B | 12.44M | 2.315 | +0.009 |
| 1 (MQA) | 1,152 B | 12.22M | 2.335 | +0.029 |
| 1 + params back into the MLP | 1,152 B | 13.77M | 2.328 | +0.022 |
Halving the cache (8 → 4 kv heads) costs nothing. Quartering it costs 0.009, inside seed noise (the ladder's two GQA seeds differ by 0.022). Only MQA, an 8× smaller cache, shows a cost, 0.03 nats, and giving MQA's saved parameters to the MLP buys back only a quarter of it: the loss is about sharing, not parameter count. That is the GQA paper's picture at small scale: a few kv groups recover nearly all of MHA's quality. Where quality breaks: between 2 kv heads and 1.
9c. Sliding windows
Llama block with 2 kv heads, trained and evaluated at T=512, with each token
allowed to see only its last W tokens. Overall val loss, and loss by
position in the window (64 val windows):
| W | val code | pos 0-16 | 16-64 | 64-128 | 128-256 | 256-512 |
|---|---|---|---|---|---|---|
| full | 2.314 | 3.82 | 2.80 | 2.45 | 2.20 | 1.97 |
| 128 | 2.424 (+0.11) | 3.78 | 2.75 | 2.42 | 2.31 | 2.25 |
| 64 | 2.559 (+0.24) | 3.78 | 2.73 | 2.55 | 2.57 | 2.48 |
| 16 | 3.141 (+0.83) | 3.79 | 3.14 | 3.03 | 3.21 | 3.08 |
The full-attention curve keeps falling with position: tokens 256-512 are
predicted 0.5 nats better than tokens 16-64, because more of the file is
visible. A windowed model's curve goes flat once position passes W:
beyond that, it sees no more than it did at position W. So the cost of a
window is concentrated in long files, which is exactly where code needs it
(imports, earlier definitions).
Two details worth noticing. Within their window, the windowed models are slightly better than full attention (window 64 at positions 16-64: 2.73 vs 2.80): a small model with fewer positions to attend over spends less capacity on far context. And six layers × 64 tokens is a 384-token "receptive field" in principle, yet window-64 loses 0.5 nats at positions 256-512: information passed hop by hop through layers is a poor substitute for a direct look.
9d. Longer than trained: NTK scaling
The final ladder model (RoPE, trained at T=512 only), evaluated on longer
windows with the RoPE base stretched by s (§3), no fine-tuning (32
windows per length):
| context | s |
loss at 256-512 | at 512-1024 | at 1024-2048 |
|---|---|---|---|---|
| 1,024 | 1 | 1.96 | 2.20 | — |
| 1,024 | 2 | 1.98 | 2.00 | — |
| 1,024 | 4 | 2.03 | 2.01 | — |
| 2,048 | 1 | 1.94 | 2.09 | 2.56 |
| 2,048 | 2 | 1.96 | 1.87 | 2.23 |
| 2,048 | 4 | 2.03 | 1.86 | 2.19 |
Without scaling, positions past 512 get worse the further out they are
(2.20 at 512-1024, 2.56 at 1024-2048), but RoPE does not collapse the way
learned positions did in Stage 03: relative rotations beyond the trained
range are unfamiliar, not meaningless. With NTK scaling s = 2, positions
512-1024 are as good as positions 256-512 were at training length, and with
s = 4, positions 1024-2048 recover 0.37 of the 0.6 lost. The cost: a
small loss at short range (0.02-0.07 at positions 256-512), because the
slow clocks no longer turn at the speed the model learned. A short
fine-tune at the new length usually removes it; we did not.
9e. Attention sinks
Mean attention weight on token 0, for queries past position 32, in the final ladder model (QK-norm on). Uniform attention over the visible prefix would give 0.0057:
layer 1 0.005 0.005 0.005 0.005 0.006 0.006 0.005 0.005
layer 2 0.005 0.003 0.002 0.005 0.002 0.002 0.002 0.001
layer 3 0.001 0.002 0.001 0.000 0.000 0.000 0.000 0.000
layer 4 0.002 0.002 0.001 0.000 0.000 0.001 0.000 0.002
layer 5 0.002 0.002 0.001 0.000 0.002 0.000 0.001 0.006
layer 6 0.019 0.005 0.010 0.047 0.007 0.051 0.058 0.009
No strong sinks. Most heads put less than uniform weight on token 0; the strongest, in the last layer, put 5-6%, ten times uniform but nothing like the sink heads Stage 04 found in a GPT-2-style model (which sent most of their weight to position 0). One plausible reason: QK-norm bounds every score, so no single key can win a softmax by an enormous margin, which is how a sink forms. We did not run the matching model without QK-norm, so this is a hypothesis, not a measurement.
10. What we found
| Question | Answer, measured |
|---|---|
| GPT-2 → full Llama block | 2.518 → 2.274 (−0.244), 11% fewer parameters, 4× smaller cache |
| Biggest single change | RoPE, −0.230 |
| QK-norm | −0.055: worth more than SwiGLU (−0.026) at lr 1e-3 |
| RMSNorm, no biases | +0.033 and +0.009: costs within noise, kept for speed and simplicity |
| How few kv heads? | 4 and 2 heads: free (±0.01); 1 head (MQA): +0.03, and extra MLP width buys back only a quarter |
| Sliding window | +0.11 (W=128), +0.24 (W=64), +0.83 (W=16); loss stops improving with position past W |
| Longer than trained | RoPE degrades gently; NTK s=2 at 2× length recovers fully, s=4 at 4× recovers 0.37 of 0.6 |
| Attention sinks | none strong with QK-norm (max 5.8% on token 0) |
One habit from this stage: when a change arrives in a bundle, unbundle it before believing any part of it. "Llama is better than GPT-2" is true here, but 94% of it is one change (RoPE), and two of the bundle's changes cost a little.
Chapter 15
Mixture of Experts
Every model so far has been dense: every parameter is used for every token. Making the model bigger makes every token more expensive.
A Mixture of Experts (MoE) model breaks that link. It replaces each MLP with many smaller MLPs, the experts, and a small router that sends each token to just a few of them. The model can hold 4×, 8× or 50× more parameters while each token still pays for only the few experts it visits. Mixtral 8x7B has 47B parameters and uses 13B per token. DeepSeek-V3 has 671B and uses 37B.
This stage builds an MoE layer from scratch, trains it head to head against a dense model with the same active parameters, and then breaks the router to watch the classic failure, expert collapse.
Shape letters: N tokens in the batch (B·T, flattened, because routing is
per token), C width, E experts, k experts per token.
1. The picture
dense block: x ── MLP (C → 4C → C) ── + x
every token, every weight
MoE block: x ── router ── probabilities over E experts
│ (N, E)
│ pick the top k (here k = 2)
│
├──→ expert 3 ──┐ × 0.7
├──→ expert 6 ──┤ × 0.3 the other E−k experts
│ │ never see this token
└───────────── (Σ) ── + x
Attention, norms and embeddings stay dense and shared. Only the MLP is split. That is where two thirds of a block's parameters are (Stage 05 §5), and it is the part where each token is processed alone, so tokens can be sent to different places without breaking anything.
2. Total vs active parameters
Our setup: a dense SwiGLU MLP has hidden size Hd. The MoE layer has E = 8
experts, each a SwiGLU with hidden size Hd/2, and each token uses k = 2.
dense MLP: 3 · C · Hd params, all used per token
one expert: 3 · C · Hd/2
MoE total: 8 · 3 · C · Hd/2 = 4 × dense
MoE active: 2 · 3 · C · Hd/2 = 1 × dense ← same FLOPs per token
So the MoE model has about 4× the MLP parameters with the same compute per token. That is the fair comparison the curriculum asks for: an active-parameter-matched dense baseline. If the MoE wins, it won by having more parameters to store knowledge in, not by doing more arithmetic.
The cost is memory: all experts must be in GPU memory, even though each token uses two. That is why MoE models are cheap to run per token but expensive to host.
3. The router
The router is one linear layer, C → E, followed by a softmax:
logits = x · W_router (N, E)
probs = softmax(logits) (N, E), rows sum to 1
w, idx = top-k(probs) (N, k): which experts, and how much
w = w / sum(w) renormalise over the chosen k
y = Σ_j w_j · expert_{idx_j}(x)
Why the weights matter. If every chosen expert were weighted 1, the router
would get no gradient at all: top-k is a hard selection, and you cannot
differentiate "which one was picked". Multiplying by w makes the output
depend smoothly on the router's probabilities, so the router learns: an
expert that helped the loss gets a larger weight next time.
Top-k picking is still discontinuous. A token whose second- and third-choice experts have nearly equal probability can flip between them from one step to the next. This is part of why MoE training is noisier than dense training.
4. The hard part: load balance
4a. Collapse
Picture the start of training. By chance, expert 3 is slightly better than the others. The router sends it more tokens. Expert 3 gets more gradient, so it improves faster. The router sends it even more. The other experts get almost no tokens and almost no gradient, and never catch up.
This feedback loop ends in expert collapse: one or two experts process nearly everything, and the rest are dead weight. The model has 4× the parameters on paper and the quality of a dense model in practice (or worse, since its working experts are half-size).
4b. The auxiliary load-balancing loss
The Switch Transformer (Fedus et al. 2021) adds a loss that is smallest when
the load is even. For each expert i:
f_i= the fraction of token assignments that went to experti(counted from the hard top-k choices);P_i= the average router probability for expertiover the batch.
aux = E · Σ_i f_i · P_i
Why this form. f_i is a count: it has no gradient. P_i is smooth: it
does. The product says "for experts that are already overloaded (large f_i),
push their probability P_i down". The gradient of aux with respect to
P_i is E · f_i, so overloaded experts are pushed hardest.
Why multiply by E. With perfect balance, f_i = P_i = 1/E for every
expert, and aux = E · E · (1/E)(1/E) = 1. With total collapse onto one
expert, f = P = 1 for that expert and aux = E. So aux runs from 1
(balanced) to E (collapsed) whatever E is, and one coefficient (we use
0.01) works across expert counts. test_moe.py checks both ends.
4c. Capacity and dropped tokens
In a real distributed system each expert lives on a GPU with a fixed buffer. The capacity factor sets the buffer size:
capacity = capacity_factor · N · k / E tokens per expert per batch
With factor 1.0 and perfect balance, every slot is used. Any imbalance means some expert gets more tokens than it has slots. The overflow tokens are dropped: they skip the MLP for this layer and pass through on the residual stream alone. Factors of 1.25-2.0 are common. Our layer supports a capacity, and by default it has none (every token is processed), because on one GPU there is no fixed buffer to overflow.
5. Router z-loss
ST-MoE (Zoph et al. 2022) found that router logits tend to grow large over training. Large logits make the softmax nearly one-hot and numerically fragile in bf16, a source of loss spikes. The z-loss penalises their size:
z = mean over tokens of ( logsumexp(logits) )²
logsumexp is close to the largest logit, so this keeps the largest logit
near zero. Coefficient 0.001. It is a stability measure, like QK-norm
(Stage 12 §5) for attention.
6. Shared and fine-grained experts
DeepSeek-MoE (2024) changed two things, both now common:
- Fine-grained experts. Instead of 8 experts of hidden size
Hd/2with top-2, use 32 experts ofHd/8with top-8. The same active compute, but far more ways to combine experts: C(8,2) = 28 possible pairs versus C(32,8) ≈ 10.5 million combinations. Experts can specialise more narrowly. - Shared experts. One or two experts that every token always uses, plus the routed ones. Common knowledge (syntax, frequent words) goes into the shared expert once, instead of being copied into every routed expert.
Our MoE layer supports both (n_shared, and any E, k). §9d measures them.
7. What we do not build: expert parallelism
On one GPU, all experts live in one memory, and our dispatch is a loop over experts. At scale, experts are spread across GPUs: GPU 0 holds experts 0-7, GPU 1 holds 8-15, and so on. Each MoE layer then needs two all-to-all communications: every GPU sends each of its tokens to the GPU holding that token's experts, and the results come back.
GPU 0 tokens ──┐ ┌──→ GPU 0 experts ──┐ ┌──→ GPU 0 tokens
GPU 1 tokens ──┼─────┼──→ GPU 1 experts ──┼─────┼──→ GPU 1 tokens
GPU 2 tokens ──┘ └──→ GPU 2 experts ──┘ └──→ GPU 2 tokens
all-to-all compute all-to-all back
This is why load balance matters even more in production: an overloaded expert's GPU makes every other GPU wait.
Why MoE is harder to fine-tune and serve. Fine-tuning on a narrow dataset can shift routing and unbalance it again, and the experts each see only a fraction of the fine-tuning data. Serving needs every expert resident in memory (all 47B of Mixtral's parameters, for 13B active), and batching is less efficient because different tokens in a batch need different experts.
8. Build order and acceptance criteria
llmfs/model/moe.py (the layer) and the n_experts switch in
llmfs/model/llama.py.
- one expert with top-1 equals the dense MLP with the same weights;
- the output equals the hand-computed weighted sum of the chosen experts;
aux= 1 when balanced andEwhen collapsed; its gradient reaches the router;- capacity drops exactly the overflow;
- active parameters of the 8-expert top-2 model equal the dense model's within 1%;
- a dense model and the active-matched MoE trained head to head;
- the expert-utilisation histogram, with and without the aux loss.
9. Experiments
Same base as Stage 12 (6 layers, C=384, 8 query heads / 2 kv heads, RoPE, RMSNorm), T=512, B=16, 4,000 steps: 33M tokens of the 85/15 mix, lr 1e-3. Only the MLP changes. MoE runs are uncompiled (data-dependent routing recompiles constantly); the dense baseline here is uncompiled too.
9a. Dense vs MoE, same active parameters
| model | total params | active params | val code | val English | time |
|---|---|---|---|---|---|
| dense (SwiGLU, hidden 1,024) | 12.4M | 12.4M | 2.320 | 4.153 | 354 s |
| MoE, 8 experts × 512, top-2 | 33.7M | 12.5M | 2.325 | 4.119 | 466 s |
| MoE, 16 experts × 256, top-4 (fine-grained) | 33.7M | 12.5M | 2.303 | 4.109 | 560 s |
| MoE, 7 routed × 512 top-1 + 1 shared | 33.7M | 12.5M | 2.369 | 4.203 | 458 s |
| dense, hidden 4,096 (same total params) | 33.7M | 33.7M | 2.354 | 4.140 | 643 s |
At this budget, MoE is roughly a tie with the dense model on code (+0.005 for 8×top-2, −0.017 for the fine-grained 16×top-4) and a little better on English (−0.03 to −0.04). The textbook MoE win, "more parameters for the same compute", needs each expert to see enough data: with 8 experts and top-2, each expert sees a quarter of the tokens, about 8M here. Our 33M-token runs are short for that, the same lesson as Stage 10's "a big model on few tokens loses".
Two comparisons are informative anyway:
- MoE beats a dense model of the same total size by 0.03-0.05. The 33.7M-parameter dense model at 1 token per parameter is badly undertrained (Stage 10) and costs 2.7× the compute per token. MoE gets those parameters without paying for them per token.
- Fine-grained experts are the best MoE here (−0.022 vs 8×top-2), as DeepSeek-MoE reported: more, smaller experts, more combinations.
- The shared-expert variant is the worst (+0.049). Its routed part is top-1 over 7 experts, so each token gets one routed expert instead of two: half of its active MLP is fixed, half chosen from 7. At this scale, the routing flexibility mattered more than the always-on expert.
MoE costs wall-clock time: +32% for 8 experts, +58% for 16, from our loop-over-experts dispatch (§7). A grouped-matmul kernel removes most of that; ours is written to be read.
9b. Turning the aux loss off
Same 8×top-2 model, with the load-balancing and z-losses set to 0. "Share" below is an expert's fraction of all top-2 assignments, so a balanced expert has 0.125 and an expert chosen for every token has 0.5:
| busiest expert's share (mean over layers) | aux loss value | val code | |
|---|---|---|---|
| with aux loss | 0.21-0.33 during training, 0.23 at the end | 1.09 | 2.325 |
| without | 0.41-0.43 from step 100 on | 2.46 | 2.326 |
The collapse is fast and severe: by step 100 the busiest expert in each layer takes 0.41 of the assignments, meaning it sees about 83% of all tokens. Per layer, on val code, at the end of training:
expert: 0 1 2 3 4 5 6 7
without aux layer 3 0.03 0.00 0.00 0.46 0.50 0.01 0.00 0.00
layer 4 0.00 0.19 0.05 0.00 0.13 0.13 0.49 0.00
with aux layer 3 0.05 0.13 0.19 0.34 0.10 0.07 0.05 0.06
layer 4 0.14 0.11 0.14 0.12 0.13 0.12 0.15 0.09
Without the aux loss, layer 3 runs on two experts; the other six get essentially nothing and never train. In the middle MoE layer, 4 of 8 experts are dead (zero tokens as anyone's first choice). With it, every expert carries 5-34%.
And the loss barely moved: 2.326 vs 2.325. With experts this size and this little data, two live experts per layer are about as good as eight half-trained ones. The cost of collapse is the wasted capacity, 75% of the MoE parameters doing nothing, which would show up as a quality gap only when there is enough data to train eight experts. The aux loss is what keeps that capacity available.
9c. What the experts specialise in
With the aux loss on, each token's first-choice expert in the middle MoE layer, on 32 windows of val code and 32 of val English:
| expert | English share of its tokens | its most frequent code tokens |
|---|---|---|
| 0 | 96% | from, newline + indent, def, self |
| 7 | 83% | import, ., (, models |
| 6 | 70% | newline, #, def, the, param |
| 2 | 1% | (, =, =, ,, _ |
| 4 | 1% | ,, newline + indents, =, ): |
| 3 | 14% | _, ., 0, 2, self (identifiers and digits) |
Nobody told the router which tokens are English. It sent prose mostly to experts 0, 6 and 7, and split code between a "punctuation and indentation" expert (4), a "call and assignment syntax" expert (2) and an "identifiers and numbers" expert (3). This is the surface-level specialisation real MoE studies report: by token type and syntax, not by topic or "skill".

9d. Fine-grained and shared experts
Covered in §9a's table: fine-grained (16 × 256, top-4) is the best MoE variant here; one shared expert plus top-1 routing is the worst. In the balance plot, read each curve against its own balanced value: 1/8 = 0.125 of assignments for 8 experts, 1/16 = 0.0625 for 16. The 16-expert model's busiest expert sits at 0.11-0.12, about 1.8× its balanced share; the 8-expert model's at 0.23, about 1.8× too. The aux loss holds both at the same relative imbalance.
10. What we found
| Question | Answer, measured |
|---|---|
| MoE vs active-matched dense, 33M tokens | Tie on code (2.325 vs 2.320), −0.03 on English |
| Best MoE variant | Fine-grained 16 × top-4: 2.303 (−0.017 vs dense) |
| MoE vs same-total-size dense | MoE better by 0.03-0.05, at 37% of the compute per token |
| Aux loss off | Busiest expert 0.41-0.43 of assignments (vs 0.23); 4 of 8 experts dead in the middle layer; aux value 2.46 vs 1.09 |
| Did collapse hurt loss? | Not at this budget: 2.326 vs 2.325. It wasted 75% of the MoE capacity |
| What do experts learn? | Token types: English vs code, punctuation/indentation, identifiers/digits |
| Cost | +32% (8 experts) to +58% (16) wall time with a loop dispatch |
One habit from this stage: measure utilisation, not only loss. The no-aux run's loss looked fine; the histogram showed half the model dead.
Chapter 16
Other kinds of attention, longer context
Stage 12 shrank the KV cache by sharing key/value heads (GQA). This stage looks at three more radical answers to the same pressure. Attention's cost grows with the length of the text: the cache grows linearly, and the compute for a full forward pass grows quadratically.
- MLA, multi-head latent attention (DeepSeek-V2, 2024): cache a small compressed vector per token instead of full keys and values.
- Linear attention: rewrite attention so that the past is summarised in a fixed-size state, the way an RNN does.
- State-space models (S4, Mamba): skip attention entirely and use a learned linear recurrence, which can be computed either step by step or all at once.
Then a different question: how do we know a model actually uses long context? Average loss hides it. A needle-in-a-haystack test shows it.
1. Three ways to remember the past
what is kept per token cost to read the past at step t
full attention k, v: 2 · H · d numbers O(t) (all of it)
GQA k, v: 2 · Hk · d O(t) (Hk/H of it)
MLA latent: r + d_rope O(t) (tiny, then expanded)
linear attn nothing per token: one O(1) (fixed state)
/ SSM d × d (or D) state total
The first three still store something for every token and read all of it at
every step. They only make each token's record smaller. The last row is the
qualitative change: memory does not grow with t at all. The price is that a
fixed-size state must compress an unbounded past, and things get lost.
2. MLA: compress keys and values into a latent
2a. The idea
GQA makes heads share keys and values. MLA keeps every head's keys and values different, but makes them all derived from one small vector per token:
c = RMSNorm(x · W_down) (r,) the latent: r numbers, cached
k_h = c · W_up_k[h] (d,) head h's key, rebuilt when needed
v_h = c · W_up_v[h] (d,) head h's value
Only c is cached: r numbers per token per layer, instead of 2 · H · d.
DeepSeek-V2 uses r = 512 against 2 · 128 · 128 = 32,768 for MHA: a 64×
smaller cache, and in their experiments better quality than MHA, where
GQA is usually slightly worse.
Why can it be better? GQA forces groups of heads to share exactly the same keys. MLA forces every head's keys into the same r-dimensional space, but each head can read a different direction of it. It is a low-rank constraint, not a sharing constraint. If the useful information in keys and values really is low-rank, little is lost.
2b. The catch: RoPE
RoPE (Stage 03 §4) rotates each key by an angle that depends on its position.
If k = c · W_up_k and RoPE is applied after, the rotation has to be applied
to the rebuilt k at every step, for every cached position. That is cheap
enough in our simple implementation, but it blocks the trick that makes MLA
fast in practice: absorbing W_up_k into the query, so attention is
computed directly against the latents without ever rebuilding k. A rotation
sitting between c and the dot product does not commute with that matmul.
DeepSeek's fix is decoupled RoPE: split each key into two parts.
k_h = [ c · W_up_k[h] ; RoPE( x · W_rope ) ]
content: no rotation position: d_rope dims, SHARED by all heads
q_h = [ q_content_h ; RoPE( q_rope_h ) ]
The content part goes through the latent and carries no position. The
position part is a small extra key (we use d_rope = 16) shared by all heads,
like MQA. It is cached too. Cache per token per layer: r + d_rope numbers.
2c. Cache arithmetic for our model
L = 6, H = 8, d = 48, bf16, per token across all layers:
| Variant | numbers per layer | bytes per token |
|---|---|---|
| MHA | 2 · 8 · 48 = 768 | 9,216 |
| GQA, 2 kv heads | 2 · 2 · 48 = 192 | 2,304 |
| MQA | 2 · 1 · 48 = 96 | 1,152 |
| MLA, r = 64 | 64 + 16 = 80 | 960 |
| MLA, r = 16 | 16 + 16 = 32 | 384 |
The ablation shrinks r until quality cracks (§7b).
3. Linear attention and the kernel trick
Softmax attention for one query (Stage 04 §2):
out_t = Σ_{s≤t} exp(q_t · k_s) v_s / Σ_{s≤t} exp(q_t · k_s)
The exp couples q_t and k_s, so the sum has to be recomputed for every
new query. Katharopoulos et al. (2020) replaced exp(q · k) with a product of
feature maps, φ(q) · φ(k), with φ(x) = elu(x) + 1 to keep it
positive. Then the query factors out of the sum:
out_t = φ(q_t)ᵀ [ Σ_{s≤t} φ(k_s) v_sᵀ ] / φ(q_t)ᵀ [ Σ_{s≤t} φ(k_s) ]
└──── S_t: (d, d) ────┘ └── z_t: (d,) ──┘
S_t and z_t are running sums. Each new token adds one outer product to
S. The past is a d × d matrix, whatever the length. That is an RNN,
derived from attention.
Two forms of the same computation:
- parallel (training): build the
T×Tmatrix ofφ(q)·φ(k), mask it, multiply byv. GPU-friendly. - recurrent (inference): carry
Sandz, one token at a time. Constant memory.
test_variants.py checks they agree to 1e-10. The cost: φ(q)·φ(k) is a
much blunter similarity than exp(q·k). It cannot make one key dominate the
way softmax can, so precise look-ups ("copy the token after the last (")
suffer. Pure linear attention lost to softmax attention on language; the ideas
survive in hybrids and in the SSM line below.
4. State-space models and Mamba
A linear state-space model (SSM) carries a hidden state h and updates it
with a linear recurrence, per channel:
h_t = a ⊙ h_{t-1} + b ⊙ x_t a in (0, 1): how much of the past to keep
y_t = c ⊙ h_t
Like linear attention, it has two forms:
- recurrent: one step at a time, constant memory, ideal for generation;
- parallel: unroll it, and
h_t = Σ_{s≤t} (a^{t−s}) b x_s, which is a convolution or, in general, a scan that a GPU computes inO(log T)parallel steps.
This recurrence/parallel duality is the core of S4 (Gu et al. 2021) and
Mamba (Gu & Dao 2023). Training uses the parallel form; generation uses the
recurrent form; they are the same function. test_variants.py checks our
ssm_recurrent against ssm_parallel.
Mamba's addition is selectivity: a, b and c are computed from the
input at each step, so the model decides per token what to remember and what
to forget. With fixed a, an SSM can only fade the past at a set rate. With
input-dependent a, it can hold a variable name for 1,000 tokens and drop a
comment immediately.
Hybrids. Recent models (Jamba, Zamba, several 2025 releases) mix a few attention layers into a mostly-SSM stack. The SSM layers handle the bulk cheaply; the occasional attention layer gives exact look-up when needed. We build the two forms and test their equality; we do not train an SSM language model in this stage. The scan kernel that makes Mamba fast is its own project.
5. Perplexity hides long-range failure
Average loss over a 512-token window is dominated by tokens whose prediction needs only the last few dozen tokens: the next character of an identifier, a closing bracket, an indent. A model that cannot see past 64 tokens loses very little average loss. Stage 12's sliding-window runs measure exactly how little.
The needle-in-a-haystack test (Kamradt 2023) asks a sharper question. Hide a fact at a chosen depth in a long context and ask for it at the end:
<real Python from the val set ...>
SECRET_KEY = "48213" ← at depth 10% / 50% / 90%
<more real Python ...>
assert SECRET_KEY == " ← the model must continue 4 8 2 1 3
Our tokenizer splits every digit, so this is five exact copies from far back. A model that only looks at the last 64 tokens should get it right only when the needle is within 64 tokens of the end; a full-attention model should get it right anywhere it has learned to copy.
Real long-context evaluation goes further (RULER, multi-needle, reasoning over retrieved facts). One needle is the simplest test that average loss cannot fake.
6. Acceptance criteria
- MLA's cached decode equals its full forward pass (1e-4), and its cache
is
r + d_ropenumbers per token per layer (test_llama.py); - parallel and recurrent linear attention agree to 1e-10; so do parallel and
recurrent SSMs (
test_variants.py); - MLA trained against Stage 12's GQA/MHA runs with the identical recipe, a table of cache bytes vs loss;
- the latent ablation,
r∈ {128, 64, 32, 16, 4}; - the needle harness run on full-attention, sliding-window and MLA models, next to their val losses.
7. Experiments
Same base and recipe as Stage 12 (6 layers, C=384, 8 heads of 48, RoPE, SwiGLU, T=512, 4,000 steps). The GQA/MHA points are Stage 12's runs; only the attention module changes.
7a. MLA vs GQA
| attention | KV cache per token (all layers, bf16) | params | val code |
|---|---|---|---|
| MHA, 8 kv heads | 9,216 B | 13.77M | 2.306 |
| GQA, 2 kv heads | 2,304 B | 12.44M | 2.315 |
| MQA, 1 kv head | 1,152 B | 12.22M | 2.335 |
| MLA, r = 128 | 1,728 B | 13.22M | 2.414 |
| MLA, r = 64 | 960 B | 12.77M | 2.476 |
At our scale, MLA loses to GQA at every cache size. MLA with a 128-number latent has a smaller cache than GQA-2 and is 0.10 nats worse; MQA, with a cache two thirds the size of MLA-128's, is 0.08 better. DeepSeek-V2 reports MLA beating MHA. Three differences that plausibly explain the gap, none of which we tested:
- Scale and training length. DeepSeek trained for trillions of tokens; the
up-projections
W_up_k,W_up_vhere had 33M tokens to learn how to rebuild 8 heads' keys and values from one latent. - Head size. Their content heads are 128 wide with a 64-wide rope part; ours are 48 with 16. The decoupled-rope key, shared by all heads, is a larger fraction of a small head.
- Their latent is 512 against 32,768 numbers of MHA cache (1.6%); ours at r=128 is 128 + 16 against 768 (19%). We are not compressing harder; we are compressing a model that has less redundancy to compress.
7b. Shrinking the latent
| r | cache per token | val code | Δ vs r=128 |
|---|---|---|---|
| 128 | 1,728 B | 2.414 | — |
| 64 | 960 B | 2.476 | +0.06 |
| 32 | 576 B | 2.765 | +0.35 |
| 16 | 384 B | 2.801 | +0.39 |
| 4 | 240 B | 3.198 | +0.78 |
Quality cracks between r = 64 and r = 32: halving the latent there costs 0.29 nats, against 0.06 for the halving before it. At r = 16 and r = 4 the model is leaning almost entirely on the 16-number shared rope key, which carries position but no content: a model that knows where things are but not what they were.
7c. Needles
30 cases per cell (so each percentage has a standard error of about ±9
points), greedy, the 5-digit SECRET_KEY needle at depth 10/50/90% of a
context of real val code:
| model | val code loss | mean retrieval | needle outside the window |
|---|---|---|---|
| GQA, full attention | 2.314 | 51% | — |
| window 128 | 2.424 | 31% | 0% (4 of 4 cells) |
| window 64 | 2.559 | 9% | 0% (7 of 7 cells) |
| MLA r = 64 | 2.476 | 58% | — |
| MLA r = 16 | 2.801 | 4% | — |
Perplexity hides long-range failure, in both directions.
- The window-128 model is only 0.11 nats worse than full attention on average, and it cannot retrieve anything further back than 128 tokens: 0% in every cell where the needle is outside its window, 50-67% where it is inside. The average loss counts the long-range tokens, but there are few of them, and they are a small share of the total.
- MLA r = 64 has worse loss than GQA (+0.16) and better retrieval (58% vs 51%, about one standard error). Loss is dominated by short-range prediction; copying five digits from far back is a different skill.
Our full-attention model also only manages about half the needles. A 12M model after 33M tokens has a partial copying ability, independent of distance here (43-77% across the grid with no length trend). The retrieval does not get worse at 512 than at 128: what limits it is the skill, not the reach.

8. What we found
| Question | Answer, measured |
|---|---|
| Is MLA exact under caching? | Yes, 1e-4 against the full pass, multi-token chunks included |
| Do the two forms of linear attention / SSMs agree? | To 1e-10 / 1e-8 (float64) |
| MLA vs GQA at our scale | MLA worse at every cache size: r=128 2.414 vs GQA-2 2.315 |
| Where does the latent crack? | Between r = 64 (2.476) and r = 32 (2.765) |
| Does a window hurt retrieval? | 0% beyond the window, while average loss rises only 0.11-0.24 |
| Do loss and retrieval agree? | No: MLA-64 is worse on loss and better on needles than GQA |
Two habits from this stage:
- Test the capability you need directly. For code, that includes "use something defined far above". No average loss stands in for it.
- A published win at 100B parameters is a hypothesis at 10M. MLA's advantage did not transfer to our scale; we report that rather than tuning until it did.
Chapter 17
Faster decoding
Stage 07 found that decoding is limited by memory, not arithmetic: each step reads every weight of the model from GPU memory to produce one token. The GPU's arithmetic units mostly wait.
Speculative decoding uses that idle arithmetic. A small, fast draft model guesses several tokens ahead. The big target model then checks all the guesses in a single forward pass, which costs about the same as producing one token, because reading the weights is the expensive part and it happens once either way. If the target agrees with the first three guesses, three tokens came out of one target step.
The remarkable part: with the right acceptance rule, the output distribution is exactly the target model's. Speculative decoding is not an approximation. It is a faster way to sample from the same distribution.
1. One round
context: ... def is_prime(n):\n
draft proposes γ = 4: " if n < 2"
target, ONE forward pass over all 4 → its own distribution at each position
compare position by position:
" " target agrees ✓ accept
"if" target agrees ✓ accept
" n" target agrees ✓ accept
" <" target prefers " <=" sometimes... test says reject ✗
→ sample a replacement from what the target wanted instead
output this round: " if n" + replacement = 4 tokens for 1 target call
If every guess is accepted, the target's forward pass also gave its
distribution for the position after the last guess, so one more token comes
for free: up to γ + 1 tokens per target call.
2. The acceptance rule, and why it is exact
At one position, the draft's distribution is q and the target's is p. The
draft sampled token x from q.
accept x with probability min(1, p(x) / q(x))
if rejected: sample from r = max(0, p − q) / Σ max(0, p − q)
Why the result is distributed exactly as p. Split the target's
distribution into the part the draft already covers and the part it misses:
- For a token where the draft is under-confident (
q(x) ≤ p(x)), every draw ofxis accepted. The draft produces it with probabilityq(x). - For a token where the draft is over-confident (
q(x) > p(x)), draws are accepted onlyp(x)/q(x)of the time: probabilityq(x) · p(x)/q(x) = p(x). Exactly right. - Under-confident tokens are still short by
p(x) − q(x). That missing mass is exactly what the rejections redistribute: the total rejection probability equalsΣ max(0, p − q), and the replacement is drawn frommax(0, p − q)normalised.
Adding the two routes gives p(x) for every x. A worked example with three
tokens:
p q accept prob P(output via accept) leftover p−q
token A 0.5 0.3 1.0 0.3 0.2
token B 0.3 0.6 0.5 0.3 0
token C 0.2 0.1 1.0 0.1 0.1
───── ─────
0.7 accepted 0.3 rejected
replacement drawn from [0.2, 0, 0.1] / 0.3:
A gets 0.3 · 2/3 = 0.2, C gets 0.3 · 1/3 = 0.1
final: A 0.3+0.2 = 0.5, B 0.3, C 0.1+0.1 = 0.2 = p ✓
After the first rejection, the round stops: later guesses were conditioned on a token we just replaced, so they are no longer valid.
For greedy decoding (temperature 0), p and q are one-hot, and the rule
becomes "accept while the draft's token is the target's argmax". The output
is then token-for-token identical to plain greedy decoding with the target,
which is the first test.
3. When does it pay off?
Let α be the probability that the target accepts a draft token, and c the
cost of one draft step relative to one target step. With γ guesses per
round, the expected number of tokens per round (Leviathan et al.) is
E[tokens] = (1 − α^(γ+1)) / (1 − α)
and each round costs γ · c + 1 target-step-equivalents. Speedup:
speedup = (1 − α^(γ+1)) / ((1 − α)(γ·c + 1))
| α | c | best γ | speedup |
|---|---|---|---|
| 0.8 | 0.05 | 8 | 3.09× |
| 0.6 | 0.05 | 4 | 1.92× |
| 0.6 | 0.3 | 1 | 1.23× |
| 0.4 | 0.3 | 1 | 1.08× |
The acceptance rate decides everything. A draft that agrees with the
target 80% of the time on cheap tokens pays well. A draft that agrees 40% of
the time is close to useless, however fast it is. And c matters more than
it looks: at our tiny sizes, the "draft" is not much cheaper than the target
per step, because both are dominated by fixed per-step overhead (Python, kernel
launches) rather than by reading weights. We measure both and expect a modest
speedup. This is the honest result at 30M parameters; the 3× numbers in papers
come from 70B targets with 1B drafts, where c ≈ 0.02.
Code is a good case for speculation: much of it is predictable (indentation,
closing brackets, repeated identifiers), so α is high on those stretches.
4. Variants
- Self-speculation / Medusa (Cai et al. 2024): instead of a separate draft
model, add a few extra output heads to the target, each predicting a token
further ahead (
t+2,t+3, ...) from the same final hidden state. No second model to host. Medusa uses a tree of candidates and a relaxed acceptance rule, which trades exactness for speed. - EAGLE (Li et al. 2024): a light draft head that reads the target's hidden features rather than tokens, which gives much higher acceptance.
- Multi-token prediction as a training objective (Gloeckle et al. 2024; DeepSeek-V3): train the model from the start with extra heads predicting several tokens ahead. It improves the representations a little, and the heads double as a built-in draft at inference.
We build the original draft-model version, because its exactness is the interesting property and it can be tested.
5. Acceptance criteria
stages/15_speculative/speculative.py, test_speculative.py:
- greedy speculative output equals plain greedy target output, for several γ;
- a draft identical to the target accepts 100% and gives
γ + 1tokens per target call; - sampled output: the joint distribution of the first two tokens matches the target's exact distribution (enumerated) within sampling noise (total variation < 0.05 over 6,000 draws on a 6-token vocabulary).
6. Experiments
Target: the Stage 11 workhorse (30M). Draft: the Stage 06 4-layer model (5M), same tokenizer. bf16, batch 1, 160 new tokens from four code prompts. One draft step costs 0.43 of a target step: at these sizes both are mostly per-step overhead (Stage 07 §8a), so the draft is not nearly as cheap as its 6× fewer parameters suggest.
| τ | γ | acceptance | tokens per target call | speedup |
|---|---|---|---|---|
| 0 (greedy) | 1 | 0.93 | 1.92 | 0.86× |
| 0 | 2 | 0.89 | 2.74 | 1.04× |
| 0 | 4 | 0.83 | 4.29 | 1.17× |
| 0 | 6 | 0.77 | 5.59 | 1.20× |
| 0 | 8 | 0.73 | 6.62 | 1.15× |
| 0.7 | 4 | 0.61 | 3.42 | 0.99× |
| 1.0 | 1 | 0.67 | 1.67 | 0.82× |
| 1.0 | 8 | 0.26 | 3.08 | 0.25× |
- Greedy acceptance is high: the 5M draft agrees with the 30M target on 83% of tokens at γ = 4. Much of code is predictable to both (indentation, brackets, repeated names), and both loop in similar ways.
- The speedup is small anyway: 1.20× at best. The formula from §3, with
α = 0.83, c = 0.43, γ = 4, predicts 1.31×; we measure 1.17×. The gap is
the Python acceptance loop, which the formula does not charge for. The
ceiling is set by
c: with a draft costing 43% of the target, eight draft steps cost 3.4 target steps. - Sampling makes it worse. At τ = 1, acceptance falls to 0.26-0.67 and every γ is a slowdown, down to 0.25× at γ = 8. The draft and target agree on the most likely token far more often than their full distributions agree on a random one.
- Exactness: in fp32, greedy speculative output is identical to plain greedy decoding on all 4 prompts. In bf16, 3 of 4 are identical and one diverges at token 130, where the target's top two logits differ by 0.031: verification scores five tokens in one pass, plain decoding scores one, and the different bf16 rounding flips a near-tie (journal).
A bigger pair, worse ratio. With the 92M capstone as target and the 30M
workhorse as draft (run.py sweep --tag capstone), greedy acceptance rises
to 0.97 (γ = 1) and 0.89 (γ = 4), and every output is token-identical to plain
greedy decoding. But a 30M draft step costs 0.67 of a 92M target step, so
the best speedup is 0.98× (γ = 6), and τ = 1 runs at 0.50-0.75×. The §3
formula with α = 0.89, c = 0.67, γ = 4 predicts 1.09×. Better agreement
cannot make up for a draft that is almost as slow as the target.

Speculative decoding is a technique for large targets with cheap drafts. On our hardware at our sizes the precondition fails, and the measurement shows exactly how much: the acceptance rate was there, the cost ratio was not.

7. What we found
| Question | Answer, measured |
|---|---|
| Is the output distribution the target's? | Yes: TV 0.03 on an enumerable case (test); greedy identical in fp32 |
| Greedy acceptance, 5M draft for a 30M target | 0.93 (γ=1) to 0.73 (γ=8) |
| Best speedup | 1.20× (greedy, γ=6) |
| Why so small? | Draft step costs 0.43 of a target step; both are overhead-bound |
| Sampling at τ=1 | acceptance 0.26-0.67, always slower |
| bf16 exactness | 1 of 4 prompts flips at a near-tie (top-2 gap 0.031) |
| 92M target, 30M draft | acceptance 0.89 @γ4, identical outputs, best speedup 0.98× (draft costs 0.67) |
Chapter 18
Teaching it to follow instructions
The pretrained model from Stage 11 is a base model: it continues text. Give it a docstring and it writes something that looks like what follows docstrings in its training data: sometimes a function body, sometimes another docstring, sometimes a test file. It has no idea it is being asked anything.
Supervised fine-tuning (SFT) teaches a format: a request, then an answer, then stop. It is the same next-token training as pretraining, on a small, curated set of request/answer pairs, with one important change to the loss.
What is in this stage:
- base vs instruct behaviour, measured;
- chat templates and the special tokens that mark who is speaking;
- loss masking: train on the answer only;
- padding vs packing, and the attention-mask trap;
- catastrophic forgetting;
- how much data SFT needs (LIMA's answer);
- the ablation: train on the prompt tokens too.
1. Base model vs instruct model
The difference is behaviour, not knowledge. SFT on a few thousand examples cannot teach a model Python; it took billions of tokens to do that. What SFT changes is what the model does with a prompt:
base model, given "def add(a, b):\n \"\"\"Add two numbers.\"\"\"\n"
→ " return a + b\n\n\ndef sub(a, b):\n \"\"\"Subtract..." keeps going
instruct model, given the same as a user turn
→ "def add(a, b):\n ...\n return a + b\n<|im_end|>" answers, stops
The base model's habit of continuing is not a bug. It is exactly what it was trained to do: predict the next token of a file. After a function there is usually another function.
2. Chat templates
A chat template turns a conversation into one token sequence. Ours is ChatML, using the special tokens reserved since Stage 01:
<|im_start|>user
def add(a, b):
"""Add two numbers."""
<|im_end|>
<|im_start|>assistant
def add(a, b):
"""Add two numbers."""
return a + b
<|im_end|>
<|im_start|> (id 8194) and <|im_end|> (id 8195) can never be produced by
encoding ordinary text: our tokenizer only emits them when asked (Stage 01 §5).
So a user cannot fake a turn boundary by typing the string <|im_end|>.
These embedding rows were never trained during pretraining: the tokens never appeared in the data. SFT is the first time the model sees them. This is normal, and one reason a new chat template needs some SFT data to "take".
At inference time we render the user turn, append <|im_start|>assistant\n,
and let the model write until it produces <|im_end|>. Learning to emit
<|im_end|> is half the point of SFT: a model that answers correctly and
then keeps writing is not usable.
3. Loss masking
In pretraining every token is a target. In SFT, the prompt is given, not generated. If the loss includes prompt tokens, the model spends capacity learning to predict user questions, which it will never need to do, and the gradient from the (often longer) prompt drowns the gradient from the answer.
So the targets for prompt tokens are set to -100, which PyTorch's
cross_entropy(..., ignore_index=-100) skips:
tokens: <s> user \n def add ... """ <e> \n <s> assistant \n def add ... return a + b <e>
labels: -100 -100 ... -100 def add ... return a + b <e>
└──── prompt: no loss ────┘ └──── reply: loss ────┘
The closing <|im_end|> is a target: that is how the model learns to stop.
The test test_loss_mask_covers_exactly_the_reply checks that the unmasked
tokens decode to exactly the reply, plus the stop token.
What breaks without the mask? §8c trains with the prompt included in the loss and compares.
4. Padding, packing, and the mask trap
Examples have different lengths. Two ways to batch them:
Padding. Put each example in its own row and fill the rest with
<|pad|>. The pad positions get label -100. With right padding (pads
after the text), the ordinary causal mask is already correct: a real token
can only attend to earlier positions, and all pads come later. The test
test_right_padding_does_not_change_real_logits checks it. The cost is
wasted compute on pads.
Packing. Concatenate several examples into one full row with no pads.
Efficient, but now example 2 can attend to example 1. Unless the attention
mask is changed to block-diagonal (each example sees only itself), the
model learns from, and is conditioned on, unrelated neighbours. This is the
attention-mask correctness trap: it raises no error and silently changes
what the model learns. Pretraining tolerates it (documents separated by
<|endoftext|>, Stage 02); for SFT, where each example is a separate
conversation, it is a real leak.
We use right padding. SFT data is small, so the wasted compute is affordable, and the correctness argument is one line.
5. The data: docstring → function
CodeSearchNet Python has 412k functions with docstrings from GitHub. We keep
free functions (no self/cls) that parse on their own, have a docstring and
a body, and fit in 512 tokens. That leaves roughly a third.
Each one becomes:
- user: the signature and docstring, exactly the shape of a HumanEval prompt;
- assistant: the whole function.
No annotation is needed. The data is "free" because GitHub authors wrote docstrings. The cost: docstrings are often poor specifications ("Helper function.") and the functions use libraries the model has never seen. It is real-world data, not curated data.
How much is needed? LIMA (Zhou et al. 2023) fine-tuned a 65B model on 1,000 carefully chosen examples and matched models tuned on 50× more. The lesson is that SFT mostly teaches format and style, which needs few examples; the knowledge was already there. A 30M-100M model has much less knowledge to unlock, so we use more data, and measure val loss on held-out pairs as it trains.
6. Catastrophic forgetting
Fine-tuning on a narrow dataset pushes the weights towards that dataset and away from everything else. Train long enough on docstring→function and the model's general code modelling gets worse. We measure it directly: the pretraining val loss (code and English) before and after SFT. A small, stable learning rate (1e-4, a tenth of pretraining) and a short run keep the damage small.
7. Acceptance criteria
stages/16_sft/sft.py, test_sft.py:
- the loss mask covers exactly the reply plus
<|im_end|>; - collation pads on the right, never targets a pad, and shifts correctly;
- right padding does not change any real position's logits;
- the prompt-loss ablation trains on every non-pad token;
run.py: SFT the Stage 11 base model; report completion val loss, pretraining val loss before/after (forgetting), HumanEval and MBPP pass@1 before vs after, and side-by-side completions;- the ablation: same run with the prompt in the loss.
8. Experiments
Base: the Stage 11 workhorse (30M). Data: 119,178 CodeSearchNet pairs survived the filters (of 412,178 functions), 1,000 held out. 3,000 steps of 16 examples (48k examples, 0.4 epoch), lr 1e-4, warmup 50, cosine. Base-model HumanEval/MBPP numbers come from the Stage 22 table, where the prompt trailing-newline trap (journal) is handled; this run's own "base mode" measurement predates that fix and is not used.
8a. Base vs SFT
| completion val loss | HumanEval pass@1 | MBPP pass@1 | |
|---|---|---|---|
| base model, prompted as chat (it has never seen the template) | 1.168 | 0.0% | 0.0% |
| after SFT | 1.033 | 1.2% (2/164) | 0.0% |
The loss on assistant tokens falls from 1.168 to 1.036 in the first 250
steps and then barely moves (1.033 at step 3,000): the format is learned
almost immediately, LIMA's observation at our scale. The two solved problems
are strlen and concatenate.
The behavioural change is easiest to see in the outputs. Given HumanEval/0
as a user turn, the SFT model repeats the signature and docstring exactly
(as its training targets did), writes a body, and stops with <|im_end|>:
def has_close_elements(numbers: List[float], threshold: float) -> bool:
""" Check if in given list of numbers, are any two numbers closer to each other than
given threshold.
...
"""
if len(numbers) == 2:
return True
if len(threshold) == 2:
return False
The format is right; the logic is not. A 30M model has learned what a
function looks like, not what this one should do. Failures on HumanEval are
59 wrong answers (AssertionError), 56 syntax errors and 11 indentation
errors, the latter two mostly from the tab/space mixing Stage 11 noticed.
8b. Forgetting
Pretraining val loss on the same windows, before and after SFT:
| before SFT | after SFT | change | |
|---|---|---|---|
| code | 1.684 | 1.832 | +0.148 |
| English | 3.341 | 3.646 | +0.305 |
0.4 epoch of a narrow dataset at a tenth of the pretraining learning rate costs 0.15 nats of general code modelling and twice that on English, which the SFT data contains almost none of. The completion loss stopped improving after step 250, so 92% of these steps bought forgetting and nothing else. A shorter run would be strictly better here.
8c. Training on the prompt too
Same run with every non-pad token in the loss:
| completion-only loss (ours) | prompt + completion | |
|---|---|---|
| completion val loss | 1.0328 | 1.0295 |
| HumanEval | 1.2% | 1.2% (the same two problems) |
| pretraining val, code / English | 1.832 / 3.646 | 1.843 / 3.654 |
Almost no difference at this scale. The prompt here (signature + docstring) is itself the start of the same function, so learning to predict it is not wasted effort; and with 119k examples there is no shortage of completion signal for it to drown out. The prompt-trained run forgets slightly more (+0.011 code, +0.008 English) because it trains on more tokens. Loss masking matters most where prompts are long and unlike the answers (chat, retrieval-augmented prompts); for docstring → function, the two are nearly the same task.
8d. The capstone (92M)
Same data, steps and learning rate, on the Stage 11 capstone (activation checkpointing on: B = 16 does not fit in 8 GB otherwise, journal Session 10):
| 30M workhorse | 92M capstone | |
|---|---|---|
| completion val loss, before → after | 1.168 → 1.033 | 0.998 → 0.886 |
| step at which it flattened | 250 | 250 (0.888) |
| HumanEval, base model prompted as plain code (Stage 22 harness) | see Stage 22 | 3.05% (5/164) |
| HumanEval, after SFT, prompted as chat | 1.2% (2/164) | 1.22% (2/164) |
| MBPP, after SFT | 0.0% | 0.4% (2/500) |
| forgetting, code / English | +0.148 / +0.305 | +0.159 / +0.311 |
The bigger model starts lower and ends lower on the completion loss, and the same 250-step story repeats: 0.971 at step 0, 0.888 at step 250, 0.886 at step 3,000. Forgetting is almost identical in size.
The surprise is the HumanEval row. SFT made the capstone worse at
HumanEval: the base model, given the prompt as a file to continue, solves 5
problems; the SFT model, given the same prompt as a chat turn, solves 2, and
only one of them (HumanEval/28, concatenate) is in both sets. HumanEval's
prompts are already "signature + docstring, now write the body": exactly
what a base model continues well. SFT bought the chat format, a habit of
stopping, and 0.16 nats of forgetting; for a benchmark that needs none of
those, the trade was a loss. A bigger model gains more from pretraining
alone, so it has more to lose.
9. What we found
| Question | Answer, measured |
|---|---|
| Does SFT teach the format? | Yes: completion loss 1.168 → 1.036 within 250 steps; the model stops with `< |
| Does it teach coding? | Barely: HumanEval 0 → 1.2% (2 problems), MBPP 0% |
| Forgetting | +0.148 code, +0.305 English pretraining loss, mostly after the format was learned |
| Prompt in the loss | A tie here: 1.0295 vs 1.0328, same problems solved |
| On the 92M capstone | Same shape: flat after 250 steps, +0.16 / +0.31 forgetting, and HumanEval 3.05% (base, as code) → 1.22% (SFT, as chat) |
| How much data? | The format took ~4,000 examples (250 steps × 16); the rest cost forgetting |
One habit from this stage: stop SFT when the completion loss flattens. Every step after that is paid for in forgetting.
Chapter 19
Fine-tuning with 1% of the parameters: LoRA
Stage 16 fine-tuned every weight of the model. For our 30-100M models that is fine. For a 7B model it means 7B gradients and 14B Adam state numbers: about 112 GB of training memory (16 bytes per parameter, Stage 00), for a model whose weights are 14 GB. Most people fine-tuning a 7B model have one GPU with 24 GB or less.
LoRA (Hu et al. 2021) freezes the original weights and trains a tiny add-on instead. QLoRA (Dettmers et al. 2023) also stores the frozen weights in 4 bits. Together they fit a 65B fine-tune on a single 48 GB GPU.
This stage builds both from scratch, checks LoRA against the peft library
number for number, and measures what is lost.
1. The low-rank hypothesis
Fine-tuning changes each weight matrix W by some update ΔW. For a
768 × 768 matrix, ΔW has 589,824 numbers. But fine-tuning only nudges a
model towards a new format or task; it does not rebuild it. Aghajanyan et al.
(2020) measured that the useful part of fine-tuning updates lives in a
surprisingly small number of directions: the updates have low intrinsic
rank.
Rank, in plain words: a matrix of rank r can be written as the product
of a tall thin matrix and a short wide one:
ΔW = B · A
(d×k) (d×r) (r×k) r ≪ d, k
At d = k = 768, r = 8: B and A hold 768·8 + 8·768 = 12,288 numbers,
2% of ΔW's 589,824. If the true update is close to rank 8, we lose almost
nothing by learning B and A instead of ΔW.
2. LoRA
x (.., k)
│
┌──────┴──────┐
│ │
▼ ▼
W x A x (.., r) A: r × k, trained
(frozen) ▼
│ B (A x) (.., d) B: d × r, trained, starts at ZERO
│ │ × α/r
└────(+)──────┘
│
▼ y = W x + (α/r) B A x
Three details, each with a reason:
Bstarts at zero. ThenBA = 0at step 0, and the model is exactly the pretrained model. Fine-tuning starts from where pretraining ended, not from a randomly perturbed version. (test_zero_init_changes_nothing.)Astarts random, not zero. If both were zero, the gradient ofB(which is proportional toA x) and the gradient ofA(proportional toBᵀ) would both be zero forever. One of them must be non-zero to break the symmetry.- The
α/rscale. Asrgrows,BAsums more terms and its size grows with it. Dividing byrkeeps the update's scale roughly independent ofr, so a learning rate tuned atr = 8still works atr = 64.αis then a single knob for "how strong is the adapter" (commonlyα = 2r). rsLoRA (Kalajievski 2023) argues forα/√rinstead, for the same reason done more carefully; the difference shows up at larger.
Which matrices? The original paper adapted only the attention q and v
projections. Later work (QLoRA) found that adapting every linear layer,
MLP included, at a smaller rank works better for the same parameter count. We
target c_attn, c_proj and c_fc: every linear in the block.
Merging. After training, W' = W + (α/r) B A is an ordinary matrix of
the original shape. Fold it in and the adapter costs nothing at inference.
(test_merge_equals_unmerged.) Or keep it separate, and serve many
adapters on one base model: each customer's fine-tune is a few MB, swapped
per request.
3. The memory arithmetic
For full fine-tuning in bf16 compute with fp32 master weights and AdamW (Stage 00's accounting), per parameter: 4 (weights) + 4 (grads) + 8 (Adam) = 16 bytes. With LoRA, the frozen weights need no gradients and no optimizer state: 2 bytes each in bf16. Only the adapter pays 16 bytes per parameter.
| 7B full FT | 7B LoRA r=16, all linears | 7B QLoRA | |
|---|---|---|---|
| frozen weights | — | 14 GB (bf16) | 3.5 GB (4-bit) |
| trainable params | 7B | ~40M | ~40M |
| grads + Adam + master | 112 GB | 0.6 GB | 0.6 GB |
| total (excl. activations) | ~112 GB | ~15 GB | ~4 GB |
Activations still need memory and are not shrunk by LoRA. §8 measures our own version on our model.
4. Why fewer parameters can still learn the task
Intuition: the pretrained model already contains the skills. Fine-tuning
mostly needs to select and reweight existing features: "after
<|im_start|>assistant, behave like the code-writing mode, and stop at the
end". Such a change is a small number of directions in weight space, which is
what a low-rank update can express. Teaching genuinely new knowledge (a new
programming language, a new fact base) is less low-rank, and that is where
LoRA falls behind full fine-tuning (Biderman et al. 2024, "LoRA learns less
and forgets less"). The forgets less half is the other side of the same
coin: the frozen weights are untouched, so forgetting (Stage 16 §6) is
limited.
5. QLoRA and NF4
QLoRA keeps LoRA's adapters in bf16 and stores the frozen base in 4 bits, dequantizing each weight block on the fly in the forward pass. Gradients flow through the dequantized weights into the adapters; the 4-bit codes never change.
NF4 ("4-bit NormalFloat"). 4 bits give 16 levels. Where should they go? Trained weights are roughly normally distributed: most are near zero, few are large. Evenly spaced levels (int4) waste most of their codes on the rare large values. NF4 places the 16 levels at the quantiles of a normal distribution, so each level is used about equally often:
int4 levels (scaled): -1 -.86 -.71 -.57 -.43 -.29 -.14 0 .14 .29 .43 .57 .71 .86 1
NF4 levels: -1 -.70 -.53 -.39 -.28 -.18 -.09 0 .08 .16 .25 .34 .44 .56 .72 1
└──── crowded near 0, where the weights are ────┘
Each block of 64 weights is scaled by its own absolute maximum (stored in
bf16), so level × absmax reconstructs the weight. Storage: 4 bits per weight
plus 16 bits per 64 weights = 4.25 bits per weight. QLoRA's double
quantization quantizes those absmax values too (to 8 bits, in blocks of
256), bringing it to about 4.13 bits; we skip that refinement. Paged
optimizers move optimizer state to CPU memory during memory spikes; on one
small model we do not need them.
test_nf4_levels_match_paper checks our 16 levels against the paper's table.
6. Variants, briefly
- DoRA (Liu et al. 2024): split each weight into a magnitude (one number per column) and a direction, and apply LoRA to the direction only. Closer to full fine-tuning at the same rank.
- rsLoRA: scale by
α/√r(§2). - LoRA+: a larger learning rate for
Bthan forA.
7. Acceptance criteria
llmfs/post/lora.py, stages/17_lora/test_lora.py:
- zero-initialised adapter leaves the model's output bit-identical;
- only adapter parameters are trainable, and their count is
r·(in+out)per layer; - outputs match
peft's LoRA with the sameA,Bto 1e-5; - merged model equals unmerged model to 1e-5;
BAhas rankr; - NF4 levels match the paper; 4-bit storage is 0.5 bytes per weight plus scales;
run.py: LoRA SFT vs full SFT (Stage 16 data and steps) on the same base: trainable params, peak memory, step time, completion val loss, pass@1;- rank sweep
r∈ {1, 4, 16, 64}; QLoRA atr = 16; a merged adapter.
8. Experiments
Base: the Stage 11 workhorse (30M). Data, steps and batch: Stage 16's
(119k docstring → function pairs, 3,000 steps of 16, completion-only loss).
Learning rate 1e-4 for full fine-tuning, 1e-3 for the adapters (adapters
start at zero and need larger steps). LoRA on every linear layer of every
block (c_attn, c_proj, c_fc), α = 2r.
| method | trainable params | peak MB (training, above weights) | ms / step | completion val loss | HumanEval |
|---|---|---|---|---|---|
| full fine-tune | 29,941,760 (100%) | 4,615 | 253 | 1.0328 | 1.2% |
| LoRA r = 1 | 65,536 (0.22%) | 4,105 | 261 | 1.0318 | 0.0% |
| LoRA r = 4 | 262,144 (0.88%) | 4,091 | 263 | 1.0278 | 0.6% |
| LoRA r = 16 | 1,048,576 (3.5%) | 4,104 | 263 | 1.0281 | 0.6% |
| LoRA r = 16, merged | — | — | — | 1.0280 | — |
| LoRA r = 64 | 4,194,304 (14%) | 4,158 | 266 | 1.0328 | 0.6% |
| QLoRA r = 16 (NF4 base) | 1,048,576 | 4,104 | 267 | 1.0321 | 0.6% |
Quality saturates at rank 1. With 0.22% of the parameters trainable, LoRA matches full fine-tuning (1.0318 vs 1.0328), and ranks 4-16 are slightly better (1.028). The low-rank hypothesis of §1 holds strongly here: this SFT is learning a format (the chat template, the stop token, "write the whole function"), and a format is a handful of directions. More capacity does not help, and r = 64 and full fine-tuning, with the most capacity, are a little worse: closer to fitting the training pairs' specifics. HumanEval moves between 0 and 2 problems of 164 across all rows, which is noise.
Merging is free: the r = 16 adapter folded into the weights gives 1.0280 against 1.0281 unmerged (§2).
QLoRA costs 0.004 over LoRA at the same rank (1.0321 vs 1.0281): the base model's weights are now 4-bit NF4, and the adapter trains around the quantization error.
The memory savings are small at this size, and the table shows why.
LoRA saves 510 MB of a 4.6 GB training peak (−11%). That is almost exactly
the 16-bytes-per-parameter accounting of §3 for the gradients and Adam state
LoRA no longer keeps: 30M × 16 B = 480 MB. The rest of the 4.1 GB is
activations (16 sequences × 512 tokens, and the 16 × 512 × 8,196 logits in
fp32), which LoRA does not touch. For a 7B model, where the 112 GB of
optimizer state dwarfs the activations, the same mechanism is the
difference between impossible and possible on one GPU. QLoRA saves nothing
visible here either: its 4-bit base is 22 MB instead of 57 MB, against a
4 GB peak. Speed is also unchanged (253-267 ms/step): the forward and
backward passes still run through the whole frozen network.
9. What we found
| Question | Answer, measured |
|---|---|
Does our LoRA equal peft's? |
Yes, to 1e-5 with the same A, B (test) |
| Where does quality saturate? | At r = 1 (0.22% of params): 1.0318 vs full 1.0328; r = 4-16 best at 1.028 |
| Merge | 1.0280 merged vs 1.0281 unmerged |
| QLoRA cost | +0.004 over LoRA r = 16 |
| Memory saved | 510 MB of 4.6 GB (= the 30M × 16 B optimizer accounting); activations dominate at 30M |
| Speed | unchanged (~260 ms/step) |
One habit from this stage: work out where the memory goes before choosing a memory technique. LoRA attacks optimizer state; at 30M parameters the optimizer state was 11% of the peak.
Chapter 20
Learning what people prefer: reward models
SFT (Stage 16) shows the model good answers. It never shows it bad ones, so it cannot learn what makes one answer better than another. RLHF's answer is a reward model: a network that reads a prompt and a response and outputs a single number, "how good is this?". Once you have one, you can push a policy towards responses it scores highly (Stage 19's PPO), or use it to rank samples.
This stage trains one. Our domain lets us do it without any human labels, and then check it against an objective ground truth, which most reward-model work cannot do.
1. Why learn a reward at all?
For many tasks there is no formula for "good": helpfulness, tone, whether an explanation is clear. People can still compare two responses and say which they prefer, quickly and fairly consistently. A reward model turns many such comparisons into a function that can score responses no one has seen.
The data format is a preference pair: a prompt, a chosen response and a rejected one. No absolute scores: humans are bad at "rate this 1-10" and much better at "which of these two".
2. Bradley-Terry: from comparisons to scores
The Bradley-Terry model (1952, invented for ranking chess players and
sports teams) assumes each item has a hidden score r, and the probability
that a beats b is
P(a ≻ b) = exp(r_a) / (exp(r_a) + exp(r_b)) = σ(r_a − r_b)
where σ is the sigmoid. Only the difference of scores matters: adding
the same constant to every score changes nothing. A difference of 0 gives a
50/50 chance; a difference of 2 gives 88%.
Training the reward model is then maximum likelihood on the observed
preferences. For one pair, the probability of what we saw (chosen beat
rejected) is σ(r_c − r_r). Its negative log is the loss:
loss = −log σ(r_c − r_r)
That is logistic regression on the score difference. Worked numbers:
r_c − r_r |
σ |
loss |
|---|---|---|
| 0 | 0.50 | 0.693 (= ln 2, the starting point) |
| 1 | 0.73 | 0.313 |
| 3 | 0.95 | 0.049 |
| −1 | 0.27 | 1.313 (ranked the wrong way) |
The gradient pushes r_c up and r_r down, by 1 − σ(r_c − r_r): hard when
the model ranks the pair wrong, gently when it already ranks it right.
3. The architecture: a language model with a different head
Take the SFT model, drop the C → V output head, and add a C → 1 head that
reads the hidden state at the last token of the response:
<im_start>user ... <im_end> <im_start>assistant def f(x): ... return y <im_end>
↑
hidden state here → Linear(C, 1) → r
Why the last token: with causal attention, it is the only position that has seen the whole response. Why start from the SFT model rather than from scratch: understanding code is the hard part, and the pretrained network already has it. The reward head only has to learn to read it out.
With padding, "last token" means the last real token of each row, not the
last column. Reading the pad position instead is a classic bug: the reward
then depends on how much padding the batch needed.
(test_reward_reads_last_real_token.)
4. Accuracy is a ceiling on everything after
Everything downstream optimises against this model: PPO maximises its score,
best-of-n picks by it. If the reward model prefers the right answer 70% of
the time, nothing trained against it can reliably do better than its idea of
"right". Pairwise accuracy on held-out pairs (the fraction where
r_c > r_r) is the number to report.
Calibration asks a second question: when the model says σ(r_c − r_r) = 0.9, is it right 90% of the time? A well-calibrated reward model's margins
mean something.
Annotator noise limits accuracy from the data side. Human annotators agree with each other on 60-75% of pairs in typical chat preference datasets. A reward model cannot be "more right" than its labels: when 20% of labels are flipped, the best possible agreement with them is 80%. §8c flips labels on purpose.
5. Our preference data: code with a planted bug
We have something chat data does not: a machine check for correctness. So we generate preferences instead of collecting them:
- chosen: a real, working function;
- rejected: the same function with one mutation: a comparison
flipped (
<→>=), an operator swapped (+→-), a constant nudged by one,and↔or, areturn xreplaced byreturn None, anotdropped.
chosen rejected
if x < lo: if x >= lo: ← one character of meaning
return lo return lo
Two sources:
- train: CodeSearchNet functions (Stage 16's data). No tests, so a mutant
is only very likely to be broken. Some mutations are harmless (changing
an unused default,
x + 0→x - 0). That is label noise, built in. - test: MBPP reference solutions, where every mutant is run against the tests and kept only if it fails. These labels are certain.
The trap: formatting. The mutant is produced by parsing the code into a
syntax tree, changing one node, and printing it back with ast.unparse.
Printed-back code has normalised formatting: quotes, spacing, parentheses. If
the chosen side kept its original formatting, every pair would differ in
formatting too, and the reward model would learn "unparse-style formatting =
bad", reaching high accuracy without reading the logic at all. So both
sides go through ast.unparse. The only difference left is the bug.
This is what reward hacking looks like from the data side: any systematic difference between chosen and rejected that is not the property you care about becomes a shortcut.
6. Reward hacking and over-optimisation
A reward model is an approximation of what we want, fitted on a finite set of pairs. Push a policy hard enough against it and the policy finds the approximation's errors: responses that score highly for the wrong reason. Gao et al. (2022) measured this: as a policy is optimised against a reward model, the true quality first rises, then falls, while the reward model's score keeps going up. The KL penalty in RLHF (Stage 19) exists to stop the policy from going far enough to find these holes.
Our setting will show its own version: a reward model trained on single- mutation pairs has learned "does this look like a subtly broken version of some function?". It has not learned "does this solve the problem?". Stage 20 avoids the issue by using the tests themselves as the reward.
7. Acceptance criteria
stages/18_reward/reward.py, test_reward.py:
- mutation keeps both sides in canonical formatting and changes behaviour;
- the Bradley-Terry loss gives ln 2 at equal scores and the table values;
- the reward is read at the last real token, independent of padding;
run.py: RM from the SFT model, trained on CodeSearchNet pairs; accuracy on held-out CodeSearchNet pairs and on MBPP verified pairs; histograms ofr_candr_r; calibration ofσ(r_c − r_r);- the ablation: 20% (and 40%) of training labels flipped.
8. Experiments
Backbone: the Stage 16 SFT workhorse (30M). Training: 40,000 CodeSearchNet correct-vs-mutant pairs, 2,000 steps of 16 pairs (2 micro-batches of 8, sequences capped at 640 tokens), lr 2e-5 (head 2e-4). Test: 1,000 held-out CodeSearchNet pairs and 1,218 MBPP pairs whose rejected side was run and fails the tests.
8a. Accuracy
| before training (random head) | after | |
|---|---|---|
| CodeSearchNet held-out pairs | 50.7% | 82.6% |
| MBPP, test-verified bugs | 56.8% | 85.2% |
A model that passes 1.2% of HumanEval (Stage 16) picks the working version of a function over its single-mutation twin 85% of the time. Discriminating is far easier than generating. Accuracy on the MBPP pairs, which the reward model never trained on and whose labels are certain, is as high as on held-out pairs from the training distribution: what it learned transfers.
By kind of bug (MBPP pairs, clean labels):
| mutation | pairs | accuracy |
|---|---|---|
return x → return None |
376 | 100% |
| arithmetic operator swapped | 324 | 82% |
| constant nudged / other | 345 | 78% |
| comparison flipped | 153 | 76% |
and ↔ or |
20 | 65% |
The easy bug is visible in the text alone (a function that returns None is
rarely right). The hard ones need the model to know what the code is for:
x < y and x >= y are equally plausible Python until you know the
intended behaviour.
8b. Calibration
Grouping MBPP pairs by the model's confidence σ(r_c − r_r):
| predicted P(chosen better) | pairs | actual accuracy |
|---|---|---|
| 0.5-0.6 | 118 | 52% |
| 0.6-0.7 | 87 | 64% |
| 0.7-0.8 | 95 | 72% |
| 0.8-0.9 | 110 | 79% |
| 0.9-1.0 | 808 | 95% (mean confidence 98.7%) |
Well calibrated in the middle, mildly over-confident at the top: when it is
"98.7% sure" it is right 95% of the time. Two thirds of the pairs land in
the top bucket, mostly the return None bugs.
The reward histogram (figure, left) shows something calibration tables hide: absolute rewards overlap almost completely between chosen and rejected functions across problems. A good function for one problem can score below a bad function for another. Bradley-Terry only constrains differences, so only differences within the same prompt mean anything. Anything downstream that compares rewards across prompts (thresholding "good enough", best-of-n across tasks) is using a number the training never calibrated.
8c. Label noise
The same run with 20% and 40% of training pairs' labels swapped:
| labels flipped | CodeSearchNet held-out | MBPP verified |
|---|---|---|
| 0% | 82.6% | 85.2% |
| 20% | 78.3% | 76.6% |
| 40% | 64.0% | 71.6% |
Accuracy falls as noise rises, but it does not fall to 1 − noise: with 40%
flipped, the model still ranks 72% of MBPP pairs correctly. That is the
majority vote at work: at 40% noise, 60% of the labels for any kind of bug
still point the right way, and a model fitting the average learns the
majority direction. The cost shows up as slower learning, a lower ceiling,
and worse accuracy on the subtle bugs (and/or: 65% → 35%, below chance)
while the easy return None bug barely moves (100% → 97%).

8d. The capstone as a judge
Same recipe on the 92M capstone's SFT model (activation checkpointing on):
| 30M workhorse | 92M capstone | |
|---|---|---|
| before training (random head) | 50.7% / 56.8% | 44.1% / 44.7% |
| CodeSearchNet held-out | 82.6% | 87.1% |
| MBPP verified | 85.2% | 86.5% |
| pairs with confidence 0.9-1.0 | 808 of 1,218, 94.8% right | 977 of 1,218, 93.3% right |
Three times the parameters buys +4.5 points on held-out pairs from the training distribution and only +1.3 on MBPP. The capstone is also more confident: 80% of its MBPP judgements land in the top bin, against 66% for the workhorse, at slightly lower accuracy there. Most of what "this code is broken" takes at this level, the 30M model already had.
9. What we found
| Question | Answer, measured |
|---|---|
| Can a 30M model learn "working beats broken"? | 85.2% on test-verified MBPP pairs it never trained on |
| Which bugs are easy? | return None 100%; comparisons 76%; and/or 65% |
| Calibrated? | Mostly; over-confident at the top (98.7% → 95%) |
| Are absolute rewards meaningful? | No: chosen and rejected overlap across prompts; only within-prompt differences are |
| Does a 3× bigger backbone judge better? | Slightly: 87.1% vs 82.6% held-out, 86.5% vs 85.2% on MBPP |
| 20% / 40% flipped labels | 76.6% / 71.6% on MBPP; subtle bugs degrade first |
One habit from this stage: check what the reward model can see. The
easy wins (return None) are textual; the hard ones need understanding.
A reward model's average accuracy is mostly a statement about the mix of
easy and hard pairs in the test set.
Chapter 21
RLHF, DPO and GRPO
Stage 18 built a model of "which response is better". This stage uses preferences to change the policy itself. Three methods, in historical order:
- PPO (2017, used for InstructGPT/ChatGPT): sample responses, score them with the reward model, reinforce the good ones. Powerful and notoriously fiddly.
- DPO (Rafailov et al. 2023): a derivation showing that the same goal can be reached with a simple classification-style loss on preference pairs. No reward model, no sampling during training.
- GRPO (DeepSeekMath, 2024): PPO without the value network, using a group of samples as its own baseline. Stage 20 builds it.
We read and diagram PPO, implement DPO from scratch and run it, and sweep DPO's one hyperparameter, β.
1. Text generation as reinforcement learning
Reinforcement learning (RL) is learning from rewards for actions. The mapping to a language model:
| RL term | Language model |
|---|---|
| state | the prompt plus the tokens written so far |
| action | the next token |
policy π |
the model's next-token distribution |
| episode | one complete response |
| reward | the reward model's score for the complete response (0 for every token before the last) |
The goal: change π so its responses get high reward, without drifting
too far from the SFT model. Drifting far is how the policy finds the reward
model's mistakes (Stage 18 §6) and loses the fluency it already had. The
standard objective makes the drift explicit:
maximise E_{y ~ π(·|x)} [ r(x, y) ] − β · KL( π(·|x) ‖ π_ref(·|x) )
π_ref is the frozen SFT model. KL (Kullback-Leibler divergence) measures
how different two distributions are: 0 when identical. β sets the price of
drifting.
2. PPO, read and diagrammed
PPO needs four models in memory at once:
prompts ──→ [ policy π ] ──samples y──→ [ reward model ] ──→ r(x, y)
│ │
│ log π(y) [ reference π_ref ] ──→ KL penalty per token
│ │
└──────────→ [ value model V ] ──→ baseline, advantage via GAE
│
clipped policy-gradient update of π, regression update of V
- Policy
π: being trained. - Reference
π_ref: frozen SFT copy, for the KL penalty. - Reward model: frozen, scores whole responses.
- Value model
V: trained alongside, predicts the expected future reward from each token position. It turns one end-of-response reward into a per-token signal.
Advantage. For each token, "was this better or worse than expected?":
A_t ≈ (reward that followed) − V(state_t). GAE (generalised advantage
estimation) blends multi-step estimates of that difference to trade bias for
variance with one parameter λ.
The clipped objective. The update reuses each batch of samples for a few
gradient steps. To stop one batch from moving the policy too far, PPO clips
the probability ratio ρ = π_new(y_t)/π_old(y_t) to [1 − ε, 1 + ε]
(ε = 0.2):
L = −E_t [ min( ρ_t · A_t, clip(ρ_t, 1−ε, 1+ε) · A_t ) ]
If an action was good (A > 0), its probability can rise by at most 20% per
batch; if bad, fall by at most 20%. Our GRPO implementation (Stage 20) uses
exactly this loss, and test_clip_stops_large_ratio_gains checks it.
Why it is a memory nightmare. Four models of the policy's size, plus optimizer state for two of them, plus a generation loop in the middle of training. For a 7B policy that is far beyond one GPU. And it is fiddly: the value model, GAE, KL coefficient, clipping and learning rates all interact.
3. DPO: the derivation that removes the reward model
The KL-regularised objective in §1 has a known exact solution. For any reward
function r, the best policy is
π*(y|x) = π_ref(y|x) · exp( r(x, y) / β ) / Z(x)
where Z(x) normalises. In words: start from the reference, and reweight each
response by the exponential of its reward. Responses the reward likes get
more probability, by an amount controlled by β.
Now turn it around. Take logs and solve for r:
r(x, y) = β · log( π*(y|x) / π_ref(y|x) ) + β · log Z(x)
Any policy implicitly defines a reward: β times its log-ratio to the
reference, plus a term that depends only on the prompt. Put this into the
Bradley-Terry preference model from Stage 18, P(c ≻ r) = σ(r(x, c) − r(x, r)).
The awkward log Z(x) appears in both rewards and cancels in the
difference:
P(chosen ≻ rejected) = σ( β log π(c|x)/π_ref(c|x) − β log π(r|x)/π_ref(r|x) )
So we can fit the policy directly to preference pairs, by maximum likelihood, exactly as Stage 18 fitted the reward model:
loss_DPO = −log σ( β [ (log π(c|x) − log π_ref(c|x)) − (log π(r|x) − log π_ref(r|x)) ] )
No reward model, no sampling, no value network. Two models in memory (policy and frozen reference). The training loop looks like SFT on pairs.
log π(y|x) is the sum of the response's token log-probabilities, with
the prompt masked out (Stage 16's mask). The quantity β (log π − log π_ref)
is the implicit reward; we plot it for chosen and rejected responses as
training goes.
What the gradient does. It raises log π(c) and lowers log π(r), weighted
by σ(−margin): hard on pairs the policy currently ranks wrong, little on
pairs it already ranks right. At the start (π = π_ref), the margin is 0 and
the loss is exactly ln 2 (test_dpo_at_reference_is_ln2).
The β knob. Small β (0.01): the KL price is low, the policy may move far from the reference to fit the preferences. Large β (1.0): the policy stays close; preferences barely change it. In the loss, β also scales the margin: a large β makes the loss saturate after small log-ratio changes.
A known failure. DPO only constrains the difference between chosen and rejected. Both log-probabilities can fall at once, as long as rejected falls faster. In practice the chosen log-prob often decreases during DPO, and the probability mass goes to responses that are neither. We watch for it.
4. Which method when
| PPO | DPO | GRPO | |
|---|---|---|---|
| needs a reward model | yes | no | no (needs a reward function) |
| samples during training | yes | no | yes |
| models in memory | 4 | 2 | 2 (+ reward function) |
| data | prompts | fixed preference pairs | prompts + verifier |
| best when | rich learned reward, big compute | a preference dataset exists | the reward can be computed (tests, math) |
For our project, preferences are synthetic (correct vs mutated code), so DPO is the natural fit here, and the unit-test verifier makes GRPO the natural fit for Stage 20.
5. Our setup
- policy and reference: the Stage 16 SFT model;
- pairs: Stage 18's CodeSearchNet correct-vs-mutant pairs, in chat format (user: signature + docstring; chosen/rejected: the two functions);
- evaluation:
- preference accuracy of the implicit reward on held-out MBPP verified pairs: does the policy now rank working code above broken code?
- win rate vs SFT, judged by the tests themselves: on HumanEval and MBPP, pass@1 of DPO vs SFT;
- the Stage 18 reward model's mean score on the policy's own samples;
- KL from the reference on the policy's samples;
- ablation: β ∈ {0.01, 0.05, 0.1, 0.3, 1.0}.
6. Acceptance criteria
llmfs/post/dpo.py, stages/19_dpo/test_dpo.py:
- the loss is
ln 2when policy = reference; - the gradient raises chosen and lowers rejected, with magnitude
β σ(−margin); - the loss depends only on log-ratios to the reference;
run.py: DPO runs; implicit reward margins plotted; pass@1 and preference accuracy vs SFT; β sweep with KL vs reward.
7. Experiments
Policy and reference: the Stage 16 SFT workhorse (30M). Data: 20,000 CodeSearchNet correct-vs-mutant pairs in chat format. 1,000 steps of 8 pairs, lr 5e-6. Measured: preference accuracy of the implicit reward on 1,218 test-verified MBPP pairs; the Stage 18 reward model's score of the policy's own greedy samples on 64 held-out prompts; KL to the SFT model on those samples; HumanEval and MBPP pass@1.
7a. One run, β = 0.1
step 0 200 400 600 800 1000
MBPP pair accuracy 0.50 0.83 0.84 0.83 0.82 0.84
β·Δlog π(chosen) 0 −0.91 −1.84 −5.27 −3.50
β·Δlog π(rejected) 0 −1.52 −3.01 −7.47 −6.64
RM score, own samples 9.56 7.71 7.87 7.61 7.30 7.84
KL to SFT 0 0.04 0.10 0.14 0.15 0.16
DPO learns the preference quickly: the implicit reward ranks working code above its mutant on 84% of MBPP pairs by step 400 (it starts at exactly 50%: policy = reference, every margin 0). Then the failure §3 described: both log-probabilities fall, the rejected faster. By step 600 the chosen functions are 53 nats less likely than under the SFT model. The margin grows by making everything less likely, and the probability goes somewhere else: to the policy's own generations, which the reward model likes less (9.56 → 7.84) and which pass fewer tests (HumanEval 1.2% → 0%).
7b. The β sweep
| β | MBPP pair accuracy | RM score, own samples | KL to SFT | HumanEval |
|---|---|---|---|---|
| SFT (start) | 0.50 | 9.56 | 0 | 1.2% |
| 0.01 | 0.816 | 7.89 | 0.173 | 0.6% |
| 0.05 | 0.835 | 7.64 | 0.185 | 0.0% |
| 0.1 | 0.842 | 7.84 | 0.160 | 0.0% |
| 0.3 | 0.861 | 9.10 | 0.071 | 0.0% |
| 1.0 | 0.873 | 11.13 | 0.020 | 0.6% |
The pattern is the alignment-vs-divergence trade-off of §1, with a twist.
- Small β drifts far and hurts: KL 0.16-0.19, and the reward model's score of the policy's own samples falls from 9.56 to 7.6-7.9. The policy over-optimises the pairwise margin and moves away from good generations. That is the over-optimisation region, and it starts at β ≤ 0.1 here.
- β = 1.0 is best on every axis: highest preference accuracy (0.873), the only setting that raises the reward model's score (11.13 against 9.56), and the smallest drift (KL 0.02). A large β makes the loss saturate after small log-ratio changes, so the policy stops pushing once the pairs are separated instead of dragging all probabilities down.
- None of it moves pass@1. HumanEval stays at 0-1 problem out of 164. DPO on single-mutation pairs teaches the model to prefer correct-looking code among two candidates, which is a ranking skill; writing a correct function from a docstring is a generation skill it does not reach.

7c. The capstone, β = 1
The best setting from the sweep, run once on the 92M capstone (its own SFT model as policy and reference, its own reward model as judge):
| MBPP pair accuracy | RM score, own samples | KL to SFT | HumanEval | MBPP | |
|---|---|---|---|---|---|
| capstone SFT (start) | 0.563 | 20.41 | 0 | 1.22% | 0.4% |
| capstone DPO | 0.895 | 25.37 | 0.027 | 1.22% | 0.4% |
| workhorse DPO, for scale | 0.873 | 11.13 (its own RM) | 0.020 | 0.6% | 0.0% |
The bigger model learns the ranking a little better (0.895 against 0.873), its reward model likes its samples more after DPO (+4.96), and it stays as close to the SFT model as the workhorse did. And the tests do not move at all: the same two HumanEval problems and the same two MBPP problems are solved before and after. The reward scores are not comparable across the two models: each reward model has its own scale.
8. What we found
| Question | Answer, measured |
|---|---|
| Does DPO learn the preference? | Yes: MBPP pair accuracy 0.50 → 0.84 by step 400 (β = 0.1) |
| Do chosen log-probs rise? | No: −53 nats by step 600; rejected fall faster |
| Over-optimisation point | β ≤ 0.1: KL 0.16-0.19 and the reward model scores samples lower than SFT's |
| Best β | 1.0: accuracy 0.873, RM 11.13 (SFT 9.56), KL 0.02 |
| On the 92M capstone (β = 1) | Pair accuracy 0.563 → 0.895, RM 20.4 → 25.4, KL 0.027; same problems solved, pass@1 unchanged |
| Win rate vs SFT, by tests | No win: HumanEval 1.2% → 0-0.6%; MBPP 0% both |
One habit from this stage: track the chosen log-probability, not just the margin. A growing margin with a falling chosen likelihood means the model is learning what not to do by forgetting what to do.
Chapter 22
Rewards you can verify: unit tests
This is the stage the domain choice was made for (docs/domain_choice.md).
For code, "is this answer good?" has an objective answer that a computer
can check for free: run the tests. No human preference labels, no
learned reward model to hack (Stage 18 §6), no LLM judge. The reward is a
program.
Training a policy against a programmatic checker is RLVR: reinforcement learning with verifiable rewards. It is how DeepSeek-R1 and its successors learned long chains of reasoning for math and code. Here we build its algorithm, GRPO, from scratch, and run it on MBPP with reward = "do the unit tests pass".
The honest expectation, stated up front: our models are small. Most MBPP problems are beyond them, and RL cannot reinforce successes that never happen. What we can measure is whether the pass rate on the problems at the edge of the model's ability goes up, and what happens to response length.
1. Chain of thought as inference-time compute
A model that answers immediately gets one forward pass per output token to "think". A model that first writes out intermediate steps gets many: each written step is computed, then read back as input. Chain of thought (CoT) trades more generated tokens for more computation per answer, and on reasoning tasks that trade pays (Wei et al. 2022).
For code, the analogue is writing helper variables, comments, or test calls before the final answer. Whether a 30-100M model can benefit from this is an open question we can only probe.
2. RLVR: the reward is a program
prompt (MBPP problem + one example assert)
│
▼ policy samples G completions
┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│ y1 │ y2 │ y3 │ y4 │ y5 │ y6 │ y7 │ y8 │
└──┬──┴──┬──┴──┬──┴──┬──┴──┬──┴──┬──┴──┬──┴──┬──┘
▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ each run in a sandbox with the
fail PASS fail fail PASS fail fail fail problem's 3 hidden asserts, 5 s timeout
0 1 0 0 1 0 0 0 reward
The verifier is the same sandboxed executor as the evaluation harness (Stage
22): a separate python -I process, empty temp directory, CPU, memory and
file-size limits, a wall-clock timeout. Generated code is untrusted; an
infinite loop must cost 5 seconds, not the run.
"Un-hackable-ish": the policy can still find holes in a verifier. Classic
ones are printing the expected output instead of computing it, special-casing
the visible test, or exiting with status 0 before the asserts run (import os; os._exit(0)). Our sandbox catches the last one: exit status 0 is not
enough, a sentinel line printed after the asserts must also appear
(test_sandbox_rejects_early_exit_hack); the first two are a reason MBPP
keeps two of its three tests hidden from the prompt.
3. Why GRPO
PPO (Stage 19 §2) needs a value model to tell "this response was better than expected" from "this prompt is easy". GRPO (Group Relative Policy Optimization, Shao et al. 2024) drops the value model and uses the group of samples for the same prompt as the baseline:
A_i = (R_i − mean(R_1..R_G)) / (std(R_1..R_G) + ε)
In the picture above, mean = 0.25, std = 0.43: the two passing samples
get advantage +1.73, the six failing ones −0.58. Every token of a passing
completion is pushed up; every token of a failing one, down a little.
Two consequences:
- A group where every sample gets the same reward teaches nothing. All pass or all fail, the advantages are all zero. For a weak model on hard problems, most groups are all-fail. We therefore skip such groups and fill the batch with others (DAPO's "dynamic sampling", Yu et al. 2025), and report what fraction of sampled groups had any signal at all.
- No value model: half of PPO's memory, and one fewer thing to tune.
The update is PPO's clipped objective with a KL penalty to the reference,
using the unbiased k3 estimator per token (ratio − log ratio − 1, always
≥ 0):
L = − mean_tokens [ min(ρ A, clip(ρ, 1−ε, 1+ε) A) ] + β · KL_k3(π ‖ π_ref)
4. Reward shaping and format rewards
With almost no successes, a pure pass/fail reward gives almost no gradient. A format reward gives partial credit for the parts that are easy to check and on the way to a correct answer:
- the completion contains a function definition with the name the test calls;
- it parses as Python;
- it ends with
<|im_end|>instead of running on.
DeepSeek-R1 used format rewards for its <think> tags. The danger is the same
as any proxy: the policy may learn to satisfy the format and stop there. The
ablation compares outcome only with outcome + format (0.1 per
check, so a correct answer, worth 1.0, always dominates).
5. The "aha moment", and what is really going on
R1-Zero's training curves showed response length growing steadily, and the model starting to write things like "wait, let me check that". It was widely read as emergent self-reflection. Later analyses (e.g. Liu et al. 2025, "Understanding R1-Zero-like training") found that much of the length growth comes from a bias in the loss: averaging the loss over tokens per sequence means long wrong answers are penalised less per token than short wrong answers, so the policy drifts towards long ones. And the "reflection" phrases already appear in base models' samples, at low rates.
We log mean response length, separately for passing and failing samples, so we can see which way our run drifts.
Process vs outcome supervision. Our reward judges only the final program (outcome supervision). Process supervision scores each intermediate step (Lightman et al. 2023, "Let's verify step by step"). It needs step-level labels or a trained process reward model. For code, partial test passing is a weak form of process signal; we use all-or-nothing.
6. Setup
- start: the Stage 16 SFT model (it already knows the chat format);
- prompts: MBPP train + validation (464 problems), in the SFT chat format;
- reward: 1.0 if all three asserts pass; optional format reward (§4);
- G = 8 samples per prompt, temperature 1.0, up to 256 new tokens;
- 4 prompts with signal per step (dynamic sampling), 2 PPO epochs per batch, clip 0.2, β = 0.04, lr 1e-6;
- eval every 25 steps: MBPP test pass@1 (greedy, 500 problems) and HumanEval pass@1;
- logged: reward, fraction of groups with signal, response length (passing vs failing), KL to the reference, clip fraction.
7. Acceptance criteria
llmfs/post/grpo.py, stages/20_grpo/test_grpo.py:
- group advantages have zero mean and are exactly zero for uniform groups;
- on-policy with no KL, the loss is minus the mean advantage;
- the clip caps the gain from a large ratio at
1 + ε; - the
k3KL estimate is non-negative; run.py: pass@1 and length curves over training, for outcome-only and outcome + format rewards.
8. Experiments
8a. MBPP: no signal at all
The plan of §6, on the SFT workhorse (30M): MBPP train + validation prompts, 8 rollouts each at τ = 1.0. Three steps tried 72 problems, 576 programs, and none passed. Every group's rewards were identical (all 0), so every advantage was 0 and the update was exactly nothing. We stopped the run: 100 steps of this would have spent 2.5 hours changing no weights.
This is the hardest constraint on RL from verifiable rewards, and it is not specific to small models: GRPO can only amplify successes that already happen. If pass@8 on the training prompts is 0, there is no signal; the format reward of §4 exists precisely to give a gradient before the first real success. R1-style training starts from a base model that already solves a fraction of its math problems.
8b. A curriculum the model can sometimes solve
stages/20_grpo/easy_tasks.py generates templated, test-verified tasks
("return x plus 13", "return the string reversed", "return the largest number
in a list"; 16 templates), with random names and constants: 400 for training
and 150 different ones held out.
A first attempt phrased them like MBPP, as prose. The SFT model scored
0 of 80 even on these, answering def write_function(function):.
Phrased as Stage 16's SFT format (signature, docstring, one doctest):
def last_of_val(lst):
"""Return the last element of a list.
>>> last_of_val([56, 53, 42])
42
"""
the same model scored 7.5% greedy and 13.3% on the held-out set. A 30M model learns one request format in SFT and does not transfer it to another. That is also why its MBPP chat-mode score is 0.
8c. GRPO on the curriculum
60 steps; each step samples groups of 8 rollouts (τ = 0.8) until 4 groups
with mixed results are found (at most 16 tries), 2 PPO epochs per batch,
clip 0.2, β = 0.04, lr 1e-6. Two reward schemes: outcome only (1 if all
hidden asserts pass) and outcome + format (+0.1 each for: parses, defines
the right function name, ends with <|im_end|>).
| step | 0 | 15 | 30 | 45 | 60 |
|---|---|---|---|---|---|
| held-out easy pass@1, outcome only | 13.3% | 14.0% | 24.7% | 30.7% | 38.0% |
| held-out easy pass@1, outcome + format | 13.3% | 16.7% | 20.0% | 24.7% | 26.7% |
| at step 60 | outcome only | outcome + format |
|---|---|---|
| training rollouts passing (first 10 → last 10 steps) | 4.6% → 18.6% | 5.3% → 6.2% |
| failing completion length (tokens) | 94 → 65 | 93 → 78 |
| KL to the SFT model | 0.022 | 0.004 |
| HumanEval pass@1 (SFT: 1.2%) | 2.4% (4/164) | 1.2% |
| MBPP pass@1 (SFT: 0%) | 0.2% (1/500) | 0% |
Outcome-only GRPO nearly triples held-out pass@1 in 60 steps (16 minutes), and the improvement transfers a little outside the curriculum: two more HumanEval problems and the first MBPP problem ever solved by this model.
The format reward hurt. It gives a gradient in every group (all four groups tried had signal), but the signal points at "parse, name the function, stop": things the SFT model mostly did already. Correctness moved far less (26.7% vs 38.0%) and the training pass rate barely changed. The risk named in §4, satisfying the proxy instead of the goal, shows up even with a 10× weight on the real reward.
Length went down, not up. Failing completions shrank from ~94 to ~65 tokens and passing ones from ~70 to ~40. These tasks reward short, direct code; there is no reasoning to lengthen. The "longer and longer chain of thought" of R1-Zero needs problems where thinking helps, a base model able to do it, and (per Liu et al.) a loss that does not favour long wrong answers.

8d. The capstone
Outcome-only GRPO with the same settings, on the 92M capstone's SFT model (activation checkpointing on, 17 minutes):
| step | 0 | 15 | 30 | 45 | 60 |
|---|---|---|---|---|---|
| held-out easy pass@1, workhorse (30M) | 13.3% | 14.0% | 24.7% | 30.7% | 38.0% |
| held-out easy pass@1, capstone (92M) | 27.3% | 38.0% | 42.0% | 53.3% | 73.3% |
| at step 60 | workhorse | capstone |
|---|---|---|
| training rollouts passing (first 10 → last 10 steps) | 4.6% → 18.6% | 9.0% → 24.4% |
| train tasks solved at least once | 129 of 400 | 158 of 400 |
| KL to the SFT model | 0.022 | 0.018 |
| HumanEval pass@1 (its SFT model) | 2.4% (1.2%) | 3.05% (1.22%) |
| MBPP pass@1 (its SFT model) | 0.2% (0%) | 0.4% (0.4%) |
The capstone starts twice as high and gains more: +46 points against +25. That is §6's rule from the other side. RL sharpens what the model can already sometimes do, so a model that solves more at the start has more to sharpen, and more groups carry signal from the first step. Held-out pass@1 rose by 20 points between steps 45 and 60 alone; the curve had not flattened when the run ended.
The transfer to HumanEval is real but small: 2 → 5 problems. Five is exactly what the capstone base model solved when prompted as plain code (Stage 16 §8d). In HumanEval terms, SFT then GRPO bought back what SFT lost, plus the chat format; GRPO's large gain stayed mostly on the kind of task it trained on.
9. What we found
| Question | Answer, measured |
|---|---|
| GRPO on MBPP with our 30M model? | 0 of 576 rollouts passed: no signal, no update |
| Does the request format matter? | Prose prompts 0/80; signature + docstring 7.5% on the same tasks |
| GRPO on a reachable curriculum | Held-out easy tasks 13.3% → 38.0% in 60 steps |
| Transfer | HumanEval 1.2% → 2.4%; MBPP 0 → 0.2% |
| On the 92M capstone | 27.3% → 73.3% in 60 steps (+46, against the workhorse's +25); HumanEval 1.22% → 3.05% |
| Outcome-only vs + format | 38.0% vs 26.7%: the format reward diluted the signal |
| Response length | Fell (94 → 65 tokens failing): no "aha", short tasks reward short code |
One habit from this stage: check pass@k before planning RL. The number that decides whether reinforcement learning can work at all is how often the model already succeeds.
Chapter 23
Smaller and faster: distillation and quantization
Two ways to make a trained model cheaper to run:
- distillation: train a smaller model to imitate the big one;
- quantization: keep the same model, but store its numbers in fewer bits.
Both trade a little quality for a lot of size or speed. This stage builds both by hand and measures the trade.
1. Distillation: learning from a teacher's whole distribution
A normal training target is a hard label: the next token was return,
so push the probability of return up and everything else down. But a
trained model, the teacher, knows more than that. After def add(a, b):\n
its distribution might be:
" return" 0.62 " \"\"\"" 0.21 " if" 0.05 " result" 0.04 ...
That says "a docstring is also quite plausible here, an if less so". A hard
label throws that away. Soft targets keep it: train the student to
match the teacher's whole distribution (Hinton et al. 2015).
loss = α · T² · KL( softmax(z_teacher / T) ‖ softmax(z_student / T) )
+ (1 − α) · CE(z_student, true next token)
- KL divergence measures how far the student's distribution is from the teacher's. Zero when they match.
- Temperature
T(as in Stage 07) softens both distributions so the small probabilities, the "dark knowledge", are large enough to learn from. T²: dividing logits byTshrinks the gradients by1/T²; multiplying back keeps the KL term's scale independent ofT.αmixes in the ordinary hard-label loss.
Why soft targets carry more signal. A hard label is one number per
position, about log₂ V ≈ 13 bits of information at most, and usually far
less. A teacher distribution is a full vector over 8,196 entries. Each training
token tells the student how the teacher ranks every alternative, which is
why a distilled student learns faster from the same tokens than one trained
on raw data.
On-policy vs off-policy. We distil on the training data (off-policy: the student imitates the teacher on text neither of them wrote). On-policy distillation (Agarwal et al. 2024, "GKD") has the student generate and the teacher score the student's own samples, which fixes the mismatch between training on real text and generating its own. It needs sampling in the loop; we note it and stay off-policy.
2. Quantization: fewer bits per number
Our weights are 16- or 32-bit floats. Most of those bits are precision a network does not need. Quantization maps each weight to one of a few integer levels and keeps a scale to map back:
quantize: q = clamp( round(w / s) + z, q_min, q_max )
dequantize: ŵ = (q − z) · s
Worked example, int8 symmetric, weights [0.50, −1.27, 0.00, 1.27]:
s = max|w| / 127 = 1.27 / 127 = 0.01
q = round(w / s) = [50, −127, 0, 127] one byte each instead of four
ŵ = q · s = [0.50, −1.27, 0.00, 1.27] exact here; usually off by up to s/2
test_worked_example_int8_symmetric checks it.
2a. Symmetric vs asymmetric
Symmetric: z = 0, levels centred on 0: [−127, 127] for int8,
[−7, 7] for int4. Zero is represented exactly, and dequantization is a
single multiply. Asymmetric: map [min, max] onto [0, 255] (or
[0, 15]) using a zero-point z. Better when the values are lopsided, such as
activations after a ReLU, which are never negative. Weights are roughly
symmetric, so symmetric is usual for them.
2b. Granularity: how many weights share one scale
| one scale per | overhead (fp16 scale) | robust to outliers | |
|---|---|---|---|
| per-tensor | whole matrix | ~0 | no |
| per-channel | output row | 2 B per row | some |
| group-wise | g consecutive weights (32-128) |
16/g bits per weight | yes |
The problem a scale has to solve: one large weight sets the scale for
everyone sharing it. If one weight in a row is 100× larger than the rest,
s = max/7 (int4) puts every normal weight in the bottom one or two levels:
they all round to 0 or ±1. Group-wise scaling confines the damage to one
group of 64. test_outlier_hurts_per_tensor_not_per_group measures it: the
error is more than 50× larger per-tensor than per-group with a single outlier.
2c. Bits per weight, all in
int8 per-channel: 8 bits + 16/C ≈ 8.0
int4 group-128: 4 bits + 16/128 = 4.125
int4 group-32: 4 bits + 16/32 = 4.5
NF4 block-64: 4 bits + 16/64 = 4.25 (Stage 17)
3. Post-training quantization vs quantization-aware training
PTQ (post-training quantization): take the trained weights, quantize them, done. What we build. Round-to-nearest (RTN) is the simplest PTQ.
Smarter PTQ methods use a little calibration data:
- GPTQ (Frantar et al. 2022): quantize one column at a time and adjust the not-yet-quantized columns to compensate for the error just made, using second-order (Hessian) information from calibration activations.
- AWQ (Lin et al. 2023): find the ~1% of weight channels that multiply the largest activations and scale them up before quantization (and the activations down by the same factor), so they lose less precision.
QAT (quantization-aware training): simulate quantization during training ("fake quant" in the forward pass, straight-through gradients), so the model learns weights that survive rounding. Best quality, needs a training run.
4. Outliers, and why naive int8 broke big models
Dettmers et al. (2022, "LLM.int8()") found that above about 6.7B parameters, transformers develop outlier features: a handful of hidden dimensions whose activations are 20-100× larger than the rest, in every layer. Stage 06 met their cousin in GPT-2 small: residual-stream values near 3,000 in a few dimensions. Quantizing such activations with one scale wipes out every other dimension's information. LLM.int8() keeps the outlier dimensions in fp16 and quantizes the rest. Weight-only quantization (what we do) avoids the problem on the activation side entirely.
KV-cache quantization applies the same ideas to the cache (Stage 07 §6d): at long context the cache, not the weights, dominates memory, and int8 or int4 keys and values halve or quarter it.
5. The frontier: quality, size, speed
Quantization's speed benefit comes from memory bandwidth in decoding
(Stage 07 §6c): reading 4-bit weights moves a quarter of the bytes of bf16.
That needs a fused kernel that reads the packed codes and dequantizes in
registers. Our QuantLinear dequantizes the whole matrix in PyTorch and then
calls an ordinary matmul. That is slower than bf16, not faster. Its
memory savings and quality numbers are real; its speed numbers are honest
about missing kernels. We report all three.
6. Acceptance criteria
llmfs/post/quant.py, stages/21_distill_quant/test_quant.py:
- the int8 worked example; asymmetric maps
[min, max]exactly; - round-trip error ≤ half a quantization step for every granularity;
- a single outlier: per-tensor int4 error ≫ group-wise;
QuantLinearequals fake-quant math; 4-bit codes take 0.5 byte per weight;run.py distill: student trained from scratch vs distilled from the teacher, same steps and tokens;run.py quant: a size / val-loss / tokens-per-second table for bf16, int8 (per-tensor, per-channel), int4 (per-tensor, per-channel, group 128, group 32, asymmetric group 128), NF4 block 64;- the ablation: per-tensor vs per-group int4 on the same weights.
7. Experiments
7a. Distillation
Teacher: the Stage 11 workhorse (30M, val code 1.684 on these windows).
Student: the 4-layer, C=256 GPT (5.4M). Both student runs see the same
6,000 steps × 16 × 512 tokens, same seed and order. The distilled one uses
0.5 · T²·KL(teacher ‖ student) + 0.5 · CE with T = 2.
| step | 1,000 | 2,000 | 3,000 | 4,500 | 6,000 |
|---|---|---|---|---|---|
| from scratch | 4.25 | 3.68 | 3.006 | 2.632 | 2.518 |
| distilled | 4.35 | 3.64 | 2.901 | 2.533 | 2.438 |
The distilled student is 0.080 nats better on the same tokens, and it is ahead from step 2,000 to the end. Early on (step 1,000) it is slightly behind: matching a full distribution is a harder target than predicting one token, until the student is good enough to use the extra information.
The price is compute: every training step runs the 30M teacher too, so the distilled run took 1,126 s against 380 s, 3× the wall time. Whether distillation "beats training from scratch" depends on what is held fixed. With the same tokens, it wins clearly. With the same GPU time, the scratch run could have seen 3× the tokens; Stage 10 says that is worth more than 0.08 for a model this size. Distillation is the right tool when data, not compute, is the limit, or when the teacher's outputs can be computed once and reused.
7b. Quantization
The workhorse (30M), weights only, every nn.Linear except the tied output
head; embeddings and norms stay bf16. Val loss on 256 code windows, size as
stored, decoding speed at batch 1:
| scheme | val code | Δ vs bf16 | size | tokens/s |
|---|---|---|---|---|
| bf16 | 1.6838 | — | 57.1 MB | 725 |
| int8 per-channel | 1.6842 | +0.0004 | 33.2 MB | 416 |
| int8 per-tensor | 1.6859 | +0.0021 | 33.1 MB | 276 |
| NF4, block 64 | 1.6994 | +0.0156 | 21.9 MB | 178 |
| int4 group-32 | 1.7042 | +0.0204 | 24.1 MB | 289 |
| int4 group-128, asymmetric | 1.7078 | +0.0240 | 21.9 MB | 289 |
| int4 group-128 | 1.7190 | +0.0352 | 21.9 MB | 292 |
| int4 per-channel | 1.7424 | +0.0586 | 21.2 MB | 295 |
| int3 group-32 (simulated) | 1.8164 | +0.1326 | — | — |
| int4 per-tensor | 4.0773 | +2.3935 | 21.1 MB | 290 |

Reading it:
- int8 is free. +0.0004 per channel. 256 levels are more than these weights need.
- The ablation: per-tensor vs per-group int4 is +2.39 vs +0.035, a 70× difference in damage for the same 4 bits. With one scale per matrix, the largest weight in the whole matrix sets the step size, and with 15 levels most ordinary weights round to 0 or ±1 step. The model is broken (loss 4.08 is worse than the 5M student). Per channel (+0.059) and per group (+0.035 at 128, +0.020 at 32) confine each outlier's damage to its own row or group. The unit test showed the mechanism on a planted outlier; real weights have them too.
- NF4 is the best 4-bit scheme, +0.016 at block 64: levels placed where the weights are (Stage 17 §5) beat evenly spaced int4 at the same block size and storage.
- Asymmetric helps a little (+0.024 vs +0.035 at group 128): weight groups are not perfectly centred on zero.
- 3 bits (simulated) costs 0.13: the frontier bends sharply below 4.
- Every quantized model is slower, 178-416 tokens/s against 725. That is
the honest result of §5: our
QuantLineardequantizes the whole matrix in PyTorch on every forward, then calls a normal matmul. The memory saving is real (57 → 22 MB), the speed needs a fused kernel we did not write.
The capstone (92M), same schemes:
| scheme | Δ val code, workhorse (30M) | Δ val code, capstone (92M) | capstone size |
|---|---|---|---|
| int8 per-channel | +0.0004 | +0.0000 | 95.1 MB |
| int8 per-tensor | +0.0021 | +0.0021 | 94.7 MB |
| NF4, block 64 | +0.0156 | +0.0134 | 56.8 MB |
| int4 group-32 | +0.0204 | +0.0156 | 64.4 MB |
| int4 group-128, asymmetric | +0.0240 | +0.0184 | 56.8 MB |
| int4 group-128 | +0.0352 | +0.0254 | 56.8 MB |
| int4 per-channel | +0.0586 | +0.0456 | 54.6 MB |
| int3 group-32 (simulated) | +0.1326 | +0.1096 | — |
| int4 per-tensor | +2.3935 | +3.2174 | 54.2 MB |
(bf16: val code 1.4233, 175.7 MB, 451 tokens/s.) The ranking is identical. Every fine-grained scheme hurts the bigger model a little less (NF4 +0.013 against +0.016, int4 group-128 +0.025 against +0.035), which matches the usual observation that larger models quantize more gracefully. The one coarse scheme hurts it more: per-tensor int4 breaks the capstone worse (+3.22, loss 4.64) than the workhorse (+2.39). Bigger matrices hold more weights, so the single largest one, which sets the step for all of them, sits further from the typical weight.
The size column stops at 21 MB, not 57 / 4 = 14: the 8,196 × 512 embedding table (8.4 MB in bf16) and the norms stay unquantized, and every group carries a 16-bit scale.
8. What we found
| Question | Answer, measured |
|---|---|
| Distilled vs scratch student, same tokens | 2.438 vs 2.518 (−0.080), ahead from step 2,000 |
| Cost of distillation | 3× wall time per step (teacher forward) |
| int8 | +0.0004 (per channel): free; 57 → 33 MB |
| Best 4-bit | NF4 block-64, +0.016; 22 MB |
| Per-tensor vs per-group int4 | +2.39 vs +0.035: one scale per matrix breaks the model |
| int3 | +0.13 |
| Speed | All quantized variants slower (178-416 vs 725 tokens/s) without a fused kernel |
One habit from this stage: say what is held fixed. "Distillation wins" is true for equal tokens and false for equal GPU time; "4-bit is nearly free" is true per group and catastrophically false per tensor.
Chapter 24
Measuring what matters
Every stage so far produced a number. This stage asks which numbers deserve trust, puts all our checkpoints through one harness, and produces one table.
What is in this stage:
- what perplexity is good for, and where it misleads;
- multiple-choice scoring by log-likelihood, and length normalisation;
- generative benchmarks: HumanEval and MBPP, pass@k and its estimator;
- LLM-as-judge, its position bias, pairwise win rates and Elo, and why we do not use them;
- contamination: did the test leak into the training data?
- why published benchmark numbers are often not comparable.
1. Perplexity: necessary, not sufficient
Perplexity is exp(loss): "the model is as unsure as if it were choosing
uniformly among this many tokens". Our capstone's code loss of about 1.5
nats is a perplexity of about 4.5.
Uses: comparing models with the same tokenizer on the same text (every stage up to now); spotting training problems; a smooth signal that moves with every change.
Limits:
- Not comparable across tokenizers. A tokenizer with longer tokens has fewer, harder predictions per byte. Use bits per byte instead (Stage 06 did this to compare against GPT-2).
- Dominated by easy tokens. Most code tokens are predictable (closing brackets, indentation, the rest of an identifier). A model can lower average loss a lot while getting no better at the rare tokens that decide whether a program is correct. Stage 14 showed a window-64 model with almost the same loss as full attention and very different long-range retrieval.
- Not the task. We want working programs. Loss says nothing directly about whether a sampled function passes its tests.
2. Multiple-choice scoring and length normalisation
Benchmarks like HellaSwag and MMLU give a question and several candidate answers. A base model is scored by asking which candidate it finds most likely:
score(answer) = log P(answer | question) = Σ_t log P(token_t | question, tokens_<t)
pick the answer with the highest score
The problem: a sum of log-probabilities favours short answers, since every extra token adds a negative number. A three-token wrong answer can beat a ten-token right one just by being short. Length normalisation divides by the number of tokens (or by bytes, which is tokenizer-independent):
score_norm(answer) = (1/len) · Σ_t log P(token_t | ...)
Neither is "correct". Different leaderboards use different ones (lm-eval-harness
reports both acc and acc_norm), and they can rank models differently.
Our version, for code. For each MBPP problem: the reference solution and
three single-mutation variants (Stage 18) that fail the tests. The model
must give the working one the highest score. Mutations change length a little:
x < y → x >= y adds a token, return x → return None changes several.
§8c scores this with and without normalisation and shows how much the
ranking of our checkpoints depends on that choice.
3. Generative benchmarks and pass@k
HumanEval (Chen et al. 2021): 164 hand-written Python problems, each a signature and docstring, with hidden unit tests. MBPP (Austin et al. 2021): 974 short problems in plain English with three asserts each; we use the 500 test problems, showing one assert in the prompt (the standard setup).
The model writes code; the code is run; it passes or not. No judgement involved. This is the objective number the whole project was designed around.
pass@k: the probability that at least one of k samples passes. Sampling
exactly k times per problem is noisy. Chen et al.'s unbiased estimator
samples n ≥ k times, counts the c that pass, and computes the probability
that a random subset of k contains at least one pass:
pass@k = 1 − C(n − c, k) / C(n, k)
Example: n = 10, c = 3, k = 2: 1 − C(7,2)/C(10,2) = 1 − 21/45 = 0.533.
(test_pass_at_k_estimator.) pass@1 with greedy decoding (n = 1,
temperature 0) is the most common single number; pass@10 at temperature
0.8 measures "can it get there at all".
Our harness is tested before it is trusted: all 164 HumanEval reference
solutions pass through it, at least 99% of MBPP's references pass, and
return None stubs fail (stages/22_evaluation/test_eval.py). A harness that
scores the reference solutions below 100% is measuring itself.
Honest expectations. Published small code models: codegen-350M-mono gets 12.8% HumanEval pass@1; GPT-2-sized general models get ~0%. Our 30M and ~100M models, trained on 1-2B tokens, should land in the low single digits or at zero. The number matters because it is objective and comparable, not because it is large.
4. LLM-as-judge, and why not here
For open-ended tasks (chat, summaries) there are no unit tests, so a strong model is asked to judge: "which of these two answers is better?" Known problems (Zheng et al. 2023, "Judging LLM-as-a-judge"):
- position bias: judges prefer the first (or second) answer shown. The control: judge every pair in both orders, count a win only if it survives the swap;
- verbosity bias: longer answers win;
- self-preference: models prefer outputs like their own.
Pairwise judgements are aggregated into win rates or Elo ratings (the chess rating system: each comparison moves both ratings by an amount that depends on how surprising the result was). Chatbot Arena does this with human votes.
At 100M parameters, our models' open-ended answers are too poor for a judge's preferences to measure anything but noise, and we have tests. We use tests.
5. Contamination
If test problems (or their solutions) appear in the training data, the model may have memorised them, and the score measures memory, not skill. HumanEval was written by hand in 2021 to avoid this, but solutions to it have since been posted all over GitHub. MBPP problems are textbook exercises that exist in many forms.
Detection: search the training data for long exact overlaps with each benchmark's solutions. We hash every 13-token window of each reference solution (in our tokenizer) and scan all 1.33B training code tokens for matches. 13-gram overlap is the GPT-3 paper's contamination test. A problem is flagged if any 13-gram of its solution appears in training.
Caveats: an exact 13-gram match can be innocent (for i in range(len(arr)):
is common), and a paraphrased leak has no exact matches. It is a screen, not
proof. We report pass@1 on flagged and unflagged problems separately.
6. Why papers' numbers are often not comparable
The same benchmark name can hide different prompts, few-shot examples, decoding settings, stop sequences, answer extraction, normalisation, and test subsets. MBPP alone has been reported with 0, 1 or 3 tests in the prompt, on the 500-problem test set or the 427-problem sanitized subset. A 2-point gap between two papers is often smaller than the gap between two harnesses run on the same model. Comparing our own checkpoints with one harness is the honest thing we can do; for external comparison we state every setting.
Our settings: greedy pass@1, max 256-300 new tokens, completions cut at the first top-level statement after the function, MBPP test split (500) with one assert in a docstring prompt, HumanEval as published. Base models continue the raw prompt; chat models get it as a user turn.
7. Acceptance criteria
- harness: reference solutions pass, stubs fail, the early-exit hack fails,
pass@k matches the formula (
test_eval.py); run.py table: one row per checkpoint: val loss (code, English), bits per byte, HumanEval pass@1, MBPP pass@1, and pass@10 for the main models;run.py contamination: flagged problems and pass@1 split by flag;run.py mc: mutant-discrimination accuracy with and without length normalisation, and the model ranking under each.
8. Experiments
8a. The table
Every checkpoint through one harness (§6 settings). Val loss on the same 256 windows of 512 tokens; bits per byte for code (comparable across tokenizers, §1); greedy pass@1; pass@10 from 10 samples at τ = 0.8 with the unbiased estimator, for the two real models' checkpoints. Base models continue the raw prompt; SFT / DPO / GRPO models get it as a chat turn.
| model | params | val code | val English | bpb code | HumanEval pass@1 | pass@10 | MBPP pass@1 | pass@10 |
|---|---|---|---|---|---|---|---|---|
| Stage 06 GPT, 4 layers | 5.3M | 2.356 | 4.118 | 1.087 | 0 | — | 0 | — |
| Stage 12 Llama, 6 layers | 12.4M | 2.271 | 4.116 | 1.048 | 0 | — | 0 | — |
| Stage 13 MoE, 8 experts top-2 | 33.7M (total) | 2.325 | 4.119 | 1.073 | 0 | — | 0 | — |
| workhorse base | 29.9M | 1.684 | 3.341 | 0.777 | 0 | 1.22% | 0 | 0 |
| workhorse SFT | 1.832 | 3.646 | 0.846 | 1.22% | 2.44% | 0 | 0.4% | |
| workhorse DPO (β = 1) | 2.013 | 3.697 | 0.929 | 0 | 0.61% | 0 | 0 | |
| workhorse GRPO | 1.833 | 3.646 | 0.846 | 2.44% | 1.83% | 0.2% | 0 | |
| capstone base | 92.1M | 1.423 | 2.950 | 0.657 | 3.05% | 5.49% | 0.2% | 0.4% |
| capstone SFT | 1.582 | 3.261 | 0.730 | 1.22% | 4.88% | 0.4% | 0.4% | |
| capstone DPO (β = 1) | 1.632 | 3.274 | 0.753 | 1.22% | 1.83% | 0.4% | 0.6% | |
| capstone GRPO | 1.582 | 3.260 | 0.730 | 3.05% | 4.88% | 0.4% | 0.6% |
Reading it:
- Loss orders the models exactly as size and data do, and pass@1 is zero for everything below the workhorse. The three small models differ by up to 0.085 nats of code loss and are identical on both benchmarks: loss sees differences that tests cannot yet.
- The best HumanEval model is the capstone base model, prompted as plain code: 3.05% greedy, 5.49% pass@10. No post-training stage beat it on HumanEval. SFT lowered greedy pass@1 to 1.22% while barely touching pass@10 (4.88%): the right answer was still among the samples, just not first. GRPO brought greedy back to 3.05%.
- Every post-training stage raised the pretraining loss: SFT by 0.15-0.16 nats of code, DPO by a further 0.05-0.18. DPO is the most expensive in loss and the least useful in tests (Stage 19: it pushes log-probabilities of chosen and rejected answers down together).
- The numbers are tiny and noisy. One HumanEval problem is 0.61 points. Stage 19 measured workhorse DPO at 1 of 164 with the same settings; here it is 0 of 164. Greedy decoding in bf16 flips at near-ties, and the batch a prompt is generated in changes the arithmetic slightly (Stage 15 saw the same). Differences of one or two problems are not findings.
- pass@10 below pass@1 (workhorse GRPO: 1.83% vs 2.44%) is not a bug: the two come from different decoding. Greedy picks the single most likely completion, which RL sharpened; τ = 0.8 samples spend most of their tries elsewhere.
What got solved, and was it in the training data? Every problem any checkpoint solved:
| model | problems solved (HumanEval / MBPP) | any 13-gram in training? |
|---|---|---|
| capstone base | HumanEval 23, 28, 29, 35, 53; mbpp 242 | none |
| capstone GRPO | HumanEval 23, 28, 29, 35, 53; mbpp 127, 242 | none |
| capstone SFT, DPO | HumanEval 28, 34; mbpp 127, 242 | none |
| workhorse GRPO | HumanEval 23, 28, 35, 53; mbpp 336 | none |
| workhorse SFT | HumanEval 23, 28 | none |
HumanEval 23 is strlen, 28 concatenate, 29 filter_by_prefix, 35
max_element, 53 add: one-line bodies. None of the solved problems has a
single 13-token window of its reference solution in our 1.33B training
tokens, so the four heavily overlapping problems of §8b contributed
nothing. The scores are small, and they are clean.
8b. Contamination
Every 13-token window of each reference solution (HumanEval: prompt + canonical solution; MBPP: reference code), hashed and searched for in all 1.33B training code tokens:
| share of a problem's 13-grams found in training | HumanEval (164) | MBPP test (500) |
|---|---|---|
| any (≥ 1 window) | 69 | 50 |
| ≥ 5% | 16 | 20 |
| ≥ 20% | 1 | 3 |
| ≥ 50% | 0 | 0 |
"Any match" flags 42% of HumanEval, and it means almost nothing: the shared
windows are boilerplate (from typing import List\n\n\ndef, docstring
openings, for i in range(len(). No problem has half its solution in our
training data. The most-overlapping ones are textbook snippets that exist in
thousands of repositories:
# HumanEval/55, 23% of 13-grams in training
if n == 0:
return 0
if n == 1:
return 1
return fib(n - 1) + fib(n - 2)
# mbpp/102, 40%
def snake_to_camel(word):
import re
return ''.join(x.capitalize() or '_' for x in word.split('_'))
Neither is a leak of the benchmark; both are code any Python corpus contains. We treat problems with ≥ 20% overlap as "heavily overlapping" and report pass@1 split by that flag in the table: if a model solves only those, the score is suspect.
8c. Length normalisation
352 MBPP test problems where the reference passes its tests and three distinct single mutations each fail them (Stage 18's mutator). Four options, so chance is 25%. Each option is scored by the log-probability the model gives it after the prompt: summed over its tokens, or per token.
| model | summed | per token | change |
|---|---|---|---|
| Stage 06 GPT (5M) | 50.3% | 56.2% | +5.9 |
| Stage 12 Llama (12M) | 48.3% | 54.8% | +6.5 |
| Stage 13 MoE (34M total) | 46.0% | 50.0% | +4.0 |
| workhorse base | 59.4% | 66.8% | +7.4 |
| workhorse SFT | 62.2% | 69.3% | +7.1 |
| workhorse DPO | 65.3% | 65.1% | −0.2 |
| workhorse GRPO | 62.2% | 68.2% | +6.0 |
| capstone base | 71.6% | 76.7% | +5.1 |
| capstone SFT | 71.9% | 77.0% | +5.1 |
| capstone DPO | 76.7% | 77.8% | +1.1 |
| capstone GRPO | 71.9% | 76.7% | +4.8 |
Three things:
- Every model is far above chance, including the 5M one. Picking the working program out of four near-identical ones is much easier than writing it: the models that score 0 on HumanEval get half of these right. This is Stage 18's finding (a model that cannot write code can judge it) without any reward-model training.
- Normalising helps by 4-7 points, except for DPO. Mutations change length by a token or two in either direction (§2). A sum charges for every token, so a mutant that happens to be shorter gets a head start it did not earn; dividing by length removes it. (We did not count how many mutants are shorter; the size of the gain says it is a common case.)
- The ranking depends on the choice. Summed, workhorse DPO is the best
workhorse checkpoint (65.3%); per token, it is the worst (65.1%, below
base's 66.8%). DPO was trained on exactly this kind of pair, and with a
summed objective (Stage 19's loss sums log-probabilities over the
answer), so it learned to win on summed scores. That is a benchmark result
that measures how the model was trained as much as what it knows; the
same thing happens when a leaderboard reports
accand a paper reportsacc_norm.

9. What we found
| Question | Answer, measured |
|---|---|
| Does the harness measure itself? | No: 164/164 HumanEval references pass, ≥ 99% of MBPP's, stubs and the early-exit hack fail |
| Best HumanEval model | The capstone base model as plain code: 3.05% greedy, 5.49% pass@10 |
| What did post-training buy on HumanEval? | Nothing net: SFT 3.05 → 1.22%, GRPO back to 3.05%; DPO stayed at 1.22% |
| Do models under 30M solve anything? | No: 0 on both benchmarks, though their code losses differ by 0.085 |
| Contamination | 69 HumanEval problems share some 13-gram with training, none share half; every solved problem shares none |
| Noise floor | One problem = 0.61 points; the same checkpoint scored 0 and 1 of 164 in two runs |
| Choosing the working program of four | 46-78%, all far above 25% chance; the 5M model gets 56% |
| Length normalisation | +4 to +7 points, and it reorders models: DPO is best summed, worst normalised among workhorse checkpoints |
The habits from this stage:
- Test the harness on the answers before testing a model on the questions. The trailing-newline trap emptied every base-model completion until one was read raw.
- Evaluate each model in its best format. Comparing an SFT model in chat mode against its base model in chat mode made SFT look like a gain; in the base model's own format it was a loss.
- Below about ten problems, report counts, not percentages. "3.05%" is five one-line functions.
Chapter 25
Serving it
A model that answers one request at a time on one GPU wastes almost all of that GPU. This stage builds a small inference server that answers many requests at once, and measures what the key idea of modern serving, continuous batching, buys under a realistic, bursty load.
1. The one fact that explains serving
Stage 07 split generation into two phases:
- Prefill: the whole prompt in one forward pass. Many tokens per weight read, so the GPU's arithmetic is busy: compute-bound.
- Decode: one token per step. Every step reads every weight (and the KV cache) from memory to do a little arithmetic for one token: memory-bandwidth-bound.
During decode the expensive part, reading the weights, is the same whether the step produces 1 token or 32. So batching decode steps across requests is almost free: 32 requests decoding together take barely longer per step than one. Every serving system is built on that.
Two latency numbers follow:
- TTFT (time to first token): queueing + prefill. What a user feels as "it started answering".
- TPOT (time per output token): one decode step. What a user feels as "how fast it types".
And one throughput number: tokens per second across all requests.
2. Static vs continuous batching
Static batching: collect a batch of requests, run them together until all are finished, then take the next batch.
slot 1: ████████████████████████████████ (long answer)
slot 2: ████████░░░░░░░░░░░░░░░░░░░░░░░░ done early, slot idles
slot 3: ███████████████░░░░░░░░░░░░░░░░░
slot 4: ███░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
new requests wait for the whole batch
Two problems: finished requests leave their slot idle until the longest one ends, and new requests wait for the whole batch, however short it would be for them.
Continuous batching (Orca, Yu et al. 2022): the batch is rebuilt every decode step. A finished request leaves immediately; a waiting request joins on the next step after a quick prefill.
slot 1: ████████████████████████████████
slot 2: ████████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█████ new request joins at once
slot 3: ███████████████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
slot 4: ███▓▓▓▓▓▓▓▓▓▓████▓▓▓▓▓▓▓▓▓▓▓▓▓▓
Requests of very different lengths can now share the GPU without the short ones paying for the long ones. Under bursty load this shows up most in the tail: the p99 latency (the slowest 1% of requests).
3. Our engine
Sslots, each holding one request's KV cache rows;- every step: admit waiting requests into free slots (prefill each one into its slot), then one batched decode over all active slots, each slot attending only to its own cache rows via a length mask, then retire finished requests;
- the same engine runs static mode by admitting only when it is empty.
test_engine.py checks that every request's output, served in a batch with
others joining and leaving, is token-for-token identical to running that
request alone with Stage 07's sampler. Batching is an optimisation; it must
not change answers.
4. PagedAttention and KV-cache fragmentation
Our cache reserves T_max positions for every slot, whether the request uses
50 or 1,000. With requests of mixed lengths most of that reservation is empty:
internal fragmentation. Since the cache size is what limits how many
requests fit at once (Stage 07 §6d), wasted cache means a smaller batch and
lower throughput.
PagedAttention (vLLM, Kwon et al. 2023) borrows virtual memory from operating systems. The cache is split into fixed-size blocks (say 16 tokens). Each request has a block table mapping its logical positions to physical blocks, allocated on demand as it grows. No reservation, almost no waste; the attention kernel follows the block table. Bonus: identical prefixes (a shared system prompt) can point to the same physical blocks: prefix caching.
We do not build paging: on one small model and one GPU, our cache fits comfortably. The fragmentation it would fix is reported (§7) as "cache reserved vs cache used".
5. Chunked prefill and what real servers add
A long prompt's prefill can take as long as dozens of decode steps, and while it runs, every other request's decoding stalls: a spike in their TPOT. Chunked prefill splits a long prompt into pieces processed alongside decode steps, so no single step is huge.
vLLM and SGLang add, on top of continuous batching and paging: fused attention kernels over paged caches, CUDA graphs to remove launch overhead, speculative decoding (Stage 15), quantized weights and caches (Stage 21), prefix caching with a radix tree (SGLang), and multi-GPU tensor parallelism.
vLLM comparison, honestly. The curriculum asks for vLLM on the same
weights. vLLM pins its own PyTorch and CUDA builds (several GB), and the disk
has about 26 GB free with checkpoints still to write. We do not install it.
The reference point we use instead is Hugging Face generate on the same
weights exported to GPT-2 format, batched and unbatched, which is also what
vLLM's own papers compare against.
6. Acceptance criteria
- engine outputs equal single-request greedy outputs, in both modes;
run.py curve: throughput and latency against offered load (requests per second), for continuous batching at several slot counts;run.py bursty: the same bursty trace (Poisson arrivals with bursts, mixed output lengths) served by static and continuous batching: p50/p99 latency, TTFT, throughput;- cache reserved vs used under that trace.
7. Experiments
Model: the Stage 11 workhorse (30M), bf16. Requests: prompts are real val code windows of 32-256 tokens; output lengths are heavy-tailed (16 tokens plus a Pareto draw, capped at 256; mean 66), greedy, 200 requests per run, Poisson arrivals.
7a. Throughput against latency
| slots | 2 req/s | 5 | 10 | 20 | 40 |
|---|---|---|---|---|---|
| 1 | 137 tok/s · 0.23 s | 292 · 2.95 s | 295 · 12.5 s | 296 · 17.5 s | 295 · 20.1 s |
| 4 | 138 · 0.16 s | 339 · 0.17 s | 652 · 0.32 s | 770 · 3.31 s | 782 · 5.69 s |
| 16 | 138 · 0.16 s | 340 · 0.17 s | 660 · 0.22 s | 1,142 · 0.69 s | 1,189 · 2.88 s |
| 32 | 138 · 0.16 s | 340 · 0.17 s | 661 · 0.23 s | 1,173 · 0.60 s | 1,304 · 2.40 s |
(tokens per second across all requests · median request latency)
At low load every configuration serves the offered rate with ~0.16 s median latency: throughput is just what arrives. As load rises, each configuration hits its ceiling and latency explodes, the "hockey stick" of the figure. One slot saturates at ~295 tokens/s: a single sequence decoding one token at a time (Stage 07's overhead-bound regime). Batching raises the ceiling 4.4×, to 1,304 tokens/s at 32 slots, because one decode step for 32 sequences costs little more than one for a single sequence. Time per output token rises from 3.4 ms (1 slot) to 21 ms (32 slots, full): the per-step cost does grow with batch, just much more slowly than the tokens it produces.
7b. Static vs continuous batching under bursty load
Same 16 slots, a trace with Poisson arrivals at 10 requests/s plus bursts (15% of arrivals land at once with the previous one):
| static | continuous | ratio | |
|---|---|---|---|
| median latency | 0.777 s | 0.272 s | 2.9× |
| p99 latency | 1.953 s | 1.563 s | 1.25× |
| median time to first token | 0.377 s | 0.008 s | 47× |
| p99 time to first token | 1.190 s | 0.020 s | 60× |
| throughput | 696 tok/s | 725 tok/s | 1.04× |
Throughput is nearly the same: at this load the GPU is not the bottleneck. What changes is who waits. Under static batching a new request waits for the whole running batch to finish, including its one 256-token straggler, before its prefill even starts: a median 0.38 s of pure queueing. Under continuous batching it is prefilled on the next step, 8 ms later. The p99 improves less (1.25×) because the slowest requests are the long ones, and a long request takes long under any policy.
Cache reserved vs used: requests used 21% of the T_max cache rows
reserved for them on average. That 79% waste is exactly what PagedAttention
(§4) reclaims, and it would let roughly 4× more requests share the same cache
memory.

The same trace on the 92M capstone:
| static | continuous | workhorse (30M), continuous | |
|---|---|---|---|
| median latency | 0.911 s | 0.283 s | 0.272 s |
| p99 latency | 2.130 s | 1.502 s | 1.563 s |
| median time to first token | 0.440 s | 0.008 s (55×) | 0.008 s |
| throughput | 707 tok/s | 720 tok/s | 725 tok/s |
Three times the parameters and the serving numbers barely move: 720 against 725 tokens/s, the same 8 ms first token. At 16 slots and these lengths, each decode step is dominated by fixed per-step costs (Python, kernel launches, the scheduler), not by the matmuls the parameters feed, as Stage 07 found for the KV cache. The model would have to be much bigger, or the batch much larger, before its size showed up here. (At batch 1 it does: 451 against 725 tokens/s, Stage 21.)
7c. Against Hugging Face generate
The workhorse's weights exported into a Hugging Face GPT2LMHeadModel
(transposing back to Conv1D layout). The outputs do not match (max
logit difference 12.2): the workhorse uses QK-norm (Stage 10 §8f), which
GPT-2's architecture does not have, so the exported model silently drops the
q_gain/k_gain tensors. The comparison is therefore of throughput only,
on a model with the same shapes and nearly the same FLOPs:
| batch 1 | batch 16 | |
|---|---|---|
HF generate (static batch) |
425 tok/s | 3,170 tok/s |
| our engine (continuous) | 293 tok/s | 1,561 tok/s |
HF is 1.5-2× faster. Our engine writes each slot's keys and values with a Python loop and builds a length mask every step; HF runs one padded batch with its cache layout optimised for that. A production engine (vLLM) adds CUDA graphs and paged-attention kernels on top. The lesson from §7b is the scheduling one, not raw speed: continuous batching wins on latency even when its per-step code is slower.
8. What we found
| Question | Answer, measured |
|---|---|
| Does batching change answers? | No: engine output equals single-request greedy, both policies (test) |
| Throughput ceiling, 1 → 32 slots | 295 → 1,304 tokens/s (4.4×) |
| Static vs continuous, bursty 10 req/s | p50 0.78 → 0.27 s; p99 1.95 → 1.56 s; TTFT p50 377 → 8 ms |
| KV cache actually used | 21% of reserved rows: the case for paging |
vs HF generate |
HF 1.5-2× faster per token; logits differ because HF GPT-2 has no QK-norm |
One habit from this stage: measure the latency distribution, not the average. The median and the time-to-first-token showed the policy change plainly; throughput alone said nothing happened.
Chapter 26
The whole pipeline on one page
One model, taken the whole way:
tokenizer (01) → data (02) → pretrain (11) → SFT (16) → DPO (19) → GRPO (20)
→ quantize (21) → evaluate (22) → serve (23)
Every step below uses code built and tested in its own stage. Nothing here is
new machinery; this stage is about putting it on one page, with one set of
numbers, and being honest about what the result can and cannot do. The model
card is MODEL_CARD.md at the repository root; every number in it comes
from results/24_capstone/pipeline.json, which is assembled from the stage
result files without recomputing anything.
1. The pipeline, with its numbers
The model: GPT-2 layout (12 layers, width 768, 12 heads, learned positions, LayerNorm, GELU, tied embeddings) plus QK-norm, 92,138,496 parameters, our 8,196-row tokenizer, context 1,024.
val code HumanEval MBPP what this step was measured on
pretrain (11) 1.295* 3.05% 0.2% 1.80B tokens, ~20 GPU-hours, max grad-norm 1.03
└─ SFT (16) 1.582 1.22% 0.4% 119k docstring → function pairs, 3,000 steps
├─ DPO (19) 1.632 1.22% 0.4% pair accuracy 0.563 → 0.895, KL 0.027
└─ GRPO (20) 1.582 3.05% 0.4% easy held-out 27.3% → 73.3% in 60 steps
reward model (18) 86.5% on test-verified MBPP pairs
quantize (21) NF4 +0.013, int8 +0.000, int4 per-tensor +3.22; 176 → 57 MB
serve (23) 720 tok/s; first token p50 0.44 s (static) → 0.008 s (continuous)
* 1.295 is Stage 11's validation set (all windows, 1,024 tokens). Every other loss in this stage comes from Stage 22's harness (256 windows of 512 tokens), where the same base model scores 1.423. Shorter windows give each prediction less context, so the loss is higher; compare numbers only within one column's source.
HumanEval and MBPP are greedy pass@1 from the Stage 22 harness. Base models continue the raw prompt; the SFT, DPO and GRPO models get it as a chat turn.
What each step did, in one line each:
| step | what it bought | what it cost |
|---|---|---|
| pretraining | everything the model knows: val code 1.295; on the Stage 22 harness 0.66 bits per byte (workhorse 0.78) | 20 GPU-hours |
| SFT | the chat format and a stop token (completion loss 0.998 → 0.886, flat after step 250) | +0.16 code loss, +0.31 English; HumanEval 5 → 2 problems |
| reward model | a judge: 86.5% on MBPP pairs (workhorse 85.2%) | — |
| DPO | ranking: pair accuracy 0.895 | +0.05 code loss; no change in what it solves |
| GRPO | the only post-training step that moved a pass rate: 27% → 73% on its curriculum, HumanEval back to 5 problems | 17 minutes |
| quantization | 3.1× smaller at NF4 for +0.013 nats | slower without a fused kernel (106 vs 451 tok/s at batch 1) |
| serving | 55× faster first token under bursty load at the same throughput | — |
The best checkpoint depends on the question. For HumanEval, the base model and the GRPO model tie at 5 problems (3.05%), and the base model has the best pass@10 (5.49%). For telling a working program from a broken one, DPO is best (77.8% normalised). For the curriculum it trained on, GRPO (73.3%).

2. What the model can and cannot do
It can write Python that looks like Python: imports, functions, classes, docstrings, consistent naming. It solves one-line problems when the docstring nearly says the answer:
def filter_by_prefix(strings: List[str], prefix: str) -> List[str]:
""" Filter an input list of strings only for ones that start with a given prefix.
... # HumanEval/29: the base
""" # model's greedy completion
return [s for s in strings if s.startswith(prefix)]
The five HumanEval problems it solves are strlen, concatenate,
filter_by_prefix, max_element and add. Four are one line (return len(string), return x + y); max_element takes four, with a redundant
special case before return max(l). None of them has a single 13-token
window in the training data (Stage 22 §8b).
It also picks the working program out of four near-identical ones 77% of
the time: it can judge code it cannot write.
It cannot write a function that needs two ideas in a row. On
HumanEval/0 ("is any pair of numbers closer than threshold?") it writes
if len(numbers) == 2: return True, then == 3, == 4, and on to the
token limit: the shape of a case analysis with nothing inside it. Greedy
decoding of def fibonacci(n)::
def fibonacci(n):
return n * (n - 1)
def fibonacci_n(n):
return n * (n - 1)
and so on, for 200 tokens. Greedy decoding falls into repetition loops on every prompt we tried, in English too ("The printing press is a very important part of the printing press." eight times). Sampling at τ = 0.8 avoids the loop and produces fluent, wrong code. It has no facts about the world beyond what code comments carry, no multi-step reasoning, and no instruction following outside the docstring → function format SFT taught. It has had no safety training and will continue any prompt.
These are the expectations CLAUDE.md set before the first line of code: "HumanEval pass@1 will be low single digits." It is 3.05%. What the project produced is not a useful model; it is a model of which every part was built, tested against a reference, broken on purpose, and measured.
3. What was learned, part by part
Foundations (Stages 00-07). The tokenizer decided more than expected: a code-specific 8,192-token vocabulary compresses our Python 1.5× better than GPT-2's, and at small model sizes the embedding table is a large share of the parameters (39% of our 5M model, 31% of GPT-2 small, 7% of the 92M capstone with our vocabulary; it would be 30% with GPT-2's), so vocabulary size is a model-size decision (Stages 01, 06). Data work was most of the work: near-duplicate removal cut train/val leakage from 34% to 8% (Stage 02). Every architectural piece has a failure you can produce on purpose and measure: no positions (+0.83), no √d at width 256 (+0.95), no residual (the model learns only unigram statistics, 6.86), post-norm at depth (fails at 24 layers), no next-token shift (train loss 0, real loss 21.9). Loading OpenAI's GPT-2 weights into our own code and matching Hugging Face's logits (float64 difference 2e-11) was the moment the model became trustworthy (Stage 06).
Training (Stages 08-11). A training loop fails quietly. The one-batch overfit test caught nothing because nothing was wrong, which is the point of running it; the resume test caught a real checkpoint bug on its first run (Stage 11). The biggest single speedup was not mixed precision but kernel fusion (2.1×), because after bf16 the step was dominated by elementwise operations (Stage 09). Scaling laws transferred to our scale: our IsoFLOP optima sit within 15% of Chinchilla's 20 tokens per parameter (Stage 10). But the first sweep diverged: attention scores grew to two million over long runs of a small model, and QK-norm, borrowed early from Stage 12's list, fixed it (Stage 10).
Architecture (Stages 12-15). Unbundled, GPT-2 → Llama is mostly one change: RoPE is −0.230 of the −0.244 (Stage 12). GQA is free down to 2 kv heads. MoE, MLA and speculative decoding all depend on scale or data we do not have: MoE ties a dense model at 33M tokens, MLA loses to GQA at 12M parameters, and speculative decoding reaches 1.2× because a 5M draft step costs 43% of a 30M target step. Each is still worth building, because the measurement says exactly which precondition is missing.
Post-training (Stages 16-21). SFT teaches a format in 250 steps and then only forgets (Stage 16). LoRA at rank 1 matches full fine-tuning on that format (Stage 17). A 30M model that cannot write code can still judge it: 85% accuracy telling working functions from their one-mutation twins (Stage 18). DPO learned that ranking and did not improve generation; at small β it over-optimised, lowering the reward model's own opinion of its samples (Stage 19). GRPO with unit tests as the reward could not start on MBPP (0 of 576 rollouts passed) and nearly tripled pass@1 on a curriculum the model could sometimes solve (Stage 20). Quantization granularity matters more than bit width between 4 and 8 bits (Stage 21).
Evaluation and serving (Stages 22-23). The harness had to be tested
before the models: reference solutions must pass, stubs must fail, and an
early os._exit(0) must not count. A trailing newline in HumanEval's prompts
emptied every base-model completion until we read one raw (Stage 22).
Continuous batching changed who waits, not how fast the GPU runs: 47× faster
first token at the same throughput (Stage 23).
4. What is still fuzzy
- Why small models' gradient norms creep upward over long runs even with
QK-norm (the 3-layer model's grew from 1.3 to 2.5 over 73k steps). Is it
the embedding norm, the output logits, or Adam's
ε? - Whether MoE and MLA win at a scale we can reach. Both lost or tied at 33M tokens; neither was tried at the workhorse's 590M.
- What DPO on synthetic bug pairs would do with more data or a larger model: whether pairwise preference can ever move pass@1, or only ranking.
- How much of the HumanEval gap is format. The SFT model scored 0% on prose-phrased tasks it solved 7.5% of the time when phrased as code. A mixed-format SFT set would answer it.
- Repetition. Four epochs cost 0.11 nats, more than published results; our repeated slice was also less diverse. Untangling those two needs a randomly sampled slice.
5. What to learn next
- Multi-GPU training: data, tensor and pipeline parallelism, and the communication that dominates them. Everything here fit on one GPU, which hid the hardest part of training large models.
- Fused kernels: a Triton kernel for the quantized matmul (Stage 21's missing speedup) and for paged attention (Stage 23's missing memory saving).
- Data quality at scale: classifier-based filtering (as FineWeb-Edu did) applied to code, and measured with the Stage 22 harness.
- Reasoning that needs steps: an RLVR curriculum where thinking helps (multi-step arithmetic, small algorithmic tasks), to see whether response length grows when it pays.
A small Python-code language model built from scratch, as the end point of
the curriculum in this repository. It exists to be understood, not used.
Every number below comes from a results file in results/, named next to it.
What it is
| Architecture | GPT-2-style decoder: 12 layers, width 768, 12 heads, learned positions, pre-norm LayerNorm, GELU MLP, tied embeddings, plus QK-norm (Stage 10 §8f) |
| Parameters | 92.1M (85.1M non-embedding) |
| Context | 1,024 tokens |
| Tokenizer | our byte-level BPE, 8,192 merges + 4 specials, every digit split (data/tokenizers/split_8192.json) |
| Pretraining data | 85% permissively-licensed Python (codeparrot-clean, deduplicated) / 15% FineWeb-Edu English |
| Pretraining tokens | 1,802,240,000 (27,500 steps × 65,536), about 20 per parameter; ~20 GPU-hours, resumed once across a 5-day pause (results/11_pretrain/capstone.json) |
| Hardware | one RTX 4060 Laptop GPU, 8 GB |
| Variants | base; SFT (docstring → function, CodeSearchNet); DPO (correct vs mutated code); GRPO (unit-test reward on an easy function-writing curriculum) |
Results
All from results/24_capstone/pipeline.json, which copies them from the
stage result files listed in its sources.
Language modelling (base model). Validation loss on held-out code 1.295 nats per token, English 2.898, on Stage 11's validation set. Stage 22's harness, which uses 512-token windows, gives 1.423 and 2.950 (0.66 bits per byte of code); the rows below use that harness.
Code benchmarks (Stage 22 harness; greedy pass@1, pass@10 at τ = 0.8 from 10 samples):
| variant | val code | HumanEval pass@1 | pass@10 | MBPP pass@1 | pass@10 |
|---|---|---|---|---|---|
| base (prompt continued as code) | 1.423 | 3.05% (5/164) | 5.49% | 0.2% | 0.4% |
| SFT (chat) | 1.582 | 1.22% (2/164) | 4.88% | 0.4% | 0.4% |
| DPO, β = 1 (chat) | 1.632 | 1.22% | 1.83% | 0.4% | 0.6% |
| GRPO (chat) | 1.582 | 3.05% | 4.88% | 0.4% | 0.6% |
For reference, published codegen-350M-mono scores 12.8% HumanEval pass@1.
Other measurements
| Picking the working program among 4 (352 MBPP items, chance 25%) | base 76.7%, DPO 77.8% (per-token scoring) |
| Reward model on test-verified MBPP pairs | 86.5% |
| GRPO curriculum, held-out | 27.3% → 73.3% in 60 steps |
| Quantization damage (val code) | int8 per-channel +0.000; NF4 +0.013 (176 → 57 MB); int4 per-tensor +3.22 (broken) |
| Serving, bursty trace, 16 slots | 720 tok/s; time to first token p50 8 ms (continuous batching) vs 440 ms (static) |
Intended use
Reading, running and breaking, to learn how a language model is built. It is a teaching artifact with an objective score, not a coding assistant.
Limitations, stated plainly
- At 92M parameters and 1.8B tokens it has no world knowledge to speak of, no multi-step reasoning, and no general instruction following.
- It writes Python that is often syntactically plausible and usually wrong. It solves 5 of 164 HumanEval problems, each a one- to four-line body, and 2 of 500 MBPP problems. Greedy decoding falls into repetition loops.
- Its English is fluent at the sentence level and unreliable beyond it.
- It has seen no safety training. It will continue any prompt.
- Its training code comes from public GitHub repositories (permissive licences only); it can reproduce fragments of that code.
How it was evaluated
HumanEval (164) and MBPP test (500) with our own harness, verified on the
reference solutions (164/164 pass), greedy pass@1 and sampled pass@10
(unbiased estimator), sandboxed execution with a sentinel against early-exit
hacks. A 13-gram contamination scan of all 1.33B training code tokens found no
benchmark problem with ≥ 50% of its 13-grams in training, and no 13-gram at
all from any problem the model solves (results/22_evaluation/contamination.json).
Post-training made HumanEval worse before GRPO restored it: compare variants
in their own best prompt format (docs/22_evaluation.md §8a).
Reproducing
README.md → "Running the stages". The pretraining run is resumable:
uv run python stages/11_pretrain/run.py capstone.
Appendix A
Glossary
Every term, defined once, in plain language. Alphabetical. Add a term the first time it appears in any stage.
Acceptance rate — In speculative decoding, the fraction of draft tokens the target model accepts. Decides whether speculation pays off. Stage 15.
Activation checkpointing — Don't store intermediate activations during the forward pass; recompute them during the backward pass instead. Trades roughly 30% more compute for a large cut in memory. Stage 09.
Activations — The intermediate tensors produced by the forward pass. They must be kept alive until the backward pass uses them, which is why they dominate memory at long sequence lengths.
Active parameters — The parameters actually used for one token. In an
MoE, everything shared plus k of the E experts per layer. Compute per
token scales with active parameters; memory with total. Stage 13.
Adam / AdamW — Optimizer keeping two running averages per weight: the
gradient (m, momentum) and the squared gradient (v), stepping by
m/√v so every weight moves on the same scale. AdamW applies weight decay
directly to the weights instead of through the gradient. Stage 08.
Advantage — How much better an action turned out than expected. PPO estimates it with a value model (GAE); GRPO with the group mean. Stage 19.
Attention — A mechanism where each position builds its output as a weighted average of all (allowed) positions' values, with weights computed from query-key similarity. Stage 04.
Attention map — The (T, T) matrix of attention weights for one head:
row i shows how token i splits its attention over earlier tokens. Shows where a
head looked, not what it used. Stage 04.
Attention sink — A position (usually the first token) that an attention head dumps weight on when it has nothing useful to read, because softmax weights must sum to 1. The weight is large but carries little information. Stage 04.
Autocast — PyTorch mode that runs matmuls in a low-precision format (bf16) while keeping reductions, softmax and the weights themselves in fp32. Stage 09.
Autoregressive — Generating a sequence one token at a time, each token
conditioned on all previous ones. Formally: P(x) = Π P(x_t | x_<t).
bf16 (bfloat16) — 16-bit float with the same exponent range as fp32 but fewer mantissa bits. Range matters more than precision for training, which is why bf16 needs no loss scaling while fp16 does. Stage 09.
Bias correction — Dividing Adam's m and v by 1 − βᵗ to undo their
zero initialisation. Makes step 1 move every weight by exactly ±lr. Stage 08.
Bits per byte (bpb) — Loss converted to bits and divided by the number of bytes of text predicted, instead of tokens. Comparable across tokenizers, which loss per token is not. Stage 06.
BPE (Byte Pair Encoding) — A tokenizer training algorithm: repeatedly find the most frequent adjacent pair of symbols in the corpus and merge it into a new symbol. Stage 01.
Bradley-Terry model — P(a beats b) = σ(r_a − r_b): preferences explained
by hidden scores whose differences matter. The reward-model loss is its
negative log-likelihood. Stage 18.
Capacity factor — In MoE, the per-expert token buffer as a multiple of the balanced share. Tokens over capacity are dropped (skip the layer). Stage 13.
Catastrophic forgetting — Fine-tuning on narrow data degrading what the model knew before. Measured as pretraining val loss before and after. Stage 16.
Causal mask — Setting attention scores to -inf for future positions, so
position t can only attend to positions ≤ t. What makes the model
autoregressive. Stage 04.
Chat template — The fixed format that turns a conversation into one token
sequence, with special tokens marking roles (ours: ChatML,
<|im_start|> / <|im_end|>). Stage 16.
Chinchilla — The 2022 result that compute-optimal training uses roughly 20 training tokens per parameter — far more data than earlier practice. Stage 10.
Compute-optimal — For a fixed compute budget, the model size and token count that give the lowest loss. Chinchilla: about 20 tokens per parameter. Stage 10.
Contamination — Benchmark problems or solutions present in the training data, so a score measures memory rather than skill. Screened with long n-gram overlap. Stage 22.
Context length — The maximum number of tokens the model can attend over in one forward pass. Also called block size or sequence length.
Continuous batching — Rebuilding the decode batch every step, so finished requests leave and new ones join immediately. Stage 23.
Cosine schedule — Learning rate that falls from its peak along half a cosine curve to a floor (10% of peak here). Most of a run's final loss improvement comes during this decay. Stage 08.
Cross-entropy loss — −log p(correct token), averaged over positions. At
uniform guessing over V tokens it equals ln V (9.01 for our 8,196). The
training objective of every language model here. Stage 06.
d_model / n_embd — The width of the residual stream; the embedding dimension that every block reads from and writes to.
Decode (phase) — Generating one token per step after the prompt is processed. Reads every weight and the KV cache for little arithmetic, so it is limited by memory bandwidth. Stage 07, Stage 23.
Distillation — Training a smaller student to match a larger teacher's output distributions (soft targets), not just the true next token. Stage 21.
Document masking — A block-diagonal attention mask that stops tokens of one packed document from attending to the previous document. The fix for packing's cross-document contamination; used in long-context training and SFT. Stage 02.
DPO (Direct Preference Optimization) — Fine-tuning on preference pairs via a closed-form loss that provably optimizes the same objective as RLHF, with no reward model and no RL loop. Stage 19.
Dropout — Zeroing a random fraction p of activations during training
(survivors scaled by 1/(1-p)), off at inference. Fights overfitting, so it
only helps when data repeats. Modern pretraining runs use p = 0. Stage 05.
Elo — A rating system from chess: each pairwise comparison moves both players' ratings by an amount that depends on how surprising the result was. Chatbot Arena ranks models this way from human votes. Stage 22.
Embedding — A lookup table mapping each token id to a learned vector. Mathematically a one-hot vector times a matrix. Stage 03.
Exact dedup — Removing byte-identical copies by hashing content. Cheap, and blind to a fork that changed one character. Stage 02.
Expert — One of several parallel FFN sub-networks in an MoE layer. Each token is routed to only a few of them. Stage 13.
Expert collapse — In MoE training, the router sending almost all tokens to one or two experts, which then get all the gradient while the rest stay untrained. Stage 13.
FFN / MLP — The per-position feed-forward network inside a transformer block, usually expanding width 4x and projecting back. Where most parameters live. Stage 05.
FlashAttention — An attention implementation that tiles the computation so the n×n attention matrix is never written to memory. Same math, far less memory traffic. Stage 09.
Format reward — Partial reward for easy-to-check structure (it parses, it defines the right function, it stops). Helps when correct answers are rare. Stage 20.
fp16 / loss scaling — 16-bit float with a small range (≈6e-5 to 65,504). Small gradients underflow to zero, so fp16 training multiplies the loss by a large factor before backward and divides it out after. bf16 does not need this. Stage 09.
Gated linear unit (GLU) — An MLP that makes two projections of the input and multiplies them elementwise, one passed through an activation to act as a per-unit gate on the other. SwiGLU is the SiLU-gated version. Stage 05.
GELU — x · Φ(x), a smooth version of ReLU with a small dip below zero.
GPT-2 uses a tanh approximation of it (gelu_new). Stage 05.
GQA (Grouped-Query Attention) — Query heads are grouped and each group shares one key/value head, shrinking the KV cache. MHA and MQA are its two extremes. Stage 12.
Gradient accumulation — Summing gradients over several small forward/backward passes before stepping the optimizer, to simulate a large batch on small memory. Stage 08.
Gradient clipping (global norm) — If the norm of all gradients together, viewed as one vector, exceeds a threshold (1.0), scale them all down to the threshold. Keeps the direction, limits the step after a rare huge gradient. Stage 08.
Greedy decoding — Always picking the highest-probability next token. Deterministic, and prone to repetition loops. Stage 07.
Group-wise quantization — One scale per group of g consecutive
weights (32-128), so one outlier only damages its own group. Stage 21.
GRPO (Group Relative Policy Optimization) — An RL method that samples a group of responses per prompt and uses their relative rewards as advantages, removing the value network. Stage 20.
Head — One attention subspace. Multi-head attention splits d_model into
n_head heads of size d_model / n_head, each attending independently.
Implicit reward — In DPO, β · log(π(y|x)/π_ref(y|x)): the reward a
policy implies, by DPO's derivation. Stage 19.
IsoFLOP curve — Final loss against model size for runs that all use the same compute. U-shaped; its minimum is the compute-optimal size. Stage 10.
Jaccard similarity — Overlap of two sets: |A ∩ B| / |A ∪ B|, from 0 (disjoint)
to 1 (identical). Near-dedup measures it over sets of word 5-grams. Stage 02.
Jacobian — The matrix of all partial derivatives of a vector function's outputs with respect to its inputs. The backward pass multiplies gradients by one per layer. Stage 05.
Kernel fusion — Combining several GPU operations into one kernel so the
data is read from memory once instead of once per operation. What
torch.compile does for chains of elementwise operations. Stage 09.
KL divergence — Σ p log(p/q): how different distribution p is from
q. Zero when equal. Used to keep a fine-tuned policy near its reference.
Stage 19.
KV cache — Stored keys and values from previous decoding steps, so each new token's attention does not recompute them. Turns O(n²) decoding work into O(n). Stage 07.
LayerNorm — Normalising each token's vector on its own: subtract its mean,
divide by its standard deviation, then apply a learned gain γ and bias β.
Keeps a vector's shape, discards its offset and size. GPT-2. Stage 05.
Leakage (data) — Validation text that the model effectively saw during training, so validation loss measures memorization rather than generalization. For code, mostly forks and vendored copies under different repo names. Stage 02.
Learned absolute positions — A lookup table with one learned vector per slot number (0, 1, 2, ...), added to the token vectors. GPT-2 uses 1,024 rows and cannot run on longer input: there is no row for position 1,024. Stage 03.
Length normalisation — In log-likelihood scoring of multiple choices, dividing a candidate's total log-probability by its length so short answers are not favoured. Stage 22.
Linear attention — Attention with exp(q·k) replaced by φ(q)·φ(k), so
the past can be kept as a fixed-size running sum: an RNN in disguise.
Stage 14.
LLM-as-judge — Using a strong model to compare or grade outputs. Biased by position, length and self-preference. Stage 22.
Load-balancing loss — The MoE auxiliary loss E · Σ f_i P_i (fraction of
tokens routed to expert i times its mean router probability). Equals 1 when
balanced, E when collapsed. Stage 13.
Logits — The raw, unnormalized scores over the vocabulary that come out of the final linear layer, before softmax.
LoRA (Low-Rank Adaptation) — Freeze the base weights and train a low-rank
update B·A instead, cutting trainable parameters by orders of magnitude.
Stage 17.
Loss masking — Setting the targets of prompt tokens to -100 so only the response is trained on. Stage 16.
LSH (Locality-Sensitive Hashing) — Splitting a MinHash signature into bands and bucketing documents by each band, so only documents likely to be similar are ever compared. Turns an O(n²) all-pairs search into roughly O(n). Stage 02.
Massive activations — A few hidden dimensions in a trained transformer's residual stream with values hundreds or thousands of times larger than the rest (≈3,000 in GPT-2 small). They make float32 rounding errors visible and break naive int8 quantization of activations. Stage 06, Stage 21.
Memmap (memory-mapped file) — A file mapped into the address space so the OS loads pages only when touched. A 5 GB token array costs almost no RAM until read. Stage 02.
MFU (Model FLOPs Utilization) — Achieved FLOP/s divided by the GPU's peak FLOP/s. The honest measure of training efficiency. Stage 09.
MinHash — A fixed-size fingerprint of a set: for each of P hash functions, keep the minimum hash over the set's elements. The fraction of positions where two fingerprints agree is an unbiased estimate of their Jaccard similarity. Stage 02.
MLA (Multi-head Latent Attention) — DeepSeek's attention that caches a small latent vector per token and rebuilds each head's keys and values from it, plus a small shared RoPE key. Stage 14.
Model card — A short document published with a model: what it is, how it
was trained, how it scores, and what it should not be used for. Ours is
MODEL_CARD.md. Stage 24.
MoE (Mixture of Experts) — Replacing one FFN with many, and routing each token to a few, so total parameters grow without per-token FLOPs growing. Stage 13.
Momentum — A running average of recent gradients, followed instead of the
latest one. Cancels zigzags, accumulates consistent directions. Adam's m.
Stage 08.
MQA (Multi-Query Attention) — Attention where all query heads share one key head and one value head. The smallest KV cache; some quality loss. GQA with one group. Stage 12.
Multi-head attention — Running H smaller attentions side by side, each on
a d = C / H slice, then mixing their outputs with one C × C projection.
Same parameter count as one big head; H attention patterns instead of one.
Stage 04.
Near-duplicate dedup — Removing documents that are almost, but not exactly, the same (forks, reformatted copies). Done with MinHash + LSH. Stage 02.
Needle in a haystack — A long-context test: hide a fact deep in a long input and ask for it at the end. Shows retrieval failures that average loss hides. Stage 14.
NF4 (4-bit NormalFloat) — A 4-bit format whose 16 levels sit at quantiles of a normal distribution, matching how trained weights are distributed, with one scale per block of 64. Stage 17.
Non-embedding parameters — Parameter count excluding the token and position tables. Scaling laws use it because a table lookup costs memory but almost no compute per token. GPT-2 small: 85.1M of 124.4M. Stage 06.
NoPE (no positional encoding) — A causal language model given no position information at all. It still learns some sense of order, because the causal mask lets token t see exactly t+1 tokens. Stage 03 measures how much it loses.
NTK-aware scaling — Extending RoPE to longer contexts by raising its base
θ, which slows the slow rotation pairs by the stretch factor while barely
changing the fast ones. Stage 12.
One-hot vector — A vector of zeros with a single 1, at the index of the item it represents. Multiplying a one-hot by a matrix selects one row, which is why an embedding layer is a linear layer on one-hot inputs. Stage 03.
Output head / unembedding — The final C × V matrix that turns each
position's hidden vector into one score (logit) per vocabulary token. Often
shares its weights with the embedding table (see weight tying). Stage 03.
Overfitting — Fitting the training data in ways that do not carry over to new data, usually by memorising examples seen many times. Shows as training loss falling while validation loss stalls or rises.
Packing — Concatenating documents into one stream separated by an end-of-text token and cutting fixed-length windows from it, instead of padding each document to length. No wasted compute on padding. Stage 02.
PagedAttention — Storing the KV cache in fixed-size blocks allocated on demand through a block table, so cache memory is not reserved and wasted. vLLM. Stage 23.
pass@k — The probability that at least one of k sampled programs
passes the tests, estimated without bias from n ≥ k samples as
1 − C(n−c, k)/C(n, k). Stage 22.
Permutation equivariance — Shuffling the input shuffles the output the
same way and changes nothing else. Attention with no mask and no position
information has this property, so it cannot tell a = b from b = a. Stage 03.
Perplexity — exp(cross-entropy loss). Intuitively, how many tokens the
model is effectively choosing between at each step. Lower is better.
Position bias — An LLM judge's tendency to prefer whichever answer it is shown first (or second), regardless of quality. Controlled by judging each pair in both orders. Stage 22.
Post-norm — Normalising after the residual add: Norm(x + f(x)). The
2017 transformer and BERT. Puts a norm on the residual path itself, which makes
deep stacks harder to train. Stage 05.
PPO (Proximal Policy Optimization) — RL algorithm with a clipped objective that limits how far one batch can move the policy. RLHF's original workhorse, with policy, reference, reward and value models. Stage 19.
Pre-norm — Normalizing the input to each sublayer rather than its output. Required for stable training at depth. Stage 05.
Prefill (phase) — Processing the whole prompt in one forward pass to fill the KV cache. Many tokens per weight read, so it is compute-bound. Stage 07.
Previous-token head — An attention head that puts most of its weight on the token just before. Shows as a bright line one step below the diagonal of its attention map. Stage 04.
PTQ / QAT — Post-training quantization (quantize trained weights; e.g. GPTQ, AWQ) vs quantization-aware training (simulate quantization while training). Stage 21.
QK-norm — RMSNorm applied to each head's queries and keys before the dot product, keeping attention scores in a bounded range for stability. Stage 12.
QLoRA — LoRA on top of a base model stored in 4-bit NF4, dequantized on the fly. Stage 17.
Quantization — Storing numbers as low-bit integers plus a scale (and
maybe a zero-point): w ≈ (q − z) · s. Stage 21.
Query, key, value — The three vectors each token makes for attention: the query is what it is looking for, the key is what it matches on, the value is what it hands over when picked. Each is the token vector times its own learned matrix. Stage 04.
Rank collapse — Every position's vector becoming the same as you go up a stack of attention layers, so tokens can no longer be told apart. What actually breaks when residual connections are removed (measured: cosine 1.000 between positions by block 12). Stage 05.
ReLU — max(0, x). Cheap; its gradient is exactly 0 for negative inputs,
so a unit can stop learning ("die"). Stage 05.
Repetition penalty — Lowering the logits of tokens already in the context (divide positive logits, multiply negative ones, by ~1.1-1.3). A blunt fix for loops that also discourages legitimate repetition, such as variable names in code. Stage 07.
Residual connection — Adding a layer's output to its input, x + f(x),
instead of replacing it. The layer learns a correction, and the gradient gets a
direct path past the layer. Stage 05.
Residual stream — The running sum that each block reads from and adds to. The "highway" that lets gradients reach early layers.
Residual-scaled init — Initialising the layers that write into the
residual stream (c_proj) with std 0.02/√(2L), so the summed contribution
of all 2L sublayers at init has the size of one. GPT-2's choice. Stage 06.
Reward hacking — A policy reaching high reward through flaws in the reward (model or verifier) rather than by doing the task. Stage 18.
Reward model — A language model with a scalar head that scores a (prompt, response) pair; trained on preference pairs. Stage 18.
RLVR (RL with verifiable rewards) — Reinforcement learning where the reward is computed by a program (tests, answer checker) instead of a learned model. Stage 20.
RMSNorm — Normalization by root-mean-square only, without subtracting the mean. Cheaper than LayerNorm with equal quality. Stage 05.
RoPE (Rotary Position Embedding) — Encoding position by rotating query and key vectors by an angle proportional to position, making attention scores depend on relative distance. Stage 03.
Router / gate — The small network in an MoE layer that decides which experts each token goes to. Stage 13.
Router z-loss — Penalty on the square of logsumexp(router logits) that
keeps router logits small and the softmax numerically stable. Stage 13.
SFT (Supervised Fine-Tuning) — Training a base model on instruction/response pairs so it answers instead of merely continuing text. Stage 16.
SGD (stochastic gradient descent) — θ ← θ − lr · g, with g estimated
on one batch. The baseline optimizer. Stage 08.
Shared expert — An MoE expert every token always uses, alongside its routed experts. Holds common knowledge once. DeepSeek-MoE. Stage 13.
Shift (next-token targets) — Targets are the inputs moved left by one:
input ids[:, :-1], target ids[:, 1:]. Together with the causal mask it
turns one window of T+1 tokens into T next-token training examples.
Stage 06.
Shingle — An overlapping window of n consecutive words (we use n = 5). A document's set of shingles is what near-dedup compares. Stage 02.
SiLU (swish) — x · sigmoid(x). Smooth, with a dip below zero; the gate
in SwiGLU. Stage 05.
Sinusoidal positions — Position encoded as the sines and cosines of
p·ω_i at many speeds ω_i, like a row of clocks running at different rates.
No parameters; moving by k positions is a fixed rotation. From the 2017
transformer paper. Stage 03.
Sliding-window attention — Each token attends only to the last W
tokens. Bounded cache and compute; information still travels further across
layers. Stage 12.
Softmax — Turns a vector of scores into a probability distribution:
exp(x_i) / Σ exp(x_j).
Softmax saturation — When the inputs to softmax are far apart, one weight
approaches 1 and the rest 0. Softmax's slope is then near zero everywhere, so
almost no gradient flows back. Dividing attention scores by √d prevents it.
Stage 04.
Speculative decoding — A small draft model proposes several tokens; the big model checks them all in one pass; a rejection-sampling rule keeps the output distribution exactly the big model's. Stage 15.
State-space model (SSM) — A layer that carries a hidden state through a
learned linear recurrence h_t = a·h_{t−1} + b·x_t, computable step by step
or all at once by a scan. S4, Mamba. Stage 14.
SwiGLU — A gated feed-forward variant: (W1·x ⊙ silu(W3·x))·W2. Standard in
modern models. Stage 05.
Temperature — Dividing logits before softmax. <1 sharpens the distribution,
1 flattens it. Stage 07.
TF32 — A tensor-core mode that multiplies fp32 inputs using only 10 mantissa bits. Faster matmuls with one line of code, slightly less precise. Stage 09.
Token — The unit the model actually sees: a sub-word chunk of bytes produced by the tokenizer. Not a word, not a character. Stage 01.
Top-k / top-p sampling — Truncating the next-token distribution to the k most likely tokens, or to the smallest set whose probability sums to p, before sampling. Stage 07.
TTFT / TPOT — Time to first token (queueing + prefill) and time per output token (one decode step). The two latencies users feel. Stage 23.
Unigram loss — The cross-entropy of predicting every token from its overall frequency alone, ignoring all context. The loss of a model that learned nothing about context: 6.86 on our code validation set. Stage 05.
Warmup — Ramping the learning rate up from ~0 over the first few hundred steps, because Adam's variance estimates are unreliable early. Stage 08.
Weight decay — Shrinking every weight slightly towards zero each step. Applied to matrices, not to biases or norm gains. Stage 08.
Weight tying — Sharing one matrix between the input embedding and the output
projection. Saves vocab × d_model parameters. Stage 03 (measured), Stage 06.
Appendix B
Every result in one table
Numbers only. Every experiment that produced a measurement goes here so trends stay visible across months.
| Date | Stage | Experiment | Metric | Value |
|---|---|---|---|---|
| 2026-10-14 | 00 | 12.6M-param toy model, fp32 + AdamW | predicted vs measured fixed VRAM | 192.0 MB vs 208.3 MB (8.5% error) |
| 2026-10-14 | 00 | same | peak allocated incl. activations | 256.3 MB |
| 2026-10-14 | 01 | RegexBPE on tinyshakespeare (1.0M chars train) | held-out bytes/token @ vocab 512 | 1.878 |
| 2026-10-14 | 01 | same | held-out bytes/token @ vocab 1024 | 2.257 (+20.2% over 512) |
| 2026-10-14 | 01 | our encoder vs tiktoken, 100k chars | encode throughput | 0.53 MB/s vs 14.4 MB/s (27x slower) |
| 2026-10-14 | 01 | gpt2 / cl100k / o200k on same held-out text | bytes/token | 3.107 / 3.557 / 3.614 |
| 2026-10-14 | 01 | weighted-dedup training vs naive | merge lists identical, suite runtime | 8.8s → 3.25s |
| 2026-10-25 | 01 | stage-01 trainer on 20 MB real Python | time per merge | 0.22 s (4.9M chunks → 110k unique) |
| 2026-10-25 | 02 | codeparrot-clean shard profile | files / text / permissive bytes | 100k / 1.02 GB / 57.7% per shard |
| 2026-10-25 | 02 | leakage, 2 shards, file split, no near-dedup | rare val lines in train / files >50% leaked | 43.9% / 48.6% |
| 2026-10-25 | 02 | leakage, 2 shards, repo split, no near-dedup | rare val lines in train / files >50% leaked | 34.4% / 43.3% |
| 2026-10-25 | 02 | near-dedup, 12 shards, 729,865 files, 149 s | train dropped / val dropped | 28.2% / 39.5% (1,258 of 1,264 had a train copy) |
| 2026-10-25 | 02 | leakage, file split, after near-dedup | rare val lines in train / files >50% leaked | 21.7% / 27.4% |
| 2026-10-25 | 02 | leakage, repo split, after near-dedup | rare val lines in train / files >50% leaked | 8.1% / 13.8% |
| 2026-10-25 | 02 | exact dedup check on real shards | exact duplicates found | 0 (confirms upstream claim) |
| 2026-10-25 | 01 | held-out code B/tok @ 8192: grouped / cap3 / split | compression | 3.381 / 3.376 / 3.337 |
| 2026-10-25 | 01 | held-out code B/tok @ 16384, grouped | compression | 3.586 (+6.1% over 8192) |
| 2026-10-25 | 01 | GPT-2 (50k) / cl100k (100k) on same held-out code | compression | 2.222 / 4.244 |
| 2026-10-25 | 01 | llmfs cached encoder vs stage-01, 1 core, real code | throughput | 8.14 vs 0.66 MB/s (12×), 98.2% cache hits |
| 2026-10-25 | 02 | full tokenization, 18 workers | tokens / time | 2,357M / ~4.5 min (~36 MB/s) |
| 2026-10-25 | 02 | train_code / train_en / val_code / val_en | tokens | 1,330.1M / 1,016.9M / 4.9M / 5.2M |
| 2026-10-25 | 02 | fineweb-edu exact duplicates | dropped | 1,476 train, 13 val |
| 2026-10-25 | 02 | MixedLoader B=16 T=1024, cpu / cuda / cuda+pinned | tokens/s | 56M / 125M / 140M (700-1750× need) |
| 2026-10-29 | 03 | tiny LM (4L, C=256, 32.8M tok, 3 seeds), no position | held-out code loss | 3.350 ± 0.013 |
| 2026-10-29 | 03 | same, learned absolute positions | held-out code loss | 2.689 ± 0.012 |
| 2026-10-29 | 03 | same, sinusoidal without √C token scaling | held-out code loss | 4.723 ± 0.080 (position 35× token size) |
| 2026-10-29 | 03 | same, sinusoidal with √C token scaling | held-out code loss | 2.633 ± 0.001 |
| 2026-10-29 | 03 | same, RoPE, tied head | held-out code loss | 2.523 ± 0.010 |
| 2026-10-29 | 03 | same, RoPE, untied head (+2.10M params) | held-out code loss | 2.598 ± 0.009 |
| 2026-10-29 | 03 | trained T=256, eval positions 256-511: none / sin-scaled / RoPE / RoPE-untied | loss (vs 0-255) | 3.51 (3.30) / 4.94 (2.61) / 3.29 (2.51) / 3.19 (2.58) |
| 2026-10-30 | 04 | random q,k,v, 256 keys, no √d, d=64 / 1024 | score-gradient median; queries with ~none | 1.23 / 0.022; 2% / 41% |
| 2026-10-30 | 04 | same, gradient at q, scaled vs unscaled, d=1024 | norm | 3.1 vs 63.1 (grows, not vanishes) |
| 2026-10-30 | 04 | naive vs fused attention, B=1 H=8 d=64 bf16 fwd+bwd, T=8192 | peak MB / ms | 4,168 / 148 vs 64.5 / 10.7; naive OOM at 16,384 |
| 2026-10-30 | 04 | tiny LM with our attention (= Stage 03 learned), seed 0 |
held-out code loss | 2.6856 (Stage 03 with SDPA: 2.6849) |
| 2026-10-30 | 04 | 4 heads × 64, scaled / unscaled, 3 seeds | held-out code loss | 2.689 ± 0.012 / 2.652 ± 0.006 |
| 2026-10-30 | 04 | 1 head × 256, scaled / unscaled, 3 seeds | held-out code loss | 2.705 ± 0.003 / 3.655 ± 0.018 |
| 2026-10-30 | 04 | same, attention entropy / top weight | nats / weight | 2.78 / 0.29 vs 0.92 / 0.78 |
| 2026-10-30 | 04 | trained d=64 model, head statistics | prev-token head; sinks | L2H2 68%; L3H0 24%, L3H1 37% on first token |
| 2026-11-06 | 05 | untrained 24L, block-1 / block-24 grad norm: pre / post / no-residual | grad | 2.21/0.38 · 1.32/0.12 · 3.65/2.63 |
| 2026-11-06 | 05 | same, mean cosine between positions after block 24 | cosine | 0.69 · 0.03 · 1.000 (no residual, from block 12) |
| 2026-11-06 | 05 | unigram (token-frequency) cross-entropy, 512 val code windows | loss | 6.860 |
| 2026-11-06 | 05 | pre-norm 4L / 24L, small embeddings, seed 0 | held-out code loss | 2.685 / 2.567 |
| 2026-11-06 | 05 | post-norm 4L / 24L, small embeddings | held-out code loss | 6.856 / 6.857 (frequency floor) |
| 2026-11-06 | 05 | no residual 4L / 24L | held-out code loss | 6.856 / 6.856; block-1 grad 3.8e-19 @ step 1000 (24L) |
| 2026-11-06 | 05 | post-norm 4L, edit size rms(f)/rms(x) at step 500: small emb / √C emb | ratio | 2-24 / 0.3-0.6 |
| 2026-11-06 | 05 | √C embeddings: pre 4L / post 4L / pre 24L / post 24L / post 24L no warmup | held-out code loss | 2.685 / 2.693 / 2.469 / 6.700 / 6.856 |
| 2026-11-06 | 05 | post-norm 4L small emb, lr 3e-4 / 1e-4 | held-out code loss | 3.822 / 4.698 |
| 2026-11-06 | 05 | 4L sweep, 3 seeds: baseline / RMSNorm / ReLU / SwiGLU | held-out code loss | 2.689±.012 / 2.712±.027 / 2.714±.002 / 2.651±.012 |
| 2026-11-06 | 05 | no MLP 4L / no MLP 12L (param-matched) / dropout 0.1 | held-out code loss | 2.959±.028 / 2.909±.022 / 2.775±.024 |
| 2026-11-06 | 05 | norm fwd+bwd, 8192×C bf16, C=256: LN ours / RMS ours / nn.LN / nn.RMS | ms | 1.18 / 0.60 / 0.42 / 0.30 (C=4096 fused: 3.92 / 3.91; Linear C×C 36.8) |
| 2026-11-06 | 06 | our GPT with OpenAI GPT-2 weights vs HF, 200 val windows, GPU fp32 / fp64 | max logit diff | 0.055 / 2e-11 (residual stream max ≈3,000) |
| 2026-11-06 | 06 | GPT-2 small parameter count | by hand = numel | 124,439,808 |
| 2026-11-06 | 06 | GPT-2 124M on our val (650-tok windows) | bits per byte code / English | 1.394 / 1.064 |
| 2026-11-06 | 06 | 256-tok windows: GPT-2 124M vs ours 5.3M (12k steps) | bits/byte code; English | 1.522 vs 1.066; 1.122 vs 1.774 |
| 2026-11-06 | 06 | stream rms after last block at init, plain vs scaled, 12L / 48L | rms (embed 0.028) | 0.474 vs 0.090 / 0.933 vs 0.089 |
| 2026-11-06 | 06 | 12L, 4k steps, 2 seeds: plain vs scaled residual init | held-out code loss | 2.581 vs 2.568 (tie) |
| 2026-11-06 | 06 | no shift (target = input), 1k steps | train / next-token val | 0.0001 / 21.86 (shift: 4.09) |
| 2026-11-06 | 06 | tied vs untied, 4L, 4k / 12k steps | held-out code loss | 2.6814 vs 2.7576 / 2.3577 vs 2.3608 |
| 2026-11-06 | 07 | KV cache vs naive, batch 1, fp32, length 512 / 1024 | speedup 5M / 30M / 92M | 1.27 / 3.32 / 4.47 ; 2.28 / 5.51 / 7.23 |
| 2026-11-06 | 07 | cached vs naive tokens, 36 settings | identical | 36/36 (greedy and sampled) |
| 2026-11-06 | 07 | Stage 06 model, greedy / τ0.7 / τ1.0 / τ2.0 | distinct-2 ; mean log-prob | 0.07/0.32/0.79/1.00 ; −0.24/−0.95/−3.19/−9.51 |
| 2026-11-06 | 08 | hand AdamW vs torch, 25 steps, fp32 / fp64 | max weight diff | 2.3e-4 / 4.2e-13 |
| 2026-11-06 | 08 | 4L, 1.5k steps: SGD / +momentum / Adam / AdamW / Adam+L2 (0.1) | held-out code loss | 5.615 / 4.310 / 3.609 / 3.614 / 6.695 |
| 2026-11-06 | 08 | overfit one batch (8×256) | steps to loss < 1 / 0.1 / 0.01 | 72 / 96 / 129 (spike ×1,600 at step 259) |
| 2026-11-06 | 08 | TinyStories 10.1M, 49M tokens | val loss / minutes | 1.510 / 11.5 |
| 2026-11-06 | 08 | 6L/384 lr 3e-3: base / no clip / no warmup / neither | held-out code loss | 2.946 / 3.028 / 4.781 / 5.057 |
| 2026-11-06 | 08 | 4L 4k steps: sequential / random / shuffled windows | held-out code loss | 3.937 / 2.695 / 2.683 |
| 2026-11-06 | 09 | 4096² matmul fp32 / TF32 / bf16 / fp16 | TFLOP/s | 5.48 / 10.43 / 23.63 / 24.76 |
| 2026-11-06 | 09 | 8L/512 T=512 B=8: fp32 → TF32 → bf16 → SDPA → fused Adam → compile | tokens/s | 14,271 → 18,536 → 23,142 → 34,490 → 35,098 → 73,656 (5.16×, MFU 63%) |
| 2026-11-06 | 09 | + activation checkpointing | tokens/s / peak MB | 60,955 / 718 (from 1,221) |
| 2026-11-06 | 09 | T=1024 full stack: workhorse B16 / capstone B8 | tokens/s (MFU) | 70,200 (67%) / 25,389 (71%) |
| 2026-11-06 | 10 | 4L/256, 13k steps, plain GPT-2 recipe | max attention score / val | 2,191,156 / 2.656 (diverged) |
| 2026-11-06 | 10 | same: lr 5e-4 / QK-norm lr 1e-3 | val code | 2.431 / 2.280 |
| 2026-11-07 | 10 | IsoFLOP 3e15 (L2..L8) | val code | 2.480 / 2.329 / 2.279 / 2.481 / 3.667 |
| 2026-11-07 | 10 | IsoFLOP 1e16 (L3..L10) | val code | 2.184 / 2.065 / 2.055 / 2.241 / 2.622 |
| 2026-11-07 | 10 | fitted optimum 3e15 / 1e16 | N (tokens/param) | 4.2M (28) / 8.6M (22.5); Chinchilla 5.0M / 9.1M |
| 2026-11-07 | 10 | 4L, 108M tokens: code100 / 85-15 / 70-30 | val code ; English | 2.182 / 2.204 / 2.260 ; 5.308 / 4.046 / 3.844 |
| 2026-11-07 | 10 | 4L code, 1 / 4 / 16 epochs | val code | 2.176 / 2.288 / 2.803 |
| 2026-11-07 | 10 | 3L, 1× / 2× / 5× / 10× optimal tokens | val code | 2.534 / 2.365 / 2.228 / 2.178 |
| 2026-11-07 | 11 | workhorse 30M, 590M tokens, 2h18m | val code / English | 1.554 / 3.293 (max grad norm after step 1k: 1.49) |
| 2026-11-07 | 12 | ladder (2 seeds): GPT-2 / +RMS / +RoPE / +SwiGLU / +no bias / +GQA2 / +QK-norm | val code | 2.518 / 2.551 / 2.321 / 2.295 / 2.304 / 2.329 / 2.274 |
| 2026-11-07 | 12 | kv heads 8 / 4 / 2 / 1 / 1+MLP | val code | 2.306 / 2.305 / 2.315 / 2.335 / 2.328 |
| 2026-11-07 | 12 | window full / 128 / 64 / 16 | val code | 2.314 / 2.424 / 2.559 / 3.141 |
| 2026-11-07 | 12 | trained @512, eval @2048, NTK s=1 / 2 / 4 | loss at pos 1024-2048 | 2.557 / 2.232 / 2.187 |
| 2026-11-07 | 13 | dense / MoE 8×top2 / no aux / 7+1 shared top1 / 16×top4 / dense same total | val code | 2.320 / 2.325 / 2.326 / 2.369 / 2.303 / 2.354 |
| 2026-11-07 | 13 | busiest expert share of top-2 assignments, with / without aux | fraction (balanced 0.125) | 0.23 / 0.41 (4 of 8 dead mid-layer) |
| 2026-11-07 | 14 | MLA r=128 / 64 / 32 / 16 / 4 | val code (cache B/token) | 2.414 (1728) / 2.476 (960) / 2.765 (576) / 2.801 (384) / 3.198 (240) |
| 2026-11-07 | 14 | needle mean retrieval: full / win128 / win64 / MLA64 / MLA16 | fraction | 0.51 / 0.31 / 0.09 / 0.58 / 0.04 |
| 2026-11-07 | 11 | resume at 600: resumed / fresh Adam | final val (uninterrupted 3.9158) | 3.9158 (bit-identical) / 3.9323 |
| 2026-11-07 | 15 | spec. decoding, 30M target / 5M draft, greedy γ=1/4/6/8 | acceptance ; speedup | 0.93/0.83/0.77/0.73 ; 0.86/1.17/1.20/1.15 |
| 2026-11-07 | 15 | same, τ=1.0, γ=1 / 8 | acceptance ; speedup | 0.67 / 0.26 ; 0.82 / 0.25 |
| 2026-11-07 | 16 | SFT workhorse, 3k steps: completion val ; HumanEval / MBPP pass@1 (chat) | loss ; fraction | 1.168→1.033 ; 0.0122 / 0.0 |
| 2026-11-07 | 16 | SFT forgetting: pretraining val code / English | loss before → after | 1.684→1.832 / 3.341→3.646 |
| 2026-11-07 | 18 | RM on SFT workhorse: CSN held-out / MBPP verified | pairwise acc | 0.826 / 0.852 (untrained 0.507 / 0.568) |
| 2026-11-07 | 18 | labels flipped 0 / 20 / 40% | MBPP acc | 0.852 / 0.766 / 0.716 |
| 2026-11-07 | 19 | DPO β 0.01/0.05/0.1/0.3/1.0: MBPP pair acc | fraction | 0.816 / 0.835 / 0.842 / 0.861 / 0.873 |
| 2026-11-07 | 19 | same: RM score of own samples (SFT 9.56) ; KL | score ; nats | 7.89/7.64/7.84/9.10/11.13 ; 0.173/0.185/0.160/0.071/0.020 |
| 2026-11-07 | 20 | GRPO on MBPP, SFT workhorse, 3 steps | rollouts passing | 0 / 576 |
| 2026-11-07 | 20 | easy tasks held-out pass@1, steps 0/15/30/45/60, outcome only | fraction | 0.133 / 0.140 / 0.247 / 0.307 / 0.380 |
| 2026-11-07 | 20 | same, outcome + format | fraction | 0.133 / 0.167 / 0.200 / 0.247 / 0.267 |
| 2026-11-07 | 20 | after GRPO (outcome only): HumanEval / MBPP pass@1 | fraction | 0.0244 / 0.002 (SFT 0.0122 / 0) |
| 2026-11-07 | 21 | 5.4M student, 6k steps: scratch / distilled from workhorse | val code | 2.518 / 2.438 (380 s / 1,126 s) |
| 2026-11-07 | 21 | workhorse quant: int8-ch / NF4-64 / int4-g32 / int4-g128 / int4-ch / int4-tensor / int3-g32 | Δ val code | +0.0004 / +0.016 / +0.020 / +0.035 / +0.059 / +2.39 / +0.13 |
| 2026-11-07 | 23 | serving ceiling, 1 / 4 / 16 / 32 slots | tokens/s | 295 / 782 / 1,189 / 1,304 |
| 2026-11-07 | 23 | bursty 10 req/s, static vs continuous | p50 / p99 / TTFT p50 (s) | 0.777 / 1.953 / 0.377 vs 0.272 / 1.563 / 0.008 |
| 2026-11-07 | 17 | SFT full / LoRA r1 / r4 / r16 / r64 / QLoRA r16 | completion val loss | 1.0328 / 1.0318 / 1.0278 / 1.0281 / 1.0328 / 1.0321 |
| 2026-11-07 | 17 | peak training MB, full vs LoRA r16 | MB | 4,615 vs 4,104 |
| 2026-11-14 | 11 | capstone 92M, 1.80B tokens, ~20.4 GPU-h | val code / English | 1.295 / 2.898 (max grad norm after warm-up 1.03) |
| 2026-11-13 | 11 | capstone resume after 5-day pause, steps 10,500 / 10,620 / 10,700 | train loss before vs after | 1.5527=1.5527 / 1.8381 vs 1.8383 / 1.5945=1.5945 |
| 2026-11-14 | 15 | capstone target, workhorse draft: greedy acceptance γ1 / γ4 / γ8 ; best speedup | fraction ; × | 0.972 / 0.891 / 0.791 ; 0.98 (draft costs 0.671 of target) |
| 2026-11-14 | 16 | capstone SFT: completion val loss before / step 250 / after | nats | 0.998 / 0.888 / 0.886 |
| 2026-11-14 | 16 | capstone forgetting, code / English | Δ nats | +0.159 / +0.311 |
| 2026-11-14 | 16 | capstone HumanEval: base as code vs SFT as chat | pass@1 | 0.0305 vs 0.0122 |
| 2026-11-14 | 18 | capstone RM: held-out CSN / MBPP verified | accuracy | 0.871 / 0.865 (workhorse 0.826 / 0.852) |
| 2026-11-14 | 19 | capstone DPO β=1: pair acc ; RM own samples ; KL | 0.563→0.895 ; 20.41→25.37 ; 0.027; pass@1 unchanged | |
| 2026-11-14 | 20 | capstone GRPO easy held-out, steps 0/15/30/45/60 | pass@1 | 0.273 / 0.380 / 0.420 / 0.533 / 0.733 |
| 2026-11-14 | 20 | capstone GRPO: HumanEval / MBPP | pass@1 | 0.0305 / 0.004 (SFT 0.0122 / 0.004) |
| 2026-11-14 | 21 | capstone quant: int8-ch / NF4-64 / int4-g128 / int4-ch / int4-tensor | Δ val code | +0.0000 / +0.0134 / +0.0254 / +0.0456 / +3.2174 |
| 2026-11-14 | 23 | capstone bursty: static vs continuous | tok/s ; TTFT p50 (s) | 707 vs 720 ; 0.440 vs 0.008 |
| 2026-11-14 | 22 | HumanEval greedy / pass@10: workhorse base, SFT, DPO, GRPO | fraction | 0/.012, .012/.024, 0/.006, .024/.018 |
| 2026-11-14 | 22 | HumanEval greedy / pass@10: capstone base, SFT, DPO, GRPO | fraction | .0305/.0549, .0122/.0488, .0122/.0183, .0305/.0488 |
| 2026-11-14 | 22 | 5M / 12M / 34M-MoE models, HumanEval and MBPP | pass@1 | 0 / 0 / 0 |
| 2026-11-14 | 22 | MC (352 items, 4 options): summed vs per-token, capstone base / DPO, workhorse base / DPO | accuracy | .716/.767, .767/.778, .594/.668, .653/.651 |
| 2026-11-14 | 22 | solved problems with any training 13-gram | count | 0 of 9 distinct |
Appendix C
Reproducing everything
Every number in this book comes from a command in the companion repository. This appendix lists those commands in the order they depend on each other, with what each one costs on the machine the book was written on: an RTX 4060 Laptop GPU (8 GB), Python 3.12, PyTorch 2.11 with CUDA 12.8.
The three longest runs take about 30 hours of GPU time between them: about 20 for the 92M capstone pretraining, about 7 for its post-training and evaluation chain, and 2 h 18 min for the 30M workhorse. The other experiments run from seconds to an hour or two each. The pretraining runs can be stopped and resumed by running the same command again.
C.1 What you need
| Resource | Amount | Where it goes |
|---|---|---|
| NVIDIA GPU | 8 GB or more, CUDA 12.8 driver | everything trains on it |
| Disk | about 25 GB | Python environment 7.1 GB, raw data 5.8 GB, tokenized data 5.0 GB, checkpoints 5.0 GB |
| Network | about 12 GB of downloads | the Python environment (~6 GB) and the datasets (~6 GB) |
| Tools | git, uv |
nothing else is installed by hand |
A smaller GPU runs the early chapters (stages 00-08 train models of 10M parameters or less). The 92M capstone needs the full 8 GB, with the memory tricks from chapter 11.
C.2 The environment
git clone https://github.com/karanjakhar/llm-from-scratch
cd llm-from-scratch
uv sync --extra dev # ~7 GB, mostly CUDA libraries
uv run python stages/00_setup/verify_env.py # GPU, memory, bf16, the 16-bytes-per-parameter check
uv run pytest -q # 295 tests, about 50 s
pyproject.toml and uv.lock pin every package, and point PyTorch at the
CUDA 12.8 wheel index so uv cannot quietly install a CPU-only build. Always
run code through uv run. During the project a separately managed Python
environment disappeared between sessions, and the project kept working only
because these two files define the environment (journal, 2026-10-25).
C.3 The data
Every dataset is downloaded from Hugging Face at a pinned revision, so you get the same bytes the book's numbers were made from.
uv run python stages/02_data/download.py # 12 codeparrot shards + 1 fineweb-edu file, ~4.9 GB
uv run python stages/02_data/download_extras.py # HumanEval, MBPP, CodeSearchNet, TinyStories, ~1 GB
uv run python stages/02_data/dedup.py # near-duplicate removal, ~2-3 min
uv run python stages/01_tokenizer/train_production.py # the production tokenizer, ~1 h
uv run python stages/02_data/prepare.py --tokenizer data/tokenizers/split_8192.json # ~5 min
uv run python stages/08_training/prepare_tinystories.py # the smoke-test data
What comes out:
| File | Contents |
|---|---|
data/tokenizers/split_8192.json |
8,192 learned tokens + 4 specials, digits split one per token |
data/bins/split_8192/train_code.bin |
1,330M tokens of permissive-licence Python, 521,423 files |
data/bins/split_8192/train_en.bin |
1,017M tokens of English, 720,855 documents |
data/bins/split_8192/val_*.bin |
4.9M code / 5.2M English tokens from held-out repositories |
data/bins/split_8192/manifest.json |
sources, revisions, counts: enough to rebuild the bins |
The tokenizer must be trained before prepare.py, and every checkpoint is
tied to it. Retraining it with a different setting silently invalidates every
model trained afterwards.
C.4 The stages, in order
Each stage has the same three files: <topic>.py (the implementation),
test_<topic>.py (its acceptance tests) and run.py (the experiments). Each
run.py lists its experiments, and what they cost, in its docstring. Numbers
go to results/NN_*/ as JSON, figures to docs/visuals/. The results/
files from the book's runs are committed, so you can compare yours against
them line by line.
Foundations (stages 01-08), each minutes to about an hour:
uv run python stages/01_tokenizer/run.py --vocab 8192
uv run python stages/02_data/run.py leakage
uv run python stages/03_embeddings/run.py ablation
uv run python stages/04_attention/run.py ablation && uv run python stages/04_attention/run.py maps
uv run python stages/05_block/run.py depth && uv run python stages/05_block/run.py sweep
uv run python stages/06_gpt/run.py oracle # downloads OpenAI GPT-2 and matches Hugging Face's outputs
uv run python stages/06_gpt/run.py tie # also saves the 4-layer model chapter 17 uses as a draft
uv run python stages/07_generation/run.py speed
uv run python stages/08_training/run.py tinystories # 10M smoke test, ~20 min
Efficiency and scaling (stages 09-10):
uv run python stages/09_efficiency/bench.py stack # 14.3k -> 73.7k tokens/s, one optimisation at a time
uv run python stages/10_scaling/run.py isoflop --budget 3e15
uv run python stages/10_scaling/run.py isoflop --budget 1e16
uv run python stages/10_scaling/run.py fit
The pretraining runs (stage 11):
uv run python stages/11_pretrain/run.py workhorse # 30M parameters, 590M tokens, 2 h 18 min
uv run python stages/11_pretrain/run.py capstone # 92M parameters, 1.80B tokens, ~20 h
Both resume from checkpoints/11_pretrain/<name>/ckpt.pt if stopped. Expect a
final validation code loss of 1.554 (workhorse) and 1.295 (capstone).
Architecture experiments (stages 12-15) train their own small models from the same data, except stage 15, which needs the stage 11 and stage 06 checkpoints:
uv run python stages/12_modern_arch/run.py ladder
uv run python stages/13_moe/run.py train
uv run python stages/14_attention_variants/run.py mla
uv run python stages/15_speculative/run.py sweep
Post-training on the workhorse (stages 16-21, 23). Each step reads the checkpoint the previous one wrote:
W=checkpoints/11_pretrain/workhorse/final.pt
uv run python stages/16_sft/run.py --base $W --tag workhorse
uv run python stages/17_lora/run.py --base $W --tag workhorse
uv run python stages/18_reward/run.py --sft checkpoints/16_sft/workhorse.pt --tag workhorse
uv run python stages/19_dpo/run.py --sft checkpoints/16_sft/workhorse.pt --tag workhorse --beta 0.1
uv run python stages/20_grpo/run.py --sft checkpoints/16_sft/workhorse.pt --tag workhorse
uv run python stages/21_distill_quant/run.py quant --model $W --tag workhorse
uv run python stages/23_serving/run.py bursty --model $W
The capstone chain (stages 16-24 on the 92M model), about 7 hours:
bash stages/24_capstone/run_post.sh # SFT, reward model, DPO, GRPO, quantize, serve, evaluate
It stops at the first failure, and runs with activation checkpointing because the 92M model does not fit SFT's batch otherwise (chapter 26).
Evaluation (stage 22) scores every checkpoint above with one harness:
uv run python stages/22_evaluation/run.py table --pass10
uv run python stages/22_evaluation/run.py contamination
uv run python stages/22_evaluation/run.py mc
A caution about evaluation. HumanEval, MBPP and GRPO's reward all run code
the model wrote. Each program runs in a separate Python process in a temporary
directory, with a time limit and a memory cap (llmfs/eval/execution.py).
That stops runaway loops and memory blow-ups. It is not a security sandbox: a
program could still read or delete files your user can. A 92M model is very
unlikely to write anything harmful, but if you change the prompts or use a
larger model, run evaluation inside a container or a throwaway VM.
C.5 What will differ on your machine
- Speed. Tokens per second, and so every wall-clock time above, depend on the GPU. The losses do not.
- The last digit. bf16 arithmetic and some CUDA kernels are not bit-for-bit deterministic. Expect losses within about 0.01 of the book's.
- Single problems. One HumanEval problem is 0.61 percentage points, and the same checkpoint scored 0 and 1 of 164 in two evaluations with the same settings (chapter 24). Differences of one or two problems are noise.
- Dataset revisions cannot drift: every download names its commit hash. If a dataset is removed from Hugging Face upstream, the hash will fail loudly rather than fetch something different.