CodeRigor

LESSON

Recurrent networks and backpropagation through time

Unroll a recurrent network over a sequence, then send the error back through every time step while the shared weights collect a gradient from each one.

A recurrent network reads a sequence one element at a time and carries a state from step to step. Training it needs the derivative of the loss with respect to those shared weights, and that derivative collects a contribution from every step. This lesson pairs with Lecture 13 of CMU's 11-785 (Fall 2026), linked under Watch & read. You build the forward pass, the backward sweep over time and gradient clipping in NumPy, and grade them against PyTorch's autograd.

At step t the network reads the input xₜ and the previous state hₜ₋₁, computes the new state, and reads an output from it:

  • hₜ = tanh(Wxh xₜ + Whh hₜ₋₁ + bh)
  • yₜ = Why hₜ + by

The same five arrays are used at every step, stored (out, in) like torch.nn.Linear. The code keeps the states in one array: hs[0] is the start state (zeros unless you pass h0) and hs[t + 1] is the state after reading xs[t]. In the formulas hₜ means hs[t + 1] and hₜ₋₁ means hs[t]. The logits yₜ feed a softmax cross-entropy at every step, and the loss is the mean over the T steps, so the error at the logits is (p - y) / T.

Write the loop out T times and you have a deep network with T layers whose weights are all the same. Ordinary backpropagation applies to it, and applying it to the unrolled network is called backpropagation through time.

Unrolled over three steps
start / 5
The same Wxh, Whh and bh sit inside every state. Each state also produces an output and a share of the loss. Backward, each state except the last receives error from two places.
Unrolled over three steps
The same Wxh, Whh and bh sit inside every state. Each state also produces an output and a share of the loss. Backward, each state except the last receives error from two places.

Go backward from t = T - 1 to 0. Let dhₜ be the derivative of the loss with respect to hₜ, and dzₜ the derivative with respect to the value inside the tanh. A state is used twice: to read its own output, and to compute the next state. So dhₜ has two sources, and the second is zero only at the last step:

  • dhₜ = Whyᵀ · dlogitsₜ + Whhᵀ · dzₜ₊₁
  • dzₜ = dhₜ ⊙ (1 - hₜ²)
  • dWxh += dzₜ xₜᵀ, dWhh += dzₜ hₜ₋₁ᵀ, dbh += dzₜ

The last line uses += because each weight was used T times, and the derivative of a shared weight is the sum of the T terms. Why and by do not feed the recurrence, so their gradients come straight from the logits and hs[1:] in one product. The code keeps the second source in a vector dh_next, set to zeros before the loop and refilled at the end of every iteration.

Here is one run with real numbers: one hidden unit, two steps, and the second source marked.

Python
import numpy as np

Wxh, Whh = 0.5, 0.8                  # H = D = 1, no bias
Why = np.array([1.0, -1.0])          # two classes
xs, targets, h0 = [1.0, -1.0], [0, 1], 0.5
hs = [h0]
for x in xs:
    hs.append(np.tanh(Wxh * x + Whh * hs[-1]))

carried, dWhh, dWhh_no_carry = 0.0, 0.0, 0.0
for t in (1, 0):
    p = np.exp(Why * hs[t + 1])
    p /= p.sum()
    p[targets[t]] -= 1
    own = Why @ (p / 2)              # this step's output error; the loss is a mean over 2 steps
    slope = 1 - hs[t + 1] ** 2
    dWhh += (own + carried) * slope * hs[t]
    dWhh_no_carry += own * slope * hs[t]
    print(t, "own", round(own, 4), "carried", round(carried, 4))
    carried = Whh * (own + carried) * slope
print("dWhh", round(dWhh, 4), "without the carried error", round(dWhh_no_carry, 4))

At t = 1 the error comes from the output alone. At t = 0 the output sends -0.1927 and the carried error is +0.4268. The two have opposite signs, so ignoring the second source does not merely shrink dWhh: it gives 0.3353 instead of the correct 0.4392. A finite-difference check on the same numbers gives 0.4392.

The carried error is multiplied at every step by Whhᵀ and by a tanh slope that is at most 1. After k steps back it has passed through k such factors, and a product of many factors tends to grow or shrink geometrically.

How the error shrinks or grows going back
Norm of the error at each state when a unit error starts at the last one. Whh is s times an orthogonal matrix, so every direction is scaled by s. The vertical axis is logarithmic.
How the error shrinks or grows going back
Norm of the error at each state when a unit error starts at the last one. Whh is s times an orthogonal matrix, so every direction is scaled by s. The vertical axis is logarithmic.
Python
import numpy as np

rng = np.random.default_rng(0)
H, T = 4, 12
Q, _ = np.linalg.qr(rng.normal(size=(H, H)))   # orthogonal: it keeps lengths
Wxh = rng.normal(size=(H, 2)) * 0.02
xs = rng.normal(size=(T, 2))
for s in (0.5, 1.5):
    Whh = s * Q                                # every direction is scaled by s
    hs = [np.zeros(H)]
    for x in xs:
        hs.append(np.tanh(Wxh @ x + Whh @ hs[-1]))
    g, norms = np.ones(H) / 2, []
    for t in range(T - 1, -1, -1):             # error at the last state, sent back
        norms.append(np.linalg.norm(g))
        g = Whh.T @ (g * (1 - hs[t + 1] ** 2))
    print(s, [float(f"{n:.3g}") for n in (norms[0], norms[5], norms[11])])

With s = 0.5 the error is 0.0311 of its size five steps back and 0.000486 after eleven: early steps receive almost no signal. With s = 1.5 it has grown to 43.4. The middle curve stays flat only because these states are small, so the tanh slope is close to 1. A trained Whh does not scale every direction equally, and a saturated tanh has slope near zero, so treat the curves as an illustration of the mechanism, not a prediction for your network.

Exploding gradients have a cheap remedy. Compute the global norm, the square root of the sum of squares over every entry of every gradient array, and if it exceeds a limit multiply every array by max_norm / total_norm. One common factor keeps the direction of the whole gradient and only shortens it. Gradients within the limit are left alone: clipping never enlarges anything. With entries [3, 0] and [0, 4] the norm is 5, and a limit of 2.5 halves everything. Vanishing gradients cannot be repaired this way, and the next lesson's recurrent cell exists for that.

These are the mistakes that matter:

  • Leaving out dh_next. Each step then behaves as if the sequence ended there. A one-step sequence still passes, which hides it.
  • Writing = where += is needed, so that only one step's contribution survives.
  • Clipping every gradient on every call, or each array by its own norm. The first enlarges small gradients, the second changes the direction.
  • Reading the tanh slope from the wrong state, or using Whh where Whhᵀ belongs. Whh is square, so shapes cannot warn you about the second; only a gradient check can.

The hidden tests differentiate the same unrolled loop with PyTorch's autograd and compare all five gradients, and the public tests measure slopes of individual weights. PyTorch's clip_grad_norm_ divides by total_norm + 1e-6, so it agrees with your exact factor only to about six digits. These checks show your backward sweep matches the function you wrote. They do not show that the network can learn dependencies across many steps, which is a separate question about the model.

Watch & read

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