Simple Algorithm
Machine Learning · Descent · 24 min

Training Networks Well

Normalization, regularization and the recipes that make deep learning work.

A network that can represent the right function can still fail to learn it. The loss explodes on step three, sits at chance for an hour, or falls to zero while validation accuracy goes nowhere. Training well is a sequence of decisions, and each one has a reason you can derive. This lesson takes them in the order you meet them, from scaling the inputs to reading the loss curves.

What you’ll learn

  • Standardize inputs, and explain from the Hessian of a linear model why uncentered or badly scaled features slow gradient descent.
  • Relate the largest stable learning rate to the curvature of the loss, and choose an optimizer, a warmup and a decay schedule.
  • Derive the batch-normalization forward pass, explain why it behaves differently in training and inference, and contrast it with layer normalization.
  • Apply weight decay, dropout, data augmentation and early stopping, and state what each one changes.
  • Diagnose a training run from its loss at initialization, its ability to overfit a small subset, and its training and validation curves.

Before the first step: inputs and initialization

Gradient descent is only as fast as the shape of the loss allows, and the inputs set that shape first. For a linear layer with squared loss L(w)=1n∥Xw−y∥2L(\mathbf w)=\frac1n\norm{X\mathbf w-\mathbf y}^2 the Hessian is ∇2L=2nX⊤X\nabla^2L=\frac2nX^\top X: twice the matrix of second moments of the inputs. Every feature's mean and scale lands directly in it.

So the default first step is standardization (LeCun, Bottou, Orr & Müller, 1998): replace each feature by (xj−mj)/sj(x_j-m_j)/s_j, with the mean mjm_j and standard deviation sjs_j computed on the training set only and then reused, unchanged, on validation and test data. Computing them on all the data leaks information from the test set.

DerivationWhat an uncentered feature does to the curvature
  1. ∇2L=2(E[x2]E[x]E[x]1)=2(μ2+s2μμ1)\nabla^2L=2\begin{pmatrix}\E[x^2]&\E[x]\\ \E[x]&1\end{pmatrix}=2\begin{pmatrix}\mu^2+s^2&\mu\\ \mu&1\end{pmatrix}

    Take one feature xx with mean μ\mu and standard deviation ss, and the model y^=wx+b\hat y=wx+b with mean squared error. The Hessian in (w,b)(w,b) holds the second moments of (x,1)(x,1):

  2. κ+1κ+2=(λ++λ−)2λ+λ−=(μ2+s2+1)2s2\kappa+\frac1\kappa+2=\frac{(\lambda_++\lambda_-)^2}{\lambda_+\lambda_-}=\frac{(\mu^2+s^2+1)^2}{s^2}

    For a 2×22\times2 positive definite matrix the eigenvalues satisfy λ++λ−=Tr⁡\lambda_++\lambda_-=\Tr and λ+λ−=det⁡\lambda_+\lambda_-=\det. Here the trace is 2(μ2+s2+1)2(\mu^2+s^2+1) and the determinant 4s24s^2, so the condition number κ=λ+/λ−\kappa=\lambda_+/\lambda_- obeys

  3. μ=0, s=1⟹∇2L=2I,κ=1\mu=0,\ s=1\quad\Longrightarrow\quad\nabla^2L=2I,\qquad\kappa=1

    A mean that is large compared with ss, or a spread far from 1 in either direction, makes κ\kappa large: the loss becomes a long, narrow valley (for a large positive mean, it runs along the direction that raises the slope while lowering the intercept). Centering (μ=0\mu=0) and scaling (s=1s=1) give ∇2L=2I\nabla^2L=2I and κ=1\kappa=1: every direction has the same curvature, so one learning rate suits them all.

Predict before you look

A feature has mean μ=3\mu=3 and standard deviation s=1s=1 and is not centered. What is the condition number κ\kappa of the Hessian in the one-feature model above?

Show the answer

119

