Simple Algorithm
Deep Learning · Emergence · 28 min

Normalization & Stability in Transformers

Pre-LN versus Post-LN, logit growth, QK-norm and loss spikes.

The original transformer put LayerNorm after each residual addition and could not be trained well without a learning-rate warmup; moving the normalization inside the branch fixed that and became the default. At scale, new failures appeared: attention logits that grow until attention collapses onto single tokens, output logits that drift, and loss spikes that strike without warning. This lesson works through the theory of where the normalization goes, and the remedies large training runs adopted: rescaled residuals, QK-norm, the z-loss and more.

What you’ll learn

  • State and interpret the theorem that Post-LN transformers have depth-independent gradients near the output at initialization, while Pre-LN's shrink like 1/L1/\sqrt L, and connect it to warmup.
  • Explain the amplification effect, by which a Post-LN model's output moves O(N)\order{N} under a parameter perturbation against O(log⁡N)\order{\log N} for Pre-LN, and derive DeepNorm's constants (2N)1/4(2N)^{1/4} and (8N)−1/4(8N)^{-1/4}.
  • Show that attention logits grow quadratically in the query and key weights, state the lower bound on attention entropy, and bound the logits under QK-norm.
  • Explain output-logit divergence and the z-loss, and how small models at high learning rates reproduce large-scale instabilities.
  • Describe loss spikes and the remedies of large training runs, and Pre-LN's own weakness, separating established results from open questions.

Post-LN, Pre-LN and the warmup puzzle

The original transformer (Vaswani et al., 2017) normalized after each residual addition and raised its learning rate linearly over the first 4,000 steps. For a sublayer FF (attention or the MLP), the two standard arrangements are:

Post-LN:  xl+1=LN⁡(xl+F(xl)),Pre-LN:  xl+1=xl+F(LN⁡(xl)),  output from LN⁡(xL)\text{Post-LN: }\ \mathbf x_{l+1} = \operatorname{LN}\big(\mathbf x_l + F(\mathbf x_l)\big),\qquad\text{Pre-LN: }\ \mathbf x_{l+1} = \mathbf x_l + F\big(\operatorname{LN}(\mathbf x_l)\big),\ \ \text{output from }\operatorname{LN}(\mathbf x_L)
Post-LN normalizes the residual stream itself; Pre-LN normalizes only what each branch reads and adds one final normalization before the output layer.

The difference is not cosmetic. On IWSLT German–English translation with Adam, a Post-LN transformer trained without warmup reached a BLEU score of only 8.45, against about 34 with 4,000 warmup steps, and even 500 warmup steps gave 31.16 or 2.77 depending on the peak learning rate. Pre-LN transformers trained without any warmup to comparable results, and faster (Xiong et al., 2020). Their explanation is a calculation at initialization.

DerivationWhy: LayerNorm divides gradients by the size of its input
  1. ∥∂LN⁡(x)∂x∥2=O(d∥x∥2)\Big\lVert\frac{\partial\operatorname{LN}(\mathbf x)}{\partial\mathbf x}\Big\rVert_2 = \order{\frac{\sqrt d}{\norm{\mathbf x}_2}}

    LayerNorm's Jacobian has norm of order d/∥x∥\sqrt d/\norm{\mathbf x}: a gradient passing back through it is divided by the size of the input (Deriving Backward Passes derives the exact projection).

  2. (1+l2)d ≤ E∥xl∥2 ≤ (1+3l2)d\Big(1 + \frac l2\Big)d\ \le\ \E\norm{\mathbf x_l}^2\ \le\ \Big(1 + \frac{3l}{2}\Big)d

    In Post-LN every block's output is normalized, so the stream has norm of order d\sqrt d at every depth. In Pre-LN nothing normalizes the stream, and every branch adds to it; at initialization its squared norm grows linearly in the layer index ll:

  3. Post-LN: O(dln⁡d),Pre-LN: O(dln⁡dL)\text{Post-LN: }\order{d\sqrt{\ln d}},\qquad\text{Pre-LN: }\order{d\sqrt{\frac{\ln d}{L}}}

    The last sublayer's gradient passes back through the final normalization. In Pre-LN its input has norm of order Ld\sqrt{Ld}, so the gradient is divided by L\sqrt L; in Post-LN no such factor appears, and the gradient near the output stays large however deep the model. Xiong et al.'s less formal analysis of the other layers adds that Post-LN's gradients are largest near the output and tend to decay toward the input, while Pre-LN's are similar in every layer. That is an approximate picture: for the widget's tanh model, Residual Connections derives a slow power-law growth of the Pre-LN gradient with depth.

