Deep LearningRegularization in Deep Nets

Regularization in Deep Nets

Background
  • 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
The Concept

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.

How it Links
  • 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
Concrete Example
Training a ResNet without batch norm: gradients vanish or explode, training diverges. Add batch norm: training stabilizes. Add dropout: the model stops memorizing specific training examples. The regularized model achieves higher test accuracy despite identical architecture.
Learning outcomes
  • 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

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.

Bayesian view of regularization

L2 weight decay is exactly maximum a posteriori (MAP) estimation under a Gaussian prior on weights:

−log⁡p(θ∣D)∝−log⁡p(D∣θ)+λ2 ∥θ∥22.-\log p(\theta \mid D) \propto -\log p(D \mid \theta) + \frac{\lambda}{2}\, \lVert \theta \rVert_2^2.

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 λ2∥θ∥22\tfrac{\lambda}{2}\lVert \theta \rVert_2^2 to the loss. The gradient becomes ∇L+λθ\nabla \mathcal{L} + \lambda \theta, and a plain SGD step is

θt+1=θt−η (∇L+λθt)=(1−ηλ) θt−η∇L.\theta_{t+1} = \theta_t - \eta\, (\nabla \mathcal{L} + \lambda \theta_t) = (1 - \eta \lambda)\, \theta_t - \eta \nabla \mathcal{L}.

This is decay in the literal sense: a uniform multiplicative shrinkage of θ\theta. 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 v^t\sqrt{\hat{v}_t}:

θt+1=θt−ηv^t+ϵ (m^t+λθt).\theta_{t+1} = \theta_t - \frac{\eta}{\sqrt{\hat{v}_t} + \epsilon}\, \bigl(\hat{m}_t + \lambda \theta_t\bigr).

The decay term picks up a per-parameter scaling: parameters with large v^t,i\hat{v}_{t,i} get effectively smaller decay than parameters with small v^t,i\hat{v}_{t,i}. This breaks the “uniform shrinkage” interpretation. The fix from Loshchilov & Hutter [11] is to apply the decay outside the adaptive scaling:

θt+1=θt−η m^tv^t+ϵ−η λ θt.\theta_{t+1} = \theta_t - \eta\, \frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon} - \eta\, \lambda\, \theta_t.

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 pp at training time. To keep the expected activation magnitude unchanged, the kept activations are scaled by 1/(1−p)1/(1-p) at training time (this is “inverted dropout”; original dropout scaled by 1−p1-p at inference, but every modern framework uses inverted dropout):

