◆ AI All-in-One

Level 3 In-Depth AI · Deep Learning

Vanishing and Exploding Gradients

In a deep network the gradient is a long product of numbers, one per layer. If they are a bit below one, it shrinks to nothing and the early layers stop learning; a bit above one, and it blows up. This is why deep networks were once untrainable, and how ReLU, good initialisation, normalisation, residual connections and clipping fixed it.

Level
●●●●● Intermediate
Reading
13 min
To learn it well
45 minutes to read, an hour to practise
↗ Plan a path here

Read first

BackpropagationActivation Functions

This leads to

LSTMs and GRUsResidual Connections
The full path from zero — 17 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Supervised, Unsupervised and Reinforcement Learning
  10. Gradient Descent
  11. Supervised Learning
  12. Linear Regression
  13. The Perceptron
  14. Logistic Regression
  15. Neural Networks
  16. Backpropagation
  17. Activation Functions
  18. Vanishing and Exploding Gradients

Read them roughly in this order. See it on the concept map →

Why it matters

Through the 1990s and most of the 2000s, neural networks with more than two or three hidden layers were almost impossible to train. Adding layers should have made networks more powerful (see Why Neural Networks Work), but in practice the extra layers just sat there, barely changing from their random starting values. The culprit was the vanishing gradient: the learning signal fades away as it travels backwards through the layers.

Its twin, the exploding gradient, does the opposite. The signal grows layer by layer until a single update throws the weights to absurd values and the loss becomes nan ("not a number").

Understanding these two problems explains a lot of modern deep-learning design: why hidden layers use ReLU instead of sigmoid, why weights start at carefully chosen sizes, why networks contain normalisation layers and skip connections, and why every large language model is trained with gradient clipping. Each was introduced, at least partly, to keep gradients at a healthy size through dozens or hundreds of layers. When you train your own networks, these are also the first things to check when the loss refuses to move or suddenly blows up.

The intuition

Remember the game of telephone, where a message is whispered down a line of people. With a few people it arrives mostly intact. With thirty, it arrives garbled or not at all. Each person loses a little, and the losses compound.

Backpropagation is a game of telephone run backwards. The error signal starts at the loss and is passed from layer to layer towards the input. At each layer it is multiplied by that layer's local slope. Multiply many numbers together and the result depends dramatically on whether they are a bit below one or a bit above one:

  • 0.950≈0.0050.9^{50} \approx 0.005. Fifty factors of 0.9 shrink the signal 200-fold.
  • 1.150≈1171.1^{50} \approx 117. Fifty factors of 1.1 grow it more than a hundredfold.
  • 0.2510≈0.0000010.25^{10} \approx 0.000001. Ten sigmoid layers, each with slope at most 0.25, shrink it a millionfold.

Only factors very close to 1 survive a long chain. Everything else vanishes or explodes.

Sigmoid layers: each multiplies the gradient by at most 0.25 loss 1 layer 5 0.25 layer 4 0.0625 layer 3 0.0156 layer 2 0.0039 layer 1 0.00098 Each layer multiplies by about 2 loss 1 layer 5 2 layer 4 4 layer 3 8 layer 2 16 layer 1 32 ReLU + good init, or residual connections: factor about 1 loss 1 layer 5 1 layer 4 1 layer 3 1 layer 2 1 layer 1 1 red numbers: size of the gradient arriving at each layer, starting from 1 at the loss
Fig. 1 How the size of the gradient changes as it travels back from the loss. With sigmoid layers each step multiplies it by at most 0.25 and it vanishes; with factors of 2 it explodes; with factors near 1 it reaches the first layer intact.

When gradients vanish, the layers near the input get almost no learning signal. They stay close to their random starting values, and the network behaves as if it were much shallower than it is. The loss falls a little, then stalls. When gradients explode, the update step is enormous. One batch can wreck everything learned so far.

Key idea The gradient reaching an early layer is a product of one factor per layer above it. To train deep networks, those factors must stay close to 1. ReLU, careful initialisation, normalisation and residual connections all exist to make that happen; clipping is the safety net for explosions.

How it works

Where the factors come from

Take a deep network where each layer computes hk=f(Wkhk−1+bk)\mathbf{h}_{k} = f(\mathbf{W}_k \mathbf{h}_{k-1} + \mathbf{b}_k) for layers k=1,…,nk = 1, \dots, n. From the Backpropagation chapter, each step of the backward pass does two things to the gradient:

  1. It multiplies by the slope of the activation function, f′(z)f'(z), element by element.
  2. It multiplies by the transposed weight matrix, Wk⊤\mathbf{W}_k^\top.

