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
- Builds on
- 17 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 17 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Backpropagation
- Activation Functions
- 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:
- . Fifty factors of 0.9 shrink the signal 200-fold.
- . Fifty factors of 1.1 grow it more than a hundredfold.
- . 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.
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 for layers . From the Backpropagation chapter, each step of the backward pass does two things to the gradient:
- It multiplies by the slope of the activation function, , element by element.
- It multiplies by the transposed weight matrix, .
So the gradient arriving at layer 1 is roughly a product of slopes and weight matrices. To see the effect, imagine one neuron per layer with weight and the same slope everywhere. Then the gradient at the first layer is the gradient at the loss times
If the product shrinks exponentially with depth: the gradient vanishes. If it grows exponentially: the gradient explodes. With real matrices the picture is the same, except that 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 ). 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).
The numbers are dramatic:
| Setup | Gradient at layer 1 | Gradient at layer 20 |
|---|---|---|
| Sigmoid | ||
| ReLU, PyTorch default initialisation | ||
| ReLU, weights twice the He size | ||
| ReLU, He initialisation | ||
| ReLU, residual connections + LayerNorm |
With sigmoid, the first layer's gradient is 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 inputs, Xavier (Glorot) initialisation draws weights with variance (or a closely related average of inputs and outputs), which suits tanh. He initialisation uses variance , 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 into one of about . 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:
Here is the layer's usual computation. The derivative of with respect to is now instead of just . 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:
Here is the gradient of all parameters stacked into one vector, is its norm (length), and ("tau") is the threshold. The direction is unchanged; only an over-long step is shortened. A worked example: if and the gradient is , its norm is , so it is scaled by to become , which has norm 1. A gradient of , 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
nanas bad luck. Ananloss 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
- Weight Initialization: deriving the Xavier and He variances, and why symmetric starting weights fail.
- Normalization Layers: BatchNorm and LayerNorm: BatchNorm, LayerNorm and RMSNorm.
- Residual Connections: skip connections, ResNets and the Transformer's residual stream.
- LSTMs and GRUs: gating as the recurrent-network answer to vanishing gradients.
- Optimizers: SGD, Momentum and Adam: Adam rescales each parameter's update by the size of its recent gradients, which partly masks badly scaled gradients but doesn't cure them.
- Training Neural Networks in Practice: the practical checklist, including what to log.
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
- In the experiment, change
depthfrom 20 to 5 and then to 50. How does the sigmoid network's layer-1 gradient change? Is it roughly exponential in depth?- Replace
torch.sigmoidwithtorch.tanh. Is tanh better or worse than sigmoid? Why might that be, given their maximum slopes?- Compute by hand: the gradient is clipped with . What is the result?
Hint for 3: the norm is , so every entry is multiplied by .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Yes you should understand backprop
A short essay on why practitioners must understand the backward pass, with concrete failure cases: saturated sigmoids, dead ReLUs and exploding gradients in RNNs.
Understanding the difficulty of training deep feedforward neural networks
Diagnosed why deep nets trained badly, and introduced Xavier/Glorot initialisation.
On the difficulty of training Recurrent Neural Networks
Explains vanishing and exploding gradients in RNNs and popularised gradient-norm clipping as the fix for explosions.
Deep Residual Learning for Image Recognition
ResNet: skip connections made networks with 100+ layers trainable.
Understanding Deep Learning
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