hitrain={hi/(1−p)with probability 1−p,0with probability p.h_i^{\text{train}} = \begin{cases} h_i / (1 - p) & \text{with probability } 1 - p, \\ 0 & \text{with probability } p. \end{cases}

At inference time, dropout is off: hieval=hih_i^{\text{eval}} = h_i.

The implicit ensemble

A network with nn dropout-able units defines 2n2^n possible sub-networks (each of the nn 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 1/(1−p)1/(1-p) approximates the geometric mean of the predictions of all 2n2^n sub-networks. So dropout is implicitly training an ensemble of 2n2^n 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, p∈[0.1,0.5]p \in [0.1, 0.5].
  • Just before the final logits: a smaller pp 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 z∈RB×Cz \in \mathbb{R}^{B \times C} (batch size BB, channels CC), compute per-channel statistics across the batch:

μc=1B∑i=1Bzi,c,σc2=1B∑i=1B(zi,c−μc)2,\mu_c = \frac{1}{B} \sum_{i=1}^{B} z_{i,c}, \qquad \sigma_c^2 = \frac{1}{B} \sum_{i=1}^{B} (z_{i,c} - \mu_c)^2,

and normalize, then apply learned scale γc\gamma_c and shift βc\beta_c:

z^i,c=zi,c−μcσc2+ϵ,yi,c=γc z^i,c+βc.\hat{z}_{i,c} = \frac{z_{i,c} - \mu_c}{\sqrt{\sigma_c^2 + \epsilon}}, \qquad y_{i,c} = \gamma_c\, \hat{z}_{i,c} + \beta_c.

At training time, μ,σ\mu, \sigma are computed per minibatch. The layer also maintains exponentially-moving-average running estimates μˉ,σˉ\bar{\mu}, \bar{\sigma} for inference time, when the input may be a single example.

The Santurkar 2018 revisionist view

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 h∈RB×dh \in \mathbb{R}^{B \times d},

μi=1d∑j=1dhi,j,σi2=1d∑j=1d(hi,j−μi)2,\mu_i = \frac{1}{d} \sum_{j=1}^{d} h_{i,j}, \qquad \sigma_i^2 = \frac{1}{d} \sum_{j=1}^{d} (h_{i,j} - \mu_i)^2,

then h^i,j=γj(hi,j−μi)/σi2+ϵ+βj\hat{h}_{i,j} = \gamma_j (h_{i,j} - \mu_i) / \sqrt{\sigma_i^2 + \epsilon} + \beta_j. 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 GG groups and normalize per (sample, group). For CC channels and group size C/GC/G, this interpolates between layer norm (G=1G = 1, normalize over all channels) and instance norm (G=CG = C, 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.

NormalizationAxes normalizedPer-sample stats?Train != eval?Batch size sensitivityStandard use
Batch normacross 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 normacross features (per sample)yesnononeDefault in transformers, RNNs.
Group normacross (group of channels x H x W) per sampleyesnolowCV with small batch (segmentation, video, medical).
Instance normacross H x W per (sample, channel)yesnononeStyle transfer, image generation.

Other regularization tools

Early stopping

Track validation loss every epoch (or every kk steps). Save the best-validation-loss checkpoint. When validation loss stops improving for PP 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:

ysmooth=(1−α) yonehot+αK 1,y^{\text{smooth}} = (1 - \alpha)\, y^{\text{onehot}} + \frac{\alpha}{K}\, \mathbf{1},

where KK is the number of classes and α∈[0.05,0.2]\alpha \in [0.05, 0.2] is typical. Introduced in Inception-v3 [6].

Label smoothing as a confidence regularizer

The cross-entropy loss with smoothed targets is

Lsmooth=−∑k=1Kyksmoothlog⁡pk=−(1−α)log⁡py−αK∑k=1Klog⁡pk.\mathcal{L}^{\text{smooth}} = -\sum_{k=1}^{K} y_k^{\text{smooth}} \log p_k = -(1 - \alpha) \log p_y - \frac{\alpha}{K} \sum_{k=1}^{K} \log p_k.

The first term is the usual cross-entropy on the true class; the second term is, up to a constant, α\alpha times the KL divergence from the model distribution to the uniform distribution. So minimizing Lsmooth\mathcal{L}^{\text{smooth}} is the same as minimizing standard cross-entropy plus a KL pull toward uniform:

Lsmooth  =  LCE+α KL ⁣(Uniform ∥ p)+const.\mathcal{L}^{\text{smooth}} \;=\; \mathcal{L}^{\text{CE}} + \alpha\, \mathrm{KL}\!\bigl( \mathrm{Uniform}\, \big\|\, p \bigr) + \text{const}.

The KL pull penalizes the model for being confidently wrong by preventing pyp_y 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 (x1,y1)(x_1, y_1) and (x2,y2)(x_2, y_2) and a λ∼Beta(α,α)\lambda \sim \text{Beta}(\alpha, \alpha). Train on (λx1+(1−λ)x2, λy1+(1−λ)y2)\bigl( \lambda x_1 + (1 - \lambda) x_2,\, \lambda y_1 + (1 - \lambda) y_2 \bigr). 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 NN augmentations from a fixed library (rotate, shear, color, etc.) and apply each at magnitude MM, 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 x+f(x)x + f(x) with xx at probability pℓp_\ell). 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 p=0.4p = 0.4).

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.

python
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))
Block-level: Conv -> BatchNorm -> GELU -> Dropout. Final classifier has dropout at 0.3 just before the logits.

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:

