LayerNorm vs. RMSNorm in Transformer Architectures

Medium · Machine Learning · Software Engineer · Technical Screen

Prompt

Contrast LayerNorm and RMSNorm inside a transformer layer: state both mathematical definitions, analyze what changes when mean centering is removed, and explain the practical reasons modern transformer designs often favor RMSNorm.

Assume normalization runs independently across the hidden channel dimension of each individual token, comparing standard affine LayerNorm (learned gain and bias) against scale-only RMSNorm (learned gain without bias). Keep in mind that real-world implementations may differ in sublayer placement (pre-norm vs. post-norm), whether an additive bias is kept, where the numerical stability constant eps sits, and which floating-point precision handles the reductions.

Scope & Expectations

  • Formulas and normalization axis: Define affine LayerNorm and scale-only RMSNorm over a single token's hidden vector, clarify how their statistics relate algebraically, and state where normalization sits in a transformer block.
  • Impact of dropping mean subtraction: Compare shift and scale invariances, output mean behavior, backward-pass gradient geometry, and how residual-stream offsets interact with downstream projections.
  • Systems and training trade-offs: Explain why eliminating centering makes RMSNorm appealing for GPU memory bandwidth, kernel fusion, parameter count, and deep-network optimization.
  • Floating-point stability: Discuss how fp16/bf16 reductions, variance cancellation, and eps placement affect numerical accuracy.