(μ2+s2+1)2/s2=112=121(\mu^2+s^2+1)^2/s^2=11^2=121, so κ+1/κ=119\kappa+1/\kappa=119 and κ≈119\kappa\approx119. Gradient descent needs a number of steps roughly proportional to κ\kappa (Gradient Descent), so subtracting the mean, a one-line preprocessing step, saves about a factor of 100 in iterations on this problem.

The weights need random starting values. If every unit of a layer starts with the same weights, all of them compute the same function and receive the same gradient, and gradient descent keeps them identical forever. Random initialization breaks this symmetry, and its scale matters: weights with variance about 1/nin1/n_{\text{in}} for tanh units (LeCun et al., 1998), or 2/nin2/n_{\text{in}} for ReLU units (He, Zhang, Ren & Sun, 2015), keep the size of the activations roughly constant from layer to layer, where ninn_{\text{in}} is the number of inputs to a unit. Biases usually start at zero. The Convergence lesson Initialization & Signal Propagation derives these rules.

Check your understanding

Every weight and bias of a multilayer perceptron is initialized to exactly 0.10.1, and it is trained by gradient descent. What happens?

  1. Training works normally, because 0.10.1 is small
  2. The gradients are exactly zero, so nothing ever changes
  3. All units within each layer stay identical, so each layer acts like a single unit
  4. The output is stuck at 0.10.1 for every input
Show the answer

C. All units within each layer stay identical, so each layer acts like a single unit

The units of a layer compute the same function of the same inputs and receive the same gradient, so every update keeps them equal. However wide the layer, it carries one feature. Random initialization breaks the symmetry.

The learning rate and its schedule

Near a minimum the loss is approximately quadratic, L(θ)≈L⋆+12e⊤HeL(\boldsymbol\theta)\approx L^\star+\frac12\mathbf e^\top H\mathbf e with e=θ−θ⋆\mathbf e=\boldsymbol\theta-\boldsymbol\theta^\star. One gradient-descent step maps the error to e↦(I−ηH)e\mathbf e\mapsto(I-\eta H)\mathbf e, so along an eigenvector of HH with eigenvalue λi\lambda_i the error is multiplied by 1−ηλi1-\eta\lambda_i. Every factor must have absolute value below 1:

∣1−ηλi∣<1  for all i⟺0<η<2λmax⁡(H)\abs{1-\eta\lambda_i}<1\ \text{ for all } i\quad\Longleftrightarrow\quad0<\eta<\frac{2}{\lambda_{\max}(H)}
The steepest direction caps the learning rate, and the flattest direction then shrinks by only 1−ηλmin⁡1-\eta\lambda_{\min} per step. Too large and training diverges; too small and it crawls. That is why η\eta is usually the first hyperparameter to tune. Real networks are not quadratic, and Training Dynamics & the Edge of Stability shows what full-batch training does at the boundary 2/λmax⁡2/\lambda_{\max}.
Predict before you look

The surface below is f(x,y)=0.05x2+2y2f(x,y)=0.05x^2+2y^2. Past what learning rate does plain gradient descent stop converging on it?

Show the answer

0.5

The Hessian is diag⁡(0.1, 4)\operatorname{diag}(0.1,\,4), so λmax⁡=4\lambda_{\max}=4 and gradient descent needs η<2/4=0.5\eta<2/4=0.5. The floor of the valley alone would tolerate η<20\eta<20, but the steep direction decides. At η=0.3\eta=0.3 the steep coordinate is multiplied by 1−1.2=−0.21-1.2=-0.2 each step (a zig-zag that dies out), the flat one by 0.970.97 (a slow creep).

Choosing an optimizer. Two defaults cover most practice: SGD with momentum 0.90.9, common for convolutional networks, and Adam, standard for transformers. Kingma & Ba's (2015) defaults for Adam are η=10−3\eta=10^{-3}, β1=0.9\beta_1=0.9, β2=0.999\beta_2=0.999, ε=10−8\varepsilon=10^{-8}. With Adam, use decoupled weight decay (AdamW; Loshchilov & Hutter, 2019); Adaptive & Second-Order Methods derives why an L2 penalty is not the same thing there.

