Contents

The course

Start here

You will write, by hand, every part of a small GPT that writes Python: the tokenizer, attention, the transformer, the training loop, fine-tuning and evaluation. Each part is checked by the same tests the original project used, and each module ends with a number you can compare against the book.

How a module works

  1. Why: what this part solves, and what breaks without it.
  2. Read the marked sections of the book chapter.
  3. Implement: the module's functions have their bodies replaced by a hint and raise NotImplementedError. Write them.
  4. Check: uv run python course/check.py <module> runs the tests.
  5. Run the experiment and compare your number with the book's.
  6. Break it: remove what you built and measure the damage.
  7. Check yourself: a few questions, answers folded away.

Setup

On your own machine (NVIDIA GPU with 6 GB or more for the later modules; module 1 needs only a CPU):

git clone https://github.com/karanjakhar/llm-from-scratch-course
cd llm-from-scratch-course
uv sync --extra dev          # installs Python 3.12, PyTorch with CUDA, and the rest (~7 GB)
uv run python course/check.py 1

uv is the only thing you install by hand.

On Google Colab (free T4 GPU): open the module's notebook from course/colab/ and run its first cell. It mounts your Google Drive and keeps this repository there (MyDrive/llm-course), so your code and the data you build in module 2 survive when Colab resets the machine.

Module 0 · stage 00

Setup and the memory budget

You will build the arithmetic that decides what you can train: how many parameters a layer has, how many bytes training them costs, the largest model your GPU can hold, and a function that measures it on the real allocator.

