Vanishing and exploding gradients

In a network with many layers, the early layers sometimes barely learn, or the loss suddenly turns into NaN in the middle of training. Both come from the same cause. Change the number of layers and the value each layer multiplies by, and watch the gradient of each layer shrink or grow.

Short answer. Backpropagation walks back from the output to the input and multiplies the gradient by each layer's ratio. If the ratio is below 1, it gets multiplied once per layer and heads to 0 (vanishing: the early layers do not learn). If it is above 1, it keeps growing (exploding: the loss jumps or turns NaN). 0.25 multiplied ten times is about 0.00000095. So the fix is to keep the ratio near 1: ReLU, good initialization, normalization layers, residual connections. Gradients that already blew up are cut down with gradient clipping.

Each bar is the size of the gradient one layer's weights get. The vertical axis is a log scale, so one grid step is 100 times. The thick line is 1 (unchanged). Blue bars are below 1 and orange bars are above 1. This is a small toy model: the gradient above the last layer is set to 1, and every layer multiplies by the same value. In a real network the ratio is different at every layer, and it is a matrix, not one number, so it stretches some directions more than others.

Try this. ① At the start (10 layers, × 0.25) the first layer gets 9.54 × 10⁻⁷ and the last layer gets 0.25. The first layer is updated 2.62 × 10⁵ times (262,144 times) less. ② Set the ratio to 1 and every bar sits on the line at 1. ③ Set it to 1.5 and the first layer gets 57.7. Raise the layers to 20 and it gets 3.33 × 10³. ④ With 20 layers, 0.9 gives the first layer 0.122 and 1.1 gives 6.73. Being off from 1 by only 10% turns into a factor of several over many layers.

Definitions

The text below explains with experiments and pictures. The textbook definitions are as follows. L is the loss, and a gradient is the partial derivative of L with respect to a weight or a layer's value.

chain rule in backpropagation
Take an n-layer network where only one number passes through each layer: hk=σ(zk),zk=wkhk−1,h0=x. The chain rule gives the gradient of the first weight as below. Each time we go back through one layer, that layer's partial derivative (the "ratio" in the text) is multiplied in once.

∂L∂w1=∂L∂hn(∏k=2n∂hk∂hk−1)∂h1∂w1

∂hk∂hk−1=σ′(zk)wk

vanishing gradient
The size of the gradient from backpropagation shrinks exponentially with the number of layers as we move away from the output (toward the input), and gets close to 0. It happens when each layer's partial derivative in the product above is smaller than 1 in size, and the weights of those layers barely get updated.
exploding gradient
The size of the gradient from backpropagation grows exponentially with the number of layers as we move toward the input. It happens when each layer's partial derivative in the product above is larger than 1 in size. One update step becomes too large, and the loss jumps or turns into inf or NaN.
residual connection
A connection that adds a layer's input, unchanged, to that layer's output. If F is what the layer computes, the partial derivative of one layer becomes 1 + F′, so it stays near 1 even when F′ is close to 0.

hk=hk−1+F(hk−1)

∂hk∂hk−1=1+F′(hk−1)

gradient clipping
If the norm of g, the vector made by joining the gradients of all parameters, is larger than a chosen value c, shrink g so its norm becomes c while keeping its direction. If the norm is c or less, leave g as it is.

𝐠←min(1,c‖𝐠‖)𝐠

1. What it is: a gradient multiplied on the way back

A gradient says "if I nudge this weight a little, how much does the loss change". Training changes every weight by its gradient times the learning rate (gradient descent). So if a layer's gradient is close to 0, that layer hardly changes.

For a network with many layers, the gradients come from backpropagation. It starts at the output and walks back one layer at a time. At each layer it multiplies by "if the input of this layer changes a little, how many times as much does its output change". This page calls that the layer's ratio. The earlier the layer, the more ratios get multiplied in.

2. How the formula is built

Take a very narrow network with 10 layers. One number passes through each layer: h₁ = σ(w₁ × x), h₂ = σ(w₂ × h₁), …, h₁₀ = σ(w₁₀ × h₉). σ is the sigmoid, and z is the value that goes into σ (for example z₂ = w₂ × h₁). All weights are 1 and the input x is 1 too. Let us find the gradient ∂L/∂w₁ that the very first weight w₁ gets.

Press "Next" to go one step at a time. A piece is added to the formula above (the orange background marks the new piece), bars appear from right to left, and the reason shows up below. The bars use the largest possible σ′ (0.25), so they are the best case. In practice z is not 0, σ′ is smaller, and the gradient shrinks even faster.

  1. Start: ∂L/∂h₁₀ = 1. Set the gradient for the last value to 1. Its real value just multiplies every gradient below by the same amount.
  2. One layer back: × ∂h₁₀/∂h₉. This is the chain rule. This layer's ratio is σ′(z₁₀) × w₁₀. The slope of the sigmoid is σ′(z) = σ(z) × (1 − σ(z)), and it is largest at z = 0: 0.5 × 0.5 = 0.25. So with w₁₀ = 1 the ratio is at most 0.25.
  3. Once per layer: × … × ∂h₂/∂h₁. By h₁ you have multiplied nine times: 0.25⁹ ≈ 0.0000038.
  4. Done: ∂L/∂w₁ = ∂L/∂h₁₀ × ∂h₁₀/∂h₉ × … × ∂h₂/∂h₁ × ∂h₁/∂w₁. The last piece ∂h₁/∂w₁ = σ′(z₁) × x is also at most 0.25. Ten factors in all: 0.25¹⁰ ≈ 0.00000095, about one millionth.

