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 , , outputs and a total loss (Recurrent Neural Networks), the hidden state influences the loss in two ways: through its own output and through the next state . Going backward from to 1:
with . The sums over are the fan-out rule for shared weights (Computational Graphs).
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 to a state steps earlier is
a product of Jacobians with the same matrix. If the largest singular value of is below 1 (and tanh can only shrink), the product decays exponentially in ; if it is well above 1, it can explode (Vanishing and Exploding Gradients).
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 , carries the hidden state forward across chunks, but stops gradients at chunk boundaries (h = h.detach()). Memory is ; the price is that dependencies longer than 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.LSTMuses fused cuDNN kernels. hidden = hidden.detach()between chunks implements truncated BPTT.- Orthogonal initialization of (all singular values 1) delays vanishing in plain RNNs.
Exercises
Exercise 1: Shared-weight gradient
A scalar linear RNN with , inputs , and loss . Compute .
Answer
.
Solution
, . So and the derivative is 1. With BPTT: step 2 contributes , step 1 contributes .
Exercise 2: Decay rate
A scalar RNN has and tanh derivatives near 1. Roughly how much smaller is the gradient from 20 steps back?
Answer
About .
Solution
Each step multiplies by about ; .
Exercise 3: Truncation (code)
For the linear RNN , compute exactly and with truncation .
Answer
exactly; 0 with truncation.
Solution
. Truncated BPTT stops at 10 steps back, so (29 steps back) gets no gradient.
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 is…
- taken from the last step only
- a sum of contributions from every time step
- the average hidden state
- zero
Why do plain RNNs struggle with long-range dependencies?
- They have too many parameters
- The gradient over steps is a product of Jacobians with the same matrix, which shrinks or grows exponentially
- They cannot read long inputs
- tanh is not differentiable
Truncated BPTT limits…
- the forward pass length
- how far back gradients flow, to save memory
- the hidden size
- the vocabulary