CodeRigor

LESSON

Vanishing gradients and the LSTM

See how a tanh recurrence shrinks or explodes its gradient, then build the LSTM cell whose additive cell state gives the error a path that the gates control.

A recurrent network reuses one weight matrix at every time step, and that reuse is why its gradients are hard to control. This lesson measures the problem and then builds the cell that was designed around it. It pairs with Lecture 14 of CMU's 11-785 (Fall 2026), linked under Watch & read. You will write an LSTM cell and a loop that runs it over a sequence, and check both against torch.nn.LSTM.

Start with the plain recurrence hₜ = tanh(W_hh hₜ₋₁ + W_ih xₜ + b). An error that reaches step t travels back to step t - 1 through the tanh slope 1 - hₜ² and then through W_hhᵀ. After k steps it has crossed k such pairs, a product of k factors. The slope never exceeds 1, so if every singular value of W_hh is below 1, the error norm shrinks by at least that factor per step. Above 1 it can grow, but it does not have to, because saturated units have slope near 0. The run below uses a random orthogonal Q, so every singular value of W_hh equals the scale.

Python
import numpy as np

H, steps = 16, 30
rng = np.random.default_rng(0)
Q, _ = np.linalg.qr(rng.normal(size=(H, H)))      # orthogonal: every singular value is 1
Win = rng.normal(0, 0.05, (H, H))
xs = rng.normal(size=(steps + 1, H))


def back_norms(scale):
    Whh = scale * Q
    h, hs = np.zeros(H), []
    for x in xs:
        h = np.tanh(Whh @ h + Win @ x)
        hs.append(h)
    g = np.ones(H) / np.sqrt(H)                    # a unit error at the last step
    norms = [1.0]
    for h in reversed(hs[1:]):
        g = Whh.T @ (g * (1 - h * h))              # back through tanh, then through Whh
        norms.append(float(np.linalg.norm(g)))
    return norms


for scale in (0.9, 2.5):
    n = back_norms(scale)
    print(scale, round(n[10], 4), round(n[30], 4))

The error that left the last step with norm 1 arrives 30 steps earlier with norm 0.0023 at scale 0.9, and with norm 514 at scale 2.5. That is one seed and one input sequence, and the growth is irregular because the slopes change with the state, but the geometric trend is the point. A signal 30 steps back either contributes almost nothing to the weight update or swamps everything else.

How far the error survives, going back in time
Norm of an error that starts with norm 1 at the last step, after k steps back. The two tanh recurrences use W_hh = 0.9·Q and 2.5·Q (Q random orthogonal). The LSTM lines follow only the cell path, where each step multiplies by a forget gate.
How far the error survives, going back in time
Norm of an error that starts with norm 1 at the last step, after k steps back. The two tanh recurrences use W_hh = 0.9·Q and 2.5·Q (Q random orthogonal). The LSTM lines follow only the cell path, where each step multiplies by a forget gate.

The LSTM keeps a second state c next to h and updates it by addition. Each step computes four gates from the input and the old hidden state: the input gate i, the forget gate f, the candidate g and the output gate o. Then

  • cₜ = f ⊙ cₜ₋₁ + i ⊙ g
  • hₜ = o ⊙ tanh(cₜ)

The gates i, f and o are logistic sigmoids, so each entry lies between 0 and 1. The candidate g is a tanh. Hold the gate values fixed and differentiate: ∂cₜ/∂cₜ₋₁ is the diagonal matrix of f. There is no weight matrix and no squashing on this path, only one elementwise factor. Over k steps the error along it is scaled by the product of k forget values, and if f is close to 1 that product stays close to 1.

Python
import numpy as np

rng = np.random.default_rng(1)
f = rng.uniform(0.97, 1.0, size=30)               # one forget gate per step, held fixed
i, g = rng.uniform(0, 1, 30), rng.uniform(-1, 1, 30)


def last_cell(c0):
    c = c0
    for t in range(30):
        c = f[t] * c + i[t] * g[t]
    return c


eps = 1e-6
measured = (last_cell(1.0 + eps) - last_cell(1.0 - eps)) / (2 * eps)
print(round(measured, 6), round(float(np.prod(f)), 6))
print(f"{0.5 ** 30:.2e}")

The finite difference and the product of the gates agree, and with f = 0.5 at every step the same product would be about 9.31e-10. Be precise about what this shows. The gates themselves depend on hₜ₋₁, so other paths exist, and those do pass through weight matrices and can still shrink or grow. The cell state gives the error one path that the gates, not a matrix, control.

PyTorch stacks the four gates along the rows: W_ih has shape (4H, D) and W_hh has shape (4H, H), with the blocks in the order i, f, g, o. There are two bias vectors, both added. So gates = x W_ihᵀ + b_ih + h W_hhᵀ + b_hh has shape (N, 4H), and np.split(gates, 4, axis=1) cuts it into the four blocks.

One LSTM step, in the order it is computed
start / 5
The cell state runs along the bottom: the old cell is scaled by the forget gate, the input gate lets a new candidate in, and the result is the next cell state.
One LSTM step, in the order it is computed
The cell state runs along the bottom: the old cell is scaled by the forget gate, the input gate lets a new candidate in, and the result is the next cell state.

A worked step with real numbers. Take zero weights, so only the biases act, with biases ln 3, 0, (ln 3) / 2 and -ln 3 for i, f, g, o, and an old cell value of 2.

Python
import numpy as np

sig = lambda z: 1 / (1 + np.exp(-z))
b = np.array([np.log(3), 0.0, np.log(3) / 2, -np.log(3)])   # biases in the order i, f, g, o
i, f, g, o = sig(b[0]), sig(b[1]), np.tanh(b[2]), sig(b[3])
c = f * 2.0 + i * g                                          # the old cell holds 2.0
h = o * np.tanh(c)
print(round(i, 4), round(f, 4), round(g, 4), round(o, 4))
print(round(c, 4), round(h, 4))

The forget gate halves the old 2 to 1, the input gate lets in 0.75 · 0.5 = 0.375, and the new cell is 1.375. The output gate then passes a quarter of tanh(1.375).

Three mistakes are common:

  • Reading the blocks in the wrong order, say i, f, o, g. Every block has the same shape, so nothing crashes and the numbers look plausible, but they are wrong.
  • Leaving out the tanh in hₜ = o ⊙ tanh(cₜ). The cell state is not squashed, so it can grow past 1, and hₜ would leave the range of (-1, 1).
  • Writing the sigmoid as 1 / (1 + exp(-z)). For z = -1000 the exponential overflows. The build uses ½(1 + tanh(z / 2)), which is the same function and cannot overflow. A result that silently underflows to 0 is fine.

Two practical notes. The forget bias is often initialised to a positive number, so f starts near 1 and the cell remembers by default. It has to be large to matter over long spans: σ(1) = 0.73 has a 30th power of 0.00008, σ(3) = 0.95 gives 0.23 and σ(5) = 0.993 gives 0.82. The GRU is a lighter relative with two gates and no separate cell state.

The hidden tests compare your lstm_cell with torch.nn.LSTMCell and your lstm_forward with torch.nn.LSTM, outputs and final states, to 1e-10 in float64, and they feed inputs of magnitude 1000 with overflow errors turned on. That proves your forward pass equals PyTorch's. It does not test any gradient, and it does not show that a trained LSTM uses its memory. The gates make long memory possible. They do not guarantee that learning finds a use for it.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

The lecture this lesson is built around: why a plain recurrent network struggles to carry information across many steps, and the gated LSTM cell designed for it. Watch it first, then build the cell here and compare it with PyTorch.