Skip to content
Visual explainer 3h 30m to learn 5 steps

Early stopping, checkpoints and reproducible PyTorch runs

Use validation curves, regularisation, learning-rate choices, early stopping and checkpoints to produce a repeatable training run.

By Invicly Tech, , in AI and Machine Learning with Python. About 11 minutes to read.

Topic 20 of 34

In short

A neural network can memorise its training data, so the real goal is a model that does well on data it has not seen. Validation curves tell you when that starts to fail, and tools such as weight decay, dropout, a sensible learning rate and early stopping keep it in check. Checkpoints and seeds make the best run something you can reload and repeat.

Explained simply

A big neural network can remember every training example, including its mistakes and noise. When that happens it scores brilliantly on training data and badly on anything new. This is called overfitting, and fighting it is most of the craft of deep learning.

Your main tool is a validation set: data held back from training and checked after every epoch. Plotting training and validation loss together shows you whether the model is still learning useful patterns or has started memorising.

Several simple techniques help. Weight decay keeps weights small. Dropout randomly switches parts of the network off during training. A well-chosen learning rate stops training from crawling or bouncing around. Early stopping ends training at the point where validation results were best.

Finally, you want to be able to get the same model again. Saving checkpoints lets you reload the best version, and fixing random seeds lets you repeat a run and trust that a change in score came from your change, not from luck.

Press Play on a diagram to walk through it one step at a time.

CompareReading train and validation loss curves
Underfitting
  • Both losses high and flat
  • Model too small or lr too low
  • Train longer or add capacity
Good fit
  • Both losses fall together
  • Small, steady gap
  • Keep the best validation epoch
Overfitting
  • Train loss keeps falling
  • Validation loss turns upwards
  • Add regularisation or stop early
FlowEarly stopping with checkpoints
  1. 1
    Train one epoch
  2. 2
    Measure validation loss

    model.eval() and torch.no_grad()

  3. 3
    Improved?

    If yes, save a checkpoint and reset the counter

  4. 4
    No improvement

    Add one to the patience counter

  5. 5
    Stop and reload

    When patience runs out, load the best checkpoint

MapWays to reduce overfitting
Validation loss rising
  • More signal
    • Collect more data
    • Augment training data
  • Smaller effective model
    • Fewer or narrower layers
    • Weight decay
    • Dropout
  • Train less
    • Early stopping
    • Lower learning rate late on
  • Check the data
    • Leakage between splits
    • Noisy or wrong labels

In depth

Reading learning curves

Plot one line for training loss and one for validation loss, with epochs along the bottom. In a healthy run both fall, quickly at first and then slowly. The gap between them is the generalisation gap. A gap that stays small means the model is learning patterns that transfer. A gap that widens while validation loss climbs means overfitting has begun.

If both curves stay high, the model is underfitting: it is too small, the learning rate is too low, or the features carry little signal. Noisy, jagged validation curves often mean a small validation set, so look at the trend over several epochs rather than reacting to one bad point. Also track the metric you care about, such as accuracy or F1, because loss and accuracy do not always move together.

  • Both high: add capacity, train longer or raise the learning rate
  • Gap widening: regularise, augment or stop earlier
  • Jagged validation: use a bigger validation set or smooth the view

Weight decay and dropout

Weight decay shrinks every weight a little at each step, which discourages the network from relying on a few huge weights. With torch.optim.AdamW you set it directly, for example weight_decay=0.01, its default. AdamW applies decay separately from the gradient update, which works better with Adam than adding an L2 term to the loss.

Dropout, added with nn.Dropout(p=0.2) to 0.5 between layers, zeroes a random fraction of activations during training and scales the rest up to keep the average the same. At evaluation time it does nothing, which is why model.eval() matters. Batch normalisation and data augmentation also regularise. Start with one technique, change one setting at a time, and keep the run that gives the best validation score.

Choosing and scheduling the learning rate

The learning rate controls the size of each update. Too high and the loss jumps around or becomes NaN; too low and training crawls. Good starting points are about 1e-3 for Adam or AdamW and 0.01 to 0.1 for SGD with momentum. A quick sweep over values spaced by a factor of 10, run for a few epochs each, shows the region worth exploring.

Schedulers change the rate during training. ReduceLROnPlateau lowers it when validation loss stops improving; you call scheduler.step(val_loss) after each epoch. StepLR and cosine annealing follow a fixed plan instead. A lower rate late in training often squeezes out a little more validation performance.

CompareSymptoms of the learning rate
Too low
  • Loss falls very slowly
  • Looks like underfitting
  • Wastes compute
About right
  • Fast early drop
  • Smooth, steady progress
  • Validation follows training
Too high
  • Loss jumps or rises
  • May become NaN
  • Never settles

Checkpoints that you can trust

Save a dictionary holding model.state_dict(), optimizer.state_dict(), the scheduler state, the epoch and the best validation score. Save it whenever validation improves, plus a latest copy if runs are long and might be interrupted. To resume, rebuild the same model and optimiser classes, then call load_state_dict on each.

Security matters here. torch.load uses Python's pickle format, which can run code when loading. Since PyTorch 2.6 the weights_only argument defaults to True, which restricts loading to tensors and simple types; keep it that way and only load files you produced or trust. For sharing weights, the safetensors format stores tensors without any executable content.

Seeds and the limits of reproducibility

Call torch.manual_seed(seed) at the start, and also seed Python's random module and NumPy if you use them. Pass a seeded torch.Generator to DataLoader and random_split so shuffling repeats too. With these in place, a CPU run on the same machine and versions should give the same numbers each time.

