A VQ-VAE squeezes a picture or a sound into a short string of symbols, each taken from a fixed list, like a paint-by-numbers palette. A decoder paints the picture back from those symbols. Because the result looks like a sentence of words, a language-style model can read and write images and audio. This is the bridge between pixels or waveforms and text-style generation.
After this lesson, you will be able to:
Explain why a fixed list of symbols (a codebook) suits data that is naturally made of pieces, such as words, sound frames and image patches
Walk through the three parts of the VQ-VAE training score (rebuild, move the codebook, commit the encoder) and say why each is needed
Explain the straight-through shortcut: it lets training pass through a lookup that has no slope
Spot dead codes (most of the list never used) and fix them with running-average updates and resampling
Aaron van den Oord and colleagues at DeepMind introduced the VQ-VAE in 2017, in a paper called "Neural Discrete Representation Learning." The motivation was simple: language is discrete, audio splits naturally into frames, and many kinds of meaning are categories rather than smooth quantities. A VAE forces everything into Gaussian latents, which is powerful but loses the discrete structure of the data.
The encoder takes the input x (say, an image) and produces a continuous latent map z_e(x) of shape (H, W, D), for example an 8×8 grid of 64-number vectors. Each position in the grid holds one continuous vector that we will quantize.
#Step 2: Nearest-neighbor lookup against the codebook
The codebook is a learned matrix E of shape (K, D): K codes, each with D numbers. For every position in z_e, find the closest codebook entry by ordinary straight-line (L2) distance and snap to it.
k∗=argkmin∥ze−ek∥22⇒zq=ek∗
Move an encoder output around the plane and watch it snap to its nearest codebook entry.
Loading visualization...
Do: Drag the point around the plane, and press the random-latent button a few times.
Notice: The snapped entry changes only when the point crosses a straight border between two codes. Inside one cell, the output does not change at all.
Why: The nearest-code rule splits the plane into flat-sided cells. The snap is computed exactly; the blurry and sharp panels are drawn illustrations.
Each code ends up owning a region of the plane, and the region has flat sides. Open the derivation to see why the borders are straight lines (planes in higher dimensions).
#Step 3: Decoder reconstructs from the quantized latent
The decoder takes z_q (the quantized latent grid) and rebuilds x̂. The rebuild loss is the usual pixel-by-pixel squared error (MSE) or binary cross-entropy (BCE).
Picture first. The training score has three parts, each with its own job. (1) Rebuild: the decoder's picture should match the input. (2) Move the codebook: each code drifts toward the encoder outputs that chose it, so the palette fits the data. (3) Commit: each encoder output is pulled toward the code it chose, so it does not wander off. The symbol sg[·] (stop-gradient) marks which side is held still in each term, so each term moves exactly one thing.
The commitment-loss weight β is typically 0.25, the default from the 2017 paper, and it works for most problems.
The three terms give the encoder, the decoder and the codebook different jobs. Open the derivation to see exactly which parameter each term moves, and in which direction.
Each grid position holds one of K codes, so it carries at most log2 K bits (a bit is one yes-or-no answer). The arithmetic below shows how a 256 by 256 image can become only 1024 tokens.
After training, a second model learns which code grids look like real data. The original paper uses an autoregressive prior: it predicts each code from the codes before it, the same way a language model predicts the next word. Open the derivation to see how its loss, a number of bits, is built.
The snap has no usable slope. The argmin (pick the nearest) and lookup step has zero gradient almost everywhere, so if you pass the learning signal back through it naively, the encoder gets nothing to learn from.
The straight-through shortcut works like this. Going forward, output z_q. Going backward, copy the gradient that arrived at z_q directly to z_e, as if the snap were the identity function (output equals input).
∂ze∂L≈∂zq∂L
That z_e + (z_q - z_e).detach() line is the entire trick. The forward output equals z_q (the quantized version) but the gradient flows through z_e (the continuous encoder output).
Why does that one line give the right forward value and the right backward signal? Open the derivation to check both, line by line.
The codebook loss ||sg[z_e] - e||² learns the codebook entries by gradient descent. It works, but it is slow and unstable: codes that are rarely picked drift around or never update.
Exponential moving average (EMA) updates replace the codebook gradient with a direct running average that gives recent batches more weight. Every batch, each codebook entry e_k moves toward the average of the encoder outputs assigned to it.
EMA updates are now the default. They remove the codebook-loss term and train more smoothly than gradient steps (a small smoothing term is usually added to the count). EMA does not revive a dead code: a code that wins no points gets no update and stays where it is. That is why code resampling is added on top, as the cell below shows.
The EMA update of the codebook is a running average of the vectors each code has been given. Open the derivation to see the weights. The derivation unrolls the EMA recursion step by step, and the centroid idea comes from Clustering: K-Means, DBSCAN & Hierarchical.
How do you see dead codes in one number? Count how often each code is chosen over a batch, call the share of code k p_k, and compute the perplexity of that usage. It reads as the effective number of codes in use.
The cell below trains a toy 16-code codebook with EMA twice, once alone and once with code resampling, and prints how many codes each run uses. Run it before you read the explanation.
pythonplayground.py · Pyodide
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Tests: Verify that EMA alone leaves some of the 16 codes unused, that adding code resampling uses all 16, and that resampling gives the lower reconstruction error. The cell asserts the first two.
For audio compression, a single codebook can't represent fine-grained signals at low bitrates. Residual VQ quantizes z_e with a first codebook, computes the residual z_e - z_q, quantizes the residual with a second codebook, and so on. The final latent is the sum of all stages. EnCodec and SoundStream stack several quantizer stages (EnCodec uses between 2 and 32 depending on the target bitrate) at about 75 frames per second for 24kHz audio (each frame is one token per stage).
Each stage works on what the previous stages left over. Open the derivation to see why the stages add up to z_e and what the bitrate is.
Add an adversarial loss + LPIPS perceptual loss to VQ-VAE training. The reconstructions become much sharper because the discriminator pushes the decoder to produce realistic textures. Then train a transformer prior over the resulting code sequence. This was the architecture behind DALL-E mini's image tokens, and some Latent Diffusion experiments also used it as a first stage.
Mentzer et al. 2023 noticed that you can drop the codebook entirely. Instead, project z_e to a low-dimensional space (say 5-D), bound each dimension to [-1, 1], and round each scalar to one of L levels. The "codebook" is the implicit lattice — no explicit table, no codebook loss, and no table entries to go dead. Empirically matches VQ-VAE quality on many tasks with a fraction of the implementation complexity.
FSQ replaces the learned table by a grid, so its size comes from a product. Open the derivation to see how the product appears.
What Do You Think?
You train a VQ-VAE with codebook size K=8192, but inspecting the assignment histogram shows only ~200 codes ever get used. What's most likely happening, and how do you fix it?
The fix is EMA codebook updates plus code resampling. The problem is dead codes: after a few epochs a small subset of codes captures most of the encoder outputs, and the rest drift far from the data and are never selected again. EMA updates make each code follow the center of its assigned points steadily. Code resampling (restart any code whose count falls below a threshold at a random encoder output) keeps the whole codebook in use.
VQ-VAE replaces continuous Gaussian latents with a finite codebook of discrete codes. Each input gets snapped to its nearest codebook entry, turning the latent into a categorical symbol that downstream models (transformers, LLMs) can predict like a token.
Three loss terms (reconstruction, codebook, commitment) train the encoder, decoder, and codebook jointly — Modern implementations replace the codebook loss with EMA updates for stability; commitment loss with β ≈ 0.25 keeps the encoder anchored to the codes it picks.
The straight-through estimator is the trick that makes backprop work through the non-differentiable lookup — Forward pass quantizes; backward pass copies the gradient at z_q directly to z_e as if the quantization were the identity function.
Dead codes are the standard failure mode. A few codes capture all assignments, the rest drift dead. EMA updates plus code resampling are the production-standard fixes.
VQ-VAE underlies modern multimodal generation. DALL-E 1's image tokenizer, EnCodec/SoundStream's audio tokenizers, and the visual streams of Chameleon, Show-o, and Janus all rely on a discrete tokenizer in the VQ family. FSQ is the simpler 2023+ alternative when you don't need a learnable codebook.