Lecture 4 · Autoregressive Models II: Attention, Tokens and Caching

Deep Unsupervised Learning · Lecture 04。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: UC Berkeley CS294-158 Deep Unsupervised Learning (Spring 2024), Lecture 2 · Thu 1/25/2024 · Likelihood Models: Autoregressive Models, third part (slides 82–157 and appendix 171–179): masked attention, scaled dot-product and multi-head self-attention, Transformers, computational scaling; tokens for text (characters, words, BPE; GPT-1/2/3), for images (raw pixels, Sparse Transformer, iGPT, discrete autoencoders, VQGAN + Transformer), for video and audio, multimodal sequences; caching; encoder-decoder models; modern recurrent models (linear state-space models, linear attention). Homework 1, Questions 3–6. Basis: The slides give the attention formula, the FLOP count, and a long tour of tokenizers and systems, each in a slide or two. These notes derive the mechanics (masks for any order, the cost formula, why the KV cache is exact, why a linear recurrence can be a convolution or a scan, why linear attention is an RNN) and run the homework questions on ShapeWorld, where every tokenizer can be compared with exact likelihoods and every generated caption or image can be checked against the world. Code: code/lecture04/ (6 scripts + transformer_ar.py; PyTorch (CPU); models cached; first runs from seconds to ~8 minutes) Reading time: 4–5 hours including running the code


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Write scaled dot-product attention with a mask, explain multi-head attention, and say why attention has an unlimited receptive field, O(1)O(1) parameters in the sequence length, and parallel training — and why masks give any order for free.
  2. Assemble a decoder-only Transformer (pre-LN blocks, MLP, residuals, learned positions, <bos>) and derive its cost: 8D2L+4DL28D^2L + 4DL^2 FLOPs per attention layer, 16D2L16D^2L per MLP.
  3. Compare tokenizers for text (characters, words, BPE) and images (raw pixels, lossless patches, learned dictionaries, k-means / VQ codes) by sequence length, vocabulary, fidelity — and explain why “the tokenizer is key”.
  4. Build a multimodal model as one token stream with modality tokens, and use it for text → image and image → text.
  5. Explain the KV cache and why it is an exact speed-up.
  6. Describe encoder-decoder models and when they are preferred.
  7. Compute a linear state-space model as a recurrence, a convolution and a parallel scan, and write causal linear attention as an RNN.

0.2 Prerequisites and scope

AssumedIntroduced hereDeveloped later
Lecture 3 (masked models, receptive fields, PixelCNN; the leaderboard)attention, Transformers, positions, <bos>/<eos>discrete autoencoders properly: VQ-VAE (Lecture 8), VQGAN (Lecture 10)
matrix products, softmaxBPE, image tokenizers, multimodal sequencesscaling laws, long context, KV-cache compression (Lecture 16)
KV caching, linear recurrencesmultimodal models (Lecture 22), video tokens (Lecture 17)

0.3 Map

§1  attention: queries, keys, values, masks, orders                                      ← code 01
§2  the Transformer and its cost                                                           ← code 01
§3  tokens: text (chars / words / BPE) and images (pixels, patches, dictionaries, codes)  ← code 02, 04
§4  multimodal sequences                                                                   ← code 05
§5  caching                                                                                ← code 03
§6  encoder-decoder vs decoder-only
§7  modern recurrent models: state-space models and linear attention                     ← code 06
§8  summary   §9 pitfalls   §10 exercises   §11 further reading   §12 next lecture

0.4 Notation

SymbolMeaning
LLsequence length (number of tokens)
DDmodel width (embedding dimension); HH heads of size d=D/Hd = D/H
VVvocabulary size (number of token values)
Q,K,VQ, K, V (matrices)queries, keys, values, each L×DL \times D (the value matrix shares its letter with the vocabulary size; context makes it clear)
<bos>, <eos>beginning / end of sequence tokens

0.5 How the experiments are run

All Transformers share one recipe (TF_CONFIG, TF_TRAIN): D=64D = 64, 4 layers, 4 heads, learned position embeddings; AdamW, 2,000 steps of 32 sequences, warm-up 200 steps then cosine decay (homework 1’s tip). Image data are Lecture 1’s 10,000 / 2,000 ShapeWorld images (floor 17.80 bits; Lecture 3’s best, the gated PixelCNN, 22.3 bits). Text data are 10,000 / 1,000 ShapeWorld captions (exact entropy 11.97 bits per caption).


1. Attention

1.1 The problem attention solves

Lecture 3’s models all hit the same wall: a convolution sees only what its receptive field covers, and the copy rule of ShapeWorld — the right shape repeats the left one 56% of the time, 12 or more columns away — was learned by none of them. An RNN sees everything, but through a fixed-size state and one step at a time. The slides list what (self-)attention offers instead:

  • an unlimited receptive field: any position can read any earlier position in one step;
  • O(1)O(1) parameter scaling with respect to the data dimension: the same weights for a sequence of 10 or 10,000 tokens;
  • parallel computation: all positions at once (unlike an RNN).

1.2 Scaled dot-product attention

Every position tt computes three vectors from its input xtx_t: a query qt=WQxtq_t = W_Q x_t (“what am I looking for?”), a key kt=WKxtk_t = W_K x_t (“what do I contain?”) and a value vt=WVxtv_t = W_V x_t (“what do I hand over?”). Its output is a weighted average of the values,

