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 shows why: unrolling gives , so . Over forty steps, shrinks a gradient to , whereas inflates it to . 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 steps with shared recurrent parameters and average sequence loss . 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 nonlinearity (we restore immediately afterward). For a minibatch of sequences with step inputs , the linear RNN computes
with , , and . Figure 8.5.1 depicts three unrolled time steps of this network, showing the forward pass in grey and the backward pass in red.
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 , and one from the next state, through .
Let denote the gradient of the total loss with respect to . Because feeds into both its immediate output and the next hidden state , and backpropagating through a right-multiplication multiplies by the transposed weight matrix (Section 4.3), obeys the backward recursion
corresponding to the two incoming red arrows at each hidden state in Figure 8.5.1. Unrolling (8.5.2) backward from down to yields
Thus, the loss at future step communicates back to the state steps earlier through the power of (for a general nonlinear transition , this matrix power is replaced by the product of the intermediate state Jacobians ). Once are computed in a single backward sweep, the parameter gradients simply sum one outer product per step:
As we saw in Section 1.3.5 and Section 4.4, raising a matrix to the power scales each eigenvector by . Letting denote the spectral radius (largest ) of , the norm of scales asymptotically as : when , contributions from distant steps vanish exponentially; when , they explode exponentially. Reintroducing the activation multiplies each step's backward gradient entrywise by its local derivative before multiplying by . Because , never amplifies a gradient and pulls strongly toward vanishing whenever hidden units saturate near , while still permitting explosion if 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 , hidden size , 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 (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 , we step backward through time via and plot the geometric mean of the relative gradient norm as a function of the lag .
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 has a spectral radius near , 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 ), close to the rough estimate that multiplies the spectral radius by the average 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 tokens requires retaining all forward hidden states in memory and traversing all 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 and halting backpropagation at each segment boundary (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 (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 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 steps multiplies state Jacobians, which reduces in a linear RNN to , gradients explode when and vanish when . Including multiplies each step by , causing gradients in our trained RNN to fall below 1% within roughly eight steps despite . 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#
- Backward pass by hand. One step of
RNNScratch(Section 8.4.2) computes
Let be the gradient arriving from later steps and from the output at step .
- Derive the contributions of this step to , , , and as functions of , , , , and .
- Adding the output contribution at step to the contribution to gives a recursion for . Show that it reduces to (8.5.2) when the and the bias are dropped, and name the factor that the adds at every step. Explain also how the parameter gradients accumulate over the steps of a window, and compare with (8.5.4).
Adapted from CMU 11-785, Homework 3 Part 1.
-
Power iteration and alignment. Let be symmetric with eigenvalues and eigenvectors for , ordered so that .
- Show that has eigenvalues with the same eigenvectors.
- Show that for a random vector with independent standard normal entries, becomes aligned with as grows. State the condition on the eigenvalues that this requires and the sense in which the alignment holds.
- What does this imply for the gradient (8.5.3) of an RNN, beyond the change in its norm?
-
[code] Backward pass in code. ● Train
d2l.RNNLMScratchond2l.TimeMachineas in Section 8.4.2. Using the single-step gradients and the recursion of problem 1, implement the backward pass of itsRNNScratchcell 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 ofW_xh,W_hh, andb_hwith those computed by automatic differentiation.Adapted from CMU 11-785, Homework 3 Part 1.
-
[code] Nonlinear Jacobians. ● Draw a random symmetric matrix, rescale it to spectral radius , and plot the norm of its power against on a logarithmic axis: three straight lines, as the eigenvalues predict. Then leave the symmetric linear case.
- Replace the symmetric matrix by a general, nonsymmetric rescaled to each radius, and plot against . Report the largest value of at and the lag at which it occurs. Explain why the ratio can exceed one and why it stays bounded as grows (a random matrix is diagonalizable with probability one).
- Return to the symmetric and run the RNN
for a single sequence () with inputs whose entries are drawn independently from . Plot the norm of the product of the Jacobians along the trajectory for and . How do the nonlinearity and the input scale change the growth of the norm, and why?
-
Explain why a largest singular value of 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 curves at and .
-
[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.
- 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). - Retrain with
num_stepsset to 128, measure the gradient against the lag on stretches of 256 validation tokens, and compare the result with your prediction. - 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?
- Before running anything: if the model is retrained with