Skip to content
BIASED

Autoregressive transformers

A causal transformer as a PixelCNN without a blind spot, image tokens from a palette and from VQGAN, temperature, top-k and top-p, and text-to-image with DALL·E and Parti.

Images as text

The topic Autoregressive models left us an exact likelihood and a slow sampler. The chain rule turns an image into a product of one-value conditionals, and a PixelCNN learns them all in one parallel pass. But its masked convolutions see only a local window of the past, with a blind spot inside it, and sampling takes one network pass per value.

Language models solve the same problem for text. A GPT predicts each token from all earlier tokens and is trained on billions of them. Can images be generated the way text is?

The obstacle is length. A 256×256256 \times 256 colour image read one value at a time is a sequence of

256⋅256⋅3=196,608256 \cdot 256 \cdot 3 = 196{,}608

values, while GPT-2 reads at most 1,0241{,}024 tokens. Self-attention compares every position with every earlier one, so its cost per layer grows with the square of the length (the topic Latent diffusion hit the same wall in pixel space).

So we change what a token is. There are two answers, and this topic follows both:

  • a colour from a small palette, one per pixel of a small image (ImageGPT);
  • a code of a learned discrete autoencoder — the VQ-VAE of β-VAE and VQ-VAE, made sharper (VQGAN, DALL·E, Parti).

Once an image is a short sequence of codes, text-to-image generation becomes continuing a caption.

A PixelCNN without a blind spot

A decoder-only transformer is a stack of blocks. Each block has a self-attention layer and then a small network applied to every position separately, with residual connections around both. Self-attention is the mechanism from Latent diffusion, except that queries, keys and values all come from the sequence itself.

The causal mask sets the attention scores of later positions to −∞-\infty before the softmax, so their weights are exactly zero. The output at position ii then depends only on positions 1,…,i1, \dots, i. The per-position networks mix nothing across positions, so this holds in every layer.

A sequence s=(s1,…,sN)s = (s_1, \dots, s_N) of tokens from a vocabulary of KK codes gets the chain-rule model

pθ(s)=∏i=1Npθ(si∣s<i),p_\theta(s) = \prod_{i=1}^{N} p_\theta(s_i \mid s_{<i}),

where each conditional is a softmax over KK logits, like PixelCNN's 256-way softmax. An h×wh \times w grid of codes is read row by row, so N=hwN = hw.

Training is one parallel pass with the true tokens as input (teacher forcing) and a cross-entropy loss at every position; the sum is exactly −log⁡pθ(s)-\log p_\theta(s). One detail mirrors mask A of PixelCNN. The input is shifted by one: (BOS,s1,…,sN−1)(\text{BOS}, s_1, \dots, s_{N-1}), with a start token BOS. The output at position ii has seen BOS and s1,…,si−1s_1, \dots, s_{i-1}, and predicts sis_i. The mask hides the future; the shift hides the target.

There is no blind spot: every layer can attend to every earlier position. The price is cost. Position ii attends to ii positions, so one layer compares

∑i=1Ni=N(N+1)2\sum_{i=1}^{N} i = \frac{N(N+1)}{2}

pairs. This quadratic count decides how many tokens an image can afford.

Sampling and the KV cache

Sampling is as sequential as in PixelCNN. Draw s1s_1 from pθ(s1∣BOS)p_\theta(s_1 \mid \text{BOS}), append it, draw s2s_2, and so on: NN network passes for NN tokens.

A naive sampler reruns the whole network on the prefix at every step. Generating token tt then costs t(t+1)/2t(t+1)/2 pairs per layer, and the whole sample costs

∑t=1Nt(t+1)2=N(N+1)(N+2)6\sum_{t=1}^{N} \frac{t(t+1)}{2} = \frac{N(N+1)(N+2)}{6}

pairs per layer. The sum follows from the telescoping identity t(t+1)(t+2)−(t−1)t(t+1)=3t(t+1)t(t+1)(t+2) - (t-1)t(t+1) = 3t(t+1).

Most of that work is repeated. Because of the causal mask, the keys and values of earlier positions never see later tokens, so appending a token does not change them. A KV cache stores them, one key and one value vector per layer and position. Each step then computes attention only for the new query against the tt stored keys, and the whole sample costs

∑t=1Nt=N(N+1)2\sum_{t=1}^{N} t = \frac{N(N+1)}{2}

pairs per layer — the same as one training pass.

The cache cuts the work, not the number of steps. A 32×3232 \times 32 grid of codes still needs 1,0241{,}024 passes, one after another.

