Course contents 33 / 34

33 / 34 · Autoregressive Models

Autoregressive transformers: ImageGPT, VQGAN, DALL·E and Parti

Generate images token by token with a causal transformer: why pixel sequences are too long, ImageGPT's colour palette, VQGAN's learned tokens, and text-to-image with DALL·E and Parti.

On this page 9

A 256×256256 \times 256 colour image, read value by value, is a sequence of 196,608196{,}608 numbers. A PixelCNN predicts each of them from a fixed neighbourhood. A language model of the GPT family predicts each word from all earlier words, and it works for sequences of a few thousand tokens. Could we generate images the way GPT generates text?

The obstacle is length. Self-attention compares every position with every earlier one, so a sequence 100 times longer costs 10,000 times more per layer. The way around it is to change what a token is: a palette colour of a small image in ImageGPT, then a code of a learned discrete autoencoder in VQGAN, DALL·E and Parti. Once an image is a short sequence of codes, text-to-image becomes continuing a caption.

From convolutions to attention#

A decoder-only transformer is a stack of blocks, each a self-attention layer followed by a small network applied to every position separately, both with residual connections. Self-attention is the block of SAGAN: each position takes a weighted average of the values of the positions it sees, with softmax weights from query–key scores. Here it carries a causal mask: scores of later positions are set to −∞-\infty before the softmax, so their weights are e−∞=0e^{-\infty} = 0 and the first layer’s output at position ii depends only on positions 1,…,i1, \dots, i. The per-position network and the residual connections mix nothing across positions, so by induction over the layers the same holds for every layer. If you have taken the NLP course, its attention note derives self-attention and its masks in full; it is optional background here.

The network models a token sequence s=(s1,…,sN)s = (s_1, \dots, s_N) from a vocabulary of KK tokens with the chain rule of the previous note, p(s)=∏ip(si∣s<i)p(s) = \prod_i p(s_i \mid s_{<i}). A grid of h×wh \times w tokens is read row by row, so N=hwN = hw. Training is that of the previous note: one parallel pass with teacher forcing and a cross-entropy at every position.

Two details line up with PixelCNN. The mask keeps later tokens out, and a shift keeps the target itself out: the input is (BOS,s1,…,sN−1)(\text{BOS}, s_1, \dots, s_{N-1}) with a start token BOS, and the output at input position ii, which has seen (BOS,s1,…,si−1)(\text{BOS}, s_1, \dots, s_{i-1}), predicts sis_i. Mask A of PixelCNN did both at once by hiding the centre. And there is no blind spot: every layer can attend to every earlier position.

The price is the number of pairs. 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, a cost that grows with the square of the sequence length and decides what the tokens of an image can be.

Figure

How many tokens one image takes

Sequence length for different tokenizationspixels, 256×256×3: 196,608; pixels, 32×32×3: 3,072; ImageGPT: 32×32, 512 colours: 1,024; DALL·E, Parti: 32×32 codes: 1,024; VQGAN: 16×16 codes: 256.10²10³10⁴10⁵10⁶pixels, 256×256×3196,60819.3 bnpixels, 32×32×33,0724.7 MImageGPT: 32×32, 512 colours1,024524,800DALL·E, Parti: 32×32 codes1,024524,800VQGAN: 16×16 codes25632,896pairsSequence length for different tokenizationspixels, 256×256×3: 196,608; pixels, 32×32×3: 3,072; ImageGPT: 32×32, 512 colours: 1,024; DALL·E, Parti: 32×32 codes: 1,024; VQGAN: 16×16 codes: 256.10²10³10⁴10⁵10⁶pixels, 256×256×3196,60819.3 bnpixels, 32×32×33,0724.7 MImageGPT: 32×32, 512 colours1,024524,800DALL·E, Parti: 32×32 codes1,024524,800VQGAN: 16×16 codes25632,896pairs
Sequence length (bar, logarithmic scale) and the number of pairs one causal attention layer compares, n(n + 1)/2. A 256×256 image in pixels is 196,608 values and 19.3 bn pairs per layer; a 32×32 grid of codes is 1,024 tokens and 524,800 pairs, about 37,000 times fewer.