Scheduling it. A constant step never lets SGD settle: mini-batch noise leaves it hovering at a distance from the minimum that scales with η\eta (Stochastic Gradient Descent), so the rate is reduced as training goes on. The start needs care too. Many runs warm up, raising η\eta linearly from nearly zero during an initial stretch of training, because Adam's average of squared gradients v^\hat v has seen only a handful of steps, and because the first full-size steps from a random initialization can land where training is unstable. Goyal et al. (2017) paired a 5-epoch warmup with a linear scaling rule (multiply η\eta by kk when the batch size grows kk-fold) and trained a ResNet-50 on ImageNet with batches of 8,192 images.

The batch size is usually set by memory and hardware. A larger batch averages away gradient noise, so each step can be longer, but past a problem-dependent critical size, extra examples per step barely reduce the number of steps needed (Batch Size, Learning Rate & Noise).

python
import math

def learning_rate(step, peak=3e-4, warmup=1_000, total=100_000, floor=0.0):
    """Linear warmup to peak, then cosine decay to floor."""
    if step < warmup:
        return peak * (step + 1) / warmup
    progress = (step - warmup) / max(1, total - warmup)
    return floor + 0.5 * (peak - floor) * (1 + math.cos(math.pi * progress))

One common schedule: warmup, then cosine decay (Loshchilov & Hutter, 2017). Step decay (divide by 10 at fixed epochs) and linear decay to zero are other popular shapes; PyTorch ships them in torch.optim.lr_scheduler. To find the peak, Smith's (2017) range test trains briefly while increasing η\eta, and you pick a value somewhat below the point where the loss stops falling and starts to blow up.

Normalization layers

Standardizing the inputs fixes the first layer only. Every later layer sees activations whose mean and scale drift as the earlier weights change. Batch normalization (Ioffe & Szegedy, 2015) standardizes each unit's pre-activation zz across the mm examples of the mini-batch, then lets the network rescale it:

μ=1m∑i=1mzi,σ2=1m∑i=1m(zi−μ)2,yi=γ zi−μσ2+ϵ+β\mu=\frac1m\sum_{i=1}^mz_i,\qquad\sigma^2=\frac1m\sum_{i=1}^m(z_i-\mu)^2,\qquad y_i=\gamma\,\frac{z_i-\mu}{\sqrt{\sigma^2+\epsilon}}+\beta
One unit, one mini-batch. The scale γ\gamma and shift β\beta are learned per unit, so normalization does not limit what the layer can represent; ϵ\epsilon (often 10−510^{-5}) avoids division by zero. In a convolutional layer the statistics of each channel are also pooled over all spatial positions.
DerivationWhat normalization makes irrelevant
  1. (azi+c)−(aμ+c)aσ=zi−μσ\frac{(az_i+c)-(a\mu+c)}{a\sigma}=\frac{z_i-\mu}{\sigma}

    Replace every pre-activation by azi+caz_i+c with a>0a>0 (ignore ϵ\epsilon). The batch mean becomes aμ+ca\mu+c and the standard deviation aσa\sigma, so the normalized value does not change:

  2. L(aw)=L(w)for all a>0L(a\mathbf w)=L(\mathbf w)\quad\text{for all }a>0

    Two consequences. A bias added just before the normalization is wasted (β\beta plays its role), so such layers are usually built without one. And when z=w⊤xz=\mathbf w^\top\mathbf x, scaling the incoming weights w\mathbf w by any a>0a>0 leaves the output and the loss unchanged: only the direction of w\mathbf w matters. That changes how the learning rate and weight decay act on those weights, which Normalization Layers works out.

Training versus inference. In training mode, μ\mu and σ\sigma come from the current batch, so one example's output shifts with whatever else was sampled alongside it. A deployed model may see one input at a time, so at inference the layer uses exponential moving averages of μ\mu and σ2\sigma^2 kept during training instead (PyTorch's default update is running←0.9⋅running+0.1⋅batch value\text{running}\leftarrow0.9\cdot\text{running}+0.1\cdot\text{batch value}). With small batches the batch statistics are noisy estimates, and accuracy suffers.

