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.

Intermediate 4 min readLesson 10 of 14

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:

king⃗−man⃗+woman⃗≈queen⃗\vec{\text{king}} - \vec{\text{man}} + \vec{\text{woman}} \approx \vec{\text{queen}}

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 ht\mathbf{h}_t — a memory summarising everything seen so far:

ht=tanh⁡(Wxhxt+Whhht−1+b)\mathbf{h}_t = \tanh(W_{xh}\mathbf{x}_t + W_{hh}\mathbf{h}_{t-1} + \mathbf{b})

The same weights are used at every step (weight sharing across time, like convolutions share across space).

h₁h₂h₃h₀RNNRNNRNNthemovierockedpositivefrom h₃

Configurations:

PatternExample
Many → oneSentiment classification (use the final hidden state)
One → manyImage 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 WhhW_{hh} 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 ct\mathbf{c}_t — a conveyor belt of memory updated additively — controlled by learned gates (sigmoids between 0 and 1):

GateDecides
Forget gate ftf_tWhat to erase from the cell state
Input gate iti_tWhat new information to write
Output gate oto_tWhat part of the cell to expose as the hidden state
ct=ft⊙ct−1+it⊙c~t,ht=ot⊙tanh⁡(ct)\mathbf{c}_t = f_t \odot \mathbf{c}_{t-1} + i_t \odot \tilde{\mathbf{c}}_t, \qquad \mathbf{h}_t = o_t \odot \tanh(\mathbf{c}_t)

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.

Python
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 / LSTMsTransformers
Sequential: step t needs step t−1 → can't parallelise across timeAll positions processed in parallel → fast training on GPUs
Long-range information must survive many stepsAny 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.
Key takeaways
  • 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.