Key takeaways
- An RNN (recurrent neural network) carries a fixed-size memory, the hidden state, and updates it token by token with the same weights every time. But during training the gradient has to pass through a long chain of multiplications, so it tends to vanish or explode.
- The LSTM (long short-term memory) gives memory its own conveyor belt, the cell state ct, guarded by forget, input and output gates. Gradients can travel a long way back along that belt.
- A Transformer links any two words in a single step and trains in parallel. The price is O(n2) attention compute and a KV cache that keeps growing.
- A state space model (SSM) uses a linear recurrence that can be rewritten as a convolution, so training is parallel and generation is cheap. Mamba makes B, C and Δ depend on the input, so it can remember selectively.
- In theory, with one hidden unit per transition, a ReLU RNN can simulate any DFA exactly, so RNNs can recognize at least every regular language.
Taking notes as you read
Back in episode 7, we saw that every time a Transformer generates a new word, it looks back at every single word that came before. The longer the context, the more there is to look at, and the KV cache from episode 12 keeps growing right along with it.
That's not how people read. As we read, we keep a few notes in our head: read a word, update the notes, keep going. And those notes stay the same size, no matter how thick the book is.
Could we build a model that works this way? That's exactly the idea behind the RNN. Before the Transformer came along, RNNs and their upgraded cousin, the LSTM, ruled language tasks for years (roughly RNN → LSTM → GRU → Transformer). And lately, state space models like Mamba have brought the idea roaring back. This episode follows that thread all the way through.
Intuition: An RNN is like a reader who takes notes as they go. It reads tokens left to right, and after each one it updates the memory in its head (the hidden state), then uses that memory to make sense of the next token. It can't flip back to earlier pages. Everything rides on one memory vector that keeps getting overwritten.
Recurrent networks: one rule, used over and over
A one-dimensional warm-up
Start with the simplest case, where the memory is a single number called the hidden state, h. Each time an input x comes in, we update h with the same rule:
ht=tanh(1.0⋅xt+0.5⋅ht−1)
tanh is the activation function from episode 1; its output always stays between −1 and 1. Start with h0=0 and feed in 1,−1,0.5:
- Step 1: 1×1+0=1, and tanh(1)≈0.76.
- Step 2: −1+0.5×0.76=−0.62, and tanh(−0.62)≈−0.55.
- Step 3: 0.5−0.28≈0.22, and after tanh it's still about 0.22.
Every h blends the current input with a memory of the past.
Vectors and matrices
In a real RNN, at each step t the input is a vector xt∈RD and the previous hidden state is ht−1∈RH, where D is the input size and H is the hidden size. The two coefficients become two weight matrices, Wx∈RH×D and Wh∈RH×H, plus a bias b:
ht=tanh(Wxxt+Whht−1+b)
To make a prediction, one more output matrix turns ht into an output yt, such as scores for the next word:
yt=Woutht+bout
Watch out: The key point is that every step uses the same Wx and Wh: the weights are shared across time steps. It's like applying one rule to every word, which is why an RNN can handle sequences of any length with a fixed number of parameters.
Unrolling the loop through time
Now unroll that loop through time. This time the memory is a 2-dimensional vector, and the input is three vectors, for "The", "cat" and "sat":
- Step 1: h0 is all zeros. Read in "The", and we get h1≈(0.66, 0.29).
- Step 2: multiply the vector for "cat" by Wx to get (−0.5, 0.9), and multiply h1 by Wh to get (0.39, −0.09). Add them, pass the result through tanh, and out comes h2≈(−0.11, 0.67).
- Step 3 works the same way and gives h3.
Drawn out, that's three boxes in a row, but they're really one and the same unit with the same weights, just reused at different moments. At every step the network can also output a y that predicts the next word: after "The" it guesses "cat", after "The cat" it guesses "sat". Compare the guesses with the right answers and you get the loss.
Watch out: There's a fundamental limit here. h2 has to wait for h1, and h3 has to wait for h2. The computation can only go one step at a time, so it can't run in parallel.
Vanishing and exploding gradients
The gradient travels back along the chain
During training, the gradient of the loss has to travel back along this chain one step at a time. This is called backpropagation through time. By the chain rule from episode 2, each step backward multiplies the gradient by one more factor, ∂ht−1∂ht:
∂h1∂L=∂h6∂L⋅∂h5∂h6⋅∂h4∂h5⋯∂h1∂h2
In our one-dimensional example, that factor is tanh′(zt)×0.5. The derivative of tanh is at most 1 and gets much smaller as z moves away from zero, so each step back shrinks the gradient by at least half.
Small factors, multiplied many times
Even a factor just a little below 1 adds up fast, and the same goes for a factor just above 1:
| Steps back |
×0.9 per step |
×1.1 per step |
| 10 |
about 0.35 |
about 2.6 |
| 50 |
about 0.005 |
about 117 |
| 100 |
about 3 in 100,000 |
over 13,000 |
The first is a vanishing gradient: inputs from long ago get almost no learning signal. The second is an exploding gradient: a single update can fling the parameters way off course.
The vector case: a product of matrices
With vectors it's the same story, except each step's factor becomes a matrix. Let zt=Wxxt+Whht−1+b. Then
∂ht−1∂ht=diag(tanh′(zt))Wh
a diagonal matrix of tanh derivatives, times Wh. Going back T−1 steps multiplies that many of these matrices together:
∂h1∂hT=t=2∏Tdiag(tanh′(zt))Wh
Since tanh′∈(0,1], those derivatives can only shrink things, and Wh gets multiplied in over and over. The result usually either fades to zero or blows up.
Watch out: Vanishing gradients aren't a bug. They're a mathematical consequence of the structure itself: the same matrix multiplied again and again, plus a saturating activation. Exploding is the easier problem, since gradient clipping from episode 4 can catch it. Vanishing is the real trouble.
Take this sentence: "I grew up in France", then dozens of words later, "I speak fluent". To guess "French", the gradient has to travel all the way back to "France". That's why a plain RNN struggles with long-range dependencies like this one. To fix it, we have to change the architecture itself.
LSTM: a conveyor belt for memory
The belt and its three gates
The LSTM (long short-term memory), proposed in 1997, became the most successful fix for this problem. The core idea: give the memory its own conveyor belt.
The belt is called the cell state, ct. Once information is on it, it can ride straight along, meeting only element-wise multiplication and addition on the way: no matrix multiplication, and no tanh.
To erase or write anything, you have to go through a gate. Each gate is a sigmoid that outputs a number between 0 and 1, like a valve: 0 is fully closed, 1 is fully open. Every gate looks at the same two things: the previous hidden state ht−1 and the current input xt. (So at each step an LSTM takes three inputs: ht−1, ct−1 and xt.)
- The forget gate, f, decides how much of the old memory to keep, multiplying the c on the belt one entry at a time. It was actually added a few years after the original 1997 design.
- The input gate, i, teams up with a candidate, c~. The candidate is the new information this step wants to write; the input gate decides how much of it gets written, and that gets added onto the belt.
- The output gate, o: first the memory on the belt goes through a tanh, then the output gate picks which parts to take out, and those become this step's hidden state h.
That h does double duty: it's this step's output, and it's passed on to the next step, where it controls that step's gates.
Intuition: Take the single, constantly overwritten memory of an RNN and upgrade it to a conveyor belt. Information rides steadily along the belt, and a few valves decide what gets erased, what gets written and what gets read out.
The formulas
The square brackets [ht−1,xt] mean we glue the previous h and the current x together into one long vector. The three gates share the same form, each with its own weights:
ft=σ(Wf⋅[ht−1,xt]+bf)
it=σ(Wi⋅[ht−1,xt]+bi)
ot=σ(Wo⋅[ht−1,xt]+bo)
The candidate uses tanh instead, so its values fall between −1 and 1:
c~t=tanh(Wc⋅[ht−1,xt]+bc)
The heart of it all is this line: forget some of the old ct−1, then add some of the new c~t. The circle with a dot, ⊙, means element-wise multiplication:
ct=ft⊙ct−1+it⊙c~t
Finally, the new hidden state is
ht=ot⊙tanh(ct)
Plugging in numbers
|
Entry 1 |
Entry 2 |
Entry 3 |
| Old memory ct−1 |
2 |
−1 |
0.5 |
| Forget gate ft |
1 |
0.1 |
0.9 |
| Input gate it |
0 |
0.9 |
0.2 |
| Candidate c~t |
0.3 |
0.8 |
−0.5 |
| New memory ct |
2 |
0.62 |
0.35 |
| Output gate ot |
0 |
1 |
0.5 |
| Hidden state ht |
0 |
0.55 |
0.17 |
- Forget gate: entry 1 is kept completely (times 1), entry 2 is almost wiped out (times 0.1).
- Input gate: nothing gets written into entry 1 (times 0), while entry 2 takes in most of its new content. For entry 2: 0.1×(−1)+0.9×0.8=0.62.
- The 2 in entry 1 rides along on the belt, completely untouched.
- The output gate is 0 for entry 1, so h is 0 there: entry 1 is still remembered, it just isn't used at this step.
Why the gradient survives
Take one step back along the belt, and the derivative of ct with respect to ct−1 is simply the forget gate, applied element by element:
∂ct−1∂ct=diag(ft)
When ft is 1, multiplying the gradient by 1 a hundred times still leaves 1. Even with f at 0.99, about 0.37 survives after 100 steps, far better than the 3 in 100,000 we got with 0.9.
Intuition: As long as the forget gate stays near 1, ct=ft⊙ct−1+… basically copies the old memory straight over, so gradients can travel back through many time steps almost undamaged. The belt is a highway with only element-wise multiplications and additions, no matrix multiplications and no nonlinearities. Information is added or removed only through the gates.
Cell state vs. hidden state
An LSTM carries two vectors with different jobs:
- ct is the long-term memory.
- ht=ot⊙tanh(ct) is a filtered view for the current output. It plays two roles: (1) the cell's output to the outside world, and (2) the cell's query into itself on the next step, because all the gates at step t+1 are computed from ht, not from ct.
A plain RNN makes a single vector serve as both long-term memory and current output, and it ends up doing neither job well. Splitting the two apart is exactly why the LSTM works. The later GRU is a simplified version with just two gates, a reset gate and an update gate.
RNN vs. Transformer: head to head
First, how does information get from the first word to the eighth?
- In an RNN, the first word's information has to squeeze into the hidden state and survive every update along the way. And gradients from a distant time step can't influence how an earlier time step was processed.
- In a Transformer, the eighth word looks straight at the first one through attention: one step, no matter how far apart they are. The gradient flows back along that same direct path.
Attention gives a direct, O(1) path between any two tokens, regardless of the distance between them: each token looks directly at every other token, and all pairwise relationships are computed at once. That's the fundamental reason Transformers are so good at long-range dependencies.
Next, parallelism. In training the whole sentence is already known, so with a causal mask a Transformer computes every position in one go. An RNN has to go one by one: step eight waits for the seven before it. As we saw in episode 14, GPUs excel at doing huge numbers of identical calculations at once, so Transformers train much faster. That's a big reason they replaced RNNs after 2017.
But Transformers pay a price too: attention compute grows with the square of the length, and during generation the KV cache keeps getting bigger. An RNN only has to update one fixed-size state per new word, so its cost per word is constant.
|
Training |
Generating one token |
| RNN / LSTM |
O(n), one step at a time |
fixed cost |
| Transformer |
parallel, attention O(n2) |
reads the whole KV cache |
Is there a way to get the best of both, training in parallel like a Transformer and generating as cheaply as an RNN? That's exactly what state space models set out to do.
State space models: starting from continuous time
A leaky bucket
State space models come from control theory. They describe a system that changes continuously over time.
Picture a leaky bucket. The water level is the state h. A tap pours water in, and how fast it pours is the input x. There's a small hole near the bottom, and the higher the water, the faster it leaks. As equations:
h′(t)=Ah(t)+Bx(t)
y(t)=Ch(t)
h′ is the rate of change of the water level. A is negative: that's the leak. B sets how strongly the inflow fills the bucket, and the output we actually see, y, is C times h. Turn the tap on and the level rises; turn it off and the water slowly drains away. The system remembers its recent input and gradually forgets it.
In a real SSM, h is an N-dimensional vector and A is an N×N matrix, usually a diagonal one. The idea is the same as this one-dimensional bucket.
Discretization: chopping time into slices
Text comes as separate tokens, not a continuous signal. So we chop time into small slices, each Δ long. This step is called discretization.
A derivative is just change divided by time, so
Δhk−hk−1≈Ahk−1+Bxk
Multiply both sides by Δ and move hk−1 over to the right:
hk≈hk−1+ΔAhk−1+ΔBxk
Collect the terms:
hk≈(1+ΔA)hk−1+ΔBxk
Call those two coefficients Aˉ and Bˉ, and we have a recurrence:
hk=Aˉhk−1+Bˉxk,yk=Chk
With a more exact discretization, Aˉ=eΔA, which is about 1+ΔA when Δ is small, and Bˉ≈ΔB.
Intuition: This looks almost exactly like an RNN: the old state times one coefficient, plus the input times another. The difference is that there's no tanh, so the update is linear. That linearity is what makes the next trick possible.
Watch out: You may see different letters elsewhere: the input written as uk (a 1D signal) and the latent state as xk (N-dimensional), giving xk=Axk−1+Buk. Here we use x for the input and h for the state to match the RNN above. It's the same equation.
One model, two ways to compute it
The recurrent view
Take Aˉ=0.5, Bˉ=0.5 and C=1, with inputs 1,2,0,1, and start from h0=0:
- h1=0.5×0+0.5×1=0.5
- h2=0.5×0.5+0.5×2=1.25
- h3=0.625
- h4=0.8125
This is the recurrent view: just like an RNN, one step after another.
The convolutional view
Because the update is linear, we can unroll the recurrence completely:
h4=Bˉx4+AˉBˉx3+Aˉ2Bˉx2+Aˉ3Bˉx1
The coefficient on x4 is Bˉ, x3 picks up one extra factor of Aˉ, and so on: the earlier the input, the more times it gets multiplied by Aˉ. Line these coefficients up and you have the convolution kernel:
K=(CBˉ, CAˉBˉ, CAˉ2Bˉ, CAˉ3Bˉ)=(0.5, 0.25, 0.125, 0.0625)
It depends only on Aˉ, Bˉ and C, not on the input. So every output is a weighted sum of the inputs, with the kernel as the weights:
yk=j≤k∑Kk−jxj
Check y4: 0.0625×1+0.125×2+0.25×0+0.5×1=0.8125, exactly what the recurrence gave.
Convolution for training, recurrence for generation
- Training: the kernel is fixed and the whole sequence is known, so the outputs at every position can be computed at the same time. Training runs in parallel, with compute growing almost linearly with length.
- Generation: switch back to the recurrent view. Each new token updates the fixed-size state h just once, and nothing piles up the way a KV cache does. The cost per step is fixed.
In complexity terms: SSMs are O(n) and parallel during training, then O(1) per step and sequential during inference. Transformers are parallel but have O(n2) attention; RNNs are O(n) but sequential. SSMs aim to have it both ways.
Mamba: remembering selectively
Parameters that depend on the input
An SSM like the one above treats every input exactly the same. Whether it reads a key piece of information or a filler word like "um" or "so", it handles them all the same way.
Mamba, introduced in 2023, made one key change: B, C and the step size Δ all become functions of the current input:
Bk=fB(xk),Ck=fC(xk),Δk=fΔ(xk)
- B decides how much of this token gets written into the state.
- C decides what gets read out of the state.
- Δ controls the time scale: how long this step should be remembered.
How Δ does its job
Back to the one-dimensional bucket: Aˉ=eΔA, and A is negative, say A=−1, so Aˉ=e−Δ.
- When Δ is small, Aˉ is close to 1: the old state is kept almost untouched, and this token is just skimmed over.
- When Δ is large, Aˉ is close to 0: the old memory gets wiped, and the state is mostly set by the current token.
So the model can learn on its own to skim over filler words, hold on tight to key information, and clear out old context when it needs to. That's what "selective" means.
The catch, and the trade-off
Once the parameters change with the input, the kernel is no longer fixed, so the convolutional view stops working. Instead Mamba uses an algorithm called a parallel scan, which merges results in pairs like a tree (8 leaves reach the root in 3 rounds), together with optimizations tailored to the GPU. It still trains in parallel, and its compute grows linearly with length.
Adding SSMs to the comparison table:
|
Training |
Generating one token |
| RNN / LSTM |
O(n), one step at a time |
fixed cost |
| Transformer |
parallel, attention O(n2) |
reads the whole KV cache |
| SSM / Mamba |
parallel (convolution or scan), about O(n) |
fixed cost |
Watch out: There's no free lunch. The memory is still a fixed size, so the history has to be compressed. When you need details from long ago word for word, like copying out a long passage exactly, Transformers usually still come out ahead. That's why quite a few models now mix attention layers with SSM layers, so each covers the other's weak spots.
Mamba's selective mechanism keeps the efficiency of SSMs while adding the ability to decide what to remember based on content, which is what turned SSMs into serious competitors to the Transformer.
Theory: formal languages
To finish, a theoretical question. An RNN is a machine that moves forward carrying a fixed-size memory. Just how complex a pattern can a machine like that recognize? The classes of languages from the theory of computation answer exactly this kind of question, "how powerful a device do you need to recognize a given structure?", which ties directly into what neural networks can express.
What's a "language"?
In computer science, any set of strings is called a language. For example, all the strings of 0s and 1s that contain an even number of 1s form a language.
- A regular language is one that a finite state machine (also called a finite automaton) can recognize. A finite state machine has a limited number of states, and each time it reads a character it follows a rule to jump to its next state. The most common kind is the DFA (deterministic finite automaton): the current state plus the character just read pins down exactly one next state.
- A context-free language takes a pushdown automaton to recognize: a finite state machine plus a stack. A stack can hold any number of items, but you can only see the one on top.
Matching parentheses needs a stack
To check whether parentheses match, push each opening one onto the stack and pop one off for each closing one. If the stack is exactly empty when you finish, they match. Reading (()()), for instance, ends with an empty stack. Programming-language syntax, nested function calls and matching pairs of HTML tags all belong to this family.
Why can't a finite state machine do this? Because nesting can go arbitrarily deep. Say the machine has only three states. By the time it reads the fourth opening parenthesis, it must land in the same state as some earlier depth. Now it can't tell which depth it's at, so it doesn't know how many closing parentheses to expect. More states won't help: nest one level deeper and you get another collision.
So the regular languages sit inside the context-free languages. Also, every finite language is regular: list all of its valid strings, and with enough states a machine can recognize every one of them.
A tiny DFA: is the number of 1s even?
This DFA checks whether a string of 0s and 1s contains an even number of 1s. It needs just two states: even and odd.
- It starts in "even". Read a 0 and the state stays put; read a 1 and it jumps to the other state.
- "Even" is the accepting state (drawn as a double circle): if the machine ends up there after reading the whole string, the answer is "yes".
Try 0101. Read 0: stay in even. Read 1: jump to odd. Read 0: stay in odd. Read 1: jump back to even. It ends in even, so it accepts, and sure enough, 0101 has two 1s.
Through the whole run, the machine remembers just one thing: which state it's in right now. Doesn't that sound a lot like an RNN's hidden state?
ReLU as an AND gate
It's more than a resemblance: any DFA can be simulated exactly by a ReLU RNN. Let's build one.
The idea is to use one-hot encoding: a vector with a single 1 and zeros everywhere else, which says "this is the situation right now". Characters get encoded the same way.
The key tool is ReLU: negative numbers become 0, positive numbers pass straight through. If a and b can only be 0 or 1, then
ReLU(a+b−1)={1,0,a=b=1a+b≤1
In other words, it's an AND gate: it outputs 1 only when both conditions hold.
The most direct approach, and why it fails
The most direct approach: make the hidden dimension equal to the number of states k, holding a one-hot encoding of the current state. For each transition δ(qi,σk)=qj (in state qi, reading character σk, go to qj), set
(Wh)ji=1,(Wx)jk=1,bj=−1
Apply it to our parity machine: two hidden units, one for even and one for odd. Two transitions lead into even: even reading a 0, and odd reading a 1. So the "even" unit gets a weight of 1 from both even and odd, and a weight of 1 from both characters.
The result? No matter where it was or what it reads, it computes 1+1−1=1. The unit is stuck on.
Watch out: The problem is that addition can't tell "even with a 0" apart from "even with a 1". All it knows is that the state side added a point and the character side added a point. For the AND gate to check one specific combination, this state with that character, every combination needs a unit of its own.
Simulating a DFA with a ReLU RNN
One unit per transition arrow
The fix: let each hidden unit stand for one transition arrow of the DFA. The parity machine has four arrows, so the hidden state gets four units:
| Unit |
Transition arrow |
| ① |
even —read 0→ even |
| ② |
even —read 1→ odd |
| ③ |
odd —read 0→ odd |
| ④ |
odd —read 1→ even |
When a unit lights up, it means we just followed that arrow. If unit ② is lit, we were just in even and read a 1.
The rule for setting weights stays the same; we just apply it arrow by arrow. Take arrow ②, which starts from even and reads a 1:
- every arrow that arrives at even (① and ④) gives it a weight of 1;
- the character 1 gives it a weight of 1;
- the bias is still −1.
Now the ReLU AND gate checks exactly two things: did the last step arrive at even, and is this step reading a 1? Only when both are true does this arrow light up. Set up all four arrows this way and you get two matrices of 0s and 1s, with every bias at −1:
Wh=1100001100111100,Wx=10100101,b=−1−1−1−1
The two columns of Wx are for the characters 0 and 1. The update rule is ht=ReLU(Whht−1+Wxxt+b).
Running 0101
To start, light up unit ①. It's an arrow that leads into even, so it tells the network "we're in even right now".
Step 1 reads a 0:
- Whh: since h is one-hot, it just picks out the first column of Wh, (1,1,0,0), meaning "the last step came into even";
- Wxx picks out the column for the character 0, (1,0,1,0), meaning "we just read a 0";
- add them to get (2,1,1,0), subtract 1 to get (1,0,0,−1), and ReLU gives (1,0,0,0).
Only unit ① stays lit: even reads a 0 and stays in even. Exactly right. The next three steps work the same way: units ②, ③ and ④ light up in turn, matching the DFA's path step for step.
For the final output, add up arrows ① and ④, the ones that arrive at the accepting state, even. The result is 1: accept.
The general result
In general, with k states and m characters there are at most k×m transitions. Give the hidden state k×m units, one per transition, and you can simulate any DFA exactly. So an RNN can recognize at least every regular language.
And the other way around: if its numbers have finite precision, the hidden state can only take finitely many values, so an RNN like that is itself just a very large finite state machine.
Recap
- An RNN carries a fixed-size hidden state and updates it with the same weights at every step. But the gradient has to pass through a long product of diag(tanh′)Wh factors, so it tends to vanish or explode, and long-range dependencies are hard to learn.
- The LSTM uses its cell state as a conveyor belt with forget, input and output gates, separating long-term memory c from the current output h. With the forget gate near 1, gradients travel a long way along the belt. The GRU is a two-gate simplification.
- A Transformer links any two words in one step and trains in parallel, at the cost of O(n2) attention and an ever-growing KV cache.
- Discretizing the continuous SSM equation gives a linear recurrence, hk=Aˉhk−1+Bˉxk, which can be rewritten as a convolution: parallel training, fixed cost per generated token. Mamba makes B, C and Δ depend on the input to remember selectively, and trains with a parallel scan. But a fixed-size memory still can't recall details word for word as well as attention.
- In theory, regular languages ⊂ context-free languages, and with one unit per transition a ReLU RNN can simulate any DFA exactly.
Next time: how a language model learns to see images, in multimodality.