Training deep networks
What makes a deep network trainable and keeps it from overfitting: He and Glorot initialization that preserves the scale of signals, dropout as an ensemble and as a penalty, weight decay against an L2 penalty under Adam (AdamW), learning-rate schedules with warm-up, early stopping, data augmentation, residual connections and layer normalization.
Exact gradients are not enough
The topic Backpropagation gave us exact gradients for a network of any depth, and ended with a warning: exact does not mean useful. Two things go wrong in practice.
The first is scale. The gradient that reaches the first layer is a product of one Jacobian per layer. If every factor shrinks a signal a little, thirty factors shrink it enormously. Here is an experiment on two moons, with classes : an input layer , then 30 ReLU layers of width 32, then one logit, trained with binary cross-entropy. All weights start at PyTorch's default initialization.
- At the start, the gradient with respect to the first layer's weights has norm .
- After 200 Adam steps the training loss is still , the loss of predicting probability for every point, and the training accuracy is .
Nothing is wrong with the gradient: it is computed exactly. It is simply too small to move anything.
The second is capacity. A network flexible enough to fit any rule also fits the noise in its labels. This is overfitting from the topic Validation and overfitting, and a large network is very good at it.
This topic collects the standard remedies. Some make a deep network trainable at all: initialization that preserves the scale, residual connections, layer normalization and a learning-rate schedule. Others keep it from overfitting: dropout, weight decay, early stopping and data augmentation. The course Deep Learning takes each of them further. Here we see what each one does and why it works, mostly on the two-moons stack above and on the small digits from the topic From linear models to networks.
Initialization that preserves the scale
Why not start from zero? If all weights of a layer are equal, every unit of the layer computes the same function and receives the same gradient. The units stay identical forever, and the layer acts like a single unit. Random weights break this symmetry. The question is their scale.
A layer computes and , with ; biases start at zero and are left out. The input width is the layer's fan-in. The weights are independent draws with mean 0 and variance , independent of the inputs. One pre-activation is a sum of terms with mean zero. They are uncorrelated, so their variances add (see the topic Joint distributions and independence of Probability Theory):
It is the second moment of , not its variance: after a ReLU the activations are not centred. If is symmetric around zero, the ReLU keeps half of its distribution, and . Each ReLU layer therefore multiplies the variance by , and depth turns that factor into a power. It equals one at the weight variance of He initialization:
For tanh, which is close to near zero, the factor is , and the variance is kept by . The backward pass sums over the outputs instead, so it wants . Glorot initialization takes the compromise , often as a uniform distribution on ; a uniform on has variance . For ReLU, He et al. (2015) showed that keeping either direction is enough in practice.
A simulation of 30 ReLU layers of width 256, for the weight variances , and :
import numpy as np
rng = np.random.default_rng(0)
x = rng.standard_normal((512, 256)) # 512 inputs of width 256
for v in (1 / 256, 2 / 256, 4 / 256): # weight variance 1/n, 2/n (He), 4/n
h = x
for layer in range(30):
z = h @ rng.normal(0, np.sqrt(v), (256, 256))
h = np.maximum(z, 0)
print(f"{v * 256:.0f}/n: {np.mean(z**2):.2g}")1/n: 4e-09
2/n: 1.4
4/n: 2.2e+09The theory predicts , and . The simulation lands within a factor of about two, the drift that random weights accumulate over 30 layers. What matters is the eighteen orders of magnitude between the ends. PyTorch's default for nn.Linear has variance , six times below He, and that is why the stack of the first block died. With He initialization the same stack starts with a first-layer gradient of and fits the two moons perfectly in 200 steps. Initialization fixes the scale only at the start; residual connections and normalization, later in this topic, keep it under control during training.
Dropout
Dropout switches off each unit of a layer at random during training. In the form used today, inverted dropout, each activation is replaced by
with a fresh mask for every example and every step. Here is the probability of dropping, as in nn.Dropout(p). The division by keeps the expectation, , so at test time the mask is simply removed: model.eval() turns dropout off. The original paper by Srivastava et al. (2014) used the retention probability instead and scaled the weights at test time; the two forms are equivalent.
An ensemble of thinned networks. A network with droppable units contains thinned subnetworks, one per mask, all sharing the same weights. Each training step trains one of them, sampled at random. At test time the full network stands in for the average of all their predictions. This is exact only in special cases, such as a single linear layer, but it works well in practice. Like bagging in the topic Bagging and random forests, dropout averages many models and decorrelates them by randomizing what each one sees. Unlike bagging, the members share their weights.
A penalty in disguise. For a linear model with dropout on its inputs, the expected squared error has a closed form. Write with , so that and . Since ,
Dropout adds a ridge-like penalty, as in the topic Regularization. The weight is penalized more when feature is large and when the dropout rate is high. For , , and : , the penalty is , and the expected loss is . An average over a million random masks gives .
Typical rates are to on hidden layers. Dropout matters most for large fully connected layers trained on modest data. Transformers use ; convolutional networks with batch normalization often use little or none.
Weight decay and AdamW
With SGD, weight decay and an L2 penalty are the same. The penalty adds to the gradient , and an SGD step becomes
Every step multiplies the weights by before the usual update: this is weight decay. The topic Regularization read the penalty as a Gaussian prior on the weights.
With Adam they differ. Adam from the topic Stochastic and adaptive optimizers divides each coordinate of its step by , the root mean square of that coordinate's recent gradients. With an L2 penalty, the term enters the gradient and is divided too. A weight whose gradients are typically large is decayed less; one with small gradients, more. Decoupled weight decay, the AdamW of Loshchilov and Hutter (2019), applies the shrinkage outside the adaptive step:
Now every weight decays at the same rate .
A worked example. Take , and a weight . Under AdamW it shrinks by per step, whatever its gradients. Under Adam with an L2 penalty the shrinkage is about , ignoring the penalty's own small share in . That is if the weight's gradients have root mean square , and if it is . The penalty we wrote down is the same for all weights, but the L2 version applies it a hundred times more strongly to one than to the other, depending only on how loud their gradients are.
In practice AdamW with between and is the default for Transformers. Biases and the scales of normalization layers are usually exempt from decay. Mind the names in PyTorch: torch.optim.AdamW(..., weight_decay=λ) is the decoupled version, while the weight_decay argument of torch.optim.Adam adds the L2 term to the gradient.
Learning-rate schedules and warm-up
A constant learning rate is a compromise. The topic Stochastic and adaptive optimizers showed that with stochastic gradients a constant step leaves the weights bouncing in a noise ball whose size grows with , and that a decreasing step gets both speed and precision. In deep learning the decrease is a hand-made schedule:
- Step decay: divide by 10 at a few fixed epochs.
- Cosine decay: for epoch of , a smooth glide from to (Loshchilov and Hutter, 2017):
- Inverse square root, the schedule of the original Transformer (Vaswani et al., 2017): linear growth over the first 4000 steps, then decay like .
With , and , the cosine gives , and . A linear decay would give at epoch 25. The cosine stays near the peak longer and spends its last quarter at small rates, where the noise ball shrinks.
Warm-up starts from a small rate and increases it linearly over the first steps, from a few hundred steps to a few epochs. At the start the weights are random, the gradients are large and point in inconsistent directions, and Adam's rests on very few steps. A full-size step at that moment can throw the network into a bad region it never leaves. Goyal et al. (2017) needed a warm-up over 5 epochs to train ResNet-50 with large batches and a correspondingly large rate. Transformers that normalize after the residual addition need it too.
Which peak rate? There is no formula. A short sweep over a logarithmic grid, a few hundred steps each, shows where the loss falls fastest without diverging. The schedule then shapes everything around that peak.
Early stopping and augmentation
Early stopping uses the number of steps as a regularizer. The training loss keeps falling, while the validation loss falls and then rises once the network starts fitting noise. So we keep the checkpoint with the lowest validation loss, and stop once it has not improved for a set number of epochs, the patience. For a quadratic loss, steps of gradient descent with rate act approximately like an L2 penalty with : fewer steps, stronger regularization.
An experiment. Take 300 training digits, and replace 30 % of their labels by random digits. A network trains with full-batch Adam for 300 epochs. The validation loss is lowest at epoch 127, at , and has risen to by epoch 300. On a separate test set the checkpoint from epoch 127 classifies of the digits correctly, the last one only . The validation set made a decision here, the epoch, so the honest accuracy comes from the test set, as the topic Validation and overfitting insisted.
Data augmentation adds knowledge instead of removing capacity. When the label is known not to change under some transformations of the input, we train on transformed copies: random crops, flips and colour changes for photographs, time shifts and added noise for audio. The model sees a new variant of each example in every epoch, and it is pushed to be invariant to those changes. The training loss becomes an expectation over a random transformation :
Each minibatch estimates it with one sampled per example, a Monte Carlo estimate in the sense of the topic Monte Carlo methods of Probability Theory.
The transformations encode prior knowledge, and wrong knowledge hurts: a mirrored "b" is a "d", and a 6 turned upside down is a 9. On the digits, a network trains on the same 300 digits, once as they are and once with four extra copies shifted by one pixel. On centred test digits, like the training ones, both classify correctly ( and ). On test digits shifted by one pixel in a random direction, the plain network drops to , while the augmented one keeps . Augmentation buys exactly the robustness it covers. Whether it raises the test score depends on whether the test data contain that variation. Tabular data usually have no natural transformation at all.
Residual connections and layer normalization
Deeper is not automatically better, even on the training set. He et al. (2016) found that a plain 56-layer convolutional network has a higher training error on the CIFAR-10 images than a 20-layer one. This degradation is not overfitting. The deeper network could copy the shallower one and set its extra layers to the identity; the optimizer simply fails to find such a solution. A residual connection makes the identity the default:
where , the residual branch, is a small stack of layers. With small weights , and the block passes its input through; it only has to learn a correction.
The chain rule shows what this does to the gradient. Unrolled over a stack ending at , the output is the input plus a sum of corrections, , instead of a product. With the adjoints and the rule from the topic Backpropagation,
The identity term carries the gradient to every layer without passing through a single weight matrix. This makes a vanishing gradient much less likely, but it is not a guarantee: the branch cancels the identity and zeroes the gradient. On the two moons, the stack of the first block with residual connections and the same default initialization starts with a first-layer gradient of instead of , and after 200 Adam steps classifies every training point correctly. A residual block needs its input and output to have the same shape, or a projection on the skip path. Residual connections are why ResNets reach hundreds of layers, and why Transformers stack dozens of blocks.
Normalization layers control the scale during training, not only at the start. Batch normalization standardizes each feature over the examples of a batch. That ties every output to the rest of the batch and requires running averages at inference. Layer normalization (Ba, Kiros and Hinton, 2016) standardizes each example over its own features:
where and are the mean and the variance of the entries of , and are learned. It does not depend on the batch, behaves the same in training and inference, and works for sequences of any length. That is why every Transformer uses it, or its variant RMSNorm. The topic Normalization and initialization of the course Deep Learning compares the normalization layers in detail.
A default recipe, and what comes next
Put together, a reasonable starting point for a new network:
- He initialization for ReLU-family layers, or the library default together with normalization layers.
- Residual connections and a normalization layer once the network has more than a handful of layers.
- AdamW with weight decay to , not applied to biases and normalization parameters.
- A peak learning rate from a short sweep, a linear warm-up, then cosine decay.
- Augmentation for every invariance the task really has; dropout where the network still overfits.
- A validation check every epoch that keeps the best checkpoint. Before any of this, check that the network can drive the loss to almost zero on one small batch: that catches most bugs in the model and the loss.
- Evaluation in evaluation mode:
model.eval()turns dropout off,torch.no_grad()records no graph, andmodel.train()switches back. Fixed seeds make a run repeatable, and a few seeds show how much of a difference is noise. The test set is evaluated once, at the end.
| A plain deep network | With the remedies of this topic | |
|---|---|---|
| signal scale at the start | shrinks or grows geometrically with depth | kept by He or Glorot initialization |
| gradient path to early layers | a product of one Jacobian per layer | an identity path through residual connections |
| regularization | none: the network fits label noise | dropout, decoupled weight decay, augmentation, early stopping |
| learning rate | one constant | warm-up, then decay |
| normalization | none | batch norm for convolutional networks, layer norm for Transformers |
Every remedy adds hyperparameters, and the derivations hold only at initialization; theory still lags behind practice here. The course Deep Learning goes deeper in its topics Normalization and initialization, Optimizing deep networks and Training networks in practice.
This topic closes the neural networks module. Every method so far, from nearest neighbours to deep networks, learned from examples with labels: a price, a class, a digit. Labels are expensive, and often there are none, only the inputs. The question then is what structure the inputs have: groups of similar customers, typical and unusual transactions, a few directions that explain most of the variation. The next topic, Clustering, opens the module Learning without labels, starting with k-means and the loss it minimizes.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.