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 colour image, read value by value, is a sequence of 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 before the softmax, so their weights are and the first layer’s output at position depends only on positions . 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 from a vocabulary of tokens with the chain rule of the previous note, . A grid of tokens is read row by row, so . 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 with a start token BOS, and the output at input position , which has seen , predicts . 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 attends to positions, so one layer compares
pairs, a cost that grows with the square of the sequence length and decides what the tokens of an image can be.
How many tokens one image takes
Sampling multiplies the cost again. Producing token by rerunning the network on the whole prefix of length compares pairs per layer. To sum over , factor the difference of two consecutive products:
Summed from to , the left side telescopes to , so ; halving gives the total without a cache. With a cache, step compares one new query with keys:
The keys and values of earlier positions do not change when a token is appended: by the induction above, the state of position in every layer depends only on tokens . So a KV cache keeps them and computes attention only for the new query. For a grid of tokens that is 179,481,600 pairs per layer without the cache and 524,800 with it, times fewer. The memory price is two vectors per layer and position.
Three knobs turn a predicted distribution into a sample. Temperature divides the logits by before the softmax; for the gaps between logits grow and the mass moves to the likeliest values. Top- keeps the likeliest values, and top- the smallest set of likeliest values whose probabilities sum to at least ; 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 image is values; against GPT-2’s context of 1024 tokens, the attention matrix would be times larger. So the image is first downsampled to or , 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 or 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 , an image becomes a grid of tokens, and the transformer never sees a pixel.
Two stages: an image tokenizer and a transformer over its tokens
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
where is the last layer of the decoder and prevents division by zero. The gradient that reaches is , and with this the second term has norm : neither loss overwhelms the other.
With , a image becomes a grid, and the paper’s default codebook has entries:
| Quantity | Value |
|---|---|
| tokens per image | |
| bits per token, | 10 |
| bits per image | 2,560 |
| raw pixels, | 1,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 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):
| Sampling | FID |
|---|---|
| top-, | 29.20 |
| top-, | 15.98 |
| top- 973 and top- 0.88 | 15.78 |
| mixed , best 5% by a ResNet-101 classifier | 5.88 |
| BigGAN, for comparison | 7.53 |
The rows filter by different scores. Top- and top- 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 image into a grid over 8192 codes: 1024 tokens for 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 images to . 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#
| Model | Image tokens | Vocabulary | Transformer | Parameters |
|---|---|---|---|---|
| ImageGPT (iGPT-L) | palette pixels | 512 colours | decoder | 1.4 B |
| VQGAN | codes | 1024 (16,384 on ImageNet) | decoder | 307 M |
| DALL·E | codes after the text | 8192 | decoder, sparse attention | 12 B |
| Parti | codes, text in an encoder | 8192 | encoder–decoder | 20 B |
Where it breaks#
The tokenizer caps what the transformer can produce, because every sample is a decoder output. In VQGAN with , one token stands for a patch of 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 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 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 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 pairs.
- The KV cache cuts naive sampling from pairs per layer to .
- 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 tokens sharp.
- DALL·E puts the caption in the sequence, Parti in an encoder; top-, top- 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 itsevaluation_strategyargument, renamedeval_strategy. - A chat model with memory (cells 36–58):
Qwen/Qwen2-0.5B-Instructanswers “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 unlessreturn_full_text=False. - State and trimming (cells 59–70): an extra
languagefield persists between turns, andtrim_messagescuts 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 .
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- with 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#
- M. Chen, A. Radford, R. Child, J. Wu, H. Jun, D. Luan, I. Sutskever. Generative Pretraining from Pixels. ICML, 2020. Section 3.2 (context reduction, the 512-colour palette), Section 3.3 (iGPT-L).
- P. Esser, R. Rombach, B. Ommer. Taming Transformers for High-Resolution Image Synthesis. CVPR, 2021. Section 3 (VQGAN, the adaptive weight, the sliding window); in the arXiv version 3, Table 4 (sampling on ImageNet) and Table 5 (reconstruction FID).
- A. Ramesh, M. Pavlov, G. Goh, S. Gray, C. Voss, A. Radford, M. Chen, I. Sutskever. Zero-Shot Text-to-Image Generation. ICML, 2021.
- J. Yu et al. Scaling Autoregressive Models for Content-Rich Text-to-Image Generation. TMLR, 2022. Section 2.4 (classifier-free guidance and reranking).
- J. Yu, X. Li, J. Y. Koh, H. Zhang, R. Pang, J. Qin, A. Ku, Y. Xu, J. Baldridge, Y. Wu. Vector-quantized Image Modeling with Improved VQGAN. ICLR, 2022. ViT-VQGAN.
- A. van den Oord, O. Vinyals, K. Kavukcuoglu. Neural Discrete Representation Learning. NeurIPS, 2017. VQ-VAE.
- R. Isachenko. Deep Generative Models, MIPT and Yandex School of Data Analysis, 2025, lectures 1–2 (ImageGPT as an autoregressive model over raster-ordered pixels).