Vanishing and exploding gradients
Last updated
Backpropagation multiplies one factor per layer on its way from the loss to the first layer. Twenty factors a bit smaller than 1 make a number so small the first layers never learn; twenty a bit bigger than 1 make one so big a single step wrecks the weights. This lesson measures the gradient in every layer of a deep network, shows why sigmoid makes it vanish, and caps exploding gradients with clipping.
By the end of this lesson you can
- Explain why gradients shrink or grow as they flow back through many layers
- Measure the gradient's size in each layer of a PyTorch model
- Say why sigmoid makes gradients vanish and ReLU doesn't
- Cap exploding gradients with clip_grad_norm_
Gradients multiplied through many layers
Lesson 6.4 found the gradient for layer from the one above it:
In words: take the gradient of the layer above, send it back through that layer's weights, and multiply each unit's share by the slope of its activation. Every layer does this once, so the gradient that reaches layer 1 of a 20-layer network has been multiplied by 19 weight matrices and 19 activation slopes.
Multiply 19 numbers together and the result depends hugely on whether they're a little below or a little above 1:
Too small, and the gradient vanishes: the first layers get updates so tiny they never change. Too big, and it explodes: one step throws the weights so far that the loss jumps to nan. A shallow network with 2 or 3 layers hardly notices either. A deep one has to be built so that each layer's factor stays close to 1, and lessons 7.5 to 7.9 are the tricks that do it.
Sigmoid saturation
The activation's slope is one of the factors, and lesson 6.2 showed sigmoid's:
In words: the slope is largest at , where and the slope is . Anywhere else it's smaller, and for large , where sigmoid flattens out (it saturates), it's close to 0.
So every sigmoid layer multiplies the gradient by at most a quarter. Nineteen of them, even in the best case:
ReLU's slope is 1 wherever the unit is on, and 0 where it's off. It doesn't shrink the gradient it passes on, which is the main reason ReLU replaced sigmoid inside deep networks. Sigmoid is still the right choice for an output that has to be a probability, where it appears once, not twenty times.
Gradient norms by layer
You can measure this. After loss.backward(), each layer's weight.grad holds its gradient, and .norm() gives its size: the square root of the sum of the squares, the length of the gradient as one long vector. This script builds a 20-layer network twice, once with sigmoid and once with ReLU, does one backward pass on 256 digits, and prints every layer's gradient size:
"""Gradient size in each layer of a 20-layer network: sigmoid against ReLU, one backward pass.""" import torch from sklearn.datasets import load_digits from torch import nn X, y = load_digits(return_X_y=True) X, y = torch.tensor(X / 16, dtype=torch.float32), torch.tensor(y) def deep(act, depth=20, width=32): layers = [nn.Linear(64, width), act()] for _ in range(depth - 2): layers += [nn.Linear(width, width), act()] return nn.Sequential(*layers, nn.Linear(width, 10)) for name, act in (("sigmoid", nn.Sigmoid), ("relu", nn.ReLU)): torch.manual_seed(0) model = deep(act) loss = nn.functional.cross_entropy(model(X[:256]), y[:256]) loss.backward() norms = [m.weight.grad.norm().item() for m in model if isinstance(m, nn.Linear)] print(f"{name}: gradient size of the weights in layers 1 to {len(norms)}") print(" " + " ".join(f"{n:.1e}" for n in norms))
(.venv) $ python grad_norms.py sigmoid: gradient size of the weights in layers 1 to 20 4.4e-17 9.0e-17 4.5e-16 3.2e-15 2.5e-14 2.3e-13 1.5e-12 1.2e-11 7.4e-11 5.8e-10 4.2e-09 2.4e-08 2.0e-07 1.3e-06 8.5e-06 6.2e-05 4.4e-04 3.4e-03 2.2e-02 1.5e-01 relu: gradient size of the weights in layers 1 to 20 2.4e-08 1.4e-08 1.3e-08 1.1e-08 1.4e-08 6.4e-08 1.2e-07 3.2e-07 7.6e-07 3.0e-06 6.1e-06 1.6e-05 3.1e-05 7.5e-05 1.9e-04 4.4e-04 1.1e-03 2.1e-03 4.6e-03 1.2e-02
sigmoid, PyTorch's default initialisation: the last layer's gradient is 1.5 × 10⁻¹, the first layer's 4.4 × 10⁻¹⁷. That's about 3 × 10¹⁵ times smaller at the bottom.
With sigmoid, the gradient falls by about 7 times at every layer on the way down, on average: from at the last layer to at the first. That's 3 million billion times smaller. An update of that size can't change a weight at all, as step 5 shows.
ReLU is far better, but with PyTorch's default starting weights it still loses a factor of about 500,000 between the top and the bottom. The slope isn't the problem any more; the weights are. nn.Linear starts its weights small enough that each layer shrinks the signal a little, in both directions. Lesson 7.6 picks starting weights that don't.
Gradient clipping
Exploding gradients are the other failure: a steep spot on the loss landscape gives a huge gradient, the step is huge too, and the weights land somewhere awful. Gradient clipping caps the step. Put all the gradients together as one vector ; if it's longer than a limit , shrink it to length without changing its direction:
In words: a gradient shorter than is left alone; a longer one is scaled down to exactly . It still points the same way, so the step goes in the right direction, just not too far.
In PyTorch it's one line, between loss.backward() and optimizer.step(). The script trains a small network with a learning rate of 2, far too high, with and without a limit of 1:
"""Gradient clipping by norm: the same too-large learning rate, with and without clipping.""" import torch from sklearn.datasets import load_digits from torch import nn from torch.utils.data import DataLoader, TensorDataset X, y = load_digits(return_X_y=True) data = TensorDataset(torch.tensor(X / 16, dtype=torch.float32), torch.tensor(y)) for clip in (None, 1.0): torch.manual_seed(0) model = nn.Sequential(nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 10)) optimizer = torch.optim.SGD(model.parameters(), lr=2.0) biggest = 0.0 for epoch in range(5): total = 0.0 for xb, yb in DataLoader(data, batch_size=32, shuffle=True): loss = nn.functional.cross_entropy(model(xb), yb) optimizer.zero_grad() loss.backward() # returns the norm before clipping; with max_norm=inf it only measures norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=clip if clip else float("inf")) biggest = max(biggest, norm.item()) optimizer.step() total += loss.item() * len(xb) print(f"clip {str(clip):4}: loss in epoch 5 {total / len(data):.3f}, biggest gradient norm seen {biggest:.1f}")
(.venv) $ python clipping.py clip None: loss in epoch 5 2.321, biggest gradient norm seen 29.3 clip 1.0 : loss in epoch 5 0.430, biggest gradient norm seen 6.6
Without clipping, a gradient of length 29.3 at a learning rate of 2 moved the weights a distance of about 59 in one step, and the network never recovered. Its loss in epoch 5, 2.321, is no better than guessing: a uniform guess over 10 digits scores . With clipping, no step was longer than , and the same network reached 0.430.
clip_grad_norm_ returns the length before clipping, which is why the clipped run can still report 6.6. Printing it now and then is a cheap way to watch for trouble. Clipping is standard for recurrent networks (Stage 8) and transformers (Stage 10), usually with a limit of 1. It isn't a fix for a learning rate that's simply too high, though: it only stops the occasional huge step.
Wrong way: a 20-layer sigmoid network
Deeper should be at least as good as shallower: a deep network could always learn to copy a shallow one. So here are 20 sigmoid layers, trained for 10 epochs on the digits, beside the same 20 layers with ReLU and the starting weights of lesson 7.6:
"""The wrong way: a 20-layer sigmoid network trained for 10 epochs, beside the same network with ReLU.""" import torch from sklearn.datasets import load_digits from torch import nn from torch.utils.data import DataLoader, TensorDataset X, y = load_digits(return_X_y=True) data = TensorDataset(torch.tensor(X / 16, dtype=torch.float32), torch.tensor(y)) def deep(act, depth=20, width=32): layers = [nn.Linear(64, width), act()] for _ in range(depth - 2): layers += [nn.Linear(width, width), act()] return nn.Sequential(*layers, nn.Linear(width, 10)) for name, act in (("sigmoid", nn.Sigmoid), ("relu", nn.ReLU)): torch.manual_seed(0) model = deep(act) if name == "relu": # He init keeps ReLU signals the same size (lesson 7.6) for m in model: if isinstance(m, nn.Linear): nn.init.kaiming_normal_(m.weight, nonlinearity="relu") nn.init.zeros_(m.bias) optimizer = torch.optim.SGD(model.parameters(), lr=0.003, momentum=0.9) first = model[0].weight.detach().clone() for epoch in range(10): for xb, yb in DataLoader(data, batch_size=32, shuffle=True): loss = nn.functional.cross_entropy(model(xb), yb) optimizer.zero_grad() loss.backward() optimizer.step() with torch.no_grad(): accuracy = (model(data.tensors[0]).argmax(dim=1) == data.tensors[1]).float().mean().item() moved = (model[0].weight - first).abs().mean().item() print(f"{name:8} accuracy {accuracy:.3f} first layer's weights moved {moved:.1e} on average")
(.venv) $ python sigmoid20.py sigmoid accuracy 0.101 first layer's weights moved 0.0e+00 on average relu accuracy 0.900 first layer's weights moved 3.3e-02 on average
The sigmoid network scores 10.1%, the same as always answering one digit. And its first layer's weights moved by exactly 0. Not a small amount: zero. The gradient reaching them is about ; times a learning rate of 0.003, the update is around . A float32 weight near 0.1 can only change in steps of about , so adding to it gives back the same number. The first layers are frozen at their random starting values, and every layer above them is learning from random noise.
The ReLU network, with the same depth, data and optimiser, reaches 90.0%.
When a deep network won't learn at all, print the gradient norms by layer before changing anything else. A column of numbers that falls several times over at every layer is a diagnosis. The fixes: ReLU-like activations (6.2), good starting weights (7.6), normalisation (7.7) and residual connections (7.9).
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- Goodfellow, Bengio and Courville, Deep Learning: section 10.7, the challenge of long-term dependencies: repeated multiplication makes gradients vanish or explode
- Pascanu, Mikolov and Bengio, On the difficulty of training recurrent neural networks, 2013: exploding gradients, and clipping the gradient's norm
- Nielsen, Neural Networks and Deep Learning: chapter 5, why deep networks are hard to train: the vanishing gradient problem, worked through for sigmoid
- PyTorch: torch.nn.utils.clip_grad_norm_: clips the norm of all the gradients together, and returns the norm before clipping