TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › Early Stopping and Checkpointing

Early Stopping and Checkpointing

How many epochs should you train? Too few and the model underfits; too many and it starts to memorise the training set, so the validation loss climbs again while the training loss keeps falling. Early stopping answers the question with data: watch the validation loss and stop when it has not improved for a while, then go back to the best weights. To go back you need checkpoints: saved copies of the training state. Checkpoints also let a long run survive a crash or a preempted cloud machine, which on real projects matters even more.

The rule

Track a validation metric after every epoch (here the validation loss, lower is better). Keep the best value so far and a counter:

  1. If the new value beats the best by more than min_delta, it is an improvement: save it as the best, remember the epoch and the weights, reset the counter to 0.
  2. Otherwise add 1 to the counter (the wait).
  3. When the wait reaches patience, stop. Then restore the best weights.

In symbols, epoch ee improves when ve<vbest−δmin⁡v_e < v_{\text{best}} - \delta_{\min}. This is the rule of Keras' EarlyStopping callback; PyTorch Lightning's is the same.

epochloss best epoch (restore)stop patience trainvalidation

Play with patience

The lab draws illustrative curves (a smooth formula plus seeded noise, not a real training run, as the lab says on screen): training loss keeps falling, validation loss bottoms out and slowly rises. Raise the noise σ\sigma with a small patience and the run stops on a random bump long before the real minimum. Raise the patience and the stop moves later, past the minimum, but the restored epoch stays near the best one. minDelta ignores improvements that are too small to matter.

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.

Patience trades two risks. Too small: noise in the validation curve stops training early. Too large: you waste compute (the restored weights are the same, but you trained longer to find them). Typical values are 5 to 20 epochs, or more when each "epoch" is a short evaluation interval.

Early stopping in NumPy

A real run: a degree-12 polynomial fitted by full-batch gradient descent to 15 noisy points of sin⁡πx\sin \pi x (one step per epoch), validated on 200 other points. Such a flexible model overfits if it trains long enough.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
def make(n):
    x = rng.uniform(-1, 1, n)
    return x, np.sin(np.pi * x) + rng.normal(0, 0.2, n)
x_tr, y_tr = make(15)                                    # 15 training points
x_val, y_val = make(200)                                 # 200 validation points
feats = lambda x: np.vander(x, 13, increasing=True)      # degree-12 polynomial: can overfit
F_tr, F_val = feats(x_tr), feats(x_val)
mse = lambda w, F, y: np.mean((F @ w - y) ** 2)

class EarlyStopping:
    """Stop when the monitored value has not improved by min_delta for `patience` epochs."""
    def __init__(self, patience, min_delta=0.0):
        self.patience, self.min_delta = patience, min_delta
        self.best, self.best_epoch, self.wait, self.best_w = np.inf, 0, 0, None
    def step(self, value, epoch, w):
        if value < self.best - self.min_delta:          # an improvement
            self.best, self.best_epoch, self.wait = value, epoch, 0
            self.best_w = w.copy()                        # remember the best weights
        else:
            self.wait += 1
        return self.wait >= self.patience               # True: stop now

w = np.zeros(13)
stopper = EarlyStopping(patience=300, min_delta=1e-5)
for epoch in range(1, 50001):                            # full batch: one step per epoch
    w -= 0.3 * F_tr.T @ (F_tr @ w - y_tr) / len(y_tr)
    val = mse(w, F_val, y_val)
    if epoch in (10, 100, 500, 1000):
        print(f"epoch {epoch:5d}  train MSE {mse(w, F_tr, y_tr):.4f}  val MSE {val:.4f}")
    if stopper.step(val, epoch, w):
        print(f"stopped at epoch {epoch}: no improvement since epoch {stopper.best_epoch}")
        break
print(f"val MSE at the stop {val:.4f}, with the restored best weights {mse(stopper.best_w, F_val, y_val):.4f}")
epoch    10  train MSE 0.1776  val MSE 0.4334
epoch   100  train MSE 0.0679  val MSE 0.1551
epoch   500  train MSE 0.0324  val MSE 0.0865
epoch  1000  train MSE 0.0222  val MSE 0.0673
stopped at epoch 1729: no improvement since epoch 1429
val MSE at the stop 0.0645, with the restored best weights 0.0637

The best epoch was 1429; training went on for the 300 epochs of patience and stopped at 1729. Restoring gives a validation MSE of 0.0637. Without early stopping the same loop keeps lowering the training error, and by epoch 200 000 the validation MSE has grown to about 0.28: four times worse.

Two honesty notes. First, the epoch was chosen on the validation set, so 0.0637 is slightly optimistic; report a score on a separate test set (Holdout and K-Fold). Second, early stopping works like a regulariser: gradient descent from zero fits the large, smooth components of the data first and the noise later, so stopping early limits how far the weights travel, much as weight decay does.

What a checkpoint contains

Restoring the best weights is enough for using the model. Resuming training needs everything that changes during training:

