Skip to content

9.1 Vanilla RNN with manual BPTT and truncation

Every model so far sees a fixed window: the bigram model sees one byte, the n-gram model sees n−1n - 1 tokens, and Bengio’s neural probabilistic language model sees a fixed context of embeddings. Text has dependencies longer than any window you can afford: a quote opened 200 characters ago must close. A recurrent network keeps a state hth_t that it updates once per token, so in principle it sees the whole past. In practice it forgets, and the reason is in the gradient. To learn that a quote must close, the gradient of the closing step’s loss has to travel back 200 steps through the recurrence.

Concepts from other sections (15)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

In this section you write that backward pass by hand, so you can see where the gradient goes, why it vanishes or explodes, and why training cuts it short (truncation). The LSTM and GRU sections then fix the vanishing with gates, and the RNN language model trains all three cells as language models on the same text. There, cell='rnn' runs as one fused autograd op over the rnn_forward and rnn_backward you build here, and it is the rnn row of the recurrent language-model comparison.

This section builds on Matrix differentials, the trace trick, and closed-form VJPs from Mathematics, whose matmul_vjp is each step’s backward, and on Eigenvalues, power iteration, and the spectral radius, whose spectral_radius is the diagnostic. The cross-check runs the same forward through the Tensor and op library of Part 0 and compares gradients with autograd. Useful background reading is Jacobians, the multivariable chain rule, and numeric JVP/VJP and, from Software Engineering, TDD, unit tests, and mutation testing. The solution is manual.py, with RNNCache, rnn_forward, rnn_backward, tbptt_windows, tbptt_grads, and gradient_flow; its contract is manual.pyi and its model tests are test_rnn.py.

Learning objectives

  • Derive backpropagation through time as reverse mode on the unrolled loop, including the carry from step t+1t + 1.
  • Write each step’s backward as two matmul VJPs and the tanh derivative 1−ht21 - h_t^2, accumulating the shared weight gradients.
  • Implement truncated BPTT(k1k_1, k2k_2) as bookkeeping on windows, and check it against full BPTT.
  • Predict exploding and vanishing gradients from the spectral radius ρ(Whh)\rho(W_{hh}), and explain why the diagnostic multiplies by Whh⊤W_{hh}^\top.

The table below fixes the symbols used throughout the section, with their shapes.

SymbolMeaningType / shape
T,B,D,HT, B, D, Htime steps, batch size, input size, hidden sizeintegers
xtx_tthe input at step tt (a row per batch element)float64[B, D]
hth_tthe hidden state after step tt; h−1=h0h_{-1} = h_0 is the given startfloat64[B, H]
WxhW_{xh}, WhhW_{hh}, bhb_hinput-to-hidden, hidden-to-hidden weights, bias[D, H], [H, H], [H]
at=xtWxh+ht−1Whh+bha_t = x_t W_{xh} + h_{t-1} W_{hh} + b_hthe pre-activation[B, H]
LLa scalar loss computed from the hidden statesreal
hˉt=∂L/∂ht\bar h_t = \partial L/\partial h_tthe total gradient reaching hth_t[B, H]
gtg_t (dh_all[t])the part of hˉt\bar h_t that comes directly from the loss at step tt[B, H]
aˉt\bar a_tthe gradient of the pre-activation[B, H]
ρ(W)\rho(W)spectral radius, max⁡∣λ∣\max \lvert\lambda\rvert over WW‘s eigenvaluesreal
k1,k2k_1, k_2truncation: cut every k1k_1 steps, backpropagate k2k_2 stepsintegers

The recurrence is ht=tanh⁡(at)h_t = \tanh(a_t) with at=xtWxh+ht−1Whh+bha_t = x_t W_{xh} + h_{t-1} W_{hh} + b_h, for t=0,…,T−1t = 0, \dots, T - 1. The same three parameters are used at every step: the network is one cell applied TT times. We use rows (one row per batch element) and right-multiplied weights, so x @ Wxh reads like the math. torch stores the transposes, weight_ih_l0 =Wxh⊤= W_{xh}^\top and weight_hh_l0 =Whh⊤= W_{hh}^\top, and two biases whose sum is bhb_h; the golden test maps between the two conventions.

