The Big Question
So far, our neural networks have assumed that the input is a fixed collection of numbers. Tabular features are vectors. Images are grids. But many important problems arrive one step at a time.
Consider two messages:
I did eat the burger.
The only difference is the word not, but the meaning changes completely. A model cannot understand the sentence by treating words as independent pieces.
How can a neural network remember what it has already seen?
Why Fixed-Vector Networks Struggle
Suppose we flatten a sentence into one vector:
This creates three problems.
| Variable length | Some sentences have 3 words. Others have 300. Standard networks expect fixed-size inputs. |
| Position matters | Jessie ate the burger and The burger ate Jessie contain similar words but different meanings. |
| Memory matters | Later words often depend on earlier context. |
Sequence models are designed for this setting: ordered inputs where the current interpretation depends on what came before.
Core Intuition
Imagine reading a novel. You do not wait until you have read all 500 pages before understanding the first page. You update your understanding as each sentence arrives.
A sequence model works the same way. At every step, it receives the current input and its previous memory. Then it produces an updated memory and, optionally, an output.
What Is A Sequence?
A sequence is an ordered collection. The order is the point.
| Domain | Example | Why order matters |
|---|---|---|
| Language | The burger was delicious | Word order changes meaning |
| Stock prices | 101, 103, 99, 104 | Future values depend on previous movement |
| DNA | A, T, G, C | Biological meaning depends on ordered bases |
| Speech | audio samples over time | Sounds unfold sequentially |
The Core Computation
The model repeatedly applies the same update:
- current input
- previous memory
- updated memory
- optional prediction
This repeated computation is the defining idea behind recurrent sequence models.
Interactive Demo
Sentence processed one word at a time
Unrolled RNN
The drawing shows many boxes, but every box uses the same learned weights.
| t | word | previous h | new h | memory note |
|---|---|---|---|---|
| 1 | Jessie | 0.00 | 0.83 | subject: Jessie |
| 2 | did | 0.83 | 0.71 | action is coming |
| 3 | not | 0.71 | -0.70 | negation is active |
| 4 | eat | -0.70 | 0.43 | food action |
| 5 | the | 0.43 | 0.39 | object is coming |
| 6 | burger | 0.39 | 0.91 | object: burger |
h_t = -0.700
Long-range dependency
The word not must influence the later interpretation of eat the burger. Lower memory strength and watch old information fade more quickly.
Step through the sentence one word at a time. The hidden state is a compressed memory, not a perfect copy of the entire sentence.
Mathematics
Recurrent Neural Networks
The simplest neural sequence model is the recurrent neural network, or RNN. At time step , it receives the current input and the previous hidden state .
The hidden state is the model's memory: a running summary of what has been seen so far.
What Each Term Means
| x_t | the current word, stock price, DNA base, or audio frame |
| h_{t-1} | the memory from the previous time step |
| W_x | weights that process the current input |
| W_h | weights that process the previous memory |
| f | usually tanh in a vanilla RNN |
Worked Example
Suppose we simplify everything to one-dimensional values. Initially, . Let and .
For the first word, represent Jessie as :
For the second word, represent likes as :
The second memory depends on both the current word and the memory from the previous word. That recursive dependency is what makes the model sequential.
Unrolling Through Time
RNNs are often drawn as one box, but during computation we unroll that box across time:
It looks like many networks, but every time step uses the same weights. This is called parameter sharing through time. The same grammar-like computation is reused at every position in the sequence.
Sequence Task Types
| Pattern | Example | Description |
|---|---|---|
| One-to-one | Image classification | One fixed input produces one label |
| One-to-many | Image captioning | One input produces a sequence |
| Many-to-one | Sentiment analysis | A sequence produces one label |
| Many-to-many | Translation | One sequence produces another sequence |
| Many-to-many same length | Part-of-speech tagging | Each input step receives an output label |
The Weakness Of Vanilla RNNs
The hidden state gave neural networks memory, but it is an imperfect memory. If an important word appears many time steps ago, its influence must survive repeated transformations.
In long sentences, ordinary RNNs gradually forget. This is the long-term dependency problem, and it motivates LSTMs and GRUs in the next chapter.
Implementation
This minimal PyTorch model processes a sequence one step at a time. The RNN produces hidden states, and the final hidden state is used for a many-to-one classification task such as sentiment analysis.
import torch
from torch import nn
class SimpleRNNClassifier(nn.Module):
def __init__(self, vocab_size, embed_dim, hidden_dim, num_classes):
super().__init__()
self.embedding = nn.Embedding(vocab_size, embed_dim)
self.rnn = nn.RNN(
input_size=embed_dim,
hidden_size=hidden_dim,
batch_first=True,
)
self.classifier = nn.Linear(hidden_dim, num_classes)
def forward(self, token_ids):
# token_ids shape: (batch_size, sequence_length)
x = self.embedding(token_ids)
# outputs contains every hidden state.
# final_hidden contains the last hidden state.
outputs, final_hidden = self.rnn(x)
last_memory = final_hidden[-1]
logits = self.classifier(last_memory)
return logits
model = SimpleRNNClassifier(
vocab_size=10000,
embed_dim=64,
hidden_dim=128,
num_classes=2,
)
batch = torch.randint(0, 10000, (32, 20))
logits = model(batch)
print(logits.shape) # (32, 2)For next-token prediction, the classifier can be applied to every hidden state instead of only the final one. The same RNN machinery supports many sequence task shapes.
Interview Discussion
Why can a standard feed-forward network not naturally process variable-length sequences?
It expects a fixed-size input vector. Sequences can have different lengths, and their meaning depends on order and previous context.
What is the hidden state?
The hidden state is a compressed memory of what the RNN has seen so far.
Why do RNNs share weights across time?
The same computation should apply at every position, allowing the model to process sequences of arbitrary length with one set of learned weights.
What does it mean to unroll an RNN?
It means drawing the repeated computation across time steps while remembering that each step uses the same parameters.
What is the main weakness of a vanilla RNN?
It struggles with long-term dependencies because information from earlier time steps can fade as it is repeatedly transformed.
Active Recall
1. Give three examples of sequence data.
2. Why does word order matter in language modeling?
3. Write the vanilla RNN update equation from memory.
4. What information does the hidden state contain?
5. Why is the same RNN cell reused at every time step?
6. What is the difference between many-to-one and many-to-many sequence tasks?
7. What limitation of vanilla RNNs motivates LSTMs and GRUs?
Common Mistakes
- Thinking the hidden state stores the entire sequence exactly.
- Believing every time step has separate parameters.
- Confusing sequence length with network depth.
- Assuming vanilla RNNs solve all sequence problems.
- Forgetting that order, not just membership, is the key property of sequence data.
Connection To LSTMs and GRUs
Sequence models gave neural networks memory. But vanilla RNN memory fades across long sequences. LSTMs and GRUs improve the memory mechanism by learning what to keep, what to forget, and when to update.