Skip to main content

Transformers and Pretraining

The transformer architecture with positional encodings, residual connections and layer normalization; segment-level recurrence for long contexts; autoregressive, masked and contrastive pretraining objectives; fine-tuning and LoRA; and case studies from GPT-1 to GPT-3 and in-context learning, ViT, Swin, CLIP and SigLIP, Whisper, and masked autoregressive image generation.

Ch. 8 introduced attention as a way for every position to read every other position. This chapter assembles it into the transformer and shows the recipe that made it the universal architecture: one sequence model, pretrained on huge unlabeled data with a simple objective, then adapted to many tasks. The same recipe works for text, images, and audio once each is turned into a sequence of tokens.

A modern model can be described by five choices: (1) the input and its tokenization, (2) the model that extracts and mixes information, (3) the output space it decodes to, (4) the objective that defines what to fit, and (5) the recipe: data, stages, and which parameters are updated.

9.1 The Transformer

Definition 9.1 (Transformer Block) A transformer block maps \(X\in\mathbb R^{T\times d}\) to an output of the same shape with two sublayers, each wrapped in a residual connection and layer normalization (Ch. 3):

\[ Z=X+\mathrm{MultiHead}\bigl(\mathrm{LN}(X)\bigr), \qquad Y=Z+\mathrm{FFN}\bigl(\mathrm{LN}(Z)\bigr), \]

where \(\mathrm{FFN}(z)=W_2\,\phi(W_1z+b_1)+b_2\) is a position-wise MLP, typically with hidden width \(4d\). This is the pre-norm form used by most modern models; the original paper used post-norm, \(\mathrm{LN}\bigl(x+\mathrm{Sublayer}(x)\bigr)\).

  • Attention mixes across positions; the FFN transforms each position. The FFN’s nonlinearity is essential: without activations, stacked layers collapse into a single linear map, which can only reshape space linearly. Normalization keeps activations on a controlled scale, which stabilizes gradients and allows larger learning rates.
  • The original transformer (Vaswani et al., 2017, “Attention Is All You Need”) is an encoder–decoder for translation:
    • the encoder stacks self-attention and FFN blocks over the source sentence;
    • the decoder stacks masked (causal) self-attention, cross-attention whose queries come from the decoder and whose keys and values come from the encoder output, and an FFN;
    • a linear layer and softmax produce next-token probabilities.
    It set a new state of the art in translation at a fraction of the training cost of recurrent models, and transferred to other tasks such as parsing. Its innovation was not attention itself but replacing recurrence entirely, stacking attention so that everything is parallel over positions.
  • Decoder-only models (GPT) keep only the causal self-attention stack; encoder-only models (BERT, ViT) keep only the bidirectional one.

Proposition 9.1 (Self-Attention Ignores Order) Without positional information, self-attention is permutation-equivariant: for any permutation matrix \(P\), \(\mathrm{SA}(PX)=P\,\mathrm{SA}(X)\).

