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 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 penalty and weight decay coincide for SGD, compute the per-step shrink factor , 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 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 .
- 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 : regularization, with strength . Follow one SGD step with learning rate and mini-batch gradient :
The penalized objective and its gradient:
An SGD step on it, regrouped:
So each step first multiplies every weight by , then takes the ordinary gradient step: the weights decay. Without gradients, steps would leave
a decay with time constant 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 penalty.
A classic CIFAR-10 ResNet recipe uses SGD with and , 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 %
: a 1.9% shrink per epoch. Small, but relentless: over 100 epochs the decay alone would multiply a weight by , 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 , the root mean square of its recent gradients. If the penalty's gradient is added to the loss gradient, it is divided too, and the equivalence above breaks (Loshchilov & Hutter, 2019). To see it, drop momentum, and bias correction:
Adam with an penalty: the penalty's gradient enters the normalized step, so each coordinate decays at its own rate.
Coordinates with large gradients (large ) are hardly decayed at all, and rarely updated coordinates with tiny gradients are decayed hardest: the opposite of an isotropic Gaussian prior.
Decoupled weight decay (AdamW) applies the shrink outside the normalization, so every coordinate decays by the same factor, as in SGD:
Loshchilov and Hutter proved that no choice of 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 less dependent on . AdamW became the default optimizer for transformers.
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 scheduleExcluding biases and normalization gains from decay is common practice rather than theory: shrinking a gain toward zero changes what the layer computes. A 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 .
You train with Adam and add to the loss. Which weights end up regularized least?
- All weights equally, as with SGD
- Weights whose gradients are consistently large
- Weights whose gradients are usually tiny
- Only the biases
Show the answer
B. Weights whose gradients are consistently large
Adam divides the whole gradient, penalty included, by . Where gradients are large the penalty's push is small, so those weights barely decay. AdamW avoids this by shrinking every weight by 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 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 during training:
With keep probability , by what factor does inverted dropout multiply the units it keeps during training?
Show the answer
1.25
. A unit survives 80% of the time, so its expected output is , exactly what the next layer sees at test time when nothing is dropped.
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 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 droppable units defines 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 and inputs with . 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.
A colleague trains with inverted dropout (keep probability ) but, following the original paper, also multiplies the activations by at test time. What happens?
- Nothing: the two scalings are equivalent, so applying both is harmless
- The network becomes an exact ensemble of its subnetworks
- Dropout is effectively turned off during training
- 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 . Scaling by 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:
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 checkpointPatience 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 with invertible, least-squares solution , and gradient descent started at :
The gradient is , so each step contracts the error by a fixed matrix:
Along each eigenvector the least-squares coefficient is multiplied by a filter factor. Ridge, , does the same with a different factor:
Both factors are near for strong directions (large ) and near for weak ones. Gradient descent's factor, about , switches over near ; ridge's near . So stopping at step behaves like ridge with
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.
For least squares with step size , you double the number of steps before stopping. In the ridge analogy, what happens to the effective penalty?
- It doubles: longer training regularizes more
- It is unchanged: the penalty depends only on
- It roughly halves, since
- It drops to zero as soon as the training loss stops changing
Show the answer
C. It roughly halves, since
The crossover eigenvalue is about ; doubling halves it, so more directions get fitted, as ridge would with half the . Run to convergence and you approach the unregularized solution.
The rest of the toolbox
| Method | What it does | Notes |
|---|---|---|
| Label smoothing | Trains toward the target instead of the one-hot over classes, so infinite logits are never rewarded (Szegedy et al., 2016) | Common in image classification and translation; see Reshaping Cross-Entropy |
| Stochastic depth | Skips each residual block with some probability during training and keeps every block at test time (Huang et al., 2016): dropout for whole layers | Used in very deep residual networks and vision transformers; see Residual Connections |
| Max-norm constraint | After each step, projects every unit's incoming weight vector back onto the ball | Srivastava et al. found it pairs well with dropout and large learning rates, with around 3 to 4 |
| Input or weight noise | Adds Gaussian noise during training; for least squares, input noise of variance per coordinate equals ridge with in expectation (Bishop, 1995) | Dropout is the multiplicative, Bernoulli cousin |
| Data augmentation | Trains on label-preserving transformations of the inputs | Often 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 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 penalty is exactly weight decay: every step multiplies the weights by . It is MAP estimation under a Gaussian prior with .
- 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 and scales survivors by , so the expected activation is unchanged and the test-time network is used as is; it trains weight-sharing subnetworks at once.
- Early stopping keeps the checkpoint with the best validation loss. For least squares, steps of gradient descent filter the solution like ridge with , 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.
SGD with learning rate on is the same as which update?
Show the answer
A.
The penalty's gradient is , and the step multiplies it by : .
Why did decoupled weight decay (AdamW) replace an penalty in Adam?
- Adam cannot compute the gradient of a penalty term
- 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
- AdamW uses second-order information that Adam lacks
- An 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 decays by per step. Decoupling restores the uniform shrink that a Gaussian prior intends, and in Loshchilov and Hutter's experiments it generalized better.
A network was trained with inverted dropout. What should happen at test time?
- Keep sampling dropout masks and use a single random pass
- Multiply every activation by the keep probability
- Divide every activation by once more
- 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 scaling during training already matches the expected activations to the full network, so at test time nothing is dropped and nothing is rescaled.
Why do many large language models skip dropout during pretraining but use it for fine-tuning?
- Dropout cannot be applied to attention layers
- Language models cannot overfit, whatever the data
- 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
- 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.
Gradient descent on least squares, started at zero, is stopped after steps. Which components of the least-squares solution has it fitted?
- Mostly those along directions of large data variance; weak directions stay near their starting value
- All components equally, each to a fraction
- Mostly those along directions of small data variance, which have the largest coefficients
- 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 is multiplied by , which is near when and near when . Strong directions are fitted quickly, weak ones barely: ridge-like shrinkage with .
Go deeper
- Dropout in Depth · Subnetwork ensembles, adaptive L2 penalties and the noise-injection family.
- What Weight Decay Really Does · Scale invariance, effective learning rates and rotational equilibrium: why decay matters when it barely regularizes.
- Early Stopping & Regularization by Time · Training time as a regularizer: spectral filtering, ridge equivalence and label noise.
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).