Recurrent neural networks and BPTT
Sharing one set of weights across time — and paying for it in gradients
Recurrent networks were the first neural architecture to model sequences of arbitrary length, and they ruled NLP from 2014 to 2017. Their equations are simple, but deriving backpropagation through time exposes the product of Jacobians that makes gradients vanish or explode — the single most important training pathology in deep learning, which also explains why residual connections (4.6 Initialization and normalization), gating (6.5 LSTM and GRU) and ultimately attention (7.1 Attention Is All You Need: the big picture) were invented.
You'll be able to
- Classify sequence tasks (one-to-many, many-to-one, many-to-many) and write the RNN recurrence
- Derive backpropagation through time and the Jacobian product ∏ Wᵀ diag(σ′) that controls gradient flow
- Explain vanishing and exploding gradients with a bound and a numeric example, and apply gradient clipping and truncated BPTT
- Train and sample from a character-level RNN language model
Key ideas
- An RNN carries a hidden state hₜ = tanh(W_hh hₜ₋₁ + W_xh xₜ + b) and reuses the same weights at every step; parameters do not grow with sequence length.
- Unrolling over T steps gives a T-layer network with tied weights; BPTT is ordinary reverse-mode autograd on that graph.
- ∂hₜ/∂hₖ = ∏ W_hhᵀ diag(tanh′): a product of t−k Jacobians controls how far gradients travel.
Show 4 more key ideas
- ‖∂hₜ/∂hₖ‖ ≤ (λγ)^{t−k}: gradients vanish when λγ < 1 and may explode when λγ > 1 (0.9⁵⁰ ≈ 0.005, 1.1⁵⁰ ≈ 117).
- Clip gradients for explosions; use gating (LSTM/GRU), careful initialization or residual paths for vanishing; truncate BPTT for cost.
- Train language models with teacher forcing and masked padding, evaluate with perplexity, generate by sampling with temperature.
- RNNs cannot parallelize across time steps — the computational weakness attention and transformers fixed.
Suggested path through this lesson
Sequences need shared weights
A feed-forward network (4.1 From perceptron to MLP; universal approximation) takes a fixed-size input. Text, audio and time series have variable length and the same patterns can appear at any position. Karpathy's taxonomy of sequence tasks: one-to-one (image classification), one-to-many (image captioning), many-to-one (sentiment, "is this review positive?"), many-to-many aligned (part-of-speech tagging) and unaligned (translation, 6.6 Seq2seq, encoder–decoder and beam search). A recurrent network handles all of them with one idea: process the sequence one step at a time, carrying a hidden state that summarizes everything seen so far, and reuse the same weights at every step.
The recurrence
With input (an embedding, 6.3 Word embeddings) and hidden state ,
The parameter count is for the recurrence plus for the output — independent of sequence length. Unrolling the recurrence over steps gives a -layer-deep network whose layers share weights; that picture is what makes training possible with ordinary backprop (4.4 Backpropagation, fully derived). For a language model the target at step is the next token and the loss is the cross-entropy summed over steps, , exactly the n-gram objective of 6.2 Classical NLP and n-gram language models with an unbounded context. A char-RNN trained on Shakespeare generates plausible Elizabethan English by sampling one character at a time and feeding it back in.
Backpropagation through time
Apply the chain rule to the unrolled graph. The loss at step depends on through every earlier hidden state, so
where denotes the "immediate" derivative treating as a constant. Each factor is the Jacobian of one step: the recurrent weight matrix times the diagonal of activation derivatives (for , ). Because weights are shared, the gradient of the total loss is the sum of these contributions over all and all , and in code you simply run reverse-mode autograd over the unrolled graph — that is BPTT.
Intuition. The term says how much the state at time still "remembers" a nudge made at time . For the network to learn a long-range dependency (a subject at position 3 fixing a verb at position 40), this term must be reasonably large for .
Vanishing and exploding gradients
Bound the norm of the Jacobian product using sub-multiplicativity of norms (1.2 Matrices as transformations): if (its largest singular value) and (with for , for the sigmoid), then
If the bound decays exponentially — the gradient from distant steps vanishes and the model learns only short-range structure. If the gradient can explode, producing NaNs and wrecked parameters. In one dimension the picture is exact: with recurrent weight a signal from 50 steps back is scaled by ; with weight it is scaled by . (Pascanu, Mikolov & Bengio, 2013, make this rigorous with the largest eigenvalue of .) Saturated units make things worse because there — the same saturation problem as in deep feed-forward nets (4.2 Activation functions).
Remedies, in order of importance:
- Gradient clipping for explosions: if , rescale . Cheap, standard, used for transformers too (4.5 Optimizers and learning-rate schedules).
- Gating for vanishing: LSTM and GRU add an additive path for the state so the Jacobian has a factor close to the identity (6.5 LSTM and GRU). Residual connections are the feed-forward analogue (4.6 Initialization and normalization).
- Initialization and architecture: orthogonal or identity initialization of (singular values near 1), ReLU RNNs with identity init, layer normalization inside the recurrence.
- Truncated BPTT for cost, not gradients: unroll only steps backward while carrying the hidden state forward. It bounds memory and compute but also bounds the dependency length the model can learn.
Training RNNs in practice
Use teacher forcing: feed the true previous token as input during training, not the model's own sample (6.6 Seq2seq, encoder–decoder and beam search). Batch variable-length sequences with padding and a mask so padded positions contribute no loss (or pack sequences). Apply dropout to inputs/outputs and between layers but not to the recurrent connection unless you use variational dropout (the same mask at every step). Monitor perplexity on held-out text (6.2 Classical NLP and n-gram language models). At inference, sample with a temperature (8.5 Decoding and sampling): low temperature gives repetitive, safe text; high temperature gives inventive nonsense. Sequential dependence means an RNN cannot parallelize over time during training — each step waits for the previous hidden state — which is the computational limitation that attention removed (7.1 Attention Is All You Need: the big picture).
Where this shows up later
- Gated recurrences — 6.5 LSTM and GRU; encoder–decoder RNNs and attention — 6.6 Seq2seq, encoder–decoder and beam search, 6.7 Attention is born.
- The vanishing-gradient product motivates residual connections and normalization — 4.6 Initialization and normalization; clipping and schedules — 4.5 Optimizers and learning-rate schedules.
- Transformers replace the sequential path with attention paths — 7.1 Attention Is All You Need: the big picture; linear RNNs and state-space models revive the recurrence with parallel training — 7.12 Beyond vanilla attention: state space models, long context and hybrids; the character-level LM project — 6.8 Project: character-level language model.
Common pitfalls (4)
- Forgetting that the gradient of shared weights sums contributions from every time step (the double sum in BPTT).
- Treating truncated BPTT as a fix for vanishing gradients; it only limits compute and shortens learnable dependencies.
- Clipping each gradient element instead of rescaling the whole gradient vector by its norm.
- Computing loss on padded positions, which teaches the model to predict padding.
Recap: all 7 key points
- An RNN carries a hidden state hₜ = tanh(W_hh hₜ₋₁ + W_xh xₜ + b) and reuses the same weights at every step; parameters do not grow with sequence length.
- Unrolling over T steps gives a T-layer network with tied weights; BPTT is ordinary reverse-mode autograd on that graph.
- ∂hₜ/∂hₖ = ∏ W_hhᵀ diag(tanh′): a product of t−k Jacobians controls how far gradients travel.
- ‖∂hₜ/∂hₖ‖ ≤ (λγ)^{t−k}: gradients vanish when λγ < 1 and may explode when λγ > 1 (0.9⁵⁰ ≈ 0.005, 1.1⁵⁰ ≈ 117).
- Clip gradients for explosions; use gating (LSTM/GRU), careful initialization or residual paths for vanishing; truncate BPTT for cost.
- Train language models with teacher forcing and masked padding, evaluate with perplexity, generate by sampling with temperature.
- RNNs cannot parallelize across time steps — the computational weakness attention and transformers fixed.
Watch
The unrolled view and a numeric demonstration of exploding/vanishing gradients.
Read
Exercises
- Jacobian product in 1-D
For a scalar RNN with and small inputs so , compute approximately. Repeat with . Expected: (explodes) and (vanishes); then explain what changes if saturates near ±1.
- Char-RNN from scratch
Implement a vanilla RNN language model in PyTorch (embedding → RNN cell → linear → softmax) and train it on a book with truncated BPTT of 64 characters, gradient clipping at norm 1 and Adam. Log perplexity every 500 steps and sample 300 characters at temperatures 0.5, 1.0 and 1.5. Expected: perplexity drops from ≈ V to the single digits per character; low temperature repeats common words, high temperature invents words.
- Watch gradients vanish
In the trained model, compute for using autograd on a single sequence and plot it on a log scale. Expected: roughly exponential decay with ; compare the slope before and after replacing the RNN cell with an LSTM (next lesson).
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →