Batch Normalisation from Scratch: Why It Works and When It Doesn't

Implement BatchNorm, LayerNorm, InstanceNorm, and GroupNorm from scratch in NumPy. See how each changes activation distributions, and learn when to use which.

Cover Image for Batch Normalisation from Scratch: Why It Works and When It Doesn't

You're training a network, and changing its depth or learning rate makes the loss much harder to settle. The values passed between layers are worth examining alongside the final prediction. During training, batch normalisation adjusts those intermediate values using statistics from the current batch, giving us a way to study how their scale affects training.

Adjusting those intermediate values changes which learning rates are usable. Without batch normalisation, rate 0.1 gives 11% accuracy. With it, rate 0.5 reaches 98.6%. We implement Ioffe and Szegedy's 2015 operation in NumPy, check it against PyTorch and test batch size and prediction-time statistics.

In this post, we will implement all four normalisation layers from scratch in NumPy, verify each one against PyTorch, visualise how they reshape activation distributions, and give you a practical decision tree for choosing the right one.

Let's Build It

Click the badge to run this yourself:

Open In Colab

First, let's see the dramatic effect of batch normalisation on training. We build a 5-layer CNN (matching the depth used in the fast.ai notebooks) and train it with and without BatchNorm:

import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms

transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.1307,), (0.3081,))
])
train_data = datasets.MNIST('data', train=True, download=True, transform=transform)
test_data = datasets.MNIST('data', train=False, transform=transform)
train_loader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_data, batch_size=1000)

