Neural Discrete Representation Learning
- Publication
- NeurIPS 2017Conference
- First submitted to arXiv
- arXiv:1711.00937
Cite this paper · BibTeX
The citation identifies the linked source version. It cites the original paper and its authors.
@misc{imagegenerationvqvae2017,
title = {{Neural Discrete Representation Learning}},
author = {Aaron van den Oord and Oriol Vinyals and Koray Kavukcuoglu},
year = {2017},
eprint = {1711.00937},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/1711.00937}
}
Feed the model a recording of someone reading English aloud, and it spits out 25 integers per second, each between 0 and 127.
Nobody ever told it what a phoneme is. But map each of these 128 integers to the phoneme it most often shows up with, then use that to guess the phoneme labels for the whole recording, and you get 49.3% right. If the latent variables had nothing to do with what is being said, the best you could do is always answer the most common phoneme, which gets only 7.2%.
This is a small experiment from Section 4.3 of the VQ-VAE paper. The paper comes from DeepMind, and its first author, Aäron van den Oord, had finished PixelCNN and WaveNet only the year before, two autoregressive models for generating discrete sequences. This paper wants a VAE's latent variables to become a string of integers as well, so that van den Oord's own PixelCNN and WaveNet can sit on top of those integers and learn their distribution.
Defining the problem
Discrete latent variables are hard to train
What makes a VAE trainable is the reparameterization trick. When the latent variable is Gaussian, sampling can be written as , and the gradient flows back to the encoder through and . If the latent variable is "pick one of categories," that path is cut; the act of picking has no gradient.
Section 2 of the paper lists the approaches available at the time:
- NVIL, VIMCO: estimate the gradient directly with REINFORCE-style estimators, then use assorted tricks to push the variance down; VIMCO takes several samples at once.
- Concrete / Gumbel-Softmax: replace the discrete choice with a continuous distribution that has a temperature, and cool it down slowly during training. At high temperature the gradient has low variance but is biased; at low temperature it gets close to discrete and is unbiased, but the variance grows.
The authors' verdict is that none of these had caught up with continuous VAEs using Gaussian reparameterization, and most had only been evaluated on small datasets like MNIST, with fewer than 8 latent dimensions.
A decoder that is too strong throws the latent variables away
The other problem comes from the decoder. Autoregressive models like PixelCNN and WaveNet can learn the data distribution very well on their own. Put one behind a VAE as its decoder, and the usual result is that the KL term squeezes every posterior into the prior, and the decoder ignores the latent variables entirely and finishes the picture by itself. This is called posterior collapse.
So what the authors want comes with three conditions. The latent variables are discrete integers; training is as easy as for a continuous VAE; and with a powerful decoder attached, the latent variables still get used.
Solving the problem
Walking through one figure

