Build an LLM from Scratch

Tokenizer, GPT decoder, pretraining, sampling, KV cache and supervised fine-tuning: one small Python file that trains to a working model on a laptop CPU in a few minutes, with no downloads.

Hands-on tutorial · after the Transformer module and labs 01–03 Code: build-llm/build_llm.py (torch ≥ 2.1) Full run: ~1 min on 4 CPU threads, ~3 min on 1

Prerequisites

  • Transformer: attention, causal masking, KV cache
  • Python and basic PyTorch (nn.Module, autograd, an optimizer step)
  • Cross-entropy loss and softmax

What you'll learn

  • How byte-level BPE turns any string into token ids and back
  • The modern decoder block: pre-norm RMSNorm, RoPE, causal SDPA, SwiGLU, tied embeddings
  • A pretraining loop and how to read its loss curve
  • Temperature, top-k and top-p sampling, and a KV cache you test against the full forward pass
  • What SFT changes (format and stopping) and what it does not (knowledge)

Time

60–90 min reading, 1–3 min running python build_llm.py all, plus exercises.

Run it

pip install -r requirements.txt
python build_llm.py all

0 The whole pipeline in one file

The Transformer module explained a decoder as a diagram. This tutorial builds one end to end and runs every stage. Each stage is a subcommand of build_llm.py, and all runs them in order:

Notation (as in the Transformer module): N = tokens in a context, d = width, h = heads, L = layers, V = vocab. T is used only for the sampling temperature; the code keeps nanoGPT's B, T, C for batch, tokens and width.

1 · Data 2 · Tokenizer 3 · Model 4 · Train 5 · Sample 6 · KV cache 7 · SFT generated world4,000 short docs byte-level BPE512 tokens GPT decoder0.87M params AdamW, 600 stepsnext-token loss greedy, T,top-k, top-p decode = fullforward (test) 24 Q&A pairschat template python build_llm.py all datatokenizer(in train) trainsamplekvcachesft → out/base.pt, out/loss.csv → out/sft.pt subcommand names in purple; sample, kvcache and sft read out/base.pt, so run train first

The seven stages and the subcommand that runs each. Everything after training reads the checkpoint, so you can re-run sampling or SFT without retraining.

Why so small?

A 0.87M-parameter model on 2.5M training tokens (12.6 passes over a 195K-token corpus) costs about 6 × 0.87M × 2.46M ≈ 12.8 TFLOP, about a minute of CPU time. That is enough to watch every mechanism work. The code is the same shape as a real LLM; the last section lists what changes when you scale it up.

1 Data: a tiny world you can check

Real pretraining reads trillions of tokens of web text. Here the corpus is generated by make_corpus() from a dozen made-up people, each with a town, a pet, a job and a favourite colour. The facts never change across the corpus, so you can test later whether the model learned them. Nothing is downloaded and every sentence was written for this repo.

Three kinds of document are mixed: fact sheets (35%), Q&A notes (15%, the toy version of the FAQ pages that real web text contains) and short stories (50%) that combine people, places and pets at random.

$ python build_llm.py data
4,000 documents, 663,222 characters, 235 distinct words
  - On a windy morning, Ada left Riverton and went to the bakery. She painted a yellow sign for the bakery. She bought some fish at the bakery. Biscuit the dog barked at a duck. It was a good day for Ada the painter.
  - Kiwi is Lena's parrot. Lena works as a teacher. Lena has a parrot named Kiwi.
  - In Fernwick, everyone knows Priya the doctor. Priya works as a doctor. Priya's favorite color is purple.
  - Nora works as a nurse. Luna is Nora's cat. Nora has a cat named Luna. ...
What a synthetic corpus can and cannot show

The stories are random combinations, so even a perfect model cannot predict them exactly: the loss has a floor above zero. The vocabulary is tiny (235 words), so the model learns grammar in about a hundred steps. Real text has a long tail of rare words and facts, which is why real models need so much more data and so many more parameters.

2 Tokenizer: byte-level BPE from scratch

A model reads integers, not text. Byte-pair encoding (BPE, Sennrich et al., 2015) builds the vocabulary bottom-up:

  1. Start with the 256 byte values. Any string is a sequence of UTF-8 bytes, so any string can be encoded: nothing is ever "unknown".
  2. Pre-tokenize the text into chunks (a word with its leading space, a number, punctuation, whitespace) with a GPT-2-style regex. Merges never cross chunk boundaries.
  3. Count every adjacent pair of tokens, merge the most frequent pair into a new token, and repeat until the vocabulary is full.

