Lecture 12 · Multimodal II: Tokenizing Images and Generating Them

Advanced Natural Language Processing · Lecture 12。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

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

本篇目录

Maps to: CMU 11-711 Spring 2026, Lecture 12 (02/19), slides anlp-s2026-12-multimodal-ii.pdf; course code 12_multimodal_ii/vqvae.ipynb. Readings: A. van den Oord, O. Vinyals, K. Kavukcuoglu, Neural Discrete Representation Learning (VQ-VAE, NeurIPS 2017); P. Esser, R. Rombach, B. Ommer, Taming Transformers for High-Resolution Image Synthesis (VQGAN, CVPR 2021). Additional: M. Chen et al., Generative Pretraining from Pixels (Image GPT, ICML 2020); A. Ramesh et al., Zero-Shot Text-to-Image Generation (DALL·E, ICML 2021); Chameleon Team (Meta), Chameleon: Mixed-Modal Early-Fusion Foundation Models (2024); D. Kingma, M. Welling, Auto-Encoding Variational Bayes (2013). Sources: the public slides and notebook, the readings, and the papers cited in each section. Every number labelled “measured” comes from code/lecture12/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14, one CPU thread). Code: code/lecture12/ — four demos, each under two minutes. Reading time: ~100 minutes for the prose; ~25 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Name the four paradigms of generative modeling (autoregressive, VAE, GAN, diffusion) and say what each learns and how each samples.
  2. Explain why modeling pixels autoregressively works in principle and fails in practice: sequence length and the low information per token. Compute both.
  3. Derive the ELBO (importance sampling + Jensen), explain its two terms as reconstruction and rate, and explain why the reparameterization trick is needed.
  4. Explain the VQ-VAE: nearest-codebook quantization, the codebook and commitment losses, the straight-through gradient, dead codes. Explain why VQGAN adds perceptual and adversarial losses.
  5. Describe early-fusion mixed-modal models (DALL·E, Chameleon): image tokens in the LM’s vocabulary, text-to-image by next-token prediction, reranking. Name their main weakness, information lost in the tokenizer.

0.2 Prerequisites and scope

  • Prerequisites:
    • Lecture 3: language modeling as ∏tp(xt∣x<t)\prod_t p(x_t \mid x_{<t}); bits and entropy.
    • Lecture 9: sampling, top-k, the KV cache.
    • Lecture 11: Shape World, ViT, CLIP, parse().
    • Lecture 1, demo 05: the score-function (REINFORCE) gradient.
  • Scope: multi-to-image and multi-to-multi with discrete image tokens.
  • Not in scope:
    • Diffusion and flow models: Lecture 15, which the slides name as the route to state-of-the-art image quality.
    • GANs, beyond their role in VQGAN.
    • Video and audio tokenizers (the same ideas apply).

0.3 Section → code map

SectionIdeaDemo in code/lecture12/
§2.1sequence lengths and attention cost01_pixels.py Part A
§2.2information per token, exactly01_pixels.py Part B (+ image_tokens.py)
§2.3a pixel Transformer vs the exact entropy; where the bits go; samples01_pixels.py Parts C–D
§3.1–3.2the ELBO; importance-weighted bounds; β; reparameterization02_vae.py
§3.3–3.4VQ-VAE: codes, fidelity, usage, straight-through, grid size03_vqvae.py
§4text → image with one Transformer; sampling; CLIP reranking04_text_to_image.py

0.4 Notation

SymbolMeaning
xxan image; x1,…,xTx_1, \dots, x_T its tokens (pixels or codes)
zza latent variable (continuous for the VAE, discrete codes for the VQ-VAE)
p(z)p(z), pθ(x∣z)p_\theta(x \mid z)prior and decoder
qϕ(z∣x)q_\phi(z \mid x)encoder (approximate posterior)
e1,…,eK∈RDe_1, \dots, e_K \in \mathbb{R}^Dcodebook vectors; ze(x)z_e(x) encoder output, zq(x)z_q(x) its quantized version
sg[⋅]\mathrm{sg}[\cdot]stop-gradient: identity forward, zero gradient backward
HHentropy in bits

1. Generating images: the goal and the paradigms

1.1 Where we are

Lecture 11 built models whose input includes images and whose output is text. Products now go further. A model like GPT-4o takes text and images in and puts text and images out (“remove the bridges from this photo”). The slides’ goal is concrete:

  • an image tokenizer that turns an image into tokens;
  • an image de-tokenizer that turns tokens back into an image;
  • a single Transformer for text and images, which reads and writes both.

Each of the three demands is a design decision with a measurable cost, and the lecture is about those costs.

1.2 Four paradigms

