Normalization Layers

Dive into Deep Learning · §7.3

Normalization Layers
minibatch standardization · scale invariance & self-stabilizing LR · training vs. eval modes · LayerNorm & GroupNorm

Why Unnormalized Networks Have Fragile Learning Rates

Motivation & Scale Drift

  • Sigmoid & ReLU scale drift: LeNet stalls at \eta = 0.1 (\approx 60\%) and only trains inside a narrow 3\times band (\eta_0 \in [1, 3]); NiN and GoogLeNet diverge at \eta_0 = 0.1.
  • Initialization only holds at step 0: Once gradient steps update weights, layer activation and gradient scales drift apart unless actively normalized.

Batch Normalization: Standardizing Over a Minibatch

Mathematical Formulation

\textrm{BN}(x_i) = \gamma \, \frac{x_i - \hat{\mu}_\mathcal{B}}{\sqrt{\hat{\sigma}^2_\mathcal{B} + \epsilon}} + \beta

  • Minibatch moments: \hat{\mu}_\mathcal{B} = \frac{1}{m}\sum_{i=1}^m x_i and \hat{\sigma}^2_\mathcal{B} = \frac{1}{m}\sum_{i=1}^m (x_i - \hat{\mu}_\mathcal{B})^2 (\epsilon = 10^{-5}).
  • Affine restore (\gamma, \beta): Learnable scale (init 1) and shift (init 0) per feature preserve expressive power.

Concrete Standardization & Why Pre-BN Biases Vanish

Invariance to Affine Shifts

  • Shift & scale invariance: (2, 4, 6, 8), (20, 40, 60, 80), and (102, 104, 106, 108) all standardize to (-1.34, -0.45, 0.45, 1.34).
  • Why set bias=False before BN: In x_i = \mathbf{w}^\top \mathbf{h}_i + b, the bias b shifts \hat{\mu}_\mathcal{B} by +b and cancels identically in x_i - \hat{\mu}_\mathcal{B} (\partial L / \partial b = 0).

Scale Invariance and Self-Stabilizing Learning Rates

Optimization Theory

\textrm{BN}(a\mathbf{w}^\top \mathbf{h}_i) = \textrm{BN}(\mathbf{w}^\top \mathbf{h}_i) \implies \nabla_{\mathbf{w}} L(a\mathbf{w}) = \frac{1}{a} \nabla_{\mathbf{w}} L(\mathbf{w})

  • Orthogonal gradients (\mathbf{w}^\top \mathbf{g} = 0): By Pythagoras, \|\mathbf{w} - \eta \mathbf{g}\|^2 = \|\mathbf{w}\|^2 + \eta^2 \|\mathbf{g}\|^2.
  • Self-stabilizing LR: Large \eta grows \|\mathbf{w}\|, which automatically damps subsequent gradients by 1/\|\mathbf{w}\|.

Batch Normalization in Dense vs. Convolutional Layers

Spatial Equivariance

  • Dense layers (m \times d): Pools over axis 0 (m examples per feature, shape 1 \times d).
  • Conv layers (m examples, c channels, p \times q pixels): Pools over the batch and both spatial axes (m \cdot p \cdot q values per channel, one statistic per channel) to preserve spatial translation equivariance (100{,}352 values/channel in LeNet Conv1).

Training Mode vs. Prediction Mode & Running Averages

Two Execution Modes

\hat{\mu} \leftarrow \rho\,\hat{\mu} + (1 - \rho)\,\hat{\mu}_\mathcal{B}, \qquad \hat{\sigma}^2 \leftarrow \rho\,\hat{\sigma}^2 + (1 - \rho)\,\hat{\sigma}^2_\mathcal{B}

  • Train vs. eval split: Training uses live batch stats (\hat{\mu}_\mathcal{B}, \hat{\sigma}^2_\mathcal{B}) and updates running buffers; eval freezes (\hat{\mu}, \hat{\sigma}^2) for deterministic N=1 scoring.
  • Pitfall: Framework BatchNorm layers call the mixing weight momentum, but some define it as 1-\rho (e.g., 0.1) and others as \rho (e.g., 0.9), so we pass explicit values whenever defaults differ.

Implementing Batch Normalization from Scratch

From-Scratch Implementation

Our batch_norm function branches on training, pooling over axis 0 for dense layers and axes (0, 2, 3) (or (0, 1, 2) in channels-last) for convolutional layers:

def batch_norm(X, gamma, beta, moving_mean, moving_var, eps, momentum,
               training):
    if not training:
        # Prediction mode: normalize with the running estimates
        X_hat = (X - moving_mean) / torch.sqrt(moving_var + eps)
    else:
        assert len(X.shape) in (2, 4)
        # Fully connected: average over examples. Convolutional: over
        # examples and positions, one mean and variance per channel
        dims = 0 if len(X.shape) == 2 else (0, 2, 3)
        mean = X.mean(dim=dims, keepdim=True)
        var = ((X - mean) ** 2).mean(dim=dims, keepdim=True)
        X_hat = (X - mean) / torch.sqrt(var + eps)
        # Update the running estimates; `momentum` is the decay rho
        moving_mean = momentum * moving_mean + (1.0 - momentum) * mean
        moving_var = momentum * moving_var + (1.0 - momentum) * var
    Y = gamma * X_hat + beta  # Scale and shift
    return Y, moving_mean.detach(), moving_var.detach()

