Simple Algorithm
Deep Learning · Representation · 22 min

Weight Decay, Dropout & Early Stopping

The classic regularizers, and what each one actually does to a deep network.

Three regularizers have been part of deep-learning recipes since the early 2010s, and each takes only a few lines of code. Here you derive what they do to the weights: weight decay is a constant shrink factor per step, which stops being an L2L_2 penalty inside Adam; dropout trains an exponential family of thinned subnetworks at once; and early stopping turns training time itself into a penalty.

What you’ll learn

  • Derive that an L2L_2 penalty and weight decay coincide for SGD, compute the per-step shrink factor 1−ηλ1-\eta\lambda, and read the penalty as a Gaussian prior.
  • Explain why the equivalence fails for Adam, and set up decoupled weight decay (AdamW) with the usual exclusions.
  • Implement inverted dropout, derive its 1/p1/p scaling, and explain the weight-scaling inference rule and the ensemble view.
  • Run early stopping with a validation set and patience, and show that for least squares it filters the solution like ridge with λ≈1/(ηt)\lambda\approx1/(\eta t).
  • Place label smoothing, stochastic depth and max-norm constraints in the same toolbox, and say which regularizers each training regime typically uses.

Weight decay is an L2 penalty, for SGD

The oldest regularizer adds a penalty on the squared size of the weights to the training loss L(θ)\loss(\boldsymbol\theta): L2L_2 regularization, with strength λ\lambda. Follow one SGD step with learning rate η\eta and mini-batch gradient gt\mathbf g_t:

DerivationFrom penalty to decay
  1. Lλ(θ)=L(θ)+λ2∥θ∥2,∇Lλ(θ)=∇L(θ)+λθ\loss_\lambda(\boldsymbol\theta)=\loss(\boldsymbol\theta)+\frac\lambda2\norm{\boldsymbol\theta}^2,\qquad\nabla\loss_\lambda(\boldsymbol\theta)=\nabla\loss(\boldsymbol\theta)+\lambda\boldsymbol\theta

    The penalized objective and its gradient:

  2. θt+1=θt−η(gt+λθt)=(1−ηλ) θt−η gt\boldsymbol\theta_{t+1}=\boldsymbol\theta_t-\eta(\mathbf g_t+\lambda\boldsymbol\theta_t)=(1-\eta\lambda)\,\boldsymbol\theta_t-\eta\,\mathbf g_t

    An SGD step on it, regrouped:

  3. θt=(1−ηλ)tθ0≈e−ηλt θ0,\boldsymbol\theta_t=(1-\eta\lambda)^t\boldsymbol\theta_0\approx e^{-\eta\lambda t}\,\boldsymbol\theta_0,

    So each step first multiplies every weight by 1−ηλ1-\eta\lambda, then takes the ordinary gradient step: the weights decay. Without gradients, tt steps would leave

  4. a decay with time constant 1/(ηλ)1/(\eta\lambda) steps. A weight survives only if its gradient keeps pushing back: the network keeps large only the weights that keep earning their size. This is weight decay, and for plain SGD it is exactly the L2L_2 penalty.

Predict before you look

A classic CIFAR-10 ResNet recipe uses SGD with η=0.1\eta=0.1 and λ=5×10−4\lambda=5\times10^{-4}, and an epoch has 391 steps. If the gradients were zero, what percentage of a weight's size would remain after one epoch?

Show the answer

98.1 %

(1−5×10−5)391≈e−0.0196≈0.981(1-5\times10^{-5})^{391}\approx e^{-0.0196}\approx0.981: a 1.9% shrink per epoch. Small, but relentless: over 100 epochs the decay alone would multiply a weight by e−1.96≈0.14e^{-1.96}\approx0.14, so only weights that the gradient keeps feeding stay large.

Inside Adam, an L2 penalty is not weight decay

Adam divides each coordinate's step by v^j\sqrt{\hat v_j}, the root mean square of its recent gradients. If the penalty's gradient λθj\lambda\theta_j is added to the loss gradient, it is divided too, and the equivalence above breaks (Loshchilov & Hutter, 2019). To see it, drop momentum, ϵ\epsilon and bias correction:

DerivationTwo ways to add decay to Adam
  1. θj←θj−η gj+λθjvj=(1−ηλvj)θj−η gjvj\theta_j\leftarrow\theta_j-\eta\,\frac{g_j+\lambda\theta_j}{\sqrt{v_j}}=\Big(1-\frac{\eta\lambda}{\sqrt{v_j}}\Big)\theta_j-\eta\,\frac{g_j}{\sqrt{v_j}}

    Adam with an L2L_2 penalty: the penalty's gradient enters the normalized step, so each coordinate decays at its own rate.

  2. Coordinates with large gradients (large vj\sqrt{v_j}) are hardly decayed at all, and rarely updated coordinates with tiny gradients are decayed hardest: the opposite of an isotropic Gaussian prior.

  3. θj←(1−ηλ) θj−η m^jv^j+ϵ\theta_j\leftarrow(1-\eta\lambda)\,\theta_j-\eta\,\frac{\hat m_j}{\sqrt{\hat v_j}+\epsilon}

    Decoupled weight decay (AdamW) applies the shrink outside the normalization, so every coordinate decays by the same factor, as in SGD:

  4. Loshchilov and Hutter proved that no choice of L2L_2 coefficient makes the two coincide unless the preconditioner is a multiple of the identity, and found that the decoupled form generalized better and made the best λ\lambda less dependent on η\eta. AdamW became the default optimizer for transformers.

python
import torch

model = torch.nn.Sequential(torch.nn.Linear(512, 512), torch.nn.LayerNorm(512), torch.nn.Linear(512, 10))
decay, no_decay = [], []
for name, p in model.named_parameters():
    # matrices are decayed; biases and normalization gains (1-D) usually are not
    (decay if p.ndim >= 2 else no_decay).append(p)

opt = torch.optim.AdamW(
    [{"params": decay, "weight_decay": 0.1},
     {"params": no_decay, "weight_decay": 0.0}],
    lr=3e-4, betas=(0.9, 0.95))
# each step multiplies the decayed weights by (1 - lr * 0.1), so the decay follows the lr schedule

Excluding biases and normalization gains from decay is common practice rather than theory: shrinking a gain toward zero changes what the layer computes. A λ\lambda of 0.1 with AdamW is a common choice for transformers; GPT-3 used it "to provide a small amount of regularization" (Brown et al., 2020). For SGD on ImageNet ResNets, He et al. (2016) used 10−410^{-4}.

Check your understanding

You train with Adam and add λ2∥θ∥2\frac\lambda2\norm{\boldsymbol\theta}^2 to the loss. Which weights end up regularized least?

  1. All weights equally, as with SGD
  2. Weights whose gradients are consistently large
  3. Weights whose gradients are usually tiny
  4. Only the biases
Show the answer

B. Weights whose gradients are consistently large

Adam divides the whole gradient, penalty included, by vj\sqrt{v_j}. Where gradients are large the penalty's push ηλθj/vj\eta\lambda\theta_j/\sqrt{v_j} is small, so those weights barely decay. AdamW avoids this by shrinking every weight by 1−ηλ1-\eta\lambda directly.

Dropout

Dropout (Hinton et al., 2012; Srivastava et al., 2014) makes training noisy on purpose. At every step each unit of a layer is kept with probability pp and set to zero otherwise, with a fresh random mask for every example. A unit can no longer count on any particular partner being present, which discourages fragile co-adaptations. In the now-standard inverted form, the kept units are scaled up by 1/p1/p during training:

h~=m⊙hp,mj∼Bernoulli(p)⟹E[h~j]=hj,Var⁡[h~j]=1−pp hj2\tilde{\mathbf h}=\frac{\mathbf m\odot\mathbf h}{p},\quad m_j\sim\mathrm{Bernoulli}(p)\qquad\Longrightarrow\qquad\E[\tilde h_j]=h_j,\qquad\Var[\tilde h_j]=\frac{1-p}{p}\,h_j^2
Because the expected activation is unchanged, the network is used as is at test time, with dropout switched off. Srivastava et al. described the equivalent original form: no scaling during training, and every outgoing weight multiplied by pp at test time, the weight-scaling inference rule.
Predict before you look

With keep probability p=0.8p=0.8, by what factor does inverted dropout multiply the units it keeps during training?

Show the answer

1.25

1/p=1/0.8=1.251/p=1/0.8=1.25. A unit survives 80% of the time, so its expected output is 0.8×1.25 h=h0.8\times1.25\,h=h, exactly what the next layer sees at test time when nothing is dropped.

python
import torch
import torch.nn.functional as F

def inverted_dropout(h, keep=0.8, training=True):
    if not training:
        return h                                  # test time: identity
    mask = (torch.rand_like(h) < keep).to(h.dtype)
    return h * mask / keep                        # E[output] = h

h = torch.randn(32, 256)
a = inverted_dropout(h, keep=0.8)
b = F.dropout(h, p=0.2, training=True)            # same thing: PyTorch's p is the DROP probability
layer = torch.nn.Dropout(p=0.2)                   # active after model.train(), identity after model.eval()

A common bug: PyTorch's p is the probability of dropping a unit, while this course (like Srivastava et al.) writes pp for the probability of keeping it. Another: forgetting model.eval(), which leaves dropout on at inference and makes predictions noisy and worse.

The ensemble view. A layer with nn droppable units defines 2n2^n thinned subnetworks that share weights. Each training step samples one of them and takes a gradient step on it; most are never sampled, yet all of them improve, since they share parameters. At test time one would like the average prediction of the whole family. The weight-scaling rule replaces that average by a single deterministic pass. When the dropped units feed a single softmax layer directly, the rule is exact for the normalized geometric mean of the subnetworks' predictions (derived in Dropout in Depth); in deeper networks it is an approximation, and on MNIST Srivastava et al. found that averaging about 50 sampled subnetworks was needed to match it.

Where to put it. The original networks dropped hidden units of fully connected layers with p=0.5p=0.5 and inputs with p≈0.8p\approx0.8. On convolutional feature maps neighboring activations are strongly correlated, so dropping single units does little; dropping whole channels or blocks works better. The original base transformer applied dropout with rate 0.1 to each sublayer's output and to the summed embeddings (Vaswani et al., 2017). Large language model pretraining often uses none at all: PaLM "was trained without dropout, although dropout of 0.1 is used for finetuning in most cases" (Chowdhery et al., 2023). With roughly one pass over an enormous corpus there is little overfitting to prevent, while the noise slows optimization; fine-tuning on a small dataset brings overfitting, and dropout, back.

Check your understanding

A colleague trains with inverted dropout (keep probability 0.50.5) but, following the original paper, also multiplies the activations by 0.50.5 at test time. What happens?

  1. Nothing: the two scalings are equivalent, so applying both is harmless
  2. The network becomes an exact ensemble of its subnetworks
  3. Dropout is effectively turned off during training
  4. Test-time activations are half the size the next layer was trained to expect, so outputs are systematically distorted
Show the answer

D. Test-time activations are half the size the next layer was trained to expect, so outputs are systematically distorted

Inverted dropout already made the expected training activation equal to hh. Scaling by 0.50.5 again at test time halves every input to the next layer, so pre-activations shift and the predictions go wrong. Use one convention, not both.

Early stopping

Early stopping costs nothing and is used almost everywhere a validation set exists. Evaluate the validation loss every epoch (or every few hundred steps), remember the best checkpoint, and stop once the loss has not improved for a set number of evaluations, the patience:

