Simple Algorithm
Deep Learning · Representation · 22 min

Initialization & Vanishing Gradients

Xavier and He: choosing weight scales so signals survive many layers.

Before its first gradient step, a deep network is a random function, and its gradients are products of random matrices. Make the weights slightly too small and the signal fades away within a few dozen layers; slightly too large and it explodes. A one-line variance calculation picks the scale that keeps it alive, and it is the difference between a 30-layer ReLU network that trains and one that stalls.

What you’ll learn

  • Derive the forward variance recursion Var⁡(z(ℓ))=nℓ−1σw2 E[ϕ(z(ℓ−1))2]\Var(z^{(\ell)}) = n_{\ell-1}\sigma_w^2\,\E[\phi(z^{(\ell-1)})^2] and obtain the LeCun, Glorot (Xavier) and He scales from it.
  • Derive the backward recursion, explain vanishing and exploding gradients as a per-layer factor raised to the depth, and explain Glorot's compromise between fan-in and fan-out.
  • Explain why all-zero or identical weights fail while zero biases are fine, and why orthogonal initialization preserves norms exactly in linear networks.
  • Initialize networks in PyTorch, and state what nn.Linear does by default.

The forward pass of a random network

Draw every weight of layer ℓ\ell independently with mean 00 and variance σw2\sigma_w^2, set the biases to 00, and send in an input. What is the typical size of the pre-activations zi(ℓ)=∑jWij(ℓ)hj(ℓ−1)z^{(\ell)}_i = \sum_jW^{(\ell)}_{ij}h^{(\ell-1)}_j deep in the network? Each is a sum of nℓ−1n_{\ell-1} independent terms, and the weights are independent of the incoming activations:

DerivationThe variance recursion
  1. Var⁡(z(ℓ))=nℓ−1 σw2 E[ϕ(z(ℓ−1))2]\Var\big(z^{(\ell)}\big) = n_{\ell-1}\,\sigma_w^2\,\E\big[\phi(z^{(\ell-1)})^2\big]

    The weights have mean zero, so E[zi(ℓ)]=0\E[z^{(\ell)}_i] = 0, and the terms are uncorrelated, so their variances add. Because WijW_{ij} is independent of hjh_j and has mean zero, Var⁡(Wijhj)=E[Wij2] E[hj2]\Var(W_{ij}h_j) = \E[W_{ij}^2]\,\E[h_j^2]:

  2. σw2=1nin\sigma_w^2 = \frac{1}{n_{\text{in}}}

    For an activation that is close to linear near zero (tanh with small inputs, or the identity), E[ϕ(z)2]≈Var⁡(z)\E[\phi(z)^2]\approx\Var(z), and the variance is multiplied by nℓ−1σw2n_{\ell-1}\sigma_w^2 at every layer. Keeping it constant gives LeCun's scale (LeCun, Bottou, Orr & Müller, 1998):

  3. σw2=2nin\sigma_w^2 = \frac{2}{n_{\text{in}}}

    For ReLU and a pre-activation symmetric about zero, exactly half the mass is zeroed, so E[ReLU⁡(z)2]=12Var⁡(z)\E[\operatorname{ReLU}(z)^2] = \tfrac12\Var(z). The per-layer factor is nℓ−1σw2/2n_{\ell-1}\sigma_w^2/2, and keeping it at one gives He initialization (He, Zhang, Ren & Sun, 2015):

  4. Var⁡(z(L))=c L−1 Var⁡(z(1)),c=n σw2 E[ϕ(z)2]Var⁡(z)\Var\big(z^{(L)}\big) = c^{\,L-1}\,\Var\big(z^{(1)}\big),\qquad c = n\,\sigma_w^2\,\frac{\E[\phi(z)^2]}{\Var(z)}

    With any other scale the variance changes by a fixed factor cc per layer, and after LL layers by cLc^L: geometric growth or decay. Only c=1c = 1 survives depth.

Check your understanding

