Home/How Learning Works

Exploding and Vanishing Gradients

Each layer multiplies the gradient by its own factor. Chain enough together and the product either shrinks to zero or grows to infinity.

Controls

1.00

< 1 vanishing  |  > 1 exploding

8

Set weight scale below 1 to see vanishing, above 1 to see exploding. Press Animate to watch gradients flow backward layer by layer.

Gradient Flow Through Layers

—

Gradient Magnitudes

Last Layer1.000
First Layer1.000
Ratio (first/last)1.000
Diagnosis
Stable

With weight scale 1.0, gradients pass through unchanged. Move the slider to break the balance.

Overview

Each layer multiplies the gradient by its own factor.

In this guide
  1. Context first
  2. The chain rule is a product
  3. Vanishing gradients
  4. Exploding gradients
  5. Seeing it with numbers
  6. What keeps gradients in range
  7. Where it is worst
  8. Questions people ask about Exploding and Vanishing Gradients
  9. Exploding and Vanishing Gradients: recap in one screen

Exploding and Vanishing Gradients

Why depth breaks gradient descent, and what you can do about it.

Context first

Training a deep network means passing a loss signal backward through every layer. Each layer multiplies the incoming gradient by its own local derivative. Chain enough of these together and the product either shrinks toward zero or grows toward infinity.

This is the exploding and vanishing gradient problem. It was the biggest reason deep networks seemed untrainable before good init, normalisation and skip connections came along. You hit it the moment you stack more than a handful of layers. You hit it again every time you train a recurrent network over long sequences.

The chain rule is a product

Backpropagation computes gradients by the chain rule, layer after layer. For a network with L layers the gradient at the first layer looks like:

dL/dW_1 = (dL/da_L) * (da_L/da_{L-1}) * ... * (da_2/da_1) * (da_1/dW_1)

Each factor depends on the weight matrix and the activation slope at that layer. The gradient at layer 1 is a product of L-1 such factors.

Products of many numbers amplify small biases. If the typical factor is a bit below 1, the product shrinks fast. If it is a bit above 1, it grows fast. Only when each factor sits close to 1 does the product stay in a useful range.

Vanishing gradients

When weights are small or neurons saturate, each factor drops below 1. After 50 layers the gradient at layer 1 is 0.95^50 ≈ 0.08 of what it was at the last layer. After 100 layers it is 0.95^100 ≈ 0.006. The early layers get almost no signal. Their weights barely move, so they learn nothing while the final layers train fine. You see a loss curve that goes flat early even though the network has plenty of room.

Sigmoid made this worse. Its slope peaks at 0.25 and drops toward zero for large inputs. Every saturated neuron scales the gradient by a number near zero. ReLU fixed this cause: its slope is exactly 1 for positive inputs.

Exploding gradients

When weights are large the factors exceed 1 and the product grows fast. After a few dozen layers the gradient can reach thousands or millions. One step moves the weights so far that the next forward pass gives inf or NaN. Training crashes in a single update. You spot this by a loss that jumps to NaN after running fine for a while.

This is common in recurrent networks. An RNN shares one weight matrix across every time step. Backprop through 100 steps means the same matrix is applied 100 times. If its largest singular value is above 1, the product blows up. That is why gradient clipping is standard for RNNs and transformers.

Seeing it with numbers

import numpy as np

rng = np.random.default_rng(42)

for scale, label in [(0.5, "vanishing"), (1.5, "exploding")]:
    W = rng.normal(0, scale, (4, 4))
    grad = np.ones(4)
    print(f"--- {label} (weight scale {scale}) ---")
    for layer in range(1, 21):
        grad = W.T @ grad
        norm = np.linalg.norm(grad)
        bar = "#" * min(int(norm), 60)
        print(f"  layer {layer:2d}  gradient norm {norm:12.4f}  {bar}")
    print()

Run this and you will see the gradient norm either collapse to near zero or shoot into the millions within 20 layers.