Step-by-step walkthrough

  1. Clarify the normalization axis and block placement

    In a transformer, activations have shape [batch, seq_len, d], where d is the model's hidden width. A hidden vector is the slice of d numbers representing one token at one layer. Both LayerNorm and RMSNorm normalize across that last axis (d) independently for every single token. Neither shares statistics across examples in the batch or across sequence positions. By contrast, BatchNorm (Batch Normalization) averages features across different examples in a batch and tracks running averages from training to reuse at inference; avoiding batch statistics is why LayerNorm and RMSNorm behave identically during training and single-token generation at any sequence length.

    Placement inside the transformer block determines what the normalizer actually sees. Every modern transformer passes tokens along a residual stream, an un-normalized main pathway where each attention or feed-forward sublayer adds its output (x = x + Sublayer(...)). Two standard layouts exist: pre-norm applies normalization to a branch copy right before each sublayer reads it, whereas post-norm applies normalization on the main pathway after adding the sublayer's output.

    Pre-norm block (LLaMA, Mistral 7B, GPT-2/3)      Post-norm block (original 2017 Transformer)
        x (residual stream, un-normalized)               x
        |---------------+                                |---------------+
        |               v                                |               v
        |            Norm1(x)                            |            Attn(x)
        |               |                                |               |
        |            Attn(.)                             +-------> (+) <-+
        |               |                                           |
        +-------> (+) <-+                                    h = Norm1(x + Attn(x))
        h          |                                                |
        |----------+----+                                           +----+
        |               v                                           |    v
        |            Norm2(h)                                       |  FFN(h)
        |               |                                           |    |
        |             FFN(.)                                        +-> (+) -> Norm2(.)
        |               |
        +-------> (+) <-+   (plus one final Norm before the vocabulary head)
    

    In a pre-norm stack, nothing resets the mean of the residual stream x itself. Whatever constant offset earlier layers add into x arrives directly at Norm1(x) and Norm2(h), which makes how the normalizer treats the mean directly visible.

  2. Write the LayerNorm and RMSNorm equations

    Given one token's hidden vector x = [x_1, x_2, ..., x_d] and a small positive constant eps (such as 1e-5 or 1e-6) that prevents division by zero:

    LayerNorm centers the vector to zero mean, scales it to unit variance, and applies a learned affine transformation — an element-wise stretch gamma and shift beta of length d:

    mu    = (1 / d) * sum_{i=1..d} x_i
    var   = (1 / d) * sum_{i=1..d} (x_i - mu)^2       (population variance: divides by d, not d - 1)
    y_i   = gamma_i * (x_i - mu) / sqrt(var + eps) + beta_i
    learned parameters: gamma (d numbers), beta (d numbers) -> 2d total per norm
    

    RMSNorm drops both the mean subtraction and the learned bias beta. It divides directly by the vector's root mean square (RMS) — the square root of the average of the squared entries, which measures typical entry magnitude around zero rather than spread around the mean:

    ms    = (1 / d) * sum_{i=1..d} x_i^2              (mean square, no centering)
    y_i   = g_i * x_i / sqrt(ms + eps)
    learned parameters: g (d numbers) -> d total per norm
    

    Expanding the squared deviation in var connects the two statistics with zero approximation:

    var = (1 / d) * sum_i (x_i^2 - 2 * mu * x_i + mu^2)
        = (1 / d) * sum_i x_i^2  -  2 * mu * ((1 / d) * sum_i x_i)  +  mu^2
        = ms - 2 * mu^2 + mu^2
        = ms - mu^2      ===>      ms = var + mu^2
    

    So ms equals variance plus the squared mean. Whenever a token already has mu = 0, ms equals var, and RMSNorm with gain g produces the exact same output as LayerNorm with gamma = g and beta = 0.

    Trace both on x = [2, 2, 4, 8] (d = 4) with unit gains (1), zero bias (0), and eps = 0:

    Input:      x = [2, 2, 4, 8]
    
    LayerNorm:  mu  = (2 + 2 + 4 + 8) / 4 = 4.0
                x - mu = [-2, -2, 0, 4]
                var = (4 + 4 + 0 + 16) / 4 = 6.0,       std = sqrt(6.0) = 2.4495
                y   = [-0.816, -0.816, 0.000, 1.633]    (output mean = 0.000, mean square = 1.000)
    
    RMSNorm:    ms  = (4 + 4 + 16 + 64) / 4 = 22.0      (check: var + mu^2 = 6.0 + 16.0 = 22.0)
                rms = sqrt(22.0) = 4.6904
                y   = [ 0.426,  0.426, 0.853, 1.706]    (output mean = 0.853, mean square = 1.000)
    

    Both outputs have mean square 1 (Euclidean length sqrt(d) = 2), but only LayerNorm centers the output to mean 0.

  3. See what omitting mean subtraction changes

    We can compare normalization layers by their invariances (assuming eps = 0): - Shift invariance (re-centering invariance) means adding the same constant c to every feature (x_i -> x_i + c) leaves the output unchanged. - Scale invariance (re-scaling invariance) means multiplying every feature by a positive constant a > 0 (x_i -> a * x_i) leaves the output unchanged.

    LayerNorm has both shift invariance and positive scale invariance. RMSNorm keeps positive scale invariance (multiplying x by a > 0 multiplies rms by a, which cancels in x / rms), while negating x -> -x flips the output sign in both norms (before beta). However, RMSNorm is not shift-invariant, and its output mean can sit anywhere in [-1, 1] before applying g (since var = ms - mu^2 >= 0 implies |mu_out| <= 1).

    Add c = 5 to every feature of our example so x + 5 = [7, 7, 9, 13]:

    Input:      x + 5 = [7, 7, 9, 13]
    
    LayerNorm:  mu = 9.0,  (x + 5) - mu = [-2, -2, 0, 4]
                y  = [-0.816, -0.816, 0.000, 1.633]     (completely unchanged; spread is 2.449)
    
    RMSNorm:    ms = (49 + 49 + 81 + 169) / 4 = 87.0 = 6.0 + 9^2
                rms = sqrt(87.0) = 9.3274
                y  = [ 0.750,  0.750, 0.965, 1.394]     (shifted toward 1; spread shrinks to 0.643)
    

    Notice two distinct consequences of skipping mean subtraction: 1. In the numerator, little expressiveness is lost. Subtracting the mean is a fixed linear projection P = I - (1/d) * 1 * 1^T. Because a normalized vector immediately enters a linear weight matrix W (such as W_Q, W_K, W_V, or W_up), the matrix W can learn to ignore or use the all-ones mean direction on its own. 2. In the denominator, a large mean compresses feature differences. Because rms = sqrt(var + mu^2), a large common offset mu dominates the unit-RMS budget and squeezes all entries toward [1, 1, ..., 1] (or [-1, ..., -1]). In practice, trained transformers naturally keep residual-stream means small or use the mean direction as an extra signal. Zhang and Sennrich (2019) showed empirically that scale invariance, not mean centering, is the property that stabilizes deep transformer training.

  4. Why RMSNorm is attractive in practice

    Dropping mean centering buys four practical advantages:

    • One reduction pass instead of two. LayerNorm must reduce across d twice (first mean(x), then mean((x - mu)^2)) or maintain two coupled accumulators. RMSNorm needs a single reduction (mean(x^2)) and no subtraction or bias addition.
    • Better fit for memory-bound GPU execution. Normalization layers are memory-bandwidth bound, meaning runtime is bottlenecked by reading and writing activation tensors between GPU main memory (HBM) and on-chip SRAM rather than arithmetic speed. For hidden size d = 4096, a norm does roughly 4d ≈ 16K FLOPs (RMSNorm) or 7d ≈ 29K FLOPs (LayerNorm) per token, whereas one block's dense matrix multiplications do roughly 24 * d^2 ≈ 403M FLOPs. Kernel fusion — combining squaring, summing, and scaling into a single GPU kernel so x is read from HBM once — is simpler and uses less register pressure with one statistic, typically trimming total model wall-clock time by a modest single-digit percentage (though the norm kernel itself is ~10–50% faster).
    • No subtraction cancellation in the statistic. Summing x_i^2 adds only non-negative numbers, avoiding catastrophic cancellation when computing variance in one pass.
    • Half the norm parameters with matching model quality. Each norm stores d weights instead of 2d (saving 4,096 numbers per norm at d = 4096, tiny next to ~201M block weights, but cleaner). Scale-only normalization has become standard across modern open LLMs, including T5, LLaMA, and Mistral 7B.
  5. How gradients behave through both norms

    During backpropagation, a layer multiplies incoming gradients by its Jacobian matrix — the d × d grid of partial derivatives dy_i / dx_j describing how nudging input x_j changes output y_i. With unit gains (1), zero bias, and eps = 0, let y be the normalized output, r = rms(x), and s = std(x):

    RMSNorm Jacobian:    dy / dx = (1 / r) * (I  -  (1 / d) * y * y^T)
    LayerNorm Jacobian:  dy / dx = (1 / s) * (I  -  (1 / d) * 1 * 1^T  -  (1 / d) * y * y^T)
    

    Every term has a direct geometric meaning: - Both project out the radial direction y. Stretching x along itself (x -> (1 + delta) * x) does not change the normalized output y, so gradients parallel to y vanish. This prevents weight updates from merely inflating activation norms to game the loss. - Both scale gradients inversely with input magnitude (1 / r or 1 / s). If a residual stream doubles in norm at deeper layers, gradients entering that sublayer automatically halve, keeping effective step sizes stable without fragile learning-rate warmup. - Only LayerNorm projects out the all-ones vector 1. Because shifting every coordinate equally does not change LayerNorm's output, gradients sum to zero across features; RMSNorm lets mean-direction gradients pass straight through.

  6. Numerical precision, reductions, and epsilon

    Modern training and serving store activations in 16-bit formats: fp16 (1 sign, 5 exponent, 10 fraction bits; max value 65,504) or bf16 (1 sign, 8 exponent, 7 fraction bits; same huge range as 32-bit fp32 but coarse precision). Computing reductions directly in 16-bit fails in two ways:

    1. Overflow in fp16 and swamping in both fp16 and bf16. Swamping (absorption) happens when adding a small number to a much larger running sum rounds right back to the larger number because the spacing between representable floats exceeds the addend.
    Overflow:  in fp16, any feature |x_i| >= 256 squares to 256^2 = 65536 > 65504 -> inf!
    Swamping:  adding 1.0 to an fp16 accumulator 4096 times stalls at 2048.0 (not 4096.0),
               because at 2048 the gap between adjacent fp16 numbers is 2.0, so 2048 + 1 -> 2048.
               bf16 avoids the 256^2 overflow, but its gap reaches 2.0 at just 256.0!
    

    The standard production fix (used in LLaMA and Mistral reference code) is to upcast x to fp32, compute the mean/mean-square and division in fp32, cast back to x.dtype, and apply the learned weight.

    1. Catastrophic cancellation in naive one-pass LayerNorm. Catastrophic cancellation is losing most significant digits when subtracting two nearly equal numbers. If x = [10002, 10002, 10004, 10008] in fp32, the textbook shortcut E[x^2] - E[x]^2 subtracts two numbers near 1.0008e8 (where fp32 spacing is 8.0) and severely corrupts (or zeroes out) the true variance 6.0. LayerNorm must therefore use a two-pass subtraction or Welford's algorithm — a stable single-pass recurrence that updates a running mean and running squared deviations incrementally. RMSNorm never subtracts, so mean(x^2) in fp32 is naturally cancellation-free.

    Finally, eps caps the maximum amplification at 1 / sqrt(eps) (~316 for eps = 1e-5), which also attenuates tiny-norm vectors because output RMS becomes rms / sqrt(rms^2 + eps):

    eps = 1e-5:   input rms = 0.100 -> output rms = 0.9995
                  input rms = 0.010 -> output rms = 0.9535
                  input rms = 0.003 -> output rms = 0.6882
                  input rms = 0.001 -> output rms = 0.3015
    

    Always match checkpoint conventions when porting weights: some libraries place eps inside sqrt(ms + eps) while others compute sqrt(ms) + eps, and values vary between 1e-5 and 1e-6.

  7. Verify every property in NumPy

    Here are clean reference implementations that upcast reductions to fp32 and verify shift behavior, scale invariance, zero-mean equivalence, and the analytic Jacobians:

    import numpy as np
    
    
    def layer_norm(x, gamma, beta, eps=1e-5):
        # Promote low-precision inputs (e.g. fp16) to at least fp32 without downcasting fp64
        acc_dtype = np.result_type(x.dtype, np.float32)
        x_acc = x.astype(acc_dtype)
        mu = x_acc.mean(axis=-1, keepdims=True)
        # Two-pass variance avoids catastrophic cancellation when |mu| is large
        var = ((x_acc - mu) ** 2).mean(axis=-1, keepdims=True)
        y = (x_acc - mu) / np.sqrt(var + eps)
        return (gamma * y + beta).astype(x.dtype)
    
    
    def rms_norm(x, g, eps=1e-5):
        acc_dtype = np.result_type(x.dtype, np.float32)
        x_acc = x.astype(acc_dtype)
        ms = (x_acc ** 2).mean(axis=-1, keepdims=True)
        y = x_acc / np.sqrt(ms + eps)
        return (g * y).astype(x.dtype)
    
    
    x = np.array([[2.0, 2.0, 4.0, 8.0]])
    ones = np.ones(4)
    zeros = np.zeros(4)
    
    # 1. Shift invariance: LayerNorm ignores +5; RMSNorm changes
    assert np.allclose(layer_norm(x, ones, zeros, 0.0), layer_norm(x + 5.0, ones, zeros, 0.0))
    assert not np.allclose(rms_norm(x, ones, 0.0), rms_norm(x + 5.0, ones, 0.0))
    
    # 2. Positive scale invariance: both ignore multiplying by 2.5 (when eps = 0)
    assert np.allclose(layer_norm(x, ones, zeros, 0.0), layer_norm(2.5 * x, ones, zeros, 0.0))
    assert np.allclose(rms_norm(x, ones, 0.0), rms_norm(2.5 * x, ones, 0.0))
    
    # 3. Zero-mean input: RMSNorm and bias-free LayerNorm match identically
    x_centered = x - x.mean(axis=-1, keepdims=True)
    assert np.allclose(rms_norm(x_centered, ones, 0.0), layer_norm(x_centered, ones, zeros, 0.0))
    
    # 4. Check both analytic Jacobians against central finite differences
    v = np.array([0.4, -1.5, 1.8, 0.9, -0.6], dtype=np.float64)
    d = len(v)
    h = 1e-6
    
    y_rms = rms_norm(v, np.ones(d), 0.0)
    r = np.sqrt((v ** 2).mean())
    jac_rms_analytic = (np.eye(d) - np.outer(y_rms, y_rms) / d) / r
    
    y_ln = layer_norm(v, np.ones(d), np.zeros(d), 0.0)
    s = np.sqrt(((v - v.mean()) ** 2).mean())
    jac_ln_analytic = (np.eye(d) - np.ones((d, d)) / d - np.outer(y_ln, y_ln) / d) / s
    
    jac_rms_numeric = np.zeros((d, d))
    jac_ln_numeric = np.zeros((d, d))
    for j in range(d):
        step = np.zeros(d)
        step[j] = h
        jac_rms_numeric[:, j] = (rms_norm(v + step, np.ones(d), 0.0) - rms_norm(v - step, np.ones(d), 0.0)) / (2.0 * h)
        jac_ln_numeric[:, j] = (
            layer_norm(v + step, np.ones(d), np.zeros(d), 0.0) - layer_norm(v - step, np.ones(d), np.zeros(d), 0.0)
        ) / (2.0 * h)
    
    assert np.max(np.abs(jac_rms_analytic - jac_rms_numeric)) < 1e-8
    assert np.max(np.abs(jac_ln_analytic - jac_ln_numeric)) < 1e-8
    