The recursion uses the second moment E[ϕ(z)2]\E[\phi(z)^2], not the variance Var⁡(ϕ(z))\Var(\phi(z)). For ReLU with z∼N(0,1)z\sim\mathcal N(0, 1) these are 0.50.5 and about 0.340.34. What goes wrong if you use the variance?

  1. Nothing: the mean of ϕ(z)\phi(z) cancels when it is multiplied by zero-mean weights, so either works
  2. You would choose σw2≈2.9/n\sigma_w^2\approx2.9/n instead of 2/n2/n, and the signal's mean square would grow by about 47% per layer
  3. You would choose a smaller scale and the signal would vanish
  4. The variance is undefined for ReLU
Show the answer

B. You would choose σw2≈2.9/n\sigma_w^2\approx2.9/n instead of 2/n2/n, and the signal's mean square would grow by about 47% per layer

Var⁡(Wijhj)=E[Wij2]E[hj2]\Var(W_{ij}h_j) = \E[W_{ij}^2]\E[h_j^2] because E[Wij]=0\E[W_{ij}] = 0: the mean of hjh_j still contributes. Matching nσw2×0.34=1n\sigma_w^2\times0.34 = 1 gives σw2≈2.93/n\sigma_w^2\approx2.93/n, a per-layer factor 2.93/2≈1.472.93/2\approx1.47 in the variance, which compounds to explosion over depth.

Predict before you look

A 20-layer ReLU network uses LeCun's scale σw2=1/n\sigma_w^2 = 1/n, which suits tanh, and zero biases. The input has mean square 11. By what factor is the RMS of the 20th layer's output (after its ReLU) smaller than the input's?

Show the answer

1024 ×

At this scale each matrix multiply preserves the mean square and each ReLU halves it, so after 20 layers the mean square is 2−202^{-20} and the RMS 2−10=1/10242^{-10} = 1/1024. A thousandfold loss from a factor of 2 per layer: that factor is exactly what He initialization puts back.

The backward pass, and Glorot’s compromise

Gradients travel the other way through the transposed weights: δ(ℓ)=(W(ℓ+1)⊤δ(ℓ+1))⊙ϕ′(z(ℓ))\boldsymbol\delta^{(\ell)} = \big(W^{(\ell+1)\top}\boldsymbol\delta^{(\ell+1)}\big)\odot\phi'(\mathbf z^{(\ell)}). The same calculation, treating the backward weights as independent of the forward activations (the standard approximation for wide networks), gives a recursion with the fan-out and the activation's slope:

Var⁡(δ(ℓ))=nℓ+1 σw2 E[ϕ′(z(ℓ))2] Var⁡(δ(ℓ+1))\Var\big(\delta^{(\ell)}\big) = n_{\ell+1}\,\sigma_w^2\,\E\big[\phi'(z^{(\ell)})^2\big]\,\Var\big(\delta^{(\ell+1)}\big)
For tanh near zero ϕ′≈1\phi'\approx1; for ReLU E[ϕ′(z)2]=12\E[\phi'(z)^2] = \tfrac12. A per-layer factor below one makes gradients vanish toward the input, above one makes them explode. The weight gradient ∂ℓ/∂W(ℓ)=δ(ℓ)h(ℓ−1)⊤\partial\ell/\partial W^{(\ell)} = \boldsymbol\delta^{(\ell)}\mathbf h^{(\ell-1)\top} needs both signals healthy.

Forward stability asks for ninσw2=1n_{\text{in}}\sigma_w^2 = 1 and backward stability for noutσw2=1n_{\text{out}}\sigma_w^2 = 1; they agree only when the layer is square. Glorot and Bengio (2010) took the compromise σw2=2/(nin+nout)\sigma_w^2 = 2/(n_{\text{in}} + n_{\text{out}}), usually drawn uniformly, and called it normalized initialization (now "Xavier"). Their experiments also showed why the older practice failed: with the logistic sigmoid and small random weights, the top hidden layer saturated early in training. He et al. noted that for ReLU either the fan-in or the fan-out condition suffices: if every layer uses the fan-in rule, the backward factors are nℓ/nℓ−1n_\ell/n_{\ell-1}, whose product over the network telescopes to nL/n1n_L/n_1 instead of compounding with depth.