Unroll the loop and you have a deep feed-forward graph whose layers share weights. Reverse mode, as in Scalar reverse mode: the Value graph, walks it from the last node back. The state hth_t feeds two places: the loss at step tt (through whatever reads it, an output layer in the RNN language model), and step t+1t + 1 through at+1a_{t+1}. So its total gradient is the sum of both paths:

hˉt=gt+aˉt+1Whh⊤,hˉT−1=gT−1+(gradient from after the sequence, dh_next).\bar h_t = g_t + \bar a_{t+1} W_{hh}^\top, \qquad \bar h_{T-1} = g_{T-1} + (\text{gradient from after the sequence, } \texttt{dh\_next}).

The second term is the carry. Walking t=T−1,…,0t = T-1, \dots, 0, you keep it in a variable and add it to gtg_t before anything else. Then you pass through the tanh, using tanh⁡′(a)=1−tanh⁡2(a)=1−ht2\tanh'(a) = 1 - \tanh^2(a) = 1 - h_t^2, read from the saved output so that ata_t need not be kept:

aˉt=hˉt⊙(1−ht⊙ht).\bar a_t = \bar h_t \odot (1 - h_t \odot h_t).

From there each step is two matmul VJPs. The pre-activation ata_t contains xtWxhx_t W_{xh} and ht−1Whhh_{t-1} W_{hh}, both of the form Y=ABY = AB, whose VJP is Aˉ=YˉB⊤\bar A = \bar Y B^\top, Bˉ=A⊤Yˉ\bar B = A^\top \bar Y. So

xˉt=aˉtWxh⊤,Wˉxh+=xt⊤aˉt,hˉt−1 (the next carry)=aˉtWhh⊤,Wˉhh+=ht−1⊤aˉt,bˉh+=∑rowsaˉt.\bar x_t = \bar a_t W_{xh}^\top,\quad \bar W_{xh} \mathrel{+}= x_t^\top \bar a_t,\quad \bar h_{t-1} \text{ (the next carry)} = \bar a_t W_{hh}^\top,\quad \bar W_{hh} \mathrel{+}= h_{t-1}^\top \bar a_t,\quad \bar b_h \mathrel{+}= \textstyle\sum_{\text{rows}} \bar a_t.

The weight gradients accumulate over time, because the same weight is used at every step, and Wˉhh\bar W_{hh} pairs aˉt\bar a_t with the previous state ht−1h_{t-1}, the one that was multiplied. After t=0t = 0 the carry is ∂L/∂h0\partial L/\partial h_0.

That carry is also where the trouble starts. If the loss only reads the last state, the carry from step T−1T-1 back to step tt is multiplied by diag⁡(1−hs2) Whh⊤\operatorname{diag}(1 - h_s^2)\,W_{hh}^\top once per step. Near the linear regime (hh small, 1−h2≈11 - h^2 \approx 1) that is Whh⊤W_{hh}^\top applied T−1−tT - 1 - t times, and the component along the top eigenvector grows or shrinks by ρ(Whh)\rho(W_{hh}) per step. So the gradient norm behaves like ρT−1−t\rho^{T-1-t}: for ρ=1.25\rho = 1.25 it is 1.2529≈6501.25^{29} \approx 650 times larger 30 steps back, and for ρ=0.8\rho = 0.8 about 1500 times smaller. Saturated tanh units (∣h∣→1|h| \to 1) shrink it further.

gradient_flow returns the per-step norms and ρ\rho (computed with the QR algorithm from the spectral-radius section), the diagnostic to print when training stalls. Note the transpose: walking back multiplies by Whh⊤W_{hh}^\top, and for a non-normal WhhW_{hh} the spectral norm (largest singular value) can be large while ρ\rho is small. The long-run growth is set by ρ\rho.