Intuition & how it works

Imagine preparing four raw test scores [2, 2, 4, 8] from a single student (one token) so their overall scale stays predictable before entering the next stage of a deep network. LayerNorm grades strictly "on a curve": it first computes and subtracts the average (4) so the centered scores average to zero ([-2, -2, 0, 4]), then divides by their standard deviation (2.449) and applies a learned stretch and shift. RMSNorm skips finding and subtracting the average altogether: it simply divides each feature by the vector's root mean square (RMS) — the square root of the average squared entry — keeping the vector's overall size steady while doing only one pass over the features instead of two.

Without per-token normalization, hidden numbers flowing down dozens of transformer layers can balloon or vanish, making gradients unstable and training diverge. However, computing full LayerNorm requires two sequential reductions across the hidden dimension (or a single-pass variance shortcut that breaks numerically in floating-point arithmetic) on hardware that is already memory-bandwidth bound — bottlenecked waiting on memory reads and writes rather than math operations.

Walking through x = [2, 2, 4, 8] (d = 4, unit gain 1, zero bias 0, eps = 0) makes the difference concrete. LayerNorm computes mean mu = 4, variance var = ((2-4)^2 + (2-4)^2 + (4-4)^2 + (8-4)^2) / 4 = 6.0, and outputs [-0.816, -0.816, 0.000, 1.633] (mean 0.000, mean square 1.000). RMSNorm computes mean square ms = (4 + 4 + 16 + 64) / 4 = 22.0 (which equals var + mu^2 = 6.0 + 4^2) and divides by sqrt(22.0) = 4.690 to output [0.426, 0.426, 0.853, 1.706] (mean square 1.000, but mean 0.853). If we add 5 to every feature ([7, 7, 9, 13]), LayerNorm subtracts the new mean 9 and produces the exact same output, whereas RMSNorm divides by sqrt(87.0) = 9.327 and outputs [0.750, 0.750, 0.965, 1.394], letting the shared offset consume most of the unit-RMS budget.

