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 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.Lineardoes by default.
The forward pass of a random network
Draw every weight of layer independently with mean and variance , set the biases to , and send in an input. What is the typical size of the pre-activations deep in the network? Each is a sum of independent terms, and the weights are independent of the incoming activations:
The weights have mean zero, so , and the terms are uncorrelated, so their variances add. Because is independent of and has mean zero, :
For an activation that is close to linear near zero (tanh with small inputs, or the identity), , and the variance is multiplied by at every layer. Keeping it constant gives LeCun's scale (LeCun, Bottou, Orr & Müller, 1998):
For ReLU and a pre-activation symmetric about zero, exactly half the mass is zeroed, so . The per-layer factor is , and keeping it at one gives He initialization (He, Zhang, Ren & Sun, 2015):
With any other scale the variance changes by a fixed factor per layer, and after layers by : geometric growth or decay. Only survives depth.
The recursion uses the second moment , not the variance . For ReLU with these are and about . What goes wrong if you use the variance?
- Nothing: the mean of cancels when it is multiplied by zero-mean weights, so either works
- You would choose instead of , and the signal's mean square would grow by about 47% per layer
- You would choose a smaller scale and the signal would vanish
- The variance is undefined for ReLU
Show the answer
B. You would choose instead of , and the signal's mean square would grow by about 47% per layer
because : the mean of still contributes. Matching gives , a per-layer factor in the variance, which compounds to explosion over depth.
A 20-layer ReLU network uses LeCun's scale , which suits tanh, and zero biases. The input has mean square . 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 and the RMS . 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: . 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:
Forward stability asks for and backward stability for ; they agree only when the layer is square. Glorot and Bengio (2010) took the compromise , 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 , whose product over the network telescopes to instead of compounding with depth.
| Scheme | Designed for | In PyTorch | |
|---|---|---|---|
| LeCun (1998) | tanh-like units near zero; SELU | kaiming_normal_(w, nonlinearity='linear') | |
| Glorot / Xavier (2010) | ; uniform bound | tanh, sigmoid, linear | xavier_uniform_(w), xavier_normal_(w) |
| He / Kaiming (2015) | (or ) | ReLU and its relatives | kaiming_normal_(w, nonlinearity='relu') |
| Orthogonal | with | linear and tanh networks, RNNs | orthogonal_(w, gain=g) |
calculate_gain supplies the multiplier for each activation: for linear and sigmoid, for tanh, for ReLU, for leaky ReLU with slope .A tanh layer maps inputs to outputs. What is the bound of Glorot's uniform initialization ?
Show the answer
C.
A uniform variable on has variance . Setting gives .
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 , so every weight gradient 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.
Which of these initializations of a tanh MLP leaves training able to make the hidden units of a layer different from one another?
- All weights and biases zero
- Every weight equal to , every bias zero
- Weights random with the Xavier scale, biases zero
- Every weight equal to , 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 , 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 , 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 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 gives the bound : weights uniform on , with variance , 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 per layer; modern architectures get away with it because normalization layers and residual connections reset the scale. For a plain deep network, initialize explicitly:
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 1With 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 , 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 set by the random biases, where the activations carry almost no information about the input.
Key takeaways
- With zero-mean independent weights, : the signal changes by a fixed factor per layer, and only a factor of one survives depth.
- LeCun () suits tanh-like units, He () suits ReLU because , and Glorot's 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.Lineardefault has variance ; initialize deep plain networks explicitly withnn.init.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A ReLU layer has inputs. What standard deviation does He initialization (fan-in, Gaussian) give its weights?
Show the answer
D.
He's variance is , so the standard deviation is .
In a deep ReLU network every layer has width and weight variance . By what factor is the variance of the backpropagated error multiplied at each layer?
- , because only about half the units pass gradient
- , because backpropagation is linear
Show the answer
B. , because only about half the units pass gradient
, and . He's makes the factor exactly one in both directions.
What variance does PyTorch's default nn.Linear initialization give the weights of a layer with inputs?
- : uniform on
- , He initialization
- , Xavier initialization
- , LeCun initialization
Show the answer
A. : uniform on
kaiming_uniform_(weight, a=math.sqrt(5)) yields the bound , and a uniform variable on has variance . That is a third of LeCun's scale, fine when normalization follows, too small for a deep plain ReLU stack.
Why can orthogonal initialization do something Gaussian initialization at the same average scale cannot, in a deep linear network?
- It makes the weights sparse, which speeds up training
- It preserves the norm of every vector exactly at every layer, so the product of many layers neither stretches nor crushes any direction
- It makes the loss convex
- 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 , 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
- Learning Dynamics of Deep Linear Networks · Exact solutions, stage-like learning and the implicit pull toward low rank.
- Exploding Gradients & Clipping · Cliffs in the loss, relaxed smoothness and why clipping speeds training.
- Criticality & Finite-Width Effects · Tuning initialization to criticality, and why the depth-to-width ratio governs finite networks.
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).