Full BPTT over a 100 000-token stream needs every hidden state in memory and a backward pass as long as the stream. Williams and Peng’s TBPTT(k1k_1, k2k_2) runs the forward straight through and, every k1k_1 steps, differentiates the losses of the last k1k_1 steps back through at most k2k_2 steps. The window ending at ee starts at s=max⁡(0,e−k2)s = \max(0, e - k_2). The state entering it, hs−1h_{s-1}, is a constant (the cut), and only the losses of steps [eprev,e)[e_{\text{prev}}, e) enter, since earlier steps of an overlapping window were already counted at their own cut. tbptt_windows lists the cuts and tbptt_grads sums the window gradients.

Two checks pin the bookkeeping. With k2≥Tk_2 \ge T every loss reaches its whole history exactly once, which is full BPTT. With k1=k2=1k_1 = k_2 = 1 no gradient crosses WhhW_{hh} at all. The RNN language model uses k1=k2=kk_1 = k_2 = k with the state carried across batches (stateful TBPTT).

Take D=H=B=1D = H = B = 1, Wxh=0.5W_{xh} = 0.5, Whh=0.8W_{hh} = 0.8, bh=0b_h = 0, h0=0h_0 = 0, inputs x=[1,0]x = [1, 0], and the loss L=h1L = h_1 (the state after the second step), so g=[0,1]g = [0, 1].

Forward. h0=tanh⁡(1⋅0.5+0)=0.462117h_0 = \tanh(1 \cdot 0.5 + 0) = 0.462117; h1=tanh⁡(0⋅0.5+0.462117⋅0.8)=tanh⁡(0.369694)=0.353724h_1 = \tanh(0 \cdot 0.5 + 0.462117 \cdot 0.8) = \tanh(0.369694) = 0.353724.

Backward at t=1t = 1. The carry is 0, so hˉ1=g1=1\bar h_1 = g_1 = 1. Then aˉ1=1⋅(1−0.3537242)=0.874879\bar a_1 = 1 \cdot (1 - 0.353724^2) = 0.874879. That gives Wˉxh+=x1aˉ1=0\bar W_{xh} \mathrel{+}= x_1 \bar a_1 = 0, Wˉhh+=h0aˉ1=0.462117×0.874879=0.404297\bar W_{hh} \mathrel{+}= h_0 \bar a_1 = 0.462117 \times 0.874879 = 0.404297, bˉh+=0.874879\bar b_h \mathrel{+}= 0.874879, xˉ1=0.874879×0.5=0.437440\bar x_1 = 0.874879 \times 0.5 = 0.437440, and the carry becomes aˉ1Whh=0.699904\bar a_1 W_{hh} = 0.699904.

Backward at t=0t = 0. hˉ0=g0+carry=0+0.699904\bar h_0 = g_0 + \text{carry} = 0 + 0.699904, so aˉ0=0.699904×(1−0.4621172)=0.550438\bar a_0 = 0.699904 \times (1 - 0.462117^2) = 0.550438. Then Wˉxh+=x0aˉ0=0.550438\bar W_{xh} \mathrel{+}= x_0 \bar a_0 = 0.550438, Wˉhh+=h−1aˉ0=0\bar W_{hh} \mathrel{+}= h_{-1} \bar a_0 = 0 (the start state is 0), and bˉh+=0.550438\bar b_h \mathrel{+}= 0.550438, so bˉh=1.425317\bar b_h = 1.425317. Finally xˉ0=0.275219\bar x_0 = 0.275219 and ∂L/∂h−1=aˉ0Whh=0.440350\partial L/\partial h_{-1} = \bar a_0 W_{hh} = 0.440350.

Without the carry, aˉ0\bar a_0 would be 0 and Wˉxh\bar W_{xh} would be 0: the first input would look useless although it decides h1h_1.

Truncation windows. With T=10T = 10, k1=4k_1 = 4, k2=6k_2 = 6, the cuts fall at 4, 8, and 10 (the last, partial chunk), reaching back to max⁡(0,4−6)=0\max(0, 4 - 6) = 0, 8−6=28 - 6 = 2, and 10−6=410 - 6 = 4: [(0, 4), (2, 8), (4, 10)]. The window (2,8)(2, 8) backpropagates only the losses of steps 4 to 7.