Layer normalization (Ba, Kiros & Hinton, 2016) takes the mean and variance across the features of each example, not across the batch. No example ever sees another, so the layer does exactly the same thing in training and at inference; it is the usual normalizer in transformers and recurrent networks.

Check your understanding

A network with batch normalization gives a different prediction for the same test image depending on which other images share its batch. What is the most likely cause?

  1. The model is still in training mode, so it normalizes with the statistics of the test batch
  2. ϵ\epsilon is too small
  3. The learning rate was too high during training
  4. γ\gamma and β\beta were not trained
Show the answer

A. The model is still in training mode, so it normalizes with the statistics of the test batch

In training mode the layer uses the current batch's mean and variance, so every example's output depends on its neighbors. Inference must use the running averages (in PyTorch, call model.eval()), which makes each prediction a deterministic function of its own input.

Regularization: four tools and what each one changes

A network large enough to fit its training set can also memorize it, noise included. Regularization gives up a little training fit for better generalization. Four tools do most of the work in practice.

DerivationWeight decay, and why the optimizer matters
  1. w←w−η(∇L(w)+λw)=(1−ηλ) w−η ∇L(w)\mathbf w\leftarrow\mathbf w-\eta\big(\nabla L(\mathbf w)+\lambda\mathbf w\big)=(1-\eta\lambda)\,\mathbf w-\eta\,\nabla L(\mathbf w)

    Add the penalty λ2∥w∥2\frac\lambda2\norm{\mathbf w}^2 to the loss. One SGD step on the penalized loss first shrinks every weight by a constant factor, hence the name weight decay:

  2. AdamW:wi←(1−ηλ) wi−η m^iv^i+ε\text{AdamW:}\quad w_i\leftarrow(1-\eta\lambda)\,w_i-\eta\,\frac{\hat m_i}{\sqrt{\hat v_i}+\varepsilon}

    Adam divides each coordinate of the gradient by v^i\sqrt{\hat v_i}, its running gradient size, and the penalty's gradient λwi\lambda w_i gets divided too: weights with large past gradients are decayed much less. AdamW keeps the shrinking outside the adaptive scaling, so every weight decays at the same relative rate:

Dropout (Srivastava, Hinton, Krizhevsky, Sutskever & Salakhutdinov, 2014) zeroes each hidden unit independently during training, keeping it with probability qq. In the standard "inverted" form the kept units are multiplied by 1/q1/q, so with mask δ∼Bernoulli(q)\delta\sim\mathrm{Bernoulli}(q) the expected activation is unchanged, E[δa/q]=a\E[\delta a/q]=a, and at test time the full network runs with no masking and no rescaling. No unit can rely on a particular partner being present, and each step trains a different thinned subnetwork, all sharing one set of weights: an implicit ensemble.

Data augmentation trains on transformed copies of each example that keep its label: random crops, flips and color changes for photos, noise and time shifts for audio. It is the most direct way to tell a network about an invariance you know holds.

Early stopping monitors the validation loss, keeps the checkpoint with the best value, and stops after a set number of epochs (the "patience") without improvement. For gradient descent on a linear model it acts much like ridge regression, with ηt\eta t, the learning rate times the number of steps, playing the role of 1/λ1/\lambda.

python
import torch
import torch.nn as nn

model = nn.Sequential(
    nn.Linear(784, 512, bias=False), nn.BatchNorm1d(512), nn.ReLU(), nn.Dropout(p=0.2),
    nn.Linear(512, 10),
)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)

model.train()   # dropout on, batch norm uses batch statistics
# ... training loop ...
model.eval()    # dropout off, batch norm uses its running averages

PyTorch's p is the probability of dropping a unit, so p=0.2p=0.2 means q=0.8q=0.8. The first layer has no bias because the batch normalization after it would cancel one. Forgetting the switch between train() and eval() silently changes both dropout and batch normalization.

