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

Open in Colab

Neural net training fails silently.

Andrej Karpathy, A Recipe for Training Neural Networks (2019)

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.

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).

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.

16.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:

θ←θ−η ∇θLbatch(θ)\theta \leftarrow \theta - \eta \, \nabla_\theta L_{\text{batch}}(\theta)

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 η\eta 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:

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 (ln⁡10\ln 10). 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:

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:

v←μv+∇L,θ←θ−ηv(μ≈0.9)v \leftarrow \mu v + \nabla L, \qquad \theta \leftarrow \theta - \eta v \qquad (\mu \approx 0.9)

The zigzags across the ravine cancel out in vv; the steady push along it adds up, to about 1/(1−μ)=101/(1-\mu) = 10 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 mm and a squared-gradient average vv, each corrected for its start at zero:

m←β1m+(1−β1)g,v←β2v+(1−β2)g2,θ←θ−ηm^v^+ϵm \leftarrow \beta_1 m + (1-\beta_1) g, \quad v \leftarrow \beta_2 v + (1-\beta_2) g^2, \quad \theta \leftarrow \theta - \eta \frac{\hat m}{\sqrt{\hat v} + \epsilon}

with β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999 and η=10−3\eta = 10^{-3} as defaults that work surprisingly often. Here are the three on a ravine, L(w1,w2)=12(w12+25 w22)L(w_1, w_2) = \tfrac12 (w_1^2 + 25\, w_2^2), starting from the same point with 40 steps:

Source
<Figure size 1000x360 with 1 Axes>

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 η\eta 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:

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 λθ\lambda\theta to the gradient. Inside Adam, that term is then divided by v^\sqrt{\hat v}, which weakens the decay exactly for the parameters with large gradients. AdamW applies the decay separately, θ←θ−η(m^/(v^+ϵ)+λθ)\theta \leftarrow \theta - \eta(\hat m / (\sqrt{\hat v}+\epsilon) + \lambda \theta), 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: ηt=12η0(1+cos⁡(πt/T))\eta_t = \tfrac12 \eta_0 (1 + \cos(\pi t / T)), smooth from η0\eta_0 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:

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 0.510≈0.0010.5^{10} \approx 0.001 of it; if each multiplies by 2, it receives 210≈10002^{10} \approx 1000 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:

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 3×10−73 \times 10^{-7} 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 nn inputs sums nn terms, so the weights need variance about 1/n1/n (Xavier, or Glorot, for tanh); ReLU zeroes half of its inputs, so it needs twice that, 2/n2/n (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:

x^=x−μbatchσbatch2+ϵ,y=γx^+β\hat x = \frac{x - \mu_{\text{batch}}}{\sqrt{\sigma^2_{\text{batch}} + \epsilon}}, \qquad y = \gamma \hat x + \beta

where γ\gamma and β\beta are learned, one pair per unit. If the best is no normalisation at all, the network can learn γ=σ\gamma = \sigma, β=μ\beta = \mu and undo it.

Training and evaluation differ. In training, μ\mu and σ\sigma 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:

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:

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.

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 pp at every training step, and scales the others by 1/(1−p)1/(1-p) 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
<Figure size 1100x360 with 2 Axes>

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
<Figure size 1500x330 with 4 Axes>
What you seeLikely causeWhat to try
Loss becomes NaN or inflearning rate far too high, exploding gradients, a log of 0lower the rate, clip gradients, check the loss code
Loss jumps up early, then stays at chance levelthe first steps were too large: dead unitslower the rate, add warm-up
Loss bounces and does not settlerate too high for this stagelower it, or add a schedule
Loss falls very slowly, almost a straight linerate too low, or vanishing gradientsraise the rate, check initialisation, add normalisation
Loss stays exactly at ln⁡(classes)\ln(\text{classes})nothing learns: a bug, a dead network, labels not reaching the losssanity checks below
Training loss falls, validation loss risesoverfittingregularise, stop early, get more data
Both losses high and close togetherunderfittinga bigger model, longer training, a higher rate

Gradient clipping guards against the occasional huge gradient: if the gradient’s norm exceeds a threshold cc, it is scaled down to norm cc, 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:

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:

  1. The initial loss: with KK balanced classes, a network at initialisation should give about ln⁡K\ln K (2.30 for 10 classes). Much more means the outputs are too large.

  2. 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.

  3. Random labels: shuffle the labels; the validation accuracy must fall to chance. If it does not, information is leaking (Chapter 7).

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

  1. Look at the data (Chapter 7) and fix a validation set, and a test set you will touch once.

  2. Start small: a simple model, no tricks; check the initial loss, overfit one batch.

  3. Use the defaults that work: He initialisation, ReLU, batch or layer normalisation, Adam at 10-3 (or SGD with momentum 0.9).

  4. Tune the learning rate first, by factors of 10, then add a schedule with warm-up.

  5. Then fight overfitting: more data or augmentation, dropout, weight decay, early stopping.

  6. Watch the curves every run, both losses, and the gradient norm; clip if it spikes.

  7. 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

  1. 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.

  2. With momentum μ=0.9\mu = 0.9 and a constant gradient gg, what does the velocity converge to? What does that mean for the effective learning rate?

  3. Why does Adam divide by v^\sqrt{\hat v} and not by v^\hat v? What are the units of the step in each case?

  4. 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?

  5. 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?

  6. Dropout with p=0.5p = 0.5 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?

  7. 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).