The vanishing gradient

The vanishing gradient

28 min read

The previous lesson, on backpropagation through time (BPTT), ended with a correct gradient and a loose end. Correct, because the numerical probe confirmed it entry by entry; a loose end, because computing it repeats a single move that nobody stopped to examine. To carry the error from one position back to the one before, you multiply it by the recurrent matrix Whh\mathbf{W}_{hh}, and in a forty-token sequence that multiplication comes round almost forty times. This lesson measures what repeating the same multiplication that many times in a row does to the gradient, and finds the number in Whh\mathbf{W}_{hh} that puts a ceiling on the result.

This is no numerical curiosity: what's at stake is the one reason to prefer a recurrent neural network (RNN) over the network this block opened with. Take a review that starts I doubt this helps anyone and, thirty words later, ends with its rating. That opening I doubt flips the sign of everything after it, but the network can only learn the connection if the gradient computed at the last word survives the long trip to the first ones. If it fades along the way, the network never learns to pin the rating on those opening words, and the memory that defined it ends up, in practice, as a memory of the recent past only.

Before tackling the whole matrix, strip away coordinates until only one is left. With dh=1d_h = 1 the state is a number, Whh\mathbf{W}_{hh} is a number ww, and carrying the error one step back means multiplying it by ww. Repeating that step dd times multiplies it by wdw^{d}.

And wdw^{d} has no middle ground. If ∣w∣<1\lvert w \rvert < 1 it sinks: with w=0.5w = 0.5, forty steps leave the error at 0.540≈9×10−130.5^{40} \approx 9 \times 10^{-13}, twelve orders of magnitude below where it started. If ∣w∣>1\lvert w \rvert > 1 it shoots up: 1.540≈1.1×1071.5^{40} \approx 1.1 \times 10^{7}. Only ∣w∣=1\lvert w \rvert = 1 keeps the error the same size, and that's a knife-edge a single point wide: stray a hair either way and you fall off one side or the other. With more than one coordinate, ww becomes a matrix, and its role splits between two numbers that the argument below keeps apart: one caps the gradient step by step, mask included; the other sets the long-run pace of the matrix multiplied by itself. The explorable shows the second, the spectral radius, for a recurrence with no mask (every slope of the tanh⁡\tanh at 11). Slide it to either side of 11 and you'll see both halves of the phenomenon: below, the curve dives; above, it goes through the roof.

The gradient of a recurrence with no mask, in orders of magnitude, plotted against how many steps it has to travel back. Below a spectral radius of 1 it vanishes; above 1 it explodes; and the longer the sequence, the more extreme the result. The line tilts, but it never bends.

Go back to the previous lesson's backward recurrence and follow it for more than one step. There, each step's error came from the next one's in two moves, transport and mask:

δt=(Whh⊤δt+1)⊙(1−ht⊙ht).\boldsymbol{\delta}_t = \left(\mathbf{W}_{hh}^{\top}\boldsymbol{\delta}_{t+1}\right) \odot \left(\mathbf{1} - \mathbf{h}_t \odot \mathbf{h}_t\right).

The ⊙\odot with the slope of the tanh⁡\tanh amounts to multiplying by a diagonal matrix (diag ⁣(1−ht⊙ht)\text{diag}\!\left(\mathbf{1} - \mathbf{h}_t \odot \mathbf{h}_t\right), with those slopes on the diagonal and zeros everywhere else), so one step of the backward pass multiplies δt+1\boldsymbol{\delta}_{t+1} by two matrices: first Whh⊤\mathbf{W}_{hh}^{\top}, then that diagonal. Chain the recurrence from the last step down to some distant step kk and the pair repeats, once per position:

δk=(∏t=kT−1diag ⁣(1−ht⊙ht)Whh⊤)δT∈Rdh.\boldsymbol{\delta}_k = \left(\prod_{t=k}^{T-1} \text{diag}\!\left(\mathbf{1} - \mathbf{h}_t \odot \mathbf{h}_t\right)\mathbf{W}_{hh}^{\top}\right)\boldsymbol{\delta}_T \in \mathbb{R}^{d_h}.