So the gradient arriving at layer 1 is roughly a product of nn slopes and nn weight matrices. To see the effect, imagine one neuron per layer with weight ww and the same slope f′f' everywhere. Then the gradient at the first layer is the gradient at the loss times

(w⋅f′)n(w \cdot f')^n

If ∣w⋅f′∣<1|w \cdot f'| < 1 the product shrinks exponentially with depth: the gradient vanishes. If ∣w⋅f′∣>1|w \cdot f'| > 1 it grows exponentially: the gradient explodes. With real matrices the picture is the same, except that ∣w∣|w| is replaced by how much the matrix stretches or shrinks vectors on average.

The two culprits: activations and weights

Saturating activations. The sigmoid's slope is at most 0.25, and much smaller when its input is far from zero (0.0066 at z=5z = 5). A neuron in its flat region is saturated and passes almost nothing back. Tanh has slope at most 1 but also saturates. With sigmoid hidden layers, even perfect weights can't stop the gradient shrinking by a factor of 4 or more per layer.

Badly sized weights. If the weights are too small, every layer shrinks both the forward signal and the backward gradient. If they are too large, every layer magnifies them. Neither failure needs a bad activation function. A purely linear deep network has the same problem.

Measuring it

You can watch this happen. The experiment below builds a 20-layer network, 64 neurons wide, pushes a batch through it, and measures the size of each layer's weight gradient, its gradient norm (the length of the gradient vector: the square root of the sum of its squared entries).

10⁻¹⁸ 10⁻¹² 10⁻⁶ 1 10⁶ 10¹² 1 5 10 15 20 layer (1 = next to the input, 20 = next to the loss) size of weight gradient (log scale) ReLU, weights 2× too big explodes ReLU + residual + LayerNorm healthy ReLU + He init healthy sigmoid vanishes ReLU, PyTorch default init vanishes
Fig. 2 Size of the weight gradient in each of 20 layers, on a log scale, for five setups. With sigmoid the first layer's gradient is about 10⁻¹⁸, seventeen orders of magnitude smaller than the last layer's. ReLU with PyTorch's default initialisation also vanishes. Weights twice too large make every gradient explode to around 10¹¹. ReLU with He initialisation, or with residual connections and LayerNorm, keeps all layers near 1.

The numbers are dramatic:

Setup Gradient at layer 1 Gradient at layer 20
Sigmoid 1.1×10−181.1 \times 10^{-18} 1.2×10−11.2 \times 10^{-1}
ReLU, PyTorch default initialisation 5.3×10−105.3 \times 10^{-10} 6.9×10−36.9 \times 10^{-3}
ReLU, weights twice the He size 2.0×10112.0 \times 10^{11} 6.3×10116.3 \times 10^{11}
ReLU, He initialisation 3.5×10−13.5 \times 10^{-1} 1.11.1
ReLU, residual connections + LayerNorm 1.41.4 1.11.1

With sigmoid, the first layer's gradient is 10−1710^{-17} times the last layer's. With any reasonable learning rate, layer 1 will not move at all. Note that the second row isn't a bug in PyTorch: its default initialisation is designed for networks that contain normalisation layers, and on a bare 20-layer ReLU stack it is too small.

Fix 1: non-saturating activations

ReLU has slope exactly 1 for every positive input. It never saturates on the positive side, so it doesn't shrink the gradients of active neurons. This single change, popularised around 2010–2012, made it possible to train networks of 8 to 20 layers directly. The price is that inactive neurons pass back nothing at all, which can lead to dead neurons. GELU and SiLU keep the same benefit with a smooth curve. See Activation Functions.

Fix 2: careful initialisation

Choose the starting weights so that each layer, on average, neither shrinks nor grows the signal. For a layer with ninn_{\text{in}} inputs, Xavier (Glorot) initialisation draws weights with variance 1/nin1/n_{\text{in}} (or a closely related average of inputs and outputs), which suits tanh. He initialisation uses variance 2/nin2/n_{\text{in}}, which suits ReLU: the factor 2 makes up for ReLU zeroing out half its inputs. In the experiment above, He initialisation alone turned a gradient of 10−1010^{-10} into one of about 0.350.35. Weight Initialization derives these numbers.

Fix 3: normalisation layers

Initialisation sets the scale only at the start. As training changes the weights, signals can drift. Normalisation layers rescale the activations inside the network so that they always have roughly zero mean and unit variance, whatever the weights do. BatchNorm (2015) did this for image networks and made much deeper ones trainable. LayerNorm and RMSNorm do it in every The Transformer. See Normalization Layers: BatchNorm and LayerNorm.

Fix 4: residual connections

The most powerful fix changes the shape of the network. A residual connection adds a layer's input directly to its output:

hk=hk−1+F(hk−1)\mathbf{h}_{k} = \mathbf{h}_{k-1} + F(\mathbf{h}_{k-1})

Here FF is the layer's usual computation. The derivative of hk\mathbf{h}_k with respect to hk−1\mathbf{h}_{k-1} is now 1+F′1 + F' instead of just F′F'. The "1" is a direct path along which the gradient flows back unchanged, however many layers there are, like an express lane past all the local stops. In the experiment, residual connections with LayerNorm kept every layer's gradient between 1.1 and 1.4. Residual connections are what allowed ResNet to reach 152 layers in 2015, and they run through every Transformer. See Residual Connections.

Fix 5: gradient clipping (for explosions)

Exploding gradients can strike even in well-designed networks: one unusual batch, or a recurrent network multiplying by the same matrix hundreds of times. Gradient clipping is a simple safety net. Before each update, compute the norm of the whole gradient. If it is larger than a threshold, scale the gradient down so its norm equals the threshold:

g←g⋅min⁡(1,τ∥g∥)\mathbf{g} \leftarrow \mathbf{g} \cdot \min\left(1, \frac{\tau}{\lVert \mathbf{g} \rVert}\right)

Here g\mathbf{g} is the gradient of all parameters stacked into one vector, ∥g∥\lVert \mathbf{g} \rVert is its norm (length), and τ\tau ("tau") is the threshold. The direction is unchanged; only an over-long step is shortened. A worked example: if τ=1\tau = 1 and the gradient is (30,40)(30, 40), its norm is 302+402=50\sqrt{30^2 + 40^2} = 50, so it is scaled by 1/501/50 to become (0.6,0.8)(0.6, 0.8), which has norm 1. A gradient of (0.3,0.4)(0.3, 0.4), with norm 0.5, is left alone.

Clipping doesn't help vanishing gradients at all, since it only ever shrinks. But it is cheap insurance, and a threshold of 1.0 is a common choice in language-model training. GPT-3, for example, was trained with the gradient norm clipped at 1.0.

Recurrent networks: the hardest case

A recurrent network applies the same weight matrix at every step of a sequence. Backpropagating through 100 time steps multiplies by that matrix 100 times. If it stretches vectors by even a little, the gradient explodes; if it shrinks them, the gradient vanishes, and the network can't learn connections between words far apart. This is why plain RNNs struggle with long-range dependencies, and why the LSTM was invented. Its cell state is updated mostly by addition rather than multiplication, an early cousin of the residual connection.

In code

The gradient-norm experiment, in PyTorch. The loss is just a stand-in (the mean of the squared outputs), since we only care how the gradient changes on its way back.

import torch
from torch import nn

def first_and_last_grad(act, he_init=False, residual=False, depth=20, width=64):
    torch.manual_seed(0)
    layers = [nn.Linear(width, width) for _ in range(depth)]
    norms = [nn.LayerNorm(width) for _ in range(depth)]
    if he_init:
        for layer in layers:
            nn.init.kaiming_normal_(layer.weight, nonlinearity="relu")
    h = torch.randn(256, width)                      # a batch of random inputs
    for layer, norm in zip(layers, norms):
        if residual:
            h = h + act(layer(norm(h)))              # skip connection + LayerNorm
        else:
            h = act(layer(h))
    h.pow(2).mean().backward()                       # a stand-in loss
    return layers[0].weight.grad.norm().item(), layers[-1].weight.grad.norm().item()

for name, kwargs in [("sigmoid", dict(act=torch.sigmoid)),
                     ("relu", dict(act=torch.relu)),
                     ("relu + He init", dict(act=torch.relu, he_init=True)),
                     ("relu + residual + LayerNorm", dict(act=torch.relu, residual=True))]:
    first, last = first_and_last_grad(**kwargs)
    print(f"{name:28s} layer 1: {first:.1e}   layer 20: {last:.1e}")

# sigmoid                      layer 1: 1.1e-18   layer 20: 1.2e-01
# relu                         layer 1: 5.3e-10   layer 20: 6.9e-03
# relu + He init               layer 1: 3.5e-01   layer 20: 1.1e+00
# relu + residual + LayerNorm  layer 1: 1.4e+00   layer 20: 1.1e+00

Gradient clipping is one line, placed between backward() and the optimizer step. It returns the norm before clipping, which is worth logging:

import torch
from torch import nn

torch.manual_seed(0)
model = nn.Linear(10, 1)
x, y = torch.randn(32, 10), torch.randn(32, 1)
loss = ((model(x) - y) ** 2).mean() * 1e4          # pretend a bad batch made the loss huge
loss.backward()

before = nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)  # returns the norm before clipping
after = torch.cat([p.grad.flatten() for p in model.parameters()]).norm()
print(f"gradient norm before clipping {before:.1f}, after {after:.3f}")

