Chapter 12: Transformers

Language Models · v1.0.8

2026-10-27 00:18:01

Where we are

Where this fits

  • Convolutional networks share parameters across image positions and assume a fixed input size
  • Text inputs vary in length, and the connections between words depend on the words rather than on their positions
  • Self-attention supplies both properties in a single layer

Outline of key topics

  1. Dot-product self-attention — values, queries, keys, and the matrix form
  2. Extensions used in practice — positional encoding, scaling, multiple heads
  3. The transformer layer — attention, position-wise MLP, residuals, LayerNorm
  4. Tokens and embeddings — sub-word tokenization, learned embeddings
  5. Encoder, decoder and encoder-decoder models — BERT, GPT3, translation
  6. Scaling to long sequences — the quadratic cost and its remedies
  7. Transformers for images — pixels and patches as tokens

Requirements for a sequence layer

The motivating passage

The restaurant refused to serve me a ham sandwich because it only cooks vegetarian food. […] Their ambiance was just as good as the food and service.

  • 37 words at embedding length 1024 gives an encoded input of \(37 \times 1024 = 37888\)
  • One input may be a sentence, another many sentences
  • it refers to restaurant, not to ham sandwich

Two requirements

  1. Parameter sharing across positions, so one network accepts any length \(N\)
  2. Connections between positions whose strength depends on the inputs

A fully connected layer over the whole passage satisfies neither. An image of the wrong size can be resampled; a 40-word passage has no comparable operation.

Both are properties of the layer, not of the data.

Dot-product self-attention

Values and routing

Output one weights the three values by \(0.1\), \(0.3\), \(0.6\). Output two uses \(0.5\), \(0.2\), \(0.3\); output three another set.

A self-attention block maps \(N\) inputs of size \(D \times 1\) to \(N\) outputs of size \(D \times 1\).

\[\mathbf{v}_m = \boldsymbol\beta_v + \boldsymbol\Omega_v\mathbf{x}_m\]

\[\mathbf{sa}_n[\mathbf{x}_1, \ldots, \mathbf{x}_N] = \sum_{m=1}^{N} a[\mathbf{x}_m, \mathbf{x}_n]\,\mathbf{v}_m\]

  • \(\boldsymbol\beta_v \in \mathbb{R}^{D \times 1}\), \(\boldsymbol\Omega_v \in \mathbb{R}^{D \times D}\)
  • weights \(a[\bullet, \mathbf{x}_n]\) are non-negative and sum to one
  • each output is a routing of the same values in different proportions

Queries, keys and the attention weights

Queries and keys per input; dot products of one query against all keys pass through a softmax; the resulting attentions route the values.

\[\mathbf{q}_n = \boldsymbol\beta_q + \boldsymbol\Omega_q\mathbf{x}_n, \qquad \mathbf{k}_m = \boldsymbol\beta_k + \boldsymbol\Omega_k\mathbf{x}_m\]

\[a[\mathbf{x}_m, \mathbf{x}_n] = \frac{\exp\!\left[\mathbf{k}_m^T\mathbf{q}_n\right]}{\sum_{m'=1}^{N}\exp\!\left[\mathbf{k}_{m'}^T\mathbf{q}_n\right]}\]

  • the dot product measures similarity between query and key
  • the softmax makes the keys compete
  • queries and keys share a dimension \(D_q\); values need not

Properties of the mechanism

Parameters

\[\boldsymbol\phi = \{\boldsymbol\beta_v, \boldsymbol\Omega_v, \boldsymbol\beta_q, \boldsymbol\Omega_q, \boldsymbol\beta_k, \boldsymbol\Omega_k\}\]

  • one set, independent of \(N\)
  • applied identically at every position

Scaling

  • value computation is linear in \(N\)
  • one attention weight per ordered pair \((\mathbf{x}_m, \mathbf{x}_n)\), so the weight count is quadratic in \(N\) and independent of \(D\)

Nonlinearity

  • both halves are linear maps; the weights are nonlinear in the input
  • one branch computes the weights of another: a hypernetwork

