Highlights

Contents

Part XIII
13

Training: From Random Numbers to a Model

A decoder learns through repeated predictions and corrections. Loss measures its miss and gradients describe a local improvement. The optimizer, schedule, validation, and reproducibility policy determine how those corrections become a useful model.

YOU ARE HERE"raw text"tokenizerembeddings+ positionslearnedwavesRoPEDECODER BLOCK× NnormattentionQKVsoftmaxmaskheadsn × n+normMLP+residual streamKV cachefinal normLM headsoftmaxP(next)training: the loss sends a correction back to every weight

#Section 69One Loop, Repeated Many Times

Training takes a batch, runs forward to obtain predictions, computes a loss, then runs backward to find the gradient. The optimizer updates the weights. Clearing stored gradients prevents unintended accumulation into the next step.

ONE TRAINING STEP, SIX MOVES, REPEATED TENS OF THOUSANDS OF TIMES1. batchx, y = next_batch()2. forwardlogits = model(x)3. losscross_entropy(logits, y)4. backwardloss.backward()5. stepoptimizer.step()6. zerooptimizer.zero_grad()predict, measure,blame, nudge
Figure 1.95One training step. Every model you have heard of was trained by running these six moves over and over, with the line of code for each move beside it.

The remaining sections explain the objective, update, stability controls, and reproducibility.

#Section 70Measuring a Miss: Cross-Entropy

At every position the model outputs a probability for each of the 32,000 tokens. We know the correct next token. The loss used for language models is cross-entropy. For one position, it is minus the natural logarithm of the probability assigned to the correct token.

loss=−ln⁡p(correct token)\text{loss} = -\ln p(\text{correct token})

Cross-entropy rises as the correct token's probability falls, penalizing confident mistakes strongly. Its natural-log unit is the nat; conversion to bits changes the unit, not the prediction.

p(correct token)loss = −ln pp = 0.9 → 0.11p = 0.5 → 0.69p = 0.1 → 2.30p = 0.01 → 4.6100.51confident and wrong:the loss explodesconfident and right:loss near zero
Figure 1.96The cross-entropy loss for one position. Near p = 1 it is almost zero; as p falls toward zero it climbs steeply. Being confidently wrong is very expensive.

Average loss over supervised positions. Perplexity exponentiates that average, expressing uncertainty on a different scale. An initially near-uniform distribution provides a useful sanity check.

#Section 71Gradients: Which Way Is Downhill

Picture the loss as hilly terrain. Every possible setting of the 42 million weights is a point, and the loss at that point is the height. Training is walking downhill toward low ground. The gradient tells you the slope under your feet: for each weight, how much the loss would change if you nudged that weight up a tiny bit. A negative slope for a weight means increasing it lowers the loss; a positive slope means decreasing it does.

Take a toy loss with one weight, L(w)=(w−3)2L(w) = (w - 3)^2, whose lowest point is at w=3w = 3. Standing at w=1w = 1, the loss is 4 and the slope is 2(w−3)=−42(w - 3) = -4. The slope is negative, so we should increase ww. Gradient descent takes a step against the slope, scaled by a small number called the learning rate, η\eta (eta):

w←w−η ∂L∂ww \leftarrow w - \eta \, \frac{\partial L}{\partial w}

With η=0.1\eta = 0.1: w←1−0.1×(−4)=1.4w \leftarrow 1 - 0.1 \times (-4) = 1.4. The loss drops from 4 to 2.56. Repeat, and ww creeps toward 3. The symbol ∂L/∂w\partial L / \partial w is the partial derivative, mathematician's notation for "the slope of LL in the direction of ww, holding everything else fixed".

A GRADIENT IS A SLOPE: WHICH WAY IS DOWNHILL, AND HOW STEEP (TOY LOSS (w − 3)²)weight wlossw = 1, loss = 4, slope = −4step: w − 0.1 × (−4) = 1.4minimum0123456negative slope:increase w
Figure 1.97A gradient is a slope. At w = 1 the slope of (w − 3)² is −4, so a step against it with learning rate 0.1 moves w to 1.4, closer to the minimum at 3.

Backpropagation follows the computation backward, combining local derivatives to find each weight's effect on the loss. PyTorch records the forward graph and computes this with loss.backward(). Residual additions provide a direct gradient route alongside each sub-layer.

#Section 72How Big a Step, and Which Direction

The learning rate

A small learning rate moves slowly; a large one can overshoot and diverge. The figure illustrates that trade-off on a simple loss surface.

SIX STEPS ON (w − 3)² FROM w = 1 AT FOUR LEARNING RATESlr = 0.01too small: crawlsw₆ = 1.23lr = 0.1reasonablew₆ = 2.48lr = 0.45fast: lands in 3 stepsw₆ = 3.00lr = 1.1too big: divergesw₆ = -2.97
Figure 1.98Six steps from the same start at four learning rates. Too small crawls, well chosen converges, too big overshoots further on every step.