The product has T−kT - k pairs, one for each step between kk and TT (the distance the error travels). And every pair contains the same Whh⊤\mathbf{W}_{hh}^{\top}: this isn't a different layer per position, the way the blocks Wt(1)\mathbf{W}^{(1)}_t of the concatenated first layer were in the lesson on why the multilayer perceptron (MLP) fails on sequences, but a single matrix raised, in effect, to the power of the distance. That's the move the previous lesson kept repeating without looking at it.

Why it decays or explodes

A product of matrices is hard to look at directly; its size isn't. Take norms on both sides and use the fact that the norm of a product is never bigger than the product of the norms:

∥δk∥≤∥δT∥∏t=kT−1∥diag ⁣(1−ht⊙ht)∥∥Whh⊤∥.\lVert \boldsymbol{\delta}_k \rVert \le \lVert \boldsymbol{\delta}_T \rVert \prod_{t=k}^{T-1} \left\lVert \text{diag}\!\left(\mathbf{1} - \mathbf{h}_t \odot \mathbf{h}_t\right)\right\rVert \left\lVert \mathbf{W}_{hh}^{\top}\right\rVert.

That ∥⋅∥\lVert \cdot \rVert is now measuring a matrix, not a vector. For any matrix A\mathbf{A} it's defined as

∥A∥=max⁡v≠0∥Av∥∥v∥,\lVert \mathbf{A} \rVert = \max_{\mathbf{v} \neq \mathbf{0}} \frac{\lVert \mathbf{A}\mathbf{v} \rVert}{\lVert \mathbf{v} \rVert},

the largest factor by which A\mathbf{A} can stretch a vector's length, taking the worst case over every possible direction. That definition is what makes ∥Av∥≤∥A∥∥v∥\lVert \mathbf{A}\mathbf{v} \rVert \le \lVert \mathbf{A} \rVert \lVert \mathbf{v} \rVert true for any v\mathbf{v} (multiply both sides of the definition by ∥v∥\lVert \mathbf{v} \rVert), and applying it twice in a row gives ∥AB∥≤∥A∥∥B∥\lVert \mathbf{A}\mathbf{B} \rVert \le \lVert \mathbf{A} \rVert \lVert \mathbf{B} \rVert: B\mathbf{B} stretches by at most ∥B∥\lVert \mathbf{B} \rVert, and A\mathbf{A} then stretches that result by at most a further ∥A∥\lVert \mathbf{A} \rVert.

Both factors in each pair have a ceiling. For a diagonal matrix, that maximum is easy to find: diag(d)\text{diag}(\mathbf{d}) stretches each coordinate by its own entry, so the worst case is lining v\mathbf{v} up with the coordinate whose entry is largest in absolute value, and ∥diag(d)∥=max⁡i∣di∣\lVert \text{diag}(\mathbf{d}) \rVert = \max_i \lvert d_i \rvert. Here each diagonal entry is a slope of the tanh⁡\tanh (one per coordinate of ht\mathbf{h}_t): it never goes above 11, and as soon as that coordinate saturates it gets close to 00. Those are the red bands you already saw in the explorable in the lesson on activation functions. The largest of those slopes across every step from kk to T−1T - 1 is therefore also ≤1\le 1; call it γ\gamma. The ceiling for Whh⊤\mathbf{W}_{hh}^{\top} comes from the same definition, without the convenience of a diagonal, and the one new fact you need here is that a matrix stretches a vector's length by at most its largest singular value σmax⁡\sigma_{\max}, so multiplying by it dd times stretches it by at most σmax⁡d\sigma_{\max}^{d}. Put the two bounds together over the T−kT - k pairs:

∥δk∥≤(γ σmax⁡)T−k∥δT∥.\lVert \boldsymbol{\delta}_k \rVert \le \left(\gamma\,\sigma_{\max}\right)^{T-k}\lVert \boldsymbol{\delta}_T \rVert.