outt=∑sαts vs,αts=exp⁡(qt⋅ks/d)∑s′exp⁡(qt⋅ks′/d),\text{out}_t = \sum_{s} \alpha_{ts}\, v_s, \qquad \alpha_{ts} = \frac{\exp(q_t \cdot k_s / \sqrt{d})}{\sum_{s'} \exp(q_t \cdot k_{s'} / \sqrt{d})},

or in matrix form Attn(Q,K,V)=softmax(QK⊤/d) V\text{Attn}(Q, K, V) = \mathrm{softmax}(QK^\top / \sqrt{d})\, V. It is a soft, content-based lookup: the query is compared with every key, and the best matches contribute most. Self-attention means queries, keys and values all come from the same sequence.

Why divide by d\sqrt{d}? If the components of qq and kk are independent with unit variance, q⋅kq \cdot k has variance dd; without the scaling, scores grow with the head size and the softmax saturates into a near one-hot choice with vanishing gradients.

Masking makes attention autoregressive: adding −∞-\infty to the scores of forbidden pairs (s>ts > t) gives them weight exactly 0. Script 01 does it by hand on four tokens:

softmax weights after the causal mask        outputs = weights @ V
  1.00  0.00  0.00  0.00                       1.00  0.00
  0.33  0.67  0.00  0.00                       0.33  0.67
  0.25  0.25  0.50  0.00                       0.50  0.50
  0.46  0.16  0.23  0.16                       0.89  0.59

Token 0 can only attend to itself; token 3 mixes all four values with weights set by how well its query matches their keys. Distance plays no role — a token 1,000 positions back is as reachable as the previous one. Script 01 also checks a whole 3-layer model: the gradient of output tt with respect to every input after tt is exactly zero, and every allowed input is used.

Multi-head attention splits DD into HH heads of size d=D/Hd = D/H that attend independently (one head can track “the shape in the other panel” while another tracks “the pixel above”), then concatenates and mixes them with a final linear map.

1.3 Masks are orders

Convolutions hard-wire raster order into the kernel masks. With attention, the order is just the mask: to generate pixels in a zigzag (boustrophedon) order, allow pixel ii to attend to pixel jj iff jj comes earlier in that order. Script 01 prints both masks for a 4×44 \times 4 image; in zigzag order pixel 6 (row 1, column 2) may see row 0 and the pixel to its right — impossible for any fixed masked-convolution kernel (the slides’ “conv?”). This is how MADE-like flexibility (Lecture 3, §3.4) comes back cheaply.

The slides’ appendix also shows masked attention + convolution (PixelSNAIL, Chen et al., 2017): interleaving causal convolutions (cheap, local) with causal attention (global) — the convolution handles texture, the attention long-range structure.


2. The Transformer

2.1 The block

A Transformer (Vaswani et al., 2017) stacks identical blocks of multi-head self-attention and an MLP, each wrapped in a residual connection with layer normalization. We use the pre-LN form of GPT-2:

x←x+Attn(LN(x)),x←x+MLP(LN(x)),MLP(x)=W2 GELU(W1x), W1∈R4D×D.x \leftarrow x + \text{Attn}(\text{LN}(x)), \qquad x \leftarrow x + \text{MLP}(\text{LN}(x)), \qquad \text{MLP}(x) = W_2\, \text{GELU}(W_1 x),\ W_1 \in \mathbb{R}^{4D \times D}.

The residual path carries information and gradients through many blocks unchanged; normalizing the input of each sub-layer keeps that path clean. Attention mixes information across positions; the MLP transforms each position independently. An autoregressive Transformer is this stack with a causal mask, plus:

  • token embeddings (a lookup table V×DV \times D) and position embeddings — attention by itself is permutation-invariant, so it needs to be told where each token is. iGPT and the homework use learned position embeddings; the original Transformer used fixed sinusoids;
  • a <bos> token at the start, so that the first real token also gets a prediction (iGPT); the input at position tt is token t−1t-1;
  • a final LayerNorm and a linear head over the vocabulary.

This is all of TransformerAR in transformer_ar.py, built from Linear, LayerNorm, GELU and Embedding as homework 1 Q3 requires.

2.2 What it costs

The slides give the FLOPs of one layer for a sequence of LL tokens of width DD (multiply-adds counted as 2 FLOPs):

  • attention: the projections to Q,K,VQ, K, V and back cost 4×2D2L=8D2L4 \times 2D^2L = 8D^2L; the scores QK⊤QK^\top and the weighted sum αV\alpha V cost 2DL22DL^2 each, 4DL24DL^2 in total. So 8D2L+4DL28D^2L + 4DL^2 — quadratic in both DD and LL;
  • MLP: two matrices of size D×4DD \times 4D, 2×2×4D2L=16D2L2 \times 2 \times 4D^2 L = 16 D^2 L.

Script 01 counts and measures (D=64D = 64, batch 8):

LLattention MFLOPsshare of the L2L^2 termMLP MFLOPsattention msMLP ms
723.736%4.70.50.2
14410.053%9.41.40.4
28830.769%18.95.50.8
576103.882%37.720.81.9
1152377.590%75.579.33.1

Attention cost

The L2L^2 term dominates once LL exceeds a few times DD; ShapeWorld as raw pixels (L=288L = 288) is already there, and a 64×64×364 \times 64 \times 3 image as raw subpixels would be L≈12,000L \approx 12{,}000. That cost — not modeling power — is why the resolution of the tokens matters so much (§3).


