8.5 Backpropagation Through Time

Our experiments with the RNN language model in Section 8.4.2 left us with two striking empirical findings: without gradient clipping, most training runs destabilized; with clipping, training converged reliably, yet the learned network used only the last few tokens of its 32-token context window. Both phenomena share the exact same mathematical root. Because a recurrent network applies the same weight matrix at every time step, any gradient propagating backward through a sequence is multiplied by a state Jacobian at each step. Over many steps these factors compound, much like compound interest, causing the gradient to grow or shrink geometrically.

Even a scalar recurrence ht=whht−1+xth_t = w_\textrm{h} h_{t-1} + x_t shows why: unrolling gives ht=∑s≤twht−sxsh_t = \sum_{s \leq t} w_\textrm{h}^{t-s} x_s, so ∂ht/∂ht−k=whk\partial h_t / \partial h_{t-k} = w_\textrm{h}^k. Over forty steps, wh=0.9w_\textrm{h} = 0.9 shrinks a gradient to 0.940≈0.0150.9^{40} \approx 0.015, whereas wh=1.1w_\textrm{h} = 1.1 inflates it to 1.140≈451.1^{40} \approx 45. Exploding gradients destabilize optimization immediately, forcing us to clip updates; vanishing gradients are quieter yet more insidious, attenuating error signals from distant tokens until the model cannot learn long-range dependencies.

Computing gradients in an RNN requires no new differentiation algorithm: we unroll the recurrence across time into a deep feedforward network with shared weights and apply standard backpropagation (Section 4.3), a procedure known as backpropagation through time (BPTT) (Werbos, 1990). Below, we derive the backward recursion directly in matrix form, measure how far gradients actually travel inside our trained RNN from Section 8.4.2, and examine truncated backpropagation through time.

8.5.1 Vanishing and Exploding Gradients#

Consider an RNN unrolled across TT steps with shared recurrent parameters and average sequence loss L=1T∑t=1Tl(yt,ot)L = \frac{1}{T}\sum_{t=1}^T l(\mathbf{y}_t, \mathbf{o}_t). Backpropagation handles weight sharing by summing the local gradient contributions from every time step where a weight matrix appears. To see the structure of the backward pass transparently, take the RNN of Section 8.4 and temporarily omit biases and the tanh⁡\tanh nonlinearity (we restore tanh⁡\tanh immediately afterward). For a minibatch of bb sequences with step inputs Xt∈Rb×d\mathbf{X}_t \in \mathbb{R}^{b\times d}, the linear RNN computes

Ht=XtWxh+Ht−1Whh,Ot=HtWhq,(8.5.1)\begin{aligned} \mathbf{H}_t &= \mathbf{X}_t \mathbf{W}_\textrm{xh} + \mathbf{H}_{t-1}\mathbf{W}_\textrm{hh}, \\ \mathbf{O}_t &= \mathbf{H}_t \mathbf{W}_\textrm{hq}, \end{aligned} \tag{8.5.1}

with Wxh∈Rd×h\mathbf{W}_\textrm{xh}\in\mathbb{R}^{d\times h}, Whh∈Rh×h\mathbf{W}_\textrm{hh}\in\mathbb{R}^{h\times h}, and Whq∈Rh×q\mathbf{W}_\textrm{hq}\in\mathbb{R}^{h\times q}. Figure 8.5.1 depicts three unrolled time steps of this network, showing the forward pass in grey and the backward pass in red.

Figure 8.5.1:

Forward pass (grey) and backward pass (red) of a linear RNN unrolled over three time steps. The gradient that reaches each hidden state except the last is the sum of two red arrows: one from its own output, through Whq⊤\mathbf{W}_\textrm{hq}^\top, and one from the next state, through Whh⊤\mathbf{W}_\textrm{hh}^\top.

Let Gt=∂L/∂Ht\mathbf{G}_t = \partial L/\partial \mathbf{H}_t denote the gradient of the total loss with respect to Ht\mathbf{H}_t. Because Ht\mathbf{H}_t feeds into both its immediate output Ot\mathbf{O}_t and the next hidden state Ht+1\mathbf{H}_{t+1}, and backpropagating through a right-multiplication multiplies by the transposed weight matrix (Section 4.3), Gt\mathbf{G}_t obeys the backward recursion