Encoding replays the merges in the order they were learned. Decoding concatenates each token's bytes. Training counts each distinct chunk once, weighted by its frequency, so 252 merges take 0.1 s here.

Step through BPE merges
Most frequent pairs nowcount
#Merges learned so far

Edit the text and press "Next merge". Orange chips are the tokens created by the latest merge; ␣ is a space. Watch the token count fall as frequent pairs such as "␣c" + "at" become one token.

$ python build_llm.py tokenizer
   merge   1:       b'h' + b'e'       -> b'he'          (seen 14,906x)
   merge   2:       b' ' + b't'       -> b' t'          (seen 11,069x)
   ...
   merge   8:      b' t' + b'he'      -> b' the'        (seen 7,249x)
trained 252 merges in 0.1s -> vocab 512 (256 bytes + 252 merges + 4 specials)
212 bytes -> 71 tokens: On| a| w|in|d|y| morning|,| Ada| left| Riverton| and| went| to| the| baker|y|.| ...
round-trip OK on 202 strings, incl. unseen unicode (58 tokens, mostly raw bytes)
compression: 3.11 bytes/token on the corpus

The round-trip test

The one property a tokenizer must have is decode(encode(s)) == s for every string. The script asserts it on 200 documents, on text the tokenizer never saw (accents, CJK, an emoji, tabs and newlines) and on the special tokens. Unseen characters fall back to their raw bytes: "Café 🙂" is 10 bytes and 10 tokens, but it round-trips exactly.

build_llm.py
tests = docs[:200] + ["Café ☕, naïve résumé, 東京, emoji 🙂, tabs\tand\nnewlines",
                      "<|user|>hi<|assistant|>ok<|end|>"]
for s in tests:
    assert tok.decode(tok.encode(s)) == s, f"round-trip failed for {s!r}"

Special tokens and the leading-space trap

Four ids are reserved after the merges: <|endoftext|> separates documents, and <|user|>, <|assistant|>, <|end|> form the chat template used in SFT. They are matched literally before BPE runs, so user text can never produce them by accident.

Notice that " Ada" (with its space) is one token, while "Mira" at the very start of a string becomes M|ira. To BPE, a word with and without a leading space are different tokens. This matters in step 7: the chat template puts a space before the answer so that the answer's first word is the same token the model saw in pretraining.

Real tokenizers

GPT-2's byte-level BPE has 50,257 tokens (config); recent models use larger vocabularies. A larger vocabulary means fewer tokens per sentence (cheaper attention and KV cache) but a larger embedding table and output layer. On edge devices the [d, V] output projection can be a noticeable share of decode time.

3 Model: a modern GPT decoder

The block is the decoder from the Transformer module with the changes that most open LLMs have adopted since GPT-2. Each is a few lines in build_llm.py:

Pre-norm GPT block (× 4 layers), d = 128, 4 heads token ids [B, N] Embedding E [V, d] x : [B, N, d] × 4 RMSNorm Causal attention RoPE(q, k) · SDPA + RMSNorm SwiGLU MLP d → 352 → d + residual stream (never normalized) final RMSNorm lm_head = Eᵀ → logits [B, N, V] tied Pre-norm Normalize the input of each branch, add the output back to an untouched residual stream. Trains stably. RMSNorm x · g / rms(x): no mean subtraction, no bias. Cheaper than LayerNorm, works as well in practice. RoPE + causal SDPA Rotate q and k by position-dependent angles, so q·k depends on relative position. One fused attention call. SwiGLU down(silu(gate(x)) ⊙ up(x)). Three matrices, so d_ff ≈ 8/3·d keeps the parameter count of a 4·d GELU MLP. Tied embeddings One [V, d] matrix for lookup and output projection: saves V·d = 65,536 params (7% of this model).

The grey bar is the residual stream; each branch reads a normalized copy and adds its result back. Compare with the post-norm block, LayerNorm and sinusoidal positions in the original Transformer.

build_llm.py: the block
def apply_rope(x, cos, sin):
    """Rotate each (x1, x2) pair of channels by a position-dependent angle. x: [B, n_head, T, head_dim]."""
    x1, x2 = x.chunk(2, dim=-1)
    return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1)

