AI Logic

Weight Initialization

ReZero

Updated:

Transformer layers with ReZero. The top shows the original Transformer (Post-Norm), which applies layer normalization after adding the residual for both self-attention and feed-forward. The middle shows ReZero, which removes layer normalization and multiplies the outputs of the two sublayers by the same scalar α_i, initialized to 0, before adding the residual. The bottom gives the ReZero equation and notes that the layer is the identity map right after initialization

Background and overview

ReZero (residual with zero initialization) is a method that multiplies the transformation FF of each layer with a residual connection by a learnable scalar αi\alpha_i and starts training from αi=0\alpha_i = 0. It was proposed in 2020 by Thomas Bachlechner et al. (University of California, San Diego).

xi+1=xi+αi F(xi),αi=0 (initial value)x_{i+1} = x_i + \alpha_i\, F(x_i), \qquad \alpha_i = 0 \text{ (initial value)}

In deep networks, signals and gradients shrink or swell by a constant factor each time they pass through a layer, making vanishing gradients and exploding gradients likely. This has been addressed by combining careful initialization, normalization such as batch normalization and layer normalization, and residual connections. ReZero simply adds one scalar per layer and starts it at 0, which carries signals deep into the network without normalization.

The paper added ReZero to fully connected networks, ResNet, and the Transformer, and showed that training became faster in every case. In particular, for the Transformer, a 128-layer model was trained with layer normalization and learning rate warmup removed.

The top of the figure shows a layer of the original Transformer (Post-Norm, which applies layer normalization after the addition), and the middle shows a ReZero layer. ReZero removes layer normalization and multiplies the outputs of both sublayers by the same αi\alpha_i before adding them.

Theory (why start from 0)

This section walks through the reasoning in Sections 2–3 of the paper.

  1. A measure of trainability is the singular values of the input–output Jacobian: How much the output moves when the input is perturbed slightly is determined by the input-to-output Jacobian Jio=∂xL/∂x0J_{io} = \partial x_L / \partial x_0. Pennington et al. showed that having all singular values close to 1 (dynamical isometry) is a condition for training deep networks efficiently, because signals in every direction propagate without shrinking or swelling.
  2. ReLU, layer normalization, and self-attention break this condition: ReLU zeroes out changes in some inputs. Layer normalization removes the mean and variance of the input, so two singular values per position become 0. Self-attention also drives many singular values toward 0. The paper measured, for a Transformer encoder initialized with Xavier uniform, that the number of zero singular values grows as layers get deeper (Figure 5a).
  3. With αi=0\alpha_i = 0, the network right after initialization is the identity map: Every layer gives xi+1=xix_{i+1} = x_i, so the Jacobian is the identity matrix and all singular values are 1. Whatever the layers contain, dynamical isometry is satisfied automatically.
  4. Compare with a toy single-neuron model: An LL-layer model in which the weight ww and α\alpha are shared across all layers gives xL=(1+αw)Lx0x_L = (1 + \alpha w)^L x_0 (Eq. 5). With α=1\alpha = 1 (an ordinary residual network) and w≈1w \approx 1, the output is nearly 2L2^L times the input and reacts strongly to even tiny changes in the input. To converge, the learning rate must shrink exponentially with depth (Eq. 7). λ∝L−1(1+w)−(L−1)\lambda \propto L^{-1} (1 + w)^{-(L-1)}
  5. Starting from α=0\alpha = 0, a learning rate polynomial in depth suffices: On the first update, the gradient with respect to ww is 0, and only α\alpha moves, by −λLwx0 ∂xC-\lambda L w x_0\, \partial_x C (Eq. 8, where CC is the loss). Because α\alpha moves first to a value at which the output does not get too large, the parameters stay in a well-behaved region as training proceeds.

As an analogy, it is like not having a newcomer speak in front of everyone right away, but letting them only listen at first and gradually giving them more speaking time as they get used to things. αi\alpha_i learns the "speaking volume" of each layer.

