Deep learning in practice · lesson 5 of 13
Parts in this lesson
Am.weight.grad.norm()how big one layer's gradient is
Btorch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)shrink the whole gradient if it's longer than 1, between backward() and step()
Cnn.init.kaiming_normal_(m.weight, nonlinearity="relu")a better start for ReLU layers, lesson 7.6's subject

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 l from the one above it:

δ[l]=(W[l+1]⊤δ[l+1])⊙g′(z[l])

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:

0.519≈0.0000019,1.519≈2217

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:

σ′(z)=σ(z)(1−σ(z))≤14

In words: the slope is largest at z=0, where σ(z)=12 and the slope is 12⋅12=14. Anywhere else it's smaller, and for large |z|, 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:

(14)19≈3.6×10−12

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))
Terminal, in ml-local/7-5
(.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
Gradient thermometerhow big each layer's gradient is, after one backward pass
10-1810-1510-1210-910-610-3100output end ↑layer 14.4e-17layer 29.0e-17layer 34.5e-16layer 43.2e-15layer 52.5e-14layer 62.3e-13layer 71.5e-12layer 81.2e-11layer 97.4e-11layer 105.8e-10layer 114.2e-9layer 122.4e-8layer 132.0e-7layer 141.3e-6layer 158.5e-6layer 166.2e-5layer 174.4e-4layer 183.4e-3layer 192.2e-2layer 201.5e-1

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 1.5×10−1 at the last layer to 4.4×10−17 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 η∇L is huge too, and the weights land somewhere awful. Gradient clipping caps the step. Put all the gradients together as one vector g; if it's longer than a limit c, shrink it to length c without changing its direction:

g←g⋅min⁡(1,c‖g‖)

In words: a gradient shorter than c is left alone; a longer one is scaled down to exactly c. 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}")
Terminal, in ml-local/7-5
(.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 ln⁡10≈2.303. With clipping, no step was longer than 2×1=2, 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")
Terminal, in ml-local/7-5
(.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 10−17; times a learning rate of 0.003, the update is around 10−19. A float32 weight near 0.1 can only change in steps of about 10−8, so adding 10−19 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

Why does the gradient in a deep sigmoid network shrink on its way to the first layer?
clip_grad_norm_ with max_norm = 1 receives a gradient of length 5. What does it do?
A deep network’s accuracy stays at 10%. You print the gradient norms by layer: 10⁻², 10⁻³, …, 10⁻¹⁷ from the top down. What’s the first thing to try?

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.

All sources for Simple Machine Learning