Chapter 9: Recurrent Networks
Every model in the book so far predicts from a fixed window of context. This chapter gives the model a state: a vector it updates once per token, so in principle it can carry information across any distance. Making that work in practice is a story about gradients. You start by writing backpropagation through time by hand for a vanilla RNN, and you see exactly why the gradient into an early state vanishes or explodes: it is a product of Jacobians, one per step, and its size is governed by the spectral radius of the recurrent matrix. Clipping and gating are the cures.
Concepts from other sections (18)
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.
- Backpropagation through time (BPTT): reverse-mode differentiation of the recurrence unrolled over time, with weights shared across steps. Read more: 9.1 Vanilla RNN with manual BPTT and truncation
- Jacobian: the matrix of partial derivatives of a function . Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP in Mathematics
- Spectral radius: . Read more: 9.4 Eigenvalues, power iteration, and the spectral radius in Mathematics
- Gated recurrent unit (GRU): a recurrent cell with one state and two gates, . Read more: 9.3 GRU (torch gate order)
- Bidirectional layer: two recurrent modules, one reading left to right and one right to left, with outputs concatenated per position. Read more: 9.4 Bidirectional RNN with length-aware reversal
- Linear probe: a softmax regression fitted on frozen features to measure what a layer encodes in easily usable form. Read more: 9.5 ELMo: biLM, ScalarMix, linear probes
- Exploding and vanishing gradients: gradient norms that grow or shrink like as they travel back through the recurrence. Read more: 9.1 Vanilla RNN with manual BPTT and truncation
- RNN language model: an embedding, a recurrent layer, and a linear read-out trained to predict the next token. Read more: 9.6 RNN language model with stateful TBPTT
- biLM: a forward and a backward language model over the same sentence, sharing the embedding and the softmax, trained separately in each direction. Read more: 9.5 ELMo: biLM, ScalarMix, linear probes
- ScalarMix: , a learned per-task convex combination of layers with a scale. Read more: 9.5 ELMo: biLM, ScalarMix, linear probes
- vector-Jacobian product (VJP): the function mapping an output gradient to input gradients without forming the Jacobian. Read more: 6.2 Tensor, broadcasting backward, and no_grad
- 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
- op library (
F): the module of differentiable functions, each a NumPy forward plus one closed-form VJP joined byfrom_op. Read more: 6.3 The op library and gradcheck_all - 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
- cell state: the LSTM’s additively updated memory, protected by forget, input, and output gates. Read more: Chapter 3: Neural Architectures and Their History
- Dropout: randomly zeroing activations during training to approximate an ensemble of subnetworks. Read more: Chapter 2: Deep Learning
- Padding mask: a per-step boolean that freezes a finished sequence’s state and zeros its output. Read more: 9.2 LSTM (torch gate order)
- Bits per character (bpc): mean negative log-likelihood in nats divided by . Read more: 9.6 RNN language model with stateful TBPTT
The gated cells come next. The LSTM adds a memory cell updated by addition, so along it the gradient is multiplied only by a learned forget gate; the GRU gets most of the same effect with one state and two gates. Both are built in torch’s exact gate order and parameter layout, so weights load from torch checkpoints, and a golden comparison catches the gate-order and reset-placement bugs that otherwise fail silently. Then you compose two single-direction cells into a bidirectional layer, which looks trivial until padded batches force a length-aware reversal. The chapter closes by turning all three cells into a language model trained with stateful truncated BPTT, where the state flows across training windows but the gradient is cut at each boundary. An optional section on ELMo shows how the states of a bidirectional language model become contextual word vectors, and how a linear probe measures what each layer has learned.
Learning objectives
- Derive and implement backpropagation through time by hand, including truncation, and predict exploding and vanishing gradients from the spectral radius.
- Build LSTM and GRU cells, stacked and masked for padded batches, that match torch’s outputs, gradients, and parameter names.
- Compose a bidirectional layer with a length-aware reversal that keeps padding out of both directions.
- Train an RNN language model with stateful truncated BPTT: contiguous lanes, detached carried state, epoch resets, and clipping.
- (Optional) Build a biLM, mix its layers with ScalarMix, and probe them with a linear classifier.
Before you begin
Section titled “Before you begin”You should be comfortable with vector-Jacobian products, from Matrix differentials, the trace trick, and closed-form VJPs, and with gradient clipping, from Learning-rate schedules and gradient clipping, both in Mathematics. The spectral radius comes from Eigenvalues, power iteration, and the spectral radius. Everything here runs on the autograd engine, op library, and module system of Part 0, and the language model is compared against the models of Part 2. For a C implementation of the LSTM cell worked through by hand, see lstm_cell.c in Neural Architectures, whose RNN and LSTM sections this chapter absorbs.
In this chapter
Section titled “In this chapter”- Vanilla RNN with manual BPTT and truncation: backpropagation through time written by hand as reverse mode on the unrolled loop, truncated BPTT as bookkeeping on windows, and a gradient-flow diagnostic that predicts explosion and vanishing from .
- LSTM (torch gate order): the additive cell state that keeps gradients alive, built in torch’s layout with a forget bias of 1, orthogonal recurrence, stacking, dropout, and padding masks.
- GRU (torch gate order): one state and two gates, with the reset gate placed where torch and cuDNN put it, and the test that tells the two placements apart.
- Bidirectional RNN with length-aware reversal: two directions joined per position, with a per-sequence reversal that is its own inverse and keeps padding at the end.
- ELMo: biLM, ScalarMix, linear probes (optional): a bidirectional language model whose layers become contextual word vectors, a learned mix of them, and a deterministic linear probe.
- RNN language model with stateful TBPTT: the three cells as language models, trained on one long stream with a carried, detached state, evaluated in bits per character.
Further reading
Section titled “Further reading”- Olah, Understanding LSTM Networks; Karpathy, The Unreasonable Effectiveness of Recurrent Neural Networks.
- Hochreiter and Schmidhuber, Long Short-Term Memory (1997); Cho et al., GRU; Peters et al., ELMo.