How to use it in the Transformer

The original Transformer adds the output of each sublayer (self-attention and feed-forward) as a residual and then applies layer normalization (Eq. 9).

xi+1=LayerNorm(xi+sublayer(xi))x_{i+1} = \mathrm{LayerNorm}\bigl(x_i + \mathrm{sublayer}(x_i)\bigr)

ReZero removes layer normalization and multiplies the sublayer output by αi\alpha_i (Eq. 10).

xi+1=xi+αi sublayer(xi)x_{i+1} = x_i + \alpha_i\, \mathrm{sublayer}(x_i)

The self-attention and feed-forward within one Transformer layer share the same αi\alpha_i. In other words, the only added parameter is one scalar per layer. The paper lays out the differences in where normalization is placed (Pre-LN and Post-LN) as follows (Table 1).

FormEquation
Residual networkxi+1=xi+F(xi)x_{i+1} = x_i + F(x_i)
Residual + Pre-Normxi+1=xi+F(Norm(xi))x_{i+1} = x_i + F(\mathrm{Norm}(x_i))
Residual + Post-Normxi+1=Norm(xi+F(xi))x_{i+1} = \mathrm{Norm}(x_i + F(x_i))
ReZeroxi+1=xi+αiF(xi)x_{i+1} = x_i + \alpha_i F(x_i)

When a 64-layer ReZero Transformer was trained, ∣αi∣|\alpha_i| rose sharply early in training to a peak and then slowly decreased to a small value. Early in training, higher layers reached their peaks sooner, and by the end all layers were used to a similar degree. The mean ∣αi∣|\alpha_i| after training was 0.0898 for 12 layers and 0.0185 for 64 layers, roughly 1/L1/L (LL is the number of layers) (Figure 6).

Experimental results

These are the results reported in the paper.

Transformer, 12-layer model on enwik8 (number of updates until validation BPB reaches 1.2, fewer is better. BPB is bits per byte, the cross-entropy loss expressed in base 2. Table 3)

ModelUpdatesSpeed (relative to Post-Norm + warmup)
Post-Norm (original Transformer)Diverged—
Post-Norm + warmup13,6901×
Pre-Norm17,7650.77×
GPT2-Norm21,1870.65×
ReZero (initialized with α=1\alpha = 1)14,5060.94×
ReZero (initialized with α=0\alpha = 0)8,8001.56×

Deep Transformers, enwik8 (test BPB, lower is better. Table 4)

ModelLayersParametersBPB
Transformer + warmup1238M1.17
ReZero (α=0\alpha = 0)1234M1.17
Transformer (with or without warmup)6451MDiverged
ReZero (α=1\alpha = 1)6451MDiverged
ReZero (α=0\alpha = 0)6451M1.11
ReZero128101M1.08

ResNet, CIFAR-10 (validation error and epochs to reach 80% accuracy; lower is better for both. Table 2)

ModelErrorEpochs to 80%
ResNet-566.27%20
ResNet-56 + Fixup7.26%13
ResNet-56 + ReZero6.58%15
ResNet-1106.24%23
ResNet-110 + Fixup7.10%15
ResNet-110 + ReZero5.93%14
Pre-activation ResNet-186.38%26
Pre-activation ResNet-18 + ReZero5.43%12
Pre-activation ResNet-505.37%26
Pre-activation ResNet-50 + ReZero4.80%17
  • Starting α\alpha at 0 matters: Initialized with α=1\alpha = 1, it was no different from the original Transformer at 12 layers and diverged at 64 layers.
  • Deeper models had lower BPB: ReZero reached 1.11 with 64 layers and 1.08 with 128 layers, approaching the Character Transformer that uses auxiliary losses (1.06 with 64 layers and 219M parameters) with fewer parameters.
  • Faster for fully connected networks too: Training a 32-layer fully connected network of width 256 with ReLU on CIFAR-10, ReZero fit the training data 7–15 times faster than the other forms, and even a 10,000-layer fully connected network could be trained (Figure 3).
  • Combined with batch normalization for ResNet: In the ResNet experiments, ReZero sped up training while keeping the regularizing effect of batch normalization, and its error was lower than Fixup's. With pre-activation ResNet-18 and a One-cycle learning rate, the epochs to reach 94% accuracy dropped from 60 to 45.

