All courses

Vanishing and exploding gradients

Explain that the gradient through a deep network is a product of per-layer Jacobians. Show why that product tends to shrink or grow exponentially with depth.

Builds on: Backpropagation as reverse-mode autodiff, MLPs and why nonlinearities matter

▶ Watch this lesson Start the whole course

What the animation says

Backprop runs through every layer

Backprop gives an exact gradient for every weight. So why do deep stacks often refuse to train? The first layers barely move, or the updates blow up and training diverges. Going backward, each layer multiplies the incoming gradient by its own local derivative. To reach the input, the gradient passes through every layer, one multiplication each. Tap the layer whose gradient sits behind the most factors.

Three layers by hand

Take a chain of three layers, one number each. The gradient at the top is one. Each layer's factor is its weight times its activation slope: point eight, point five, and point six. One times point eight is point eight. Times point five gives point four. Times point six gives point two four. The typical factor here, the geometric mean, is about point six two. Now stack thirty layers with that typical factor. What reaches the input?

Vanish or explode

Point six two, thirty times over, is about six ten-millionths. The gradient has all but vanished. Nudge the factor up to one point three, and thirty layers give about two thousand six hundred. A product of many factors never drifts gently. Below one it vanishes, above one it explodes. Only factors sitting right at one keep the size stable. A tell: the sigmoid's slope is at most a quarter. So unless the weights stretch the signal more than four times, every sigmoid layer shrinks the gradient.

Real layers: matrices

In a real network, each factor is a matrix: the layer's Jacobian. It's the activation slopes on a diagonal, times the transposed weights. Each backward step multiplies the gradient row by one Jacobian. The input gradient is the top gradient times all of them. If no Jacobian can stretch a vector by more than some c below one, the gradient shrinks at least like c to the L. And each layer's weight gradient scales with the gradient arriving there, so early weights stall.

Watch it in numpy

Here's a thirty-layer tanh network in numpy. Scale sets how much each weight matrix stretches a vector. This loop runs the backward pass: multiply by the tanh slope, then by the transposed weights. It starts from a gradient of norm eight. At scale point five, the norm collapses to about ten to the minus eight. At scale one, it ends near one. A two-times change in the weights moved the gradient about eight orders of magnitude. At scale two, a factor of two per layer would mean two to the thirtieth. What actually happens?

Saturation, and the takeaway

It grows roughly a hundredfold or more, far less than two to the thirtieth. Big weights push tanh inputs into its flat tails, where the slope is nearly zero. Those near-zero slopes cap the blow-up. So remember: the input gradient is the top gradient times one factor per layer. When typical factors are below one, it vanishes. When they are above one, it explodes. Deep networks that train well use design choices that keep each layer's factor close to one.

Why do deep networks resist training?

Backprop gives an exact gradient for every weight, so you might expect a 50-layer network to train as easily as a 2-layer one. In practice, plain deep stacks often fail. The first layers barely move, or the updates blow up and training diverges. What about **depth itself** makes the gradient that reaches early layers unreliable? And why does it get worse so fast as you add layers?

A long chain of multiplications

Going backward, each layer takes the incoming gradient and multiplies it by its own local derivative. To get back to the network's input, the signal passes through *every* layer, so it gets multiplied $L$ times. Layers near the input sit behind almost all of those factors. A product of many factors does not drift gently. If the typical factor is $0.8$, the result shrinks like $0.8^L$. If it is $1.2$, the result grows like $1.2^L$. Only factors sitting right at $1$ keep the size stable.

Gradient = product of Jacobians

Layer $\ell$: $a_\ell=u_{\ell-1}W_\ell$, $u_\ell=\phi(a_\ell)$ (rows). Let $g_\ell=\partial\mathcal L/\partial u_\ell$. Let $J_\ell=\partial u_\ell/\partial u_{\ell-1}$ be layer $\ell$'s Jacobian. The chain rule gives $$g_{\ell-1}=g_\ell J_\ell,\quad J_\ell=D_\ell W_\ell^\top,\quad D_\ell=\mathrm{diag}(\phi'(a_\ell))$$ $$g_0=g_L\,J_LJ_{L-1}\cdots J_1$$ With $\|J\|$ the operator norm (the most $J$ can stretch any vector), $\|g_0\|\le\|g_L\|\prod_\ell\|J_\ell\|$. So if every $\|J_\ell\|\le c<1$, the gradient shrinks at least as fast as $c^L$. Also, $\partial\mathcal L/\partial W_\ell=u_{\ell-1}^\top(g_\ell\odot\phi'(a_\ell))$, so the weight gradient of each layer scales with $g_\ell$.

Three layers, then thirty

Scalar chain with top gradient $g_3=1$. The per-layer factors $w\,\phi'$ are $0.8, 0.5, 0.6$. - $g_2=1\times0.8=0.8$ - $g_1=0.8\times0.5=0.4$ - $g_0=0.4\times0.6=0.24$ The geometric mean factor is about $0.62$. Over 30 such layers, $0.62^{30}\approx6\times10^{-7}$. With factors of $1.3$ instead, $1.3^{30}\approx2600$. The sigmoid has $\sigma'\le0.25$. Unless the weights stretch the signal by more than $4\times$, every sigmoid layer shrinks the gradient.

Watch it happen in numpy

This is a 30-layer tanh MLP. `scale` sets roughly how much each random weight matrix stretches a vector. The backward loop applies $g\leftarrow(g\odot\phi'(a))W^\top$ layer by layer, starting from a gradient of norm 8. At scale 0.5 the norm collapses to about $10^{-8}$. At 1.0 it ends near 1, a modest few-fold drop. So going from 0.5 to 1.0, a 2× change in weight size, moves the gradient by about 8 orders of magnitude. At 2.0 it grows roughly a hundredfold or more. That is far less than $2^{30}$, because large inputs saturate tanh, and saturated units have $\phi'\approx0$.
import numpy as np
rng = np.random.default_rng(0)
d, L = 64, 30
for scale in [0.5, 1.0, 2.0]:
    Ws = [rng.normal(0, scale/np.sqrt(d), (d, d)) for _ in range(L)]
    u, acts = rng.normal(size=(1, d)), []
    for W in Ws:
        a = u @ W; acts.append(a); u = np.tanh(a)
    g = np.ones((1, d))
    for W, a in zip(reversed(Ws), reversed(acts)):
        g = (g * (1 - np.tanh(a)**2)) @ W.T
    print(scale, np.linalg.norm(g))

Remember this

The gradient at the network's input, $g_0$, is the top gradient times the product of all $L$ layer Jacobians. Early layers' weight gradients sit behind nearly as many factors. A product of $L$ factors scales like $c^L$, so it **vanishes** when typical factors are below 1 and **explodes** when they are above 1. Deep networks that train well use design choices that keep each layer's factor close to 1.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.