Chapter 04
How Training Changes the Model
On this page
Training changes the arrays used by the forward computation. We can understand an update by tracing the error from a predicted token back to the weights, then asking how examples, batch size, and numerical precision affect that update.
From a wrong probability to an update¶
Return to the two-token example from Chapter 2. Both logits are zero, so both probabilities are 0.5. The observed target is token 0. We want the next update to increase its probability, but we need more than the statement that the answer was wrong: we need a direction and magnitude for changing each parameter.
For target y, cross entropy can be written as -z_y + log(sum(exp(z_i))). Differentiating with respect to logit z_i gives p_i - indicator(i=y). In our example, the gradient is [-0.5,0.5]. Subtracting 0.1 times that gradient changes the logits to [0.05,-0.05]. The target probability rises to about 0.525.
That calculation treats logits as adjustable values. In a transformer they are outputs of the computation we just traced. Backpropagation uses the chain rule to carry the loss gradient through the output projection, decoder layers, and embedding lookup. The resulting gradient has one component for each trained parameter. A forward pass computes predictions; a backward pass computes how changing parameters would change the loss locally.
With weights denoted by theta, gradient g, and learning rate eta, stochastic gradient descent applies:
The learning rate controls the size of the parameter update along the negative gradient.
The local qualification matters. A gradient describes the slope near the current weights. A sufficiently large step can move beyond the region in which that direction helps. Nor does improvement on one batch establish improvement on new questions. Those are reasons to monitor a separate validation set rather than treating every decrease in training loss as progress toward the application.
A small model we can train completely¶
The companion Bigram model replaces the transformer with a table. Each row corresponds to one input character, and each column is a logit for the next character. It remembers only the preceding character. That severe limitation makes every parameter and gradient visible, while preserving the next-token objective.
Training on ababa and babab should make b more likely after a and a more likely after b. We do not need a neural-network framework to compute the exact table gradient. The example below uses two microbatches with unequal numbers of targets, combines their gradients, clips their norm, and performs one update. The following sections explain those choices.
Example status: Runnable excerpt; execute from the repository root.
from math import hypot
from examples.tiny_lm import Bigram
from examples.training_step import accumulated_gradient
model = Bigram("ab")
microbatches = [["ab"], ["ababa", "babab"]]
before, gradient = accumulated_gradient(model, microbatches)
norm = hypot(*(g for row in gradient for g in row))
max_norm, learning_rate = 0.25, 0.1
factor = min(1.0, max_norm / norm) if norm else 1.0
model.logits = [
[w - learning_rate * factor * g
for w, g in zip(row, grad_row)]
for row, grad_row in zip(model.logits, gradient)
]
batch = [s for microbatch in microbatches for s in microbatch]
after, _ = model.loss_and_gradient(batch)
assert abs(before - 0.693147) < 1e-6
assert abs(after - 0.680650) < 1e-6
print(f"loss: {before:.6f} -> {after:.6f}")
The loss falls from approximately 0.693147 to 0.680650. This is a measurement of this small update, not a promise that every batch or learning rate reduces loss. examples/training_step.py also provides a checked update function, while python -m examples.tiny_lm trains, saves, restores, and generates with the complete bigram model. Part IX's primary lab instead uses the attention decoder introduced in Chapter 3. A transformer changes the prediction function and the backward computation; it does not change the basic distinction between examples, loss, gradient, and update.
A forward pass and a backward pass produce an update. The next step uses the new weights; an adaptive optimizer also carries its own state between steps.
Choose the averaging unit deliberately¶
A microbatch is the set of examples processed in one forward/backward pass. Gradient accumulation combines several such passes before updating weights. It lets a larger effective batch be processed without keeping every example's activations in memory at once.
Our first microbatch has one target, and the second has eight. If the objective is mean loss per supervised token, their mean gradients must receive weights 1/9 and 8/9. Giving each microbatch weight one half would optimize a different objective. The same mistake occurs when workers with unequal target counts average their local means without compensating for those counts.
At fixed sequence shapes, the number of sequences per global update is:
Multiply sequences per microbatch by accumulation rounds and data-parallel workers.
For two sequences, eight accumulation rounds, and four workers, the result is 64 sequences per update. For variable-length examples, record supervised token counts as well. Those counts determine the normalization of a token-mean loss. Part V derives the reduction rules when the batch is distributed across workers.
Increasing the global batch also reduces the number of updates made for a fixed token budget. Warmup and learning-rate decay therefore need a declared unit: tokens, updates, or elapsed time. Two runs with equal “step counts” may have processed different amounts of data. Part II uses these quantities to design and compare complete training recipes.
Why an optimizer carries state¶
Plain SGD uses the current gradient. Momentum also uses a moving average of previous gradients, allowing a persistent direction to survive noisy individual batches. Adam adds a moving average of squared gradients to estimate a scale for each coordinate. For the first and second moments:
The first moment averages recent gradients, element by element.
The second moment averages squared gradients, element by element.
The square in the second equation is not a matrix product. Both arrays have one value per trained parameter. Starting the arrays at zero biases early averages toward zero, so Adam corrects them by dividing by 1-beta_1^t and 1-beta_2^t, with the first update numbered one. For a first gradient of 2, beta values 0.9 and 0.99 give raw moments 0.2 and 0.04 but corrected moments 2 and 4.
AdamW uses these corrected moments and applies a separate weight shrinkage:
The superscript c denotes bias correction; lambda controls decoupled weight decay.
Adam and decoupled weight decay supply the underlying methods. For our systems purposes, notice the consequence: weights alone do not describe the next training update. The optimizer moments and schedule position matter too. Saving weights is enough to run a fixed model, but resuming the same training trajectory requires additional state.
Keep the update numerically usable¶
Gradient clipping limits the norm of a finite gradient. For threshold c>0, scale a nonzero gradient by min(1,c/norm(g)); leave a zero gradient unchanged. A gradient [3,4] has norm 5 and becomes [1.2,1.6] at threshold 2. Clipping preserves its direction while reducing its magnitude.
The bigram example's gradient norm is about 0.503077. Clipping to 0.25 and using learning rate 0.1 makes the plain-SGD update norm 0.025. This bound does not carry over unchanged to AdamW, whose moments, adaptive scaling, and decay also affect the update. Frequent clipping is something to investigate, not evidence that the source of instability has been fixed.
Precision is another separate choice. Weights, activations, gradients, and optimizer moments need not use the same numerical format. BF16 has FP32's exponent range with fewer significand bits; FP16 has a narrower exponent range. Low-precision matrix operations can save storage and transfer work, while sensitive reductions and optimizer state often use FP32.
For FP16 training, loss scaling can move small gradients into a representable range. Multiply the loss before backward computation, then unscale gradients before checking or clipping their norm. A non-finite gradient must not quietly become an ordinary update. In a distributed run, workers must agree on whether the step happened; otherwise their model and optimizer states diverge. The implementation details belong in the distributed training chapters and the framework's mixed-precision examples.
Diagnose a failed training step¶
Suppose loss suddenly rises. The forward computation tells us where to start: compare the batch, target shift, and loss mask with a known good step. The backward computation adds gradient norms, clipping, and overflow checks. The update adds learning rate, moments, and restored schedule state. Keeping these observations together is more useful than seeing a final NaN without its history.
A successful update is still different from a useful training program. For structured extraction, we need held-out messages to test whether learned formatting and interpretation transfer to new inputs. For code generation, a lower training loss does not establish that proposed programs work. Part II uses task evidence to choose training data and stages; Chapter 7 establishes how to compare the resulting systems.
We can now hold the trained weights fixed and return to generation. The next problem is computational: how do we avoid repeating the entire prefix computation for every new token?
Exercises and worked answers¶
- Why are the example's microbatch gradients weighted by one ninth and eight ninths? Those are their shares of the supervised targets. Equal microbatch weights would give the single target too much influence.
- What is missing from a weights-only training checkpoint? At least optimizer and schedule state; reproducible continuation also needs data position and relevant random and numerical state. Part V develops a complete checkpoint protocol.
- A run's steps become 20% faster but it needs 30% more steps at equal batch size. Is it faster to the same loss? No.
0.8*1.3=1.04: it takes about 4% longer before other overheads. - Why test on examples outside the training batch? The update explicitly optimizes that batch. Separate examples provide evidence about whether the learned change transfers beyond it.
Train attention and reproduce the next update¶
The bigram exercise makes its entire parameter table inspectable. The decoder lab supplies the missing next step: attention, residual transformations and a real optimizer update use the same shifted-target objective. batch() returns two seven-position rows with respectively one and two scored targets. These are ordinary batch rows, not concatenated packed documents. The reference compares one batched gradient with two row-wise accumulated gradients, each divided by the same total of three targets, and then compares their SGD updates. It does not claim segment-packed equivalence.
Example status: Optional PyTorch example; run with requirements-experiments.txt installed.
from examples.decoder_lab import Decoder, batch, loss_sum
import torch
torch.manual_seed(2718)
model = Decoder().double()
x, y, mask = batch()
optimizer = torch.optim.AdamW(model.parameters(), lr=0.01)
optimizer.zero_grad(set_to_none=True)
logits, _ = model(x)
objective = loss_sum(logits, y, mask) / mask.sum()
objective.backward()
optimizer.step()
loss_sum computes unreduced cross entropy at each aligned position, multiplies by the target mask and sums. A zero target mask removes that position's direct logit-loss derivative; it does not remove the token from earlier context or prohibit gradients through its embedding into later scored predictions. The lab asserts both zero direct gradients on unscored logits and nonzero gradients on scored logits. Confusing these two statements produces an incorrectly masked attention computation.
After forty updates, the program serializes model weights, AdamW moments and step, RNG state, and a data cursor. It loads a fresh model and optimizer, applies the same next batch, and compares both parameters and optimizer moments. This is stronger than comparing logits immediately after loading weights. The fixture has deterministic batches and no dropout; a stochastic loader or augmentation pipeline needs its own recoverable state. The loss reduction demonstrates fitting these two sequences, not useful task generalization.
The final experiment freezes a linear base and initializes a low-rank residual with a zero output factor. Its initial output equals the base. On the first backward pass, the zero factor blocks the other factor's gradient; after the optimizer changes it, the output changes while the base stays fixed. This explains the adapter initialization through the actual gradient path before Part II considers adapting a full language model.