paradigmlearnsgenerates by
autoregressivep(x)=∏tpθ(xt∣x<t)p(x) = \prod_t p_\theta(x_t \mid x_{<t}), one dimension (pixel, token) at a timesampling the dimensions in order
VAEan encoder x→zx \to z and a decoder z→xz \to x, trained to reconstruct through a compressed zzsampling zz from a prior, decoding
GANa generator G(z)G(z) that fools a discriminator D(x)D(x) trained to spot fakessampling zz, one forward pass
diffusionto undo small steps of added noisestarting from noise, denoising step by step (Lecture 15)

The autoregressive route is the one an LM already knows. The question of this lecture is what it should treat as a “token” of an image.


2. Attempt 1: pixels as tokens

2.1 The idea, and the sequence-length problem

Treat an image x∈RH×W×Cx \in \mathbb{R}^{H \times W \times C} as a sequence of pixel values x1,…,xTx_1, \dots, x_T in raster order (row by row). Each value is in {1,…,256}\{1, \dots, 256\}, or an index into a color palette. Then train a language model:

LMLE=−∑t=1Tlog⁡pθ(xt∣x<t).\mathcal{L}_{\text{MLE}} = -\sum_{t=1}^{T} \log p_\theta(x_t \mid x_{<t}).

This lineage is real and successful at small scale:

  • PixelRNN / PixelCNN (van den Oord et al., 2016): LSTMs and masked convolutions.
  • Image Transformer (Parmar et al., 2018): local self-attention blocks.
  • Image GPT (Chen et al., 2020): GPT-2 on pixel sequences. Its features rivaled contrastive methods on linear probes (CIFAR-10: 96.3% for iGPT-L).

The slides name two challenges. The first is sequence length. Measured in demo 01 Part A:

sequencetokens TTattention scores T2T^2 per head and layer
1024×1024 RGB, one token per channel value3,145,7289.9 × 10¹² (≈ 40 TB in fp32)
256×256, one token per pixel65,5364.3 × 10⁹ (17 GB)
VQGAN / DALL·E tokens for a 256×256 image (32×32)1,0241.0 × 10⁶
Shape World 24×24 pixels5763.3 × 10⁵
Shape World at 12×121442.1 × 10⁴
Shape World as VQ tokens (§3.3)361.3 × 10³

Image GPT therefore trained on 32×32 to 64×64 images, with a 9-bit (512-color) palette found by k-means, and still needed “memory-efficient attention patterns”. At our tiny scale the same wall appeared. A training step of the same 2-layer model took about 9× longer on 576 tokens than on 144 (demo 01; times vary by machine), so demo 01 models 12×12 images, as Image GPT downsampled.

2.2 The information problem, measured exactly

The second challenge: “each pixel carries relatively little semantic information compared to a word token”. Shape World lets us compute this exactly. A one-object scene is a shape (4), a color (5), a size (2) and a position (196 or 324 positions). Enumerating every scene the sampler can produce (10,400 of them, with their probabilities) gives:

representationbits per imagebits per token (average)
24×24 pixels (576 tokens)13.300.023
12×12 palette pixels (144 tokens)12.910.090
VQ tokens (36)≤ 13.30≤ 0.37
the scene itself (shape, color, size, x, y)13.302.66

At 12×12 some scenes look identical: 8,452 distinct pictures, with 12.91 bits of entropy. A pixel model must spend most of its computation predicting tokens that are almost certain. A word in a caption carries orders of magnitude more information than a pixel. This is the deeper reason for tokenizers: put more meaning into each position.

2.3 Measured: a pixel Transformer on 144 tokens

Demo 01 trains Lecture 5’s Transformer (2 layers, d=64d = 64) on 20,000 12×12 palette images, for 2,000 steps of 32 images. Because the exact entropy is known, we can say how far from perfect the model is. No model can average below 12.91 bits per image.

training step5001,0001,5002,000
test bits per image18.6016.6915.6715.29
excess over the entropy5.693.782.762.38

Where do the bits go?

pixelsshare of the tokensmean bits per tokenshare of all bits
background92.1%0.03631.0%
the first colored pixel (raster order)0.7%7.5149.1%
other object pixels7.2%0.29419.9%

61.9% of all pixel tokens cost less than 0.01 bit. Half the information of an image is decided at a single token, the first colored pixel. That token says where the object starts and in which color; the rest is nearly determined. A pixel LM thus spends 144 sequential steps to make roughly one decision that matters.

Samples (demo 01 Part D). Of 500 samples drawn at temperature 1, 35.4% are an exact picture of a shape, checked against every possible rendering. Colors are balanced among the valid ones (30–43 per color). One wrong pixel among 144 spoils an image, and errors compound over sequential steps. Lecture 9 made the same argument about tail mass in text. Drawing all 500 took about a second with the KV cache: 144 sequential steps per image.


