Part III Β· Ch. 9 β€” Remembering Machines

Part III Β· Chapter 9 of 13

Remembering Machines

RNNs and LSTMs β€” and why transformers took their crown


When order is the whole point

Last chapter's CNN treated an image as a grid and shared one small filter across every position in space. That works because a picture is, at heart, a bag of neighborhoods. But now say a sentence out loud β€” "the dog chased the cat" β€” and shuffle it: "the cat chased the dog." Same five words, opposite meaning. For pictures, a bag of pixels is fine. For language, order is the signal, and a network that ignores order is useless.

Two things about a sequence break the plain stack of neurons from the neuron. The first is length: a sentence can be three words or three hundred, but a fixed grid of neurons expects a fixed-size input, and there is no natural number of slots to pour a sentence into. The second is order and context: the meaning of a word depends on what came before it β€” "bank" after "river" is a muddy edge, "bank" after "money" is a vault β€” so the network needs some memory of the sequence so far. A grid has neither. It sees everything at once and remembers nothing.

The fix is the spine of this whole chapter. Instead of swallowing the sequence in one gulp, read it one element at a time β€” the way you are reading this line, left to right β€” and carry a running summary of everything seen so far. That running summary is a hidden state, and a network built to loop over a sequence this way, updating that memory at each step, is a recurrent neural network, or RNN. One picture holds the whole idea.

Two panels. Left panel 'the loop (rolled)': a single rounded box labeled 'RNN cell' with a mint input arrow entering from below labeled x-t, a mint arrow leaving the top labeled h-t, and a curved violet arrow leaving the right side and looping back into the left side of the same box, labeled 'h-(t minus 1) β€” memory fed back'. Right panel 'the loop (unrolled)': three identical cell boxes in a row for t=1, t=2, t=3, each with a mint input arrow from below labeled x-1, x-2, x-3 and a mint output arrow above labeled h-1, h-2, h-3; between adjacent boxes a horizontal violet arrow carries the hidden state left to right like a baton, tagged 'same weights', and each cell is tagged 'shared w-x, w-h, b'.
One cell, run over and over. An RNN is a single cell with its output looped back as next step's input (left) β€” or, unrolled, one copy of the same cell per time step, passing the hidden state along like a baton (right). The weights are shared across every step, exactly as a CNN shares its filter across every position β€” here the sharing is across time. That one shared cell can read a sequence of any length.

Now the honest arc, so this chapter has stakes. RNNs were how machines read for years β€” translation, speech recognition, the autocomplete on your phone β€” and then, around 2017, they were almost entirely replaced by a different idea called attention. This chapter builds the RNN for real, shows you the exact weakness that doomed it, and tells the honest, mechanical story of why its successor won. The successor is built in full on the sister site; here we earn the reason it had to exist.

The loop: one step, repeated

Let us build the recurrent cell, and it turns out we already own every piece. At each time step $t$, the cell takes two things β€” the current input $x_t$ (the new word) and the previous hidden state $h_{t-1}$ (the memory so far) β€” mixes them with weights, and produces the new hidden state $h_t$. That is a neuron from the neuron, whose two inputs happen to be "the new thing" and "what I remembered," and whose output becomes next step's memory. Written out:

$$h_t = f\!\left(w_x\,x_t + w_h\,h_{t-1} + b\right)$$

In words: blend a bit of the new input with a bit of the old memory, add a bias, squash the result with an activation $f$, and that squashed number is the updated memory β€” which then feeds the next step.

Here is the fact that makes it work: the same weights $w_x$, $w_h$, and $b$ are used at every single step. The network does not learn one rule for word 1 and a different rule for word 50; there is only ever one cell, run over and over. This is precisely the weight sharing from seeing machines, moved off the space axis and onto the time axis: one small rule, applied repeatedly. And that is exactly what lets an RNN swallow a sequence of any length β€” three words or three hundred, it is the same single cell run more or fewer times. The two views in the figure above β€” the compact "rolled" loop and the "unrolled" chain β€” are the same machine; we will reason with the unrolled one, where the hidden state passes down the line like a baton.

Now the smallest honest example, with numbers you can check on your fingers. Set the weights so plain you can watch the memory form: $w_x = 1$, $w_h = 1$, $b = 0$, and use no squash at all (the identity, $f(z) = z$). The update collapses to a running total, $h_t = h_{t-1} + x_t$. Start the memory at $h_0 = 0$ and feed the sequence $x = (1, 0, 1)$:

$$h_0 = 0,\quad h_1 = h_0 + x_1 = 1,\quad h_2 = h_1 + x_2 = 1,\quad h_3 = h_2 + x_3 = 2$$