These two hand cases become unit tests. The model tests in test_rnn.py pin them exactly: with Wxh=0.5W_{xh} = 0.5, Whh=0.8W_{hh} = 0.8, x=[1,0]x = [1, 0], h0=0h_0 = 0, and L=h1L = h_1, they expect Wˉxh=0.550438\bar W_{xh} = 0.550438, Wˉhh=0.404297\bar W_{hh} = 0.404297, and ∂L/∂h−1=0.440350\partial L / \partial h_{-1} = 0.440350. They add central differences with a dh_next, the windows with a partial chunk, k2≥Tk_2 \ge T against rnn_backward, one-step windows, and gradient_flow on a non-normal WhhW_{hh}.

The module exposes a cache type and five functions:

python/tinyllm/rnn/manual.py
class RNNCache(NamedTuple): x; h0; h; Wxh; Whh # what the backward needs
def rnn_forward(x, h0, Wxh, Whh, bh) -> tuple[NDArray, RNNCache] # h [T, B, H]
def rnn_backward(dh_all, cache, dh_next=None) -> dict[str, NDArray] # keys x, h0, Wxh, Whh, bh
def tbptt_windows(T, k1, k2) -> list[tuple[int, int]]
def tbptt_grads(x, h0, Wxh, Whh, bh, dh_all, k1, k2) -> dict[str, NDArray]
def gradient_flow(cache, dh_last) -> tuple[NDArray, float] # (norms [T], rho)

rnn_forward returns all hidden states and the cache; rnn_backward takes the per-step loss gradients dh_all, the cache, and an optional dh_next arriving from after the sequence, and returns a dictionary of gradients keyed by input name. tbptt_windows and tbptt_grads implement truncation, and gradient_flow takes a gradient arriving at the last state and returns the per-step norms and ρ\rho.

Before reading the code, it helps to see the reasoning chain that fixes its shape.

  1. The backward needs every state. Each step’s VJP needs its input xtx_t, the previous state ht−1h_{t-1} (for Wˉhh\bar W_{hh}), and 1−ht21 - h_t^2; all are functions of the saved hh. So the forward stores the whole [T, B, H] tensor and the cache holds x, h0, h, and the two weight matrices. The pre-activation is not stored, because tanh⁡′=1−h2\tanh' = 1 - h^2.
  2. Walk time in reverse with one carry. hth_t has two consumers (the loss at tt and step t+1t + 1), so its gradient is a sum; processing t=T−1t = T - 1 down to 0, the second term is exactly what step t+1t + 1 just produced. One variable, initialised from dh_next, holds it.
  3. Each step is two matmuls, so two VJPs. matmul_vjp(da, x_t, Wxh) gives (xˉt,Wˉxh contribution)(\bar x_t, \bar W_{xh}\text{ contribution}) and matmul_vjp(da, h_prev, Whh) gives (the next carry, the Wˉhh\bar W_{hh} contribution). Reusing the tested primitive means no transposes are written by hand, which is where sign and orientation bugs live.
  4. Shared weights accumulate. The same WxhW_{xh}, WhhW_{hh}, bhb_h are used at every step, so their gradients are sums over steps; per-step inputs (xˉt\bar x_t) are written once.
  5. Truncation is bookkeeping on windows. Each cut at ee differentiates the losses since the previous cut through at most k2k_2 steps, treating the entering state as a constant. That means: run rnn_backward on the window with h0 set to hs−1h_{s-1}, a gradient that is zero for steps already counted, and sum the results.
  6. Diagnose with the actual backward map. The carry is multiplied by diag⁡(1−hs2)Whh⊤\operatorname{diag}(1 - h_s^2) W_{hh}^\top per step; the diagnostic must apply exactly that, and report ρ(Whh)\rho(W_{hh}) as the long-run growth rate.

The forward is one loop that keeps every state.

