Sign in

Trainer

Training loop (trainer)

The fit loop: epochs, mini-batch steps, gradient accumulation, weight decay, gradient clipping, SGD with momentum and periodic validation.

Overview

Training a model is a loop. Take a small batch of data, measure how wrong the model is, find the direction that would make it less wrong, and nudge the parameters that way. Repeat many times. A trainer is that loop with a few practical refinements: average several batches before stepping when one batch is too small, limit the size of a step so one bad batch cannot throw the model off, keep some momentum from earlier steps, and check on held-out data from time to time.

A short history

The fit loop combines several ideas. Robbins and Monro introduced stochastic approximation in 1951, the basis of stochastic gradient descent. Boris Polyak described the momentum method in 1964. Rumelhart, Hinton and Williams popularised backpropagation in 1986, which made gradient training of multi-layer networks practical. Pascanu, Mikolov and Bengio analysed exploding gradients in 2013 and recommended clipping the gradient norm. Frameworks later packaged the loop as a reusable trainer.

How it works

  1. At the start of each epoch (one pass over the data), shuffle the row order and cut it into batches of batch_size.
  2. For each batch, call the model's loss_and_grads to get the loss and the gradient of every parameter.
  3. Add up the gradients of accumulate_steps batches and divide by their number, giving one averaged gradient.
  4. If set, add weight decay to the gradient, then clip the gradient when its overall norm exceeds max_grad_norm.
  5. Take one optimizer step: update the velocity with momentum and move the parameters against it, scaled by lr.
  6. Every eval_every epochs compute the loss on validation data. Stop at max_steps, or when the on_epoch_end hook returns True.

Watch out for

  • A learning rate that is too high makes the loss jump or grow without limit, and one that is too low makes it fall so slowly that training looks stuck.
  • Clipping caps the size of a step but keeps its direction. If almost every step is clipped, the threshold has become the real learning rate.
  • Momentum multiplies the long-run step size by about 1/(1−μ)1 / (1 - \mu), so adding momentum 0.9 to a tuned learning rate makes steps roughly ten times larger.
  • Accumulation reduces the number of optimizer steps per epoch, so with the same number of epochs the model takes fewer steps.
  • This is a single-process NumPy loop with hand-written gradients for small models. It has no automatic differentiation, no GPU and no mixed precision, which large frameworks add to the same structure.

Use cases

When to use it

As the skeleton of any gradient-based training. Use accumulation when the batch you want does not fit in memory, clipping when gradients occasionally explode, and max_steps when the budget is counted in steps.

In industry

Language modelling
Large Transformer models are trained with gradient accumulation, because the batch size that works best does not fit in the memory of one device.
Speech and sequence models
Recurrent networks such as LSTMs occasionally produce very large gradients. Clipping the gradient norm keeps one bad batch from wrecking the weights.
Applied teams
A company retraining a ranking model weekly sets a step budget and validates at fixed intervals, so every run costs the same and can be compared.

Choosing it: what must hold

  • A model with a differentiable loss that can return the gradient of every parameter.
  • Data that can be served in mini-batches.
  • A learning rate and batch size chosen, or a plan to tune them.
  • A validation set if training progress is to be monitored.

When to choose something else

IfUse instead
The model is not trained by gradients, such as a decision tree, Random Forest, KNN or Naive BayesThat model's own fitting procedure
Training needs more than one deviceThe distributed data-parallel training lesson
A small linear model has an exact solutionLinear Regression solved in closed form

Math foundations

  1. Gradient accumulation

    gˉ=1k∑j=1kgj\bar{g} = \frac{1}{k} \sum_{j=1}^{k} g_j

    The gradients of kk batches are averaged before one step. With equal batch sizes this is the gradient of one batch kk times as large, without holding it in memory at once.

  2. Weight decay

    g←gˉ+λ θg \leftarrow \bar{g} + \lambda\, \theta

    Adds a pull toward zero in proportion to each parameter's size. It is the gradient of the penalty λ2∥θ∥2\tfrac{\lambda}{2} \lVert \theta \rVert^2 and discourages large weights.

  3. Clipping the global norm

    g←g⋅min⁡ ⁣(1,  c∥g∥),∥g∥=∑all parametersg2g \leftarrow g \cdot \min\!\left(1,\; \frac{c}{\lVert g \rVert}\right), \qquad \lVert g \rVert = \sqrt{\sum_{\text{all parameters}} g^2}

    If the gradient, taken as one long vector over all parameters, is longer than cc, it is scaled down to length cc. The direction does not change.

  4. Momentum

    v←μ v+gv \leftarrow \mu\, v + g

    The velocity is a decaying sum of past gradients. Directions that keep agreeing build up speed and directions that flip sign cancel out.

  5. The parameter update

    θ←θ−η v\theta \leftarrow \theta - \eta\, v

    Move against the velocity, scaled by the learning rate. With μ=0\mu = 0 the velocity is the gradient and this is plain SGD.

  6. Optimizer steps per epoch

    S=⌈⌈n/b⌉k⌉S = \left\lceil \frac{\lceil n / b \rceil}{k} \right\rceil

    There are ⌈n/b⌉\lceil n / b \rceil batches per epoch and one step per kk batches. Leftover batches at the end of an epoch still get a step.

