Skip to content

Module 09

Anurag Prasad edited this page Nov 9, 2026 · 10 revisions

Module 09 — Weight Initialization, Normalization and Gradient Flow

⬅️ Module 08 · 🗺️ Curriculum · 🏠 Home · Module 10 ➡️

Level: Intermediate · Prerequisites: Modules 05, 07, 08 · Time: about 6–7 hours

On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading


Overview and learning goals

A deep network is a long product of matrices and nonlinearities. Unless each layer roughly preserves the scale of signals going forward and gradients going backward, activations and gradients shrink to zero or blow up exponentially with depth. This module explains how initialisation, normalisation and residual connections keep training stable.

After this module you should be able to:

  • explain symmetry breaking and derive Xavier and He initialisation from variance arguments;
  • analyse vanishing/exploding signals through depth;
  • write BatchNorm, LayerNorm, GroupNorm, InstanceNorm and RMSNorm and say which axes each normalises;
  • explain train/eval differences and small-batch issues of BatchNorm;
  • explain why residual connections create identity gradient paths.

Beginner: the big picture

Imagine passing a message through 50 people where each person either halves or doubles its volume: after 50 steps it is silent or deafening. Layers act the same way. Good initialisation sets each layer's gain to about 1; normalisation re-centres and re-scales activations on the fly; residual connections give the signal a "highway" that bypasses layers.

Forward signal vs depth for different initialisations

Figure 9.1 — Mean squared activation in a 40-layer, width-512 ReLU network. He init ($\sqrt{2/d}$) stays at scale 1; Xavier ($\sqrt{1/d}$) halves the second moment per layer ($2^{-40}\approx10^{-12}$); a fixed std of 0.01 vanishes and 0.1 explodes. Original figure (figures/make_figs_2.py).

flowchart LR
    X["x"] --> F["F(x): conv/linear, norm, activation"]
    X --> ID["identity shortcut"]
    F --> ADD(("+"))
    ID --> ADD
    ADD --> Y["y = x + F(x)"]
Loading

Core concepts and derivations

Zero/random initialisation and symmetry breaking

All-zero (or all-equal) weights give identical neurons identical gradients, so they never differentiate. Random initialisation breaks the symmetry; biases may start at zero.

Variance analysis: Xavier, He and LeCun

For $z=\sum_{i=1}^{n_{in}}w_ix_i$ with independent zero-mean $w_i,x_i$: $\mathrm{Var}(z)=n_{in}\mathrm{Var}(w)\mathrm{Var}(x)$. To keep $\mathrm{Var}(z)=\mathrm{Var}(x)$ choose $\mathrm{Var}(w)=1/n_{in}$ (LeCun). For the backward pass the analogous condition is $1/n_{out}$; Xavier/Glorot (2010) compromises, $\mathrm{Var}(w)=\frac2{n_{in}+n_{out}}$, assuming a roughly linear activation (tanh near 0).

He/Kaiming (2015) for ReLU: if $z_{\ell-1}$ is symmetric with variance $\sigma^2$, then $\mathbb{E}[\mathrm{ReLU}(z)^2]=\frac12\sigma^2$, so

$$\mathrm{Var}(z_\ell)=n_{in}\mathrm{Var}(w)\cdot\frac12\mathrm{Var}(z_{\ell-1})\ \Longrightarrow\ \mathrm{Var}(w)=\frac{2}{n_{in}} .$$

Per layer, the second moment is multiplied by $g=\frac12n_{in}\mathrm{Var}(w)$; over $L$ layers by $g^L$ — exponential unless $g=1$. With Xavier and ReLU, $g=\frac12$ (Figure 9.1).

Forward variance and backward gradient variance

The backward recursion $\mathbf{\delta}^{(\ell)}=(W^\top\mathbf{\delta}^{(\ell+1)})\odot\phi'$ has the same multiplicative structure, so gradient magnitude also scales like $g^{L-\ell}$. Initialising for the forward pass ("fan-in") or backward pass ("fan-out") are both valid; the choice rarely matters if layers are similar in width.

Vanishing and exploding signal propagation

For a linear chain the signal scales with the product of spectral norms: $\lVert W_L\cdots W_1\mathbf{x}\rVert\le \prod\sigma_{\max}(W_\ell)\lVert\mathbf{x}\rVert$. Gains persistently below 1 vanish; above 1 explode. Saturating activations add a derivative factor $\le\frac14$ (sigmoid), compounding the problem.

BatchNorm

For a mini-batch of activations of one feature, with batch mean $\mu_B$ and variance $\sigma_B^2$:

$$\hat x=\frac{x-\mu_B}{\sqrt{\sigma_B^2+\epsilon}},\qquad y=\gamma\hat x+\beta,$$

with learnable scale $\gamma$ and shift $\beta$ (so the layer can undo normalisation if useful). Statistics are per feature/channel across batch (and spatial) axes. During training running averages $\mu_{run}\leftarrow(1-m)\mu_{run}+m\mu_B$ are maintained; at evaluation these fixed statistics are used, so outputs do not depend on other examples in the batch. Benefits: higher learning rates, less sensitivity to initialisation, mild regularisation from batch noise. Santurkar et al. (2018) argue the main effect is smoothing the loss landscape rather than reducing "internal covariate shift".