3. Attempt 2: learn a tokenizer

3.1 The VAE: compress, then generate

Intuition. An image’s information fits in far fewer numbers than its pixels (§2.2). So learn to compress an image into a short code zz, and to decompress zz back into an image. If the codes also follow a simple distribution, generation is: sample a code, decompress.

The model (Kingma & Welling, 2013). Assume data arises as:

  • sample a latent z∼p(z)=N(0,I)z \sim p(z) = \mathcal{N}(0, I);
  • produce xx with a decoder pθ(x∣z)p_\theta(x \mid z).

An encoder qϕ(z∣x)q_\phi(z \mid x), a Gaussian whose mean and variance are produced by a network, approximates the intractable posterior p(z∣x)p(z \mid x).

The ELBO. The slides derive it in four lines:

log⁡p(x)=log⁡∫p(x,z) dz=log⁡Eq(z∣x)[p(x,z)q(z∣x)]  ≥  Eq(z∣x)[log⁡p(x,z)q(z∣x)]\log p(x) = \log \int p(x, z)\, dz = \log \mathbb{E}_{q(z \mid x)}\left[\frac{p(x, z)}{q(z \mid x)}\right] \;\ge\; \mathbb{E}_{q(z \mid x)}\left[\log \frac{p(x, z)}{q(z \mid x)}\right] =Eq(z∣x)[log⁡p(x∣z)]−DKL(q(z∣x) ∥ p(z)).= \mathbb{E}_{q(z \mid x)}[\log p(x \mid z)] - D_{\mathrm{KL}}\big(q(z \mid x) \,\|\, p(z)\big).

  • The second equality is importance sampling: multiply and divide by qq.
  • The inequality is Jensen’s (log⁡E≥Elog⁡\log \mathbb{E} \ge \mathbb{E} \log).
  • The gap between the two sides is exactly DKL(q(z∣x) ∥ p(z∣x))D_{\mathrm{KL}}(q(z \mid x) \,\|\, p(z \mid x)).

Training maximizes this evidence lower bound; the loss is its negative, LVAE\mathcal{L}_{\text{VAE}}. Its terms:

  • reconstruction: decode a sampled zz and score xx;
  • regularization: keep each encoding close to the prior, so that samples from the prior look like encodings.

The reparameterization trick. The expectation is over z∼qϕ(z∣x)z \sim q_\phi(z \mid x), which depends on the encoder’s parameters. To get a gradient through the sample, write z=μϕ(x)+σϕ(x)⊙εz = \mu_\phi(x) + \sigma_\phi(x) \odot \varepsilon with ε∼N(0,I)\varepsilon \sim \mathcal{N}(0, I). The randomness then sits in ε\varepsilon, and zz is a differentiable function of ϕ\phi.

Measured (demo 02; one-object images; a 16-dimensional latent; the decoder a Gaussian with σ = 0.1 per pixel channel).

  • Term by term. With β=1\beta = 1: reconstruction Eq[log⁡p(x∣z)]=2172.9\mathbb{E}_q[\log p(x \mid z)] = 2172.9 nats, KL = 25.1 nats, ELBO = 2147.7 nats. These are continuous densities, so only differences matter.
  • Jensen’s gap is real. Importance-weighted bounds (Burda et al., 2016) with KK samples climb toward log⁡p(x)\log p(x):
importance samples KK110100
bound on log⁡p(x)\log p(x) (nats)2148.02154.3 (+6.3)2156.2 (+8.2)
  • Why the trick matters. For one image, the gradient of Eq[log⁡p(x∣z)]\mathbb{E}_q[\log p(x \mid z)] with respect to μ\mu was estimated 1,000 times with one sample each:
estimatorvariance per coordinate
reparameterization135
score function (REINFORCE, Lecture 1): log⁡p(x∣z) ∇μlog⁡q(z∣x)\log p(x \mid z)\, \nabla_\mu \log q(z \mid x)2.58 × 10⁸
score function with a mean baseline1.62 × 10³

The score-function estimator multiplies ∇log⁡q\nabla \log q by log⁡p(x∣z)≈2,173\log p(x \mid z) \approx 2{,}173 nats. Every sample’s estimate is therefore huge, and the samples cancel only on average: 1.9 million times the variance. A baseline helps (12× instead), but reparameterization differentiates through the sample. It is why VAEs train at all.

3.2 Rate, distortion, and why VAE samples disappoint

The KL term has a second reading. It is the rate: how many nats the code carries about the image (Alemi et al., 2018). Shape World tells us what the rate should be: a one-object image holds 13.30 bits. Demo 02 trains three VAEs, weighting the KL by β\beta (β-VAE, Higgins et al., 2017):