Symbols

gjg_j
gradient of the loss on batch j
kk
accumulate_steps
gˉ\bar{g}
gradient averaged over the accumulated batches
θ\theta
the model's parameters
λ\lambda
weight_decay
cc
max_grad_norm
vv
velocity, the running sum of gradients
μ\mu
momentum
η\eta
learning rate, lr
n, bn,\, b
number of training rows and batch_size
SS
optimizer steps per epoch

Worked by hand

Parameters start at θ=(1,1)\theta = (1, 1) with zero velocity. The gradient is g=(3,4)g = (3, 4) in two steps running. Use c=1c = 1, μ=0.9\mu = 0.9 and η=0.1\eta = 0.1.

∥g∥=32+42=5>1  ⇒  g←(3,4)×15=(0.6,  0.8)\lVert g \rVert = \sqrt{3^2 + 4^2} = 5 > 1 \;\Rightarrow\; g \leftarrow (3, 4) \times \tfrac{1}{5} = (0.6,\; 0.8)
v1=0.9×(0,0)+(0.6,0.8)=(0.6,  0.8),θ1=(1,1)−0.1×(0.6,0.8)=(0.94,  0.92)v_1 = 0.9 \times (0, 0) + (0.6, 0.8) = (0.6,\; 0.8), \qquad \theta_1 = (1, 1) - 0.1 \times (0.6, 0.8) = (0.94,\; 0.92)
v2=0.9×(0.6,0.8)+(0.6,0.8)=(1.14,  1.52),θ2=(0.94,0.92)−0.1×(1.14,1.52)=(0.826,  0.768)v_2 = 0.9 \times (0.6, 0.8) + (0.6, 0.8) = (1.14,\; 1.52), \qquad \theta_2 = (0.94, 0.92) - 0.1 \times (1.14, 1.52) = (0.826,\; 0.768)
n=320,  b=32,  k=4:S=⌈104⌉=3n = 320,\; b = 32,\; k = 4: \qquad S = \left\lceil \frac{10}{4} \right\rceil = 3

Clipping shrank the gradient to length 1. The second step is almost twice the first because momentum added the earlier gradient. With 10 batches and k=4k = 4 there are 3 steps per epoch, the last from 2 batches.

Visual example

Loading the example.

Try this

  • Press Step and click through the stages to follow one gradient from the batches to the parameter update.
  • Set max_grad_norm to 1 and compare the norm before and after clipping in the Clip stage.
  • Raise accumulate_steps to 4: there are fewer optimizer steps per epoch and each uses the mean of four batch gradients.

Code sample

import numpy as np
from impl import Trainer, MLPRegressor
from config import TrainerConfig

rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, size=(400, 1))
y = np.sin(X[:, 0])

model = MLPRegressor(n_features=1, hidden=16, seed=0)
trainer = Trainer(TrainerConfig(epochs=200, batch_size=32, lr=0.05, momentum=0.9, max_grad_norm=5.0))
history = trainer.fit(model, X[:320], y[:320], X[320:], y[320:])
print(history["train_loss"][0], history["train_loss"][-1], history["val_loss"][-1])   # train loss about 0.08 -> 0.004, last validation (epoch, loss)
Read the implementation (158 lines)
"""The fit loop: epochs, mini-batch steps, gradient accumulation, gradient clipping, SGD with momentum and
weight decay, validation, and a per-epoch hook that can stop training.

NumPy only, gradients by hand. The trainer works with any model that has
    params                       dict from name to float array (updated in place)
    loss_and_grads(X, y)         returns (mean loss over the batch, dict of gradients with the same keys)
Two such models are included: `LinearRegressor` and `MLPRegressor` (one tanh hidden layer), both with the
mean squared error loss.
"""
from __future__ import annotations

