30 Mins

5. Batch Normalization & Layer Normalization

Internal Covariate Shift and Normalization Principles

Internal Covariate Shift (ICS) describes the phenomenon where the distribution of each layer's inputs changes during training as the parameters of previous layers change. This requires lower learning rates and careful parameter initialization, as layers must continuously adapt to new input distributions, slowing convergence significantly.

Normalization techniques aim to mitigate this by ensuring that the inputs to each activation function have a stable distribution with a constant mean and variance. By constraining the inputs, we ensure that the gradients are more stable, allowing for higher learning rates and reducing the dependency on initialization strategies.

Operator Note: Standardizing inputs helps prevent the vanishing/exploding gradient problem by keeping activation inputs within a regime where non-linearities (like sigmoid/tanh) are sensitive.
Python 3
import torch
import torch.nn as nn

# Mocking an input tensor representing a batch of 32 samples with 128 features
input_data = torch.randn(32, 128)

# Manual normalization to demonstrate centering and scaling
mean = input_data.mean(dim=0)
std = input_data.std(dim=0)
normalized_input = (input_data - mean) / (std + 1e-5)
print(f'Mean: {normalized_input.mean():.4f}, Std: {normalized_input.std():.4f}')

Batch Normalization (BN) Mechanisms

Batch Normalization computes the mean and variance across the batch dimension for every individual feature. During training, BN tracks the running mean and variance using exponential moving averages, which are then used during inference. This allows the model to normalize test data based on the statistics learned across the training distribution.

A critical aspect of BN is the introduction of learnable affine parameters, gamma and beta. These allow the network to 'undo' the normalization if the identity transformation is deemed optimal, essentially giving the network the flexibility to shift and rescale the normalized activations to maximize representational capacity.

Operator Note: Batch Normalization is highly dependent on batch size; very small batches yield noisy estimates of statistics, which can degrade model performance.
Python 3
bn = nn.BatchNorm1d(num_features=128)
# Training mode enables running statistics updates
bn.train()
output = bn(torch.randn(32, 128))
# During inference, BN uses the collected running statistics
bn.eval()
output_eval = bn(torch.randn(1, 128))

Layer Normalization (LN) and Sequential Data

Unlike BN, Layer Normalization computes the mean and variance across all features for each individual sample. This makes LN independent of the batch size, which is highly advantageous for Recurrent Neural Networks (RNNs) or Transformers where sequence lengths vary or batch sizes are constrained by memory limits.

By normalizing across the feature dimension, LN captures the correlations between hidden units within a specific observation. In Transformers, LN is often placed 'pre-norm' or 'post-norm' relative to attention and feed-forward blocks, providing stable training signals across deep stacks without the need for global batch statistics.

Operator Note: Always prefer Layer Normalization over Batch Normalization when working with variable sequence lengths or tasks where batch sizes must be small due to GPU memory constraints.
Python 3
ln = nn.LayerNorm(normalized_shape=128)
# LN normalizes per-sample, regardless of batch index
sample_input = torch.randn(1, 128)
output = ln(sample_input)
print(f'Sample Mean: {output.mean():.4f}, Sample Std: {output.std():.4f}')

Knowledge Check

Ready to test your understanding of 5. Batch Normalization & Layer Normalization?

Back