Implementing the Stateful BatchNorm Layer

Trainable Params vs. Running Buffers

BatchNorm separates learnable gamma, beta from running buffers moving_mean, moving_var:

class BatchNorm(nn.Module):
    # `num_features`: outputs of a fully connected layer or channels of a
    # convolutional layer. `num_dims`: 2 or 4, the number of input axes
    def __init__(self, num_features, num_dims):
        super().__init__()
        shape = (1, num_features) if num_dims == 2 else (1, num_features, 1, 1)
        # Scale and shift, learned, start at 1 and 0
        self.gamma = nn.Parameter(torch.ones(shape))
        self.beta = nn.Parameter(torch.zeros(shape))
        # Running estimates, not learned, start at 0 and 1
        self.register_buffer('moving_mean', torch.zeros(shape))
        self.register_buffer('moving_var', torch.ones(shape))

    def forward(self, X):
        Y, moving_mean, moving_var = batch_norm(
            X, self.gamma, self.beta, self.moving_mean, self.moving_var,
            eps=1e-5, momentum=0.9, training=self.training)
        self.moving_mean.copy_(moving_mean)
        self.moving_var.copy_(moving_var)
        return Y

Verifying Against the Framework’s Built-In Layer

Numerical Verification

X = 2 + 3 * torch.randn(128, 6, 28, 28)
bn, bn_ref = BatchNorm(6, num_dims=4), nn.BatchNorm2d(6)  # rho 0.9, eps 1e-5
with torch.no_grad():
    Y, Y_ref = bn(X), bn_ref(X)  # New layers are in training mode
{'largest channel mean': float(Y.mean(dim=(0, 2, 3)).abs().max()),
 'average channel variance': float(Y.var(dim=(0, 2, 3),
                                         unbiased=False).mean()),
 'largest difference': float((Y - Y_ref).abs().max()),
 'running means': bn.moving_mean.reshape(-1)}
{'largest channel mean': 1.8056253736631334e-07,
 'average channel variance': 0.9999989867210388,
 'largest difference': 7.152557373046875e-07,
 'running means': tensor([0.1994, 0.1993, 0.2000, 0.2007, 0.1991, 0.1981])}

Adding Batch Normalization to LeNet (BNLeNet)

Concise Implementation

BatchNorm before LeNet’s four hidden sigmoids adds only 226 parameters to 61{,}706:

class BNLeNet(d2l.Classifier):
    """LeNet with batch normalization before each hidden sigmoid."""
    def __init__(self, lr=0.1, num_steps=4690, num_classes=10):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.Sequential(  # No biases before batch normalization
            nn.LazyConv2d(6, kernel_size=5, padding=2, bias=False),
            nn.LazyBatchNorm2d(), nn.Sigmoid(),
            nn.AvgPool2d(kernel_size=2, stride=2),
            nn.LazyConv2d(16, kernel_size=5, bias=False),
            nn.LazyBatchNorm2d(), nn.Sigmoid(),
            nn.AvgPool2d(kernel_size=2, stride=2),
            nn.Flatten(),
            nn.LazyLinear(120, bias=False), nn.LazyBatchNorm1d(), nn.Sigmoid(),
            nn.LazyLinear(84, bias=False), nn.LazyBatchNorm1d(), nn.Sigmoid(),
            nn.LazyLinear(num_classes))

    weight_init = d2l.LeNet.weight_init  # Xavier weights, zero biases

Why Cosine Decay Stabilizes Running Statistics

Schedule & Running-Stat Interaction

Comparing CosineLeNet and BNLeNet over 10 epochs at peak learning rate \eta_0 = 0.1 demonstrates both faster convergence and why learning-rate decay is essential for batch normalization:

  • Immediate convergence at \eta_0 = 0.1: Plain LeNet stalls at chance (10%) for several epochs and finishes near \approx 60\%, whereas BNLeNet clears 70\% in epoch 1 and reaches \approx 88\%.
  • Eliminating running-stat lag: Under a constant \eta = 0.1, weights keep jumping while running averages lag by \sim 10 steps, causing 10-point validation dips. Annealing \eta_t \to 0 lets weights settle so (\hat{\mu}, \hat{\sigma}^2) lock onto the final network.

A 300-Fold Usable Learning-Rate Band

Empirical Scale Invariance

Sweeping the peak learning rate \eta_0 \in \{0.03, 0.1, 0.3, 1, 3, 10\} over 10 epochs confirms the self-stabilizing scale-invariance prediction:

  • Unnormalized LeNet (3\times band): Succeeds only inside a narrow window around \eta_0 \in [1, 3] (84\text{--}87\%); below 1 gradients are too weak, and at 10 runs become erratic or stall at chance.
  • Normalized BNLeNet (300\times band): Clears \approx 85\% at every peak rate from 0.03 to 10, reaching \approx 91\% for \eta_0 \ge 1 (limited at still higher rates only because the final linear output layer is unnormalized).

