08 / 34 · Variational Autoencoders
VAE variants: β-VAE and VQ-VAE
Two changes to a VAE: a weight on the KL term that sets how much the code may carry (β-VAE), and a discrete code from a learned codebook whose prior is fitted afterwards (VQ-VAE and VQ-VAE-2).
On this page 5
A VAE trained on faces gives blurry reconstructions, and its prior samples are worse than its reconstructions, because the codes fill the prior only roughly. Both complaints come from the two terms of its objective:
The first term wants the code to say as much about the image as possible; the second charges for every nat it says. We can change the balance between them, which is the β-VAE. Or we can change what a code is, a grid of symbols from a learned codebook instead of a Gaussian vector, and fit the prior afterwards with a model strong enough to match the codes, which is the VQ-VAE.
β-VAE: a weight on the KL term#
The β-VAE (Higgins et al., 2017) maximizes
is the plain VAE. For the objective is still a lower bound on , since it subtracts more of a non-negative quantity; for it can exceed and bounds nothing. Either way changes which model training prefers, not just the scale of the loss. A Gaussian decoder with fixed variance already hides such a weight: with squared error as the loss, the effective is .
Rate and distortion#
Averaged over the data, the two terms have names from information theory (Alemi et al., 2018). The rate is the average KL,
in nats. It is the mutual information between images and codes plus the KL from the aggregate posterior to the prior, so it bounds the mutual information from above. The distortion is the average reconstruction loss:
The negative ELBO is , and the β-VAE minimizes : the Lagrangian of “reconstruct as well as possible with at most a given rate”. Every picks one point of the trade-off. Since , for , so among the weights that still give a bound, gives the tightest.
Worked example: one latent dimension#
Take one latent dimension, the prior and a fixed linear decoder with and . Let the data come from this very model, . Holding the decoder fixed isolates what does to the encoder . Using and the closed-form KL, the objective for one is, up to constants,
We set both derivatives to zero:
They give the optimal encoder:
At these are and , the mean and variance of the exact posterior by the conditional formula, so the bound is tight. Write , the same for every . With , has and over . Averaging the closed-form KL and the expected squared error above gives
The table measures distortion by this squared error, which is up to an additive constant. At , and , so and the squared error is :
| rate (nats) | distortion | |||
|---|---|---|---|---|
| 0.25 | 0.976 | 0.024 | 1.89 | 0.025 |
| 1 | 0.909 | 0.091 | 1.20 | 0.100 |
| 4 | 0.714 | 0.286 | 0.55 | 0.376 |
| 16 | 0.385 | 0.615 | 0.13 | 1.032 |
Raising pulls the mean toward 0 and the variance toward 1, so the code says less and the reconstruction gets worse. At the distortion, 1.03, is close to the data variance 1.1: the code carries almost nothing. Lowering buys sharper reconstructions with a higher rate.
β moves a VAE along the rate–distortion curve
A high rate does not mean a code far from the prior. Here the aggregate posterior is . At its variance is 1.071 and its KL to the prior is 0.001 of the 1.89 nats, so almost all of the rate is information about . Prior samples suffer only when the aggregate posterior leaves the prior or the decoder is wrong where the prior puts mass. In this toy the decoder is fixed and exact, so prior samples stay exact for every ; in a jointly trained VAE a small also weakens the penalty on the mismatch, and samples can get worse.
What β buys and what it does not#
Higgins et al. (2017) report that makes single latent coordinates track single factors of variation, such as the position, scale and rotation of a sprite. They call this disentanglement: a latent unit is sensitive to one generative factor and relatively invariant to the others. On CelebA with , single units turn the head, change the smile or the hair while the rest of the face stays; in a plain VAE the unit that turns the head also changes the expression and other attributes (their Figure 1).
The proposed mechanism is the pressure to spend little rate: a factorized prior is cheapest to match with a posterior whose coordinates are independent. The effect is not guaranteed. Locatello et al. (2019) prove that without supervision or inductive biases disentanglement cannot be identified from data, and in more than 12,000 trained models find that random seeds and hyperparameters matter more than the choice among disentangling objectives. Burgess et al. (2018) replace the fixed weight by a target rate that grows during training, maximizing , so that the code is allowed one more nat at a time. What reliably controls is the rate.
VQ-VAE: a discrete latent code#
Start from k-means. Its encoder maps a point to the one-hot index of the nearest centre, and its decoder maps the index back to that centre: an autoencoder with a discrete code. Sampling an index uniformly and decoding it is a valid generative model, but a poor one, since it can only produce centres (He, 2024, lecture 2).
The VQ-VAE (van den Oord, Vinyals and Kavukcuoglu, 2017) makes this deep and spatial. The encoder outputs a map of vectors of shape , and each vector at position is replaced by the nearest of learned codebook vectors before it reaches the decoder:
The code of an image is the grid of indices : for the images below, 64 integers between 1 and 512 at the bottom level.
Vector quantization: the nearest codebook vector
What happens to the KL term? With a categorical posterior over codes and a uniform prior,
The identity is one line: . The VQ-VAE’s posterior is one-hot at , so its entropy is zero and the KL is per position, a constant (Isachenko, 2025, lecture 4). The KL term drops out, and the VQ-VAE trains as an autoencoder with a quantized bottleneck.
Training through the argmin#
The argmin has no useful gradient: a small change of either keeps the same or jumps to another. The VQ-VAE uses the straight-through estimator (Bengio, Léonard and Courville, 2013): the forward pass feeds to the decoder, and the backward pass copies the gradient with respect to to unchanged. In code it is one line, z_q = z_e + (z_q - z_e).detach(), whose value is and whose derivative is that of .
The copy is a surrogate. Inside a cell the quantizer is constant, so its true Jacobian is zero, and on a cell boundary it jumps; straight-through replaces that Jacobian by the identity. The decoder’s gradient, evaluated at , is a reasonable guess for the direction in which to move only when is close to . Two extra terms keep it close. With the stop-gradient, which passes its argument forward and has zero derivative, and , the loss summed over positions is
The reconstruction term trains the decoder and, through the copy, the encoder. The codebook term moves toward the encoder output and does not touch the encoder. The commitment term moves the encoder output toward and does not touch the codebook; without it the encoder outputs can drift away faster than the codebook follows. The paper uses and reports that results are robust to it.
Worked example: one quantization step#
Take , , the codebook , , and one encoder output , the red point of the figure. The squared distances are
The nearest vector is , so the decoder receives and the code is the index 2. The codebook term is and the commitment term : the same distance, with gradients sent to different places. If the decoder’s loss has gradient with respect to , the encoder receives at plus the commitment gradient
which points from toward , so a descent step moves toward .
The codebook as online k-means#
The codebook term moves each toward the encoder outputs assigned to it: the update of k-means. The appendix of the VQ-VAE paper replaces it by exponential moving averages. Each code keeps a count and a sum , updated with the outputs assigned to it in the batch:
with , and the codebook term leaves the loss. Each is then a running mean of its cell, the k-means centroid computed online. With and , so that , and a batch of two outputs and assigned to it, the update gives , and : a small step toward the batch mean .
Where the prior went#
During training the prior is uniform, and sampling the indices independently and uniformly would give an image of random patches. The positions of a code grid are not independent, so the prior must model their joint distribution (He, 2024, lecture 2). The VQ-VAE fits it after the autoencoder: encode the training set into grids of indices and train an autoregressive model on them, a PixelCNN in the paper, which predicts each index from the ones before it. Generation samples a grid from this prior and decodes it.
The split divides the work. The autoencoder handles the pixels, and the prior models a grid that is tens of times smaller and made of symbols, where autoregressive models are strong (autoregressive models). The same grids, now called image tokens, are what transformer and diffusion priors model later in the course.
VQ-VAE-2: two levels of codes#
A single grid has to carry both the global layout and the fine texture. VQ-VAE-2 (Razavi, van den Oord and Vinyals, 2019) uses a coarse top grid for the layout and a finer bottom grid for detail, quantized after seeing the top. For ImageNet at the grids are and with 512 codes each; FFHQ at uses three levels. The prior is hierarchical too: an autoregressive model over the top codes, with self-attention, and a conditional one over the bottom codes given the top.
A small VQ-VAE-2: two code maps
How much does the code compress? A small version for CIFAR-10 images uses a top grid and an bottom grid with 512 codes each:
| Quantity | Value |
|---|---|
| image, bytes | 24,576 bits |
| code, indices of bits | 720 bits |
| ratio | about 34 |
| sequential sampling steps, subpixels against codes | 3072 against 80 |
| at : subpixels against codes | 196,608 against 5120 |
The prior samples 80 indices one after another instead of 3072 subpixels.
A third change to the VAE keeps the Gaussian code and replaces the pixel-wise likelihood by the exact likelihood of a normalizing flow conditioned on , which can model dependencies between pixels for a given code. VAPNEV (Agrawal and Dukkipati, 2016) does this with a real NVP flow; it needs the flows of a later section and appears there as an application of flow architectures.
Where it breaks: dead codes#
A code that no encoder output selects gets no update and stays where it was initialized: a dead code. Under the codebook loss its term is absent from the sum; under the EMA, multiplies both and by , which leaves where it was. Its cell keeps taking no outputs, so it stays dead, and the effective codebook shrinks.
A toy run shows the size of the effect. The encoder outputs are four small blobs at with standard deviation 0.1, and the 64 codes start from , so most of them start far from every output. After 500 EMA steps:
import numpy as np
def run(restart, steps=500, K=64, B=256, gamma=0.99, seed=0):
rng = np.random.default_rng(seed)
blobs = lambda n: rng.normal(scale=0.1, size=(n, 2)) + rng.choice([-0.3, 0.3], size=(n, 2))
e = rng.normal(size=(K, 2)) # codebook drawn from N(0, I)
N, m, last = np.ones(K), e.copy(), np.zeros(K) # EMA counts, sums, last use
for t in range(1, steps + 1):
z = blobs(B) # encoder outputs
k = ((z[:, None] - e[None]) ** 2).sum(-1).argmin(1)
n = np.bincount(k, minlength=K)
s = np.zeros((K, 2)); np.add.at(s, k, z)
N, m = gamma * N + (1 - gamma) * n, gamma * m + (1 - gamma) * s
e = m / N[:, None]
last[n > 0] = t
if restart and t % 20 == 0: # restart codes unused for 20 steps
dead = last < t - 20
e[dead] = z[rng.choice(B, dead.sum())]
N[dead], m[dead] = 1.0, e[dead]
z = blobs(4096)
k = ((z[:, None] - e[None]) ** 2).sum(-1).argmin(1)
return np.unique(k).size, ((z - e[k]) ** 2).sum(1).mean()
for restart in (False, True):
used, err = run(restart)
print(f"restart={restart}: codes used {used} of 64, quantization error {err:.4f}")
# restart=False: codes used 25 of 64, quantization error 0.0056
# restart=True: codes used 64 of 64, quantization error 0.0024
Without restarts 39 of the 64 codes are dead, and the mean squared quantization error is more than twice what the full codebook achieves. Restarting unused codes at recent encoder outputs, as in Jukebox (Dhariwal et al., 2020), revives all of them. Looking codes up in a low-dimensional, normalized space, as in ViT-VQGAN (Yu et al., 2022), attacks the same problem from the other side. Implementations often add a small constant to the counts so that unused codes do not divide by zero; that keeps the arithmetic safe and revives nothing.
What changed#
| VAE | β-VAE | VQ-VAE / VQ-VAE-2 | |
|---|---|---|---|
| code | continuous Gaussian | continuous Gaussian | grid of indices into a codebook |
| objective | ELBO | reconstruction − β · KL | reconstruction + codebook + commitment |
| prior | fixed | the same, weighted by | uniform in training, then a learned autoregressive model |
| gradient through the code | reparameterization | reparameterization | straight-through copy |
| typical trouble | blur, holes in the prior | the trade-off itself | dead codes, slow sequential prior |
The β-VAE moves along the VAE’s rate–distortion curve without leaving it. The VQ-VAE leaves it: it gives up the likelihood bound during training, and in exchange the prior becomes a separate model as strong as we can afford.
What you should remember#
- β-VAE minimizes distortion + β · rate; β > 1 gives a lower rate and worse reconstructions, and disentanglement is not guaranteed.
- Rate = mutual information + KL from the aggregate posterior to the prior; a high rate is mostly information.
- VQ-VAE: nearest codebook vector, constant KL of per position, straight-through gradient, codebook and commitment terms.
- The EMA codebook update is online k-means; dead codes need restarts.
- The prior over code grids is learned afterwards by an autoregressive model; VQ-VAE-2 uses a coarse and a fine grid.
Notebook#
The VQ-VAE part follows the VQ-VAE-2 notebook of the HSE-LAMBDA Deep Generative Models repository. It has no saved outputs, so it documents the procedure only.
- Quantizer: distances to all 512 codebook vectors through , the EMA update with decay 0.99, the commitment distance and the straight-through line. The codebook is a buffer moved only by the EMA. Its counts start at 0 while its sums start at the random codebook, so after the first update an unselected code is divided by a smoothed count of about and its norm grows about times. In our own toy run of this update, not a notebook output, only 2 or 3 of the 512 codes were selected between steps 2 and 1000; starting the counts at 1 avoids the jump.
- Model: residual encoders that downsample CIFAR-10 by 4 to an bottom map and by 2 more to a top map, 64-dimensional codes, and a decoder that receives the upsampled top codes with the bottom codes. Training: MSE plus times the commitment term, Adam at , batch 32, five epochs.
- Priors: two PixelCNNs of seven masked layers without gating, an unconditional one for the top codes and a conditional one for the bottom codes. The condition is mixed into the input before the first type-A mask, so the mask also hides it at the position being predicted; we checked by differentiating a re-implementation. The condition should enter every layer unmasked, as in the conditional Gated PixelCNN. The plain stack also has the blind spot.
- Sampling: 16 sequential steps for the top grid and 64 for the bottom grid, each rerunning the network on the whole grid.
save_image(..., range=(-1, 1))uses an argument that torchvision renamed tovalue_range.
The β-VAE has no trained example: the VAE notebook has a beta argument but trains only with .
Next#
Two grids of samples, one from a β-VAE and one from a VQ-VAE, look different: one is smoother, the other sharper but sometimes broken. The VQ-VAE’s ELBO is not even comparable with the β-VAE’s. The next note starts the Evaluation section, which scores a generator by its samples alone.
References#
- I. Higgins, L. Matthey, A. Pal, C. Burgess, X. Glorot, M. Botvinick, S. Mohamed, A. Lerchner. β-VAE: Learning basic visual concepts with a constrained variational framework. ICLR, 2017. Section 1: the definition of disentanglement; Figure 1: CelebA latent traversals.
- A. Alemi, B. Poole, I. Fischer, J. Dillon, R. A. Saurous, K. Murphy. Fixing a broken ELBO. ICML, 2018. Rate and distortion.
- C. P. Burgess, I. Higgins, A. Pal, L. Matthey, N. Watters, G. Desjardins, A. Lerchner. Understanding disentangling in β-VAE. arXiv, 2018.
- F. Locatello, S. Bauer, M. Lucic, G. Rätsch, S. Gelly, B. Schölkopf, O. Bachem. Challenging common assumptions in the unsupervised learning of disentangled representations. ICML, 2019.
- A. van den Oord, O. Vinyals, K. Kavukcuoglu. Neural discrete representation learning. NeurIPS, 2017. The EMA codebook update is in appendix A.1.
- A. Razavi, A. van den Oord, O. Vinyals. Generating diverse high-fidelity images with VQ-VAE-2. NeurIPS, 2019.
- Y. Bengio, N. Léonard, A. Courville. Estimating or propagating gradients through stochastic neurons for conditional computation. arXiv, 2013. The straight-through estimator.
- K. He. Deep Generative Models, MIT 6.S978, fall 2024. Lecture 2: k-means as an autoencoder, VQ-VAE and tokenizers.
- R. Isachenko. Deep Generative Models, MIPT and YSDA, autumn 2025. Lecture 4: discrete latents and the VQ-VAE.
- P. Dhariwal, H. Jun, C. Payne, J. W. Kim, A. Radford, I. Sutskever. Jukebox: A generative model for music. arXiv, 2020. Random restarts of unused codes.
- J. Yu, X. Li, J. Y. Koh, H. Zhang, R. Pang, J. Qin, A. Ku, Y. Xu, J. Baldridge, Y. Wu. Vector-quantized image modeling with improved VQGAN. ICLR, 2022. Factorized, normalized codebook lookup.
- S. Agrawal, A. Dukkipati. Deep variational inference without pixel-wise reconstruction. arXiv:1611.05209, 2016. VAPNEV.