3. Tokens

The slides’ key sentence: autoregressive Transformers are general-purpose, modality-agnostic models — they can model any complex distribution as long as you can tokenize (discretize) the data. Tokenization decides the sequence length (cost: L2L^2), the vocabulary (the size of every prediction), and — if it is lossy — the best fidelity any model can reach.

3.1 Tokens for text

  • Characters (a=0,b=1,…a = 0, b = 1, \dots): a small vocabulary, but many tokens per text — and attention is quadratic.
  • Words (car=0,apple=1,…\text{car} = 0, \text{apple} = 1, \dots): few tokens, a huge vocabulary — and a new word cannot be represented at all.
  • Byte-pair encoding (BPE; Sennrich, Haddow & Birch, 2015) sits in between. Start from characters; repeatedly find the most frequent adjacent pair of tokens in the training text and merge it into a new token; stop at the desired vocabulary size. Frequent words become one token, rare words stay split into pieces (“umbr” + “ella”), and any new combination of characters can still be encoded — 1–2 tokens per word in practice. GPT-2 runs BPE on bytes, so no input is ever unknown.

On ShapeWorld captions (script 04):

tokenizervocabulary (+ <bos>, <eos>)tokens per captionattention pairs
characters4673.75,430
BPE, 64 tokens6637.01,372
words2618.0324

A sentence with two unseen words, “a huge hexagon at the top left and a tiny star at the bottom center.”: characters (70 tokens) and BPE (44 tokens: 'he' 'x' 'a' 'g' 'o' 'n' for “hexagon”) encode it exactly; words turn both new words into <unk>. In a language of only 23 words, BPE with a larger vocabulary simply converges to words.

GPT-1/2/3 are decoder-only Transformers on BPE tokens (Radford et al. 2018, 2019; Brown et al. 2020). GPT-1 showed that unsupervised pretraining followed by supervised fine-tuning beats task-specific models; GPT-2 (1.5B parameters) improved with scale even without fine-tuning (zero-shot); GPT-3 showed in-context learning emerging as the number of parameters grows. Lecture 16 is about that scaling.

3.2 Language models on captions

Homework 1 Q5 trains a character-level Transformer with <bos> and <eos> tokens (<eos> tells the sampler when to stop). Script 04 trains the same Transformer on each tokenization. Since each tokenization is lossless, −log⁡2p(caption)-\log_2 p(\text{caption}) is the same quantity for all of them — and for captions it has an exact floor:

modeltest bits per captionvalid captions (of 200 samples)valid and new
characters11.91100.0%22.5%
BPE, 64 tokens11.9499.5%30.5%
words11.8899.5%17.0%
(Lecture 1) character 5-gram16.75
true distribution (exact bits on these test captions)11.86100%23.0%

A note on the floor: the population entropy of a caption is 11.97 bits, but the exact average −log⁡2p-\log_2 p over these 1,000 test captions is 11.86 (the standard error of a 1,000-caption average is about 0.09 bits). During calibration a model scored 11.72 on 500 captions — seemingly below the entropy — until the exact value for those 500 turned out to be 11.69. Compare models with the exact log-probability of the same test set, not with a population number.

  • All three Transformers are within 0.1 bit of the floor: this language is easy, and the tokenizer changed the cost (5,430 vs 1,372 vs 324 attention pairs), not the quality.
  • The 5-gram needs 16.75 bits: four characters of context cannot see that the second shape’s words depend on the first’s (the copy rule) or which size words allow which positions.
  • Almost all samples are valid captions — “a huge frame at the middle center and a big frame at the middle center.” — but only 17–30% are new. That looks like memorization until you check the truth: the true distribution itself gives only 23% captions outside the training set, because there are only about 25,000 possible captions and the likely ones are already in the 10,000 training captions. Novelty must be judged against what the true distribution would give.

3.3 Tokens for images

The slides’ tour:

  • Raw pixels: each colour channel of each pixel is a byte (0–255). 64×64×3=1264 \times 64 \times 3 = 12k tokens; 256×256×3=196256 \times 256 \times 3 = 196k tokens. Quadratic attention makes this prohibitive.
  • Sparse Transformer (Child et al., 2019): keep raw pixels but use hard-coded sparse masks (each position attends to its row and a strided set of earlier positions), O(LL)O(L\sqrt{L}) instead of O(L2)O(L^2). State-of-the-art likelihoods (2.80 bits/dim on CIFAR-10, Lecture 1), but sample quality still lacking.
  • iGPT (Chen et al., 2020): cluster RGB colours with k-means into a 9-bit palette (512 colours) — one token per pixel instead of three, a ~3× shorter sequence — and train a large GPT on 32×3232 \times 32 (and smaller) images. It showed strong representation-learning results from a purely generative objective. But it still needed tiny images.
  • Discrete autoencoders: learn an encoder that maps an image to a small grid of discrete codes and a decoder that maps codes back — Gumbel-softmax / concrete relaxations, vector quantization (VQ-VAE), finite scalar quantization (FSQ) and lookup-free quantization (LFQ). The slides’ example: 256×256×3→16×16256 \times 256 \times 3 \to 16 \times 16 codes, 384× fewer bytes and 768× shorter sequences — but lossy.
  • VQGAN + Transformer (Esser, Rombach & Ommer, 2021): an AR Transformer over VQGAN codes — high-resolution synthesis becomes tractable. The same recipe extends to video (VideoPoet, MAGVIT-v2: “language model beats diffusion — tokenizer is key”), to in-context learning for vision (Bai et al., 2023: a large AR model over sequences of image tokens), and to audio (AudioCraft).