SchemeVar⁡(Wij)\Var(W_{ij})Designed forIn PyTorch
LeCun (1998)1/nin1/n_{\text{in}}tanh-like units near zero; SELUkaiming_normal_(w, nonlinearity='linear')
Glorot / Xavier (2010)2/(nin+nout)2/(n_{\text{in}} + n_{\text{out}}); uniform bound 6/(nin+nout)\sqrt{6/(n_{\text{in}} + n_{\text{out}})}tanh, sigmoid, linearxavier_uniform_(w), xavier_normal_(w)
He / Kaiming (2015)2/nin2/n_{\text{in}} (or 2/nout2/n_{\text{out}})ReLU and its relativeskaiming_normal_(w, nonlinearity='relu')
OrthogonalW=g QW = g\,Q with Q⊤Q=IQ^\top Q = Ilinear and tanh networks, RNNsorthogonal_(w, gain=g)
PyTorch's calculate_gain supplies the multiplier for each activation: 11 for linear and sigmoid, 5/35/3 for tanh, 2\sqrt2 for ReLU, 2/(1+a2)\sqrt{2/(1 + a^2)} for leaky ReLU with slope aa.
Check your understanding

A tanh layer maps nin=256n_{\text{in}} = 256 inputs to nout=512n_{\text{out}} = 512 outputs. What is the bound aa of Glorot's uniform initialization Wij∼U(−a,a)W_{ij}\sim U(-a, a)?

  1. a=2/768≈0.051a = \sqrt{2/768}\approx0.051
  2. a=1/256=0.0625a = \sqrt{1/256} = 0.0625
  3. a=6/768≈0.088a = \sqrt{6/768}\approx0.088
  4. a=6/256≈0.153a = \sqrt{6/256}\approx0.153
Show the answer

C. a=6/768≈0.088a = \sqrt{6/768}\approx0.088

A uniform variable on (−a,a)(-a, a) has variance a2/3a^2/3. Setting a2/3=2/(256+512)a^2/3 = 2/(256 + 512) gives a=6/768≈0.088a = \sqrt{6/768}\approx0.088.

Breaking symmetry

Why random at all? Set every weight of the network to the same value, zero or otherwise, and every bias to zero. Then the units of a hidden layer all compute the same function of the input and pass it on through the same outgoing weights, so by the backward-pass formulas they receive identical gradients, and gradient descent keeps them identical forever: a layer of 512 units behaves like a layer of one. All-zero weights are worse still: with tanh every hidden activation is 00, so every weight gradient δh⊤\boldsymbol\delta\mathbf h^\top vanishes, the output layer's included, and nothing but the output bias learns. Any difference between the units breaks the tie (even random biases alone eventually would), but random weights give every unit its own feature from the first step, which is why they are the standard way to break the symmetry.

Check your understanding

Which of these initializations of a tanh MLP leaves training able to make the hidden units of a layer different from one another?

  1. All weights and biases zero
  2. Every weight equal to 0.010.01, every bias zero
  3. Weights random with the Xavier scale, biases zero
  4. Every weight equal to 0.010.01, every bias zero, trained with small noisy mini-batches so that the noise can push the units apart
Show the answer

C. Weights random with the Xavier scale, biases zero

Random weights give each unit its own function and its own gradient, so zero biases are harmless. With every weight equal and every bias zero, the units of a layer compute the same function and pass it on through the same weights, so they receive identical gradients on every batch and stay copies of one another forever.

Beyond averages: orthogonal weights

The variance recursion tracks an average over random weights. A single deep linear network computes WL⋯W1xW_L\cdots W_1\mathbf x, and even when each Gaussian factor preserves the mean square on average, the product does not treat all directions alike: some are stretched and others crushed, and the spread of the product's singular values grows with depth, the faster the narrower the layers. An orthogonal matrix has every singular value equal to 11, so a product of orthogonal matrices preserves the norm of every vector, forward and backward. A network whose input–output Jacobian has all singular values near 11 is said to have dynamical isometry.