ToolWhat it changesWatch out for
Weight decaypulls every weight toward zero at each stepuse AdamW with Adam; biases and normalization parameters are often exempted; for weights feeding a normalization layer it mainly changes the effective learning rate
Dropouttrains many weight-sharing subnetworks; the test-time network approximates their averagemust be off at inference; usually lighter or absent where data are plentiful
Data augmentationadds transformed copies, encoding an invarianceeach transformation must preserve the label (a rotated 6 can become a 9)
Early stoppinglimits how far training moves from its starting pointthe validation set used to stop is no longer an unbiased estimate of test error
Check your understanding

A hidden layer is trained with inverted dropout, keeping each unit with probability q=0.5q=0.5. What should you do to that layer's activations at test time?

  1. Multiply them by 0.50.5
  2. Multiply them by 22
  3. Drop half of them at random, as in training
  4. Nothing: use them as they are
Show the answer

D. Nothing: use them as they are

Inverted dropout already rescales the kept units by 1/q1/q during training, so the expected activation equals the undropped one. At test time the full layer runs unchanged. (The original formulation instead multiplied the weights by qq at test time; inverted dropout moves that correction into training.)

Reading the curves: a debugging recipe

Before tuning anything, establish that the pipeline can learn at all. A recipe that catches most problems early:

  1. Check the loss at initialization. With small random weights the logits are nearly equal, so a KK-class softmax assigns about 1/K1/K to every class and the cross-entropy should be close to ln⁡K\ln K. A very different number points to a bug in the loss, the labels or the initialization scale.
  2. Overfit a tiny subset. Turn regularization off and train on one or a few batches: the training loss should go nearly to zero. If it does not, the problem is capacity, optimization or a bug, not generalization.
  3. Find the learning rate with a short range test, then train on everything while plotting training and validation loss together.
  4. Regularize only once the model overfits, and stop on the validation curve.
Predict before you look

A 10-class classifier is freshly initialized, and its logits are nearly equal for every input. What should its average cross-entropy loss be, in nats?

Show the answer

2.3

Equal logits give probability 1/101/10 to the true class, so the loss is −ln⁡(1/10)=ln⁡10≈2.303-\ln(1/10)=\ln10\approx2.303. An initial loss of, say, 9 means the network starts out confidently wrong, usually because the final layer's weights are too large.

What you seeLikely causeFirst thing to try
Loss is NaN or explodes in the first stepssteps too large for the curvature; bad initialization scalelower the learning rate, add warmup, clip gradients
Loss stays near ln⁡K\ln Kno learning signal: mismatched labels, learning rate far too small, a bugoverfit one batch; look at inputs and labels by hand
Training loss falls, validation loss turns upoverfittingaugmentation, weight decay, dropout, early stopping, more data
Both losses high and close togetherunderfittinga larger model, longer training, less regularization
Validation far worse than training from the startthe splits come from different distributions, or are preprocessed differentlyaudit how the splits were made and preprocessed

Key takeaways

  • Standardize inputs with training-set statistics. For one feature with a bias, κ+1/κ+2=(μ2+s2+1)2/s2\kappa+1/\kappa+2=(\mu^2+s^2+1)^2/s^2: an uncentered or tightly clustered feature makes the loss a narrow valley.
  • On a quadratic, gradient descent is stable iff η<2/λmax⁡\eta<2/\lambda_{\max}, and the flat directions then set the pace. Warm up, then decay the learning rate; SGD with momentum and Adam(W) are the standard optimizers.
  • Batch normalization standardizes each unit over the mini-batch and switches to running averages at inference; layer normalization normalizes each example over its features and needs no batch.
  • Weight decay, dropout, augmentation and early stopping each limit memorization in a different way. With Adam, use decoupled weight decay (AdamW).
  • Debug in order: loss at initialization near ln⁡K\ln K, overfit a tiny subset, range-test the learning rate, then regularize while watching the gap between training and validation curves.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

