5.5 — RNNs and backpropagation through time (BPTT)
Goal: Define the vanilla RNN recurrence, derive backpropagation through time, and prove the vanishing/exploding gradient result of Bengio, Simard & Frasconi (1994) that ultimately motivates abandoning recurrence for attention.
1. Why this session exists
The -gram model of 5.4 was crushed by a fixed-range Markov assumption. The first family of neural architectures designed to escape that constraint was the recurrent neural network (RNN), introduced in modern form by Elman (1990)[4].
The mathematical hope of an RNN is elegant: instead of conditioning on a fixed-length window, maintain a hidden state that summarises the entire history , and update it sequentially as new tokens arrive. In principle, an RNN can model arbitrary-range dependencies — the conditioning context is all of the past.
In practice, RNNs hit a structural wall that took two decades to fully diagnose: the vanishing/exploding gradient problem, formalised by Bengio, Simard, and Frasconi (1994)[6]. That problem isn't a bug — it's a consequence of the recurrence structure, and it is the single most important reason modern LLMs abandoned recurrence in favour of attention.
This session does three things:
- Define the vanilla RNN and write down its forward pass.
- Derive backpropagation through time (BPTT).
- Prove the vanishing/exploding gradient bound and quantify what it costs.[2, 3]
2. The vanilla RNN
Fix a hidden-state dimension and an input dimension (the embedding dimension from 5.2). The Elman RNN is defined by three weight matrices, one bias vector, and an initial state:
For a sequence of input embeddings , the recurrence is:
where is a per-coordinate non-linearity (typically in early RNN papers, though ReLU is also used). The logits go through softmax to produce , and the cross-entropy loss of 5.3 is summed over time.
2.1 The unrolled computation graph
The recurrence defines a computation graph that, unrolled over time, looks like a deep feedforward network in which:
- Each "layer" corresponds to one time step.
- All "layers" share the same weights .
- Each layer also receives an external input .
- Each layer also produces an output that contributes to the total loss.
A 4-step unroll has the structure
with branching off from each . This is a depth- network with weight sharing across depth — structurally similar to a CNN sharing weights across space (4.2), but here the sharing is across time.
2.2 Parameter counts
For a hidden size and an input/output dimension (treating embeddings as part of the model):
For an RNN with and , this is around — comparable in size to a modest Transformer, but as we'll see, dramatically less expressive.
3. Backpropagation through time
The loss is the sum of per-step cross-entropies:
We need , , , .
The easy ones first. appears only in , so by 1.8 §4:
The hard ones are and , which are used at every time step. Define the "delta at time ":
Two sources feed 's effect on the loss:
- Directly through . produces , which produces .
- Through the next state . enters , which then influences .
So the backward recurrence for is:
where is the pre-activation at step , and . Read it the way you read the backprop recursion of 2.6 §3: the gradient flows backward through time, multiplied by and the activation-derivative diagonal at each step.
Once you have for every , the parameter gradients are sums over time:
(The diagonal comes from differentiating .)
Because the weights are shared across all time steps, every parameter gradient is a sum of contributions from every time step — not the average or the most recent. This is the discrete-time analogue of weight sharing in a CNN.
3.1 Truncated BPTT
The full BPTT in §3 needs to store every for during the forward pass so that the backward pass can use them. Memory is . For long documents (millions of tokens for an LLM-scale corpus), this is infeasible.
In practice, RNN training uses truncated BPTT (TBPTT): break the sequence into chunks of tokens, run the forward and backward pass within each chunk treating as the previous chunk's final state (no gradient flows across chunk boundaries). Common values: . The cost: any dependency longer than steps gets no gradient signal at all, which compounds the vanishing problem we're about to derive.[1, 7]
4. Vanishing and exploding gradients
The backward recurrence in §3 is a product: depends on multiplied by . Unrolling this product backwards from time to time :
where is the local contribution at time .
The gradient signal from a distant time step has to be multiplied by copies of the same kind of matrix. Take the spectral (operator) 2-norm:
Let \sigma_\max(W) denote the largest singular value of . For , , so — call this bound .
Two qualitatively different regimes:
(a) \sigma_\max(W) \cdot \gamma_t < 1. Each factor shrinks the gradient by at most a constant . After steps:
\|\delta_\tau\|_\text{from-$T$} \le (\sigma_\max(W) \cdot \gamma)^{T - \tau}\, \|\delta_T^\text{(local)}\| \to 0 \quad \text{exponentially in } T - \tau.This is the vanishing gradient: information from a distant future loss can't reach far-past hidden states.
(b) \sigma_\max(W) \cdot \gamma_t > 1. The bound is in the wrong direction — the norm can grow, and empirically often does:
\|\delta_\tau\|_\text{from-$T$} \sim (\sigma_\max(W) \cdot \gamma)^{T - \tau}\, \|\delta_T^\text{(local)}\| \to \infty \quad \text{exponentially in } T - \tau.This is the exploding gradient.
4.1 The Bengio–Simard–Frasconi theorem
Bengio, Simard, and Frasconi (1994) proved a clean version: for a non-linearity with , if \sigma_\max(W) \cdot \gamma < 1, then exponentially as . Conversely, if \sigma_\max(W) \cdot \gamma > 1, the product can grow without bound.
The killer corollary: there is no choice of that simultaneously preserves gradient norm and lets the RNN compute non-trivial functions of long contexts. The same matrix that we need to grow representations over time has to not blow them up, and the boundary \sigma_\max(W) \cdot \gamma = 1 is unstable — small perturbations push the system into vanishing or exploding regimes.
4.2 Mitigations and their limits
(a) Gradient clipping (Pascanu, Mikolov, Bengio, 2013; already covered in 3.7): rescale the gradient if . This bounds the exploding side but does nothing for vanishing.
(b) Careful initialisation. Initialising to be (approximately) orthogonal sets \sigma_\max(W) \approx 1, putting you on the boundary. Helps in practice but doesn't change the asymptotic behaviour.
(c) Gated architectures (LSTM, GRU). Replace the simple multiplicative recurrence with a gated one whose default behaviour is the identity — see Appendix 5.A. This was the dominant mitigation from 1997 until the Transformer in 2017 and substantially extends the practical range of recurrence, but does not eliminate the asymptotic problem.
(d) Attention. The radical solution: replace the recurrent product with a single one-hop dependency from every position to every other. We will see in 5.6 and Chapter 6 why this is qualitatively different from any RNN fix.
5. The other architectural constraint: no parallelism
The vanishing-gradient analysis above is a learning limit. There is a second, often-overlooked limit that is a systems problem.
The RNN forward pass is, by definition, sequential: cannot be computed until is known. For a sequence of length , the GPU must do matrix-vector multiplies in series, each waiting for the previous one.
Compare this with an MLP block on the same sequence. If you pack the embeddings into a matrix , then a "no-recurrence" feed-forward layer is one GEMM that the GPU can parallelise across the -axis. The wall-clock cost is dominated by the matrix size, not by the number of time steps.
This second limit is what makes recurrent models practically untrainable at LLM scale even when LSTMs partially solve the gradient problem. Modern Transformer pretraining processes context windows of 4k–1M tokens in parallel per forward pass. A vanilla RNN would need 4k–1M sequential matrix multiplies per forward pass; there is no GPU large enough or fast enough to make this competitive.
5.6 collects this argument and the long-range argument into a single brief that motivates attention.
6. What we keep going forward
Three durable ideas from RNNs survive into modern LLMs:
- Stateful sequential generation at inference. Even Transformer LLMs generate one token at a time at inference — they maintain an analog of (the KV cache) and update it autoregressively. The inference loop is recurrent in a meaningful sense, even though the training-time forward pass is not.
- The autoregressive loss carries over verbatim from §5.3 — it doesn't depend on the architecture.
- The vanishing-gradient lesson generalises beyond RNNs. Every very deep network (CNN, MLP, Transformer) faces a related issue, mitigated by residual connections and layer normalisation. The structural pattern is the same: design the network so that the gradient has a clean, near-identity path through depth.
(a) Write out the forward pass of a 3-step Elman RNN explicitly: given and weight matrices , write as nested functions. Then write using the chain rule.
(b) Suppose for a scalar and with . What is the behaviour of as for ? Identify which case is vanishing, which is exploding, which is the boundary.
(c) Why does gradient clipping help with exploding but not with vanishing? Sketch the bias it introduces if the true gradient is consistently rescaled down by clipping.
(d) Argue, using §5, that a recurrent network with sequence length would have at least sequential GPU operations per forward pass. Compare with a Transformer that needs kernel launches at most. (Don't compute exact wall-clock; just give the qualitative comparison.)
(e) The KV-cache in a Transformer at inference time stores tensors and updates incrementally. Argue that this is structurally similar to maintaining an RNN's hidden state at inference — and dissimilar from how a Transformer trains. Why is this not a contradiction with §5?
References
- [1]
Bishop, C. M. (2006). Pattern Recognition and Machine Learning, §3.4 and §5.5. — L2 as Gaussian prior / MAP (Appendix 3.A).
↩ - [2]
Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning, §10 (Sequence Modeling: Recurrent and Recursive Nets). MIT Press. — RNN, BPTT, LSTM/GRU (5.5, Appendix 5.A).
↩ - [3]
Prince, S. J. D. (2023). Understanding Deep Learning, §12 (Sequence-to-Sequence Models) and §15 (Recurrent Networks). MIT Press. — Embeddings (5.2), RNN treatment (5.5).
↩ - [4]
Elman, J. L. (1990). "Finding structure in time". Cognitive Science, 14(2), 179–211. — The modern (Elman) RNN (5.5).
↩ - [5]
Hochreiter, S. (1991). Untersuchungen zu dynamischen neuronalen Netzen. Diploma thesis, TU Munich. — First analysis of vanishing gradients in RNNs (already cited in Cap 2; recalled in 5.5).
↩ - [6]
Bengio, Y., Simard, P., & Frasconi, P. (1994). "Learning long-term dependencies with gradient descent is difficult". IEEE Trans. Neural Networks, 5(2), 157–166. — Formal vanishing/exploding gradient theorem for RNNs (5.5 §4.1).
↩ - [7]
Werbos, P. J. (1990). "Backpropagation through time: What it does and how to do it". Proceedings of the IEEE, 78(10), 1550–1560. — BPTT (5.5 §3).
↩