Saxe, McClelland and Ganguli (2014) showed that this matters for training, not just for the first forward pass: in deep linear networks, random orthogonal initialization (like layer-wise pretraining) gives learning times that stay finite as depth grows, while scaled random Gaussian initialization does not. With nonlinearities the picture depends on the activation: Pennington, Schoenholz and Ganguli (2017) found that ReLU networks cannot achieve dynamical isometry, while sigmoid-shaped networks (tanh among them) can, but only with orthogonal weights and a carefully tuned scale. Orthogonal initialization is also a standard choice for recurrent weight matrices, which are multiplied by themselves at every time step.

Initialization in practice

PyTorch's nn.Linear does not use He or Xavier by default. Its reset_parameters calls kaiming_uniform_(weight, a=math.sqrt(5)), whose gain 2/(1+5)=1/3\sqrt{2/(1 + 5)} = \sqrt{1/3} gives the bound 3⋅1/3/nin=1/nin\sqrt3\cdot\sqrt{1/3}/\sqrt{n_{\text{in}}} = 1/\sqrt{n_{\text{in}}}: weights uniform on (−1/nin,1/nin)(-1/\sqrt{n_{\text{in}}}, 1/\sqrt{n_{\text{in}}}), with variance 1/(3nin)1/(3n_{\text{in}}), a third of LeCun's. Biases are uniform on the same interval. In a plain ReLU stack this scale multiplies the mean square of the activations by about 1/61/6 per layer; modern architectures get away with it because normalization layers and residual connections reset the scale. For a plain deep network, initialize explicitly:

python
import math
import torch
import torch.nn as nn

layer = nn.Linear(512, 256)        # default: U(-1/√512, 1/√512), variance 1/(3·512)
print(layer.weight.std().item(), 1 / math.sqrt(3 * 512))   # both ≈ 0.0255

def init_relu_mlp(m: nn.Module) -> None:
    if isinstance(m, nn.Linear):
        nn.init.kaiming_normal_(m.weight, mode='fan_in', nonlinearity='relu')  # 2/fan_in
        nn.init.zeros_(m.bias)

mlp = nn.Sequential(*[nn.Sequential(nn.Linear(512, 512), nn.ReLU()) for _ in range(30)])
mlp.apply(init_relu_mlp)           # visits every submodule

h = torch.randn(1024, 512)         # inputs with unit mean square
with torch.no_grad():
    for i, block in enumerate(mlp):
        h = block(h)
        if (i + 1) % 10 == 0:
            print(i + 1, h.pow(2).mean().item())   # mean square stays of order 1

With He initialization each matrix multiply doubles the mean square and each ReLU halves it, so it stays of order one through all 30 layers instead of shrinking geometrically, although at this width a single random draw can still end a factor of two or more away from 11, a finite-width effect. Skip mlp.apply and keep the default instead: the mean square falls about sixfold per layer for the first few layers, then settles on a floor of about 4×10−44\times10^{-4} set by the random biases, where the activations carry almost no information about the input.

Key takeaways

  • With zero-mean independent weights, Var⁡(z(ℓ))=nℓ−1σw2 E[ϕ(z(ℓ−1))2]\Var(z^{(\ell)}) = n_{\ell-1}\sigma_w^2\,\E[\phi(z^{(\ell-1)})^2]: the signal changes by a fixed factor per layer, and only a factor of one survives depth.
  • LeCun (1/nin1/n_{\text{in}}) suits tanh-like units, He (2/nin2/n_{\text{in}}) suits ReLU because E[ReLU⁡(z)2]=12Var⁡(z)\E[\operatorname{ReLU}(z)^2] = \tfrac12\Var(z), and Glorot's 2/(nin+nout)2/(n_{\text{in}} + n_{\text{out}}) balances the forward and backward passes.
  • Random weights break the symmetry between units (units with identical weights get identical gradients and stay copies forever); zero biases are fine, and zero-initialized final layers in residual branches are a deliberate exception.
  • Orthogonal initialization preserves every direction's norm in linear networks (dynamical isometry); the variance calculation is an infinite-width average, and finite width adds depth-to-width fluctuations.
  • PyTorch's nn.Linear default has variance 1/(3nin)1/(3n_{\text{in}}); initialize deep plain networks explicitly with nn.init.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A ReLU layer has nin=512n_{\text{in}} = 512 inputs. What standard deviation does He initialization (fan-in, Gaussian) give its weights?

  1. 1/512≈0.0021/512\approx0.002
  2. 1/512≈0.044\sqrt{1/512}\approx0.044
  3. 2/512≈0.00392/512\approx0.0039
  4. 2/512=0.0625\sqrt{2/512} = 0.0625
