Train mode, evaluation mode and validation
What it is
An epoch runs all training batches once, but the meaningful unit of optimisation is usually the update step rather than the epoch. In training mode, each batch follows the complete loop—forward pass, loss, backward, and optimiser step—while validation measures held-out data without updating parameters. model.train() enables training behaviour such as dropout and current batch statistics; model.eval() switches layers to inference behaviour, and torch.no_grad() prevents autograd from retaining unnecessary activations. Save the checkpoint with the best validation metric rather than automatically trusting the final epoch.
Why it matters
Validation loss is the signal for early stopping, model selection, and learning-rate scheduling. Training loss alone cannot tell you whether the model is learning a reusable pattern or memorising. A widening train/validation gap is evidence to investigate capacity, augmentation, data quality, or regularisation—not a cue to simply train longer.
In the real world: Measuring a model on held-out data in the right mode, so the reported accuracy matches production.
Visual example
Deep learningParameter updates happen only on training batches; validation is a separate measurement.
import torch
model.train()
for xb, yb in train_loader:
opt.zero_grad(); loss_fn(model(xb), yb).backward(); opt.step()
model.eval()
with torch.no_grad():
val = sum(loss_fn(model(xb), yb).item() for xb, yb in val_loader) / len(val_loader)
print(val)Validating in train mode. Dropout and batch-normalisation then alter the score, making runs noisy and comparisons unreliable.
Practise it: Batch Norm Behaves Differently at Inference