Pixels as tokens: ImageGPT

ImageGPT (Chen et al., 2020) applies GPT-2 to images with as little change as possible. The context is the first problem. A 224×224×3224 \times 224 \times 3 image has 150,528150{,}528 values, and attending over all of them would cost (150,528/1,024)2=1472=21,609(150{,}528 / 1{,}024)^2 = 147^2 = 21{,}609 times more than GPT-2's context.

So ImageGPT shrinks the image twice:

  • it downsamples it to 32×3232 \times 32 (or 48×4848 \times 48);
  • it replaces the three channel values of each pixel by the nearest of 512 colours, a palette found by k-means on training pixels.

A 32×3232 \times 32 image becomes 1,0241{,}024 tokens over a vocabulary of 512. In the language of β-VAE and VQ-VAE, the palette is the simplest possible tokenizer: a codebook of 512 colours, with the nearest-colour lookup as the quantizer, and no encoder or decoder around it. The largest model, iGPT-L, is a GPT-2 with 48 layers and about 1.4 billion parameters.

The paper's main result is about representations, not samples. A network trained only to predict the next pixel learns features that reach 96.3% accuracy on CIFAR-10 with a linear classifier on top, and 99.0% after fine-tuning.

As a generator it stays small. The palette turns three values into one token, but it never shrinks the grid: every pixel is still a token. Larger images need a tokenizer that also shrinks the grid.

Learned tokens: VQGAN

That tokenizer is the two-stage recipe of the VQ-VAE. Train a discrete autoencoder, freeze it, encode every image into a grid of codes and fit an autoregressive model to the grids. With a downsampling factor ff, an H×WH \times W image becomes an (H/f)×(W/f)(H/f) \times (W/f) grid, and the transformer never sees a pixel. The tokenizer handles texture and local detail; the transformer handles composition. It is the same division of labour as in Latent diffusion.

The catch: a plain VQ-VAE trained with squared error gets blurry under heavy compression. VQGAN (Esser, Rombach and Ommer, 2021) keeps the quantizer, the codebook and the commitment terms and replaces the squared error by two losses: a perceptual loss on features of a pretrained network, and a patch discriminator that calls small patches of the reconstruction real or fake. If they sound familiar, the autoencoder of latent diffusion inherited them from VQGAN.

The two losses live on very different scales, so the adversarial one gets an adaptive weight. With WLW_L the decoder's last layer,

λ=∥∇WLLrec∥∥∇WLLGAN∥+δ,δ=10−6,\lambda = \frac{\big\lVert \nabla_{W_L} \mathcal L_{\text{rec}} \big\rVert}{\big\lVert \nabla_{W_L} \mathcal L_{\text{GAN}} \big\rVert + \delta}, \qquad \delta = 10^{-6},

and the decoder minimizes Lrec+λ LGAN\mathcal L_{\text{rec}} + \lambda\, \mathcal L_{\text{GAN}}, where Lrec\mathcal L_{\text{rec}} includes the perceptual term.

The token budget. With f=16f = 16 and K=1,024K = 1{,}024 codes, a 256×256256 \times 256 image becomes a 16×1616 \times 16 grid: 256 tokens of log⁡21,024=10\log_2 1{,}024 = 10 bits each, 2,5602{,}560 bits in all. The raw pixels take 256⋅256⋅3⋅8=1,572,864256 \cdot 256 \cdot 3 \cdot 8 = 1{,}572{,}864 bits.

The second stage is a GPT-2-sized transformer over the 256 tokens. A condition simply goes in front as extra tokens: a class label, or the codes of a segmentation map from a second VQGAN. For megapixel images the transformer samples with a sliding window, each token predicted from a 16×1616 \times 16 neighbourhood of codes.

Temperature, top-k and top-p

At each step the transformer outputs logits ℓ1,…,ℓK\ell_1, \dots, \ell_K, one per code. Sampling straight from their softmax reproduces the model's distribution, tail and all. In practice the distribution is reshaped first, in one of three ways.

Temperature τ\tau divides the logits before the softmax:

pk(τ)=exp⁡(ℓk/τ)∑j=1Kexp⁡(ℓj/τ).p_k^{(\tau)} = \frac{\exp(\ell_k / \tau)}{\sum_{j=1}^{K} \exp(\ell_j / \tau)} .

At τ=1\tau = 1 this is the model itself; τ<1\tau < 1 sharpens it toward the likeliest code, and τ>1\tau > 1 flattens it. (τ\tau is not the step count TT of diffusion.)

