Lesson 9 of 187 min
Reading loss curves
Read a run's two loss curves together, and make the network memorize one small batch before a long run: each way a run goes wrong leaves its own shape.
After this lesson you can diagnose a training run from its curves.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
A first loss far from 2.30
Every run in the video started near 2.30, so the start check passed. When it fails, the bug is before any training. A common one: pixels left as they came. The digits' pixels go from 0 to 16, and the same network starts at 3.84 on them. Divided by 16, it starts at 2.33.
torch.manual_seed(0)
model = net()
raw = torch.tensor(digits.data.astype(np.float32))
labels = torch.tensor(digits.target)
print(round(F.cross_entropy(model(raw), labels).item(), 4))
print(round(F.cross_entropy(model(raw / 16), labels).item(), 4))3.8359 2.3264
Validation below training at the start
In the first epochs, the validation loss is often a little below the training loss. That's no bug. The training loss is the average of the epoch's batches, and most of them were scored before the network improved. Scored again after the epoch, the training pictures land close to the validation pictures.
torch.manual_seed(0); model = net()
opt = torch.optim.Adam(model.parameters(), lr=0.001)
total = 0
for x, y in loader:
loss = F.cross_entropy(model(x), y)
opt.zero_grad(); loss.backward(); opt.step()
total += loss.item()
with torch.no_grad():
print(round(total / len(loader), 4), round(F.cross_entropy(model(x_train), y_train).item(), 4),
round(F.cross_entropy(model(x_val), y_val).item(), 4))2.2389 2.134 2.1394
Smooth a noisy curve
The loss of each step jumps around, much more than an epoch's average. To read its trend, draw a running average next to it. Here run 7's rate of 0.05 gives step losses from 0.015 to 0.372 after step 100. Averaged over 20 steps, they stay between 0.109 and 0.161.
torch.manual_seed(0); model = net()
opt = torch.optim.Adam(model.parameters(), lr=0.05)
steps = []
for epoch in range(3):
for x, y in loader:
loss = F.cross_entropy(model(x), y)
opt.zero_grad(); loss.backward(); opt.step()
steps.append(loss.item())
s = np.array(steps); smooth = np.convolve(s, np.ones(20) / 20, mode="valid")
print(round(s[100:].min(), 3), round(s[100:].max(), 3), round(smooth[100:].min(), 3), round(smooth[100:].max(), 3))0.015 0.372 0.109 0.161
Gradient clipping
Big runs add one line between backward() and step(). It shrinks the gradient when its size passes a limit, so one bad batch can't throw the weights far. It returns the size before clipping. At run 7's rate, 21 of the first epoch's 45 steps passed 1.0. It helps, but it's no cure: PaLM had it on and still spiked.
torch.manual_seed(0); model = net()
opt = torch.optim.Adam(model.parameters(), lr=0.05)
sizes = []
for x, y in loader:
loss = F.cross_entropy(model(x), y)
opt.zero_grad(); loss.backward()
sizes.append(torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0).item())
opt.step()
print(len(sizes), round(max(sizes), 2), sum(size > 1.0 for size in sizes))45 1.82 21
Run on Python 3.13.3, PyTorch 2.15.0, scikit-learn 1.9.1 and NumPy 2.5.5. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: The training loop
The loader shuffles the 1,437 training pictures and hands them out in batches of 64. Training runs for 10 epochs. How many steps does it take in all?
2 of 3
A run prints a training loss of 2.31 every epoch, the same to the third decimal, and no error. What do you do first?
3 of 3
A run's training loss falls a little and stays above 2. Its validation loss climbs from the very first epoch, and it gets fewer than one in ten of the new pictures right. What went wrong?
The ideas in this lesson
- Reading the two curves
- Read the training and validation losses together: falling together is learning; a gap that opens is memorizing.
- Memorize one batch first
- Before a long run, make the network memorize one small batch; if it can't, the code or the rate is broken.
- Loss spike
- A sudden jump in the loss from a step that went too far; big runs go back to a saved copy.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Which run would you keep?
Here's a bet. We trained the same network four times. Three of the runs went wrong, with no error at all. So which run would you keep?
Four runs
Here are the four runs. It's the same network each time, learning to read handwritten digits. Each card shows its training loss, epoch by epoch.
Runs one and four end high, above two. Runs two and three end low, close to zero. Run three ends lowest.
Is it the one to keep?
The second curve
One curve can't tell you whether a network learned.
So after every epoch, score the three hundred and sixty pictures set aside. That's the validation loss. Draw it beside the first one, and read the two curves together.
Run two: both curves fall together, and end up close. It gets about ninety-five percent of the new pictures right.
Run three's training loss ends lowest... but its validation loss stops at about zero point five. It gets about eighty-seven percent right.
Run three had only a hundred pictures to learn from, while the others had more than fourteen hundred. It memorized them. That's overfitting.
The gap between its two curves is the sign.
The run to keep
So the run with the lowest training loss wasn't the one to keep. Run two is. Its two curves fall together.
A validation loss that only climbs
Now look at run one. What's odd about it?
Its training loss only falls a little, and stays above two. But its validation loss climbs from the very first epoch.
It ends near two point four. It gets about six percent right. That's fewer than one in ten: worse than picking a digit at random. Its labels had been shuffled separately from its pictures, so every picture had a random digit. The network started to memorize which digit went with which picture... and none of that works on new pictures. So when the validation loss only climbs, look at a few pictures with their labels, and check that they match.
When the training loss won't fall
Now runs five and six, the same digits network. In both, the training loss won't come down. The first suspect is the learning rate. A rate that's too small crawls, and a rate that's too big jumps. The usual rate is zero point zero zero one. Run five's is a hundred times smaller, and after thirty epochs its loss has barely moved. Run six's is a thousand times bigger. Its loss jumps to over twelve in the first epoch, off the top of the chart... then it stays above where it started.
Completely flat
Now spot what's strange about run four. Two point three one, every epoch, exactly the same. A rate that's too small still crawls. A rate that's too big still jumps. This one doesn't move at all. Here's what happened. In a notebook, the cell that makes the network was run again. It ran after the cell that made the optimizer. The optimizer still holds the first network's weights. So every step changes those weights. The new network, the one being scored, never changes. And there's no error.
Memorize one batch
So how could you catch this before an hour of training?
Its first loss, two point three one, looks right. A fair guess among ten digits gives two point three oh, and every run starts near it.
So check that it can learn at all. Make it memorize one batch of thirty-two pictures, the same batch, again and again.
In run three, memorizing was the problem. Here, we want it, on purpose: any working network can memorize thirty-two pictures. Can run four's code do it?
The right code gets that batch down to zero point zero two, in five hundred steps.
That takes less than a second.
Run four's code stays at two point three one, at every step.
If a network can't memorize one small batch, something is broken: the code, or a learning rate that's far off.
Before the long run
That check takes less than a second, before a run that takes hours.
A spike
Here's run seven, the digits network with a rate that's a little too big. It learns fast: after one epoch, it's ninety-one percent right. Then its curves go up and down.
At epoch twelve, its validation loss is about zero point one. Two epochs later, it has tripled. Does the loss come back down?
Yes. By epoch sixteen, it's back down, close to where it was. A sudden jump like this is called a spike. One step of training went too far for where the network was. At the usual rate, run two doesn't have any. And small spikes go back down on their own.
Big runs spike too
Big runs spike too. PaLM, a model with five hundred and forty billion weights, spiked about twenty times in its training. Each time, the team went back to a saved copy of the weights, from about a hundred steps earlier. They skipped two hundred to five hundred batches... and the loss didn't spike again there.
In code
In code, keep both losses in two lists, one number each epoch. Then draw them together, with matplotlib.
Before the long run, two checks. First, one line checks the first loss. If the first loss is far from two point three oh, a fair guess, the program stops.
Second, make it memorize one batch of thirty-two, for five hundred steps, and print the loss. Zero point zero two. So the code can learn.
Three readings
So, read both curves together. Make the network memorize one batch before a long run. And a spike is one step that went too far.
Read them together
Read the two curves together, never just one. Now try it on this lesson's page, and take the quiz. Find another run that can't learn one small batch.
You use this lesson in Lab 4: A training run that checks itself, after Warmup and learning-rate schedules.
Facts last checked on .