Measured at initialization on translation models of 6 to 14 layers, the last sublayer's gradient norm stayed near 1.61.6 in Post-LN as depth grew and shrank in Pre-LN, as the theorem predicts. A full learning rate applied to the large gradients at the top destabilizes Post-LN early on, and warmup keeps the learning rate small until that phase has passed. This is one account of why warmup helps; Why Warmup Works weighs it against others, such as Adam's noisy early estimates of the second moments.

Predict before you look

By the lemma above, after l=48l = 48 layers of a Pre-LN transformer at initialization, E∥xl∥2≥(1+l/2) d\E\norm{\mathbf x_l}^2\ge(1 + l/2)\,d. What is the corresponding lower bound on the stream's RMS, as a multiple of the input's RMS (which is 11, since E∥x0∥2=d\E\norm{\mathbf x_0}^2 = d)?

Show the answer

5 ×

1+48/2=25=5\sqrt{1 + 48/2} = \sqrt{25} = 5, and the upper bound is 1+72≈8.5\sqrt{1 + 72}\approx8.5. Every Pre-LN branch then adds a signal of fixed size to a stream five to eight times larger, which is why late branches start as small corrections, and why their gradients are well behaved.

Amplification, Admin and DeepNorm

If Post-LN only needed warmup, the story would end there. But deep Post-LN transformers diverge even with warmup, and when they do train they often end up better than Pre-LN ones. Liu et al. (2020) argued that unbalanced gradients are not the root cause, and identified an amplification effect. Write each Post-LN block as xi=LN⁡(bi)\mathbf x_i = \operatorname{LN}(\mathbf b_i) with bi=xi−1+fi(xi−1)\mathbf b_i = \mathbf x_{i-1} + f_i(\mathbf x_{i-1}), and let βi,i2\beta_{i,i}^2 be the share of bi\mathbf b_i's variance that comes from its own branch fif_i: how much layer ii depends on its residual branch.

The prediction held up: the measured output shift grew linearly in NN for Post-LN and like log⁡N\log N for Pre-LN (R2=0.99R^2 = 0.99 for random perturbations). With actual Adam updates in place of random noise the fit was weaker (R2=0.75R^2 = 0.75), but Post-LN's shift was still larger by orders of magnitude. Heavy dependence on the branches is what gives Post-LN its potential, and what makes every update shake the output. Liu et al.'s Admin keeps the potential and tames the start: it computes bi=xi−1⊙ωi+fi(xi−1)\mathbf b_i = \mathbf x_{i-1}\odot\boldsymbol\omega_i + f_i(\mathbf x_{i-1}), with ωi\boldsymbol\omega_i initialized from one profiling batch to ∑j<iVar⁡[fj]\sqrt{\sum_{j<i}\Var[f_j]}, so that early on βi,i2≈1/i\beta_{i,i}^2\approx1/i as in Pre-LN, after which training is free to change it.

DeepNet (Wang et al., 2022) bounded the update itself. Its DeepNorm computes xl+1=LN⁡(α xl+Gl(xl))\mathbf x_{l+1} = \operatorname{LN}(\alpha\,\mathbf x_l + G_l(\mathbf x_l)), up-weighting the skip path by a constant α>1\alpha > 1 before the normalization, and shrinks the initialization of some weights by a factor β\beta.

