Regularization in Deep Nets
- Dropout by Hinton et al. (2012) was the first widely-used regularization technique specific to neural networks
- Batch normalization (Ioffe & Szegedy, 2015) solved internal covariate shift and enabled very deep networks
- Modern regularization (weight decay, stochastic depth, mixup) builds on these foundations
Regularization prevents overfitting by constraining model capacity or adding noise during training. Dropout randomly zeros neurons, forcing redundant representations. Batch norm normalizes layer inputs, improving gradient flow. Weight decay penalizes large weights (L2 regularization). Together they make deep networks trainable and generalizable.
- Connects directly to the bias-variance trade-off at the deep learning scale
- Layer norm (used in Transformers instead of batch norm) is a direct variant
- Stochastic depth (randomly dropping entire layers) and DropPath connect to neural architecture search
- Compare L1, L2, and decoupled weight decay; explain why AdamW is preferred over Adam + L2.
- Define dropout and explain its train vs eval mode and the implicit ensemble interpretation.
- Define batch norm, layer norm, and group norm; pick the right one for CV vs NLP vs small-batch settings.
- Explain the Santurkar 2018 revisionist view of batch norm: it smooths the loss landscape rather than reducing internal covariate shift.
- Apply early stopping, label smoothing, MixUp/CutMix/RandAugment, stochastic depth, and weight tying as part of a modern training recipe.
TL;DR
Regularization in deep nets is a stack of techniques that shrink, perturb, or normalize parameters and activations to improve generalization. Weight decay (decoupled in AdamW [11]) shrinks parameters; dropout [1] stochastically zeros activations and trains an implicit ensemble of sub-networks; batch norm [2] standardizes pre-activations per minibatch and (per Santurkar 2018 [5]) smooths the loss landscape rather than fixing internal covariate shift; layer norm [3] normalizes across features per sample (the standard choice in transformers); group norm [4] is the fix for small-batch CV. Early stopping, label smoothing [6], MixUp/CutMix/RandAugment [7][8][9], stochastic depth [10], and weight tying [12] round out the modern recipe.
Intuition
A modern deep network has tens of millions to billions of parameters and is trained on a fraction of the data needed to constrain them all. Without help, gradient descent will find a configuration that fits the training set perfectly and generalizes badly. Regularization is the umbrella term for everything that biases optimization toward simpler, smoother, or more invariant functions.
The techniques in this section split into three broad families:
- Parameter penalties. Add a term to the loss that shrinks parameters (L1, L2, weight decay).
- Stochastic noise injection. Randomly perturb activations, layers, or labels at training time so the model cannot memorize specific patterns (dropout, stochastic depth, label smoothing, MixUp/CutMix, RandAugment).
- Normalization. Standardize internal activations to keep their distribution stable across the network and across training, removing brittle dependencies on initialization and learning-rate (batch norm, layer norm, group norm).
Almost every production training recipe combines one technique from each family.
L2 weight decay is exactly maximum a posteriori (MAP) estimation under a Gaussian prior on weights:
L1 corresponds to a Laplace prior. Dropout, MixUp, label smoothing, and most data augmentations correspond to implicit priors that are harder to write down but encode the same idea: prefer functions that are smooth (small weights), invariant to certain noises (dropout, MixUp), or non-overconfident (label smoothing) [13].
Weight decay
The plain L2 regularizer adds to the loss. The gradient becomes , and a plain SGD step is
This is decay in the literal sense: a uniform multiplicative shrinkage of . Under SGD this is identical to L2 regularization.
Why Adam + L2 is not weight decay
Under Adam, the gradient (including the L2 term) is divided by :
The decay term picks up a per-parameter scaling: parameters with large get effectively smaller decay than parameters with small . This breaks the “uniform shrinkage” interpretation. The fix from Loshchilov & Hutter [11] is to apply the decay outside the adaptive scaling:
Same uniform shrinkage as plain SGD + L2. This optimizer is AdamW, and on transformer / ViT / LLM workloads it consistently outperforms Adam + L2 by 0.5-2% absolute accuracy or perplexity.
L1 weight decay (sum of absolute values) is sometimes used to encourage sparsity but is rarely applied in deep learning beyond the input layer; the soft-thresholding interpretation makes more sense in compressed-sensing settings than in modern training.
Dropout
Dropout [1] independently sets each activation to zero with probability at training time. To keep the expected activation magnitude unchanged, the kept activations are scaled by at training time (this is “inverted dropout”; original dropout scaled by at inference, but every modern framework uses inverted dropout):
At inference time, dropout is off: .
The implicit ensemble
A network with dropout-able units defines possible sub-networks (each of the units kept or dropped). Each minibatch trains one of these sub-networks, sampled uniformly. At inference, using the full network with all activations multiplied by approximates the geometric mean of the predictions of all sub-networks. So dropout is implicitly training an ensemble of models and averaging them at inference, all at the cost of training a single model.
Where to put it
Typical placements:
- MLPs and FFN blocks of transformers: between hidden layers, .
- Just before the final logits: a smaller to prevent overconfidence on the output.
- Within attention: attention dropout (drop attention weights) and residual dropout (drop the output of each sub-layer) are standard in transformer training.
Do not stack dropout with strong batch norm in the same path: BN’s stats interact badly with dropout’s noise; the canonical fix is “dropout after BN” or “no dropout, use BN only.”
Batch normalization
Batch norm [2] standardizes each pre-activation along the batch dimension. For a tensor of pre-activations (batch size , channels ), compute per-channel statistics across the batch:
and normalize, then apply learned scale and shift :
At training time, are computed per minibatch. The layer also maintains exponentially-moving-average running estimates for inference time, when the input may be a single example.
The original Ioffe & Szegedy paper [2] motivated batch norm as a fix for internal covariate shift: the changing distribution of layer inputs as the layers above are updated. This story is intuitive and stuck.
Santurkar et al. 2018 [5] tested it directly: they trained a baseline net with batch norm, then trained a net with batch norm followed by deliberate noise injection that increased the input distribution shift downstream of every layer. The noisy net had at least as much “internal covariate shift” as a vanilla unnormalized net, yet trained essentially as well as the normal batch-norm net. The conclusion: internal covariate shift is not the mechanism.
What batch norm actually does, per Santurkar et al., is smooth the loss landscape: it reparameterizes the objective so that the Lipschitz constant of the gradient is smaller. Smoother gradients allow larger learning rates, which is the empirical effect everyone observes (and the original paper noted but mis-explained).
This is one of the cleanest examples in deep learning of a wrong but useful intuition surviving for years before being properly tested.
Layer norm and group norm
Batch norm fails in two settings: (a) batch size is very small (e.g. semantic segmentation where each batch is a few images), so the per-channel statistics are noisy; (b) sequence-to-sequence models where the batch dimension is shuffled with the time dimension and “per channel across batch” is no longer meaningful.
Layer norm [3]: normalize across the feature dimension per sample. For activations ,
then . Training and eval modes are identical (no running stats needed). Layer norm is the default in transformers (BERT, GPT, ViT), where the batch dimension is heterogeneous and the feature dimension is the natural axis to normalize.
Group norm [4]: split the channel dimension into groups and normalize per (sample, group). For channels and group size , this interpolates between layer norm (, normalize over all channels) and instance norm (, normalize each channel independently). Group norm is the standard fix for CV with very small batch size (semantic segmentation, video, medical imaging) where batch norm’s per-batch statistics are too noisy.
| Normalization | Axes normalized | Per-sample stats? | Train != eval? | Batch size sensitivity | Standard use |
|---|---|---|---|---|---|
| Batch norm | across batch (per channel) | no (uses minibatch) | yes (running stats) | high (fails at B = 1, 2) | Default for CNNs with B at least 16-32. |
| Layer norm | across features (per sample) | yes | no | none | Default in transformers, RNNs. |
| Group norm | across (group of channels x H x W) per sample | yes | no | low | CV with small batch (segmentation, video, medical). |
| Instance norm | across H x W per (sample, channel) | yes | no | none | Style transfer, image generation. |
Other regularization tools
Early stopping
Track validation loss every epoch (or every steps). Save the best-validation-loss checkpoint. When validation loss stops improving for epochs (the “patience”), restore the best checkpoint and stop training. Equivalent to a soft cap on effective model complexity: by stopping before the train loss reaches its minimum, you stop in the underfit-overfit transition rather than the overfit regime.
Label smoothing
Replace one-hot labels with a soft target:
where is the number of classes and is typical. Introduced in Inception-v3 [6].
Label smoothing as a confidence regularizer
The cross-entropy loss with smoothed targets is
The first term is the usual cross-entropy on the true class; the second term is, up to a constant, times the KL divergence from the model distribution to the uniform distribution. So minimizing is the same as minimizing standard cross-entropy plus a KL pull toward uniform:
The KL pull penalizes the model for being confidently wrong by preventing from saturating at exactly 1, which improves calibration and mildly improves accuracy. Standard in image classification (ResNet ImageNet recipes), machine translation, and most LLM training pipelines.
Data augmentation
Replace each training example with a random transformation that preserves the label.
- Standard CV augmentation. Random crop, horizontal flip, color jitter, slight rotation. The classic recipe behind ImageNet training.
- MixUp [7]. Sample two examples and and a . Train on . Encourages the network to behave linearly in between training examples; reduces overconfidence.
- CutMix [8]. Cut a random rectangle out of one image and paste in the corresponding region from another, mixing the labels by the area ratio. Combines the regularization of MixUp with the spatial inductive bias that small image patches still mean something.
- RandAugment [9]. Sample augmentations from a fixed library (rotate, shear, color, etc.) and apply each at magnitude , both treated as hyperparameters. Replaces the AutoAugment search with two scalars; nearly as good and 1000× cheaper.
Stochastic depth
Stochastic depth [10]: at each training step, randomly skip the residual computation of a fraction of the residual blocks (replace with at probability ). At inference time use the full network. Like dropout but applied to entire layers; particularly useful for very deep ResNets and ViTs (e.g. ViT-Huge with stochastic depth ).
Weight tying
Tie the input embedding matrix and the output softmax projection in language models [12]. Cuts parameter count by ~30M for a typical language model and improves perplexity. Standard in GPT-style models. The intuition: the input embedding maps tokens to vectors, and the output projection maps vectors back to token logits; both should encode the same word-vector geometry, so why learn them twice.
Implementations
A small CNN in PyTorch with each of the major techniques wired in. Toggle them on or off to recreate any modern training recipe.
import torch.nn as nn
# Small CNN for CIFAR-10 with: BN, dropout, GELU, weight init.
# AdamW + label smoothing + MixUp are wired in the training loop.
class Block(nn.Module):
def __init__(self, c_in, c_out, drop=0.1):
super().__init__()
self.conv = nn.Conv2d(c_in, c_out, kernel_size=3, padding=1, bias=False)
self.bn = nn.BatchNorm2d(c_out) # batch norm after conv
self.act = nn.GELU()
self.drop = nn.Dropout2d(drop) # spatial dropout
def forward(self, x):
return self.drop(self.act(self.bn(self.conv(x))))
class TinyCNN(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.features = nn.Sequential(
Block(3, 64), Block(64, 64), nn.MaxPool2d(2),
Block(64, 128), Block(128, 128), nn.MaxPool2d(2),
nn.AdaptiveAvgPool2d(1), nn.Flatten(),
)
self.classifier = nn.Sequential(
nn.Linear(128, 256), nn.GELU(), nn.Dropout(0.3),
nn.Linear(256, num_classes),
)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, nonlinearity='relu')
elif isinstance(m, nn.Linear):
nn.init.kaiming_normal_(m.weight, nonlinearity='relu')
nn.init.zeros_(m.bias)
def forward(self, x):
return self.classifier(self.features(x))Run a from-scratch numpy demo of dropout’s regularization effect: a small overfit-prone MLP trained twice (with and without dropout) on a tiny dataset:
(no output yet)
Interactive demo
Drag the polynomial-degree slider to watch a model fit (or overfit) noisy data. Higher-degree polynomials nail the training points but oscillate wildly between them, exactly the failure mode regularization is designed to tame. Mentally translate “polynomial degree” to “number of parameters in a deep net”: dropout, weight decay, and early stopping all push the effective capacity down without changing the architecture.
Dashed gray = sin(2πx); blue = polynomial fit; green dots = noisy training points.
Real-world uses
| Recipe | Domain | Components | Citation |
|---|---|---|---|
| ResNet ImageNet | CV classification | BN + L2 weight decay 1e-4 + label smoothing 0.1 + standard augmentation | Original ResNet + Inception-v3 label smoothing |
| ViT / DeiT | CV classification | LN + AdamW (decay 0.05) + RandAugment + MixUp + CutMix + stochastic depth | DeiT (Touvron et al. 2021) |
| BERT / GPT pretraining | NLP | LN + AdamW (decay 0.01-0.1) + dropout 0.1 + warmup-cosine LR + weight tying | BERT, GPT-2 papers |
| Modern LLM finetuning | NLP | LN (already in base) + AdamW + label smoothing + dropout + early stopping | Most LLM finetuning recipes |
| Small-batch segmentation (medical, video) | CV | Group norm + stochastic depth + heavy augmentation | Group Norm paper, U-Net variants |
| Style transfer / GANs | CV generative | Instance norm or layer norm; no dropout in the generator | Pix2Pix, StyleGAN |
Pitfalls
When the batch size drops below ~16, the per-channel statistics become noisy and the network’s internal distributions wobble each step. Symptoms: training loss is fine but validation loss is much worse than expected; sometimes training oscillates. Fix: switch to group norm (set to 32 by default) or layer norm. Wu & He documented multi-percent gains on COCO at batch 2 just from this swap [4].
Forgetting to call model.eval() (PyTorch) or pass training=False (Keras) before inference leaves dropout on, which scrambles predictions. The symptom: predictions jitter between successive runs on the same input. Always wrap inference in with torch.no_grad(): model.eval(); ... or use the predict() API.
Both work; mixing them in the same network is the bug. The most common modern pattern is Conv -> BN -> Activation -> (optional Dropout). If you put dropout before BN, the BN statistics become biased toward the (1-p) of activations that survived dropout, which is fine within one minibatch but inconsistent with the running stats used at eval. Pick a convention and stick to it.
Repeating from the previous page because it shows up here too: if you write optim.Adam(..., weight_decay=lam) in older PyTorch versions, that is L2 added to the gradient, which is not equivalent to decoupled weight decay. Use optim.AdamW(..., weight_decay=lam) for the decoupled version. A several-percent gap on transformer benchmarks [11].
Label smoothing pulls predictions toward uniform, which improves calibration if the model was previously overconfident. If the model is already underconfident (small dataset, heavy augmentation), label smoothing makes it worse. Always check expected calibration error (ECE) on a validation set before and after.
Pop quiz
- 1. How does dropout act like an ensemble?
- 2. Per Santurkar et al. 2018, what does batch norm actually do?
- 3. When should you choose group norm over batch norm?
- 4. What is the regularization interpretation of label smoothing?
- 5. Which combination is the modern transformer regularization recipe?
Interview Q&A
Why does dropout act like an ensemble of sub-networks, and how does inference-time scaling preserve the expectation?onsite
Setup. A dropout layer with rate and activations defines a mask where each independently. The training-time forward pass uses
There are possible masks; each minibatch trains a different sub-network sampled uniformly.
Inference. With all activations active and no dropout scaling on the input,
so the eval-time activation matches the expectation of the train-time activation. (This is why we use inverted dropout rather than scaling at eval; modern frameworks all use inverted dropout.)
Ensemble interpretation. With activations scaled to match, evaluating the full network approximates the geometric mean of the predictions of all sub-networks. This is exact for linear models and an approximation for non-linear ones, but the empirical accuracy gains track ensemble averaging predictions [1].
Practical guidance. Use dropout 0.1-0.3 in transformer FFN blocks, 0.5 only in shallow MLPs, and rarely after batch norm (the noise interactions degrade BN’s running stats).
Why does batch norm allow higher learning rates? Cite both the original explanation and the Santurkar 2018 view.research
Original (Ioffe-Szegedy 2015) [2]. The “internal covariate shift” story: as upstream layers update, the distribution of inputs to downstream layers changes, forcing them to constantly readapt. Batch norm pins the per-channel mean and variance, so the input distribution to each layer stays approximately fixed. With a stable input distribution, downstream layers can train with larger steps. This explanation was widely accepted for several years.
Revisionist (Santurkar et al. 2018) [5]. Direct test: train a network with batch norm followed by deliberate distribution-shift injection (random noise added to the BN outputs at every step). The downstream-layer input distribution shift is by construction worse than a vanilla unnormalized network. Yet the network trains essentially as well as the standard batch-norm one. Conclusion: covariate shift is not the mechanism.
What is? Santurkar et al. showed empirically and theoretically that batch norm makes the loss surface measurably smoother:
with much smaller than the same constant without BN. Smoother gradients let you take larger steps without diverging, which is the empirical observation.
Implication. BN is mainly an optimization aid, not a regularizer. When you remove BN and add layer norm (transformers) you keep the smoothing without the per-batch coupling that makes BN finicky.
What changes between train and eval modes in a typical CNN?phone
Three components flip:
- Dropout. On at train (zeros activations with probability , scales the rest), off at eval (passthrough).
- Batch norm. At train, computes per-minibatch statistics and updates an EMA of those statistics. At eval, uses the running EMA for normalization (so a single example can be evaluated).
- Stochastic depth (if used). Drops residual blocks with probability at train; uses all blocks (no dropping) at eval.
Layer norm and group norm use per-sample statistics in both modes, so they are unchanged by the train/eval switch. Forgetting to call model.eval() is a common bug whose symptom is non-deterministic predictions [1][2].
Show that label smoothing is equivalent to a KL pull toward uniform.onsite
Let be the true label and be the model’s predicted distribution. The smoothed target is where is the one-hot at index .
Cross-entropy:
The second term equals . Now compute the KL from to the uniform distribution :
So . Putting it together:
The constant is irrelevant for optimization. The first term is rescaled CE; the second is a KL pull toward uniform that penalizes overconfident predictions. That is the “confidence regularizer” interpretation [6].
A short project that takes about an evening:
- Train a small ResNet on CIFAR-10 with the bare minimum: SGD + momentum, no BN, no dropout, no augmentation. Record train/test accuracy.
- Add batch norm. Re-train. Note the speedup and the higher LR you can tolerate.
- Add basic augmentation (random crop + horizontal flip). Note the test accuracy jump.
- Swap SGD for AdamW with weight decay 0.05. Re-tune the LR.
- Add MixUp and label smoothing 0.1. Compare ECE before and after with
sklearn.calibration.calibration_curve. - Stretch: replace BN with group norm and reduce batch size to 4 to see when each shines.
References
- Srivastava, N., Hinton, G., Krizhevsky, A., Sutskever, I., and Salakhutdinov, R. (2014). Dropout: A Simple Way to Prevent Neural Networks from Overfitting. Journal of Machine Learning Research 15, 1929-1958. https://jmlr.org/papers/v15/srivastava14a.html
- Ioffe, S. and Szegedy, C. (2015). Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift. ICML 2015. arXiv:1502.03167
- Ba, J. L., Kiros, J. R., and Hinton, G. E. (2016). Layer Normalization. arXiv preprint. arXiv:1607.06450
- Wu, Y. and He, K. (2018). Group Normalization. ECCV 2018. arXiv:1803.08494
- Santurkar, S., Tsipras, D., Ilyas, A., and Madry, A. (2018). How Does Batch Normalization Help Optimization?. NeurIPS 2018. arXiv:1805.11604
- Szegedy, C., Vanhoucke, V., Ioffe, S., Shlens, J., and Wojna, Z. (2016). Rethinking the Inception Architecture for Computer Vision. CVPR 2016. arXiv:1512.00567
- Zhang, H., Cisse, M., Dauphin, Y. N., and Lopez-Paz, D. (2017). mixup: Beyond Empirical Risk Minimization. ICLR 2018 (arXiv preprint 2017). arXiv:1710.09412
- Yun, S., Han, D., Oh, S. J., Chun, S., Choe, J., and Yoo, Y. (2019). CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features. ICCV 2019. arXiv:1905.04899
- Cubuk, E. D., Zoph, B., Shlens, J., and Le, Q. V. (2020). RandAugment: Practical Automated Data Augmentation with a Reduced Search Space. CVPR Workshops 2020. arXiv:1909.13719
- Huang, G., Sun, Y., Liu, Z., Sedra, D., and Weinberger, K. Q. (2016). Deep Networks with Stochastic Depth. ECCV 2016. arXiv:1603.09382
- Loshchilov, I. and Hutter, F. (2017). Decoupled Weight Decay Regularization. ICLR 2019 (arXiv preprint 2017). arXiv:1711.05101
- Press, O. and Wolf, L. (2017). Using the Output Embedding to Improve Language Models. EACL 2017. arXiv:1608.05859
- Goodfellow, I., Bengio, Y., and Courville, A. (2016). Deep Learning. MIT Press. https://www.deeplearningbook.org