Idle (packages: numpy)
(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.

Polynomial fit — bias vs variance
x=0.00 y=0.55x=0.03 y=0.20x=0.07 y=0.23x=0.10 y=0.62x=0.14 y=0.73x=0.17 y=1.07x=0.21 y=0.82x=0.24 y=0.76x=0.28 y=0.68x=0.31 y=1.24x=0.34 y=1.07x=0.38 y=0.91x=0.41 y=0.42x=0.45 y=0.34x=0.48 y=0.50x=0.52 y=-0.27x=0.55 y=-0.15x=0.59 y=-0.34x=0.62 y=-0.57x=0.66 y=-1.06x=0.69 y=-0.67x=0.72 y=-0.94x=0.76 y=-1.25x=0.79 y=-0.73x=0.83 y=-0.95x=0.86 y=-0.95x=0.90 y=-0.34x=0.93 y=-0.46x=0.97 y=-0.46x=1.00 y=0.28
train MSE = 0.0578 test MSE = 0.0518

Dashed gray = sin(2πx); blue = polynomial fit; green dots = noisy training points.

Real-world uses

RecipeDomainComponentsCitation
ResNet ImageNetCV classificationBN + L2 weight decay 1e-4 + label smoothing 0.1 + standard augmentationOriginal ResNet + Inception-v3 label smoothing
ViT / DeiTCV classificationLN + AdamW (decay 0.05) + RandAugment + MixUp + CutMix + stochastic depthDeiT (Touvron et al. 2021)
BERT / GPT pretrainingNLPLN + AdamW (decay 0.01-0.1) + dropout 0.1 + warmup-cosine LR + weight tyingBERT, GPT-2 papers
Modern LLM finetuningNLPLN (already in base) + AdamW + label smoothing + dropout + early stoppingMost LLM finetuning recipes
Small-batch segmentation (medical, video)CVGroup norm + stochastic depth + heavy augmentationGroup Norm paper, U-Net variants
Style transfer / GANsCV generativeInstance norm or layer norm; no dropout in the generatorPix2Pix, StyleGAN

Pitfalls

Batch norm + small batch size breaks accuracy

When the batch size drops below ~16, the per-channel statistics μ,σ\mu, \sigma 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 GG to 32 by default) or layer norm. Wu & He documented multi-percent gains on COCO at batch 2 just from this swap [4].

Dropout at inference time is a bug

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.

Dropout before BN vs after BN, pick one

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.

Adam + L2 is not weight decay

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 reduces calibration on the wrong scale

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

Check yourself
Score: 0 / 5(0 answered)
  1. 1. How does dropout act like an ensemble?
  2. 2. Per Santurkar et al. 2018, what does batch norm actually do?
  3. 3. When should you choose group norm over batch norm?
  4. 4. What is the regularization interpretation of label smoothing?
  5. 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 pp and nn activations defines a mask M∈{0,1}nM \in \{0, 1\}^n where each Mi∼Bernoulli(1−p)M_i \sim \text{Bernoulli}(1 - p) independently. The training-time forward pass uses

hitrain=Mi hi1−p.h_i^{\text{train}} = \frac{M_i\, h_i}{1 - p}.

There are 2n2^n possible masks; each minibatch trains a different sub-network sampled uniformly.

Inference. With all activations active and no dropout scaling on the input,

hieval=hi=EM ⁣[Mi hi1−p],h_i^{\text{eval}} = h_i = \mathbb{E}_M\!\left[\frac{M_i\, h_i}{1 - p}\right],

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 2n2^n 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:

∥∇L(θ+Δ)−∇L(θ)∥  ≤  LBN ∥Δ∥\bigl\lVert \nabla \mathcal{L}(\theta + \Delta) - \nabla \mathcal{L}(\theta) \bigr\rVert \;\le\; L_{\text{BN}}\, \lVert \Delta \rVert

with LBNL_{\text{BN}} 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:

  1. Dropout. On at train (zeros activations with probability pp, scales the rest), off at eval (passthrough).
  2. Batch norm. At train, computes per-minibatch statistics and updates an EMA of those statistics. At eval, uses the running EMA μˉ,σˉ\bar{\mu}, \bar{\sigma} for normalization (so a single example can be evaluated).
  3. Stochastic depth (if used). Drops residual blocks with probability pℓp_\ell 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 y∈{1,…,K}y \in \{1, \dots, K\} be the true label and p∈ΔK−1p \in \Delta^{K-1} be the model’s predicted distribution. The smoothed target is ysmooth=(1−α) ey+(α/K) 1y^{\text{smooth}} = (1 - \alpha)\, e_y + (\alpha / K)\, \mathbf{1} where eye_y is the one-hot at index yy.

