Capstone II — Build Your Own Model
local graph
Chapter 30 — Capstone II — Build Your Own Model
Section titled “Chapter 30 — Capstone II — Build Your Own Model”Part VIII — Capstone and Frontiers
Chapter 30 — Capstone II — Build Your Own Mode
Every piece is now in place. This chapter is the book’s second capstone, and its most practical: a concrete, end-to-end recipe for building your own small DeepSeek-style model — not a 671-billion-parameter behemoth, but a real model, with MLA and Mixture-of-Experts, that a small team or a determined individual can actually train and ship. Where Chapter 10 built a GPT, here we assemble everything from Parts IV through VII into a deployable system, and point at the chapter and the tool behind each step.
30.1 Scope It to What You Can Afford
Section titled “30.1 Scope It to What You Can Afford”The first decision is size, and the right answer is almost always “smaller than you think.” A model in the hundreds of millions to a few billion parameters, trained on tens of billions of tokens, is enough to learn from and to be useful for a focused task — and it fits a budget measured in hundreds of GPU-hours, not millions. Better still, you rarely need to start from scratch: the most efficient path for most teams is to take a strong open base model and apply continued pre-training (Chapter 17) and fine-tuning, inheriting trillions of tokens of capability for a fraction of the cost. Build from zero to learn how it works; build on an existing base to ship something useful.
30.2 The End-to-End Checklist
Section titled “30.2 The End-to-End Checklist”The whole book reduces to a sequence of steps, each built in an earlier chapter and served by mature open tooling. Table 30.1 is the recipe.
| Step | Task | Chapter | Open tool |
|---|---|---|---|
| 1 | Train a tokenizer | 5 | tokenizers, minbpe |
| 2 | Build the data pipeline | 6 | datatrove, nanoGPT |
| 3 | Define the model (MLA + MoE) | 16 | your code (Part III-IV) |
| 4 | Pretrain — or continue-pretrain a base | 17-21 | your loop, nanoGPT, FSDP |
| Step | Task | Chapter | Open tool |
|---|---|---|---|
| 5 | Supervised fine-tune (+ LoRA) | 22 | trl (SFTTrainer), peft |
| 6 | Align to preferences (DPO) | 24 | trl (DPOTrainer) |
| 7 | Add reasoning (GRPO) — optional | 25 | trl (GRPOTrainer) |
| 8 | Evaluate (incl. a private set) | 29 | lm-eval-harness, your evals |
| 9 | Quantize and serve | 26, 28 | GPTQ/AWQ, vLLM |
Table 30.1 — Building a model end to end: the step, the chapter, the tool
30.3 A Concrete Small Configuration
Section titled “30.3 A Concrete Small Configuration”To make it tangible, Table 30.2 gives a small but genuinely DeepSeek-shaped configuration — the FrontierLM of Chapter 16, scaled down. It uses MLA and a modest fine-grained MoE, fits comfortably on a single high-memory GPU for inference, and can be pretrained on a small multi-GPU node or continued-pretrained on one.
| Parameter | Value | Parameter | Value |
|---|---|---|---|
| Layers | 12 | Routed experts | 16 |
| Hidden dim | 768 | Active experts | 2 |
| Attention heads | 12 | Shared experts | 1 |
| MLA KV latent | 256 | Dense layers (first) | 1 |
| Vocabulary | ~32K | Context length | 4K |
| Total parameters | ~1B | Active per token | ~0.3B |
Table 30.2 — A small DeepSeek-style configuration
Scale any dimension to fit your hardware; the code is identical to Chapter 16’s. With MoE, total parameters exceed active ones — you get the capacity of a ~1B model at the inference cost of a ~0.3B one.
30.4 Practical Advice
Section titled “30.4 Practical Advice”A few hard-won principles separate a project that ships from one that stalls. Start smaller than the target and scale up once the pipeline works end to end — most failures are plumbing, not modeling, and they are cheaper to find at small scale. Lean on existing models: continued pre-training and distillation from a strong teacher (Chapters 17 and 26) will beat from-scratch training on any realistic budget. Use the open tooling in Table 30.1 rather than reimplementing it; the value you add is the data and the task, not a fresh training loop. Build your private evaluation set first (Chapter 29), before you train anything, so you can tell whether each step actually helped. And watch the cost — the economics of Chapter 20 apply at every scale; an efficient small model you can afford to run beats a larger one you cannot.
You can build this Everything in this capstone is within reach of a small team today. The model architecture is the code of Part IV; the training recipe is Part V; alignment and reasoning are Part VI; serving and evaluation are Part VII. The frontier labs have more compute, but — thanks to open weights, open infrastructure, and the techniques in this book — no longer a monopoly on the method. The gap is capital and data, not secret knowledge.
You have now built a complete model, twice: a GPT in Chapter 10, and a modern DeepSeek-style model here. The remaining two chapters look beyond the text model you have built — outward to the multimodal systems and agents layered on top of it, and forward to the research frontier that will shape the models after these.
30.5 Worked Example: The Whole Book as One Pipeline
Section titled “30.5 Worked Example: The Whole Book as One Pipeline”Every part of this book is a stage in a single pipeline. The Chapter 30 capstone is, at the highest level, just these calls in sequence — each one a part of the book, together turning random weights into a trained, aligned, reasoning model:
model = build_model(config) # Parts III-IV: architecturepretrain(model, web_data, steps=N) # Part V: train at scalesft(model, instruction_data) # Part VI: make it helpfulgrpo(model, verifiable_tasks, reward_fn) # Part VI: teach it to reasonserve(model, engine="vllm") # Part VII: deploy it# scale each stage and this is, in outline, how DeepSeek-V3 -> R1# (Chapter 45) and GLM-5.2 (Chapter 44) were actually builtPython — the end-to-end pipeline: architecture to reasoning model
30.6 Common Pitfalls and How They Show Up
Section titled “30.6 Common Pitfalls and How They Show Up”A first end-to-end run rarely fails loudly; it usually fails quietly, producing plausible-looking loss curves and useless models. The mistakes are nearly always one of a small, recurring set, and each has a characteristic symptom that — once you know it — points straight at the cause:
| Pitfall | Symptom | Fix |
|---|---|---|
| No SFT loss mask | model echoes the prompt | mask non-assistant tokens (22.5) |
| Train/eval format differ | good loss, bad outputs | share one chat template (22.7) |
| Learning rate too high | loss spikes or NaNs | lower peak, add warmup (17.2) |
| Data not shuffled | periodic loss ripples | shuffle / interleave shards (6) |
| Optimizer state not saved | resume restarts badly | checkpoint full state (20.5) |
| Tokenizer mismatch | garbage from step one | same tokenizer end to end (5) |
Table 30.1 — Recurring pitfalls, their symptoms, and fixes
The unifying lesson is that most “the model doesn’t work” bugs are not in the model at all — they are in the seams between stages: the boundary between tokenizer and model, between training format and inference format, between a checkpoint and its resume. When a run misbehaves, suspect the seams before the science. The single most common of all is the loss-mask omission of Section 22.5, which produces a model that fluently repeats whatever you ask it — a symptom distinctive enough to diagnose at a glance.
30.7 Worked Example: A Training Budget on a Single Node
Section titled “30.7 Worked Example: A Training Budget on a Single Node”Scope discipline (Section 30.1) means knowing the bill before you start. Take a run you could actually afford: a 1-billion-parameter model on one 8×H100 node, trained Chinchilla-optimally on about 20 billion tokens. The arithmetic chains together the chapters of Part V.
The compute required is roughly 6 × parameters × tokens = 6 × 10⁹ × 2×10¹⁰ = 1.2×10²⁰ FLOPs. An 8×H100 node delivers on the order of 8 PFLOP/s of usable BF16 throughput, but at a realistic 40% model-FLOPs utilization (Section 20.3) you keep about 3.2×10¹⁵ FLOP/s. Dividing gives 1.2×10²⁰ / 3.2×10¹⁵ ≈ 37,500 seconds — about 10 hours. At a few dollars per GPU-hour, that is a run costing low hundreds of dollars, not millions. The point of the estimate is not its precision but its shape: it tells you, before committing, whether a project is an afternoon or a mortgage, and it is built entirely from the token budget of Section 17.3 and the MFU of Section 20.3.
Estimate before you train 6 × params × tokens gives the FLOPs; divide by (peak × MFU) for the time. Two lines of arithmetic separate a feasible plan from a fantasy — do them first, every time.
30.8 From Capstone to Production: What Is Still Missing
Section titled “30.8 From Capstone to Production: What Is Still Missing”A capstone model that trains cleanly and generates fluent text is a genuine accomplishment — and it is not yet a product. The gap between the two is not more science but the engineering that surrounds the science, and it is worth naming honestly so the achievement is not mistaken for the finish line.
A deployable system adds layers the capstone omits. It needs robust serving — the paged attention, continuous batching, and autoscaling of Chapter 28 — rather than a research generation loop. It needs observability (Section 36.5) so its health and cost are visible, and safety guardrails (Section 43.7) so its outputs are filtered and monitored. It needs an evaluation harness (Chapter 29) that catches regressions before users do, versioning and rollback so a bad update can be undone, and the unglamorous operational discipline of on-call rotations and incident response. None of this is in the capstone, and none of it is optional in production. The right way to read the capstone, then, is as proof that you understand how the model works — which is exactly what the rest of this book’s systems chapters (Part VII and Part IX) build upon to make that understanding deployable. The science is the foundation; the engineering around it is the building.
A working model is the foundation, not the building The capstone proves the science. Serving, observability, safety, evaluation,
‘ersioning, and on-call discipline are the engineering that turns it ‘nto a product — all of it necessary, none of it scientific, and all of it covered by the systems chapters that surround this one.
30.9 Debugging a Training Run
Section titled “30.9 Debugging a Training Run”When a capstone training run misbehaves — the loss will not fall, or falls to nonsense — the temptation is to start tuning hyperparameters. Almost always that is the wrong first move; the problem is a bug, and there is a systematic order of cheap checks that catches the overwhelming majority before any expensive run is launched. The most powerful single test is whether the model can overfit one batch:
x, y = next(iter(loader)) # one fixed batchfor _ in range(100): # train on it repeatedly loss = F.cross_entropy(model(x), y) loss.backward(); optimizer.step(); optimizer.zero_grad()# loss should approach zero; if not, it is a bug, not tuningPython — debug/overfit.py: can the model memorize a single batch?
If a model cannot drive the loss toward zero on a single batch it is allowed to memorize, no learning-rate sweep will save the full run — something is broken in the data, the model, or the gradient flow. The other quick checks are equally diagnostic. The loss at initialization should be close to the natural logarithm of the vocabulary size (an untrained model is uniform over tokens); a wildly different starting loss signals a bug in the output layer or the labels. Gradients should be finite and non-zero everywhere; NaNs or dead zeros point to the culprit layer. And the data pipeline should be checked for the classic off-by-one in how inputs and targets are shifted (Section 4.5). The discipline this encodes is the one that governs all of Part V: validate small before scaling, because a bug found on one batch costs minutes, while the same bug found on a thousand-GPU run costs a fortune.
Overfit one batch before trusting the run If the model cannot memorize a single batch, the problem is a bug, not a hyperparameter. That test, plus checking the initial loss (≈ ln V) and the gradient flow, catches most failures for minutes instead of a fortune.