AI Logic

Normalization

DeepNorm

Updated:

Comparison of Post-LN and DeepNorm Transformer layers. Left: Post-LN adds the input to the sublayer output and then applies layer normalization. Right: DeepNorm scales the input (residual) by α before adding it, and initializes the feed-forward weights and some attention weights scaled by β. Bottom: a table of the formulas for α and β for each architecture

What Is DeepNorm?

DeepNorm is a method that, in a Post-LN Transformer, scales the residual (the layer's input) by a constant α\alpha before adding it to the sublayer output, and then applies layer normalization. It also initializes some of the sublayer weights scaled down by a constant β\beta. Wang et al. (Microsoft Research) proposed it in 2022, and the paper calls the deep Transformers built this way DeepNet.

There are two ways to arrange a Transformer layer: Post-LN and Pre-LN. Post-LN performs well, but training becomes unstable as layers get deeper. Pre-LN trains stably, but in the paper's experiments its BLEU was 0.5–1.0 points lower than that of Post-LN when Post-LN trained successfully. DeepNorm aims to combine the performance of Post-LN with the stability of Pre-LN.

The change takes only a few lines. With it, the paper successfully trained a Transformer with 500 encoder layers and 500 decoder layers, 1,000 layers in total (2,500 attention and feed-forward sublayers). That is an order of magnitude deeper than previous deep Transformers.

Computation Steps

Scale the residual by α, then normalize

Let GlG_l be the function of the ll-th sublayer (attention or feed-forward) and xlx_l its input. Post-LN and DeepNorm compute the following (Section 4.1 of the paper).

Post-LN:xl+1=LN(xl+Gl(xl,θl))\text{Post-LN}: \quad x_{l+1} = \mathrm{LN}\bigl(x_l + G_l(x_l, \theta_l)\bigr)

DeepNorm:xl+1=LN(α xl+Gl(xl,θl))\text{DeepNorm}: \quad x_{l+1} = \mathrm{LN}\bigl(\alpha\, x_l + G_l(x_l, \theta_l)\bigr)

The only difference is multiplying the residual xlx_l by α\alpha (a constant greater than 1). In the figure at the top of the article, the left shows a Post-LN layer and the right a DeepNorm layer.

Initialize sublayer weights scaled by β

The other change is initialization. After ordinary initialization such as Xavier initialization, only the following weights are multiplied by β\beta (a constant less than 1) (Figure 2 of the paper).

  • The feed-forward weights
  • The attention value projection WVW_V and output projection WOW_O

The query and key projections WQW_Q and WKW_K are initialized at their usual scale. The paper shows that the magnitude of the attention output is determined only by WVW_V and WOW_O, and that WQW_Q and WKW_K do not affect it (Lemma 4.1).

Values of α and β

α\alpha and β\beta are constants that are not learned; they depend only on the architecture and the number of layers (Figure 2 of the paper; NN is the number of encoder layers and MM the number of decoder layers).

ArchitectureEncoder α\alphaEncoder β\betaDecoder α\alphaDecoder β\beta
Encoder-only (BERT, etc.)(2N)1/4(2N)^{1/4}(8N)−1/4(8N)^{-1/4}——
Decoder-only (GPT, etc.)——(2M)1/4(2M)^{1/4}(8M)−1/4(8M)^{-1/4}
Encoder-decoder (translation, etc.)0.81 (N4M)1/160.81\,(N^4 M)^{1/16}0.87 (N4M)−1/160.87\,(N^4 M)^{-1/16}(3M)1/4(3M)^{1/4}(12M)−1/4(12M)^{-1/4}

For example, a 24-layer decoder-only model has α=481/4≈2.63\alpha = 48^{1/4} \approx 2.63 and β=192−1/4≈0.27\beta = 192^{-1/4} \approx 0.27. The deeper the model, the larger α\alpha and the smaller β\beta.

Why Deep Post-LN Can Be Trained Stably

Post-LN breaks down because of overly large updates early in training

The paper studied an 18-layer-by-18-layer Post-LN translation model and showed that the instability arises from the following chain (Section 3 of the paper).

  1. Early in training, the model's output changes too much. The updates of all sublayers accumulate, so a single update moves the output of the whole model a lot.
  2. The inputs to layer normalization become large. As a result of these erratic updates, the model gets stuck in a bad local optimum, and the magnitude of the values just before normalization greatly exceeds d\sqrt{d}, the square root of the dimension dd.
  3. Gradients vanish. The magnitude of the gradient through layer normalization is O(d/∥x∥)O(\sqrt{d} / \|x\|), which shrinks as the input xx grows. The gradients therefore vanish (vanishing gradients), and the model cannot escape the bad local optimum.

The paper explains that warmup and initializations with smaller weights stabilize training because they suppress the overly large updates in step 1.

Keep the update size within a fixed range regardless of depth

The paper showed that the change ∥ΔF∥\|\Delta F\| in the output of a model stacking NN DeepNorm layers is bounded as follows (Theorem 4.2). vi,wiv_i, w_i are the magnitudes of the sublayer weights (WVW_V and WOW_O for attention), and θi∗−θi\theta_i^* - \theta_i is the change in the parameters in one update.

∥ΔF∥≤∑i=12Nvi2+wi2α ∥θi∗−θi∥\|\Delta F\| \le \sum_{i=1}^{2N} \frac{\sqrt{v_i^2 + w_i^2}}{\alpha}\, \|\theta_i^* - \theta_i\|

Ordinary Post-LN corresponds to α=1\alpha = 1 and vi=wi=1v_i = w_i = 1, so the output change is the sum of the updates of all sublayers, O(∑∥θi∗−θi∥)O\bigl(\sum \|\theta_i^* - \theta_i\|\bigr). The deeper the model, the more the updates accumulate, and the more the output moves early in training.

This bound shows two ways to keep updates small: enlarge α\alpha in the denominator (make the residual larger, reducing the relative contribution of the sublayer outputs), and shrink vi,wiv_i, w_i in the numerator (the β\beta-scaled initialization). The paper chose α\alpha and β\beta so that the output change from one update stays on the order of the learning rate η\eta (Θ(η)\Theta(\eta)) regardless of the number of layers. For the decoder, for example, the total output change from 3M3M sublayers is roughly η⋅3M⋅v2+w2α2\eta \cdot 3M \cdot \frac{v^2 + w^2}{\alpha^2}, so setting α2=(3M)1/2\alpha^2 = (3M)^{1/2} and v2+w2=(3M)−1/2v^2 + w^2 = (3M)^{-1/2} (with v=w=βv = w = \beta) makes the coefficient on η\eta equal to 1 regardless of the number of layers. This is where α=(3M)1/4\alpha = (3M)^{1/4} and β=(12M)−1/4\beta = (12M)^{-1/4} come from (Section 4.3 of the paper).

As an analogy, Post-LN is like "many people each turning the rudder a little, so that in total the ship turns far too much". DeepNorm makes the ship's heading (the residual) heavier (α\alpha) and weakens each person's rudder (β\beta), so that the total turn stays constant even as more people join.

Pre-LN also stays stable when made deep, but the paper suggests that in Pre-LN the gradients of layers near the input tend to be larger than those near the output, which leads to worse performance. DeepNorm stabilizes training while keeping the Post-LN arrangement, so it retains Post-LN's performance.

Experimental Results

Translation accuracy at different depths: on WMT-17 English→German translation, BLEU was compared while varying the number of encoder and decoder layers (Table 1 of the paper, base-size models).

ModelNormalization6-6 layers18-18 layers50-50 layers100-100 layers
Post-LN (original Transformer)Post-LN28.1DivergedDivergedDiverged
T-FixupNone27.528.427.9Diverged
Pre-LNPre-LN27.028.128.027.4
DeepNet (DeepNorm)DeepNorm27.828.829.028.9
  • Post-LN diverged at 18-18 layers, while DeepNorm trained stably up to 100-100 layers.
  • Pre-LN trained at every depth, but its BLEU was lower than DeepNorm's.
  • Methods that stabilize training through initialization without normalization, such as T-Fixup, trained up to 50-50 layers, but accuracy did not improve beyond 18-18 layers. ReZero was unstable in half-precision training and diverged at 18-18 layers.

1,000-layer multilingual translation: on OPUS-100, which covers 100 languages, DeepNet was deepened to 1,000 layers (500 encoder layers and 500 decoder layers, 3.8 billion parameters). Its average BLEU was 32.1, 4.4 points above the 48-layer baseline (27.7) (Table 2 of the paper). The paper also reports that BLEU grows with depth dd in the form Alog⁡d+BA \log d + B.

Comparison with a shallow, wide model: a 200-layer DeepNet with 3.2 billion parameters was compared with M2M-100, which has 48 layers and 12 billion parameters (Table 3 of the paper).

Evaluation dataM2M-100 (48 layers, 12B)DeepNet (200 layers, 3.2B)
WMT31.933.9
OPUS18.423.0
TED18.720.1
Flores (7,482 translation directions)13.618.6

With about a quarter of the parameters, the deeper DeepNet outperformed it on every evaluation set.

Practical Considerations

Recompute α and β for the architecture and number of layers. The formulas differ for encoder-only, decoder-only, and encoder-decoder models, and the values change when the number of layers changes. Only the feed-forward weights and the attention WVW_V and WOW_O are scaled by β; WQW_Q and WKW_K are not.

Scaling the residual by α alone, or changing the initialization alone, does not satisfy the theory's assumptions. The paper's bound is derived so that both α (in the denominator) and β (in the numerator) keep the update size in check. Using only one of them may fail to contain the updates in deep models.

Also keep the following points in mind.

  • The experiments focus on machine translation. The paper leaves applications such as language model pretraining, protein structure prediction, and image pretraining to future work.
  • The theory assumes SGD. The paper states that experiments confirmed it also works well with Adam.
  • PyTorch has no built-in layer. nn.TransformerEncoderLayer is Post-LN (norm_first=False), but it has no argument to multiply the residual by α, so write the layer yourself as in the code example below.
  • Use learning-rate warmup as usual. In the paper's translation experiments, the DeepNorm models were also trained with 4,000 warmup steps and an inverse-square-root learning-rate decay (Appendix D of the paper). DeepNorm is not a way to remove warmup but a way to keep training from breaking down as models get deeper.

Comparison with Other Methods

Methods for stably training deep Transformers, compared side by side:

AspectDeepNormPost-LNPre-LNT-Fixup, ReZeroLayerScale
Position of normalizationAfter adding the residualAfter adding the residualBefore the sublayerNot usedBefore the sublayer (Pre-LN)
Coefficients on residual and branchConstant α on the residual; branch weights initialized scaled by βNoneNoneSpecial initialization; learned coefficient on the branch (ReZero starts from 0)Learned per-channel coefficient on the branch output
Stability when deep (WMT-17)Stable even at 100-100 layersDiverges at 18-18 layersStable even at 100-100 layersT-Fixup up to 50-50 layers; ReZero diverges at 18-18 layersStable up to 36 layers in image Transformers (LayerScale paper)
Performance (WMT-17, BLEU)27.8–29.028.1 at 6-6 layers27.0–28.126.9–28.4—

Rough guidelines for choosing:

  • You want a Transformer deeper than 100 layers, especially while keeping Post-LN's performance: DeepNorm.
  • A few dozen layers, and stable training is enough: Pre-LN. It is simple to implement and is the default option in many libraries.
  • Using an existing Post-LN model (such as BERT) as is: keep Post-LN and add warmup.
  • You want to deepen an image Transformer (such as ViT): LayerScale is also an option.

PyTorch example

Show code
python
import torch
import torch.nn as nn

class DeepNormEncoderLayer(nn.Module):
    """Post-LN layer following the paper's equation x_{l+1} = LN(α x_l + G_l(x_l)) (not built into PyTorch)"""
    def __init__(self, d_model, n_heads, d_ff, alpha, beta):
        super().__init__()
        self.alpha = alpha                                   # constant multiplied onto the residual (not learned)
        self.attn = nn.MultiheadAttention(d_model, n_heads, batch_first=True)
        self.ffn = nn.Sequential(nn.Linear(d_model, d_ff), nn.GELU(), nn.Linear(d_ff, d_model))
        self.ln1 = nn.LayerNorm(d_model)
        self.ln2 = nn.LayerNorm(d_model)
        self._deepnorm_init(d_model, beta)

    def _deepnorm_init(self, d, beta):
        # Figure 2(a) of the paper: Xavier init with gain=β for FFN, W_V, W_O and gain=1 for W_Q, W_K
        w = self.attn.in_proj_weight                         # [3d, d] = W_Q, W_K, W_V stacked vertically
        nn.init.xavier_normal_(w[:d], gain=1.0)              # W_Q
        nn.init.xavier_normal_(w[d:2 * d], gain=1.0)         # W_K
        nn.init.xavier_normal_(w[2 * d:], gain=beta)         # W_V
        nn.init.xavier_normal_(self.attn.out_proj.weight, gain=beta)   # W_O
        for m in self.ffn:
            if isinstance(m, nn.Linear):
                nn.init.xavier_normal_(m.weight, gain=beta)

    def forward(self, x):                                    # x: [batch, sequence length, d_model]
        a, _ = self.attn(x, x, x, need_weights=False)
        x = self.ln1(self.alpha * x + a)                     # scale the residual by α, add, then normalize
        x = self.ln2(self.alpha * x + self.ffn(x))
        return x

# α and β for an encoder-only model (N layers): α = (2N)^(1/4), β = (8N)^(-1/4)
N = 24
alpha, beta = (2 * N) ** 0.25, (8 * N) ** -0.25              # α ≈ 2.63, β ≈ 0.27
encoder = nn.Sequential(*[DeepNormEncoderLayer(512, 8, 2048, alpha, beta) for _ in range(N)])

x = torch.randn(2, 16, 512)
y = encoder(x)
print(y.shape)   # torch.Size([2, 16, 512])

FAQ

Q. Doesn't multiplying by α make the residual keep growing layer after layer?
A.

No. DeepNorm uses the Post-LN arrangement, so after the residual is scaled by α and added, layer normalization is applied every time. The magnitude of the values passed to the next layer is normalized, so multiplying by α does not make the values swell as layers are stacked. α serves to increase the weight of the residual relative to the sublayer output just before normalization.

Q. Can DeepNorm be used in a Pre-LN model?
A.

DeepNorm assumes the Post-LN arrangement (normalizing after adding the residual), and the paper's theory is derived for Post-LN layers. To make a Pre-LN model deeper, either keep using Pre-LN or consider methods such as LayerScale.

Q. Are α and β adjusted during training?
A.

No. Both are constants determined only by the architecture and the number of layers. α is a fixed value multiplied in every forward pass, and β is a value applied to the weights once at initialization. After training starts, the weights are updated by the optimizer as usual.

References

  1. H. Wang, S. Ma, L. Dong, S. Huang, D. Zhang, and F. Wei, "DeepNet: Scaling Transformers to 1,000 Layers," arXiv, 2022.
  2. R. Xiong et al., "On Layer Normalization in the Transformer Architecture," ICML, 2020.
  3. A. Vaswani et al., "Attention Is All You Need," NeurIPS, 2017.