def rnn_forward(x, h0, Wxh, Whh, bh):
x, h0, Wxh, Whh, bh = (_f64(a) for a in (x, h0, Wxh, Whh, bh)) # float64 throughout
_check(x, h0, Wxh, Whh, bh) # x [T,B,D], Wxh [D,H], Whh [H,H], h0 [B,H], bh [H]
T, B, _ = x.shape
h = np.empty((T, B, Whh.shape[0]), dtype=np.float64)
prev = h0
for t in range(T):
prev = np.tanh(x[t] @ Wxh + prev @ Whh + bh) # rows times right-multiplied weights
h[t] = prev
return h, RNNCache(x, h0, h, Wxh, Whh) # everything the backward reads

The backward has four ingredients: the carry, the tanh derivative from the saved output, two VJPs, and accumulation.

def rnn_backward(dh_all, cache, dh_next=None):
x, h0, h, Wxh, Whh = cache
g = _f64(dh_all) # g[t]: the loss's direct gradient into h_t
# ... shape checks ...
carry = np.zeros_like(h0) if dh_next is None else _f64(dh_next) # from after the sequence
dx = np.zeros_like(x)
dWxh = np.zeros_like(Wxh)
dWhh = np.zeros_like(Whh)
dbh = np.zeros(Whh.shape[0], dtype=np.float64)
for t in range(h.shape[0] - 1, -1, -1):
# Both paths into h_t: the loss at step t, and step t + 1 through Whh.
dh = g[t] + carry
da = dh * (1.0 - h[t] * h[t]) # tanh'(a_t) = 1 - tanh(a_t)^2 = 1 - h_t^2
h_prev = h[t - 1] if t > 0 else h0 # the state that was multiplied by Whh
dx[t], dW = matmul_vjp(da, x[t], Wxh) # a_t contains x_t @ Wxh
dWxh += dW # shared weight: accumulate
carry, dW = matmul_vjp(da, h_prev, Whh) # a_t contains h_{t-1} @ Whh: next carry
dWhh += dW
dbh += da.sum(axis=0) # the bias is broadcast over the batch
return {"x": dx, "h0": carry, "Wxh": dWxh, "Whh": dWhh, "bh": dbh} # final carry = dL/dh0

Trace the hand example through it. At t=1t = 1, carry is 0, dh is 1, and da is 0.874879; the first VJP gives xˉ1=0.437440\bar x_1 = 0.437440 and adds 0 to dWxh (since x1=0x_1 = 0); the second gives the carry 0.874879×0.8=0.6999040.874879 \times 0.8 = 0.699904 and adds h0aˉ1=0.404297h_0 \bar a_1 = 0.404297 to dWhh. At t=0t = 0, dh is the carry, da is 0.550438, dWxh becomes 0.550438, h_prev is the start state 0, so dWhh stays 0.404297, and the final carry is 0.4403500.440350.

The window list has ends every k1k_1 steps plus a last partial chunk, and each window reaches back k2k_2.

def tbptt_windows(T: int, k1: int, k2: int) -> list[tuple[int, int]]:
if T < 0 or k1 < 1 or k2 < k1:
raise ValueError(...) # a window must cover the losses it owns
ends = list(range(k1, T + 1, k1))
if T > 0 and (not ends or ends[-1] != T):
ends.append(T) # never drop the last partial chunk
return [(max(0, e - k2), e) for e in ends] # reach back k2, not k1

k2 < k1 is refused because the window (e−k2,e)(e - k_2, e) would not contain all the losses [e−k1,e)[e - k_1, e) it is responsible for. The hand example, T=10T = 10, k1=4k_1 = 4, k2=6k_2 = 6, gives ends 4, 8, 10 and windows [(0, 4), (2, 8), (4, 10)].

With the windows in hand, tbptt_grads does one full forward, then one rnn_backward per window with the entering state as a constant and only the window’s own losses.