βrate (KL, bits)distortion (MSE)reconstruction parses exactlyprior samples valid
0.2556.90.0026727.6%12.0%
136.30.0024523.0%39.6%
420.00.0025722.6%42.4%

Three lessons:

  • The code is inefficient. Even at β = 4 it uses 20 bits for 13.3 bits of content, and the extra rate does not buy exact reconstructions.
  • β trades rate for sample quality. A low β writes information into the code that the Gaussian prior never produces. Prior samples then land between the training codes, and decode into nothing (12.0% valid).
  • Reconstructions are blurry (23% parse exactly). The decoder is trained with a pixel-wise Gaussian (L2) likelihood. When a detail is uncertain, the L2-optimal output is the average of the possibilities: a blur.

Demo 02’s interpolation shows one more property. Decoding the point halfway between the codes of a purple circle and a red square gives a green square. A straight line in latent space is not a straight line in the world.

These are the classic VAE complaints: blurry outputs, and samples worse than reconstructions. They motivate discrete codes: a prior over a finite set of codes can be an LM, which is far more flexible than N(0,I)\mathcal{N}(0, I).

3.3 The VQ-VAE: a discrete tokenizer

From continuous to discrete (van den Oord et al., 2017). Keep the encoder and the decoder, but force the code through a codebook e1,…,eK∈RDe_1, \dots, e_K \in \mathbb{R}^D:

  1. The encoder maps the image to a grid of vectors ze(x)z_e(x). Ours is 6×6 vectors for a 24×24 image, so each vector summarizes a 4×4-pixel cell.
  2. Quantize: replace each vector by its nearest codebook vector, zq(x)=ek∗z_q(x) = e_{k^*} with k∗=arg⁡min⁡j∥ze(x)−ej∥2k^* = \arg\min_j \lVert z_e(x) - e_j \rVert_2. The posterior is one-hot: q(z=k∣x)=1q(z = k \mid x) = 1 iff k=k∗k = k^*.
  3. The decoder reconstructs from zq(x)z_q(x).

The tokens are the integers k∗k^*: an image becomes 36 integers from a vocabulary of 64.

The loss (the slides):

L=−log⁡p(x∣zq(x))+∥sg[ze(x)]−e∥22+β∥ze(x)−sg[e]∥22.\mathcal{L} = -\log p(x \mid z_q(x)) + \lVert \mathrm{sg}[z_e(x)] - e \rVert_2^2 + \beta \lVert z_e(x) - \mathrm{sg}[e] \rVert_2^2.

  • Reconstruction: as in the VAE (we use MSE).
  • Codebook loss: moves each chosen codebook vector toward the encoder outputs assigned to it. It is k-means done by gradient descent.
  • Commitment loss (β=0.25\beta = 0.25): keeps the encoder near its chosen codes, so its outputs do not drift away from the codebook.
  • Straight-through gradient. The argmin has no gradient, so the decoder’s gradient with respect to zqz_q is copied to zez_e (the slides’ “Copy” arrow). In code: z_q = z_e + (z_q - z_e).detach(). The value is zqz_q; the gradient is zez_e‘s.
  • No KL term. The KL to a uniform prior over codes is a constant here. The prior is fitted afterwards: PixelCNN in the paper, a Transformer in VQGAN and DALL·E.

3.4 Measured: what the tokenizer keeps and loses

The standard tokenizer (demo 03: 6×6 grid, K=64K = 64, 3,000 steps). Reading the reconstructions of 1,000 test images back with parse():

round trip image → 36 tokens → imagecolorshapesizearrangementexact
standard tokenizer100%80.9%99.6%100%80.8%

Colors, sizes and arrangements survive; shapes do not always. The errors are specific: a cross comes back as a circle 109 times, a triangle as a square 77 times. Demo 03 Part C prints one such reconstruction. The arms of a small cross come back as a soft blob, the L2 average of the shapes its codes could stand for.

How the codes are used.

  • 74.0% of all cells are pure background, and a handful of codes cover them: the top 8 codes are all background codes.
  • The 33 most frequent codes cover 90% of all tokens. The course notebook found the same concentration on MNIST: 36 of 128 codes covered 90%.
  • Among the codes, 21 mostly encode background and 43 mostly encode one color or another. 34 codes have a single content in at least 90% of their cells.
  • Dead codes. A code no encoder output selects gets no gradient and stays dead. The notebook’s MNIST run used 81 of 128 codes in its first epoch. Our training re-seeded 34 dead codes from current encoder outputs, and all 64 codes end up in use.

Equal budget, three designs (1,000 steps):