What keeps gradients in range

Five fixes target the problem, each at a different point.

Good init. Xavier init sets the variance of each weight matrix so the signal stays the same size going forward and backward. He init does the same but adjusts for ReLU zeroing half the outputs. Without good init the problem starts on the first forward pass.

Batch and layer norm. Batch norm rescales layer outputs to zero mean and unit variance. This stops activations from drifting into flat regions and keeps each chain factor near 1. Layer norm does the same per sample, which helps when batches are small.

Skip connections. A residual block computes y = x + F(x). The gradient through the skip path is exactly 1. Even if F gives a tiny gradient, the total is at least 1. This is why ResNets can stack hundreds of layers without the gradient dying.

Gradient clipping. Gradient clipping caps the gradient norm before the update step. It does not fix the root cause but it stops the one bad update that crashes training. Standard in RNNs and transformers.

Gating. LSTMs and GRUs replace plain recurrent multiplication with gates that learn when to pass gradients and when to block them. The cell state in an LSTM can carry a gradient unchanged across many steps. This is why LSTMs largely solved vanishing gradients for sequences.

Where it is worst

Recurrent networks are the worst case. An RNN with a sequence of length T applies the same weight matrix T times during backprop through time. T = 100 is common. T = 1000 shows up in speech and music. The odds that a product of 100 matrices stays in a useful range without gating or clipping are near zero.

Very deep feed-forward networks hit the same wall. Skip connections have made this rare, but before ResNet, training a 50-layer CNN was very hard.

Questions people ask about Exploding and Vanishing Gradients

Is vanishing or exploding worse? Exploding is louder — training crashes with NaN. Vanishing is sneakier — training seems to work, just poorly. Early layers quietly stop learning.

Does batch norm fix vanishing gradients for good? It helps a lot but cannot promise stable gradients at any depth. Skip connections are more reliable for very deep networks.

Why did ReLU help? Its slope is 1 for positive inputs, so it does not shrink the gradient the way sigmoid does (max slope 0.25). The "dying ReLU" problem is a different issue: a neuron that outputs zero for all inputs and never learns again.

Can I spot the problem during training? Yes. Log the gradient norm at each layer. If the norm at layer 1 is far smaller than at the last layer, gradients are vanishing. If any norm spikes to thousands, they are exploding.

What does the widget show? The interactive above lets you set a weight scale and a layer count. It passes gradients backward and shows how they shrink or grow at each layer.

Do transformers have this problem? Transformers use skip connections and layer norm, which keep gradients stable. They still clip as a safety net, but the design avoids the problem from the start.

Exploding and Vanishing Gradients: recap in one screen

  • The gradient at early layers is a product of one factor per layer.
  • Factors below 1 make the product vanish. Factors above 1 make it explode.
  • Xavier/He initialisation keeps the factors near 1 at the start.
  • Batch normalisation prevents activations from drifting.
  • Residual connections add a gradient path of exactly 1.
  • Gradient clipping caps the damage when all else fails.
  • RNNs are the worst case; gating (LSTM, GRU) and clipping are both needed there.

Predict, then reveal

About to run: set Layers to its maximum (15). Before it does — what happens to the readout?

Committing to an answer first is the point — the reveal runs the experiment on the visualisation above and reads the real value back, so nothing here is scripted.

Recall check

0 of 3

Say the answer out loud before you reveal it — recalling it is what makes it stick, and rereading it is not.

  1. What does this module say about “Gradient Magnitudes”?

  2. What does this module say about “Context first”?

  3. What does this module say about “The chain rule is a product”?

Cheat sheet

Exploding and Vanishing Gradients

Watch gradients shrink to zero or explode to infinity as they flow backward through a chain of layers.

DEEP LEARNING · vizlearn.in/deep_learning/exploding_and_vanishing_gradient.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.

Teaching a course with this? Individual teachers can use it freely; for a whole department or programme, see institutional licences.