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 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 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.
- bigram model: a language model that predicts the next token from the current token alone, stored as a table. Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- Reverse mode: automatic differentiation that records the computation and walks it backward once from the output, pushing adjoints into inputs. Read more: 14.2 Scalar reverse mode: the Value graph in Mathematics
- VJP (vector-Jacobian product): , the gradient of ; what reverse mode computes. Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP in Mathematics
- vanishing gradient: the shrinking of gradients through a long product of Jacobians, which prevents learning long-range dependencies. Read more: Chapter 3: Neural Architectures and Their History
- Spectral radius: . Read more: 9.4 Eigenvalues, power iteration, and the spectral radius in Mathematics
- hidden states: the block inputs and outputs, before the final norm, that a VLM can tap. Read more: 14.3 Vision transformer encoder
- Eigenvector / eigenvalue: a non-zero and scalar with . Read more: 9.4 Eigenvalues, power iteration, and the spectral radius in Mathematics
- Golden test: a comparison against numbers an independent implementation produced and a maintainer recorded. Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
- Gradient norm: a measure of update magnitude before optimizer-specific scaling. Read more: 17.5 Training failures, profiling, and recovery
- QR algorithm: the iteration , converging to block upper triangular (real Schur) form. Read more: 9.4 Eigenvalues, power iteration, and the spectral radius in Mathematics
- Spectral norm: , the largest stretch of a unit vector. Read more: 9.5 SVD, Eckart-Young low rank, and least squares in Mathematics
- central differences: the numerical derivative , used as an oracle for analytic gradients. Read more: 6.3 The op library and gradcheck_all
- Gradcheck: a comparison of a hand-written gradient against central differences of . Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
- cell state: the LSTM’s additively updated memory, protected by forget, input, and output gates. Read more: Chapter 3: Neural Architectures and Their History
- Gradient clipping: rescaling all gradients by one factor when their global norm exceeds a limit. Read more: 16.4 Learning-rate schedules (cosine, WSD, Noam) and gradient clipping in Mathematics
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 .
- Write each step’s backward as two matmul VJPs and the tanh derivative , accumulating the shared weight gradients.
- Implement truncated BPTT(, ) as bookkeeping on windows, and check it against full BPTT.
- Predict exploding and vanishing gradients from the spectral radius , and explain why the diagnostic multiplies by .
The recurrence and its notation
Section titled “The recurrence and its notation”The table below fixes the symbols used throughout the section, with their shapes.
| Symbol | Meaning | Type / shape |
|---|---|---|
| time steps, batch size, input size, hidden size | integers | |
| the input at step (a row per batch element) | float64[B, D] | |
| the hidden state after step ; is the given start | float64[B, H] | |
| , , | input-to-hidden, hidden-to-hidden weights, bias | [D, H], [H, H], [H] |
| the pre-activation | [B, H] | |
| a scalar loss computed from the hidden states | real | |
| the total gradient reaching | [B, H] | |
(dh_all[t]) | the part of that comes directly from the loss at step | [B, H] |
| the gradient of the pre-activation | [B, H] | |
| spectral radius, over ‘s eigenvalues | real | |
| truncation: cut every steps, backpropagate steps | integers |
The recurrence is with , for . The same three parameters are used at every step: the network is one cell applied 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 and weight_hh_l0 , and two biases whose sum is ; the golden test maps between the two conventions.
BPTT is reverse mode on the unrolled loop
Section titled “BPTT is reverse mode on the unrolled loop”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 feeds two places: the loss at step (through whatever reads it, an output layer in the RNN language model), and step through . So its total gradient is the sum of both paths:
The second term is the carry. Walking , you keep it in a variable and add it to before anything else. Then you pass through the tanh, using , read from the saved output so that need not be kept:
From there each step is two matmul VJPs. The pre-activation contains and , both of the form , whose VJP is , . So
The weight gradients accumulate over time, because the same weight is used at every step, and pairs with the previous state , the one that was multiplied. After the carry is .
Exploding and vanishing gradients
Section titled “Exploding and vanishing gradients”That carry is also where the trouble starts. If the loss only reads the last state, the carry from step back to step is multiplied by once per step. Near the linear regime ( small, ) that is applied times, and the component along the top eigenvector grows or shrinks by per step. So the gradient norm behaves like : for it is times larger 30 steps back, and for about 1500 times smaller. Saturated tanh units () shrink it further.
gradient_flow returns the per-step norms and (computed with the QR algorithm from the spectral-radius section), the diagnostic to print when training stalls. Note the transpose: walking back multiplies by , and for a non-normal the spectral norm (largest singular value) can be large while is small. The long-run growth is set by .
Truncated BPTT
Section titled “Truncated BPTT”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(, ) runs the forward straight through and, every steps, differentiates the losses of the last steps back through at most steps. The window ending at starts at . The state entering it, , is a constant (the cut), and only the losses of steps 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 every loss reaches its whole history exactly once, which is full BPTT. With no gradient crosses at all. The RNN language model uses with the state carried across batches (stateful TBPTT).
Working it by hand
Section titled “Working it by hand”Take , , , , , inputs , and the loss (the state after the second step), so .
Forward. ; .
Backward at . The carry is 0, so . Then . That gives , , , , and the carry becomes .
Backward at . , so . Then , (the start state is 0), and , so . Finally and .
Without the carry, would be 0 and would be 0: the first input would look useless although it decides .
Truncation windows. With , , , the cuts fall at 4, 8, and 10 (the last, partial chunk), reaching back to , , and : [(0, 4), (2, 8), (4, 10)]. The window 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 , , , , and , they expect , , and . They add central differences with a dh_next, the windows with a partial chunk, against rnn_backward, one-step windows, and gradient_flow on a non-normal .
Designing the interface
Section titled “Designing the interface”The module exposes a cache type and five functions:
class RNNCache(NamedTuple): x; h0; h; Wxh; Whh # what the backward needsdef 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, bhdef 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 .
Building it step by step
Section titled “Building it step by step”Before reading the code, it helps to see the reasoning chain that fixes its shape.
- The backward needs every state. Each step’s VJP needs its input , the previous state (for ), and ; all are functions of the saved . So the forward stores the whole
[T, B, H]tensor and the cache holdsx,h0,h, and the two weight matrices. The pre-activation is not stored, because . - Walk time in reverse with one carry. has two consumers (the loss at and step ), so its gradient is a sum; processing down to 0, the second term is exactly what step just produced. One variable, initialised from
dh_next, holds it. - Each step is two matmuls, so two VJPs.
matmul_vjp(da, x_t, Wxh)gives andmatmul_vjp(da, h_prev, Whh)gives (the next carry, the contribution). Reusing the tested primitive means no transposes are written by hand, which is where sign and orientation bugs live. - Shared weights accumulate. The same , , are used at every step, so their gradients are sums over steps; per-step inputs () are written once.
- Truncation is bookkeeping on windows. Each cut at differentiates the losses since the previous cut through at most steps, treating the entering state as a constant. That means: run
rnn_backwardon the window withh0set to , a gradient that is zero for steps already counted, and sum the results. - Diagnose with the actual backward map. The carry is multiplied by per step; the diagnostic must apply exactly that, and report as the long-run growth rate.
The forward
Section titled “The forward”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 readsThe backward
Section titled “The backward”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/dh0Trace the hand example through it. At , carry is 0, dh is 1, and da is 0.874879; the first VJP gives and adds 0 to dWxh (since ); the second gives the carry and adds to dWhh. At , 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 .
Truncation windows
Section titled “Truncation windows”The window list has ends every steps plus a last partial chunk, and each window reaches back .
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 k1k2 < k1 is refused because the window would not contain all the losses it is responsible for. The hand example, , , , gives ends 4, 8, 10 and windows [(0, 4), (2, 8), (4, 10)].
Truncated gradients
Section titled “Truncated gradients”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 = 0for 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 = endreturn outBuilding 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 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 each window is one step whose entering state is a constant, so dWhh only receives from the immediate loss and no gradient travels through to an earlier step.
Gradient flow
Section titled “Gradient flow”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 normThe full solution is manual.py.
Why this design
Section titled “Why this design”Forward and backward both cost time. Memory is for the saved states, which is what full BPTT costs and what truncation bounds: TBPTT(, ) runs rnn_backward over windows of at most steps, time, and a streaming implementation needs only states at once.
The cache saves and not because , so is enough, and is needed anyway: it is the output, and feeds . Saving too would double the memory for nothing. The backward reuses matmul_vjp because the transposes in , 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 ” 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 ); 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 .
What can go wrong
Section titled “What can go wrong”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.
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| The two-step hand example | unit | every number of the hand example | the carry and are right |
| Gradcheck of full BPTT | gradcheck | all five gradients against central differences | the backward is the derivative of the forward |
dh_next enters at the last step | gradcheck | a gradient arriving from after the sequence | stacking and windows in the language model |
| Matches autograd | differential | the same forward through Tensor gives the same gradients | the language model fuses this as one autograd op |
| Matches torch’s RNN | golden | torch.nn.RNN outputs and gradients with transposed weights and summed biases | the convention is torch’s |
| TBPTT window examples | unit | the hand windows, tiling, the partial chunk, bad arguments | the trainer’s schedule |
| TBPTT with long reach is full BPTT | property | equals full BPTT for every | each loss counted exactly once |
| TBPTT cuts long paths | unit | : no gradient crosses | what truncation gives up |
| Gradient flow explodes and vanishes | property | norms follow along the top eigenvector; reported | diagnosing a stalled run |
| Gradient flow uses | unit | a non-normal : per step, not the norm 2.13 | the diagnostic predicts the real gradient |
| Shapes and bad arguments | boundary | ; mismatched shapes raise | errors at the call site |
The bugs these checks catch fall into five families.
Warning: Forgetting to carry the gradient from step into 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 , or computing it from the wrong saved value, puts gradients off by a factor that grows with . The solution uses
da = dh * (1.0 - h[t] * h[t])with the same step’s output.
Warning: Pairing with instead of in , 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 h0anddWhh += dW.
Warning: TBPTT bookkeeping errors (reaching back instead of , 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 instead of , or with the spectral norm, makes the diagnostic predict explosion where the gradient vanishes.
gradient_flowmultiplies byWhh.Tand reportsspectral_radius.
Where this leads
Section titled “Where this leads”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 piece | Production equivalent | What it adds | Where to look |
|---|---|---|---|
rnn_forward/rnn_backward | cuDNN RNN (cudnnRNNForward, cudnnRNNBackwardData) | the input matmul for all steps as one GEMM, persistent kernels keeping in registers | aten/src/ATen/native/cudnn/RNN.cpp |
tbptt_grads | Keras stateful=True, fairseq’s detach between chunks | stateful batching where row of each batch continues row of the previous one | keras/layers/rnn/base_rnn.py |
gradient_flow | gradient-norm logging and clipping (clip_grad_norm_) | clipping caps the explosion this diagnostic predicts | torch/nn/utils/clip_grad.py |
| the vanilla cell | linear recurrences (S4, Mamba, RWKV) | recurrences with held below 1 by construction, trained in parallel over time | mamba_ssm/ops/selective_scan_interface.py |
Further reading
Section titled “Further reading”- 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).
Key terms
Section titled “Key terms”- Backpropagation through time (BPTT): reverse-mode differentiation of the recurrence unrolled over time, with weights shared across steps.
- Carry: the gradient that step sends back into , added to the loss’s direct gradient .
- Truncated BPTT, TBPTT(, ): run the forward straight through and, every steps, backpropagate the latest losses through at most steps, treating the entering state as a constant.
- Spectral radius : the largest eigenvalue magnitude of , which sets the long-run growth or decay rate of repeated multiplication by .
- Exploding and vanishing gradients: gradient norms that grow or shrink like as they travel back through the recurrence.
Summary
Section titled “Summary”- BPTT is reverse mode on the unrolled loop: the gradient reaching is what the loss sends it directly plus what step sends back through .
- Every step’s backward is two matmul VJPs and the tanh derivative , read from the saved output, so the forward must keep every hidden state.
- Shared weights accumulate their gradients over steps, and pairs with the previous state .
- Truncated BPTT keeps the forward running but cuts the gradient: every steps, the losses since the last cut are differentiated back steps; with it is full BPTT.
- The gradient into an early state is the late one multiplied by once per step, so its norm grows or shrinks like : exploding and vanishing gradients, predicted by the spectral radius.
Review questions
Section titled “Review questions”- In the hand example, why would be 0 without the carry?
Answer
The 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. - Why does at step pair with and not ?
Answer
The 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$. - In
tbptt_grads, why isgwzero beforeprev_end - start?Answer
Windows 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. - A non-normal has spectral norm 2.13 but . Do gradients explode or vanish over long spans, and why does
gradient_flowmultiply byWhh.T?Answer
They 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. - Why does truncation not change the forward?
Answer
Truncation 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.