Chapter 16: Training Deep Networks — Implementation
The theory chapter built every tool by hand in NumPy. Here are the same tools in PyTorch, as they are used in practice:
A network with batch normalisation and dropout, and the
train()/eval()switchOptimisers and a warm-up + cosine schedule
A learning-rate range test
Watching the gradients: per-layer norms and clipping
Early stopping with a checkpoint
A training monitor that says whether a run converges or diverges
import copy
import math
import numpy as np
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
torch.manual_seed(0)
X, y = load_digits(return_X_y=True)
Xtr, Xva, ytr, yva = train_test_split(X / 16, y, test_size=0.3, random_state=0, stratify=y)
Xtr, Xva = torch.tensor(Xtr, dtype=torch.float32), torch.tensor(Xva, dtype=torch.float32)
ytr, yva = torch.tensor(ytr), torch.tensor(yva)
print(Xtr.shape, Xva.shape)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.
def make_net(depth=4, width=128, bn=True, drop=0.2):
layers, n = [], 64
for _ in range(depth):
layers += [nn.Linear(n, width)] + ([nn.BatchNorm1d(width)] if bn else []) + [nn.ReLU()] + ([nn.Dropout(drop)] if drop else [])
n = width
return nn.Sequential(*layers, nn.Linear(n, 10))
net = make_net()
x = Xva[:5]
net.train(); a, b = net(x), net(x)
print('training mode, same input twice, same output?', torch.allclose(a, b))
net.eval()
with torch.no_grad(): a, b = net(x), net(x)
print('evaluation mode, same input twice, same output?', torch.allclose(a, b))
with torch.no_grad(): one, five = net(x[:1]), net(x)[:1]
print('evaluation mode: an image alone or in a batch of 5, same output?', torch.allclose(one, five))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.
def fit(net, opt, epochs=20, batch=64, sched=None, clip=None, seed=0):
g = torch.Generator().manual_seed(seed); loss_fn = nn.CrossEntropyLoss()
hist = {'loss': [], 'val_loss': [], 'val_acc': [], 'lr': [], 'gnorm': []}
for ep in range(epochs):
net.train()
for idx in torch.randperm(len(Xtr), generator=g).split(batch):
opt.zero_grad()
loss = loss_fn(net(Xtr[idx]), ytr[idx]); loss.backward()
gn = nn.utils.clip_grad_norm_(net.parameters(), clip if clip else float('inf'))
opt.step()
if sched: sched.step()
hist['lr'].append(opt.param_groups[0]['lr']); hist['gnorm'].append(float(gn))
net.eval()
with torch.no_grad():
hist['loss'].append(float(loss_fn(net(Xtr), ytr)))
zv = net(Xva); hist['val_loss'].append(float(loss_fn(zv, yva))); hist['val_acc'].append(float((zv.argmax(1) == yva).float().mean()))
return hist
for name, mk in [('SGD', lambda p: torch.optim.SGD(p, lr=0.01)),
('SGD + momentum', lambda p: torch.optim.SGD(p, lr=0.01, momentum=0.9)),
('Adam', lambda p: torch.optim.Adam(p, lr=1e-3)),
('AdamW', lambda p: torch.optim.AdamW(p, lr=1e-3, weight_decay=0.01))]:
torch.manual_seed(0); net = make_net(bn=False, drop=0)
h = fit(net, mk(net.parameters()), epochs=15)
print(f'{name:<15} training loss after 15 epochs {h["loss"][-1]:.3f}, validation accuracy {h["val_acc"][-1]:.3f}')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):
def warmup_cosine(opt, warm, total):
f = lambda t: t / warm if t < warm else 0.5 * (1 + math.cos(math.pi * (t - warm) / max(1, total - warm)))
return torch.optim.lr_scheduler.LambdaLR(opt, f)
epochs, per = 20, math.ceil(len(Xtr) / 64)
results = {}
for kind in ['constant', 'warm-up + cosine']:
torch.manual_seed(0); net = make_net(depth=8)
opt = torch.optim.SGD(net.parameters(), lr=0.2, momentum=0.9)
sched = warmup_cosine(opt, 2 * per, epochs * per) if kind != 'constant' else None
results[kind] = fit(net, opt, epochs=epochs, sched=sched)
print(f'{kind:<17} validation accuracy, last 5 epochs: {[round(a, 3) for a in results[kind]["val_acc"][-5:]]}')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
fig, axes = plt.subplots(1, 2, figsize=(11, 3.4))
for k, h in results.items():
axes[0].plot(h['lr'], label=k); axes[1].plot(h['val_acc'], label=k)
axes[0].set_xlabel('step'); axes[0].set_title('learning rate'); axes[1].set_xlabel('epoch'); axes[1].set_title('validation accuracy'); axes[1].set_ylim(0.85, 1)
axes[1].legend(); plt.tight_layout(); plt.show()
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.
def lr_range_test(make, lo=1e-5, hi=10, steps=120, batch=64):
torch.manual_seed(0); net = make(); opt = torch.optim.SGD(net.parameters(), lr=lo, momentum=0.9)
gamma = (hi / lo) ** (1 / steps); loss_fn = nn.CrossEntropyLoss(); lrs, losses, smooth = [], [], None
g = torch.Generator().manual_seed(0)
for t in range(steps):
idx = torch.randint(0, len(Xtr), (batch,), generator=g)
opt.zero_grad(); loss = loss_fn(net(Xtr[idx]), ytr[idx]); loss.backward(); opt.step()
l = loss.item(); smooth = l if smooth is None else 0.9 * smooth + 0.1 * l
lrs.append(opt.param_groups[0]['lr']); losses.append(smooth)
if not math.isfinite(smooth) or smooth > 4 * losses[0]: break
for pg in opt.param_groups: pg['lr'] *= gamma
return np.array(lrs), np.array(losses)
lrs, losses = lr_range_test(lambda: make_net(bn=False, drop=0))
best = lrs[np.argmin(losses)]
print(f'lowest smoothed loss at lr {best:.3g}; stopped at lr {lrs[-1]:.3g}; suggested rate about {best / 10:.2g}')
plt.figure(figsize=(6, 3.2)); plt.semilogx(lrs, losses); plt.axvline(best / 10, ls='--', c='grey')
plt.xlabel('learning rate'); plt.ylabel('smoothed loss'); plt.title('learning-rate range test'); plt.tight_layout(); plt.show()lowest smoothed loss at lr 0.631; stopped at lr 3.16; suggested rate about 0.063

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:
def layer_grad_norms(net):
loss = nn.CrossEntropyLoss()(net(Xtr[:256]), ytr[:256]); net.zero_grad(); loss.backward()
return [float(m.weight.grad.norm()) for m in net if isinstance(m, nn.Linear)]
def sigmoid_net(bn):
layers, n = [], 64
for _ in range(12):
layers += [nn.Linear(n, 64)] + ([nn.BatchNorm1d(64)] if bn else []) + [nn.Sigmoid()]; n = 64
return nn.Sequential(*layers, nn.Linear(64, 10))
for bn in [False, True]:
torch.manual_seed(0); g = layer_grad_norms(sigmoid_net(bn))
print(f'batch norm {str(bn):<5}: gradient norm, first layer {g[0]:.1e}, middle {g[6]:.1e}, last {g[-1]:.1e}')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:
def he_net(depth=8, width=64):
layers, n = [], 64
for _ in range(depth):
lin = nn.Linear(n, width); nn.init.kaiming_normal_(lin.weight, nonlinearity='relu'); nn.init.zeros_(lin.bias)
layers += [lin, nn.ReLU()]; n = width
return nn.Sequential(*layers, nn.Linear(n, 10))
for clip in [None, 1.0]:
torch.manual_seed(0); net = he_net()
h = fit(net, torch.optim.SGD(net.parameters(), lr=0.1, momentum=0.9), epochs=10, clip=clip)
print(f'clip {str(clip):<4}: largest gradient norm seen {max(h["gnorm"]):.3g}, final training loss {h["loss"][-1]:.3f}, validation accuracy {h["val_acc"][-1]:.3f}')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.
rng = np.random.default_rng(5)
Xs, ys = Xtr[:300].clone(), ytr[:300].clone()
flip = torch.tensor(rng.random(300) < 0.3); ys[flip] = torch.tensor(rng.integers(0, 10, int(flip.sum())))
def fit_early(net, opt, patience=10, max_epochs=300, batch=32):
loss_fn, best, best_state, wait, g = nn.CrossEntropyLoss(), float('inf'), None, 0, torch.Generator().manual_seed(0)
for ep in range(max_epochs):
net.train()
for idx in torch.randperm(len(Xs), generator=g).split(batch):
opt.zero_grad(); loss_fn(net(Xs[idx]), ys[idx]).backward(); opt.step()
net.eval()
with torch.no_grad(): vl = float(loss_fn(net(Xva), yva))
if vl < best - 1e-4:
best, best_state, wait = vl, copy.deepcopy(net.state_dict()), 0
else:
wait += 1
if wait == patience: break
net.load_state_dict(best_state)
with torch.no_grad(): acc = float((net(Xva).argmax(1) == yva).float().mean())
return ep + 1, best, acc
torch.manual_seed(0); net = make_net(depth=2, width=256, bn=False, drop=0)
stopped, best, acc = fit_early(net, torch.optim.Adam(net.parameters(), lr=1e-3))
print(f'stopped after {stopped} epochs; restored the best weights: validation loss {best:.3f}, accuracy {acc:.3f}')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.
def diagnose(loss, val_loss, n_classes=10, window=5):
loss, val_loss = np.asarray(loss, float), np.asarray(val_loss, float)
if not np.all(np.isfinite(loss)):
return 'diverged: the loss became NaN or infinite'
if loss[-1] > loss[0]:
return 'diverging: the loss ends higher than it started'
if abs(loss[-1] - math.log(n_classes)) < 0.05:
return 'stuck at chance: nothing is learned'
tail = loss[-window:]
if np.std(np.diff(tail)) > 0.5 * abs(tail[-1] - tail[0]) / window + 0.05:
return 'unstable: the loss bounces; lower the learning rate'
if val_loss[-1] > val_loss.min() * 1.2 and loss[-1] < val_loss[-1] / 2:
return f'overfitting: the validation loss was lowest at epoch {int(np.argmin(val_loss)) + 1}'
if (loss[-window] - loss[-1]) / loss[-window] > 0.2:
return 'still converging: train longer'
return 'converged'
runs = {
'Adam 1e-3': lambda n: torch.optim.Adam(n.parameters(), lr=1e-3),
'SGD 1e-4': lambda n: torch.optim.SGD(n.parameters(), lr=1e-4),
'SGD 3.0, no clipping': lambda n: torch.optim.SGD(n.parameters(), lr=3.0, momentum=0.9),
}
for name, mk in runs.items():
torch.manual_seed(0); net = make_net(depth=4, bn=False, drop=0)
h = fit(net, mk(net), epochs=25)
print(f'{name:<22} -> {diagnose(h["loss"], h["val_loss"])}')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 either. The gradient norms tell them apart: small but steady for a slow run, zero for dead units.
Summary¶
model.train()andmodel.eval()switch dropout and batch normalisation; forgettingeval()makes predictions random and batch-dependent.torch.optimprovides SGD, Adam and AdamW;lr_scheduler.LambdaLRwrites 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_dictand restores it.Simple rules on the loss history catch the common failures automatically.