Real loss surfaces are more complicated. Choose a learning rate by controlled experiments, rather than treating a toy optimum as a model default.

Adam and AdamW

Plain gradient descent, often called SGD (stochastic gradient descent, "stochastic" because each batch is a random sample of the data), uses the same learning rate for every weight. That works badly in long, narrow valleys, which are common in real models: the steepest slope points mostly across the narrow side, so SGD zig-zags from wall to wall and makes slow progress along the valley floor.

Adam, introduced by Diederik Kingma and Jimmy Ba in 2014, fixes this by keeping two running averages for every weight: mm, the average of recent gradients (which direction it has been pushed lately), and vv, the average of recent squared gradients (how large its pushes usually are). Each step moves the weight by m/vm / \sqrt{v}, scaled by the learning rate.

m←β1m+(1−β1) gv←β2v+(1−β2) g2w←w−η m^v^+εm \leftarrow \beta_1 m + (1 - \beta_1)\, g \qquad v \leftarrow \beta_2 v + (1 - \beta_2)\, g^2 \qquad w \leftarrow w - \eta \, \frac{\hat m}{\sqrt{\hat v} + \varepsilon}

Here gg is the current gradient for this weight, β1\beta_1 and β2\beta_2 (typically 0.9 and 0.95 for language models) control how long the averages remember, and m^\hat m, v^\hat v are the averages with a small correction for their first few steps. Dividing by v\sqrt{v} means a weight whose gradients are usually huge takes cautious steps and a weight whose gradients are usually tiny takes bolder ones. The zig-zag across the valley, where gradients are large and alternate in sign, gets damped; the steady push along the valley floor accumulates in mm.

A NARROW VALLEY: PLAIN GRADIENT DESCENT ZIG-ZAGS, ADAM HEADS DOWN THE VALLEY (ILLUSTRATIVE)startSGD: bounces wall to wallAdam: per-weight step sizes
Figure 1.99In a long, narrow valley, plain gradient descent bounces from wall to wall while Adam's per-weight step sizes head down the valley. (Illustrative.)

AdamW, introduced by Loshchilov and Hutter in 2017, applies weight decay separately from the adaptive gradient update. The shrinkage discourages unnecessary weight growth; optimizer history adds memory cost.

ADAMW MEMORY: EVERY WEIGHT HAS COMPANYweights4 bytes / weight160.707 MiBgradients4 bytes / weight160.707 MiBfirst moment m4 bytes / weight160.707 MiBsecond moment v4 bytes / weight160.707 MiB42,128,384 × 16 = 674,054,144 bytesthe weights alone are only a quarter of this bill
Figure 1.100Finch-19 has 42,128,384 parameters. In fp32, weights, gradients and the two AdamW moments each take 168,513,536 bytes, or 160.707 MiB rounded to three decimals. Together they take 674,054,144 bytes. This ledger excludes activations and other runtime storage.

#Section 73Warmup, Decay and Clipping

The schedule

Warmup limits early updates while optimizer state settles. Later decay reduces step size as training progresses. The schedule's boundaries and units must match the implementation.

FINCH-19’S SCHEDULE: 200 WARMUP STEPS TO 6e-4, COSINE DECAY TO 6e-5 AT STEP 10,000steplearning ratewarmup3.4e-46.0e-502,5005,0007,50010,000big steps early,small steps to settle
Figure 1.101Linear warmup, then cosine decay. Big steps early when there is far to go, small steps late to settle.

Gradient clipping

Sometimes a batch produces a huge gradient, from an odd example or a numerical spike, that would send the weights flying. Gradient clipping caps the total length of the gradient vector at a threshold cc:

g←g⋅min⁡ ⁣(1,c∥g∥)g \leftarrow g \cdot \min\!\left(1, \frac{c}{\lVert g \rVert}\right)

Clipping leaves small gradients unchanged and rescales an oversized combined gradient without changing its direction. It limits the update rather than repairing an invalid gradient.

GRADIENT CLIPPING: SAME DIRECTION, LENGTH CAPPED AT c = 1cap c = 1g, length 5g = [4, 3], ‖g‖ = 5scale = min(1, c / ‖g‖) = 0.2clipped g = [0.8, 0.6], length 1one odd batch cannotfling the weights away
Figure 1.102Gradient clipping keeps the direction and caps the length. A gradient of length 5 becomes length 1.
Finch-19's recipe Value
Batch 256 sequences × 1,024 tokens = 262,144 tokens
Steps 10,000 (about 2.6 billion tokens)
Optimizer AdamW, β1=0.9\beta_1 = 0.9, β2=0.95\beta_2 = 0.95, weight decay 0.1
Learning rate warmup 200 steps to 6×10−46 \times 10^{-4}, cosine to 6×10−56 \times 10^{-5}
Gradient clipping total norm 1.0
Precision bf16 compute, fp32 master weights and optimizer state