You train a new network with Adam at learning rate 0.10.1, and the loss becomes NaN within five steps. What should you change first?

  1. Add dropout
  2. Train for more epochs
  3. Increase the weight decay
  4. Lower the learning rate, and add a warmup
Show the answer

D. Lower the learning rate, and add a warmup

A loss that blows up in the first steps is the signature of steps too large for the local curvature (η>2/λmax⁡\eta>2/\lambda_{\max} on a quadratic). For Adam, 0.10.1 is a hundred times its usual default of 10−310^{-3}. A smaller peak rate, a warmup, or gradient clipping are the fixes.

Question 2

Why does standardizing the input features speed up gradient descent?

  1. Backpropagation cannot compute gradients for unscaled features
  2. It makes the Hessian better conditioned, so one learning rate suits all directions
  3. It prevents overfitting by shrinking the weights
  4. It makes the trained network invariant to rescaled inputs at test time
Show the answer

B. It makes the Hessian better conditioned, so one learning rate suits all directions

For a linear layer the Hessian is the second-moment matrix of the inputs. Means and unequal scales make it ill-conditioned, so the step size allowed by the steepest direction barely moves the flattest one. Centered, unit-variance features make the curvature similar in every direction.

Question 3

Over which numbers does layer normalization compute the mean and variance it normalizes with?

  1. One unit's pre-activations across the examples of the mini-batch
  2. Running averages collected over many training batches
  3. All the pre-activations of a single example, across its features
  4. The entries of the layer's weight matrix
Show the answer

C. All the pre-activations of a single example, across its features

Layer normalization standardizes each example by the mean and spread of its own features, so it never looks at other examples: it works with a batch of one and does the same thing in training and at inference. Batch normalization pools one unit across the batch instead.

Question 4

Training accuracy is 100%, validation accuracy is 72%, and the validation loss has been rising since epoch 10. Which change is most likely to help?

  1. Stronger augmentation or weight decay, and stopping near epoch 10
  2. A larger learning rate
  3. A bigger network
  4. Removing the weight decay
Show the answer

A. Stronger augmentation or weight decay, and stopping near epoch 10

A perfect training score with a widening validation gap is overfitting. Regularization (augmentation, weight decay, dropout) narrows the gap, and early stopping keeps the checkpoint from before the validation loss turned up.

Question 5

How do an L2 penalty λ2∥w∥2\frac\lambda2\norm{\mathbf w}^2 and decoupled weight decay compare?

  1. They are identical for every optimizer
  2. Weight decay only has an effect with adaptive optimizers
  3. For SGD they give the same update; for Adam they differ, because Adam rescales the penalty's gradient by 1/v^1/\sqrt{\hat v} along with the loss gradient
  4. The L2 penalty always generalizes better
Show the answer

C. For SGD they give the same update; for Adam they differ, because Adam rescales the penalty's gradient by 1/v^1/\sqrt{\hat v} along with the loss gradient

With SGD, w−η(∇L+λw)=(1−ηλ)w−η∇L\mathbf w-\eta(\nabla L+\lambda\mathbf w)=(1-\eta\lambda)\mathbf w-\eta\nabla L, exactly a decay. Adam rescales coordinate ii by 1/(v^i+ε)1/(\sqrt{\hat v_i}+\varepsilon), so the penalty decays weights with large past gradients less. AdamW shrinks every weight by the same factor 1−ηλ1-\eta\lambda.

Go deeper

Further reading

  • I. Goodfellow, Y. Bengio & A. Courville, Deep Learning (MIT Press, 2016), chapters 7, 8 and 11.
  • Y. LeCun, L. Bottou, G. B. Orr & K.-R. Müller, "Efficient BackProp," in Neural Networks: Tricks of the Trade, Lecture Notes in Computer Science 1524, 9–50 (Springer, 1998).
  • S. Ioffe & C. Szegedy, "Batch normalization: accelerating deep network training by reducing internal covariate shift," ICML (2015).
  • I. Loshchilov & F. Hutter, "Decoupled weight decay regularization," ICLR (2019).