from typing import Callable

import numpy as np

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


class LinearRegressor:
    """y_hat = X @ w + b with loss mean((y_hat - y)^2).

    params: "w" shape (n_features,), "b" shape (1,).
    """

    def __init__(self, n_features: int) -> None:
        self.params = {"w": np.zeros(n_features), "b": np.zeros(1)}

    def predict(self, X: np.ndarray) -> np.ndarray:
        """X: shape (n, n_features). Returns shape (n,)."""
        return X @ self.params["w"] + self.params["b"][0]

    def loss_and_grads(self, X: np.ndarray, y: np.ndarray) -> tuple[float, dict]:
        """X: (n, n_features), y: (n,). Returns the mean squared error and its gradients."""
        error = self.predict(X) - y
        grads = {"w": 2.0 * X.T @ error / len(y), "b": np.array([2.0 * error.mean()])}
        return float((error**2).mean()), grads


class MLPRegressor:
    """One hidden layer: y_hat = tanh(X @ W1 + b1) @ w2 + b2, loss mean((y_hat - y)^2).

    params: "W1" (n_features, hidden), "b1" (hidden,), "w2" (hidden,), "b2" (1,).
    """

    def __init__(self, n_features: int, hidden: int = 16, seed: int = 0) -> None:
        rng = np.random.default_rng(seed)
        self.params = {
            "W1": rng.normal(scale=1.0 / np.sqrt(n_features), size=(n_features, hidden)),
            "b1": np.zeros(hidden),
            "w2": rng.normal(scale=1.0 / np.sqrt(hidden), size=hidden),
            "b2": np.zeros(1),
        }

    def predict(self, X: np.ndarray) -> np.ndarray:
        """X: shape (n, n_features). Returns shape (n,)."""
        p = self.params
        return np.tanh(X @ p["W1"] + p["b1"]) @ p["w2"] + p["b2"][0]

    def loss_and_grads(self, X: np.ndarray, y: np.ndarray) -> tuple[float, dict]:
        """X: (n, n_features), y: (n,). Returns the mean squared error and its gradients (backpropagation)."""
        p = self.params
        hidden = np.tanh(X @ p["W1"] + p["b1"])            # (n, hidden)
        error = hidden @ p["w2"] + p["b2"][0] - y          # (n,)
        d_out = 2.0 * error / len(y)                       # d loss / d y_hat, (n,)
        d_pre = np.outer(d_out, p["w2"]) * (1.0 - hidden**2)   # back through tanh, (n, hidden)
        grads = {"W1": X.T @ d_pre, "b1": d_pre.sum(axis=0), "w2": hidden.T @ d_out, "b2": np.array([d_out.sum()])}
        return float((error**2).mean()), grads