Matrix form

\(\mathbf{X}\) is operated on separately by the query, key and value matrices; dot products by matrix multiplication; softmax column-wise; values post-multiplied by the attentions.

With the \(N\) inputs as columns of \(\mathbf{X} \in \mathbb{R}^{D \times N}\):

\[\mathbf{V} = \boldsymbol\beta_v\mathbf{1}^T + \boldsymbol\Omega_v\mathbf{X}\] \[\mathbf{Q} = \boldsymbol\beta_q\mathbf{1}^T + \boldsymbol\Omega_q\mathbf{X}\] \[\mathbf{K} = \boldsymbol\beta_k\mathbf{1}^T + \boldsymbol\Omega_k\mathbf{X}\]

\[\mathbf{Sa}[\mathbf{X}] = \mathbf{V} \cdot \mathbf{Softmax}\!\left[\mathbf{K}^T\mathbf{Q}\right]\]

  • \(\mathbf{Softmax}[\bullet]\) acts independently on each column
  • every output is a convex combination of the values
  • \(\mathbf{K}^T\mathbf{Q}\) is \(N \times N\)

Extensions used in practice

Positional encoding

A sinusoidal positional encoding matrix \(\boldsymbol\Pi\). Each column differs, so positions are distinguishable. The columns may instead be learned.

Self-attention is equivariant to permutation of its inputs:

\[\mathbf{Sa}[\mathbf{X}\mathbf{P}] = \mathbf{Sa}[\mathbf{X}]\mathbf{P}\]

for any permutation matrix \(\mathbf{P}\). Order is supplied from outside the mechanism.

  • Absolute. A matrix \(\boldsymbol\Pi\) with a distinct column per position is added to \(\mathbf{X}\), at the input or at every layer, sometimes to the queries and keys but not the values
  • Relative. A parameter \(\pi_{a,b}\) is learned per offset between key position \(a\) and query position \(b\), and modifies the attention matrix

Scaled dot-product attention

\[\mathbf{Sa}[\mathbf{X}] = \mathbf{V} \cdot \mathbf{Softmax}\!\left[\frac{\mathbf{K}^T\mathbf{Q}}{\sqrt{D_q}}\right]\]

  • Large dot products move the softmax into a region where the largest value dominates
  • Small input changes then have little effect, and the gradients are very small
  • \(D_q\) is the dimension of the queries and keys — the row count of \(\boldsymbol\Omega_q\) and \(\boldsymbol\Omega_k\), which must agree

The scaling addresses a gradient problem, not an accuracy problem.

Multiple heads

Two heads, each with their own queries, keys and values. The outputs are concatenated and recombined by \(\boldsymbol\Omega_c\).

\(H\) sets of values, queries and keys are computed, and head \(h\) is

\[\mathbf{Sa}_h[\mathbf{X}] = \mathbf{V}_h \cdot \mathbf{Softmax}\!\left[\frac{\mathbf{K}_h^T\mathbf{Q}_h}{\sqrt{D_q}}\right]\]

The outputs are concatenated vertically and recombined:

\[\mathbf{MhSa}[\mathbf{X}] = \boldsymbol\Omega_c\!\left[\mathbf{Sa}_1[\mathbf{X}]^T, \ldots, \mathbf{Sa}_H[\mathbf{X}]^T\right]^T\]

  • values, queries and keys are of size \(D/H\)
  • the parameter count and computation stay comparable to one head of dimension \(D\)

The transformer layer

Composition

The input is a \(D \times N\) matrix of word embeddings for \(N\) tokens; the output has the same size.

\[ \begin{aligned} \mathbf{X} &\leftarrow \mathbf{X} + \mathbf{MhSa}[\mathbf{X}] \\ \mathbf{X} &\leftarrow \mathbf{LayerNorm}[\mathbf{X}] \\ \mathbf{x}_n &\leftarrow \mathbf{x}_n + \mathbf{mlp}[\mathbf{x}_n] \quad \forall\, n \\ \mathbf{X} &\leftarrow \mathbf{LayerNorm}[\mathbf{X}] \end{aligned} \]

  • both units are residual
  • LayerNorm normalizes each embedding separately, using statistics across its \(D\) dimensions
  • a transformer model is \(K\) such layers in series

