DeepNorm is a method that, in a Post-LNTransformer, scales the residual (the layer's input) by a constant α 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 β. 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 Gl be the function of the l-th sublayer (attention or feed-forward) and xl its input. Post-LN and DeepNorm compute the following (Section 4.1 of the paper).
Post-LN:xl+1=LN(xl+Gl(xl,θl))
DeepNorm:xl+1=LN(αxl+Gl(xl,θl))
The only difference is multiplying the residual xl by α (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 β (a constant less than 1) (Figure 2 of the paper).
The feed-forward weights
The attention value projection WV and output projection WO
The query and key projections WQ and WK are initialized at their usual scale. The paper shows that the magnitude of the attention output is determined only by WV and WO, and that WQ and WK do not affect it (Lemma 4.1).
Values of α and β
α and β are constants that are not learned; they depend only on the architecture and the number of layers (Figure 2 of the paper; N is the number of encoder layers and M the number of decoder layers).
For example, a 24-layer decoder-only model has α=481/4≈2.63 and β=192−1/4≈0.27. The deeper the model, the larger α and the smaller β.
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).
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.
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, the square root of the dimension d.
Gradients vanish. The magnitude of the gradient through layer normalization is O(d/∥x∥), which shrinks as the input x 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∥ in the output of a model stacking N DeepNorm layers is bounded as follows (Theorem 4.2). vi,wi are the magnitudes of the sublayer weights (WV and WO for attention), and θi∗−θi is the change in the parameters in one update.
∥ΔF∥≤∑i=12Nαvi2+wi2∥θi∗−θi∥
Ordinary Post-LN corresponds to α=1 and vi=wi=1, so the output change is the sum of the updates of all sublayers, O(∑∥θi∗−θi∥). 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 α in the denominator (make the residual larger, reducing the relative contribution of the sublayer outputs), and shrink vi,wi in the numerator (the β-scaled initialization). The paper chose α and β so that the output change from one update stays on the order of the learning rate η (Θ(η)) regardless of the number of layers. For the decoder, for example, the total output change from 3M sublayers is roughly η⋅3M⋅α2v2+w2, so setting α2=(3M)1/2 and v2+w2=(3M)−1/2 (with v=w=β) makes the coefficient on η equal to 1 regardless of the number of layers. This is where α=(3M)1/4 and β=(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 (α) and weakens each person's rudder (β), 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).
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 d in the form Alogd+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 data
M2M-100 (48 layers, 12B)
DeepNet (200 layers, 3.2B)
WMT
31.9
33.9
OPUS
18.4
23.0
TED
18.7
20.1
Flores (7,482 translation directions)
13.6
18.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 WV and WO are scaled by β; WQ and WK 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:
Constant α on the residual; branch weights initialized scaled by β
None
None
Special 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 layers
Diverges at 18-18 layers
Stable even at 100-100 layers
T-Fixup up to 50-50 layers; ReZero diverges at 18-18 layers
Stable up to 36 layers in image Transformers (LayerScale paper)
Performance (WMT-17, BLEU)
27.8–29.0
28.1 at 6-6 layers
27.0–28.1
26.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.