class Trainer:
    """Run the training loop on a model.

    After `fit`:
        history  dict with "train_loss" (mean batch loss per epoch), "val_loss" (list of (epoch, loss)),
                 "epochs" (epochs completed) and "steps" (optimizer steps taken)
    """

    def __init__(self, config: TrainerConfig | None = None) -> None:
        self.config = config or TrainerConfig()
        self.history: dict = {}
        self._velocity: dict = {}

    def _apply(self, model, grad_sum: dict, n_batches: int) -> None:
        """One optimizer step from the gradients accumulated over n_batches batches."""
        cfg = self.config
        grads = {name: total / n_batches for name, total in grad_sum.items()}   # average, not sum
        if cfg.weight_decay:
            grads = {name: g + cfg.weight_decay * model.params[name] for name, g in grads.items()}
        if cfg.max_grad_norm:
            norm = float(np.sqrt(sum((g**2).sum() for g in grads.values())))    # one norm over all parameters
            if norm > cfg.max_grad_norm:
                grads = {name: g * (cfg.max_grad_norm / norm) for name, g in grads.items()}
        for name, g in grads.items():
            if cfg.momentum:
                self._velocity[name] = cfg.momentum * self._velocity.get(name, 0.0) + g
                g = self._velocity[name]
            model.params[name] -= cfg.lr * g

    @staticmethod
    def evaluate(model, X, y, batch_size: int = 1024) -> float:
        """Mean loss of the model over a dataset, computed in batches without changing the model."""
        total = 0.0
        for start in range(0, len(y), batch_size):
            loss, _ = model.loss_and_grads(X[start: start + batch_size], y[start: start + batch_size])
            total += loss * len(y[start: start + batch_size])
        return total / len(y)

    def fit(self, model, X, y, X_val=None, y_val=None, on_epoch_end: Callable | None = None) -> dict:
        """Train `model` in place and return the history.

        X: (n, ...) training inputs, y: (n, ...) targets. X_val, y_val: optional validation data.
        on_epoch_end: function(epoch, logs) called after every epoch with logs = {"train_loss": ...,
                      "val_loss": ... (when evaluated), "step": ...}. Returning True stops training
                      (early stopping, time budgets, ...).
        """
        cfg = self.config
        X, y = np.asarray(X, dtype=float), np.asarray(y, dtype=float)
        if len(X) != len(y):
            raise ValueError(f"X has {len(X)} rows, y has {len(y)}")
        rng = np.random.default_rng(cfg.seed)
        self._velocity = {}
        self.history = {"train_loss": [], "val_loss": [], "epochs": 0, "steps": 0}
        steps = 0
        done = False
        for epoch in range(cfg.epochs):
            order = rng.permutation(len(X)) if cfg.shuffle else np.arange(len(X))
            grad_sum: dict = {}
            pending = 0                     # batches accumulated since the last optimizer step
            losses = []
            for start in range(0, len(X), cfg.batch_size):
                batch = order[start: start + cfg.batch_size]
                loss, grads = model.loss_and_grads(X[batch], y[batch])
                losses.append(loss)
                for name, g in grads.items():
                    grad_sum[name] = grad_sum.get(name, 0.0) + g
                pending += 1
                last_batch = start + cfg.batch_size >= len(X)
                if pending == cfg.accumulate_steps or last_batch:   # leftovers at the end of an epoch still count
                    self._apply(model, grad_sum, pending)
                    grad_sum, pending = {}, 0
                    steps += 1
                    if cfg.max_steps and steps >= cfg.max_steps:
                        done = True
                        break
            logs = {"train_loss": float(np.mean(losses)), "step": steps}
            self.history["train_loss"].append(logs["train_loss"])
            if X_val is not None and (epoch + 1) % cfg.eval_every == 0:
                logs["val_loss"] = self.evaluate(model, np.asarray(X_val, dtype=float), np.asarray(y_val, dtype=float))
                self.history["val_loss"].append((epoch, logs["val_loss"]))
            self.history["epochs"], self.history["steps"] = epoch + 1, steps
            if on_epoch_end is not None and on_epoch_end(epoch, logs):
                done = True
            if done:
                break
        return self.history
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
10, run with python3 -m unittest -v

Practice

Train LinearRegressor(n_features=3) with Trainer(TrainerConfig(epochs=20, batch_size=32, lr=0.05)).fit(model, X, y, X_val, y_val) on noisy linear data and print history["train_loss"] and history["steps"]. Repeat with momentum=0.9, then with accumulate_steps=4, and explain how the loss curve and the step count change.

Check on learning

  1. With batch_size 8 and accumulate_steps 4 the trainer steps on the average of 32 samples. In what ways is that the same as batch_size 32, and when could it differ?
    A way to think about it

    For a plain average of per-sample gradients the two match. Think about a short last batch, and about models with layers that use statistics of the current batch.

  2. Your loss falls steadily, then suddenly jumps to a huge value at one step and never recovers. Which trainer setting addresses this, and why does it work?
    A way to think about it

    One batch produced an enormous gradient and the step threw the parameters far away. Ask what limits the length of a single step.

  3. Why does momentum speed up training along a long, narrow valley of the loss surface?
    A way to think about it

    Across the valley the gradient keeps changing sign, along it the gradient keeps the same sign. Apply v←μv+gv \leftarrow \mu v + g to each direction separately.

  4. You add momentum 0.9 to a run that was stable at lr 0.1 and it diverges. Explain, and say what you would change.
    A way to think about it

    With a constant gradient the velocity settles at g/(1−μ)g / (1 - \mu). Work out the effective step size before and after.

  5. Training loss keeps going down while validation loss starts to rise after epoch 30. What is happening, and how do on_epoch_end and weight_decay each help?
    A way to think about it

    The model is fitting details of the training rows that do not carry over. One tool stops the fitting in time, the other makes such fitting more costly.