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.
#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.
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.
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.
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, , whose lowest point is at . Standing at , the loss is 4 and the slope is . The slope is negative, so we should increase . Gradient descent takes a step against the slope, scaled by a small number called the learning rate, (eta):
With : . The loss drops from 4 to 2.56. Repeat, and creeps toward 3. The symbol is the partial derivative, mathematician's notation for "the slope of in the direction of , holding everything else fixed".
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.
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: , the average of recent gradients (which direction it has been pushed lately), and , the average of recent squared gradients (how large its pushes usually are). Each step moves the weight by , scaled by the learning rate.
Here is the current gradient for this weight, and (typically 0.9 and 0.95 for language models) control how long the averages remember, and , are the averages with a small correction for their first few steps. Dividing by 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 .
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.
#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.
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 :
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.
| Finch-19's recipe | Value |
|---|---|
| Batch | 256 sequences × 1,024 tokens = 262,144 tokens |
| Steps | 10,000 (about 2.6 billion tokens) |
| Optimizer | AdamW, , , weight decay 0.1 |
| Learning rate | warmup 200 steps to , cosine to |
| 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.
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 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.
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: can differ from 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.
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.