# gradient norm before clipping 13570.1, after 1.000

In a real training loop the order is: loss.backward(), then clip_grad_norm_(...), then optimizer.step().

Common pitfalls

  • Diagnosing by loss alone. A loss that falls a little and then stalls can mean vanishing gradients, a learning rate that's too low, or a bug. Log the gradient norm of each layer (or each block) for a few steps. If early layers' gradients are thousands of times smaller than late layers', you have vanishing gradients.
  • Sigmoid or tanh in deep stacks. Fine for gates and outputs; harmful in many stacked hidden layers.
  • Mixing initialisation and activation. Xavier initialisation with ReLU, or He with tanh, gives a factor per layer of about 0.5 or 2. Over 30 layers that's a factor of a billion. Match them.
  • Clipping too hard. A threshold far below the typical gradient norm clips every step, which effectively lowers the learning rate and slows training. Log the pre-clipping norm and set the threshold above its normal range.
  • Treating nan as bad luck. A nan loss is almost always an explosion: too high a learning rate, missing clipping, or a numerically unsafe operation such as the log of zero. Restarting from the same settings usually fails again.

Watch out A spike in gradient norm often comes a few steps before the loss blows up. In long training runs, plot the gradient norm next to the loss. Large language model teams watch it closely, and recurring spikes are a sign to lower the learning rate or tighten clipping.

