Lesson 4 of 97 min
Recurrent networks and their limit
A recurrent network reads one token at a time and keeps all of it in one small state, so the start fades and every step waits for the one before.
After this lesson you can follow a hidden state through a sequence, and say what it forgets and why attention was the answer.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Keep both LSTM states
An LSTM passes on a hidden state h and a cell state c. The hidden state is the part that goes out to the next layer. The cell state carries memory forward inside the LSTM. batch_first=True puts the batch first in x and out. The states still start with the layer dimension. PyTorch’s LSTM reference
import torch
from torch import nn
torch.manual_seed(7)
x = torch.randn(1, 7, 64)
lstm = nn.LSTM(64, 64, batch_first=True)
out, (h, c) = lstm(x)
print(out.shape, h.shape, c.shape)torch.Size([1, 7, 64]) torch.Size([1, 1, 64]) torch.Size([1, 1, 64])
Watch the three gates
A gate gives each cell its own share between zero and one. The forget gate scales the old cell, the input gate scales the update, and the output gate controls how much becomes visible in the hidden state. Here’s one cell, with the gates already calculated.
old cell ─× forget gate─┐
├─ new cell ─ tanh ─× output gate─ hidden state
update ───× input gate──┘old, update = 0.8, -0.4
forget, add, show = 0.75, 0.25, 0.5
cell = forget * old + add * update
hidden = show * torch.tanh(torch.tensor(cell))
print(round(cell, 3), round(hidden.item(), 3))0.5 0.231
Follow the gradient back
Calling backward() on a loss at the last step also sends a gradient to earlier steps in the same graph. That’s backpropagation through time. In this untrained RNN you can see how much smaller the gradient is at the first input. The sizes depend on the weights and input. PyTorch’s autograd tutorial
torch.manual_seed(7)
seq = torch.randn(1, 20, 8, requires_grad=True)
states, _ = nn.RNN(8, 16, batch_first=True)(seq)
states[:, -1].square().mean().backward()
print(seq.grad[0, 0].norm() < seq.grad[0, -1].norm())tensor(True)
Read a model’s mix of layers
Qwen3.5 uses Gated DeltaNet in 18 of its 24 layers. That state update can train on groups of tokens in parallel. The other six layers use full attention. For streaming sensor readings, an RNN can update its state as each sample arrives. Qwen configuration · Gated DeltaNet paper
from collections import Counter
from transformers import AutoConfig
name = "Qwen/Qwen3.5-0.8B-Base"
revision = "dc7cdfe2ee4154fa7e30f5b51ca41bfa40174e68"
config = AutoConfig.from_pretrained(name, revision=revision)
print(Counter(config.text_config.layer_types))Counter({'linear_attention': 18, 'full_attention': 6})Run on Python 3.13, PyTorch 2.15.0, Transformers 5.24.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Layers and networks
A smaller digits network: nn.Sequential(nn.Linear(64, 16), nn.ReLU(), nn.Linear(16, 10)). Its hidden layer is 16 wide. How many weights does it have, with the biases too?
2 of 3
A recurrent network reads a long text. Why does the start fade from its state?
3 of 3
One text of 12 tokens, each a vector of 64 numbers, goes into PyTorch's recurrent layer. What does this print?
import torch
from torch import nn
rnn = nn.RNN(input_size=64, hidden_size=64, batch_first=True)
x = torch.zeros(1, 12, 64)
out, h = rnn(x)
print(out.shape, h.shape)The ideas in this lesson
- Recurrent network
- It reads one token at a time, passing a state of fixed size from step to step through the same layer.
- What the state forgets
- One state of fixed size has to take in every token, so each new one pushes the older ones out.
- Why attention replaced it
- Each step waits for the one before and the start fades; attention lets every token look back at every token at once.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Recurrent networks
Here's a question. Before today's models, a model read text one piece at a time. It kept one note of what it had read. That note never grew. So what happens to the first words, a few lines later?
Keep your guess
Are they still in the note, only smaller?
Or are they mostly gone?
Hold on to your guess. We'll follow one sentence: "Penguins live in the Antarctic."
One token at a time
A layer of a network takes in a list of numbers. Always the same length. But a text can be seven tokens long. Or seven thousand.
So how can a network read a text of any length?
It reads one token at a time, with the same layer every time. Seven tokens here, so seven steps.
A state, passed on
So what goes into the layer at each step?
Two things. The token's vector, its row in the table.
And the state, the numbers the layer made at the step before.
At the first token, the state is all zeros. The vector and the state each get their own weights. The layer adds the two results, and bends the total, as every layer does.
Out comes the new state: sixty-four numbers, passed on to the next step.
A recurrent network
Step by step, to the period.
After "Penguins live in the", all the network keeps of what it read is in those sixty-four numbers, mixed together. And that's all it has when it guesses the next token.
Unlike a note you write, nothing chooses what to keep. The same layer mixes every token in.
A network that passes its state back into the same layer is called a recurrent network, or RNN. The state is its hidden state.
The state never grows
A recurrent network passes one small state from token to token. That state is sixty-four numbers. After one token, or after a thousand.
So where does the start of a long text go?
Change the first word to "Seals", and read both sentences.
By the period, will the network still know which animal it began with?
Look at the gap, how far apart the two states are. It starts large, and it shrinks at every step. By the period, a ninth of it is left.
It fades fast
Now the same test, at four hundred places in Wikipedia text. Change one token, and read on. Ten tokens later, how much of the change is left?
About one percent.
One token later, about forty percent is left. Thirty tokens later, almost nothing.
Sixty-four numbers can't hold a growing text. Each new token pushes the older ones out.
The best of them
Is this only a problem with a small network? The best kind of recurrent network, the LSTM, was measured in twenty eighteen, on this same text. That network used about two hundred tokens of earlier text. But only the last fifty in the right order. It kept just a rough sense of the words further back.
Each step waits
A recurrent network passes one state from token to token, and that state forgets. There's a second problem. Watch the steps light up. What is the GPU, the chip AI trains on, doing at step fifty?
It's waiting for step forty-nine, because it needs that state.
A text of a thousand tokens is a thousand steps in a row. A GPU is made to do thousands of calculations side by side, and here it mostly waits.
So training on huge amounts of text took too long.
Attention drops the state
In twenty seventeen, a new model dropped the state. Each token looks straight back at every token before it, in one step.
And every token does it at the same time. That's attention.
Nothing has to fit in sixty-four numbers, so the first word is as easy to reach as the last.
And because no step waits for another, training runs side by side.
But attention has a cost: the longer the text, the more each token has to look at.
How attention works is a lesson of its own.
The state is back
So are recurrent networks gone?
Not quite. The idea of a state came back. The model this series uses is from twenty twenty-six. Three out of every four of its layers carry a state.
It's a newer kind of state, built so that training can still run side by side. The rest, every fourth layer, look back at every token.
A state doesn't cost much, even on long texts. Attention can find any earlier token again. So one of the newest models uses both.
In code
Now in real code. PyTorch has a recurrent layer ready to use. Sixty-four numbers in, and a state of sixty-four. Give it the sentence's seven vectors. What shape will the first output be?
One text, seven tokens, sixty-four numbers: a state after every token. The second output is just the last state.
Inside the layer, there's a loop of three lines. For each token: one matrix times the token's vector, one matrix times the state, add them, then bend.
The loop ends with exactly the same last state.
And here's a real use: read the model's settings, and count its kinds of layers.
Eighteen carry a state. Six look back at every token.
Three ideas
So a recurrent network reads one token at a time, and passes one small state along. That state forgets the start, and every step waits for the one before. Attention looks back at every token, all at once.
One small state
A recurrent network passes on one small state, and it forgets. Now try it on this lesson's page, and take the quiz. Change one word, and watch it disappear.
You use this lesson in Lab 2: Attention, written by hand, after Queries, keys, values and heads.
Facts last checked on .