def make_cnn(use_bn=False):
    """Build a 5-layer CNN, optionally with BatchNorm after each conv."""
    layers = []
    channels = [(1, 8, 5), (8, 16, 3), (16, 32, 3), (32, 64, 3), (64, 64, 3)]
    for ni, nf, ks in channels:
        layers.append(nn.Conv2d(ni, nf, ks, padding=ks//2, stride=2, bias=not use_bn))
        if use_bn:
            layers.append(nn.BatchNorm2d(nf))
        layers.append(nn.ReLU())
    layers += [nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(64, 10)]
    return nn.Sequential(*layers)

def train_and_evaluate(model, lr, epochs=5):
    optimiser = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9)
    results = []
    for epoch in range(epochs):
        model.train()
        for images, labels in train_loader:
            loss = F.cross_entropy(model(images), labels)
            optimiser.zero_grad()
            loss.backward()
            optimiser.step()
        model.eval()
        correct = 0
        with torch.no_grad():
            for images, labels in test_loader:
                correct += (model(images).argmax(1) == labels).sum().item()
        results.append(correct / len(test_data) * 100)
        print(f"  Epoch {epoch+1}: {results[-1]:.1f}%")
    return results

# Without BN: lr=0.01 works, lr=0.1 DIVERGES
print("Without BatchNorm (lr=0.01):")
torch.manual_seed(42)
acc_safe = train_and_evaluate(make_cnn(use_bn=False), lr=0.01)

print("\nWithout BatchNorm (lr=0.1) — diverges:")
torch.manual_seed(42)
acc_diverge = train_and_evaluate(make_cnn(use_bn=False), lr=0.1)

print("\nWith BatchNorm (lr=0.5) — stable and fast:")
torch.manual_seed(42)
acc_bn = train_and_evaluate(make_cnn(use_bn=True), lr=0.5)
Without BatchNorm (lr=0.01):
  Epoch 1: 95.7%  Epoch 2: 97.1%  Epoch 3: 97.5%  Epoch 4: 98.2%  Epoch 5: 98.2%

Without BatchNorm (lr=0.1) — diverges:
  Epoch 1: 85.5%  Epoch 2: 11.3%  Epoch 3: 9.8%  Epoch 4: 10.1%  Epoch 5: 11.3%

With BatchNorm (lr=0.5) — stable and fast:
  Epoch 1: 97.2%  Epoch 2: 98.0%  Epoch 3: 97.9%  Epoch 4: 98.5%  Epoch 5: 98.6%

Training curves: without BN lr=0.1 diverges catastrophically, with BN lr=0.5 converges smoothly

Without batch normalisation, lr=0.1 causes the network to diverge completely (accuracy drops to random chance at 11%). With BatchNorm, we can safely use lr=0.5, which is 50x higher, and still converge to 98.6%. This is the practical payoff: BatchNorm makes the loss landscape smoother, letting you take much larger optimisation steps.

What Just Happened?

The Core Idea

Batch normalisation normalises each channel's activations across the mini-batch to have zero mean and unit variance. Then it applies learnable scale (γ\gamma) and shift (β\beta) parameters so the network can recover any distribution it needs.

For a mini-batch of activations with shape (B, C, H, W):

x^c=xc−μcσc2+ϵ\hat{x}_{c} = \frac{x_c - \mu_c}{\sqrt{\sigma_c^2 + \epsilon}}
yc=γc⋅x^c+βcy_c = \gamma_c \cdot \hat{x}_{c} + \beta_c

Where μc\mu_c and σc2\sigma_c^2 are the mean and variance computed over the batch and spatial dimensions for each channel cc.

Building BatchNorm from Scratch

Here is the complete implementation, matching the one from the fast.ai notebook:

import numpy as np

class BatchNorm2d_NumPy:
    """Batch normalisation for 2D inputs (B, C, H, W)."""

    def __init__(self, num_features, momentum=0.1, eps=1e-5):
        self.eps = eps
        self.momentum = momentum
        # Learnable parameters
        self.gamma = np.ones((1, num_features, 1, 1))
        self.beta = np.zeros((1, num_features, 1, 1))
        # Running statistics (for inference)
        self.running_mean = np.zeros((1, num_features, 1, 1))
        self.running_var = np.ones((1, num_features, 1, 1))

    def forward(self, x, training=True):
        if training:
            # Compute mean and variance over batch and spatial dims
            mean = x.mean(axis=(0, 2, 3), keepdims=True)
            var = x.var(axis=(0, 2, 3), keepdims=True)
            # Update running statistics
            self.running_mean = (1 - self.momentum) * self.running_mean + self.momentum * mean
            self.running_var = (1 - self.momentum) * self.running_var + self.momentum * var
        else:
            mean = self.running_mean
            var = self.running_var

        # Normalise, then scale and shift
        x_hat = (x - mean) / np.sqrt(var + self.eps)
        return self.gamma * x_hat + self.beta

The key detail: during training, we compute statistics from the current mini-batch. During inference, we use the running averages accumulated during training. This is why BatchNorm behaves differently in model.train() vs model.eval().

Verifying Against PyTorch

import torch
import torch.nn as nn

np.random.seed(42)
x_np = np.random.randn(4, 3, 4, 4).astype(np.float32)

# NumPy version
bn_np = BatchNorm2d_NumPy(3)
out_np = bn_np.forward(x_np, training=True)

# PyTorch version
bn_pt = nn.BatchNorm2d(3, momentum=0.1, eps=1e-5)
with torch.no_grad():
    bn_pt.weight.fill_(1.0)
    bn_pt.bias.fill_(0.0)
bn_pt.train()
out_pt = bn_pt(torch.tensor(x_np)).detach().numpy()

print(f"Max difference: {np.max(np.abs(out_np - out_pt)):.2e}")
print(f"Match: {np.allclose(out_np, out_pt, atol=1e-5)}")
Max difference: 1.19e-07
Match: True

Removing the Bias Term

Notice in CNN_BN we use bias=False in the conv layers. This is because BatchNorm's β\beta parameter already acts as a bias. If we kept both, the conv layer's bias would be absorbed into μc\mu_c during normalisation and then replaced by βc\beta_c. The fast.ai notebook makes this explicit: "if BN layer added, bias is removed for that layer, because it is unnecessary due to beta."

Visualising the Effect on Activations

The real insight comes from watching what happens to activation distributions across layers:

def get_activation_stats(model, data_loader, n_batches=10):
    """Collect activation means and stds from each conv/bn layer."""
    stats = {}
    hooks = []

    def hook_fn(name):
        def fn(module, input, output):
            if name not in stats:
                stats[name] = {'means': [], 'stds': []}
            stats[name]['means'].append(output.detach().mean().item())
            stats[name]['stds'].append(output.detach().std().item())
        return fn

    for name, module in model.named_modules():
        if isinstance(module, (nn.Conv2d, nn.BatchNorm2d, nn.ReLU)):
            hooks.append(module.register_forward_hook(hook_fn(name)))

    model.eval()
    with torch.no_grad():
        for i, (images, _) in enumerate(data_loader):
            if i >= n_batches: break
            model(images)

    for h in hooks: h.remove()
    return stats

Activation histograms: without BatchNorm (top row) activations grow across layers; with BatchNorm (bottom row) they stay centred and well-scaled

Without normalisation, the mean drifts and the standard deviation either collapses or explodes as you go deeper. With BatchNorm, every layer's activations are recentred to zero mean and unit variance before the learnable γ\gamma and β\beta are applied. This is what allows higher learning rates: the gradients stay well-scaled throughout the network.

The Normalisation Family

Batch normalisation is just one member of a family. The difference between them is which dimensions they normalise over.

The four normalisation approaches: Batch, Layer, Instance, and Group normalisation, showing which dimensions each one averages over

Diagram adapted from Wu & He (2018), "Group Normalization".

LayerNorm: Normalise Over Features

LayerNorm normalises over the channel and spatial dimensions for each sample independently. It does not depend on the batch at all, making it suitable for variable-length sequences and small batches.

class LayerNorm_NumPy:
    """Layer normalisation: normalise over (C, H, W) for each sample."""

    def __init__(self, eps=1e-5):
        self.eps = eps
        self.gamma = 1.0
        self.beta = 0.0

    def forward(self, x):
        # Normalise over channels and spatial dims (axes 1, 2, 3)
        mean = x.mean(axis=(1, 2, 3), keepdims=True)
        var = x.var(axis=(1, 2, 3), keepdims=True)
        x_hat = (x - mean) / np.sqrt(var + self.eps)
        return self.gamma * x_hat + self.beta

From the fast.ai notebook: "LayerNorm is suitable for use in something like RNNs, for other tasks nowhere as good as BatchNorm." This is because LayerNorm treats all channels equally. It cannot distinguish between a high-activation channel (bright region) and a low-activation channel (dark region) within a single sample. For classification, this matters; for sequence modelling (transformers, RNNs), it does not.

Use LayerNorm for: transformers, RNNs, any architecture where batch statistics are unreliable.

InstanceNorm: Normalise Each Channel Independently

InstanceNorm normalises over spatial dimensions only, for each sample and each channel independently. It was designed for style transfer, where you want to remove per-instance contrast information.

class InstanceNorm_NumPy:
    """Instance normalisation: normalise over (H, W) per sample per channel."""

    def __init__(self, num_features, eps=1e-5):
        self.eps = eps
        self.gamma = np.ones((1, num_features, 1, 1))
        self.beta = np.zeros((1, num_features, 1, 1))

    def forward(self, x):
        # Normalise over spatial dims only (axes 2, 3)
        mean = x.mean(axis=(2, 3), keepdims=True)
        var = x.var(axis=(2, 3), keepdims=True)
        x_hat = (x - mean) / np.sqrt(var + self.eps)
        return self.gamma * x_hat + self.beta

The fast.ai notebook poses a thought experiment: "Can InstanceNorm distinguish foggy days from sunny days?" No, because it normalises away the overall intensity of each channel. This is useful for style transfer (where style is about relative patterns, not absolute brightness) but catastrophic for classification (where absolute intensity carries information).

Use InstanceNorm for: style transfer, image generation where you want to remove contrast.

GroupNorm: A Practical Compromise

GroupNorm splits channels into groups and normalises within each group. It is batch-independent (like LayerNorm) but preserves some channel-specific information (like BatchNorm).

class GroupNorm_NumPy:
    """Group normalisation: normalise within channel groups."""

    def __init__(self, num_groups, num_channels, eps=1e-5):
        self.num_groups = num_groups
        self.eps = eps
        self.gamma = np.ones((1, num_channels, 1, 1))
        self.beta = np.zeros((1, num_channels, 1, 1))

    def forward(self, x):
        B, C, H, W = x.shape
        G = self.num_groups
        # Reshape to (B, G, C//G, H, W)
        x = x.reshape(B, G, C // G, H, W)
        mean = x.mean(axis=(2, 3, 4), keepdims=True)
        var = x.var(axis=(2, 3, 4), keepdims=True)
        x_hat = (x - mean) / np.sqrt(var + self.eps)
        x_hat = x_hat.reshape(B, C, H, W)
        return self.gamma * x_hat + self.beta

GroupNorm with num_groups=C is equivalent to InstanceNorm. GroupNorm with num_groups=1 is equivalent to LayerNorm. In practice, 32 groups is a common default.

Use GroupNorm for: small batch sizes (detection, segmentation with large images), or when you need batch-independent normalisation but better accuracy than LayerNorm.

The Decision Tree

SituationBest choiceWhy
CNNs with batch size >= 16BatchNormStrongest empirical performance
Transformers / RNNsLayerNormBatch-independent, works with variable sequences
Small batch sizes (1-4)GroupNormBatch-independent, better than LayerNorm for vision
Style transferInstanceNormRemoves per-instance contrast (desired for style)
Batch size of 1GroupNorm or InstanceNormBatchNorm cannot compute statistics from 1 sample

The Small Batch Problem

The fast.ai notebook demonstrates this directly: train with a batch size of 2 and standard BatchNorm gives only 12% accuracy (random chance on MNIST). The variance estimate from 2 samples is meaningless. The solution in the notebook is a RunningBatchNorm that uses smoother running statistics even during training:

class RunningBatchNorm_NumPy:
    """Running BN: uses exponential moving averages during training too.

    Solves the small-batch problem by never relying on batch statistics alone.
    """

    def __init__(self, num_features, momentum=0.1, eps=1e-5):
        self.eps = eps
        self.momentum = momentum
        self.gamma = np.ones((1, num_features, 1, 1))
        self.beta = np.zeros((1, num_features, 1, 1))
        self.running_mean = np.zeros((1, num_features, 1, 1))
        self.running_var = np.ones((1, num_features, 1, 1))
        self.step = 0

    def forward(self, x, training=True):
        if training:
            batch_mean = x.mean(axis=(0, 2, 3), keepdims=True)
            batch_var = x.var(axis=(0, 2, 3), keepdims=True)
            self.step += 1
            self.running_mean = ((1 - self.momentum) * self.running_mean
                                  + self.momentum * batch_mean)
            self.running_var = ((1 - self.momentum) * self.running_var
                                 + self.momentum * batch_var)
            # Use debiased running stats instead of raw batch stats
            debias = 1 - (1 - self.momentum) ** self.step
            mean = self.running_mean / debias
            var = self.running_var / debias
        else:
            mean = self.running_mean
            var = self.running_var

        x_hat = (x - mean) / np.sqrt(var + self.eps)
        return self.gamma * x_hat + self.beta

Going Deeper

The Effect of Batch Normalisation

The original paper by Ioffe & Szegedy (2015) argued that BatchNorm reduces "internal covariate shift": the distribution of each layer's inputs changes during training as the preceding layers' parameters update. By normalising activations, each layer sees a more stable input distribution.

This explanation has been challenged. Santurkar et al. (2018) in "How Does Batch Normalization Actually Help?" showed that BatchNorm does not meaningfully reduce internal covariate shift. Instead, they argue it makes the loss landscape significantly smoother (smaller Lipschitz constant), which allows larger learning rates and more stable optimisation.

Both perspectives agree on the practical effect: BatchNorm enables higher learning rates, faster convergence, and more stable training. The mechanistic explanation remains an active research question.

The Training/Inference Gap

During training, BatchNorm uses mini-batch statistics. During inference, it uses running averages. This gap can cause problems:

  1. Small batches: Mini-batch statistics are noisy, hurting training
  2. Eval mode forgotten: If you forget model.eval(), inference uses batch statistics from the test data, causing inconsistent results
  3. Distributed training: Each GPU sees a different mini-batch, so the statistics differ across devices (SyncBatchNorm fixes this)

This train/eval asymmetry is BatchNorm's most common source of bugs. Always call model.eval() before inference and model.train() before training.

Interaction with Other Techniques

With optimisers: BatchNorm allows much higher learning rates. The fast.ai notebook trains at lr=0.9 with BatchNorm versus lr=0.4 without. Combined with the 1-cycle policy, learning rates can go as high as 2.0.

With weight decay: The fast.ai notebook notes that weight decay interacts with BatchNorm in subtle ways. Since BatchNorm normalises activations, the scale of the conv weights does not affect the output. Weight decay on BatchNorm parameters (γ\gamma and β\beta) is usually set to zero.

With dropout: Using both BatchNorm and dropout can cause issues because dropout changes the mean and variance of activations during training. Modern architectures typically use one or the other, not both.

Where This Comes From

Ioffe & Szegedy (2015)

Batch normalisation was introduced in "Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift" by Sergey Ioffe and Christian Szegedy at Google. The paper demonstrated that BN-Inception matched the accuracy of the original Inception network in 14x fewer training steps.

"We define Internal Covariate Shift as the change in the distribution of network activations due to the change in network parameters during training." -- Ioffe & Szegedy (2015)

The paper's key technical contribution was making normalisation differentiable by including it as a layer in the network (with learnable γ\gamma and β\beta), rather than normalising as a preprocessing step.

The Normalisation Variants

Further Reading

Interactive Tools

  • 2D Convolution Visualizer: See the convolution operation that BatchNorm normalises after, step by step with adjustable parameters
  • CNN Layer Visualizer: The shapes BatchNorm normalises over. Build a conv and pool stack and read the channel and spatial dimensions at every layer
  • Overfitting Explorer: Visualise the bias-variance tradeoff that regularisation techniques like BatchNorm help manage

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions