AI Logic

Normalization

Pre-LN vs. Post-LN

Updated:

Comparison of where Layer Normalization sits in one Transformer layer. Post-LN (left) normalizes after adding the residual to the outputs of attention and the feed-forward network. Pre-LN (right) normalizes before each sublayer, adds the residual unchanged, and places a final Layer Normalization after the L layers

What Are Pre-LN and Post-LN?

Pre-LN and Post-LN are two conventions for where to place Layer Normalization relative to the residual connection in each layer of a Transformer.

  • Post-LN: Normalizes after adding the residual to the output of the sublayer (attention or feed-forward). This is the arrangement of the original Transformer and BERT.
  • Pre-LN: Normalizes before the input enters the sublayer, and adds the residual unchanged. One more Layer Normalization is placed after the last layer.

The only difference is the position of the normalization, but it greatly changes how easy the model is to train. The paper by Xiong et al. (2020) showed, both theoretically and experimentally, that in Post-LN the gradients of layers near the output are large at the start of training, so training breaks down without warmup that gradually raises the learning rate, whereas in Pre-LN the gradients are uniform across layers, so it can train from a large learning rate without warmup, and trains faster.

The figure at the top of the article shows one layer of Post-LN (left) and Pre-LN (right). Both flow from bottom to top, and the blue lines are residual connections. In Post-LN, Layer Normalization sits on the main residual path, so the values on the main path are normalized each time they pass through a layer. In Pre-LN, Layer Normalization sits inside the branch to the sublayer, and the main path passes straight through with additions only.

Computation in the Two Arrangements

Let xlx_l be the input at some position to the ll-th layer. A Transformer layer consists of two sublayers: self-attention and the feed-forward network (FFN). The computation in Table 1 of the paper, with simplified notation, is as follows.

Post-LN (each sublayer: sublayer β†’ add residual β†’ normalize)

  1. a=Attention(xl)a = \mathrm{Attention}(x_l)
  2. h=LayerNorm(xl+a)h = \mathrm{LayerNorm}(x_l + a)
  3. f=FFN(h)f = \mathrm{FFN}(h)
  4. xl+1=LayerNorm(h+f)x_{l+1} = \mathrm{LayerNorm}(h + f)

Pre-LN (each sublayer: normalize β†’ sublayer β†’ add residual)

  1. a=Attention(LayerNorm(xl))a = \mathrm{Attention}\bigl(\mathrm{LayerNorm}(x_l)\bigr)
  2. h=xl+ah = x_l + a
  3. f=FFN(LayerNorm(h))f = \mathrm{FFN}\bigl(\mathrm{LayerNorm}(h)\bigr)
  4. xl+1=h+fx_{l+1} = h + f

In Pre-LN, after passing through LL layers, a final Layer Normalization xfinal=LayerNorm(xL+1)x_{\text{final}} = \mathrm{LayerNorm}(x_{L+1}) is applied before passing the result to the output layer (softmax).

Comparing the equations, in Pre-LN the input reaches the next layer through additions only, as in xl+1=xl+a+fx_{l+1} = x_l + a + f. In Post-LN, normalization is applied after each addition, so the input does not arrive in its original form.

Why Post-LN Needs Warmup

The paper examined the magnitude of gradients right at the start of training (at initialization). The three key points are as follows.

  1. Magnitude of hidden states: In Post-LN, the magnitude of the values just before normalization (the expected squared norm) is constant at 32d\frac{3}{2}d in every layer (dd is the hidden dimension). In Pre-LN, values are added layer by layer to the unnormalized main path, so at the ll-th layer it lies between (1+l2)d(1 + \frac{l}{2})d and (1+3l2)d(1 + \frac{3l}{2})d, growing in proportion to depth (Lemma 2 in the paper).
  2. Layer Normalization divides the gradient by the magnitude of its input: The magnitude of the gradient through Layer Normalization is inversely proportional to the norm of its input (Lemma 3). The larger the input, the smaller the gradient passing through it.
  3. The result: In Post-LN, the gradient of the FFN weights in the last layer has magnitude O(dln⁑d)O(d\sqrt{\ln d}), which stays large regardless of the number of layers LL. In Pre-LN, the input to the final Layer Normalization grows in proportion to LL, so the gradient shrinks by a factor of L\sqrt{L} to O(dln⁑d/L)O\bigl(d\sqrt{\ln d / L}\bigr) (Theorem 1).

Measurements on an actual 6-layer Transformer showed that in Post-LN, layers closer to the output had larger gradients, whereas in Pre-LN the gradients were nearly the same across layers (Figure 3 in the paper).

Applying a large learning rate from the start where the gradients near the output are large makes updates too big and destabilizes training. Warmup is thought to avoid this by keeping the learning rate small until the gradients settle. In the paper, Post-LN gradients had also become sufficiently small after warmup.

As an analogy, Post-LN is like plumbing where the faucets closest to the outlet have the highest water pressure. Opening the main valve fully at once makes the outlet side overflow, so it must be opened gradually (warmup). In Pre-LN every faucet has the same pressure, so the valve can be fully open from the start.

Experimental Results

Post-LN cannot train without warmup: On IWSLT14 Germanβ†’English translation (Adam), training Post-LN without warmup reached a BLEU of only 8.45, versus about 34 with warmup (4000 steps). The same trend held with SGD: without warmup, BLEU stayed near 0 even after 15 epochs. Performance is also sensitive to the warmup length: with 500 steps, BLEU dropped to 31.16 at a maximum learning rate of 5Γ—10βˆ’45 \times 10^{-4} and to 2.77 at 10βˆ’310^{-3}.

Pre-LN reaches the same accuracy faster without warmup:

TaskPost-LN (with warmup)Pre-LN (without warmup)
IWSLT14 De→En translationBLEU about 34BLEU about 34. At epoch 9, performance roughly matches Post-LN at epoch 15
WMT14 En→De translationBaselineSame trend (reaches comparable performance faster)
BERT pre-trainingLearning rate 10βˆ’410^{-4} with 10,000 warmup steps; diverges at 3Γ—10βˆ’43 \times 10^{-4}Learning rate 3Γ—10βˆ’43 \times 10^{-4} with linear decay; reached the same validation loss (1.69) about 40% faster

(From Sections 3.2 and 4.2 of the paper. On the BERT downstream tasks MRPC and RTE, Pre-LN also improved accuracy faster.)

In comparison with RAdam, an optimizer designed to make warmup unnecessary, RAdam could train Post-LN without warmup, but with Pre-LN there was almost no difference from Adam. The paper concludes that changing the position of normalization has a larger effect than changing the optimizer.

Practical Considerations

In Pre-LN, do not forget the final Layer Normalization. Because the main path in Pre-LN is not normalized and values accumulate layer by layer, the output of the last layer does not have a consistent scale. The paper's Pre-LN also places a final Layer Normalization before the output layer. When stacking layers with norm_first=True in PyTorch's nn.TransformerEncoder, pass norm=nn.LayerNorm(d_model) to add the final normalization.

PyTorch's nn.TransformerEncoderLayer is Post-LN by default. The default is norm_first=False, which normalizes after adding the residual. Specify norm_first=True for Pre-LN. When loading the weights of an existing pretrained model, the arrangement must match that model, or it will not work correctly.

Also keep the following in mind.

  • Pre-LN still needs learning rate tuning. What the paper removed is the warmup phase; it still uses schedules that lower the learning rate during training (for translation, e.g., multiplying by 0.1 at fixed epochs).
  • Post-LN is not inferior. In the paper's experiments, Post-LN with properly configured warmup reaches final performance comparable to Pre-LN. The differences lie in training speed and the effort of tuning hyperparameters.
  • Very deep models have other techniques. The paper that proposed DeepNorm (Wang et al., 2022) states that a normalization that changes how the residual connection is scaled, together with a matching initialization, combines the good performance of Post-LN with the stable training of Pre-LN, and successfully trained a 1000-layer Transformer.

Comparison and How to Choose