3.4 Five tokenizations of ShapeWorld

Script 02 compares, on the same images:

tokenizertokens / imagevocabularyattention pairsexact reconstructionvalid reconstruction
raw pixels288282,944100%100%
2×2 patches (each patch’s 4 bits as one number)72165,184100%100%
4×4 patch dictionary (every 4×4 patch seen in training gets an id)18469324100%100%
4×4 k-means, K=64K = 64 (nearest of 64 prototypes)18643241.6%1.7%
one token per panel (an oracle: 960 possible panels)29604100%100%

Out of 216=65,5362^{16} = 65{,}536 possible 4×44 \times 4 binary patches, ShapeWorld uses only 469 — and no test image contains a patch absent from training, so the dictionary is lossless here (real data always contain unseen patches; that is why real tokenizers are lossy or fall back to smaller units). k-means trades fidelity for vocabulary:

codebook KKbits per tokenpixel errorexact reconstruction
164.00.07700.1%
646.00.03091.6%
1287.00.014615.8%
2568.00.005150.6%
4698.90.0000100.0%

A pixel error of 3% sounds small, but one wrong pixel makes a shape invalid: only 1.6% of images survive a 64-code round trip.

3.5 The same Transformer on each tokenization

A lossless tokenizer is a bijection on images, so −log⁡2p(tokens)=−log⁡2p(image)-\log_2 p(\text{tokens}) = -\log_2 p(\text{image}): the bits are directly comparable with the floor and with Lecture 3.

tokensparamstest bits / imagetraining time (est., 2,000 steps)validnovel validcopy rate
raw pixels218,88225.63350 s32%26%0.28 (n=64)
2×2 patches206,86418.7949 s90%80%0.27 (n=179)
4×4 patch dictionary261,84518.9218 s90%78%0.26 (n=179)
4×4 k-means, K=64K = 64 (lossy)209,600(18.94 code bits)17 s0%0%—
one token per panel324,16019.005 s100%81%0.27 (n=200)
(Lecture 3) gated PixelCNN176,38622.28~170 s38%38%0.05 (n=38)

Tokenizer samples

Samples of the same Transformer recipe with five tokenizers (02_tokens_for_images.py).

This is the central result of the autoregressive lectures:

  1. With 2×2 or 4×4 tokens the Transformer lands about 1 bit above the 17.80-bit floor — 3.5 bits better than Lecture 3’s best CNN — and 90% of its samples are valid ShapeWorld images, 80% of them new. On raw pixels, the same recipe after the same 2,000 steps is still at 25.6 bits and cost 7× the compute. (A calibration run with 3,000 steps reached 21.7 bits: raw pixels work, they are just slow.) Shorter sequences mean cheaper steps (quadratic attention) and easier learning (each token carries more of the image).
  2. Coarser is not automatically better. One token per panel gives the shortest sequence and 100% valid samples by construction (every token is a real panel), but no better bits: it over-fits (train 16.9 bits, test 19.0), because a 960-word vocabulary shares nothing between panels — a square at (5, 5) and a square at (5, 6) are unrelated symbols. Lecture 2’s histogram problem, again. And it exists only because we know the world.
  3. Lossy tokens cap fidelity. The Transformer models the k-means codes about as well as the lossless ones, but every decoded sample inherits the tokenizer’s errors: none is pixel-perfect. This is why real systems invest so much in the tokenizer — VQGAN adds adversarial and perceptual losses to its autoencoder (Lecture 10), MAGVIT-v2’s title says it outright.
  4. The copy rule is only partly learned. Attention can reach every earlier token, and copy rates rise above the CNNs’ (≈0.27 for every tokenization vs 0.05–0.29 before), but stay far from the world’s 0.56: a relational pattern — same kind, different size and place — needs more than 2,000 steps. (Plan vs reality: we expected attention to solve it at this budget.)

4. Multimodal sequences

The general nature of Transformers makes it easy to combine modalities: tokenize each, put them in one sequence, model it. Homework 1 Q6 does it with word tokens for captions and VQ tokens for images, special tokens <end of text> / <end of image>, both orders (50/50), and sampling restricted to the current modality. Script 05 uses caption words (23) and 4×4 dictionary image tokens (469):

text first : <eoi>  a huge ring at the ... center .  <eot>  [18 image tokens]
image first: <eot>  [18 image tokens]  <eoi>  a huge ring at the ... center .

(The convention: a sequence starts with the end token of the other modality.) During sampling, logits outside the current modality are masked to −∞-\infty.

The chain rule in two orders. Both orders estimate the same joint probability −log⁡2p(caption,image)-\log_2 p(\text{caption}, \text{image}), which here equals −log⁡2p(image)-\log_2 p(\text{image}) (a caption is a function of the image) — exactly 17.70 bits on these 300 test images:

orderfirst partsecond part (given the first)totalexact
caption, then imagecaption 12.02image | caption 6.3418.3611.97 + 5.83
image, then captionimage 18.74caption | image 0.0318.7817.80 + 0.00