Gt=∂L∂OtWhq⊤+Gt+1Whh⊤,GT+1=0,(8.5.2)\begin{aligned} \mathbf{G}_t &= \frac{\partial L}{\partial \mathbf{O}_t}\mathbf{W}_\textrm{hq}^\top + \mathbf{G}_{t+1}\mathbf{W}_\textrm{hh}^\top, \\ \mathbf{G}_{T+1} &= \mathbf{0}, \end{aligned} \tag{8.5.2}

corresponding to the two incoming red arrows at each hidden state in Figure 8.5.1. Unrolling (8.5.2) backward from GT\mathbf{G}_T down to Gt\mathbf{G}_t yields

Gt=∑j=tT∂L∂Oj Whq⊤(Whh⊤)j−t.(8.5.3)\mathbf{G}_t = \sum_{j=t}^{T} \frac{\partial L}{\partial \mathbf{O}_j}\, \mathbf{W}_\textrm{hq}^\top\big(\mathbf{W}_\textrm{hh}^\top\big)^{j-t}. \tag{8.5.3}

Thus, the loss at future step jj communicates back to the state k=j−tk = j - t steps earlier through the kthk^\textrm{th} power of Whh⊤\mathbf{W}_\textrm{hh}^\top (for a general nonlinear transition Ht=g(Ht−1,Xt,Whh)\mathbf{H}_t = g(\mathbf{H}_{t-1}, \mathbf{X}_t, \mathbf{W}_\textrm{hh}), this matrix power is replaced by the product of the j−tj - t intermediate state Jacobians ∏i=t+1j∂Hi/∂Hi−1\prod_{i=t+1}^j \partial \mathbf{H}_i / \partial \mathbf{H}_{i-1}). Once G1,…,GT\mathbf{G}_1, \ldots, \mathbf{G}_T are computed in a single backward sweep, the parameter gradients simply sum one outer product per step:

∂L∂Whh=∑t=1THt−1⊤Gt,∂L∂Wxh=∑t=1TXt⊤Gt.(8.5.4)\begin{aligned} \frac{\partial L}{\partial \mathbf{W}_\textrm{hh}} &= \sum_{t=1}^{T} \mathbf{H}_{t-1}^\top \mathbf{G}_t, \\ \frac{\partial L}{\partial \mathbf{W}_\textrm{xh}} &= \sum_{t=1}^{T} \mathbf{X}_t^\top \mathbf{G}_t. \end{aligned} \tag{8.5.4}

As we saw in Section 1.3.5 and Section 4.4, raising a matrix to the kthk^\textrm{th} power scales each eigenvector by λk\lambda^k. Letting ρ\rho denote the spectral radius (largest ∣λ∣|\lambda|) of Whh\mathbf{W}_\textrm{hh}, the norm of (Whh⊤)k(\mathbf{W}_\textrm{hh}^\top)^k scales asymptotically as ρk\rho^k: when ρ<1\rho \lt 1, contributions from distant steps vanish exponentially; when ρ>1\rho > 1, they explode exponentially. Reintroducing the tanh⁡\tanh activation multiplies each step's backward gradient entrywise by its local derivative 1−Ht2∈(0,1]1 - \mathbf{H}_t^2 \in (0, 1] before multiplying by Whh⊤\mathbf{W}_\textrm{hh}^\top. Because 1−h2≤11 - h^2 \leq 1, tanh⁡\tanh never amplifies a gradient and pulls strongly toward vanishing whenever hidden units saturate near ±1\pm 1, while still permitting explosion if Whh\mathbf{W}_\textrm{hh} is large and activations stay near zero.

Let us measure what actually happens inside our trained language model from Section 8.4.2. We first load the TimeMachine dataset with 32-token windows.

data = d2l.TimeMachine(batch_size=1024, num_steps=32)

Next, we instantiate the from-scratch recurrent language model RNNLMScratch with embedding dimension d=512d = 512, hidden size h=128h = 128, and dropout.

rnn = d2l.RNNScratch(num_inputs=512, num_hiddens=128)
model = d2l.RNNLMScratch(rnn, vocab_size=len(data.vocab), lr=4, dropout=0.5,
                         emb_dropout=0.1)

We train model for 10 epochs with learning rate lr=4 and global gradient clipping at gradient_clip_val=1.

trainer = d2l.Trainer(max_epochs=10, gradient_clip_val=1, num_gpus=1)
trainer.fit(model, data)