#Section 74Reading Loss Curves

To diagnose training, plot loss against steps with two curves. The training loss is measured on the batches the model is learning from. The validation loss is measured on held-out text the model never trains on.

Early on both fall fast, from about 10.37 toward 3. Then they flatten. If training continues long enough on data that is small compared to the model, the validation loss stops falling and starts rising while the training loss keeps going down. That is overfitting: the model has begun memorizing its training text instead of learning patterns that carry over to new text. The best checkpoint to keep is the one where validation loss was lowest.

TRAINING LOSS FALLS; VALIDATION LOSS TURNS UP ONCE THE MODEL MEMORIZES (ILLUSTRATIVE)training step (×100)lossbest checkpointtrainingvalidationstart ≈ ln 32,000 = 10.37
Figure 1.103Training and validation loss. Both fall from about ln 32,000; when the model starts memorizing, validation turns upward. Keep the checkpoint at the validation minimum. (Illustrative.)

Large language models usually see each piece of text only once or a few times, so they barely overfit; their curves just flatten. Small experiments, fine-tuning on small datasets, and Finch-sized models trained for many passes over a small corpus overfit all the time. Two other shapes are worth recognizing. A loss that suddenly jumps up mid-training and then slowly recovers is a loss spike, usually from an odd batch or a learning rate that is too high. A loss that sits flat at ln⁡V\ln V and never moves usually means the gradients are not reaching the weights at all, from a detached tensor, a learning rate of zero, or a broken mask.

#Section 75Running It Twice: Reproducibility

If you cannot rerun an experiment and get the same answer, you cannot tell whether a change helped or you just got lucky. Reproducibility sounds easy and turns out not to be.

Everything "random" in training, the initial weights, the order of the data, dropout, comes from a random number generator started from a number called the seed. Fix the seed and the "random" numbers come out the same every time. Two runs with the same seed and the same everything else should produce identical loss curves. Two runs with different seeds follow different paths from the start but typically end at similar losses.

TWO RUNS, THREE SITUATIONS (ILLUSTRATIVE LOSS CURVES)same seeddifferent seedsame seed, nondeterministic kernelscurves identicaldifferent paths, similar endidentical, then drifting apart
Figure 1.104Three situations. The same seed gives identical curves; a different seed gives a different path to a similar place; the same seed with nondeterministic GPU kernels starts identical and slowly drifts. (Illustrative.)

The third case is the sneaky one. Some GPU operations add up numbers from thousands of parallel threads in whatever order the threads finish. Floating-point addition is not exactly associative: (a+b)+c(a + b) + c can differ from a+(b+c)a + (b + c) in the last digit, because each addition rounds. So the same computation, with the same seed, can produce answers that differ in the last bit from run to run. Those tiny differences feed into the next step, and the next, and grow until the curves visibly drift apart.

THE REPRODUCIBILITY CHECKLISTSeed every RNGPython, NumPy, PyTorch CPU and GPUDeterministic kernelsuse_deterministic_algorithms(True)Seed data workersbase seed + worker idFixed data orderrecord shard order and shuffle seedSave the full configevery hyperparameter, in the run folderPin library versionslock file or container imageCheckpoint everythingweights, optimizer, scheduler, RNG, data positionRecord the hardwareGPU model, driver, CUDA version
Figure 1.105What makes a run reproducible. Seeding alone is not enough; data order, kernels, versions, checkpoints and hardware all matter.

Sharp edges of training

Atomic adds on GPU. Use torch.use_deterministic_algorithms(True) to force deterministic kernels where they exist, at some speed cost. Operations without a deterministic version will raise an error, which is what you want.

Different hardware. Different GPUs, drivers and library versions do arithmetic in slightly different ways. Bit-for-bit matches across machines are rare. Record versions and expect “statistically the same”, not “bitwise the same”, across machines.

Data loader workers. Data loading often runs in several parallel workers. If they share one seed, or get a fresh random one each run, the data order changes between runs. Seed each worker from the base seed plus its worker id.

Resuming loses state. If you stop a run and restart from a checkpoint that saved only the weights, Adam’s running averages are gone and the schedule restarts from the beginning; the run will not continue as it would have. Checkpoint the weights, optimizer state, scheduler state, random number generator states and the position in the data.

Changing batch size changes the best learning rate. A bigger batch gives a less noisy gradient, so the best learning rate usually rises. Doubling the batch and keeping everything else fixed often trains worse. Retune, or scale the learning rate with the batch size and check.