The two totals land within 0.5 bit of each other: one model, one joint distribution, factored either way — imperfectly, so the two factorizations make slightly different errors. Image → caption is almost free (0.03 bits); caption → image must invent what the caption leaves open (6.3 bits vs the exact 5.83 — Lecture 1’s “bits of the image a caption leaves open”).

Generation, checked against the world (ShapeWorld images can be read back exactly):

taskresult
text → image: valid images87.0%
text → image: image exactly matches the requested caption78.0% (89.7% of the valid ones)
image → text: caption exactly right98.3% (99.9% of words in the right place)
unconditional pairs: caption and image agree exactly79.7%

Text to image

Text → image works because every image token can attend to every word in the same sequence. Compare Lecture 3’s class-conditional PixelCNN, whose label — added as a bias everywhere — leaked into the wrong panel. One next-token objective gives a captioner, a text-to-image model and a joint generator at once: the recipe behind VideoPoet and later “any-to-any” models (Lecture 22).


5. Caching

Sampling is sequential: one network pass per token. Part of the cost is waste. Without caching, step tt re-runs the whole prefix through every layer — although the keys and values of old positions never change (they depend only on old tokens; the causal mask guarantees it). The KV cache stores, per layer, the keys and values computed so far; step tt computes qt,kt,vtq_t, k_t, v_t for the new position only and attends from qtq_t to [K<t,kt][K_{<t}, k_t]. Homework 1 Q3c measures it; script 03:

sequencewith cachewithout cachespeed-upidentical samples
2×2 patch tokens (72 per image), 32 samples0.06 s0.37 s6.2×yes
raw pixels (288 per image), 32 samples0.43 s11.69 s27.4×yes

Cost of one step at position tt (raw-pixel model, ms):

tt03171143287
with cache0.580.871.031.122.69
without cache0.403.8510.6831.01102.22

KV cache

  • Exact: the samples are identical — caching reorganizes the computation, it does not approximate it.
  • Without the cache a sample costs O(L2)O(L^2) position-passes; with it, O(L)O(L). The cached step still grows slowly (attention reads all tt cached keys), far less than the uncached one.
  • The gain grows with the sequence length — exactly where raw-pixel models hurt. The price is memory: 2×layers×L×D2 \times \text{layers} \times L \times D numbers per sequence, which for large language models becomes the bottleneck of inference (Lecture 16: multi-query and grouped-query attention).

The convolutional analogue exists too: Fast PixelCNN++ caches the activations that a new pixel does not affect (Lecture 3, §7).


6. Encoder-decoder vs decoder-only

A decoder-only model (GPT, iGPT, our script 05) puts the condition and the target in one causal sequence. An encoder-decoder model (the original Transformer; T5 for text, Parti for text-to-image, PaLI for image-to-text) first encodes the condition with a bidirectional encoder (no causal mask — every condition token sees every other), and the autoregressive decoder cross-attends to the encoder’s outputs (queries from the decoder, keys and values from the encoder).

The slides’ guidance: encoder-decoder is a good choice when there is a clear conditional distribution to model — machine translation, text-to-image, captioning, video captioning, summarization. Both kinds generally scale similarly, but encoder-decoder models seem to learn more useful (or easier to extract) representations, and many text-to-image and video models condition on features from a T5 encoder (Imagen, Lecture 12); decoder-only conditioning has seen less success there. Decoder-only models are simpler and handle “any order, any modality” in one stream, as §4 showed.


7. Modern recurrent models

Transformers model complex distributions efficiently but scale quadratically in the sequence length; RNNs are O(L)O(L) but sequential. How can recurrences be computed in parallel? The slides give two answers.

7.1 Linear state-space models

Consider a linear recurrence (one layer, one input channel for simplicity):

ht=Aht−1+But,yt=Cht,h0=0,h_t = A h_{t-1} + B u_t, \qquad y_t = C h_t, \qquad h_0 = 0,

with learnable (discretized) A,B,CA, B, C — used as a replacement for an attention layer. Because it is linear, it can be computed three ways:

  1. Recurrence: LL sequential steps — ideal for generation (constant memory: only hth_t).
  2. Convolution: unrolling gives yt=∑s≤tCAt−sB usy_t = \sum_{s \le t} C A^{t-s} B\, u_s, a causal convolution with kernel Kj=CAjBK_j = C A^j B of length LL — computable with an FFT in O(Llog⁡L)O(L \log L), fully parallel.
  3. Parallel (associative) scan: each step is an affine map h↦Ah+bth \mapsto A h + b_t; composing two affine maps is again affine, (A2,b2)∘(A1,b1)=(A2A1,A2b1+b2)(A_2, b_2) \circ (A_1, b_1) = (A_2 A_1, A_2 b_1 + b_2), and composition is associative, so all prefix compositions take log⁡2L\log_2 L rounds of pairwise combinations.

Script 06 computes one SSM all three ways:

LLrecurrence vs convolutionrecurrence vs scansequential steps (recurrence)scan rounds
644.4e-152.7e-15646
2566.2e-155.3e-152568
10247.1e-157.1e-15102410

Identical up to rounding. Training uses a parallel form; generation uses the recurrence. This is the idea behind S4 (Gu, Goel & Ré, 2021) and its successors (Mamba makes A,B,CA, B, C input-dependent, keeping the scan).

7.2 Linear attention

