VQGAN, the vector-quantized generative adversarial network, is an image model that learns to compress a picture into a compact grid of discrete tokens drawn from a learned codebook and to reconstruct it with realistic texture. In generative AI, it serves mainly as an image tokenizer: it converts pixels into a short sequence of symbols that a transformer or another generative model can predict, then turns predicted symbols back into a full-resolution image.
Introduced in 2021 in the work titled “Taming Transformers for High-Resolution Image Synthesis”, VQGAN combined the discrete bottleneck of VQ-VAE with an adversarial loss and a perceptual loss. That combination allowed much stronger compression than earlier discrete autoencoders while keeping reconstructions sharp, which made autoregressive image generation at megapixel scale practical for the first time.
How VQGAN encodes and decodes an image
VQGAN works as a convolutional encoder, a quantizer and a decoder trained together. The encoder downsamples an image, typically by a factor of 8 or 16 per side, into a grid of continuous feature vectors. The quantizer replaces each vector with its nearest neighbor in a codebook of learned embeddings, and the decoder upsamples the resulting grid back to pixels.
Because the nearest-neighbor lookup is not differentiable, training uses the straight-through estimator: gradients from the decoder are copied past the quantizer directly to the encoder. A codebook loss pulls the chosen embeddings toward encoder outputs, and a commitment loss keeps encoder outputs close to their assigned codes, exactly as in VQ-VAE.
The following table summarizes the components and the role each one plays in the model.
| Component | Function | Typical configuration |
|---|---|---|
| Encoder | Maps pixels to a low-resolution feature grid | ResNet blocks with attention at the lowest scale |
| Codebook | Stores discrete embedding vectors | 1,024 to 16,384 entries of 256 dimensions |
| Quantizer | Assigns each feature to its nearest code | Euclidean or cosine distance lookup |
| Decoder | Reconstructs the image from code embeddings | Mirror of the encoder with upsampling |
| Discriminator | Judges realism of local image patches | PatchGAN convolutional classifier |
Training objective of VQGAN
The VQGAN objective adds two terms to the standard vector-quantized reconstruction loss. A perceptual loss, usually LPIPS computed on features of a pretrained network, rewards reconstructions that look similar to the original rather than matching pixel by pixel. An adversarial loss from a patch-based discriminator penalizes blurry or unrealistic local texture.
The adversarial term is weighted adaptively: its weight is set from the ratio of gradient norms of the reconstruction and adversarial losses at the last decoder layer. This adaptive weight keeps the discriminator from dominating early training. In practice, the discriminator is often switched on only after several thousand steps, once reconstructions are reasonable.
| Loss term | Effect on the model | Failure when missing |
|---|---|---|
| Reconstruction (L1 or L2) | Preserves overall structure and color | Shapes drift from the input |
| Perceptual (LPIPS) | Preserves semantic and textural similarity | Outputs look plausible but wrong in detail |
| Adversarial (patch GAN) | Produces sharp, realistic local texture | Blurry, smeared reconstructions |
| Codebook and commitment | Keeps encoder and codebook aligned | Unstable or diverging quantization |
VQGAN compared with related generative models
VQGAN sits between discrete autoencoders and latent generative models. It differs from a plain GAN because it is an autoencoder with an explicit encoder, so every image has a token representation. It differs from a variational autoencoder because its latent space is discrete rather than a continuous Gaussian distribution.
The comparison below places VQGAN among the neighboring models of the Generative AI topic.
| Model | Latent representation | Main use |
|---|---|---|
| VQ-VAE | Discrete codes, pixel-level losses | Tokenizer with moderate compression |
| VQGAN | Discrete codes, perceptual and adversarial losses | High-compression image tokenizer |
| Variational autoencoder | Continuous Gaussian latent | Latent space for diffusion models |
| GAN | Random noise vector, no encoder | Direct image synthesis |
| Latent diffusion model | Continuous latent from an autoencoder | Text-to-image generation |
The autoencoder inside Stable Diffusion is itself a descendant of VQGAN: it uses the same perceptual and adversarial training recipe, but usually replaces hard quantization with a lightly regularized continuous latent. This lineage explains why VQGAN remains relevant even where diffusion dominates.
Generating images with VQGAN tokens
VQGAN itself only reconstructs images; generation requires a second-stage prior that learns the distribution of token grids. In the original design, a GPT-style transformer predicts the codes one after another in raster order. A 256 by 256 image compressed with a factor of 16 becomes a 16 by 16 grid of 256 tokens, short enough for a transformer to model.
Conditioning is added by prefixing tokens for a class label, a segmentation map, a depth map or text. Later systems replaced raster-order prediction with masked generative transformers, which predict many tokens in parallel, and with visual autoregressive modeling across scales. In each case, VQGAN or a close successor provides the vocabulary.
- Class-conditional synthesis: a class token precedes the image tokens.
- Semantic image synthesis: tokens of a segmentation map guide the layout.
- VQGAN+CLIP: an optimization loop adjusts the latent so that CLIP scores the decoded image as a match to a text prompt.
- Multimodal language models: image tokens share one sequence with text tokens.
Key settings and practical trade-offs
The two settings that matter most are the downsampling factor and the codebook size. Higher compression shortens sequences and speeds up the second stage, but discards fine detail. A larger codebook can represent more patterns, yet without care many entries are never used.
| Setting | Lower value | Higher value |
|---|---|---|
| Downsampling factor | Sharper detail, longer token sequences | Shorter sequences, loss of small text and faces |
| Codebook size | Easy to train, limited expressiveness | Richer detail, risk of dead codes |
| Code dimension | Better codebook usage with factorized lookup | More information per code, harder matching |
| Adversarial weight | Stable but softer textures | Sharper textures, possible artifacts |
Reconstruction quality is usually measured with reconstruction FID and PSNR on held-out images, while codebook utilization shows how many entries are actually used. Successful tokenizers aim for utilization close to the full codebook.
Limitations and common problems
The best-known weakness is codebook collapse, in which only a small fraction of codes is ever selected. Remedies include low-dimensional factorized codes, L2-normalized codes, k-means initialization and periodic reset of dead entries. Newer schemes such as lookup-free quantization and finite scalar quantization avoid a learned codebook entirely.
VQGAN also struggles with small text, fine faces and high-frequency patterns at strong compression, and adversarial training can introduce repeating artifacts. Raster-order autoregressive sampling over its tokens is slow for large images. Finally, the discrete bottleneck cannot be edited smoothly, which makes latent interpolation less natural than in continuous latent spaces.
Understanding it simply
VQGAN turns a picture into a short list of codes. Think of a mosaic built from a fixed set of tiles. The model learns which tiles to keep in its box. To store an image, it picks the best tile for each small area.
To show the image again, it rebuilds the picture from those tiles. A second network acts as a strict critic during training. It rejects blurry results, so the rebuilt image looks sharp. The key idea is simple: images become words, and other AI models can then write new images word by word.
Applied in practice
A research team building a multimodal model wants it to both read and generate images inside one transformer. It trains a VQGAN on several million photographs at 256 by 256 pixels, with a downsampling factor of 16 and a codebook of 8,192 entries. Each image becomes 256 discrete tokens, which are added to the vocabulary alongside text tokens.
Early runs show that only about a fifth of the codebook is used. The team switches to low-dimensional, normalized codes and resets unused entries during training, which raises utilization above 90 percent. Reconstructions of landscapes and products become clearly sharper, although small printed text remains hard to read.
The final outcome is a shared token space for text and images: the transformer can caption a photograph and, given a caption, predict a token grid that the VQGAN decoder turns into a new picture.