Let's take the ImageNet setting from Section 4.2 and follow a image through the left half.
- Encode. The convolutional encoder shrinks the image to a feature map . Each position is a -dimensional vector, 1,024 vectors in all.
- Look up the nearest code. The model has a codebook , here with , and each row is a -dimensional code vector. Each of the 1,024 vectors finds the code at the smallest Euclidean distance in the codebook and records its index.
- Get a grid of integers. The result is a grid with an integer from 0 to 511 in each cell, the grid in the middle of the figure with 1, 3, 2, 53 written in it.
- Look up and decode. Swap each integer back for its code vector to get , the same shape as , and hand it to the decoder to reconstruct the image.
Written as formulas, these are the paper's Eq. (1) and (2):
How much information can this grid of integers hold? , so each cell holds at most 9 bits, and the whole grid bits. The original image is pixels at 8 bits each, 393,216 bits in total, so that is a compression of about 42.6 times.
A codebook with only 4 entries
Shrink the dimensions down to something you can work out by hand. Suppose and the codebook has only 4 vectors, sitting on the four corners of a square:
At some position the encoder outputs . The squared distances to the four codes are:
| Code | Squared distance |
|---|---|
The nearest is , so this position gets index 1, and .
This is a one-hot distribution, with and everything else 0. The authors treat it as the VAE's posterior and take a uniform prior , so the KL divergence is:
For the 4-entry codebook that is , which is 2 bits; for the ImageNet grid, every cell's KL is 9 bits, a fixed 9,216 bits for the whole grid. Whatever the encoder outputs, this number never changes.
The KL term becomes a constant with no gradient for any parameter, so it is simply dropped during training. This also explains why VQ-VAE has no fear of posterior collapse. In an ordinary VAE the KL term pushes the posterior toward the prior, and when the decoder is strong enough, the model just sets the posterior equal to the prior and passes along no information at all. VQ-VAE's KL is fixed at ; however much information the latent variables carry, the KL stays the same, so the decoder has no reason to leave those 9,216 bits unused. The price is that the latent variables can carry at most of information, where is the number of cells.
How the gradient gets through argmin
Which brings us back to square one. Between and sits an argmin that no gradient can pass, so how does the encoder learn?
The authors use the straight-through estimator. In the forward pass the lookup runs as usual and goes to the decoder; in the backward pass, the decoder's gradient with respect to is copied unchanged to , pretending the step in between is the identity function.
This works because and live in the same -dimensional space. When the decoder says "it would be better if moved this way," the encoder moves the same way. As long as and are close enough, that direction won't be far off.
Back to the 4-entry codebook. Suppose the decoder's gradient with respect to is (a number made up for the demonstration), meaning that moving down would reduce the reconstruction error. The straight-through estimator hands the same to the encoder, and one step at learning rate 0.2 moves from to .
On the next forward pass, the squared distance from to becomes 2.29 and to only 0.29, so the index switches from 1 to 4. This is what the right half of Figure 1 draws: the red gradient arrow pushes and may push it across a boundary, into another code's territory.
Three loss terms
The straight-through estimator only takes care of the encoder and the decoder. What about the codebook? In the backward pass the gradient jumps straight from to , so the code vectors receive no gradient at all from the reconstruction term.
So the authors add two more terms. Here is the paper's Eq. (3) written as a loss to minimize:
is stop-gradient: the identity function in the forward pass and zero gradient in the backward pass, which amounts to treating whatever is inside the brackets as a constant. is the code vector chosen at this position.
Each of the three terms trains something different:
- The reconstruction term trains the decoder, and, through the straight-through estimator, the encoder.
- The codebook term updates only the code vectors, pulling the chosen code toward the encoder output. The authors call this "one of the simplest dictionary learning algorithms," namely vector quantization (VQ).
- The commitment loss updates only the encoder, pulling the encoder output toward the code it chose.
Let's run the first step of the 4-entry codebook through it. The codebook term is 0.53, and its gradient with respect to is , so gradient descent moves toward . The commitment loss is , and its gradient with respect to is , nudging a little toward . The gradient the encoder actually receives is the passed along by the straight-through estimator plus this term.
Why split the same distance into two terms? Write only without stop-gradient, and the code vectors and the encoder move toward each other with equal force. Split apart, the codebook term lets the code vectors chase the encoder at full strength, while the commitment loss pulls the encoder back with only of the force. The paper's reason is that the embedding space has no fixed scale: if the code vectors can't learn as fast as the encoder, the encoder's outputs can keep growing outward. The commitment loss makes the encoder "commit" to staying near its chosen code, and it also keeps true the " and are close enough" that the straight-through estimator relies on.
Every experiment in the paper uses , and the paper says results barely change for anywhere from 0.1 to 2.0, though the actual best value shifts with the scale of the reconstruction loss. With multiple latent positions, the codebook term and the commitment loss are averaged over all of them.
In code
Nearly every later VQ-style tokenizer reuses this layer. The paper came without code; DeepMind later put an official VectorQuantizer into the Sonnet library. Below it is rewritten in PyTorch, following its order of operations:
import torch
import torch.nn as nn
import torch.nn.functional as F
class VectorQuantizer(nn.Module):
def __init__(self, K=512, D=64, beta=0.25):
super().__init__()
self.codebook = nn.Embedding(K, D)
self.beta = beta
def forward(self, z_e): # z_e: [B, H, W, D]
flat = z_e.reshape(-1, z_e.shape[-1]) # [BHW, D]
e = self.codebook.weight # [K, D]
dist = (flat.pow(2).sum(1, keepdim=True) # ||z||^2 - 2 z·e + ||e||^2
- 2 * flat @ e.t()
+ e.pow(2).sum(1)) # [BHW, K]
idx = dist.argmin(1)
z_q = e[idx].view_as(z_e)
codebook_loss = F.mse_loss(z_q, z_e.detach()) # updates only the codebook
commit_loss = F.mse_loss(z_e, z_q.detach()) # updates only the encoder
z_q = z_e + (z_q - z_e).detach() # straight-through: z_q forward, identity backward
return z_q, idx.view(z_e.shape[:-1]), codebook_loss + self.beta * commit_loss
The second-to-last line is the entire straight-through estimator. In the forward pass ; in the backward pass the parenthesized term is cut off by detach, so the gradient of the output with respect to is 1. The Sonnet version uses mean rather than sum, so its numerical scale differs from the paper's formula by a constant, while plays the same role. It also returns a perplexity, , where is the fraction of this batch that picked the -th code, for seeing how many codes the codebook actually uses.
The codebook can do without gradients
Appendix A.1 gives another way to write the codebook term. Suppose that in some batch, encoder outputs picked code . The codebook term for is:
The that minimizes it has a closed-form solution, the mean of these vectors, , the same as the step in K-means that updates the cluster centers. In mini-batch training each batch sees only part of the data, so an exponential moving average is used instead:
counts how many times the code was chosen and sums the vectors that chose it; dividing one by the other gives a moving cluster center, with in the paper. The paper's own experiments don't use this version, while Sonnet's docstring says that "For most experiments the EMA version trains faster than the non-EMA version." Sonnet also adds a very small smoothing constant to , because some codes may never be chosen, which would leave at 0.
The prior is trained last
While the VQ-VAE trains, the prior stays uniform the whole time, which is why the KL term can be dropped. Once training is done, the authors encode every training image into a grid of integers and train a separate autoregressive model to learn the distribution of these grids: PixelCNN for images, WaveNet for audio. A grid of integers has only one channel, so PixelCNN only needs spatial masking and doesn't have to deal with an ordering among the three RGB channels.
To generate a new image, PixelCNN first samples a grid of integers one cell at a time; looking it up gives , which goes to the decoder. PixelCNN only has to handle 1,024 positions instead of pixels, so both training and sampling are much faster. The authors also say that training the prior jointly with the VQ-VAE might work better, and leave that for the future.
Computing the log-likelihood of the whole model, , requires summing over every possible grid. The authors argue that the decoder has only ever been trained on , so after convergence it won't assign probability to other grids, giving ; by Jensen's inequality, this approximation is also a lower bound on .
Discussion
Against a continuous VAE on CIFAR-10
Section 4.1 compares three models with the same architecture on CIFAR-10. The encoder is two stride-2 convolutions followed by two residual blocks, all 256 wide, and the decoder mirrors it. Adam with learning rate , batch 128, 250,000 steps; VIMCO uses 50 samples.
| Model | bits/dim |
|---|---|
| Continuous VAE | 4.51 |
| VQ-VAE | 4.67 |
| VIMCO (discrete) | 5.14 |
Compiled from Section 4.1 of the paper.
bits/dim converts the negative log-likelihood into bits and divides by the total number of pixel values (), and lower is better; all three numbers are converted from lower bounds on the likelihood, so they are upper bounds on bits/dim. VQ-VAE trails the continuous VAE by 0.16 and beats the other discrete method, VIMCO, by nearly 0.5. On this basis the authors say VQ-VAE is the first discrete latent variable model to catch up with continuous VAEs.
This comparison is light on details. The paper says it varied the capacity of the latent variables, but it doesn't list the or the grid size used for VQ-VAE here, nor any error bars across multiple training runs.
ImageNet: reconstruction first, then generation

