4.4 Numerical Stability and Initialization
In Section 4.2, initializing our one-hidden-layer MLP with weights caused a sluggish first epoch, yet the network recovered and reached accuracy. What happens if we stack ten hidden layers of width with that same initialization? Ten epochs later, the loss has not budged from and accuracy sits at random guessing. Conversely, if we initialize the weights with , activations and gradients come out astronomically large, and a single SGD update throws the weights so far that the next forward pass overflows to inf and NaN.
As we saw in Section 4.3, forward activations and backward gradients pass through a product of weight and slope matrices across a -layer network. Unless each layer preserves the signal variance, keeping its multiplicative factor near , signals either vanish exponentially to zero or explode exponentially to infinity. In this section, we quantify per-layer variance propagation, derive Xavier and He initialization, verify them on a 10-layer MLP on Fashion-MNIST, and prove why initial weights must be random to break permutation symmetry among hidden units.
4.4.1 Vanishing and Exploding Gradients#
4.4.1.1 A Product over Layers#
In a -layer MLP with hidden layers and of width , the backward recurrence from Section 4.3 propagates activation gradients one layer down via
Unrolling (4.4.1) from the top hidden layer down to layer expresses the gradient at layer as a product of matrix--slope factors:
For a single example with upstream gradient row and downstream gradient row across a layer of width whose weights are drawn i.i.d. with mean and variance , each coordinate has expected square (treating weights, slopes, and upstream gradients as approximately independent at initialization)
Across layers, the gradient's mean square is multiplied by . For symmetric pre-activations and ReLU, is half the time, so and the per-layer multiplier is . At width :
- With : the multiplier is , which after hops shrinks the gradient mean square by vanishing gradients.
- With : the multiplier is , which after hops inflates the gradient mean square by exploding gradients.
- With sigmoid activations (, so ): even if , every layer shrinks the gradient mean square by at least a factor of ((Bengio et al., 1994)).
Let us verify these three predictions directly on a 10-layer, width-256 network at initialization using moments:
def moments(phi, dphi, scale, depth=10, width=256, n=256):
"""Mean squares of the activations and of their gradients, per layer."""
Ws = [scale * torch.randn(width, width) for _ in range(depth)]
H, Zs, acts = torch.randn(n, width), [], []
for W in Ws: # forward pass, keeping the pre-activations
Zs.append(H @ W)
H = phi(Zs[-1])
acts.append(float((H ** 2).mean()))
G, grads = torch.randn(n, width), [] # dL/dH at the top layer
for W, Z in zip(reversed(Ws), reversed(Zs)): # backward pass
grads.insert(0, float((G ** 2).mean()))
G = (G * dphi(Z)) @ W.T # dL/dH one layer down
return acts, grads
relu = (torch.relu, lambda Z: (Z > 0).float())
sigmoid = (torch.sigmoid, lambda Z: torch.sigmoid(Z) * (1 - torch.sigmoid(Z)))Let us compare three setups: ReLU with (as in Section 4.2), ReLU with , and sigmoid with (so , isolating pure activation attenuation).
runs = {'ReLU, N(0, 0.01²)': moments(*relu, 0.01),
'ReLU, N(0, 1)': moments(*relu, 1.0),
'sigmoid, N(0, 1/256)': moments(*sigmoid, 1 / 16)}
for name, (acts, grads) in runs.items():
print(f'{name}: gradient mean square at layer 1: {grads[0]:.1e}')
d2l.plot(list(range(1, 11)), [grads for acts, grads in runs.values()],
'layer', 'mean square of gradient', legend=list(runs),
yscale='log', figsize=(4.5, 3))ReLU, N(0, 0.01²): gradient mean square at layer 1: 8.5e-18
ReLU, N(0, 1): gradient mean square at layer 1: 8.2e+18
sigmoid, N(0, 1/256): gradient mean square at layer 1: 5.5e-12
On a logarithmic vertical axis, all three curves are straight lines whose slopes match our analytical multiplier (4.4.3) (, , and at layer 1).
4.4.2 Parameter Initialization#
4.4.2.1 Xavier Initialization#
How do we choose the initial weight variance so that every layer's multiplier equals ? Consider a linear layer with inputs (the layer's fan-in) and outputs (its fan-out), where weights are i.i.d. with mean and variance and inputs are uncorrelated with mean and variance . In the forward pass, and
Preserving forward variance across the layer requires . By (4.4.3) with unit slope, preserving backward gradient variance requires . When , Xavier initialization (or Glorot initialization, (Glorot and Bengio, 2010)) averages the two fan counts:
drawing weights either from or from the variance-matched uniform interval . Xavier initialization is the standard choice for linear and zero-centered unit-slope activations such as .
4.4.2.2 He Initialization#
For ReLU layers, zeroing out the negative half of a symmetric zero-mean pre-activation cuts its mean square in half: . Because holds for zero-mean independent weights even when the inputs have positive mean, the activation mean square evolves across a ReLU layer as
Keeping constant across depth therefore requires doubling the variance:
This is He initialization (or Kaiming initialization, (He et al., 2015)), the default for ReLU networks (note that standard framework layers often default to , , or Xavier unless He is requested explicitly).
4.4.2.3 Activations, Gradients, and Training across Depth#
Let us first compare , Xavier (), and He () across our 10-layer synthetic ReLU probe moments(*relu, ...):
runs = {'N(0, 0.01²)': moments(*relu, 0.01),
'Xavier': moments(*relu, (1 / 256) ** 0.5),
'He': moments(*relu, (2 / 256) ** 0.5)}
for name, (acts, grads) in runs.items():
print(f'{name}: activations at layer 10: {acts[-1]:.1e}, '
f'gradient at layer 1: {grads[0]:.1e}')
d2l.plot(list(range(1, 11)), [acts for acts, grads in runs.values()],
'layer', 'mean square of activations', legend=list(runs),
yscale='log', figsize=(4.5, 3))N(0, 0.01²): activations at layer 10: 1.2e-19, gradient at layer 1: 1.2e-17
Xavier: activations at layer 10: 7.4e-04, gradient at layer 1: 1.9e-03
He: activations at layer 10: 5.7e-01, gradient at layer 1: 8.3e-01
Notice how crushes layer-10 activations to and Xavier halves the activation mean square at every ReLU layer ( by layer 10), whereas He initialization keeps both activations and gradients near . To see how this variance propagation governs real training, we now define a 10-hidden-layer ReLU classifier DeepMLP parameterized by a per-layer standard-deviation rule std(n_in, n_out):
class DeepMLP(d2l.Classifier):
"""A deep MLP whose weights have the standard deviation std(n_in, n_out)."""
def __init__(self, std, lr, depth=10, width=256):
super().__init__()
self.save_hyperparameters(ignore=['std'])
sizes = [784] + [width] * depth + [10]
layers = [nn.Flatten()]
for n_in, n_out in zip(sizes[:-1], sizes[1:]):
layer = nn.Linear(n_in, n_out)
nn.init.normal_(layer.weight, std=std(n_in, n_out))
nn.init.zeros_(layer.bias)
layers += [layer, nn.ReLU()]
self.net = nn.Sequential(*layers[:-1]) # No ReLU after the logitsAll three runs share the exact same architecture and hyperparameters,
varying only std(n_in, n_out). Let us compare their training curves and
final validation accuracies.
inits = {'N(0, 0.01²)': lambda n_in, n_out: 0.01,
'Xavier': lambda n_in, n_out: (2 / (n_in + n_out)) ** 0.5,
'He': lambda n_in, n_out: (2 / n_in) ** 0.5}
data = d2l.FashionMNIST(batch_size=256)
losses = {}
for name, std in inits.items():
trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
trainer.board.display = False
trainer.fit(DeepMLP(std, lr=0.05), data)
losses[name] = trainer.history['train_loss']
print(f'{name}: validation accuracy {trainer.history["val_acc"][-1]:.2f}')
d2l.plot(list(range(1, 11)), list(losses.values()), 'epoch', 'training loss',
legend=list(losses), figsize=(4.5, 3))N(0, 0.01²): validation accuracy 0.10
Xavier: validation accuracy 0.84
He: validation accuracy 0.87
Look at how closely the 10-epoch training curves follow our variance analysis:
- Under , layer-10 activations () and layer-1 gradients () vanish completely, leaving the training loss frozen at and validation accuracy at .
- Under Xavier, losing a factor of per ReLU layer shrinks signals by , causing a slower first epoch before training recovers to above accuracy.
- Under He initialization, both activations and gradients stay near order across all 10 layers and training drops smoothly from the very first epoch.
Initialization is not the whole answer to depth, though. The variance argument describes the network at step only: once SGD has moved the weights, nothing keeps the per-layer factor of (4.4.3) near . Networks with dozens or hundreds of layers therefore rely on mechanisms that act throughout training. Normalization layers (Section 7.3) rescale the activations at every step, residual connections (Section 7.4) give signals and gradients a path around each layer, and gradient clipping (Section 8.4) caps the occasional exploding gradient. A good initialization gets training started. These mechanisms keep the signals scaled afterwards.
4.4.3 Symmetry among Hidden Units#
Why must initial weights be random rather than setting every entry of to the deterministic constant ? Because hidden units within a layer are permutation-symmetric: if all columns of start identical (and all rows of start identical), then every hidden unit computes the same forward activation, receives the same backward gradient, and takes the same SGD update step forever, collapsing a 256-unit layer into a single effective neuron. Let us verify on a 16-unit layer that constant He-scaled weights give identical gradient columns (0.00 difference between units), whereas random He-scaled weights give every unit a distinct gradient direction:
def hidden_grad(W1, W2, X, y):
"""Gradient of the squared loss with respect to the hidden weights."""
W1 = W1.clone().requires_grad_(True)
L = ((torch.relu(X @ W1) @ W2 - y) ** 2).mean() / 2
L.backward()
return W1.grad
d, h = 20, 16
X, y = torch.randn(64, d), torch.randn(64, 1)
c, c_out = (2 / d) ** 0.5, (1 / h) ** 0.5
inits = {'constant': (torch.full((d, h), c), torch.full((h, 1), c_out)),
'random': (c * torch.randn(d, h), c_out * torch.randn(h, 1))}
for name, (W1, W2) in inits.items():
G = hidden_grad(W1, W2, X, y)
print(f'{name}: largest difference between two hidden units '
f'{float((G - G[:, :1]).abs().max()):.2f}')constant: largest difference between two hidden units 0.00
random: largest difference between two hidden units 0.16
4.4.4 Summary#
Across a -layer MLP of width and initial weight variance , each layer multiplies activation and gradient mean squares by roughly , causing signals to vanish or explode exponentially with depth unless that factor stays close to . Xavier initialization sets to balance forward and backward variance in linear and layers, while He initialization doubles the variance to to offset ReLU zeroing out its negative half-line, allowing deep ReLU stacks to train cleanly from the first epoch. Because hidden units within a layer are permutation-symmetric, weights must also be drawn independently at random rather than set to a constant; otherwise every unit receives identical gradients and updates throughout training. Beyond step , deeper architectures pair variance-preserving initialization with normalization layers and residual connections to keep signals well scaled as weights evolve.
4.4.5 Exercises#
-
Spectral norm bounds. For a single example, written as a column vector, the step (4.4.1) multiplies the gradient above layer by the matrix , where places the entries of a vector on the diagonal of an otherwise zero matrix, so the gradient in (4.4.2) is a product of such matrices times the gradient at the top. The spectral norm (the largest singular value) is submultiplicative: .
- Prove submultiplicativity from the definition .
- Use it to bound the norm of the gradient in terms of the norms of the factors. Which condition on these norms keeps the bound from growing geometrically with depth?
- This bound is only an upper bound. Explain why the condition of the previous part rules out exploding gradients but not vanishing ones, and give two matrices that satisfy the condition with equality but whose product has spectral norm strictly smaller than one.
-
Other symmetries. Permuting the hidden units is not the only change of parameters that leaves the function of an MLP unchanged. Consider a one-hidden-layer MLP in which hidden unit has incoming weights , bias , and outgoing weights .
- Prove that for . Use this identity to show that replacing by leaves the function of a ReLU network unchanged.
- Find a transformation of the parameters of a single hidden unit that leaves the function of a network unchanged.
- Identical hidden units are a fixed point of the permutation, and gradient descent started at that fixed point stays there. Find the parameters of a unit that the transformation of the previous part leaves unchanged. Then show that if all weights and biases of a network are initialized to zero, gradient descent changes only the output bias, at every step.
Adapted from Simon Prince, Understanding Deep Learning, Problems 3.5, 4.3, and 7.15.
-
Fan-in versus averaged fans. Following He et al. (2015), consider a linear network with layers in which layer maps inputs to outputs and draws its weights with variance . By the computation of Section 4.4.2.1, layer multiplies the variance of the forward signal by and that of the backward signal by .
- Set in every layer. Show that the forward variance is preserved and that the backward variance changes by the total factor at any depth.
- Let the widths alternate as , and use Xavier initialization in every layer. Compute the factor by which one pair of layers multiplies the forward variance, and the factor after 50 such pairs.
- Which of the two rules keeps both variances within a depth-independent factor of their initial values for every sequence of widths?
-
Variance under ReLU. ● The derivation in Section 4.4.2.2 tracks the mean square rather than the variance, because the next layer's pre-activation , with inputs and independent zero-mean weights has for any mean of .
- For , compute and , and show that the variance equals rather than .
- A tempting shortcut substitutes for in the Xavier computation. Show that this shortcut prescribes instead of . Compute the factor by which each ReLU layer initialized this way actually multiplies the mean square, and the total factor over fifty layers.
-
[code] Tanh networks. ● Repeat the measurement of Section 4.4.2.3 with in place of ReLU, with Xavier initialization and fifty layers. A layer then maps the mean square of its input to , where is approximately .
- Use for small to show that . Over many layers, does the mean square stay constant, decay geometrically, or decay more slowly? Show that the mean square at layer is about for large .
- Check the prediction by plotting the measured mean square against the layer on logarithmic axes. What happens to the gradient?