Sampling multiplies the cost again. Producing token tt by rerunning the network on the whole prefix of length tt compares t(t+1)/2t(t+1)/2 pairs per layer. To sum over tt, factor the difference of two consecutive products:

t(t+1)(t+2)−(t−1)t(t+1)=t(t+1)[(t+2)−(t−1)]=3 t(t+1).\begin{aligned} &t(t+1)(t+2) - (t-1)t(t+1) \\ &\quad = t(t+1)\big[(t+2) - (t-1)\big] \\ &\quad = 3\,t(t+1) . \end{aligned}

Summed from t=1t = 1 to NN, the left side telescopes to N(N+1)(N+2)−0N(N+1)(N+2) - 0, so ∑t=1Nt(t+1)=N(N+1)(N+2)/3\sum_{t=1}^{N} t(t+1) = N(N+1)(N+2)/3; halving gives the total without a cache. With a cache, step tt compares one new query with tt keys:

no cache:∑t=1Nt(t+1)2=N(N+1)(N+2)6,KV cache:∑t=1Nt=N(N+1)2.\begin{aligned} \text{no cache:}\quad \sum_{t=1}^{N} \frac{t(t+1)}{2} &= \frac{N(N+1)(N+2)}{6}, \\ \text{KV cache:}\quad \sum_{t=1}^{N} t &= \frac{N(N+1)}{2} . \end{aligned}

The keys and values of earlier positions do not change when a token is appended: by the induction above, the state of position jj in every layer depends only on tokens 1,…,j1, \dots, j. So a KV cache keeps them and computes attention only for the new query. For a grid of N=1024N = 1024 tokens that is 179,481,600 pairs per layer without the cache and 524,800 with it, (N+2)/3=342(N+2)/3 = 342 times fewer. The memory price is two vectors per layer and position.

Three knobs turn a predicted distribution into a sample. Temperature TT divides the logits by TT before the softmax; for T<1T < 1 the gaps between logits grow and the mass moves to the likeliest values. Top-kk keeps the kk likeliest values, and top-pp the smallest set of likeliest values whose probabilities sum to at least pp; the kept values are renormalized. The Code section implements all three. On images they act like the truncation trick of GANs, as the VQGAN numbers below show.

Pixels as tokens: ImageGPT#

ImageGPT (Chen et al., 2020) applies GPT-2 to images with as little change as possible. A 224×224×3224 \times 224 \times 3 image is 150,528150{,}528 values; against GPT-2’s context of 1024 tokens, the attention matrix would be (150,528/1024)2=1472=21,609(150{,}528 / 1024)^2 = 147^2 = 21{,}609 times larger. So the image is first downsampled to 32×3232 \times 32 or 48×4848 \times 48, and the three channels of each pixel are replaced by the nearest of 512 colours found by k-means: a sequence of 1024 or 2304 tokens over a vocabulary of 512. The palette is the simplest tokenizer, a VQ-VAE with an identity encoder and decoder. The largest model, iGPT-L, is GPT-2 with 48 layers and width 1536, 1.4 billion parameters.

The paper’s main interest is representation. A model trained only to predict the next pixel learns features that classify CIFAR-10 with 96.3% accuracy by a linear classifier on top and 99.0% after fine-tuning. Its sequences describe only 32×3232 \times 32 or 48×4848 \times 48 images: pixel tokens do not scale to larger ones.

Learned tokens: the two-stage recipe#

The way out was already in the VQ-VAE: train a discrete autoencoder first, then an autoregressive model over its codes. With a downsampling factor ff, an H×WH \times W image becomes a grid of (H/f)×(W/f)(H/f) \times (W/f) tokens, and the transformer never sees a pixel.

