Taming Transformers for High-Resolution Image Synthesis
- Publication
- CVPR 2021Conference
- First submitted to arXiv
- arXiv:2012.09841
Cite this paper · BibTeX
The citation identifies the linked source version. It cites the original paper and its authors.
@misc{imagegenerationvqgan2020,
title = {{Taming Transformers for High-Resolution Image Synthesis}},
author = {Patrick Esser and Robin Rombach and Björn Ommer},
year = {2020},
eprint = {2012.09841},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/2012.09841}
}

This 1280×460 landscape was painted one cell at a time by a transformer.
At the end of 2020, that was not an everyday thing. Transformer attention computes the relationship between every pair of elements in a sequence, so its cost grows with the square of the sequence length; and an image's sequence length grows with the square of its resolution. In the paper's survey of how transformers had been used for image generation up to then, good results mostly stopped at 64×64 or below. OpenAI's Image GPT, half a year earlier, ran autoregression directly on pixels, and even it had to squeeze the colors down to 512 and the resolution down to something tiny.
The paper comes from Patrick Esser, Robin Rombach and Björn Ommer at Heidelberg University. In case the team doesn't ring a bell, a year later they made Latent Diffusion, the predecessor of Stable Diffusion, and the autoencoder in that paper was trained with this paper's recipe.
Their approach has two stages. First a convolutional network compresses the image into a small grid of integers, then a transformer learns that grid. The skeleton of the first stage is VQ-VAE.
Defining the problem
First, how long is the sequence?
Flatten a RGB image into a sequence of pixels, and its length is . The attention matrix is the square of that length, about entries, computed once in every layer.
Section 2 of the paper lists several ways of saving compute. Some restrict each position to its neighborhood, at the cost of expressiveness; some use sparse attention, which brings down to , though the authors consider that still too expensive beyond 64 pixels.
The other road is two stages. First compress the image into a grid of integers with VQ-VAE, then learn a distribution over the grids. VQ-VAE uses PixelCNN as the second stage, and VQ-VAE-2 adds a hierarchy; Image GPT also tried encoding with a VQ-VAE first, but deliberately used a very shallow VQ-VAE with a small receptive field, so each code stayed very close to a pixel. The authors' view is that the convolutional PixelCNN is bad at capturing long-range relationships, while a shallow first stage doesn't compress the image enough.
Squeeze harder, get blurrier
Why not compress harder in the first stage?
On ImageNet, VQ-VAE compresses to , each code covering pixels, and the reconstructions are already a little blurrier than the originals. The loss is pixel MSE, and for a patch of uncertain texture, the model's safest answer is the average, which is to say a blur. To have the transformer handle only tokens for a image, each code has to cover pixels, and training that with MSE would come out blurrier still.
So this paper has two problems to solve. The first stage has to let each code stand for a large chunk of the image and still draw clear textures when decoding; and the second-stage transformer can only afford to learn 256 tokens, so how does it draw images much larger than 256×256?
Solving the problem
The big picture