Key points

  • Per-token feature axis: Given activations [batch, seq_len, d], both normalize each token's hidden vector (its d features) independently, unlike BatchNorm (which averages across batch examples and tracks running training statistics). Modern LLMs (such as LLaMA and Mistral 7B) use pre-norm, applying normalization to a branch copy before each attention or feed-forward sublayer while leaving the main residual stream (x = x + Sublayer(Norm(x))) un-normalized.
  • Equations and algebraic link: Affine LayerNorm computes y_i = gamma_i * (x_i - mu) / sqrt(var + eps) + beta_i (2d learned parameters; an affine transformation is an element-wise stretch and shift). Scale-only RMSNorm computes y_i = g_i * x_i / sqrt(ms + eps) (d parameters), where ms = mean(x^2) = var + mu^2. When mu = 0 and beta = 0, the two formulas are identical.
  • Invariances and dropping centering: Both satisfy positive scale invariance (multiplying x by a > 0 leaves the output unchanged when eps = 0). Only LayerNorm satisfies shift invariance (adding c to every feature cancels out in x_i - mu). In RMSNorm, a large non-zero mean inflates sqrt(var + mu^2) and compresses relative differences between features, though the next linear layer can handle any remaining mean offset.
  • Why RMSNorm is attractive: It needs one reduction (mean(x^2)) instead of two, omits subtraction and bias, avoids subtraction cancellation, and makes kernel fusion (combining small GPU ops into one pass to avoid extra HBM memory round-trips) simpler and faster while matching LayerNorm's model quality.
  • Gradient geometry: Both Jacobian matrices (the d × d grids of output-to-input partial derivatives) project out the radial direction y and divide incoming gradients by input scale (1 / rms or 1 / std), stabilizing backward updates; LayerNorm additionally removes the all-ones mean direction.
  • Precision and epsilon: Reductions are upcast from 16-bit (fp16 or bf16) to 32-bit fp32 to avoid fp16 overflow (256^2 = 65536 > 65504) and swamping (small addends rounding to zero when added to a large running sum). Epsilon caps magnification at 1 / sqrt(eps) and shrinks inputs whose RMS is near or below sqrt(eps).