On the left are the originals; on the right, reconstructions from a grid of integers with . At 42.6 times compression, the reconstructions are only slightly blurrier than the originals, mostly in fine textures like the fur of the hound and the hyena and the carving on the craft piece. The decoder is nothing but deconvolutions, and the loss is MSE on pixels. The authors themselves note that a loss closer to human perception (a GAN, for example) might do better, and leave it for the future. Three years later, VQGAN did exactly that.

These images are sampled from the PixelCNN prior and then drawn by the decoder. The caption lists a class name per column, and each column holds three samples of the same class. The animals' fur colors and the textures of sea and coral look convincing; the gray whale column mostly shows only sea surface, and objects with a fixed structure, like the microwave and the pickup truck, get only rough outlines, with details often crooked.
This experiment has only pictures: no FID, no Inception Score, and no likelihood on ImageNet. The only numbers in the whole paper set side by side with other work are those three CIFAR-10 bits/dim figures from earlier.
A room in 27 bits
To test posterior collapse directly, the authors stack two levels on frames from DeepMind Lab (a 3D maze game environment). The first VQ-VAE compresses each frame into a grid of integers, and its reconstructions are almost identical to the originals. The second VQ-VAE takes that grid as input and swaps in a PixelCNN as its decoder, exactly the configuration where an ordinary VAE collapses most easily. It has only 3 latent variables, each with , for bits in total, fewer than a single float32.

