Regularization, Normalization and Initialization
The toolkit that makes deep networks generalize and train stably: weight decay, dropout, early stopping, data augmentation, batch and layer normalization, and principled weight initialization.
Modern networks have far more parameters than training examples — they can memorise even randomly labelled data (Zhang et al., 2016). Two families of techniques keep them useful. [[regularization|Regularization]] discourages memorisation so the model generalizes to new data. Normalization and initialization keep the signals and gradients flowing through many layers at a healthy scale so that training works at all. This lesson covers the standard tools in both families and their knobs[1].
Weight decay (L2 regularization)
- L′(w)
- the regularized loss that is actually minimized
- L(w)
- the original data loss
- λ
- lambda — Weight decay strength, e.g. 10⁻⁴ to 10⁻²; the /2 is there so the penalty's gradient is simply λw
- ‖w‖²
- squared L2 norm: the sum of all weights squared, w₁² + w₂² + …
- ⇒
- “which leads to” (take the gradient of L′ and plug it into gradient descent)
- w
- the weights
- ←
- update the weights
- ηλ
- η times λ: the fraction by which every weight shrinks per step
- η
- Learning rate
- ∇L(w)
- Gradient of the original data loss
- ·
- multiplication
▸Worked example
Weight decay prefers solutions with small weights, which tend to be smoother functions that change gently with the input — less able to thread through every noisy training point. It is cheap, almost always helps a little, and is on by default in most modern recipes (AdamW)[1].
- What it is
- Strength of the pull of every weight toward zero.
- ↑ If you increase it
- Less overfitting and a smaller train/val gap; too high and the model underfits — both losses rise and predictions flatten.
- ↓ If you decrease it
- More capacity to fit the training set; at 0, only other regularizers (or early stopping) prevent memorisation.
- Typical values
- SGD: 1e-4–5e-4. AdamW: 0.01–0.1. Exclude biases and normalization parameters.
Dropout
- training
- the mode used while learning (
model.train()in PyTorch) - inference
- the mode used for predictions (
model.eval()): Dropout is switched off - h̃
- “h-tilde”: the activations after dropout, passed to the next layer
- h
- the layer's activations (a vector)
- m
- random mask vector of 0s and 1s, drawn fresh for every example and step
- mᵢ
- mask entry for unit i
- ⊙
- element-wise product: units whose mask is 0 become 0
- p
- drop probability, e.g. 0.1–0.5 (the
pinnn.Dropout(p)) - ~
- “is drawn from” a probability distribution
- Bernoulli
- a biased coin flip: 1 with probability 1 − p, 0 with probability p
▸Worked example
Dropout (Srivastava et al., 2014) randomly removes units during training[2]. Each mini-batch trains a different “thinned” sub-network that shares weights with all the others; at test time the full network acts like an average of this huge ensemble. It prevents units from co-adapting (relying on very specific partners) and was a key ingredient of AlexNet. Remember to switch it off for evaluation (model.eval()).
- What it is
- Probability of zeroing each unit during training (PyTorch
nn.Dropout(p)). Note: some papers use the keep probability instead. - ↑ If you increase it
- Stronger regularization and less overfitting, but noisier and slower training; too high (≥ 0.7) and the network underfits.
- ↓ If you decrease it
- Faster convergence and less noise; at 0 there's no dropout. Large pretrained models fine-tuned on lots of data often use 0–0.1.
- Typical values
- 0.5 for large fully connected layers (classic); 0.1 in Transformers; 0.1–0.2 on inputs; often lower in CNNs that use BatchNorm.
Early stopping and data augmentation
[[early-stopping|Early stopping]] monitors the validation loss each epoch, remembers the best checkpoint, and stops when there has been no improvement for patience epochs. It effectively tunes the number of epochs for free and limits how far weights can travel from their initialization — it behaves like a form of L2 regularization[1]. [[data-augmentation|Data augmentation]] creates new, label-preserving variations of training examples: random crops, flips, rotations, colour jitter for images; noise, time-stretching or SpecAugment-style masking for audio; synonym replacement or back-translation for text. It is often the single most effective regularizer for vision, because it teaches invariances the model would otherwise have to learn from more data.
- What it is
- How many epochs (or evaluations) without improvement in validation loss to tolerate before stopping.
- ↑ If you increase it
- More robust to noisy validation curves and temporary plateaus (e.g. before an LR drop), but wastes compute after the true optimum.
- ↓ If you decrease it
- Stops sooner and saves compute, but may quit on a random bump before the model has really converged.
- Typical values
- 5–20 epochs; scale with how noisy the validation loss is. Pair with a small
min_delta.
- What it is
- How aggressive the random transformations are (crop scale range, rotation angle, jitter amount, probability of each transform).
- ↑ If you increase it
- Stronger regularization and more robustness; too strong and examples stop looking like their label (a rotated “6” becomes a “9”), so the model underfits and training slows.
- ↓ If you decrease it
- Faster training, closer fit to the training distribution, more overfitting on small datasets.
- Typical values
- Images: random resized crop + horizontal flip as a baseline; stronger policies (RandAugment, mixup) for long training runs.
Batch normalization
- x̂
- “x-hat”: the normalized value (mean 0, variance 1 across the batch)
- x
- one feature's (or channel's) value for one example in the mini-batch
- μ_B
- mu — mean of that feature over the mini-batch
- σ²_B
- sigma squared — variance of that feature over the mini-batch
- √
- square root: turns the variance into a standard deviation
- ε
- small constant (PyTorch: 10⁻⁵) against division by zero
- γ
- gamma — learned scale, initialized to 1
- β
- beta — learned shift, initialized to 0 (not the momentum β)
- y
- output of the Batch normalization layer
- ·
- multiplication
▸Worked example
Batch normalization (Ioffe & Szegedy, 2015) normalizes each channel's activations to zero mean and unit variance across the batch, then lets the network rescale them[3]. It allows much higher learning rates, makes training less sensitive to initialization and adds a mild regularizing noise (each example's normalization depends on its batch-mates). The original motivation, “reducing internal covariate shift”, has been questioned: Santurkar et al. (2018) argue its main benefit is a smoother loss landscape. Its weak spots: it depends on the batch size (poor below ~8–16), behaves differently in train and eval mode, and is awkward for variable-length sequences.
Layer normalization (and friends)
Layer normalization (Ba et al., 2016) uses the same formula, but computes μ and σ² over the features of a single example instead of over the batch[4]. It therefore works identically for batch size 1, in training and inference, and for each token of a sequence — which is why it is the standard in RNNs and Transformers. RMSNorm (Zhang & Sennrich, 2019) drops the mean subtraction and is used in many recent LLMs; GroupNorm normalizes over groups of channels and is popular for detection/segmentation with small batches.
| BatchNorm | LayerNorm | RMSNorm | |
|---|---|---|---|
| Statistics computed over | The batch (per channel) | Features of one example | Features of one example (RMS only) |
| Depends on batch size? | Yes | No | No |
| Train ≠ eval behaviour? | Yes (running stats) | No | No |
| Typical use | CNNs (ResNet) | Transformers, RNNs | Recent LLMs (e.g. LLaMA) |
Weight initialization
Initial weights must be random (to break symmetry) and correctly scaled. If they are too large, activations and gradients grow layer by layer and explode; too small and they shrink to nothing (Vanishing (and exploding) gradient). Glorot & Bengio (2010) derived a scale that keeps the variance of activations and gradients roughly constant across layers for tanh/sigmoid networks[5]; He et al. (2015) corrected it for ReLU, which zeroes half its inputs and so needs twice the variance[6].
- Xavier/Glorot
- Weight initialization of Glorot & Bengio (2010), for tanh/sigmoid layers (
nn.init.xavier_normal_) - He/Kaiming
- initialization of He et al. (2015), for ReLU layers (
nn.init.kaiming_normal_) - Var(w)
- variance of the random initial weights (mean 0; std = √Var)
- n_in
- fan-in: number of inputs feeding each neuron
- n_out
- fan-out: number of outputs (neurons) of the layer
▸Worked example
- What it is
- The standard deviation (or uniform range) used to draw initial weights, usually set by a scheme like Xavier or He.
- ↑ If you increase it
- Activations grow with depth: saturated tanh/sigmoid units, exploding ReLU activations and gradients, loss NaN in deep nets.
- ↓ If you decrease it
- Activations shrink toward zero with depth; gradients vanish and the network learns very slowly or not at all.
- Typical values
- He (Kaiming) for ReLU-family; Xavier for tanh/sigmoid/linear. PyTorch layers default to a scaled uniform init — fine for most models.
import torch
import torch.nn as nn
class Net(nn.Module):
def __init__(self, d_in, d_hidden=256, n_classes=10, p_drop=0.3):
super().__init__()
self.body = nn.Sequential(
nn.Linear(d_in, d_hidden), nn.BatchNorm1d(d_hidden), nn.ReLU(), nn.Dropout(p_drop),
nn.Linear(d_hidden, d_hidden), nn.BatchNorm1d(d_hidden), nn.ReLU(), nn.Dropout(p_drop),
nn.Linear(d_hidden, n_classes),
)
for m in self.modules():
if isinstance(m, nn.Linear):
nn.init.kaiming_normal_(m.weight, nonlinearity="relu") # He init
nn.init.zeros_(m.bias)
def forward(self, x):
return self.body(x)
model = Net(d_in=784)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.05)
model.train() # dropout ON; BatchNorm uses batch stats and updates running stats
# ... training loop with early stopping (see the hyperparameters lesson) ...
model.eval() # dropout OFF; BatchNorm uses running stats
with torch.no_grad():
preds = model(x_val).argmax(dim=1)train() / eval() switch changes the behaviour of dropout and BatchNorm.import torch
from torchvision.transforms import v2
train_tf = v2.Compose([
v2.RandomResizedCrop(224, scale=(0.08, 1.0)), # random crop + resize
v2.RandomHorizontalFlip(),
v2.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4),
v2.ToImage(), v2.ToDtype(torch.float32, scale=True),
v2.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
val_tf = v2.Compose([ # no randomness for validation!
v2.Resize(256), v2.CenterCrop(224),
v2.ToImage(), v2.ToDtype(torch.float32, scale=True),
v2.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])- Forgetting `model.eval()` before validation/inference: dropout stays on and BatchNorm uses the current batch — predictions become random-ish and depend on batch composition.
- BatchNorm with tiny batches (1–4): statistics are too noisy; use GroupNorm/LayerNorm, or freeze BN statistics when fine-tuning.
- Augmenting the validation or test set with random transforms: your metrics become noisy and biased.
- Weight decay on BatchNorm/LayerNorm γ and on biases: usually harmless but can hurt; most recipes exclude them.
- Stacking every regularizer at maximum on a small model: it underfits. Add regularization only when you see overfitting.
▸Go deeper: dropout as an ensemble, and where to put LayerNorm
A layer with n units has 2ⁿ possible dropout masks, so dropout trains an exponential number of weight-sharing sub-networks. Srivastava et al. show that scaling the weights at test time approximates the geometric mean of their predictions (exactly for a single linear-softmax layer)[2]. Running several stochastic forward passes with dropout on (“MC dropout”) gives a cheap uncertainty estimate.
The original Transformer applied LayerNorm after each residual addition (Post-LN). Xiong et al. (2020) showed that putting it before each sub-layer (Pre-LN) keeps gradients well-behaved at initialization, so training can often use a shorter (or no) warmup — most modern LLMs use Pre-LN or Pre-RMSNorm.
Quiz
model.eval(). What do you observe?References
- [1]Deep Learning — Chapter 7: Regularization for Deep LearningBookGoodfellow, Bengio & Courville2016deeplearningbook.org
- [2]Dropout: A Simple Way to Prevent Neural Networks from OverfittingPaperSrivastava et al.2014jmlr.org
- [3]Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate ShiftPaperIoffe & Szegedy2015arxiv.org
- [4]Layer NormalizationPaperBa, Kiros & Hinton2016arxiv.org
- [5]Understanding the difficulty of training deep feedforward neural networksPaperGlorot & Bengio2010proceedings.mlr.press
- [6]Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet ClassificationPaperHe et al.2015arxiv.org