16 Advanced VAE Variants
From VAEs to VAE Variants
In 15 we built the core variational autoencoder from the ground up: the evidence lower bound (ELBO), the reparameterisation trick, and the closed-form Gaussian KL divergence that makes training practical. The vanilla VAE is elegant, but it carries several well-known limitations.
Key Idea.
The standard VAE uses a mode-covering KL divergence that averages over modes, contributing to blurry samples. Its latent dimensions are typically entangled, offering little control over individual generative factors. It has no built-in mechanism for conditional generation, and it restricts the latent space to continuous variables, even when the data is naturally discrete. Each of these limitations sparked a family of architectural variants.
This chapter traces five such variants, each addressing a specific weakness:
-VAE (The -VAE: Disentangled Representations): a single hyperparameter change that encourages disentangled latent representations.
Conditional VAE (Conditional VAE): extending the VAE to generate data conditioned on side information such as class labels.
VQ-VAE (VQ-VAE: Vector Quantised Variational Autoencoder): replacing the continuous latent space with a learned discrete codebook.
VQ-GAN (VQ-GAN: Adversarial Codebook Learning): adding adversarial and perceptual losses to sharpen VQ-VAE outputs.
VQ-VAE-2 (VQ-VAE-2: Hierarchical Discrete Representations): a hierarchical extension with multiple codebook levels for high-resolution generation.
Historical Note.
The period from 2015 to 2019 saw an explosion of VAE variants. Within two years of Kingma and Welling [1], over a dozen architectures had appeared, each targeting a specific weakness of the original model. By 2021, discrete-latent models such as VQ-VAE had become backbone components in large-scale systems like DALL-E and Stable Diffusion, far beyond what the original VAE paper envisioned.
The -VAE: Disentangled Representations
What if we could learn a latent space where each dimension captures exactly one independent generative factor, such as colour, shape, or orientation? This is the promise of disentangled representations, and the -VAE achieves it with a remarkably simple modification to the standard ELBO.
Definition 1 (-VAE Objective).
The -VAE objective is (BETA OBJ) where is a scalar hyperparameter that controls the strength of the KL regularisation relative to reconstruction.
Setting recovers the standard VAE ELBO from 15. Increasing beyond places stronger pressure on the approximate posterior to match the prior, while decreasing below yields a “loosened” VAE that prioritises reconstruction fidelity.
Remark 1 ( Recovers the Standard ELBO).
When , (BETA OBJ) is exactly the evidence lower bound derived in The Evidence Lower Bound. Values have also found use in practice: they produce sharper reconstructions at the cost of a less structured latent space.
Why does a larger encourage disentanglement? The intuition connects to the information bottleneck principle: by aggressively penalising the KL term, the encoder is forced to transmit only the most essential information about through . Under this pressure, the most “efficient” encoding aligns each latent dimension with an independent generative factor, producing an axis-aligned, factorial posterior.
Definition 2 (Disentangled Representation).
A latent representation is disentangled with respect to a set of independent generative factors if each latent dimension is sensitive to changes in exactly one factor and invariant to all others.
Proposition 1 (Extreme Trade-off).
Consider the -VAE objective in (BETA OBJ).
As , the optimal encoder satisfies for all , leading to posterior collapse: the latent code carries no information about the input.
As , the KL term vanishes and the model reduces to a deterministic autoencoder with no regularisation on the latent space.
Proof.
For part (i), suppose . The objective becomes For to remain finite as , we need for every . Since the KL divergence equals zero if and only if the two distributions are identical almost everywhere, this forces . But then is independent of , which is precisely posterior collapse (see Posterior Collapse).
For part (ii), setting removes the KL penalty entirely, so the optimisation reduces to . Without regularisation, can concentrate all mass on a single point , recovering a deterministic autoencoder with no structure in the latent space.
Insight.
The -VAE illustrates a fundamental tension in representation learning: compression versus reconstruction. A practitioner must choose to balance these goals. Typical values for disentanglement experiments lie in the range , depending on the dataset and the desired level of latent interpretability.
Historical Note.
Irina Higgins and colleagues at DeepMind introduced the -VAE in 2017 [2]. The idea was strikingly simple: change one hyperparameter. Yet it sparked an entire research direction on disentanglement metrics and benchmarks (dSprites, 3D Shapes). The subsequent debate over whether unsupervised disentanglement is even possible without inductive biases remains one of the liveliest topics in representation learning.
Conditional VAE
So far, both the VAE and the -VAE generate data unconditionally: we sample from the prior and decode. But what if we want to generate a specific digit, a face with particular attributes, or an image from a text description? The Conditional VAE (CVAE) extends the framework to condition on side information .
Definition 3 (Conditional VAE).
A Conditional VAE defines a generative model for data given side information through a latent variable : (CVAE Model) where is the prior over latents, and is the conditional decoder. The approximate posterior (encoder) is , which conditions on both the data and the side information.
The side information can be a discrete class label, a continuous attribute vector, or even a natural language description. The key modelling choice is that feeds into both the encoder and the decoder.
Theorem 1 (Conditional ELBO).
For any distribution with support containing that of , (CVAE ELBO) The gap between the left-hand side and the right-hand side equals .
Proof.
The derivation mirrors the unconditional ELBO (The Evidence Lower Bound), with every term conditioned on . Start from the log-marginal likelihood: (CVAE Jensen) where the inequality in (CVAE Jensen) follows from Jensen's inequality applied to the concave logarithm. Expanding the joint gives (CVAE ELBO Final) For the gap, write using Bayes' rule . Since KL divergence is non-negative, the bound is tight when the approximate posterior equals the true posterior.
Caution.
If the encoder ignores the side information and uses instead of , it cannot capture label-dependent variation in the latent space. The posterior approximation becomes suboptimal, and the bound loosens. In the worst case, the decoder learns to ignore as well, and the model ceases to be a true conditional generative model.
Example 1 (Conditional MNIST Generation).
Consider training a CVAE on MNIST with as the digit label. During training, the encoder receives both the image and the one-hot label , producing . The decoder reconstructs from . At generation time, we fix (say), sample , and decode: every sample is a plausible rendition of the digit , with variation in stroke width, slant, and style captured by the random .
Historical Note.
Kihyuk Sohn, Honglak Lee, and Xinchen Yan introduced the Conditional VAE at NeurIPS 2015 [3]. A key insight of the paper was that conditioning the prior on (i.e., using instead of ) is possible but often unnecessary for practical applications. Conditioning only the encoder and decoder already allows the model to generate class-specific outputs while keeping the training procedure simple.
From Continuous to Discrete Latent Spaces
The VAE, -VAE, and CVAE all use continuous latent variables, typically drawn from a Gaussian. But many modalities are inherently discrete: language is composed of tokens, music consists of notes, and images can be described by a finite palette of visual patterns. Why not use a discrete latent space directly?
There is a deeper reason beyond matching data structure. Continuous latent codes produced by a Gaussian prior encourage the decoder to “average” nearby codes, which contributes to the characteristic blurriness of VAE samples. Discrete codes, by contrast, can index sharp prototypes in a learned codebook: each code maps to a single, well-defined embedding vector, eliminating the averaging effect.
Insight.
Discrete representations also align naturally with downstream tasks that require reasoning, planning, or symbolic manipulation. A finite codebook turns the latent space into a vocabulary, making it amenable to powerful sequence models such as autoregressive transformers and PixelCNNs.
The following table summarises the key differences between continuous and discrete latent variable models:
| Property | Continuous VAE | Discrete VQ-VAE |
| Latent type | ||
| Posterior | Gaussian | One-hot (deterministic) |
| KL divergence | Analytical (Gaussian KL) | Constant |
| Gradient through | Reparameterisation trick | Straight-through estimator |
| Sample quality | Often blurry | Sharper (codebook prototypes) |
Historical Note.
Vector quantisation itself is not a deep learning invention. Yoseph Linde, Andrés Buzo, and Robert Gray introduced the LBG algorithm for vector quantisation in 1980 [4], originally for speech coding and signal compression. Nearly four decades later, van den Oord and colleagues revived the idea within the deep generative modelling framework, combining classical VQ with neural encoders and decoders.
VQ-VAE: Vector Quantised Variational Autoencoder
The Vector Quantised VAE (VQ-VAE) replaces the continuous Gaussian latent space of a standard VAE with a discrete codebook of learnable embedding vectors. This section develops the full mathematical machinery.
Architecture
Definition 4 (VQ-VAE).
A VQ-VAE consists of three components:
An encoder that maps input to a continuous embedding.
A codebook (embedding table) of learnable prototype vectors.
A quantisation step that maps the encoder output to the nearest codebook entry: (Quantise)
A decoder that reconstructs the input from the quantised code.
Definition 5 (Codebook).
The codebook is a learnable dictionary of prototype vectors in . Each encoder output is “snapped” to its nearest codebook entry during the forward pass. The codebook can be thought of as a discrete “vocabulary” of latent representations, where each entry encodes a reusable visual or structural pattern.
Posterior and KL Divergence
Unlike the Gaussian VAE, where the posterior is a continuous density, the VQ-VAE posterior is a deterministic categorical distribution.
Proposition 2 (Deterministic Posterior and Constant KL).
In VQ-VAE, the posterior is a one-hot distribution: With a uniform prior , the KL divergence is constant:
Proof.
Since places all its mass on a single index , the KL divergence reduces to where we used and . All other terms vanish because for , and by convention.
Since the KL is constant, it does not depend on the encoder parameters and drops out of the gradient computation. The training objective is therefore driven entirely by the reconstruction term and two auxiliary losses.
The VQ-VAE Loss Function
Definition 6 (VQ-VAE Loss).
The total VQ-VAE training loss is (Vqvae LOSS) where is the decoder output, is the selected codebook vector, and denotes the stop-gradient operator.
Each of the three terms plays a distinct role. Let us examine the less familiar ones.
Remark 2 (The Stop-Gradient Operator).
The operator acts as the identity during the forward pass
but produces zero gradient during backpropagation. In PyTorch, this is
implemented via x.detach(). The stop-gradient decouples the encoder
and codebook updates: in the codebook loss
, gradients flow only to the codebook
vectors , while in the commitment loss
, gradients flow only to the encoder.
Remark 3 (Commitment Loss).
The commitment loss prevents the encoder outputs from growing unboundedly or drifting away from the codebook vectors. Without it, the encoder could produce embeddings in a region of far from any codebook entry, making the quantisation step meaningless. The hyperparameter is typically set to .
Gradient Flow: The Straight-Through Estimator
The in (Quantise) is a discrete, non-differentiable operation. How do gradients from the decoder reach the encoder?
Proposition 3 (Straight-Through Estimator).
The straight-through estimator approximates the gradient of the quantisation step by copying the gradient of the decoder input directly to the encoder output: That is, in the forward pass the discrete mapping is applied as usual, but in the backward pass the is treated as the identity function, allowing the decoder's gradient signal to flow unaltered back to the encoder.
This approximation is justified by the observation that the codebook and commitment losses keep and close together, so the local geometry around and is similar. In practice, it works remarkably well, and VQ-VAE trains stably with standard optimisers.
Historical Note.
Aaron van den Oord, Oriol Vinyals, and Koray Kavukcuoglu at DeepMind introduced VQ-VAE in 2017 [5]. The paper was notable for demonstrating that discrete latent variables could match continuous ones in reconstruction quality while completely avoiding posterior collapse. Because the posterior is deterministic (one-hot) rather than a soft Gaussian, the decoder cannot “ignore” the latent code. This elegant side-stepping of one of the VAE's biggest practical problems attracted widespread attention.
VQ-GAN: Adversarial Codebook Learning
VQ-VAE produces reasonable reconstructions, but they still lack the crisp, photorealistic quality that modern applications demand. Why? The reconstruction loss penalises pixel-level deviations equally, rewarding blurry “average” outputs over sharp ones that might differ in a few pixels. VQ-GAN addresses this by augmenting the VQ-VAE objective with an adversarial loss and a perceptual loss.
Definition 7 (VQ-GAN).
A VQ-GAN consists of a VQ-VAE backbone (encoder, codebook, decoder) augmented with:
A patch-based discriminator that classifies overlapping image patches as real or generated.
A perceptual loss computed from intermediate features of a pretrained network (e.g., VGG).
Definition 8 (VQ-GAN Objective).
The total VQ-GAN training objective combines three losses: (Vqgan OBJ) where is the three-term VQ-VAE loss from (Vqvae LOSS), is the adversarial loss from the patch discriminator, and is the perceptual loss. The scalars and balance the three terms.
Remark 4 (Patch Discriminator).
Unlike a standard GAN discriminator that produces a single real/fake score for the entire image, a patch discriminator classifies each overlapping patch independently. This provides spatially localised feedback to the generator, encouraging local sharpness and texture quality rather than only global coherence.
Insight.
VQ-GAN codebooks serve as a discrete “visual vocabulary.” Each codebook entry encodes a reusable visual pattern (an edge, a texture, a colour gradient), and an image is represented as a spatial grid of codebook indices. This representation is perfectly suited for autoregressive modelling with transformers: treat the codebook indices as tokens and generate images token by token, exactly like generating text. This idea underpins OpenAI's DALL-E and the latent diffusion framework behind Stable Diffusion.
Historical Note.
Patrick Esser, Robin Rombach, and Björn Ommer introduced VQ-GAN at CVPR 2021 [6]. Their key contribution was demonstrating that the adversarial and perceptual losses dramatically improved both codebook utilisation (more codebook vectors are actively used) and image quality. VQ-GAN became the backbone tokeniser for latent diffusion models: Rombach and Esser went on to develop Stable Diffusion, where a VQ-GAN first compresses images to a discrete latent grid, and a diffusion model then generates in that compressed space.
VQ-VAE-2: Hierarchical Discrete Representations
A single-level codebook captures the data at one resolution, but high-resolution images contain structure at many scales: global layout (is this a face or a landscape?), mid-level composition (where are the eyes?), and fine-grained texture (individual hair strands). VQ-VAE-2 addresses this with a hierarchical architecture that encodes at multiple levels.
Definition 9 (VQ-VAE-2).
VQ-VAE-2 is a multi-level VQ-VAE with:
A top-level encoder that produces a low-resolution latent map quantised with codebook , capturing global structure.
A bottom-level encoder that produces a higher-resolution latent map quantised with codebook , conditioned on the top-level codes, capturing local detail.
A decoder that reconstructs the input from both levels: .
For example, a image might be encoded to a top-level map and a bottom-level map.
Stage 1: Hierarchical Encoding and Reconstruction
The first training stage learns the hierarchical codebooks and the decoder jointly, using the standard VQ-VAE loss applied to both levels.
Algorithm 1 (VQ-VAE-2 Stage 1: Codebook Training).
- Input: Encoders ; decoder ; codebooks ; training batch
- Encode at low resolution
- Nearest-neighbour lookup in top codebook
- Encode at high resolution, conditioned on top codes
- Nearest-neighbour lookup in bottom codebook
- Decode from both levels
- Update all parameters via VQ-VAE loss at both levels
Stage 2: Autoregressive Prior over Codes
Once the codebooks are trained, the second stage fits an autoregressive prior over the discrete codes. This decouples representation learning (stage 1) from density modelling (stage 2).
Algorithm 2 (VQ-VAE-2 Stage 2: Prior Training and Sampling).
- Input: Frozen encoders and codebooks from Stage 1
- Collect code datasets
- for each in training set
- ;
- Unconditional autoregressive prior
- Conditional on top codes
- Sampling:
- Sample top codes autoregressively
- Sample bottom codes conditioned on top
- Decode to image
Remark 5 (Why Two Stages?).
Stage 1 learns the codebook (compression), while stage 2 learns the prior over codes (generation). This separation simplifies training considerably: the VQ-VAE objective in stage 1 does not require modelling the full joint distribution of codes, and the autoregressive model in stage 2 operates over a much smaller, discrete space rather than raw pixels.
Remark 6 (Codebook Collapse).
A practical challenge in VQ-VAE training is codebook collapse: some codebook vectors are never selected as nearest neighbours and therefore receive no gradient updates. Over time, these “dead” vectors drift further from the encoder outputs and are never used again. A common mitigation is random restarts: periodically reassign dead codebook vectors to randomly chosen encoder outputs, ensuring all vectors remain in active use.
Historical Note.
Ali Razavi, Aaron van den Oord, and Oriol Vinyals published VQ-VAE-2 at NeurIPS 2019 [7]. The paper showed that a two-stage pipeline, separating representation learning from density modelling, could generate diverse images that rivalled the quality of BigGAN. The key architectural insight was that hierarchical codebooks allow the model to allocate capacity efficiently: the top level handles global composition while the bottom level handles textures and fine details.
Case Study: High-Fidelity Image Generation with VQ-VAE-2
How well can a likelihood-based model compete with GANs on image quality? Before VQ-VAE-2, the conventional wisdom was that GANs produced sharp images while VAEs produced blurry ones. Razavi et al. [7] challenged this assumption head-on.
Architecture Details
For ImageNet generation, VQ-VAE-2 uses the two-level hierarchy described in Definition 9:
| Level | Resolution | Downsample | Codebook | Dim | Captures |
| Top | from input | 512 | 64 | global structure | |
| Bottom | from input | 512 | 64 | local detail |
The encoder and decoder are built from residual blocks with hidden units and convolutions. Strided convolutions handle downsampling in the encoder, and strided transposed convolutions handle upsampling in the decoder. The codebook uses exponential moving average (EMA) updates with decay and commitment loss coefficient .
The total compression ratio is striking: a image ( values) is compressed to discrete codes, a roughly compression. For face generation on FFHQ, a three-level hierarchy achieves approximately compression.
The PixelSNAIL Prior
The Stage 2 autoregressive priors are powerful models in their own right:
Top prior ( codes): a gated PixelCNN with multi-headed self-attention (PixelSNAIL-style), using layers, hidden units, and attention layers with heads each. Self-attention at resolution is tractable and allows the prior to capture long-range spatial dependencies across the entire image.
Bottom prior ( codes): a deep conditional PixelCNN without self-attention (since attention over positions is prohibitively expensive). Instead, global context is provided by conditioning on the top-level codes through a -layer residual conditioning stack.
Remark 7 (Classifier-Based Rejection Sampling).
To improve sample quality further, the authors introduce a rejection sampling scheme: generate candidate images from the prior, score each with a pretrained ImageNet classifier, and reject samples where the classifier's confidence in the target class falls below a threshold. This provides a smooth quality-diversity trade-off, analogous to the truncation trick in BigGAN. Stricter rejection produces higher-fidelity but less diverse samples.
Results: Rivalling GANs
The results challenged the prevailing belief that likelihood-based models could not match GAN quality. To measure both quality and diversity, the authors used the Classification Accuracy Score (CAS): train an ImageNet classifier exclusively on generated samples, then evaluate it on real test images. A model suffering from mode collapse produces a poor classifier, regardless of individual sample quality.
| Model | CAS Top-1 (%) | CAS Top-5 (%) |
| VQ-VAE-2 | ||
| BigGAN-deep (truncation ) | ||
| Real data (upper bound) |
VQ-VAE-2 significantly outperforms BigGAN on diversity (CAS), while producing images that are visually competitive in quality. The precision-recall analysis confirmed this: VQ-VAE-2 achieves slightly lower precision (individual sample sharpness) but substantially higher recall (mode coverage) than BigGAN.
Insight.
VQ-VAE-2 demonstrated a crucial lesson for generative modelling: sample quality and sample diversity are distinct goals, and models should be evaluated on both. A model that produces stunning samples of only a few modes (like a mode-collapsing GAN) may look impressive on FID but fail on diversity-sensitive metrics like CAS.
Case Study: Jukebox and Music Generation
Can the VQ-VAE framework extend beyond images to generate minutes of coherent music with singing? Jukebox [8], developed at OpenAI, demonstrated exactly this by scaling hierarchical VQ-VAE to raw audio. The challenge is immense: a four-minute song at contains over million samples, orders of magnitude more than a image.
Three-Level VQ-VAE for Audio
Jukebox uses three independently trained VQ-VAE levels, each compressing raw audio at a different temporal resolution:
| Level | Hop Length | Compression | Codebook | Context (seconds) |
| Bottom | ||||
| Middle | ||||
| Top |
Each encoder uses downsampling convolutions followed by residual blocks of non-causal 1-D dilated convolutions (WaveNet-style, dilation growth rate , filter size ). The decoder mirrors this structure. The entire VQ-VAE has only about million parameters, a tiny fraction of the overall system.
The hierarchy creates a natural separation of information: the top level, which compresses audio samples into a single code, captures high-level musical structure (melody, rhythm, song sections). The bottom level, at compression, captures fine acoustic detail (timbre, consonants, breaths).
Combating Codebook Collapse with Random Restarts
With codebook entries per level, maintaining full codebook utilisation is critical. Jukebox tracks the mean usage of each codebook vector via an exponential moving average. When usage falls below a threshold, the “dead” vector is randomly reset to one of the encoder outputs from the current batch. This simple strategy maintains approximately bits of codebook entropy (the maximum for ) throughout training, confirming near-complete utilisation.
Spectral Loss for Audio Fidelity
A standard sample-level reconstruction loss tends to reconstruct only low frequencies, producing muffled audio. Jukebox addresses this with a multi-scale spectral loss, computed on magnitude spectrograms at three resolutions: (Spectral LOSS) where indexes three STFT configurations with window sizes , , and samples. Operating on magnitude spectrograms (ignoring phase) captures frequency content across multiple time scales.
The total VQ-VAE loss combines all components: (Jukebox Vqvae LOSS) with commitment coefficient (lower than the typical used in image VQ-VAEs, reflecting the different loss scales in audio).
Autoregressive Priors with Sparse Transformers
The Stage 2 priors are the computational heart of Jukebox. The top-level prior is a massive billion parameter sparse transformer with layers, a width of dimensions, and a context window of tokens (about seconds of music). Full self-attention over tokens would be prohibitively expensive, so Jukebox uses factorised sparse attention: the token sequence is reshaped into blocks, and three attention patterns alternate across layers:
Row attention (local context): each token attends only to tokens in the same row.
Column attention (global context): each token attends along its column across all rows.
Previous-row attention: full attention to the entire preceding row.
This factorisation reduces the attention cost from to , making it feasible to model long musical sequences.
The middle and bottom upsamplers are smaller ( billion parameters combined). They condition on the upper-level codes through a WaveNet-style residual network followed by upsampling strided convolutions.
Conditioning on Artist, Genre, and Lyrics
Jukebox conditions generation on rich metadata:
Artist and genre: Learned embedding vectors for artists and genres are summed and provided as the first token of each sequence.
Timing: A positional signal encodes total song duration, the current timestamp, and the fraction of the song elapsed, enabling the model to learn song structure (intros, verses, outros).
Lyrics: A character-level transformer encoder ( layers, dimensions) processes the lyrics. The top-level prior becomes an encoder-decoder model: cross-attention layers are interleaved into the -layer decoder, allowing music tokens to attend to lyric tokens.
Remark 8 (Scale of Jukebox Training).
Jukebox was trained on million songs. The VQ-VAE required V100 GPUs for days. The -billion-parameter top prior required V100s for weeks, with an additional weeks to fine-tune the lyrics conditioning. Generating one minute of top-level tokens takes approximately one hour; full upsampling to a waveform takes approximately eight hours. These numbers illustrate the immense computational cost of modelling raw audio at the waveform level.
Insight.
Jukebox validated the VQ-VAE paradigm far beyond images. By compressing audio at up to , the discrete codebook reduces the sequence modelling problem to a tractable length for transformers. The three-level hierarchy is essential: without it, modelling the full million samples of a song autoregressively would be computationally infeasible. The two-stage recipe, learn to compress, then learn to generate in the compressed space, has since become the dominant paradigm across modalities.
Historical Note.
Prafulla Dhariwal, Heewoo Jun, Christine Payne, Jong Wook Kim, Alec Radford, and Ilya Sutskever at OpenAI released Jukebox in April 2020 [8], alongside thousands of non-cherry-picked generated samples. The model could generate coherent songs lasting several minutes, conditioned on artist style, genre, and even lyrics. While the generated audio was not indistinguishable from real recordings, it demonstrated a striking ability to capture musical structure, instrumentation, and vocal styles. The Jukebox codebase and pretrained models were publicly released, enabling further research into music generation with discrete latent codes.
Connections and Outlook
The variants we have studied form a progression from the standard VAE towards increasingly powerful and flexible generative models. The following table summarises their key properties:
1.2
Model Latent KL Term Sample Quality Key Application VAE continuous analytical blurry general generation -VAE continuous analytical blurry disentanglement CVAE continuous analytical blurry conditional generation VQ-VAE discrete constant moderate discrete tokens VQ-GAN discrete constant sharp image tokenisation VQ-VAE-2 discrete (hier.) constant per level sharp high-res generation
Connection to diffusion models.
VQ-GAN codebooks serve as the compression backbone for latent diffusion models. Rather than running a diffusion process in pixel space (which is expensive at high resolution), latent diffusion first encodes images to a compact VQ-GAN latent grid, then applies diffusion in that compressed space. This is the architecture behind Stable Diffusion, one of the most widely deployed generative models.
Connection to transformers.
Discrete tokens from VQ-VAE and VQ-GAN are directly amenable to autoregressive modelling with transformers. Treat each codebook index as a “word” in a visual vocabulary, and a standard language model can generate images token by token. This paradigm underpins DALL-E, Parti, and other vision-language models.
Open directions.
Several challenges remain in the design of VAE variants:
Codebook utilisation: many entries remain unused even with random restarts. Better initialisation and training schedules are active research topics.
Scaling to higher resolution: adding more hierarchical levels introduces engineering complexity and can slow convergence.
Hybrid latent spaces: combining continuous and discrete latents in a single model could capture the benefits of both worlds.
Exercises
Exercise 1 (Conditional ELBO Derivation).
Derive the conditional ELBO from scratch. Starting from , introduce a variational distribution and show that Identify the gap between the ELBO and the true log-likelihood, and explain under what conditions this gap equals zero.
Exercise 2 (Conditional Reparameterisation).
In a CVAE with Gaussian encoder , we write with . Prove that follows the correct distribution. Then explain why this reparameterisation is necessary for computing gradients of the ELBO via backpropagation.
Exercise 3 (-VAE Trade-off Analysis).
In the -VAE objective :
Show that recovers the standard ELBO.
Prove that as , the optimal encoder must satisfy (posterior collapse).
Argue informally why increasing encourages disentanglement, connecting your argument to the information bottleneck principle.
Exercise 4 (VAE vs. EM Algorithm).
Compare the VAE training procedure and the Expectation-Maximisation (EM) algorithm for fitting a latent variable model. Address the following:
How is the posterior over latent variables computed in each approach?
How are the model parameters updated?
What role does amortised inference play in VAEs but not in EM?
Exercise 5 (VQ-VAE Gradient Flow).
In VQ-VAE, the encoder output is mapped to the nearest codebook vector via where .
Explain why the gradient of the reconstruction loss cannot flow through the operation.
Describe how the straight-through estimator addresses this problem.
What is the role of the commitment loss ?
Exercise 6 (KL Divergence for Uniform Distributions).
Let and with .
Compute the KL divergence from its definition and show that it equals .
Compute . What happens and why?
Relate this to the VQ-VAE setting where the prior is uniform over codebook entries and the posterior is a point mass.
Exercise 7 (Ignoring in the CVAE Encoder).
Consider a CVAE where the encoder ignores , using instead of .
Show that the ELBO with this restricted encoder is at most as tight as the ELBO with the full encoder .
Give a concrete example where ignoring leads to a strictly worse bound.
Under what condition on the true posterior does ignoring incur no loss?
Exercise 8 (Constant KL in VQ-VAE).
In VQ-VAE, the posterior is deterministic (one-hot) and the prior is (uniform).
Prove that for every input .
Explain why this means the KL term drops out of the gradient with respect to the encoder parameters.
What would change if the prior were non-uniform, say with ?
Exercise 9 (Exponential Moving Average Codebook Updates).
An alternative to gradient-based codebook learning is the exponential moving average (EMA) update. Let be the number of encoder outputs assigned to codebook entry at step , and let be their mean. The EMA update rule is: where is the decay rate.
Show that in steady state (when statistics are stationary), converges to the mean of encoder outputs assigned to entry .
Compare this to the gradient-based codebook update from the loss term . Which approach is more stable, and why?
What happens to if entry receives no assignments for many consecutive steps?
Exercise 10 (Adversarial Loss and Mode Behaviour).
In VQ-GAN, the adversarial loss supplements the reconstruction loss .
Explain why the reconstruction loss is mode-covering (it prefers blurry averages over sharp samples) while the adversarial loss is mode-seeking (it rewards sharp, realistic outputs).
Why does combining both losses yield better results than either alone?
The perceptual loss compares features from a pretrained VGG network rather than raw pixels. Explain why this encourages structural similarity rather than pixel-level matching.
References
-
Auto-Encoding Variational Bayes
BibTeX
@inproceedings{kingma2013auto, title={Auto-Encoding Variational {B}ayes}, author={Kingma, Diederik P and Welling, Max}, booktitle={International Conference on Learning Representations}, year={2014} }Conference paper
-
$eta$-VAE: Learning Basic Visual Concepts with a Constrained Variational Framework
BibTeX
@inproceedings{higgins2017beta, title={$\beta$-{VAE}: Learning Basic Visual Concepts with a Constrained Variational Framework}, author={Higgins, Irina and Matthey, Loic and Pal, Arka and Burgess, Christopher and Glorot, Xavier and Botvinick, Matthew and Mohamed, Shakir and Lerchner, Alexander}, booktitle={International Conference on Learning Representations}, year={2017} }Conference paper
-
Learning Structured Output Representation using Deep Conditional Generative Models
BibTeX
@inproceedings{sohn2015cvae, title={Learning Structured Output Representation using Deep Conditional Generative Models}, author={Sohn, Kihyuk and Lee, Honglak and Yan, Xinchen}, booktitle={Advances in Neural Information Processing Systems}, pages={3483--3491}, year={2015} }Conference paper
-
An Algorithm for Vector Quantizer Design
BibTeX
@article{linde1980algorithm, title={An Algorithm for Vector Quantizer Design}, author={Linde, Yoseph and Buzo, Andr{\'e}s and Gray, Robert M}, journal={IEEE Transactions on Communications}, volume={28}, number={1}, pages={84--95}, year={1980} }Journal article
-
Neural Discrete Representation Learning
BibTeX
@inproceedings{oord2017vqvae, title={Neural Discrete Representation Learning}, author={van den Oord, Aaron and Vinyals, Oriol and Kavukcuoglu, Koray}, booktitle={Advances in Neural Information Processing Systems}, pages={6306--6315}, year={2017} }Conference paper
-
Taming Transformers for High-Resolution Image Synthesis
BibTeX
@inproceedings{esser2021vqgan, title={Taming Transformers for High-Resolution Image Synthesis}, author={Esser, Patrick and Rombach, Robin and Ommer, Bj{\"o}rn}, booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition}, pages={12873--12883}, year={2021} }Conference paper
-
Generating Diverse High-Fidelity Images with VQ-VAE-2
BibTeX
@inproceedings{razavi2019vqvae2, title={Generating Diverse High-Fidelity Images with {VQ-VAE-2}}, author={Razavi, Ali and van den Oord, Aaron and Vinyals, Oriol}, booktitle={Advances in Neural Information Processing Systems}, pages={14866--14876}, year={2019} }Conference paper
-
Jukebox: A Generative Model for Music
BibTeX
@article{dhariwal2020jukebox, title={Jukebox: A Generative Model for Music}, author={Dhariwal, Prafulla and Jun, Heewoo and Payne, Christine and Kim, Jong Wook and Radford, Alec and Sutskever, Ilya}, journal={arXiv preprint arXiv:2005.00341}, year={2020} }Journal article