Attention’s similarity exp⁡(q⋅k)\exp(q \cdot k) can be replaced by any non-negative kernel κ(q,k)=ϕ(q)⋅ϕ(k)\kappa(q, k) = \phi(q) \cdot \phi(k) with a feature map ϕ\phi (Katharopoulos et al., 2020; we use ϕ(x)=elu(x)+1\phi(x) = \text{elu}(x) + 1). Then

outt=∑s≤tϕ(qt)⊤ϕ(ks) vs∑s≤tϕ(qt)⊤ϕ(ks)=ϕ(qt)⊤Stϕ(qt)⊤zt,St=∑s≤tϕ(ks)vs⊤,zt=∑s≤tϕ(ks),\text{out}_t = \frac{\sum_{s \le t} \phi(q_t)^\top \phi(k_s)\, v_s}{\sum_{s \le t} \phi(q_t)^\top \phi(k_s)} = \frac{\phi(q_t)^\top S_t}{\phi(q_t)^\top z_t}, \qquad S_t = \sum_{s \le t} \phi(k_s) v_s^\top, \quad z_t = \sum_{s \le t} \phi(k_s),

and St,ztS_t, z_t can be updated one token at a time: causal linear attention is an RNN with a d×dd \times d state — trainable in parallel like attention, sampled in O(1)O(1) per token like an RNN. Script 06: the parallel and recurrent forms agree to 2×10−162 \times 10^{-16}; linear attention differs substantially from softmax attention on the same Q,K,VQ, K, V (max difference 0.19 for outputs of typical size 0.07): the kernel cannot be as sharply peaked as exp⁡\exp, so it attends less selectively. Cost as LL grows (numpy, one head):

LL256512102420484096
softmax attention (ms)1262594
linear attention, recurrent form (ms)123714

Linear attention cost

Quadratic vs linear. The price: a fixed-size state must summarize the whole past, as in an RNN, so pure linear models are weaker at precise recall; hybrids that mix a few attention layers with recurrent ones (Based, Griffin) appear in Lecture 16.

7.3 Alternatives and complements to tokenization

The slides close the autoregressive deck with ideas that reduce sequence length without (only) a tokenizer: hierarchical and super-resolution autoregressive models — generate a subsampled or grayscale image first, then the details conditioned on it (Lecture 3, §7). Tokenizers and hierarchies combine: VAR-style next-scale prediction and multi-scale tokenizers are modern descendants.


8. Summary

  1. Attention is a masked, content-based weighted average: unlimited receptive field, parameters independent of the sequence length, parallel training. Masks implement any order. Cost per layer: 8D2L+4DL28D^2L + 4DL^2 FLOPs; the MLP 16D2L16D^2L.
  2. A decoder-only Transformer = embeddings + positions + <bos> + pre-LN blocks of attention and MLP + a softmax head, trained by maximum likelihood like every model so far.
  3. Tokens decide cost and fidelity. For captions, characters / BPE / words all reached the exact floor within 0.1 bit; they differed in length (74 / 37 / 18). For images, the same Transformer reached 18.8 bits (1 bit from the floor, 90% valid samples) on 2×2 or 4×4 lossless tokens, 25.6 bits on raw pixels at 7× the cost; too-coarse tokens over-fit, lossy tokens cap fidelity.
  4. Multimodal models are one token stream; both orders estimate the same joint, and one model captions images (98% exact) and draws captions (78% exact matches).
  5. The KV cache is an exact speed-up: O(L)O(L) instead of O(L2)O(L^2) position-passes per sample (27× for 288 tokens), paid for in memory.
  6. Encoder-decoder models use a bidirectional encoder for the condition and cross-attention in the decoder.
  7. Linear state-space models run as recurrence, convolution or scan; linear attention is an RNN. They trade attention’s precise recall for linear cost.

9. Common pitfalls

  1. Off-by-one in the input shift. Position tt must receive token t−1t-1 (or <bos>), never token tt. A model that sees its target trains to near-zero loss and generates garbage.
  2. Forgetting positions. Without position embeddings attention is permutation-invariant: “a ring left of a square” and “a square left of a ring” look the same.
  3. Comparing bits across lossy tokenizers. Code bits of a lossy tokenizer are not image bits; only lossless tokenizations can be compared with each other and with the floor.
  4. Comparing with a population entropy on a small test set. Use the exact log-probability of the same test examples when you have it (§3.2).
  5. Judging novelty without a reference. A perfect model of a small world repeats training examples often.
  6. Assuming a cache changes results. It must not; a mismatch between cached and uncached samples is a bug (e.g. wrong position offsets for new tokens).
  7. Ignoring the vocabulary side of the trade-off. A huge vocabulary makes every token a separately learned symbol (the panel tokenizer over-fit).

10. Exercises

Exercise 1 (derivation: the FLOP count). Derive 8D2L+4DL28D^2L + 4DL^2 for one attention layer and 16D2L16D^2L for the MLP (count one multiply-add as 2 FLOPs). At what LL does the L2L^2 term equal the rest of the layer (attention projections + MLP)? Evaluate for D=64D = 64 and D=4096D = 4096.

Answer

Projections: Q,K,VQ, K, V and the output map are four D×DD \times D matrix products over LL positions: 4⋅2D2L4 \cdot 2D^2L. Scores QK⊤QK^\top: L×LL \times L entries, each a DD-dimensional dot product: 2DL22DL^2; the weighted sum αV\alpha V: another 2DL22DL^2. MLP: D→4D→DD \to 4D \to D, 2⋅2⋅4D2L=16D2L2 \cdot 2 \cdot 4D^2 L = 16D^2L. Equality: 4DL2=8D2L+16D2L=24D2L⇒L=6D4DL^2 = 8D^2L + 16D^2L = 24D^2L \Rightarrow L = 6D: 384 for D=64D = 64, 24,576 for D=4096D = 4096 — large language models spend most compute in matrix products until contexts get very long.

