TExcelTAD
Home › Math for Deep Learning & LLMs › Backpropagation Through Time

Backpropagation Through Time

Training a recurrent network means backpropagating through the computation unrolled over all time steps: backpropagation through time (BPTT). Because the same weights are used at every step, their gradient is a sum over steps, and the gradient flowing back through the hidden states is multiplied by one Jacobian per step, which is where vanishing and exploding gradients come from in their purest form.

The unrolled graph

With at=Whhht−1+Wxhxt+b\mathbf{a}_t = W_{hh}\mathbf{h}_{t-1} + W_{xh}\mathbf{x}_t + \mathbf{b}, ht=tanh⁡(at)\mathbf{h}_t = \tanh(\mathbf{a}_t), outputs ot=Whyht\mathbf{o}_t = W_{hy}\mathbf{h}_t and a total loss L=∑tℓt(ot)\mathcal{L} = \sum_t \ell_t(\mathbf{o}_t) (Recurrent Neural Networks), the hidden state ht\mathbf{h}_t influences the loss in two ways: through its own output ℓt\ell_t and through the next state ht+1\mathbf{h}_{t+1}. Going backward from t=Tt = T to 1:

δt=∂L∂ht=WhyT∂ℓt∂ot+WhhT(δt+1⊙(1−ht+12))∂L∂Whh=∑t(δt⊙(1−ht2))ht−1T,∂L∂Wxh=∑t(δt⊙(1−ht2))xtT\begin{aligned} \boldsymbol{\delta}_t &= \frac{\partial\mathcal{L}}{\partial\mathbf{h}_t} = W_{hy}^T\frac{\partial\ell_t}{\partial\mathbf{o}_t} + W_{hh}^T\left(\boldsymbol{\delta}_{t+1}\odot(1 - \mathbf{h}_{t+1}^2)\right) \\ \frac{\partial\mathcal{L}}{\partial W_{hh}} &= \sum_t\left(\boldsymbol{\delta}_t\odot(1 - \mathbf{h}_t^2)\right)\mathbf{h}_{t-1}^T, \qquad \frac{\partial\mathcal{L}}{\partial W_{xh}} = \sum_t\left(\boldsymbol{\delta}_t\odot(1 - \mathbf{h}_t^2)\right)\mathbf{x}_t^T \end{aligned}

with δT+1=0\boldsymbol{\delta}_{T+1} = \mathbf{0}. The sums over tt are the fan-out rule for shared weights (Computational Graphs).

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
T, d_in, d = 6, 2, 4
xs = rng.normal(size=(T, d_in)); targets = rng.normal(size=T)
Wxh, Whh, wy = rng.normal(0, 0.5, (d, d_in)), rng.normal(0, 0.5, (d, d)), rng.normal(0, 0.5, d)

def forward(Whh):
    h = np.zeros(d); hs = [h]; loss = 0.0
    for t in range(T):
        h = np.tanh(Whh @ h + Wxh @ xs[t]); hs.append(h)
        loss += 0.5 * (wy @ h - targets[t])**2
    return loss, hs

loss, hs = forward(Whh)
dWhh = np.zeros_like(Whh); delta_next = np.zeros(d)
for t in range(T, 0, -1):
    err = wy @ hs[t] - targets[t - 1]
    delta = wy * err + delta_next                     # dL/dh_t
    da = delta * (1 - hs[t]**2)                        # through tanh
    dWhh += np.outer(da, hs[t - 1])                    # shared weight: sum over steps
    delta_next = Whh.T @ da                            # pass to h_{t-1}
num = np.zeros_like(Whh)
for idx in np.ndindex(Whh.shape):
    E = np.zeros_like(Whh); E[idx] = 1e-6
    num[idx] = (forward(Whh + E)[0] - forward(Whh - E)[0]) / 2e-6
print(f"loss {loss:.4f}; BPTT gradient matches finite differences: {np.allclose(dWhh, num, atol=1e-7)}")
loss 4.6955; BPTT gradient matches finite differences: True

Long-range gradients

The contribution of a loss at step tt to a state kk steps earlier is

∂ht∂ht−k=∏s=t−k+1tdiag⁡(1−hs2) Whh\frac{\partial\mathbf{h}_t}{\partial\mathbf{h}_{t-k}} = \prod_{s=t-k+1}^{t}\operatorname{diag}(1 - \mathbf{h}_s^2)\,W_{hh}