designtokens per imageshapeexactMSE
standard: 6×6 grid, straight-through3659.2%59.2%0.00125
12×12 grid (finer cells)14499.7%99.7%0.00026
6×6 grid, no straight-through360.0%0.0%0.01459
  • Tokens per image is the dial between fidelity and sequence length. 144 tokens reconstruct almost perfectly, but an LM over them faces 4× longer sequences: back toward §2.1’s problem. DALL·E chose 32×32 = 1,024 tokens for 256×256 images; VQGAN usually 16×16.
  • Without the straight-through gradient the encoder never learns from the reconstruction loss, and nothing useful reaches the decoder. “Copy the gradient” is what gets through the argmin.

3.5 VQGAN: sharper tokens

Esser et al. (2021) kept the VQ-VAE’s structure but changed what the decoder is rewarded for:

  • Perceptual loss: compare deep features (LPIPS) of the image and its reconstruction, not pixels. A blur that is close in L2 is far in features.
  • Adversarial loss: a patch discriminator DD is trained to tell real patches from reconstructed ones, and the decoder (“generator” GG) is trained to fool it: LGAN=log⁡D(x)+log⁡(1−D(x^))\mathcal{L}_{\text{GAN}} = \log D(x) + \log(1 - D(\hat x)). Averaged blurs are easy to spot, so the decoder must commit to one sharp possibility.
  • Then a Transformer prior: tokenize lots of images (x→(x1,…,xT)x \to (x_1, \dots, x_T)) and train an autoregressive Transformer, L=Ex[−log⁡∏tp(xt∣x<t)]\mathcal{L} = \mathbb{E}_x[-\log \prod_t p(x_t \mid x_{<t})]. With T=16×16T = 16 \times 16 or 32×3232 \times 32 instead of 65,536 pixels, megapixel synthesis became feasible.

Our attempt at a cheap perceptual loss was a failure, and an instructive one. Matching Lecture 11’s CLIP features, or up-weighting object pixels, made fidelity worse (18–21%). A perceptual loss is only as good as the features it compares. LPIPS features are calibrated to human judgments; our 3-layer CLIP’s are not.


4. One Transformer for text and images

4.1 The recipe

Once images are tokens, “multimodal” is a vocabulary question:

  1. Add the KK image codes to the LM’s vocabulary, together with markers <img> and </img>.
  2. Train on sequences that mix them. Text-to-image is caption <img> codes </img>; captioning is the reverse order.
  3. Generate an image by sampling image tokens after <img>, restricted to image codes, then de-tokenize.

Systems built this way:

  • DALL·E (Ramesh et al., 2021):
    • A discrete VAE with 8,192 codes turns a 256×256 image into 1,024 tokens.
    • A 12B-parameter Transformer models 256 text tokens followed by the 1,024 image tokens, trained on 250M image–text pairs.
    • It drew 512 samples per caption and reranked them with CLIP.
  • Chameleon (Meta, 2024):
    • Early fusion: one tokenizer and one Transformer for interleaved text and images, in both directions.
    • Trained on ~10T tokens; generates documents that mix text and images.
    • It needed stability tricks for mixed-modal training (query–key normalization, among others).

4.2 Measured: text → image in Shape World

Demo 04 adds the 64 codes of demo 03’s tokenizer to the 46 Shape World words, 110 tokens in all. It trains Lecture 5’s Transformer (d=96d = 96, 3 layers, 3,000 steps of 32 sequences) on <s> caption <img> 36 codes </img> </s>, with one next-token loss on every token. A two-object sequence is 49 tokens long, and drawing an image takes 36 sampling steps.

For 300 new captions (sizes always stated), each generated image is parsed back and compared with the caption. The ceiling is the true image of each caption, sent through the tokenizer and back. No generator on these tokens can do better on average.

validcolorshapesizearrangementexact
ceiling: true image through the tokenizer100%100%81.3%100%100%81.3%
generated, temperature 185.7%81.0%34.0%48.7%91.4%26.0%
… one-object captions92.1%87.9%54.3%67.9%—45.7%
… two-object captions80.0%75.0%16.2%31.9%91.4%8.8%
top-k, k = 489.7%86.3%38.3%53.3%92.6%26.7%

(“Arrangement” is scored over valid two-object samples: which color is left of, or above, which.)

Four observations:

  • The pipeline works, within limits. Valid scenes 85.7% of the time, colors right 81%. Shape and size are where generation fails, as for every model in Lectures 11–12: they are fine detail in token space.
  • The arrangement is easy. Where things go is coarse in token space (which cells are non-background), so the arrangement of valid two-object samples is right 91.4% of the time, even though exact matches are rare (8.8%).
  • Top-k helps a little. Truncating to the 4 most likely codes per step raises validity (85.7% → 89.7%) by cutting the unlikely, broken codes — Lecture 9’s argument, in images.
  • The ceiling is the tokenizer’s. Even a perfect generator stops at 81.3% exact, because the tokens cannot represent every cross. This is the slides’ “Con: information loss from the image tokenizer / de-tokenizer”.

