Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 16: Training Deep Networks — Implementation

Open in Colab

The theory chapter built every tool by hand in NumPy. Here are the same tools in PyTorch, as they are used in practice:

  1. A network with batch normalisation and dropout, and the train() / eval() switch

  2. Optimisers and a warm-up + cosine schedule

  3. A learning-rate range test

  4. Watching the gradients: per-layer norms and clipping

  5. Early stopping with a checkpoint

  6. A training monitor that says whether a run converges or diverges

torch.Size([1257, 64]) torch.Size([540, 64])

1. Batch Normalisation, Dropout, and the Two Modes

nn.BatchNorm1d and nn.Dropout behave differently in training and in evaluation. model.train() and model.eval() switch every such layer at once.

training mode, same input twice, same output? False
evaluation mode, same input twice, same output? True
evaluation mode: an image alone or in a batch of 5, same output? True

In training mode, dropout draws a new mask at every call, so the same input gives two different outputs. In evaluation mode the network is deterministic, and an image’s prediction does not depend on the other images in its batch, because batch normalisation uses its running statistics.

2. Optimisers and a Schedule

A reusable training loop. It takes any optimiser, an optional scheduler stepped after every batch, and an optional clipping norm, and returns the history.

SGD             training loss after 15 epochs 2.299, validation accuracy 0.128
SGD + momentum  training loss after 15 epochs 1.018, validation accuracy 0.709
Adam            training loss after 15 epochs 0.074, validation accuracy 0.959
AdamW           training loss after 15 epochs 0.072, validation accuracy 0.961

On this 4-layer network, plain SGD at 0.01 has barely left the starting point after 15 epochs (PyTorch’s default initialisation is smaller than He’s, so the first steps are tiny); momentum is on its way; Adam and AdamW have converged.

Warm-up followed by cosine decay, written as a LambdaLR (a factor applied to the base rate at each step):

constant          validation accuracy, last 5 epochs: [0.981, 0.97, 0.978, 0.981, 0.98]
warm-up + cosine  validation accuracy, last 5 epochs: [0.985, 0.981, 0.983, 0.983, 0.981]
Source
<Figure size 1100x340 with 2 Axes>

PyTorch also ships CosineAnnealingLR, OneCycleLR (warm-up and decay in one), StepLR and ReduceLROnPlateau (stepped with the validation loss, once per epoch).

3. A Learning-Rate Range Test

Start from a tiny rate and multiply it after every batch, recording the loss, until the loss explodes. The useful rates are where the loss falls fastest; a common choice is about a tenth of the rate where the loss is lowest.

lowest smoothed loss at lr 0.631; stopped at lr 3.16; suggested rate about 0.063
<Figure size 600x320 with 1 Axes>

4. Watching the Gradients

A forward hook records each layer’s activations; after backward(), each parameter’s .grad holds its gradient. Their norms per layer, at initialisation, for a 12-layer sigmoid network with and without batch normalisation:

batch norm False: gradient norm, first layer 3.8e-11, middle 2.1e-06, last 2.7e-01
batch norm True : gradient norm, first layer 3.8e-01, middle 3.7e-01, last 4.2e-01

Without normalisation, the first layer’s gradient is many orders of magnitude smaller than the last layer’s: it vanishes. With it, every layer receives a usable gradient.

clip_grad_norm_ returns the total norm before clipping, so logging it costs nothing. A spike in that log, just before the loss jumps, is the signature of an exploding gradient.

An 8-layer ReLU network with He initialisation (kaiming_normal_), no normalisation, trained with SGD and momentum at 0.1, with and without clipping at norm 1:

clip None: largest gradient norm seen 44.5, final training loss 1.079, validation accuracy 0.520
clip 1.0 : largest gradient norm seen 17.1, final training loss 0.174, validation accuracy 0.911

Unclipped, the gradient norm reaches several tens, the steps that follow undo much of the learning, and the network ends far behind. Clipped, the same network trains to about 0.91.

5. Early Stopping with a Checkpoint

Keep a copy of the weights (state_dict) whenever the validation loss improves; stop after patience epochs without improvement, and restore the best copy. We use the small noisy training set of the theory chapter.

stopped after 32 epochs; restored the best weights: validation loss 0.570, accuracy 0.902

6. A Training Monitor

A small function that reads a history and names what it sees, using the rules of the theory chapter’s table. It is a starting point to adapt, not an oracle.

Adam 1e-3              -> still converging: train longer
SGD 1e-4               -> stuck at chance: nothing is learned
SGD 3.0, no clipping   -> diverged: the loss became NaN or infinite

The rule for “stuck at chance” cannot tell a rate that is far too small from a dead network: after 25 epochs at 10-4, the loss has hardly left ln⁡10\ln 10 either. The gradient norms tell them apart: small but steady for a slow run, zero for dead units.

Summary

  • model.train() and model.eval() switch dropout and batch normalisation; forgetting eval() makes predictions random and batch-dependent.

  • torch.optim provides SGD, Adam and AdamW; lr_scheduler.LambdaLR writes any schedule, such as warm-up + cosine.

  • A learning-rate range test finds a good rate in one short run.

  • Per-layer gradient norms show vanishing gradients; clip_grad_norm_ both clips and reports the norm.

  • Early stopping keeps the best state_dict and restores it.

  • Simple rules on the loss history catch the common failures automatically.