To probe gradient flow over a longer horizon, we sample 256 random validation segments seqs of length L=64L = 64 (twice the training window) along with their following tokens targets.

L = 64
val = d2l.numpy(data.X[data.num_train:data.num_train + data.num_val, 0])
starts = np.random.default_rng().choice(len(val) - L, 256, replace=False)
seqs = np.stack([val[s:s + L] for s in starts])  # (256, L) token ids
targets = val[starts + L]                        # The token after each stretch

We now run model.rnn forward across seqs to collect all 64 per-step hidden states in H, the final-step logits, and the weight matrices W_hh and W_hq.

with torch.inference_mode():
    states, _ = model.rnn(model.embedding(
        d2l.tensor(seqs, device=d2l.try_gpu())))
    logits = model.output_layer(states[-1:])[:, 0]  # The last step only
H, logits = d2l.numpy(d2l.stack(states, 0)), d2l.numpy(logits)
W_hh, W_hq = d2l.numpy(model.rnn.W_hh), d2l.numpy(model.W_hq)

Starting from the final-step loss gradient ∂LL/∂OL=softmax(OL)−YL\partial L_L / \partial \mathbf{O}_L = \textrm{softmax}(\mathbf{O}_L) - \mathbf{Y}_L, we step backward through time via Gt−1=(Gt⊙(1−Ht2))Whh⊤\mathbf{G}_{t-1} = (\mathbf{G}_t \odot (1 - \mathbf{H}_t^2))\mathbf{W}_\textrm{hh}^\top and plot the geometric mean of the relative gradient norm ∥GL−k∥/∥GL∥\|\mathbf{G}_{L-k}\| / \|\mathbf{G}_L\| as a function of the lag kk.

P = np.exp(logits - logits.max(1, keepdims=True))
P /= P.sum(1, keepdims=True)
P[np.arange(len(targets)), targets] -= 1  # dL/dO: softmax minus one-hot
G = (P @ W_hq.T).astype(np.float64)       # dL/dH at the last step
norms = []
for t in range(L - 1, -1, -1):            # Backward through time
    norms.append(np.linalg.norm(G, axis=1))
    G = (G * (1 - H[t] ** 2)) @ W_hh.T    # Through the tanh, then W_hh
rel = np.exp(np.log(np.array(norms) / norms[0]).mean(1))
print(f'spectral radius of W_hh: {np.abs(np.linalg.eigvals(W_hh)).max():.2f}; '
      f'mean tanh derivative: {(1 - H ** 2).mean():.2f}')
print('relative gradient norm at lags 1, 2, 4, 8, 16, 32:',
      [float(f'{rel[k]:.2g}') for k in (1, 2, 4, 8, 16, 32)])
d2l.plot(np.arange(L), rel, 'lag $k$', 'relative gradient norm',
         yscale='log', figsize=(4.5, 3))
spectral radius of W_hh: 1.82; mean tanh derivative: 0.27
relative gradient norm at lags 1, 2, 4, 8, 16, 32: [0.66, 0.35, 0.099, 0.0081, 5.7e-05, 3e-09]

Even though the trained Whh\mathbf{W}_\textrm{hh} has a spectral radius near 1.81.8, which would explode in a purely linear recurrence, the actual gradient vanishes rapidly: it drops below 1% of its initial norm within roughly eight steps and shrinks to a few billionths across 32 tokens. Each backward step retains a little over half of the gradient norm (the printed value at lag 8 gives 0.0081/8≈0.550.008^{1/8} \approx 0.55), close to the rough estimate 1.8×0.27≈0.51.8 \times 0.27 \approx 0.5 that multiplies the spectral radius by the average tanh⁡\tanh derivative. This decay is consistent with our finding in Section 8.4.2 that per-position validation loss flattens out after two or three tokens of context, but it does not prove that vanishing gradients are the cause. At lags 2 and 4 the gradient still has about a third and a tenth of its size, an attenuation that SGD routinely learns through, and the Kneser--Ney counts of Section 8.4.2 saturate at the same context length without using gradients at all. What the decay does rule out is learning from tokens much further back, whatever the data may hold.

8.5.1.1 Remedies for Exploding and Vanishing Gradients#