With \(Q=XW_Q\) etc., replacing \(X\) by \(PX\) gives \(Q'=PQ\), \(K'=PK\), \(V'=PV\), and

\[ \mathrm{softmax}\Bigl(\frac{PQK^\top P^\top}{\sqrt{d_k}}\Bigr)PV=P\,\mathrm{softmax}\Bigl(\frac{QK^\top}{\sqrt{d_k}}\Bigr)P^\top PV=P\,\mathrm{SA}(X), \]

because the row-wise softmax commutes with permuting rows and columns, and \(P^\top P=I\). The FFN acts on each position separately, so the whole block is equivariant too.

So “dog bites man” and “man bites dog” would look identical. Order must be injected explicitly.

Definition 9.2 (Positional Encoding) Add a position-dependent vector to each token embedding, \(x_t\leftarrow x_t+\mathrm{PE}_t\). The original transformer uses sinusoids of geometrically spaced frequencies:

\[ \mathrm{PE}_{t,2i}=\sin\Bigl(\frac{t}{10000^{2i/d}}\Bigr), \qquad \mathrm{PE}_{t,2i+1}=\cos\Bigl(\frac{t}{10000^{2i/d}}\Bigr). \]

  • Each sine–cosine pair is a point on a circle rotating at its own frequency, so \(\mathrm{PE}_{t+k}\) is a fixed rotation of \(\mathrm{PE}_t\) for every \(t\): relative offsets are easy to express with linear maps.
  • Alternatives are learned position embeddings (GPT, BERT, ViT) and rotary embeddings (RoPE), which rotate queries and keys so that \(q_t^\top k_s\) depends only on \(t-s\); most current LLMs use RoPE.

9.1.1 Long Contexts by Segment Recurrence

The \(T\times T\) attention matrix makes long sequences memory-hungry. For RNNs the standard fix is truncated BPTT (Ch. 8); the same idea transfers to transformers.

Transformer-XL (Dai et al., 2019) processes a long sequence in segments and carries a memory of hidden states from the previous segment, which the current segment can attend to but not backpropagate into.

M = None                                   # cached hidden states
for segment s in split(sequence, length=L):
    H = Transformer(s, memory=M)           # queries from s; keys/values from [M; s]
    loss(H, targets(s)).backward()         # gradients stay inside this segment
    optimizer.step()
    M = stopgrad(H[-m:])                   # keep last m states, detached

Each step costs attention over \(L+m\) positions instead of the whole sequence, and memory is bounded, yet information can flow across many segments (through the cached states at every layer). As in truncated BPTT, the price is that gradients do not flow back beyond the current segment. Positions must then be encoded relative to the query, since absolute positions repeat across segments.

9.2 Pretraining Objectives

Definition 9.3 (Pretraining Objectives) The three standard self-supervised objectives for a sequence model are:

  • autoregressive (next-token): \(L=-\sum_t\log p_\theta(x_t\mid x_{<t})\), with a causal mask; suited to step-by-step generation (GPT);
  • masked / denoising: hide a set \(\mathcal M\) of positions (or corrupt them) and reconstruct them from the rest, \(L=-\sum_{t\in\mathcal M}\log p_\theta(x_t\mid x_{\setminus\mathcal M})\), with bidirectional attention; builds rich representations (BERT masks about 15% of tokens; MAE masks 75% of image patches);
  • contrastive: pull related pairs together in representation space and push unrelated ones apart; suited to similarity and retrieval (CLIP).
  • With teacher forcing, the autoregressive loss trains all \(T\) positions of a sequence in one parallel pass, because the causal mask already hides the future from each position.

Definition 9.4 (CLIP Contrastive Loss) CLIP (Radford et al., 2021) trains an image encoder \(f\) and a text encoder \(g\) on \(N\) matching image–caption pairs per batch. With normalized embeddings and temperature \(\tau\), let \(s_{ij}=\langle f(I_i),g(T_j)\rangle/\tau\). The loss is a symmetric cross-entropy that classifies the correct partner among all \(N\) in the batch:

\[ L=\frac1{2N}\sum_{i=1}^N\Bigl[-\log\frac{e^{s_{ii}}}{\sum_je^{s_{ij}}}-\log\frac{e^{s_{ii}}}{\sum_je^{s_{ji}}}\Bigr]. \]

The diagonal pairs are positives; all other pairs in the batch are negatives.

  • Language becomes the classifier. For zero-shot classification, embed the prompts “a photo of a {class}” for every class and pick the one most similar to the image: no fixed label set and no task-specific training.
  • SigLIP replaces the batch-wide softmax by an independent sigmoid loss per pair, \(-\sum_{i,j}\log\sigma\bigl(z_{ij}(t\,\langle f(I_i),g(T_j)\rangle+b)\bigr)\) with \(z_{ij}=+1\) on the diagonal and \(-1\) elsewhere. It needs no normalization over the batch, which simplifies very large-batch training. SigLIP 2 adds a captioning decoder, self-distillation and masked prediction for dense features, and native aspect ratios, and outperforms CLIP and SigLIP on classification, retrieval, and dense tasks.

9.2.1 Adapting a Pretrained Model

  • Pretraining learns general patterns (grammar, facts, visual structure) from massive unlabeled data.
  • Fine-tuning continues training on labeled data for target tasks, sharpening the representations toward them.
  • Parameter-efficient fine-tuning keeps the large model frozen and learns a small update.

Definition 9.5 (Low-Rank Adaptation) LoRA (Hu et al., 2021) freezes a pretrained weight \(W_0\in\mathbb R^{d\times k}\) and learns a low-rank update:

\[ W=W_0+BA,\qquad B\in\mathbb R^{d\times r},\ A\in\mathbb R^{r\times k},\ r\ll\min(d,k), \]

with \(B\) initialized to zero so that training starts exactly at the pretrained model.

For one \(4096\times4096\) projection, full fine-tuning updates \(4096^2\approx1.68\times10^7\) parameters. LoRA with \(r=8\) updates \(2\times4096\times8=65{,}536\), about \(0.4\%\). Applied to every attention projection of a large model, the trainable parameters, gradients, and optimizer states shrink by the same factor, and one base model can serve many tasks by swapping small adapters. After training, \(BA\) can be merged into \(W_0\), so inference costs nothing extra.

9.3 Language: From GPT-1 to GPT-3

  • GPT-1 (2018): a decoder-only transformer pretrained by next-token prediction, then fine-tuned. Each task is rewritten as a token sequence with special tokens marking structure (start, delimiter, extract), and fine-tuning adds only a linear layer. It improved the state of the art on 9 of 12 tasks. Findings: transferring more pretrained layers helps; zero-shot ability grows during pretraining, before any fine-tuning; transformers transfer better than LSTMs.
  • GPT-2 (2019, 1.5B parameters): scaling up model and data makes a language model perform tasks zero-shot, inferring the task from the text itself (“unsupervised multitask learning”); state of the art on 7 of 8 language-modeling datasets without fine-tuning.
  • GPT-3 (2020, 175B parameters): the shift from research to engineering, and from fine-tuning to prompting.

Definition 9.6 (In-Context Learning) In-context learning is performing a new task from examples in the prompt, without updating any weights. The model reads the prompt, detects the pattern, and applies it to the next input in the same forward pass:

  • zero-shot: a task description only;
  • one-shot: a description and one example;
  • few-shot: a description and a few examples.

In contrast, fine-tuning writes task knowledge into the weights by gradient updates.

  • In GPT-3, accuracy rises from zero- to one- to few-shot, and the gap widens with model size: larger models use context much more effectively. Across 42 benchmarks every setting improves with scale, few-shot fastest.
  • Validation loss falls smoothly as a power law in training compute across model sizes, the starting point for scaling laws (Ch. 10).

9.4 Vision

Vision Transformer (ViT, Dosovitskiy et al., 2021). Cut the image into \(16\times16\) patches, flatten and linearly embed each, add learned position embeddings, prepend a learnable [CLS] token whose final state is used for classification, and run a standard transformer encoder. Model sizes range from Base (86M parameters) to Huge (632M).

A \(224\times224\) RGB image has \(50{,}176\) pixels. With \(16\times16\) patches it becomes \(14\times14=196\) tokens (197 with [CLS]), each a \(16\cdot16\cdot3=768\)-dimensional vector before embedding. Attention over pixels would need a \(50{,}176^2\approx2.5\times10^9\)-entry matrix per head; over patches it needs \(197^2\approx3.9\times10^4\). Patching is what makes attention on images affordable, at the cost of coarser spatial resolution.

  • ViT is data-hungry. On smaller datasets ResNets win: convolutions build in locality and translation equivariance, which ViT must learn. With very large pretraining sets, ViT keeps improving after CNNs plateau, and larger ViTs pull ahead.
  • What it learns: the patch-embedding filters resemble early CNN filters; the position embeddings recover 2D grid structure; attention spans grow from local in early layers to global in deep layers.

Swin Transformer (Microsoft, 2021) brings back hierarchy and locality:

  • self-attention only within local windows of \(M\times M\) patches, so the cost is linear in image size: \(2M^2hwC\) for the attention instead of \(2(hw)^2C\) for global attention over an \(h\times w\) grid;
  • windows shift by half a window between consecutive layers, so information crosses window borders;
  • patch merging halves the resolution between stages, giving CNN-like multiscale feature maps that suit detection and segmentation.

Masked autoregressive generation (MAR, 2024). Autoregression does not require causal attention or a fixed order: it only requires predicting unknown tokens from known ones.

  • Raster order with causal attention predicts the next token from previous ones;
  • random-order autoregression predicts one token at a time in a shuffled order;
  • masked autoregression uses bidirectional attention over all known tokens and predicts several masked tokens per step.

MAR also uses continuous tokens, modeling each token’s distribution with a small diffusion head (Ch. 7) instead of a softmax over a quantized codebook.

9.5 Audio

Whisper (OpenAI, 2022) is trained on 680k hours of weakly supervised, multilingual, multitask speech data. A log-Mel spectrogram goes into a transformer encoder, and a decoder generates text. Special tokens in the decoder’s input select the language, the task (transcribe or translate), timestamps, and no-speech detection, so every speech task becomes one sequence-to-sequence problem with one token interface.

TipCase Studies at a Glance
modality model objective key idea
text Transformer (2017) supervised translation attention replaces recurrence
text GPT-1/2/3 autoregressive pretrain, then fine-tune, then prompt
image ViT supervised (large scale) patches as tokens
image Swin supervised shifted local windows, hierarchy
image–text CLIP, SigLIP contrastive language as the classifier
image MAR masked autoregressive AR without causal attention
audio Whisper autoregressive, multitask tasks as special tokens

9.6 Supplementary Notes

9.6.1 Key Results