The lower half is the first stage, VQGAN, and the upper half is the second stage, the transformer. Let's follow a image through it with the paper's most common setting.
- Encode. The convolutional encoder downsamples times, halving height and width each time, for a downsampling factor of . The output is a feature map with dimensions per position.
- Quantize. Each position finds the nearest code in the codebook , whose size is . The result is a grid of integers, which can also be seen as an integer sequence of length 256.
- Decode and discriminate. The decoder draws the looked-up back into a image; the discriminator looks at each small patch of the reconstruction and judges whether it looks real.
- Learn the distribution. The second stage encodes every training image into an integer sequence and has the transformer learn . To generate, the transformer emits 256 integers one by one, and the decoder draws them into an image.
How much information is the whole image compressed into? , so each token is 10 bits, and 256 tokens make 2,560 bits. The original image is 8-bit values, 1,572,864 bits in total, so that is a compression of about 614 times; VQ-VAE's setting on ImageNet was 42.6 times.
Drawing a clear image back out of codes this small comes down to the first stage's training objective.
Quantization stays the same
Quantization is the same as in VQ-VAE (Eq. (2)):
Gradients are copied from the decoder back to the encoder with the straight-through estimator, and the codebook term and the commitment loss carry over unchanged. Eq. (4) in v3 reads:
This formula comes with a small backstory. In v2, the commitment loss had a in front of it, and the hyperparameter table said . Appendix A of v3 admits that because of a bug in the implementation, was never used and every model was actually trained with 1.0, so the was taken out of the formula.
Open the official code, and VectorQuantizer2 still carries beta=0.25, except that it multiplies the codebook term, while the commitment loss has weight 1; the code comment reads "due to a bug the beta term was applied to the wrong term. for backwards compatibility we use the buggy version by default." So the revised Eq. (4) and the code still differ by that 0.25 in front of the codebook term (the paper was changed to match the code, but the code never changed to match the revised paper). If you continue training from the official weights, the default legacy=True keeps you on the same setting.
Replacing MSE
VQGAN's main change is to the reconstruction loss. It swaps pixel L2 for a perceptual loss (LPIPS) and adds a patch discriminator, using adversarial training to force the decoder to draw clear textures.
The perceptual loss compares the features of images after they pass through a pretrained classification network, rather than their pixel values. If two images share the same texture but the details sit slightly apart, pixel MSE punishes them heavily while the perceptual loss goes easy; conversely, a blurred image differs a lot from the original in feature space.
The patch discriminator comes from pix2pix. An ordinary discriminator gives the whole image a single real-or-fake score; a patch discriminator outputs a grid in which each cell judges only one small patch of the original image, and the grid marked r and f at the upper right of Figure 2 is exactly that. It doesn't care whether the composition of the whole image is right, only whether each patch's texture looks real, which covers precisely where MSE is weakest.
The adversarial loss is Eq. (5), and the whole first stage is a min-max problem (Eq. (6)):
The discriminator tries to tell real images from reconstructions, while the encoder, the decoder and the codebook try to make the reconstructions fool it. The official code actually uses the hinge form: the discriminator's loss is , and the generator side's loss is the mean of . The reconstruction term is L1 plus LPIPS.
The adaptive weight λ
The reconstruction loss and the adversarial loss live on completely different scales, and those scales shift during training, so is hard to pick by hand. The authors have it compute itself at every step (Eq. (7)):
is the weights of the decoder's last layer, the gradient with respect to them, and guards against division by zero.
Try it with two numbers. Suppose that at some step, the gradient norm of the reconstruction loss with respect to the last layer is 0.02, and that of the adversarial loss is 0.5. Then , and the weighted adversarial gradient norm also becomes 0.02, the same size as the reconstruction gradient. A while later the discriminator weakens and the adversarial gradient drops to 0.01, so rises to 2, and the weighted value is still 0.02. However far apart the two start out, at the decoder's last layer the two losses always push the weights with equal force.
The official code writes it like this, where last_layer is the weights of the decoder's last convolutional layer:
def calculate_adaptive_weight(self, nll_loss, g_loss, last_layer):
nll_grads = torch.autograd.grad(nll_loss, last_layer, retain_graph=True)[0]
g_grads = torch.autograd.grad(g_loss, last_layer, retain_graph=True)[0]
d_weight = torch.norm(nll_grads) / (torch.norm(g_grads) + 1e-4)
d_weight = torch.clamp(d_weight, 0.0, 1e4).detach()
return d_weight * self.discriminator_weight
This code has three things the paper doesn't. The constant in the denominator is rather than ; is clamped between 0 and ; and the result is multiplied by a discriminator_weight, which is 0.8 in both the ImageNet and the face configs, so the adversarial gradient ends up at only 80% of the reconstruction gradient. detach() makes just a number, with no gradient flowing through it.
Appendix B adds that early in training, should be kept for a while, at least one epoch, and that the longer this warm-up, the better the reconstructions usually are. The official configs control this with disc_start, step 250,001 for ImageNet and step 30,001 for faces; before that, the discriminator itself doesn't train either.
Encoder and decoder
The network architecture follows DDPM's convolutional backbone, minus the U-Net skip connections. The encoder is rounds of "residual block + downsampling," followed at the lowest resolution by a residual block, a non-local attention layer and another residual block, and finally GroupNorm, Swish and a convolution that output -dimensional features; the decoder mirrors it. The attention layer at the lowest resolution lets every position see the whole image during encoding; together with downsampling by , each code covers a large area, and the authors call a codebook like this context-rich.
Stage two: the transformer
Once the first stage is trained, every image becomes a string of integers. The transformer has the same architecture as GPT-2 and predicts the next integer one at a time in row-major scan order (from top left to bottom right); the loss is the negative log-likelihood of the sequence (Eq. (9)):
Why is the sequence fixed at ? The paper says it plainly: this is the maximum length at which GPT-2 medium (307 million parameters) can be trained on a single 12GB GPU.
The scan order wasn't picked at random. Appendix F compares six orders on ImageNet with fixed initialization and compute, and the final NLLs are row-major 4.767, Z-curve 4.810, alternating (snake) 4.812, spiral out 4.889, spiral in 4.901, and coarse-to-fine subsampling 5.015. The most common one, row-major, actually comes out best; the two worst orders, subsampling and spiral in, generate images that look more like textures, with hardly any recognizable objects.
Conditional generation uses the same transformer (Eq. (10)). When the condition is a class, a class token goes at the front of the sequence; when the condition is something spatial, such as a semantic segmentation map or a depth map, a separate VQGAN is trained to encode the condition image into an integer sequence as well, which is placed in front of , and the loss is computed only on the part.
Sliding window: drawing images larger than 256×256
The transformer has only ever learned sequences of length 256. To draw a large image, the authors use a sliding attention window.
During training, crops are taken from the image ( when ) and encoded into tokens. At sampling time, the token grid can be much bigger than . To decide the token at each position, a window is framed around it, the tokens already drawn inside the window serve as context, and the transformer predicts only this one cell. In the official sampling code, the current cell's position in the window is fixed at , moving toward the edge only near the borders.
For example, with , a image is tokens, which takes 4,160 transformer runs, each with only a 256-cell window as input. Whatever lies outside the window, the model can't see at all.
The approach only works under certain conditions. The data's statistics have to be roughly independent of position, as with landscapes and textures; or there has to be a spatial condition hinting at what each position should contain, such as a semantic segmentation map. For aligned data like faces, position itself carries meaning, and the authors suggest adding the coordinates as a condition too. The landscape at the top, and images in the appendix as large as , were all drawn this way.
Discussion
Is the transformer actually better?
Section 4.1 first checks one thing, whether on the same VQGAN codes a transformer really beats a convolutional autoregressive model. The baseline is PixelSNAIL, the strongest member of the PixelCNN family at the time and the second stage used by VQ-VAE-2. Parameter counts are matched on both sides, and because PixelSNAIL trains about twice as fast, the authors report results both for "the same number of steps" and for "the same training time."
| Data (params) | Transformer (steps) | Transformer (time) | PixelSNAIL |
|---|---|---|---|
| RIN (85M) | 4.78 | 4.84 | 4.96 |
| LSUN-CT (310M) | 4.63 | 4.69 | 4.89 |
| IN (310M) | 4.78 | 4.83 | 4.96 |
| D-RIN (180M) | 4.70 | 4.78 | 4.88 |
| S-FLCKR (310M) | 4.49 | 4.57 | 4.64 |
Compiled from Table 1 of the paper. The numbers are negative log-likelihoods, lower is better; D-RIN is conditioned on depth maps and S-FLCKR on semantic segmentation maps.
In all five settings the transformer comes out lower, even when it only gets the same amount of training time.
How much context a code should carry