a product of kk Jacobians with the same matrix. If the largest singular value of WhhW_{hh} is below 1 (and tanh can only shrink), the product decays exponentially in kk; if it is well above 1, it can explode (Vanishing and Exploding Gradients).

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
d = 32
for radius in (0.5, 1.0, 1.5):
    W = rng.normal(size=(d, d)); W *= radius / np.max(np.abs(np.linalg.eigvals(W)))
    J = np.eye(d)
    norms = {}
    for k in range(1, 51):
        J = J @ W                                     # linear RNN: Jacobian is W^k
        if k in (1, 10, 50): norms[k] = np.linalg.norm(J, 2)
    print(f"spectral radius {radius}: |dh_t/dh_(t-k)| for k=1,10,50: " + ", ".join(f"{v:.1e}" for v in norms.values()))
spectral radius 0.5: |dh_t/dh_(t-k)| for k=1,10,50: 9.1e-01, 2.8e-03, 1.9e-15
spectral radius 1.0: |dh_t/dh_(t-k)| for k=1,10,50: 1.9e+00, 3.6e+00, 5.0e+00
spectral radius 1.5: |dh_t/dh_(t-k)| for k=1,10,50: 2.9e+00, 3.0e+02, 2.3e+09

Truncated BPTT

For long sequences (a whole book), full BPTT would need to store every hidden state. Truncated BPTT splits the stream into chunks of length KK, carries the hidden state forward across chunks, but stops gradients at chunk boundaries (h = h.detach()). Memory is O(K)O(K); the price is that dependencies longer than KK steps receive no gradient signal.

Remedies

Gradient clipping handles explosions (Schedules and Clipping). For vanishing gradients the fix is architectural: gated cells whose state is updated additively (LSTM and GRU), or attention, which connects any two positions in one step.

In software

  • Autograd performs BPTT automatically once the loop is written in the framework; nn.LSTM uses fused cuDNN kernels.
  • hidden = hidden.detach() between chunks implements truncated BPTT.
  • Orthogonal initialization of WhhW_{hh} (all singular values 1) delays vanishing in plain RNNs.

Exercises

Exercise 1: Shared-weight gradient

A scalar linear RNN ht=wht−1+xth_t = wh_{t-1} + x_t with h0=0h_0 = 0, inputs x1=1,x2=0x_1 = 1, x_2 = 0, and loss L=h2\mathcal{L} = h_2. Compute ∂L/∂w\partial\mathcal{L}/\partial w.

Answer

11.

Solution

h1=1h_1 = 1, h2=wh_2 = w. So L=w\mathcal{L} = w and the derivative is 1. With BPTT: step 2 contributes δ2h1=1⋅1\delta_2 h_1 = 1 \cdot 1, step 1 contributes δ1h0=w⋅0=0\delta_1 h_0 = w \cdot 0 = 0.

Exercise 2: Decay rate

A scalar RNN has ∣w∣=0.8\lvert w \rvert = 0.8 and tanh derivatives near 1. Roughly how much smaller is the gradient from 20 steps back?

Answer

About 0.820≈0.0120.8^{20} \approx 0.012.

Solution

Each step multiplies by about 0.80.8; 0.820=e20ln⁡0.8≈e−4.46≈0.01150.8^{20} = e^{20\ln 0.8} \approx e^{-4.46} \approx 0.0115.

Exercise 3: Truncation (code)

For the linear RNN ht=0.9ht−1+xth_t = 0.9h_{t-1} + x_t, compute ∂h30/∂x1\partial h_{30}/\partial x_1 exactly and with truncation K=10K = 10.

Answer

0.929≈0.0470.9^{29} \approx 0.047 exactly; 0 with truncation.

Solution

h30=∑t0.930−txth_{30} = \sum_t 0.9^{30 - t}x_t. Truncated BPTT stops at 10 steps back, so x1x_1 (29 steps back) gets no gradient.

python · try it yourself
K, T = 10, 30
exact = 0.9 ** (T - 1)
truncated = exact if T - 1 < K else 0.0
print(round(exact, 4), truncated)
0.0471 0.0

Test yourself

In BPTT, the gradient of the shared matrix WhhW_{hh} is…

  1. taken from the last step only
  2. a sum of contributions from every time step
  3. the average hidden state
  4. zero

Why do plain RNNs struggle with long-range dependencies?

  1. They have too many parameters
  2. The gradient over kk steps is a product of kk Jacobians with the same matrix, which shrinks or grows exponentially
  3. They cannot read long inputs
  4. tanh is not differentiable

Truncated BPTT limits…

  1. the forward pass length
  2. how far back gradients flow, to save memory
  3. the hidden size
  4. the vocabulary