Division of labour

Multi-head self-attention

  • moves information between positions
  • the only operation in the layer by which one token’s representation depends on another’s
  • masking the attention matrix alone therefore makes a decoder causal

Position-wise MLP

  • processes information within a position
  • the same network applied separately to each of the \(N\) representations
  • supplies the nonlinearity self-attention lacks
  • indifferent to \(N\), so the layer accepts any sequence length

Tokens and embeddings

Sub-word tokenization

Initial tokenization into characters and whitespace, with token frequencies.

After 22 iterations: letters, word fragments and frequent whole words.

Byte pair encoding merges the most frequent adjacent token pair at each iteration, halting at a chosen vocabulary size.

  • the last character of the first merged token cannot be whitespace, which prevents merging across words
  • word vocabularies fail on names, punctuation and suffix variants
  • character vocabularies force the network to relearn the relations between letters
  • the token count first rises as fragments are added, then falls as fragments merge into words

Embeddings

\(\boldsymbol\Omega_e\) multiplied by the one-hot matrix \(\mathbf{T}\) selects one embedding column per token. The two occurrences of an give the same embedding.

\[\mathbf{X} = \boldsymbol\Omega_e\mathbf{T}\]

  • \(\boldsymbol\Omega_e \in \mathbb{R}^{D \times |\mathcal{V}|}\), learned like any other parameter
  • \(\mathbf{T} \in \mathbb{R}^{|\mathcal{V}| \times N}\) holds one-hot columns
  • typical \(D = 1024\), \(|\mathcal{V}| = 30{,}000\)

The embedding depends only on the token index. Position and context are supplied later, by the positional encoding and the attention layers.

Three model types

Model Self-attention Keys and values Trained by
Encoder Unmasked Own embeddings Predicting masked tokens
Decoder Masked Own embeddings Predicting the next token
Encoder-decoder Masked in the decoder Encoder output, in cross-attention Predicting the next output token
  • An encoder produces a representation supporting a variety of tasks
  • A decoder predicts the next token to continue the input text
  • An encoder-decoder converts one text string into another

Encoder, decoder and encoder-decoder models

BERT: architecture

Specification

Vocabulary 30,000 tokens
Embedding 1024
Layers 24
Heads 16
\(D_q\) per head 64
MLP hidden 4096
Parameters ~340 million

Two stages

  • Pre-training learns the parameters by self-supervision on a large corpus, giving general information about the statistics of language
  • Fine-tuning adapts the network to a task using a smaller labelled dataset

\(\boldsymbol\Omega_{vh}, \boldsymbol\Omega_{qh}, \boldsymbol\Omega_{kh}\) are \(64 \times 1024\).

BERT: pre-training

Tokens and a <cls> token are embedded and passed through the transformer layers; every token attends to every other token.

A fraction of input tokens are replaced by <mask>; the corresponding outputs pass through softmax functions under a multiclass classification loss.

Max input 512 tokens
Batch size 256
Steps 1 million
Corpus 3.3 billion words
  • both left and right context are used
  • data efficiency is low: seven tokens processed for two loss terms
  • the task forces syntax, and some common sense: train is likelier than peanut in The <mask> pulled into the station

BERT: fine-tuning

Sentiment classification from the <cls> embedding, and named entity recognition from each word’s embedding.

An extra layer converts the output vectors to the required format.

  • Text classification. The <cls> vector maps to one number through a logistic sigmoid, under binary cross-entropy
  • Word classification. Each \(\mathbf{x}_n\) maps to an \(E \times 1\) vector over \(E\) entity types, under multiclass cross-entropy
  • Text span prediction. Each token maps to two numbers scoring the start and end of the answer span; two softmax functions give the span likelihood