4.3 Reranking with CLIP

DALL·E sampled many images per caption and kept the ones CLIP scored highest: best-of-N with a learned verifier, an idea Lecture 23 generalizes. Demo 04 draws 8 images per caption and keeps CLIP’s favorite (CLIP from Lecture 11):

validcolorshapesizearrangementexact
first sample85.7%81.0%34.0%48.7%91.4%26.0%
CLIP’s pick of 891.3%91.3%57.7%72.3%97.8%52.7%
… one-object captions96.4%96.4%83.6%87.9%—79.3%
… two-object captions86.9%86.9%35.0%58.8%97.8%29.4%
  • Reranking doubles exact matches (26.0% → 52.7%). For a perfect reranker, one that knows which samples are exact, it would be 70.3%: the best of 8 is often right.
  • Does CLIP’s relation-blindness hurt? Lecture 11 showed CLIP cannot tell “X left of Y” from “Y left of X”. Here the arrangement rose too (91.4% → 97.8%), but only along with everything else, because CLIP picks samples whose colors and shapes are right.
  • The direct test. Look at captions whose 8 samples include the right colors in both arrangements. That happened for only 11 captions, and CLIP chose the right arrangement in 8. With 11 cases, an exact binomial test gives p = 0.23: too few to tell from a coin flip. Lecture 14 is about exactly this kind of question: how many cases one needs before a difference means something.

4.4 Pros and cons, and what comes next

  • Pros: one generative model for everything. It is autoregressive, everything is tokens, and every trick for LMs carries over: scaling, KV caches, sampling, instruction tuning, and generation in both directions.
  • Cons:
    • Information loss from the tokenizer: our ceiling was 81.3%, and real tokenizers struggle with text in images, faces and fine textures.
    • Many sequential steps per image: 1,024 for DALL·E.
    • Errors that compound token by token.

State-of-the-art image generation therefore moved to diffusion (Lecture 15). Diffusion refines all pixels (or continuous latents) in parallel over a few dozen steps, and needs no discrete bottleneck. Hybrids — discrete diffusion over tokens, autoregression with continuous tokens — are an active research area.


5. Summary

  1. Generative paradigms: autoregressive (one dimension at a time), VAE (compress + decode), GAN (fool a discriminator), diffusion (denoise). An LM is the autoregressive kind; the question is what an image token is.
  2. Pixels as tokens: correct in principle, wasteful in practice.
    • Sequences explode: 3.1M tokens for a 1024×1024 RGB image.
    • Information per token is tiny: measured exactly, 0.023 bits per pixel.
    • A pixel Transformer reached 15.29 bits per image against a 12.91-bit floor, put half its bits on one token, and drew valid pictures 35.4% of the time.
  3. VAE: ELBO = reconstruction − KL (rate), derived by importance sampling + Jensen.
    • Importance weighting tightened the bound by 8.2 nats.
    • Reparameterization cut the gradient variance by a factor of ~2 million against REINFORCE.
    • β trades rate (56.9 → 20.0 bits) for sample validity (12% → 42%).
    • Outputs are blurry, because the L2-optimal output averages possibilities.
  4. VQ-VAE: nearest-codebook quantization, codebook + commitment losses, straight-through gradient.
    • Measured: 36 tokens per image keep colors, sizes and arrangements but lose some shapes (80.8% exact).
    • 144 tokens keep almost everything (99.7%) at 4× the sequence length.
    • Without straight-through, nothing is learned.
    • VQGAN sharpens tokens with perceptual + adversarial losses.
  5. Early-fusion generation (DALL·E, Chameleon): image codes join the vocabulary; text → image is next-token prediction.
    • Measured: 26.0% exact (ceiling 81.3%); CLIP reranking of 8 samples, 52.7%.
    • The tokenizer’s information loss is the price; diffusion (Lecture 15) avoids it.

Common pitfalls

  • Comparing bits per image without an entropy floor. “15.3 bits” means nothing until you know the floor is 12.9.
  • Judging generators by eye. Measure faithfulness with a parser, a verifier, or at least a classifier, attribute by attribute.
  • Forgetting the tokenizer ceiling. Before blaming the generator, reconstruct the true images through the tokenizer.
  • Too few tokens per image. The tokenizer blurs exactly the details captions mention (here, shapes).
  • Dead codes. Monitor codebook usage; re-seed unused codes or use EMA updates.
  • Removing or mis-wiring the straight-through estimator. The encoder silently stops learning (0% fidelity).
  • A VAE with a small β, judged by its reconstructions. Its prior samples can be far worse (12% valid).
  • Drawing conclusions from a handful of cases. 8 of 11 is not evidence (p = 0.23).

Exercises

  1. Sequence arithmetic. A 512×512 RGB image is modeled (a) per channel value, (b) per pixel with a palette, (c) as VQ tokens with downsampling factor 16. How many tokens each? By what factor does attention memory shrink from (a) to (c)?

    Answer(a) 512·512·3 = 786,432; (b) 262,144; (c) (512/16)² = 32² = 1,024. Attention scores scale with $T^2$: (786,432 / 1,024)² = 768² ≈ 590,000× fewer.
  2. The ELBO gap. Show that log⁡p(x)−ELBO=DKL(q(z∣x) ∥ p(z∣x))\log p(x) - \text{ELBO} = D_{\mathrm{KL}}(q(z \mid x) \,\|\, p(z \mid x)). Why does the importance-weighted bound with KK samples tighten as KK grows?

    AnswerELBO $= \mathbb{E}_q[\log p(x, z) - \log q(z \mid x)] = \mathbb{E}_q[\log p(z \mid x) + \log p(x) - \log q(z \mid x)] = \log p(x) - D_{\mathrm{KL}}(q \,\|\, p(z \mid x))$. The IWAE bound $\mathbb{E}[\log \frac{1}{K}\sum_k w_k]$ with $w_k = p(x, z_k)/q(z_k \mid x)$ is Jensen applied to an average of $K$ weights. The average concentrates around its mean $p(x)$ as $K$ grows, so the Jensen gap shrinks (Burda et al., 2016). Measured: +6.3 nats at K = 10, +8.2 at K = 100.
  3. Reparameterization vs score function. For z∼N(μ,1)z \sim \mathcal{N}(\mu, 1) and f(z)=z2+cf(z) = z^2 + c, write both one-sample estimators of ddμE[f(z)]\frac{d}{d\mu}\mathbb{E}[f(z)]. How does each depend on the constant cc?

    AnswerReparameterized: $z = \mu + \varepsilon$, estimator $f'(z) = 2z$; it does not depend on $c$. Score function: $f(z)\,\frac{d}{d\mu}\log \mathcal{N}(z; \mu, 1) = (z^2 + c)(z - \mu)$; its mean is unaffected by $c$ (since $\mathbb{E}[z - \mu] = 0$), but its variance grows like $c^2$. That is why demo 02's estimator with $\log p(x \mid z) \approx 2{,}173$ had ~2 million times the variance, and why subtracting a baseline (an estimate of $c$) helps.
  4. Commitment loss. What goes wrong if β=0\beta = 0, or if the codebook loss is removed?

    AnswerWith β = 0 the encoder's outputs are not tied to the codebook. They can grow or drift (the decoder only sees $z_q$), so assignments flip constantly and training is unstable. Without the codebook loss the codebook vectors get no gradient at all: the straight-through path skips them. They stay at their random initialization, and the encoder must chase fixed points. The two terms split the work: codes move toward encoder outputs, encoder outputs stay near codes.
  5. Dead codes. A codebook of 512 is initialized uniformly in [−1/K,1/K][-1/K, 1/K] while encoder outputs have norm ~5. Explain why most codes may never be selected, and give two fixes.

    AnswerAll codes start near the origin; the nearest code to every encoder output is whichever few lie closest to the data's direction. Only those get codebook-loss gradients, so they move toward the data while the rest stay behind, never nearest to anything. Fixes: re-seed unused codes from random current encoder outputs (as here: 34 re-seeded); initialize the codebook by k-means on encoder outputs; update codes by exponential moving averages; or use lower-dimensional, normalized codes.
  6. The tokenizer ceiling. In demo 04, 26.0% of first samples are exact, the tokenizer ceiling is 81.3%, and CLIP’s pick of 8 reaches 52.7%. A colleague proposes a 4× larger Transformer. Another proposes a 12×12 tokenizer. What does each change, and at what cost?

    AnswerA larger Transformer can close part of the gap between 26.0% (or 52.7%) and the 81.3% ceiling, but never exceed the ceiling, and it costs compute per step. A 12×12 tokenizer raises the ceiling to ~99.7% (demo 03), but every image becomes 144 tokens instead of 36. Training and sampling cost ~4× more per image in our timing (66 vs 18 ms per step), and the generator has more tokens to get right, so its exact rate may not rise at first. Which helps more depends on whether the bottleneck is the generator (here, yes: 26% ≪ 81%) or the tokenizer.
  7. Reranking as best-of-N. If each of NN independent samples is exact with probability pp, what is the best possible reranked accuracy? With p=0.26p = 0.26 and N=8N = 8, compare with the measured perfect-reranker score of 70.3% and explain the difference.

    Answer$1 - (1 - p)^N = 1 - 0.74^8 \approx 0.91$. The measured 70.3% is lower because samples are not independent across captions. Some captions are hard for the model (two objects, small crosses), with per-caption $p$ near 0; others are easy, with $p$ near 1. Averaging $1 - (1 - p_i)^N$ over a spread of $p_i$ gives less than plugging in the average $p$. Lecture 23 returns to this coverage-vs-difficulty effect.
  • Assignment 2 (end-to-end NLP system building) is in progress. If your system generates structured outputs, the lesson of §4 applies: build an automatic checker for each attribute you care about, and measure the “ceiling” of every lossy component before tuning the model on top. These notes do not provide assignment code.

