Layer normalization: choose the statistical slice
层归一化
Compare feature-only and time-feature normalization, affine parameter shapes, sample locality and information lost by centering.
layer-normalizationNormalize a token, or normalize a whole sequence?
A tensor has shape (2, 2, 3): two examples, two time positions, three features. “Apply layer normalization” still leaves a choice. Normalizing the last feature axis gives each token its own statistics. Normalizing the last two axes makes the two time positions share statistics. Both operations can be expressed by a LayerNorm interface, but they do different work.
Ba, Kiros and Hinton’s 2016 paper, Section 3 computes statistics across a layer’s hidden units for one training case; its recurrent formulation uses statistics at each time step. The fixed PyTorch 2.8 LayerNorm documentation specifies the last dimensions through normalized_shape, with per-element affine parameters and input-derived statistics in both training and evaluation.
The reduction axes define the operation
Fix the indices outside a chosen trailing set of axes. Flatten just that slice to a vector x of length D. Its normalization is:
The variance divides by D, without a sample-estimation correction. No running average is needed: the current slice supplies its own mean and variance. A different example in the batch therefore cannot change this operation’s output, provided the batch axis is not among the reduced axes.
For shape (N,T,D), reducing only D makes statistics local to each (example, time) pair. Reducing T and D makes statistics local only to each example. These choices also determine the number of affine parameters:
The factor two counts γ and β. The first choice shares the same feature-wise parameters over all time positions; the second permits different parameters at different positions and requires the configured trailing shape. Neither count depends on batch size.
In our first example, the two tokens are (1,2,3) and (11,12,13). Feature-only means are 2 and 12, with variance 2/3 each. Combining both axes gives mean 7 and variance 77/3. A token’s offset disappears under feature-only centering, but its position relative to the other token survives joint centering.
What information is removed?
Write zε(x) for the normalized vector before γ and β. For a scalar offset c and positive scale a:
Centering removes the offset; variance scales by a², giving the second identity. With positive ε, arbitrary positive rescaling is not exactly invariant. The normalized empirical variance is v/(v+ε). For a constant slice it is zero, and output equals β. In particular, a one-feature slice always loses its input value through centering. Layer normalization is not an invertible rescaling of arbitrary inputs.
Change one axis choice and inspect the result
This complete Python 3.12 / NumPy 1.26.4 program accepts a trailing shape and checks it explicitly. It excludes the batch axis, keeps reduced dimensions for broadcasting, and requires γ and β to match the normalized shape exactly. Inputs are small finite tensors; ε is bounded away from zero. It returns fresh outputs and statistics, without a train/eval flag because this operation has no running-state branch.
import numpy as np
def layernorm(x, shape, gamma, beta, eps=1e-5):
x=np.array(x,dtype=np.float64,copy=True)
if not 2<=x.ndim<=4 or not 0<x.size<=4096 or any(d==0 for d in x.shape):raise ValueError('bounded nonempty tensor required')
if not isinstance(shape,tuple) or not 1<=len(shape)<x.ndim or any(type(d) is not int or d<1 for d in shape):raise ValueError('positive trailing shape excluding batch axis required')
if x.shape[-len(shape):]!=shape:raise ValueError('normalized shape must match trailing dimensions')
gamma,beta=[np.array(v,dtype=np.float64,copy=True) for v in (gamma,beta)]
if gamma.shape!=shape or beta.shape!=shape:raise ValueError('affine arrays must match normalized shape')
if any(not np.isfinite(v).all() or np.any(np.abs(v)>1000) for v in (x,gamma,beta)):raise ValueError('finite bounded entries required')
if type(eps) not in (int,float) or not np.isfinite(eps) or not 1e-12<=eps<=1000:raise ValueError('bounded positive epsilon required')
axes=tuple(range(x.ndim-len(shape),x.ndim))
mean=x.mean(axis=axes,keepdims=True)
var=((x-mean)**2).mean(axis=axes,keepdims=True)
return gamma*(x-mean)/np.sqrt(var+eps)+beta,mean,var
if __name__=='__main__':
x=np.array([[[1,2,3],[11,12,13]],[[2,4,6],[4,8,12]]],dtype=float)
y,mean,var=layernorm(x,(3,),[2,1,.5],[0,1,-1],eps=1/3)
print('last-feature output:',np.round(y,6).tolist())
print('last-feature means:',mean[...,0].tolist())
_,wide_mean,wide_var=layernorm(x,(2,3),np.ones((2,3)),np.zeros((2,3)),eps=1/3)
print('time-feature means:',wide_mean[:,0,0].tolist())
print('time-feature variances:',np.round(wide_var[:,0,0],6).tolist())
singleton=layernorm([[7]],(1,),[3],[2])[0]
print('one-feature output:',singleton.tolist())
Actual output:
last-feature output: [[[-2.0, 1.0, -0.5], [-2.0, 1.0, -0.5]], [[-2.309401, 1.0, -0.42265], [-2.412091, 1.0, -0.396977]]]
last-feature means: [[2.0, 12.0], [4.0, 8.0]]
time-feature means: [7.0, 6.0]
time-feature variances: [25.666667, 10.666667]
one-feature output: [[2.0]]
For the first two tokens, ε=1/3 makes the denominator one. With γ=(2,1,1/2), β=(0,1,−1), both outputs are (−2,1,−1/2). The second example’s tokens have larger variances and therefore different denominators. The joint time-feature means are 7 and 6; their variances are 77/3 and 32/3.
Tests check these literal statistics and outputs, prove locality by changing another example or token, and verify the offset and scaling identities numerically. Constant slices, the one-feature case, wrong trailing shapes and nonfinite data are checked separately. Computation and output storage are O(number of tensor elements); affine storage is proportional to the product of the normalized dimensions.
Batch independence is a local property
Layer normalization does not mix examples in this implementation. The surrounding network may still use batch-dependent losses or layers, so the complete training procedure need not be independent across examples. Likewise, per-token normalization does not prevent attention or recurrence from mixing time positions elsewhere.
Normalizing across time can mix future and past values if the slice contains both. A causal model must choose axes consistent with its information boundary. Padding can also affect a jointly normalized slice unless handled explicitly. The program does not implement masks, variable-length joint normalization or a causal attention model.
Per-element γ and β are important when comparing with other normalization layers. Matching the set of normalized values is not sufficient if affine parameters are shared along different axes. Compare group normalization only after fixing both choices.
The original paper reports improvements in its studied models; the numerical audit here tests the operation and its information loss, not convergence speed or universal superiority over batch normalization.
Which values share a denominator?
- For the first example, what are the means when only three features are normalized?
Answer 1: Two and twelve, one mean per token.
- What mean appears when both time and feature dimensions are normalized?
Answer 2: Seven for that example.
- How many affine parameters do shapes (3,) and (2,3) require?
Answer 3: Six and twelve, respectively.
- What does a one-feature slice output?
Answer 4: β, because its centered input and variance are both zero.
Read the axis specification, not just the layer name
The paper supplies the per-case formulation and recurrent motivation. The fixed API supplies trailing-axis and affine-shape conventions. Our tensor, axis comparison, invariance calculation and tests are original; no framework implementation or reported benchmark was reproduced.
Read batch normalization for statistics that cross examples during training, and tensor shapes before changing data layouts. A correct shape can still express the wrong statistical comparison.
Make a prediction, then check
For shape(N,T,D), which normalized_shape gives separate statistics for each token?
Learning objectives
- Specify normalization axes and affine parameter shape.
- Explain locality, invariance and constant-slice information loss.
Prerequisites & connections
Explore related knowledge →References
- Layer Normalization — arXiv1607.06450v1
Jimmy Lei Ba; Jamie Ryan Kiros; Geoffrey E. Hinton · 2016 - LayerNorm — PyTorch 2.8
PyTorch contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter. Normalization axes and groups, matched residual fits and reverse graph paths are checked against literal references, analytic identities and finite differences. Two examples use NumPy1.26.4; two use the standard library.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Layer Normalization — arXiv1607.06450v1 · Fixedv1 Section3 Eq3 and Section3.1 Eq4, physicalpages2–3: per-case hidden-unit statistics and per-time recurrent statistics; no benchmark replication.
- LayerNorm — PyTorch 2.8 · Fixed2.8 LayerNorm body: trailing normalized_shape dimensions, biased variance, per-element affine parameters and input statistics in train/eval.
Related topics