The top row is the originals; the bottom row is frames reconstructed from nothing but those 27 bits, sampled by the second level's PixelCNN. The colors of the walls and floors and the rough shape of the room line up, while the angles and texture details of the walls are filled in by PixelCNN itself. Had posterior collapse happened, the bottom row would have nothing to do with the top row.
The figure shows that the latent variables are being used, but it is only qualitative evidence. The paper doesn't quantify how much information the 27 bits actually carry, nor does it include a Gaussian VAE under the same setting as a control that would let readers see whether one really collapses.
Phonemes in speech
The speech experiments use VCTK (English read aloud by 109 speakers). The encoder is 6 stride-2 one-dimensional convolutions, shrinking the time axis to 1/64 of its original length, with a codebook of 512 codes; the decoder uses WaveNet-style dilated convolutions, conditioned on both the latent grid and a one-hot speaker ID.
The reconstructed speech says the same words, but with a different waveform and intonation. The latent space has only 1/64 as many steps as the raw samples, too few to store the waveform point by point, and what survives is the content. Swap the speaker ID for someone else's, and you get the same sentence in another person's voice; the paper uses this for unsupervised speaker conversion.
On the 460 speakers of LibriSpeech, the authors compress the time axis to 1/128 and train a WaveNet prior. Each segment of 40,960 samples (2.56 seconds) corresponds to 320 latent steps. The paper says unconditional samples from the original WaveNet sound like babbling, while VQ-VAE samples contain clear words and phrases; for this part, you'll have to go and listen on the authors' web page.
The phoneme experiment from the opening uses a different setting, with a codebook of 128 codes at 25 codes per second (640 times downsampling). Each code is mapped to the phoneme it most often co-occurs with (41 phonemes in all), and this lookup table is used for 41-way classification, reaching 49.3% accuracy; the 7.2% for comparison is the accuracy of always guessing the most common phoneme. Phoneme labels played no part in training, so this number shows that the codes are highly correlated with phonemes. It also has two limits. With this "map each code to its most common label" scheme, accuracy is easier to push up the more codes there are; and the paper doesn't say whether the lookup table and the accuracy were computed on the same data. In a footnote the authors add that a code's meaning may depend on context, the way a bigram or trigram does, and that a finer-grained mapping should score higher.
Dead codes
One problem the paper never discusses later became the most common ailment of VQ-style models.
Back to the 4-entry codebook. If the encoder's outputs all land in the upper right, will never be the nearest code. The codebook term updates only codes that get chosen, so receives no gradient at all and stays put from the moment it is initialized. A code like this is called a dead code, and the bigger the codebook, the larger the fraction of dead codes tends to be.
People have since come up with plenty of remedies. Some initialize the codebook with k-means centers from the first batch; some replace codes that haven't been chosen for a while with encoder outputs from the current batch; others l2-normalize both the code vectors and the encoder outputs and do the lookup in a low-dimensional space. The widely used vector-quantize-pytorch turns all of these into switches, and its README has an entire section called "Increasing codebook usage."
FSQ (Mentzer et al., 2023) measured the problem clearly. In MaskGIT's image generation setting, even with entropy regularization, VQ's codebook usage drops below 50% once the codebook exceeds , and larger codebooks manage to use only about codes. FSQ instead rounds each dimension directly to one of a few fixed values, with no need for a commitment loss, codebook resets or similar machinery, and its codebook gets to use more than codes. The straight-through estimator has been reworked too: the 2024 rotation trick turns into with a rotation plus a rescaling, so that the angle and the length difference between the two also show up in the gradient.
The tokenizers that followed
The two-stage approach of compressing images into grids of integers and then learning the grids' distribution with an autoregressive model went on to become an entire line of work. DALL·E's dVAE trains discrete codes with Gumbel-Softmax, and BEiT uses it as the image tokenizer for pretraining; BEiT v2's VQ-KD keeps the straight-through estimator and the codebook loss, and adds l2 normalization and 32-dimensional codes; MAR goes the other way and argues that autoregressive generation doesn't necessarily need discretization.
Conclusion
VQ-VAE turns the encoder's outputs into integers with a nearest-neighbor lookup, lets the gradient skip over the lookup with the straight-through estimator, and uses the codebook term and the commitment loss to pull the codebook and the encoder toward each other. The uniform prior makes the KL a constant , and with it goes the incentive for posterior collapse; the prior is left for last, for PixelCNN or WaveNet to learn on the grids of integers. On CIFAR-10 its bits/dim trails the continuous VAE by only 0.16, and on speech it learns codes highly correlated with phonemes without a single label. The ImageNet and DeepMind Lab results are pictures only.
If you implement it yourself, the quantization layer is under twenty lines; the trouble is the codebook. During training, log the perplexity or how often each code gets chosen. If you see usage sliding steadily down, first try EMA updates, k-means initialization of the codebook and periodic resets of unchosen codes; once the codebook grows past a few thousand codes, consider a codebook-free quantizer such as FSQ. is the only value the paper ever used, so if you change the scale of the reconstruction loss, remember to retune it.
The paper is titled Neural Discrete Representation Learning, and the three letters VAE appear nowhere in that title. Once the KL term is fixed at , what is actually doing the work during training really is just an autoencoder with a quantization bottleneck.