class Attention(nn.Module):
    def forward(self, x, cos, sin, cache=None):
        B, T, C = x.shape
        q, k, v = self.qkv(x).split(C, dim=2)            # one fused GEMM for Q, K, V
        q, k, v = (t.view(B, T, self.n_head, self.head_dim).transpose(1, 2) for t in (q, k, v))
        q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
        if cache is not None:
            k, v = cache.update(k, v)                     # all keys/values so far
        y = F.scaled_dot_product_attention(q, k, v, is_causal=T > 1)
        return self.proj(y.transpose(1, 2).reshape(B, T, C))

class Block(nn.Module):
    def forward(self, x, cos, sin, cache=None):
        x = x + self.attn(self.norm1(x), cos, sin, cache)   # pre-norm
        return x + self.mlp(self.norm2(x))

The code follows nanoGPT: B, T, C = batch, tokens, width, so the code's T is the N (tokens) of the prose and diagrams, and C is d. In apply_rope, x is [B, h, N, d_k].

Where the 869,504 parameters are

PartShapeParametersNote
Token embedding (= lm_head)512 × 12865,536counted once because it is tied
Attention per layerqkv 128×384, proj 128×12865,5364·d², no biases
SwiGLU per layer3 × 128×352135,168d_ff = 352 (8/3·d rounded up to 32)
2 RMSNorm gains per layer2 × 128256
× 4 layers + final norm803,840 + 128
Total869,504printed as 0.87M

4 Pretraining: next-token prediction

The training signal is free: every position predicts the token that follows it. get_batch samples 32 windows of 128 tokens; the targets are the same windows shifted by one. The loss is the average cross-entropy over all 4,096 positions.

build_llm.py: one training step
for step in range(args.steps):
    for g in opt.param_groups:
        g["lr"] = lr_at(step, args.steps, peak=3e-3, warmup=30)   # linear warmup, cosine decay to 10%
    x, y = get_batch(train_data, batch_size, cfg.ctx, gen)       # y = x shifted left by one token
    _, loss = model(x, y)
    opt.zero_grad(set_to_none=True)
    loss.backward()
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)      # cap rare large updates
    opt.step()                                                   # AdamW, weight decay on matrices only
  • AdamW (Loshchilov & Hutter) with β = (0.9, 0.95) and weight decay 0.1 on matrices, none on norm gains.
  • Warmup then cosine decay. Adam's moment estimates are noisy for the first steps, so the learning rate ramps up over 30 steps.
  • Gradient clipping at norm 1.0 keeps a single bad batch from undoing progress.
  • Initialization: N(0, 0.02), with the output projections of each residual branch scaled down by √(2·layers), as in GPT-2.

Reading the loss curve

Recorded run: python build_llm.py all --threads 4 (torch 2.1, i7-13700H) 0.25 0.5 1 2 4 0 100 200 300 400 500 600 training step loss (nats/token, log scale) uniform guess: ln 512 = 6.24 val 0.45 at step 100 val 0.297 at step 600 train (one batch, every 10 steps) validation (held-out docs, every 50)

What to notice: the loss starts at ln V, as an untrained model's uniform guess should, falls about 14× in the first 100 steps, and then creeps down. Validation tracks training closely, so there is little overfitting despite 12.6 epochs.

  • Start at ln V. An initial loss far from ln 512 = 6.24 points to an initialization bug. This one starts at 6.257.
  • Plateau above zero. The final validation loss is 0.297 nats/token, a perplexity of e0.297 ≈ 1.35: on average the model hesitates between about 1.35 equally likely tokens, because the stories are random (which friend, which place).
  • Train vs. validation. If validation rose while training fell, the model would be memorizing the training windows. Here the gap is about 0.04 at the end.
Measured run (i7-13700H, torch 2.1, CPU)Pretraining, 600 stepsWhole all pipelineThroughput
--threads 463 s66 s≈ 39,000 tok/s
--threads 1176 s180 s≈ 14,000 tok/s

Training compute ≈ 6 × params × tokens (Chinchilla writes this 6·N·D, with N = parameters and D = tokens; elsewhere on this page N counts the tokens in a context). With 869,504 parameters and 2,457,600 training tokens it is 12.8 TFLOP, so the 4-thread run sustained about 0.2 TFLOP/s. The same arithmetic tells you what a real run costs; see At scale.

5 Sampling: from logits to text