LayerNorm and normalisation axes

LayerNorm normalises across the features of one example (Ba et al. 2016): $\hat x_j=(x_j-\mu)/\sqrt{\sigma^2+\epsilon}$ with $\mu,\sigma^2$ over the feature axis. It is independent of batch size and identical in train/eval — hence its use in RNNs and Transformers.

Method Statistics computed over Typical use
BatchNorm batch (+ spatial), per channel CNNs with large batches
LayerNorm all features of one sample Transformers, RNNs
InstanceNorm spatial axes, per sample & channel style transfer
GroupNorm groups of channels, per sample small-batch vision
RMSNorm RMS over features (no mean) LLMs

GroupNorm, InstanceNorm and RMSNorm

GroupNorm (Wu & He 2018) splits $C$ channels into $G$ groups and normalises within each; $G=1$ resembles LayerNorm, $G=C$ is InstanceNorm. RMSNorm (Zhang & Sennrich 2019) drops mean-centring: $y_j=\frac{x_j}{\sqrt{\frac1d\sum_ix_i^2+\epsilon}}\,g_j$ — cheaper and as effective in LLMs.

Train/evaluation behaviour and small-batch issues

BatchNorm with tiny batches has noisy statistics and a train/test mismatch; use GroupNorm/LayerNorm, or synchronised BatchNorm across devices. Remember model.eval() before inference, and beware stale running statistics after fine-tuning on a new domain.

Residual connections and identity gradient paths

A residual block computes $\mathbf{y}=\mathbf{x}+F(\mathbf{x})$ (He et al. 2016). Its Jacobian is $I+\partial F/\partial\mathbf{x}$, so unrolling $L$ blocks:

$$\frac{\partial L}{\partial\mathbf{x}_0}=\frac{\partial L}{\partial\mathbf{x}_L}\prod_{\ell=1}^{L}\Bigl(I+\frac{\partial F_\ell}{\partial\mathbf{x}_{\ell-1}}\Bigr)=\frac{\partial L}{\partial\mathbf{x}_L}\Bigl(I+\sum_\ell\frac{\partial F_\ell}{\partial\mathbf{x}}+\cdots\Bigr).$$

The leading term $I$ is a direct, unattenuated gradient path from the loss to every layer. Residual nets behave like ensembles of paths of different lengths (Veit et al. 2016). In Transformers, pre-LN ($\mathbf{x}+F(\mathrm{LN}(\mathbf{x}))$) keeps the identity path clean and trains stably without long warm-up; post-LN ($\mathrm{LN}(\mathbf{x}+F(\mathbf{x}))$) normalises the shortcut and is harder to train deep (Xiong et al. 2020).

Worked example

He init width. For $n_{in}=512$: $\sigma_w=\sqrt{2/512}=0.0625$; Xavier with equal widths gives $\sqrt{1/512}=0.0442$.

BatchNorm on one channel with batch values $(1,2,3,6)$: $\mu=3$; deviations $(-2,-1,0,3)$; $\sigma^2=(4+1+0+9)/4=3.5$, $\sigma=1.871$; $\hat x=(-1.069,-0.535,0,1.604)$. With $\gamma=2,\beta=1$: $y=(-1.138,-0.069,1,4.207)$. LayerNorm instead takes the mean and variance over the features of each row, so the result for one example never depends on the rest of the batch.

Implementation

import numpy as np

def batchnorm(x, gamma, beta, eps=1e-5):          # x: (B, C); stats over batch axis
    mu, var = x.mean(0), x.var(0)
    return gamma * (x - mu) / np.sqrt(var + eps) + beta

def layernorm(x, gamma, beta, eps=1e-5):          # stats over feature axis
    mu, var = x.mean(-1, keepdims=True), x.var(-1, keepdims=True)
    return gamma * (x - mu) / np.sqrt(var + eps) + beta

def rmsnorm(x, g, eps=1e-6): return g * x / np.sqrt((x ** 2).mean(-1, keepdims=True) + eps)

x = np.array([[1.], [2.], [3.], [6.]]); print(batchnorm(x, 1., 0.).ravel())   # [-1.069 -0.535 0 1.604]
import torch.nn as nn
nn.init.kaiming_normal_(layer.weight, nonlinearity='relu')    # He
nn.init.xavier_uniform_(layer.weight)                          # Glorot
# model.train() uses batch stats; model.eval() uses running stats

Advanced topics

  • Dynamical isometry and mean-field theory: choose initialisations (e.g. orthogonal) so the input–output Jacobian has singular values near 1, enabling trainable networks of 10,000 layers.
  • Fixup/SkipInit/ReZero: residual networks without normalisation by scaling branches at init.
  • $\mu$P (maximal update parametrisation): scales init and learning rates with width so hyperparameters transfer.
  • Weight normalisation, spectral normalisation (GANs, Module 19), QK-norm in attention.
  • Initialising residual branches to zero (final norm scale 0) makes each block start as the identity; scaling by $1/\sqrt{2L}$ in deep Transformers.
  • Normalisation and optimisation: BN makes loss scale-invariant in weights, giving an effective learning rate that depends on $\lVert w\rVert$ (interaction with weight decay).

