Foundations to Frontier
Tests
E. Deep Learning › E5 Normalization Layers (one page each)

Layer Normalization

Layer normalisation standardises each example over its own features, so it needs no batch statistics and behaves identically in training and inference at any batch size. That makes it the normalisation of transformers and recurrent networks. This page covers the computation, where it sits in a transformer block (pre-LN versus post-LN), why it suits sequence models, and how it differs from BatchNorm. In the exercises you implement and gradient-check LayerNorm and confirm each example's output ignores the rest of the batch, then compare it with BatchNorm in a deep MLP and find, honestly, that it beat BatchNorm with batches of 4 but did not share BatchNorm's tolerance of large learning rates in this setting.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Normalise each example on its own

BatchNorm standardises each feature across the examples in a batch, so every example’s result depends on the others. Layer normalisation instead standardises each example across its own features: one mean and one spread per example. Nothing depends on the batch, so a single example at inference is processed exactly as during training, and sequences of any length are easy.

Normalisation layers: which values share a mean and variance?
channels →ex 1ex 2ex 3ex 4ex 5ex 6
Click a cell. Highlighted cells (16 values each) are pooled to compute the mean and variance used to normalise it.
per-example mean / sd after normalising0.00/1.00 0.00/1.00 0.00/1.00 0.00/1.00 0.00/1.00 0.00/1.00
per-channel mean / sd after normalising0.63/0.25 0.59/0.76 0.05/1.18 -0.92/0.23 -1.14/0.66 -0.37/1.01 0.45/0.23 0.70/0.81
BatchNorm noise: with batch size 6, a channel's batch mean is off from its population mean by 0.288 on average.
BatchNorm makes every channel have mean 0 and sd 1 across the batch, but each example's own statistics still vary, and its statistics depend on which other examples are in the batch: shrink N to 1 or 2 and watch the noise grow. LayerNorm, InstanceNorm and GroupNorm compute everything within one example, so they work the same at any batch size and at test time; they differ in which channels they pool.
Why engineers care

Every transformer (GPT, BERT, ViT, and the language and vision models built on them) uses LayerNorm or its cheaper cousin RMSNorm. Where it sits in the block (before or after attention) decides whether very deep transformers train stably.

📝 Quick check (Level 0)
0/3 answered
  1. 1. LayerNorm computes statistics over…
  2. 2. LayerNorm at inference…
  3. 3. LayerNorm is the standard normalisation in…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Per example x ∈ ℝᵈ: μ = mean(x), σ² = var(x), y = γ ⊙ (x − μ)/√(σ² + ε) + β, with γ, β ∈ ℝᵈ.
  • Example: x = (1, 3): μ = 2, σ = 1, normalised (−1, 1). For x = (10, 30) the result is the same: scaling and shifting a whole example does not change its output.
  • Parameters: 2d, for example 1536 for d = 768.
  • In a transformer, statistics are per token, over the model dimension.
  • Placement:
    • Post-LN (original Transformer): y = LN(x + f(x)).
    • Pre-LN (GPT-2 onward): y = x + f(LN(x)).
    • Example with x = (1, 3), f(z) = 2z: pre-LN gives (−1, 5); post-LN gives (−1, 1).
📝 Quick check (Level 1)
0/3 answered
  1. 1. LN of (10, 30):
  2. 2. LN parameters for d = 768:
  3. 3. Pre-LN computes…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

LayerNorm in code

Exercise 1.

  • The analytic gradient matched finite differences to 10⁻⁹.
  • Replacing the other four examples in the batch with large random values left the first example’s output unchanged.
  • Scaling one example by 4 and shifting it by −9 left its output unchanged.

Practice.

  • nn.LayerNorm(d) normalises over the last dimension. In transformers, use pre-LN with a final LN after the last block.
  • Post-LN transformers usually need learning-rate warm-up to train stably; pre-LN ones are more forgiving (Xiong et al., 2020).
  • Do not decay γ and β; initialise γ = 1, β = 0.
  • For CNNs, LayerNorm over channels is used in ConvNeXt; GroupNorm (E5-4) is the usual batch-free alternative.
class Block(torch.nn.Module):
    def __init__(self, d): super().__init__(); self.ln = torch.nn.LayerNorm(d); self.mlp = torch.nn.Sequential(torch.nn.Linear(d, 4 * d), torch.nn.GELU(), torch.nn.Linear(4 * d, d))
    def forward(self, x): return x + self.mlp(self.ln(x))     # pre-LN