PyTorch's reproducibility notes are clear that results are not guaranteed across releases, platforms or between CPU and GPU. Some GPU operations are non-deterministic by default; torch.use_deterministic_algorithms(True) forces deterministic versions or raises an error where none exists. Because exact repeats are fragile, a better habit is to run three or more seeds and report the mean and spread. A gain smaller than the seed-to-seed spread is not a real gain.

  • Seed torch, numpy and random
  • Pass a seeded generator to DataLoader
  • Record library versions with every run
  • Report mean and spread over several seeds

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Read validation curves~40m
  2. 2
    Add dropout and weight decay~40m
  3. 3
    Tune the learning rate~40m
  4. 4
    Stop early and save checkpoints~40m
  5. 5
    Seed runs for reproducibility~40m

Key points

  • Always judge a run on validation loss and metrics, never on training loss alone.
  • Weight decay and dropout reduce overfitting; more and more varied data helps most.
  • The learning rate is usually the most important single setting to tune.
  • Save the state_dict of the model and optimiser, not the whole pickled model object.
  • Seeds make runs repeatable on one machine and version, but not bit-identical everywhere.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
best, patience, wait = float("inf"), 5, 0
for epoch in range(100):
    train_one_epoch(model, train_dl, opt)
    val = evaluate(model, val_dl)
    if val < best:
        best, wait = val, 0
        torch.save({"model": model.state_dict(),
                    "opt": opt.state_dict(),
                    "epoch": epoch}, "best.pt")
    else:
        wait += 1
        if wait >= patience:
            break
ckpt = torch.load("best.pt", weights_only=True)
model.load_state_dict(ckpt["model"])

train_one_epoch and evaluate are your own functions from the training-loop topic.

Adding early stopping to an overfitting run

A dense network on a small tabular set reaches its lowest validation loss at epoch 12, then validation loss rises while training loss keeps falling. Step 1: set patience to 5 epochs. Step 2: save a checkpoint each time validation improves. Step 3: training stops at epoch 17 and you reload the epoch 12 weights. Expected evidence: the reloaded model's validation score matches the epoch 12 log line exactly, and the run used about a sixth of the planned 100 epochs. Rollback: delete best.pt and rerun if you change the architecture, because old checkpoints will not load into a different model.

python
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)
sched = torch.optim.lr_scheduler.ReduceLROnPlateau(opt, mode="min", factor=0.5, patience=2)
for epoch in range(100):
    train_one_epoch(model, train_dl, opt, loss_fn)
    val_loss, val_acc = evaluate(model, val_dl, loss_fn)
    sched.step(val_loss)
    print(epoch, round(val_loss, 4), opt.param_groups[0]["lr"])

Showing that a change is real, not luck

You add dropout and validation accuracy goes from 86.1 to 86.6 percent. Is that real? Step 1: write a function that sets every seed and trains from scratch. Step 2: run the baseline and the dropout version with seeds 0 to 4. Step 3: compare means and standard deviations. If the baseline is 86.0 plus or minus 0.4 and dropout is 86.5 plus or minus 0.5, the gain is within noise, so you should not claim it. Record the seeds and versions in your notes either way.

python
import random, numpy as np, torch

def set_seed(seed):
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)

scores = []
for seed in range(5):
    set_seed(seed)
    scores.append(run_experiment(dropout=0.3))  # your function
print(np.mean(scores), np.std(scores))

Quick reference

  • Judge runs by validation metrics; keep the best epoch, not the last
  • AdamW starting point: lr 1e-3, weight_decay 0.01
  • nn.Dropout only acts in train mode; model.eval() switches it off
  • Save model, optimiser, scheduler, epoch and best score in one checkpoint dict
  • torch.load(path, weights_only=True) and only for files you trust
  • Seed torch, numpy and random; pass a seeded generator to DataLoader
  • Report mean and spread over at least 3 seeds before claiming a gain

Common mistakes

  • Picking the final epoch instead of the best validation epoch.
  • Tuning against the test set until it stops being an honest estimate.
  • Loading checkpoints from unknown sources; torch.load can run code unless weights_only=True.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Training loss is 0.05 and still falling; validation loss bottomed at 0.40 and is now 0.55. What should you do first?

Question 2

2Why does PyTorch recommend weights_only=True when calling torch.load?

Question 3

3The loss turns into NaN after a few hundred steps. What is the most likely cause?

Question 4

4Two runs with different seeds score 85.2 and 86.0 percent. What does this tell you?

Question 5

5What does ReduceLROnPlateau need you to pass to scheduler.step()?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Add dropout with p=0.3 after the hidden ReLU of a two-layer network and confirm that two forward passes of the same input differ in train mode but match in eval mode.

  2. Exercise 2medium

    Save a checkpoint with model, optimiser and epoch, then rebuild a fresh model and optimiser and restore them. Check that predictions match.

  3. Exercise 3hard

    Run a learning-rate sweep over 1e-4, 1e-3, 1e-2 and 1e-1 with AdamW, 5 epochs each and 3 seeds per rate. Print the mean and standard deviation of the final validation loss per rate and choose one.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

How many epochs should I train for?
There is no fixed number. Set a generous maximum and let early stopping decide based on validation loss; the right count depends on data size, model and learning rate.
Is dropout still used in modern networks?
Yes, though less in convolutional image models, which lean on batch normalisation and augmentation. It remains common in transformers and dense networks.
Why do I get different results on my laptop and on a GPU machine?
Different hardware, libraries and some non-deterministic GPU operations change the arithmetic slightly. PyTorch does not promise identical results across platforms, so compare averages over several seeds.

Go deeper

ShareXLinkedInWhatsApp