RNNs & Sequence Models
Modelling sequences — tokenisation and word embeddings, recurrent neural networks and backpropagation through time, vanishing gradients, LSTMs and GRUs, sequence-to-sequence encoder–decoder models, the bottleneck that motivated attention, and modern state-space models.
Text, speech, time series, DNA, user clickstreams — much data is sequential: order matters, and lengths vary. Before transformers took over, recurrent neural networks were the standard way to model sequences. Understanding them explains why attention was such a breakthrough.
Turning text into numbers
Tokenisation
Text is split into tokens — words, sub-words or characters — and each token is mapped to an integer ID. Modern models use sub-word tokenisers (Byte-Pair Encoding, WordPiece, SentencePiece): common words are single tokens, rare words split into pieces, so there are no unknown words.
"unbelievably fast tokenizers" → ["un", "believ", "ably", " fast", " token", "izers"] → [403, 31852, 2245, 4062, 11241, 12509]Word embeddings
One-hot vectors (a 50,000-long vector with a single 1) are huge and treat every word as equally different. Embeddings map each token to a dense vector (e.g. 300 dimensions) where similar meanings are close. word2vec and GloVe learned these by predicting words from their neighbours ("you shall know a word by the company it keeps"), producing famous analogies:
In modern networks the embedding table is simply the first layer, learned along with everything else (Embeddings and RAG).
Recurrent neural networks
An RNN processes a sequence one step at a time, maintaining a hidden state — a memory summarising everything seen so far:
The same weights are used at every step (weight sharing across time, like convolutions share across space).
Configurations:
| Pattern | Example |
|---|---|
| Many → one | Sentiment classification (use the final hidden state) |
| One → many | Image captioning |
| Many → many (aligned) | Part-of-speech tagging, per-frame labels |
| Many → many (seq2seq) | Translation, summarisation |
Training: backpropagation through time
"Unroll" the RNN across all time steps into one deep network and apply backpropagation. Gradients for the shared weights are summed over steps.
The problem: vanishing gradients
The gradient flowing from step 100 back to step 1 is multiplied by and the tanh derivative ~99 times. It vanishes (or explodes), so plain RNNs can't learn long-range dependencies: in "The keys that I left on the kitchen table yesterday are missing", connecting "keys" to "are" is hard.
LSTMs and GRUs
The Long Short-Term Memory network (1997) adds a cell state — a conveyor belt of memory updated additively — controlled by learned gates (sigmoids between 0 and 1):
| Gate | Decides |
|---|---|
| Forget gate | What to erase from the cell state |
| Input gate | What new information to write |
| Output gate | What part of the cell to expose as the hidden state |
Because the cell state is updated by addition (not repeated multiplication), gradients can flow across hundreds of steps. The GRU is a simplified variant with two gates and no separate cell state — fewer parameters, similar performance.
import torch
from torch import nn
class SentimentLSTM(nn.Module):
def __init__(self, vocab_size, embed_dim=128, hidden=256):
super().__init__()
self.embed = nn.Embedding(vocab_size, embed_dim)
self.lstm = nn.LSTM(embed_dim, hidden, batch_first=True, bidirectional=True)
self.out = nn.Linear(2 * hidden, 1)
def forward(self, token_ids): # (batch, seq_len)
x = self.embed(token_ids) # (batch, seq_len, embed_dim)
_, (h, _) = self.lstm(x) # h: (2 directions, batch, hidden)
h = torch.cat([h[0], h[1]], dim=1) # forward + backward final states
return self.out(h).squeeze(1) # logit for "positive"Bidirectional RNNs read the sequence both ways, so each position sees past and future context (useful for classification and tagging, not for generation).
Sequence-to-sequence and the bottleneck
For translation, an encoder RNN reads the source sentence into a final hidden state, and a decoder RNN generates the target sentence token by token from that state (2014).
The flaw: the entire source sentence must be squeezed into one fixed-size vector. Quality dropped sharply for long sentences.
Attention (Bahdanau et al., 2014) fixed this: at each decoding step, the decoder looks back at all encoder states and takes a weighted average, focusing on the relevant source words. Translation improved dramatically — and a few years later, the Transformer ("Attention Is All You Need", 2017) dropped recurrence entirely (Attention and transformers).
Why transformers replaced RNNs
| RNNs / LSTMs | Transformers |
|---|---|
| Sequential: step t needs step t−1 → can't parallelise across time | All positions processed in parallel → fast training on GPUs |
| Long-range information must survive many steps | Any position attends directly to any other |
| Memory per step is constant (good for streaming) | Attention cost grows quadratically with length |
State-space models and the RNN comeback
Recurrence has a real advantage: constant memory and compute per generated token, regardless of length. Modern architectures like Mamba (selective state-space models), RWKV and linear-attention variants train in parallel like transformers but run like RNNs at inference. Hybrid models combine them with attention layers for long-context efficiency.
Other sequence data
- Time-series forecasting: classical ARIMA/exponential smoothing, gradient boosting on lag features, and deep models (LSTMs, temporal CNNs, transformers).
- Speech: models like Whisper use a transformer encoder–decoder over audio spectrograms.
- Biology: protein language models treat amino-acid sequences like text.
- Text becomes token IDs via sub-word tokenisers, then dense embeddings where similar meanings are close.
- RNNs process sequences step by step with a hidden state and shared weights, trained by backpropagation through time.
- Plain RNNs suffer vanishing gradients; LSTMs and GRUs use gates and an additive memory to learn long-range dependencies.
- Seq2seq encoder–decoders squeezed inputs into one vector; attention removed this bottleneck.
- Transformers replaced RNNs by parallelising over positions; state-space models revive recurrence for efficient long sequences.