h, cache = rnn_forward(x, h0, Wxh, Whh, bh) # the forward is never truncated
# ... g, shape check, zero-initialised out ...
prev_end = 0
for start, end in tbptt_windows(h.shape[0], k1, k2):
# The state entering the window is a constant: the cut.
h_in = cache.h0 if start == 0 else h[start - 1]
wcache = RNNCache(cache.x[start:end], h_in, h[start:end], cache.Wxh, cache.Whh)
gw = np.zeros_like(h[start:end])
# Only the losses since the last cut; earlier ones were counted then.
gw[prev_end - start :] = g[prev_end:end]
grads = rnn_backward(gw, wcache)
out["x"][start:end] += grads["x"]
if start == 0:
out["h0"] += grads["h0"] # only a window that reaches t = 0 touches h0
for k in ("Wxh", "Whh", "bh"):
out[k] += grads[k]
prev_end = end
return out

Building the window’s cache from slices of the full forward means the window sees exactly the states the untruncated run produced; only the gradient is cut. With k2≥Tk_2 \ge T every window starts at 0, so each loss is backpropagated through its entire history exactly once and the sum equals rnn_backward on the whole sequence. With k1=k2=1k_1 = k_2 = 1 each window is one step whose entering state is a constant, so dWhh only receives ht−1⊤aˉth_{t-1}^\top \bar a_t from the immediate loss and no gradient travels through WhhW_{hh} to an earlier step.

The diagnostic applies the true backward map to a gradient arriving at the last state and records the norm at each earlier state.

def gradient_flow(cache: RNNCache, dh_last) -> tuple[NDArray, float]:
h, Whh = cache.h, cache.Whh
T = h.shape[0]
# ... T >= 1, dh_last [B, H] ...
norms = np.empty(T, dtype=np.float64)
norms[T - 1] = np.linalg.norm(g)
for t in range(T - 1, 0, -1):
g = (g * (1.0 - h[t] * h[t])) @ Whh.T # diag(1 - h_t^2), then W_hh transposed
norms[t - 1] = np.linalg.norm(g)
return norms, float(spectral_radius(Whh)) # rho, not the spectral norm

The full solution is manual.py.

Forward and backward both cost O(TB(DH+H2))O(T B (D H + H^2)) time. Memory is O(TBH)O(T B H) for the saved states, which is what full BPTT costs and what truncation bounds: TBPTT(k1k_1, k2k_2) runs rnn_backward over ⌈T/k1⌉\lceil T / k_1 \rceil windows of at most k2k_2 steps, O((T/k1)k2B(DH+H2))O((T / k_1) k_2 B (DH + H^2)) time, and a streaming implementation needs only k2k_2 states at once.

The cache saves hh and not aa because tanh⁡′(a)=1−h2\tanh'(a) = 1 - h^2, so hh is enough, and hh is needed anyway: it is the output, and ht−1h_{t-1} feeds Wˉhh\bar W_{hh}. Saving aa too would double the memory for nothing. The backward reuses matmul_vjp because the transposes in Aˉ=YˉB⊤\bar A = \bar Y B^\top, Bˉ=A⊤Yˉ\bar B = A^\top \bar Y are the most common source of silent errors; one tested primitive used twice per step removes them and makes the backward read like the math.

Why write a backward by hand at all, when autograd exists? The RNN language model wraps this pair as one fused autograd op: one graph node per sequence instead of a handful per step, and a backward with no Python-level graph traversal. Writing it also exposes the carry, which is where vanishing and exploding gradients come from. TBPTT is rebuilt from rnn_backward because windows are just short sequences with a constant entering state and a masked loss gradient, so the same tested backward serves both; the property ”k2≥Tk_2 \ge T equals full BPTT” then checks the bookkeeping, not a second backward.

The design accepts some tradeoffs: Python loops over time (the per-step matmuls dominate for useful HH); float64 for exactness over speed; and a diagnostic that uses one gradient direction, so it shows the growth of that direction, bounded in the long run by ρ\rho.

A correct solution has to survive a range of checks, from the hand example to golden comparisons with torch. The table lists them with the reason each matters downstream.

