AI Logic

Weight Initialization

LSUV

Updated:

The LSUV procedure. The left shows the network's layers from the bottom: layers 1 and 2 already adjusted, layer L being adjusted, and the upper layers still at orthogonal initialization. The right shows the adjustment of layer L: forward a minibatch, measure the output variance Var(B_L), and divide the weights by √Var(B_L), repeating until the variance is close to 1. The three steps are listed below

Background and overview

LSUV (Layer-Sequential Unit-Variance initialization) is an initialization method that passes real data through the network and sets the weight scale so that the output variance of each layer is 1. It was proposed in 2015 by Dmytro Mishkin and JiΕ™Γ­ Matas (ICLR 2016, "All you need is a good init").

It has just two stages.

  1. Initialize the weights of all convolutional and fully connected layers with orthogonal initialization.
  2. Going from the input side, pass a minibatch through, measure the output variance of the layer, and divide the weights until the variance is 1.

In a deep network, if each layer multiplies the signal by kk, after LL layers it is multiplied by kLk^L. If k>1k > 1 the output explodes, and if k<1k < 1 the signal and gradients vanish (exploding gradients, vanishing gradients). Xavier initialization and He initialization derive by formula the weight variance that makes this factor 1. However, the formula has to be derived for each activation function and layer type, and there was no ready-to-use formula for Maxout, Tanh, max pooling, and so on.

Instead of deriving formulas, LSUV measures on data and adjusts. As a result, it can be used regardless of layer type or activation function. On CIFAR-10/100, the paper trained a thin, deep 17-layer network (FitNet-4) in a single training run, without auxiliary networks or staged training, and reached accuracy close to the state of the art at the time.

The left side of the figure at the top shows the layers being adjusted in order from the input side, and the right side shows the adjustment loop for one layer.

Theory (procedure)

This section walks through Algorithm 1 of the paper. WLW_L is the weight of layer LL (a convolutional or fully connected layer), and BLB_L is the output of that layer.

  1. Initialize all layers with orthogonal matrices: Following Saxe et al. (2014), fill the weights with standard normal random numbers and then replace them with an orthogonal matrix via QR decomposition or singular value decomposition. A convolutional layer's weights are treated as an "output channels Γ— everything else" matrix.
  2. Select the first layer on the input side: Adjustment proceeds one layer at a time from the input side to the output side.
  3. Forward a minibatch and measure the output variance of the selected layer: Var(BL)\mathrm{Var}(B_L) is the variance computed over all elements of the output in the minibatch.
  4. Divide the weights: Dividing by the output standard deviation brings the output variance close to 1. WL←WLVar(BL)W_L \leftarrow \frac{W_L}{\sqrt{\mathrm{Var}(B_L)}}
  5. Repeat 3–4 until the variance is close to 1: Stop when the following condition holds or the number of iterations reaches the limit Tmax⁑T_{\max}. βˆ£β€‰Var(BL)βˆ’1β€‰βˆ£<Tolvar\left|\,\mathrm{Var}(B_L) - 1\,\right| < \mathrm{Tol}_{\mathrm{var}}
  6. Move to the next layer: Once the last layer is done, initialization is complete, and training proceeds as usual.

The iterations are needed because the minibatch changes on each measurement and the variance estimate fluctuates. In the paper's experiments, the limit Tmax⁑T_{\max} was never reached, and the target variance was achieved in 1–5 iterations. The tolerance Tolvar\mathrm{Tol}_{\mathrm{var}} only affects how many iterations initialization takes; in the range 0.01–0.1 it made almost no difference to performance after training.

Proceeding from the input side matters because the output variance of layer LL is determined by the weights of the layers below it. Fixing the lower layers first ensures that adjusting a lower layer will not disturb layer LL after it has been adjusted.

Why it works

The reasons LSUV works come down to three points.

  • It measures and corrects the actual factor instead of relying on a formula's assumptions: Xavier and He initialization derive, assuming a linear or ReLU activation, the variance at which the per-layer factor is 1 on average. LSUV measures the output when real data is passed through, so it can equalize each layer's output scale to 1 even when layers that are hard to handle with formulas, such as Maxout, max pooling, and local response normalization, are mixed in.
  • Orthogonal initialization reduces correlations among layer outputs: An orthogonal matrix transmits signals in every direction with the same factor. The paper says orthogonal initialization reduces correlations among layer activations, an effect that batch normalization does not have. Initializing with a Gaussian and then applying LSUV lowered performance slightly but consistently.
  • It is close to applying batch normalization only on the first minibatch: The paper says LSUV can be seen as "a combination of orthogonal initialization and batch normalization performed only on the first minibatch". Nothing is added during training, so there is no per-step computational burden as with batch normalization (the paper notes that batch normalization adds 30% computation per update).