Figure

Two stages: an image tokenizer and a transformer over its tokens

Tokenizer and autoregressive transformerStage 1: an encoder turns a 256×256 image into a 32×32 grid of indices into 8192 codes, and a decoder reconstructs pixels from it. Stage 2: text tokens and image tokens in raster order form one sequence, and a transformer learns to predict each token from the ones before it. At generation, image tokens are sampled one at a time and passed to the stage-1 decoder.image256×256×3encoderone of 8192 codestoken grid32×32 = 1024decodertokens → pixelsimage256×256×3promptcaptiontext tokensup to 256, BPEtransformernext tokenimage tokens1024, one by onetargetsgenerationstage 1: image tokenizerstage 2: transformer over tokensTokenizer and autoregressive transformerStage 1: an encoder turns a 256×256 image into a 32×32 grid of indices into 8192 codes, and a decoder reconstructs pixels from it. Stage 2: text tokens and image tokens in raster order form one sequence, and a transformer learns to predict each token from the ones before it. At generation, image tokens are sampled one at a time and passed to the stage-1 decoder.image256×256×3encoderone of 8192 codestoken grid32×32 = 1024decodertokens → pixelsimage256×256×3promptcaptiontext tokensup to 256, BPEtransformernext tokenimage tokens1024, one by onetargetsgenerationstage 1: image tokenizerstage 2: transformer over tokens
The numbers of DALL·E. Top, stage 1: a discrete autoencoder compresses a 256×256 image into a 32×32 grid of indices into 8192 codes. Bottom, stage 2: the caption and the image tokens form one sequence, and a causal transformer predicts each token from the earlier ones; at generation the stage-1 decoder turns the sampled tokens into pixels.

The two stages divide the work as in latent diffusion, which came later from the same group as VQGAN: the tokenizer handles textures and local detail, and the transformer handles composition. The tokenizer must therefore compress hard and still reconstruct sharp images, which a plain VQ-VAE trained with a squared error does not do.

VQGAN#

VQGAN (Esser, Rombach and Ommer, 2021) keeps the vector quantizer, the codebook and the commitment terms of the VQ-VAE and changes the reconstruction loss. The squared error is replaced by a perceptual loss, as in LPIPS, and a patch-based discriminator judges small patches of the reconstruction as real or not. The two losses have very different scales, and the adversarial one gets an adaptive weight

λ=∥∇GLLrec∥∥∇GLLGAN∥+δ,\lambda = \frac{\lVert \nabla_{G_L} \mathcal L_{\text{rec}} \rVert}{\lVert \nabla_{G_L} \mathcal L_{\text{GAN}} \rVert + \delta},

where GLG_L is the last layer of the decoder and δ=10−6\delta = 10^{-6} prevents division by zero. The gradient that reaches GLG_L is ∇Lrec+λ∇LGAN\nabla \mathcal L_{\text{rec}} + \lambda \nabla \mathcal L_{\text{GAN}}, and with this λ\lambda the second term has norm ∥∇Lrec∥⋅∥∇LGAN∥/(∥∇LGAN∥+δ)≈∥∇Lrec∥\lVert \nabla \mathcal L_{\text{rec}} \rVert \cdot \lVert \nabla \mathcal L_{\text{GAN}} \rVert / (\lVert \nabla \mathcal L_{\text{GAN}} \rVert + \delta) \approx \lVert \nabla \mathcal L_{\text{rec}} \rVert: neither loss overwhelms the other.

With f=16f = 16, a 256×256256 \times 256 image becomes a 16×1616 \times 16 grid, and the paper’s default codebook has K=1024K = 1024 entries:

QuantityValue
tokens per image16⋅16=25616 \cdot 16 = 256
bits per token, log⁡21024\log_2 102410
bits per image2,560
raw pixels, 256⋅256⋅3⋅8256 \cdot 256 \cdot 3 \cdot 81,572,864 bits

