Topic 4 of 6 · 5 min read
Training loop and reading loss curves
Goal: Diagnose from a loss log whether a run is learning, overfitting or diverging and choose the next change to make.
Training repeats one cycle: predict, measure the error with cross-entropy, compute gradients, and let the optimizer nudge every weight; the loss log is how you tell whether the cycle is working.
Check yourself · 1 of 3
A new character-level model with 65 characters has not been trained at all. About what cross-entropy loss should the first step print?
Why it matters
A run can take hours and fail quietly. Reading train and validation loss together tells you in minutes whether to keep going, stop, or change something. Guessing wastes compute.
How to do it
- Flatten logits and targets for the loss: logits
(B, T, V)become(B*T, V), targets(B, T)become(B*T,). ThenF.cross_entropy(logits, targets). - Know your starting point. An untrained model guesses uniformly, so the first loss should be near
ln(vocab_size). For 65 characters that is about 4.17. A first loss far from that points to a bug in initialization or data. - Use AdamW with a learning rate around
3e-4to1e-3for a small model, and weight decay such as 0.1. - Schedule the learning rate. Warm up linearly for the first few hundred steps, then decay (cosine decay is common) to a fraction of the peak. Warmup avoids wild early updates while Adam's statistics are still poor.
- Clip gradients (
clip_grad_norm_to 1.0) so one bad batch cannot wreck the weights. - Evaluate every N steps with
model.eval()andtorch.no_grad(), averaging loss over many batches of both train and validation data. Switch back withmodel.train().
Before and after
Reading the log is the skill. Here is a run:
step 0: train 4.19, val 4.20
step 500: train 1.80, val 1.92
step 1000: train 1.40, val 1.62
step 2000: train 1.05, val 1.58
step 3000: train 0.71, val 1.74
A weak reading says "train loss keeps falling, so it is still learning". A better reading: validation loss bottomed near step 2000 and then rose while training loss kept falling. The model is memorizing. The next change is to stop at step 2000, save that checkpoint, and then try more dropout, a smaller model or more data.
What goes wrong
- Flat loss near
ln(V). Nothing is learning: learning rate far too low, targets not shifted, or gradients not reaching the weights becauseoptimizer.zero_grad()orloss.backward()is missing. - Loss becomes NaN or jumps. The learning rate is too high or there is no warmup. Lower the rate and add clipping.
- Noisy evaluation. Loss measured on one batch jumps around. Average over 100 or more batches.
- Forgetting
model.eval(). Dropout stays active during evaluation and makes validation loss look worse than it is.
Examples
A minimal training step
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.1)
for step in range(max_steps):
for g in optimizer.param_groups:
g["lr"] = get_lr(step) # warmup then cosine decay
xb, yb = get_batch(train_data, block_size, batch_size)
logits = model(xb)
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), yb.view(-1))
optimizer.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
If this loop prints 4.2 at step 0 and still 4.2 at step 1000, check that yb is shifted and that zero_grad and backward run in this order.
Key points
- Cross-entropy needs logits flattened to (BT, V) and targets flattened to (BT).
- A fresh model should start near ln(vocab_size), about 4.17 for 65 characters; a very different first loss signals a bug.
- AdamW with learning-rate warmup, decay and gradient clipping is the standard recipe for small GPTs.
- Read train and validation loss together: both falling means learning, validation rising while train falls means overfitting.
- Evaluate with model.eval(), no gradients and an average over many batches, then switch back to train mode.
Common mistakes
- Judging a run by training loss alone and missing the point where validation loss turns upward.
- Skipping learning-rate warmup and seeing NaN in the first hundred steps.
- Evaluating on a single batch and reacting to noise.
- Calling loss.backward() without zero_grad, so gradients pile up across steps.
Check yourself · 2 of 3
Training loss keeps falling, but validation loss reached its minimum at step 2000 and has risen since. What is happening?
Check yourself · 3 of 3
Loss turns to NaN within the first 100 steps at a learning rate of 1e-2 with no warmup. What is the best first change?
Practice items, not counted towards your mastery.
Start here
- Neural Networks: Zero to Hero (Andrej Karpathy) (opens in a new tab)CourseFree
Free course that builds up to a GPT from scratch, with notebooks.
- nanogpt-lecture (Karpathy) (opens in a new tab)ToolFree
The code written in the "Let's build GPT" lecture, with a git history that follows it step by step.
- nanoGPT (Karpathy) (opens in a new tab)ToolFree
A compact GPT training script to compare your own model against.
More for this topic
- Decoupled Weight Decay Regularization (AdamW) (opens in a new tab)PaperFree
Explains why AdamW applies weight decay separately from the gradient update.