Pitfalls and best practices

  • Forgetting model.eval(): BatchNorm keeps using batch statistics (noisy, batch-dependent predictions).
  • BatchNorm with batch size 1–4, or with sequences of varying padding.
  • Applying weight decay to $\gamma,\beta$ and biases.
  • Using Xavier with ReLU for very deep plain nets; use He.
  • Normalising inputs but forgetting the same preprocessing at inference.

Conceptual questions and answers

Q1. Derive He initialisation.

Show answer

$\mathrm{Var}(z_\ell)=n_{in}\mathrm{Var}(w)\mathbb{E}[x^2]$ and for $x=\mathrm{ReLU}(z_{\ell-1})$ with symmetric $z_{\ell-1}$, $\mathbb{E}[x^2]=\frac12\mathrm{Var}(z_{\ell-1})$. Requiring $\mathrm{Var}(z_\ell)=\mathrm{Var}(z_{\ell-1})$ gives $\mathrm{Var}(w)=2/n_{in}$.

Q2. Why does zero initialisation fail?

Show answer

All neurons in a layer compute and receive the same values, so they stay identical; with ReLU, zero weights also give zero gradients to earlier layers.

Q3. Why does BatchNorm behave differently in train and eval mode?

Show answer

Training normalises with the current batch's statistics; evaluation uses running averages so that each prediction is independent of the other examples. Mismatch between the two causes degraded accuracy with small or shifted batches.

Q4. Why do Transformers use LayerNorm rather than BatchNorm?

Show answer

Sequence lengths and padding vary, batch statistics are noisy for token positions, and LayerNorm is independent of batch size and identical at train and test time.

Q5. Why do residual connections make very deep networks trainable?

Show answer

The Jacobian $I+\partial F/\partial x$ contains an identity term, so gradients reach early layers without passing through any weight matrix or nonlinearity.

Q6. What is the role of $\gamma$ and $\beta$ in BatchNorm?

Show answer

They restore representational power: the network can learn any scale and shift, including undoing the normalisation if that is optimal.

Q7. Pre-LN versus post-LN: which is more stable and why?

Show answer

Pre-LN: the residual stream is never normalised inside the block, preserving the identity gradient path, so gradients are better-behaved at initialisation and warm-up requirements are milder; post-LN can have large gradients near the output.

Q8. When do you choose GroupNorm?

Show answer

For vision models with small per-device batches (detection, segmentation, video) where BatchNorm statistics would be unreliable.

Q9. How does RMSNorm differ from LayerNorm?

Show answer

It omits mean subtraction (and usually the bias), rescaling only by the root-mean-square; this is cheaper and works comparably in practice.

Sources and further reading

  • Glorot, X., & Bengio, Y. (2010). Understanding the difficulty of training deep feedforward neural networks. AISTATS.
  • He, K., Zhang, X., Ren, S., & Sun, J. (2015). Delving deep into rectifiers: surpassing human-level performance on ImageNet classification. ICCV. arXiv:1502.01852.
  • Ioffe, S., & Szegedy, C. (2015). Batch normalization: accelerating deep network training by reducing internal covariate shift. ICML. arXiv:1502.03167.
  • Ba, J. L., Kiros, J. R., & Hinton, G. E. (2016). Layer normalization. arXiv:1607.06450.
  • Wu, Y., & He, K. (2018). Group normalization. ECCV.
  • Ulyanov, D., Vedaldi, A., & Lempitsky, V. (2016). Instance normalization. arXiv:1607.08022.
  • Zhang, B., & Sennrich, R. (2019). Root mean square layer normalization. NeurIPS.
  • He, K., Zhang, X., Ren, S., & Sun, J. (2016). Deep residual learning for image recognition. CVPR. arXiv:1512.03385.
  • Santurkar, S., et al. (2018). How does batch normalization help optimization? NeurIPS.
  • Xiong, R., et al. (2020). On layer normalization in the Transformer architecture. ICML.
  • Veit, A., Wilber, M., & Belongie, S. (2016). Residual networks behave like ensembles of relatively shallow networks. NeurIPS.
  • Pennington, J., Schoenholz, S., & Ganguli, S. (2017). Resurrecting the sigmoid in deep learning through dynamical isometry. NeurIPS.

⬅️ Module 08 · 🗺️ Curriculum · 🏠 Home · Module 10 ➡️

🎓 Deep Learning Hub

🏠 Home · 🗺️ Curriculum · 🧭 Learning paths

❓ Question bank · 📖 Glossary · 📚 References

Jump to module:

01 02 03 04 05 06 07 08 09 10 11 12

13 14 15 16 17 18 19 20 21 22 23 24

Part 1 · Mathematical foundations
Part 2 · Neural network fundamentals
Part 3 · Training deep networks
Part 4 · Core architectures
Part 5 · Representation and generative learning
Part 6 · Specialised, modern and responsible deep learning
Reference and meta

Clone this wiki locally