Back to paper library

Pre-LN Transformer

No More Warm-Up

Original paper

On Layer Normalization in the Transformer Architecture

Paper authors

Ruibin Xiong · Yunchang Yang · Di He …

Show all 10 authors

Ruibin Xiong · Yunchang Yang · Di He · Kai Zheng · Shuxin Zheng · Chen Xing · Huishuai Zhang · Yanyan Lan · Liwei Wang · Tie-Yan Liu

Publication
ICML 2020Conference
First submitted to arXiv
arXiv:2002.04745
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{transformerspreln2020,
  title = {{On Layer Normalization in the Transformer Architecture}},
  author = {Ruibin Xiong and Yunchang Yang and Di He and Kai Zheng and Shuxin Zheng and Chen Xing and Huishuai Zhang and Yanyan Lan and Liwei Wang and Tie-Yan Liu},
  year = {2020},
  eprint = {2002.04745},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2002.04745}
}
On this page

One odd habit of training Transformers is that you can't set the learning rate where you want it right from the start.

For the first 4000 steps, the original Transformer paper has the learning rate climb slowly from near 0 to its maximum, then gradually decay. This climb is called learning-rate warm-up. Convolutional networks usually start with a fairly large learning rate and lower it over time; only special cases such as very-large-batch training need warm-up. Transformers, though, need it almost every time.

Warm-up is a nuisance. It slows training down and adds two more hyperparameters to tune, the maximum learning rate and the number of warm-up steps, and the final results are sensitive to both. When training a large model like BERT, every setting you try is expensive.

Why do Transformers insist on warm-up? In February 2020, Ruibin Xiong, Yunchang Yang, Di He, and colleagues from the Chinese Academy of Sciences, Peking University, Microsoft Research Asia, and Nankai University released this paper. They argue that the problem lies in where LayerNorm is placed.

Defining the Problem

Two Arrangements

Each Transformer layer has two sub-layers, self-attention and a feed-forward network (FFN). Each sub-layer has a residual connection, and each has a LayerNorm. These three pieces can be arranged in different orders:

Diagrams of two Transformer layers side by side. (a) The input x_l goes through Multi-Head Attention, is added to the shortcut, and then goes through Layer Norm; it then goes through the FFN, is added to the shortcut, and goes through Layer Norm again to give x_l+1. (b) The input x_l first goes through Layer Norm, then into Multi-Head Attention, and is added to the shortcut; next comes Layer Norm, then the FFN, then the addition with the shortcut, giving x_l+1. In both, the shortcut is drawn as a thick gray arrow
Figure 1 from the paper, excerpted from page 2 of the v2 PDF. (a) A Post-LN Transformer layer; (b) a Pre-LN Transformer layer.

On the left is what the original Transformer and BERT do, running the sub-layer, residual addition, and LayerNorm in that order. LayerNorm sits between the residual blocks, and the authors call this Post-LN. Taking the FFN sub-layer as an example:

xl+1=LN(x+FFN(x))x_{l+1} = \mathrm{LN}\big(x + \mathrm{FFN}(x)\big)

On the right, LayerNorm moves inside the residual branch, before the sub-layer; this is called Pre-LN:

xl+1=x+FFN(LN(x))x_{l+1} = x + \mathrm{FFN}\big(\mathrm{LN}(x)\big)

Pre-LN's main path has nothing but additions; since the main path is never normalized along the way, one more LayerNorm has to be added before the final output.

Pre-LN was already in use before this paper. The language models of Baevski and Auli and OpenAI's Sparse Transformer both adopted it, and translation toolkits such as tensor2tensor and OpenNMT implemented it; Wang et al. even found that Pre-LN beats Post-LN as the number of layers grows. Still, all of these works kept warm-up in their training pipelines.

How Much Does Warm-Up Really Matter?

The authors first confirm the effect of warm-up with a Post-LN Transformer on the IWSLT14 German-to-English translation task. The warm-up schedule is:

lr(t)=tTwarmup lrmax⁡,t≤Twarmup\mathrm{lr}(t) = \frac{t}{T_{\text{warmup}}}\,\mathrm{lr}_{\max}, \quad t \le T_{\text{warmup}}

followed by inverse square root decay. They train with Adam and with plain SGD, comparing runs with and without warm-up and with different warm-up lengths:

Two groups of line charts, all with epochs on the horizontal axis. (a) Training with Adam: validation loss on the left, BLEU on the right. The two dashed lines without warm-up stall at a loss of around 7 with BLEU below 10; the orange line with 500 warm-up steps and a maximum learning rate of 1e-3 is also poor; the two lines with 4000 warm-up steps bring the loss down to about 4 and BLEU up above 30. (b) Training with SGD: with warm-up, the loss falls from 10 to between 6 and 7, with BLEU around 7; without warm-up, the loss stays above 8.5 and BLEU is near 0
Figure 2 from the paper, excerpted from page 4 of the v2 PDF. Validation loss and BLEU on IWSLT14 German-to-English: (a) with Adam, (b) with SGD.

Warm-up has to be there, and its length has to be right too.

  • Without warm-up, it won't train. With Adam and no warm-up, BLEU reaches only 8.45; models with warm-up get about 34. SGD does much worse than Adam to begin with, but the trend is the same, with BLEU staying barely above 0 over 15 epochs without warm-up.
  • The warm-up length is a sensitive setting too. With only 500 warm-up steps, maximum learning rates of 5e-4 and 1e-3 give BLEU scores of just 31.16 and 2.77, respectively.

Others had explained what warm-up does before. The authors of RAdam argued that warm-up reduces the variance of Adam's adaptive learning rate early in training. But here SGD needs warm-up too, so the authors conclude that the benefit of warm-up isn't tied to any particular optimizer, and the cause has to be sought in the model itself.

Solving the Problem

Looking at the Moment of Initialization

Warm-up only happens during the first few thousand steps, so the authors focus on initialization, examining the gradients when the network has just been built and all its parameters are random.

They analyze it with mean field theory and make a few simplifications. Attention uses a single head; every weight matrix is d×dd\times d with Xavier initialization; the attention matrices WQW^Q and WKW^K are initialized to 0, so attention starts out uniform; and the input vectors are treated as Gaussian as well.

The analysis has three steps, looking first at the size of the hidden states, then at how LayerNorm treats gradients, and finally at the two put together.

Step 1: How Big Is the Signal on the Main Path?

Post-LN ends every layer with LayerNorm, so each layer's output norm is fixed at around d\sqrt{d}. The authors look instead at xpost,5x^{\text{post},5}, just before the last normalization: the vector after the FFN output is added to the residual. Pre-LN's main path isn't normalized, and every layer adds something on top. The authors prove:

E∥xlpost,5∥22=32d,(1+l2)d≤E∥xlpre∥22≤(1+3l2)d\mathbb{E}\big\|x^{\text{post},5}_{l}\big\|_2^2 = \tfrac{3}{2}d, \qquad \Big(1+\tfrac{l}{2}\Big)d \le \mathbb{E}\big\|x^{\text{pre}}_{l}\big\|_2^2 \le \Big(1+\tfrac{3l}{2}\Big)d

Post-LN stays the same size at every layer; Pre-LN grows linearly with depth.

Where does the 32\tfrac{3}{2} come from? xpost,3x^{\text{post},3} has just gone through LayerNorm, so its squared norm is dd. Then it passes through the FFN. After multiplying by the Xavier-initialized W1W^1, each element has variance 1; ReLU cuts out half, leaving a squared norm of d/2d/2; multiplying by W2W^2 keeps it at d/2d/2. Add the two together and you get d+d/2=32dd + d/2 = \tfrac{3}{2}d. Each Pre-LN layer likewise adds at least the FFN's d/2d/2, which is where the l/2l/2 in the lower bound comes from.

Step 2: LayerNorm Divides the Gradient by the Size of Its Input

LayerNorm subtracts the mean from its input and divides by the standard deviation. Scale the input up by kk, and the output stays the same; so, conversely, the derivative of the output with respect to the input shrinks by a factor of kk. The authors write this as:

∥JLN(x)∥2=O ⁣(d∥x∥2)\big\|J_{\mathrm{LN}}(x)\big\|_2 = O\!\left(\frac{\sqrt{d}}{\|x\|_2}\right)

JLNJ_{\mathrm{LN}} is LayerNorm's Jacobian matrix. Each time the input's length doubles, its spectral norm halves. When the gradient propagates back through LayerNorm, it's multiplied by this Jacobian, so the larger the input, the smaller the gradient passed back.

Step 3: Putting It Together

Putting the first two steps together gives the paper's main theorem. The authors analyze the second weight matrix of the last FFN layer, W2,LW^{2,L}, and conclude (with high probability):

