Normalizations
This article studies normalization in the context of a language model: token IDs become embeddings, attention and FFN layers modify hidden states, and an output head produces next-token logits. At each stage, a vector’s direction and magnitude can affect the next computation. Normalization changes which of these differences that computation can use.
The main path is token representations, LN/RMSNorm, attention scaling and QK-Norm, and residual connections. L2 normalization helps explain the geometry. AdaLN shows how conditions can modify normalized features. BN, IN, GN, and other families provide comparisons, including uses in vision components of multimodal systems; their inclusion does not imply that they are standard replacements inside a causal text decoder. Each time, ask: which numbers are grouped together, what information is removed on this path, and where can the complete model still use it?
1. What Problem Are We Solving?
1. 我们为什么需要 Normalization?
1.1 Separate Pattern, Scale, and Offset
1.1 先区分相对模式、尺度与共同偏移
At one LM layer, suppose a token could have hidden state $(1,2,3)$ or $(101,102,103)$. These are two hypothetical states at the same computational site. The second has the same differences between coordinates, but a common offset of 100. A third state, $(10,20,30)$, multiplies both the values and their differences by ten. A coordinate is one entry of the vector; a vector with $d$ coordinates has dimension $d$.
These changes matter to the next computation. A fixed linear map sees a tenfold input scale as a tenfold output scale, before any bias. A nonlinear function can react even more differently: large differences between attention scores can push softmax into its flat, nearly one-hot regime. Attention and Language Models illustrates this effect.
Where could these changes come from inside an LM? A token’s vector does not stay at its initial embedding. As it passes through the network, successive computations revise it using context and learned features. In a GPT-style block, attention mixes information from visible token positions, while an FFN transforms each position’s features. Each is a sublayer: one computation within the larger block.
To understand how one sublayer revises the representation, call the incoming token vector $x$ and the sublayer’s computed contribution $u$. After any required output projection, $u$ has the same dimension as $x$, so the two can be added coordinate by coordinate:
\[x_{\mathrm{new}}=x+u.\]This addition is called residual addition. The original $x$ reaches the addition directly, and the sublayer supplies a learned change $u$. The resulting $x_{\mathrm{new}}$ is passed onward as the token’s updated representation. Here “updated” refers to a hidden state changing during a forward pass; the model parameters need not change. We will place normalization within this computation in Section 6.1.
Now the scale question becomes concrete. If $x=(1,2,3)$ and a sublayer produces $u=(10,10,10)$, the next representation is $(11,12,13)$. If the following sublayer adds the same contribution, it becomes $(21,22,23)$. The common offset has grown even though the differences between coordinates are unchanged.
Magnitude can change as well. If a sublayer happens to contribute a vector equal to its incoming $x$, the addition produces $2x$. Repeating that particular situation would double the state at every addition. These are possible numerical examples, not a claim that trained sublayers always produce such contributions. They establish the limited point we need: residual addition preserves a route for the incoming representation, but the addition itself does not keep its mean or magnitude fixed. Consequently, later computations can receive vectors on different numerical scales.
Normalization provides a reference for a particular computation. This is a modeling choice with an information cost: removing a common scale makes that computation unable to distinguish some inputs. In an LM, we must first understand what scale can do, then examine where normalization occurs.
1.2 Can Scale Carry Useful Information in an LM?
1.2 在 LM 中,尺度是否包含有用信息?
It can. A norm measures magnitude, and magnitude can change how a representation affects the model. There is no universal rule that a larger hidden-state norm means a more important token or a more confident answer. Its meaning depends on where the vector is used. The following examples hold other quantities fixed so that we can isolate each effect.
Attention scores: how selective is the read? A query $q$ is compared with candidate keys $k_j$ using dot products. Holding the keys fixed, multiplying the query by a positive number multiplies all its dot-product scores by that number, provided no intervening normalization removes the change. Scores $(1,0)$ give softmax weights about $(0.731,0.269)$; scores $(10,0)$ give about $(0.99995,0.00005)$. The preferred key stays the same, but selection becomes much sharper. Query scale can therefore control selectivity. Scaling an individual key changes its own score; if that score is negative, increasing its magnitude makes it more negative rather than more attractive.
Value vectors: how much is contributed? After selecting weights, attention forms a weighted sum of value vectors. If a key receives weight 0.2, its contribution is $0.2v$. Replacing its value by $10v$, while keeping the weights fixed, makes that contribution ten times larger. Other contributions can reinforce or cancel it, and an output projection can further change it. The attention weight alone therefore does not determine the size of the resulting contribution. These examples follow directly from the attention computation.
Residual states: how much can a new update change the representation? A residual stream is the hidden vector carried between sublayers. Each sublayer adds an update $u$, producing $x+u$. For a fixed $u$ that is not parallel to $x$, adding it to $x$ changes the direction more than adding it to $10x$. For example, $(1,0)+(0,1)=(1,1)$ turns by 45 degrees, while $(10,0)+(0,1)=(10,1)$ turns by only about 5.7 degrees. Thus the existing state’s scale helps determine how strongly the next sublayer can alter its direction.
Output logits: how concentrated is the prediction? Logits are the scores immediately before the vocabulary softmax. For an illustrative two-token vocabulary, logits $(1,0)$ versus $(10,0)$ again give probabilities about $(0.731,0.269)$ versus $(0.99995,0.00005)$. The ranking is unchanged, but the assigned likelihoods—and the cross-entropy loss—are very different. A sharper distribution need not be more correct. This example scales the logits themselves; scaling a hidden state before a final LN/RMSNorm does not necessarily scale the logits, because that normalization can remove the change.
These are computational roles that scale can play, not evidence that every trained LM gives norm a particular semantic meaning. Whether a specific model uses it for a particular task requires examining that model.
Why normalize, then? We choose which paths should depend on absolute scale and which should have a stable reference. LN and RMSNorm restrict scale dependence on their normalized path; a Pre-Norm residual path can still preserve scale and let it affect later computation. Section 6.1 works through this distinction. Training may also represent useful distinctions through coordinate patterns that survive normalization; this is a possibility enabled by learning, not a guarantee that discarded information is always recovered.
1.3 The Recipe: Group, Measure, Transform
1.3 通用步骤:选一组数、测量、再变换
First choose a set $S$ containing $m$ numbers. Our starting case is the hidden coordinates of one token at one layer; other statistical groups will be compared in Section 3. Compute their mean and variance:
\[\mu_S=\frac1m\sum_{j\in S}x_j,\qquad \sigma_S^2=\frac1m\sum_{j\in S}(x_j-\mu_S)^2.\]The $m$ in both denominators counts the entries selected into $S$. For a token vector $(1,2,3)$, $S$ contains its three coordinate indices, so $m=3$. The formulas become $\mu_S=(1+2+3)/3=2$ and $\sigma_S^2=((1-2)^2+(2-2)^2+(3-2)^2)/3=2/3$. In token-wise LayerNorm with hidden width $d$, $m=d$, regardless of batch size or the number of tokens in the dataset.
The mean specifies the common level. The variance $\sigma_S^2$ measures the average squared distance from that level. Its square root, the standard deviation $\sigma_S$, has the same units as the original numbers. Throughout the article, $\sigma^2$ denotes variance and $\sigma$ denotes standard deviation when describing these statistics. Centering and dividing by that scale gives
\[\hat x_i=\frac{x_i-\mu_S}{\sqrt{\sigma_S^2+\epsilon}},\qquad y_i=\gamma_i\hat x_i+\beta_i.\]Here $\epsilon>0$ prevents division by zero. There are two stages in the formula. First, compute $\mu_S,\sigma_S^2$ from the input and use them to obtain $\hat x_i$. Then multiply by a learned scale $\gamma_i$ and add a learned shift $\beta_i$. These last two numbers let the model adjust what the next layer receives.
Why adjust values after standardizing them? Zero mean and approximately unit variance provide a convenient reference, but they are not necessarily the most useful output statistics for the next computation. Stopping at $\hat x$ would require every input group to keep that reference. The affine stage lets training choose how to use it: $\gamma_i$ adjusts how strongly coordinate $i$ varies, while $\beta_i$ changes its baseline.
For example, suppose a standardized coordinate takes values $-1,0,1$ across three inputs. Setting $\gamma_i=2,\beta_i=3$ maps them to $1,3,5$. The relative variation remains, but its size doubles and the baseline moves to 3. Those particular values are just an illustration; training learns the parameters from the loss. Both changes can affect which region of a subsequent nonlinear function the feature reaches.
This second stage is optional. Setting every $\gamma_i=1$ and $\beta_i=0$ gives the standardized values unchanged, and a layer can omit these parameters entirely. If a freely learned linear map follows immediately, the affine transform can also be absorbed into that map’s weights and, where available, bias. Its usefulness therefore depends on the surrounding architecture; normalization does not mathematically require trainable parameters.
To see where these numbers come from, consider two tokens entering the same normalization layer, each represented by three coordinates:
\[x_A=(1,2,3),\qquad x_B=(10,20,30).\]For this example, choose the token-wise rule that we will later call LayerNorm. Token A computes its mean from its own three numbers: $\mu_A=2$, with variance $\sigma_A^2=2/3$. Token B separately computes $\mu_B=20$ and $\sigma_B^2=200/3$. When standardizing A, all three coordinates subtract the same 2 and divide by the same $\sqrt{2/3+\epsilon}$. This reuse of one pair of statistics is what “sharing statistics” means. B uses its own pair; the two tokens are not pooled together.
Now consider the second stage. This layer stores three learned scales $(\gamma_1,\gamma_2,\gamma_3)$ and three learned shifts $(\beta_1,\beta_2,\beta_3)$. Unlike the means and variances, these six parameters are not recalculated from each token. They are model parameters, updated during training and reused wherever this layer is applied.
The first coordinate of either token uses $\gamma_1,\beta_1$. The second uses $\gamma_2,\beta_2$, and the third uses $\gamma_3,\beta_3$. “Sharing parameters” means reusing the same stored parameters, rather than giving each token a separate set. For example, if $\gamma_1=2$ and $\beta_1=0$, this layer doubles the standardized first coordinate of both tokens.
| Entry being transformed | Statistics used in the first stage | Parameters used in the second stage |
|---|---|---|
| A, coordinate 1 | $\mu_A,\sigma_A^2$ | $\gamma_1,\beta_1$ |
| A, coordinate 2 | $\mu_A,\sigma_A^2$ | $\gamma_2,\beta_2$ |
| A, coordinate 3 | $\mu_A,\sigma_A^2$ | $\gamma_3,\beta_3$ |
| B, coordinate 1 | $\mu_B,\sigma_B^2$ | $\gamma_1,\beta_1$ |
| B, coordinate 2 | $\mu_B,\sigma_B^2$ | $\gamma_2,\beta_2$ |
| B, coordinate 3 | $\mu_B,\sigma_B^2$ | $\gamma_3,\beta_3$ |
Compare A’s first and second coordinates: they share statistics but use different parameter entries. Compare A’s and B’s first coordinates: they use separately computed statistics but share parameters. We therefore need to specify both which inputs are measured together and where each learned scale and shift is reused. Later methods will make different choices.
Ignoring $\epsilon$, both example tokens become approximately $(-1.225,0,1.225)$ before the learned scale and shift. With $\epsilon>0$, each standardized group’s variance is $\sigma_S^2/(\sigma_S^2+\epsilon)$, slightly below 1. After the learned affine transform, neither zero mean nor unit variance is guaranteed.
Does this undo normalization? In the idealized example with $\epsilon=0$, A and B have already become identical. Applying the same learned scales and shifts keeps them identical; it cannot recover A’s original scale of 1 and B’s original scale of 10. Normalization removes the input-dependent common scale, while the affine parameters supply a learned scale reused across inputs. The model gets a choice of output range without automatically restoring the discarded input-specific information.
What exactly is being “normalized”? (Click to expand)
Standardization fixes a group’s first two moments: mean and variance. It does not turn arbitrary data into a Gaussian distribution, remove correlations between coordinates, or guarantee bounded individual values. A single outlier can still be large relative to the group’s average scale.
The $m$ is the group size in the $1/m$ factors of the mean and variance formulas above. For our three-coordinate token, $m=3$; for token-wise LN at hidden width $d$, $m=d$. Dividing by $m$ defines the variance of the actual group being transformed. Some statistical estimators divide by $m-1$ to estimate an underlying population variance without bias from independent samples whose mean is also estimated. Normalizing a token’s coordinates does not require treating them as such a sample. These divisors should not be silently interchanged in an implementation.
2. Normalizing One Vector
2. 对一个向量进行 Normalization
2.1 L2-Norm: Keep Direction, Set Length
2.1 L2-Norm:保留方向、调整长度
A vector’s Euclidean length is $\lVert x\rVert_2=\sqrt{\sum_i x_i^2}$. This norm is a scalar measurement. L2 normalization uses it to transform the vector:
\[u=\frac{x}{\max(\lVert x\rVert_2,\epsilon)}.\]For $x=(3,4)$, the length is 5 and the result is $(0.6,0.8)$. For $(30,40)$ the result is the same. Except near the numerical floor, the output has length 1 and preserves direction. There is no mean subtraction, so $(3,4)$ and $(103,104)$ generally point in different directions and normalize differently.
Why use this for embeddings? A dot product combines length and alignment:
\[x^\top y=\lVert x\rVert_2\lVert y\rVert_2\cos\phi.\]When neither norm is clamped by the numerical floor, normalizing both nonzero embeddings makes their dot product equal cosine similarity. A vector can no longer obtain a high similarity merely by being long. This can be a deliberate choice when comparing text embeddings for retrieval. It is not an instruction to normalize every hidden vector in an LM: Section 1.2 showed why magnitude can affect computation. The zero vector has no direction; the numerical convention above returns zero.
L1 normalization similarly divides by $\sum_i\lvert x_i\rvert$; max-norm scaling divides by $\max_i\lvert x_i\rvert$. L1-normalized values form probabilities only when they are nonnegative. None of these operations is the same as adding an L2 penalty to a training loss.
2.2 LayerNorm: Remove the Common Level First
2.2 LayerNorm:先去掉共同水平
For a sequence tensor $X\in\mathbb R^{B\times T\times d}$, $B$ is batch size, $T$ is sequence length, and $d$ is embedding or hidden width. Token-wise LayerNorm chooses one vector $x=X_{b,t,:}$ and applies the standardization recipe across its $d$ coordinates:
\[\operatorname{LN}(x)_i=\gamma_i \frac{x_i-\mu(x)}{\sqrt{\sigma^2(x)+\epsilon}}+\beta_i.\]Each token gets its own two scalar statistics. The same learned vectors $\gamma,\beta\in\mathbb R^d$ are reused across tokens and examples. No running population statistics are needed; this operation uses the current input during both training and inference. This is the sequence convention used here; more generally, LayerNorm can reduce over a specified set of trailing dimensions. LayerNorm paper
The choice of axis expresses a modeling decision. We want to stabilize the representation presented by each token, even if the batch contains one example or generation has reached only one position. Computing statistics over tokens instead would couple this token’s output to other positions and potentially future information.
For example, $(1,2,3)$ and $(101,102,103)$ become identical before the affine transform. A fixed $\beta$ can restore a useful learned baseline, but it cannot reconstruct which input originally had offset 100: that input-specific information has been discarded on this branch.
2.3 RMSNorm and Its Relationship to L2-Norm
2.3 RMSNorm 与 L2-Norm 有什么关系?
We can control magnitude without first removing the mean. Consider one token’s hidden vector $x=(x_1,\ldots,x_d)$. Here $d$ is the number of coordinates in this vector, also called its hidden dimension. If the full tensor has shape $[B,T,d]$, we fix one example and one token and use only its last-axis vector. Thus $d$ is the group size $m$ from Section 1.3 in this setting, not the batch size or context length.
Root mean square means exactly “square the entries, average, then take the square root.” There are $d$ squared entries, so averaging means summing them and dividing by $d$:
\[\operatorname{RMS}(x)=\sqrt{\frac1d\sum_{j=1}^{d}x_j^2},\qquad \operatorname{RMSNorm}(x)_i=\gamma_i\frac{x_i}{\sqrt{\frac1d\sum_{j=1}^{d}x_j^2+\epsilon}}.\]The index $j$ runs over all coordinates when computing the shared denominator; $i$ identifies the output coordinate being computed. For $x=(3,4)$, $d=2$, so $\operatorname{RMS}(x)=\sqrt{(3^2+4^2)/2}=\sqrt{12.5}$. Both coordinates are divided by the same RMS scale before their respective learned gains are applied.
The usual RMSNorm formulation learns a scale vector and omits an additive bias. It uses the same token group as token-wise LN, but no centering. It requires fewer kinds of reductions; actual speed depends on the implementation and hardware. RMSNorm paper
The relationship to L2 normalization follows directly from replacing a sum with an average:
\[\operatorname{RMS}(x)=\frac{\lVert x\rVert_2}{\sqrt d}, \qquad \frac{x}{\operatorname{RMS}(x)} =\sqrt d\,\frac{x}{\lVert x\rVert_2}.\]Ignoring $\epsilon$ and learned scale, L2 normalization targets length 1; RMS normalization targets length $\sqrt d$, so the mean squared coordinate is 1. For $(3,4)$, RMS is $\sqrt{12.5}\approx3.536$, giving approximately $(0.849,1.131)$.
Another useful identity is
\[\operatorname{RMS}(x)^2=\sigma^2(x)+\mu(x)^2.\]If the mean is zero, LN and RMS normalization have the same denominator and numerator before affine parameters. If the mean is large, their behavior differs. For $(101,102,103)$, RMS normalization produces three positive values close to 1; LN reveals the centered pattern $(-1.225,0,1.225)$. RMSNorm preserves direction before learned coordinate scaling; LN generally changes it by centering.
ScaleNorm uses one learned scalar $g$: $g\,x/\lVert x\rVert_2$. It learns the common target length rather than a separate gain for every coordinate. Fixed-length embedding normalization is also called FixNorm in this line of work. ScaleNorm and FixNorm
2.4 Change the Input and Compare
2.4 改变输入,直接比较结果
The figure below starts with $(1,2,3)$ and lets you change its common scale and offset. Each panel plots three coordinate values, before or after the named normalization; learned affine parameters are omitted. Gray bars always show the result for the original $(1,2,3)$, while colored bars show the result for the current input. Thus a colored bar remaining level with its gray neighbor means that coordinate has not changed.
First click “Add 100 only”: the input increases, but LN still matches its gray reference; L2 and RMSNorm change. Then click “Multiply by 10 only”: all three normalized outputs almost match their references, except for the small effect of $\epsilon$. The three output panels share a fixed vertical scale, while the input panel uses its own adaptive scale—read its ticks rather than comparing its bar heights directly with output bars.
Why does normalization also change gradients? (Click to expand)
The mean and denominator are computed from the input, so backpropagation must differentiate through them. Changing one coordinate changes the denominator and therefore affects other normalized coordinates.
For pure L2 normalization, write $u=x/\lVert x\rVert_2$. At nonzero $x$, with no numerical floor active, its derivative matrix is
\[J=\frac1{\lVert x\rVert_2}(I-uu^\top).\]$J$ maps a small input perturbation to the corresponding first-order output change. The term $uu^\top$ extracts the component parallel to the current vector. Subtracting it removes that component: increasing only the length does not change the normalized output. Transverse changes, which rotate the direction, do affect the result.
LN additionally removes the common-shift direction. These operations reshape gradient flow; they do not guarantee that every network gradient has a safe magnitude. A very small denominator can amplify sensitivity. Basics of Optimizers explains how the resulting gradient is subsequently converted into a parameter update.
3. Which Numbers Share Statistics?
3. 哪些数共享同一组统计量?
For a causal LM, an axis choice also determines which information a token can access. Token-wise LN/RMSNorm use only that position’s coordinates, so they do not introduce access to later positions. The next methods show what changes when statistics cross tokens or examples. Image-based variants are included to interpret vision components and to make the axis comparison precise.
3.1 BatchNorm: Compare the Same Feature across Examples
3.1 BatchNorm:跨 Examples 比较同一个 Feature
Suppose a batch contains vectors $(1,10)$, $(3,20)$, and $(5,30)$. LN compares the two entries within each row. BN compares the first coordinate across the three rows, and separately the second coordinate. The column means are $(3,20)$. Ignoring $\epsilon$ and affine parameters, the BN outputs are approximately $(-1.225,-1.225)$, $(0,0)$, and $(1.225,1.225)$.
Why compare columns? A coordinate represents the same learned feature across examples, so BN estimates that feature’s typical level and variability. For an image tensor $[B,C,H,W]$, it pools over $B,H,W$ independently for each channel $C$. The channel’s affine parameters are shared over examples and positions. BatchNorm paper
For sequence data written as $[B,T,d]$, a common temporal BN convention pools over $B,T$ per coordinate. Pooling over the full sequence during autoregressive training can leak future information through the statistics. This is one reason to distinguish “supports tensors of this shape” from “preserves this model’s causal structure.”
Training normally uses current-batch statistics and maintains running estimates. Evaluation normally uses those saved estimates, so one example’s prediction no longer depends on its evaluation companions. In PyTorch, training normalization uses the biased batch variance, while the running variance update uses an unbiased estimate; turning off running-stat tracking changes evaluation behavior. BatchNorm1d documentation
Small or correlated batches provide noisy statistics. Batch size 1 is not automatically undefined for image BN because spatial positions still contribute, but many correlated pixels are not equivalent to many independent images. Gradient accumulation also does not merge the normalization statistics of separate forward passes.
3.2 InstanceNorm and GroupNorm: Statistics inside One Example
3.2 InstanceNorm 与 GroupNorm:只在一个 Example 内统计
InstanceNorm takes one example and one channel, then standardizes that channel over spatial positions. For $[B,C,H,W]$, its group is $H\times W$ at fixed $(b,c)$. It can remove an image’s channel-specific contrast and offset, which is useful in style transfer but may discard meaningful absolute intensity. The usual instance-statistics configuration uses each input’s statistics in both phases. InstanceNorm
GroupNorm puts $C/G$ channels into each of $G$ groups within an example and pools over those channels and spatial positions. More channels contribute to each estimate than in IN, while other examples remain excluded. Require $G$ to divide $C$. GroupNorm
At $G=C$, GN has IN’s statistical groups. At $G=1$, it normalizes the entire example over $C,H,W$. This equals LN’s statistics only if LN is configured over those same axes. It is not the same as normalizing channels independently at every pixel or token. Affine parameter shapes may still differ even when reduction groups match.
3.3 A Tensor View of the Differences
3.3 从 Tensor 中看清这些区别
The figure uses $[B,T,D]$. For images, interpret $T$ as flattened spatial positions and $D$ as channels. For sequences, $T$ is token position and $D$ is hidden width. Orange points form one reduction group. Rotate the figure: a line means one axis varies; a plane means two axes vary. The geometry describes membership in a group, not the shape of the normalization formula or the output tensor.
| Method | Fixed indices | Reduced indices | Common learned parameters |
|---|---|---|---|
| Token LN / RMSNorm | example, token | hidden coordinates | per coordinate |
| Temporal BN | coordinate | examples, tokens | per coordinate |
| Image BN | channel | examples, height, width | per channel |
| Image IN | example, channel | height, width | optional per channel |
| Image GN | example, channel group | channels in group, height, width | per channel |
3.4 Useful BatchNorm Variants
3.4 常用与有用的 BatchNorm 变体
SyncBatchNorm synchronizes training statistics across participating devices, increasing the group beyond one device’s local batch. It adds communication and retains BN’s dependence on which examples contribute. Frozen BN keeps saved statistics fixed, commonly when transferring a pretrained vision backbone; whether its affine parameters are also frozen is a separate choice. SyncBatchNorm documentation
Ghost BatchNorm goes the other way: compute statistics on smaller virtual sub-batches inside a large batch. The optimizer can still aggregate gradients over the large batch. Batch Renormalization adds bounded corrections based on running statistics to reduce the discrepancy between training’s batch-dependent normalization and inference. Neither operation is equivalent to LN. Ghost BN, Batch Renormalization
There are also methods that learn how to combine normalization statistics, such as Switchable Normalization, and methods combining batch and channel normalization, such as Batch-Channel Normalization. Their defining extra decision is how multiple statistical references are mixed or composed. Switchable Normalization, BCN
4. Conditional Normalization: AdaLN and Related Methods
4. 条件化 Normalization:AdaLN 及其相关方法
In a causal text LM, the prefix already conditions each hidden state through attention. AdaLN adds another possible route: a conditioning vector explicitly chooses feature scales and shifts. That vector could describe an externally supplied task or come from an available prefix. It must not include unseen future tokens. The diffusion examples below explain the method’s established setting; AdaLN is an architectural option, not a required component of next-token prediction.
4.1 Let the Condition Choose Scale and Shift
4.1 让 Condition 决定 Scale 与 Shift
Ordinary LN uses the same learned $\gamma,\beta$ for every example. Suppose a generative model must respond differently to a noise level or a class label. Let $c$ be a vector encoding that condition. A small network can turn $c$ into the scale and shift:
\[s(c),b(c)=\operatorname{MLP}(c),\qquad \operatorname{AdaLN}(x,c)=(1+s(c))\odot\operatorname{LN}_0(x)+b(c).\]$\operatorname{LN}_0$ denotes LN without learned affine parameters. The symbol $\odot$ means elementwise multiplication. The $1+s$ convention makes $s=0$ correspond to unit scale; a formulation using $\gamma(c)$ directly is equivalent after changing parameterization.
For $x$ of shape $[B,T,d]$ and global conditions $c$ of shape $[B,d_c]$, the predicted $s,b$ have shape $[B,d]$ and are broadcast over tokens. Different examples may receive different modulations, while all tokens of one example share that modulation. Input statistics are still computed separately per token.
For a simple example, suppose two normalized coordinates are $(-1,1)$. One condition predicts $s=(0,0),b=(0,0)$ and leaves them unchanged. Another predicts $s=(1,0),b=(0,3)$ and produces $(-2,4)$. The condition can amplify a feature and change its baseline before the next computation. This is conditional feature modulation; it does not alter which axes LN reduces. DiT paper
4.2 AdaLN-Zero: Start a Residual Branch at Zero
4.2 AdaLN-Zero:让 Residual Branch 从零贡献开始
Scale and shift control the input to a sublayer. We can separately control how much of its output is added to the residual stream:
\[h=x+\alpha(c)\odot F\!\left(\operatorname{AdaLN}(x,c)\right).\]The gate $\alpha(c)$ is another condition-dependent vector. If it starts at zero, this sublayer initially returns $h=x$. In a DiT-style block, attention and FFN have separate scale, shift, and gate vectors: six vectors altogether. Zero-initializing the final modulation projection gives zero shifts, zero scale deviations, and zero gates. This is the relevant zero initialization, not setting every attention and FFN weight to zero. DiT reference implementation
There is a useful gradient consequence. On the first step, a zero gate suppresses the loss gradient into that residual branch’s internal weights. The gate can still receive a gradient proportional to the branch output; once it moves away from zero, the branch can learn through it. This provides a gradual way to introduce residual changes.
4.3 FiLM, Conditional BN, AdaIN, and SPADE
4.3 FiLM、Conditional BN、AdaIN 与 SPADE
FiLM is the general featurewise affine modulation $\gamma(c)\odot x+\beta(c)$. Normalization is optional: FiLM itself does not require subtracting a mean or dividing by a variance. AdaLN combines this conditioning idea with LN. Conditional BatchNorm combines condition-dependent affine parameters with BN’s statistics. An adaptive RMS variant similarly combines condition-dependent gains, and optionally shifts, with an RMS-normalized input; the actual formula should be stated because naming conventions vary. FiLM
AdaIN obtains a target channel mean and standard deviation directly from style features $s$, then applies them to standardized content features $x$:
\[\operatorname{AdaIN}(x,s) =\sigma(s)\odot\frac{x-\mu(x)}{\sqrt{\sigma^2(x)+\epsilon}}+\mu(s).\]Each statistic is computed over spatial positions within a channel. This connects style control to matching feature statistics; with positive $\epsilon$, matching is approximate. AdaIN
SPADE lets the modulation vary across spatial locations, predicted from a semantic layout. A global class condition might ask for “a street”; a spatial condition can indicate where the road and buildings belong. Its scale and shift maps therefore retain position indices rather than being broadcast uniformly over the image. SPADE
5. Normalizing Weights and Attention Scores
5. 对 Weights 与 Attention Scores 进行 Normalization
LMs contain learned projections for Q/K/V, FFNs, and the vocabulary head. Controlling a projection’s weights is a different intervention from normalizing the token vector supplied to it. We first compare weight-based operations, then examine the attention-specific choices: fixed dimension scaling and normalization of individual queries and keys. These operations can coexist at different sites.
5.1 WeightNorm and Weight Standardization
5.1 WeightNorm 与 Weight Standardization
So far, statistics have come from activations. We can instead change how a neuron’s weight vector is represented:
\[w=g\frac{v}{\lVert v\rVert_2}.\]In WeightNorm, optimization learns $v$ and a scalar $g$. One parameter controls direction, the other magnitude. There is no batch statistic and no promise that the resulting activations have zero mean or unit variance. WeightNorm
Weight Standardization centers and rescales the entries within each output filter:
\[\hat w=\frac{w-\operatorname{mean}(w)} {\sqrt{\operatorname{mean}((w-\operatorname{mean}(w))^2)+\epsilon}}.\]For a convolution, the reduction covers input channels and kernel positions for one output channel. This acts on weights; GN can separately act on the resulting activations. Their combination is useful in the micro-batch setting studied by the WS work. Weight Standardization
5.2 SpectralNorm: Limit the Largest Amplification
5.2 SpectralNorm:限制最大的放大倍数
Normalizing each weight vector does not directly control how a full matrix amplifies arbitrary inputs. Its spectral norm, the largest singular value, answers that question:
\[\sigma_{\max}(W)=\max_{\lVert u\rVert_2=1}\lVert Wu\rVert_2,\qquad \bar W=\frac{W}{\sigma_{\max}(W)}.\]If $W$ stretches one axis by 3 and another by 1, its spectral norm is 3. Dividing the whole matrix by 3 limits the largest stretch to 1; the second axis now stretches by $1/3$. This preserves relative singular values, rather than making all directions equally strong.
With exact normalization and nonzero $W$, $\lVert\bar Wx-\bar Wy\rVert_2\le\lVert x-y\rVert_2$. This is a Lipschitz bound for that linear map. Implementations usually estimate the largest singular value by power iteration; an approximate estimate is not an exact certificate. Residual additions and other layers must be accounted for when discussing the full network. For convolutions, normalizing a reshaped kernel need not give the exact norm of the full spatial convolution operator. Spectral Normalization
5.3 Dividing by √dₖ: Fixed Statistical Scaling
5.3 除以 √dₖ:固定的统计尺度归一化
Yes: dividing attention scores by $\sqrt{d_k}$ is normalization in the broad sense of setting a reference scale. It is usually called scaled dot-product attention. Unlike LN or RMSNorm, the denominator is fixed by the head dimension, rather than measured from the current activations:
\[s_{ij}=\frac{q_i^\top k_j}{\sqrt{d_k}}.\]Why does dimension enter? One dot product sums $d_k$ coordinate products. Suppose the query and key coordinates are independent, zero-mean, and unit-variance. Each product then has variance 1, and the sum has variance $d_k$. Its standard deviation, a measure of typical magnitude, is $\sqrt{d_k}$. Dividing by that number returns the variance to 1 under these assumptions. Scaled dot-product attention
For example, increasing head width from 16 to 64 increases the unscaled score’s standard deviation from 4 to 8 in this toy model. Without compensation, a wider head can produce sharper attention merely because it sums more terms. The divisor compensates for this predictable dimensional effect.
The issue is the difference between competing scores. In a two-key example, one key’s softmax weight is a sigmoid of the score gap. Very large positive or negative gaps place it in a flat tail where small score changes barely move the weight. Scaling helps avoid this source of small softmax derivatives. It does not guarantee that the full loss gradient is small or large: that also depends on the downstream loss and the rest of the computation. The sigmoid illustration makes this local sensitivity visible.
The assumptions also explain the limitation. Learned queries and keys need not retain unit variance or independence. If their magnitudes grow during training, a fixed $\sqrt{d_k}$ cannot respond. It neither forces each score row to unit variance nor makes each query a unit vector.
Why a square root, rather than dₖ? (Click to expand)
For independent zero-mean summands, variances add. The variance grows by a factor of $d_k$, so the standard deviation grows by $\sqrt{d_k}$. Dividing the score by $d_k$ instead would give variance $1/d_k$, progressively shrinking the logits as width grows. That would compute an average coordinate product, which has a different scale target.
If query and key coordinates have variances $\sigma_q^2$ and $\sigma_k^2$, the same independence calculation gives unscaled score variance $d_k\sigma_q^2\sigma_k^2$. After division by $\sqrt{d_k}$, the variance is $\sigma_q^2\sigma_k^2$, not necessarily 1. The operation cancels width, not arbitrary activation scale.
5.4 QK-Norm and Softmax Have Different Jobs
5.4 QK-Norm 与 Softmax 分别在做什么?
In attention, the score $q^\top k$ depends on both vector lengths and their alignment. The original QK-Norm proposal L2-normalizes each query and key along the head dimension and uses a learned scale for the resulting cosine score:
\[s_{ij}=g\left(\frac{q_i}{\lVert q_i\rVert_2}\right)^\top \left(\frac{k_j}{\lVert k_j\rVert_2}\right).\]The learned scale controls how sharp attention can become without requiring Q/K magnitudes to grow. This proposal replaces the usual fixed $1/\sqrt{d_k}$ score scaling. “QK normalization” can also refer to architectures applying LN or RMSNorm to Q and K; axis, affine parameters, and subsequent score scaling must be specified. Original QK-Norm
Softmax comes after these scores and a visibility mask. It converts allowed scores into nonnegative weights that sum to 1. L2-normalizing a key vector does not create attention probabilities, and softmax does not standardize the Q/K coordinates. Attention and Language Models follows the full Q/K/V computation.
6. Putting Normalization into a Model
6. 把 Normalization 放进模型
6.1 Pre-Norm, Post-Norm, and the Residual Path
6.1 Pre-Norm、Post-Norm 与 Residual Path
Choosing the function and choosing its position are separate decisions. Let $N$ be LN or RMSNorm and $F$ an attention or FFN sublayer:
\[\text{Pre-Norm:}\quad y=x+F(N(x)), \qquad \text{Post-Norm:}\quad y=N(x+F(x)).\]Pre-Norm gives the sublayer a normalized input while keeping the residual bypass unchanged. Post-Norm normalizes the result of the addition, so the bypass also passes through normalization. A block containing attention and FFN usually has a separate normalization site and residual addition for each sublayer. A final normalization can then precede the output head. Pre-Norm analysis
For Pre-Norm, the local derivative includes an identity term: $I+J_FJ_N$. This gives gradients a direct path, though it does not guarantee stability through an arbitrary stack. Notice also that LN discards offset only on the normalized branch; the residual path can preserve the original information. The full block therefore has different invariances from LN in isolation.
Return to $x_A=(1,2,3)$ and $x_B=10x_A$. Ignore $\epsilon$, and fix all other inputs and any randomness. LN or RMSNorm maps these two states to the same normalized input, so the sublayer computes the same update $u$. The residual outputs are nevertheless $x_A+u$ and $10x_A+u$, which remain different.
If $u$ is not parallel to $x_A$, those outputs generally have different directions as well. For example, with $u=(1,0,0)$ they are $(2,2,3)$ and $(11,20,30)$; even a subsequent LN distinguishes their centered patterns. Thus scale preserved by a residual path can influence information read by a later normalized branch. This is a possible route, not a guarantee: a final normalization can still erase distinctions that remain only a common positive scale (and, for LN, a common offset).
The distinction matters when assessing whether normalization is appropriate for an LM. Training with normalization allows upstream weights to develop useful representations under these constraints. Inserting it into an already trained model is not generally equivalent: it can change attention, residual updates, and predictions. Nor does a large norm automatically indicate greater semantic importance; its effect must be traced through the actual computation.
LayerScale, ReZero, and depth-dependent residual scaling adjust the strength of residual branches. They are related stabilization choices, but do not themselves compute an activation mean, variance, or norm. AdaLN-Zero combines modulation with such a gate. LayerScale, ReZero
6.2 Read the Reduction Axis in Code
6.2 在代码中读清 Reduction Axis
The snippet below implements vector L2, token LN, RMSNorm, and conditional LN in PyTorch. Hover or select a highlighted expression to see its shape and role beside the code. These are transparent mathematical implementations; production kernels may fuse the same operations. For low-precision inputs, the reductions are accumulated in float32 before casting the result back.
For $[B,T,d]$, reducing over the last axis with keepdim=True produces $[B,T,1]$. Broadcasting repeats each scalar over that token’s $d$ coordinates. AdaLN instead broadcasts a condition’s $[B,d]$ modulation as $[B,1,d]$. These two singleton axes serve different purposes.
Use the centered-square variance formula to avoid subtracting two large nearly equal quantities. Treat $\epsilon$ as part of the definition: adding it inside a square root, outside a square root, or using a clamped norm are different operations near zero.
7. Other Useful Meanings of Normalization
7. 其他有用的 Normalization
Token IDs are categorical indices into an embedding table; their numerical mean and variance do not describe word meaning. The input preprocessing methods below instead concern continuous features, such as audio/image inputs to a multimodal model or embedding representations in a downstream pipeline. They should not be applied to token IDs as if those IDs were measured quantities.
7.1 Input Scaling, Robust Scaling, and Whitening
7.1 Input Scaling、Robust Scaling 与 Whitening
Before a network, z-score standardization uses a training dataset’s per-feature mean and standard deviation. Save them and reuse them for validation and test data. Unlike token LN, this applies a fixed reference learned from the dataset. Min-max scaling maps training extrema to a target range; new out-of-range inputs can still fall outside it. Robust scaling uses a median and a quantile range, making the reference less sensitive to extreme values. It does not remove outliers automatically. Preprocessing reference
Whitening goes beyond independent feature scaling by transforming the covariance matrix toward identity. If the centered data have covariance $\Sigma$, a regularized symmetric whitening transform is
\[z=(\Sigma+\epsilon I)^{-1/2}(x-\mu).\]The matrix inverse square root rotates and rescales correlated directions. Without regularization and with invertible $\Sigma$, the transformed covariance is identity. With $\epsilon>0$, this is approximate. LN only controls the statistics within its selected group; it does not perform this covariance transformation.
7.2 Match the Operation to the Purpose
7.2 根据要解决的问题选择操作
| Purpose | Relevant family | What to check |
|---|---|---|
| Compare embedding directions | L2, fixed-length normalization | Does magnitude carry useful information? |
| Stabilize each token representation | LN, RMSNorm, ScaleNorm | Centering, coordinate gains, residual placement |
| Standardize image features across examples | BN and SyncBN | Batch statistics, evaluation reference |
| Normalize images without batch dependence | GN, IN | Channel groups and spatial axes |
| Inject global or spatial conditions | AdaLN, AdaIN, conditional BN, SPADE | Source and shape of modulation |
| Separate weight direction and size | WeightNorm | Reparameterization and learned gain |
| Standardize individual weight filters | Weight Standardization | Which filter dimensions are reduced? |
| Control a matrix’s largest amplification | SpectralNorm | Operator definition and estimation accuracy |
| Compensate for attention head width | Fixed $1/\sqrt{d_k}$ scaling | Variance assumptions; no input statistics |
| Control attention score magnitude | QK normalization | Head dimension, score scale, mask |
| Adjust input units and correlations | Standardization, robust scaling, whitening | Fit statistics using training data |
Two related terms deserve a final distinction. Gradient clipping scales a gradient down only when it exceeds a threshold; gradient normalization sets a target norm. Adam’s second-moment scaling uses an optimizer state accumulated across steps. These act on updates or gradients, not hidden activations, and are developed in Basics of Optimizers.
Other specialized methods include Local Response Normalization (local competition across neighboring channels) and FRN (per-channel spatial RMS normalization paired with a thresholded activation). Their groups and transforms differ from token RMSNorm. LRN documentation, Filter Response Normalization
When encountering another “Norm,” reconstruct its group, measurement, transform, learned parameters, and train/eval behavior. Those five pieces are enough to place it in this framework and to identify what an implementation actually does.