CaseKind of checkChecksWhy it matters downstream
The two-step hand exampleunitevery number of the hand examplethe carry and 1−h21 - h^2 are right
Gradcheck of full BPTTgradcheckall five gradients against central differencesthe backward is the derivative of the forward
dh_next enters at the last stepgradchecka gradient arriving from after the sequencestacking and windows in the language model
Matches autograddifferentialthe same forward through Tensor gives the same gradientsthe language model fuses this as one autograd op
Matches torch’s RNNgoldentorch.nn.RNN outputs and gradients with transposed weights and summed biasesthe convention is torch’s
TBPTT window examplesunitthe hand windows, tiling, the partial chunk, bad argumentsthe trainer’s schedule
TBPTT with long reach is full BPTTpropertyk2≥Tk_2 \ge T equals full BPTT for every k1k_1each loss counted exactly once
TBPTT cuts long pathsunitk1=k2=1k_1 = k_2 = 1: no gradient crosses WhhW_{hh}what truncation gives up
Gradient flow explodes and vanishespropertynorms follow ρT−1−t\rho^{T-1-t} along the top eigenvector; ρ\rho reporteddiagnosing a stalled run
Gradient flow uses Whh⊤W_{hh}^\topunita non-normal WhhW_{hh}: Whh⊤W_{hh}^\top per step, ρ=0.5\rho = 0.5 not the norm 2.13the diagnostic predicts the real gradient
Shapes and bad argumentsboundaryT=0T = 0; mismatched shapes raiseerrors at the call site

The bugs these checks catch fall into five families.

Warning: Forgetting to carry the gradient from step t+1t + 1 into hth_t gives early inputs zero gradient, so the network only learns one-step dependencies. The solution writes dh = g[t] + carry, with the carry from the second VJP.

Warning: Taking the tanh derivative as 1−h1 - h, or computing it from the wrong saved value, puts gradients off by a factor that grows with ∣h∣\lvert h\rvert. The solution uses da = dh * (1.0 - h[t] * h[t]) with the same step’s output.

Warning: Pairing aˉt\bar a_t with hth_t instead of ht−1h_{t-1} in Wˉhh\bar W_{hh}, or overwriting instead of accumulating, gives a wrong recurrent gradient, and training diverges or stalls. The solution uses h_prev = h[t - 1] if t > 0 else h0 and dWhh += dW.

Warning: TBPTT bookkeeping errors (reaching back k1k_1 instead of k2k_2, counting a loss in two windows, dropping the last partial chunk) give a gradient that is neither full nor truncated, possibly larger than full BPTT. The solution uses max(0, e - k2), gw[prev_end - start:], and the appended final end.

Warning: Diagnosing with WhhW_{hh} instead of Whh⊤W_{hh}^\top, or with the spectral norm, makes the diagnostic predict explosion where the gradient vanishes. gradient_flow multiplies by Whh.T and reports spectral_radius.

Looking back, this section leaned on matmul_vjp from Matrix differentials, the trace trick, and closed-form VJPs, used twice per step; on spectral_radius from Eigenvalues, power iteration, and the spectral radius as the explosion predictor; and on Tensor and the op library (F.tanh, F.matmul, F.stack) for the autograd cross-check. Looking forward, the LSTM’s cell state keeps the gradient from vanishing, and the RNN language model wraps rnn_forward and rnn_backward as one autograd op for cell='rnn' and trains it with stateful TBPTT. Gradient clipping, from Learning-rate schedules and gradient clipping, caps the explosion this diagnostic predicts.

Each piece here has a production counterpart worth reading:

