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: . 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.
- 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.
- 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.
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.
- Vanishing gradient: the ratios are below 1, so the gradient of the early layers gets close to 0. The early layers barely learn.
- Exploding gradient: the ratios are above 1, so the gradient of the early layers gets very large. One step throws the weights far away and the loss jumps. When a number grows past what the computer can store, it becomes infinity (inf), and math like inf − inf gives NaN (not a number).
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.
- 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. - 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. - Once per layer:
× … × ∂h₂/∂h₁. By h₁ you have multiplied nine times: 0.25⁹ ≈ 0.0000038. - Done:
∂L/∂w₁ = ∂L/∂h₁₀ × ∂h₁₀/∂h₉ × … × ∂h₂/∂h₁ × ∂h₁/∂w₁. The last piece∂h₁/∂w₁ = σ′(z₁) × xis 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 multiplied | by 0.25 | by 1.5 |
|---|---|---|
| 1 | 0.25 | 1.5 |
| 2 | 0.0625 | 2.25 |
| 3 | 0.015625 | 3.375 |
| 5 | 0.0009765625 | 7.59375 |
| 10 | 0.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
| Property | In plain words | In the experiment |
|---|---|---|
| Multiplied, not added | Every extra layer is one more multiplication, so the number of layers sits in the exponent | Raise the number of layers |
| Worse for early layers | The farther from the output, the more ratios are multiplied in. The last layer can be fine while the first one is broken | Bars get longer toward the left |
| Only near 1 is safe | Being a little off, like 0.9 or 1.1, adds up to a big gap over many layers | Try this ④ |
| Ratio = slope of the activation × weight | There are two places to fix: the activation function (ReLU) and the size of the weights (initialization) | Section 2, step ② |
| Vanishing is quiet, exploding is loud | Vanishing raises no error, training just gets slow, so it is easy to miss. Exploding shows up right away as a jumping loss or NaN | Section 5 |
5. Symptoms and how to check
- Vanishing: the weights of the input side layers barely change during training. The loss hardly goes down from the start, or goes down very slowly.
- Exploding: the loss suddenly jumps or becomes inf or NaN. Once NaN gets into a weight, every later calculation is NaN too and it does not come back.
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
- ReLU. Makes one half of the ratio, the slope of the activation, equal to 1. The slope of ReLU is 1 for positive inputs and 0 for negative ones. The sigmoid's slope is at most 0.25, and far from 0, for example at z = 5, it flattens to about 0.0066. tanh has a slope of at most 1 (at z = 0), but it also gets close to 0 far from 0.
- Good initialization. Sets the other half of the ratio, the size of the weights. The more values flow into a layer (fan_in), the smaller the starting weights, so values and gradients keep about the same size as they pass through layers. Use Xavier initialization (variance
2 ÷ (fan_in + fan_out)) for sigmoid and tanh, and He initialization (variance2 ÷ fan_in) for ReLU. - Normalization layers. Bring the values between layers back to about mean 0 and variance 1 (normalization and standardization). This breaks the chain of growing or shrinking in the middle, and keeps values from being pushed into the flat ends of functions like the sigmoid.
- Residual connections. Add the layer's input straight to its output:
h = h_prev + F(h_prev). The ratio becomes1 + F′, so even when the ratio through F is close to 0, the total stays near 1. The gradient passes through the addition path times 1. The "add" in the transformer's "add and norm" is this. - Gradient clipping. If the total length (norm) of the gradient is above a set value, scale it down to that value. The direction stays the same (see the figure below). It helps with exploding, not with vanishing. In PyTorch, put one line
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)betweenloss.backward()andoptimizer.step()(1.0 is an example value).
√(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
| Option | Good | Bad | Use it when |
|---|---|---|---|
| ReLU family activations | Slope of 1 on the positive side, so the activation does not shrink the gradient. Cheap to compute | Slope 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 nothing | Only sets the start. As the weights change during training, things can drift again | Always. 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 easier | More computation and parameters. Batch norm depends on the batch size | Deep convolutional networks (batch norm), transformers (layer norm) |
| Residual connections | The gradient passes through the addition path times 1, so very deep networks can train | The two values you add must have the same shape. You have to change the network's layout | Networks with many layers, such as deep convolutional networks like ResNet, and transformers |
| Gradient clipping | Even when gradients explode, one step cannot get too big. One line of code | Does nothing for vanishing. You have to pick the clipping value | Training 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
- When you design a deep network. Choose the activation, initialization, residual connections and normalization layers together.
- Recurrent neural networks (RNNs). The same weights are multiplied again at every time step, so the same thing happens over long sentences. LSTM and GRU are designs made to reduce it, and gradient clipping is often used with them.
- Transformers. Every layer has a residual connection and layer normalization (transformer).
- When training looks wrong. If the loss does not go down or turns NaN, print the gradient size per layer first (section 5).
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 here | What textbooks call it |
|---|---|
| gradient heading to 0 | vanishing gradient |
| gradient getting huge | exploding gradient |
| a layer's ratio | local gradient. With many values, the Jacobian matrix |
| multiplying on the way back | chain rule, backpropagation |
| flat ends of a function | saturation |
| number of values coming in, going out | fan-in, fan-out |
| Xavier initialization, He initialization | Glorot initialization, Kaiming initialization |
| path that adds the input back | residual connection, skip connection |
| cutting the gradient down | gradient clipping. By total length: clipping by norm |
| total length of the gradient | norm |
| not a number, infinity | NaN, inf |
| a ReLU stuck on negative inputs | dying ReLU |
Sources
- Xavier Glorot, Yoshua Bengio, Understanding the difficulty of training deep feedforward neural networks, AISTATS (PMLR volume 9). How gradients differ by layer in deep sigmoid networks, and Xavier initialization.
- Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun, Delving Deep into Rectifiers, arXiv:1502.01852. Initialization for ReLU networks (He initialization).
- Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun, Deep Residual Learning for Image Recognition, arXiv:1512.03385. Residual connections.
- Razvan Pascanu, Tomas Mikolov, Yoshua Bengio, On the difficulty of training recurrent neural networks, arXiv:1211.5063. Vanishing and exploding gradients in RNNs, and clipping the gradient by its norm.