Exploding and vanishing gradients demand fundamentally different remedies. Because an exploding gradient threatens to corrupt the parameters in a single oversized update, global gradient clipping (Section 8.4) provides a simple safeguard—yet multiplying the entire gradient sum (8.5.3) by a scalar never changes the relative weight of distant versus recent lags. Overcoming vanishing gradients therefore requires changing the recurrence itself so that state Jacobians stay near unity along memory directions: either via gated recurrent cells (such as LSTMs and GRUs) that create an additive memory path controlled by learned gates, or via structured linear recurrences and state space models that remove the state nonlinearity and constrain eigenvalues near the unit circle. Both families are developed in Chapter 12.

8.5.2 Truncated Backpropagation Through Time#

Evaluating (8.5.2) across an entire corpus of TT tokens requires retaining all TT forward hidden states in memory and traversing all TT steps for a single parameter update. Truncated backpropagation through time caps both memory and compute per update by slicing long streams into fixed-length segments of length T0T_0 and halting backpropagation at each segment boundary (Figure 8.5.2).

Figure 8.5.2:

Full and truncated backpropagation through time over a token sequence. Both run the same forward pass (grey). Full backpropagation sends the gradient (red) back along the entire sequence. Truncation cuts the sequence into segments of four tokens and detaches the state at each boundary: its value crosses into the next segment, but no gradient flows back across.

Whether each window resets H0=0\mathbf{H}_0 = \mathbf{0} (as in Section 8.4.2) or carries the previous segment's final state forward while detaching it from the computational graph (as in Figure 8.5.2), no gradient ever crosses a segment boundary, imposing a hard learning horizon of at most T0T_0 steps (Jaeger, 2002). In a vanilla RNN, however, vanishing gradients already choke off the backward signal after roughly eight steps, well inside our 32-token window, so lengthening the window alone cannot extend the model's effective memory.

8.5.3 Summary#

Backpropagation through time applies ordinary backpropagation to an unrolled RNN, propagating loss sensitivities backward via (8.5.2) and summing parameter gradients across time steps ((8.5.4)). Because a gradient traveling back kk steps multiplies kk state Jacobians, which reduces in a linear RNN to (Whh⊤)k∼ρk(\mathbf{W}_\textrm{hh}^\top)^k \sim \rho^k, gradients explode when ρ>1\rho > 1 and vanish when ρ<1\rho \lt 1. Including tanh⁡\tanh multiplies each step by 1−Ht2∈(0,1]1 - \mathbf{H}_t^2 \in (0, 1], causing gradients in our trained RNN to fall below 1% within roughly eight steps despite ρ≈1.8\rho \approx 1.8. Gradient clipping contains exploding spikes, truncated BPTT bounds memory and compute per update, and architectural innovations (Chapter 12) are required to preserve gradients over long horizons.

8.5.4 Exercises#

  1. Backward pass by hand. One step of RNNScratch (Section 8.4.2) computes
Ht=tanh⁡(XtWxh+Ht−1Whh+bh).\mathbf{H}_t = \tanh(\mathbf{X}_t \mathbf{W}_{\textrm{xh}} + \mathbf{H}_{t-1} \mathbf{W}_{\textrm{hh}} + \mathbf{b}_\textrm{h}).

Let Gt=∂L/∂Ht\mathbf{G}_t = \partial L / \partial \mathbf{H}_t be the gradient arriving from later steps and from the output at step tt.

  1. Derive the contributions of this step to ∂L/∂Wxh\partial L / \partial \mathbf{W}_{\textrm{xh}}, ∂L/∂Whh\partial L / \partial \mathbf{W}_{\textrm{hh}}, ∂L/∂bh\partial L / \partial \mathbf{b}_\textrm{h}, and ∂L/∂Ht−1\partial L / \partial \mathbf{H}_{t-1} as functions of Gt\mathbf{G}_t, Xt\mathbf{X}_t, Ht\mathbf{H}_t, Ht−1\mathbf{H}_{t-1}, and Whh\mathbf{W}_{\textrm{hh}}.
  2. Adding the output contribution at step t−1t-1 to the contribution to ∂L/∂Ht−1\partial L / \partial \mathbf{H}_{t-1} gives a recursion for Gt−1\mathbf{G}_{t-1}. Show that it reduces to (8.5.2) when the tanh⁡\tanh and the bias are dropped, and name the factor that the tanh⁡\tanh adds at every step. Explain also how the parameter gradients accumulate over the TT steps of a window, and compare with (8.5.4).