The model outputs a score (logit) for every token in the vocabulary. Generation repeatedly turns the last position's logits into one token and appends it. How you choose that token changes the text a lot:

  • Greedy (T = 0): always the argmax. Deterministic, and prone to loops in larger models.
  • Temperature T: divide the logits by T before the softmax. T < 1 sharpens the distribution, T > 1 flattens it.
  • Top-k: keep only the k most likely tokens.
  • Top-p (nucleus, Holtzman et al.): keep the smallest set of tokens whose probabilities add up to at least p. The set adapts: narrow when the model is confident, wide when it is not.
Next token after "One morning, Mira walked to the …" (toy logits)
samples: –

Move the sliders. Grey bars are tokens removed by top-k or top-p; the remaining probabilities are renormalized. At T = 0 everything goes to the argmax. Watch how T = 2 hands real probability to "cat" and "Oakvale", which make no sense here.

build_llm.py
def sample_next(logits, temperature=1.0, top_k=None, top_p=None, gen=None):
    if temperature == 0:
        return logits.argmax(-1, keepdim=True)            # greedy
    logits = logits / temperature
    if top_k is not None:
        kth = torch.topk(logits, min(top_k, logits.size(-1))).values[..., -1:]
        logits = logits.masked_fill(logits < kth, float("-inf"))
    probs = F.softmax(logits, dim=-1)
    if top_p is not None and top_p < 1.0:
        p_sorted, idx_sorted = probs.sort(-1, descending=True)
        outside = p_sorted.cumsum(-1) - p_sorted >= top_p   # mass before this token already >= top_p
        p_sorted = p_sorted.masked_fill(outside, 0.0)
        choice = torch.multinomial(p_sorted / p_sorted.sum(-1, keepdim=True), 1, generator=gen)
        return idx_sorted.gather(-1, choice)
    return torch.multinomial(probs, 1, generator=gen)
$ python build_llm.py sample
[greedy (T=0)]
One morning, Mira walked to the hill with Pip. She bought some cheese at the hill. Pip the cat chased a leaf. Then Mira went home to Oakvale.

[T=0.8, top-k=20]
One morning, Mira walked to the park with Pip. She bought some fish at the park. The weather was windy, so she stayed near the park. Mira said hello to Pip. It was a good day for Mira the baker.

[T=2.0 (too hot)]
One morning, Mira walked to the park with Pip. Sheer the bakery the rabbit�� everyone Kenji went to Fernwick. bakery afternoon, ...

fact recall (greedy): 'Mira lives in' -> ' Oakvale'
fact recall (greedy): 'Tomas lives in' -> ' Riverton'

The model has learned grammar, the story templates and the facts: Mira's pet is Pip and she goes home to Oakvale. At T = 2 the flattened distribution gives weight to tokens that never follow each other, and it even emits single bytes of a multi-byte character (the � marks).

6 KV cache: fast decoding, tested

Without a cache, generating token t re-runs the model on all t tokens, recomputing keys and values that have not changed. With a cache, each layer stores K and V for past positions; a decode step computes q, k, v for the one new token only, appends k and v, and attends over everything cached.

No cache: step t re-runs all t tokens KV cache: step t runs 1 token, reads t − 1 cached K, V computed this step read from the cache token-steps of projection + MLP work: 1 + 2 + … + N = O(N²) token-steps of projection + MLP work: N = O(N)

Rows are decode steps 1–6, cells are token positions. Attention still reads all cached keys at each step, so long contexts make decode memory-bandwidth bound: the KV cache is what you pay for in memory.

The test: cached decode must equal the full forward

An optimization you cannot verify is a bug waiting to happen. cmd_kvcache runs the full causal forward over 128 tokens once, then runs a 16-token prefill into an empty cache followed by 112 single-token decode steps, and compares every logit:

build_llm.py
full, _ = model(idx)                                   # [1, T, V], one causal pass
caches = model.new_kv_cache(1)
steps = [model(idx[:, :16], caches=caches)[0]]         # prefill 16 tokens
for t in range(16, idx.shape[1]):                      # then decode one token at a time
    steps.append(model(idx[:, t:t + 1], caches=caches)[0])
inc = torch.cat(steps, dim=1)
assert torch.allclose(full, inc, atol=1e-4)
$ python build_llm.py kvcache
logits: full forward vs prefill(16) + 112 cached decode steps: max |diff| = 7.63e-06
greedy generation of 119 tokens is identical with and without the cache
  no cache:   925.9 tok/s   (re-runs all N tokens every step: O(N^2) GEMM work)
  KV cache:  1809.4 tok/s   (one new token per step:          O(N)   GEMM work; attention reads still grow as O(N^2))