There's the exponent, and with it the one condition that holds whatever happens along the way. The error reaching position kk is at most the error at the end multiplied by γ σmax⁡\gamma\,\sigma_{\max} raised to the distance. If γ σmax⁡<1\gamma\,\sigma_{\max} < 1, the gradient vanishes, with no escape: the ceiling plummets with the distance and the gradient can't rise above it, whatever the masks turn out to be. Since γ≤1\gamma \le 1, σmax⁡<1\sigma_{\max} < 1 is enough to guarantee this on its own, and saturation only adds to the margin. The converse doesn't hold. If γ σmax⁡>1\gamma\,\sigma_{\max} > 1, the ceiling no longer holds the gradient down and it can explode, but nothing forces it to: that inequality is necessary for an explosion, not sufficient.

The bound is also usually too generous: a given vector rarely gets stretched by the maximum at every single step. What Whh\mathbf{W}_{hh} really does when multiplied by itself over the long run is measured by a different number, its spectral radius ρ(Whh)\rho(\mathbf{W}_{hh}) (the largest modulus among its eigenvalues), which never exceeds σmax⁡\sigma_{\max}. In a recurrence with no mask, every slope at 11, the product is a power of Whh⊤\mathbf{W}_{hh}^{\top}, and there ρ\rho really does decide: below 11 the gradient sinks, above 11 it shoots up, and in between there's nothing but that knife-edge. It's the number the explorable let you move.

Once the masks get in the way, ρ\rho stops being a guarantee: the product alternates Whh⊤\mathbf{W}_{hh}^{\top} with diagonals and is no longer the power of a single matrix. What still holds then is γ σmax⁡<1\gamma\,\sigma_{\max} < 1, which is why that's the real condition. You won't need to compute any eigenvalues in this lesson; what you do need to know is that ρ\rho exists, that it sets the pace of the matrix on its own, and that it never exceeds σmax⁡\sigma_{\max}.

See why the spectral radius stops deciding once the masks come in

In a recurrence with no mask, the product is (Whh⊤)d\left(\mathbf{W}_{hh}^{\top}\right)^{d}, and in the long run ∥(Whh⊤)d∥1/d\left\lVert \left(\mathbf{W}_{hh}^{\top}\right)^{d}\right\rVert^{1/d} tends to the spectral radius ρ(Whh)\rho(\mathbf{W}_{hh}) as dd grows. That's why, in that case, ρ<1\rho < 1 guarantees vanishing and ρ>1\rho > 1 makes the norm of the power grow without limit, even though over short distances the bound with σmax⁡\sigma_{\max} runs ahead of the real pace.

With the tanh⁡\tanh, what repeats is no longer Whh⊤\mathbf{W}_{hh}^{\top} but each pair, and a mask can switch off precisely the coordinate that was holding the growth in check. Take Whh⊤=(22−2−2)\mathbf{W}_{hh}^{\top} = \begin{pmatrix} 2 & 2 \\ -2 & -2 \end{pmatrix}. Its square is the zero matrix, so ρ=0\rho = 0 and its powers die out in two steps. But if the mask is diag(1, 0.1)\text{diag}(1,\ 0.1) at every step, each pair is (22−0.2−0.2)\begin{pmatrix} 2 & 2 \\ -0.2 & -0.2 \end{pmatrix}, whose spectral radius is 1.81.8, and the product grows like 1.8d1.8^{d}. That doesn't contradict the real condition: here γ=1\gamma = 1 and σmax⁡=4\sigma_{\max} = 4, and a γ σmax⁡\gamma\,\sigma_{\max} of 44 never promised the gradient would sink.

Check it on a real matrix, without reducing it to a single coordinate: numpy.linalg has svd for σmax⁡\sigma_{\max} and eig for the eigenvalues that give ρ\rho.

import numpy as np