🐍 Exercise 1: LayerNorm forward and backward
Implement LayerNorm's forward and backward passes, gradient-check them, and verify independence from the rest of the batch.
📝 Quick check (Level 2)
0/3 answered
  1. 1. nn.LayerNorm(d) normalises over…
  2. 2. Post-LN transformers usually need…
  3. 3. ConvNeXt uses…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Batch independence. LayerNorm’s output for one example is a function of that example alone. There are no running statistics, no train–test discrepancy, and no leakage of information between examples, which matters for autoregressive models and for distributed training with tiny per-device batches.

Invariances. LN is invariant to scaling and shifting each example’s whole feature vector, and to scaling the incoming weight matrix as a whole. It is not invariant to scaling individual input features (BatchNorm is) (Ba, Kiros and Hinton, 2016).

Pre-LN versus post-LN. In post-LN, the residual stream passes through LN after every block, so gradients near the output are large at initialisation and early updates can be unstable without warm-up. In pre-LN the residual path is an identity from input to output and gradients are well-behaved (Xiong et al., 2020). Pre-LN’s own drawback is that later blocks’ contributions can shrink relative to the growing residual stream; DeepNorm and other schemes rescale residuals to address this.

Why not BatchNorm in transformers? Sequences vary in length and padding, statistics across tokens of different examples are not meaningful, and BN’s batch statistics fluctuate strongly in NLP data (Shen et al., 2020).

📝 Quick check (Level 3)
0/3 answered
  1. 1. LN is invariant to scaling…
  2. 2. In pre-LN, the residual path is…
  3. 3. BatchNorm struggles in NLP partly because of…

Level 4: Expert

★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.

LayerNorm versus BatchNorm in a deep MLP

History.

  • J. Ba, J. Kiros and G. Hinton (2016) introduced LayerNorm for recurrent networks.
  • A. Vaswani et al. (2017) used post-LN in the Transformer; A. Radford et al. (2019) used pre-LN in GPT-2.
  • R. Xiong et al. (2020) analysed pre- versus post-LN.
  • Z. Liu et al. (2022) used LayerNorm in ConvNeXt.

Exercise 2. The 8-layer ReLU MLP of E5-1 on spirals with no normalisation, BatchNorm or LayerNorm before each ReLU. Test accuracy for three seeds:

normalisation batch 4, η = 0.01 batch 32, η = 0.1
none 0.966, 0.757, 0.992 0.340, 0.331, 0.320
BatchNorm 0.710, 0.589, 0.620 0.998, 0.995, 1.000
LayerNorm 0.675, 0.826, 0.796 0.340, 0.800, 0.320
  • With batches of 4, LayerNorm beat BatchNorm (0.77 against 0.64 on average), as its batch independence predicts.
  • But it did not give BatchNorm’s tolerance of a large learning rate here: at η = 0.1 it failed in 2 of 3 runs.
  • With small batches the plain network was best (0.91 on average): in this small MLP neither normalisation was needed at a small learning rate.
  • Lesson: LayerNorm’s value is batch independence; its reported optimisation benefits come from transformers and recurrent networks, which this small MLP does not test.
🐍 Exercise 2 (research): LayerNorm versus BatchNorm
Train a deep MLP with no normalisation, BatchNorm and LayerNorm at a small batch and at a large learning rate, and compare test accuracy.

LayerNorm in AI, robotics and aerospace

  • Transformers for language, vision, planning and multimodal robotics policies use LayerNorm or RMSNorm in every block.
  • Recurrent models of telemetry and control use LayerNorm inside LSTM and GRU cells.
  • Online inference with one sample at a time, as on a robot, needs batch-independent normalisation.

References

  1. J. L. Ba, J. R. Kiros, G. E. Hinton (2016). “Layer normalization.” arXiv:1607.06450.
  2. R. Xiong et al. (2020). “On layer normalization in the Transformer architecture.” Proc. ICML.
  3. S. Shen, Z. Yao, A. Gholami, M. Mahoney, K. Keutzer (2020). “PowerNorm: rethinking batch normalization in transformers.” Proc. ICML.
  4. A. Vaswani et al. (2017). “Attention is all you need.” Advances in NeurIPS.