Sign in

Callbacks

Training callbacks

Training hooks kept outside the fit loop: early stopping, model checkpoints and metric logging, called at fixed points of training.

Overview

A training loop has one job: step, step, step. But around it you want other things to happen. Stop when the model has stopped improving. Save the best version so far. Write the numbers down. Putting all that inside the loop makes it long and hard to change. Callbacks are small objects the loop calls at fixed moments, such as the end of each epoch (one pass over the data). Each one looks at the latest metrics and does its own job, and the loop stays short.

A short history

Callbacks are a software pattern, with no single inventor, for letting outside code act at fixed points of a loop. The best known one, early stopping, is much older than the pattern's use in deep learning: stopping when validation error rises was common practice for neural networks by the early 1990s, and Lutz Prechelt's 1998 study Early Stopping, But When? compared the stopping rules. The Keras library, released by Francois Chollet in 2015, made the callback interface standard.

How it works

  1. The loop owns a TrainState holding the parameter arrays and a stop_training flag.
  2. It calls on_train_begin once, on_epoch_end(epoch, logs, state) after every epoch, and on_train_end once.
  3. EarlyStopping reads the monitored metric from logs. An improvement larger than min_delta becomes the new best and resets a counter. Otherwise the counter goes up by one.
  4. When the counter reaches patience, it sets stop_training. At the end it copies the best parameters back if restore_best is on.
  5. ModelCheckpoint writes the parameters to an .npz file, only on improvement or every epoch, under a temporary name that is then renamed.
  6. MetricLogger keeps the metrics in memory and optionally in a CSV file. CallbackList runs several callbacks as one and build_callbacks assembles the usual set from a config.

Watch out for

  • A patience that is too small stops on an ordinary noisy wobble of the validation loss, before the model has finished learning.
  • With mode set the wrong way round (min for an accuracy), every increase counts as getting worse and training stops after patience epochs.
  • Without restore_best, the model you keep is the one from the last epoch, which is patience epochs past its best.
  • Early stopping picks the stopping epoch using the validation set, so the validation score at that epoch is slightly optimistic. Keep a test set for the final number.
  • The loop must check state.stop_training itself. A callback can only raise the flag, it cannot break out of the loop.

Use cases

When to use it

In any training loop that runs for more than a few epochs. Early stopping is a cheap guard against overfitting when a validation set exists, and checkpoints make long runs survivable.

In industry

Deep learning research
Long image or language model runs save a checkpoint every epoch, so a crashed or preempted job restarts from the last checkpoint and not from zero.
Applied tabular modelling
Gradient boosting and neural network training stop when the validation metric has not improved for a set number of rounds, which saves compute and limits overfitting.
Cloud training
Teams on interruptible low-cost machines rely on checkpoint callbacks, because the provider may take a machine back at short notice.

Choosing it: what must hold

  • An iterative training loop that exposes fixed points such as the end of each epoch.
  • For early stopping, a validation set separate from the training data and from the final test set.
  • A metric logged every epoch under a stable name.
  • Storage for checkpoints when long runs must be recoverable.

When to choose something else

IfUse instead
The model is fitted in one shot with no epochs, such as linear regression by a closed form or a single decision treeNo callbacks. Fit once and evaluate
There is no validation set to monitorA fixed number of epochs, with weight decay in the trainer lesson for regularisation
You want the full history kept and compared across runsThe experiment tracking lesson, called from a logging callback