The tokens hold about 614 times fewer bits than the pixels. The second stage is a GPT-2-medium transformer with 307 million parameters, and 256 tokens was the longest sequence that fit its training on a 12 GB GPU. Conditions are prepended as tokens: a class label, or the codes of a segmentation or depth map from a second VQGAN. Images in the megapixel range are generated with a sliding attention window, each token predicted from a 16×1616 \times 16 neighbourhood of codes.

Sampling knobs on images#

The class-conditional ImageNet model of VQGAN, with 16,384 codes, shows how much sampling settings matter (Esser, Rombach and Ommer, 2021, Table 4):

SamplingFID
top-kk, k=973k = 97329.20
top-kk, k=250k = 25015.98
top-kk 973 and top-pp 0.8815.78
mixed kk, best 5% by a ResNet-101 classifier5.88
BigGAN, for comparison7.53

The rows filter by different scores. Top-kk and top-pp drop, at every step, the codes the model itself finds unlikely. The classifier row draws whole images and keeps the 5% with the highest ResNet-101 score for their class: it filters by the classifier’s confidence, not by the model’s likelihood. Every row only removes or reweights the model’s own samples, so none adds samples where the model puts no mass; such filtering trades recall for precision. The FID improves because the remaining samples are more typical of their class; the model does not cover more of the data.

Text to image: DALL·E#

DALL·E (Ramesh et al., 2021) applies the recipe at scale. Its tokenizer, a discrete VAE, turns a 256×256256 \times 256 image into a 32×3232 \times 32 grid over 8192 codes: 1024 tokens for 196,608196{,}608 values, 192 times fewer. The caption is encoded into at most 256 BPE tokens from a vocabulary of 16,384, and text and image tokens are concatenated into one sequence. A single decoder-only transformer with 12 billion parameters and sparse attention models the whole stream, trained on 250 million image–caption pairs. Generation is the continuation of a caption: feed the text tokens and sample the 1024 image tokens.

Samples are drawn in batches and reranked: a contrastive image–text model (CLIP) scores each of 512 candidates against the caption, and the best are kept. Against DF-GAN, a GAN trained on MS-COCO, human raters preferred the DALL·E sample as more realistic 90.0% of the time and as better matching the caption 93.3% of the time, although DALL·E never trained on MS-COCO captions.

Parti: an encoder–decoder at scale#

Parti (Yu et al., 2022) treats text-to-image as translation. An encoder reads the caption, and a decoder generates the 1024 image tokens of a ViT-VQGAN, a VQGAN whose encoder and decoder are vision transformers, with 8192 codes. A small super-resolution network raises the decoded 256×256256 \times 256 images to 1024×10241024 \times 1024. Quality and agreement with the text keep improving from 350 million to 20 billion parameters; the largest model reaches a zero-shot FID of 7.23 on MS-COCO.

Two tools from other families improve the samples. Classifier-free guidance works on logits as it works on scores: the model is trained with the caption sometimes dropped, and sampling combines the unconditional and conditional predictions with a weight above one. The audio note derives which distribution this samples. Reranking keeps the best of 16 samples per prompt instead of DALL·E’s 512. The paper also introduced PartiPrompts, the set of over 1,600 prompts described in the human evaluation note.

The models side by side#

ModelImage tokensVocabularyTransformerParameters
ImageGPT (iGPT-L)32×3232 \times 32 palette pixels512 coloursdecoder1.4 B
VQGAN16×1616 \times 16 codes1024 (16,384 on ImageNet)decoder307 M
DALL·E32×3232 \times 32 codes after the text8192decoder, sparse attention12 B
Parti32×3232 \times 32 codes, text in an encoder8192encoder–decoder20 B

Where it breaks#