Part Why it is needed
model weights (and buffers such as batch-norm running statistics) the model itself
optimizer state (momentum, Adam's moment estimates) without it the first steps after resuming behave differently
learning-rate scheduler state, epoch and step counters the schedule continues where it was
random-number generator states (data shuffling, dropout, augmentation) the same batches and masks as an uninterrupted run
best metric so far, early-stopping counter the stopping rule continues correctly
config, code version, data version to know what produced it

The next example trains logistic regression with momentum for 6 epochs straight, then again with a "crash" after epoch 3: a checkpoint is pickled into an in-memory file, loaded back and training resumes.

python · try it yourself
import io, pickle
import numpy as np
from sklearn.datasets import make_classification

X, y = make_classification(n_samples=600, n_features=8, random_state=0)

def run_epochs(state, first, last):
    """SGD with momentum on logistic regression; state holds everything that changes."""
    w, v, rng = state["w"], state["v"], state["rng"]
    for epoch in range(first, last + 1):
        order = rng.permutation(len(y))                    # shuffling uses the RNG
        for start in range(0, len(y), 32):
            idx = order[start:start + 32]
            p = 1 / (1 + np.exp(-(X[idx] @ w)))
            v = 0.9 * v + X[idx].T @ (p - y[idx]) / len(idx)   # optimizer state: velocity
            w = w - 0.05 * v
        state.update(w=w, v=v, epoch=epoch)
    return state

fresh = lambda: {"w": np.zeros(8), "v": np.zeros(8), "epoch": 0, "rng": np.random.default_rng(0)}

straight = run_epochs(fresh(), 1, 6)                       # 6 epochs without a break

state = run_epochs(fresh(), 1, 3)                          # 3 epochs, then save a checkpoint
buf = io.BytesIO()
pickle.dump({"weights": state["w"], "optimizer": {"velocity": state["v"]},
             "epoch": state["epoch"], "rng": state["rng"].bit_generator.state}, buf)
print("checkpoint size:", len(buf.getvalue()), "bytes; keys:", list(pickle.loads(buf.getvalue())))

buf.seek(0); ckpt = pickle.load(buf)                       # ... the process crashed; resume
rng = np.random.default_rng(); rng.bit_generator.state = ckpt["rng"]
resumed = run_epochs({"w": ckpt["weights"], "v": ckpt["optimizer"]["velocity"], "rng": rng},
                     ckpt["epoch"] + 1, 6)
print("full resume identical to the straight run:", np.array_equal(resumed["w"], straight["w"]))

weights_only = run_epochs({"w": ckpt["weights"], "v": np.zeros(8), "rng": np.random.default_rng(0)}, 4, 6)
print("weights-only resume identical:", np.array_equal(weights_only["w"], straight["w"]),
      " max weight difference", round(float(np.abs(weights_only["w"] - straight["w"]).max()), 4))
checkpoint size: 477 bytes; keys: ['weights', 'optimizer', 'epoch', 'rng']
full resume identical to the straight run: True
weights-only resume identical: False  max weight difference 0.0732

With the full state the resumed run is bit-for-bit the run that never stopped. With weights only, the momentum restarts from zero and the shuffling restarts from the seed (repeating epoch 1's order), so the result drifts. The drift is small here but it makes bugs and comparisons hard to reproduce.

In PyTorch the same checkpoint is a dictionary passed to torch.save:

text
torch.save({"epoch": epoch, "model": model.state_dict(), "optimizer": opt.state_dict(),
            "scheduler": sched.state_dict(), "best_val": best, "rng": torch.get_rng_state()},
           "ckpt.pt")

and resuming calls load_state_dict on each part. Common policies: keep the last checkpoint (to resume) and the best one (to deploy), save every N steps on long runs, write to a temporary file and rename it so a crash during saving never corrupts the only copy. Only unpickle checkpoints you trust: a pickle file can run code when loaded (PyTorch's torch.load(weights_only=True), the default since 2.6, and the safetensors format avoid this).

Pitfalls

  • Early stopping on the test set. The stop epoch is a hyperparameter; choose it on validation data.
  • Forgetting to restore. The weights at the stop are patience epochs past the best.
  • Monitoring a noisy metric with tiny patience. Smooth it, raise patience or set min_delta.
  • Stopping on loss when you care about a metric (or the reverse). Monitor what you will report, with the right direction (mode="max" for accuracy).
  • Checkpoints without optimizer and RNG state, then wondering why a resumed run differs.
  • Combining early stopping with a decaying schedule whose low-learning-rate phase you never reach: the schedule's length and the patience must fit together (Learning-Rate Schedules).

Practice

  1. Validation losses for epochs 1 to 8 are 0.90, 0.70, 0.62, 0.63, 0.61, 0.615, 0.62, 0.64. With patience 2 and min_delta 0, at which epoch does training stop and which epoch is restored? And with min_delta 0.02?
Answer

min_delta 0: improvements at 1, 2, 3, then 4 (0.63) is a wait of 1, 5 (0.61) improves, 6 and 7 are waits 1 and 2, so it stops at epoch 7 and restores epoch 5. With min_delta 0.02: epoch 3 improves (0.62<0.70−0.020.62 < 0.70 - 0.02); epoch 4 is wait 1; epoch 5 needs a value below 0.62−0.02=0.600.62 - 0.02 = 0.60, and 0.61 is not, so wait 2: stop at epoch 5, restore epoch 3.

  1. You resume a run from a checkpoint that has the weights and the optimizer state but not the RNG state. Name two things that will differ from an uninterrupted run.
Answer

The order of the mini-batches (shuffling) and any random masks or augmentations (dropout, random crops) after the resume. The final model is usually similar in quality but not identical.

Test yourself

With patience 5, when does early stopping end training?

  1. After 5 epochs
  2. When the validation loss has not improved for 5 consecutive epochs
  3. When the training loss reaches 5
  4. When the validation loss rises once

In the NumPy run, the best epoch was 1429 and training stopped at 1729. Which weights should be used for the model?

  1. Those of epoch 1729
  2. Those of epoch 1429
  3. The average of both
  4. Those of epoch 1

Which part of a checkpoint makes the resumed run reproduce the same mini-batch order?

  1. The model weights
  2. The random-number generator state
  3. The learning rate
  4. The validation score

Why can a validation score chosen by early stopping be slightly optimistic?

  1. Because the training set is too small
  2. Because the stopping epoch was selected using that same validation data
  3. Because early stopping always underfits
  4. It cannot be optimistic