As an analogy, it is like tuning the instruments one by one before an ensemble performance. Instead of calculating the theoretically correct string tension, each instrument is actually played and matched to a reference pitch. Tuning happens once before the performance, and nothing is adjusted while playing.

In Table 10 of the paper's appendix, the initial gradient variances of each layer of FitNet-4 (ReLU) were all around 10βˆ’910^{-9} for every convolutional layer with LSUV. The ratio of gradient variance between the last fully connected layer and the first convolutional layer was 255 with LSUV, 20 with He initialization, about 12.2 million with orthogonal initialization, and about 3.18 million with Xavier initialization.

Experimental results

These are the results reported in the paper.

CIFAR-10/100, FitNet-4 (test accuracy, higher is better. Data augmentation: horizontal flips and translations. Table 2)

Initialization / training methodCIFAR-10CIFAR-100
LSUV93.94%70.04%
Orthogonal initialization93.78%70.44%
Training with hints (FitNets)91.61%64.96%
Highway Networks92.46%68.09%

Comparison by activation function (CIFAR-10, FitNet-4, test accuracy. n/c means training did not converge. Table 3)

InitializationMaxoutReLUVLReLUTanh
LSUV93.94%92.11%92.97%89.28%
Orthogonal initialization93.78%91.74%92.40%89.48%
Xavier initialization91.75%90.63%92.27%89.82%
He initializationn/c90.91%92.43%89.54%

VLReLU is a Leaky ReLU with a large negative slope of 0.333. Sigmoid could not be trained with any initialization.

Networks with residual connections (CIFAR-10, FitResNet-4, test accuracy. Table 4)

InitializationMaxoutReLUVLReLUTanh
LSUV94.16%92.82%93.36%89.17%
Orthogonal initializationn/c91.42%n/c89.31%
Xavier initializationn/c92.48%93.34%89.62%
He initializationn/cn/cn/c88.59%
  • It converged regardless of activation function: On FitResNet-4 with residual connections, LSUV was the only initialization that converged with every activation function except Sigmoid without extra tuning.
  • On par or better on MNIST: The FitNet-MNIST error rate was 0.48% for both LSUV and orthogonal initialization, and 0.51% when trained with hints.
  • Mixed results on ImageNet: On GoogLeNet, LSUV kept higher accuracy until the end, with a final accuracy of 0.680 versus 0.672. On CaffeNet (a variant of AlexNet), the initial period during which the loss does not decrease shrank from 0.5 epochs to 0.05 epochs, but the original initialization overtook it around epoch 30, and the final accuracy was 1.3% lower. The paper says it cannot explain why.
  • Initialization is fast: Including the singular value decomposition for orthogonalization, even CaffeNet, the slowest case, took about 3.5 minutes (210 seconds) (Table 6).
  • Almost unaffected by the minibatch size used to measure variance: For FitNet-4 (Tanh), varying the measurement minibatch from 2 to 1,024 images gave final accuracies of 89.27–89.31% (Table 7).

Practical caveats

LSUV only equalizes scale once before training and does not maintain it during training. In the experiments of the Fixup paper, very deep residual networks (over 100 layers) could not be trained with the same large learning rate as batch normalization. Equalizing the output scale of each layer does not prevent the output from moving a lot as residual block updates pile up. The paper's authors also do not claim that a good initialization can always replace batch normalization.

Keep the following points in mind as well.

  • PyTorch has no built-in version: torch.nn.init has no LSUV function, so extract layer outputs with hooks and write it by hand (see the implementation example below). nn.init.orthogonal_ can be used for orthogonal initialization.
  • Use model.eval() while measuring: With Dropout or similar layers present, the output fluctuates on every measurement. The networks in the LSUV paper do not use normalization layers. In networks with batch normalization, those layers re-equalize the variance, so applying LSUV matters less.
  • Take minibatches from the training data: The variance depends on the data, so measuring with random numbers or other data with a different distribution throws off the matched scale.
  • Set biases to 0: The algorithm divides only the weights. If biases are nonzero, dividing the weights does not reduce the output variance as intended.
  • Normalize inputs before measuring: The output variance of the first layer is determined by the input scale. For images, use data with the same preprocessing as in training (subtracting the mean, dividing by the standard deviation, etc.).

Comparison with other initializations

The table lines up LSUV with initializations and normalizations it is often compared with, from the same angles.

MethodHow scale is setUses dataComputation during trainingAssumed layers / activations
He initializationVariance 2/nin2/n_{\mathrm{in}} from a formulaNoNoneReLU and its relatives
Orthogonal initializationOrthogonal matrix with all singular values 1NoNoneNearly linear activations
LSUVAfter orthogonal initialization, divides by the measured output varianceOnly at initializationNoneAny
Batch normalizationNormalizes with the minibatch mean and variance every stepThroughout trainingEvery stepAny
FixupShrinks residual branches according to depth and sets the last layer to 0NoNoneResidual networks

