The idea
An RNN reads a sequence one element at a time and folds it into a fixed-size hidden state — a running, lossy summary of everything seen so far:
The same , , are reused at every step: weight sharing across time, exactly as a CNN shares weights across space. That makes the model length-agnostic and keeps parameters at regardless of sequence length — but it also means one matrix, , sits on every path from the past to the present.
Backpropagation through time (BPTT). To train, unroll the recurrence into a deep feedforward net with one layer per step (all layers sharing weights), backpropagate, and sum each weight gradient over every step where the weight was used. The chain rule from step back to step multiplies one recurrent Jacobian per step:
Why gradients vanish or explode. A product of near-identical matrices scales like powers of the largest singular value : at per step, 50 steps leave a factor ; at , they produce . So gradients from distant steps either drown (vanish — the model simply never learns long-range dependencies, and trains fine otherwise, which is what makes it insidious) or blow up (explode — loss spikes, NaNs). Tanh saturation compounds the vanishing side: the factor is at most 1 and near 0 for saturated units, dragging the effective per-step factor below .
Fix for explosion: clip. Rescale the gradient when its global norm exceeds a threshold (typically 1–5): if . Direction preserved, step size capped. Cheap, standard — and useless against vanishing, since you cannot rescale a signal that never arrived.
Fix for vanishing: the LSTM. Add a second state, the cell , with an additive update controlled by three sigmoid gates (each a function of and ):
Forget gate : what fraction of old memory to keep. Input gate : how much of the new candidate to write. Output gate : how much of the memory to expose as . The gradient payoff is the direct path through the cell: — no , no tanh derivative. When the network holds near 1, gradients travel back essentially unchanged: a gated highway through time. (Residual connections are the same additive trick with the gate hard-wired to 1.) Practical corollary: initialize the forget-gate bias to 1–2 so the highway starts open.
GRU: the 2-gate budget option. Merge cell and hidden state, keep an update gate and a reset gate :
Three gated blocks instead of four, so about 3/4 the parameters, often matching LSTM quality. (Convention gotcha: some sources swap the roles of and — check before comparing code to a paper.)
What gating never fixed. Training is still sequential — waits for , so no parallelism across positions, which is what GPUs want — and information steps back must still survive updates through a fixed-size state, so effective context stays far below nominal context. Transformers solved both: all positions train in parallel, and attention gives an -hop path between any two tokens. Recurrence remains sensible where its strengths bind: streaming/online inference (constant-size state, per step vs a growing KV cache), small data, constrained compute, and some time series. Modern state-space models (Mamba and kin) revisit exactly this trade with parallelizable training.
Worked example
One LSTM step with scalar states, so every number can be checked by hand. Previous cell , and suppose the gate pre-activations (the values of ) come out as:
| Gate | Pre-activation | Activation | Value |
|---|---|---|---|
| forget | |||
| input | |||
| candidate | |||
| output |
(Check: ; ; ; .)
New cell state — keep 88.1% of the old memory, write half of the candidate:
New hidden state — squash the cell, then let the output gate meter it out:
Note what did not happen to : it was never multiplied by a recurrent weight matrix or pushed through a saturating nonlinearity — only scaled by and nudged additively. The backward derivative along that path is exactly .
Gradient survival 20 steps back, direct path only, per-step factor to the 20th power:
| Architecture | Per-step factor | After 20 steps |
|---|---|---|
| vanilla RNN (saturated tanh, factor ) | ||
| LSTM, forget gate as above | ||
| LSTM, forget gate open () |
The vanilla signal is gone; the open-gate LSTM keeps 82% of it. But note : LSTMs mitigate vanishing, they do not repeal it — any forget gate below 1 still decays geometrically, just with a base the network controls.
Cheat sheet
Vanilla RNN: — same weights every step; hidden state = fixed-size running summary.
BPTT: unroll, backprop, sum gradients over steps; is a product of Jacobians , so it scales like (tanh saturation pushes the effective base lower).
LSTM: , ; ; . Gradient highway: .
| Symptom | Diagnosis | Fix |
|---|---|---|
| Loss spikes / NaNs on long sequences | exploding gradients | clip global norm, , – |
| Model ignores anything more than ~10–20 steps back | vanishing gradients | LSTM/GRU; forget bias init 1–2; ultimately attention |
| LSTM slow to pick up long dependencies early in training | forget gate starts half-closed | initialize to |
| BPTT out of memory / too slow | full-length unroll | truncated BPTT (cuts direct gradient paths at chunk boundaries; hidden state may still carry information forward) |
| Need whole-sequence context per token | unidirectional state | bidirectional RNN (offline tasks only) |
| Vanilla RNN | LSTM | GRU | |
|---|---|---|---|
| Gates | 0 | 3 () | 2 () |
| States | and | only | |
| Params per layer | vanilla | vanilla | |
| Long-range gradient | dies through powers | additive cell path, gated | additive via blend |
- Clipping fixes explosion only — a vanished gradient cannot be rescaled back into existence.
- LSTMs mitigate, not solve: per-step survival is ; but .
- is the exposed working memory; is the protected long-term memory — do not conflate them.
- vs transformers: recurrence trains sequentially ( steps, no position parallelism) with -hop gradient paths; attention trains in parallel with -hop paths but pays compute and a growing KV cache. RNN inference state stays .
- Still reach for RNN/LSTM: streaming/online inference, small datasets, edge/latency budgets, some time series. State-space models (e.g. Mamba) are the modern recurrent revival.
- GRU convention gotcha: whether multiplies the old state or the candidate differs across papers/frameworks.