Sub topic 9
Training and validating
This chapter assumes you can read PyTorch code and know what a loss, a gradient step, and an epoch are. It also assumes you have already built train_loader, val_loader, model (with a new head), criterion, optimizer, and device in the earlier chapters. Here you will write the loop that connects them and learn to read its output.
What one epoch does
An epoch is one full pass over the training images, followed by one pass over the validation images. The two passes use the same model, but they differ in three ways:
- Weights change only during training. The optimizer updates parameters on training batches. Validation batches only measure the model.
- Layer behavior differs. Dropout and batch normalization act differently in training mode and evaluation mode.
- Gradients are needed only for training. Skipping them during validation saves memory and time.
One function for both phases
Writing separate training and validation loops invites drift. For example, you might fix a device-transfer bug in one loop and forget the other. A single function with an optional optimizer keeps the phases identical except where they must differ.
import torch
import torch.nn as nn
def run_epoch(model, loader, criterion, device, optimizer=None, freeze_bn=False):
training = optimizer is not None
model.train(training)
if training and freeze_bn:
# Keep frozen backbone's batch-norm statistics fixed.
for module in model.modules():
if isinstance(module, nn.BatchNorm2d):
module.eval()
total_loss, correct, count = 0.0, 0, 0
with torch.set_grad_enabled(training):
for images, labels in loader:
images, labels = images.to(device), labels.to(device)
logits = model(images)
loss = criterion(logits, labels)
if training:
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_loss += loss.item() * images.size(0)
correct += (logits.argmax(dim=1) == labels).sum().item()
count += images.size(0)
return total_loss / count, correct / countHow the pieces work
model.train(training)sets training mode whentrainingisTrueand evaluation mode when it isFalse. This is the same as callingmodel.train()ormodel.eval().torch.set_grad_enabled(training)turns autograd on or off for the whole block. With gradients off, PyTorch does not store the activations it would need for a backward pass.optimizer.zero_grad()clears gradients from the previous step. Without it, gradients accumulate across batches and the updates become wrong.loss.item() * images.size(0)converts the batch's mean loss back into a sum. The last batch is usually smaller than the others, so dividing bycountat the end gives a true per-image average. Averaging the per-batch means directly would overweight the small last batch.logits.argmax(dim=1)picks the highest-scoring class for each image. You do not need softmax for accuracy, because softmax does not change which class has the largest score.CrossEntropyLossalso expects raw logits, so do not apply softmax before it.
The training loader uses shuffle=True so that batches differ from epoch to epoch. The validation loader uses shuffle=False, which makes validation results repeatable.
Running the loop
Call the function once per phase and keep the best weights as you go:
import copy
best_acc, best_state = 0.0, None
for epoch in range(5):
train_loss, train_acc = run_epoch(model, train_loader, criterion, device, optimizer)
val_loss, val_acc = run_epoch(model, val_loader, criterion, device)
print(
f"epoch {epoch + 1}: "
f"train loss {train_loss:.3f} acc {train_acc:.3f} | "
f"val loss {val_loss:.3f} acc {val_acc:.3f}"
)
if val_acc > best_acc:
best_acc = val_acc
best_state = copy.deepcopy(model.state_dict())
model.load_state_dict(best_state)
print(f"best validation accuracy: {best_acc:.3f}")copy.deepcopy matters here. state_dict() returns references to the live parameter tensors, so a plain assignment would change as training continues, and best_state would end up holding the latest weights instead of the best ones.
What healthy output looks like
With a frozen ResNet-18 backbone and a few hundred images per class, expect something like this:
- Training and validation loss fall together in the first epochs.
- Validation accuracy rises quickly in epoch 1, then flattens.
- Training accuracy may sit slightly below validation accuracy early on. Augmentation makes training images harder than validation images, so this is normal.
Reading the two curves
Compare training and validation numbers each epoch. The pattern tells you what to do next.
| Pattern | Likely meaning | What to try |
|---|---|---|
| Both losses fall, accuracies rise | Learning is working | Keep going, or move to fine-tuning |
| Train accuracy high, validation accuracy flat or falling | Overfitting | More augmentation, weight decay, fewer trainable layers, more data |
| Both accuracies low and flat | Underfitting or a bug | Check labels, normalization, and learning rate; unfreeze more layers |
| Validation loss rises while validation accuracy holds | The model is growing overconfident | Stop earlier, or use label smoothing |
| Loss is `nan` | Learning rate too high or bad input | Lower the learning rate; check for corrupt images |
| Validation accuracy jumps around by many points | Small validation set, or a noisy learning rate | Use more validation images; lower the learning rate |
Common errors
Forgetting evaluation mode
If validation runs in training mode, batch normalization uses the statistics of each validation batch and dropout randomly zeroes activations. Your validation numbers become noisy and slightly wrong, and the model does not appear broken. Passing training into model.train(...) removes this class of mistake, because the mode follows from whether an optimizer was supplied.
Batch normalization in a frozen backbone
Setting requires_grad = False stops weight updates, but it does not stop batch normalization from updating its running mean and variance. These are buffers, not parameters. Calling model.train() puts every BatchNorm2d layer into training mode, so a "frozen" ResNet backbone still shifts its statistics toward your small dataset. This is why run_epoch has the freeze_bn option.
- With a small dataset and a fully frozen backbone, use
freeze_bn=True. This keeps the pretrained statistics intact. - When you unfreeze later stages and have a reasonable batch size, such as 32 or more, leaving it
Falseis acceptable. - With very small batches, batch statistics are noisy, so keep batch normalization frozen.
Mismatched optimizer and trainable parameters
An optimizer only updates the parameters you gave it. If you unfreeze layer4 but keep the old optimizer, which holds only model.fc.parameters(), the new layers receive gradients and never change. Always build a new optimizer after changing what is frozen, as in the fine-tuning stage from the previous chapter.
Moving tensors but not the model
images.to(device) returns a new tensor, so you must assign it. The model is different: model.to(device) moves the parameters in place, but assigning the result, as in model = model.to(device), is still the safe habit.
Leaking validation data into decisions
You pick the best epoch using validation accuracy. That makes the best validation score slightly optimistic, because you chose it as the maximum. Report the final number from the separate test split, which the loop never sees.
Practical details
- Speed. Calling
.item()forces the GPU to finish its work before Python continues. For a small project this is fine. For large runs, accumulate tensors on the device and convert once per epoch. - Worker processes.
num_workers=4in the loaders runs image decoding in parallel. If you see a hang on Windows or in a notebook, trynum_workers=0to rule out multiprocessing problems. - Reproducibility. Call
torch.manual_seed(0)before building the loaders if you want repeatable shuffling and augmentation. Exact repeatability on a GPU can still vary slightly. - Timing. Time one epoch before launching many. If the loop is slow and the GPU is mostly idle, the bottleneck is usually image loading, not the model.
Check your understanding
Exercise
A colleague's validation accuracy looks unstable and is a few points lower than expected. Their run_epoch calls model.train() at the top for both phases and wraps both in torch.no_grad() only when no optimizer is given. Name the bug, explain why it affects validation numbers, and give the one-line fix.
Show answer
Validation runs with the model in training mode. Batch normalization then normalizes each validation batch with that batch's own statistics (and updates its running statistics), and dropout, if present, randomly drops activations. Predictions depend on which images share a batch, so accuracy becomes noisy and biased. The fix is to set the mode from the phase: model.train(training), where training = optimizer is not None, so validation runs in evaluation mode.
Exercise
You train for 10 epochs. Training accuracy climbs from 0.70 to 0.99, while validation accuracy peaks at 0.88 in epoch 4 and drifts down to 0.84. Which weights should you keep, which signal tells you this, and name two changes that could improve the result?
Show answer
Keep the epoch 4 weights, the checkpoint with the best validation accuracy (stored with copy.deepcopy(model.state_dict())). The widening gap between training and validation accuracy signals overfitting. Two changes: stronger augmentation or weight decay, and training fewer layers (or collecting more images per class).