TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › The Training Loop, Step by Step

The Training Loop, Step by Step

Every model you have trained so far, from LinearRegression().fit(X, y) to a neural network, hides the same small program inside fit. Scikit-learn often hides it behind a closed-form solution or a specialised solver, but anything trained by gradients (logistic regression with SGD, every neural network, gradient-boosted trees in a different form) runs a training loop: take a batch of examples, make predictions, measure how wrong they are, work out which way to move each parameter, move it a little, and repeat. When you can write that loop yourself, the knobs of every deep-learning library (batch_size, epochs, lr, scheduler, callbacks) stop being magic.

This lesson names each step of the loop and runs it once in NumPy on the simplest model there is. The next three lessons grow it into a complete loop for logistic regression, for a small neural network, and then show the same loop in PyTorch.

The anatomy of one training run

inner loop: one step per batch 1 batch 2 forward 3 prediction 4 loss 5 backprop 6 update 7 next batch, until every example has been used once (one epoch) outer loop: once per epoch epoch of training steps 8 validation (no updates) 9 save if best so far next epoch, until the epoch budget or early stopping ends the run
Step What happens Where in code
1 batch take BB examples (Xb,yb)(X_b, \mathbf{y}_b) from the shuffled training set X[idx]
2 forward run the inputs through the model with the current parameters θ\theta z = X_b @ w + b
3 prediction the model's output y^\hat{\mathbf{y}} (a number, a probability, a vector of class scores) y_hat
4 loss one number that says how wrong the batch predictions are, L(θ)L(\theta) np.mean((y_hat - y_b) ** 2)
5 backprop the gradient ∇θL\nabla_\theta L: how the loss changes when each parameter moves grad_w = ...
6 update the optimizer moves the parameters against the gradient w -= lr * grad_w
7 next batch / epoch repeat until every example has been seen once: that is one epoch for epoch ...: for batch ...:
8 validation measure the loss or metric on held-out data, with no updates val_loss = ...
9 save keep a copy (checkpoint) of the parameters when validation improves best = w.copy()

The update in step 6 is, for plain gradient descent with learning rate η\eta,

θ←θ−η ∇θL(θ;Xb,yb)\theta \leftarrow \theta - \eta \, \nabla_\theta L(\theta; X_b, \mathbf{y}_b)

Everything else in this course plugs into one of these boxes. Losses are box 4 (MSE, MAE, Huber, cross-entropy). Optimizers are box 6 (SGD, Adam). Metrics and validation strategies are box 8. Early stopping and checkpointing are box 9.

Two loops, three words

  • An iteration (or step) is one pass through boxes 1 to 6: one batch, one parameter update.
  • An epoch is one pass over the whole training set. With nn training examples and batch size BB there are ⌈n/B⌉\lceil n / B \rceil steps per epoch.
  • The training run is many epochs. Its length is set by an epoch budget, a time budget or early stopping.

So 800 examples with B=32B = 32 give ⌈800/32⌉=25\lceil 800/32 \rceil = 25 steps per epoch, and 20 epochs are 500 updates. The lesson on batch size, iterations and epochs looks at how BB changes the noise of each step.

A complete loop in 30 lines

Here is the whole loop for linear regression, y^=w⊤x+b\hat{y} = \mathbf{w}^\top \mathbf{x} + b with the mean squared error. The data are synthetic, generated from known weights (2,−3,0.5)(2, -3, 0.5) and bias 11, so you can see whether training finds them. The gradient of the batch MSE is

∇wL=2BXb⊤(y^−yb),∂L∂b=2B∑i=1B(y^i−yi)\nabla_{\mathbf{w}} L = \frac{2}{B} X_b^\top (\hat{\mathbf{y}} - \mathbf{y}_b), \qquad \frac{\partial L}{\partial b} = \frac{2}{B} \sum_{i=1}^{B} (\hat{y}_i - y_i)
python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
true_w, true_b = np.array([2.0, -3.0, 0.5]), 1.0
X = rng.normal(size=(1000, 3))
y = X @ true_w + true_b + rng.normal(scale=0.5, size=1000)    # noise sd 0.5
X_tr, y_tr, X_val, y_val = X[:800], y[:800], X[800:], y[800:]  # train / validation

w, b = np.zeros(3), 0.0             # parameters
lr, batch_size, epochs = 0.05, 32, 8
best_val, best = np.inf, None
for epoch in range(epochs):
    order = rng.permutation(len(X_tr))                  # shuffle once per epoch
    for start in range(0, len(X_tr), batch_size):
        idx = order[start:start + batch_size]           # 1 batch
        Xb, yb = X_tr[idx], y_tr[idx]
        y_hat = Xb @ w + b                              # 2-3 forward, prediction
        err = y_hat - yb
        loss = np.mean(err ** 2)                        # 4 loss
        grad_w = 2 * Xb.T @ err / len(idx)              # 5 gradients
        grad_b = 2 * err.mean()
        w -= lr * grad_w                                # 6 update
        b -= lr * grad_b
    train_loss = np.mean((X_tr @ w + b - y_tr) ** 2)
    val_loss = np.mean((X_val @ w + b - y_val) ** 2)    # 8 validation
    if val_loss < best_val:                             # 9 keep the best
        best_val, best = val_loss, (w.copy(), b)
    print(f"epoch {epoch + 1}  train MSE {train_loss:.4f}  val MSE {val_loss:.4f}")

