Initialisation and normalisation¶
A deep network can only learn if signals survive the trip forward and gradients survive the trip back. Initialisation sets the weights' scale so that each layer neither shrinks nor amplifies what passes through it; normalisation layers re-standardise activations during training so the scale stays right. Get these wrong and a 50-layer network's activations shrink by forty orders of magnitude before it has seen a single example.
10,000 ft
Every deep network multiplies its input by one weight matrix after another. Products of many random factors either vanish or explode unless each factor has size close to one, so the starting scale of the weights decides whether training can begin at all. Xavier (2010) and He (2015) initialisation turned this into simple formulas; batch normalisation (2015) made very deep convolutional networks fast to train; layer normalisation (2016) and its cheaper cousin RMSNorm (2019) sit in every transformer block of every modern LLM (the transformer block). Where the normalisation goes (before or after the residual addition) decides whether a large transformer trains smoothly, and methods such as μP use the same variance arithmetic to transfer hyperparameters from small models to large ones (scaling laws). This page builds on the \(\chi\) analysis of the activations page.
2,000 ft
Four decisions, in the order you make them:
- Random, not constant: identical weights give identical units forever.
- Variance-preserving scale: choose \(\operatorname{Var}(W_{ij}) = \text{gain}^2/n_{\text{in}}\) so each layer keeps activation variance near constant; the gain depends on the activation (\(\sqrt{2}\) for ReLU).
- Normalise: standardise each feature (BatchNorm, across the batch) or each example (LayerNorm/RMSNorm, across features), then let the network learn its own scale \(\gamma\) and shift \(\beta\).
- Place carefully: in transformers, normalise the input of each residual branch (pre-norm) and start branches small, so the residual stream begins as an identity map.
Ground level¶
Why not start at zero?¶
If every weight in a layer starts at the same value, every hidden unit computes the same function of the input, receives the same gradient (the backward pass is symmetric too) and is updated identically. They stay clones forever: a layer of 512 units behaves like one unit. Random initialisation breaks the symmetry. Biases are usually started at zero; that is safe because the random weights already make the units different.
How big should the random weights be?¶
Consider one layer \(z_j = \sum_{i=1}^{n} W_{ji}x_i\) with independent, zero-mean weights of variance \(\sigma_w^2\) and inputs of variance \(v\). The variance of a sum of \(n\) independent terms is the sum of their variances:
So each linear layer multiplies the signal's variance by \(n\sigma_w^2\) (and a ReLU then halves its second moment). With \(n = 512\) and the innocent-looking \(\sigma_w = 0.01\), that factor is \(0.051\): the standard deviation shrinks by a factor of 4.4 per layer. With \(\sigma_w = 1\) it grows by a factor of 22.6 per layer. Fifty layers compound these into astronomically large or small numbers, and the backward pass suffers the same fate. The experiment in Build it measures it on a 50-layer, 512-wide ReLU network:
| Initialisation | std of activations, layer 1 | layer 50 | gradient at input / at output |
|---|---|---|---|
| \(\mathcal{N}(0, 1)\) | \(1.3 \times 10^{1}\) | \(9.8 \times 10^{59}\) | \(1.6 \times 10^{60}\) |
| \(\mathcal{N}(0, 0.01^2)\) | \(1.3 \times 10^{-1}\) | \(9.0 \times 10^{-41}\) | \(1.4 \times 10^{-40}\) |
PyTorch nn.Linear default |
\(3.4 \times 10^{-1}\) | \(1.4 \times 10^{-20}\) | \(3.0 \times 10^{-20}\) |
| Xavier (\(1/n\)) | \(5.8 \times 10^{-1}\) | \(3.1 \times 10^{-8}\) | \(3.7 \times 10^{-8}\) |
| He (\(2/n\)) | \(8.2 \times 10^{-1}\) | \(6.3 \times 10^{-1}\) | \(8.8 \times 10^{-1}\) |
Two lessons hide in that table. First, the right answer is a narrow target: a factor of 2 in variance (Xavier versus He) is the difference between a network that works and one whose signal has shrunk about 20 million-fold. Second, PyTorch's default nn.Linear initialisation, \(U(-1/\sqrt{n}, 1/\sqrt{n})\), has variance \(1/(3n)\), and on a plain deep ReLU stack it vanishes. That is not a bug: real architectures add normalisation layers and residual connections that make the default harmless, but it is why you should never assume a deep plain MLP "just works" at the defaults.
Xavier (Glorot) initialisation¶
Glorot and Bengio (2010) studied why deep sigmoid and tanh networks trained so poorly, observed saturated units and shrinking gradients at initialisation, and derived a fix. Keeping the forward variance constant needs \(n_{\text{in}}\sigma_w^2 = 1\); keeping the backward variance of gradients constant needs \(n_{\text{out}}\sigma_w^2 = 1\) (the backward pass multiplies by \(W^\top\), which sums over \(n_{\text{out}}\) terms). Both cannot hold unless the layer is square, so they compromise:
The derivation assumes the activation is linear near zero with slope 1, which holds for tanh but not for ReLU (it zeroes half its inputs) or sigmoid (slope 0.25, mean 0.5). The older "LeCun" initialisation \(\sigma_w^2 = 1/n_{\text{in}}\) (from Efficient BackProp, 1998) is the forward-only version.
He (Kaiming) initialisation¶
He et al. (2015) redid the calculation for ReLU. If \(z \sim \mathcal{N}(0, q)\), then \(\mathbb{E}[\operatorname{ReLU}(z)^2] = q/2\): half the variance is thrown away with the negative half. To compensate, double the weight variance:
This is exactly the condition \(\chi = 1\) from the activations page, and it is what made 30-layer plain ReLU networks trainable from scratch in their experiments. Frameworks express the rule through a gain: \(\sigma_w = \text{gain}/\sqrt{n_{\text{in}}}\), with gain 1 for linear and sigmoid layers, \(5/3\) for tanh, \(\sqrt{2}\) for ReLU and \(\sqrt{2/(1 + \alpha^2)}\) for leaky ReLU with slope \(\alpha\) (PyTorch's nn.init.calculate_gain). In PyTorch: nn.init.kaiming_normal_(w, nonlinearity="relu").
Orthogonal initialisation and dynamical isometry¶
Variance arguments control the average gain of a layer. But the input–output Jacobian of a deep network is a product of matrices, and products of random Gaussian matrices have singular values that spread out with depth: some directions are amplified, others crushed, even when the average is right. Saxe, McClelland and Ganguli (2013) showed that for deep linear networks, random orthogonal weight matrices (all singular values exactly 1) give learning times that do not grow with depth, while scaled Gaussian ones do not. Pennington, Schoenholz and Ganguli (2017) extended this to nonlinear networks: achieving dynamical isometry (all singular values of the network's Jacobian near 1) is possible with orthogonal weights and tanh-like activations but not with ReLU, and networks that achieve it train dramatically faster. Orthogonal initialisation (nn.init.orthogonal_) remains common in recurrent networks and reinforcement learning, where the same matrix is applied many times.
Data-dependent initialisation
Instead of trusting a formula, measure: push a batch through the network and rescale each layer's weights until its outputs have unit variance (Mishkin and Matas's LSUV, 2015). This is robust to unusual architectures and activations and needs one forward pass per layer.
Initialising residual networks: start as the identity¶
A residual block computes \(\mathbf{x} + f(\mathbf{x})\) (residual networks). If each of \(N\) branches adds an independent signal of variance \(v\), the residual stream's variance grows like \(Nv\), so deep residual stacks need their branches to start small. Three widely used recipes:
- Zero-γ: initialise the last normalisation scale \(\gamma\) of each residual branch to 0, so each block starts as the identity (Goyal et al., 2017, in their one-hour ImageNet training).
- Scaled residual projections: GPT-2 scales the weights of residual layers at initialisation by \(1/\sqrt{N}\), where \(N\) is the number of residual layers (Radford et al., 2019). Many LLM codebases follow it.
- Fixup (Zhang, Dauphin and Ma, 2019): rescale branch weights by a depth-dependent factor and zero-initialise the last layer of each branch; residual networks then train stably without normalisation, even at 10,000 layers.
μP: making the scale right at every width¶
Standard initialisation keeps activations at the right scale as width grows, but the updates do not scale the same way: in the standard parameterisation the best learning rate drifts as you widen a model, so hyperparameters tuned on a small model are wrong for a large one. The maximal update parameterisation (μP; Yang and Hu, and Yang et al., 2022) rescales initialisation and per-layer learning rates with width so that every layer's update changes its activations by a width-independent amount. Then optimal hyperparameters transfer: the Tensor Programs V paper reports outperforming published numbers for the 6.7B-parameter GPT-3 by tuning on a 40M-parameter proxy, at a tuning cost of 7% of pre-training. It is the same variance bookkeeping as He initialisation, applied to the gradient step as well as the forward pass.
Normalisation: re-standardise as you go¶
Initialisation sets the scale at step 0. Training then changes the weights, and the distribution of each layer's inputs drifts. Normalisation layers fix the scale during training by standardising activations and then letting the network choose the scale it wants:
where \(\gamma\) and \(\beta\) are learned per feature and \(\epsilon\) (about \(10^{-5}\)) prevents division by zero. The variants differ only in which values \(\mu\) and \(\sigma^2\) are computed over:
Batch normalisation¶
Ioffe and Szegedy (2015) normalise each feature using the mean and variance over the mini-batch (and, for convolutions, over all spatial positions). A worked example: one feature takes the values \(2, 4, 6, 8\) across a batch of four. Then \(\mu = 5\), \(\sigma^2 = 5\), and the normalised values are \((-3, -1, 1, 3)/\sqrt{5} = (-1.342, -0.447, 0.447, 1.342)\); \(\gamma\) and \(\beta\) then rescale and shift them.
At inference there may be no batch, so BatchNorm keeps exponential running averages of \(\mu\) and \(\sigma^2\) during training (PyTorch: running = 0.9 · running + 0.1 · batch by default) and uses those instead. The original paper reports reaching the same ImageNet accuracy as its baseline with 14 times fewer training steps, permitting much higher learning rates and acting as a regulariser, because each example's normalisation depends on the random other examples in its batch.
BatchNorm's weaknesses all come from its dependence on the batch:
- Small batches give noisy statistics, and accuracy falls (Wu and He, 2018, motivate GroupNorm with exactly this).
- Train/eval mismatch: behaviour differs between
model.train()andmodel.eval(). Forgetting to switch is a classic bug, as is evaluating on data whose statistics differ from the running averages. - Distributed training needs synchronised statistics across devices (
SyncBatchNorm) or per-device batches large enough to estimate them. - Sequences of varying length and autoregressive generation (one token at a time) make batch statistics awkward or meaningless, which is why language models do not use it.
Why does BatchNorm work? The explanation changed
The original paper attributed the gains to reducing internal covariate shift, the drift of each layer's input distribution. Santurkar et al. (2018) tested this directly: injecting deliberate distribution shift after BatchNorm layers did not hurt, and the measured shift was not reduced much. Their alternative explanation is that BatchNorm makes the loss landscape smoother (gradients change more predictably), which allows larger steps. A third, complementary view is scale invariance, derived in First principles. Treat "covariate shift" as historical motivation, not mechanism.
Layer normalisation¶
Ba, Kiros and Hinton (2016) normalise each example across its features: for a token vector \(\mathbf{x} \in \mathbb{R}^d\), \(\mu = \frac1d\sum_i x_i\) and \(\sigma^2 = \frac1d\sum_i (x_i - \mu)^2\). No batch statistics, so training and inference behave identically, any batch size works (including 1), and every token in a sequence is normalised independently. That makes it the natural choice for recurrent networks and transformers. The original transformer applied LayerNorm after each residual addition; almost every language model since has used a variant of it.
RMSNorm¶
Zhang and Sennrich (2019) asked whether the mean subtraction in LayerNorm is needed, hypothesised that "re-centering invariance" is dispensable, and dropped it:
One reduction instead of two and no \(\beta\); they report running-time reductions of 7% to 64% across models with comparable quality. On the row \((2, 4, 6, 8)\), the root mean square is \(\sqrt{30} = 5.477\), giving \((0.365, 0.730, 1.095, 1.461)\): rescaled but not centred, unlike LayerNorm's \((-1.342, -0.447, 0.447, 1.342)\). LLaMA (2023) adopted RMSNorm, and as of 2026 it is the default normalisation in most large open-weight language models.
GroupNorm (Wu and He, 2018) splits channels into groups and normalises within each group of each example, which works for vision models trained with tiny per-device batches (detection, segmentation, video, diffusion models). InstanceNorm (Ulyanov et al., 2016) is GroupNorm with one channel per group, useful in style transfer, where per-image contrast should be removed.
Where the normalisation goes: post-norm versus pre-norm¶
In a residual block there are two places to put the normalisation:
In post-LN, every residual addition is followed by a normalisation, so the skip path is not a clean identity: gradients must pass through every LayerNorm on the way down. Xiong et al. (2020) proved with mean-field analysis that at initialisation a post-LN transformer has large expected gradients for parameters near the output, which is why it needs a learning-rate warm-up to avoid diverging. In pre-LN, the normalisation is applied to the input of each branch and the residual stream \(\mathbf{x} + f(\operatorname{LN}(\mathbf{x}))\) has an unobstructed identity path; it trains stably without warm-up (though most recipes keep one, learning-rate schedules), at the cost of the residual stream's scale growing with depth, which a final normalisation before the output head handles. GPT-2 moved to pre-LN with a final LayerNorm, and nearly every large LLM since has used pre-normalisation, typically with RMSNorm. Variations add normalisation in more places (for example normalising queries and keys inside attention, "QK-norm") or rescale the residual for very deep models (DeepNet's DeepNorm trained 1,000-layer transformers; Wang et al., 2022).
Can we do without normalisation?¶
Normalisation costs memory bandwidth and, for BatchNorm, couples examples. Several lines of work remove it. Fixup and SkipInit get residual networks to train through initialisation alone. NFNets (Brock et al., 2021) combine scaled residual branches with adaptive gradient clipping and matched batch-normalised ImageNet accuracy while training faster. Most recently, Dynamic Tanh (Zhu, Chen, He, LeCun and Liu, 2025) replaces each LayerNorm in a transformer with the elementwise \(\operatorname{DyT}(\mathbf{x}) = \tanh(\alpha\mathbf{x})\) (plus the usual \(\gamma\), \(\beta\)), motivated by the observation that trained LayerNorms produce tanh-like S-shaped input–output maps; the authors report matching or exceeding normalised transformers across vision and language settings, mostly without retuning. As of 2026 this is an active research thread, not the default.
In practice¶
| Architecture | Initialisation | Normalisation |
|---|---|---|
| Plain MLP or CNN, ReLU | He (kaiming_normal_, fan-in) |
BatchNorm after conv/linear, before ReLU |
| ResNet | He; zero-γ on the last BN of each block | BatchNorm (GroupNorm for small batches) |
| Transformer LLM | small normal (often std 0.02) plus \(1/\sqrt{N}\)-scaled residual projections; or μP | pre-norm RMSNorm + final norm |
| RNN / LSTM | orthogonal recurrent weights | LayerNorm if any |
Diagnose with histograms: log the mean and standard deviation of every layer's activations and gradients for the first few hundred steps. A healthy network keeps them within an order of magnitude of each other across layers (training recipe).
History¶
From careful tricks to architecture
1998: LeCun, Bottou, Orr and Müller's Efficient BackProp recommends normalising inputs and initialising with variance \(1/n_{\text{in}}\). 2006–2009: deep networks are trained by layer-wise unsupervised pre-training, partly because nobody can get good starting weights any other way. 2010: Glorot and Bengio explain the failure at initialisation and derive Xavier initialisation. 2013: Saxe et al.'s exact solutions for deep linear networks and orthogonal initialisation; Sutskever et al. show careful initialisation plus momentum suffices without pre-training. 2015: He initialisation; batch normalisation; Mishkin and Matas's LSUV. 2016: layer normalisation, weight normalisation, instance normalisation; mean-field "edge of chaos" theory (Poole et al.; Schoenholz et al.). 2017: zero-γ for large-batch ResNets; dynamical isometry. 2018: GroupNorm; BatchNorm's smoothing explanation. 2019: Fixup; RMSNorm; GPT-2's pre-LN and residual scaling. 2020: the post-LN warm-up analysis. 2021–2022: NFNets; μP; DeepNet. 2025: Dynamic Tanh.
First principles¶
Signal propagation is a product of random gains. Each layer multiplies the forward signal's variance by \(n\sigma_w^2\,\mathbb{E}[\phi^2]/\operatorname{Var}(z)\) and the backward gradient's variance by \(n\sigma_w^2\,\mathbb{E}[\phi'^2]\). Over \(L\) layers these compound geometrically. The only stable choice is gain 1, and the variance formulas above are just that condition solved for \(\sigma_w^2\). Everything on this page is bookkeeping for that single requirement.
Why fan-in? In the forward pass, unit \(j\) sums \(n_{\text{in}}\) terms; in the backward pass, unit \(i\)'s gradient sums \(n_{\text{out}}\) terms. Scaling by fan-in protects the forward signal; by fan-out, the gradients. He et al. showed either is fine for a network whose layers have similar widths, because the two products differ only by the ratio of the first and last widths.
Why does normalisation help optimisation? Scale invariance. If a layer's output is normalised, then scaling its weight matrix by any \(a > 0\) changes nothing downstream: \(L(aW) = L(W)\). Differentiate this identity:
- with respect to \(a\) at \(a = 1\): \(\langle\nabla L(W), W\rangle = 0\). The gradient is always orthogonal to the weights;
- with respect to \(W\): \(a\,\nabla L(aW) = \nabla L(W)\), so \(\nabla L(aW) = \nabla L(W)/a\). Larger weights get smaller gradients.
Together these mean the weights' direction is all that matters, and plain gradient descent automatically lowers its effective step size as \(\lVert W\rVert\) grows: the effective learning rate on the direction is \(\eta/\lVert W\rVert^2\). Because each step is orthogonal to \(W\), \(\lVert W\rVert\) can only grow, so without weight decay the effective learning rate decays on its own; with weight decay the norm settles at an equilibrium. The snippet in Build it confirms both identities numerically. This is why weight decay on normalised layers behaves like a learning-rate schedule (regularisation).
Why learn γ and β? Standardising forces every feature to mean 0 and variance 1, which may be the wrong representation (a sigmoid gate might need inputs far from 0). With \(\gamma = \sigma\) and \(\beta = \mu\) the layer can undo the normalisation entirely, so it loses no expressive power; but the scale is now a single explicit parameter rather than an emergent product of many weights, which is far easier for the optimiser to control.
Why mean subtraction may be unnecessary. Most of the benefit comes from controlling scale: the scale-invariance argument needs division by a norm, not centring. RMSNorm keeps the division and drops the centring, and in transformers that are already pre-normalised and residual, the mean carries little harm.
The maths¶
Variance of a linear layer. For \(z_j = \sum_{i=1}^{n} W_{ji}h_i\) with \(W_{ji}\) i.i.d., \(\mathbb{E}[W_{ji}] = 0\), \(\operatorname{Var}(W_{ji}) = \sigma_w^2\), and \(W\) independent of \(\mathbf{h}\):
Note \(\mathbb{E}[h^2]\), the second moment, not the variance: for ReLU outputs the mean is non-zero and counts.
Derivation: Xavier and He initialisation
Forward. Let \(q_\ell = \operatorname{Var}(z^{(\ell)})\). Then \(q_{\ell+1} = n_\ell\,\sigma_w^2\,\mathbb{E}[\phi(z^{(\ell)})^2]\).
- For a linear (or tanh-near-0) activation, \(\mathbb{E}[\phi(z)^2] = q_\ell\), so \(q_{\ell+1} = q_\ell\) requires \(\sigma_w^2 = 1/n_{\text{in}}\).
- For ReLU, with \(z \sim \mathcal{N}(0, q)\) symmetric, \(\mathbb{E}[\operatorname{ReLU}(z)^2] = \tfrac12\mathbb{E}[z^2] = q/2\), so \(\sigma_w^2 = 2/n_{\text{in}}\).
Backward. \(\delta_i^{(\ell)} = \phi'(z_i^{(\ell)})\sum_j W_{ji}\,\delta_j^{(\ell+1)}\) gives \(\operatorname{Var}(\delta^{(\ell)}) = n_{\ell+1}\,\sigma_w^2\,\mathbb{E}[\phi'^2]\operatorname{Var}(\delta^{(\ell+1)})\). For tanh near 0, \(\mathbb{E}[\phi'^2] \approx 1\), requiring \(\sigma_w^2 = 1/n_{\text{out}}\); for ReLU, \(\mathbb{E}[\phi'^2] = 1/2\), requiring \(\sigma_w^2 = 2/n_{\text{out}}\).
Compromise (Glorot). \(\sigma_w^2 = 2/(n_{\text{in}} + n_{\text{out}})\), the harmonic mean of the two conditions. A uniform distribution \(U(-a, a)\) has variance \(a^2/3\), so \(a = \sqrt{6/(n_{\text{in}} + n_{\text{out}})}\).
Checking the table. Through a ReLU layer the variance factor is \(n\sigma_w^2/2\). PyTorch's nn.Linear default, \(U(-1/\sqrt{n}, 1/\sqrt{n})\), has \(\sigma_w^2 = 1/(3n)\), so the factor is \(1/6\) and the standard deviation shrinks by \(1/\sqrt{6} \approx 0.41\) per layer: \(0.41^{49} \approx 10^{-19}\) over the 49 layers after the first, matching the measured fall from \(3.4 \times 10^{-1}\) to \(1.4 \times 10^{-20}\). Xavier's \(1/n\) gives \(1/\sqrt{2}\) per layer, \(0.707^{49} \approx 4 \times 10^{-8}\), matching \(5.8 \times 10^{-1} \to 3.1 \times 10^{-8}\).
Batch normalisation, forward (per feature, batch of \(B\)):
Derivation: the BatchNorm backward pass
Let \(g_n = \partial L/\partial y_n\) and \(s = \sqrt{\sigma^2 + \epsilon}\). Directly, \(\partial L/\partial\gamma = \sum_n g_n\hat{x}_n\) and \(\partial L/\partial\beta = \sum_n g_n\). With \(\hat{g}_n = \gamma g_n\) (the gradient at \(\hat{x}_n\)), every \(x_m\) affects every \(\hat{x}_n\) through \(\mu\) and \(\sigma^2\):
using \(\partial\mu/\partial x_m = 1/B\) and \(\partial\sigma^2/\partial x_m = 2(x_m - \mu)/B\) (the term through \(\mu\) in \(\sigma^2\) vanishes because \(\sum_n(x_n - \mu) = 0\)). Summing against \(\hat{g}_n\):
Two consequences you can check: \(\sum_m \partial L/\partial x_m = 0\) (shifting every input equally changes nothing) and \(\sum_m (\partial L/\partial x_m)\,\hat{x}_m = 0\) (scaling every input equally changes nothing). The gradient is projected onto the directions the normalisation does not remove.
LayerNorm uses the same formulas with the sum over the \(d\) features of one example instead of over the batch, and \(\boldsymbol{\gamma}, \boldsymbol{\beta} \in \mathbb{R}^d\). RMSNorm: \(y_i = \gamma_i\,x_i/\operatorname{rms}(\mathbf{x})\) with \(\operatorname{rms}(\mathbf{x}) = \sqrt{\tfrac1d\lVert\mathbf{x}\rVert^2 + \epsilon}\); its Jacobian is \(\frac{1}{\operatorname{rms}}\operatorname{diag}(\boldsymbol\gamma)\big(I - \frac{\mathbf{x}\mathbf{x}^\top}{d\,\operatorname{rms}^2}\big)\), a scaled projection that removes the radial component.
Scale invariance. If \(L(aW) = L(W)\) for all \(a > 0\), then \(\langle\nabla L(W), W\rangle = 0\) (Euler's theorem for degree-0 homogeneous functions) and \(\nabla L(aW) = a^{-1}\nabla L(W)\). Under gradient descent, \(\lVert W_{t+1}\rVert^2 = \lVert W_t\rVert^2 + \eta^2\lVert\nabla L(W_t)\rVert^2\), so the norm grows monotonically without weight decay.
Build it¶
First, signal propagation through a 50-layer ReLU MLP under five initialisations (this produced the table and figure above):
import numpy as np
rng = np.random.default_rng(0)
n, L, B = 512, 50, 256
inits = { # weight std for a square n x n layer
"N(0, 1)": 1.0,
"N(0, 0.01^2)": 0.01,
"PyTorch default": np.sqrt(1 / (3 * n)), # U(-1/sqrt(n), 1/sqrt(n))
"Xavier (1/n)": np.sqrt(1 / n),
"He (2/n)": np.sqrt(2 / n),
}
print(f"{'':16} std of activations at layer: grad ratio")
print(f"{'':16} {'1':>9} {'10':>9} {'25':>9} {'50':>9} layer1/layer50")
for name, s in inits.items():
Ws = [rng.normal(0, s, (n, n)) for _ in range(L)]
h, Zs, stds = rng.standard_normal((B, n)), [], []
for W in Ws:
z = h @ W; Zs.append(z); h = np.maximum(z, 0); stds.append(h.std())
g = rng.standard_normal((B, n)); top = np.linalg.norm(g)
for W, z in zip(reversed(Ws), reversed(Zs)):
g = (g * (z > 0)) @ W.T # back through ReLU, then the matmul
picks = [stds[i] for i in (0, 9, 24, 49)]
print(f"{name:16} " + " ".join(f"{v:9.1e}" for v in picks) + f" {np.linalg.norm(g)/top:9.1e}")
std of activations at layer: grad ratio
1 10 25 50 layer1/layer50
N(0, 1) 1.3e+01 1.0e+12 1.1e+30 9.8e+59 1.6e+60
N(0, 0.01^2) 1.3e-01 1.1e-08 1.2e-20 9.0e-41 1.4e-40
PyTorch default 3.4e-01 1.0e-04 1.2e-10 1.4e-20 3.0e-20
Xavier (1/n) 5.8e-01 2.9e-02 1.5e-04 3.1e-08 3.7e-08
He (2/n) 8.2e-01 9.1e-01 7.0e-01 6.3e-01 8.8e-01
Then BatchNorm by hand: the worked example, RMSNorm on the same numbers, a gradient check of the backward formula derived above, and the two scale-invariance identities.
import numpy as np
rng = np.random.default_rng(0)
eps = 1e-5
def bn_forward(x, gamma, beta): # x: (B, d); statistics over the batch axis
mu, var = x.mean(0), x.var(0)
xhat = (x - mu) / np.sqrt(var + eps)
return gamma * xhat + beta, (xhat, var)
def bn_backward(dy, gamma, cache):
xhat, var = cache; B = len(dy)
dxhat = dy * gamma
dx = (B * dxhat - dxhat.sum(0) - xhat * (dxhat * xhat).sum(0)) / (B * np.sqrt(var + eps))
return dx, (dy * xhat).sum(0), dy.sum(0) # dx, dgamma, dbeta
# worked example: one feature, batch of four
y, _ = bn_forward(np.array([[2.], [4.], [6.], [8.]]), 1.0, 0.0)
print("BatchNorm of [2, 4, 6, 8]:", np.round(y.ravel(), 3))
row = np.array([2., 4., 6., 8.])
print("RMSNorm of [2, 4, 6, 8]:", np.round(row / np.sqrt(np.mean(row**2) + eps), 3))
# gradient check of the backward formula, loss = sum(y * R) for a random R
x, gamma, beta = rng.normal(2, 3, (8, 5)), rng.normal(size=5), rng.normal(size=5)
R = rng.normal(size=(8, 5))
y, cache = bn_forward(x, gamma, beta)
dx, dgamma, dbeta = bn_backward(R, gamma, cache)
num = np.zeros_like(x)
for i in np.ndindex(x.shape):
xp, xm = x.copy(), x.copy(); xp[i] += 1e-6; xm[i] -= 1e-6
num[i] = ((bn_forward(xp, gamma, beta)[0] - bn_forward(xm, gamma, beta)[0]) * R).sum() / 2e-6
print(f"BN backward vs numeric: max abs diff {np.abs(dx - num).max():.1e}")
print(f"largest |sum of dx over the batch| (should be ~0): {np.abs(dx.sum(0)).max():.1e}")
# scale invariance: a loss of BN(h @ W) does not change when W is scaled
h, W, T = rng.normal(size=(16, 5)), rng.normal(size=(5, 5)), rng.normal(size=(16, 5))
def loss_grad(W): # loss = sum(BN(hW) * T)
y, cache = bn_forward(h @ W, 1.0, 0.0)
dz, _, _ = bn_backward(T, 1.0, cache)
return (y * T).sum(), h.T @ dz
(L1, G1), (L2, G2) = loss_grad(W), loss_grad(2 * W)
cos = np.sum(G1 * W) / (np.linalg.norm(G1) * np.linalg.norm(W))
print(f"loss at W {L1:.6f}, at 2W {L2:.6f}")
print(f"cos(grad, W) = {cos:.1e} |grad at 2W| / |grad at W| = {np.linalg.norm(G2)/np.linalg.norm(G1):.3f}")
BatchNorm of [2, 4, 6, 8]: [-1.342 -0.447 0.447 1.342]
RMSNorm of [2, 4, 6, 8]: [0.365 0.73 1.095 1.461]
BN backward vs numeric: max abs diff 8.0e-10
largest |sum of dx over the batch| (should be ~0): 2.5e-16
loss at W 3.887183, at 2W 3.887204
cos(grad, W) = 1.1e-06 |grad at 2W| / |grad at W| = 0.500
The loss changes in the sixth digit and the cosine is \(10^{-6}\) rather than exactly 0 only because of \(\epsilon\) in the denominator; doubling \(W\) halves the gradient exactly as the identity predicts.
Things to try
- Add a row to the initialisation experiment with orthogonal matrices scaled by \(\sqrt{2}\) (
np.linalg.qrof a Gaussian matrix). Compare the spread of singular values of the end-to-end Jacobian with He's Gaussian version. - Insert a BatchNorm (no γ, β) after every linear layer of the \(\mathcal{N}(0, 0.01^2)\) network. The activations at layer 50 should now have unit scale despite the terrible initialisation.
- Implement LayerNorm's backward pass by transposing the BatchNorm code (statistics over axis 1) and gradient-check it.
- Train the spiral MLP from backpropagation with ten hidden layers using Xavier and then He initialisation, and plot the per-layer gradient norms after the first backward pass.
- Run gradient descent on the scale-invariant loss for 1,000 steps without weight decay and plot \(\lVert W\rVert\): it only grows. Add weight decay and watch it settle.
Check yourself¶
Why can't all weights start at the same value, but biases can?
Identical incoming weights make all units in a layer compute the same function and receive the same gradient, so they never become different. Biases are added after the random weights have already made the units' inputs different, so zero biases do not reintroduce the symmetry.
A 512-wide layer has weights with standard deviation 0.01. By what factor does it scale the activations' standard deviation (ignore the activation function)?
\(\sqrt{n}\,\sigma_w = \sqrt{512} \times 0.01 \approx 0.226\): each layer shrinks the signal by about 4.4×.
Derive He initialisation in two lines.
\(\operatorname{Var}(z^{(\ell+1)}) = n\sigma_w^2\,\mathbb{E}[\operatorname{ReLU}(z^{(\ell)})^2] = n\sigma_w^2\operatorname{Var}(z^{(\ell)})/2\). Setting the factor \(n\sigma_w^2/2 = 1\) gives \(\sigma_w^2 = 2/n\).
Your model works in training mode but gives garbage after model.eval(). Name two BatchNorm-related causes.
The running mean and variance were computed on data with different statistics from the evaluation data (for example a domain shift, or very small or unshuffled training batches), or the running statistics were never properly updated (trained with frozen BN, or momentum misconfigured). A third: the model is evaluated with batch size 1 in training mode, so statistics come from a single example.
Why do transformers use LayerNorm or RMSNorm rather than BatchNorm?
Batch statistics are awkward for variable-length sequences and padding, meaningless during autoregressive generation one token at a time, noisy at the small per-device batch sizes used for large models, and they couple examples in a batch. Per-token normalisation across features has none of these problems and behaves identically in training and inference.
What problem does pre-LN solve relative to post-LN, and what does it cost?
Post-LN puts a normalisation on the residual path, so gradients near the output are large at initialisation and training needs a warm-up to be stable. Pre-LN leaves the residual stream as a clean identity path, so gradients flow evenly and training is stable; the cost is that the residual stream's scale grows with depth (each block adds to it unnormalised), handled with a final normalisation layer and sometimes with residual scaling.
Hard: show that a layer followed by normalisation has a gradient orthogonal to its weights, and explain what that does to the effective learning rate.
The loss is invariant to \(W \to aW\): \(L(aW) = L(W)\). Differentiating in \(a\) at \(a = 1\) gives \(\langle\nabla L(W), W\rangle = 0\); differentiating in \(W\) gives \(\nabla L(aW) = \nabla L(W)/a\). A step of size \(\eta\) changes the direction of \(W\) by roughly \(\eta\lVert\nabla L\rVert/\lVert W\rVert\), and \(\lVert\nabla L\rVert \propto 1/\lVert W\rVert\), so the angular step is \(\propto \eta/\lVert W\rVert^2\). Since steps are orthogonal to \(W\), \(\lVert W\rVert\) grows each step, shrinking the effective learning rate; weight decay counteracts this and sets an equilibrium.
Hard: why does μP exist if He initialisation already keeps activations at unit scale at any width?
He initialisation fixes the forward and backward signal at step 0. It says nothing about the size of updates: under standard parameterisation with a fixed learning rate, the change in a layer's output caused by one gradient step scales with width (some layers' updates blow up, others vanish as width grows), so the optimal learning rate shifts with model size. μP rescales initialisations and per-layer learning rates so that updates also change activations by a width-independent amount, which is what lets hyperparameters tuned on a small model transfer to a large one.
Go deeper¶
Papers
- Understanding the difficulty of training deep feedforward neural networks — Glorot and Bengio, AISTATS 2010. Saturation at initialisation diagnosed, Xavier initialisation derived. Read the activation histograms.
- Delving deep into rectifiers — He et al., 2015. Section 2.2 is He initialisation in a page and a half.
- Exact solutions to the nonlinear dynamics of learning in deep linear neural networks — Saxe, McClelland and Ganguli, 2013. Orthogonal initialisation and depth-independent learning times.
- Resurrecting the sigmoid in deep learning through dynamical isometry — Pennington, Schoenholz and Ganguli, 2017. Why the spectrum of the Jacobian, not just its average, matters.
- Batch normalization — Ioffe and Szegedy, 2015. Algorithms 1 and 2 are the whole method; the "covariate shift" story has since been revised.
- How does batch normalization help optimization? — Santurkar et al., 2018. The smoothing explanation and the experiment that undercut covariate shift.
- Layer normalization — Ba, Kiros and Hinton, 2016. Including its analysis of invariance properties of each normalisation scheme.
- Root mean square layer normalization — Zhang and Sennrich, 2019. RMSNorm.
- Group normalization — Wu and He, 2018. Figure 2 is the clearest picture of all the normalisation axes.
- On layer normalization in the transformer architecture — Xiong et al., 2020. Why post-LN needs warm-up and pre-LN does not.
- Fixup initialization — Zhang, Dauphin and Ma, 2019. Residual networks without normalisation, to 10,000 layers.
- Tensor Programs V: tuning large neural networks via zero-shot hyperparameter transfer — Yang et al., 2022. μP and μTransfer.
- Transformers without normalization — Zhu et al., 2025. Dynamic Tanh as a drop-in replacement for LayerNorm.
Videos and lectures
- Building makemore Part 3: Activations & Gradients, BatchNorm — Andrej Karpathy. Fixing a badly initialised network step by step, then deriving and implementing BatchNorm; the best practical hour on this page's topic.
- Building makemore Part 4: Becoming a Backprop Ninja — Andrej Karpathy. Derives the BatchNorm backward pass by hand, matching the derivation above.
Articles and documentation
- CS231n: Neural Networks Part 2, setting up the data and the model — Stanford. Data preprocessing, weight initialisation and batch normalisation in practice.
- torch.nn.init — PyTorch docs. Every initialiser, the gain table, and the fan-in/fan-out modes.
Courses and books
- Understanding Deep Learning — Simon Prince. Chapter 7 (initialisation, with exploding and vanishing gradients) and chapter 11 (residual networks and batch normalisation).
- The Principles of Deep Learning Theory — Roberts, Yaida and Hanin, 2021. The effective-theory treatment of initialisation and criticality, for when you want the full physics-style derivation.
Where this leads¶
- Residual connections and very deep networks — the additive path that, with normalisation, makes 100+ layers routine.
- Optimisers — learning rates, warm-up and weight decay, which interact with normalisation through scale invariance.
- The transformer block — pre-norm RMSNorm in its natural habitat.
- A recipe for training (and debugging) networks — activation and gradient histograms as a diagnostic habit.