Backpropagation Through Time

Dive into Deep Learning · §8.5

Backpropagation Through Time
unrolled computational graphs · Jacobian products · matrix powers & spectral radius · vanishing vs. exploding gradients · truncated BPTT

Two Empirical Mysteries with One Mathematical Root

Motivation & Scalar Intuition

\frac{\partial h_t}{\partial h_{t-k}} = w_{\textrm{h}}^k

  • Compound multiplication through time: In a 1D linear recurrence h_t = w_{\textrm{h}} h_{t-1} + x_t, sensitivity across lag k scales geometrically as w_{\textrm{h}}^k.
  • The 40-step razor’s edge: At w_{\textrm{h}} = 0.9, a gradient traveling back 40 steps shrinks to 0.9^{40} \approx 0.015 (vanishing); at w_{\textrm{h}} = 1.1, it inflates to 1.1^{40} \approx 45.3 (exploding).
  • Backpropagation Through Time (BPTT): Unrolling the recurrence across T steps and applying reverse-mode autodiff explains both phenomena in matrix form.

Unrolling a Recurrence into a Shared-Weight Graph

Computational Graph Structure

\frac{\partial L}{\partial w_{\textrm{h}}} = \frac{1}{T}\sum_{t=1}^T \frac{\partial l(y_t, o_t)}{\partial o_t}\,\frac{\partial o_t}{\partial h_t}\,\frac{\partial h_t}{\partial w_{\textrm{h}}}

  • Weight tying across depth: Unrolling across T steps yields a depth-T network where w_{\textrm{h}} is shared at every step t \in \{1, \ldots, T\}.
  • Total derivative under weight sharing: By the multivariable chain rule, w_{\textrm{h}} accumulates the sum of its local gradient paths across all T steps.
  • Recursive sensitivity: Changing w_{\textrm{h}} alters h_t = g(h_{t-1}, x_t, w_{\textrm{h}}) both directly at step t and indirectly through h_{t-1}.

Chain Rule Over Time: Forward Sensitivity Recursion

Jacobian Product Expansion

\frac{\partial h_t}{\partial w_{\textrm{h}}} = \frac{\partial g_t}{\partial w_{\textrm{h}}} + \sum_{i=1}^{t-1}\left(\prod_{j=i+1}^t \frac{\partial g_j}{\partial h_{j-1}}\right)\frac{\partial g_i}{\partial w_{\textrm{h}}}

  • First-order sensitivity recursion: Applying the chain rule gives \frac{\partial h_t}{\partial w_{\textrm{h}}} = u_t + c_t \frac{\partial h_{t-1}}{\partial w_{\textrm{h}}} with immediate effect u_t = \partial g_t / \partial w_{\textrm{h}} and step Jacobian c_t = \partial g_t / \partial h_{t-1}.
  • Why reverse-mode BPTT wins: Evaluating \prod_{j=i+1}^t c_j separately for every pair (i, t) would cost O(T^2) Jacobian products; reverse-mode autodiff factors the sum backward in a single O(T) sweep.

Forward and Backward Flows in an Unrolled Linear RNN

Matrix BPTT Setup

To see the exact matrix structure of the backward sweep, consider a minibatch linear RNN (\phi = \textrm{id}, zero biases) with inputs \mathbf{X}_t \in \mathbb{R}^{b \times d}, states \mathbf{H}_t \in \mathbb{R}^{b \times h}, and outputs \mathbf{O}_t \in \mathbb{R}^{b \times q}:

  • Forward equations (grey arrows): \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}}
  • Two outgoing children per hidden state: In the unrolled graph, each state \mathbf{H}_t (for t < T) feeds into two downstream nodes: its immediate output \mathbf{O}_t (via \mathbf{W}_{\textrm{hq}}) and the next state \mathbf{H}_{t+1} (via \mathbf{W}_{\textrm{hh}}).
  • Backward flow (red arrows): By reverse-mode differentiation, the adjoint \mathbf{G}_t = \partial L / \partial \mathbf{H}_t is the sum of the two incoming red arrows at node \mathbf{H}_t.

The Backward Recursion for Hidden-State Gradients

Reverse-Mode Dynamic Program

\mathbf{G}_t = \frac{\partial L}{\partial \mathbf{O}_t}\mathbf{W}_{\textrm{hq}}^\top + \mathbf{G}_{t+1}\mathbf{W}_{\textrm{hh}}^\top

  • Two incoming paths at \mathbf{H}_t: Because \mathbf{H}_t feeds both \mathbf{O}_t and \mathbf{H}_{t+1}, its adjoint \mathbf{G}_t = \partial L / \partial \mathbf{H}_t \in \mathbb{R}^{b \times h} sums the local output sensitivity and the backpropagated future adjoint (with \mathbf{G}_{T+1} = \mathbf{0}).
  • Single O(T) backward sweep: Each step from t = T down to 1 requires just one (b \times h) \times (h \times h) GEMM by \mathbf{W}_{\textrm{hh}}^\top.