Common mistakes

  • Confusing the normalization axis with BatchNorm: Normalizing across the batch or sequence dimension instead of each individual token's d hidden features, or claiming LayerNorm/RMSNorm maintains running mean/variance buffers for inference.
  • Writing RMSNorm with standard deviation: Writing x / std(x) instead of x / sqrt(mean(x^2) + eps) — RMS includes mu^2 inside the denominator (rms^2 = std^2 + mu^2).
  • Claiming RMSNorm produces zero-mean or shift-invariant outputs: RMSNorm only fixes the pre-gain mean square to 1 (ignoring eps); its output mean can be anywhere in [-1, 1] and shifts whenever a constant is added to x.
  • Claiming sign invariance: Saying Norm(-x) == Norm(x). Scaling by -1 flips the sign of the normalized vector in both LayerNorm (before beta) and RMSNorm.
  • Using naive one-pass variance E[x^2] - E[x]^2 for LayerNorm: When |mu| is large relative to std, subtracting two huge nearly equal floats suffers catastrophic cancellation (losing precision and returning 0 or negative variance); LayerNorm requires two passes or Welford's algorithm (an incremental running-mean variance update).
  • Overstating end-to-end training speedups: Because dense matrix multiplications (O(d^2) per token) dominate norm arithmetic (O(d) per token), switching LayerNorm to RMSNorm gives a clean memory-bound win (often a few percent end-to-end), not a multi-times training speedup.

