AI from scratch · Recurrent networks · Stage 5: seeing and reading
Recurrent networks
A CNN looks at a whole image at once. Text, speech, sensor readings and prices arrive one piece at a time, and what a piece means depends on what came before. A recurrent network (RNN) reads a sequence in order and carries a running summary, its hidden state, from each step to the next. For a decade RNNs ran speech recognition, translation and phone keyboards. Then transformers (chapter 7, next on the path) replaced them for most text, for reasons this lesson makes concrete. It's still worth knowing them well: the problem they ran into, and the gates that fixed it, show up all over deep learning.
1. Memory in a loop
An RNN is one small layer applied at every step. It takes the new input \(x_t\) and its own previous state \(h_{t-1}\), and makes the next state:
\[ h_t = \tanh(W h_{t-1} + U x_t + b), \qquad \hat y_t = V h_t \]
The same \(W, U, b\) are used at every step, like chapter 6's filter is used at every position: one set of weights, any length of sequence. Below is a tiny RNN built by hand (no training) with two hidden numbers: one counts how deep inside brackets you are, the other flips between 0 and 1 each time it sees a quote mark. Type, and watch its state after each character.
A bracket inside quotes doesn't count: the depth update is multiplied by "not inside quotes". That's the whole point of a hidden state: what a character does depends on what the network has seen. A trained RNN finds states like these on its own; Karpathy's 2015 char-RNN essay found single neurons that tracked quotes and line lengths in exactly this way.
An RNN has 100 hidden units and reads 32-dimensional inputs. How many numbers are in \(W\), \(U\) and \(b\) together?
- 10,000
- 13,300
- 13,300 × the sequence length
An RNN applies one small layer at every step, feeding its own output back in, so its state is a running summary of everything read so far.
2. Training it: backpropagation through time
To train, unroll the loop: a sequence of 50 steps becomes a 50-layer network whose layers all share the same weights, and chapter 4's backprop runs through it (backpropagation through time, BPTT). The blame for an error at step 50 reaches step 1 by being multiplied, once per step, by the same kind of factor: \(W\) times the slope of tanh. The toolkit lesson on deep nets met this exact problem in depth instead of time. Change the factor and the gap:
plain RNN LSTM memory cell
Below 1, the signal from far back vanishes, so the network can't learn that something 40 steps ago matters. Above 1 it explodes, and one huge gradient wrecks the weights; gradient clipping (rescale the gradient whenever its length passes a limit, torch.nn.utils.clip_grad_norm_) is the standard guard, and every RNN training loop uses it.
The gradient is multiplied by 0.9 at each step back. About how much of it reaches 50 steps back? (A decimal.)
Training unrolls the loop into a deep network with shared weights, so the gradient is multiplied by the same factor at every step back: it vanishes or explodes.
3. Gates: LSTM and GRU
The LSTM (long short-term memory, 1997) adds a second state, the cell \(c_t\), that changes by addition instead of by passing through a matrix and a squash. Three gates, each a sigmoid between 0 and 1 computed from \(x_t\) and \(h_{t-1}\), decide what happens to it:
\[ c_t = f_t \odot c_{t-1} + i_t \odot g_t, \qquad h_t = o_t \odot \tanh(c_t) \]
| Gate | Asks |
|---|---|
| forget \(f_t\) | How much of the old memory to keep (1 = all of it) |
| input \(i_t\) | How much of the new candidate \(g_t = \tanh(\dots)\) to write in |
| output \(o_t\) | How much of the memory to show as the state \(h_t\) |
(\(\odot\) multiplies entry by entry.) Going back one step through the cell multiplies the gradient by just \(f_t\). If the network learns to keep \(f_t\) near 1 for something worth remembering, the gradient survives hundreds of steps: the widget's green line. It's the same idea as a residual connection, a path where information is added rather than transformed, found 18 years earlier. The GRU (2014) merges the gates into two and the states into one; it's a little smaller and often about as good.
How much does it matter? In the practice notebook both networks must remember the first of 40 random symbols until the end of the sequence. After 2,000 training steps the plain RNN is at chance (12.5%); the LSTM, with its forget-gate bias started at 1, gets it right every time.
Why does the LSTM's memory carry gradients so much further back than a plain RNN's state?
- It has four times the parameters
- Because sigmoids have bigger slopes than tanh
- The cell is updated by addition, so stepping back multiplies the gradient only by the forget gate, which can stay near 1
An LSTM keeps a separate memory updated by addition, with gates deciding what to forget, write and show, so gradients can travel back as far as the forget gate stays open.
Why the gradient through a plain RNN shrinks or grows geometrically
- One step back: \(\partial h_t / \partial h_{t-1} = \operatorname{diag}(\tanh'(z_t))\, W\), a matrix.
- \(k\) steps back is the product of \(k\) such matrices. If they were all the same \(M\), it would be \(M^k\).
- Linear algebra 2: \(M^k\) stretches each eigenvector direction by \(\lambda^k\). Any eigenvalue below 1 in size dies away geometrically; any above 1 blows up.
- tanh's slope is at most 1 and usually smaller, which pushes everything toward vanishing; a large \(W\) pushes the other way. Keeping the whole product near 1 for hundreds of steps by tuning \(W\) alone is a knife-edge.
- The LSTM sidesteps it: along the cell, one step back is just \(\operatorname{diag}(f_t)\), with entries the network controls directly, and no squash in between.
4. RNNs and transformers
| RNN / LSTM | Transformer (chapters 7 and 10) | |
|---|---|---|
| Training | Step by step: step 50 waits for step 49, so a GPU can't work on all positions at once | All positions at once: one big matrix product per layer |
| Long-range links | Through every step in between, if the gates allow | Direct: any word attends to any other in one step |
| Cost per new token when generating | Constant: update one state | Grows with the context: attend to everything so far |
| Memory of the past | A fixed-size state | Everything in the context window |
The first two rows are why transformers won for text: training on GPUs at scale needs parallel work, and direct links learn long-range patterns more easily. The last two rows are why recurrence keeps coming back: newer "state-space" models such as Mamba and RWKV are recurrent networks designed to train in parallel, aiming for a transformer's quality with an RNN's constant cost per token.
Why can a transformer train on a 1,000-token text much faster on a GPU than an LSTM of similar size?
- The LSTM must compute step 1,000 after step 999 after step 998…, while the transformer computes all positions in parallel
- The transformer has fewer parameters
- Transformers don't use matrix products
RNNs read in order with a fixed-size memory; transformers look at everything at once, which trains faster on GPUs and links distant words directly.
Where it breaks: what gates don't fix
- Very long gaps. Gates help, not cure. In the notebook's memory test, the LSTM that solved a gap of 40 is at chance on a gap of 80 after the same training; memory over thousands of steps is still hard for RNNs.
- A fixed-size state is a bottleneck. Everything about a long text must squeeze into the same few hundred numbers. Translation RNNs compressed a whole sentence into one vector and did badly on long sentences, which is exactly why attention was invented (the seq2seq elective tells that story).
- Small data, big memory. On the 379 station names, every recurrent model in the notebook learns the training names nearly by heart while its loss on held-out names stops improving early: stop at the best validation loss, as chapter 11 says.
5. What to carry forward
- RNN: \(h_t = \tanh(W h_{t-1} + U x_t + b)\), the same weights at every step.
- BPTT multiplies the gradient by the same factor each step back: vanishing or exploding. Clip gradients.
- LSTM: a memory updated by addition, gated by forget, input and output; start the forget bias at 1. GRU: a lighter cousin.
- Transformers replaced RNNs for text because they train in parallel and link distant positions directly; recurrence lives on where constant cost per step matters.
All lessons: AI from scratch. Christopher Olah's "Understanding LSTM Networks" and Andrej Karpathy's "The Unreasonable Effectiveness of Recurrent Neural Networks" are the classic companions.
Last updated