GPT3: autoregressive language modelling

\[Pr(t_1, t_2, \ldots, t_N) = Pr(t_1)\prod_{n=2}^{N} Pr(t_n \mid t_1, \ldots, t_{n-1})\]

  • The model predicts the conditionals \(Pr(t_n \mid t_1, \ldots, t_{n-1})\), and so indirectly the joint probability of all \(N\) tokens
  • Maximizing the joint probability is therefore the next-token prediction task
  • After the transformer layers, one linear layer maps each output embedding to the vocabulary size, followed by a softmax

GPT3: masked self-attention

Each position attends to its own embedding and those earlier in the sequence. Every word contributes a loss term; only the left context is used.

Passing the whole sentence in one forward pass would give the term for \(\log Pr(\text{great} \mid \text{It takes})\) access to the answer and the right context.

  • The dot products for later positions are set to \(-\infty\) before the softmax
  • Tokens interact only in self-attention, so this alone makes the model causal
  • The objective is the summed log probability of the next ground-truth token, a multiclass cross-entropy loss

GPT3: generation and scale

Generation

A sequence, possibly just <start>, is fed in; a token is chosen and the extended sequence fed back. Prior embeddings do not depend on later ones, so computation is reused.

  • Beam search tracks several completions, since the most likely sequence is not reached by greedy choice
  • Top-k sampling draws from the \(K\) most likely tokens, excluding the low-probability tail

Scale

Sequence length 2048
Batch 3.2 million tokens
Layers 96
Embedding 12288
Heads 96
\(D_q\) per head 128
Training tokens 300 billion
Parameters 175 billion

Given example pairs and a further question, the model often completes the sequence correctly without fine-tuning: few-shot learning.

Encoder-decoder: machine translation

The source passes through an encoder. The target passes through a decoder using masked self-attention that also attends to the encoder output through cross-attention, the orange rectangle.
  • The encoder processes the source sentence into one representation per token
  • The decoder receives the ground-truth target, uses masked self-attention, and predicts the following word at each position
  • A cross-attention layer is inserted between the masked self-attention and the MLP

Each output word is conditioned on the previous output words and on the source sentence.

Cross-attention

The computation is that of standard self-attention; the queries come from \(\mathbf{X}_{dec}\) and the keys and values from \(\mathbf{X}_{enc}\).

\[\mathbf{Q} = \boldsymbol\beta_q\mathbf{1}^T + \boldsymbol\Omega_q\mathbf{X}_{dec}\] \[\mathbf{K} = \boldsymbol\beta_k\mathbf{1}^T + \boldsymbol\Omega_k\mathbf{X}_{enc}\] \[\mathbf{V} = \boldsymbol\beta_v\mathbf{1}^T + \boldsymbol\Omega_v\mathbf{X}_{enc}\]

  • the arithmetic is unchanged from the scaled dot-product form
  • the output \(\mathbf{V} \cdot \mathbf{Softmax}[\mathbf{K}^T\mathbf{Q}]\) has \(N_d\) columns
  • the encoder holds source-language statistics, the decoder target-language statistics

Scaling to long sequences

Interaction matrices

Left: in an encoder every token interacts with every other token. Right: in a decoder each token interacts only with previous tokens.

  • encoder complexity is quadratic in sequence length
  • a decoder has roughly half the interactions, and is still quadratic
  • the \(N \times N\) attention matrix is the source of both all-pairs interaction and its cost

Sparse interaction patterns

A convolutional structure: each token interacts with a few neighbours.

Global tokens, the left two columns and top two rows, interact with all tokens.
  • Local attention gives a block-diagonal matrix; information cannot cross blocks, so such layers alternate with full attention
  • Dilated patterns widen the receptive field across layers, as convolution kernels do
  • Global embeddings represent no word and supply long-distance connections; BigBird adds a random sampling of connections

Three strategies

Reduce the matrix

  • Memory-compressed attention applies strided convolution to the keys and values
  • LinFormer projects keys and values onto a smaller subspace, the attention quantities being low rank in practice

