TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › A Reusable Training and Evaluation Loop

A Reusable Training and Evaluation Loop

The idiomatic PyTorch loop of the training course was written out inline, for one model and one data set. Every later lesson of this course trains something: an MLP, a CNN, an LSTM, a transformer, a VAE. Rewriting the loop each time invites the classic bugs (a forgotten model.eval(), a missing zero_grad, a loss averaged wrongly), so this lesson packages it once as two functions, about forty lines together:

  • evaluate(model, loader, loss_fn) returns the mean loss and the accuracy over a whole loader;
  • fit(model, train_loader, val_loader, loss_fn, optimizer, epochs, scheduler=None, patience=None) trains, validates after every epoch, keeps a history, stops early, and restores the best weights.

Later lessons call these two functions (or a compact copy of them, since every recorded example must run on its own). What each piece does and why was taught in the training course: the loop itself in loop-pytorch, the stopping rule and checkpoints in early stopping and checkpointing, schedules in learning-rate scheduling. Here the focus is on getting the bookkeeping right.

Two pieces of arithmetic the loop must get right

The epoch loss is a weighted mean. A loader yields batches of size nbn_b, and the loss function returns the mean over the batch, Lˉb\bar{L}_b. The mean over all N=∑bnbN = \sum_b n_b examples is

Lˉ=1N∑i=1Nℓi=∑bnb Lˉb∑bnb\bar{L} = \frac{1}{N} \sum_{i=1}^{N} \ell_i = \frac{\sum_b n_b \, \bar{L}_b}{\sum_b n_b}

and not the plain average of the batch means, 1B∑bLˉb\frac{1}{B} \sum_b \bar{L}_b, which gives the last, smaller batch the same weight as a full one. The same holds for accuracy: count correct predictions and divide once by NN.

Early stopping. With validation loss vtv_t after epoch tt, best value so far v∗v^{*} at epoch t∗t^{*}, a minimum improvement δ≥0\delta \ge 0 and a patience pp, epoch tt counts as an improvement when

vt<v∗−δv_t < v^{*} - \delta

and training stops after the first epoch with t−t∗=pt - t^{*} = p, that is, pp epochs in a row without improvement. The weights of epoch t∗t^{*} are then restored. A larger pp tolerates noisy validation curves at the cost of extra epochs; δ>0\delta > 0 ignores improvements too small to matter.

Both rules in NumPy, on numbers chosen to make the effects visible:

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
per_example = rng.gamma(2.0, 0.15, size=1077)      # stand-in per-example losses of one epoch
order = rng.permutation(1077)
per_example[order[-53:]] *= 3                      # the last batch happens to hold hard examples

sizes, means = [], []
for s in range(0, 1077, 256):
    b = per_example[order[s:s + 256]]
    sizes.append(len(b)); means.append(b.mean())
sizes, means = np.array(sizes), np.array(means)
print("batch sizes", sizes.tolist())
print(f"true mean            {per_example.mean():.4f}")
print(f"mean of batch means  {means.mean():.4f}")
print(f"size-weighted mean   {(sizes * means).sum() / sizes.sum():.4f}")

def early_stopping(val_losses, patience, min_delta=0.0):
    best, best_epoch, wait = float("inf"), 0, 0
    for epoch, v in enumerate(val_losses, start=1):
        if v < best - min_delta:
            best, best_epoch, wait = v, epoch, 0
        else:
            wait += 1
            if wait >= patience:
                return best_epoch, epoch
    return best_epoch, len(val_losses)

val = [0.90, 0.52, 0.38, 0.31, 0.29, 0.285, 0.30, 0.284, 0.29, 0.31, 0.30, 0.33, 0.35]
for patience, delta in [(3, 0.0), (5, 0.0), (3, 0.01)]:
    best, stop = early_stopping(val, patience, delta)
    print(f"patience {patience}, min_delta {delta}: best epoch {best} (val {val[best - 1]}), stopped after epoch {stop}")
batch sizes [256, 256, 256, 256, 53]
true mean            0.3304
mean of batch means  0.4246
size-weighted mean   0.3304
patience 3, min_delta 0.0: best epoch 8 (val 0.284), stopped after epoch 11
patience 5, min_delta 0.0: best epoch 8 (val 0.284), stopped after epoch 13
patience 3, min_delta 0.01: best epoch 5 (val 0.29), stopped after epoch 8

The 1077 examples form four batches of 256 and one of 53. Averaging the five batch means gives 0.4246 instead of the true 0.3304, because the 53 hard examples get a fifth of the weight instead of 53/107753 / 1077, about 5 %. Weighting by batch size recovers 0.3304 exactly. In the stopping rule, the dip to 0.284 at epoch 8 is a real improvement for δ=0\delta = 0 (the best epoch moves from 6 to 8 and the wait counter restarts), but with δ=0.01\delta = 0.01 neither 0.285 nor 0.284 beats 0.29−0.010.29 - 0.01, so the run stops three epochs after epoch 5.

Play with the stopping rule

