AI Logic

Weight Initialization

Xavier (Glorot) Initialization

Updated:

On the left, a graph of the variance when 10 layers of equal width are stacked (log-scale vertical axis): Xavier initialization stays at 1×, while the earlier uniform distribution U[−1/√n, 1/√n] shrinks by 1/3 per layer to about 1.7×10^−5 at layer 10. On the right, a bar chart of the per-layer factor for a layer whose output is half as wide as its input: matching fan_in gives 1 forward and 1/2 backward, Xavier gives 4/3 and 2/3, and matching fan_out gives 2 and 1

Background and overview

Xavier initialization is a weight initialization method that draws each layer's weights from a distribution with mean 0 and variance 2/(nin+nout)2/(n_{in}+n_{out}) (ninn_{in} is the number of inputs connected to one output, and noutn_{out} the number of outputs one input connects to). This keeps the variance of both the activations flowing forward and the gradients flowing back in backpropagation from changing much as layers are stacked. It was proposed in 2010 by Xavier Glorot and Yoshua Bengio (AISTATS 2010). The paper calls it "normalized initialization", and after the first author it is known as Xavier initialization or Glorot initialization.

At the time, it was known that deep networks did not train well from random initial values with gradient descent alone. A commonly used initialization drew weights from the uniform distribution U[−1/n, 1/n]U[-1/\sqrt{n},\, 1/\sqrt{n}]. Its variance is 1/(3n)1/(3n), so the variance shrinks by about 1/3 at each layer, and after 10 layers it falls to 3−10≈1.7×10−53^{-10} \approx 1.7 \times 10^{-5} times (vanishing gradients). Xavier initialization brought this "per-layer factor" close to 1, so that signals and gradients reach their destinations even in deep networks.

The left side of the figure at the top shows how the variance changes as layers of equal width are stacked. The right side compares the forward and backward factors for a layer whose output is half as wide as its input. Matching only the forward pass or only the backward pass leaves the other off by 1/2 or 2 times, but Xavier initialization takes the middle ground.

Theory (how variance propagates)

This section walks through the derivation in Section 4.2.1 of the paper. Write the computation of layer ii as follows.

si=ziWi+bi,zi+1=f(si)s^i = z^i W^i + b^i, \qquad z^{i+1} = f(s^i)