Unrolling G_t: Matrix Powers Across Time Lags

Explicit Matrix Power Expansion

\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}

\frac{\partial L}{\partial \mathbf{W}_{\textrm{hh}}} = \sum_{t=1}^T \mathbf{H}_{t-1}^\top \mathbf{G}_t, \quad \frac{\partial L}{\partial \mathbf{W}_{\textrm{xh}}} = \sum_{t=1}^T \mathbf{X}_t^\top \mathbf{G}_t

  • The lag-k operator: A loss signal at step j traverses the k^\textrm{th} matrix power (\mathbf{W}_{\textrm{hh}}^\top)^k (k = j - t) to reach \mathbf{H}_t.
  • Outer-product accumulation: Once \mathbf{G}_{1:T} are computed, weight gradients sum one outer product per step.

Spectral Radius Governs Matrix Power Growth

Eigenvalue & Singular-Value Analysis

  • Asymptotic exponential scaling (\|(\mathbf{W}_{\textrm{hh}}^\top)^k\| \sim \rho^k): Letting \rho = \max_i |\lambda_i(\mathbf{W}_{\textrm{hh}})| denote the spectral radius, raising \mathbf{W}_{\textrm{hh}}^\top to the k^\textrm{th} power scales each eigenvector by \lambda_i^k:
    • Vanishing (\rho < 1): \|(\mathbf{W}_{\textrm{hh}}^\top)^k\| \to 0 exponentially.
    • Exploding (\rho > 1): Leading eigenspace grows as \rho^k \to \infty.
    • Critical boundary (\rho = 1): Only |\lambda_i| = 1 preserves norm over long horizons.
  • Transient non-normal growth: If \mathbf{W}_{\textrm{hh}} is asymmetric with \sigma_{\max}(\mathbf{W}_{\textrm{hh}}) > 1 > \rho, norms can hump at small lags before \rho^k decays.

How the tanh Nonlinearity Contrasts with Linear BPTT

Nonlinear State Jacobians

\mathbf{G}_{t-1} = \frac{\partial L}{\partial \mathbf{O}_{t-1}}\mathbf{W}_{\textrm{hq}}^\top + \Big(\mathbf{G}_t \odot \big(1 - \mathbf{H}_t^2\big)\Big)\mathbf{W}_{\textrm{hh}}^\top

  • Strict local contraction: Because H_{t,i} \in (-1, 1), every entry of \tanh'(z) = 1 - \mathbf{H}_t^2 lies in (0, 1] and never amplifies a gradient.
  • Saturation accelerates vanishing: Whenever a hidden unit saturates near \pm 1, 1 - H_{t,i}^2 \approx 0 chokes off backward gradient flow.
  • Effective step multiplier: Even when \rho(\mathbf{W}_{\textrm{hh}}) > 1, the net per-step factor \overline{(1 - H^2)} \cdot \rho(\mathbf{W}_{\textrm{hh}}) can fall well below 1.

Setting Up the Gradient Horizon Experiment (L = 64)

Empirical Probe on Our Trained RNN

To measure how far gradients actually travel inside our trained language model from §8.4 (d = 512, h = 128, dropout 0.5, clipped at \theta = 1), we run the trained network forward over 256 validation segments of length L = 64 tokens:

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
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)
  • Isolating the lag-k sensitivity: We take the cross-entropy loss at the final position t = L and propagate \mathbf{G}_t backward 64 steps via \mathbf{G}_{t-1} = (\mathbf{G}_t \odot (1 - \mathbf{H}_t^2))\mathbf{W}_{\textrm{hh}}^\top without adding intermediate output losses.

Measured Gradient Decay Inside the Trained RNN

Empirical Probe Results

Plotting the geometric-mean relative gradient norm \|\mathbf{G}_{L-k}\| / \|\mathbf{G}_L\| against lag k \in \{0, \ldots, 63\} explains the short horizon from §8.4:

  • Large weights, fast vanishing: Although \rho(\mathbf{W}_{\textrm{hh}}) \approx 1.80, \tanh saturation lowers the mean derivative to \overline{1 - H^2} \approx 0.27.
  • \approx 0.55\times per step: Gradients shrink by nearly half per step (1.80 \times 0.27 \approx 0.49), falling below 1\% by lag k = 8 and to \sim 10^{-9} by lag 32.
  • Short effective memory: Lags 2–4 retain 10\text{--}35\% of the signal (where Kneser–Ney also saturates); beyond lag 8, almost no gradient reaches \mathbf{W}_{\textrm{hh}}.

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]

