Warmup, which raises the learning rate gradually from near 0, has been considered indispensable for training Transformers. Starting from a large learning rate without warmup breaks training, while keeping the learning rate small is too slow. The paper traced the cause to the combination of the early instability of Adam and the shrinking of gradients that pass through layer normalization. It then extended the idea of Fixup, designed for residual networks, to Transformer attention, and derived an initialization that allows layer normalization itself to be removed.
All it does is multiply specific weights by specific factors after the standard Xavier initialization. Nothing is added to the model architecture.
The left side of the figure at the top shows an encoder layer and the right side a decoder layer, each annotated with the weights to shrink and the factors. N is the number of layers and d is the embedding dimension.
Why warmup becomes necessary
This section walks through the analysis in Section 3.1 of the paper.
Adam's updates fluctuate most at the start of training: Adam divides the learning rate by vtβ, a moving average of squared gradients. Liu et al. (the RAdam paper) showed that because vtβ is estimated from few gradients early in training, the variance of the updates can become unboundedly large. Using a large learning rate without warmup made the initial updates about an order of magnitude larger (Figure 2).
Large updates make the inputs to layer normalization large: Without warmup, the magnitude (L2 norm) of the input to the layer normalization after the decoder's self-attention grew 2β3 times, especially in upper layers (Figure 3).
The larger the input, the smaller the gradient through layer normalization: Xiong et al. showed that the magnitude of the gradient of layer normalization with respect to its input x follows the expression below (Eq. 1).
ββxβLN(x)ββ=O(β₯xβ₯dββ)
With an embedding dimension of d=512, dββ22.6. Once the input norm exceeds this, the gradient shrinks each time it passes through layer normalization, and lower layers get smaller gradients. Within a few steps, the gradient to the input embeddings had nearly vanished (vanishing gradients).
Small gradients make Adam even more unstable: When gradients vanish, the estimate of vtβ becomes even more unstable, and large updates continue. This vicious cycle lasts until Adam accumulates enough history, by which time the model has entered a bad plateau.
The paper verified this by changing one condition at a time. With Adam, layer normalization, and no warmup, training diverged completely; switching Adam to SGD stalled training at first but it recovered. On the other hand, merely removing layer normalization made training very unstable even with warmup. Pre-LN, which moves layer normalization before the sublayer, stabilizes training but has been reported to sometimes lower translation accuracy.
Theory (deriving the initialization and the procedure)
As with Fixup, T-Fixup's goal is that "one update changes the model output by an amount proportional to the learning rate Ξ·".
β₯Ξfβ₯=Ξ(Ξ·)
If the size of the updates is bounded regardless of depth, Adam's early instability is also kept in check, and training does not break even without layer normalization. The derivation goes as follows.
It suffices to bound each decoder block's update to Ξ(1/Ldβ): The decoder is a stack of residual blocks yl+1β=ylβ+Glβ(ylβ). Since the updates of Ldβ blocks add up, making each block's contribution Ξ(1/Ldβ) gives Ξ(1) overall.
Derive the condition for an attention block: Attention can be written as follows using the key, query, and value projections k,q,v and the output projection w (Eq. 5).
Attn(a,b,c)=softmax(dβ1βbqkβ€aβ€)cvwβ€
The paper showed that the condition for the update of encoder attention (whose keys and values are the encoder output m) to be Ξ(Ξ·/Ldβ) is the following (Theorem 3.1).
β₯vβ₯2β₯wβ₯2+β₯wβ₯2β₯miββ₯2+β₯vβ₯2β₯miββ₯2=Ξ(1/Ldβ)
The query and key projections q,k inside the softmax do not enter the condition, so they need not be shrunk.
Derive the conditions for the whole encoder and decoder: An N-layer model has Leβ=2N blocks in the encoder (self-attention and MLP) and Ldβ=3N blocks in the decoder (self-attention, encoder attention, and MLP). By the same reasoning, conditions are derived for the encoder, the decoder, and the connection between them (Eqs. 6β8).
Choose magnitudes that satisfy the conditions: Setting the magnitudes of the decoder's v,w and the input embeddings x,y to (3Ldβ)β1/4=(9N)β1/4 satisfies the decoder conditions. Solving the remaining encoder conditions gives about 0.67Nβ1/4 for the encoder's v,w.
The actual procedure is as follows.
Initialize all parameters except the input embeddings with Xavier initialization, and the input embeddings with a normal distribution with mean 0 and standard deviation dβ1/2.
Multiply v,w of each decoder attention, the weights of each decoder MLP, and the encoder and decoder input embeddings by (9N)β1/4.
Multiply v,w of each encoder attention and the weights of each encoder MLP by 0.67Nβ1/4.
Remove all layer normalization and train without warmup.
For example, for a 6-layer model (N=6), the decoder factor is 54β1/4β0.369 and the encoder factor is 0.67Γ6β1/4β0.428.
Fixup set the last layer of each residual branch to 0 and added scalar multipliers and biases. T-Fixup does none of these and only shrinks weights. The paper showed that if the initialization is derived to fit the Transformer architecture, it works well enough without adding anything to the architecture. The paper calls Fixup R-Fixup, in the sense of being for residual networks.
Experimental results
These are the results reported in the paper. All are 6-layer models; T-Fixup removes layer normalization and warmup (the others use both).
Machine translation (test BLEU, higher is better. "β" means not reported. Table 1)
Method
IWSLT'14 DeβEn (small)
IWSLT'14 EnβDe (small)
WMT'18 FiβEn (base)
WMT'17 EnβDe (base)
WMT'17 EnβDe (big)
Original Transformer
34.2
28.6
25.25
27.3
29.3
Pre-LN
β
β
β
27.1
28.7
R-Fixup (Fixup)
34.5
β
β
β
29.3
RAdam (no warmup)
34.8
28.5
β
β
β
T-Fixup
35.5
29.4
25.7
29.1
29.7
small, base, and big are models whose embedding dimension, MLP dimension, and number of attention heads are 512-1024-4, 512-2048-8, and 1024-4096-16.
Deep models (WMT'17 EnβDe, base, test BLEU. Table 2)
Method
Layers
BLEU
Original Transformer
6
27.3
Pre-LN
20
28.9
DLCL
25
29.2
DLCL-Pre-LN
30
29.3
T-Fixup
6
29.1
T-Fixup
20
29.4
T-Fixup
30
29.7
Even 6 layers match deep models: T-Fixup with 6 layers reached about the same BLEU as Pre-LN with 20 layers and DLCL with 25 layers. On WMT'14 EnβDe as well, T-Fixup scored 29.3, 29.6, and 30.1 at 12, 20, and 30 layers, beating other methods of similar depth (28.7 for DS-Init with 20 layers, 29.5 for LRI with 24 layers) (Table 3).
Trainable up to 200 layers: With dimensions reduced to 64-128-2, encoder and decoder of 200 layers each (over 1,000 attention and MLP blocks in total) trained without diverging. Test BLEU on IWSLT'14 DeβEn was 25.35, 28.29, 29.28, 28.98, and 27.65 at 6, 20, 50, 100, and 200 layers, with overfitting beyond 50 layers due to the small dataset (Figure 4b).
Can start from a large learning rate: The deep WMT'17 models stayed stable up to 500,000 updates even when started at a learning rate of 5e-4 rather than warmup's starting value of 1e-7 (Figure 4a).
No warmup needed even with large minibatches: Increasing the minibatch up to 8 times (about 200,000 tokens), every depth from 6 to 30 layers trained without problems, and BLEU barely changed (Figure 4c).
Gradients do not vanish: In the original Transformer without warmup, the gradient to the input embeddings vanished within a few steps, but with T-Fixup the gradients and Adam updates were stable from the start of training (Figure 2).
Practical caveats
Only specific weights are shrunk, and the factors differ between encoder and decoder. In attention, only the value projection v and the output projection w are shrunk; the query and key projections q,k are left as they are. The encoder uses 0.67Nβ1/4, and the decoder and the input embeddings use (9N)β1/4. Mixing them up breaks the conditions the paper derived.
Keep the following points in mind as well.
Assumes the base initialization is Xavier: The factors are derived relative to Xavier initialization. PyTorch's nn.MultiheadAttention applies Xavier initialization to a single matrix (3dΓd) that combines the query, key, and value projections, so the scale differs from initializing each projection separately with Xavier. When using T-Fixup, it is safest to make each projection a separate nn.Linear and initialize them one by one (see the implementation example below). The official implementation (fairseq) also multiplies the value projection by 2β before shrinking it, to cancel the difference from the library's default initialization.
The paper verified it on encoderβdecoder translation models: The derivation of the factors fits the encoderβdecoder architecture, including encoder attention. For decoder-only language models and the like, the paper's factors are not necessarily optimal as they are.
The optimizer verified is Adam: The theory is derived from SGD updates, but all experiments use Adam.
Keeping layer normalization changes the meaning: T-Fixup sets its factors assuming an architecture without layer normalization. If normalization is kept, the output scale is re-equalized, so the factors do not have their theoretical effect.
With no normalization layers, the only difference between model.train() and model.eval() is Dropout.
Comparison with other methods
The figure lines up the residual branches of methods that train deep residual networks without normalization layers. From top to bottom: Fixup, SkipInit, ReZero, and T-Fixup; the small yellow boxes are learnable scalars.
Multiplies the branch output by a scalar Ξ±iβ starting from 0
One scalar per layer
Not used
Trainable without it
T-Fixup
Shrinks the attention v,w and MLP weights in proportion to Nβ1/4
None
Not used
Trainable without it
SkipInit also multiplies the branch by a scalar, as ReZero does, but its paper dealt with ResNet.
Rough guidelines for choosing:
For encoderβdecoder Transformers such as for translation, to remove normalization and warmup without changing the architecture, use T-Fixup: Initialization alone suffices, and inference computation does not change.
If small changes to the architecture are acceptable and it should also work for encoder-only or decoder-only models, use ReZero: It only adds one scalar, with no need to re-derive factors.
To leave the initialization unchanged, use Pre-LN: Training tends to be stable even without warmup, but in the paper it sometimes lowered translation BLEU.
PyTorch example
βΆShow code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
class Attention(nn.Module):
"""multi-head attention with separate q, k, v, and output projections (q, k, v, w in Eq. 5)"""
def __init__(self, d: int, heads: int):
super().__init__()
self.h = heads
self.q, self.k, self.v, self.w = (nn.Linear(d, d) for _ in range(4))
def forward(self, query, key_value, mask=None):
B, T, D = query.shape
S = key_value.shape[1]
split = lambda t, n: t.view(B, n, self.h, D // self.h).transpose(1, 2)
q, k, v = split(self.q(query), T), split(self.k(key_value), S), split(self.v(key_value), S)
out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
return self.w(out.transpose(1, 2).reshape(B, T, D))
def mlp(d: int, d_ff: int) -> nn.Sequential:
return nn.Sequential(nn.Linear(d, d_ff), nn.ReLU(), nn.Linear(d_ff, d))
class EncoderLayer(nn.Module): # no layer normalization
def __init__(self, d, heads, d_ff, p):
super().__init__()
self.attn, self.ff, self.drop = Attention(d, heads), mlp(d, d_ff), nn.Dropout(p)
def forward(self, x):
x = x + self.drop(self.attn(x, x))
return x + self.drop(self.ff(x))
class DecoderLayer(nn.Module): # no layer normalization
def __init__(self, d, heads, d_ff, p):
super().__init__()
self.self_attn, self.enc_attn = Attention(d, heads), Attention(d, heads)
self.ff, self.drop = mlp(d, d_ff), nn.Dropout(p)
def forward(self, y, m, mask):
y = y + self.drop(self.self_attn(y, y, mask))
y = y + self.drop(self.enc_attn(y, m)) # keys and values are the encoder output m
return y + self.drop(self.ff(y))
class TFixupTransformer(nn.Module):
def __init__(self, vocab: int, N: int = 6, d: int = 512, heads: int = 8, d_ff: int = 2048, p: float = 0.1):
super().__init__()
self.src_emb, self.tgt_emb = nn.Embedding(vocab, d), nn.Embedding(vocab, d)
self.enc = nn.ModuleList(EncoderLayer(d, heads, d_ff, p) for _ in range(N))
self.dec = nn.ModuleList(DecoderLayer(d, heads, d_ff, p) for _ in range(N))
self.out = nn.Linear(d, vocab)
t_fixup_init(self, N, d)
def forward(self, src, tgt):
x = self.src_emb(src) # positional encoding omitted
for layer in self.enc:
x = layer(x)
T = tgt.shape[1]
mask = torch.ones(T, T, dtype=torch.bool, device=tgt.device).tril()
y = self.tgt_emb(tgt)
for layer in self.dec:
y = layer(y, x, mask)
return self.out(y)
@torch.no_grad()
def t_fixup_init(model: TFixupTransformer, N: int, d: int) -> None:
# Step 1: Xavier except embeddings; embeddings N(0, d^(-1/2)) (standard deviation d^(-1/2))
for mod in model.modules():
if isinstance(mod, nn.Linear):
nn.init.xavier_uniform_(mod.weight)
nn.init.zeros_(mod.bias)
for emb in (model.src_emb, model.tgt_emb):
nn.init.normal_(emb.weight, mean=0.0, std=d ** -0.5)
dec_scale = (9 * N) ** -0.25 # (9N)^(-1/4)
enc_scale = 0.67 * N ** -0.25 # 0.67 N^(-1/4)
# Step 2: scale decoder v, w, MLP weights, and both input embeddings by (9N)^(-1/4)
for layer in model.dec:
for attn in (layer.self_attn, layer.enc_attn):
attn.v.weight.mul_(dec_scale)
attn.w.weight.mul_(dec_scale) # q and k are not shrunk
layer.ff[0].weight.mul_(dec_scale)
layer.ff[2].weight.mul_(dec_scale)
model.src_emb.weight.mul_(dec_scale)
model.tgt_emb.weight.mul_(dec_scale)
# Step 3: scale encoder v, w and MLP weights by 0.67 N^(-1/4)
for layer in model.enc:
layer.attn.v.weight.mul_(enc_scale)
layer.attn.w.weight.mul_(enc_scale)
layer.ff[0].weight.mul_(enc_scale)
layer.ff[2].weight.mul_(enc_scale)
model = TFixupTransformer(vocab=1000, N=6)
src = torch.randint(0, 1000, (2, 20))
tgt = torch.randint(0, 1000, (2, 15))
print(model(src, tgt).shape) # torch.Size([2, 15, 1000])
# Step 4: train with a constant learning rate from the start, without warmup
optimizer = torch.optim.Adam(model.parameters(), lr=5e-4, betas=(0.9, 0.98))
model.train() # no normalization layers, so the only difference from eval() is Dropout
FAQ
Q. What is the difference between T-Fixup and Fixup?
A.
Fixup is a method for the MLP and convolution blocks of residual networks (ResNet) that sets the last layer of each branch to 0 and adds scalar multipliers and biases. T-Fixup re-derives the conditions for Transformer attention blocks from the same goal of "bounding the size of one update regardless of depth"; it adds nothing to the architecture and only shrinks specific weights. In the paper's translation experiments, T-Fixup achieved higher BLEU.
Q. Why aren't the query and key projections in attention shrunk?
A.
Because in Theorem 3.1 of the paper, the condition that bounds the size of the attention update involves only the magnitudes of the value projection v, the output projection w, and the input (the encoder output m). The query and key projections sit inside the softmax and only determine how the attention weights are distributed; they do not directly affect the output magnitude.
Q. With T-Fixup, is warmup never needed?
A.
In the paper's machine translation experiments, training worked without warmup from 6 to 200 layers, and even with the minibatch increased 8 times. However, what was verified is encoderβdecoder translation models trained with Adam. For models with a different architecture or optimizer, judge by observing the behavior, for example adding a short warmup if training is unstable.