AspectPost-LNPre-LN
Position of Layer NormalizationAfter the residual addition (on the main path)Before the sublayer (inside the branch) + one at the end
Gradients at initializationLarger for layers closer to the outputNearly the same across layers
Learning rate warmupEssential; performance is sensitive to its lengthCan train without it
Large learning ratesProne to divergenceEasy to use
Training speed (paper's experiments)BaselineReaches the same performance faster (about 40% for BERT)
ExamplesOriginal Transformer, BERTImplementations cited in the paper, such as Tensor2Tensor and OpenNMT

Rough guidelines for choosing:

  • Training a new Transformer, especially with many layers or little room to tune the learning rate: Pre-LN. There is no need to be fussy about the warmup length or the maximum learning rate.
  • Using or reproducing an existing Post-LN model (such as BERT): Keep Post-LN and include warmup as in the original setup.
  • A very deep model where Post-LN performance should not be sacrificed: Consider methods that adjust how the residual is applied, such as DeepNorm.

To make normalization itself lighter, Pre-LN's Layer Normalization can also be replaced with RMSNorm.

PyTorch example

Show code
python
import torch
import torch.nn as nn


class PostLNBlock(nn.Module):
    """Post-LN: sublayer β†’ add residual β†’ Layer Normalization (original Transformer)"""
    def __init__(self, d_model=512, n_head=8, d_ff=2048):
        super().__init__()
        self.attn = nn.MultiheadAttention(d_model, n_head, batch_first=True)
        self.ffn = nn.Sequential(nn.Linear(d_model, d_ff), nn.ReLU(), nn.Linear(d_ff, d_model))
        self.norm1, self.norm2 = nn.LayerNorm(d_model), nn.LayerNorm(d_model)

    def forward(self, x):
        h = self.norm1(x + self.attn(x, x, x, need_weights=False)[0])
        return self.norm2(h + self.ffn(h))


class PreLNBlock(nn.Module):
    """Pre-LN: Layer Normalization β†’ sublayer β†’ add residual (the main path is not normalized)"""
    def __init__(self, d_model=512, n_head=8, d_ff=2048):
        super().__init__()
        self.attn = nn.MultiheadAttention(d_model, n_head, batch_first=True)
        self.ffn = nn.Sequential(nn.Linear(d_model, d_ff), nn.ReLU(), nn.Linear(d_ff, d_model))
        self.norm1, self.norm2 = nn.LayerNorm(d_model), nn.LayerNorm(d_model)

    def forward(self, x):
        y = self.norm1(x)
        h = x + self.attn(y, y, y, need_weights=False)[0]
        return h + self.ffn(self.norm2(h))


x = torch.randn(2, 10, 512)                      # [batch, sequence length, d_model]
pre_stack = nn.Sequential(*[PreLNBlock() for _ in range(6)], nn.LayerNorm(512))  # do not forget the final normalization
print(PostLNBlock()(x).shape, pre_stack(x).shape)

# PyTorch built-in: norm_first=False (default) is Post-LN, True is Pre-LN
layer = nn.TransformerEncoderLayer(d_model=512, nhead=8, batch_first=True, norm_first=True)
encoder = nn.TransformerEncoder(layer, num_layers=6, norm=nn.LayerNorm(512))  # final normalization for Pre-LN
print(encoder(x).shape)                          # torch.Size([2, 10, 512])

FAQ

Q. With Pre-LN, is a learning rate schedule no longer needed at all?
A.

No. What the paper showed can be removed is the warmup phase, which gradually raises the learning rate at the start of training. Schedules that lower the learning rate later in training are still used in the Pre-LN experiments.

Q. Why is the "final Layer Normalization" in Pre-LN necessary?
A.

In Pre-LN the main residual path is not normalized, so values accumulate as layers are stacked, and the scale of the last layer's output varies with the number of layers. Normalizing once before the output layer makes the scale consistent. In the paper's theory, this final normalization is also what reduces the gradient by a factor of √L.

Q. BERT uses Post-LN. Can it be retrained with Pre-LN?
A.

Yes, if pre-training from scratch. The paper also converts BERT to Pre-LN and reaches the same validation loss about 40% faster without warmup. However, the publicly released pretrained BERT weights were trained with the Post-LN arrangement, so loading them directly into a Pre-LN model will not work correctly.

References

  1. R. Xiong, Y. Yang, D. He, K. Zheng, S. Zheng, C. Xing, H. Zhang, Y. Lan, L. Wang, and T.-Y. Liu, "On Layer Normalization in the Transformer Architecture," ICML, 2020.
  2. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser, and I. Polosukhin, "Attention Is All You Need," NIPS, 2017.
  3. H. Wang, S. Ma, L. Dong, S. Huang, D. Zhang, and F. Wei, "DeepNet: Scaling Transformers to 1,000 Layers," arXiv:2203.00555, 2022.
  4. PyTorch Documentation, "torch.nn.TransformerEncoderLayer."