Show the answer

D. 2/512=0.0625\sqrt{2/512} = 0.0625

He's variance is 2/nin=2/5122/n_{\text{in}} = 2/512, so the standard deviation is 2/512=1/16=0.0625\sqrt{2/512} = 1/16 = 0.0625.

Question 2

In a deep ReLU network every layer has width nn and weight variance σw2\sigma_w^2. By what factor is the variance of the backpropagated error multiplied at each layer?

  1. nσw2n\sigma_w^2
  2. nσw2/2n\sigma_w^2/2, because only about half the units pass gradient
  3. 2nσw22n\sigma_w^2
  4. 11, because backpropagation is linear
Show the answer

B. nσw2/2n\sigma_w^2/2, because only about half the units pass gradient

Var⁡(δ(ℓ))=n σw2 E[ϕ′(z)2] Var⁡(δ(ℓ+1))\Var(\delta^{(\ell)}) = n\,\sigma_w^2\,\E[\phi'(z)^2]\,\Var(\delta^{(\ell+1)}), and E[ReLU⁡′(z)2]=P(z>0)=12\E[\operatorname{ReLU}'(z)^2] = P(z > 0) = \tfrac12. He's σw2=2/n\sigma_w^2 = 2/n makes the factor exactly one in both directions.

Question 3

What variance does PyTorch's default nn.Linear initialization give the weights of a layer with ninn_{\text{in}} inputs?

  1. 1/(3nin)1/(3n_{\text{in}}): uniform on (−1/nin,1/nin)(-1/\sqrt{n_{\text{in}}}, 1/\sqrt{n_{\text{in}}})
  2. 2/nin2/n_{\text{in}}, He initialization
  3. 2/(nin+nout)2/(n_{\text{in}} + n_{\text{out}}), Xavier initialization
  4. 1/nin1/n_{\text{in}}, LeCun initialization
Show the answer

A. 1/(3nin)1/(3n_{\text{in}}): uniform on (−1/nin,1/nin)(-1/\sqrt{n_{\text{in}}}, 1/\sqrt{n_{\text{in}}})

kaiming_uniform_(weight, a=math.sqrt(5)) yields the bound 1/nin1/\sqrt{n_{\text{in}}}, and a uniform variable on (−a,a)(-a, a) has variance a2/3a^2/3. That is a third of LeCun's scale, fine when normalization follows, too small for a deep plain ReLU stack.

Question 4

Why can orthogonal initialization do something Gaussian initialization at the same average scale cannot, in a deep linear network?

  1. It makes the weights sparse, which speeds up training
  2. It preserves the norm of every vector exactly at every layer, so the product of many layers neither stretches nor crushes any direction
  3. It makes the loss convex
  4. It gives the weights a larger variance than Gaussian initialization
Show the answer

B. It preserves the norm of every vector exactly at every layer, so the product of many layers neither stretches nor crushes any direction

All singular values of an orthogonal matrix equal 11, so the input–output Jacobian of a deep linear network stays an isometry. Gaussian factors preserve norms only on average; the spread of the product's singular values grows with depth (and with the ratio of depth to width).

Go deeper

Further reading

  • X. Glorot & Y. Bengio, "Understanding the difficulty of training deep feedforward neural networks," AISTATS (2010).
  • K. He, X. Zhang, S. Ren & J. Sun, "Delving deep into rectifiers: Surpassing human-level performance on ImageNet classification," ICCV (2015).
  • A. M. Saxe, J. L. McClelland & S. Ganguli, "Exact solutions to the nonlinear dynamics of learning in deep linear neural networks," ICLR (2014).
  • Y. LeCun, L. Bottou, G. B. Orr & K.-R. Müller, "Efficient BackProp," in Neural Networks: Tricks of the Trade (Springer, 1998).