Chapter 6: Numerics and Autograd
Every model in this book, from a bigram to a Llama-family decoder, rests on the same small stack of machinery: a way to represent a model’s weights, a way to compute gradients through any expression, a library of differentiable operations and losses, a way to organize parameters into named layers, a loop that trains them, and file formats that save the result so other programs can load it. This chapter builds that stack from scratch in Python and NumPy.
Concepts from other sections (17)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Byte-level: the base alphabet is the 256 bytes (through the byte map), so every text encodes and there is no unknown token. Read more: 7.2 Byte-level BPE
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- row gather: indexing a table by ids to select rows, equivalent to multiplying by one-hot vectors. Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- safetensors: a checkpoint format of an 8-byte header length, a JSON header, and raw little-endian row-major tensor bytes. Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- fused loss: a loss implemented as one graph node with a closed-form gradient, instead of a chain of ops. Read more: 6.4 Losses with a fused backward
- negative log-likelihood (NLL): the mean of over the predicted tokens, in nats per token. Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- Cumulative distribution function (CDF): , defined for every random variable, discrete or continuous; it rises from 0 to 1, and for a continuous variable its derivative is the density. Read more: Chapter 13: Probability and Statistics in Mathematics
- vector-Jacobian product (VJP): the function mapping an output gradient to input gradients without forming the Jacobian. Read more: 6.2 Tensor, broadcasting backward, and no_grad
- reverse topological order: an ordering in which every node comes after all of its consumers, so its gradient is complete when it is processed. Read more: 6.2 Tensor, broadcasting backward, and no_grad
- grad mode: a per-thread flag that controls whether ops record a graph;
no_gradturns it off and restores it. Read more: 6.2 Tensor, broadcasting backward, and no_grad - stable softmax: softmax computed after subtracting the largest logit, so
expnever overflows. Read more: 25.6 Usage policy enforcement - inverted dropout: zeroing elements with probability and scaling survivors by during training, so evaluation is the identity. Read more: 6.3 The op library and gradcheck_all
- Cross-entropy: , the average surprise when data from are predicted with . Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator in Mathematics
- label smoothing: mixing the one-hot target with a uniform distribution over all classes, weight . Read more: 6.4 Losses with a fused backward
- training step: one zero-grad, loss, finiteness check, backward, clip, and optimizer update on one batch. Read more: 6.6 Training loop and the autograd bigram
- BF16: a 16-bit float with float32’s sign and exponent and 7 mantissa bits; the top half of a rounded float32. Read more: 6.7 Safetensors for every dtype, atomic checkpoints, and the token stream
- F8_E4M3 (fn): an 8-bit float with 4 exponent bits (bias 7) and 3 mantissa bits, no infinity, maximum 448, NaN only at . Read more: 6.7 Safetensors for every dtype, atomic checkpoints, and the token stream
The chapter opens with the smallest real language model: a byte-level bigram fitted by counting, whose logits come from a NumPy row gather and whose weights are written as a safetensors checkpoint that the Rust engine serves. That one model gives every other layer of the system something to carry. The rest of the chapter then builds an autograd engine and retrains the same bigram with it, behind the same checkpoint format. Because the bigram’s optimum is known exactly (it is the count model), gradient descent finding it again is the most precise end-to-end test of the autograd there is. The chapter closes with every dtype the book needs, crash-safe checkpoints, and a memory-mapped token stream that resumes bit for bit.
Learning objectives
- Fit, evaluate, and sample a byte-level bigram language model, and write it as a safetensors file byte-identical to the reference library’s.
- Build reverse-mode autograd on NumPy arrays, including broadcasting, repeated indices, and
no_grad.- Implement and gradient-check a library of differentiable ops and fused losses, with stable numerics and correct padding rules.
- Organize parameters into modules whose names match PyTorch’s, and save and load them in place.
- Write a reproducible training loop, crash-safe checkpoints, and a token stream that resumes exactly.
Before you begin
Section titled “Before you begin”You should be comfortable with Python and NumPy from Programming and Algorithms (arrays, dtypes, broadcasting, views versus copies, uv projects) and with Vectors, matrices, row-major layout, and matmul from Mathematics. The autograd sections also draw on Scalar reverse mode: the Value graph and Matrix differentials, the trace trick, and closed-form VJPs, and the training loop on the optimizers of Adam and AdamW. Each section names the exact pieces it uses as it goes.
In this chapter
Section titled “In this chapter”- Byte bigram: counts, logits, safetensors v0. The smallest real language model: a smoothed count table, its negative log-likelihood, temperature sampling by inverse CDF, and a canonical safetensors writer and strict reader.
- Tensor, broadcasting backward, and no_grad. Reverse-mode autograd on arrays: one VJP per op, reverse topological order, why broadcasting and repeated indices mean summed gradients, and a grad mode that nests and survives exceptions.
- The op library and gradcheck_all. Activations, reductions, shape and selection ops, the stable softmax family, and inverted dropout, each with one closed-form VJP, plus a gradient checker strong enough to fail.
- Losses with a fused backward. Cross-entropy as one graph node with gradient ,
ignore_indexand label smoothing done right, and stable MSE and binary cross-entropy, with a test suite that pins them down. - Module system and basic layers. Parameter registration by assignment, PyTorch-compatible names, all-or-nothing in-place loading, and
Linear,Embedding,LayerNorm,Dropout, and the containers. - Training loop and the autograd bigram. A seeded data loader, a training step in the right order, honest evaluation, and the bigram retrained by gradient descent to the count model’s NLL, sampling exactly as the Rust engine does.
- Safetensors for every dtype, atomic checkpoints, and the token stream. BF16 and F8_E4M3 with round to nearest even, a checkpoint protocol that survives a crash at any instant, and llm.c token shards read through a memory map with an exact cursor.