When Batch Stats Fail: Small Batches & Sequences

Limits of Minibatch Coupling

  • Micro-batch collapse (m \le 2): In a dense layer at m=1, x_1 = \hat{\mu}_\mathcal{B} \implies \textrm{BN}(x_1) \equiv \beta (zero gradient). On ImageNet at 2 images/GPU, BN ResNet-50 error spikes from 23.6\% to 34.7\%.
  • Train–test drift & sequences: Running stats drift during domain fine-tuning, and causal autoregressive sequences cannot pool across tokens or examples.

Layer, Group, and Instance Normalization

Single-Example Normalizers

Every alternative normalizer applies the exact same formula \gamma (x - \hat{\mu})/\sqrt{\hat{\sigma}^2 + \epsilon} + \beta but computes (\hat{\mu}, \hat{\sigma}^2) strictly within each individual example (N axis unpooled):

  • Layer Normalization (LN): Normalizes within one example across all channels/features (in Transformers and ConvNeXt, across the C channels at each individual token or pixel position).
  • Group Normalization (GN): Splits C channels into G groups (typically G=32) and pools over (C/G) \times H \times W per example.
  • Instance Normalization (IN): The G = C limit, normalizing each individual (N, C) spatial map over H \times W.

Group Normalization Holds Steady at 2 Images per GPU

Batch-Size Independence

Verifying GroupNorm in code and on ImageNet shows why single-example normalizers require no running averages and never degrade at small batch sizes:

  • Exact single-example invariance: Evaluating gn(X[:1]) produces the exact same tensor as gn(X)[:1] (zero train/eval split).
  • ResNet-50 ImageNet top-1 error (Wu & He, 2018):
    • At 32 images/GPU: BatchNorm 23.6\% vs. GroupNorm 24.1\% (0.5\% edge for BN’s minibatch noise).
    • At 2 images/GPU: BatchNorm spikes to 34.7\%, while GroupNorm stays unchanged at 24.1\%.
X = torch.randn(32, 16, 8, 8)
gn = nn.GroupNorm(4, 16).requires_grad_(False)  # 4 groups of 4 channels
Y = gn(X)
G = Y.reshape(32, 4, -1)  # Collect each (example, group) pair's numbers
(G.mean(dim=2).abs().max(), G.var(dim=2, unbiased=False).mean(),
 (gn(X[:1]) - Y[:1]).abs().max())
(tensor(3.3528e-08), tensor(1.0000), tensor(0.))

Normalizer-Free Networks & Direct Weight Scaling

Alternative Scale Control

\hat{W}_{o,i,k} = \gamma \cdot \frac{W_{o,i,k} - \mu_{W_o}}{\sqrt{N_{\text{in}}}\,\sigma_{W_o} + \epsilon}

  • NFNets (Brock et al., 2021): Standardize filter weights directly and apply Adaptive Gradient Clipping (\|\mathbf{G}_l\|_F / \|\mathbf{W}_l\|_F \le \lambda).
  • Takeaway: Confirms that preserving signal scale across depth is the core role of normalization.

Concept Check: Normalization Axes, Buffers & Eval Bugs

Concept Check

Work out these three concrete normalization problems:

  1. Element counts per mean: A convolutional layer has N = 16 examples, C = 64 channels, and H \times W = 32 \times 32 spatial positions. How many scalar activations are averaged to compute a single mean \hat{\mu} in (a) 2D batch normalization, (b) group normalization (G = 16), and (c) per-pixel channel layer normalization (as in ConvNeXt)?
  2. Trainable parameters vs. buffers: How many trainable parameters and how many non-trainable running buffers does a 64-channel 2D batch-normalization layer add?
  3. Training mode at N=1: What happens if you accidentally evaluate a dense 1D batch-normalized network in training mode with batch size N=1?

Answers:

  1. (a) BatchNorm: pools over (N, H, W) \implies 16 \cdot 32 \cdot 32 = 16{,}384 elements. (b) GroupNorm(G=16): pools over (C/G, H, W) = (4, 32, 32) \implies 4{,}096 elements. (c) Per-pixel LayerNorm: pools over C \implies 64 elements.
  2. 128 trainable parameters (\gamma, \beta \in \mathbb{R}^{64}) and 128 non-trainable buffers (moving_mean, moving_var \in \mathbb{R}^{64}).
  3. Every feature equals its own mean (x_1 - \hat{\mu}_\mathcal{B} = 0), so every normalized layer outputs constant \beta regardless of the input image (or raises a framework ValueError).

Summary: Key Takeaways on Normalization Layers

Summary

  • BatchNorm (BN): Pools (N, H, W) per channel C; uses running stats (\hat{\mu}, \hat{\sigma}^2) at eval and folds into conv weights (N \ge 16).
  • GroupNorm (GN, G=32): Pools (C/G, H, W) per example N; batch-size independent for detection/segmentation (N=1\text{--}2).
  • Per-Pixel LN & InstanceNorm: LN pools (C,) per token/pixel (ViT, ConvNeXt); IN pools (H, W) per channel (style transfer).