Layer Normalization

2 min read

Layer normalization normalizes across the feature dimension for each individual sample:

LayerNorm(x)=γxμσ2+ϵ+β\text{LayerNorm}(\mathbf{x}) = \gamma \odot \frac{\mathbf{x} - \mu}{\sqrt{\sigma^2 + \epsilon}} + \beta

where μ\mu and σ2\sigma^2 are the mean and variance computed over the features of a single input, and γ,β\gamma, \beta are learned scale and shift parameters.

LayerNorm vs BatchNorm:

BatchNormLayerNorm
Normalizes overBatch dimensionFeature dimension
Depends on batchYes (problematic for small batches)No
At inferenceUses running statisticsSame as training
Dominant inCNNsTransformers

Why transformers use LayerNorm:

  • Sequences have variable length → batch statistics across positions are meaningless
  • No dependence on batch size → works with any batch, including batch size 1
  • Stabilizes the residual stream by keeping activations on a consistent scale

Pre-Norm vs Post-Norm:

  • Post-Norm (original transformer): x+LayerNorm(Sublayer(x))x + \text{LayerNorm}(\text{Sublayer}(x)) — harder to train deep models
  • Pre-Norm (GPT-2+, standard now): x+Sublayer(LayerNorm(x))x + \text{Sublayer}(\text{LayerNorm}(x)) — more stable gradients, enables deeper models

RMSNorm — a simplified variant that skips the mean subtraction and the bias β\beta, dividing only by the root-mean-square:

RMSNorm(x)=xRMS(x)+ϵγ,RMS(x)=1Di=1Dxi2\text{RMSNorm}(\mathbf{x}) = \frac{\mathbf{x}}{\text{RMS}(\mathbf{x}) + \epsilon} \odot \gamma, \qquad \text{RMS}(\mathbf{x}) = \sqrt{\tfrac{1}{D}\textstyle\sum_{i=1}^{D} x_i^2}

Forcing unit RMS destroys learned scale, so the per-dimension γRD\gamma \in \mathbb{R}^D gives it back: γi>1\gamma_i > 1 amplifies dimension ii, γi0\gamma_i \approx 0 kills it. Cheaper than LayerNorm (no mean, no β\beta) and equally stable in practice — used in LLaMA and other modern LLMs.

See also: Batch Normalization, Residual Connections, Self-Attention

Linked from