Adapted from CMU 11-785, Homework 3 Part 1.

  1. Power iteration and alignment. Let M∈Rh×h\mathbf{M} \in \mathbb{R}^{h \times h} be symmetric with eigenvalues λi\lambda_i and eigenvectors vi\mathbf{v}_i for i=1,…,hi = 1, \ldots, h, ordered so that ∣λi∣≥∣λi+1∣|\lambda_i| \geq |\lambda_{i+1}|.

    1. Show that Mk\mathbf{M}^k has eigenvalues λik\lambda_i^k with the same eigenvectors.
    2. Show that for a random vector x∈Rh\mathbf{x} \in \mathbb{R}^h with independent standard normal entries, Mkx\mathbf{M}^k \mathbf{x} becomes aligned with v1\mathbf{v}_1 as kk grows. State the condition on the eigenvalues that this requires and the sense in which the alignment holds.
    3. What does this imply for the gradient (8.5.3) of an RNN, beyond the change in its norm?
  2. [code] Backward pass in code. ● Train d2l.RNNLMScratch on d2l.TimeMachine as in Section 8.4.2. Using the single-step gradients and the recursion of problem 1, implement the backward pass of its RNNScratch cell over a full window with tensor operations only, starting from the gradient of the loss with respect to the logits (Section 3.1.2.2). Run it on one training minibatch, and compare your gradients of W_xh, W_hh, and b_h with those computed by automatic differentiation.

    Adapted from CMU 11-785, Homework 3 Part 1.

  3. [code] Nonlinear Jacobians. ● Draw a random symmetric 100×100100 \times 100 matrix, rescale it to spectral radius ρ∈{0.9,1.0,1.1}\rho \in \{0.9, 1.0, 1.1\}, and plot the norm of its kthk^\textrm{th} power ∥Jk∥\|\mathbf{J}^k\| against kk on a logarithmic axis: three straight lines, as the eigenvalues predict. Then leave the symmetric linear case.

    1. Replace the symmetric matrix by a general, nonsymmetric Whh\mathbf{W}_\textrm{hh} rescaled to each radius, and plot ∥Jk∥\|\mathbf{J}^k\| against kk. Report the largest value of ∥Jk∥\|\mathbf{J}^k\| at ρ=0.9\rho = 0.9 and the lag at which it occurs. Explain why the ratio ∥Jk∥/ρk\|\mathbf{J}^k\| / \rho^k can exceed one and why it stays bounded as kk grows (a random matrix is diagonalizable with probability one).
    2. Return to the symmetric Whh\mathbf{W}_\textrm{hh} and run the tanh⁡\tanh RNN
Ht=tanh⁡(Ht−1Whh+Xt),H0=0,(8.5.5)\mathbf{H}_t = \tanh(\mathbf{H}_{t-1}\mathbf{W}_\textrm{hh} + \mathbf{X}_t), \qquad \mathbf{H}_0 = \mathbf{0}, \tag{8.5.5}

for a single sequence (Ht∈R1×h\mathbf{H}_t \in \mathbb{R}^{1 \times h}) with inputs Xt\mathbf{X}_t whose entries are drawn independently from N(0,s2)\mathcal{N}(0, s^2). Plot the norm of the product of the Jacobians ∂Hj/∂Hj−1\partial \mathbf{H}_j / \partial \mathbf{H}_{j-1} along the trajectory for s=0.1s = 0.1 and s=1s = 1. How do the nonlinearity and the input scale change the growth of the norm, and why?

  1. Explain why a largest singular value of Whh\mathbf{W}_\textrm{hh} below one is sufficient for the product to shrink, whereas a largest singular value above one is necessary but not sufficient for it to grow (Bengio et al., 1994; Pascanu et al., 2013). Relate the argument to your tanh⁡\tanh curves at ρ=0.9\rho = 0.9 and ρ=1.1\rho = 1.1.

  2. [code] Window length and memory horizon. ● In the model of Section 8.5.1, the gradient of the last loss falls below 1% of its size within about eight steps, well inside the training window of 32 tokens.

    1. Before running anything: if the model is retrained with num_steps=128, do you expect this horizon to move? Argue from the product of state Jacobians in (8.5.3).
    2. Retrain with num_steps set to 128, measure the gradient against the lag on stretches of 256 validation tokens, and compare the result with your prediction.
    3. Repeat the loss-by-position measurement of Section 8.4.2 for the retrained model. Does the loss now keep improving beyond the third token of context?

Discussions