Try this. Press "Next" three times to reach ④. The w₁ bar is 9.54 × 10⁻⁷. That is 2.62 × 10⁵ times smaller than the 0.25 that w₁₀ in the last layer gets. In the first experiment at its start (10 layers, × 0.25), the layer 1 bar shows the same 9.54 × 10⁻⁷.

3. By hand: multiplying 0.25 and 1.5 over and over

0.25 is 1/4, so 0.25¹⁰ = 1 ÷ 4¹⁰ = 1 ÷ 1,048,576. Multiply 1.5 the same ten times instead and you pass 57.

Times multipliedby 0.25by 1.5
10.251.5
20.06252.25
30.0156253.375
50.00097656257.59375
100.00000095367…57.665…

If it were addition, ten times would give only 2.5 and 15. Because it is multiplication, the number of layers ends up in the exponent.

4. Properties to know

PropertyIn plain wordsIn the experiment
Multiplied, not addedEvery extra layer is one more multiplication, so the number of layers sits in the exponentRaise the number of layers
Worse for early layersThe farther from the output, the more ratios are multiplied in. The last layer can be fine while the first one is brokenBars get longer toward the left
Only near 1 is safeBeing a little off, like 0.9 or 1.1, adds up to a big gap over many layersTry this ④
Ratio = slope of the activation × weightThere are two places to fix: the activation function (ReLU) and the size of the weights (initialization)Section 2, step ②
Vanishing is quiet, exploding is loudVanishing raises no error, training just gets slow, so it is easy to miss. Exploding shows up right away as a jumping loss or NaNSection 5

5. Symptoms and how to check

Do not guess. Print the size of the gradient for each layer. If the input side numbers are several digits smaller than the output side, suspect vanishing. If they suddenly grow by several digits, suspect exploding.

# PyTorch: after backward(), print the size (norm) of each layer's gradient
loss.backward()
for name, p in model.named_parameters():
    if p.grad is not None:
        print(name, p.grad.norm().item())

6. How to fix it

before (6, 8), length 10 × 0.5 after (3, 4), length 5 (−4, 2) unchanged circle radius = set value 5
Clipping by length. The made-up gradient (6, 8) has length √(6² + 8²) = 10, longer than the set value 5. So it is multiplied by 5 ÷ 10 = 0.5 and becomes (3, 4). Its length is √(3² + 4²) = 5 and its direction is unchanged. The arrow (−4, 2) inside the circle has length √20 ≈ 4.47, shorter than 5, so it is left alone. Faded dashed = before clipping, green = after, blue = inside the circle so unchanged, dashed orange circle = the set value.

7. When to use what

OptionGoodBadUse it when
ReLU family activationsSlope of 1 on the positive side, so the activation does not shrink the gradient. Cheap to computeSlope of 0 on the negative side, so a neuron that only gets negative inputs stops learning (dying ReLU)The default for hidden layers, unless you have a reason to use sigmoid or tanh there
Good initialization (Xavier, He)From the first step, sizes do not change much from layer to layer. Costs nothingOnly sets the start. As the weights change during training, things can drift againAlways. Pick it to match the activation (He for ReLU, Xavier for sigmoid and tanh)
Normalization layers (batch, layer)Reset the scale of the values at every layer. Larger learning rates become easierMore computation and parameters. Batch norm depends on the batch sizeDeep convolutional networks (batch norm), transformers (layer norm)
Residual connectionsThe gradient passes through the addition path times 1, so very deep networks can trainThe two values you add must have the same shape. You have to change the network's layoutNetworks with many layers, such as deep convolutional networks like ResNet, and transformers
Gradient clippingEven when gradients explode, one step cannot get too big. One line of codeDoes nothing for vanishing. You have to pick the clipping valueTraining where gradients sometimes spike, like RNNs and transformers. When the loss suddenly jumps or turns NaN

You usually do not pick just one. Keep the activation and initialization matched at all times, add residual connections and normalization layers when there are many layers, and add clipping if the gradients spike during training.

Where you meet it

Frequently asked questions

Does ReLU make vanishing gradients go away?

It removes the part that comes from the activation function, because the slope of ReLU is 1 for positive inputs. But a layer's ratio is the activation's slope times the weight, so small weights still shrink the gradient. A neuron that only ever gets negative inputs has a slope of 0 and stops learning. That is why ReLU is used together with good initialization, normalization layers and residual connections.

The loss became NaN. What should I check first?

Print the size of the gradient for each layer. If the gradients jumped, lower the learning rate and add gradient clipping. If the gradients look normal and you still get NaN, look for log(0), division by zero, or NaN values in the input data.

Can gradient clipping fix vanishing gradients too?

No. Gradient clipping only shrinks gradients that are larger than a set size. It never makes a small gradient bigger. Vanishing gradients are handled with ReLU, good initialization, normalization layers and residual connections.

Words

Words used hereWhat textbooks call it
gradient heading to 0vanishing gradient
gradient getting hugeexploding gradient
a layer's ratiolocal gradient. With many values, the Jacobian matrix
multiplying on the way backchain rule, backpropagation
flat ends of a functionsaturation
number of values coming in, going outfan-in, fan-out
Xavier initialization, He initializationGlorot initialization, Kaiming initialization
path that adds the input backresidual connection, skip connection
cutting the gradient downgradient clipping. By total length: clipping by norm
total length of the gradientnorm
not a number, infinityNaN, inf
a ReLU stuck on negative inputsdying ReLU

Sources

← Activation functionsWeight initialization →