text
EARLY-STOPPING(patience P, minimum improvement δ)
  best ← +∞;  wait ← 0
  for epoch = 1, 2, …:
      train for one epoch
      v ← validation loss
      if v < best − δ:
          best ← v;  wait ← 0;  save a checkpoint
      else:
          wait ← wait + 1
          if wait ≥ P: break
  restore the saved checkpoint

Patience guards against noisy validation curves, which can flatten and dip again. Prechelt (1998) compared stopping criteria on many problems and found that slower, more patient criteria bought small gains in generalization at a large cost in training time.

Why does stopping early act like a regularizer? For least squares it is exactly a spectral filter, close to ridge. Take L(w)=12n∥y−Xw∥2\loss(\mathbf w)=\frac1{2n}\norm{\mathbf y-X\mathbf w}^2 with Σ^=X⊤X/n=∑jsjvjvj⊤\hat\Sigma=X^\top X/n=\sum_js_j\mathbf v_j\mathbf v_j^\top invertible, least-squares solution w^\hat{\mathbf w}, and gradient descent started at w0=0\mathbf w_0=\mathbf 0:

DerivationGradient descent filters like ridge
  1. wt+1−w^=(I−ηΣ^)(wt−w^)⟹wt=[I−(I−ηΣ^)t]w^\mathbf w_{t+1}-\hat{\mathbf w}=(I-\eta\hat\Sigma)(\mathbf w_t-\hat{\mathbf w})\quad\Longrightarrow\quad\mathbf w_t=\big[I-(I-\eta\hat\Sigma)^t\big]\hat{\mathbf w}

    The gradient is Σ^(w−w^)\hat\Sigma(\mathbf w-\hat{\mathbf w}), so each step contracts the error by a fixed matrix:

  2. vj⊤wt=[1−(1−ηsj)t] vj⊤w^,vj⊤wλ=sjsj+λ vj⊤w^\mathbf v_j^\top\mathbf w_t=\big[1-(1-\eta s_j)^t\big]\,\mathbf v_j^\top\hat{\mathbf w},\qquad\mathbf v_j^\top\mathbf w_\lambda=\frac{s_j}{s_j+\lambda}\,\mathbf v_j^\top\hat{\mathbf w}

    Along each eigenvector the least-squares coefficient is multiplied by a filter factor. Ridge, wλ=(Σ^+λI)−1Σ^w^\mathbf w_\lambda=(\hat\Sigma+\lambda I)^{-1}\hat\Sigma\hat{\mathbf w}, does the same with a different factor:

  3. λ≈1η t\lambda\approx\frac{1}{\eta\,t}

    Both factors are near 11 for strong directions (large sjs_j) and near 00 for weak ones. Gradient descent's factor, about 1−e−ηtsj1-e^{-\eta t s_j}, switches over near sj≈1/(ηt)s_j\approx1/(\eta t); ridge's near sj≈λs_j\approx\lambda. So stopping at step tt behaves like ridge with

  4. Training longer means a weaker penalty. Weak directions, where the data say little and noise dominates, are fitted last, and early stopping leaves them near their starting value. Note the anchor: the iterate is pulled toward the initialization, which is zero only here.

Check your understanding

For least squares with step size η\eta, you double the number of steps before stopping. In the ridge analogy, what happens to the effective penalty?

  1. It doubles: longer training regularizes more
  2. It is unchanged: the penalty depends only on η\eta
  3. It roughly halves, since λ≈1/(ηt)\lambda\approx1/(\eta t)
  4. It drops to zero as soon as the training loss stops changing
Show the answer

C. It roughly halves, since λ≈1/(ηt)\lambda\approx1/(\eta t)

The crossover eigenvalue is about 1/(ηt)1/(\eta t); doubling tt halves it, so more directions get fitted, as ridge would with half the λ\lambda. Run to convergence and you approach the unregularized solution.

The rest of the toolbox

