TL;DR
The VQ-VAE is a generative model that stores each input as a short list of whole-number codes instead of a list of smooth decimal numbers. The encoder picks, for every position in its output, the nearest entry of a learned table of vectors, the codebook, and the decoder rebuilds the input from those picked entries. The paper shows that these discrete codes keep enough information for good reconstructions, and that a separate autoregressive model trained on the codes can generate new images, speech and video. Builds on: Variational Autoencoder, Vector Quantization, Straight-Through Estimator, Autoregressive Model · Leads to: MaskGIT: Masked Generative Image Transformer, Genie: Generative Interactive Environments
Why it mattered
The idea that a model can learn a discrete code, one that is a list of symbols instead of a continuous vector, now sits under many image and video generators. Systems that turn a picture into a short sequence of tokens and then model that sequence with a transformer use this same two-stage recipe: a discrete autoencoder first, then a prior over its codes. The paper reports that its speech model learned sound units close to phonemes with no labels, and it fitted a PixelCNN prior over its 32 by 32 codes for 128 by 128 colour images. Its CIFAR10 numbers were close to a continuous VAE, which made discrete latents look like a practical choice rather than a curiosity.
The problem
A variational autoencoder (VAE) encodes an input into a continuous latent vector and decodes it back. Its training is well understood when the latent is a Gaussian, because the reparameterisation trick gives low-variance gradients. Discrete latents break that path: a choice among categories has no gradient. Earlier discrete-latent methods used high-variance score-function estimators or relaxations such as the Gumbel-softmax trick, and they were tested mostly on small data such as MNIST with few latent dimensions.
A second problem is posterior collapse. When the decoder is strong, for example an autoregressive model that can predict pixels from earlier pixels, the VAE learns to ignore the latent code, and the code carries no information. The paper's aim is a model that uses discrete codes, trains with low-variance gradients, and does not collapse.
The paper also notes that a VAE usually has a fixed prior, such as a standard normal. Here the prior over codes is first uniform and then learned after training, which makes the generative step a separate, stronger model.
How it works
Take the paper's core loop on one input, with tiny numbers. The real paper uses a codebook of K = 512 entries, but K = 4 and two numbers per vector are enough to trace the idea.
- Input. An image or audio clip
xgoes into the encoder. The encoder outputs a continuous vector, herez_e(x) = (0.9, 0.2). Check: it is still just two decimal numbers, nothing discrete yet. - Codebook. The model keeps a table of four vectors:
e1 = (0, 0),e2 = (1, 0),e3 = (1, 1),e4 = (0, 1). These are learned parameters, the embedding space. - Nearest entry. Measure the squared distance from
z_e(x)to each entry. Toe1: 0.81 + 0.04 = 0.85. Toe2: 0.01 + 0.04 = 0.05. Toe3: 0.01 + 0.64 = 0.65. Toe4: 0.81 + 0.64 = 1.45. The smallest ise2, so the code isk = 2. Check: 0.05 is the smallest of the four sums. - Quantise. The code is replaced by its entry,
z_q(x) = e2 = (1, 0). The decoder sees only this vector. This is the bottleneck: the input is now described by one index out of four, which is 2 bits. Check: log2 of 4 is 2. - Decode. The decoder turns
(1, 0)into a reconstructionx_hat. Its error gives a reconstruction loss. - Backward pass. The arg-min in step 3 has no gradient, so the paper copies the decoder's gradient straight to the encoder. Suppose the decoder's gradient with respect to its input is
(0.4, -0.3). The encoder receives that same(0.4, -0.3)as its gradient. Check: the encoder moves its output by a step opposite to that gradient, and that may change which entry is nearest next time. - Move the codebook. The reconstruction loss does not reach the codebook at all, because step 4 blocked it. So a second term pulls the chosen entry
e2toward the encoder outputz_e(x). Check:e2moves from(1, 0)toward(0.9, 0.2). - Commit the encoder. A third term, weighted by beta, pulls the encoder output toward its chosen entry, so the encoder does not drift away from the codebook. The paper uses beta = 0.25.
- Generate later. After training, a prior is fitted over the codes. Sample a code sequence from it, look up the entries, and run the decoder. Nothing from the input is needed.
flowchart LR
X[Input x] --> E[Encoder]
E --> Z[Continuous output z_e]
Z --> Q{Nearest codebook entry}
C[Codebook of K vectors] --> Q
Q --> ZQ[Chosen entry z_q]
ZQ --> D[Decoder]
D --> XH[Reconstruction]
Z -. straight-through gradient .-> E
The math
A codebook is a matrix with K rows . Each row is one entry, and K is the number of discrete symbols.
Step 3 in symbols: choosing the code
The posterior over the code is one-hot on the nearest entry:
Here is the encoder's output, and the arg-min is the index of the entry closest to it in Euclidean distance. The paper calls this a deterministic proposal: no sampling happens.
Step 4 in symbols: the quantised input
The decoder receives .
Why the KL term is a constant
The prior over codes is uniform, . Since is one-hot on a single , the KL divergence reduces to
The value does not depend on the encoder, so it drops out of training.
Step 6 in symbols: the straight-through gradient
The map from to has zero gradient almost everywhere, so the paper uses
This is the straight-through estimator with the forward value kept and the gradient copied across.
Steps 7 and 8 in symbols: the full loss
The paper writes the reconstruction term as ; in training it acts as a reconstruction error to be made small, so read its sign as the usual negative log-likelihood. The symbol is the Stop-Gradient operator: it is the identity in the forward pass and blocks gradients in the backward pass. The first term trains the decoder and, through the straight-through copy, the encoder. The second moves the chosen codebook entry toward the encoder output. The third, weighted by , keeps the encoder output close to its entry. The paper reports that results barely changed for beta between 0.1 and 2.0, and uses 0.25.
Step 7 alternative: moving averages
The second term can be replaced by an exponential moving average over the encoder outputs assigned to each entry. For entry with outputs at step , the paper's updates are
with . This is the online form of the k-means update, where each entry becomes the mean of the outputs assigned to it.
Step 9 in symbols: the prior
After training, an autoregressive model is fitted over the code grid. Sampling runs in order, each code drawn given the earlier ones, and then the decoder maps the sampled codes to pixels or audio. The paper uses a PixelCNN for images and a WaveNet for audio, and it keeps the prior uniform while the VQ-VAE trains.
Worked examples
Use the codebook from the walkthrough: , , , . The encoder output is .
- Squared distance to : .
- Squared distance to : .
- Squared distance to : .
- Squared distance to : .
- All four distances tie, so the arg-min is ambiguous. Pick the smallest index, , which is a convention, not a property of the method.
- The decoder receives . The information kept is the index 1, which is 2 bits.
Interpretation: a point exactly between entries gives a tie, and the code loses which side it was on. Training pushes encoder outputs away from such ties, because the reconstruction gradient depends on which entry was picked.
The paper's image model uses K = 512 codebook entries.
- A single code index can take 512 values.
- The bits needed to store one index are .
- Since , , so each code costs 9 bits.
- The paper's second-stage model uses three latents of 9 bits each: bits in total, which the paper gives as 27 bits.
- Compare with a float32 number, 32 bits. Three codes together are 27 bits, so the whole global code is less than one float.
Interpretation: the discrete code's capacity is set by K. Doubling K adds one bit per latent, so the size of the codebook is a direct knob on how much each latent can say.
The paper compresses ImageNet images of size 128 by 128 by 3 colour channels into a 32 by 32 by 1 grid of codes, with K = 512.
- Original bits: , taking 8 bits per channel value.
- Code bits: codes, each 9 bits, gives bits.
- Ratio: .
- The paper prints this ratio as about 42.6. The exact quotient is 42.67, so the paper's figure is a slightly truncated version of the same arithmetic, and the order of magnitude is what matters.
- The PixelCNN then models a 32 by 32 grid of 512-valued codes, far smaller than the 128 by 128 by 3 pixel grid.
Interpretation: the code is about 40 times smaller in bits. The decoder must rebuild the detail, and the paper says the reconstructions look only slightly blurrier than the originals.
Try it: the speech model in the paper uses a 128-entry codebook that runs at 25 codes per second. How many bits per second does its code carry? Answer: each code takes bits, and 25 codes per second gives bits per second.
Common mistakes and tradeoffs
It is tempting to think a VQ-VAE is just an autoencoder with a rounding step. In fact the rounding has no gradient, so the paper needs the straight-through copy, the codebook loss and the commitment loss together. Without the codebook term, the entries never move toward the data and the bottleneck stays at its random starting point. The lesson is that the three loss terms each train a different part of the model.
It is tempting to think the prior is learned jointly with the autoencoder, since that is how most VAEs work. In fact the paper keeps the prior uniform during training and fits an autoregressive prior afterwards. The paper says joint training could strengthen the results but leaves it as future research. This split makes training simpler and the second stage flexible, at the cost of a code space that was not shaped for the prior.
It is tempting to think a larger codebook always helps. A larger K gives more bits per latent, but each entry then has to be learned from fewer encoder outputs. The paper's CIFAR10 result is that the discrete model (4.67 bits per dimension) comes close to the continuous VAE (4.51), not that it matches it.
When to use this: when the data is naturally symbolic or sequential, such as speech, text or image tokens, and when a separate prior over codes is wanted for generation. When not to use it: when the continuous Gaussian VAE is trainable and the latent geometry matters, for example for smooth interpolation. Alternatives include Gumbel-softmax relaxations, which keep the discrete choice differentiable with a temperature, and continuous VAEs with a learned prior.
Results
All numbers below are quoted from the paper's text.
- CIFAR10 likelihood. The continuous VAE reaches 4.51 bits per dimension, the VQ-VAE 4.67, and VIMCO with a categorical prior 5.14. All reported values are lower bounds on likelihood, so lower is better. The paper notes that its continuous VAE is comparable to a deep convolutional VAE reported at 4.54 bits per dimension on this dataset.
- Images. With K = 512 and a 32 by 32 latent grid, the paper reports reconstructions that look only slightly blurrier than the originals. The paper uses mean squared error over pixels and notes that a more perceptual loss, such as one using a GAN, could be used instead.
- Speech, phonemes. Each of the 128 latent values was mapped to its most likely phoneme among 41 phoneme classes. The accuracy was 49.3 percent, against 7.2 percent for a random latent space (the most likely phoneme for each latent value). The paper notes that the codes were learned without any phoneme labels.
- Speech, compression. The VCTK encoder reduces the waveform by 64 times. The larger-dataset model reduces it by 128 times, and chunks of 40,960 timesteps become 320 latent steps.
- Speaker conversion. The decoder takes a speaker identity as well as the code, so the same content can be voiced by another speaker. The paper shows this qualitatively with waveforms and sound samples.
Limits. The main likelihood comparison is on one dataset, CIFAR10, and each figure is a single value in the text with no error range. The sample quality for images, speech and video is judged from figures and linked audio, not scored. The prior is not trained jointly, and the video samples are generated in latent space and decoded afterwards. The paper's claim that discrete codes are as good as continuous ones rests on the CIFAR10 comparison, so it is a claim about likelihood on that dataset, not about every task.
Reading guide
- Section 1, Introduction. Read with Variational Autoencoder and Autoregressive Model in mind. The argument is that discrete codes suit language and speech and that a strong prior over them gives samples.
- Section 2, Related Work. Needs Reparameterization Trick and the Gumbel-softmax relaxation, Gumbel-Softmax Trick. The paper contrasts its method with those and with a score-function estimator.
- Section 3.1, Discrete latent variables. Needs Vector Quantization and the nearest-neighbour rule. Read with Categorical Distribution for the one-hot posterior.
- Section 3.2, Learning. Needs Straight-Through Estimator, Stop-Gradient and Dictionary Learning. Equation 3 is the loss in the math section above.
- Section 3.3, Prior. Needs Autoregressive Model. The paper names a PixelCNN for images and WaveNet for audio.
- Section 4.1, CIFAR10. Needs Variational Lower Bound (ELBO) and Kullback–Leibler Divergence to read the bits-per-dimension numbers.
- Section 4.2 and 4.3, Images and audio. Need Convolutional Neural Network, Transposed Convolution and Dilated Convolution for the encoder and decoder layouts.
- Appendix A.1, EMA updates. Needs Exponential Moving Average and K-Means Clustering.
Check yourself
QuestionWhy can gradients not flow through the nearest-entry step by default, and what does the paper do about it?Show answer
The step picks the arg-min among entries, a discrete choice. Almost everywhere its output does not change when the input changes slightly, so the derivative is zero. The paper uses the straight-through estimator: in the backward pass it copies the decoder's gradient with respect to onto , as if the step were the identity.
QuestionA codebook has K = 256 entries. How many bits does one code index carry, and how many bits do 64 codes carry together? Show the arithmetic.Show answer
One index takes bits, since . Sixty-four codes carry bits.
QuestionExplain why the KL term in the VQ-VAE objective can be left out when training the encoder, using the uniform prior.Show answer
With a uniform prior over the K entries and a one-hot posterior, the KL divergence equals for every input. It is a constant that does not depend on the encoder's parameters, so its gradient is zero and it has no effect on training.
QuestionA VQ-VAE is trained with beta = 0.25. A colleague raises beta to 2.0 and says the commitment pull on the encoder should now be eight times stronger. Is the colleague right, and what does the paper report about beta?Show answer
The commitment term is , so raising beta from 0.25 to 2.0 multiplies that term by 8, which does increase its pull. But the paper reports that results barely changed for beta between 0.1 and 2.0, so the change is not expected to matter much in practice. The reconstruction loss scale is the thing that really sets how strong the commitment should be.
QuestionAn engineer wants a discrete audio model that generates speech. The codes come at 25 per second from a 128-entry codebook. Using the paper's approach, what should be trained after the autoencoder, and why not train everything at once?Show answer
A prior over the code sequence, for example a WaveNet-style autoregressive model, should be trained after the autoencoder, so it can sample code sequences that decode to speech. The paper keeps the prior uniform during autoencoder training and fits it afterwards, and it leaves joint training as future work. Training separately keeps each stage simple, and the prior can then be a much stronger model than the codebook loss would allow.
Sources
- Aaron van den Oord, Oriol Vinyals, Koray Kavukcuoglu, "Neural Discrete Representation Learning", arXiv:1711.00937 (2017): https://arxiv.org/abs/1711.00937
- DOI for the same preprint: https://doi.org/10.48550/arXiv.1711.00937