This is the most direct figure in the whole paper. The transformer's sequence length is fixed at , and only the first stage's downsampling factor changes. For , the authors follow Image GPT and cluster RGB values into 512 colors with k-means, so each token is one pixel.
With the sequence length fixed, the smaller is, the smaller the patch of the original image the transformer's window can see. At the window is just pixels, not even big enough for one eye, and what comes out is broken patches of color; gets the colors of a face, with crooked features; can draw a complete face, but you get things like a beard on only one half, or left and right sides seen from different angles; only draws a whole, natural face.
The bottom row is speed. At , generating one image takes 7,258 seconds (GTX Titan X), and is 280 times faster, which works out to about 26 seconds. On CIFAR-10, the authors also compared training directly on pixels with training on VQGAN codes; with the same compute, the latter's FID is 18.63% better and sampling is 14.08 times faster.
So can just keep growing? Appendix C measures, on faces, the reconstruction error (LPIPS, lower is better) and the transformer's negative log-likelihood for to 64:
| Rec. error | NLL | |
|---|---|---|
| 2 | 0.11 | |
| 4 | 0.20 | |
| 8 | 0.23 | |
| 16 | 0.38 | |
| 32 | 0.63 | |
| 64 | 0.66 |
Compiled from Figure 11 of the paper.
The larger is, the fewer tokens there are and the easier it is for the transformer to learn the sequence, so the NLL keeps falling; the reconstruction error keeps climbing, with a big jump at . Reconstruction quality caps generation quality; however well the transformer learns, it's no use if the decoder can't draw it. On faces, reconstruction gets noticeably worse once goes beyond 16; landscapes are more forgiving, and reconstructions at still look reasonable, which the authors guess is because people are far more sensitive to facial features than to textures.
Reconstruction: against DALL·E's dVAE