MethodWhat it doesNotes
Label smoothingTrains toward the target (1−ε) y+ε/K(1-\varepsilon)\,\mathbf y+\varepsilon/K instead of the one-hot y\mathbf y over KK classes, so infinite logits are never rewarded (Szegedy et al., 2016)Common in image classification and translation; see Reshaping Cross-Entropy
Stochastic depthSkips each residual block with some probability during training and keeps every block at test time (Huang et al., 2016): dropout for whole layersUsed in very deep residual networks and vision transformers; see Residual Connections
Max-norm constraintAfter each step, projects every unit's incoming weight vector back onto the ball ∥w∥2≤c\norm{\mathbf w}_2\le cSrivastava et al. found it pairs well with dropout and large learning rates, with cc around 3 to 4
Input or weight noiseAdds Gaussian noise during training; for least squares, input noise of variance s2s^2 per coordinate equals ridge with λ=s2\lambda=s^2 in expectation (Bishop, 1995)Dropout is the multiplicative, Bernoulli cousin
Data augmentationTrains on label-preserving transformations of the inputsOften the strongest regularizer of all; see Data Augmentation

Which tools a recipe uses depends on the regime:

  • Small dataset, trained from scratch: everything is on the table, and each strength is tuned on validation data.
  • Fine-tuning a pretrained model: a small learning rate, light dropout (0.1 is common), weight decay, and early stopping on a validation set.
  • Large image models from scratch: weight decay, strong augmentation, label smoothing and stochastic depth.
  • Language model pretraining: AdamW with λ\lambda around 0.1, usually no dropout and no early stopping; with one pass over the data the validation loss keeps falling, and the main regularizer is the data itself.

Key takeaways

  • For SGD, an L2L_2 penalty λ2∥θ∥2\frac\lambda2\norm{\boldsymbol\theta}^2 is exactly weight decay: every step multiplies the weights by 1−ηλ1-\eta\lambda. It is MAP estimation under a Gaussian prior with λ=1/(nσp2)\lambda=1/(n\sigma_p^2).
  • Inside Adam the penalty's gradient is rescaled per coordinate, so weights with large gradients barely decay; AdamW decouples the shrink and is the standard for transformers.
  • Inverted dropout keeps each unit with probability pp and scales survivors by 1/p1/p, so the expected activation is unchanged and the test-time network is used as is; it trains 2n2^n weight-sharing subnetworks at once.
  • Early stopping keeps the checkpoint with the best validation loss. For least squares, tt steps of gradient descent filter the solution like ridge with λ≈1/(ηt)\lambda\approx1/(\eta t), shrinking toward the initialization.
  • Label smoothing, stochastic depth, max-norm constraints and noise injection complete the toolbox; language-model pretraining relies mostly on AdamW's decay and on sheer data, while small-data training uses everything.

Check yourself

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

Question 1

SGD with learning rate η\eta on L(θ)+λ2∥θ∥2\loss(\boldsymbol\theta)+\frac\lambda2\norm{\boldsymbol\theta}^2 is the same as which update?

  1. θ←(1−ηλ)θ−ηg\boldsymbol\theta\leftarrow(1-\eta\lambda)\boldsymbol\theta-\eta\mathbf g
  2. θ←(1−λ)θ−ηg\boldsymbol\theta\leftarrow(1-\lambda)\boldsymbol\theta-\eta\mathbf g
  3. θ←θ−ηg−λ sign(θ)\boldsymbol\theta\leftarrow\boldsymbol\theta-\eta\mathbf g-\lambda\,\mathrm{sign}(\boldsymbol\theta)
  4. θ←(1+ηλ)θ−ηg\boldsymbol\theta\leftarrow(1+\eta\lambda)\boldsymbol\theta-\eta\mathbf g
Show the answer

A. θ←(1−ηλ)θ−ηg\boldsymbol\theta\leftarrow(1-\eta\lambda)\boldsymbol\theta-\eta\mathbf g

