# Build an LLM from Scratch (hands-on tutorial)

A complete, minimal LLM pipeline in one file: byte-level BPE tokenizer, a GPT-style decoder (pre-norm RMSNorm, RoPE, causal SDPA, SwiGLU, tied embeddings), pretraining, sampling, a tested KV cache and supervised fine-tuning. It trains on a laptop CPU in a few minutes with `torch>=2.1`, and needs no downloads: the corpus is generated by the script from a small made-up world.

Recommended right after the [Transformer](../transformer/) module and [labs 01–03](../labs/index.html). Next: the [Vision Transformer](../vit/) module. [Build a personal agent](../build-agent/) is an optional side trip that needs only this tutorial; the learning path suggests it after Robot Foundation Models.

## Contents

| File | Description |
|------|-------------|
| [build_llm_guide.html](./build_llm_guide.html) | Interactive guide: BPE step-through, sampling sliders, KV-cache calculator, quiz and exercises |
| [build_llm.py](./build_llm.py) | The whole pipeline, one subcommand per stage (~700 lines with comments) |
| [requirements.txt](./requirements.txt) | `torch>=2.1` |

## Quick Start

```bash
pip install -r requirements.txt
python build_llm.py all              # data -> tokenizer -> train -> sample -> kvcache -> sft
python build_llm.py all --threads 4  # limit CPU threads

# or one stage at a time (sample, kvcache and sft read out/base.pt written by train)
python build_llm.py data
python build_llm.py tokenizer
python build_llm.py train --steps 600
python build_llm.py sample
python build_llm.py kvcache
python build_llm.py sft              # add --cold-start to see SFT fail without warm-started chat tokens
```

## What each stage does

| Stage | Subcommand | Key idea | Check |
|-------|------------|----------|-------|
| 1. Data | `data` | 4,000 generated docs (fact sheets, Q&A notes, stories) about 12 made-up people | facts are consistent, so recall is testable |
| 2. Tokenizer | `tokenizer` | byte-level BPE with a GPT-2-style pre-tokenizer, 252 merges + 4 special tokens | `decode(encode(s)) == s` on 202 strings incl. unseen Unicode |
| 3. Model | (in `train`) | pre-norm RMSNorm, RoPE, `F.scaled_dot_product_attention`, SwiGLU, tied embeddings; 869,504 params | initial loss ≈ ln V |
| 4. Train | `train` | AdamW, warmup + cosine, grad clipping, 600 steps × 4,096 tokens | `out/loss.csv`, ASCII loss plot |
| 5. Sample | `sample` | greedy, temperature, top-k, top-p | fact recall ("Mira lives in" → " Oakvale") |
| 6. KV cache | `kvcache` | pre-allocated per-layer K/V buffers, prefill + 1-token decode | `torch.allclose(full, cached, atol=1e-4)` and identical greedy output |
| 7. SFT | `sft` | chat template, loss masking, warm-started template tokens, 24 pairs × 30 steps | exact match on 24 held-out questions |

## Measured results (i7-13700H laptop CPU, torch 2.1.0)

| Run | Pretraining (600 steps) | Whole `all` pipeline |
|-----|-------------------------|----------------------|
| `--threads 4` | 63 s (~39K tokens/s) | 66 s |
| `--threads 1` | 176 s (~14K tokens/s) | 180 s |

- Loss: validation 6.257 at step 0 (ln 512 = 6.238), 0.455 at step 100, 0.297 at step 600.
- KV cache: max |logit difference| vs. full forward = 7.6e-6; 119 greedy tokens identical; 926 → 1,809 tokens/s.
- SFT: held-out exact match 0% → 100% in 30 steps (0.5 s). With `--cold-start` it reached only 4%, 8% and 29% in three pretraining runs (1, 4 and 14 threads); warm start reached 100% in all three.

## Key inference takeaways

- **KV cache size** = 2 × layers × context × (KV heads × head_dim) × bytes. For a 7B-class shape (L = 32, d = 4096) at 8K context in FP16 that is 4 GiB per sequence; GQA with 8 KV heads cuts it to 1 GiB.
- **Test your optimizations**: a cached decode must reproduce the full forward pass. RoPE positions (`start = cache.pos`) and attention masks are where caches break.
- **Tokenizer details reach inference**: leading spaces change token ids, and the vocabulary size sets the cost of the output projection on every decode step.

## Further resources

- [Andrej Karpathy, "Let's build GPT"](https://www.youtube.com/watch?v=kCc8FmEb1nY) (video), [nanoGPT](https://github.com/karpathy/nanoGPT), [minbpe](https://github.com/karpathy/minbpe), [nanochat](https://github.com/karpathy/nanochat)
- [Sebastian Raschka, LLMs-from-scratch](https://github.com/rasbt/LLMs-from-scratch)
- [Stanford CS336: Language Modeling from Scratch](https://cs336.stanford.edu/)

## References

- [Neural Machine Translation of Rare Words with Subword Units (BPE)](https://arxiv.org/abs/1508.07909)
- [RoFormer: Rotary Position Embedding](https://arxiv.org/abs/2104.09864)
- [Root Mean Square Layer Normalization](https://arxiv.org/abs/1910.07467)
- [GLU Variants Improve Transformer (SwiGLU)](https://arxiv.org/abs/2002.05202)
- [The Curious Case of Neural Text Degeneration (top-p)](https://arxiv.org/abs/1904.09751)
- [LIMA: Less Is More for Alignment](https://arxiv.org/abs/2305.11206)
- [Training Compute-Optimal Large Language Models (Chinchilla)](https://arxiv.org/abs/2203.15556)
- [ZeRO](https://arxiv.org/abs/1910.02054) and [PyTorch FSDP](https://arxiv.org/abs/2304.11277)
