Vanishing and Exploding Gradients
Backpropagation multiplies one Jacobian per layer. In a deep network that is a long product of matrices, and long products tend to shrink to zero or blow up exponentially. When gradients vanish, the early layers stop learning; when they explode, training diverges. This lesson shows the mechanism and previews the fixes that made deep learning work.
A product of Jacobians
For , the gradient reaching layer 1 is
Each factor scales a vector by roughly its typical gain . After layers the gradient is scaled by about : with and that is ; with it is . Only is safe.
import numpy as np
rng = np.random.default_rng(0)
n, L = 256, 50
for scale in (0.8, 1.0, 1.2):
g = rng.normal(size=n); g /= np.linalg.norm(g)
for _ in range(L):
W = rng.normal(0, scale / np.sqrt(n), (n, n)) # gain about `scale` per layer
g = W.T @ g
print(f"weight scale {scale}: gradient norm after {L} linear layers = {np.linalg.norm(g):.2e}")weight scale 0.8: gradient norm after 50 linear layers = 1.10e-05
weight scale 1.0: gradient norm after 50 linear layers = 7.75e-01
weight scale 1.2: gradient norm after 50 linear layers = 6.81e+03
The activation's share
Saturating activations add a factor below 1 at every layer: the sigmoid's derivative is at most (Activations). ReLU contributes 0 or 1, and with He initialization (variance ) the factor 2 exactly compensates for the half of units that are off.
import numpy as np
rng = np.random.default_rng(1)
n, L = 256, 30
def grad_norms(act, dact, std):
x = rng.normal(size=n); Ws, As = [], []
for _ in range(L):
W = rng.normal(0, std, (n, n)); a = W @ x; x = act(a); Ws.append(W); As.append(a)
g = np.ones(n) / np.sqrt(n); norms = []
for W, a in zip(reversed(Ws), reversed(As)):
g = W.T @ (g * dact(a)); norms.append(np.linalg.norm(g))
return norms[0], norms[-1]
sig = lambda a: 1 / (1 + np.exp(-a))
for name, act, dact, std in [
("sigmoid, std 1/sqrt(n)", sig, lambda a: sig(a) * (1 - sig(a)), 1 / np.sqrt(n)),
("tanh, std 1/sqrt(n) ", np.tanh, lambda a: 1 - np.tanh(a)**2, 1 / np.sqrt(n)),
("relu, std sqrt(2/n) ", lambda a: np.maximum(0, a), lambda a: (a > 0) * 1.0, np.sqrt(2 / n))]:
top, bottom = grad_norms(act, dact, std)
print(f"{name}: gradient norm at last layer {top:.2e}, at first layer {bottom:.2e}")sigmoid, std 1/sqrt(n): gradient norm at last layer 2.52e-01, at first layer 1.80e-19
tanh, std 1/sqrt(n) : gradient norm at last layer 9.36e-01, at first layer 9.76e-02
relu, std sqrt(2/n) : gradient norm at last layer 1.17e+00, at first layer 5.44e+00
Recurrent networks: the extreme case
An RNN applies the same matrix at every time step, so the product is raised to the sequence length. Its behavior is governed by the largest eigenvalue magnitude (spectral radius) : below 1 the gradient vanishes exponentially in the time gap, above 1 it explodes. This is why plain RNNs struggle to learn dependencies longer than about 10 to 20 steps (Backpropagation Through Time).
The toolbox of fixes
| Problem | Fix | Lesson |
|---|---|---|
| gain at initialization | variance-preserving initialization (Xavier, He) | Initialization |
| saturation | ReLU-family activations | Activations |
| drift of activation scale during training | batch and layer normalization | Batch Normalization |
| long products | residual connections (, Jacobian ) | Residual Connections |
| long products in time | gated recurrent units (LSTM, GRU), attention | LSTM and GRU |
| occasional explosions | gradient clipping | Schedules and Clipping |
In software
- Monitor per-layer gradient norms (
p.grad.norm()per parameter) during training; a layer whose gradients are orders of magnitude smaller than others is not learning. - A loss that suddenly becomes
nanusually means an explosion; clipping and a lower learning rate are the first remedies. torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)is standard in transformer training.
Go further: Vanishing and Exploding Gradients in the Deep Learning course measures the effect in NumPy and PyTorch and ranks the fixes by how often you need them.
Exercises
Exercise 1: Exponential scaling
A 100-layer network has a per-layer gradient gain of . By what factor is the gradient at layer 1 smaller than at layer 100?
Answer
About (a factor of about 170 smaller).
Solution
.
Exercise 2: Sigmoid depth bound
Ignoring the weights, what is the largest possible factor a gradient can be multiplied by passing through 20 sigmoid activations?
Answer
.
Solution
Each sigmoid derivative is at most , so the product is at most .
Exercise 3: Spectral radius (code)
For , compute for with . The spectral radius is ; what happens at first?
Answer
The norm first grows to about 4, then decays to zero.
Solution
Non-normal matrices can amplify transiently even when : , and eventually wins.
import numpy as np
W = np.array([[0.5, 4.0], [0.0, 0.5]])
for t in (1, 2, 5, 20, 50):
print(t, f"{np.linalg.norm(np.linalg.matrix_power(W.T, t) @ np.array([1.0, 0.0])):.3e}")1 4.031e+00
2 4.008e+00
5 1.250e+00
20 1.526e-04
50 3.553e-13
Test yourself
Why do gradients vanish or explode in deep networks?
- Because of the loss function
- Backprop multiplies one Jacobian per layer, and long products shrink or grow exponentially
- Because of the batch size
- Because weights are random
In a plain RNN, gradients over long time gaps are governed mainly by…
- the vocabulary size
- the spectral radius of the recurrent weight matrix
- the output layer
- the learning rate schedule
Which of these does NOT address vanishing gradients?
- Residual connections
- ReLU activations
- He initialization
- Increasing the number of sigmoid layers