The lab draws illustrative curves (smooth formulas plus seeded noise, not a real training run) and applies exactly this rule: the shaded window is the wait counter, the run stops when it reaches the patience, and the best epoch is restored. Raise the noise and watch a small patience stop too early; raise minDelta and late small improvements stop counting. With the starting values (patience 5, no minDelta, noise 0.01, run 1) training stops at epoch 47 and restores epoch 42, which is also the lowest validation loss of the full 100 epochs.

0.00.20.40.60.81.0020406080100epochlossLoss per epoch (toy curves, not real training)best 42stop 47training lossvalidation lossEpoch 47best val 0.3108at epoch 42wait 5 / 5Stopped at epoch 47.Restore epoch 42.Illustrative only:formula curves plusseeded noise, not atrained model.

fit and evaluate

python · try it yourself
import copy
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

def evaluate(model, loader, loss_fn):
    model.eval()
    total_loss, correct, n = 0.0, 0, 0
    with torch.no_grad():
        for xb, yb in loader:
            logits = model(xb)
            total_loss += loss_fn(logits, yb).item() * len(yb)     # weight by batch size
            correct += (logits.argmax(1) == yb).sum().item()
            n += len(yb)
    return {"loss": total_loss / n, "acc": correct / n}

def fit(model, train_loader, val_loader, loss_fn, optimizer, epochs, scheduler=None, patience=None):
    history, best, best_state, wait = [], float("inf"), None, 0
    for epoch in range(1, epochs + 1):
        model.train()
        run_loss, n = 0.0, 0
        for xb, yb in train_loader:
            loss = loss_fn(model(xb), yb)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            run_loss += loss.item() * len(yb); n += len(yb)
        if scheduler is not None:
            scheduler.step()
        val = evaluate(model, val_loader, loss_fn)
        history.append({"epoch": epoch, "train_loss": run_loss / n, **{f"val_{k}": v for k, v in val.items()}})
        if val["loss"] < best:
            best, wait = val["loss"], 0
            best_state = copy.deepcopy(model.state_dict())
        else:
            wait += 1
            if patience is not None and wait >= patience:
                break
    model.load_state_dict(best_state)                       # restore the best epoch
    return history

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
ds = lambda X, y: TensorDataset(torch.tensor(X, dtype=torch.float32), torch.tensor(y))

torch.manual_seed(0)
train_loader = DataLoader(ds(X_tr, y_tr), batch_size=64, shuffle=True, generator=torch.Generator().manual_seed(0))
val_loader = DataLoader(ds(X_va, y_va), batch_size=256)
test_loader = DataLoader(ds(X_te, y_te), batch_size=256)
model = nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 10))
optimizer = torch.optim.Adam(model.parameters(), lr=3e-3)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=60)
loss_fn = nn.CrossEntropyLoss()

history = fit(model, train_loader, val_loader, loss_fn, optimizer, epochs=60, scheduler=scheduler, patience=8)
for h in history:
    if h["epoch"] in (1, 5, 10, 20) or h is history[-1]:
        print(f"epoch {h['epoch']:2d}  train loss {h['train_loss']:.4f}  val loss {h['val_loss']:.4f}  val acc {h['val_acc']:.3f}")
best = min(history, key=lambda h: h["val_loss"])
print("stopped after", len(history), "epochs; best epoch", best["epoch"], f"val loss {best['val_loss']:.4f}")
print("restored model on validation:", {k: round(v, 4) for k, v in evaluate(model, val_loader, loss_fn).items()})
print("test, once at the end:", {k: round(v, 4) for k, v in evaluate(model, test_loader, loss_fn).items()})
epoch  1  train loss 2.0232  val loss 1.6230  val acc 0.839
epoch  5  train loss 0.2915  val loss 0.2791  val acc 0.933
epoch 10  train loss 0.1300  val loss 0.1704  val acc 0.947
epoch 20  train loss 0.0597  val loss 0.1282  val acc 0.975
epoch 35  train loss 0.0317  val loss 0.1222  val acc 0.972
stopped after 35 epochs; best epoch 27 val loss 0.1218
restored model on validation: {'loss': 0.1218, 'acc': 0.975}
test, once at the end: {'loss': 0.1468, 'acc': 0.9639}

A 64-128-10 MLP with Adam at learning rate 0.003 and a cosine schedule planned over 60 epochs. The validation loss falls from 1.6230 after the first epoch to its minimum of 0.1218 at epoch 27; eight epochs without improvement later, at epoch 35, early stopping ends the run. Re-evaluating the restored model gives exactly the best epoch's validation loss, 0.1218 (accuracy 0.975), which is the check that the restore worked. The test set, used once and only now, gives a loss of 0.1468 and an accuracy of 0.9639 on 360 images: a little worse than validation, as expected, since the stopping epoch was chosen on validation.

Design decisions packed into those forty lines:

Line Why
model.train() at the start of every epoch, model.eval() in evaluate dropout and batch norm behave correctly in both phases, even after an evaluation mid-training
torch.no_grad() in evaluate no graph is built, so evaluation is faster and uses less memory
loss.item() * len(yb) and one division by n the size-weighted mean from the formula above
.item() only for logging keeps no graph alive; on a GPU it synchronises once per batch, which is acceptable at this scale (devices)
the train loss is the running mean during the epoch free, but measured while the weights change and with dropout on; for a clean number call evaluate on the training loader
scheduler.step() once per epoch, after the optimizer steps the order PyTorch expects; schedules defined per step (warm-up) move it into the inner loop
copy.deepcopy(model.state_dict()) state_dict() returns references to the live tensors; without a copy the "best" weights keep changing
restore the best state at the end the returned model is the early-stopped one, matching the reported validation score

Extending it without rewriting it

The function is deliberately small. Common extensions are a few lines each:

  • A device: add device as an argument, call model.to(device) before creating the optimizer, and move each batch with xb, yb = xb.to(device), yb.to(device) in both functions.
  • Gradient clipping: torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm) between backward() and step() (gradient clipping).
  • Per-step schedules such as warm-up plus cosine (OneCycleLR, LambdaLR): call scheduler.step() after every optimizer.step() instead of once per epoch.
  • Other metrics: let evaluate collect all predictions and labels and compute F1, AUC or a confusion matrix from them; metrics that are not means of per-example values cannot be averaged over batches at all.
  • Batches that are not (x, y) pairs (dicts, padded sequences with masks): pass a step(model, batch) function that returns the loss and the number of examples, and keep the rest of the loop unchanged.
  • Mixed precision and gradient accumulation: covered in memory, mixed precision and multiple devices.
  • Full checkpoints to disk that can resume an interrupted run: checkpoints, seeds and reproducibility.

When the loop grows beyond this (many callbacks, logging to an experiment tracker, multiple GPUs), libraries such as PyTorch Lightning, Hugging Face Accelerate or Keras 3 provide the same structure with the extensions built in. Knowing what your forty lines do is what lets you trust, or debug, theirs.

Pitfalls

  • Averaging batch means. Biased whenever batches differ in size; weight by the batch size.
  • Comparing the running training loss with the validation loss. The training number is averaged over a changing model with dropout on; it is not comparable in level, only in trend.
  • Keeping model.state_dict() without copying. The saved "best" weights are the final weights.
  • Calling scheduler.step() per batch for a per-epoch schedule (or the reverse). The learning rate decays 17 times too fast or too slowly with 17 batches per epoch.
  • Early stopping on the test set, or reporting the validation score of the selected epoch as the final result. Select on validation, report the test score once.
  • Restoring nothing. Without the restore, the model returned is the one from the last epoch, up to patience epochs past the best.

Practice

  1. A validation loader has batches of 256, 256 and 104 examples with mean losses 0.20, 0.22 and 0.40. Compute the correct mean loss and the mean of batch means.
Answer

Correct: (256⋅0.20+256⋅0.22+104⋅0.40)/616=(51.2+56.32+41.6)/616=149.12/616≈0.2421(256 \cdot 0.20 + 256 \cdot 0.22 + 104 \cdot 0.40) / 616 = (51.2 + 56.32 + 41.6) / 616 = 149.12 / 616 \approx 0.2421. Mean of batch means: (0.20+0.22+0.40)/3≈0.2733(0.20 + 0.22 + 0.40) / 3 \approx 0.2733, too high by about 0.03.

  1. Add a device argument to fit and evaluate. Which lines change?
Answer

In both loops, for xb, yb in loader: is followed by xb, yb = xb.to(device), yb.to(device). The model is moved by the caller before the optimizer is created (model.to(device)), since the optimizer is passed in already built. evaluate returns Python numbers through .item(), so nothing else changes.

  1. Change fit so that it also returns the epoch whose weights were restored, and use it to check that re-evaluating the model reproduces that epoch's validation loss.
Answer

Keep best_epoch = epoch next to best_state, return history, best_epoch, then:

python
history, best_epoch = fit(...)
val = evaluate(model, val_loader, loss_fn)
assert abs(val["loss"] - history[best_epoch - 1]["val_loss"]) < 1e-9

The assertion fails if the restore is missing or if the stored state was a reference instead of a copy.

Test yourself

Why does evaluate accumulate loss.item() * len(yb) and divide by the total count once?

  1. It is faster than averaging
  2. To compute the mean over all examples; averaging batch means over-weights a smaller last batch
  3. Because CrossEntropyLoss returns a sum
  4. To avoid calling .item()

With patience p=8p = 8, the best validation loss came at epoch 27. When does training stop if no later epoch improves?

  1. After epoch 27
  2. After epoch 34
  3. After epoch 35
  4. After the last planned epoch

What goes wrong with best_state = model.state_dict() (no copy)?

  1. Nothing
  2. It holds references to the live parameters, so the restored "best" weights are the final ones
  3. It raises an error at load_state_dict
  4. It copies the optimizer state too

In the recorded run, the restored model gave val loss 0.1218 and test loss 0.1468. Which statement is right?

  1. The test score is the honest estimate; validation was used to choose the epoch, so it is optimistic
  2. The model overfits the test set
  3. The two numbers should be equal
  4. The test set should have been used for early stopping