Why Gradient Clipping Fixes Explosion, Not Vanishing

Asymmetry of the Two Gradient Pathologies

\mathbf{G}_t = \sum_{j=t}^T \frac{\partial L}{\partial \mathbf{O}_j}\mathbf{W}_{\textrm{hq}}^\top \prod_{i=t+1}^j \mathbf{J}_i

  • What clipping fixes (Exploding spikes): When an unsaturated trajectory causes \|\mathbf{g}\| \gg \theta, rescaling by \theta/\|\mathbf{g}\| caps the step size at \eta\theta so parameters cannot diverge.
  • What clipping cannot fix (Vanishing ratios): Multiplying the entire gradient sum \mathbf{g} by a single scalar rescales lag-0 and lag-20 terms equally—leaving the 1 : 10^{-6} ratio between short-range and long-range signals unchanged.

Architectural Remedies: Gates and Linear Recurrences

Preview of the State Space Models Chapter

Overcoming vanishing gradients requires redesigning the recurrent state transition g so that the step-to-step Jacobian \mathbf{J}_t = \partial \mathbf{H}_t / \partial \mathbf{H}_{t-1} has eigenvalues near 1 along memory directions:

Architectural Family Core State Transition Mechanism Why State Jacobians Stay Near Unity (\mathbf{J}_t \approx \mathbf{I})
Vanilla \tanh RNN (§8.4) \mathbf{H}_t = \tanh(\mathbf{X}_t\mathbf{W}_{\textrm{xh}} + \mathbf{H}_{t-1}\mathbf{W}_{\textrm{hh}} + \mathbf{b}_{\textrm{h}}) \mathbf{J}_t = \textrm{diag}(1 - \mathbf{H}_t^2)\mathbf{W}_{\textrm{hh}}^\top contracts by \sim 0.5\times per step whenever units saturate
Gated RNNs (LSTM, GRU — Gated Recurrent Networks section) Additive cell state \mathbf{C}_t = \mathbf{F}_t \odot \mathbf{C}_{t-1} + \mathbf{I}_t \odot \tilde{\mathbf{C}}_t with learned sigmoid gates \mathbf{F}_t \in (0, 1)^h When forget gate \mathbf{F}_t \approx \mathbf{1}, \partial \mathbf{C}_t / \partial \mathbf{C}_{t-1} = \textrm{diag}(\mathbf{F}_t) \approx \mathbf{I}, creating an unattenuated gradient highway
Structured State Space Models (SSMs / Linear RNNs — Linear Recurrences and State Space Models sections) Linear state recurrence \mathbf{h}_t = \mathbf{A}\mathbf{h}_{t-1} + \mathbf{B}\mathbf{x}_t with nonlinear readout layers Removes recurrent \tanh saturation altogether and constrains eigenvalues of \mathbf{A} near the unit disk (|\lambda_i| \le 1)

The Memory and Compute Cost of Full-Sequence BPTT

Systems Bottleneck on Long Streams

  • Activation memory grows linearly with T (O(Tbh)): Evaluating the backward pass at step t requires both \mathbf{H}_t (for 1 - \mathbf{H}_t^2) and \mathbf{H}_{t-1} (for \mathbf{H}_{t-1}^\top \mathbf{G}_t). Reverse-mode autodiff must retain all T states in VRAM until the backward sweep finishes.
  • Update latency scales as O(T): Full BPTT across The Time Machine (T = 65{,}741 tokens) would run 65{,}741 forward and 65{,}741 backward steps for a single weight update.

Truncated BPTT: Detaching State Across Segments

Bounding Memory and Compute per Update

Truncated Backpropagation Through Time (TBPTT) slices a long sequence into fixed segments of length T_0 (e.g., T_0 = 32 tokens) and halts the backward pass at each segment boundary:

  • Forward state carries over, backward gradient stops: When streaming through contiguous segments, the final state \mathbf{H}_{T_0} is passed as the initial state of the next segment after detaching it from the autograd graph (stopping its gradient).
  • O(T_0 bh) memory and frequent updates: Autograd frees each segment’s computation graph immediately after its update, bounding memory to T_0 states.

Statistical Trade-Offs of Truncation Horizons

What Truncation Sacrifices

Truncating backpropagation to windows of length T_0 trades long-range gradient credit assignment for bounded memory and parallel minibatch shuffling:

  • Hard credit-assignment horizon of T_0 steps: Within a segment of length T_0 = 32, the loss at position j \in \{1, \ldots, 32\} backpropagates through j - 1 steps within that segment (at most 31 steps, 15.5 steps on average) and never sends gradient across the detached boundary into the preceding segment.
  • Zero-state windows vs. detached streaming: In §8.4, d2l.TimeMachine sampled shuffled 32-token windows starting from \mathbf{H}_0 = \mathbf{0} so minibatches are i.i.d. for SGD; stateful streaming carries \mathbf{H}_{T_0} across segments for inference context but still blocks gradients at T_0.
  • Which horizon binds first? In our vanilla \tanh RNN, gradients already vanish below 1\% by lag k = 8 \ll T_0 = 32—so the cell’s Jacobian decay, not the 32-token window, is the active bottleneck.

