Skip to content
BIASED

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 {0,1}\{0, 1\}: an input layer 2→322 \to 32, 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 3.2⋅10−133.2 \cdot 10^{-13}.
  • After 200 Adam steps the training loss is still 0.693=ln⁡20.693 = \ln 2, the loss of predicting probability 12\tfrac12 for every point, and the training accuracy is 0.50.5.

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 zl=Wlhl−1z_l = W_l h_{l-1} and hl=φ(zl)h_l = \varphi(z_l), with h0=xh_0 = x; biases start at zero and are left out. The input width nl−1n_{l-1} is the layer's fan-in. The weights are independent draws with mean 0 and variance vlv_l, independent of the inputs. One pre-activation is a sum of nl−1n_{l-1} terms WijhjW_{ij} h_j with mean zero. They are uncorrelated, so their variances add (see the topic Joint distributions and independence of Probability Theory):

Var⁡(zl)=nl−1 vl E[hl−12].\operatorname{Var}(z_l) = n_{l-1}\, v_l\, \mathbb E\big[h_{l-1}^2\big].

It is the second moment of hh, not its variance: after a ReLU the activations are not centred. If zl−1z_{l-1} is symmetric around zero, the ReLU keeps half of its distribution, and E[ReLU⁡(z)2]=12Var⁡(z)\mathbb E[\operatorname{ReLU}(z)^2] = \tfrac12 \operatorname{Var}(z). Each ReLU layer therefore multiplies the variance by 12nl−1vl\tfrac12 n_{l-1} v_l, and depth turns that factor into a power. It equals one at the weight variance of He initialization:

vl=2nl−1.v_l = \frac{2}{n_{l-1}}.

For tanh, which is close to φ(z)=z\varphi(z) = z near zero, the factor is nl−1vln_{l-1} v_l, and the variance is kept by vl=1/nl−1v_l = 1/n_{l-1}. The backward pass hˉl−1=Wl⊤zˉl\bar h_{l-1} = W_l^\top \bar z_l sums over the nln_l outputs instead, so it wants 1/nl1/n_l. Glorot initialization takes the compromise vl=2/(nl−1+nl)v_l = 2/(n_{l-1} + n_l), often as a uniform distribution on ±6/(nl−1+nl)\pm\sqrt{6/(n_{l-1} + n_l)}; a uniform on ±a\pm a has variance a2/3a^2/3. 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 1/n1/n, 2/n2/n and 4/n4/n:

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+09

The theory predicts 2−29≈1.9⋅10−92^{-29} \approx 1.9 \cdot 10^{-9}, 22 and 231≈2.1⋅1092^{31} \approx 2.1 \cdot 10^{9}. 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 1/(3nl−1)1/(3 n_{l-1}), 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 0.180.18 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 hjh_j is replaced by

h~j=mj1−p hj,mj∼Bernoulli⁡(1−p),\tilde h_j = \frac{m_j}{1 - p}\, h_j, \qquad m_j \sim \operatorname{Bernoulli}(1 - p),

with a fresh mask for every example and every step. Here pp is the probability of dropping, as in nn.Dropout(p). The division by 1−p1 - p keeps the expectation, E h~j=hj\mathbb E\, \tilde h_j = h_j, 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 NN droppable units contains 2N2^N 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 y^=∑jrjwjxj\hat y = \sum_j r_j w_j x_j with rj=mj/(1−p)r_j = m_j / (1 - p), so that E rj=1\mathbb E\, r_j = 1 and Var⁡rj=p/(1−p)\operatorname{Var} r_j = p / (1 - p). Since E(y−y^)2=(y−Ey^)2+Var⁡y^\mathbb E (y - \hat y)^2 = (y - \mathbb E \hat y)^2 + \operatorname{Var} \hat y,

E[(y−y^)2]=(y−w⊤x)2+p1−p∑jwj2xj2.\mathbb E\big[(y - \hat y)^2\big] = (y - w^\top x)^2 + \frac{p}{1 - p} \sum_j w_j^2 x_j^2.

Dropout adds a ridge-like penalty, as in the topic Regularization. The weight wjw_j is penalized more when feature jj is large and when the dropout rate is high. For x=(1,2)x = (1, 2), w=(0.5,−0.25)w = (0.5, -0.25), y=1y = 1 and p=0.5p = 0.5: w⊤x=0w^\top x = 0, the penalty is 1⋅(0.25⋅1+0.0625⋅4)=0.51 \cdot (0.25 \cdot 1 + 0.0625 \cdot 4) = 0.5, and the expected loss is 1.51.5. An average over a million random masks gives 1.4991.499.

Typical rates are p=0.1p = 0.1 to 0.50.5 on hidden layers. Dropout matters most for large fully connected layers trained on modest data. Transformers use p=0.1p = 0.1; 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 λ2∥w∥2\tfrac\lambda2 \lVert w \rVert^2 adds λw\lambda w to the gradient gg, and an SGD step becomes

w←w−η(g+λw)=(1−ηλ) w−ηg.w \leftarrow w - \eta (g + \lambda w) = (1 - \eta\lambda)\, w - \eta g.

Every step multiplies the weights by 1−ηλ1 - \eta\lambda 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 s^\sqrt{\hat s}, the root mean square of that coordinate's recent gradients. With an L2 penalty, the term λw\lambda w 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:

w←w−ηλ w−η m^s^+ε.w \leftarrow w - \eta\lambda\, w - \eta\, \frac{\hat m}{\sqrt{\hat s} + \varepsilon}.

Now every weight decays at the same rate ηλ\eta\lambda.

A worked example. Take η=10−3\eta = 10^{-3}, λ=10−2\lambda = 10^{-2} and a weight w=1w = 1. Under AdamW it shrinks by ηλw=10−5\eta\lambda w = 10^{-5} per step, whatever its gradients. Under Adam with an L2 penalty the shrinkage is about ηλw/s^\eta\lambda w / \sqrt{\hat s}, ignoring the penalty's own small share in s^\hat s. That is 10−610^{-6} if the weight's gradients have root mean square 1010, and 10−410^{-4} if it is 0.10.1. 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 λ\lambda between 10−210^{-2} and 10−110^{-1} 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 η\eta, and that a decreasing step gets both speed and precision. In deep learning the decrease is a hand-made schedule:

  • Step decay: divide η\eta by 10 at a few fixed epochs.
  • Cosine decay: for epoch tt of TT, a smooth glide from ηmax⁡\eta_{\max} to ηmin⁡\eta_{\min} (Loshchilov and Hutter, 2017):
ηt=ηmin⁡+12(ηmax⁡−ηmin⁡)(1+cos⁡(πt/T)).\eta_t = \eta_{\min} + \tfrac12 (\eta_{\max} - \eta_{\min}) \big(1 + \cos(\pi t / T)\big).
  • Inverse square root, the schedule of the original Transformer (Vaswani et al., 2017): linear growth over the first 4000 steps, then decay like 1/t1 / \sqrt t.

With ηmax⁡=10−3\eta_{\max} = 10^{-3}, ηmin⁡=0\eta_{\min} = 0 and T=100T = 100, the cosine gives η25=8.54⋅10−4\eta_{25} = 8.54 \cdot 10^{-4}, η50=5⋅10−4\eta_{50} = 5 \cdot 10^{-4} and η75=1.46⋅10−4\eta_{75} = 1.46 \cdot 10^{-4}. A linear decay would give 7.5⋅10−47.5 \cdot 10^{-4} 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 s^\hat 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, τ\tau steps of gradient descent with rate η\eta act approximately like an L2 penalty with λ≈1/(ητ)\lambda \approx 1 / (\eta \tau): fewer steps, stronger regularization.

An experiment. Take 300 training digits, and replace 30 % of their labels by random digits. A network 64→256→1064 \to 256 \to 10 trains with full-batch Adam for 300 epochs. The validation loss is lowest at epoch 127, at 0.5920.592, and has risen to 0.7570.757 by epoch 300. On a separate test set the checkpoint from epoch 127 classifies 0.8810.881 of the digits correctly, the last one only 0.7880.788. 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 τ\tau:

1n∑i=1nEτ L(yi,a(τ(xi))).\frac1n \sum_{i=1}^n \mathbb E_\tau\, L\big(y_i, a(\tau(x_i))\big).

Each minibatch estimates it with one sampled τ\tau 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 64→128→1064 \to 128 \to 10 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 0.940.94 correctly (0.9380.938 and 0.9370.937). On test digits shifted by one pixel in a random direction, the plain network drops to 0.460.46, while the augmented one keeps 0.8880.888. 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:

xl+1=xl+Fl(xl),x_{l+1} = x_l + F_l(x_l),

where FlF_l, the residual branch, is a small stack of layers. With small weights Fl≈0F_l \approx 0, 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 xDx_D, the output is the input plus a sum of corrections, xD=xl+∑i=lD−1Fi(xi)x_D = x_l + \sum_{i=l}^{D-1} F_i(x_i), instead of a product. With the adjoints xˉ=∂L/∂x\bar x = \partial L / \partial x and the rule uˉ=J⊤vˉ\bar u = J^\top \bar v from the topic Backpropagation,

xˉl=(I+∂∂xl∑i=lD−1Fi(xi)) ⁣⊤xˉD.\bar x_l = \Big(I + \frac{\partial}{\partial x_l} \sum_{i=l}^{D-1} F_i(x_i)\Big)^{\!\top} \bar x_D.

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 F(x)=−xF(x) = -x 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 2.42.4 instead of 3.2⋅10−133.2 \cdot 10^{-13}, 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 dd features:

LN⁡(x)=γ⊙x−μσ2+ε+β,\operatorname{LN}(x) = \gamma \odot \frac{x - \mu}{\sqrt{\sigma^2 + \varepsilon}} + \beta,

where μ\mu and σ2\sigma^2 are the mean and the variance of the dd entries of xx, and γ,β∈Rd\gamma, \beta \in \mathbb R^d 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:

  1. He initialization for ReLU-family layers, or the library default together with normalization layers.
  2. Residual connections and a normalization layer once the network has more than a handful of layers.
  3. AdamW with weight decay 10−210^{-2} to 10−110^{-1}, not applied to biases and normalization parameters.
  4. A peak learning rate from a short sweep, a linear warm-up, then cosine decay.
  5. Augmentation for every invariance the task really has; dropout where the network still overfits.
  6. 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.
  7. Evaluation in evaluation mode: model.eval() turns dropout off, torch.no_grad() records no graph, and model.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.

Full notes

Answers are saved on the server and tied to this browser until you sign in.