Sparsify the matrix

  • local, dilated and convolutional patterns; GPT3 alternates a convolutional matrix with full attention

Modify the mechanism

The softmax terms \(\exp[\mathbf{k}^T\mathbf{q}]\) are treated as a kernel:

\[\exp[\mathbf{k}^T\mathbf{q}] \;\approx\; \mathbf{g}[\mathbf{k}]^T\mathbf{g}[\mathbf{q}]\]

  • this decouples queries and keys, so the matrix products can be reassociated
  • an exact exponential requires \(\mathbf{g}[\bullet]\) to map to an infinite space
  • the linear transformer substitutes a different similarity; the Performer approximates the mapping in finite dimensions

What the sparse patterns give up

The interaction is routed, not removed

  • Global-token and dilated patterns route the all-pairs interaction through intermediaries and across layers
  • A purely convolutional pattern requires many layers to integrate information over large distances

Consequence

  • Sparse patterns are alternated with full attention rather than used alone
  • GPT3 alternates a convolutional interaction matrix with full attention
  • Local attention alone cannot pass information between blocks

Transformers for images

Two obstacles to images

Why the application was not obvious

  • An image holds far more pixels than a sentence holds words, and self-attention is quadratic in the number of tokens
  • A convolutional layer is equivariant to spatial translation and encodes the 2D structure of the image; a transformer must learn both

What the architectures supply

  • ImageGPT quantizes the colour space and accepts a small image
  • Vision Transformer takes \(16 \times 16\) patches as tokens, removing the resolution barrier
  • SWin confines attention to windows, which is the sparsification used for long text

Transformers have nonetheless surpassed convolutional networks for image classification, through the scale of the models and of their pre-training data: what convolution supplies as an architectural bias, the transformer obtains from data.

ImageGPT

Left: images generated one pixel at a time along the rows. Right: completion of the lower half, three completions each.

  • a transformer decoder over pixels, predicting the next pixel value
  • 6.8 billion parameters, limited to \(64 \times 64\) images; 24-bit RGB quantized to 9 bits, giving 512 tokens per position
  • one learned positional encoding per pixel, so 2D relationships are learned
  • 27.4% top-1 error on ImageNet at \(48 \times 48\), below contemporary convolutional architectures; it fails where the target object is small or thin

Vision Transformer

The image is divided into patches, each projected to a patch embedding; the <cls> token predicts the class probabilities.
  • An encoder over \(16 \times 16\) patches, each mapped by a learned linear transformation
  • Standard 1D positional encodings are learned
  • Supervised pre-training on 303 million labelled images from 18,000 classes
  • The final layer is replaced and the system fine-tuned to the target classes
  • 11.45% top-1 error on ImageNet

Without the supervised pre-training it does not match contemporary convolutional networks.

Multi-scale vision transformers

Windows of patches, shifted in alternate layers, with \(2 \times 2\) blocks concatenated between resolutions until one window spans the image.

SWin

  • self-attention within windows of patches, shifted in adjacent layers so the receptive field expands beyond the window border
  • scale reduced by concatenating non-overlapping \(2 \times 2\) patches and mapping to twice the channels
  • no <cls> token; the final features are averaged
  • 9.89% top-1 error

DaViT

  • alternates patch attention over all channels with channel attention over all patches
  • 9.60% top-1 error

Summary

Summary

  • Self-attention routes information across variable-length sequences by learned, data-dependent query-key similarities
  • One parameter set \(\{\boldsymbol\beta_\bullet, \boldsymbol\Omega_\bullet\}\) serves all \(N\) positions; the attention matrix supplies the position-dependent connections
  • The transformer layer is multi-head self-attention between positions and an MLP within positions, both residual, each followed by LayerNorm
  • Three paradigms differ by two questions: whether the attention is masked, and where the keys and values come from
  • Quadratic cost in \(N\) limits sequence length, and has produced sparse patterns, low-rank projections and kernel rewrites
  • Images are handled by treating pixels or patches as tokens