KV cache size = 2 (K,V) x 4 layers x 128 positions x 128 dims x 4 B = 512 KiB per sequence (fp32)
PASS: KV-cache decode matches the full forward

The difference is floating-point noise (different summation order), far below the tolerance. The speedup is only about 2× here because the model is tiny and the context is 128 tokens, so per-step overheads dominate. The gap grows with model size and context length.

Two details that break caches in practice

Positions: a decode step must use the absolute position of the new token for RoPE (start = caches[0].pos), not position 0. Masking: PyTorch's is_causal=True assumes a square N × N mask aligned at the top-left. It is right for a prefill into an empty cache, and a single decode query needs no mask, but a multi-token chunk on top of an existing cache needs an explicit mask. The minimal cache here asserts against that case instead of silently computing the wrong thing.

KV cache size calculator
KV cache
–
per token
–
vs. full MHA
–

Size = 2 × L × N × batch × (KV heads × head_dim) × bytes. The defaults are a 7B-class shape (L = 32, d = 4096) at N = 8192 in FP16: 4 GiB per sequence. Set KV heads to 8 (grouped-query attention, Ainslie et al.) or bytes to 1 (FP8 cache) to see the levers serving systems use.

7 SFT: teaching the format, not the facts

The pretrained model is a document continuer. Asked in plain text, it already knows the answer, but it never stops:

base model, plain text prompt 'Where does Ada live?' -> " Ada lives in Riverton. What is Ada's favorite color?"

Supervised fine-tuning (SFT) trains on conversations written in a chat template, so the model learns where the user's turn ends, where its answer starts, and when to stop. Here: 24 question-answer pairs about people 1–6 only. People 7–12 are held out to test whether the model generalizes.

One SFT example, as the tokenizer sees it. Loss is computed only on the answer. prompt: label −100 (context only) answer + <|end|>: trained on

These are the real tokens from the trained tokenizer. Note " W" + "here": the merges never learned " Where". The answer starts with " Mira", the same token the model saw mid-sentence in pretraining.

Three details that decide whether SFT works

  1. Loss masking. Prompt positions get label −100, which cross_entropy ignores. The model is graded only on producing the answer and <|end|>.
  2. Leading spaces. Without the space after <|assistant|>, the answer starts with M|ira, a token sequence the model rarely saw. A template that fights the tokenizer makes SFT much harder.
  3. New tokens need a starting point. The template tokens never appeared in pretraining, so their embeddings are untrained. warm_start_special_tokens copies the embedding of a token that plays the same role: <|assistant|> starts as "?" (an answer follows), <|user|> and <|end|> as the document boundary.
$ python build_llm.py sft
before SFT, chat template (held-out):
   Q: Where does Ada live?                 -> "Ada lives in Riverton. What is Ada's favorite color? Ada's f"  expected 'Ada lives in Riverton.'
   sft step  10  loss 0.074
   sft step  20  loss 0.035
   sft step  30  loss 0.016
SFT: 30 steps in 0.5s
after SFT (held-out people, never seen in SFT):
   Q: Where does Ada live?                 -> 'Ada lives in Riverton.'  OK
   Q: What pet does Felix have?            -> 'Felix has a parrot named Ziggy.'  OK
   Q: What is Nora's job?                  -> 'Nora works as a nurse.'  OK
   Q: What is Kenji's favorite color?      -> "Kenji's favorite color is green."  OK
   ...
exact-match accuracy  held-out: 0% -> 100%   SFT pairs: 100%

$ python build_llm.py sft --cold-start      # same, without warm-starting the template tokens
exact-match accuracy  held-out: 0% -> 4%   SFT pairs: 100%

With warm-started template tokens, 30 steps on 24 pairs make the model answer correctly and stop for all 24 held-out questions: the facts came from pretraining, and SFT only taught the format. Cold-started, the model fits the 24 training pairs perfectly but mostly answers held-out questions with a training person's name: it memorized instead of learning the format. Across three pretraining runs (1, 4 and 14 threads, which differ only in floating-point summation order) cold start scored 4%, 8% and 29% on the held-out questions; warm start scored 100% every time. This is the toy version of an observation from LIMA: almost all knowledge is learned in pretraining, and a small, clean instruction set mostly teaches the response format.

How real chat models differ