The second column is DALL·E's dVAE, with the same and the same 8,192 codes as the VQGAN in the third column. The only difference is the training objective: DALL·E has no perceptual loss and no discriminator. The squirrel's fur and the rock beneath it turn to mush in the dVAE, while VQGAN's look almost identical to the original. The two right-hand columns raise to 16, making the sequence four times shorter, and the textures stay sharp; the price is that some details no longer line up with the original, such as the squirrel's paw, but they still look real.
The paper quantifies this with reconstruction FID (rFID). rFID is the FID between the reconstructions and the originals, and can be read as an estimate of the ceiling on second-stage generation quality:
| Model | Grid | Codebook | rFID |
|---|---|---|---|
| DALL·E dVAE | 32×32 | 8,192 | 32.01 |
| VQGAN | 16×16 | 1,024 | 7.94 |
| VQGAN | 16×16 | 16,384 | 4.98 |
| VQGAN (Gumbel) | 32×32 | 8,192 | 1.49 |
| VQGAN | 64×64 + 32×32 | 512 | 1.45 |
Compiled from Table 5 of the paper, ImageNet validation set. The last row reuses VQ-VAE-2's two-level grid setting; for VQ-VAE-2 itself there is only a figure of about 10, computed on the training set.
With only 256 tokens, the VQGAN already gets an rFID more than four times better than the dVAE with its 1,024 tokens. Copying VQ-VAE-2's two-level grid pushes rFID down to 1.45, but the sequence length becomes , far too long for a transformer.
Class-conditional ImageNet generation
This set of experiments goes straight at VQ-VAE-2, the best autoregressive result of the time. VQGAN uses with 16,384 codes; the transformer has 48 layers and 1.4 billion parameters. The v3 version was trained for 2.4 million steps, which took 45.8 days on a single A100.
| Model | Filtering | FID | IS |
|---|---|---|---|
| VQGAN (top-k) | None | 15.98 | 78.6 |
| VQGAN (top-p) | None | 15.78 | 74.3 |
| VQGAN (mixed k) | Keep 25% | 7.35 | 188.6 |
| VQGAN (k=600) | Keep 5% | 5.20 | 280.3 |
| VQ-VAE-2 | None | ≈31 | ≈45 |
| VQ-VAE-2 | Yes | ≈10 | ≈330 |
| BigGAN-deep | None | 6.84 | 203.6 |
| ADM-G (guidance 1.0) | None | 4.59 | 186.7 |
Compiled from Table 4 of the paper, , 50,000 samples against the ImageNet training set. The VQGAN rows refer to the full model, VQGAN plus transformer.
"Filtering" means classifier rejection sampling. Generate images, score them with a ResNet-101 trained on ImageNet, and keep only the the classifier is most confident about; keeping 5% means picking 1 out of 20.
Without filtering, VQGAN's FID is around 16, a good deal better than VQ-VAE-2's 31, with roughly a tenth of its parameters (VQ-VAE-2's 13.5B is the authors' estimate). Filtering lowers FID and raises IS; under the same sampling settings, going from keeping half to keeping 5% brings FID down from 10.26 to 5.88, and tightening further to keep only 0.5% actually pushes FID back up to 6.59. But with no filtering at all, BigGAN-deep reaches 6.84, and ADM, the diffusion model that had just come out, reaches 4.59 with classifier guidance. The authors' conclusion is that the model beats the other autoregressive methods and, after filtering, comes close to the best models of the time, a claim consistent with the numbers in the table.
Two more things to keep in mind when reading this table. The rejection sampling uses an ImageNet classifier, and FID and IS are both built on the features of ImageNet classification networks, so filtering pushes both scores up at once. Also, the authors admit in Appendix A that apart from BigGAN, the numbers for the other models in the table are taken from their respective papers and couldn't be re-evaluated with the same code, and that it isn't clear how each implementation resized the training images.
The appendix captions hide one more number. Top-k sampling uses , described as this codebook's "effective size," meaning only 973 of the 16,384 codes are actually used (about 5.9%; the other fifteen thousand or so never had their number called). The dead codes discussed in the VQ-VAE note come to 94% here.
Faces, semantic synthesis, and what FID can't catch
On faces, VQGAN gets an FID of 10.2 on CelebA-HQ and 9.6 on FFHQ, much better than the VAE-type models in the same table (NVAE gets 40.3 on CelebA-HQ, and VDVAE's best on FFHQ is 28.5), but behind StyleGAN2's 3.8 and PGGAN's 8.0. Generating images from semantic segmentation maps, its FID of 22.4 on COCO-Stuff edges out SPADE's 22.6, while its 35.5 on ADE20K loses to SPADE's 33.9. The authors position it as a general method that does respectably on every task, while specialized GANs are still better at individual ones.
The face FIDs take the best top-k setting from (400 for CelebA-HQ, 300 for FFHQ), which amounts to tuning a hyperparameter on the evaluation metric.
Appendix E has a more interesting experiment. The authors train on faces with a larger transformer and keep two checkpoints: the one with the lowest validation NLL (epoch 10 for FFHQ, epoch 13 for CelebA-HQ) and the one with the lowest training NLL (epoch 1,000). The latter generates faces that have near-identical twins in the training set; the model is reciting the answers. Yet its FID is 3.86 on CelebA-HQ and 2.68 on FFHQ, better than the officially reported 10.2 and 9.6.
FID only checks whether the distribution of generated images looks like the real data, and spitting the training images back out unchanged naturally gives a very similar distribution. The authors say outright that FID can't detect this kind of overfitting, and that the size of face datasets is the bottleneck for this method. Likelihood-based models at least have validation NLL to look at, one advantage they have over GANs.
The discriminator is hard to please
The issue tracker fills in much of what the paper leaves out. In April 2021 the official repo got an issue, still open today, titled "Has anyone succeeded in reproducing the results?". The poster said the reconstructions looked decent before the discriminator joined in, and that once it did, it ruined them, with the discriminator loss stuck at 1.0; more people reported the same thing afterward, someone was still asking what to do in July 2023, and the maintainers never stepped in to answer.
What does a loss stuck at 1.0 mean? Go back to the hinge form of the discriminator loss, . If the discriminator outputs 0 for both real images and reconstructions, the loss is exactly . In other words, the discriminator can't tell anything apart. In another thread, issue #93, users' experience was to push disc_start later and turn disc_weight down; one person got it working on the CUB bird dataset by starting at step 50,000 with a weight of 0.2, while someone else followed the same advice and still saw results get worse the moment the discriminator switched on.
What came next
In April 2021, Katherine Crowson et al. hooked VQGAN's decoder up to CLIP, generating images by optimizing the latent codes directly against a text description; once the Colab notebook went public it spread widely online, and in 2022 the approach was written up as the VQGAN-CLIP paper.
The longer-lasting influence lies in the first stage's training recipe. In December 2021, Rombach, Esser, Ommer and colleagues published Latent Diffusion, whose paper states that its autoencoder reuses this paper's perceptual loss and patch discriminator, with two kinds of regularization. One keeps vector quantization; the other removes the quantization layer in favor of a KL term weighted at only around , which is already very close to a plain autoencoder. The VAE that Stable Diffusion later used is the latter.
Conclusion
VQGAN's changes to VQ-VAE are concentrated in the first stage's training objective. MSE gives way to a perceptual loss plus a patch discriminator, with the balance between the two set automatically by the gradient norms at the last layer; as a result a code can stand for a block of pixels, and a image comes down to just 256 tokens. The second stage switches to a transformer with GPT-2's architecture, and a sliding window extends generation to megapixel images. The strongest evidence comes from Figure 7 and Table 5, where with the sequence length fixed only draws complete faces, and the reconstruction FID beats DALL·E's dVAE with a quarter of the tokens. The ImageNet generation results need classifier filtering to get close to the best models of the time, and on faces it still loses to StyleGAN2.
If you train a VQGAN yourself, switch the discriminator on late and let the reconstruction train alone for a while first; during training, watch d_weight, the discriminator's outputs on real images and reconstructions, and whether the discriminator loss is stuck at 1.0; and when using the official code, know what legacy=True means. Log codebook usage, and when evaluating generation quality, don't look at FID alone; take a few samples and look up their nearest neighbors in the training set.
That 16,384-code codebook in the appendix uses 973 codes on ImageNet.