Cross-entropy:

Lsmooth=−∑kyksmoothlog⁡pk=−(1−α)log⁡py−αK∑klog⁡pk.\mathcal{L}^{\text{smooth}} = -\sum_k y_k^{\text{smooth}} \log p_k = -(1 - \alpha) \log p_y - \frac{\alpha}{K} \sum_k \log p_k.

The second term equals αK⋅K⋅Eu∼Uniform[−log⁡pu]=−α Eu[log⁡pu]\frac{\alpha}{K} \cdot K \cdot \mathbb{E}_{u \sim \text{Uniform}}[-\log p_u] = -\alpha\, \mathbb{E}_u[\log p_u]. Now compute the KL from pp to the uniform distribution u=1/Ku = \mathbf{1}/K:

KL(u ∥ p)=∑kuklog⁡ukpk=−1K∑klog⁡pk−log⁡K.\mathrm{KL}(u \,\|\, p) = \sum_k u_k \log \frac{u_k}{p_k} = -\frac{1}{K} \sum_k \log p_k - \log K.

So −αK∑klog⁡pk=α KL(u ∥ p)+αlog⁡K-\frac{\alpha}{K} \sum_k \log p_k = \alpha\, \mathrm{KL}(u \,\|\, p) + \alpha \log K. Putting it together:

Lsmooth=(1−α) LCE+α KL(u ∥ p)+αlog⁡K.\mathcal{L}^{\text{smooth}} = (1 - \alpha)\, \mathcal{L}^{\text{CE}} + \alpha\, \mathrm{KL}\bigl( u\,\|\,p \bigr) + \alpha \log K.

The constant αlog⁡K\alpha \log K 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].

Build it yourself

A short project that takes about an evening:

  1. Train a small ResNet on CIFAR-10 with the bare minimum: SGD + momentum, no BN, no dropout, no augmentation. Record train/test accuracy.
  2. Add batch norm. Re-train. Note the speedup and the higher LR you can tolerate.
  3. Add basic augmentation (random crop + horizontal flip). Note the test accuracy jump.
  4. Swap SGD for AdamW with weight decay 0.05. Re-tune the LR.
  5. Add MixUp α=0.2\alpha = 0.2 and label smoothing 0.1. Compare ECE before and after with sklearn.calibration.calibration_curve.
  6. Stretch: replace BN with group norm G=32G = 32 and reduce batch size to 4 to see when each shines.

References

  1. 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
  2. Ioffe, S. and Szegedy, C. (2015). Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift. ICML 2015. arXiv:1502.03167
  3. Ba, J. L., Kiros, J. R., and Hinton, G. E. (2016). Layer Normalization. arXiv preprint. arXiv:1607.06450
  4. Wu, Y. and He, K. (2018). Group Normalization. ECCV 2018. arXiv:1803.08494
  5. Santurkar, S., Tsipras, D., Ilyas, A., and Madry, A. (2018). How Does Batch Normalization Help Optimization?. NeurIPS 2018. arXiv:1805.11604
  6. Szegedy, C., Vanhoucke, V., Ioffe, S., Shlens, J., and Wojna, Z. (2016). Rethinking the Inception Architecture for Computer Vision. CVPR 2016. arXiv:1512.00567
  7. 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
  8. 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
  9. 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
  10. Huang, G., Sun, Y., Liu, Z., Sedra, D., and Weinberger, K. Q. (2016). Deep Networks with Stochastic Depth. ECCV 2016. arXiv:1603.09382
  11. Loshchilov, I. and Hutter, F. (2017). Decoupled Weight Decay Regularization. ICLR 2019 (arXiv preprint 2017). arXiv:1711.05101
  12. Press, O. and Wolf, L. (2017). Using the Output Embedding to Improve Language Models. EACL 2017. arXiv:1608.05859
  13. Goodfellow, I., Bengio, Y., and Courville, A. (2016). Deep Learning. MIT Press. https://www.deeplearningbook.org