W = np.array([[0.5, 4.0],
[0.0, 0.5]])

sigma_max = np.linalg.svd(W, compute_uv=False)[0] # largest singular value
rho = np.max(np.abs(np.linalg.eig(W)[0])) # spectral radius

print("sigma_max = %.4f" % sigma_max)
print("rho = %.4f" % rho)
print()
print(" d ||W^d|| ||W^d||**(1/d)")
for d in [1, 5, 10, 20, 40]:
Wd = np.linalg.matrix_power(W, d)
norm_d = np.linalg.svd(Wd, compute_uv=False)[0]
print("%2d %9.2e %14.4f" % (d, norm_d, norm_d ** (1 / d)))
numpy

The first run downloads the Python interpreter (~15 MB). After that it stays in the browser cache and is reused across every lesson.

For this W\mathbf{W}, σmax⁡≈4.06\sigma_{\max} \approx 4.06 but ρ=0.5\rho = 0.5: the singular-value bound overestimates the pace of the power by a factor of eight. The table bears this out. At d=1d = 1 the raw norm is σmax⁡\sigma_{\max} (the two coincide by construction), and at d=5d = 5 it's still above 11 (the power can grow for several steps even though ρ<1\rho < 1 guarantees it sinks in the long run). By d=40d = 40 the raw norm is tiny and ∥Wd∥1/d\lVert \mathbf{W}^{d} \rVert^{1/d} has dropped below 0.580.58, closing in on ρ=0.5\rho = 0.5: actual numbers confirming what the argument above could only assert. And the two numbers answer different questions: the power on its own sinks, but with σmax⁡≈4.06\sigma_{\max} \approx 4.06, this W\mathbf{W} guarantees nothing once the masks come in.

Seeing it and clipping it in NumPy

The first cell in this section boils everything down to the one-coordinate case and looks at the raw exponent; the second tackles the half of the problem that does have a cheap fix.

The scalar case isn't a toy: it's the formula above with dh=1d_h = 1, where σmax⁡\sigma_{\max}, ρ\rho and ∣w∣\lvert w \rvert are all the same number. Run it and compare the middle row (w=1w = 1) with the other two.

# A one-coordinate W_hh is a number w. Carrying the error d steps
# back multiplies it by w**d. The tanh mask (slope <= 1) can only
# shrink it further, so w = 1 is already the most favourable case.
print(" w d=10 d=20 d=40")
for w in [0.5, 1.0, 1.5]:
print("%.1f %9.2e %9.2e %9.2e" % (w, w ** 10, w ** 20, w ** 40))

The first run downloads the Python interpreter (~15 MB). After that it stays in the browser cache and is reused across every lesson.

The first row sinks, the last shoots up and the middle one doesn't move, exactly as the start of the lesson said it would. With w=0.5w = 0.5, the error arrives forty steps back at 9×10−139 \times 10^{-13} of its original size, and no gradient descent can learn from a signal that small. And that's the best case: as soon as the state saturates, the tanh⁡\tanh mask pushes it lower still.

Explosion, on the other hand, has a straightforward answer. If the problem is that the gradient's norm grows with nothing to rein it in, give it a ceiling: fix a threshold κ\kappa and, whenever ∥g∥\lVert \mathbf{g} \rVert exceeds it, rescale the gradient to bring it back to exactly that size. This is gradient clipping:

g←g⋅min⁡ ⁣(1, κ∥g∥).\mathbf{g} \leftarrow \mathbf{g}\cdot\min\!\left(1,\ \frac{\kappa}{\lVert \mathbf{g} \rVert}\right).

The min⁡\min with 11 is the key: if the gradient is already small, the factor equals 11 and leaves it alone; it only acts on a gradient that has gone over the limit, and it does so by multiplying it by a positive number, which changes its length but not its direction. Check it.

import numpy as np

rng = np.random.default_rng(1)
kappa = 5.0 # the ceiling on the norm