DerivationDeriving DeepNorm’s constants (encoder-only or decoder-only, N layers)
  1. ∥ΔF∥ ≤ ∑i=12Nvi2+wi2α ∥θi∗−θi∥\norm{\Delta F}\ \le\ \sum_{i=1}^{2N}\frac{\sqrt{v_i^2 + w_i^2}}{\alpha}\,\norm{\boldsymbol\theta_i^* - \boldsymbol\theta_i}

    Reduce each sublayer to one dimension, with two weights vv and ww (the value and output projections, or the MLP's two matrices). For the 2N2N sublayers of an NN-layer model, Wang et al. prove that the change of the output after a parameter update obeys the bound below. Vanilla Post-LN is the case α=1\alpha = 1, v=w=1v = w = 1: the bound is the sum of all the sublayer updates, which accumulate with depth.

  2. ∥ΔF∥ ≲ 2N η v2+w2α2\norm{\Delta F}\ \lesssim\ 2N\,\eta\,\frac{v^2 + w^2}{\alpha^2}

    One SGD step moves θi\boldsymbol\theta_i by η∥∂L/∂θi∥\eta\norm{\partial\loss/\partial\boldsymbol\theta_i}, and in this model the output's sensitivity to θi\boldsymbol\theta_i is of order v2+w2/α\sqrt{v^2 + w^2}/\alpha. With all sublayers alike:

  3. α=(2N)1/4,β=(8N)−1/4\alpha = (2N)^{1/4},\qquad\beta = (8N)^{-1/4}

    Ask, as Fixup did, for a change of Θ(η)\Theta(\eta) per step, and split the factor 2N2N evenly between the skip weight and the initialization: α2=(2N)1/2\alpha^2 = (2N)^{1/2} and v2+w2=(2N)−1/2v^2 + w^2 = (2N)^{-1/2}. With v=w=βv = w = \beta:

  4. In practice β\beta is the gain of the Xavier initialization of the MLP weights and of the value and output projections (queries and keys keep gain 11), and α\alpha multiplies the residual before each LayerNorm. Encoder–decoder models get their own constants from the same argument.

Predict before you look

A decoder-only model with N=64N = 64 layers uses DeepNorm, α=(2N)1/4\alpha = (2N)^{1/4}. What is α\alpha?

Show the answer

3.36

(2⋅64)1/4=1281/4≈3.36(2\cdot64)^{1/4} = 128^{1/4}\approx3.36, and the initialization gain is β=512−1/4≈0.21\beta = 512^{-1/4}\approx0.21. Doubling the depth raises α\alpha only by 21/4≈1.192^{1/4}\approx1.19: the constants change slowly enough to scale to very deep models.

With these constants Wang et al. trained a translation transformer with 1,000 layers (2,500 attention and feedforward sublayers), and a 200-layer model with 3.2 billion parameters beat a 48-layer model with 12 billion by 5 BLEU on a benchmark of 7,482 translation directions. On WMT-17 English–German, vanilla Post-LN diverged already at 18 encoder and 18 decoder layers, Pre-LN trained at 100 and 100 but reached 27.4 BLEU, and DeepNet 28.9. Scaling Residual Branches with Depth treats branch scaling as depth grows in general.

Attention logits that grow: entropy collapse and QK-norm

Pre-LN normalizes what each attention layer reads, not the weights it reads with. With normalized token vectors x^i\hat{\mathbf x}_i as rows and Q=X^WQQ = \hat XW_Q, K=X^WKK = \hat XW_K, a logit of one head is sij=x^iWQWK⊤x^j⊤/dks_{ij} = \hat{\mathbf x}_iW_QW_K^\top\hat{\mathbf x}_j^\top/\sqrt{d_k}: bilinear in the two projections. Normalization fixes the size of x^\hat{\mathbf x}, but nothing fixes the size of WQWK⊤W_QW_K^\top except weight decay, and large learning rates make it grow quickly.

As the logits grow, each row of the softmax approaches a one-hot vector. The attention entropy −∑jaijlog⁡aij-\sum_ja_{ij}\log a_{ij} falls toward zero, and the softmax Jacobian diag⁡(a)−aa⊤\diag(\mathbf a) - \mathbf a\mathbf a^\top, through which every gradient to the queries and keys must pass, vanishes: a collapsed row stops responding to small changes of its logits. (The network's gradients need not be small, though: Zhai et al. (2023) found entropy collapse accompanied by large gradient norms rather than vanishing ones.) Dehghani et al. (2023) met this when scaling vision transformers: a model of about 8 billion parameters diverged after a few thousand steps because of extremely large attention logits, which produced almost one-hot attention weights with near-zero entropy. Their fix, following then-unpublished work by Gilmer et al., normalizes the queries and keys before the dot product, QK-norm:

A=softmax⁡ ⁣(1dkLN⁡(XWQ) LN⁡(XWK)⊤)A = \softmax\!\Big(\frac{1}{\sqrt{d_k}}\operatorname{LN}(XW_Q)\,\operatorname{LN}(XW_K)^\top\Big)
In ViT-22B the LayerNorms had no bias and no centering. Henry et al. (2020) had proposed a similar QKNorm for low-resource translation, normalizing queries and keys to unit length and replacing 1/dk1/\sqrt{d_k} by a learned scale. Language models adopted it too; OLMo 2, for instance, normalizes queries and keys with RMSNorm (Team OLMo, 2024).
DerivationHow QK-norm bounds the logits
  1. sij(cWQ,cWK)=c2 sij(WQ,WK)s_{ij}(cW_Q, cW_K) = c^2\,s_{ij}(W_Q, W_K)

    Without it, scaling both projections by cc scales every logit by c2c^2, whatever the normalized input: the logits can grow quadratically in the weights.

  2. ∣sij∣=∣∑mγq,mγk,mumvm∣dk ≤ max⁡m∣γq,mγk,m∣ ∥u∥ ∥v∥dk=dk max⁡m∣γq,mγk,m∣\abs{s_{ij}} = \frac{\big|\sum_m\gamma_{q,m}\gamma_{k,m}u_mv_m\big|}{\sqrt{d_k}}\ \le\ \frac{\max_m\abs{\gamma_{q,m}\gamma_{k,m}}\,\norm{\mathbf u}\,\norm{\mathbf v}}{\sqrt{d_k}} = \sqrt{d_k}\,\max_m\abs{\gamma_{q,m}\gamma_{k,m}}

    With it, each head's query and key are first normalized to vectors u,v∈Rdk\mathbf u,\mathbf v\in\R^{d_k} of norm dk\sqrt{d_k} (LayerNorm or RMSNorm without bias, ϵ→0\epsilon\to0), then multiplied by learned gains γq,γk\boldsymbol\gamma_q,\boldsymbol\gamma_k. Cauchy–Schwarz bounds the logit by the gains alone:

  3. With unit gains and dk=128d_k = 128, logits lie within ±128≈±11.3\pm\sqrt{128}\approx\pm11.3, so gaps of up to about 22.622.6: still enough for one key to take more than 99.99% of the attention among 4,096. QK-norm does not forbid sharp attention. It makes sharpening go through 2dk2d_k gain parameters per head instead of through the product of two weight matrices, so the logits can no longer grow quadratically in the weights.

Zhai et al. observed low attention entropy accompanying training instability, as oscillating loss or divergence, across vision, speech and language tasks, and named the pathology entropy collapse. Their remedy, σ\sigmaReparam, controls the spectral norm directly: every weight matrix is reparameterized as W^=(γ/σ(W)) W\hat W = (\gamma/\sigma(W))\,W, with σ(W)\sigma(W) the spectral norm estimated by power iteration (as in spectral normalization) and γ\gamma a learnable scalar starting at 11. It let a vision transformer train to competitive accuracy without warmup, weight decay, LayerNorm or an adaptive optimizer.

The instability does not need billions of parameters. Wortsman et al. (2023) reproduced it in models of about 10 million parameters simply by training at high learning rates: without QK-norm the largest attention logit grew by orders of magnitude and the loss diverged. With QK-norm, and the z-loss of the next screen, the same small models trained successfully across three orders of magnitude of learning rate, which made these instabilities cheap to study.

Output logits, the z-loss and loss spikes

A second drift happens at the other end of the network. Cross-entropy depends on the output logits y\mathbf y only through their differences, ℓ=−yt+log⁡Z\ell = -y_t + \log Z with Z=∑keykZ = \sum_ke^{y_k}, so it is blind to their overall level, and nothing else anchors it. Wortsman et al. found that at high learning rates, models trained without weight decay saw their output logits diverge toward very negative values late in training, taking the loss with them, at every scale they tried; weight decay also mitigated it for their larger models. Chowdhery et al. (2022) had guarded PaLM against this drift with an auxiliary z-loss, 10−4log⁡2Z10^{-4}\log^2Z, which they found increased training stability.

DerivationWhat the z-loss does
  1. ℓ(y+c1)=−(yt+c)+log⁡∑keyk+c=ℓ(y),log⁡Z(y+c1)=log⁡Z(y)+c\ell(\mathbf y + c\mathbf 1) = -(y_t + c) + \log\sum_ke^{y_k + c} = \ell(\mathbf y),\qquad\log Z(\mathbf y + c\mathbf 1) = \log Z(\mathbf y) + c

    The level of the logits is a direction the cross-entropy cannot see, while log⁡Z\log Z moves with it:

  2. ∂∂yk(λlog⁡2Z)=2λ log⁡Z  pk\frac{\partial}{\partial y_k}\big(\lambda\log^2Z\big) = 2\lambda\,\log Z\;p_k

    Penalizing λlog⁡2Z\lambda\log^2Z pins that direction. With ∂log⁡Z/∂yk=pk\partial\log Z/\partial y_k = p_k, its gradient pushes the logits toward log⁡Z=0\log Z = 0, each in proportion to its probability:

  3. log⁡Z=0⟺yk=log⁡pk  for every k\log Z = 0\quad\Longleftrightarrow\quad y_k = \log p_k\ \text{ for every }k

    At log⁡Z=0\log Z = 0 the logits are exactly log-probabilities: the output layer is self-normalized. Since the cross-entropy is indifferent to the shift, the penalty can be satisfied at no cost in fit.

python
import torch
import torch.nn as nn
import torch.nn.functional as F

def loss_with_z(logits, targets, z_coef=1e-4):
    """Cross-entropy plus the z-loss of Chowdhery et al. (2022), averaged over tokens."""
    log_z = torch.logsumexp(logits, dim=-1)       # log of the softmax normalizer, per token
    ce = F.cross_entropy(logits, targets)         # equals mean(log_z - logits[target])
    return ce + z_coef * log_z.pow(2).mean()

class QKNormAttention(nn.Module):
    """Causal multi-head self-attention with LayerNorm on queries and keys."""
    def __init__(self, d, n_heads):
        super().__init__()
        self.h, self.dk = n_heads, d // n_heads
        self.qkv = nn.Linear(d, 3 * d, bias=False)
        self.q_norm = nn.LayerNorm(self.dk)       # per head, over the head dimension
        self.k_norm = nn.LayerNorm(self.dk)
        self.out = nn.Linear(d, d, bias=False)

    def forward(self, x):                         # x: (B, T, d)
        B, T, d = x.shape
        q, k, v = self.qkv(x).view(B, T, 3, self.h, self.dk).unbind(dim=2)
        q, k = self.q_norm(q), self.k_norm(k)     # logits now bounded by the norms' gains
        q, k, v = (t.transpose(1, 2) for t in (q, k, v))          # (B, heads, T, dk)
        o = F.scaled_dot_product_attention(q, k, v, is_causal=True)
        return self.out(o.transpose(1, 2).reshape(B, T, d))

Multiplying qkv.weight by 100 leaves this layer's logits within ±dk\pm\sqrt{d_k} at unit gains, while without the two LayerNorms they would grow ten-thousandfold. scaled_dot_product_attention applies the 1/dk1/\sqrt{d_k} itself.

Slow divergences are the tractable case: they can be reproduced and predicted. Loss spikes are sudden. While PaLM's 540-billion-parameter model trained, its loss spiked about 20 times despite gradient clipping, at irregular intervals and sometimes late in training; smaller models did not spike. The remedy was empirical: restart from a checkpoint about 100 steps before the spike and skip roughly 200 to 500 batches. Feeding the same batches to an earlier checkpoint caused no spike, so the spikes came from particular batches meeting a particular parameter state, not from bad data alone (Chowdhery et al., 2022).

OLMo 2's developers saw gradient-norm spikes that often preceded loss spikes and became more frequent as models grew, together with a slow rise of the gradient norm over training. Their fixes read like a summary of this lesson: filter out documents with long repeated n-gram sequences, which were associated with spikes; initialize every weight from a normal distribution with standard deviation 0.020.02; use RMSNorm; normalize each sublayer's output instead of its input, x+RMSNorm⁡(F(x))\mathbf x + \operatorname{RMSNorm}(F(\mathbf x)), a placement proposed for Swin Transformer V2 (Liu et al., 2022); add QK-norm and the z-loss; and lower AdamW's ϵ\epsilon from 10−510^{-5} to 10−810^{-8} (Team OLMo, 2024). Wortsman et al. explain why ϵ\epsilon matters: when the gradient's RMS falls to the size of ϵ\epsilon, as it did at the largest scale they tested, the update m^/(v^+ϵ)\hat{\mathbf m}/(\sqrt{\hat{\mathbf v}} + \epsilon) shrinks and layers stop learning; lowering ϵ\epsilon to 10−1510^{-15} improved a 4.8-billion-parameter model, while raising it to 10−610^{-6} caused an instability.

A related diagnosis comes from training CLIP models: their loss spikes came one to eight steps after AdamW's second-moment estimate fell behind the squared gradients. Clipping the update instead of the gradient (AdamW with Adafactor's update clipping, which lowers the step when the ratio of squared gradient to second-moment estimate is large) removed the spikes at the scales tested and worked better than gradient clipping (Wortsman, Dettmers et al., 2023).

InstabilitySymptomRemedies
Post-LN at initializationlarge gradients near the output; training fails without warmupwarmup; Pre-LN; Admin; DeepNorm
Attention-logit growththe largest attention logits grow by orders of magnitude, attention entropy collapses, the loss divergesQK-norm; σ\sigmaReparam; a lower learning rate
Output-logit divergencelogits drift to very negative values late in trainingz-loss; weight decay
Updates swamped by Adam's ϵ\epsilongradient RMS near ϵ\epsilon; updates shrink and layers stop learninga smaller ϵ\epsilon
Loss spikessudden jumps, often after gradient-norm spikesrestart and skip batches; filter repetitive data; update clipping; the remedies above
Wortsman et al. also found that longer warmup and decoupled weight decay reduce the final loss's sensitivity to the learning rate, and that increasing depth raises that sensitivity faster than increasing width.

Pre-LN’s weak spot, and what is open

Pre-LN's stability has a price. Its stream grows with depth, so each late block adds a fixed-size correction to an ever larger vector. Liu et al. found that this light dependence on the residual branches limits what a trained model reaches, which is why tamed Post-LN variants such as Admin and DeepNorm can end up better.

Sun et al. (2025) pressed the argument for modern language models. In several open Pre-LN model families (Llama, Mistral, DeepSeek, Qwen), removing one of the deeper layers barely changed performance, and consecutive deep layers produced nearly identical representations; in the Post-LN BERT-Large, removing deep layers did hurt. They bound the growth of the stream's variance between linear and exponential in depth, argue that this drives the Jacobians of deep blocks toward the identity, and propose LayerNorm Scaling: multiply the output of layer ℓ\ell's normalization by 1/ℓ1/\sqrt\ell. In their experiments, from 130 million to 7 billion parameters, it improved pretraining. How depth is used, and wasted, is the subject of Reading the Residual Stream.

Between the two classic arrangements lies a family of placements: keep Post-LN but rescale the skip path (Admin, DeepNorm), normalize the branch output instead of its input (OLMo 2), or bound the weights instead of the activations (σ\sigmaReparam). Which is best at scale is not settled as of the mid-2020s, and the answer interacts with the optimizer, the learning-rate schedule and the parameterization (μP & Hyperparameter Transfer).

Key takeaways

  • Post-LN, LN⁡(x+F(x))\operatorname{LN}(\mathbf x + F(\mathbf x)), has depth-independent gradients of order dln⁡dd\sqrt{\ln d} near the output at initialization and needs warmup; Pre-LN, x+F(LN⁡(x))\mathbf x + F(\operatorname{LN}(\mathbf x)), divides them by L\sqrt L because its stream grows (Xiong et al., 2020).
  • Post-LN layers depend heavily on their branches, so a parameter update moves the output by O(N)\order{N} against O(log⁡N)\order{\log N} for Pre-LN; Admin and DeepNorm (α=(2N)1/4\alpha = (2N)^{1/4}, β=(8N)−1/4\beta = (8N)^{-1/4}) keep Post-LN's performance with Pre-LN's stability.
  • Attention logits are bilinear in the query and key weights, so they can grow quadratically; attention entropy can then collapse, since its lower bound decays exponentially in the logits' spectral norm, and training diverges. QK-norm bounds the logits by the normalization gains; σ\sigmaReparam bounds the spectral norms.
  • Cross-entropy cannot see the overall level of the output logits; the z-loss 10−4log⁡2Z10^{-4}\log^2Z pins it, and weight decay helps. Both logit instabilities appear in small models at high learning rates, which makes them cheap to study.
  • Loss spikes in large runs are still handled empirically (restarting and skipping batches, filtering repetitive data, QK-norm, the z-loss, a small AdamW ϵ\epsilon); Pre-LN's growing stream also leaves late layers underused, and the best placement of normalization at scale is open.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

According to Xiong et al. (2020), how does the gradient of the last feedforward sublayer at initialization depend on the depth LL?

  1. In both arrangements it shrinks like 1/L1/\sqrt L
  2. In Post-LN it is of order dln⁡dd\sqrt{\ln d} whatever the depth; in Pre-LN it shrinks like 1/L1/\sqrt L, because the final normalization's input grows like L\sqrt L
  3. In Post-LN it shrinks like 1/L1/\sqrt L; in Pre-LN it is depth-independent
  4. In both arrangements it grows linearly with LL
Show the answer

B. In Post-LN it is of order dln⁡dd\sqrt{\ln d} whatever the depth; in Pre-LN it shrinks like 1/L1/\sqrt L, because the final normalization's input grows like L\sqrt L

LayerNorm divides gradients by the norm of its input. In Post-LN that input has norm of order d\sqrt d at every depth; in Pre-LN the stream grows, so the final LayerNorm divides by about Ld\sqrt{Ld}. Large gradients at the top are why Post-LN needs warmup.

Question 2

Why does a deep Post-LN transformer's output move more under the same small parameter update than a Pre-LN transformer's, according to Liu et al. (2020)?

  1. Its gradients vanish toward the input, so the update is concentrated in a few layers
  2. It uses more parameters per layer
  3. Each Post-LN layer depends heavily on its own branch (βi,i2\beta_{i,i}^2 constant), so the branch perturbations add up to O(N)\order{N}, while Pre-LN's dependence βi,i2≈1/i\beta_{i,i}^2\approx1/i sums to O(log⁡N)\order{\log N}
  4. Its LayerNorms have learnable gains
Show the answer

C. Each Post-LN layer depends heavily on its own branch (βi,i2\beta_{i,i}^2 constant), so the branch perturbations add up to O(N)\order{N}, while Pre-LN's dependence βi,i2≈1/i\beta_{i,i}^2\approx1/i sums to O(log⁡N)\order{\log N}

The output change is about ∑iβi,i2C\sum_i\beta_{i,i}^2C. In Pre-LN each branch joins a stream that has grown like ii, giving a harmonic sum; in Post-LN the stream is renormalized and every branch keeps a constant share. Admin initializes the skip weights so that Post-LN starts with Pre-LN's shares.

Question 3

DeepNorm computes xl+1=LN⁡(αxl+Gl(xl))\mathbf x_{l+1} = \operatorname{LN}(\alpha\mathbf x_l + G_l(\mathbf x_l)) with α=(2N)1/4>1\alpha = (2N)^{1/4} > 1. What does the factor α\alpha do?

  1. It up-weights the skip path relative to the branch, shrinking each sublayer's effect on the output so that the total update stays Θ(η)\Theta(\eta) at any depth
  2. It increases the learning rate of deep layers
  3. It removes the need for LayerNorm
  4. It scales the attention logits to prevent entropy collapse
Show the answer

A. It up-weights the skip path relative to the branch, shrinking each sublayer's effect on the output so that the total update stays Θ(η)\Theta(\eta) at any depth

In the bound ∥ΔF∥≤∑ivi2+wi2 ∥Δθi∥/α\norm{\Delta F}\le\sum_i\sqrt{v_i^2 + w_i^2}\,\norm{\Delta\boldsymbol\theta_i}/\alpha, a larger α\alpha divides every sublayer's contribution; together with the smaller initialization β=(8N)−1/4\beta = (8N)^{-1/4} it keeps the sum of 2N2N contributions of order η\eta.

Question 4

During training, the query and key projections of a Pre-LN transformer both double in norm while their inputs stay normalized. What happens to the attention logits, and what would QK-norm change?

  1. Nothing: the inputs are normalized, so the logits cannot grow
  2. They double; QK-norm halves them again
  3. They grow fourfold; QK-norm divides them by dkd_k instead of dk\sqrt{d_k}
  4. They grow fourfold, since the logits are bilinear in the two projections; with QK-norm they are bounded by dk\sqrt{d_k} times the product of the normalization gains, whatever the projections
Show the answer

D. They grow fourfold, since the logits are bilinear in the two projections; with QK-norm they are bounded by dk\sqrt{d_k} times the product of the normalization gains, whatever the projections

sij=x^iWQWK⊤x^j⊤/dks_{ij} = \hat{\mathbf x}_iW_QW_K^\top\hat{\mathbf x}_j^\top/\sqrt{d_k} scales like c2c^2 when both projections scale by cc. Normalizing queries and keys removes the projections' scale, so the logits can grow only through the gains, which keeps the attention entropy away from collapse as long as the gains stay moderate.

Question 5

Why can a language model's output logits drift without the cross-entropy noticing, and what does the z-loss do about it?

  1. Cross-entropy ignores a constant added to all logits, so their overall level, measured by log⁡Z\log Z, is unconstrained; the z-loss penalizes log⁡2Z\log^2Z, pinning log⁡Z\log Z near 00 so the logits become log-probabilities
  2. Cross-entropy ignores the largest logit; the z-loss clips it
  3. The softmax saturates at large logits; the z-loss divides them by a temperature
  4. Weight decay removes the output layer's bias; the z-loss restores it
Show the answer

A. Cross-entropy ignores a constant added to all logits, so their overall level, measured by log⁡Z\log Z, is unconstrained; the z-loss penalizes log⁡2Z\log^2Z, pinning log⁡Z\log Z near 00 so the logits become log-probabilities

ℓ(y+c1)=ℓ(y)\ell(\mathbf y + c\mathbf 1) = \ell(\mathbf y) while log⁡Z\log Z shifts by cc. Penalizing log⁡2Z\log^2Z (with weight 10−410^{-4} in PaLM) fixes that one free direction at no cost in fit; Wortsman et al. showed it prevents the late divergence of the output logits.

Further reading

  • R. Xiong, Y. Yang, D. He, K. Zheng, S. Zheng, C. Xing, H. Zhang, Y. Lan, L. Wang & T.-Y. Liu, "On layer normalization in the transformer architecture," ICML (2020).
  • L. Liu, X. Liu, J. Gao, W. Chen & J. Han, "Understanding the difficulty of training transformers," EMNLP (2020).
  • H. Wang, S. Ma, L. Dong, S. Huang, D. Zhang & F. Wei, "DeepNet: Scaling transformers to 1,000 layers," arXiv:2203.00555 (2022); IEEE TPAMI (2024).
  • M. Dehghani et al., "Scaling vision transformers to 22 billion parameters," ICML (2023).
  • S. Zhai, T. Likhomanenko, E. Littwin, D. Busbridge, J. Ramapuram, Y. Zhang, J. Gu & J. Susskind, "Stabilizing transformer training by preventing attention entropy collapse," ICML (2023).
  • M. Wortsman et al., "Small-scale proxies for large-scale Transformer training instabilities," arXiv:2309.14322 (2023); ICLR (2024).