The tokenizer caps what the transformer can produce, because every sample is a decoder output. In VQGAN with f=16f = 16, one token stands for a 16×1616 \times 16 patch of 16⋅16⋅3⋅8=614416 \cdot 16 \cdot 3 \cdot 8 = 6144 bits of pixels and carries 10 bits. Detail that the codebook cannot express, such as small text or a small face in a crowd, is lost in every sample. On ImageNet, reconstructions through a 16×1616 \times 16 grid have an FID of 7.94 to the validation images with 1024 codes and 4.98 with 16,384, against 32.01 for DALL·E’s tokenizer, a 32×3232 \times 32 grid of 8192 codes trained without perceptual and adversarial losses (Esser, Rombach and Ommer, 2021, Table 5). The VQGAN paper reads this number as an estimate of the FID the second stage can reach. It is an empirical reference: it measures the reconstructions, and a prior that places its mass differently on decoder outputs can score higher or lower.

The sampling order is the second limit. A token, once drawn, is never revised, and an early mistake in the top-left corner shapes everything after it. A diffusion model refines the whole latent over 20 to 50 steps and can correct itself; an autoregressive model needs 1024 sequential passes for a 32×3232 \times 32 grid. Both families now share the rest: a separately trained autoencoder, text conditioning through attention and classifier-free guidance. The autoregressive one adds the exact likelihood of the tokens and the architecture, training code and scaling behaviour of language models.

What you should remember#

  • A causal transformer is a PixelCNN without a blind spot; one layer costs N(N+1)/2N(N+1)/2 pairs.
  • The KV cache cuts naive sampling from N(N+1)(N+2)/6N(N+1)(N+2)/6 pairs per layer to N(N+1)/2N(N+1)/2.
  • ImageGPT shortens pixel sequences with a small image and a 512-colour palette.
  • Two stages: a discrete autoencoder makes tokens, a transformer models them.
  • VQGAN: perceptual and adversarial losses with an adaptive weight make 16×1616 \times 16 tokens sharp.
  • DALL·E puts the caption in the sequence, Parti in an encoder; top-kk, top-pp and reranking trade diversity for typical samples.

Notebook#

The course has no notebook on image transformers. Its LLM notebook, Transformers-LangChain.ipynb in the HSE-LAMBDA Deep Generative Models repository, runs pretrained transformers with Hugging Face and then a chat model with LangChain and LangGraph. Cell numbers count every cell, markdown included, from 1; its outputs are saved, and the numbers below come from them.

  • Pipelines (cells 1–17): a sentiment pipeline without a named model falls back to a default DistilBERT checkpoint; wav2vec 2.0, trained on read audiobooks, transcribes telephone requests with errors such as “HOW DO I FURN A JOINA COUT”.
  • Models and tokenizers from the Hub (cells 18–31): a multilingual BERT rates a French sentence 5 stars with probability 0.73, and the tokenizer maps the emoji of the English test sentence to [UNK].
  • Fine-tuning with Trainer (cells 32–35): in markdown only; current Transformers versions reject its evaluation_strategy argument, renamed eval_strategy.
  • A chat model with memory (cells 36–58): Qwen/Qwen2-0.5B-Instruct answers “Your name is Bob.” only when earlier turns are in its input, and a LangGraph checkpointer stores them; the saved answers repeat the whole prompt, because the pipeline returns the input with the output unless return_full_text=False.
  • State and trimming (cells 59–70): an extra language field persists between turns, and trim_messages cuts the history to a token budget, the way a chat stays inside a fixed context and bounds its KV cache.

Code#

A small decoder-only transformer in NumPy, with a causal mask, a KV cache and the sampling filters. It checks that cached and uncached logits agree, that changing a later token leaves earlier predictions unchanged, and the pair counts for N=1024N = 1024.

import numpy as np

rng = np.random.default_rng(0)
V, d, L, max_len = 16, 32, 2, 64                   # vocabulary, width, layers, positions
emb, pos = rng.normal(size=(V, d)), rng.normal(size=(max_len, d))
Wq, Wk, Wv, Wo = (rng.normal(size=(L, d, d)) / np.sqrt(d) for _ in range(4))
head = rng.normal(size=(d, V)) / np.sqrt(d)