Post-LN: ∥∂L~∂W2,L∥F≤O(dln⁡d),Pre-LN: ∥∂L~∂W2,L∥F≤O(dln⁡dL)\text{Post-LN: }\left\|\frac{\partial \tilde{\mathcal{L}}}{\partial W^{2,L}}\right\|_F \le O\big(d\sqrt{\ln d}\big), \qquad \text{Pre-LN: }\left\|\frac{\partial \tilde{\mathcal{L}}}{\partial W^{2,L}}\right\|_F \le O\left(d\sqrt{\frac{\ln d}{L}}\right)

Here's the reasoning. In Post-LN, the input to the last LayerNorm is xpost,5x^{\text{post},5}, whose size is fixed at around 3d/2\sqrt{3d/2} regardless of the number of layers, so the last layer's gradient doesn't depend on the number of layers either. In Pre-LN, the input to the final LayerNorm is the main path, accumulated all the way up; its squared norm grows linearly with the number of layers LL, so its norm is on the order of L\sqrt{L}, and the gradient passing through it is divided by L\sqrt{L}.

The authors also give a preliminary extension of the analysis, concluding that in Post-LN, the closer parameters are to the output layer, the larger their gradients, shrinking toward the input; in Pre-LN, gradients are roughly the same across layers.

Measuring It for Real

The theory makes quite a few simplifications, so the authors check it on real models. They first confirm that the concentration property of the hidden-state norms holds, then measure the gradients:

Four plots. (a) and (b) are bar charts of the gradient magnitudes of W1 and W2 in each FFN layer of a Transformer with a 6-layer encoder and a 6-layer decoder: the blue bars, Pre-LN (at initialization), vary little across layers; the orange bars, Post-LN (at initialization), increase with the layer and are highest at layer 6; the green bars, Post-LN (after warm-up), are almost 0. (c) The gradient of the last-layer W2 in Pre-LN falls as the total number of layers increases from 6 to 14, from 0.3 to about 0.13. (d) The gradient of the last-layer W2 in Post-LN stays around 1.6, unchanged by the number of layers
Figure 3 from the paper, excerpted from page 7 of the v2 PDF. (a)(b) Gradient magnitudes of the FFN weights in each layer of a 6-6-layer Transformer; (c)(d) gradient magnitude of the last-layer W2W^2 in models of different sizes. Each experiment is repeated with ten random seeds.

The measurements match the theory.

  • The two plots on the right: Post-LN's last-layer gradient is around 1.6 no matter how big the model, while Pre-LN's falls as the number of layers grows.
  • The two plots on the left: Post-LN's gradients grow steadily from layer 1 to layer 6, largest in the layer closest to the output; Pre-LN's vary much less across layers.

So at initialization, Post-LN has large gradients on the parameters near the output. Using a large learning rate right away makes the update steps too big, and training becomes unstable. Warm-up sidesteps exactly this stretch by waiting until the gradients have shrunk before turning up the learning rate. The green bars in the figure (Post-LN after warm-up) are almost all 0; the gradients really have become much smaller.

The authors also tried training Post-LN without warm-up, using a fixed small learning rate of 1e-4 throughout. That does train the model to some extent, but convergence is much slower.

Looking at it the other way around, Pre-LN's gradients are well-behaved right from initialization, so it should be able to do without warm-up.

Discussion

Translation: No Warm-Up, and Faster Too

The authors test this on two translation tasks:

  • IWSLT14 German-to-English: a 6-layer encoder and a 6-layer decoder, embedding dimension 512, FFN 1024, 4 attention heads.
  • WMT14 English-to-German: the Transformer base setting, with about 4.5 million parallel sentence pairs.

Post-LN follows the original paper with 4000 warm-up steps, then inverse square root decay. Pre-LN has no warm-up at all. On IWSLT14 it starts at 5e-4 and is multiplied by 0.1 at epoch 8; on WMT14, two runs start at 7e-4 and 1.5e-3, decay at epoch 6, and then follow inverse square root decay. The two models' maximum learning rates are set to be the same. Since RAdam claims to remove the need for warm-up, the authors include it in the IWSLT14 comparison as well.