Time: 1-2 hours. Hardware: any; the measurement needs a CUDA GPU (Colab's T4 works). Book chapter: 1, What a language model actually computes.


1. Why

Every later module runs into the same wall: GPU memory. A model that does not fit does not train, and the error arrives after the data is loaded and the first batch is half done. The rule that predicts it is simple enough to do in your head, and this module makes you prove it with the allocator before you trust it.

What breaks without it: forget that Adam keeps two extra numbers per weight and your estimate is half the real cost. On the book's GPU, that is the difference between "a 350M model fits" and "it does not".

2. Read

Chapter 1 of the book:

  • §1 What a language model actually is: the one idea everything else serves, predicting the next token.
  • §2 Where the VRAM goes, including the worked 50M example.
  • §3 PyTorch essentials: skim if you have used PyTorch; read carefully if not. Every later module uses these operations.

3. Implement

Open course/module00/budget.py. Four functions are blank:

# Function What it does
1 linear_params parameters in one nn.Linear
2 training_bytes weights + gradients + optimizer state, in bytes
3 max_params the largest model whose fixed cost fits, after a reserve
4 measure_training_bytes the same thing, read from the CUDA allocator

4. Check

uv run python course/check.py 0        # Colab: !python course/check.py 0

Five tests. They check your counts against PyTorch's own, the book's 192 MB toy model, the cost of three optimizers, the largest model on the book's 7,797 MB GPU, and (on a GPU) that your measurement agrees with your prediction to within 20%.

5. Run

uv run python stages/00_setup/verify_env.py

A few seconds. It trains one step of a 12-layer, 12.6M-parameter toy model in fp32 with AdamW and reads the allocator at each point. The book's run:

book (RTX 4060 Laptop)
predicted fixed cost 192.0 MB
measured total 208.3 MB (8.5% over)
weights 48.0 MB
gradients + activations 64.3 MB
AdamW state 96.0 MB
peak, including activations 256.3 MB

The weights and AdamW rows are pure arithmetic and should match exactly on any GPU. The gradient row is 48 MB of gradients plus a few MB of activations still held, so it can move slightly. The second table it prints, "what fits on this GPU", depends on your card: on a 16 GB T4 a 350M model's fixed cost is about a third of memory, on the book's 8 GB card about two thirds.

6. Break it

The script prints the broken estimate itself: "forgot AdamW?" predicts 96 MB for a run that really takes 208 MB. Then make it break for real: in a Python shell, build a model your max_params says is just too big for your GPU and call measure_training_bytes on it. Read the OutOfMemoryError message: it tells you how much was asked for and how much was free, which is the same arithmetic you just wrote.

7. Check yourself

1. Training a 50M-parameter model in fp32 with AdamW. What is the fixed memory cost, before activations?

50M × 16 bytes = 800 MB (about 763 MiB): 200 MB of weights, 200 MB of gradients, 400 MB of Adam state.

2. Why does the AdamW state not appear until after the first opt.step()?

PyTorch's Adam creates its two state tensors lazily, the first time it updates a parameter. Before that step the memory looks like plain SGD's.

3. The book's "8 GB" GPU reports 7,797 MB. Where did the rest go, and why reserve another 600 MB?

The card has 8,192 MiB, but about 390 MB is reserved before PyTorch sees any of it, so total_memory reports 7,797. Then the CUDA context, the kernels and the allocator's slack take several hundred MB more before your first tensor. Budget against what the runtime reports, not what the box says.

4. Your activations grow with which two numbers, and why does the 16-bytes rule ignore them?

Batch size and sequence length (and the model's width and depth). The rule counts what exists for every parameter regardless of the batch; activations are the part you control by changing the batch, which is why later modules use gradient accumulation and activation checkpointing.


Stuck? The solution is course/module00/budget.py in the main repository; the book's version of the same arithmetic is inline in stages/00_setup/verify_env.py.

Next: Module 1, the tokenizer: how text becomes the integers a model reads.

Module 1 · stage 01

Tokenizer

You will build the byte-pair encoding (BPE) tokenizer that every GPT uses: the training loop that learns which byte pairs to merge, the encoder that applies those merges to new text, the decoder, and the regex pre-tokenizer that keeps merges inside words.

Time: 3-5 hours. Hardware: CPU only; runs on Colab or any laptop. Book chapter: 3, Cutting text into tokens.


1. Why

A language model cannot read text. It reads lists of integers, and the tokenizer decides what those integers mean. Too small a vocabulary (single bytes) and every sentence becomes a long sequence the model must spend compute on; too large and the embedding table eats the parameter budget. BPE learns a vocabulary from data: start with the 256 bytes, then repeatedly glue the most common neighbouring pair into a new token.

What breaks without it: with raw bytes, a 1,024-token context window holds 1,024 characters. With the tokenizer you are about to write, it holds about 2,300 characters of Shakespeare. With this project's production tokenizer, about 3,400 characters of Python.

2. Read

Chapter 3 of the book, these sections before you start:

  • §2 Bytes as the foundation: why the base vocabulary is 256 bytes and there is no "unknown" token.
  • §3 BPE: the algorithm: the worked example by hand. Do it on paper too.
  • §3 Encoding new text: why merges are applied in the order they were learned.
  • §4 Regex pre-tokenization: what the regex split prevents.

Leave §9 (the production tokenizer) for after the module.

3. Implement

Open stages/01_tokenizer/bpe.py. Eight functions have their bodies replaced by a hint and raise NotImplementedError. Write them in this order; each one uses the ones before it.

# Function What it does
1 get_stats count every neighbouring pair of ids
2 merge replace one pair with a new id, without overlaps
3 BasicBPE._build_vocab turn the merge list into id → bytes
4 BasicBPE.train the BPE loop on the raw byte stream
5 BasicBPE._encode_chunk apply learned merges to new bytes
6 BasicBPE.decode ids → text
7 RegexBPE.train the same loop, inside regex chunks, counting each unique chunk once
8 RegexBPE.encode_ordinary split, encode each chunk, join

BasicBPE() calls _build_vocab when it is created, so almost every test fails until function 3 works. That is expected: get_stats and merge have their own tests that pass first.

4. Check

uv run python course/check.py 1        # Colab: !python course/check.py 1

It lists which of the eight are still blank, then runs the 58 tests this project wrote for its own tokenizer. Among them: a round trip on 1,000 random strings including emoji and invalid UTF-8; merges that never cross a word boundary; and your fast RegexBPE.train producing exactly the same merges as the slow version. The module is done when all of them pass.

5. Run

uv run python stages/01_tokenizer/run.py --vocab 1024

About 70 seconds. It downloads tinyshakespeare (1.1 MB), trains on the first 90% and measures compression on the last 10%. Compare section 1 of the output with the book's run:

vocab held-out bytes/token, book
256 1.000
512 1.878
1024 2.257

Training is deterministic, so a correct implementation matches these to within ±0.01. A different tie-break when two pairs have the same count can move the third decimal; anything larger is a bug. (Section 3 of the output measures a different slice of text, so its 2.275 is not the number to compare.)

Section 3 also times your encoder against OpenAI's tiktoken. The book's pure-Python encoder was 27-28× slower; yours will be similar. The chapter explains why that is an algorithm problem as much as a language one.

6. Break it

Section 2 of the same output is the ablation: the same corpus, vocabulary 2,048, trained with and without the regex split.

tokens that span a word boundary held-out bytes/token
BasicBPE (no regex) 778 of 1,792 2.788
RegexBPE 0 of 1,792 2.557

Without the split, almost half the learned vocabulary is fragments like 'e ', 'and ' and ' the '. Note that BasicBPE compresses held-out Shakespeare better. Read the chapter's §4 for why that is still the wrong tokenizer, then try one more break of your own: in _encode_chunk, apply merges longest-first instead of in learned order, and watch which tests fail.

7. Check yourself

1. Why does a byte-level BPE tokenizer never need an "unknown" token?

Every one of the 256 possible byte values has an id before training starts, so any text, in any language, can be encoded as bytes in the worst case.

2. Why apply merges in the order they were learned, not longest match first?

Learned order reproduces the exact sequence of states the training text went through, so new text is cut the same way the model saw during training. Longest-match produces different cuts for the same string.

3. In section 3 of your output, your vocabulary-1024 tokenizer gets about 2.28 bytes per token and GPT-2's gets 3.11 on the same text. Name two reasons for the gap.

GPT-2 has 50,257 tokens to your 1,024, so it can hold whole common words as single tokens; and it was trained on far more text. The cost is a 50k-row embedding table, which at 10-50M parameters would be bigger than the rest of the model.

4. Why does encode treat the string <|endoftext|> as ordinary text unless told otherwise?

If user text could produce control tokens, anyone could forge the end of a document or a chat turn by typing it. Control tokens should come only from code you wrote (chapter §5).

5. "strawberry" becomes ['st', 'ra', 'w', 'ber', 'ry']. What does this tell you about asking a model to count the r's?

The model never sees individual letters for this word, only five tokens, and no token is a single "r". Counting letters needs knowledge the tokenizer hid.


Stuck? The hint is in each function's docstring. The complete solution is stages/01_tokenizer/bpe.py in the main repository.

Next: Module 2, the data pipeline: where the Python comes from, how much of a test set leaks into training without anyone noticing, and how text becomes the token files a model trains on.

Module 2 · stage 02

Data

You will build the parts of a data pipeline that decide whether a model's numbers can be trusted: a train/validation split that keeps copies of the same code on one side, exact and near-duplicate removal, and the loader that feeds the GPU windows of tokens in a shuffled order. Then you build the training data every later module uses.

Time: 3-4 hours, plus the download (2.6 GB) and about 5 minutes of processing. Hardware: CPU; about 5 GB of disk. Book chapter: 4, The data is most of the model.


1. Why

A model is a compressed copy of its training data, and its validation score is only as honest as the split. Code is full of copies: forks, vendored libraries, files pasted between projects. Split it carelessly and the "unseen" test set is mostly seen.

What breaks without it: split by file, and 43.9% of the rare lines in the validation set (lines that occur in at most five files anywhere) also appear in training. Split by repository and it is still 34.4%, because forks live under other repositories' names. Only near-duplicate detection catches those. You will measure all of this yourself.

2. Read

Chapter 4 of the book:

  • §2 What is actually in the corpus: measured, not assumed.
  • §4 Deduplication: exact, then near-duplicate with MinHash.
  • §5 The train/val split: by repository, by hash, and the ablation.
  • §7 Packing: documents end to end, separated by <|endoftext|>.
  • §10 Sampling windows from the stream: why random offsets leave 37% of the data unseen after one epoch.

3. Implement

Six blanks, in the stage's script and the library it uses:

# Function File What it does
1 split_of llmfs/data/corpus.py train or validation, from a stable hash of the repository name
2 Deduper.__call__ stages/02_data/prepare.py drop byte-identical documents
3 signature llmfs/data/dedup.py MinHash: a 120-number fingerprint of a file's 5-word phrases
4 estimated_jaccard llmfs/data/dedup.py how similar two fingerprints say two files are
5 ShuffledSampler.next llmfs/data/loader.py the next window, each visited once per epoch
6 MixedLoader.next_batch llmfs/data/loader.py a batch mixing code and English, shifted into inputs and targets

Every later module trains through your sampler and loader.

4. Check

uv run python course/check.py 2

34 tests. The split must not depend on Python's per-process hash seed; no repository may land on both sides; the deduplicator must drop the validation copy of a training file, never the reverse; MinHash's estimate must track the true similarity; the shuffled sampler must visit every window exactly once per epoch, and a resumed loader must continue exactly where it stopped.

5. Run

Download two of the twelve code shards the book used, and the English file (about 2.6 GB):

uv run python stages/02_data/download.py --code-shards 2

Then measure leakage before removing anything:

uv run python stages/02_data/run.py leakage --shards 2

About 25 seconds. The book ran exactly this, on exactly these two shards, so your numbers should match to the digit:

split rare validation lines also in train validation files more than half leaked
by file 43.9% 48.6%
by repository 34.4% 43.3%

6. Break it, then fix it

The table above is the broken version: no near-duplicate removal. Now run the fix and measure again:

uv run python stages/02_data/dedup.py
uv run python stages/02_data/run.py leakage --shards 2 --drop data/dedup/near_dups.json

Deduplication took 69 seconds on two CPU cores while this course was being written. On two shards it found and removed 16.7% of training files and 29.2% of validation files, 156 of the 158 dropped validation files having a near copy in training. Leakage after it:

split rare lines leaked, before → after files >50% leaked, before → after
by file 43.9% → 23.3% 48.6% → 29.2%
by repository 34.4% → 17.2% 43.3% → 20.1%

The book ran deduplication over all twelve shards (it can only find a copy whose original is in the data), removed 28.2% of training files, and got repository-split leakage down to 8.1% and 13.8%. More data, more copies found.

Finally, build the token files every later module trains on:

uv run python stages/02_data/prepare.py --tokenizer data/tokenizers/split_8192.json --limit-docs 100000

--limit-docs 100000 caps each source at 100,000 documents, which keeps English to about the 15% share the book used without tokenizing the whole 2 GB file. While writing this course it took 174 seconds on two CPU cores and produced 275M tokens of training code from 98,598 files, 142M tokens of English, and about 810 MB of files. That is about a fifth of the book's 1,330M tokens of code, enough for every core module. The validation code is smaller too: 1.0M tokens from 383 files, against the book's 4.9M, so your validation losses will move more from run to run than the book's did.

7. Check yourself

1. Why split by a hash of the repository name rather than by a random draw?

A hash gives the same answer on every run and every machine, whatever order the files arrive in and however many shards are added later. A random draw would put a repository on a different side each time the data is rebuilt.

2. Why not use Python's built-in hash() for it?

It is salted per process (PYTHONHASHSEED): the same string hashes differently in every run, so the split would change every time. One of the tests runs it under two different seeds to catch exactly this.

3. Splitting by repository already keeps a repository's files together. What does near-duplicate removal catch that the split cannot?

Copies of the same code under different repository names: forks, vendored libraries, files pasted between projects. The split sees two repositories; MinHash sees one file.

4. Drawing random window offsets leaves about 37% of the data unseen after one epoch's worth of draws. Where does 37% come from?

Each draw misses a given window with probability 1 − 1/N; after N draws the chance it was never picked is (1 − 1/N)^N ≈ 1/e ≈ 0.37. A shuffled order of non-overlapping windows visits every one exactly once per epoch instead.


Stuck? Solutions: llmfs/data/ and stages/02_data/prepare.py.

Next: Module 3, embeddings and position: the first layer of the model.

Module 3 · stage 03

Embeddings and position

You will build the token embedding table, the three ways of telling a model where each token sits (learned positions, sinusoidal positions and RoPE), and the two layouts of RoPE that real model weights use.

Time: 3-4 hours, plus about 6 minutes of training on the book's GPU. Hardware: GPU. Book chapter: 5, Turning ids into vectors and position.


1. Why

The tokenizer hands the model integers. An integer has no meaning a network can compute with, so each id looks up its own row of learned numbers: its embedding. That is half the job. The other half is order: attention, which you build in module 4, treats its input as a set. Without position information, "a = b" and "b = a" look identical to it.

What breaks without it: the book trained the same small model five ways. With no position information at all, held-out code loss was 3.36; with RoPE, 2.52. Add sinusoidal positions without scaling the token embeddings and it is worse than having no positions: 4.71, because the position signal is 35 times the size of the token signal and drowns it.

2. Read

Chapter 5 of the book:

  • §1 From ids to vectors: the lookup, and why it is a matrix product with a one-hot vector.
  • §3 Why position is needed at all.
  • §4-§6: learned, sinusoidal and RoPE. The RoPE section has a worked example with small numbers; do it by hand.
  • §6 Two layouts, one idea (a trap): why the same rotation can be stored two ways, and why loading weights with the wrong one fails silently.

3. Implement

Open stages/03_embeddings/embeddings.py. Seven blanks:

# Function What it does
1 TokenEmbedding.forward id → its row
2 LearnedPosition.forward the first T rows of a position table, with a hard wall
3 frequencies the speed of each sin/cos "clock"
4 sinusoidal_table the 2017 transformer's fixed positions
5 rope_angles position × speed, for RoPE
6 rope_interleaved rotate pairs (0,1), (2,3), … (Meta's layout)
7 rope_half rotate pairs (i, i + d/2) (Hugging Face's layout)

rope_complex is left complete: it is the same rotation written with complex numbers, and a test checks your rope_interleaved equals it exactly.

4. Check

uv run python course/check.py 3

22 tests. Among them: your lookup equals nn.Embedding and the one-hot product; only the rows of tokens in the batch receive a gradient; attention without position cannot see order (shuffle the input and the output is shuffled the same way, nothing else changes); with RoPE the attention score between two tokens depends only on how far apart they are; your rope_half matches Hugging Face's Llama implementation.

5. Run

uv run python stages/03_embeddings/run.py ablation --variants none learned sinusoidal sinusoidal_scaled rope

Five small models (4 layers, 256 wide), 2,000 steps each, identical except for position. About 75 seconds per model on the book's GPU. The book's numbers (seed 0, on the full 12-shard data):

position scheme held-out code loss, book
none 3.363
learned (GPT-2) 2.685
sinusoidal, unscaled 4.708
sinusoidal, tokens scaled by √C 2.633
RoPE 2.523

Your data is the two-shard subset from module 2, with its own validation set, so your losses will not equal these. On the two-shard data, run while writing this course, none scored 3.777 and rope 2.905: both about 0.4 above the book, because the validation set is a different slice of code, but the gap between them was 0.87 against the book's 0.84. The ranking is what to compare: RoPE best, unscaled sinusoidal worst, no position far behind the rest. Your run overwrites results/03_embeddings/ablation.json; git diff results/03_embeddings/ shows your numbers beside the book's.

6. Break it

The ablation above is the break: the none row is this module's component removed. Two more to try:

  1. Train with --variants rope_untied. The output layer gets its own table instead of sharing the embedding (2.10M more parameters). The book: worse, 2.606 against 2.523. Chapter §2 explains why sharing helps a small model.
  2. In rope_half, swap the signs (a*cos + b*sin, -a*sin + b*cos) and run the tests. One rotation direction is as good as the other for training, so which test fails, and why?

7. Check yourself

1. An embedding lookup is a matrix product with a one-hot vector. Why does that mean only some rows get a gradient each step?

The one-hot vector is zero everywhere except the token's own position, so the gradient with respect to every other row is zero. Rows of tokens absent from the batch do not move.

2. Learned positions have a hard wall at max_len. What happens to sinusoidal positions past the training length, and to RoPE?

Sinusoidal and RoPE can compute any position, so there is no wall. But the model never saw those angles in training: the book measured loss on positions 256-511 after training at 256 and every scheme got worse there (chapter §8). "Can compute" is not "has learned".

3. With RoPE, why does the score between query position m and key position n depend only on m − n?

Rotating q by angle mθ and k by nθ, their dot product equals the dot product of the unrotated vectors with a rotation of (m − n)θ between them. The absolute positions cancel.

4. Why did unscaled sinusoidal positions do worse than no positions at all?

The token embeddings start with standard deviation 0.02; the sinusoidal values are between −1 and 1. Added together, position is about 35 times larger than token identity, so the model starts out barely able to see which token is which. Scaling the tokens by √C fixes it (2.633).


Stuck? Solution: stages/03_embeddings/embeddings.py.

Next: Module 4, attention: how each token reads the others.

Module 4 · stage 04

Attention

You will build scaled dot-product attention, the causal mask that stops a token reading the future, and multi-head attention with the reshape that most attention bugs hide in.

Time: 3-4 hours. Hardware: any for the tests and the first experiment; GPU for the training one. Book chapter: 6, Attention, from one head up.


1. Why

Attention is how a token gathers information from the tokens before it. Each token asks a question (its query), every earlier token offers a label (its key) and a payload (its value), and the answer is a weighted average of payloads, weighted by how well each label matches the question. It is a dictionary lookup that is allowed to be fuzzy.

What breaks without the details: drop the division by √d and, with a 256-wide head, the book's model collapsed onto about 2.5 tokens per lookup and its loss rose from 2.70 to 3.64, a bigger loss than removing position information entirely. Get the head reshape wrong and the output has the right shape and the wrong contents; no error is raised.

2. Read

Chapter 6 of the book:

  • §1 The idea, with the worked example in small numbers.
  • §2 The formula and §3 Why divide by √d.
  • §4 The causal mask: why −∞ and not 0.
  • §5 Many heads instead of one: the reshape, drawn.

3. Implement

Open stages/04_attention/attention.py. Three blanks:

# Function What it does
1 causal_mask which keys each query may see
2 attention softmax(q kᵀ / √d) v, with the mask
3 MultiHeadAttention.forward split into heads, attend, merge back

4. Check

uv run python course/check.py 4

12 tests. Your attention must equal PyTorch's fused F.scaled_dot_product_attention in outputs and gradients, your multi-head layer must equal nn.MultiheadAttention with the same weights, and changing a future token must leave every earlier output unchanged. One test builds the wrong reshape on purpose and checks it gives the right shape and the wrong answer, so you can see the trap.

5. Run

uv run python stages/04_attention/run.py variance

About 10 seconds; no training, no data. Random queries and keys with head size d from 16 to 1,024, with and without the √d. The book's numbers:

d score std, scaled / unscaled top weight, unscaled queries with ~no gradient, unscaled
16 1.00 / 4.00 0.494 0%
64 1.00 / 7.98 0.740 2%
256 1.00 / 16.03 0.881 14%
1024 1.00 / 32.04 0.940 41%

These are from random numbers with a fixed seed, so they should match to the digits shown. Without the √d, the scores grow like √d, softmax piles almost all the weight on one key, and at d = 1,024 two in five queries get no gradient to learn from.

6. Break it

Train it, on your data:

uv run python stages/04_attention/run.py ablation --variants d256 d256_noscale --seeds 0

One head of size 256, with and without √d, 4,000 steps each, about 140 seconds per model on the book's GPU.

run held-out code loss, book (seed 0)
d256, scaled 2.702
d256_noscale 3.637

On the two-shard data, run while writing this course: 2.716 and 3.659, within 0.02 of the book's. Then run run.py ablation --variants d64 d64_noscale --seeds 0. The book found that with small heads, dropping √d helped slightly (2.655 against 2.686). Chapter §9c explains why, and it is the most surprising result in the chapter.

7. Check yourself

1. Why is the mask applied with −∞ rather than by setting the future scores to 0?

Softmax exponentiates. e^0 = 1, so a zero score still gets weight; e^−∞ = 0 exactly, so the future gets none and the remaining weights still sum to 1.

2. Dot products of two random d-dimensional vectors with unit-variance entries have what standard deviation, and what does dividing by √d do to it?

√d: the dot product sums d independent products of variance 1. Dividing by √d brings it back to 1 for every head size, which is the "scaled std 1.00" column above.

3. 41% of queries got no gradient at the scores at d = 1,024, yet the gradient reaching the query was larger unscaled (63 against 3.1). How?

The gradient at q is the score gradient multiplied by k. Unscaled, k enters at full size instead of divided by √d, and that factor outweighs the collapse for the queries that are not saturated. The gradient is not vanishing; it is concentrated on a few queries while the rest learn nothing (chapter §9a).

4. A wrong reshape view(B, H, T, d) instead of view(B, T, H, d).transpose(1, 2) gives the right shape. What does it compute?

It cuts the flat memory in the wrong order, so a "head" mixes pieces of different tokens. Every shape check passes; only a numerical comparison with a reference catches it.


Stuck? Solution: stages/04_attention/attention.py.

Next: Module 5, the transformer block: attention plus an MLP, normalised and stacked with a residual connection.

Module 5 · stage 05

The transformer block

You will build the pieces a transformer block is made of: LayerNorm and RMSNorm, the GELU and SiLU activations, the classic MLP and Llama's SwiGLU. The block itself, with every design choice as a switch, is provided, so you can turn each piece off and measure what it was doing.

Time: 3 hours, plus about 10 minutes of training on the book's GPU. Hardware: GPU. Book chapter: 7, The transformer block.


1. Why

A block is attention (tokens exchange information) followed by an MLP (each token processes what it gathered on its own), each wrapped in a normalisation and a residual connection. Stack a few dozen and you have a GPT. The wrapping matters as much as the contents: it is what lets the signal and the gradient survive 24 or 96 layers.

What breaks without it: remove the residual connection and the book's 24-layer model learned nothing. Its loss stayed at 6.856, the loss of a model that only knows how often each token appears (6.860). By layer 12 every position held the same vector: cosine similarity 1.000.

2. Read

Chapter 7 of the book:

  • §1 The picture.
  • §2 The residual connection: why the gradient needs a road.
  • §3 Normalisation: LayerNorm, then RMSNorm.
  • §4 Pre-norm vs post-norm.
  • §5-§6 The MLP and Activation functions.

3. Implement

Open stages/05_block/block.py. Seven blanks:

# Function What it does
1 LayerNorm.forward per token: mean 0, variance 1, then scale and shift
2 RMSNorm.forward per token: divide by the root mean square, then scale
3 gelu_tanh GPT-2's GELU
4 gelu_exact GELU through erf
5 silu x · sigmoid(x)
6 MLP.forward C → 4C → C
7 SwiGLU.forward Llama's gated MLP

Read Block below them before you start: _sublayer is the whole difference between pre-norm and post-norm, in four lines.

4. Check

uv run python course/check.py 5

23 tests. Your norms must match nn.LayerNorm, nn.RMSNorm and Hugging Face's LlamaRMSNorm in outputs and gradients; your SwiGLU must match LlamaMLP; the whole block must match Hugging Face's GPT2Block with the same weights. One test shows that a LayerNorm using x.var() (which divides by C − 1) is wrong by a small amount that only a reference comparison catches.

5. Run

uv run python stages/05_block/run.py grads --B 8

About 6 seconds. --B 8 matters: it is the batch the book used, and the default of 32 runs out of memory on an 8 GB GPU in full fp32 at 24 layers. No training: it builds untrained 24-layer stacks three ways (pre-norm, post-norm, no residual) and measures the gradient at the first and last block and how alike the token vectors become. The book's numbers:

grad norm, block 1 / block 24 cosine between positions after block 24
pre-norm 2.21 / 0.38 0.69
post-norm 1.32 / 0.12 0.03
no residual 3.65 / 2.63 1.000

A rerun while writing this course gave 2.27 / 0.385, 1.28 / 0.123 and 3.7 / 2.7, with cosines 0.697, 0.036 and 1.000. Without the residual, the gradient is fine; it is the signal that dies: every position ends up holding the same vector, so there is nothing left to learn from. The chapter's §10a calls this the surprise of the stage: the book expected vanishing gradients and found merging tokens instead.

6. Break it

Train it:

uv run python stages/05_block/run.py depth --variants pre_L4 nores_L4
run held-out code loss, book
pre_L4 (4 pre-norm blocks) 2.685
nores_L4 (no residual) 6.856

On the two-shard data, run while writing this course: 2.698 and 6.852, about 4 minutes per model on the book's GPU. 6.86 is the frequency floor: the model learned how common each token is and nothing else. If you have time, add post_L4: post-norm also sat at 6.856 in the book, and chapter §10b is a detective story about why (the answer turned out to be the size of the embeddings, not post-norm itself).

7. Check yourself

1. LayerNorm normalises over which dimension, and why not over the batch?

Over the C features of each token separately. Normalising over the batch (BatchNorm) would make a token's output depend on the other sequences in the batch, and behave differently with batch size 1 at inference.

2. RMSNorm skips the mean subtraction and the bias. What does that buy, and what did the book measure for it?

Fewer operations and parameters. In the book's 4-layer sweep it scored 2.712 ± 0.027 against LayerNorm's 2.689 ± 0.012, a tie within noise; its speed advantage disappears once the norm is a fused kernel (chapter §10e).

3. In pre-norm, x = x + f(norm(x)). Why does that keep a 24-layer stack trainable at initialisation?

The x term passes straight through every block, so the gradient has a path from the loss to the first layer that does not go through any f. Each block only adds an edit to the stream instead of replacing it.

4. SwiGLU has three weight matrices, the GELU MLP two. How does Llama keep the parameter count the same?

It shrinks the hidden width from 4C to 8C/3: three matrices of C × 8C/3 cost what two of C × 4C cost.


Stuck? Solution: stages/05_block/block.py.

Next: Module 6, GPT: stack the blocks, add an output layer, and load OpenAI's real GPT-2 weights into your model.

Module 6 · stage 06

GPT

You will build the whole GPT-2 model from your parts, its parameter count by hand, its initialisation, and a loader that copies OpenAI's released GPT-2 weights into it. Then you prove your model is GPT-2 by matching Hugging Face's implementation number for number.

Time: 3-4 hours. Hardware: GPU recommended (the comparison downloads GPT-2, 550 MB). Book chapter: 8, Assembling GPT.


1. Why

Everything so far was a part. This module puts them together: embeddings, a stack of blocks, a final norm and an output layer that scores every token in the vocabulary. The test of whether you understood the parts is unforgiving: OpenAI's 124M-parameter GPT-2 weights must load into your model and produce the same outputs as the reference implementation.

What breaks without the key idea: train without shifting the targets by one position and the model learns to copy its input. The book's run reached a training loss of 0.0001 and a next-token validation loss of 21.86, against 4.09 for the same model trained correctly. A perfect score on the wrong task.

2. Read

Chapter 8 of the book:

  • §1 The picture and §2 The shift.
  • §3 Counting parameters by hand: GPT-2 small is 124,439,808, and you will get there with arithmetic.
  • §4 Initialisation, including why the residual-writing layers start smaller.
  • §5 Names, so real weights fit: the three traps in GPT-2's checkpoint.

3. Implement

Open stages/06_gpt/gpt.py. Six blanks:

# Function What it does
1 CausalSelfAttention.forward module 4's attention, under GPT-2's names
2 Block.forward pre-norm: attention, then MLP, each added to the stream
3 GPT._scale_residual_init shrink the layers that write to the stream
4 GPT.forward ids → logits, and the loss if targets are given
5 load_gpt2_state copy OpenAI's tensors in, refusing anything that does not fit
6 count_params_by_hand the parameter count, from the config alone

This file imports your attention from module 4 and your LayerNorm and GELU from module 5.

4. Check

uv run python course/check.py 6

20 tests. Your hand count must equal PyTorch's for several shapes and give 124,439,808 for GPT-2 small; an untrained model's loss must start at ln V; the tied output layer must be the same tensor as the embedding; your loader must fail loudly on a missing or extra tensor; and, the big one, GPT-2 loaded into your model must match Hugging Face's GPT2LMHeadModel.

5. Run

uv run python stages/06_gpt/run.py oracle

About 45 seconds. It loads GPT-2 into your model and into Hugging Face's, runs both on 200 validation windows and reports the largest difference in any output score, then GPT-2's compression of our code and English (bits per byte: lower is better).

book
largest logit difference, fp32 (code) 0.055
GPT-2 bits per byte, code / English 1.394 / 1.064

On the two-shard data, run while writing this course: 0.048, and 1.318 / 1.057 bits per byte. The difference is not zero and not the book's to the digit, because the 200 windows come from your validation set; what must hold is that it stays around 0.05 rather than 1 or 10. A difference of 0.055 sounds like a bug and is not: GPT-2's residual stream reaches values near 3,000, and float32 keeps about 7 significant digits, so 0.055 is rounding. In float64 the book measured 2 × 10⁻¹¹. Chapter §6 walks through that check; it is a good habit to copy.

6. Break it

uv run python stages/06_gpt/run.py noshift

About 2.5 minutes: the 4-layer model trained with targets equal to inputs instead of shifted by one, and the same model trained correctly for comparison.

book
training loss after 1,000 steps (copy task) 0.0001
validation loss on real next-token prediction 21.86
the same model trained with the shift 4.09

On the two-shard data, run while writing this course: 0.0006, 21.41 and 4.13. It also prints what the model writes after def add(a, b):. Compare the two samples.

7. Check yourself

1. GPT-2 small has 124,439,808 parameters. Roughly what share is the token embedding, and why does that matter for a small model?

50,257 × 768 = 38.6M, about 31%. In a small model the vocabulary table is a large fraction of the budget, which is why this project uses an 8,192-token vocabulary and ties the output layer to the embedding.

2. Why does an untrained model's loss start at ln V, and what does it tell you if yours starts at 30?

Small initial weights make every logit near zero, so the predicted distribution is uniform over V tokens, and the cross-entropy of a uniform guess is ln V (9.01 for V = 8,196). A much larger starting loss means the initial outputs are far from uniform: an initialisation bug.

3. GPT-2's checkpoint stores some weights transposed. Why, and why would loading them untransposed not raise an error for every layer?

OpenAI used a Conv1D layer that stores (in, out), where nn.Linear stores (out, in). For square matrices (C × C) the shapes match either way, so only a numerical comparison catches it; for the 3C and 4C layers the shape check does.

4. The residual-writing layers start with std 0.02 / √(2L). What would happen at 48 layers without that?

2L layers each add a random edit to the stream, so its size grows with depth. The book measured the stream's size after the last block at initialisation: 0.93 at 48 layers with plain init, 0.09 with the scaled init.


Stuck? Solution: stages/06_gpt/gpt.py.

Next: Module 7, making it talk: sampling and the KV cache.

Module 7 · stage 07

Generation

You will build the sampling knobs every chat interface exposes (temperature, top-k, top-p, a repetition penalty), the function that picks the next token, and generation with a KV cache: the trick that stops a model from recomputing its whole past for every new token.

Time: 2-3 hours. Hardware: GPU. Book chapter: 9, Making it talk.


1. Why

A trained model gives a score to every token in the vocabulary for the next position. Turning that into text means choosing one, appending it and asking again, hundreds of times. How you choose decides whether the output is repetitive, sensible or random. How you avoid recomputing decides whether it takes a second or half a minute.

What breaks without the cache: generating 1,008 tokens from a 92M model took the book's GPU 23.7 seconds the simple way and 3.2 seconds with the cache, with exactly the same tokens out.

2. Read

Chapter 9 of the book:

  • §1 The loop and §2 Greedy.
  • §3 Sampling, and temperature and §4 Top-k and top-p.
  • §6 The KV cache, all of it, including §6e: the cached and uncached outputs must be identical, and how to test that.

3. Implement

Open stages/07_generation/sample.py. Six blanks:

# Function What it does
1 apply_temperature sharpen or flatten the distribution
2 top_k_filter keep only the k best tokens
3 top_p_filter keep the smallest set whose probability reaches p
4 apply_repetition_penalty push down tokens already used
5 sample_next all of the above, then draw one token
6 generate_cached prefill the prompt once, then one token per step

generate_naive, the version without a cache, is left complete above generate_cached. Read it first: yours must produce identical tokens.

4. Check

uv run python course/check.py 7

16 tests, including: a single token holding 95% of the probability survives top-p at 0.9; the repetition penalty lowers both positive and negative logits; cached and uncached logits agree; greedy and seeded-sampled outputs are identical with and without the cache; generation stops at <|endoftext|>.

5. Run

uv run python stages/07_generation/run.py speed

About 70 seconds; random untrained models, because speed does not depend on what a model knows. Three sizes, generating up to 1,024 tokens, with and without the cache. The book's speedups:

model speedup at 512 tokens at 1,024 tokens
5M (4 layers, 256 wide) 1.27× 2.28×
30M (8 layers, 512 wide) 3.32× 5.51×
92M (12 layers, 768 wide) 4.47× 7.23×

A rerun on the book's GPU while writing this course gave 1.26 / 2.15, 3.37 / 5.53 and 4.50 / 7.38, so expect a few percent of run-to-run timing noise, and different absolute speeds on a different GPU. Every row must also say identical_greedy: True and identical_sampled: True; if one says False, your cache has a bug the tests missed.

Look at the smallest model's shortest runs: the cache made it slightly slower (0.94× at 128 tokens). Chapter §8a explains why a tiny model gains little: the GPU is waiting on launch overhead, not on arithmetic.

6. Break it

In generate_cached, after the prefill, feed the model the whole sequence out each step instead of only the new token nxt (keep passing the cache). Run the tests. When the course was written, two failed (test_greedy_naive_equals_cached and the sampled version) with RuntimeError: The expanded size of the tensor (0) must match the existing size (11): every step writes the whole sequence into the cache again, so it fills up after a few steps and the next write has no room. Before it fills, the model sees each earlier token several times at the wrong positions. Then put it back.

7. Check yourself

1. Temperature 0 is handled as a special case. What would dividing the logits by 0 do, and what does temperature → 0 approach?

Division by zero gives infinities and NaNs after softmax. As temperature falls toward 0 the distribution concentrates on the highest logit, so the limit is greedy decoding (argmax), which is what the special case does.

2. Top-p at p = 0.9, and one token has probability 0.95. Why must it survive, and which comparison makes sure it does?

Removing it would leave nothing. The filter drops a token only when the tokens ranked above it already reach p; for the top token that sum is 0, so it always stays.

3. What exactly does the KV cache store, and why do queries not need caching?

The keys and values of every earlier position, for every layer. A new token only needs its own query, compared against all keys; earlier queries are never used again.

4. The cache memory grows with what? Work it out for the 92M model at 1,024 tokens in fp32.

2 (K and V) × layers × positions × width × 4 bytes = 2 × 12 × 1,024 × 768 × 4 = 75.5 MB, which is the cache_bytes_theory the script prints.


Stuck? Solution: stages/07_generation/sample.py.

Next: Module 8, the training loop: AdamW, the learning-rate schedule and gradient clipping, by hand.

Module 8 · stage 08

Training loop

You will build the optimizers (SGD, momentum, and AdamW with decoupled weight decay), the warmup-then-cosine learning-rate schedule, and gradient clipping, then train a 10M-parameter model on children's stories to prove the loop works.

Time: 3 hours, plus about 20 minutes of training on the book's GPU. Hardware: GPU. Book chapter: 10, The training loop.


1. Why

The model is a function with millions of knobs. Training is turning them, a little at a time, in whatever direction lowers the loss on the next batch. The direction comes from the gradient; how far to turn each knob is the optimizer's job, and it is where most training failures start.

What breaks without the details: on the same small model and data, the book's plain SGD reached a loss of 5.62 in 1,500 steps, Adam 3.61, and Adam with the old way of doing weight decay (folded into the loss) 6.70, barely better than a model that only knows how often each token appears (6.86). Same gradients each time; only the update rule changed.

2. Read

Chapter 10 of the book:

  • §1 The loop in one picture.
  • §2 From SGD to Adam, a-d. AdamW's "decoupled" weight decay is the subtle part.
  • §4 The learning-rate schedule and §5 Gradient clipping.
  • §7 Sanity checks before trusting a run, especially overfitting one batch.

3. Implement

Open stages/08_training/optim.py. Four blanks:

# Function What it does
1 SGD.step step downhill, with optional momentum
2 AdamW.step a per-weight step size, bias correction, decoupled decay
3 lr_schedule linear warmup, then cosine down to 10%
4 clip_grad_norm cap the length of the whole gradient, keep its direction

4. Check

uv run python course/check.py 8

10 tests. Your AdamW must track torch.optim.AdamW over 25 steps (the book measured a largest difference of 2.3 × 10⁻⁴ in float32 and 4.2 × 10⁻¹³ in float64: the float32 gap is rounding, as the float64 run proves); its first step must move every weight by exactly the learning rate; L2-in-the-loss must differ from decoupled decay; your clipping must match PyTorch's; gradient accumulation over 4 micro-batches must equal one batch 4 times larger; and a model must be able to overfit a single batch.

5. Run

Your optimizers, racing on the same model and data:

uv run python stages/08_training/run.py optimizers

A 4-layer model trained for 1,500 steps five times, once per update rule, all using your SGD, AdamW and lr_schedule. About 7.5 minutes on the book's GPU.

update rule held-out code loss, book
SGD 5.615
SGD + momentum 4.310
Adam 3.609
AdamW (decoupled decay) 3.614
Adam + L2 decay in the loss 6.695

On the two-shard data, run while writing this course: 5.653, 4.408, 3.731, 3.738 and 6.691: each 0.04-0.12 above the book except the L2 run, and the same order. Same gradients every time; only the update changed.

From here on, the course trains with the library's loop (llmfs/train/trainer.py), which uses PyTorch's fused AdamW: the algorithm you just wrote and matched, made fast. Two checks of that loop:

uv run python stages/08_training/run.py overfit

About 10 seconds: one batch of 8 × 256 tokens, trained until memorised. The book's model went below a loss of 1 at step 72, below 0.1 at 96 and below 0.01 at 129, and a rerun while writing this course gave the same three numbers. The batch comes from your data, so the counts depend on which 2,048 tokens it holds: on the two-shard data it took 53, 74 and 111 steps. Any loop that works gets below 0.01 within a few hundred steps. A loop that cannot memorise 2,048 tokens cannot learn from 49 million: never skip this check.

Then the smoke test. It needs the TinyStories data (once):

uv run python stages/02_data/download_extras.py      # if you have not already
uv run python stages/08_training/prepare_tinystories.py
uv run python stages/08_training/run.py tinystories

A 10.1M-parameter model trained on 49M tokens of children's stories. The book took 11.5 minutes and reached a validation loss of 1.510. A rerun while writing this course: 1.5104 in 10.9 minutes. Read the samples it prints at each checkpoint: at the start they are noise, then words, then sentences. TinyStories is used here because a broken loop shows in the samples within minutes; it is a test, not a goal.

6. Break it

uv run python stages/08_training/run.py ablate

The same 6-layer model at a high learning rate (3 × 10⁻³), with and without warmup and clipping:

run held-out code loss, book
warmup + clipping 2.946
no clipping 3.028
no warmup 4.781
neither 5.057

The book expected a loss spike without warmup and got something else: the loss fell to 7.0 within 10 steps and then sat there, at the level of a model that only knows token frequencies, for about 40 steps. Chapter §8d has the plot. At the default learning rate (10⁻³) both safety rails looked unnecessary; they only show their value when they carry load.

7. Check yourself

1. Adam's first step moves every weight by almost exactly the learning rate, whatever its gradient. Why?

After bias correction, the first update is m̂ / √v̂ = g / |g| = ±1 per weight (plus a tiny ε), so the step is lr in the sign of the gradient. Large and small gradients move the same distance.

2. Why is "weight decay in the loss" (L2) different from AdamW's decoupled decay?

In the loss, the decay term joins the gradient and is then divided by √v like everything else, so weights with large gradients are barely decayed. Decoupled decay shrinks every weight by the same fraction, outside Adam's per-weight scaling.

3. Gradient clipping rescales the whole gradient, not each element. What does that preserve?

The direction. Every element is multiplied by the same factor, so the step points the same way, just shorter.

4. With gradient accumulation over 4 micro-batches, why must each loss be divided by 4?

Gradients add up across backward passes. Without the division the accumulated gradient is 4 times the big-batch gradient, which is the same as training at 4 times the learning rate. One of the tests checks exactly this.


Stuck? Solution: stages/08_training/optim.py.

Next: Module 9, pretraining: the checkpoint that makes a long run survive a crash, and your own base model.

Module 9 · stage 11

Pretraining

You will build the checkpoint that lets a long training run survive a crash and continue as if nothing happened, prove it bit-for-bit, and then train (or download) the 30M-parameter base model the rest of the course fine-tunes and evaluates.

Time: 1-2 hours of work. The base model itself is 2 h 18 min of GPU on the book's machine, or a download. Hardware: GPU. Book chapter: 13, The real pretraining run.


1. Why

Everything up to now trained in minutes. A real pretraining run takes hours or days, and something always interrupts it: a crash, a power cut, a Colab session ending. A run that cannot resume exactly is a run you cannot finish. The book's 92M model trained for about 20 hours, was paused for five days in the middle, and resumed with its next losses within 0.0002 of the values logged before the pause.

What breaks without it: forget Adam's state in the checkpoint and the resumed run jumps (+0.057 in loss at the first step after resuming, still +0.017 at the end). Forget the data position and there is no visible mark at all: the model silently re-reads data it has already seen, and the loss looks better than it is.

2. Read

Chapter 13 of the book:

  • §1 Why two models: a small workhorse to debug on, one big run at the end.
  • §2 What a checkpoint must hold: the table of six things and what breaks without each.
  • §5 Determinism.
  • §8b Resume, and resume done wrong, including the bug the test caught.

3. Implement

One function, in the library trainer every later module uses: llmfs/train/trainer.py, save. Read train below it first: the resume code there is the other half of the contract, and it tells you exactly which keys your checkpoint must contain.

4. Check

uv run python course/check.py 9

Two tests, a few seconds on a GPU. They train a tiny model on random tokens for 20 steps straight through, then again with a stop at step 10 and a resume, and require the two loss curves to be identical, not close. The second test resumes without the optimizer state and requires the curve to differ, so you can see the check has teeth.

5. Run

The same test on a real model:

uv run python stages/11_pretrain/run.py resume_test

About 4 minutes: a 4-layer model, 1,200 steps, trained three ways. The book's validation losses, which a rerun while writing this course matched exactly:

run final validation code loss
uninterrupted 3.9158
stopped at step 600, resumed 3.9158 (bit-identical)
resumed without Adam's state 3.9323

Those are on the book's data. On the two-shard data the three runs gave 4.0124, 4.0124 and 4.0313: different numbers, the same verdict. Equality between the first two is the result; the values themselves depend on the data.

Then the base model. On your own GPU:

uv run python stages/11_pretrain/run.py workhorse      # resumable: rerun the same command after a stop

30M parameters, 590M tokens, 18,000 steps. The book's run took 2 h 18 min on the RTX 4060 Laptop and finished at a validation loss of 1.554 on code and 3.293 on English. Yours trains on the two-shard data from module 2: 275M tokens of unique code against the book's 1,330M, so the run's 500M tokens of code read it nearly twice. The book measured that cost directly (chapter 12, the repetition experiment): at the same budget, 4 passes over the data instead of 1 raised the loss by 0.11. Expect your workhorse to land a little above 1.554 on its own validation set.

On Colab, or to save the time, download the book's trained workhorse:

python course/get_checkpoints.py

About 240 MB from huggingface.co/karanjakhar/llm-from-scratch: the book's workhorse base and its module 11 SFT model, placed where the stage scripts look for them. Add --capstone for the 92M model (369 MB). Module 9's test still grades your save; the download only replaces the 2-hour run.

6. Break it

Edit your save to leave out "loader", and run course/check.py 9 again. Then put it back and leave out "opt". Which omission does the test catch with a different loss curve, and which would you only notice by reading the code? Chapter §8b's last paragraph is the answer.

7. Check yourself

1. Why write the checkpoint to a .tmp file and rename it, instead of saving straight over the old one?

A rename is atomic: the file is either the old checkpoint or the new one. A crash in the middle of torch.save straight over the old file leaves a half-written file and no good checkpoint at all.

2. Losing Adam's state cost +0.057 at step 610 but only +0.017 at the end. Why so mild?

At step 600 of a cosine schedule the learning rate is already well down, so the oversized first steps of a fresh Adam move the weights less than they would early in training. The damage is a permanent offset, not a blow-up.

3. The first version of the resume test crashed with "RNG state must be a torch.ByteTensor". What was wrong?

The checkpoint was loaded with map_location="cuda", which also moved the saved CPU random-number state onto the GPU. Restoring needs it back on the CPU. It would have crashed the 20-hour run's first restart.

4. Why debug every stage on a 30M model and train the 92M model only once?

A bug found at hour 2 of the workhorse costs 2 hours; the same bug at hour 12 of the capstone costs 12, and its fix needs a restart. The workhorse is big enough to behave like the real thing and small enough to rerun.


Stuck? Solution: llmfs/train/trainer.py.

Next: Module 10, evaluation: does your model write Python that passes unit tests?

Module 10 · stage 22

Evaluation

You will build the three pieces that turn "the loss went down" into "the model solves this many programming problems": cutting a completion where the function ends, running it against unit tests safely, and the unbiased pass@k estimator. Then you score your base model on HumanEval and MBPP.

Time: 2-3 hours. Hardware: GPU. Book chapter: 24, Measuring what matters.


1. Why

Loss tells you a model predicts text better. It does not tell you whether the model can do anything. For code there is a better question with an objective answer: write the function, run the tests, count the passes. That is why this project chose Python: every result in this module is a number nobody has to judge.

What breaks without the details: the first version of this harness scored the workhorse at exactly zero, and all 164 completions were empty. HumanEval prompts end with a newline, which this tokenizer encodes as a bare "\n" token; in training, a bare newline almost always meant "the next line starts in column 0". So the model began a new top-level function instead of writing the body, and truncation correctly cut it all away. The tests ran, failed and reported a real-looking 0%. The fix, stripping the prompt's trailing newline, is in evaluate, which you are not writing; the lesson is that where a token boundary falls is part of the prompt.

2. Read

Chapter 24 of the book:

  • §1 Perplexity: necessary, not sufficient.
  • §3 Generative benchmarks and pass@k, including why the naive estimate of pass@k is biased.
  • §5 Contamination: how to check that a solved problem was not in the training data.
  • §8a The table: every model the book trained, through one harness.

3. Implement

Three blanks, in the evaluation library the later stages share:

# Function File What it does
1 truncate llmfs/eval/codeeval.py cut a completion where the function ends
2 pass_at_k llmfs/eval/codeeval.py the unbiased estimator from n samples with c correct
3 run_program llmfs/eval/execution.py run code with a timeout and a memory cap, and only count a pass if it reached the end

Before the check, download HumanEval and MBPP (once), or three of the tests are skipped:

uv run python stages/02_data/download_extras.py

4. Check

uv run python course/check.py 10

10 tests. Among them: pass@k against known values; a program that loops forever times out; a program that calls sys.exit(0) before its asserts is not a pass; all 164 HumanEval reference solutions pass under your harness and wrong answers fail.

A warning. run_program executes code a model wrote. It runs in a separate process with a time limit and a memory cap, which stops runaway loops; it is not a security sandbox. At 30M parameters the risk is close to nothing, but if you point this at a larger model or change the prompts, run it inside a container or a throwaway VM.

5. Run

uv run python stages/22_evaluation/run.py table --redo

--redo matters: without it, the script reuses the book's committed rows and evaluates nothing. It scores every checkpoint you have: the validation loss, and greedy pass@1 on HumanEval's 164 problems and MBPP's 500. About 9 minutes per model on the book's GPU, most of it generating and running 664 programs.

model val code loss HumanEval pass@1 MBPP pass@1
workhorse base (book) 1.684 0 0
capstone base, 92M (book) 1.423 3.05% 0.2%

Run while writing this course on the book's workhorse with the two-shard validation set: loss 1.671, and zero on both benchmarks, as in the book. Zero is the honest answer for a 30M model choosing its single most likely completion. Add --pass10 to draw 10 samples per problem at temperature 0.8: the book's workhorse then solved 1.22% (2 of 164). Run while writing this course, it took 21 minutes for the one model and reproduced the 1.22%.

6. Break it

  1. In run_program, count any exit code 0 as a pass (drop the sentinel check). Run the tests. Then think about what a model trained with "tests pass" as its reward (chapter 22) would learn to do.
  2. Replace pass_at_k with the naive "fraction of problems where at least one of the first k samples passed" and compare on n = 10, c = 1, k = 5. The unbiased estimator gives 0.5; what does the naive one give on average, and why is it noisier?

7. Check yourself

1. Why is validation loss alone not enough to compare these models?

The book's three small models differed by up to 0.085 in code loss and all scored exactly zero on both benchmarks. Loss sees differences that the tests cannot yet, and says nothing about whether any program runs.

2. One HumanEval problem is 0.61 percentage points. The same checkpoint scored 0 and then 1 of 164 in two runs with the same settings. How should you read a difference of one problem?

As a tie. Greedy decoding in bf16 can flip at near-ties when the batch changes, so one or two problems either way is noise at this scale.

3. What does a 13-gram contamination check look for, and what did the book find?

Any 13-token run of a benchmark's reference solution that also appears in the training data. None of the 9 distinct problems the book's models solved had a single 13-gram in the 1.33B training tokens: the scores are small and clean.

4. pass@10 came out lower than pass@1 for one of the book's models. Is that a bug?

No: they come from different decoding. Greedy pass@1 takes the single most likely completion; pass@10 samples at temperature 0.8, which spends its tries elsewhere. Only the same decoding makes them comparable.


Stuck? Solutions: llmfs/eval/codeeval.py and llmfs/eval/execution.py.

Next: Module 11, instruction tuning: teach the base model to answer a request, then measure what that cost with the harness you just built.

Module 11 · stage 16

Instruction tuning

You will build the chat template that turns a request and a reply into one token sequence, the loss mask that trains only on the reply, and the batching that pads examples without corrupting them. Then you fine-tune your base model on 119,000 docstring-to-function pairs and measure, with module 10's harness, what it gained and what it forgot.

Time: 2-3 hours, plus about 40 minutes of training on the book's GPU. Hardware: GPU. Book chapter: 18, Teaching it to follow instructions.


1. Why

A base model continues text. Ask it "write a function that reverses a list" and it may continue with another request, because that is what came next in its training data. Supervised fine-tuning (SFT) shows it thousands of request → answer pairs in a fixed format, and trains it to produce only the answer part.

What breaks without the loss mask: train on the prompt as well as the reply, and the model spends its updates learning to predict docstrings it will always be given. Chapter §8c measures the cost.

2. Read

Chapter 18 of the book:

  • §1 Base model vs instruct model.
  • §2 Chat templates and §3 Loss masking.
  • §4 Padding, packing, and the mask trap.
  • §6 Catastrophic forgetting: what fine-tuning takes away.

3. Implement

Open stages/16_sft/sft.py. Three blanks:

# Function What it does
1 render user text + reply → token ids and labels, in the chat format
2 split_function a Python function → (signature + docstring, whole function)
3 collate pad a batch on the right and shift for next-token prediction

split_function builds the training data: CodeSearchNet's 412,178 Python functions, filtered to free functions with a docstring and a body. The request is the signature and docstring; the reply is the whole function.

4. Check

uv run python course/check.py 11

7 tests. The loss mask must cover exactly the reply and its closing <|im_end|> (the model must learn to stop); padding on the right must not change the logits of the real tokens; methods with self must be rejected; accumulating gradients over micro-batches must match one full batch.

5. Run

Needs the workhorse base model from module 9 and CodeSearchNet (from download_extras.py):

uv run python stages/16_sft/run.py --base checkpoints/11_pretrain/workhorse/final.pt --tag mine

3,000 steps; 37 minutes on the book's GPU, including evaluation. The book's run on the 30M workhorse:

before SFT after SFT
completion loss on held-out pairs 1.168 1.033
HumanEval pass@1 (asked as a chat turn) 0 1.22% (2 of 164)
pretraining validation loss, code 1.684 1.832
pretraining validation loss, English 3.341 3.646

Run while writing this course on the book's workhorse: the completion loss went 1.1675 → 1.0328 and HumanEval reached 1.22%, identical to the book, because the fine-tuning pairs and the base model are the same. On the two-shard validation set the forgetting read 1.671 → 1.826 (code) and 3.359 → 3.662 (English). The first row is what SFT trains. The last two rows are the forgetting: the model got worse at plain code and English while learning the format. On the book's 92M model the trade was worse still: SFT cost it 3 HumanEval problems (5 → 2), which reinforcement learning with unit tests later won back (chapter 22).

Then add your SFT model to module 10's table:

uv run python stages/22_evaluation/run.py table --redo

(The table looks for checkpoints/16_sft/workhorse.pt; copy or rename yours, checkpoints/16_sft/mine.pt, to that name first.)

6. Break it

uv run python stages/16_sft/run.py --base checkpoints/11_pretrain/workhorse/final.pt --tag mine --prompt-loss

The same fine-tune, but with the loss on the prompt too. Compare its completion loss and its forgetting with your first run, then read chapter §8c for the book's result.

7. Check yourself

1. Why must the closing <|im_end|> be inside the loss mask?

It is how the model learns to stop. If the end token is never a target, the model never learns to produce it and keeps generating past its answer.

2. Padding goes on the right and the pad positions get label IGNORE. Why does right padding leave the real tokens' logits unchanged?

The model is causal: a position only attends to positions before it. Pads placed after the real tokens are never seen by them, so their outputs are exactly what they would be without padding.

3. SFT lowered the model's skill at plain code (validation loss up by 0.15). Why train it at all?

Because the format is the point: a chat model must answer the request it is given and stop. The book measured the price honestly; whether it is worth it depends on how the model will be used. The base model, prompted as plain code, stayed the best HumanEval scorer at 92M.

4. Why keep only free functions (no self) from CodeSearchNet?

A method depends on a class the request does not show, so the reply would refer to attributes the model cannot know. Free functions with a docstring are self-contained: the request fully describes the answer.


Stuck? Solution: stages/16_sft/sft.py.

After the core path. You have built a tokenizer, a GPT, a training loop, a base model, an evaluation harness and an instruction-tuned model, each checked against a reference. The electives continue from here: LoRA (fine-tune 1% of the parameters), reward models, DPO, reinforcement learning with unit tests, quantization, serving. Each is a chapter of the book with its code and tests in the repository.