Lesson 5.4: Training a small model end to end and reading the curves
Combine everything into one training run with logging, evaluation and checkpoints. Then read the loss curves: healthy, too fast, too slow and overfitting.
By the end of this lesson you will be able to write a complete training loop with a schedule, clipping, weight decay, periodic evaluation and checkpoints, resume a run so that it matches an uninterrupted one exactly, read a loss curve to tell a healthy run from one with a learning rate that is too high, too low or an overfit, and choose where to stop. You will show that a 3,000-step run reaches a validation loss of 1.0030 (perplexity 2.726, 0.0145 above the floor of 0.9885) after seeing 1,536,000 tokens, that a run stopped at step 1,500, saved and resumed ends with weights identical to the uninterrupted run, that a peak rate of 0.3 ends at 1.8759 and one of 0.0003 at 1.1284 against 0.9981 for 0.01, and that a model trained on 1,500 tokens reaches its best validation loss (1.0652) at step 300, then climbs to 2.1423 while its training loss falls to 0.4457. You need Python and NumPy, and the files from Lessons 5.1 to 5.3.
Lessons 5.1 to 5.3 built the pieces: the loss and its floor, the optimiser, the schedule, the batch and the clip. This lesson assembles them into the loop that a real training run uses, and then does the thing that matters most in practice: it reads the output. A training run produces a stream of numbers, and a skilled builder looks at them as a doctor looks at a chart, to see what is wrong before it is too late.
The loop
Every training run, from our toy to the largest models, has the same steps, repeated:
1. Draw a batch of windows from the training data.
2. Run the model forward and compute the loss.
3. Run it backward to get the gradient.
4. Clip the gradient by its global norm.
5. Set the learning rate from the schedule.
6. Take an optimiser step, with weight decay.
7. Log the numbers: loss, gradient length, learning rate.
8. Every so often, evaluate on held-out data, and save a checkpoint.
The code does all of it. Save it as trainer.py. A few design points are worth a look.
python
# trainer.py
import numpy as np
from helpers import
from gpt import
from optim import AdamW
from schedules import lrat, clipglobalnorm
def evaluate(p, data, cfg, n=400, seed=123):
"""Average loss on n fixed windows. The same windows every time, so the numbers can be compared."""
x, y = getbatch(data, n, cfg["T"], np.random.defaultrng(seed))
logits, = gptfwd(p, x, cfg["L"], cfg["h"], sinusoidal(cfg["T"], cfg["d"]))
P = softmax(logits)
return float(-np.log(P[np.arange(n)[:, None], np.arange(cfg["T"])[None, :], y]).mean())
def trainrun(cfg, data=None, start=None, stop=None, log=None):
"""Train from step start (default 0) to stop (default cfg['steps']). Returns the model, optimiser and history."""
data = trainids if data is None else data
Pos = sinusoidal(cfg["T"], cfg["d"])
if start is None:
p = initgpt(V, cfg["d"], cfg["L"], seed=cfg["seed"])
opt = AdamW(p, cfg["lr"], weightdecay=cfg["wd"])
start = 0
else: # resume from a checkpoint
ck = np.load(cfg["checkpoint"])
p = {k[2:]: ck[k].copy() for k in ck.files if k.startswith("p/")}
opt = AdamW(p, cfg["lr"], weightdecay=cfg["wd"])
opt.m = {k[2:]: ck[k].copy() for k in ck.files if k.startswith("m/")}
opt.v = {k[2:]: ck[k].copy() for k in ck.files if k.startswith("v/")}
opt.t = int(ck["t"])
stop = cfg["steps"] if stop is None else stop
history, runloss = [], []
for step in range(start, stop):
rng = np.random.defaultrng((cfg["seed"], step)) # the batch depends only on the step, so a resumed run sees the same data
x, y = getbatch(data, cfg["batch"], cfg["T"], rng)
loss, g = lossandgrads(p, x, y, cfg["L"], cfg["h"], Pos)
norm = clipglobalnorm(g, cfg["clip"]) if cfg["clip"] else float(np.sqrt(sum((v 2).sum() for v in g.values())))
lr = lrat(step, cfg["steps"], cfg["lr"], cfg["warmup"])
opt.step(g, lr=lr)
runloss.append(loss)
if (step + 1) % cfg["evalevery"] == 0:
history.append(dict(step=step + 1, train=float(np.mean(runloss)), val=evaluate(p, valids, cfg), lr=lr, grad=norm))
runloss = []
if log:
print(f"step {step + 1:5d} train {history[-1]['train']:.4f} val {history[-1]['val']:.4f} lr {lr:.5f} grad {norm:.3f}", flush=True)
return p, opt, history
def savecheckpoint(path, p, opt):
np.savez(path, t=opt.t, {"p/" + k: v for k, v in p.items()}, {"m/" + k: v for k, v in opt.m.items()}, {"v/" + k: v for k, v in opt.v.items()})
cfg = dict(d=32, L=2, h=2, T=16, batch=32, steps=3000, lr=0.01, warmup=100, wd=0.01, clip=1.0, seed=0, evalevery=300, checkpoint="ckpt.npz")
A configuration dictionary, cfg, holds every setting in one place: width, blocks, heads, window, batch, steps, peak learning rate, warm-up, weight decay, clip, seed and how often to evaluate. A run is described by its configuration, and can be reproduced from it.
The batch depends only on the seed and the step. The line rng = np.random.defaultrng((cfg["seed"], step)) seeds a fresh generator from the pair, so step 1,501 draws the same batch whether the run started at step 0 or was resumed at 1,500. This is what makes exact resumption possible.
Evaluation uses the same windows every time. evaluate draws 400 windows with a fixed seed, so two evaluations at different steps differ only because the model changed, and not because the windows changed.
The training loss is an average since the last evaluation. A single batch's loss is noisy (Lesson 2.4), so the log reports the mean over the steps since the last report.
Checkpoints hold everything the run needs: the weights, Adam's two running averages and its step count. Saving only the weights would restart Adam from scratch, with the wrong bias correction.
One full run
python
from trainer import
p, opt, hist = trainrun(cfg, log=True)
print("final validation:", round(hist[-1]["val"], 4), " perplexity:", round(float(np.exp(hist[-1]["val"])), 3))
stop half way, save, resume, and compare with the uninterrupted run
p1, o1, = trainrun(cfg, stop=1500)
savecheckpoint(cfg["checkpoint"], p1, o1)
p2, o2, = trainrun(cfg, start=1500)
print("resumed run equals the uninterrupted run:", all(np.arrayequal(p[k], p2[k]) for k in p))
The configuration is the one Lesson 5.3 arrived at: width 32, two blocks, a peak learning rate of 0.01 with a warm-up of 100 steps and cosine decay, weight decay 0.01 and a clip of 1.0. The output:
step 300 train 1.5261 val 1.0086 lr 0.00990 grad 0.294
step 600 train 1.0131 val 1.0062 lr 0.00936 grad 0.267
step 900 train 1.0099 val 1.0117 lr 0.00842 grad 0.335
step 1200 train 1.0083 val 1.0036 lr 0.00717 grad 0.269
step 1500 train 1.0070 val 1.0021 lr 0.00575 grad 0.258
step 1800 train 1.0050 val 1.0065 lr 0.00430 grad 0.339
step 2100 train 1.0029 val 1.0044 lr 0.00298 grad 0.209
step 2400 train 1.0026 val 1.0045 lr 0.00192 grad 0.244
step 2700 train 1.0010 val 1.0016 lr 0.00124 grad 0.207
step 3000 train 0.9995 val 1.0030 lr 0.00100 grad 0.219
final validation: 1.003 perplexity: 2.726
resumed run equals the uninterrupted run: True
Reading it:
The first line's training loss, 1.5261, is an average over steps 1 to 300, which includes the early steps when the loss was still falling from 3.53. By step 600 the average is 1.0131: the model has learned the language in the first few hundred steps.
After that, progress is slow. The validation loss goes from 1.0086 to 1.0030 over the remaining 2,400 steps. The model is already near the floor of 0.9885, so the remaining gain is small. This is the long flat tail of nearly every training curve.
Validation jitters by about 0.005 from one report to the next (1.0036, 1.0021, 1.0065, 1.0044), while the learning rate is high, and settles as it falls (1.0016, 1.0030 at the end). That is the schedule doing its job.
The gradient length is steady, 0.2 to 0.34, and never near the clip of 1.0.
Training loss and validation loss are close (0.9995 and 1.0030), so there is no sign of overfitting.
The final perplexity is 2.726, which is 0.0145 nats above the floor.
The last line is the resumption test. The code trained to step 1,500, saved a checkpoint, started again from it for the remaining 1,500 steps, and compared every weight with the uninterrupted run: True. Exact resumption, bit for bit, is not a luxury. A run that takes days will be interrupted by a crash or a power cut, and you must be able to continue it without changing the result. It only works because the batch is a function of the step, the optimiser state is saved and nothing else is hidden in memory.
How much did the run cost? It processed 3,000 steps of 32 windows of 16 tokens: 1,536,000 tokens, which is 57.9 passes over the 26,547 training tokens. A common estimate of the compute for training a transformer is about 6 times the number of parameters times the number of tokens, in multiply-adds (two for the forward pass and four for the backward): 6 × 27,648 × 1,536,000 = 2.5 × 10¹¹.
Reading the curves
A healthy curve is the one above. Most of the skill is in recognising the unhealthy ones. We make four, with the same code and different settings, all for 1,500 steps with evaluations every 100.
python
from trainer import
def show(name, hist, every=3):
print(name)
for h in hist[every - 1 :: every]:
print(f" step {h['step']:5d} train {h['train']:.4f} val {h['val']:.4f} grad {h['grad']:.2f}")
base = dict(cfg, steps=1500, evalevery=100, warmup=100)
with np.errstate(all="ignore"):
show("healthy: peak learning rate 0.01", trainrun(dict(base, lr=0.01))[2])
show("too high: peak learning rate 0.3", trainrun(dict(base, lr=0.3))[2])
show("too low: peak learning rate 0.0003", trainrun(dict(base, lr=0.0003))[2])
small = trainids[:1500] # overfitting: wider model, very little data
p, o, h = trainrun(dict(base, d=64, steps=1500, evalevery=100, lr=0.003, wd=0.0, clip=None), data=small)
show("overfitting: 1,500 tokens, width 64", h, every=3)
best = min(h, key=lambda r: r["val"])
print("best validation", round(best["val"], 4), "at step", best["step"], " final validation", round(h[-1]["val"], 4))
healthy: peak learning rate 0.01
step 300 train 1.0155 val 1.0083 grad 0.29
step 600 train 1.0097 val 1.0064 grad 0.30
step 900 train 1.0060 val 1.0052 grad 0.23
step 1200 train 1.0031 val 0.9982 grad 0.32
step 1500 train 1.0031 val 0.9981 grad 0.26
too high: peak learning rate 0.3
step 300 train 2.5190 val 2.6933 grad 0.45
step 600 train 2.2287 val 2.3822 grad 3.12
step 900 train 2.5154 val 2.3336 grad 0.22
step 1200 train 2.1423 val 2.1078 grad 0.31
step 1500 train 1.9284 val 1.8759 grad 0.28
too low: peak learning rate 0.0003
step 300 train 3.1105 val 2.7911 grad 1.60
step 600 train 1.4255 val 1.3585 grad 0.72
step 900 train 1.2492 val 1.2392 grad 0.40
step 1200 train 1.1930 val 1.1735 grad 0.58
step 1500 train 1.1376 val 1.1284 grad 0.40
overfitting: 1,500 tokens, width 64
step 300 train 0.9888 val 1.0652 grad 0.45
step 600 train 0.9183 val 1.1865 grad 0.60
step 900 train 0.7418 val 1.4738 grad 0.72
step 1200 train 0.5514 val 1.9003 grad 1.02
step 1500 train 0.4457 val 2.1423 grad 1.07
best validation 1.0652 at step 300 final validation 2.1423
Healthy
Training and validation fall together to about 1.00 and stay close. The gradient length is steady, near 0.3. The final validation loss is 0.9981. (A value a little below the 1.003 of the 3,000-step run is within the noise of the evaluation: 400 windows, and a model that moves by about 0.005 between reports.)
Learning rate too high
A peak of 0.3, thirty times too large. The loss never gets near the floor. Training and validation are both high (2.5190 and 2.6933 at step 300) and then drift down slowly to 1.9284 and 1.8759. The gradient length shows an excursion (3.12 at step 600, ten times the normal 0.3). The signs of a rate that is too high: the loss plateaus at a high value, or jumps up, or never falls as far as a gentler run, and the gradient length is erratic. With a more aggressive setting the loss would become NaN. The fix is a lower peak. The clip kept this run alive, as it caps the gradient at 1.0, but a rate this large still wastes the run.
Learning rate too low
A peak of 0.0003, thirty times too small. The loss falls, but slowly: 2.7911 at step 300, 1.3585 at step 600 and 1.1284 at step 1,500, still falling. The signs: a smooth curve that is still dropping steadily when the run ends, and a large gradient length early (1.60 at step 300) that shrinks slowly. The fix is a higher peak or more steps. This is the most common mistake in practice, and the most expensive, because the run looks fine and wastes its whole budget.
Overfitting
The last scenario trains a wider model (width 64) on only 1,500 tokens. The training loss keeps falling (0.9888, 0.9183, 0.7418, 0.5514, 0.4457) and the validation loss, after a minimum of 1.0652 at step 300, rises (1.1865, 1.4738, 1.9003, 2.1423). The two curves diverge: the model is memorising the training examples. The gradient length also grows, from 0.45 to 1.07. This is the shape to fear in a real run. The remedies are the ones from Lesson 5.2: more data, weight decay, a smaller model, and early stopping: keep the checkpoint with the best validation loss (here step 300) and discard the rest. The code prints the best step: best validation 1.0652 at step 300 final validation 2.1423.
A guide to the symptoms
What you see · Likely cause · What to tryLoss starts far above the log of the vocabulary · Weights too large, or a bug in the loss · Check the initial scale (Lesson 4.4) and the loss function
Loss stays at the log of the vocabulary · The model learns nothing: a learning rate far too low, a broken backward pass or dead activations · Gradient check, overfit one batch (Lesson 4.4)
Loss falls smoothly and is still falling at the end · Learning rate too low, or too few steps · Raise the peak, or train longer
Loss plateaus high, erratic gradient length · Learning rate too high · Lower the peak, check clipping
Sudden spike, then recovery · A bad batch or a rate near the limit · Clip, lower the rate, look at the data at that step
Loss becomes NaN · Overflow: rate too high, unstable softmax, bad data · Lower the rate, use a stable loss (Lesson 5.1), find the step
Training falls, validation rises · Overfitting · More data, weight decay, smaller model, stop early
Training and validation both flat above the floor · The model is too small or the data is too hard · A larger model, more steps, better data
Validation far below training · A leak, or an unrepresentative validation set · Check the split and the mask (Lesson 3.3)
Validation below the best possible · A leak · The same
## Habits of a careful run
Log the gradient length and the learning rate with the loss. The loss alone cannot tell a spike from a bad batch from a rate near the limit.
Evaluate on a fixed set, and often enough to see the shape. Ten to a hundred reports per run is typical.
Keep the checkpoint with the best validation loss as well as the latest. The best may be earlier than the last.
Make the run reproducible: fix the seed, record the configuration and the code version, and make the batch a function of the step.
Test resumption, as above, before a long run.
Run a small version first. A 300-step run on a tenth of the data finds most bugs in a minute.
Compare to the floor. A loss with no floor beside it is a number with no meaning.
Key takeaways
A training loop draws a batch, runs forward and backward, clips, sets the learning rate, takes an optimiser step, logs, and every so often evaluates and saves a checkpoint.
Make the batch a function of the seed and the step, and save the optimiser's state with the weights. Then a resumed run matches an uninterrupted one exactly: True, for every weight.
On this run, most of the learning happens in 300 steps. The validation loss then moves from 1.0086 to 1.0030 over the remaining 2,700, jittering by about 0.005 while the rate is high and settling as it falls. The final perplexity is 2.726, 0.0145 nats above the floor.
The run used 1,536,000 tokens (57.9 passes over the data) and about 2.5 × 10¹¹ multiply-adds.
Too high a rate: the loss plateaus high (1.8759 after 1,500 steps at a peak of 0.3), the gradient is erratic. Too low: the loss falls smoothly but is still falling at the end (1.1284 at 0.0003). Overfitting: the training loss falls (0.4457) while validation rises (from 1.0652 at step 300 to 2.1423). Early stopping keeps the best checkpoint.
Read curves together with the gradient length, the learning rate and a floor.
This completes the training module. We have a model that trains to within 0.015 of the best possible loss and the tools to know when it does not.
Common mistakes
Saving only the weights. The optimiser's averages and step count are part of the state.
A batch that depends on hidden random state. Resumption then changes the data.
Evaluating on different windows each time. The curve then shows sampling noise as well as learning.
Reading the training loss at one step. Average over a stretch.
Judging a run by its last number. Look at the shape, the gradient and the gap between training and validation.
Stopping at the first sign of a spike. A spike that recovers is common. A spike that does not is the problem.
Treating a loss still falling as converged. It may be a rate that is too low.
Tuning on the validation set and then reporting it as the result. Keep a separate test set for the final number.
Training for the maximum number of steps without early stopping on small data. It can make the model worse.
Check yourself
1. A run uses 500 steps of 64 windows of 128 tokens. How many tokens does it see?
500 × 64 × 128 = 4,096,000 tokens.
2. A model has 10 million parameters and trains on 2 billion tokens. About how many multiply-adds is that, by the 6ND rule?
6 × 10⁷ × 2 × 10⁹ = 1.2 × 10¹⁷.
3. Training loss 0.8 and falling, validation loss 1.4 and rising. What do you do?
It is overfitting. Stop at the best earlier checkpoint, and try more data, weight decay or a smaller model.
4. A loss curve falls smoothly from 3.5 to 1.4 and is still dropping at the last step. What are the likely causes?
The learning rate is too low, or the run is too short. Raise the peak or train longer.
5. Why must a checkpoint contain Adam's running averages?
Without them, Adam restarts from zero with a fresh bias correction, which produces a different, usually worse, path than an uninterrupted run.
6. A run's validation loss is below the best possible loss. What do you suspect?
A leak, such as a missing causal mask or validation tokens in the training data.
Try this
Set aside three hours. You need Python, NumPy and the files from Lessons 5.1 to 5.3.
1. Run the full training and print the log. Plot training and validation loss against the step.
2. Change the learning rate peak to 0.001, 0.03 and 0.1, and read the curves with the table of symptoms. Which looks like which?
3. Train the model with a window of 8 and a window of 32. How does the final loss change, and why?
4. Make the overfitting run with weight decay of 3.0 and gradient clipping at 1.0. What happens to the best step and the final validation loss?
5. Add early stopping: save the checkpoint at the best validation loss, and restore it at the end.
6. Resume from a checkpoint with a different peak learning rate. How does the curve change at the resume step?
7. Plot the gradient length against the step for the healthy and too-high runs.
A good result is a log you can read, a resumed run that matches the original and a collection of curves labelled by their cause. The next module takes the trained model and makes it write: the ways of sampling from its probabilities, from greedy to top-p, and how to evaluate what it generates.
Read more
Andrej Karpathy, "A Recipe for Training Neural Networks" (2019), describes the habits of this lesson: start small, overfit a batch, read the curves. Jared Kaplan and colleagues, "Scaling Laws for Neural Language Models" (2020), gives the estimate of six times parameters times tokens and measures how loss falls with compute. Google Research, "Deep Learning Tuning Playbook" (2023), is a practical guide to choosing learning rates, batch sizes and reading training curves.
Tags: Build an LLM Training loop Learning curves Overfitting Checkpoints