In words: the memory starts at zero; the first input $1$ pushes it to $1$; the middle input $0$ leaves it untouched at $1$; the last input $1$ lifts it to $2$. The final hidden state, $2$, is the count of $1$s in the sequence β€” the network remembered across the zero in the middle.

A left-to-right chain of three RNN cell boxes for t=1, 2, 3, preceded on the far left by a small chip 'h-0 = 0'. Into each cell from below is a mint input chip: x-1 = 1, x-2 = 0, x-3 = 1. Along the top the hidden state passes right on violet arrows with the running value in a violet chip after each cell: h-1 = 1, h-2 = 1, h-3 = 2. Under each cell is the arithmetic: h-1 = 0 + 1 = 1, h-2 = 1 + 0 = 1, h-3 = 1 + 1 = 2. Far right, an amber callout box reads 'final memory h-3 = 2 = the count of 1s' with a note 'it remembered across the zero'. A header top-left reads 'update: h-t = h-(t minus 1) + x-t, with w-x=1, w-h=1, no squash'.
A recurrent cell remembering, by hand. With the weights set to a running total ($w_x = w_h = 1$, no squash) the hidden state carries a count: fed $1, 0, 1$ it goes $1 \to 1 \to 2$. The middle zero adds nothing, but the memory survives it, and the final state, $2$, is the number of $1$s in the whole sequence. Nobody stored the inputs β€” a single carried number summarized them. Real cells carry a richer vector and remember far subtler things.

Read what just happened, because it is the whole point. Nobody stored the individual inputs; the hidden state carried a summary β€” here, a running count β€” and that one number let a later step know something about earlier ones. The identity squash was a convenience for hand-checking; real cells use a genuine activation (usually $\tanh$, a cousin of the sigmoid) and a hidden state that is a whole vector of numbers, not a single one β€” so no reader should walk away thinking an RNN is literally an adding machine. Swap in that real squash and those extra hidden numbers and the same loop can track far subtler things than a count: whether we are inside a quotation, what the subject of the sentence was, whether a verb is still waiting for its object. Memory is just a vector, carried forward and updated.

The fading memory

Here is a sentence the running-sum toy could never fake. "The keys that the man near the old wooden desks by the window ... were on the table." Is it "was" or "were"? It is "were" β€” the verb must agree with "keys," ten words back. To get this right, an RNN has to carry the single fact "the subject is plural" in its hidden state across every intervening word, without letting it get overwritten by "man," "desks," "window," and the rest. In practice, plain RNNs lose it. Let us see exactly why, because the reason is the heart of the chapter.