Further reading

  • A. van den Oord, O. Vinyals, K. Kavukcuoglu, “Neural Discrete Representation Learning” (VQ-VAE), NeurIPS 2017 (course reading).
  • P. Esser, R. Rombach, B. Ommer, “Taming Transformers for High-Resolution Image Synthesis” (VQGAN), CVPR 2021 (course reading).
  • D. Kingma, M. Welling, “Auto-Encoding Variational Bayes”, ICLR 2014; Y. Burda, R. Grosse, R. Salakhutdinov, “Importance Weighted Autoencoders”, ICLR 2016; I. Higgins et al., “β-VAE”, ICLR 2017; A. Alemi et al., “Fixing a Broken ELBO”, ICML 2018.
  • A. van den Oord, N. Kalchbrenner, K. Kavukcuoglu, “Pixel Recurrent Neural Networks”, ICML 2016; N. Parmar et al., “Image Transformer”, ICML 2018; M. Chen et al., “Generative Pretraining from Pixels”, ICML 2020.
  • A. Ramesh et al., “Zero-Shot Text-to-Image Generation” (DALL·E), ICML 2021; Chameleon Team, “Chameleon: Mixed-Modal Early-Fusion Foundation Models”, 2024.
  • I. Goodfellow et al., “Generative Adversarial Nets”, NeurIPS 2014; R. Zhang et al., “The Unreasonable Effectiveness of Deep Features as a Perceptual Metric” (LPIPS), CVPR 2018.
  • A. Razavi, A. van den Oord, O. Vinyals, “Generating Diverse High-Fidelity Images with VQ-VAE-2”, NeurIPS 2019.

Preview of Lecture 13 — Evaluation and benchmarks

We have now measured a lot of things: zero-shot accuracy, VQA by question type, faithfulness by attribute, bits against an entropy floor. Lecture 13 steps back to ask how evaluation is done in general:

  • loss vs task metrics;
  • what makes a good benchmark;
  • exact match, pass@k, ROUGE and their failure modes;
  • LLM-as-a-judge and human preference arenas;
  • whether a benchmark score can be trusted (contamination, robustness).

Lecture 14 then asks how sure we can be of a number like “8 of 11”.


术语表 (Glossary, English → 中文)

English中文
generative model / generative modeling paradigm生成模型 / 生成建模范式
autoregressive model / raster order自回归模型 / 光栅顺序
pixel / palette / color quantization像素 / 调色板 / 颜色量化
bits per dimension / bits per image每维比特数 / 每图比特数
entropy / information per token熵 / 每词元信息量
variational autoencoder (VAE)变分自编码器
latent variable / prior / approximate posterior隐变量 / 先验 / 近似后验
evidence lower bound (ELBO) / Jensen’s inequality证据下界 / 詹森不等式
importance sampling / importance-weighted bound (IWAE)重要性采样 / 重要性加权下界
KL divergence / rate / distortionKL 散度 / 码率 / 失真
β-VAEβ-变分自编码器
reparameterization trick / score-function estimator重参数化技巧 / 得分函数估计器
generative adversarial network (GAN) / generator / discriminator生成对抗网络 / 生成器 / 判别器
diffusion model扩散模型
vector quantization (VQ) / VQ-VAE / codebook向量量化 / 向量量化变分自编码器 / 码本
codebook loss / commitment loss码本损失 / 承诺损失
stop-gradient / straight-through estimator停止梯度 / 直通估计器
dead code / codebook usage死码 / 码本利用率
image tokenizer / de-tokenizer图像分词器 / 反分词器
reconstruction fidelity / tokenizer ceiling重建保真度 / 分词器上限
perceptual loss / adversarial loss (VQGAN)感知损失 / 对抗损失
early fusion / mixed-modal / joint vocabulary早期融合 / 混合模态 / 联合词表
text-to-image generation文生图
reranking / best-of-N重排序 / 多选一
faithfulness忠实度
← 返回课程目录