Four line charts, all with epochs on the horizontal axis. (a) and (b) are validation loss and BLEU on IWSLT14: the red and orange lines for Pre-LN (with Adam or RAdam, both without warm-up) drop very low within the first few epochs, and BLEU quickly rises above 30; the green line for Post-LN with Adam and warm-up, and the blue line for Post-LN with RAdam and no warm-up, both climb more slowly and only catch up at the end. (c) and (d) are validation loss and BLEU on WMT14: at both learning rates, Pre-LN converges earlier than the corresponding Post-LN, and BLEU ends up around 26 for all
Figure 4 from the paper, excerpted from page 8 of the v2 PDF. Validation loss and BLEU on IWSLT14 German-to-English (a, b) and WMT14 English-to-German (c, d).

Reading the figure, we can sum it up in three points.

  1. Warm-up is no longer necessary. On IWSLT14, Pre-LN without warm-up ends at a BLEU of about 34 and a validation loss of about 4, on par with Post-LN with warm-up.
  2. Faster convergence. On IWSLT14, Pre-LN at epoch 9 performs about as well as Post-LN at epoch 15; WMT14 shows something similar.
  3. Where LayerNorm goes matters more than the optimizer. RAdam does let Post-LN train without warm-up; but once you switch to Pre-LN, whether you use RAdam or Adam makes almost no difference.

The authors also mention that with well-tuned hyperparameters (an initial learning rate of 7.5e-4, dropout of 0.3, and so on), Pre-LN can reach a test BLEU of 35.5 on IWSLT14.

BERT: 40% Saved

Pre-training uses BERT base (12 layers, hidden dimension 768, 12 heads), on English Wikipedia plus a BookCorpus the authors collected themselves, about 3.4 billion words in total.

Post-LN BERT follows the original paper's settings, with 10,000 warm-up steps and a maximum learning rate of 1e-4. The authors tried raising Post-LN's learning rate to 3e-4, and training simply diverged. Pre-LN BERT has no warm-up and decays linearly from 3e-4.

Three line charts, all with pre-training steps (in thousands) on the horizontal axis. (a) BERT validation loss: the orange Pre-LN line is below the blue dashed Post-LN line from the start, and the two fall roughly in parallel; Pre-LN reaches 1.69 at about 500 thousand steps, while Post-LN takes until about 700 thousand. (b) MRPC accuracy and (c) RTE accuracy: Pre-LN is above Post-LN at every stage of pre-training, with the gap most pronounced early on
Figure 5 from the paper, excerpted from page 8 of the v2 PDF. (a) Validation loss during BERT pre-training; (b)(c) accuracy on MRPC and RTE after fine-tuning models from different pre-training stages, with error bars showing 95% confidence intervals over six fine-tuning runs.

Post-LN has to train until step 700k for its validation loss to reach 1.69; Pre-LN gets there by step 500k, about 40% faster. The 200k steps saved far exceed the 10k steps of warm-up itself, so the speed-up comes from more than skipping warm-up: above all, Pre-LN can handle a much larger learning rate.

Fine-tuning models from different stages on MRPC and RTE shows that Pre-LN also converges faster on downstream tasks.

Conclusion

This paper traces an engineering habit back to an architectural cause. At initialization, Post-LN has large gradients on the parameters near the output, which warm-up is needed to avoid. Move LayerNorm inside the residual branch, before the sub-layer, and the size of the main path shrinks the last layer's gradient by 1/L1/\sqrt{L}, the gradients become more even across layers, warm-up can be dropped, and the learning rate can be turned up higher.

That said, the theoretical analysis looks only at the moment of initialization and makes simplifications such as uniform attention and a single head; the part about Post-LN gradients growing larger closer to the output is labeled by the authors themselves as a preliminary result, supported mainly by the measurements in Figure 3.

The idea of “move normalization into the branch and keep the shortcut clean” had also appeared in convolutional networks; GPT-2 likewise moved LayerNorm to the input of each sub-layer:

If you're training a Transformer from scratch, put LayerNorm before each sub-layer, and remember to add one more LayerNorm before the output. At the scale of the paper's experiments, this trains without warm-up, and you can use a somewhat larger learning rate.

Pre-LN later became the default arrangement for many large language models, but it comes at a cost, which the result of step 1 already shows. The main path's squared norm grows linearly with the number of layers, while each layer adds roughly the same amount, so the later the layer, the smaller its relative influence on the main path. In 2021, NormFormer pointed out that during Pre-LN pre-training, the early layers' gradients are much larger than the later layers', and added a few extra normalizations to each layer; in 2022, DeepNet went back and reworked Post-LN, aiming to keep both Post-LN's performance and Pre-LN's stability, and pushed Transformers to a thousand layers.

Where LayerNorm should go is a question that isn't settled yet; we'll come back to it when we get the chance.