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?

\(W\): 100 × 100 = 10,000; \(U\): 100 × 32 = 3,200; \(b\): 100. Total 13,300, whatever the length of the sequence.

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.)

\(0.9^{50} \approx 0.005\): half a percent. The early inputs get almost no say in learning.

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) \]

GateAsks
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?

\(\partial c_t / \partial c_{t-1} = f_t\): no matrix, no squash. A plain RNN multiplies by \(W\) and tanh's slope at every step. Additive paths are the common thread with residual networks.

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
  1. One step back: \(\partial h_t / \partial h_{t-1} = \operatorname{diag}(\tanh'(z_t))\, W\), a matrix.
  2. \(k\) steps back is the product of \(k\) such matrices. If they were all the same \(M\), it would be \(M^k\).
  3. 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.
  4. 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.
  5. 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 / LSTMTransformer (chapters 7 and 10)
TrainingStep by step: step 50 waits for step 49, so a GPU can't work on all positions at onceAll positions at once: one big matrix product per layer
Long-range linksThrough every step in between, if the gates allowDirect: any word attends to any other in one step
Cost per new token when generatingConstant: update one stateGrows with the context: attend to everything so far
Memory of the pastA fixed-size stateEverything 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?

A GPU is thousands of cores waiting for independent work (the GPUs lesson). Recurrence makes each step depend on the previous one; attention doesn't.

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

5. What to carry forward

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