The penalty's gradient is λθ\lambda\boldsymbol\theta, and the step multiplies it by η\eta: θ−η(g+λθ)=(1−ηλ)θ−ηg\boldsymbol\theta-\eta(\mathbf g+\lambda\boldsymbol\theta)=(1-\eta\lambda)\boldsymbol\theta-\eta\mathbf g.

Question 2

Why did decoupled weight decay (AdamW) replace an L2L_2 penalty in Adam?

  1. Adam cannot compute the gradient of a penalty term
  2. Adam divides the penalty's gradient by each coordinate's gradient scale, so weights with large gradients are barely decayed; AdamW shrinks every weight by the same factor
  3. AdamW uses second-order information that Adam lacks
  4. An L2L_2 penalty makes Adam diverge
Show the answer

B. Adam divides the penalty's gradient by each coordinate's gradient scale, so weights with large gradients are barely decayed; AdamW shrinks every weight by the same factor

With the penalty inside the gradient, coordinate jj decays by ηλ/vj\eta\lambda/\sqrt{v_j} per step. Decoupling restores the uniform shrink 1−ηλ1-\eta\lambda that a Gaussian prior intends, and in Loshchilov and Hutter's experiments it generalized better.

Question 3

A network was trained with inverted dropout. What should happen at test time?

  1. Keep sampling dropout masks and use a single random pass
  2. Multiply every activation by the keep probability pp
  3. Divide every activation by pp once more
  4. Switch dropout off and use the network as is
Show the answer

D. Switch dropout off and use the network as is

Inverted dropout's 1/p1/p scaling during training already matches the expected activations to the full network, so at test time nothing is dropped and nothing is rescaled.

Question 4

Why do many large language models skip dropout during pretraining but use it for fine-tuning?

  1. Dropout cannot be applied to attention layers
  2. Language models cannot overfit, whatever the data
  3. Pretraining makes roughly one pass over an enormous corpus, so there is little overfitting to prevent and the noise mostly slows optimization; small fine-tuning sets bring overfitting back
  4. Dropout interferes with the tokenizer
Show the answer

C. Pretraining makes roughly one pass over an enormous corpus, so there is little overfitting to prevent and the noise mostly slows optimization; small fine-tuning sets bring overfitting back

Regularizers trade a little optimization for less overfitting. When each token is seen about once, the training and validation losses stay close, so the trade is not worth it; with a few thousand fine-tuning examples it is again.

Question 5

Gradient descent on least squares, started at zero, is stopped after tt steps. Which components of the least-squares solution has it fitted?

  1. Mostly those along directions of large data variance; weak directions stay near their starting value
  2. All components equally, each to a fraction t/(t+1)t/(t+1)
  3. Mostly those along directions of small data variance, which have the largest coefficients
  4. Only the component along the single top eigenvector
Show the answer

A. Mostly those along directions of large data variance; weak directions stay near their starting value

Component jj is multiplied by 1−(1−ηsj)t1-(1-\eta s_j)^t, which is near 11 when ηtsj≫1\eta ts_j\gg1 and near ηtsj\eta ts_j when ηtsj≪1\eta ts_j\ll1. Strong directions are fitted quickly, weak ones barely: ridge-like shrinkage with λ≈1/(ηt)\lambda\approx1/(\eta t).

Go deeper

Further reading

  • N. Srivastava, G. Hinton, A. Krizhevsky, I. Sutskever & R. Salakhutdinov, "Dropout: a simple way to prevent neural networks from overfitting," Journal of Machine Learning Research 15, 1929–1958 (2014).
  • I. Loshchilov & F. Hutter, "Decoupled weight decay regularization," ICLR (2019).
  • I. Goodfellow, Y. Bengio & A. Courville, Deep Learning, §7.1, §7.8 and §7.12 (MIT Press, 2016).
  • L. Prechelt, "Early stopping — but when?," in G. B. Orr & K.-R. Müller (eds.), Neural Networks: Tricks of the Trade, LNCS 1524 (Springer, 1998).