Sequence Models
A sequence \(x_{1:T}=(x_1,\dots,x_T)\) is an ordered list in which position matters: reordering the elements usually changes the meaning. Some data is naturally sequential (language, audio, time series, robot actions); other data can be made sequential by fixing an order (image patches in raster order, DNA, proteins). Treating all of them as sequences lets one family of models handle every modality. This chapter covers how sequences are fed to a network and the three classic ways to model them: recurrence, gated memory, and attention.
8.1 Representing Sequences
8.1.1 Tokenization
To process text, first choose the units the model reads.
- Characters (stored via Unicode) are easy to define but carry little meaning each: “c”, “a”, “t” mean nothing until combined.
- Words are meaningful but ill-defined (“don’t”, “New York”) and too numerous: a vocabulary can never contain every word.
- Subwords are the practical compromise: “lower” becomes “low” + “er”. Frequent words stay whole, rare words split into known pieces, and nothing is ever out of vocabulary.
A subword tokenizer has two parts: a learner that induces a vocabulary from a training corpus, and an encoder that splits new text using that vocabulary. The two most common are byte-pair encoding (Sennrich et al., 2016) and unigram language-model tokenization (Kudo, 2018, in the SentencePiece library).
Definition 8.1 (Byte-Pair Encoding) Learner. Start with a vocabulary of single symbols (characters or bytes), with a marker \(\_\) for the start of each word. Repeat \(k\) times: find the most frequent pair of adjacent symbols \((A,B)\) in the corpus, add the merged symbol \(AB\) to the vocabulary, and replace every adjacent \(A\,B\) in the corpus by \(AB\).
Encoder. Split new text into single symbols, then apply the learned merges in the order they were learned. Finally replace each token by its integer ID.
Corpus: set new new renew reset renew, i.e. the words \(\_set\), \(\_new\), \(\_new\), \(\_renew\), \(\_reset\), \(\_renew\).
| step | merge | count | where |
|---|---|---|---|
| 1 | n e → ne | 4 | new ×2, renew ×2 (tied with e w) |
| 2 | ne w → new | 4 | same words |
| 3 | _ r → _r | 3 | renew ×2, reset |
| 4 | _r e → _re | 3 | same words |
After four merges the learner has discovered the prefix re-. Continuing adds _new, _renew, se, set, _set.
To encode renew set: start from \(\_\,r\,e\,n\,e\,w\;\_\,s\,e\,t\), apply the merges in order to get \(\_re\;new\;\_\,s\,e\,t\), and so on until \([\_renew,\ \_set]\); then look up their IDs, e.g. \([12,15]\).
8.1.2 Embeddings and Other Modalities
- Embeddings. Each token ID indexes a row of a learned embedding matrix \(E\in\mathbb R^{|V|\times d}\). A sequence of \(T\) tokens becomes a matrix \(X\in\mathbb R^{T\times d}\), one row per position: the standard input to RNNs and transformers. Word2Vec showed that such vectors acquire semantic structure, with similar words nearby; modern models learn \(E\) end-to-end with the rest of the network.
- Audio is a sequence of amplitudes in time, usually converted to the frequency domain with a short-time Fourier transform: a spectrogram (often on a log-Mel scale) or compact MFCC features per frame.
- Actions. A robot’s state at time \(t\) is a joint-position vector \(q_t\in\mathbb R^d\), a motion is \(q_{1:T}\), and an action \(a_t\) is a target position or a delta \(q_{t+1}-q_t\).
- Images \(I\in\mathbb R^{H\times W\times C}\) are cut into \(N\) patches \(x_1,\dots,x_N\) in a fixed but artificial order (raster scan). Each token stays aligned with a grid position, and the generated tokens are reshaped back into an image.
8.2 Autoregressive Models
Definition 8.2 (Autoregressive Model) An autoregressive model factorizes a joint distribution by the chain rule of probability, in a fixed order:
\[ p(x_1,\dots,x_L)=\prod_{i=1}^Lp\bigl(x_i\mid x_1,\dots,x_{i-1}\bigr), \]
with each conditional given by a network that sees only the previous elements. For example, a Gaussian autoregressive model uses \(p(x_i\mid x_{<i})=\mathcal N\bigl(\mu_\theta(x_{<i}),\sigma_\theta^2(x_{<i})\bigr)\).
- The likelihood is exact and tractable for any length \(L\), and training is plain maximum likelihood: predict each element from its prefix. A Gaussian autoregressive model is exactly an autoregressive flow (Def. 6.3).
- Generation is sequential: sample \(x_1\), then \(x_2\) given \(x_1\), and so on, \(O(L)\) network calls. The question is how to design networks that respect the ordering.
8.2.1 Causal Convolutions
WaveNet (DeepMind, 2016), for speech synthesis, computes \(p(x_i\mid x_{<i})\) with causal temporal convolutions, which only look at past samples.
- With kernel size \(k\), each layer extends the receptive field by \(k-1\), so covering \(L\) past samples needs about \(L/k\) layers. Dilated convolutions double the gap between taps at each layer, so the receptive field grows exponentially and \(\log_2L\) layers suffice.
- Evaluating the likelihood is fully parallel (one convolutional pass over the known sequence); sampling is sequential.
- Other ingredients: outputs quantized to 256 levels with a softmax, residual connections, and conditioning \(p(x\mid h)\) on text or speaker. It was the first deep generative model of raw audio waveforms.
PixelCNN (DeepMind, 2016) does the same for images in raster order. A masked convolution zeroes the kernel weights at and after the current pixel, so each output depends only on pixels above it and to its left. The likelihood of a whole image is again one parallel pass.
A \(3\times3\) masked kernel sees the row above (left, center, right) and the pixel to the left. Stack such layers: going up one row moves the visible region one column right, but going left along the current row never reaches upward again. The receptive field grows as a sawtooth, and a wedge of pixels above and to the right of the current pixel is never seen, though it is all valid context. This is the blind spot.
Fix (Gated PixelCNN, 2016). Use two stacks per layer \(\ell\):
- a vertical stack \(v^\ell\) with a mask that sees only rows strictly above, so its receptive field is a growing rectangle above the pixel;
- a horizontal stack \(h^\ell\) with a mask that sees only pixels to the left in the current row, which also receives the vertical stack:
\[ v^\ell=\phi\bigl(\mathrm{conv}(m_v\odot w_v,\;v^{\ell-1})\bigr), \qquad h^\ell=\phi\bigl(\mathrm{conv}(m_h\odot w_h,\;h^{\ell-1})+\mathrm{conv}(w_{vh},\;v^\ell)\bigr). \]
The output uses \(h^L\). Information flows only from the vertical stack into the horizontal one, never back, so causality is preserved and the blind spot disappears. Gated PixelCNN also replaces ReLU by an LSTM-style gated activation \(\tanh(W_f*x)\odot\sigma(W_g*x)\).
8.3 Recurrent Neural Networks
A convolution has a fixed receptive field. To handle arbitrarily long sequences with a fixed-size model, compress any prefix into a fixed-dimensional state.
Definition 8.3 (Recurrent Neural Network) A recurrent neural network (RNN) keeps a hidden state \(h_t\) and applies the same weights at every step:
\[ h_t=f_1\bigl(W_{xh}x_t+W_{hh}h_{t-1}+b_h\bigr), \qquad y_t=f_2\bigl(W_{hy}h_t+b_y\bigr), \]
with initial state \(h_{0}\) (usually zero), a \(\tanh\) or similar activation \(f_1\), and an output activation \(f_2\) (e.g. softmax). \(W_{hh}\) are the recurrent weights.
- \(h_t\) is a running summary (“memory”) of \(x_1,\dots,x_t\); each output \(y_t\) depends on all inputs up to \(t\), and each input affects all later states and outputs. Unrolled in time, an RNN is a very deep MLP whose layers share weights.
- Multi-layer RNNs stack recurrences: layer \(k\) takes \(h_t^{(k-1)}\) as its input. Bidirectional RNNs run one RNN forward and one backward and combine them, \(y_t=f_2\bigl(h_t^{\text f},h_t^{\text b}\bigr)\), when the output may depend on the whole input.
- Uses. Sequence classification (does this audio contain “welcome”?): pool the outputs, \(Y=\max_tY_t\), or use the last state. Language modeling: predict \(x_{t+1}\) from \(h_t\) with a cross-entropy loss.
- Backpropagation through time (BPTT): unroll the network over the sequence and run ordinary backpropagation (Ch. 1), summing the gradients of the shared weights over all time steps.
Proposition 8.1 (Exploding and Vanishing Gradients) For a linear RNN \(h_t=W_hh_{t-1}+W_xx_t\), unrolling gives
\[ h_k=W_h^{k}h_0+\sum_{i=1}^kW_h^{k-i}W_xx_i, \]
so the influence of input \(i\) scales like \(W_h^{k-i}\). With an activation, \(h_t=f(z_t)\), \(z_t=W_hh_{t-1}+W_xx_t+b\), the gradient through \(k\) steps is
\[ \frac{\partial h_k}{\partial h_0}=\prod_{t=1}^k\mathrm{diag}\bigl(f'(z_t)\bigr)W_h. \]
If the largest eigenvalue magnitude \(\lambda_{\max}\) of \(W_h\) exceeds \(1\), signals and gradients can explode exponentially; if it is below \(1\) (and \(|f'|\le1\), as for \(\tanh\) and sigmoid), they vanish exponentially, and the network cannot learn long-range dependencies.
- Explosion is easy to fix: gradient clipping (Ch. 3), initializing \(W_h\) to the identity so that \(\lambda_{\max}=1\), and truncated BPTT, which backpropagates only through the last few steps.
- Vanishing is the real problem. \(\tanh\) is preferred over sigmoid but still saturates, and the hidden state is overwritten at every step, so a plain RNN effectively remembers only a handful of steps (about 7 in practice).
8.4 Gated Memory
Definition 8.4 (Long Short-Term Memory) An LSTM (Hochreiter and Schmidhuber, 1997) keeps a separate cell \(c_t\) for long-term memory, updated only through gates, sigmoid layers whose entries in \((0,1)\) say how much of each coordinate to let through:
\[ \begin{aligned} f_t&=\sigma\bigl(W_{xf}x_t+W_{hf}h_{t-1}+b_f\bigr)&&\text{forget gate}\\ i_t&=\sigma\bigl(W_{xi}x_t+W_{hi}h_{t-1}+b_i\bigr)&&\text{input gate}\\ \tilde c_t&=\tanh\bigl(W_{xc}x_t+W_{hc}h_{t-1}+b_c\bigr)&&\text{candidate memory}\\ o_t&=\sigma\bigl(W_{xo}x_t+W_{ho}h_{t-1}+b_o\bigr)&&\text{output gate}\\ c_t&=f_t\odot c_{t-1}+i_t\odot\tilde c_t\\ h_t&=o_t\odot\tanh(c_t). \end{aligned} \]
- \(f_t\odot c_{t-1}\) drops useless old memory (\(f_t^{(j)}\to0\) forgets coordinate \(j\), \(\to1\) keeps it); \(i_t\odot\tilde c_t\) writes selected new information from \(x_t\); \(o_t\) chooses which parts of the memory to report in the next hidden state.
- Uninterrupted gradient flow. Along the cell path, \(\partial c_t/\partial c_{t-1}=\mathrm{diag}(f_t)\): an elementwise product, with no repeated multiplication by a weight matrix. When the forget gate stays near \(1\), gradients pass through many steps nearly unchanged, much like a residual connection (Ch. 3) in time. In practice memory extends from about 7 steps to about 100.
- This is not a guarantee against vanishing or exploding, just an architecture that makes long-term dependencies much easier to learn. LSTMs dominated sequence modeling from about 2013 to 2016. Remember gradient clipping.
Variants.
- Peephole connections let the gates also read the cell \(c_{t-1}\).
- Coupled gates set \(i_t=1-f_t\): whatever is forgotten is replaced, so only two gates are needed.
- The gated recurrent unit (GRU, Cho et al., 2014) merges cell and hidden state into one, with an update gate \(z_t\) and a reset gate \(r_t\): \[ \tilde h_t=\tanh\bigl(W_xx_t+W_h(r_t\odot h_{t-1})\bigr), \qquad h_t=(1-z_t)\odot h_{t-1}+z_t\odot\tilde h_t. \] It has fewer parameters and often performs comparably.
In applications LSTMs are stacked into several layers with skip connections, often bidirectional, with outputs max-pooled over time or read from the final states. As language models, they generate text one token at a time.
8.5 Attention
An RNN squeezes the entire past through one fixed-size state, so distant information fades. Attention lets each position look up any other position directly and combine whatever is relevant.
Definition 8.5 (Scaled Dot-Product Attention) Given a query \(q\in\mathbb R^{d_k}\), keys \(k_1,\dots,k_n\in\mathbb R^{d_k}\), and values \(v_1,\dots,v_n\in\mathbb R^{d_v}\), attention returns a weighted average of the values, weighted by query–key similarity:
\[ \mathrm{Attention}(q,K,V)=\sum_{j=1}^n\alpha_jv_j, \qquad \alpha_j=\frac{\exp\bigl(q^\top k_j/\sqrt{d_k}\bigr)}{\sum_{\ell=1}^n\exp\bigl(q^\top k_\ell/\sqrt{d_k}\bigr)}. \]
For all queries at once, with \(Q\in\mathbb R^{m\times d_k}\), \(K\in\mathbb R^{n\times d_k}\), \(V\in\mathbb R^{n\times d_v}\),
\[ \mathrm{Attention}(Q,K,V)=\mathrm{softmax}\Bigl(\frac{QK^\top}{\sqrt{d_k}}+M\Bigr)V, \]
where the mask \(M\) has entries \(0\) (allowed) or \(-\infty\) (blocked), e.g. a causal mask that blocks \(j>i\), or a padding mask.
In self-attention, all three come from the same sequence: \(Q=XW_Q\), \(K=XW_K\), \(V=XW_V\).
Proposition 8.2 (Why Divide by the Square Root of the Key Dimension) If the entries of \(q\) and \(k\) are independent with mean \(0\) and variance \(1\), then \(q^\top k=\sum_{i=1}^{d_k}q_ik_i\) has mean \(0\) and variance \(d_k\). Dividing by \(\sqrt{d_k}\) restores unit variance.
- Without the scaling, logits grow like \(\sqrt{d_k}\), the softmax saturates to nearly one-hot, and its gradients vanish, the same saturation problem as with sigmoids (Ch. 1).
Definition 8.6 (Multi-Head Attention) Run \(h\) attention heads in parallel, each with its own projections, and combine them:
\[ \mathrm{head}_r=\mathrm{softmax}\Bigl(\frac{Q_rK_r^\top}{\sqrt{d_k}}+M\Bigr)V_r,\quad Q_r=XW_Q^{(r)},\ K_r=XW_K^{(r)},\ V_r=XW_V^{(r)}, \]
\[ \mathrm{MultiHead}(X)=\mathrm{Concat}(\mathrm{head}_1,\dots,\mathrm{head}_h)\,W_O, \qquad W_O\in\mathbb R^{hd_v\times d_{\text{model}}}, \]
usually with \(d_k=d_v=d_{\text{model}}/h\), so the total cost matches a single full-width head.
- Different heads can attend to different things (a previous word, the subject of the sentence, a matching bracket) at the same time.
- Three ways to carry information. An RNN repeatedly compresses past and present into one hidden state; an LSTM keeps a dedicated memory and learns what to keep, update, or forget; attention looks up any position directly, so the path between two tokens has length \(1\) regardless of their distance. Ch. 9 builds the transformer from this operation.
| model | cost per layer | parallel over time | memory | in practice |
|---|---|---|---|---|
| RNN | \(O(Td^2)\) | poor | low–moderate | cheap per step, slow on long sequences |
| LSTM | \(O(Td^2)\), larger constant | poor | higher than RNN | slower than RNN: gates add matrix products |
| Transformer | \(O(T^2d)\) attention + \(O(Td^2)\) MLP | excellent | \(O(T^2)\) attention matrix | very fast on GPUs at moderate \(T\); long \(T\) is expensive |
| CNN (kernel \(k\)) | \(O(Tkd^2)\) | excellent | low–moderate | efficient for local patterns |
Attention dominates once \(T\) exceeds roughly \(d\). Two responses: FlashAttention keeps the same model but executes it better, computing attention in tiles that stay in fast on-chip memory without ever storing the \(T\times T\) matrix; Mamba changes the model, a selective state-space recurrence that is linear in \(T\) yet trains in parallel.
8.6 Supplementary Notes
8.6.1 Key Results
- Definition 8.1: BPE merges the most frequent adjacent pair, \(k\) times; encoding replays the merges in order.
- Definition 8.2: \(p(x)=\prod_ip(x_i\mid x_{<i})\); parallel likelihood, sequential sampling.
- Definition 8.3: \(h_t=f(W_{xh}x_t+W_{hh}h_{t-1}+b)\), trained by BPTT.
- Proposition 8.1: \(\partial h_k/\partial h_0=\prod_t\mathrm{diag}(f'(z_t))W_h\) explodes or vanishes with \(\lambda_{\max}(W_h)\).
- Definition 8.4: \(c_t=f_t\odot c_{t-1}+i_t\odot\tilde c_t\), \(h_t=o_t\odot\tanh c_t\).
- Definition 8.5: \(\mathrm{softmax}(QK^\top/\sqrt{d_k}+M)V\); Proposition 8.2: the scale keeps logits at unit variance.
- Definition 8.6: multi-head attention, \(d_k=d_{\text{model}}/h\).