Top-k keeps the kk likeliest codes. Top-p, or nucleus sampling, keeps the smallest set of likeliest codes whose probabilities sum to at least pp. Both renormalize what is left.

A worked example. Take the logits (2.0, 1.5, 1.0, 0.0, −1.0)(2.0,\ 1.5,\ 1.0,\ 0.0,\ -1.0).

setting probabilities
none 0.463, 0.281, 0.170, 0.063, 0.023
τ=0.7\tau = 0.7 0.555, 0.272, 0.133, 0.032, 0.008
top-k, k=3k = 3 0.506, 0.307, 0.186, 0, 0
top-p, p=0.7p = 0.7 0.622, 0.378, 0, 0, 0

Top-p keeps two codes here: the first alone holds 0.463<0.70.463 < 0.7, the first two hold 0.7440.744.

All three cut the low-probability tail. A grid of 1,0241{,}024 codes gives a rare bad code 1,0241{,}024 chances to appear, so cutting the tail makes samples cleaner and more typical, and less diverse. It is the same trade as the guidance weight ww in Latent diffusion: fidelity for diversity.

Text to image: DALL·E and Parti

DALL·E (Ramesh et al., 2021) is the recipe at scale. A discrete VAE turns a 256×256256 \times 256 image into a 32×3232 \times 32 grid over 8,1928{,}192 codes. The caption becomes at most 256 text tokens. Text tokens and image tokens are joined into one stream, and one decoder-only transformer with 12 billion parameters, using sparse attention, learns that stream on 250 million image–caption pairs.

Generation is continuing the caption: feed the text tokens, sample the 1,0241{,}024 image tokens one by one, decode the grid. Then reranking: DALL·E draws 512 candidates, and CLIP, a model trained to score how well an image matches a caption, keeps the best. On MS-COCO captions, which DALL·E was never trained on, people preferred its samples over those of DF-GAN, a GAN trained on MS-COCO, 90.0% of the time for realism and 93.3% for matching the caption.

Parti (Yu et al., 2022) treats text-to-image as translation. An encoder reads the caption; a decoder generates 1,0241{,}024 tokens of a ViT-VQGAN, a VQGAN whose encoder and decoder are vision transformers, with 8,1928{,}192 codes. A small super-resolution network takes the decoded 256×256256 \times 256 image to 1024×10241024 \times 1024. From 350 million to 20 billion parameters, image quality and text alignment keep improving.

Parti borrows classifier-free guidance from Latent diffusion. It works on logits just as it works on noise predictions. The model is trained with the caption yy sometimes replaced by an empty one ∅\varnothing, and at every step it combines

ℓ~=(1+w) ℓθ(s<i,y)−w ℓθ(s<i,∅),\tilde\ell = (1 + w)\, \ell_\theta(s_{<i}, y) - w\, \ell_\theta(s_{<i}, \varnothing),

before sampling sis_i from the softmax of ℓ~\tilde\ell. It also reranks, keeping the best of 16 samples per prompt.

Where it breaks and what we have

Two weak spots are built into the recipe.

The tokenizer caps quality. Every sample is a decoder output. In VQGAN with f=16f = 16, one token stands for a 16×1616 \times 16 patch: 6,1446{,}144 bits of pixels described by 10 bits of code. Detail the codebook cannot express — small text, faces in a crowd — is missing from every sample, however good the transformer.

A drawn token is never revised. An early mistake in the top-left corner shapes everything after it. A diffusion model refines the whole latent over 20–50 steps and can correct itself; an autoregressive model takes 1,0241{,}024 passes for a 32×3232 \times 32 grid and cannot.

Otherwise the families have converged: a separately trained autoencoder, text through attention, classifier-free guidance. Autoregressive transformers add an exact likelihood over tokens and all the tooling of language models. (The extension Audio generation: speech and music takes the same recipe to sound.)

So the course now has every family: VAEs, GANs, flows, energy-based models, diffusion and autoregressive models. Which one is good? Likelihood cannot settle it. A GAN has none. A token likelihood depends on the tokenizer, so two codebooks give numbers that do not compare. And sampling knobs change the samples without touching the model: on class-conditional ImageNet, Esser et al. cut a standard quality score, FID (two topics from now; lower is better), from 29.2 to 16.0 just by lowering top-k from 973 to 250. The samples became more typical, not the model better.

We need a score computed from samples alone. The next topic, Inception Score, asks a pretrained image classifier to judge them.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.