This pieceProduction equivalentWhat it addsWhere to look
rnn_forward/rnn_backwardcuDNN RNN (cudnnRNNForward, cudnnRNNBackwardData)the input matmul for all steps as one GEMM, persistent kernels keeping WhhW_{hh} in registersaten/src/ATen/native/cudnn/RNN.cpp
tbptt_gradsKeras stateful=True, fairseq’s detach between chunksstateful batching where row bb of each batch continues row bb of the previous onekeras/layers/rnn/base_rnn.py
gradient_flowgradient-norm logging and clipping (clip_grad_norm_)clipping caps the explosion this diagnostic predictstorch/nn/utils/clip_grad.py
the vanilla celllinear recurrences (S4, Mamba, RWKV)recurrences with ρ\rho held below 1 by construction, trained in parallel over timemamba_ssm/ops/selective_scan_interface.py
  • Werbos, “Backpropagation Through Time: What It Does and How to Do It” (1990).
  • Williams and Peng, “An Efficient Gradient-Based Algorithm for On-Line Training of Recurrent Network Trajectories” (1990).
  • Pascanu, Mikolov, and Bengio, “On the difficulty of training recurrent neural networks” (2013).
  • Backpropagation through time (BPTT): reverse-mode differentiation of the recurrence unrolled over time, with weights shared across steps.
  • Carry: the gradient aˉt+1Whh⊤\bar a_{t+1} W_{hh}^\top that step t+1t + 1 sends back into hth_t, added to the loss’s direct gradient gtg_t.
  • Truncated BPTT, TBPTT(k1k_1, k2k_2): run the forward straight through and, every k1k_1 steps, backpropagate the latest k1k_1 losses through at most k2k_2 steps, treating the entering state as a constant.
  • Spectral radius ρ(W)\rho(W): the largest eigenvalue magnitude of WW, which sets the long-run growth or decay rate of repeated multiplication by WW.
  • Exploding and vanishing gradients: gradient norms that grow or shrink like ρT−1−t\rho^{T-1-t} as they travel back through the recurrence.
  • BPTT is reverse mode on the unrolled loop: the gradient reaching hth_t is what the loss sends it directly plus what step t+1t + 1 sends back through WhhW_{hh}.
  • Every step’s backward is two matmul VJPs and the tanh derivative 1−ht21 - h_t^2, read from the saved output, so the forward must keep every hidden state.
  • Shared weights accumulate their gradients over steps, and Wˉhh\bar W_{hh} pairs aˉt\bar a_t with the previous state ht−1h_{t-1}.
  • Truncated BPTT keeps the forward running but cuts the gradient: every k1k_1 steps, the losses since the last cut are differentiated back k2k_2 steps; with k2≥Tk_2 \ge T it is full BPTT.
  • The gradient into an early state is the late one multiplied by Whh⊤W_{hh}^\top once per step, so its norm grows or shrinks like ρ(Whh)T−t\rho(W_{hh})^{T-t}: exploding and vanishing gradients, predicted by the spectral radius.
  1. In the hand example, why would Wˉxh\bar W_{xh} be 0 without the carry?
    AnswerThe loss reads only $h_1$, and $x_1 = 0$, so step 1 contributes $x_1 \bar a_1 = 0$ to $\bar W_{xh}$. The only nonzero contribution is $x_0 \bar a_0$, and $\bar a_0$ comes entirely from the carry (the direct gradient $g_0$ is 0). Dropping the carry makes the first input, which decides $h_1$, look useless.
  2. Why does Wˉhh\bar W_{hh} at step tt pair aˉt\bar a_t with ht−1h_{t-1} and not hth_t?
    AnswerThe term in $a_t$ is $h_{t-1} W_{hh}$; the VJP of $Y = AB$ with respect to $B$ is $A^\top \bar Y$, and $A$ here is $h_{t-1}$, the state that was multiplied. At $t = 0$ that is the start state $h_0$.
  3. In tbptt_grads, why is gw zero before prev_end - start?
    AnswerWindows overlap when $k_2 > k_1$. The losses of steps before `prev_end` were already backpropagated at the previous cut; including them again would count them twice and make the truncated gradient larger than full BPTT.
  4. A non-normal WhhW_{hh} has spectral norm 2.13 but ρ=0.5\rho = 0.5. Do gradients explode or vanish over long spans, and why does gradient_flow multiply by Whh.T?
    AnswerThey vanish: repeated multiplication grows like $\rho^k$ in the long run, even though a few steps can grow by up to the norm. The backward of $h_{t-1} W_{hh}$ multiplies the gradient by $W_{hh}^\top$, and a diagnostic that used $W_{hh}$ itself would follow a different map.
  5. Why does truncation not change the forward?
    AnswerTruncation is an approximation of the gradient, not of the model. The states are those of the real recurrence over the whole stream; only the backward stops at $h_{s-1}$, which is treated as a constant. `tbptt_grads` makes this explicit by running one full forward and slicing it.