Here ziz^i is the input (activation) to the layer, WiW^i the weights, and sis^i the value before the activation function ff. nin_i is the number of units in layer ii.

  1. Assume the linear regime: For activation functions like Tanh that are symmetric around 0 with slope 1 at 0, inputs are near 0 right after initialization, so f′(s)≈1f'(s) \approx 1 can be assumed (Eq. (4)). It is also assumed that the weights are mutually independent and that the input components have equal variance.
  2. Write the forward variance: The variance is multiplied by ni′Var[Wi′]n_{i'} \mathrm{Var}[W^{i'}] at each layer, so the variance of the activations at layer ii is as follows (Eq. (5)). Var[zi]=Var[x]∏i′=0i−1ni′Var[Wi′]\mathrm{Var}[z^i] = \mathrm{Var}[x] \prod_{i'=0}^{i-1} n_{i'} \mathrm{Var}[W^{i'}]
  3. Write the backward variance: Gradients come back from the output side, so the factor involves the output-side width ni′+1n_{i'+1} (Eq. (6)). dd is the number of layers. Var[∂Cost∂si]=Var[∂Cost∂sd]∏i′=idni′+1Var[Wi′]\mathrm{Var}\left[\frac{\partial \mathrm{Cost}}{\partial s^i}\right] = \mathrm{Var}\left[\frac{\partial \mathrm{Cost}}{\partial s^d}\right] \prod_{i'=i}^{d} n_{i'+1} \mathrm{Var}[W^{i'}]
  4. Derive the conditions for a factor of 1: Preserving variance in the forward pass requires niVar[Wi]=1n_i \mathrm{Var}[W^i] = 1 (Eq. (10)), and in the backward pass ni+1Var[Wi]=1n_{i+1} \mathrm{Var}[W^i] = 1 (Eq. (11)). If the input and output widths differ, both cannot be satisfied at once.
  5. Take the middle ground between the two conditions: Using the average of both widths gives the following (Eq. (12)). Var[Wi]=2ni+ni+1\mathrm{Var}[W^i] = \frac{2}{n_i + n_{i+1}} If all layers have the same width, this satisfies both Eq. (10) and Eq. (11).
  6. Draw from a uniform distribution: The paper draws weights from a uniform distribution whose variance matches Eq. (12) (Eq. (16)). The variance of a uniform distribution on [−a,a][-a, a] is a2/3a^2/3, so a=6/ni+ni+1a = \sqrt{6}/\sqrt{n_i + n_{i+1}}. W∼U[−6ni+ni+1, 6ni+ni+1]W \sim U\left[-\frac{\sqrt{6}}{\sqrt{n_i + n_{i+1}}},\ \frac{\sqrt{6}}{\sqrt{n_i + n_{i+1}}}\right]

Biases are set to 0. For example, for a fully connected layer with 784 inputs and 256 outputs, a=6/(784+256)≈0.076a = \sqrt{6/(784+256)} \approx 0.076. When drawing from a normal distribution, set the standard deviation to 2/(nin+nout)\sqrt{2/(n_{in}+n_{out})} (PyTorch's xavier_normal_).

With the earlier U[−1/n, 1/n]U[-1/\sqrt{n},\, 1/\sqrt{n}], nVar[W]=1/3n \mathrm{Var}[W] = 1/3 (Eq. (15)). Xavier initialization can be seen as widening the interval by a factor of 3\sqrt{3} to turn this 1/31/3 into 11, while taking both the input and output widths into account.

Why training becomes faster

Xavier initialization works because when the signal magnitude does not change from layer to layer, gradients of similar magnitude reach every layer. The paper confirms this with three observations.

  • The per-layer amplification approaches 1: The paper examined the average singular value of each layer's Jacobian Ji=∂zi+1/∂ziJ^i = \partial z^{i+1} / \partial z^i (a value representing how much the signal is stretched or shrunk when passing through the layer). For a Tanh network, it was about 0.5 with the earlier initialization and about 0.8 with Xavier initialization.
  • Backpropagated gradients do not shrink toward the input side: With the earlier initialization, gradients became smaller the further back they went toward the input-side layers, but this trend was not seen with Xavier initialization (Figure 7 of the paper).
  • Activations do not saturate layer by layer: In Tanh networks with the earlier initialization, activations stuck at ±1\pm 1 (saturated) one layer after another starting from layer 1 as training proceeded. Xavier initialization suppressed this phenomenon (Figures 3 and 10).

As an analogy, in a game of telephone where each person speaks a little more quietly, the message barely reaches the tenth person. Xavier initialization is a way of making each person speak "as loudly as they were spoken to", so that the voice carries both on the way out (forward pass) and on the way back (backward pass).

According to Eq. (14) of the paper, if widths are equal, the variance of the weight gradients is nearly the same across layers even with the earlier initialization. What shrinks is the gradient with respect to the activations propagated back through the layers. The paper observes these two separately and shows that as training proceeds, the magnitude of the weight gradients also varies across layers with the earlier initialization (Figure 9).

Experimental results

These are the results of Table 1 in the paper: test error (%, lower is better) of fully connected networks with 5 hidden layers (1000 units each). "N" denotes Xavier initialization, and entries without it use the earlier initialization U[−1/n, 1/n]U[-1/\sqrt{n},\, 1/\sqrt{n}]. The learning rate was chosen on validation data for each model.

Activation function and initializationShapeset-3×2MNISTCIFAR-10Small-ImageNet
Sigmoid, earlier82.612.2157.2870.66
Tanh, earlier27.151.7655.970.58
Tanh, Xavier15.601.6452.9268.57
Softsign, earlier16.271.6455.7869.14
Softsign, Xavier16.061.7253.868.13
  • Large effect for Tanh: With Xavier initialization, Tanh's error dropped on all four datasets. In particular, on Shapeset-3×2, a synthetic dataset for recognizing shapes, it fell from 27.15% to 15.60%.
  • Softsign is less sensitive to initialization: Softsign saturates more gently than Tanh, so even with the earlier initialization its results were close to Tanh with Xavier. The paper says Softsign is more robust to initialization.
  • Sigmoid is unsuitable: Because Sigmoid's output mean is not 0, the top hidden layer quickly saturated at 0 and training slowed down. The paper concludes that Sigmoid should be avoided when training from small random weights.

Small-ImageNet is a dataset of 37×37 grayscale images in 10 classes built from ImageNet.

Practical caveats

Xavier initialization assumes the activation function is linear (slope 1) near 0. ReLU sets all negative inputs to 0, so this assumption fails and the variance roughly halves at each layer. For ReLU and its relatives, use He initialization, which doubles the variance.

Keep the following points in mind as well.

  • PyTorch's default initialization is not Xavier: nn.Linear and nn.Conv2d draw weights by default from a uniform distribution over ±1/nin\pm 1/\sqrt{n_{in}}. This has the same form as the paper's "earlier initialization", with variance 1/(3nin)1/(3 n_{in}). To use Xavier initialization, initialize explicitly with nn.init.xavier_uniform_ or a similar function.
  • gain is a factor not in the paper: PyTorch's xavier_uniform_(w, gain=1.0) widens the interval by a factor of gain. nn.init.calculate_gain("tanh") returns 5/3, a value PyTorch recommends to compensate for the shrinking caused by Tanh. The paper's Eq. (16) corresponds to gain=1.0.
  • For convolutional layers, multiply by the receptive field size: For convolution weights (output channels × input channels × k×kk \times k), PyTorch computes ninn_{in} as "input channels × k2k^2" and noutn_{out} as "output channels × k2k^2".
  • Mind the orientation of the weight shape: PyTorch counts ninn_{in} and noutn_{out} assuming the nn.Linear weight shape [number of outputs, number of inputs]. When initializing a weight you keep in the x @ w form ([number of inputs, number of outputs]), pass w.T. Xavier only uses the sum nin+noutn_{in}+n_{out}, so the result is the same, but for He initialization and others the result changes.
  • It applies only right after initialization: The derivation holds only right after initialization, when weights and activations are independent and in the linear regime. As training proceeds these assumptions break, so the paper also examines behavior during training by observation.

Comparison with other initializations

The table lines up Xavier initialization with initializations it is often compared with, from the same angles.

InitializationWeight varianceWhat it preservesIntended activation functionPyTorch function
Earlier uniform distribution (same form as PyTorch's default)1/(3nin)1/(3 n_{in})Nothing in particular—Default for nn.Linear etc.
LeCun initialization1/nin1/n_{in}Forward-pass varianceNearly linear functions (e.g., stretched Tanh)nn.init.kaiming_normal_(w, nonlinearity="linear")
Xavier initialization2/(nin+nout)2/(n_{in}+n_{out})Both forward and backward (a compromise)Nearly linear functions (Tanh, Softsign, etc.)nn.init.xavier_uniform_, xavier_normal_
He initialization2/nin2/n_{in}Forward-pass variance (compensating for ReLU)ReLU and its relativesnn.init.kaiming_normal_
Orthogonal initializationOrthogonal matrix (all singular values 1)Signal magnitude in every directionLinear, or Tanh with an adjusted gainnn.init.orthogonal_

When input and output widths are equal, Xavier initialization has the same variance 1/n1/n as LeCun initialization. The difference appears when widths change from layer to layer.

Rough guidelines for choosing:

  • Use Xavier initialization with Tanh or Softsign: Even for layers whose widths change, neither the forward nor the backward pass drifts far.
  • Use He initialization with ReLU, GELU, and the like: With Xavier initialization the variance halves at each layer, and the signal vanishes in deep networks.
  • With normalization such as batch normalization, the difference is small: Normalization re-equalizes each layer's output scale, so differences in initialization have less effect on training.

PyTorch example

Show code
python
import torch
import torch.nn as nn

# initialize the weights of fully connected and conv layers with Xavier initialization (Eq. (16) of the paper, uniform)
def init_xavier(module: nn.Module) -> None:
    if isinstance(module, (nn.Linear, nn.Conv2d)):
        # gain=1.0 matches the paper; for Tanh, PyTorch recommends calculate_gain("tanh") = 5/3
        nn.init.xavier_uniform_(module.weight, gain=1.0)
        if module.bias is not None:
            nn.init.zeros_(module.bias)  # biases are 0, as in the paper


model = nn.Sequential(
    nn.Linear(784, 1000), nn.Tanh(),
    nn.Linear(1000, 1000), nn.Tanh(),
    nn.Linear(1000, 10),
)
model.apply(init_xavier)

# check the uniform bound a = sqrt(6 / (n_in + n_out))
layer = model[0]
fan_out, fan_in = layer.weight.shape  # nn.Linear weights are [num outputs, num inputs]
a = (6.0 / (fan_in + fan_out)) ** 0.5
print(f"bound ±{a:.4f}, actual max {layer.weight.abs().max().item():.4f}")


# compare how activation variance changes per layer in a 10-layer Tanh network
def activation_variances(init_fn, depth=10, width=1000):
    torch.manual_seed(0)
    x = torch.randn(512, width)
    variances = []
    for _ in range(depth):
        layer = nn.Linear(width, width, bias=False)
        init_fn(layer.weight)
        x = torch.tanh(layer(x))
        variances.append(x.var().item())
    return variances


def old_uniform(w):
    # Eq. (1) of the paper: U[-1/sqrt(n), 1/sqrt(n)] (same form as PyTorch's nn.Linear default)
    n = w.shape[1]
    nn.init.uniform_(w, -1 / n ** 0.5, 1 / n ** 0.5)


with torch.no_grad():
    xavier_var = activation_variances(nn.init.xavier_uniform_)
    old_var = activation_variances(old_uniform)

# Xavier shrinks only slowly, while the earlier initialization shrinks sharply at each layer
print("Xavier :", [f"{v:.2g}" for v in xavier_var])
print("Earlier:", [f"{v:.2g}" for v in old_var])

FAQ

Q. Should xavier_uniform_ or xavier_normal_ be used?
A.

Both give the same weight variance, 2/(n_in + n_out). The paper uses the uniform distribution (xavier_uniform_). Differences due to the shape of the distribution are often small as long as the variance matches, so when in doubt, the uniform distribution as in the paper is fine.

Q. Are Xavier initialization and Glorot initialization different things?
A.

They are the same. The difference is only whether it is named after the first name or the surname of its proposer, Xavier Glorot. PyTorch provides it as xavier_uniform_ and xavier_normal_.

Q. How should biases be initialized?
A.

As in the paper, setting them to 0 is common. The derivation of Xavier initialization only determines the weight variance; even with zero biases, the weights are random, so each unit's output differs and training proceeds.

References

  1. X. Glorot and Y. Bengio, "Understanding the difficulty of training deep feedforward neural networks," AISTATS, 2010.
  2. K. He, X. Zhang, S. Ren, and J. Sun, "Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification," ICCV, 2015.
  3. PyTorch Documentation, "torch.nn.init."
  4. PyTorch Documentation, "torch.nn.Linear."