They fine-tune on hundreds of thousands of diverse conversations, often after a "mid-training" phase that already includes chat-formatted data, and then run preference optimization or reinforcement learning (InstructGPT is the classic recipe). Diversity plays the role that warm-starting plays here: with enough different prompts, memorizing answers stops being the easiest solution.

8 What changes at scale

The loop above is the real algorithm. Scaling it to billions of parameters changes the engineering around it in four places.

This tutorialA real pretraining run
Data4,000 generated docs, 195K tokens, 12.6 epochsTrillions of tokens of filtered, deduplicated web, code and books, mixed by domain; usually under one epoch. Data quality filtering is a large part of the work.
Size vs. tokens0.87M params, 2.5M tokensChinchilla (Hoffmann et al.) found that compute-optimal training scales params and tokens together, about 20 tokens per parameter (70B params on 1.4T tokens). Models meant for cheap inference are trained far past that point.
PrecisionFP32 on CPUBF16 matmuls with FP32 master weights and optimizer state (mixed precision); FP8 matmuls on Hopper/Blackwell GPUs for more throughput. Loss scaling is needed for FP16, not BF16.
Parallelismone processMixed-precision AdamW keeps about 16 bytes per parameter (weights, grads, FP32 master + two moments; ZeRO): 112 GB for 7B, more than one 80 GB GPU. FSDP / ZeRO shards these across GPUs (14 GB each on 8 GPUs), and tensor, pipeline and sequence parallelism split the model further (PyTorch FSDP).
Evaluationval loss + exact match on 24 questionsHeld-out loss per domain, many benchmarks (checked for contamination with the training data), long-context and safety tests, and human or model-graded comparisons after post-training.
sketch: the same step with BF16 autocast and FSDP (GPU, not run here)
# torchrun --nproc_per_node=8 train.py
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
model = FSDP(GPT(cfg).cuda())                          # shard params, grads and optimizer state
opt = torch.optim.AdamW(model.parameters(), lr=3e-4, betas=(0.9, 0.95), weight_decay=0.1)
for step in range(max_steps):
    x, y = next(loader)                                # each rank reads a different shard of data
    with torch.autocast("cuda", dtype=torch.bfloat16):   # matmuls in BF16, master weights stay FP32
        _, loss = model(x.cuda(), y.cuda())
    loss.backward()
    model.clip_grad_norm_(1.0)
    opt.step(); opt.zero_grad(set_to_none=True)

A useful habit is to do the 6 × params × tokens arithmetic before launching anything: a 1B-parameter model on 20B tokens needs 6 × 10⁹ × 2×10¹⁰ = 1.2×10²⁰ FLOP. At 40% utilization of a GPU with 989 TFLOP/s of dense BF16 (H100 SXM), that is about 84 GPU-hours.

✓ Review

Key takeaways

  • Byte-level BPE can encode any string; its one hard requirement is an exact round trip.
  • To a tokenizer, a word with a leading space is a different token. Templates must respect that.
  • A modern decoder block is pre-norm RMSNorm → RoPE attention → residual, then RMSNorm → SwiGLU → residual, with tied embeddings.
  • An untrained model's loss is ln V. A loss curve that does not start there, or a validation curve that rises, is the first thing to check.
  • Temperature reshapes the distribution; top-k and top-p cut its tail. Greedy is deterministic.
  • A KV cache trades memory for compute; test it against the full forward pass, and get RoPE positions and masks right.
  • SFT mostly teaches format and stopping; the knowledge comes from pretraining.
  • At scale the algorithm is the same; data, precision, sharding and evaluation become the work.

Self-check

1. Why can a byte-level BPE tokenizer encode any Unicode string, even one with characters it never saw?

Answer
The base vocabulary is the 256 byte values and every string is a sequence of UTF-8 bytes. Merges only combine existing tokens, so in the worst case a character is encoded as its raw bytes. "Café 🙂" (10 bytes) became 10 tokens and still round-tripped.

2. With a vocabulary of 512, what loss should a freshly initialized model have, and why?

Answer
About ln 512 = 6.24 nats. With small random weights the logits are nearly equal, so the predicted distribution is close to uniform and the cross-entropy of any target is −ln(1/512). The run starts at 6.257.

3. Logits [2, 1, 0]. What are the probabilities at T = 1 and at T = 0.5?

