AI Logic

Normalization

LayerScale

Updated:

Where LayerScale sits and what it does. Left: a Pre-LN Transformer layer in which LayerScale is applied to the outputs of self-attention and the feed-forward network before they are added to the residual. Right: inside LayerScale, the d-channel output of the residual branch is multiplied by the diagonal matrix diag(λ1, …, λd). Below: comparison with methods such as ReZero that multiply all channels by a single scalar α

What Is LayerScale?

LayerScale multiplies the output of each residual block in a Transformer (self-attention and feed-forward) by a separate learnable coefficient per channel before adding it to the residual. The coefficients start from a small value ε\varepsilon. Touvron et al. proposed it in 2021 to make image classification Transformers (CaiT) deeper.

Image Transformers such as ViT and DeiT become unstable to train as layers are added, and when trained on ImageNet alone, accuracy did not improve with depth. In the paper, the DeiT training recipe did not converge well beyond 18 layers without hyperparameter tuning. With LayerScale, even 36 layers trained stably, and accuracy kept rising with depth.

It adjusts the scale of residual block outputs per channel, but unlike Layer Normalization, it does not use the mean or variance of the data; it simply multiplies by learned constants.

The figure at the top of the article shows, on the left, a Transformer layer with LayerScale, and on the right, what LayerScale does (multiplication by a diagonal matrix) compared with earlier methods that multiply by a single scalar.

Computation Steps