Methods like LSUV that set initial values by passing data through the network are collectively called data-dependent initialization.

Rough guidelines for choosing:

  • Use LSUV when no formula fits the activation function or layer type: Even with Maxout and the like, each layer's scale can be measured on data and equalized.
  • For a typical ReLU network, start with He initialization: It is determined by a formula alone, with no need to prepare data.
  • To train very deep residual networks without normalization, use residual-specific methods such as Fixup: LSUV does not account for residual block updates piling up, so as depth grows it becomes hard to train with a large learning rate. Other methods for training residual networks without normalization include SkipInit and ReZero.

PyTorch example

Show code
python
import itertools

import torch
import torch.nn as nn


@torch.no_grad()
def lsuv_init(model: nn.Module, data_iter, tol_var: float = 0.1, t_max: int = 10) -> None:
    """Algorithm 1 of the paper. data_iter is an iterator that yields minibatches of training data (inputs only)"""
    layers = [m for m in model.modules() if isinstance(m, (nn.Conv2d, nn.Linear))]

    # Step 1: initialize all conv and fully connected layers with orthogonal matrices (biases 0)
    for m in layers:
        nn.init.orthogonal_(m.weight)  # convolutions are orthogonalized as an (output channels, everything else) matrix
        if m.bias is not None:
            nn.init.zeros_(m.bias)

    was_training = model.training
    model.eval()  # keep Dropout etc. from making the output fluctuate

    # Step 2: from the input side, divide the weights until the output variance is 1
    for m in layers:
        captured = {}
        hook = m.register_forward_hook(lambda mod, inp, out: captured.__setitem__("out", out))
        for _ in range(t_max):
            model(next(data_iter))                  # forward a minibatch
            var = captured["out"].var().item()      # Var(B_L): variance over all output elements
            if abs(var - 1.0) < tol_var:
                break
            m.weight.div_(var ** 0.5)               # W_L ← W_L / sqrt(Var(B_L))
        hook.remove()

    model.train(was_training)


# Usage example (a thin, deep CNN without normalization layers)
def conv_relu(cin: int, cout: int) -> list[nn.Module]:
    return [nn.Conv2d(cin, cout, kernel_size=3, padding=1), nn.ReLU()]


model = nn.Sequential(
    *conv_relu(3, 32), *conv_relu(32, 32), *conv_relu(32, 32), nn.MaxPool2d(2),
    *conv_relu(32, 80), *conv_relu(80, 80), *conv_relu(80, 80), nn.MaxPool2d(2),
    *conv_relu(80, 128), *conv_relu(128, 128), nn.AdaptiveAvgPool2d(1), nn.Flatten(),
    nn.Linear(128, 10),
)

# in practice, take (preprocessed) training data from a DataLoader; here, random tensors of the right shape
batches = (torch.randn(64, 3, 32, 32) for _ in itertools.count())
lsuv_init(model, batches)

model.train()  # after initialization, train as usual (LSUV does nothing during training)

FAQ

Q. How does LSUV differ from batch normalization?
A.

Both equalize the output variance of each layer to 1, but LSUV divides the weights once before training and then does nothing during training. Batch normalization recomputes the mean and variance for every minibatch and re-equalizes throughout training. As a result, LSUV adds no computation during training, but it does not maintain the scale after the weights change as training proceeds.

Q. How large does the minibatch used to measure variance need to be?
A.

In the paper's experiments, apart from the extreme case of 2 images, any size from 16 to 1,024 gave almost the same final accuracy (89.28–89.31% for FitNet-4, Tanh, CIFAR-10). Even if the variance estimate fluctuates, the loop repeats until it is within tolerance, so a minibatch of the same size as in ordinary training is enough.

Q. Can LSUV be applied after ordinary Gaussian initialization instead of orthogonal initialization?
A.

It works, but in the paper, starting from a Gaussian lowered performance slightly but consistently. Orthogonal matrices reduce correlations among layer outputs, and variance equalization alone does not provide that effect.

References

  1. D. Mishkin and J. Matas, "All you need is a good init," ICLR, 2016.
  2. D. Mishkin, "LSUVinit" (official implementation), GitHub.
  3. A. M. Saxe, J. L. McClelland, and S. Ganguli, "Exact solutions to the nonlinear dynamics of learning in deep linear neural networks," ICLR, 2014.
  4. H. Zhang, Y. N. Dauphin, and T. Ma, "Fixup Initialization: Residual Learning Without Normalization," ICLR, 2019.
  5. PyTorch Documentation, "torch.nn.init."