Concept Check: BPTT Jacobians, Clipping & Detach

Check Your Understanding

Test your understanding of matrix powers, graph detachment, and gradient horizons:

  1. Sensitivity Across a 32-Token Window: In a linear RNN over a window of T_0 = 32 tokens, how many step Jacobians separate the final loss at t = 32 from the initial state \mathbf{H}_1, and by what factor does that sensitivity scale if \rho(\mathbf{W}_{\textrm{hh}}) = 0.9 versus \rho(\mathbf{W}_{\textrm{hh}}) = 1.1?
  2. The Missing Detach Bug: Suppose you train an RNN over 1,000 consecutive 32-token segments on a GPU, carrying state from segment s into segment s+1, but you forget to detach state (stop its gradient) at the end of each segment. What happens to GPU memory and backward runtime on segment s = 1, 2, 3, \ldots?
  3. Widening the Window on a Vanilla RNN: If you retrain our vanilla \tanh RNN from §8.4 with num_steps = 128 instead of num_steps = 32, will its validation loss-by-position curve keep improving beyond token 3? Why or why not?

Concept Check: BPTT Jacobians, Clipping & Detach (Answers)

Check Your Understanding

Answers:

  1. 31 Jacobians: At \rho = 0.9, 0.9^{31} \approx 0.038 (96\% lost); at \rho = 1.1, 1.1^{31} \approx 19.2. Shifting \rho by \pm 10\% around 1.0 changes the 32-step gradient norm by 500\times.
  2. Unbounded graph growth (OOM): Without the detach, segment s stays connected to the computational graphs of all previous segments 1, \ldots, s-1. Backward runtime and GPU memory grow linearly as O(s \cdot T_0) at every step until the backward pass runs out of memory.
  3. No: Because the measured decay of \approx 0.55 per step attenuates gradients below 1\% within 8 steps regardless of window length, extending T_0 from 32 \to 128 adds zero usable long-range gradient signal.

Summary: Backpropagation Through Time (BPTT)

Section Takeaways

Concept / Mechanism Mathematical Expression Scaling / Asymptotics Practical Consequence
Linear Backward Recursion \mathbf{G}_t = \nabla_{\mathbf{O}_t} L\,\mathbf{W}_{\textrm{hq}}^\top + \mathbf{G}_{t+1}\mathbf{W}_{\textrm{hh}}^\top O(T) backward sweep (1 GEMM/step) Exact reverse-mode autodiff on the unrolled graph
Unrolled Lag-k Expansion \mathbf{G}_t = \sum_{j=t}^T \nabla_{\mathbf{O}_j} L\,\mathbf{W}_{\textrm{hq}}^\top (\mathbf{W}_{\textrm{hh}}^\top)^{j-t} \|(\mathbf{W}_{\textrm{hh}}^\top)^k\| \sim \rho(\mathbf{W}_{\textrm{hh}})^k \rho < 1 \implies vanishing; \rho > 1 \implies exploding
Nonlinear \tanh BPTT \mathbf{G}_{t-1} = \nabla_{\mathbf{O}_{t-1}} L\,\mathbf{W}_{\textrm{hq}}^\top + (\mathbf{G}_t \odot (1 - \mathbf{H}_t^2))\mathbf{W}_{\textrm{hh}}^\top Measured decay \approx 0.55 per step (rough estimate \overline{(1 - H^2)}\,\rho \approx 0.49) Gradient norm falls below 1\% in \sim 8 steps despite \rho \approx 1.8
Shared Parameter Gradients \nabla_{\mathbf{W}_{\textrm{hh}}} L = \sum_{t=1}^T \mathbf{H}_{t-1}^\top \mathbf{G}_t, \nabla_{\mathbf{W}_{\textrm{xh}}} L = \sum_{t=1}^T \mathbf{X}_t^\top \mathbf{G}_t Sum of T outer products; requires storing \mathbf{H}_{1:T} Dominated by small-lag terms (j - t \le 3) when gradients vanish
Global Gradient Clipping \mathbf{g} \leftarrow \min(1, \theta / \|\mathbf{g}\|)\mathbf{g} Uniform scalar factor on entire sum \mathbf{g} Cures exploding update spikes; cannot alter near-vs-far lag ratio
Truncated BPTT (detach) Stop gradient across segment boundaries of length T_0 Bounds memory to O(T_0 bh) per update Capped credit-assignment horizon k < T_0; mandatory for long streams