To learn a long-range dependency, training has to send blame backward from the verb all the way to the far-back subject β€” the same backpropagation from teaching the network, where the chain rule multiplies a local slope at every step along the path from a weight to the loss. In an unrolled RNN, that path runs through every time step between the verb and the subject, and β€” because it is the same cell each time β€” each step multiplies the traveling signal by roughly the same factor, the recurrent weight $w_h$. (Real cells also multiply by the activation's slope at each step; one honest factor is enough for the picture.) Multiply the same number by itself many times over and exactly one of two things happens.

Make it concrete. Suppose that per-step factor is about $0.5$. Then the signal that survives back to a distant word is:

$$0.5^{5} \approx 0.03, \qquad 0.5^{10} \approx 0.001, \qquad 0.5^{20} \approx 0.000001$$

In words: five steps back, the signal is already down to three percent of its strength; ten steps back, a thousandth; twenty steps back, about a millionth β€” effectively zero. The blame from a distant word arrives so faint it cannot teach the network anything about that word.

This is the same vanishing-gradient problem you first met at the sigmoid's flat tails in drawing boundaries β€” but with a new twist. There, the signal shrank as it passed back through layers; here it shrinks as it passes back through time steps, one multiply per step. And if the factor is a touch bigger than $1$ instead β€” say $1.5$ β€” the opposite disaster strikes: $1.5^{20} \approx 3300$, the signal explodes and training blows up. That is the exploding-gradient problem, usually patched by the blunt trick of capping the signal's size when it grows too large. Below $1$ it vanishes; above $1$ it explodes; the knife edge of exactly $1$ is not something training can balance on.

A line chart. The x-axis is 'steps back through the sequence' from 0 to 20; the y-axis is 'strength of the training signal' on a linear scale from 0 to 1. A red curve labeled 'factor 0.5 β€” vanishes' starts at 1 and collapses toward zero by about step 10, with three callouts: at step 5 about 0.03, step 10 about 0.001, step 20 about 0.000001. A gentler amber curve labeled 'factor 0.7 β€” fades slower, still gone' decays more slowly but is still near zero by step 20. A faint band near y=0 is labeled 'signal too faint to learn from'. A note reads 'each step multiplies the signal by the same factor β€” exponential decay'.
Why an RNN forgets. To learn a long-range link, the training signal must travel back through every step, and each step multiplies it by roughly the same factor. Below $1$, that is exponential decay: at a factor of $0.5$ the signal is a thousandth of its strength after ten steps and a millionth after twenty β€” far too faint to teach the network anything about distant words. This is the vanishing gradient, and it is baked into the loop.

State the consequence plainly, without drama. A plain RNN can reliably learn dependencies a handful of steps apart, but the memory of anything far back fades exponentially β€” it forgets the beginning of a long sentence by the time it reaches the end. This is not a bug you can tune away by making the network bigger or training it longer; it is baked into the repeated-multiplication structure of the loop itself. The entire next idea exists to defeat it.

Gates: a conveyor belt for memory

The vanishing gradient comes from forcing every memory through the same squashing multiply at every step. So the fix, kept brief because its algebra is the sister site's business, is to stop doing that. A LSTM (short for "long short-term memory") adds a second track: a cell state that runs along the whole sequence like a conveyor belt, edited only by small, gentle, controlled tweaks instead of being rebuilt from scratch each step. Because information can ride that belt almost untouched, its gradient does not get multiplied away β€” the memory survives.

A schematic of one LSTM cell. A wide horizontal mint track runs across the top of the cell like a conveyor belt with a few chevrons, labeled 'cell state β€” the conveyor belt', entering as c-(t minus 1) on the left and exiting as c-t on the right. Two small valve glyphs interrupt the belt: a red-tinted valve labeled 'forget gate β€” wipe some' and just after it an amber-tinted valve labeled 'input gate β€” add some', each drawn as a small circle with a sigma symbol and a note '0 = shut, 1 = open'. Below the belt, a mint input chip x-t and a violet hidden chip h-(t minus 1) feed a small box that produces the gate signals, with thin arrows up to the valves. At the right, a violet-tinted valve labeled 'output gate β€” reveal some' taps the belt and produces the outgoing hidden state h-t leaving the top-right. A caption strip at the bottom reads 'memory rides the belt almost untouched β€” edited by gentle, learned valves, not rebuilt each step'.
The LSTM's rescue: a protected memory line. A cell state runs straight through the whole sequence like a conveyor belt, edited only by gentle sigmoid valves β€” a forget gate wipes a little, an input gate adds a little, an output gate reveals a little as the hidden state. Because moving along the belt is mostly addition, not repeated multiplication by a weight, the training signal can travel far back without vanishing. Same recurrent loop as before, better plumbing.

The valves have names, and we can meet them without drowning in equations. A gate is a valve run by a little sigmoid β€” the squash-to-between-$0$-and-$1$ function from drawing boundaries β€” that outputs a number from $0$ (shut) to $1$ (open) for each piece of memory, and multiplies the signal by it. An LSTM has three. The forget gate decides what to wipe off the belt; the input gate decides what new information to add to it; and the output gate decides what of the belt to reveal as this step's hidden state. That is the whole cast β€” forget, add, reveal.

And here is the one honest sentence about why it beats the plain loop, tying straight back to teaching the network. On the conveyor belt, moving from one step to the next is mostly addition β€” add a little, erase a little β€” rather than repeated multiplication by a weight. And addition does not shrink a gradient the way multiplication does: the training signal can travel far back along the belt without vanishing. That single architectural change let networks learn dependencies hundreds of steps long, and LSTMs went on to power a decade of translation, speech recognition, and text prediction. (A close cousin, the GRU, does the same job with two gates instead of three.)

Why attention took the crown

Even a well-behaved LSTM has two limits it cannot shake, and both spring from the same root: it processes a sequence one step at a time, in order. Name the first limit β€” speed. Because step 50 needs the output of step 49, which needs step 48, the computation is inherently sequential: you cannot work on all the words at once. Modern hardware β€” the GPUs that train these models β€” is built to do thousands of things in parallel, and a machine that insists on going word by word leaves most of that power idle. Train on billions of words this way and it becomes painfully slow.

Name the second limit β€” distance. To connect two far-apart words, an RNN's information has to travel through every step between them, hop by hop, and β€” even with an LSTM's gates β€” something degrades over a long chain. Two words ten apart are ten hops of memory apart. Which raises the question that changed the field: what if any word could look directly at any other word in a single step, no matter how far?

That single step is exactly what attention does, and it is the idea that dethroned recurrence. Instead of passing a memory baton down a chain, attention lets every word compute, in parallel, how much it should attend to every other word, and pull information straight from the relevant ones β€” the plural "keys" that a verb ten words later needs is now one hop away, not ten. No recurrence, no fading baton, and every position computed at once. The full mechanism β€” queries, keys, values, and the weighting that combines them β€” is built step by step on the sister site's chapter on attention; here we need only the reason it won.

Two panels, each showing the same five word-chips in a row: the, keys, were, on, table. Left panel 'recurrence β€” single file': the five chips connected left to right by violet arrows in a chain; a curved red path runs from 'were' back to 'keys', passing through every intervening chip, labeled 'to link were β†’ keys: hop through every step' with a note 'fades over distance'; a tag under the panel reads 'and: one step at a time β€” cannot parallelise'. Right panel 'attention β€” all at once': the same five chips, but now every pair is connected by a thin mint line forming a complete graph, with the direct were–keys link drawn bolder and labeled 'were β†’ keys: one hop, direct'; a tag under the panel reads 'and: every word computed in parallel'.
Why attention won, in one picture. To connect "were" to its far-back subject "keys," a recurrent network must pass information single-file through every word between them β€” slow to compute, and prone to fading over the distance (left). Attention lets every word look at every other word directly and all at once, so "were" reaches "keys" in a single hop and the whole sentence is processed in parallel (right). The advantage was mechanical β€” speed and reach β€” not a deeper grasp of language.

End honest, because "RNNs are obsolete" is too glib. Recurrence is not dead: it still fits streaming and low-resource settings, where you truly do process one element at a time as it arrives, and a newer family of recurrence-flavoured models β€” state-space models like Mamba β€” is a live research direction precisely because processing all positions at once, as attention does, gets expensive when sequences run to hundreds of thousands of tokens. The pendulum may yet swing back. But for the language models of the last several years, attention won, decisively, for the two mechanical reasons above.

Where you'll meet this

Step back and place the chapter in the story. You now understand the two dominant ways to handle a sequence: recurrence (read it in order, carry a memory) and attention (let every position see every other at once). Everything that reads text, audio, or any ordered stream uses one of these β€” and knowing why attention displaced recurrence is knowing the single most important architectural shift in modern AI.

Draw the sister-site thread explicitly. The large language models on the sister site are, at heart, giant attention machines β€” the transformer (see the sister site's attention chapter and the ones around it) is what you get when you take the "every word looks at every other word" idea, stack it dozens of layers deep, and train it on much of the internet. The reader who understands why an RNN's memory fades understands exactly what problem the transformer was built to solve.

Close warm. You have run a recurrent cell by hand β€” a running count, $0 \to 1 \to 1 \to 2$, remembering across a zero β€” watched a memory fade exponentially to a millionth of its strength across twenty steps, seen how a gated conveyor belt rescues it, and learned the honest, mechanical reason attention won: parallelism and reach, not magic. That is the whole arc of how machines learned to read.

What you now know

  • Sequences differ from grids in two ways a plain network cannot handle β€” they vary in length and their meaning depends on order β€” so recurrent networks read them one element at a time, carrying a hidden state that summarizes everything seen so far.
  • A recurrent cell is a neuron whose inputs are the current element and the previous hidden state, using the same weights at every step (weight sharing across time); our running-sum cell fed $1, 0, 1$ carried the count $0 \to 1 \to 1 \to 2$, remembering across the middle zero.
  • Everything the network still knows about the past must fit in one fixed-size hidden state, and learning a long-range link requires backprop to multiply a per-step factor many times β€” below $1$ the signal vanishes exponentially ($0.5^{20}$ is about a millionth), so plain RNNs forget the far past.
  • The LSTM fixes this with a protected cell state β€” a conveyor belt edited only by gentle sigmoid gates (forget, input, output) β€” so memory can ride across many steps by addition rather than repeated multiplication, and the gradient survives.
  • Attention replaced recurrence for language because of two mechanical wins: it processes every position in parallel (fast on modern hardware) and connects any two positions in a single hop (no fading over distance), not because it understands language better.
  • Recurrence is not obsolete β€” it still suits streaming and low-resource settings, and recurrence-flavoured state-space models are a live research direction β€” but for recent large language models, attention won decisively.

Where we're headed. We have now matched network wiring to two shapes of data: grids, where a CNN shares weights across space, and sequences, where an RNN shares weights across time (or attention connects every position at once). But look again at the sentence we kept using β€” draw it not as a chain but as a web of who-relates-to-whom and you have a graph. And plenty of data is only ever a graph: a call network is numbers joined by calls, a social network is people joined by friendships, a road map is intersections joined by streets. There is no grid, no natural left-to-right order, and every node has a different number of neighbors. The next chapter builds the network for this most general shape β€” and reveals the quiet punchline that a CNN is just a graph network on a grid and an RNN is one on a chain. It is also where link analysis β€” reasoning about who connects to whom, and what that says about them β€” finally turns into arithmetic.