def softmax(z):
    z = np.exp(z - z.max(-1, keepdims=True))
    return z / z.sum(-1, keepdims=True)

def forward(tokens, cache=None, start=0):
    """Logits for tokens at positions start .. start+T-1; cache holds keys and values of earlier positions."""
    x = emb[tokens] + pos[start:start + len(tokens)]
    for l in range(L):
        q, k, v = x @ Wq[l], x @ Wk[l], x @ Wv[l]
        if cache is not None:
            k = np.concatenate([cache[l]['k'], k]) if cache[l] else k
            v = np.concatenate([cache[l]['v'], v]) if cache[l] else v
            cache[l] = {'k': k, 'v': v}
        scores = q @ k.T / np.sqrt(d)               # [T, S]: new queries against all visible keys
        qpos = start + np.arange(len(tokens))[:, None]
        scores[np.arange(k.shape[0])[None, :] > qpos] = -np.inf   # causal mask: no later keys
        x = x + softmax(scores) @ v @ Wo[l]
    return x @ head

def filter_logits(z, temperature=1.0, top_k=None, top_p=None):
    z = z / temperature
    if top_k is not None:                           # keep the k largest logits
        z = np.where(z < np.sort(z)[-top_k], -np.inf, z)
    if top_p is not None:                           # smallest set whose probability reaches top_p
        order = np.argsort(-z)
        p = softmax(z)[order]
        drop = np.cumsum(p) - p >= top_p            # mass before this token already reaches top_p
        z[order[drop]] = -np.inf
    return z

# generate 20 tokens with the cache, one new token per pass
cache = [{} for _ in range(L)]
seq = [1, 2, 3]
logits = forward(np.array(seq), cache)
for _ in range(20):
    probs = softmax(filter_logits(logits[-1], temperature=0.7, top_k=5))
    seq.append(int(rng.choice(V, p=probs)))
    logits = forward(np.array(seq[-1:]), cache, start=len(seq) - 1)

full = forward(np.array(seq[:-1]))                 # every position recomputed from scratch
c = [{} for _ in range(L)]                         # the same positions, one token per pass
step = np.concatenate([forward(np.array([t]), c, start=i) for i, t in enumerate(seq[:-1])])
print('max |cached - full| =', float(np.abs(full - step).max()))
a = np.array(seq[:10]); b = a.copy(); b[7] = (b[7] + 1) % V
print('earlier logits unchanged:', np.allclose(forward(a)[:7], forward(b)[:7]))

N = 1024                                           # pairs compared per layer while sampling N tokens
print(N * (N + 1) * (N + 2) // 6, N * (N + 1) // 2, (N + 2) / 3)

z = np.array([2.0, 1.5, 1.0, 0.0, -1.0])
for kw in [{}, {'temperature': 0.7}, {'top_k': 3}, {'top_p': 0.7}]:
    print(kw, softmax(filter_logits(z.copy(), **kw)).round(3))
max |cached - full| = 7.105427357601002e-15
earlier logits unchanged: True
179481600 524800 342.0
{} [0.463 0.281 0.17  0.063 0.023]
{'temperature': 0.7} [0.555 0.272 0.133 0.032 0.008]
{'top_k': 3} [0.506 0.307 0.186 0.    0.   ]
{'top_p': 0.7} [0.622 0.378 0.    0.    0.   ]

The largest difference is the rounding error of 64-bit arithmetic. Top-pp with p=0.7p = 0.7 keeps two tokens, because the first alone has 0.463 of the mass and the first two have 0.744.

Next#

Images are not the only data these tools model. Sound is a one-dimensional signal with tens of thousands of samples per second, and the last note of the course generates it in two ways: a normalizing flow turns text into speech, and an autoregressive transformer like the ones above generates music over the tokens of a neural audio codec.

References#