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
- At the start of each epoch (one pass over the data), shuffle the row order and cut it into batches of
batch_size. - For each batch, call the model's
loss_and_gradsto get the loss and the gradient of every parameter. - Add up the gradients of
accumulate_stepsbatches and divide by their number, giving one averaged gradient. - If set, add weight decay to the gradient, then clip the gradient when its overall norm exceeds
max_grad_norm. - Take one optimizer step: update the velocity with
momentumand move the parameters against it, scaled bylr. - Every
eval_everyepochs compute the loss on validation data. Stop atmax_steps, or when theon_epoch_endhook 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 , 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
| If | Use instead |
|---|---|
| The model is not trained by gradients, such as a decision tree, Random Forest, KNN or Naive Bayes | That model's own fitting procedure |
| Training needs more than one device | The distributed data-parallel training lesson |
| A small linear model has an exact solution | Linear Regression solved in closed form |
Math foundations
Gradient accumulation
The gradients of batches are averaged before one step. With equal batch sizes this is the gradient of one batch times as large, without holding it in memory at once.
Weight decay
Adds a pull toward zero in proportion to each parameter's size. It is the gradient of the penalty and discourages large weights.
Clipping the global norm
If the gradient, taken as one long vector over all parameters, is longer than , it is scaled down to length . The direction does not change.
Momentum
The velocity is a decaying sum of past gradients. Directions that keep agreeing build up speed and directions that flip sign cancel out.
The parameter update
Move against the velocity, scaled by the learning rate. With the velocity is the gradient and this is plain SGD.
Optimizer steps per epoch
There are batches per epoch and one step per batches. Leftover batches at the end of an epoch still get a step.
Symbols
- gradient of the loss on batch j
- accumulate_steps
- gradient averaged over the accumulated batches
- the model's parameters
- weight_decay
- max_grad_norm
- velocity, the running sum of gradients
- momentum
- learning rate, lr
- number of training rows and batch_size
- optimizer steps per epoch
Worked by hand
Parameters start at with zero velocity. The gradient is in two steps running. Use , and .
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 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
- With
batch_size8 andaccumulate_steps4 the trainer steps on the average of 32 samples. In what ways is that the same asbatch_size32, 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.
- 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.
- 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 to each direction separately.
- You add momentum 0.9 to a run that was stable at
lr0.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 . Work out the effective step size before and after.
- Training loss keeps going down while validation loss starts to rise after epoch 30. What is happening, and how do
on_epoch_endandweight_decayeach 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.