def clip(g):
n = np.linalg.norm(g)
return g * min(1.0, kappa / n), n # factor <= 1: shrinks or leaves alone, never turns


for name, g in [("normal ", rng.normal(size=100) * 0.3),
("exploded", rng.normal(size=100) * 3.0)]:
g_clip, n = clip(g)
cosine = float(g @ g_clip) / (n * np.linalg.norm(g_clip))
print("%s ||g|| = %6.2f -> ||clipped|| = %.2f (cosine with g: %.4f)"
% (name, n, np.linalg.norm(g_clip), cosine))
numpy

The first run downloads the Python interpreter (~15 MB). After that it stays in the browser cache and is reused across every lesson.

The normal gradient passes through untouched; the exploded one, with a norm of almost 3030, comes out clipped to exactly 5.005.00, and its cosine with the original is 11 (same direction, different size). Clipping rescues training when the gradient explodes, and it costs almost nothing. What it doesn't do, and this deserves saying out loud, is anything at all about vanishing: a gradient that has already shrunk to 10−1310^{-13} has a tiny norm, the min⁡\min equals 11, and it stays exactly as it was.

Test your intuition

Four questions: what makes the gradient vanish or explode, what clipping fixes and what it doesn't, whether the tanh⁡\tanh mask can save the day, and what's lost when it can't.

What makes an RNN's gradient vanish or explode as it travels back through a long sequence?

Gradient clipping rescales g←g⋅min⁡ ⁣(1, κ/∥g∥)\mathbf{g} \leftarrow \mathbf{g}\cdot\min\!\left(1,\ \kappa/\lVert\mathbf{g}\rVert\right) when the gradient's norm exceeds a threshold κ\kappa. Which problem does it solve, and which does it leave untouched?

The mask 1−ht⊙ht\mathbf{1} - \mathbf{h}_t \odot \mathbf{h}_t that appears at every step of the backward pass is the slope of the tanh⁡\tanh. If the largest singular value of Whh\mathbf{W}_{hh} satisfies σmax⁡<1\sigma_{\max} < 1, the gradient vanishes. Can the mask rescue it?

What does an RNN lose when the gradient linking the end of the sequence to the start has vanished?


Clipping caps the explosion, but it leaves the other half of the problem where it was. A gradient that has been multiplied down towards zero doesn't recover by being multiplied by 11, and no choice of Whh\mathbf{W}_{hh} fixes both at once: pushing σmax⁡\sigma_{\max} below 11 so the gradient can't explode is exactly what guarantees that it vanishes. The problem isn't the weights, it's the path: any path that multiplies by the same matrix at every step ends up at one of the two extremes.

The way out is to change the path. What's needed is a route along which the state moves from one step to the next by adding, rather than passing through Whh\mathbf{W}_{hh} yet again: across a sum, the gradient flows without being multiplied once per position, so it neither sinks nor shoots up. That additive path is the cell state of the long short-term memory (LSTM), and building it one gate at a time, each gate fixing a specific failure of the vanilla RNN, is the next lesson, on the LSTM and its gates.

Was this helpful?
Further reading2 sources · 1 paper, 1 book

Where this lesson comes from, and where to go next. None of it is needed to carry on with the course.

  • On the difficulty of training Recurrent Neural Networks
    paperPascanu, Mikolov and Bengio, 2013arXiv:1211.5063EN

    Both halves of this lesson come from here: the bound with the slope γ that guarantees vanishing (the spectral radius only decides in the linear case), and the clipping that caps the gradient's norm at a threshold. It doesn't get into gates.

  • Gradient Flow in Recurrent Nets: the Difficulty of Learning Long-Term Dependencies
    bookHochreiter, Bengio, Frasconi and Schmidhuber, 2001A Field Guide to Dynamical Recurrent NetworksEN

    Its §2 proves what you see here on a plot: the error travelling back through the sequence decays or grows exponentially with the number of steps. It gathers the 1991 and 1994 proofs; its §4 only surveys remedies, the LSTM among them.