ViT and DeiT layers use the Pre-LN form, with Layer Normalization η\eta at the entrance of the residual branch (Eq. (2) in the paper). SA denotes self-attention and FFN the feed-forward network. xl′=xl+SA(η(xl)),xl+1=xl′+FFN(η(xl′))\mathbf{x}'_l = \mathbf{x}_l + \mathrm{SA}(\eta(\mathbf{x}_l)), \qquad \mathbf{x}_{l+1} = \mathbf{x}'_l + \mathrm{FFN}(\eta(\mathbf{x}'_l))

LayerScale computes the following in order (Eq. (4) in the paper).

  1. Compute the residual branch as usual. Layer Normalization followed by self-attention (or the feed-forward network) produces a dd-dimensional vector.
  2. Multiply the output by a diagonal matrix. Each channel ii is multiplied by its own coefficient λl,i\lambda_{l,i}. Multiplying by diag(λl,1,…,λl,d)\mathrm{diag}(\lambda_{l,1}, \ldots, \lambda_{l,d}) is the same as multiplying the value of each channel by λl,i\lambda_{l,i}.
  3. Add it to the residual. xl′=xl+diag(λl,1,…,λl,d)×SA(η(xl))\mathbf{x}'_l = \mathbf{x}_l + \mathrm{diag}(\lambda_{l,1}, \ldots, \lambda_{l,d}) \times \mathrm{SA}(\eta(\mathbf{x}_l)) xl+1=xl′+diag(λl,1′,…,λl,d′)×FFN(η(xl′))\mathbf{x}_{l+1} = \mathbf{x}'_l + \mathrm{diag}(\lambda'_{l,1}, \ldots, \lambda'_{l,d}) \times \mathrm{FFN}(\eta(\mathbf{x}'_l))

λl,i\lambda_{l,i} and λl,i′\lambda'_{l,i} are learnable parameters, all initialized to the same small value ε\varepsilon. The paper sets the value according to depth as follows.

Network depthInitial value ε\varepsilon
Up to 18 layers0.1
24 layers10−510^{-5}
Deeper10−610^{-6}

The added parameters amount to dd per block, only a few thousand across the whole network. This is negligible compared with the total number of weights.

Why It Enables Training Deep Models

The idea of the paper is to keep each block's contribution small at the start of training, so the network starts close to the identity map (a function that outputs its input unchanged), and then gradually make use of the blocks as training proceeds. When the coefficients are initialized to small values, every block initially adds almost nothing to the residual, so the signal is not badly disturbed even in a deep network.

This idea is shared with ReZero, SkipInit, Fixup, and T-Fixup. These methods multiply the output of a residual block by a single scalar. LayerScale differs in having a separate coefficient per channel. The paper explains that the aim is to group the updates of weights connected to the same output channel, and that giving each channel its own degree of freedom is the decisive advantage over earlier methods.

As an analogy, ReZero and similar methods attach a single volume knob to each block, while LayerScale attaches an equalizer with a knob for each channel. Both start almost silent.

Balanced block contributions: In a 36-layer model, the paper measures the ratio of the magnitude of the residual branch output to that of the main path at each layer. With LayerScale the ratio is uniform across layers, about 20% of the main path on average. Without LayerScale the ratio varies widely across layers and becomes small in some deep layers (Figure 4 in the paper).

Expressiveness is unchanged: λ\lambda can be folded into the weights of the last linear layer of the preceding self-attention or feed-forward network, so the set of functions the network can represent does not change. The paper attributes most of the effect to its influence on optimization. This is supported by the finding that retraining with the learned coefficients frozen gave lower accuracy than learning them (Appendix A in the paper).

Difference from ActNorm and Layer Normalization: ActNorm and Layer Normalization also multiply outputs by per-channel coefficients. However, their coefficients serve to bring activations to mean 0 and variance 1. LayerScale's coefficients serve to keep the contribution of the residual branch small; the purpose is different.

Experimental Results

Top-1 accuracy of DeiT-S (width 384) with varying numbers of layers, trained only on ImageNet-1k for 300 epochs (Table 1 in the paper). The drop rate drd_r of Stochastic Depth is tuned for each method. ReZero, T-Fixup, and Fixup did not converge in their original form, so they are compared with Layer Normalization and warmup restored.

DepthDeiT (drd_r = 0.05)DeiT (tuned drd_r)ReZeroT-FixupFixupScalar α=ε\alpha = \varepsilonLayerScale
1279.979.978.379.480.780.480.5
1880.180.780.181.782.081.681.7
24Training failed81.080.881.582.381.182.4
36Training failed81.981.682.182.481.682.9
  • In shallow models (12–18 layers), Fixup and T-Fixup are on par with LayerScale.
  • In deep models (24–36 layers), LayerScale is the best, and accuracy increases with depth.
  • LayerScale outperforms initializing a single scalar to a small value (α=ε\alpha = \varepsilon), confirming the benefit of per-channel coefficients.

Comparison of initializations (Table A.1 in Appendix A of the paper): Initializing the coefficients to 0 is better than ReZero (a scalar), but LayerScale, initialized to a small ε\varepsilon, is better still. Initializing from the uniform distribution U[0,2ε]U[0, 2\varepsilon] performs about as well as initializing to 0 and falls short of LayerScale.

DepthReZero (α=0\alpha = 0)λi=0\lambda_i = 0λi∼U[0,2ε]\lambda_i \sim U[0, 2\varepsilon]λi=ε\lambda_i = \varepsilon (LayerScale)
1278.379.780.280.5
1880.181.580.881.7
2480.882.182.182.4
3681.682.782.682.9

The paper builds CaiT by combining LayerScale with class-attention, which handles the class embedding in separate layers, and achieves 86.5% top-1 accuracy on ImageNet without external data.

Practical Considerations

Choose the initial value ε\varepsilon according to depth. In the paper it is 0.1 up to 18 layers, 10−510^{-5} at 24 layers, and 10−610^{-6} for deeper networks. The deeper the model, the smaller the value. Initializing to a small nonzero value also gave better results than initializing to 0.

Tune the Stochastic Depth rate as well. Methods such as LayerScale reduce the need for Stochastic Depth, so the paper tunes the drop rate drd_r for each method and depth (CaiT-S, based on DeiT-S, sets it with a depth-dependent formula). Simply adding LayerScale while leaving other hyperparameters unchanged may not give the best results.

Also keep the following in mind.

  • Keep Layer Normalization and warmup. LayerScale does not replace Pre-LN Layer Normalization. In the paper, ReZero and Fixup with Layer Normalization and warmup removed did not converge in deep image Transformers.
  • PyTorch's torch.nn has no built-in module. It can be implemented simply by initializing a learnable parameter of length dd to ε\varepsilon and multiplying it element-wise with the output of the residual branch (see the code example below).
  • At inference, it can be folded into the preceding linear layer. λ\lambda only scales each output channel of the preceding linear layer, so folding it into that layer's weights and bias adds no computation at inference.
  • The computation is the same at training and inference. Because it uses no data statistics, LayerScale behaves the same under model.train() and model.eval().

Comparison with Other Methods

AspectLayerScaleReZeroFixupLayer Normalization
What it doesMultiplies the residual branch output by per-channel coefficientsMultiplies the residual branch output by a scalarMultiplies by a scalar and also changes weight initialization and biasesBrings activations to mean 0 and variance 1
Number of coefficientsdd per block1 per block1 per block (plus biases, etc.)dd gains and biases per layer
Initial valueSmall value ε\varepsilon01Gain 1
Data statisticsNot usedNot usedNot usedUsed
Deep image Transformer (36 layers, Table 1 in the paper)82.9%81.6% (with normalization and warmup restored)82.4% (same)—

Rough guidelines for choosing:

  • Making an image Transformer 24 layers or deeper: Add LayerScale on top of Pre-LN Layer Normalization.
  • Around 12–18 layers: There is little difference between LayerScale and Fixup. LayerScale is easy to implement and has only ε\varepsilon as a hyperparameter, making it convenient.
  • Removing normalization altogether: LayerScale does not replace normalization, so consider methods in the ReZero or Fixup family (although in the paper's image Transformers, removing normalization prevented convergence).

PyTorch example

Show code
python
import torch
import torch.nn as nn

class LayerScale(nn.Module):
    """Eq. (4) of the paper: multiply the residual branch output by diag(λ_1, ..., λ_d)"""
    def __init__(self, dim: int, init_value: float = 1e-5):
        super().__init__()
        self.gamma = nn.Parameter(init_value * torch.ones(dim))   # all initialized to ε

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return x * self.gamma          # multiplying by a diagonal matrix = per-channel multiplication

class Block(nn.Module):
    """A Pre-LN Transformer layer with LayerScale"""
    def __init__(self, dim: int, heads: int, init_value: float):
        super().__init__()
        self.norm1 = nn.LayerNorm(dim)
        self.attn = nn.MultiheadAttention(dim, heads, batch_first=True)
        self.ls1 = LayerScale(dim, init_value)
        self.norm2 = nn.LayerNorm(dim)
        self.ffn = nn.Sequential(nn.Linear(dim, 4 * dim), nn.GELU(), nn.Linear(4 * dim, dim))
        self.ls2 = LayerScale(dim, init_value)

    def forward(self, x):
        h = self.norm1(x)
        x = x + self.ls1(self.attn(h, h, h, need_weights=False)[0])   # x' = x + diag(λ) SA(η(x))
        x = x + self.ls2(self.ffn(self.norm2(x)))                      # x_{l+1} = x' + diag(λ') FFN(η(x'))
        return x

# Choose the initial value ε by depth (paper: 0.1 up to 18 layers, 1e-5 at 24 layers, 1e-6 for deeper)
def layerscale_init(depth: int) -> float:
    if depth <= 18:
        return 0.1
    if depth <= 24:
        return 1e-5
    return 1e-6

depth, dim = 36, 384
model = nn.Sequential(*[Block(dim, heads=6, init_value=layerscale_init(depth)) for _ in range(depth)])
x = torch.randn(2, 197, dim)                  # [batch, number of tokens, d]
print(model(x).shape)

# For inference, fold λ into the preceding linear layer (the second Linear of the FFN)
blk = model[0]
lin = blk.ffn[2]
with torch.no_grad():
    lin.weight.mul_(blk.ls2.gamma.unsqueeze(1))   # multiply each output channel by λ
    lin.bias.mul_(blk.ls2.gamma)
    blk.ls2.gamma.fill_(1.0)                      # equivalent to no multiplication from now on

FAQ

Q. Can LayerScale replace Layer Normalization?
A.

No. In the paper, LayerScale keeps Pre-LN Layer Normalization and additionally multiplies the residual branch output by coefficients. Layer Normalization equalizes the scale of activations, while LayerScale adjusts the size of each block's contribution; their roles differ.

Q. How does it differ from ReZero?
A.

ReZero multiplies each residual block by a single scalar initialized to 0 and also removes Layer Normalization. LayerScale multiplies by a separate coefficient per channel, initializes it to a small nonzero value, and keeps Layer Normalization. In the paper's deep image Transformers, ReZero did not converge unless normalization and warmup were restored, and even then LayerScale achieved higher accuracy.

Q. Why is the initial value a small number rather than 0?
A.

In the experiments in Appendix A of the paper, initializing to a small value ε gave higher accuracy than initializing to 0 at every depth. Starting from 0 was better than ReZero but fell short of LayerScale.

References

  1. H. Touvron, M. Cord, A. Sablayrolles, G. Synnaeve, and H. Jégou, "Going deeper with Image Transformers," ICCV, 2021.
  2. 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:2003.04887, 2020.
  3. H. Touvron, M. Cord, M. Douze, F. Massa, A. Sablayrolles, and H. Jégou, "Training data-efficient image transformers & distillation through attention," ICML, 2021.