print("best val MSE", round(best_val, 4))
print("learned w", best[0].round(3), " b", round(best[1], 3))
epoch 1  train MSE 0.3591  val MSE 0.3688
epoch 2  train MSE 0.2496  val MSE 0.2730
epoch 3  train MSE 0.2491  val MSE 0.2725
epoch 4  train MSE 0.2487  val MSE 0.2687
epoch 5  train MSE 0.2488  val MSE 0.2701
epoch 6  train MSE 0.2490  val MSE 0.2725
epoch 7  train MSE 0.2492  val MSE 0.2708
epoch 8  train MSE 0.2488  val MSE 0.2693
best val MSE 0.2687
learned w [ 1.979 -2.977  0.526]  b 1.015

Read the output top to bottom:

  • Epoch 1 does most of the work. Each epoch is 25 updates (⌈800/32⌉\lceil 800/32 \rceil), and after the first 25 the training MSE is already 0.3591, down from 13.3 for the all-zero start.
  • Then it flattens near 0.25. That is the noise floor: the labels contain noise with standard deviation 0.5, so even the true weights have an expected MSE of 0.52=0.250.5^2 = 0.25. No model can do better on average.
  • Validation wobbles. With a constant learning rate, every mini-batch step jiggles the parameters, so the validation MSE moves up and down between 0.2687 and 0.2730 after epoch 2. The best epoch was the 4th, and that is the copy the loop kept.
  • The learned parameters (1.979,−2.977,0.526)(1.979, -2.977, 0.526) and 1.0151.015 are close to the true (2,−3,0.5)(2, -3, 0.5) and 11. The remaining gap is the noise in 800 examples, not a failure of the optimizer.

Linear regression has a closed-form solution, so you would never train it this way in practice. Its value here is that every quantity can be checked by hand. The same nine boxes with a different forward pass and gradient give you logistic regression and neural networks.

What the loop leaves out (for now)

This loop already has the shape of every training loop in this course. Real loops add:

  • a learning-rate schedule that changes η\eta across epochs (schedules and warm-up);
  • regularisation inside the loss or the update (weight decay and dropout);
  • early stopping: end the run when validation stops improving for a few epochs, then restore the best checkpoint;
  • gradient clipping before the update (clipping) and mixed precision for speed (float16 and bfloat16);
  • logging of the losses and metrics, so you can draw learning curves later.

Pitfalls

  • Forgetting to shuffle. If the training file is sorted (all class 0 first, or by date), unshuffled batches pull the parameters back and forth. Shuffle once per epoch, as the loop above does with a new permutation.
  • Updating during validation. Box 8 only measures. In PyTorch that means model.eval() and torch.no_grad(); in NumPy, simply do not touch the parameters.
  • Saving a reference instead of a copy. best = w stores a reference to the same array, which the next update changes in place. w.copy() stores the values.
  • Judging training by the training loss alone. A falling training loss only says the optimizer works. Whether the model generalises is what the validation loss says.

Practice

  1. A training set has 50,000 images and the batch size is 128. How many parameter updates happen in 10 epochs (the last batch of each epoch is smaller)?
Answer

⌈50000/128⌉=⌈390.6⌉=391\lceil 50000 / 128 \rceil = \lceil 390.6 \rceil = 391 steps per epoch, so 39103910 updates in 10 epochs.

  1. In the example, change lr to 0.5. What do you expect, and why?
Answer

For this problem the features have unit variance, so the MSE's curvature along each weight is about 22, and plain gradient descent is stable only for η<2/2=1\eta < 2/2 = 1 in the full-batch case. With η=0.5\eta = 0.5 it still converges, faster, but each mini-batch step is noisier; push η\eta above about 1 and the losses grow without bound. The lesson on gradient descent and the learning rate shows this in a lab.

  1. Why does the loop compute train_loss again after the epoch instead of averaging the batch losses?
Answer

The batch losses were measured with parameters that kept changing during the epoch, so their average describes a moving model. Re-evaluating at the end of the epoch measures the training loss of the parameters you would actually keep, on the same footing as the validation loss. (Many libraries report the running average anyway because it is free; it lags slightly behind.)

Test yourself

What is one iteration (step) of the training loop?

  1. One pass over the whole training set
  2. One batch: forward pass, loss, gradients and one parameter update
  3. One evaluation on the validation set
  4. One complete training run

With 1,200 training examples and batch size 50, how many steps are in one epoch?

  1. 50
  2. 24
  3. 1,200
  4. 60

Which step must never change the parameters?

  1. The optimizer update
  2. Backpropagation
  3. Validation
  4. The forward pass during training

Why does the loop store w.copy() rather than w as the best weights?

  1. Copies are faster to read
  2. w is updated in place, so a plain reference would silently change with every later step
  3. NumPy cannot store references
  4. To save memory