Math foundations

  1. What counts as an improvement

    improvedt  ⟺  vt<v∗−δ(mode min),vt>v∗+δ(mode max)\text{improved}_t \iff v_t < v^{*} - \delta \quad (\text{mode min}), \qquad v_t > v^{*} + \delta \quad (\text{mode max})

    The new value must beat the best so far by more than δ\delta. A positive δ\delta stops tiny, meaningless gains from keeping training alive.

  2. The patience counter

    ct={0if improvedtct−1+1otherwisec_t = \begin{cases} 0 & \text{if improved}_t \\ c_{t-1} + 1 & \text{otherwise} \end{cases}

    The number of epochs in a row without an improvement. Any improvement sets it back to zero.

  3. The stopping rule

    stop at the first t with ct≥p,tstop=t∗+p\text{stop at the first } t \text{ with } c_t \ge p, \qquad t_{\text{stop}} = t^{*} + p

    Training stops pp epochs after the best epoch t∗t^{*}, since no epoch in between improved on it.

  4. Restoring the best parameters

    θ←θt∗\theta \leftarrow \theta_{t^{*}}

    With restore_best, the parameters saved at the best epoch are written back when training ends, so the extra pp epochs cost time but do not harm the model.

Symbols

vtv_t
monitored metric at the end of epoch t
v∗v^{*}
best value seen so far
δ\delta
min_delta, the smallest change that counts
ctc_t
epochs in a row without improvement, after epoch t
pp
patience
t∗t^{*}
epoch of the best value
tstopt_{\text{stop}}
epoch at which training is stopped
θ\theta
the model's parameters

Worked by hand

The validation loss over epochs 0 to 7 is 0.50, 0.40, 0.35, 0.36, 0.34, 0.345, 0.35, 0.36. Use mode min, p=3p = 3 and δ=0\delta = 0.

t=0,1,2:improved,v∗=0.35,c=0t = 0, 1, 2: \quad \text{improved}, \quad v^{*} = 0.35, \quad c = 0
t=3:0.36≮0.35  ⇒  c=1t=4:0.34<0.35  ⇒  v∗=0.34,  c=0t = 3: \quad 0.36 \not< 0.35 \;\Rightarrow\; c = 1 \qquad\quad t = 4: \quad 0.34 < 0.35 \;\Rightarrow\; v^{*} = 0.34,\; c = 0
t=5,6,7:0.345,  0.35,  0.36≮0.34  ⇒  c=1,  2,  3t = 5, 6, 7: \quad 0.345,\; 0.35,\; 0.36 \not< 0.34 \;\Rightarrow\; c = 1,\; 2,\; 3
tstop=t∗+p=4+3=7t_{\text{stop}} = t^{*} + p = 4 + 3 = 7

Training stops after epoch 7 and the parameters from epoch 4 are restored. The brief rise at epoch 3 did not stop it, because the counter was reset at epoch 4.

Visual example

Loading the example.

Try this

  • Press Step and watch the counter c rise on an epoch without improvement and fall back to 0 on a new best.
  • Raise min_delta to 0.02: the small gains near the bottom of the curve stop counting and training ends sooner.
  • Switch to the worked example and set patience to 3: training stops after epoch 7 and epoch 4 is restored.

Code sample

import numpy as np
from impl import TrainState, build_callbacks
from config import CallbacksConfig

rng = np.random.default_rng(0)
X, X_val = rng.normal(size=(200, 3)), rng.normal(size=(50, 3))
true_w = np.array([1.0, -2.0, 0.5])
y, y_val = X @ true_w, X_val @ true_w

state = TrainState(params={"w": np.zeros(3)})
callbacks = build_callbacks(CallbacksConfig(monitor="val_loss", patience=3, min_delta=1e-8))
callbacks.on_train_begin(state)
for epoch in range(1000):
    w = state.params["w"]
    w -= 0.1 * 2 * X.T @ (X @ w - y) / len(y)                     # one gradient step
    logs = {"train_loss": float(((X @ w - y) ** 2).mean()), "val_loss": float(((X_val @ w - y_val) ** 2).mean())}
    callbacks.on_epoch_end(epoch, logs, state)
    if state.stop_training:
        break
callbacks.on_train_end(state)
print(epoch, state.params["w"])     # stops long before epoch 1000 with w close to [1, -2, 0.5]
Read the implementation (214 lines)
"""Training callbacks: early stopping, model checkpoints and metric logging as hooks around a fit loop.

Standard library and NumPy only. A training loop owns a `TrainState` (the parameter arrays and a
stop flag) and calls three hooks on a `CallbackList`:

    callbacks.on_train_begin(state)
    for epoch in ...:
        ... train one epoch ...
        callbacks.on_epoch_end(epoch, logs, state)     # logs = {"train_loss": ..., "val_loss": ...}
        if state.stop_training: break
    callbacks.on_train_end(state)

The loop stays free of early-stopping, saving and logging code, and each concern can be tested alone.
"""
from __future__ import annotations

import csv
import os
from dataclasses import dataclass, field

import numpy as np

try:
    from .config import CallbacksConfig
except ImportError:  # run from the template's own folder
    from config import CallbacksConfig


@dataclass
class TrainState:
    """What the loop shares with its callbacks.

    params:        dict from name to parameter array. Callbacks read it (checkpoint) and may write into
                   the arrays in place (restore best).
    stop_training: a callback sets this to True to ask the loop to stop after the current epoch.
    """

    params: dict = field(default_factory=dict)
    stop_training: bool = False


class Callback:
    """Base class. Override the hooks you need; the defaults do nothing."""

    def on_train_begin(self, state: TrainState) -> None:
        """Called once before the first epoch."""

    def on_epoch_end(self, epoch: int, logs: dict, state: TrainState) -> None:
        """Called after every epoch. epoch counts from 0, logs maps metric names to numbers."""

    def on_train_end(self, state: TrainState) -> None:
        """Called once after the last epoch, also when training stopped early."""


def _improved(value: float, best: float | None, mode: str, min_delta: float) -> bool:
    """True when `value` beats `best` by more than min_delta in the given direction."""
    if best is None:
        return True
    return value < best - min_delta if mode == "min" else value > best + min_delta


def _monitored(logs: dict, monitor: str) -> float:
    if monitor not in logs:
        raise KeyError(f"metric {monitor!r} is not in the logs, available: {sorted(logs)}")
    return float(logs[monitor])


class EarlyStopping(Callback):
    """Stop when the monitored metric has not improved for `patience` epochs.

    After training: best (best value seen), best_epoch, stopped_epoch (None when it never fired).
    """

    def __init__(self, monitor: str = "val_loss", mode: str = "min", patience: int = 5,
                 min_delta: float = 0.0, restore_best: bool = True) -> None:
        self.monitor, self.mode, self.patience = monitor, mode, patience
        self.min_delta, self.restore_best = min_delta, restore_best
        self.on_train_begin(TrainState())

    def on_train_begin(self, state: TrainState) -> None:
        self.best: float | None = None
        self.best_epoch: int | None = None
        self.stopped_epoch: int | None = None
        self.wait = 0
        self._best_params: dict | None = None

    def on_epoch_end(self, epoch: int, logs: dict, state: TrainState) -> None:
        value = _monitored(logs, self.monitor)
        if _improved(value, self.best, self.mode, self.min_delta):
            self.best, self.best_epoch, self.wait = value, epoch, 0
            if self.restore_best:
                self._best_params = {name: array.copy() for name, array in state.params.items()}
            return
        self.wait += 1
        if self.wait >= self.patience:
            self.stopped_epoch = epoch
            state.stop_training = True

    def on_train_end(self, state: TrainState) -> None:
        if self.restore_best and self._best_params is not None:
            for name, array in self._best_params.items():
                state.params[name][...] = array      # write in place so the model sees the restored values


def load_checkpoint(path: str) -> dict:
    """Read a checkpoint written by ModelCheckpoint: {"params": {name: array}, "epoch": int, "value": float}."""
    with np.load(path) as data:
        params = {key[len("param:"):]: data[key] for key in data.files if key.startswith("param:")}
        return {"params": params, "epoch": int(data["meta:epoch"]), "value": float(data["meta:value"])}


class ModelCheckpoint(Callback):
    """Save the parameters to .npz files.

    save_best_only=True rewrites <directory>/best.npz whenever the monitored metric improves.
    save_best_only=False writes <directory>/epoch-XXXX.npz after every epoch.
    `saved` lists the paths written, in order.
    """

    def __init__(self, directory: str, monitor: str = "val_loss", mode: str = "min",
                 save_best_only: bool = True, min_delta: float = 0.0) -> None:
        self.directory, self.monitor, self.mode = directory, monitor, mode
        self.save_best_only, self.min_delta = save_best_only, min_delta
        self.on_train_begin(TrainState())

    def on_train_begin(self, state: TrainState) -> None:
        self.best: float | None = None
        self.saved: list[str] = []

    def _save(self, name: str, epoch: int, value: float, state: TrainState) -> None:
        os.makedirs(self.directory, exist_ok=True)
        path = os.path.join(self.directory, name)
        arrays = {f"param:{key}": array for key, array in state.params.items()}
        with open(path + ".tmp", "wb") as handle:        # write, then rename: a checkpoint is never half a file
            np.savez(handle, **arrays, **{"meta:epoch": epoch, "meta:value": value})
        os.replace(path + ".tmp", path)
        self.saved.append(path)

    def on_epoch_end(self, epoch: int, logs: dict, state: TrainState) -> None:
        value = _monitored(logs, self.monitor)
        if not self.save_best_only:
            self._save(f"epoch-{epoch:04d}.npz", epoch, value, state)
        elif _improved(value, self.best, self.mode, self.min_delta):
            self.best = value
            self._save("best.npz", epoch, value, state)


class MetricLogger(Callback):
    """Keep the logs of every `every`-th epoch in `history` and, when `path` is given, append them to a CSV file.

    history: list of dicts {"epoch": ..., metric: value, ...}.
    The CSV columns are fixed by the first logged epoch; a metric missing later is left empty.
    """

    def __init__(self, path: str = "", every: int = 1) -> None:
        self.path, self.every = path, every
        self.on_train_begin(TrainState())

    def on_train_begin(self, state: TrainState) -> None:
        self.history: list[dict] = []
        self._columns: list[str] | None = None

    def on_epoch_end(self, epoch: int, logs: dict, state: TrainState) -> None:
        if epoch % self.every:
            return
        row = {"epoch": epoch, **{name: float(value) for name, value in logs.items()}}
        self.history.append(row)
        if not self.path:
            return
        first = self._columns is None
        if first:
            self._columns = list(row)
            os.makedirs(os.path.dirname(os.path.abspath(self.path)), exist_ok=True)
        with open(self.path, "w" if first else "a", newline="", encoding="utf-8") as handle:
            writer = csv.DictWriter(handle, fieldnames=self._columns, extrasaction="ignore")
            if first:
                writer.writeheader()
            writer.writerow(row)

    def curve(self, metric: str) -> list[float]:
        """The logged values of one metric, in epoch order."""
        return [row[metric] for row in self.history if metric in row]


class CallbackList(Callback):
    """Call several callbacks in order, as if they were one."""

    def __init__(self, callbacks=()) -> None:
        self.callbacks = list(callbacks)

    def on_train_begin(self, state: TrainState) -> None:
        for callback in self.callbacks:
            callback.on_train_begin(state)

    def on_epoch_end(self, epoch: int, logs: dict, state: TrainState) -> None:
        for callback in self.callbacks:
            callback.on_epoch_end(epoch, logs, state)

    def on_train_end(self, state: TrainState) -> None:
        for callback in self.callbacks:
            callback.on_train_end(state)


def build_callbacks(config: CallbacksConfig | None = None) -> CallbackList:
    """The standard set described by a config: a MetricLogger, a ModelCheckpoint when checkpoint_dir is
    set, and an EarlyStopping when patience is above 0. The logger comes first so the stopping epoch is
    logged too; early stopping comes last so the checkpoint of that epoch is written before it restores."""
    cfg = config or CallbacksConfig()
    callbacks: list[Callback] = [MetricLogger(cfg.log_path, cfg.log_every)]
    if cfg.checkpoint_dir:
        callbacks.append(ModelCheckpoint(cfg.checkpoint_dir, cfg.monitor, cfg.mode, cfg.save_best_only, cfg.min_delta))
    if cfg.patience:
        callbacks.append(EarlyStopping(cfg.monitor, cfg.mode, cfg.patience, cfg.min_delta, cfg.restore_best))
    return CallbackList(callbacks)
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
10, run with python3 -m unittest -v

Practice

Feed the eight losses from the worked example to EarlyStopping(monitor="val_loss", patience=3) by calling on_epoch_end(epoch, {"val_loss": v}, state) on a TrainState. Print wait, best_epoch and state.stop_training each time. Repeat with min_delta=0.02 and explain why it stops earlier.

Check on learning

  1. With min_delta 0.02 the same loss curve stops at epoch 5 with the best at epoch 2, not at epoch 7 with the best at epoch 4. Which result is better, and what does it depend on?
    A way to think about it

    Ask whether the drop from 0.35 to 0.34 is a real gain or noise. Think about how much the validation loss moves between two runs that differ only in the seed.

  2. Why does early stopping act against overfitting even though it never changes the model or the loss?
    A way to think about it

    Watch the training loss and the validation loss over time. Find the moment they part ways and ask what the model learns after that point.

  3. Your validation loss is noisy and jumps by about 0.01 from epoch to epoch. How should that shape your choice of patience and min_delta?
    A way to think about it

    A rule that reacts to changes smaller than the noise is reacting to noise. Compare both settings with the size of the wobble.

  4. With save_best_only you keep one file, and without it one file per epoch. When is the second worth the disk space?
    A way to think about it

    Think about resuming a crashed run from its latest state, and about wanting a model from an epoch that was not the best on the monitored metric.

  5. Why keep these behaviours in callbacks instead of writing them directly into the training loop?
    A way to think about it

    Imagine three projects that need different mixes of stopping, saving and logging. Count how many versions of the loop you would maintain each way.