Follow-up questions

  • How does adding an identical scalar offset to every coordinate of a token vector affect LayerNorm versus RMSNorm? LayerNorm subtracts the shifted mean mu + c, so (x_i + c) - (mu + c) = x_i - mu and its output stays completely identical ([2, 2, 4, 8] and [7, 7, 9, 13] both yield [-0.816, -0.816, 0.000, 1.633]). In RMSNorm, the offset stays in the numerator and grows the denominator to sqrt(var + (mu + c)^2). As |c| becomes large, x_i + c looks increasingly flat and the pre-gain output converges toward sign(mu + c) * [1, 1, ..., 1], compressing relative differences across channels unless the network keeps residual-stream means small.
  • What numerical roles do the eps term and mixed-precision floating-point reductions play during normalization? With eps inside the square root, the pre-gain output RMS equals rms / sqrt(rms^2 + eps): for eps = 1e-5, an input with rms = 0.1 keeps output RMS 0.9995, whereas a tiny input with rms = 0.003 is attenuated down to 0.688 and maximum magnification is capped at 1 / sqrt(eps) ≈ 316. In fp16, squaring overflows to inf whenever |x_i| >= 256, and wide feature sums in both fp16 and bf16 stall from swamping (for instance, summing 1.0 4,096 times in fp16 stops at 2,048). Production kernels therefore cast activations to fp32 for the reduction and reciprocal square root, cast back, and match checkpoint eps value and placement (sqrt(ms + eps) vs. sqrt(ms) + eps).
  • Are activations coming out of RMSNorm guaranteed to have a mean of zero? No — prior to multiplying by the learned gain g, RMSNorm only normalizes the mean square to 1 (ignoring eps), leaving the output mean at mu / sqrt(var + mu^2 + eps) (for [2, 2, 4, 8], that mean is 0.853). The pre-gain output averages to zero only when the incoming vector already had zero mean. After applying learned parameters, neither norm guarantees a zero-mean final output, since RMSNorm's per-channel gain g and LayerNorm's gamma and beta can shift the mean freely.

Follow-up questions

Similar questions

More Mistral AI interview questions

All 17 Mistral AI questions →