AI Logic

Weight Initialization

T-Fixup

Updated:

T-Fixup initialization. On the left, an encoder layer (self-attention and MLP, each with a residual connection), where the attention v, w and MLP weights are set to 0.67N^(βˆ’1/4) times Xavier. On the right, a decoder layer (self-attention, encoder attention, and MLP), where the same weights are scaled by (9N)^(βˆ’1/4). Below each is the input embedding, drawn from a normal distribution with mean 0 and standard deviation d^(βˆ’1/2) and scaled by (9N)^(βˆ’1/4). The four steps are listed at the very bottom

Background and overview

T-Fixup is an initialization method that makes the Transformer trainable without layer normalization or learning rate warmup by shrinking the initial weight values according to the number of layers. It was proposed in 2020 by Xiao Shi Huang, Felipe PΓ©rez, Jimmy Ba, and Maksims Volkovs (ICML 2020).

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. NN is the number of layers and dd is the embedding dimension.

Why warmup becomes necessary

This section walks through the analysis in Section 3.1 of the paper.

  1. Adam's updates fluctuate most at the start of training: Adam divides the learning rate by vtv_t, a moving average of squared gradients. Liu et al. (the RAdam paper) showed that because vtv_t 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).
  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).
  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 xx follows the expression below (Eq. 1). βˆ₯βˆ‚β€‰LN(x)βˆ‚xβˆ₯=O ⁣(dβˆ₯xβˆ₯)\left\| \frac{\partial\, \mathrm{LN}(x)}{\partial x} \right\| = O\!\left( \frac{\sqrt{d}}{\|x\|} \right) With an embedding dimension of d=512d = 512, dβ‰ˆ22.6\sqrt{d} \approx 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).
  4. Small gradients make Adam even more unstable: When gradients vanish, the estimate of vtv_t 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 Ξ·\eta".

βˆ₯Ξ”fβˆ₯=Θ(Ξ·)\|\Delta f\| = \Theta(\eta)

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.

  1. It suffices to bound each decoder block's update to Θ(1/Ld)\Theta(1/L_d): The decoder is a stack of residual blocks yl+1=yl+Gl(yl)y_{l+1} = y_l + G_l(y_l). Since the updates of LdL_d blocks add up, making each block's contribution Θ(1/Ld)\Theta(1/L_d) gives Θ(1)\Theta(1) overall.
  2. Derive the condition for an attention block: Attention can be written as follows using the key, query, and value projections k,q,vk, q, v and the output projection ww (Eq. 5). Attn(a,b,c)=softmax ⁣(1d b q k⊀a⊀)c v w⊀\mathrm{Attn}(a, b, c) = \mathrm{softmax}\!\left( \frac{1}{\sqrt{d}}\, b\, q\, k^{\top} a^{\top} \right) c\, v\, w^{\top} The paper showed that the condition for the update of encoder attention (whose keys and values are the encoder output mm) to be Θ(Ξ·/Ld)\Theta(\eta / L_d) is the following (Theorem 3.1). βˆ₯vβˆ₯2βˆ₯wβˆ₯2+βˆ₯wβˆ₯2βˆ₯miβˆ₯2+βˆ₯vβˆ₯2βˆ₯miβˆ₯2=Θ(1/Ld)\|v\|^2 \|w\|^2 + \|w\|^2 \|m_i\|^2 + \|v\|^2 \|m_i\|^2 = \Theta(1/L_d) The query and key projections q,kq, k inside the softmax do not enter the condition, so they need not be shrunk.
  3. Derive the conditions for the whole encoder and decoder: An NN-layer model has Le=2NL_e = 2N blocks in the encoder (self-attention and MLP) and Ld=3NL_d = 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).
  4. Choose magnitudes that satisfy the conditions: Setting the magnitudes of the decoder's v,wv, w and the input embeddings x,yx, y to (3Ld)βˆ’1/4=(9N)βˆ’1/4(3L_d)^{-1/4} = (9N)^{-1/4} satisfies the decoder conditions. Solving the remaining encoder conditions gives about 0.67Nβˆ’1/40.67N^{-1/4} for the encoder's v,wv, w.

The actual procedure is as follows.

  1. 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/2d^{-1/2}.
  2. Multiply v,wv, w of each decoder attention, the weights of each decoder MLP, and the encoder and decoder input embeddings by (9N)βˆ’1/4(9N)^{-1/4}.
  3. Multiply v,wv, w of each encoder attention and the weights of each encoder MLP by 0.67Nβˆ’1/40.67N^{-1/4}.
  4. Remove all layer normalization and train without warmup.

For example, for a 6-layer model (N=6N = 6), the decoder factor is 54βˆ’1/4β‰ˆ0.36954^{-1/4} \approx 0.369 and the encoder factor is 0.67Γ—6βˆ’1/4β‰ˆ0.4280.67 \times 6^{-1/4} \approx 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)

MethodIWSLT'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 Transformer34.228.625.2527.329.3
Pre-LNβ€”β€”β€”27.128.7
R-Fixup (Fixup)34.5β€”β€”β€”29.3
RAdam (no warmup)34.828.5β€”β€”β€”
T-Fixup35.529.425.729.129.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)

MethodLayersBLEU
Original Transformer627.3
Pre-LN2028.9
DLCL2529.2
DLCL-Pre-LN3029.3
T-Fixup629.1
T-Fixup2029.4
T-Fixup3029.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 vv and the output projection ww are shrunk; the query and key projections q,kq, k are left as they are. The encoder uses 0.67Nβˆ’1/40.67N^{-1/4}, and the decoder and the input embeddings use (9N)βˆ’1/4(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Γ—d3d \times 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\sqrt{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.

Comparison of residual blocks without normalization. From top: Fixup (adds scalar biases and a multiplier, sets the last convolution to 0, and shrinks the others), SkipInit (multiplies the end of the branch by Ξ± initialized to 0), ReZero (multiplies any branch F by Ξ± initialized to 0), T-Fixup (adds no scalars and shrinks the attention and MLP weights according to depth)

MethodHow the branch is shrunkAdded parametersLayer normalizationWarmup
Post-LN (original Transformer)Not shrunk (normalized after the addition)NoneUsedRequired
Pre-LNNormalizes the branch inputNoneUsedTrainable without it
Fixup (R-Fixup)Last layer 0, other layers shrunk according to depthScalar multipliers and biasesNot usedNot compared in the T-Fixup paper
ReZeroMultiplies the branch output by a scalar Ξ±i\alpha_i starting from 0One scalar per layerNot usedTrainable without it
T-FixupShrinks the attention v,wv, w and MLP weights in proportion to Nβˆ’1/4N^{-1/4}NoneNot usedTrainable 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 vv, the output projection ww, and the input (the encoder output mm). 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.

References

  1. X. S. Huang, F. PΓ©rez, J. Ba, and M. Volkovs, "Improving Transformer Optimization Through Better Initialization," ICML, PMLR 119, 2020.
  2. Layer 6 AI Labs, "T-Fixup" (official implementation), GitHub.
  3. H. Zhang, Y. N. Dauphin, and T. Ma, "Fixup Initialization: Residual Learning Without Normalization," ICLR, 2019.
  4. 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.
  5. L. Liu, H. Jiang, P. He, W. Chen, X. Liu, J. Gao, and J. Han, "On the Variance of the Adaptive Learning Rate and Beyond," ICLR, 2020.