Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Codes from a fixed dictionary
Instead of describing each patch of an image with any real numbers it likes, a VQ-VAE must pick the closest entry from a fixed dictionary of, say, 512 learned prototypes, and pass on only its index. The image becomes a small grid of integers, like words in a sentence. That makes it easy to compress, and easy to model with the same next-token predictors used for language. The catch is that some dictionary entries never get picked and stop learning. In the demo, change the codebook size and where codes start, and count how many are used.
Discrete tokenizers built on VQ-VAE compress images, audio and video for transformers; SoundStream-style codecs and VQ tokens are used for low-bandwidth telemetry and imagery links.
- 1. A VQ-VAE's latent is…
- 2. Each encoder output is replaced by…
- 3. A dead code is one that…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.By hand
- Quantisation: k = argmin_j ‖z_e − e_j‖, z_q = e_k. A 32×32 grid of codes from a 512-entry codebook holds 32 · 32 · log₂ 512 = 9216 bits.
- Loss: log p(x | z_q) + ‖sg[z_e] − e‖² + β ‖z_e − sg[e]‖², with sg the stop-gradient and β = 0.25.
- The codebook term moves codes toward encoder outputs; the commitment term keeps the encoder near its codes. They have the same value and differ only in which side receives the gradient.
- Straight-through gradient: z_q = z_e + sg[z_q − z_e] passes the decoder’s gradient to the encoder unchanged.
- EMA updates (used in practice): N_j ← γ N_j + (1 − γ) n_j, S_j ← γ S_j + (1 − γ) Σ z_e assigned to j, e_j = S_j / N_j with γ ≈ 0.99.
- Perplexity exp(−Σ p_j ln p_j) of code usage: K when all codes are used equally. Codes used 1, 2, 2 times give 1.89 of 3.
- As a VAE: the posterior is one-hot (deterministic), the prior uniform during training, so the KL is the constant log K and drops out. A learned prior (PixelCNN, transformer) is fitted afterwards on the code grids.
- VQ-VAE-2: on 256×256 images, a 32×32 top grid (8× downsampling, global structure) and a 64×64 bottom grid (4×, details), each with its own autoregressive prior; samples are drawn top first.
- 1. The commitment loss trains…
- 2. Bits in a 16×16 grid with 256 codes:
- 3. The VQ-VAE's KL term is…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.Training a VQ-VAE
Exercise 1.
- Nearest-neighbour quantisation.
- The codebook and commitment losses, and the straight-through estimator.
- EMA codebook updates and code-usage perplexity.
Practice.
- Use EMA updates (decay 0.99) and initialise the codebook from encoder outputs (k-means on the first batches).
- Monitor perplexity and dead codes; reset codes unused for many steps to random recent encoder outputs (Jukebox, SoundStream).
- L2-normalise encoder outputs and codes (cosine distance) and use a low-dimensional lookup space (ViT-VQGAN, 2022) for better usage.
- Alternatives without a learned codebook: finite scalar quantisation (FSQ, 2023) and lookup-free quantisation (MAGVIT-v2, 2023).
- Residual VQ (SoundStream, RQ-VAE) stacks codebooks that quantise what the previous level left over.
import torch, torch.nn.functional as F
def vq(z_e, codebook, beta=0.25): # z_e: (B, d, H, W), codebook: (K, d)
z = z_e.permute(0, 2, 3, 1).reshape(-1, z_e.shape[1])
idx = torch.cdist(z, codebook).argmin(1)
z_q = codebook[idx].view(z_e.shape[0], z_e.shape[2], z_e.shape[3], -1).permute(0, 3, 1, 2)
loss = F.mse_loss(z_q, z_e.detach()) + beta * F.mse_loss(z_e, z_q.detach())
z_q = z_e + (z_q - z_e).detach() # straight-through
return z_q, loss, idx- 1. A standard fix for dead codes:
- 2. FSQ and LFQ avoid…
- 3. Residual VQ quantises…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Why codes die. A code receives a codebook update only when it is the nearest neighbour of some encoder output. Codes initialised far from the data, or overtaken by neighbours, are never selected. The codebook gradient for them is zero, and under EMA their counts simply decay, so they stay where they are. The effective codebook shrinks, the bit rate log₂(used codes) falls, and reconstruction suffers.
Straight-through as a biased estimator. Treating quantisation as the identity in the backward pass is exact only if the decoder’s gradient at z_q equals its gradient at z_e. It is biased, but low-variance and works well when codes are dense near the encoder outputs, which the commitment loss encourages. Alternatives include Gumbel-softmax relaxations (used by DALL·E’s dVAE) and rotation tricks that carry gradient information through the codebook.
Rate and distortion. With K codes per vector the rate is log₂ K bits. Shannon’s distortion-rate bound for d-dimensional unit Gaussians is d · 2^(−2R/d): at 8 bits in 4-D no quantiser can beat squared error 0.25. A full 256-entry codebook approaches the bound, while splitting the bits over levels (two 16-entry codebooks) uses a constrained, product-like code that is cheaper to store and search but less efficient.
Hierarchy in VQ-VAE-2. The top grid captures global layout, the bottom grid local texture conditioned on the top. Autoregressive priors over a 32×32 and a 64×64 grid are far cheaper than over 256×256×3 pixels; Razavi et al. reported samples competitive with BigGAN on ImageNet with better diversity.
- 1. Dead codes stay dead under EMA because…
- 2. Straight-through gradients are…
- 3. Shannon's bound for 4-D unit Gaussians at 8 bits:
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.Why do codebooks collapse, and how much do restarts and hierarchical codes help?
History.
- A. van den Oord, O. Vinyals and K. Kavukcuoglu, “Neural discrete representation learning” (NeurIPS 2017).
- A. Razavi, A. van den Oord and O. Vinyals, “Generating diverse high-fidelity images with VQ-VAE-2” (NeurIPS 2019).
- P. Esser, R. Rombach and B. Ommer, “Taming transformers for high-resolution image synthesis” (VQGAN, CVPR 2021); N. Zeghidour et al., “SoundStream” (2021).
Exercise 2. Two parts on stand-ins for encoder outputs (held fixed, so only the codebook learns).
- Part A (collapse): 4000 2-D points in 16 blobs on a ring of radius 4. A 32-entry codebook trained for 300 steps with batches of 256, starting at N(0, 0.1²) near the empty origin: plain gradient updates, EMA updates (decay 0.95), EMA with restarts of unused codes to random batch points, and EMA from a codebook initialised at data points.
- Part B (levels): 4-D Gaussian vectors, 2000 for fitting (k-means) and 2000 held out; 4 bits (16 codes), 8 bits in one 256-entry codebook, and 8 bits as two residual levels of 16 codes.
| codebook training | codes used (of 32) | perplexity | squared error |
|---|---|---|---|
| gradient | 5 | 4.98 | 2.058 |
| EMA | 7 | 6.95 | 1.119 |
| EMA + dead-code restarts | 32 | 30.75 | 0.117 |
| EMA from data initialisation | 32 | 28.55 | 0.125 |
| 4-D Gaussians, held-out error | bits per vector | codebook vectors | error |
|---|---|---|---|
| 16 codes | 4 | 16 | 1.412 |
| two residual levels of 16 | 8 | 32 | 0.519 |
| 256 codes | 8 | 256 | 0.431 |
| Shannon bound | 8 | – | 0.25 |
- Collapse is about initialisation and assignment: codes that start where no data is never win a nearest-neighbour contest, so gradient and EMA updates both left 25–27 of the 32 codes dead.
- Restarts and data initialisation fixed it, using every code and cutting the error by 9× (against EMA) to 18× (against gradient updates).
- Levels are a trade-off, not a free lunch: two 4-bit levels were far better than one 4-bit codebook, but at the same 8 bits a single 256-code codebook was 17% better. The residual code stores and searches 32 vectors instead of 256. Both were well above the Shannon bound.
- Seeds 1 and 2: gradient updates used 4 and 5 codes, EMA 5 and 7; restarts used all 32 (errors 0.122 and 0.120). Held-out errors: 256 codes 0.433 / 0.437, residual 0.484 / 0.511.
- Caveat: encoder outputs were fixed. In a real VQ-VAE the encoder also moves toward its codes through the commitment loss, which can rescue some codes, or strand more.
VQ-VAEs in AI, robotics and aerospace
- Tokenisers for generative transformers: VQGAN and its successors turn images and video into tokens for autoregressive and masked transformers; robot foundation models tokenise images the same way.
- Neural audio and telemetry codecs: SoundStream and EnCodec use residual VQ to send speech at 1.5–12 kbps; the same idea compresses sensor streams over constrained links.
- Discrete world models: agents such as DreamerV2/V3 and IRIS model environments with discrete latent codes.
References
- A. van den Oord, O. Vinyals and K. Kavukcuoglu (2017). “Neural discrete representation learning.” NeurIPS.
- A. Razavi, A. van den Oord and O. Vinyals (2019). “Generating diverse high-fidelity images with VQ-VAE-2.” NeurIPS.
- P. Esser, R. Rombach and B. Ommer (2021). “Taming transformers for high-resolution image synthesis.” CVPR.
- N. Zeghidour et al. (2021). “SoundStream: an end-to-end neural audio codec.” IEEE/ACM TASLP.
- J. Yu et al. (2022). “Vector-quantized image modeling with improved VQGAN.” ICLR.
- F. Mentzer, D. Minnen, E. Agustsson and M. Tschannen (2023). “Finite scalar quantization: VQ-VAE made simple.” ICLR 2024.
- L. Yu et al. (2023). “Language model beats diffusion: tokenizer is key to visual generation” (MAGVIT-v2). ICLR 2024.