Chapter 16: Training Deep Networks
16.1 What Can Go Wrong¶
Chapter 15 trained small networks with plain gradient descent, and they learned. Deeper networks, trained on real data, fail in ways that small ones rarely do:
the step size is wrong, and the loss crawls, bounces or blows up;
the loss surface has long narrow ravines, where plain gradient descent zigzags;
the gradient shrinks or grows as it travels back through many layers, so the first layers never learn, or the weights explode;
the network has so many parameters that it memorises the training set;
and most of these failures raise no error: the code runs, a number comes out, and it is simply bad.
This chapter takes these problems one at a time, with the fix for each. To see every trick as code, we use a small NumPy library: each layer has a forward and a backward, as in Chapter 15, and each optimiser a step. The data are scikit-learn’s digits: 1 797 handwritten digits of 8×8 pixels, split 70/30 into training and validation sets.
import numpy as np
import math
import warnings
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
warnings.filterwarnings('ignore'); np.seterr(all='ignore')
X, y = load_digits(return_X_y=True); X = X / 16 # pixels in [0, 1]
Xtr, Xva, ytr, yva = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
print(f'{len(Xtr)} training images, {len(Xva)} validation images, {X.shape[1]} pixels each, 10 classes')1257 training images, 540 validation images, 64 pixels each, 10 classes
The library. Every layer stores what its backward pass needs during the forward pass; train=False switches dropout off and makes batch normalisation use its running statistics (Section 16.6).
class Dense:
def __init__(self, n_in, n_out, rng, scale='he'):
s = {'he': np.sqrt(2 / n_in), 'xavier': np.sqrt(1 / n_in), 'small': 0.01, 'large': 1.0}[scale]
self.W = rng.normal(0, s, (n_in, n_out)); self.b = np.zeros(n_out)
self.params = [self.W, self.b]
def forward(self, x, train=True):
self.x = x
return x @ self.W + self.b
def backward(self, g):
self.grads = [self.x.T @ g, g.sum(0)]
return g @ self.W.T
class ReLU:
params = []
def forward(self, x, train=True):
self.m = x > 0
return x * self.m
def backward(self, g):
return g * self.m
class Tanh:
params = []
def forward(self, x, train=True):
self.y = np.tanh(x)
return self.y
def backward(self, g):
return g * (1 - self.y ** 2)
class Sigmoid:
params = []
def forward(self, x, train=True):
self.y = 1 / (1 + np.exp(-x))
return self.y
def backward(self, g):
return g * self.y * (1 - self.y)
class BatchNorm:
def __init__(self, n, momentum=0.9, eps=1e-5):
self.gamma, self.beta = np.ones(n), np.zeros(n); self.params = [self.gamma, self.beta]
self.mean, self.var, self.mom, self.eps = np.zeros(n), np.ones(n), momentum, eps
def forward(self, x, train=True):
if train: # normalise with this batch's statistics, and remember them
mu, var = x.mean(0), x.var(0)
self.mean = self.mom * self.mean + (1 - self.mom) * mu
self.var = self.mom * self.var + (1 - self.mom) * var
else: # evaluation: the running statistics
mu, var = self.mean, self.var
self.std = np.sqrt(var + self.eps); self.xh = (x - mu) / self.std
return self.gamma * self.xh + self.beta
def backward(self, g):
n = len(g); self.grads = [(g * self.xh).sum(0), g.sum(0)]
gx = g * self.gamma
return (n * gx - gx.sum(0) - self.xh * (gx * self.xh).sum(0)) / (n * self.std)
class Dropout:
params = []
def __init__(self, p, rng):
self.p, self.rng = p, rng
def forward(self, x, train=True):
if not train or self.p == 0:
self.m = 1
return x
self.m = (self.rng.random(x.shape) >= self.p) / (1 - self.p) # keep with probability 1 - p, scaled up
return x * self.m
def backward(self, g):
return g * self.m
class Net:
def __init__(self, layers):
self.layers = layers
def forward(self, x, train=True):
for layer in self.layers:
x = layer.forward(x, train)
return x
def backward(self, g):
for layer in reversed(self.layers):
g = layer.backward(g)
def params_grads(self):
for layer in self.layers:
yield from zip(layer.params, getattr(layer, 'grads', []))
def softmax_ce(z, y):
"""Mean cross-entropy of the logits z for labels y, and its gradient with respect to z."""
z = z - z.max(1, keepdims=True); p = np.exp(z); p /= p.sum(1, keepdims=True)
n = len(y); loss = -np.log(p[np.arange(n), y] + 1e-12).mean()
g = p.copy(); g[np.arange(n), y] -= 1
return loss, g / n
def mlp(seed=0, hidden=(64, 64), scale='he', act=ReLU, bn=False, drop=0.0):
rng = np.random.default_rng(seed); layers = []; n = 64
for h in hidden:
layers.append(Dense(n, h, rng, scale))
if bn: layers.append(BatchNorm(h))
layers.append(act())
if drop: layers.append(Dropout(drop, rng))
n = h
layers.append(Dense(n, 10, rng, scale))
return Net(layers)The optimisers of Section 16.3, and a training loop that records, after each epoch, the loss and accuracy on both sets and the norm of the last gradient.
class SGD:
def __init__(self, lr, momentum=0.0, weight_decay=0.0):
self.lr, self.mu, self.wd, self.v = lr, momentum, weight_decay, {}
def step(self, pg):
for p, g in pg:
g = g + self.wd * p
v = self.v.get(id(p), 0) * self.mu + g; self.v[id(p)] = v
p -= self.lr * v
class Adam:
def __init__(self, lr=1e-3, b1=0.9, b2=0.999, eps=1e-8, weight_decay=0.0):
self.lr, self.b1, self.b2, self.eps, self.wd, self.s, self.t = lr, b1, b2, eps, weight_decay, {}, 0
def step(self, pg):
self.t += 1
for p, g in pg:
m, v = self.s.get(id(p), (0, 0))
m = self.b1 * m + (1 - self.b1) * g; v = self.b2 * v + (1 - self.b2) * g * g; self.s[id(p)] = (m, v)
mh, vh = m / (1 - self.b1 ** self.t), v / (1 - self.b2 ** self.t)
p -= self.lr * (mh / (np.sqrt(vh) + self.eps) + self.wd * p) # decoupled weight decay (AdamW)
def train(net, opt, X, y, Xv, yv, epochs=30, batch=64, clip=None):
rng = np.random.default_rng(0); hist = {'loss': [], 'val_loss': [], 'acc': [], 'val_acc': [], 'gnorm': []}
for ep in range(epochs):
idx = rng.permutation(len(X))
for s in range(0, len(X), batch):
b = idx[s:s + batch]
loss, g = softmax_ce(net.forward(X[b]), y[b]); net.backward(g)
pg = list(net.params_grads())
gn = np.sqrt(sum((gg ** 2).sum() for _, gg in pg))
if clip and gn > clip: # gradient clipping (Section 16.8)
pg = [(p, gg * clip / gn) for p, gg in pg]
opt.step(pg)
if not np.isfinite(loss): break
hist['gnorm'].append(gn)
zt, zv = net.forward(X, False), net.forward(Xv, False)
hist['loss'].append(softmax_ce(zt, y)[0]); hist['val_loss'].append(softmax_ce(zv, yv)[0])
hist['acc'].append((zt.argmax(1) == y).mean()); hist['val_acc'].append((zv.argmax(1) == yv).mean())
if not np.isfinite(hist['loss'][-1]): break
return hist16.2 Mini-Batch Gradient Descent and the Learning Rate¶
Training repeats one step: take a mini-batch of examples, compute the loss and its gradient on them, and move every parameter a little against the gradient:
One pass over the whole training set is an epoch. The batch size trades accuracy of the gradient for speed: a batch of 64 gives a noisy but cheap estimate of the full gradient, and the noise even helps to escape poor regions. Typical sizes are 32 to 512, limited by memory.
The learning rate is the most important hyperparameter of deep learning. We train the same two-layer network (64 and 64 ReLU units) for 30 epochs with five rates:
H = {}
for lr in [0.001, 0.01, 0.1, 1.0, 5.0]:
H[lr] = train(mlp(), SGD(lr), Xtr, ytr, Xva, yva, epochs=30)
print(f'lr {lr:<6} training loss after 30 epochs {H[lr]["loss"][-1]:.3f} validation accuracy {H[lr]["val_acc"][-1]:.3f}')lr 0.001 training loss after 30 epochs 2.122 validation accuracy 0.220
lr 0.01 training loss after 30 epochs 0.558 validation accuracy 0.896
lr 0.1 training loss after 30 epochs 0.056 validation accuracy 0.970
lr 1.0 training loss after 30 epochs 1.744 validation accuracy 0.204
lr 5.0 training loss after 30 epochs 2.317 validation accuracy 0.100
At 0.001 the network barely moves: after 30 epochs the loss is still 2.12, close to the 2.30 of random guessing (). Too small a rate wastes time, and looks like a model that cannot learn.
0.01 learns, slowly (0.896); 0.1 learns well (0.970).
At 1.0 the steps overshoot: the loss bounces and ends at 1.74.
At 5.0 the first steps are disastrous. Look at the loss on the first ten batches:
net, opt = mlp(), SGD(5.0)
idx = np.random.default_rng(0).permutation(len(Xtr)); first = []
for s in range(0, 640, 64):
b = idx[s:s + 64]; loss, g = softmax_ce(net.forward(Xtr[b]), ytr[b]); net.backward(g); opt.step(list(net.params_grads()))
first.append(round(float(loss), 1))
print('loss on the first ten batches:', first)loss on the first ten batches: [2.7, 21.2, 7.7, 25.0, 13.6, 8.9, 3.4, 3.0, 2.5, 2.5]
The loss jumps from 2.7 to 21 and 25. The huge steps push most ReLU units into the region where they output zero for every input; a dead unit has zero gradient and never recovers. The network ends at 2.32, predicting one class for everything (validation accuracy 0.10).
16.3 Optimisers: Momentum, RMSProp and Adam¶
Plain gradient descent has a geometric problem. Where the loss is steep in one direction and shallow in another (a ravine), the gradient points mostly across the ravine: the steps zigzag from wall to wall and advance slowly along the floor. A rate small enough not to bounce off the steep walls is too small for the shallow direction.
Momentum keeps a running sum of past gradients, a velocity:
The zigzags across the ravine cancel out in ; the steady push along it adds up, to about times a single step.
RMSProp divides each parameter’s step by a running average of its squared gradients, so parameters with large gradients take smaller steps, and parameters with small gradients larger ones. Adam (adaptive moments) combines both: a momentum and a squared-gradient average , each corrected for its start at zero:
with , and as defaults that work surprisingly often. Here are the three on a ravine, , starting from the same point with 40 steps:
Source
def path(step, w0=(-9.0, 1.6), n=40):
w = np.array(w0); out = [w.copy()]; state = {}
for t in range(1, n + 1):
g = np.array([w[0], 25 * w[1]]); w = step(w, g, state, t); out.append(w.copy())
return np.array(out)
def sgd(w, g, s, t): return w - 0.075 * g
def mom(w, g, s, t):
s['v'] = 0.8 * s.get('v', 0) + g; return w - 0.03 * s['v']
def adam(w, g, s, t):
s['m'] = 0.9 * s.get('m', 0) + 0.1 * g; s['v'] = 0.999 * s.get('v', 0) + 0.001 * g * g
return w - 0.3 * (s['m'] / (1 - 0.9 ** t)) / (np.sqrt(s['v'] / (1 - 0.999 ** t)) + 1e-8)
a, b = np.meshgrid(np.linspace(-10, 2, 200), np.linspace(-2, 2, 200))
fig, ax = plt.subplots(figsize=(10, 3.6))
ax.contour(a, b, 0.5 * (a ** 2 + 25 * b ** 2), levels=np.geomspace(0.05, 80, 14), colors='lightgrey')
for (name, f), col in zip([('gradient descent', sgd), ('momentum', mom), ('Adam', adam)], ['tab:red', 'tab:blue', 'tab:green']):
p = path(f); ax.plot(p[:, 0], p[:, 1], 'o-', ms=3, color=col, label=f'{name}: ends {np.hypot(*p[-1]):.2f} from the minimum')
ax.plot(0, 0, 'k*', ms=14); ax.set_xlabel('$w_1$ (shallow)'); ax.set_ylabel('$w_2$ (steep)'); ax.legend(loc='lower right'); ax.set_title('40 steps in a ravine')
plt.tight_layout(); plt.show()
Gradient descent zigzags across the steep direction and has not yet reached the minimum; momentum builds up speed along the floor and overshoots a little before settling; Adam’s per-parameter scaling makes both directions look alike, so its path has no zigzag. Its steps are about long whatever the slope, which is also why Adam needs a decaying rate (Section 16.4) to settle exactly into a minimum. On the digits network, at the same rate of 0.01:
for name, opt in [('SGD, lr 0.01', SGD(0.01)), ('momentum 0.9, lr 0.01', SGD(0.01, 0.9)), ('Adam, lr 0.001', Adam(1e-3))]:
h = train(mlp(), opt, Xtr, ytr, Xva, yva, epochs=20)
print(f'{name:<22} training loss after 1, 5, 10, 20 epochs: {[round(float(h["loss"][i]), 3) for i in (0, 4, 9, 19)]} validation accuracy {h["val_acc"][-1]:.3f}')SGD, lr 0.01 training loss after 1, 5, 10, 20 epochs: [2.319, 1.97, 1.578, 0.908] validation accuracy 0.848
momentum 0.9, lr 0.01 training loss after 1, 5, 10, 20 epochs: [1.935, 0.385, 0.173, 0.09] validation accuracy 0.969
Adam, lr 0.001 training loss after 1, 5, 10, 20 epochs: [1.961, 0.439, 0.157, 0.064] validation accuracy 0.970
After 20 epochs plain SGD is at a loss of 0.91 (validation accuracy 0.848); momentum and Adam are below 0.1 (0.969 and 0.970). Adam is the usual first choice; well-tuned SGD with momentum often generalises slightly better on images, and is still used to train many vision models.
AdamW. Weight decay (the L2 penalty of Chapter 9) adds to the gradient. Inside Adam, that term is then divided by , which weakens the decay exactly for the parameters with large gradients. AdamW applies the decay separately, , as our Adam class does. It is the default for Transformers.
16.4 Learning-Rate Schedules and Warm-Up¶
A rate large enough to make fast progress early is too large to settle into a minimum late: the loss keeps bouncing around the bottom. A schedule lowers the rate as training goes on:
step decay: divide by 10 at fixed epochs (for example at 50% and 75% of training);
cosine decay: , smooth from to 0;
reduce on plateau: divide when the validation loss stops improving.
Warm-up does the opposite at the start: the rate grows linearly from 0 over the first epochs. At the start the weights are random and the gradients large and unreliable, and Adam’s statistics are still empty; a full-size step then can throw the network into a bad region. Large models, Transformers in particular, are rarely trained without it.
We train an 8-layer network (with batch normalisation, Section 16.6) with SGD and momentum, either at a constant rate of 0.2, or with 3 epochs of warm-up to 0.2 followed by cosine decay:
def run_schedule(kind, epochs=20, base=0.2):
net, opt = mlp(hidden=(64,) * 8, bn=True), SGD(base, 0.9); rng = np.random.default_rng(0); acc = []
per = math.ceil(len(Xtr) / 64); total, warm, t = epochs * per, 3 * per, 0
for ep in range(epochs):
idx = rng.permutation(len(Xtr))
for s in range(0, len(Xtr), 64):
if kind == 'warm-up + cosine':
opt.lr = base * t / warm if t < warm else base * 0.5 * (1 + math.cos(math.pi * (t - warm) / (total - warm)))
b = idx[s:s + 64]; loss, g = softmax_ce(net.forward(Xtr[b]), ytr[b]); net.backward(g); opt.step(list(net.params_grads())); t += 1
acc.append((net.forward(Xva, False).argmax(1) == yva).mean())
return acc
for kind in ['constant', 'warm-up + cosine']:
acc = run_schedule(kind)
print(f'{kind:<17} validation accuracy after epochs 1, 5, 9, 13, 17: {[round(float(a), 3) for a in acc[::4]]}, final {acc[-1]:.3f}')constant validation accuracy after epochs 1, 5, 9, 13, 17: [0.846, 0.933, 0.963, 0.917, 0.965], final 0.981
warm-up + cosine validation accuracy after epochs 1, 5, 9, 13, 17: [0.756, 0.954, 0.98, 0.983, 0.983], final 0.983
The constant rate reaches 0.963 by epoch 9, then falls back to 0.917 at epoch 13 before recovering: it keeps jumping around the minimum. The schedule starts slower (0.756 after one warm-up epoch), then climbs steadily and settles at 0.983.
16.5 Vanishing and Exploding Gradients¶
Backpropagation multiplies: the gradient reaching layer 1 of a 10-layer network is a product of 10 Jacobians, one per layer. If each multiplies the gradient’s size by 0.5, layer 1 receives of it; if each multiplies by 2, it receives times. The first case is a vanishing gradient: the first layers stop learning. The second is an exploding gradient: the steps become enormous and the weights overflow.
Two things set the factor: the activation (the sigmoid’s slope is at most 0.25, and close to 0 when it saturates) and the scale of the initial weights. We build a 10-layer network with several choices and measure, before any training, the gradient’s norm at the first and last layers and the spread of the last activations:
print(f'{"weights":<8} {"activation":<9} {"gradient, first layer":>22} {"last layer":>11} {"activation spread, last layer":>31}')
for scale, act in [('small', Tanh), ('small', ReLU), ('xavier', Sigmoid), ('large', Tanh), ('xavier', Tanh), ('he', ReLU)]:
net = mlp(hidden=(64,) * 10, scale=scale, act=act)
loss, g = softmax_ce(net.forward(Xtr[:256]), ytr[:256]); net.backward(g)
gn = [np.linalg.norm(l.grads[0]) for l in net.layers if isinstance(l, Dense)]
x = Xtr[:256]
for l in net.layers[:-1]:
x = l.forward(x) # the last hidden layer's activations
print(f'{scale:<8} {act.__name__:<9} {gn[0]:>22.2e} {gn[-1]:>11.2e} {x.std():>31.3g}')weights activation gradient, first layer last layer activation spread, last layer
small Tanh 4.88e-12 5.93e-12 5.49e-12
small ReLU 1.12e-13 5.57e-14 6.6e-14
xavier Sigmoid 2.97e-07 5.55e-01 0.118
large Tanh 6.68e+02 9.37e-01 0.947
xavier Tanh 2.34e-01 2.39e-01 0.21
he ReLU 4.29e-01 2.69e-01 0.197
Small weights (standard deviation 0.01): every layer shrinks its input, the signal is gone by the last layer, and the first layer’s gradient is about 10-12. Nothing learns.
Sigmoid, even with a reasonable scale: the first layer’s gradient is about against 0.55 at the last. Each sigmoid divides the gradient by 4 or more: this is why deep networks were hard to train before ReLU.
Large weights (standard deviation 1) with tanh: the gradient grows towards the input, to about 670 at the first layer, a factor of 700 over the last.
Xavier initialisation for tanh and He initialisation for ReLU keep the gradients of the first and last layers within a factor of about 2.
The rule behind both: choose the weights’ variance so that each layer keeps the variance of its input. A layer with inputs sums terms, so the weights need variance about (Xavier, or Glorot, for tanh); ReLU zeroes half of its inputs, so it needs twice that, (He). Frameworks use these by default: PyTorch’s nn.Linear uses a variant of Xavier’s scale, and nn.init.kaiming_normal_ gives He’s.
Two more defences against vanishing gradients appear later in this part: batch normalisation (next section) and residual connections (Chapter 18), which add a layer’s input to its output so that the gradient has a path that skips the multiplications.
16.6 Batch Normalisation¶
Even with a good initialisation, the distribution of each layer’s inputs changes as the layers before it learn, and a deep network is sensitive to it. Batch normalisation (Ioffe and Szegedy, 2015) normalises each unit’s values over the mini-batch, then lets the network rescale them:
where and are learned, one pair per unit. If the best is no normalisation at all, the network can learn , and undo it.
Training and evaluation differ. In training, and come from the current batch, and running averages of them are kept. In evaluation, a single example has no batch, and a prediction should not depend on which other examples are beside it, so the running averages are used. Forgetting to switch modes (model.eval() in PyTorch) is a classic bug: the validation scores change with the batch size.
The effect on an 8-layer sigmoid network, the kind that vanishes, trained with SGD at 0.5 for 30 epochs:
for bn in [False, True]:
h = train(mlp(hidden=(64,) * 8, scale='xavier', act=Sigmoid, bn=bn), SGD(0.5), Xtr, ytr, Xva, yva, epochs=30)
print(f'batch normalisation {str(bn):<5}: training loss after 1, 6, 11, 16, 21, 26 epochs {[round(float(v), 3) for v in h["loss"][::5]]}, validation accuracy {h["val_acc"][-1]:.3f}')batch normalisation False: training loss after 1, 6, 11, 16, 21, 26 epochs [2.341, 2.325, 2.319, 2.308, 2.307, 2.306], validation accuracy 0.100
batch normalisation True : training loss after 1, 6, 11, 16, 21, 26 epochs [2.234, 0.151, 0.337, 0.065, 0.029, 0.053], validation accuracy 0.974
Without it, the loss stays at 2.31 for 30 epochs: the network never leaves the starting point. With it, the same network reaches a validation accuracy of 0.974. Batch normalisation also makes the training tolerate much larger learning rates. An 8-layer ReLU network with He initialisation and momentum, 15 epochs:
print(f'{"learning rate":<14} {"without":>9} {"with batch normalisation":>26}')
for lr in [0.05, 0.2, 0.5]:
r = [train(mlp(hidden=(64,) * 8, bn=bn), SGD(lr, 0.9), Xtr, ytr, Xva, yva, epochs=15)['val_acc'][-1] for bn in (False, True)]
print(f'{lr:<14} {r[0]:>9.3f} {r[1]:>26.3f}')learning rate without with batch normalisation
0.05 0.907 0.978
0.2 0.102 0.965
0.5 0.100 0.974
Without normalisation the network only trains at 0.05 (0.907); at 0.2 it gets stuck at chance and at 0.5 its loss becomes NaN. With it, all three rates train, to between 0.965 and 0.978.
Batch normalisation needs batches of a reasonable size (its statistics are noisy below about 16). For sequences and Transformers, layer normalisation normalises over the units of one example instead of over the batch, so it works the same in training and evaluation and for any batch size.
16.7 Dropout, Weight Decay and Early Stopping¶
A network with tens of thousands of parameters can memorise a small training set, including its mistakes. To see it, we train a wide network (two layers of 256 units) on only 300 training images, of which 30% have their label replaced by a random one (a random label is sometimes the right one, so 83 end up wrong), for 200 epochs.
rng = np.random.default_rng(5)
Xs, ys = Xtr[:300].copy(), ytr[:300].copy()
flip = rng.random(300) < 0.3; ys[flip] = rng.integers(0, 10, flip.sum())
print(f'{(ys != ytr[:300]).sum()} of 300 training labels are wrong')
runs = {}
for name, kw, wd in [('no regularisation', {}, 0.0), ('dropout 0.5', {'drop': 0.5}, 0.0), ('weight decay 0.5', {}, 0.5)]:
h = runs[name] = train(mlp(hidden=(256, 256), **kw), Adam(1e-3, weight_decay=wd), Xs, ys, Xva, yva, epochs=200, batch=32)
best = int(np.argmin(h['val_loss']))
print(f'{name:<18} after 200 epochs: training accuracy {h["acc"][-1]:.3f}, validation {h["val_acc"][-1]:.3f};'
f' lowest validation loss at epoch {best + 1}, where validation accuracy is {h["val_acc"][best]:.3f}')83 of 300 training labels are wrong
no regularisation after 200 epochs: training accuracy 1.000, validation 0.774; lowest validation loss at epoch 21, where validation accuracy is 0.865
dropout 0.5 after 200 epochs: training accuracy 0.997, validation 0.811; lowest validation loss at epoch 70, where validation accuracy is 0.898
weight decay 0.5 after 200 epochs: training accuracy 1.000, validation 0.794; lowest validation loss at epoch 21, where validation accuracy is 0.880
Without regularisation, the network fits every training label, the wrong ones included (training accuracy 1.000), and ends at 0.774 on validation. Three remedies:
Dropout (Srivastava et al., 2014) sets each unit’s output to zero with probability at every training step, and scales the others by so that the expected value is unchanged; in evaluation all units are used. No unit can rely on a specific other unit being there, so the network cannot build fragile co-adaptations that memorise single examples; it behaves like an average of many thinned networks. Here it raises the final validation accuracy to 0.811.
Weight decay pulls every weight towards zero at each step, the L2 penalty of Chapter 9. Here it helps a little (0.794).
Early stopping keeps the weights of the epoch with the lowest validation loss. It is the strongest of the three here: stopping at epoch 21 gives 0.865 without any other change, and dropout’s best epoch reaches 0.898. Training longer than that only memorises the noise.
Source
fig, axes = plt.subplots(1, 2, figsize=(11, 3.6))
for name, h in runs.items():
axes[0].plot(h['val_loss'], label=name); axes[1].plot(h['val_acc'], label=name)
for ax, t in zip(axes, ['validation loss', 'validation accuracy']):
ax.set_xlabel('epoch'); ax.set_title(t); ax.legend()
axes[0].set_ylim(0, 2); plt.tight_layout(); plt.show()
The validation loss of the unregularised network bottoms out early, then climbs while the training loss keeps falling: the signature of overfitting (Chapter 9). The other standard remedy is more data, real or made by data augmentation: shifted, flipped or cropped copies of the training images (Chapter 17).
16.8 Converging or Diverging? Reading the Training Curves¶
The training curves are the network’s vital signs. Four runs from this chapter show the typical shapes:
Source
cases = [('learning well: lr 0.1', H[0.1]), ('too slow: lr 0.001', H[0.001]), ('unstable: lr 1.0', H[1.0]), ('overfitting: noisy labels', runs['no regularisation'])]
fig, axes = plt.subplots(1, 4, figsize=(15, 3.3))
for ax, (t, h) in zip(axes, cases):
ax.plot(h['loss'], label='training'); ax.plot(h['val_loss'], label='validation'); ax.set_title(t); ax.set_xlabel('epoch'); ax.set_ylim(0, 3)
axes[0].set_ylabel('loss'); axes[0].legend(); plt.tight_layout(); plt.show()
| What you see | Likely cause | What to try |
|---|---|---|
| Loss becomes NaN or inf | learning rate far too high, exploding gradients, a log of 0 | lower the rate, clip gradients, check the loss code |
| Loss jumps up early, then stays at chance level | the first steps were too large: dead units | lower the rate, add warm-up |
| Loss bounces and does not settle | rate too high for this stage | lower it, or add a schedule |
| Loss falls very slowly, almost a straight line | rate too low, or vanishing gradients | raise the rate, check initialisation, add normalisation |
| Loss stays exactly at | nothing learns: a bug, a dead network, labels not reaching the loss | sanity checks below |
| Training loss falls, validation loss rises | overfitting | regularise, stop early, get more data |
| Both losses high and close together | underfitting | a bigger model, longer training, a higher rate |
Gradient clipping guards against the occasional huge gradient: if the gradient’s norm exceeds a threshold , it is scaled down to norm , keeping its direction. Without batch normalisation, our 8-layer ReLU network got stuck at a rate of 0.2. With the gradient clipped to norm 1:
for lr in [0.1, 0.2]:
for clip in [None, 1.0]:
h = train(mlp(hidden=(64,) * 8), SGD(lr, 0.9), Xtr, ytr, Xva, yva, epochs=15, clip=clip)
print(f'lr {lr}, clipping {str(clip):<4}: training loss after 1, 2, 3 epochs {[round(float(v), 3) for v in h["loss"][:3]]}, final {h["loss"][-1]:.3f}, validation accuracy {h["val_acc"][-1]:.3f}')lr 0.1, clipping None: training loss after 1, 2, 3 epochs [2.333, 2.164, 2.225], final 1.404, validation accuracy 0.394
lr 0.1, clipping 1.0 : training loss after 1, 2, 3 epochs [0.914, 0.601, 0.454], final 0.123, validation accuracy 0.930
lr 0.2, clipping None: training loss after 1, 2, 3 epochs [2.086, 2.31, 1.999], final 2.304, validation accuracy 0.102
lr 0.2, clipping 1.0 : training loss after 1, 2, 3 epochs [1.155, 1.085, 0.347], final 0.127, validation accuracy 0.957
At 0.2 the unclipped run ends at chance (0.102); the clipped one reaches 0.957. Clipping is standard for recurrent networks and Transformers, where a single long sequence can produce an exploding gradient.
Sanity checks. Because training fails silently, check the pipeline before trusting a long run:
The initial loss: with balanced classes, a network at initialisation should give about (2.30 for 10 classes). Much more means the outputs are too large.
Overfit one batch: a working network and loss must be able to drive the loss on a single batch of 32 examples to almost zero. If they cannot, there is a bug.
Random labels: shuffle the labels; the validation accuracy must fall to chance. If it does not, information is leaking (Chapter 7).
net, opt = mlp(), Adam(1e-2)
for i in range(200):
loss, g = softmax_ce(net.forward(Xtr[:32]), ytr[:32]); net.backward(g); opt.step(list(net.params_grads()))
if i in (0, 49, 199): print(f'one batch, step {i + 1:>3}: loss {loss:.5f}')
h = train(mlp(), Adam(1e-3), Xtr, np.random.default_rng(1).permutation(ytr), Xva, yva, epochs=40)
print(f'shuffled labels, 40 epochs: training accuracy {h["acc"][-1]:.3f}, validation accuracy {h["val_acc"][-1]:.3f}')one batch, step 1: loss 2.36126
one batch, step 50: loss 0.00009
one batch, step 200: loss 0.00002
shuffled labels, 40 epochs: training accuracy 0.364, validation accuracy 0.109
The single batch is learned (2.36 down to 10-4 in 50 steps), and with shuffled labels the validation accuracy is 0.109, chance level, while the training accuracy has already climbed to 0.364 by memorising: a network can fit noise, which is why only validation data can tell you whether it learned anything.
16.9 A Training Recipe¶
Look at the data (Chapter 7) and fix a validation set, and a test set you will touch once.
Start small: a simple model, no tricks; check the initial loss, overfit one batch.
Use the defaults that work: He initialisation, ReLU, batch or layer normalisation, Adam at 10-3 (or SGD with momentum 0.9).
Tune the learning rate first, by factors of 10, then add a schedule with warm-up.
Then fight overfitting: more data or augmentation, dropout, weight decay, early stopping.
Watch the curves every run, both losses, and the gradient norm; clip if it spikes.
Change one thing at a time, and keep a log of every run.
16.10 Summary¶
The learning rate matters most: too small crawls, too large bounces, diverges or kills units.
Momentum smooths the zigzags of a ravine; Adam also scales each parameter’s step; AdamW decouples weight decay.
Schedules lower the rate as training goes on; warm-up raises it gently at the start.
Gradients vanish or explode because backpropagation multiplies; Xavier and He initialisation keep each layer’s variance.
Batch normalisation normalises each unit over the batch, uses running statistics in evaluation, and lets deep networks train fast at high rates.
Dropout, weight decay and early stopping fight memorisation; early stopping is often the strongest.
Training curves show whether a run converges, diverges, stalls or overfits; clipping and sanity checks catch the silent failures.
Exercises¶
A network’s loss is 2.30 after 10 epochs on a 10-class problem and has not changed. List three possible causes and how you would test each.
With momentum and a constant gradient , what does the velocity converge to? What does that mean for the effective learning rate?
Why does Adam divide by and not by ? What are the units of the step in each case?
A layer has 256 inputs and ReLU activations. What standard deviation does He initialisation use? What happens to the activations’ variance after 20 layers if you use 0.01 instead?
Explain why batch normalisation must use running statistics at evaluation time. What would happen to the prediction for one image if it used the batch statistics and the batch contained only that image?
Dropout with is applied to a layer of 4 units whose outputs are 2, 0, 4, 6, with the mask 1, 0, 0, 1. What does the layer output in training? In evaluation?
Sketch the training and validation loss curves for (a) a learning rate that is too high, (b) underfitting, (c) overfitting, and say what you would change in each case.
Further Reading¶
I. Goodfellow, Y. Bengio, A. Courville, Deep Learning, MIT Press, 2016, chapter 8 (Optimization for Training Deep Models).
X. Glorot, Y. Bengio, “Understanding the difficulty of training deep feedforward neural networks”, AISTATS, 2010.
K. He, X. Zhang, S. Ren, J. Sun, “Delving deep into rectifiers”, ICCV, 2015.
S. Ioffe, C. Szegedy, “Batch normalization: accelerating deep network training by reducing internal covariate shift”, ICML, 2015.
N. Srivastava et al., “Dropout: a simple way to prevent neural networks from overfitting”, JMLR, 2014.
D. Kingma, J. Ba, “Adam: a method for stochastic optimization”, ICLR, 2015; I. Loshchilov, F. Hutter, “Decoupled weight decay regularization”, ICLR, 2019.
A. Karpathy, “A Recipe for Training Neural Networks”, 2019 (karpathy.github.io).