Back to paper library
Paper notesarXiv 2020CVPR 2021

VQGAN

The Tamer

Original paper

Taming Transformers for High-Resolution Image Synthesis

Paper authors

Patrick Esser · Robin Rombach · Björn Ommer

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}
}
On this page
A 1280×460 generated landscape: snow-covered mountains and blue sky in the distance, a dark green conifer forest in the middle ground, and in the foreground a lake reflecting the mountains and the trees.
Original Figure 1, Esser et al., from PDF page 1, arXiv license, scholarly quotation.

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 256×256256\times256 RGB image into a sequence of pixels, and its length is 256×256×3=196,608256\times256\times3=196{,}608. The attention matrix is the square of that length, about 3.9×10103.9\times10^{10} 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 n2n^2 down to nnn\sqrt n, 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 128×128128\times128 to 32×3232\times32, each code covering 4×44\times4 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 16×16=25616\times16=256 tokens for a 256×256256\times256 image, each code has to cover 16×1616\times16 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

Overall architecture of VQGAN and the transformer. The lower half is VQGAN: a photo of a dog goes through the CNN Encoder E to give the feature map ẑ; each position finds the nearest code in the codebook Z with argmin and is quantized into a grid of indices, z_q (for example 1, 42, 3, 3, 94, 60, 22, 57); the CNN Decoder G then reconstructs the dog photo, and the reconstruction goes into the CNN Discriminator D, which outputs a 4×4 grid marked real or fake. The upper half: on the left is the codebook, one color per row from 0 to N−1, with small boxes on the photo linked to their codes; on the right is the Transformer, which takes the index sequence 1, 42, 3, 3, 94, 60, 22 as s_<i and predicts a probability distribution over the next index s_i, with p(s) equal to the product of the conditional probabilities.
Original Figure 2, Esser et al., from PDF page 3, arXiv license, scholarly quotation.

The lower half is the first stage, VQGAN, and the upper half is the second stage, the transformer. Let's follow a 256×256256\times256 image through it with the paper's most common setting.

  1. Encode. The convolutional encoder EE downsamples m=4m=4 times, halving height and width each time, for a downsampling factor of f=24=16f=2^4=16. The output z^=E(x)\hat z=E(x) is a 16×1616\times16 feature map with nz=256n_z=256 dimensions per position.
  2. Quantize. Each position finds the nearest code in the codebook Z\mathcal Z, whose size is ∣Z∣=1024|\mathcal Z|=1024. The result is a 16×1616\times16 grid of integers, which can also be seen as an integer sequence ss of length 256.
  3. Decode and discriminate. The decoder GG draws the looked-up zqz_q back into a 256×256256\times256 image; the discriminator DD looks at each small patch of the reconstruction and judges whether it looks real.
  4. Learn the distribution. The second stage encodes every training image into an integer sequence and has the transformer learn p(s)=∏ip(si∣s<i)p(s)=\prod_i p(s_i|s_{<i}). 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? 1024=2101024=2^{10}, so each token is 10 bits, and 256 tokens make 2,560 bits. The original image is 256×256×3256\times256\times3 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)):

zq=q(z^):=(arg⁡min⁡zk∈Z∥z^ij−zk∥)ijz_q=q(\hat z):=\Big(\arg\min_{z_k\in\mathcal Z}\|\hat z_{ij}-z_k\|\Big)_{ij}

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:

LVQ=∥x−x^∥2+∥sg[E(x)]−zq∥22+∥sg[zq]−E(x)∥22\begin{aligned} \mathcal L_{VQ}={}&\|x-\hat x\|^2+\big\|\mathrm{sg}[E(x)]-z_q\big\|_2^2\\ &+\big\|\mathrm{sg}[z_q]-E(x)\big\|_2^2 \end{aligned}

This formula comes with a small backstory. In v2, the commitment loss had a β\beta in front of it, and the hyperparameter table said β=0.25\beta=0.25. Appendix A of v3 admits that because of a bug in the implementation, β\beta was never used and every model was actually trained with 1.0, so the β\beta 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 4×44\times4 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)):

LGAN({E,G,Z},D)=log⁡D(x)+log⁡(1−D(x^))\begin{aligned} &\mathcal L_{GAN}(\{E,G,\mathcal Z\},D)\\ &\quad=\log D(x)+\log\big(1-D(\hat x)\big) \end{aligned} Q∗=arg⁡min⁡E,G,Z max⁡DEx∼p(x)[LVQ+λ LGAN]\begin{aligned} Q^*&=\arg\min_{E,G,\mathcal Z}\ \max_D\\ &\quad\mathbb E_{x\sim p(x)}\Big[\mathcal L_{VQ}+\lambda\,\mathcal L_{GAN}\Big] \end{aligned}

The discriminator DD 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 12[ReLU(1−D(x))+ReLU(1+D(x^))]\frac12\big[\mathrm{ReLU}(1-D(x))+\mathrm{ReLU}(1+D(\hat x))\big], and the generator side's loss is the mean of −D(x^)-D(\hat x). 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 λ\lambda is hard to pick by hand. The authors have it compute itself at every step (Eq. (7)):

λ=∥∇GLLrec∥∥∇GLLGAN∥+δ\lambda=\frac{\big\|\nabla_{G_L}\mathcal L_{rec}\big\|}{\big\|\nabla_{G_L}\mathcal L_{GAN}\big\|+\delta}

GLG_L is the weights of the decoder's last layer, ∇GL\nabla_{G_L} the gradient with respect to them, and δ=10−6\delta=10^{-6} 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 λ=0.02/0.5=0.04\lambda=0.02/0.5=0.04, 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 λ\lambda 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:

python
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 10−410^{-4} rather than 10−610^{-6}; λ\lambda is clamped between 0 and 10410^4; 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 λ\lambda just a number, with no gradient flowing through it.

Appendix B adds that early in training, λ=0\lambda=0 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 mm 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 nzn_z-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 f=16f=16, 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)):

LTransformer=Ex∼p(x)[−log⁡p(s)]\mathcal L_{Transformer}=\mathbb E_{x\sim p(x)}\big[-\log p(s)\big] p(s)=∏ip(si∣s<i)p(s)=\prod_i p(s_i|s_{<i})

Why is the sequence fixed at 16×1616\times16? 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 rr as well, which is placed in front of ss, and the loss is computed only on the ss 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, 16f×16f16f\times16f crops are taken from the image (256×256256\times256 when f=16f=16) and encoded into 16×1616\times16 tokens. At sampling time, the token grid can be much bigger than 16×1616\times16. To decide the token at each position, a 16×1616\times16 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 (8,8)(8,8), moving toward the edge only near the borders.

For example, with f=16f=16, a 1280×8321280\times832 image is 80×52=4,16080\times52=4{,}160 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 1840×10241840\times1024, 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.784.844.96
LSUN-CT (310M)4.634.694.89
IN (310M)4.784.834.96
D-RIN (180M)4.704.784.88
S-FLCKR (310M)4.494.574.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

Four groups of FacesHQ face samples, with downsampling factor f of 1, 2, 8 and 16 from left to right, all with the sequence length fixed at 16×16. The two f1 samples are broken patchworks of color with no recognizable face; the four f2 samples are orange-red faces with distorted features; the six f8 samples are complete faces, though some have mismatched left and right halves; the eight f16 samples are clear, natural faces. The bottom row gives the sampling speedup relative to f1: 1.0, 3.86, 65.81, 280.68.
Original Figure 7, Esser et al., from PDF page 8, arXiv license, scholarly quotation.

This is the most direct figure in the whole paper. The transformer's sequence length is fixed at 16×1616\times16, and only the first stage's downsampling factor ff changes. For f=1f=1, 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 ff is, the smaller the patch of the original image the transformer's window can see. At f=1f=1 the window is just 16×1616\times16 pixels, not even big enough for one eye, and what comes out is broken patches of color; f=2f=2 gets the colors of a face, with crooked features; f=8f=8 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 f=16f=16 draws a whole, natural face.

The bottom row is speed. At f=1f=1, generating one image takes 7,258 seconds (GTX Titan X), and f=16f=16 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 f=2f=2 VQGAN codes; with the same compute, the latter's FID is 18.63% better and sampling is 14.08 times faster.

So can ff just keep growing? Appendix C measures, on faces, the reconstruction error (LPIPS, lower is better) and the transformer's negative log-likelihood for f=2f=2 to 64:

ffRec. errorNLL
20.115.66×1045.66\times10^4
40.201.29×1041.29\times10^4
80.234.10×1034.10\times10^3
160.382.32×1032.32\times10^3
320.632.28×1022.28\times10^2
640.666.75×1016.75\times10^1

Compiled from Figure 11 of the paper.

The larger ff 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 f=32f=32. 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 ff goes beyond 16; landscapes are more forgiving, and reconstructions at f=32f=32 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

Two rows of reconstruction comparisons, a squirrel on top and a macaw below. Five columns from left to right: the original, DALL-E VAE (f8, codebook 8192), VQGAN (f8, 8192), VQGAN (f16, 16384), VQGAN (f16, 1024). In the DALL-E VAE column the squirrel's fur and the rock texture blur together, and the fine lines on the macaw's face are blurry too; VQGAN f8 shows clear fur, feathers and rock texture, close to the original; the two f16 versions are just as sharp, but the squirrel's paw position doesn't quite match the original.
Original Figure 12, Esser et al., from PDF page 15, arXiv license, scholarly quotation.

The second column is DALL·E's dVAE, with the same f=8f=8 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 ff 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:

ModelGridCodebookrFID
DALL·E dVAE32×328,19232.01
VQGAN16×161,0247.94
VQGAN16×1616,3844.98
VQGAN (Gumbel)32×328,1921.49
VQGAN64×64 + 32×325121.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 16×1616\times16 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 642+322=5,12064^2+32^2=5{,}120, 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 f=16f=16 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.

ModelFilteringFIDIS
VQGAN (top-k)None15.9878.6
VQGAN (top-p)None15.7874.3
VQGAN (mixed k)Keep 25%7.35188.6
VQGAN (k=600)Keep 5%5.20280.3
VQ-VAE-2None≈31≈45
VQ-VAE-2Yes≈10≈330
BigGAN-deepNone6.84203.6
ADM-G (guidance 1.0)None4.59186.7

Compiled from Table 4 of the paper, 256×256256\times256, 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 nn images, score them with a ResNet-101 trained on ImageNet, and keep only the mm 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 k=973k=973, 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 256×256256\times256 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 k∈{100,…,500}k\in\{100,\dots,500\} (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, 12[ReLU(1−D(x))+ReLU(1+D(x^))]\frac12\big[\mathrm{ReLU}(1-D(x))+\mathrm{ReLU}(1+D(\hat x))\big]. If the discriminator outputs 0 for both real images and reconstructions, the loss is exactly 12(1+1)=1\frac12(1+1)=1. 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 10−610^{-6}, 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 16×1616\times16 block of pixels, and a 256×256256\times256 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 f=16f=16 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.