6.6 Training loop and the autograd bigram
The four sections before this one give you every piece of a training run and no run. The digits MLP that closes this chapter needs batches drawn in a reproducible order, a step that does the things a step does in the right order, and an evaluation that does not train. And the tracer model that the engine has served since Byte bigram: counts, logits, safetensors v0 is still a table of counts: it cannot be improved, only recounted.
Concepts from other sections (19)
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.
- PCG32: an LCG whose output is a permutation (xorshift, then a state-chosen rotation) of the old state. Read more: 12.3 Modular arithmetic, hashing, and PCG32 in Python in Mathematics
- Decoupled weight decay (AdamW): multiplying the weights by outside the gradient path. Read more: 16.3 Adam and AdamW: bias correction and decoupled weight decay in Mathematics
- Standard deviation: , the typical distance of a random variable from its mean, in the same units as the variable itself. Read more: Chapter 13: Probability and Statistics in Mathematics
- Global norm: the Euclidean length of all gradients concatenated into one vector. Read more: 16.4 Learning-rate schedules (cosine, WSD, Noam) and gradient clipping in Mathematics
- Gradient norm: a measure of update magnitude before optimizer-specific scaling. Read more: 17.5 Training failures, profiling, and recovery
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- Upstream gradient: , the gradient arriving at an op’s output. Read more: 14.3 Matrix differentials, the trace trick, and closed-form VJPs in Mathematics
- Exponential moving average (EMA): the recursion , a weighted sum with geometric weights. Read more: 8.2 Series convergence, the EMA as a geometric series, and bias correction in Mathematics
- Dropout: randomly zeroing activations during training to approximate an ensemble of subnetworks. Read more: Chapter 2: Deep Learning
- 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
- Convex function: a function whose chords lie above its graph; every stationary point is a global minimum. Read more: 16.1 Convexity, smoothness, gradient descent, and Armijo line search in Mathematics
- Log-sum-exp (lse): the log of a row’s softmax denominator, kept so tiled kernels can merge partial results. Read more: 13.7 Sliding Windows and Attention Sinks
- token window: consecutive ids, split into inputs and targets shifted by one. Read more: 6.7 Safetensors for every dtype, atomic checkpoints, and the token stream
- Pairwise summation: recursive halving of a sum, with error growing like . Read more: 15.2 Stable numerics: logsumexp, softmax, and compensated sums in Mathematics
- gradient accumulation: summing the gradients of micro-batches weighted by to reproduce one large batch’s gradient. Read more: 17.1 Mixed precision, loss scaling, gradient accumulation, and activation checkpointing
- Maximum-likelihood estimate (MLE): the distribution that maximizes the log-likelihood; for counts, the frequency . Read more: 13.3 MLE, Laplace, absolute discounting in Mathematics
- Model zoo: the manifest-driven report that scores every model family in its own unit, one row per entry. Read more: 12.7 The evaluation harness and the model zoo
- loss scale: a power of two that multiplies the loss so that small fp16 gradients stay representable; divided out before the update. Read more: 17.1 Mixed precision, loss scaling, gradient accumulation, and activation checkpointing
- Gradient check: a comparison of an analytic gradient against the numerical one that reports pass or fail and the element furthest past its allowance. Read more: 10.1 Partial derivatives, gradients, and gradcheck in Mathematics
This section writes the loop every later model trains with, then retrains the tracer’s own table with it. If the loop is right, gradient descent finds the count model again, because the bigram problem has one minimum and the counts are it. That makes the bigram the most precise end-to-end test of the autograd there is: the answer is known to many digits. The section also moves the bigram’s sampler onto PCG32 with the Rust engine’s exact arithmetic, so a seed means the same text in Python and in Rust.
The section builds on everything earlier in the chapter: no_grad from Tensor, broadcasting backward, and no_grad, F.embedding from The op library and gradcheck_all, the losses of Losses with a fused backward, and Module and Linear from Module system and basic layers. From Mathematics it uses PCG32 (Modular arithmetic, hashing, and PCG32), SGD (The Optimizer protocol), AdamW (Adam and AdamW), clip_grad_norm_ (Learning-rate schedules and gradient clipping), and the EMA used for the smoothed loss (Series convergence, the EMA as a geometric series, and bias correction). The solution is loop.py (DataLoader, train_step, evaluate) and bigram.py, taken over from the byte bigram (its earlier version is in history/L0.0/), which adds BigramLogits (the table as a trainable Module), to_lm, and BigramLM.sample on PCG32. The train verbs live in cli_train.py. The contracts are loop.pyi and bigram.pyi.
The CLI uses this code for two verbs. train bigram --method autograd --data F --out DIR runs full-batch AdamW on every byte pair of F and writes the same model directory as the counting verb, from the trained table. train mlp --data digits.npz --hidden 64 --epochs 30 --ckpt DIR trains a two-layer ReLU MLP on the UCI digits through DataLoader, with each pixel standardized by the training set’s mean and standard deviation. --method counts remains the original counting verb.
Learning objectives
- Write a training step that zeroes, computes the loss, refuses a non-finite loss, backpropagates, clips, and updates, and explain why each step is in that place.
- Build a seeded data loader whose shuffle is the spec’s Fisher-Yates, fresh each epoch.
- Write an evaluation that weights batches by rows, runs in eval mode under
no_grad, and always restores the model’s mode.- Prove that the bigram’s minimum is the unsmoothed count model and compute its NLL floor by hand.
- Sample with the engine’s exact arithmetic so a seed gives the same ids in Python and Rust.
The pieces of a training run
Section titled “The pieces of a training run”The notation for this section:
| Symbol | Meaning | Type / shape |
|---|---|---|
| every parameter of the model | list of Tensor | |
| batch size; rows in the dataset | ints | |
the loss loss_fn returns, one element | Tensor | |
| learning rate | float | |
| gradient clipping threshold, global norm | float | |
| global gradient norm over all parameters | float | |
| the bigram table, row = logits after token | float32[V, V] | |
| , | bigram counts and row totals | |
| predictions in a text of tokens | int | |
| one uniform draw in from PCG32 | float |
The loader
Section titled “The loader”DataLoader(arrays, batch_size, shuffle, rng) holds named arrays that share their first dimension and yields dictionaries of rows. Without shuffle the order is . With shuffle, when each epoch starts it builds the list and calls rng.shuffle on it: the Fisher-Yates of spec/pcg32.md, going from the end and swapping with below(i + 1). Each epoch advances the generator, so epoch 2 has a new permutation and a seeded run repeats exactly. drop_last drops a final partial batch, so every step sees rows, and len(loader) says how many batches an epoch has. Arrays of different lengths, or a shuffle without a generator, are errors: one pairs inputs with the wrong labels, the other hides an unseeded order.
The step
Section titled “The step”train_step(model, batch, loss_fn, opt, clip) does seven things, in this order:
opt.zero_grad(). Gradients accumulate acrossbackwardcalls, so without this step trains on the sum of the gradients of steps .loss = loss_fn(model, batch): a one-element Tensor, or a pair(loss, {"acc": ...})of the loss and extra metrics. More than one element is an error, becausebackward()on a vector would need an upstream gradient nobody chose.- If the loss is not finite, raise
FloatingPointErrorbefore any update. Onenanstep turns every weight intonanand the run is lost; raising first lets the caller skip the batch. loss.backward().- With
clip,clip_grad_norm_(parameters, c)rescales all gradients together when . Report the norm before clipping, because that is the number that tells you training is unstable. opt.step(), then return{"loss": ..., "grad_norm": ...}plus the extra metrics.- With
ema(anEMA), feed the loss toema.updateand reportema.value_debiased()as"loss_ema". One batch’s loss is noise; the debiased EMA is the curve a training log plots, and without the correction its first steps sit near zero. A non-finite loss raised in step 3, so it never reaches the average.
Evaluation
Section titled “Evaluation”evaluate(model, loader, loss_fn) switches the model to eval mode (dropout off), runs every batch under no_grad (no graph, no stored activations), and averages the loss and metrics weighted by rows: a last batch of 2 rows counts as 2 rows, not as a full batch. It puts the model back in the mode it found it, in a finally, so an exception in a batch cannot leave a training run with dropout silently off.
The bigram, trained
Section titled “The bigram, trained”BigramLogits(V) is a Module with one parameter, weight of shape [V, V], starting at zeros (every next token equally likely, NLL ). Its forward is a row lookup, F.embedding(weight, ids): the logits onehot(ids) @ W of the counting bigram without the multiplications by zero, for ids of any shape (the trainer feeds [B, T] windows). Backward adds each position’s into its row.
Why gradient descent finds the counts
Section titled “Why gradient descent finds the counts”The mean NLL of the table on a text is
a sum over rows of convex functions (log-sum-exp is convex, is linear). Setting the gradient of row to zero gives , so at the minimum : the unsmoothed count model. Its NLL, , is the floor no bigram can beat on that text.
The add-one model of the counting bigram sits slightly above that floor; the trained table gets within nats of it, never below. Pairs that never occur push their logits toward forever, so the loss approaches the floor without reaching it. AdamW with a large learning rate gets there in a few hundred full-batch steps.
Sampling like the engine
Section titled “Sampling like the engine”BigramLM.sample keeps its signature and switches its generator: one PCG32(seed) (stream 54) per call, one uniform() per token, and the Rust engine’s draw from Your first endpoint. That draw computes weights of in float64, sums them in id order, and picks the first whose running sum exceeds . Same arithmetic, same order, same generator: generate --seed S and the engine’s completion with seed S give the same ids. to_lm() turns the trained module into a BigramLM holding a float32 copy of the table, the object the CLI saves as bigram.weight.
Working it by hand
Section titled “Working it by hand”Start with one training step. Take Linear(1, 1) with , ; the batch , ; loss mse; and SGD with .
- The predictions are , the residuals , and the loss .
- The gradients of are and .
- The update gives and .
- A second step must use only the new gradients. The residuals are , so and . A loop that forgot
zero_gradwould add the first step’s and . - With
clip=1, the global norm is . It is reported, and both gradients are scaled by before the update.
Now the bigram, from zeros. Take BigramLogits(3) on the text abbacab (ids [0, 1, 1, 0, 2, 0, 1], predictions).
- Every row of zeros has softmax , so the NLL is .
- Row
amakes three predictions (the next tokens areb,c,b). Each contributes , and the mean divides by 6: . Descent raises and lowers ; is already right on average. - The floor: row
agoes to twice and once (, ), rowbto and once each, rowcto always. The NLL is , below the add-one model’s .
These numbers are the first cases a correct solution must reproduce.
Designing the API
Section titled “Designing the API”class DataLoader: def __init__(self, arrays: Mapping[str, NDArray], batch_size: int, shuffle: bool, rng, drop_last: bool = True) def __iter__(self) -> Iterator[dict[str, NDArray]]; def __len__(self) -> intdef train_step(model, batch, loss_fn, opt, clip: Optional[float] = None, ema: Optional[EMA] = None) -> dict[str, float] # EMA from tinyllm.num.ema (M02.2)def evaluate(model, loader, loss_fn) -> dict[str, float] # mean loss, mean metrics, "n"
# python/tinyllm/lm/bigram.py (taken over from L0.0; BigramLM keeps its v0 API)class BigramLogits(Module): def __init__(self, vocab: int = 256); def forward(self, ids) -> Tensor; def to_lm(self) -> BigramLMA correct solution reproduces the hand-worked step (loss 1, gradients and , then and ), so everyone agrees on what a step is. The second step must use and alone, because gradients accumulate. With clipping, grad_norm is and the update uses the clipped gradients, which keeps long runs stable. A nan loss raises and no weight moves, so one bad batch cannot poison the run. (loss, metrics) pairs are reported, so accuracy can sit beside the loss, and a vector loss is an error. With , the losses 1 and 0.145 must report loss_ema 1.0 and 0.55, and a nan loss never reaches the EMA; that smoothed curve is what every later training log plots.
The loader must yield in-order batches with drop_last and len right, so evaluation sees every row once; its shuffle must be the spec’s Fisher-Yates, new each epoch, so the Go and Rust ports shuffle the same way; and unequal lengths or a shuffle without a generator must fail, to prevent silent mispairing. Evaluation must count a 2-row batch as 2 rows, run in eval mode under no_grad, and restore the mode, including after an exception, so validation numbers are honest (as The evaluation harness and the model zoo requires) and dropout cannot stay off.
Two learning checks exercise the whole stack: a 2-8-1 tanh MLP must solve XOR, which puts every piece of the chapter on one path, and minibatch AdamW with clipping must reach 95% accuracy on two moons, a real minibatch run. These two are judged against a loss bar, the solution’s own mean over five seeds plus three standard deviations, so a correct but differently ordered implementation still passes and a broken one does not. The same seed must give bitwise-identical weights and metrics, and another seed must differ, for resuming in Safetensors for every dtype, atomic checkpoints, and the token stream and for regression tests.
For the bigram: the hand-worked NLL and row a’s gradient show it trains the right rows; logits must be table rows for both 1-D and [B, T] ids, with bad ids failing, since the trainer feeds token windows; the autograd bigram must reach within nats of the count floor and never go below, which is the chapter’s end-to-end run in miniature; to_lm() must give the same logits through BigramLM.logits, as a copy, so the engine serves what was trained; and the sampled ids must equal the engine’s PCG32 draw at three temperatures, so Python and Rust agree on a seed.
Building it step by step
Section titled “Building it step by step”The reasoning chain
Section titled “The reasoning chain”- A step must use this batch’s gradient and nothing else.
backwardadds into.grad, so the step zeroes first. Puttingzero_gradat the start rather than the end also covers the first step after construction or after a failed batch. - A step must never write a non-finite update. The only cheap place to check is the loss value, before
backwardandopt.step. Ananloss givesnangradients, and oneopt.stepwith them destroys every weight. So: compute the loss, test it, raise if needed, and only then backpropagate. - Clipping sits between backward and step, because it rescales gradients that exist only after backward and must be applied before the optimizer reads them. The useful number to report is the norm before clipping: after clipping it is always at most and tells you nothing.
- Reproducibility comes from one generator and one algorithm. If the permutation is drawn from PCG32 with the spec’s Fisher-Yates, the Go and Rust ports shuffle identically, and drawing it when each epoch starts makes epoch 2 differ from epoch 1 while the whole run stays a function of the seed.
- Evaluation must not train and must not leak state. Eval mode turns dropout off;
no_gradbuilds no graph. Whatever happens inside, the mode must be restored, which forces atry/finally. Averages are over rows, so a short last batch is weighted by its size. - The bigram’s optimum is known. The loss is convex with the unsmoothed counts as its minimizer, with NLL on
abbacab. A table starting at zeros (NLL ) and trained by the loop must approach that floor from above. That makes the bigram a precise check of every piece of autograd in between. - Sampling must be the engine’s arithmetic, not just its distribution. Two correct samplers with different summation orders or different generators give different ids for one seed. Copying the engine’s exact recipe (one
PCG32(seed), oneuniform()per token, float64 weights summed in id order) is the only way to make a seed mean one text in both languages.
The loader
Section titled “The loader”All validation happens in the constructor, so a bad loader fails where it is built, not at the first batch.
class DataLoader: def __init__(self, arrays, batch_size, shuffle, rng, drop_last=True) -> None: if not arrays: raise ValueError("DataLoader needs at least one array") self.arrays = {k: np.asarray(v) for k, v in arrays.items()} lengths = {len(v) for v in self.arrays.values()} if len(lengths) != 1: # Unequal lengths would silently pair inputs with the wrong labels. raise ValueError(f"arrays have different lengths: {sorted(lengths)}") if batch_size < 1: raise ValueError(f"batch_size must be >= 1, got {batch_size}") if shuffle and rng is None: raise ValueError("shuffle needs an rng (a PCG32)") # no hidden unseeded order self.n = lengths.pop() # ... store batch_size, shuffle, rng, drop_last
def __iter__(self): order = list(range(self.n)) if self.shuffle: # Drawn when the epoch starts: each epoch advances the generator, # so epoch 2 differs from epoch 1 and a seeded run repeats exactly. self.rng.shuffle(order) # spec/pcg32.md Fisher-Yates (M06.3) idx = np.asarray(order, dtype=np.int64) b = self.batch_size stop = (self.n // b) * b if self.drop_last else self.n for i in range(0, stop, b): rows = idx[i : i + b] yield {k: v[rows] for k, v in self.arrays.items()} # same rows from every array
def __len__(self) -> int: return self.n // self.batch_size if self.drop_last else math.ceil(self.n / self.batch_size)Because __iter__ is a generator, the shuffle runs when a for loop starts, which is exactly “when each epoch starts”.
The loss contract
Section titled “The loss contract”One helper normalizes what loss_fn may return, used by both the step and evaluation.
def _split(out: Any) -> tuple[Tensor, dict[str, float]]: """loss_fn's result as (loss, extra metrics).""" loss, extra = (out[0], dict(out[1])) if isinstance(out, tuple) else (out, {}) if not isinstance(loss, Tensor): raise TypeError(f"loss_fn must return a Tensor (or a (Tensor, dict) pair), got {type(loss).__name__}") if loss.data.size != 1: # backward() on a vector would need an upstream gradient nobody chose. raise ValueError(f"the loss must have one element, got shape {loss.shape}") return loss, {k: float(v) for k, v in extra.items()}The step
Section titled “The step”The order of the lines is the content: zero, loss, finite check, backward, clip, step, report.
def train_step(model, batch, loss_fn, opt, clip=None, ema=None) -> dict[str, float]: # Zero first: gradients accumulate across backward calls (L0.1). opt.zero_grad() loss, extra = _split(loss_fn(model, batch)) value = float(np.asarray(loss.data).reshape(())) if not math.isfinite(value): # Stop before the update: one nan step would poison every weight. raise FloatingPointError(f"the loss is {value}; no parameter was updated") loss.backward() stats = {"loss": value} if clip is not None: # clip_grad_norm_ returns the norm *before* rescaling: the diagnostic. stats["grad_norm"] = float(clip_grad_norm_(model.parameters(), clip)) opt.step() stats.update(extra) if ema is not None: # One step's loss is noisy; the curve to read is its EMA (M02.2), # debiased so the first steps are not pulled toward m_0 = 0. ema.update(value) # never reached by a nan: we raised above stats["loss_ema"] = float(ema.value_debiased()) return statsOn the hand-worked example, value is 1, backward fills and , and with clip=1 the reported norm is while SGD sees and . For the EMA, with : after loss 1 the raw average is and the debiased one ; after it is .
Evaluation
Section titled “Evaluation”The finally is the reason this function is longer than a loop.
def evaluate(model, loader, loss_fn) -> dict[str, float]: was_training = model.training model.eval() # dropout off, everywhere (L0.4) sums: dict[str, float] = {} n = 0 try: with no_grad(): # no graph, no stored activations for batch in loader: loss, extra = _split(loss_fn(model, batch)) rows = len(next(iter(batch.values()))) # Weight by rows: a smaller last batch must count less. for k, v in {"loss": float(np.asarray(loss.data).reshape(())), **extra}.items(): sums[k] = sums.get(k, 0.0) + v * rows n += rows finally: model.train(was_training) # restored on success and on error if n == 0: raise ValueError("evaluate: the loader produced no batches") out = {k: v / n for k, v in sums.items()} out["n"] = float(n) return outIt restores was_training, not True: evaluating a model that was already in eval mode must leave it there.
The bigram as a module
Section titled “The bigram as a module”One parameter, zeros, and a gather.
class BigramLogits(Module): def __init__(self, vocab: int = 256) -> None: super().__init__() if vocab < 1: raise ValueError(f"vocab must be >= 1, got {vocab}") # Zeros: every next token starts equally likely (NLL ln V), and no # random init is needed for a convex problem. self.weight = Tensor(np.zeros((vocab, vocab)), requires_grad=True)
def forward(self, ids: ArrayLike) -> Tensor: # A row gather is the one-hot matmul without the zeros: same logits, # and backward adds each position's gradient into its row. Any shape # of ids: the trainer feeds [B, T] windows. F.embedding checks them. return F.embedding(self.weight, ids)
def to_lm(self) -> BigramLM: # A float32 copy: training can continue without changing the served model. return BigramLM(self.weight.data.astype(np.float32, copy=True))Zeros are safe here because the problem is convex: there is no symmetry to break, unlike a hidden layer, where identical rows would receive identical gradients forever.
The CLI’s train bigram --method autograd drives BigramLogits with full-batch AdamW at learning rate 0.5 and no weight decay, using cross_entropy on model(x) for every (byte, next byte) pair; see train_bigram_full_batch in cli_train.py.
Sampling like the engine
Section titled “Sampling like the engine”The sampler keeps the counting bigram’s signature; what changed is the generator and the draw.
def sample(self, prefix: list[int], n: int, temperature: float, seed: int) -> list[int]: # ... validate prefix (non-empty), n >= 0, temperature >= 0 cur = int(_as_ids(prefix, v)[-1]) # One generator per call, stream 54: the tracer engine's PCG32(seed, 54). rng = PCG32(seed) out: list[int] = [] for _ in range(n): row = self.logits([cur])[0].astype(np.float64) if temperature == 0: nxt = int(np.argmax(row)) # first maximum: ties go to the lowest id else: nxt = _draw(row, float(temperature), rng.uniform()) # one uniform per token out.append(nxt) cur = nxt return out
def _draw(row: NDArray, temperature: float, u: float) -> int: """The tracer engine's draw (L10.0): weights exp(z - max z) of z = row / temperature in f64, summed in id order, NaN never picked; the first id whose running sum exceeds u * total.""" z = [float(x) / temperature for x in row] finite = [x for x in z if not math.isnan(x)] m = max(finite) if finite else -math.inf w = [0.0 if math.isnan(x) or m == -math.inf else math.exp(x - m) for x in z] total = 0.0 for wi in w: # a plain left-to-right sum, as the Rust loop does total += wi target = u * total cum, last = 0.0, 0 for i, wi in enumerate(w): if wi > 0.0: cum += wi last = i if cum > target: return i return last # rounding left target unreached: the last live idThe explicit Python loops are deliberate: np.sum uses pairwise summation, which can round differently from the engine’s sequential sum and move the chosen id at a boundary.
The full solution is loop.py and bigram.py, which also keeps BigramLM’s fit_counts, logits, and nll from the counting version.
Why this design
Section titled “Why this design”One step is one forward, one backward, and for clipping and the update; the loop adds nothing asymptotic. The loader’s shuffle is per epoch, and fancy indexing copies one batch at a time, so memory stays at the dataset plus one batch. The bigram’s forward is a gather, , instead of the one-hot matmul’s . (The tracer’s C matmul tl_matmul_f32, from Vectors, matrices, row-major layout, and matmul and the kernels chapter, is not needed here: BigramLM.logits reads the same rows with a NumPy gather.)
Each alternative fails in a specific way. Shuffling by argsort of uniforms is a correct random permutation but not the spec’s, so the ports would disagree. Checking for nan after opt.step detects the problem one step too late. Averaging batch means in evaluate is simpler and biased whenever the last batch is short. Sampling with np.random.choice gives the right distribution and the wrong ids.
Two tradeoffs are accepted. The step has no gradient accumulation, mixed precision, or schedule; later chapters add those around it rather than inside it. And grad_norm is reported only when clipping is on, because computing a global norm costs a pass over every gradient.
What can go wrong
Section titled “What can go wrong”| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
no zero_grad at the start of the step | the loss falls, then oscillates: every step adds all earlier gradients | opt.zero_grad() is the first line of train_step |
| evaluation that averages batches, leaves dropout on, or restores the mode only on success | validation loss biased by the last batch; noisy evaluations; training after a failed eval with dropout off | sums v * rows and divides by total rows; model.eval() then model.train(was_training) in finally |
| shuffling by sorting uniforms, or one permutation for every epoch | runs are not reproducible across languages, or every epoch sees the same order | rng.shuffle(order) (the spec’s Fisher-Yates) inside __iter__, once per epoch |
checking the loss for nan after the update | the run is already lost when the error is raised | math.isfinite(value) is tested before backward and opt.step |
| a new generator for every token, or a stream other than the engine’s | Python and Rust disagree on the same seed; repeated draws of the same | one PCG32(seed) (stream 54) per call, one uniform() per token, the engine’s _draw |
Warning: A sampler can be statistically perfect and still fail to match the engine. Summation order and generator choice change which id a given selects at a boundary, so copy the engine’s arithmetic exactly.
Where this leads
Section titled “Where this leads”This section is where the chapter closes end to end: together with the next section, the autograd bigram reaches the count MLE and the digits MLP trains through the loader. The Rust engine of Your first endpoint serves the table to_lm() produces, unchanged (tl_arch = bigram). Safetensors for every dtype, atomic checkpoints, and the token stream takes over safetensors.py and keeps the counting behaviour of bigram.py as its regression.
Later chapters call train_step and evaluate as they are. The NPLM of Bengio’s neural probabilistic language model and the encoder-decoder Transformer train through DataLoader and train_step; the RNN language model trains through train_step; GPT pre-training calls train_step each step, as does the capstone; and the model zoo of The evaluation harness and the model zoo loads the bigram as a BigramLM and scores it with the others.
Further reading
Section titled “Further reading”- Karpathy, “A Recipe for Training Neural Networks” (2019, free).
- Goodfellow, Bengio, Courville, Deep Learning, ch. 8.
torch.utils.data.DataLoader(torch/utils/data/dataloader.py): worker processes, pinned memory, samplers, and ageneratorargument for seeded shuffles.- Hugging Face
Trainer.training_step(transformers/trainer.py) and Lightning’sLightningModule: mixed precision, gradient accumulation, distributed reduction, and callbacks. torch.cuda.amp.GradScaler(torch/amp/grad_scaler.py): skips steps withinfgradients and lowers the loss scale, as in mixed-precision training.- vLLM’s per-request seeded sampling (vLLM
v1/sample/sampler.py): a generator per request on GPU, with the same draws across batch compositions.
Key terms
Section titled “Key terms”- training step: one zero-grad, loss, finiteness check, backward, clip, and optimizer update on one batch.
- global gradient norm: the square root of the sum of squares of every gradient entry across all parameters.
- gradient clipping: rescaling all gradients together when their global norm exceeds a threshold.
- Fisher-Yates shuffle: the in-place permutation algorithm that swaps each position , from the end, with a uniformly chosen position at or below it.
- debiased EMA: an exponential moving average divided by so its early values are not pulled toward zero.
- NLL floor: the NLL of the unsmoothed count model, the minimum any bigram can reach on a given text.
Summary
Section titled “Summary”- One training step is zero the gradients, compute the loss, refuse a non-finite loss, backpropagate, clip, update: in that order, every time.
- Data order comes from the seeded PCG32 through the spec’s Fisher-Yates shuffle, a fresh permutation each epoch, so two runs with one seed are bitwise identical.
- Evaluation weights every batch by its rows, runs in eval mode under
no_grad, and always hands the model back in the mode it found it. - The bigram is a convex problem whose minimum is the unsmoothed count model; the autograd-trained table reaches its NLL within nats.
samplenow draws exactly as the Rust engine does, so a seed gives the same text in Python and Rust.
Review questions
Section titled “Review questions”-
Why does
train_stepcallopt.zero_grad()at the start instead of afteropt.step()?Answer
Between two normal steps either placement works. Zeroing at the start makes the step independent of whatever ran before it: a freshly built model, a gradient check or a manual
backwardin a notebook, or a previous step whoseopt.stepraised afterbackward. The step’s contract becomes “the update uses this batch’s gradient”, with no assumption about the caller. -
Why is the finiteness check on the loss value and not on the gradients?
Answer
A non-finite loss is the first observable symptom and is one number, so it is checked before any work is done. Checking gradients would need a pass over every parameter and still has to happen before
opt.step. Raising beforebackwardalso keepsnanout of the EMA and the moment buffers. -
In
evaluate, why restorewas_trainingin afinallyinstead of callingmodel.train()at the end?Answer
An exception in any batch would skip a trailing
model.train(), leaving a training run with dropout silently off. Andmodel.train()would wrongly switch on a model that was in eval mode before the call. Restoring the saved flag infinallyis right in both cases. -
Why can
BigramLogitsstart from zeros when an MLP cannot?Answer
The bigram loss is convex in with a unique optimum (the counts’ softmax), so any start reaches it, and zeros give the honest NLL . In an MLP, hidden units with identical weights get identical gradients and stay identical; random init is what breaks that symmetry.
-
What breaks if
samplecreated a newPCG32(seed)for every token?Answer
Every token would use the same first
uniform(), so the sampler would repeat the same quantile of each row’s distribution, and it would no longer match the engine, which draws a fresh per token from one generator. A seed would mean different text in Python and Rust. -
On
abbacab, why can the trained bigram approach an NLL of but never go below it, while the add-one model sits at ?Answer
is the NLL of the unsmoothed count model, which is the unique minimizer of the convex bigram loss, so no table can do better. The add-one model is a different table (smoothed toward uniform), so its NLL is higher. Training approaches the floor from above without reaching it, because the logits of pairs that never occur keep moving toward .