Where it leads

A bit of history

Sepp Hochreiter analysed the vanishing gradient problem in his 1991 diploma thesis in Munich, focused on recurrent networks. In 1994, Yoshua Bengio, Patrice Simard and Paolo Frasconi showed that learning long-term dependencies with gradient descent is fundamentally difficult for the same reason. Hochreiter and Jürgen Schmidhuber answered with the LSTM in 1997.

For feedforward networks, a workaround came in 2006, when Geoffrey Hinton and colleagues trained deep belief networks one layer at a time before fine-tuning the whole stack. In 2010, Xavier Glorot and Yoshua Bengio analysed how activations and gradients behave across layers and proposed the initialisation that bears Glorot's name. ReLUs (2010–2011), He initialisation (2015), batch normalisation (2015) and residual networks (2015) followed in quick succession, and by the end of 2015 networks with over 100 layers trained reliably. Razvan Pascanu, Tomas Mikolov and Yoshua Bengio analysed exploding gradients in recurrent networks in 2013 and popularised gradient-norm clipping as the fix.

Try it

  1. In the experiment, change depth from 20 to 5 and then to 50. How does the sigmoid network's layer-1 gradient change? Is it roughly exponential in depth?
  2. Replace torch.sigmoid with torch.tanh. Is tanh better or worse than sigmoid? Why might that be, given their maximum slopes?
  3. Compute by hand: the gradient (3,4,12)(3, 4, 12) is clipped with τ=5\tau = 5. What is the result?

Hint for 3: the norm is 9+16+144=13\sqrt{9 + 16 + 144} = 13, so every entry is multiplied by 5/135/13.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A gradient is passed back through 50 layers, each multiplying it by about 0.9. Roughly how big is it when it reaches the first layer, compared with where it started?

  2. You clip gradients with threshold τ = 1. This step's gradient is (30, 40). What is it after clipping?

  3. Your deep sigmoid network's loss falls a little and then stalls. You log per-layer gradient norms and find layer 1's is 10⁻¹⁵ times layer 20's. Which fix will NOT help?

  4. Why does a residual connection, h_k = h_{k−1} + F(h_{k−1}), help gradients reach early layers?

  5. During a long training run, the gradient norm suddenly spikes. What is the most useful reading of this?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Article

Yes you should understand backprop

Andrej Karpathy · 2016 · Intermediate · Free

A short essay on why practitioners must understand the backward pass, with concrete failure cases: saturated sigmoids, dead ReLUs and exploding gradients in RNNs.

Book

Understanding Deep Learning

Simon J. D. Prince · 2023 · Intermediate · Free

A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/vanishing-gradients.md