Sequence Models

Sequence models process ordered data one step at a time while carrying forward an internal memory.

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 not eat the burger.
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:

x=[word1,word2,word3,word4]x=[\text{word}_1,\text{word}_2,\text{word}_3,\text{word}_4]

This creates three problems.

Variable lengthSome sentences have 3 words. Others have 300. Standard networks expect fixed-size inputs.
Position mattersJessie ate the burger and The burger ate Jessie contain similar words but different meanings.
Memory mattersLater 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.

DomainExampleWhy order matters
LanguageThe burger was deliciousWord order changes meaning
Stock prices101, 103, 99, 104Future values depend on previous movement
DNAA, T, G, CBiological meaning depends on ordered bases
Speechaudio samples over timeSounds unfold sequentially

The Core Computation

The model repeatedly applies the same update:

Inputs at time t
  • current input
  • previous memory
Outputs at time t
  • updated memory
  • optional prediction

This repeated computation is the defining idea behind recurrent sequence models.

Interactive Demo

Hidden state timeline

Sentence processed one word at a time

Unrolled RNN

RNNJessieRNNdidRNNnotRNNeatRNNtheRNNburger

The drawing shows many boxes, but every box uses the same learned weights.

twordprevious hnew hmemory note
1Jessie0.000.83subject: Jessie
2did0.830.71action is coming
3not0.71-0.70negation is active
4eat-0.700.43food action
5the0.430.39object is coming
6burger0.390.91object: burger
Current step
not
RNN update
h_t = tanh(Wx_t + Uh_t-1 + b)
h_t = -0.700
Hidden state strength-0.70
Next-word burger score0.12

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.

not signal
-0.70
final memory
0.91

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 tt, it receives the current input xtx_t and the previous hidden state ht1h_{t-1}.

ht=f(Wxxt+Whht1+b)h_t=f(W_xx_t+W_hh_{t-1}+b)

The hidden state hth_tis the model's memory: a running summary of what has been seen so far.

What Each Term Means

x_tthe current word, stock price, DNA base, or audio frame
h_{t-1}the memory from the previous time step
W_xweights that process the current input
W_hweights that process the previous memory
fusually tanh in a vanilla RNN

Worked Example

Suppose we simplify everything to one-dimensional values. Initially, h0=0h_0=0. Let Wx=2W_x=2 and Wh=0.5W_h=0.5.

For the first word, represent Jessie as x1=1x_1=1:

h1=tanh(2(1)+0.5(0))=tanh(2)0.964h_1=\tanh(2(1)+0.5(0))=\tanh(2)\approx0.964

For the second word, represent likes as x2=0.8x_2=0.8:

h2=tanh(2(0.8)+0.5(0.964))=tanh(2.082)0.969h_2=\tanh(2(0.8)+0.5(0.964))=\tanh(2.082)\approx0.969

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:

x1h1h2h3x_1\rightarrow h_1\rightarrow h_2\rightarrow h_3

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

PatternExampleDescription
One-to-oneImage classificationOne fixed input produces one label
One-to-manyImage captioningOne input produces a sequence
Many-to-oneSentiment analysisA sequence produces one label
Many-to-manyTranslationOne sequence produces another sequence
Many-to-many same lengthPart-of-speech taggingEach 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.