Practical caveats

αi\alpha_i can be sensitive to large learning rates. In the paper's One-cycle experiments, raising the learning rate of αi\alpha_i to match the other weights tended to cause divergence, so αi\alpha_i alone was given a constant learning rate of 0.1. If training is unstable, put αi\alpha_i in a separate parameter group from the other parameters and lower its learning rate.

Keep the following points in mind as well.

  • Use it in architectures with residual connections: ReZero becomes the identity map at αi=0\alpha_i = 0 only when there is a "path that passes the input through unchanged".
  • The regularizing effect of normalization does not remain: The paper says that ReZero alone removes the need for normalization for convergence, while the regularizing effect of batch normalization complements ReZero. The ResNet experiments keep batch normalization.
  • PyTorch has no built-in version: nn.TransformerEncoderLayer includes layer normalization, so write the layer yourself (see the implementation example below). Create αi\alpha_i with nn.Parameter(torch.zeros(())). Since there are no normalization layers, the only difference between model.train() and model.eval() is Dropout.
  • Decide whether to apply weight decay to αi\alpha_i: αi\alpha_i is itself how strongly each layer acts, so pulling it back toward 0 with the same strength as the weights weakens the layers. The paper does not address this point, so check experimentally whether to apply it.
  • Learning rate warmup is often unnecessary: The paper's Transformer experiments used LAMB with a fixed learning rate of 0.016, without warmup or learning rate decay.

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 parametersInitial branch outputMain target
Post-LN (original Transformer)Layer normalization after the additionNormalization γ,β\gamma, \betaNot 0Transformer (warmup required)
Pre-LNLayer normalization on the branch inputNormalization γ,β\gamma, \betaNot 0Transformer
FixupLast layer set to 0, other layers shrunk according to depthScalar multipliers and biases0Residual networks
SkipInitScalar α\alpha at the end of the branch (from 0)One scalar per block0ResNet
ReZeroScalar αi\alpha_i at the end of the branch (from 0)One scalar per layer0Transformer, ResNet, fully connected
T-FixupAttention and MLP weights shrunk according to depthNoneNot 0 (small)Transformer (encoder–decoder)

ReZero can be seen as Fixup's idea of zeroing the output-side layer narrowed down to a single scalar. The paper says it is close to the part of Fixup's rule 3 that adds a multiplier, but differs in that the initial value is 0 rather than 1. SkipInit is a method of the same form proposed independently around the same time, and its paper focuses on ResNet and the analysis of batch normalization.

Rough guidelines for choosing:

  • To train deep Transformers quickly without normalization or warmup, use ReZero: It takes a few lines to implement, and there is no depth-dependent value to set.
  • For encoder–decoder Transformers such as for translation, when the architecture should not change, use T-Fixup: It stabilizes training through initial scaling alone, without adding parameters.
  • For stable results including regularization, keep the normalization layers: ReZero can also be combined with normalization, and in the ResNet experiments that combination lowered the error.

PyTorch example

Show code
python
import torch
import torch.nn as nn


# ReZero Transformer encoder layer (Eq. (10) and Figure 4 right of the paper)
class ReZeroEncoderLayer(nn.Module):
    def __init__(self, d_model: int = 512, nhead: int = 2, d_ff: int = 2048, dropout: float = 0.2):
        super().__init__()
        self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout, batch_first=True)
        self.ff = nn.Sequential(
            nn.Linear(d_model, d_ff), nn.GELU(), nn.Dropout(dropout), nn.Linear(d_ff, d_model),
        )
        self.drop1 = nn.Dropout(dropout)
        self.drop2 = nn.Dropout(dropout)
        # ReZero: one learnable scalar per layer, initialized to 0 and shared by the two sublayers
        self.alpha = nn.Parameter(torch.zeros(()))
        # no layer normalization

    def forward(self, x: torch.Tensor, attn_mask: torch.Tensor | None = None) -> torch.Tensor:
        h, _ = self.self_attn(x, x, x, attn_mask=attn_mask, need_weights=False)
        x = x + self.alpha * self.drop1(h)            # x + α · attention(x)
        x = x + self.alpha * self.drop2(self.ff(x))   # x + α · feed-forward(x)
        return x


class ReZeroEncoder(nn.Module):
    def __init__(self, num_layers: int = 64, d_model: int = 256, **kw):
        super().__init__()
        self.layers = nn.ModuleList([ReZeroEncoderLayer(d_model, **kw) for _ in range(num_layers)])

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        for layer in self.layers:
            x = layer(x)
        return x


model = ReZeroEncoder(num_layers=64, d_model=256, d_ff=1024)
x = torch.randn(2, 128, 256)  # (batch, sequence length, embedding dim)
model.eval()  # disable Dropout (no normalization layers, so otherwise the same as train())
with torch.no_grad():
    print(torch.equal(model(x), x))  # True: α = 0, so right after initialization it is the identity map

# to use a smaller learning rate for α only, split the parameter groups
alphas = [p for n, p in model.named_parameters() if n.endswith("alpha")]
others = [p for n, p in model.named_parameters() if not n.endswith("alpha")]
optimizer = torch.optim.Adam([
    {"params": others, "lr": 1e-3},
    {"params": alphas, "lr": 1e-4},
])
model.train()

FAQ

Q. With α set to 0, aren't the weights inside the layer left untrained at first?
A.

On the very first update, the gradient with respect to the weights inside the layer is 0, and only α\alpha moves. However, the gradient with respect to α\alpha is proportional to the layer output F(x)F(x), and F(x)F(x) is not 0, so α\alpha quickly moves away from 0. After that, gradients flow to the weights inside the layer as well. The paper's toy model also shows that because α\alpha moves first to a well-behaved value, the learning rate does not need to shrink exponentially even for deep networks.

Q. What is the difference between ReZero and SkipInit?
A.

Both multiply the residual branch by a learnable scalar initialized to 0; they are nearly the same form and were proposed independently around the same time. The SkipInit paper focuses on explaining why batch normalization makes deep ResNets trainable. The ReZero paper starts from dynamical isometry (all singular values of the Jacobian equal to 1) and shows that it also works for Transformers and fully connected networks. In the Transformer, the two sublayers of one layer share α\alpha.

Q. Can layer normalization be kept when using ReZero?
A.

Yes. In the paper's ResNet experiments, ReZero was added while keeping batch normalization, and training became faster with a lower error. However, if Post-Norm layer normalization is kept in a Transformer, normalization comes after the addition, so the whole layer is not the identity map even with α=0\alpha = 0. The paper's Transformer experiments remove layer normalization.

References

  1. T. Bachlechner, B. P. Majumder, H. H. Mao, G. W. Cottrell, and J. McAuley, "ReZero is All You Need: Fast Convergence at Large Depth," arXiv, 2020.
  2. B. P. Majumder, "rezero" (official implementation), GitHub.
  3. S. De and S. L. Smith, "Batch Normalization Biases Residual Blocks Towards the Identity Function in Deep Networks," NeurIPS, 2020.
  4. J. Pennington, S. Schoenholz, and S. Ganguli, "Resurrecting the sigmoid in deep learning through dynamical isometry: theory and practice," NeurIPS, 2017.
  5. H. Zhang, Y. N. Dauphin, and T. Ma, "Fixup Initialization: Residual Learning Without Normalization," ICLR, 2019.