Exercise 2 (why d\sqrt{d}). If q,k∈Rdq, k \in \mathbb{R}^d have independent components with mean 0 and variance 1, show that q⋅kq \cdot k has variance dd. What happens to the softmax for d=64d = 64 without scaling?

Answer

Var(∑iqiki)=∑iVar(qiki)=∑iE[qi2]E[ki2]=d\mathrm{Var}(\sum_i q_i k_i) = \sum_i \mathrm{Var}(q_i k_i) = \sum_i E[q_i^2]E[k_i^2] = d. Scores then have standard deviation 8; the largest of a few dozen scores is typically several units above the rest, the softmax is nearly one-hot, and its gradient (which is proportional to α(1−α)\alpha(1-\alpha)) nearly vanishes. Dividing by d\sqrt{d} restores unit variance.

Exercise 3 (masks for orders). Write the boolean attention mask for generating a 2×32 \times 3 image in column order (column by column, top to bottom). Which pixels may pixel (0, 1) attend to?

Answer

Order: (0,0), (1,0), (0,1), (1,1), (0,2), (1,2), i.e. ranks 0..5. Pixel ii may attend to pixel jj iff rank(j)<(j) < rank(i)(i) (with the input shift: the input at a position holds the previous token in the order). Pixel (0, 1) has rank 2 and may attend to (0,0) and (1,0) — the whole first column, including the pixel below-left of it, which a raster-order kernel could never see.

Exercise 4 (BPE by hand). Run three merges of BPE on the corpus “aaab aab ab” (words split on spaces). Which tokens are created?

Answer

Pairs in “a a a b”, “a a b”, “a b”: (a, a) occurs 2 + 1 = 3 times, (a, b) 1 + 1 + 1 = 3 times — a tie, broken by a fixed rule (our code picks the lexicographically larger pair, (a, b)). Merge 1: “ab” → words “a a ab”, “a ab”, “ab”. Merge 2: (a, ab) occurs 2 times, (a, a) once → “aab” → “a aab”, “aab”, “ab”. Merge 3: (a, aab) once → “aaab”. Tokens: ab, aab, aaab — every word has become a single token. With a different tie rule the merge order changes but the final word tokens are the same here.

Exercise 5 (lossless vs lossy). Prove that for a lossless tokenizer TT (a bijection between images and token sequences), −log⁡2pθ(T(x))-\log_2 p_\theta(T(x)) under a model of token sequences is the code length of xx under the induced image model, and explain why this fails for k-means tokens.

Answer

Define q(x)=pθ(T(x))q(x) = p_\theta(T(x)). Since TT is a bijection onto the set of sequences the model can assign probability to (or a subset of it), ∑xq(x)≤1\sum_x q(x) \le 1, so qq is a (possibly sub-normalized) distribution over images with code lengths −log⁡2q(x)=−log⁡2pθ(T(x))-\log_2 q(x) = -\log_2 p_\theta(T(x)). For a lossy tokenizer, many images map to the same code: pθ(T(x))p_\theta(T(x)) is the probability of a set of images, not of xx; and decoding the code gives one representative of the set, often not xx itself.

Exercise 6 (KV-cache memory). A model has 32 layers, D=4096D = 4096, a context of 8,192 tokens, and stores keys and values in 16-bit floats. How much memory does the KV cache take per sequence? How does grouped-query attention with 8 key/value heads out of 32 query heads change it?

Answer

2 (K and V)×32×8192×4096×2 bytes=4.32 \text{ (K and V)} \times 32 \times 8192 \times 4096 \times 2 \text{ bytes} = 4.3 GB per sequence. With 8 KV heads shared by 32 query heads, K and V have width 4096×8/32=10244096 \times 8/32 = 1024: 4× smaller, 1.07 GB.

Exercise 7 (the scan). Verify the composition rule (A2,b2)∘(A1,b1)=(A2A1,A2b1+b2)(A_2, b_2) \circ (A_1, b_1) = (A_2A_1, A_2 b_1 + b_2) and that it is associative. How many rounds does a Hillis–Steele scan need for L=1000L = 1000, and how much total work does it do compared with the sequential recurrence?

Answer

Applying h↦A1h+b1h \mapsto A_1 h + b_1 then h↦A2h+b2h \mapsto A_2 h + b_2 gives A2(A1h+b1)+b2A_2(A_1 h + b_1) + b_2. Associativity follows from associativity of function composition (or check the formulas directly). Rounds: ⌈log⁡21000⌉=10\lceil \log_2 1000 \rceil = 10. Work: each round combines up to LL pairs, about Llog⁡2L≈10,000L \log_2 L \approx 10{,}000 combinations (each a d×dd \times d matrix product) vs L=1000L = 1000 steps for the recurrence — more total work, far fewer sequential steps. (Work-efficient scans exist with O(L)O(L) work and 2log⁡2L2\log_2 L rounds.)

Exercise 8 (linear attention as an RNN). Show that causal linear attention can be computed with O(d2)O(d^2) memory and O(d2)O(d^2) work per new token, independent of tt. Why can softmax attention not be rewritten this way?