Answer
T = 1: softmax([2, 1, 0]) = [0.665, 0.245, 0.090]. T = 0.5: softmax([4, 2, 0]) = [0.867, 0.117, 0.016]. Lower temperature moves mass to the top token.

4. Probabilities [0.5, 0.3, 0.1, 0.06, 0.04] and top-p = 0.85. Which tokens survive and with what renormalized probabilities?

Answer
Keep tokens until the mass before a token reaches p: before the 3rd token the mass is 0.8 < 0.85, so it is kept; before the 4th it is 0.9 > 0.85, so it is cut. Survivors: 0.5/0.9 = 0.556, 0.3/0.9 = 0.333, 0.1/0.9 = 0.111.

5. In the cached decode step, the single new query attends with is_causal=False. Why is that correct and not a leak of future tokens?

Answer
The cache only contains keys and values for positions up to and including the new token. Nothing in the future exists yet, so the new query may attend to every cached position, which is exactly what row t of a causal mask allows.

6. A model has L = 32, d = 4096, MHA with 32 heads. How big is the FP16 KV cache for one 8,192-token sequence? And with 8 KV heads (GQA)?

Answer
2 × 32 × 8192 × 4096 × 2 bytes = 4,294,967,296 bytes = 4 GiB. With 8 of 32 heads storing K and V, it is a quarter: 1 GiB.

7. Why does the SFT loss ignore the prompt tokens?

Answer
We want to train the model to produce answers, not to imitate user questions. Predicting the prompt would spend capacity on text the model never has to write, and with a fixed template it would also drown the answer signal in easy, repetitive targets.

8. Cold-start SFT reaches 100% on the 24 training pairs but only 4–29% on held-out people. What does that gap tell you, and what are two ways to close it?

Answer
The model memorized the training answers instead of learning the format (overfitting to a tiny set). Fixes: start the new template tokens from embeddings that already mean something (warm start), use many more and more diverse examples, train fewer steps or with a lower learning rate, or update fewer parameters (LoRA).

9. How much memory does mixed-precision AdamW need for the model states of a 7B model, and how does FSDP on 8 GPUs change that?

Answer
About 16 bytes per parameter (2 BF16 weights + 2 BF16 grads + 12 for FP32 master weights and the two Adam moments): 112 GB. Fully sharded over 8 GPUs that is 14 GB per GPU, before activations.

10. Using 6 × params × tokens, how many FLOPs did the 600-step run take, and what throughput did the 63-second run achieve?

Answer
6 × 869,504 × (600 × 4,096) = 1.28×10¹³ FLOP (12.8 TFLOP). 12.8 TFLOP / 63 s ≈ 0.20 TFLOP/s.

Hands-on exercises

  1. Vocabulary size.easy Run python build_llm.py tokenizer --vocab 300 and --vocab 1024. Record bytes/token for each. Self-check: the round-trip assertion still passes, and bytes/token rises with vocabulary size until merges run out.
  2. Determinism.easy In a Python shell, from build_llm import *, load the checkpoint with tok, model = load(argparse.Namespace(out="out")) and call generate(model, tok.encode("One morning,"), 40) twice. Self-check: assert a == b for greedy; with temperature=1.0 the outputs differ unless you pass the same seed.
  3. Ablate RoPE.medium Make apply_rope return x unchanged and retrain. Compare the validation loss at step 600 with 0.297 and look at the samples. Self-check: the KV-cache test must still pass; explain why a causal model can still learn something about order without position encodings.
  4. Grouped-query attention.medium Add n_kv_head = 2: project K and V to 2 heads and repeat_interleave them to 4 before SDPA, and store only the 2 heads in KVCache. Self-check: cmd_kvcache still passes torch.allclose, and caches[0].k.numel() is half of what it was.
  5. Cold start vs. LoRA.medium Run sft --cold-start, then try freezing everything except the embedding matrix, or adding rank-4 LoRA adapters to qkv and proj. Self-check: report held-out accuracy for each and the number of trainable parameters.
  6. Gradient accumulation.hard Replace one batch of 32 with two micro-batches of 16 whose losses are each divided by 2. Self-check: with the same 32 sequences, the accumulated gradients match the single-batch gradients, torch.allclose(g1, g2, atol=1e-6) for every parameter.

What next

Continue the main track: Vision Transformer (Module 2), which reuses this block on image patches. Optional side trip: Build a personal agent needs only this tutorial; the learning path suggests it after Robot Foundation Models.

↗ Resources and references

Go further: build-from-scratch courses

Papers