Answer

Keep St=St−1+ϕ(kt)vt⊤S_t = S_{t-1} + \phi(k_t) v_t^\top (d×dd \times d) and zt=zt−1+ϕ(kt)z_t = z_{t-1} + \phi(k_t) (dd); then outt=ϕ(qt)⊤St/ϕ(qt)⊤zt\text{out}_t = \phi(q_t)^\top S_t / \phi(q_t)^\top z_t: constant memory and work per token. Softmax uses exp⁡(qt⋅ks)\exp(q_t \cdot k_s), which does not factor into a function of qtq_t times a function of ksk_s with a finite feature map, so the sum over ss cannot be pre-accumulated independently of qtq_t.

Exercise 9 (the panel tokenizer). The panel model has 324,160 parameters, most of them in the embeddings and the output head over 960 tokens. Estimate how many training occurrences each panel token has, and explain the train/test gap (16.9 vs 19.0 bits) with Lecture 2’s k/2nk/2n rule.

Answer

20,000 panels (two per image) over 960 types: ~21 occurrences per type on average, but small shapes have many positions and each of their panels appears only a few times. The output head alone has 960 × 64 + 960 ≈ 62,000 parameters, essentially a 960-way histogram per context: with k≈960k \approx 960 free probabilities per panel slot and n=10,000n = 10{,}000 images, k/(2nln⁡2)≈0.07k/(2n \ln 2) \approx 0.07 bits per slot from the marginal alone, plus much more for the 960 × 960 conditional of the right panel given the left, which 10,000 examples cannot fill — hence over-fitting. Patch tokens share statistics across panels and avoid it.

Exercise 10 (homework Q6 logic). In script 05 the model must choose the order at position 0 (it costs 1.01 bits). Why exactly 1 bit for a perfect model, and how would you remove this cost when you only care about text → image?

Answer

The training data contain each pair in both orders equally often, so the first token is a fair coin: H=1H = 1 bit. If only text → image matters, train (or evaluate) only on text-first sequences, or condition on the first token by always supplying <eoi> as part of the prompt — then its probability is never scored.


11. Further reading

From the slides

  • A. Vaswani et al. Attention Is All You Need. NeurIPS 2017.
  • A. Radford et al. Improving Language Understanding by Generative Pre-Training (GPT-1), 2018; Language Models are Unsupervised Multitask Learners (GPT-2), 2019; T. Brown et al. Language Models are Few-Shot Learners (GPT-3), NeurIPS 2020.
  • R. Sennrich, B. Haddow, A. Birch. Neural Machine Translation of Rare Words with Subword Units (BPE), 2015.
  • N. Parmar et al. Image Transformer. ICML 2018; R. Child et al. Generating Long Sequences with Sparse Transformers. 2019.
  • M. Chen et al. Generative Pretraining from Pixels (iGPT), ICML 2020.
  • A. van den Oord, O. Vinyals, K. Kavukcuoglu. Neural Discrete Representation Learning (VQ-VAE), NeurIPS 2017; E. Jang, S. Gu, B. Poole. Categorical Reparameterization with Gumbel-Softmax, 2016; C. Maddison, A. Mnih, Y. W. Teh. The Concrete Distribution, 2016; F. Mentzer et al. Finite Scalar Quantization, 2023; L. Yu et al. Language Model Beats Diffusion — Tokenizer is Key to Visual Generation (MAGVIT-v2, LFQ), 2023.
  • P. Esser, R. Rombach, B. Ommer. Taming Transformers for High-Resolution Image Synthesis (VQGAN), CVPR 2021.
  • D. Kondratyuk et al. VideoPoet, 2023; Y. Bai et al. Sequential Modeling Enables Scalable Learning for Large Vision Models, 2023.
  • C. Raffel et al. T5, JMLR 2020; J. Yu et al. Parti, 2022; X. Chen et al. PaLI, 2022.
  • A. Gu, K. Goel, C. Ré. Efficiently Modeling Long Sequences with Structured State Spaces (S4), 2021; A. Katharopoulos et al. Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention, ICML 2020.
  • X. Chen et al. PixelSNAIL, 2017 (attention + convolution).

Added by these notes

  • A. Radford et al. GPT-2 code and the “byte-level BPE” detail; R. Xiong et al. On Layer Normalization in the Transformer Architecture (pre-LN), ICML 2020.
  • A. Gu, T. Dao. Mamba: Linear-Time Sequence Modeling with Selective State Spaces, 2023 — input-dependent SSMs with a parallel scan.
  • G. E. Blelloch. Prefix Sums and Their Applications, 1990 — the parallel scan.
  • A. Aghajanyan et al. / Chameleon Team. Chameleon: Mixed-Modal Early-Fusion Foundation Models, 2024 — one token stream for text and images.

12. Next lecture

Lectures 2–4 made exact likelihood tractable by the chain rule, at the price of sequential sampling. Lecture 5 starts a second way to get exact likelihoods — flow models: an invertible network maps data to a simple distribution, and the change-of-variables formula turns the density of the simple distribution into the density of the data. We begin in one and two dimensions: CDFs as flows (Lecture 2’s inverse-CDF sampling, run backwards), mixtures of logistics as flows, 2-D autoregressive flows, and the trade-off between autoregressive flows (fast density, slow sampling) and inverse autoregressive flows (the reverse).

← 返回课程目录