Back to paper library
Paper notesarXiv 2017NeurIPS 2017

VQ-VAE

Take a Number

Original paper

Neural Discrete Representation Learning

Paper authors

Aaron van den Oord · Oriol Vinyals · Koray Kavukcuoglu

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}
}
On this page

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 z=μ+σϵz=\mu+\sigma\epsilon, and the gradient flows back to the encoder through μ\mu and σ\sigma. If the latent variable is "pick one of KK 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

VQ-VAE diagram. Left: a photo of a dog goes through a CNN encoder, giving a green feature map z_e(x) of depth D. Above it is the purple Embedding Space, holding K vectors, e1, e2, e3 through eK. Each position of the feature map looks up the nearest vector in the Embedding Space, giving a grid filled with integers, q(z|x), for example 1, 3, 2, 53; looking these integers up in the table assembles the purple feature map z_q(x), which goes to the CNN decoder that outputs p(x|z_q). A red arrow ∇zL loops from the decoder's input back to the encoder's output. Right: purple code vectors scattered across the latent space; the small green dot z_e(x) is closest to e2, so z_q(x) equals e2; a red arrow ∇zL points from z_e(x) to the right.
Original Figure 1, van den Oord et al., from PDF page 4, arXiv license, scholarly quotation.

Let's take the ImageNet setting from Section 4.2 and follow a 128×128×3128\times128\times3 image through the left half.

  1. Encode. The convolutional encoder shrinks the image to a 32×3232\times32 feature map ze(x)z_e(x). Each position is a DD-dimensional vector, 1,024 vectors in all.
  2. Look up the nearest code. The model has a codebook e∈RK×De\in\mathbb R^{K\times D}, here with K=512K=512, and each row eje_j is a DD-dimensional code vector. Each of the 1,024 vectors finds the code at the smallest Euclidean distance in the codebook and records its index.
  3. Get a grid of integers. The result is a 32×3232\times32 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.
  4. Look up and decode. Swap each integer back for its code vector to get zq(x)z_q(x), the same shape as ze(x)z_e(x), and hand it to the decoder to reconstruct the image.

Written as formulas, these are the paper's Eq. (1) and (2):

q(z=k∣x)={1,k=k∗0,otherwisek∗=arg⁡min⁡j∥ze(x)−ej∥2\begin{gathered} q(z=k|x)= \begin{cases} 1, & k=k^\ast\\ 0, & \text{otherwise} \end{cases}\\ k^\ast=\arg\min_j \|z_e(x)-e_j\|_2 \end{gathered} zq(x)=ek,k=arg⁡min⁡j∥ze(x)−ej∥2z_q(x)=e_k,\qquad k=\arg\min_j \|z_e(x)-e_j\|_2

How much information can this grid of integers hold? 512=29512=2^9, so each cell holds at most 9 bits, and the whole grid 32×32×9=9,21632\times32\times9=9{,}216 bits. The original image is 128×128×3128\times128\times3 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 D=2D=2 and the codebook has only 4 vectors, sitting on the four corners of a square:

e1=(1,1),e2=(−1,1),e3=(−1,−1),e4=(1,−1)\begin{aligned} e_1&=(1,1), & e_2&=(-1,1),\\ e_3&=(-1,-1), & e_4&=(1,-1) \end{aligned}

At some position the encoder outputs ze=(0.8, 0.3)z_e=(0.8,\,0.3). The squared distances to the four codes are:

CodeSquared distance
e1e_10.22+0.72=0.530.2^2+0.7^2=0.53
e2e_21.82+0.72=3.731.8^2+0.7^2=3.73
e3e_31.82+1.32=4.931.8^2+1.3^2=4.93
e4e_40.22+1.32=1.730.2^2+1.3^2=1.73

The nearest is e1e_1, so this position gets index 1, and zq=(1,1)z_q=(1,1).

This q(z∣x)q(z|x) is a one-hot distribution, with q(z=1∣x)=1q(z=1|x)=1 and everything else 0. The authors treat it as the VAE's posterior and take a uniform prior p(z=k)=1/Kp(z=k)=1/K, so the KL divergence is:

KL(q(z∣x) ∥ p(z))=∑kq(z=k∣x)log⁡q(z=k∣x)1/K=1⋅log⁡11/K=log⁡K\begin{aligned} &\mathrm{KL}\big(q(z|x)\,\|\,p(z)\big)\\ &\quad=\sum_k q(z=k|x)\log\frac{q(z=k|x)}{1/K}\\ &\quad=1\cdot\log\frac{1}{1/K}=\log K \end{aligned}

For the 4-entry codebook that is log⁡4\log 4, which is 2 bits; for the 32×3232\times32 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 log⁡K\log K; 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 Nlog⁡KN\log K of information, where NN is the number of cells.

How the gradient gets through argmin

Which brings us back to square one. Between zez_e and zqz_q 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 zqz_q goes to the decoder; in the backward pass, the decoder's gradient with respect to zqz_q is copied unchanged to zez_e, pretending the step in between is the identity function.

This works because zez_e and zqz_q live in the same DD-dimensional space. When the decoder says "it would be better if zqz_q moved this way," the encoder moves zez_e the same way. As long as zez_e and zqz_q are close enough, that direction won't be far off.

Back to the 4-entry codebook. Suppose the decoder's gradient with respect to zqz_q is g=(0, 4)g=(0,\,4) (a number made up for the demonstration), meaning that moving zqz_q down would reduce the reconstruction error. The straight-through estimator hands the same gg to the encoder, and one step at learning rate 0.2 moves zez_e from (0.8,0.3)(0.8,0.3) to (0.8,−0.5)(0.8,-0.5).

On the next forward pass, the squared distance from zez_e to e1e_1 becomes 2.29 and to e4e_4 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 zez_e 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 zqz_q to zez_e, so the code vectors eke_k 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:

L=−log⁡p(x∣zq(x))+∥sg[ze(x)]−e∥22+β ∥ze(x)−sg[e]∥22\begin{aligned} \mathcal L=&-\log p(x|z_q(x))\\ &+\big\|\mathrm{sg}[z_e(x)]-e\big\|_2^2\\ &+\beta\,\big\|z_e(x)-\mathrm{sg}[e]\big\|_2^2 \end{aligned}

sg[⋅]\mathrm{sg}[\cdot] 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. ee is the code vector chosen at this position.

Each of the three terms trains something different:

  • The reconstruction term −log⁡p(x∣zq(x))-\log p(x|z_q(x)) trains the decoder, and, through the straight-through estimator, the encoder.
  • The codebook term ∥sg[ze]−e∥2\|\mathrm{sg}[z_e]-e\|^2 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 β∥ze−sg[e]∥2\beta\|z_e-\mathrm{sg}[e]\|^2 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 e1e_1 is 2(e1−ze)=(0.4, 1.4)2(e_1-z_e)=(0.4,\,1.4), so gradient descent moves e1e_1 toward zez_e. The commitment loss is 0.25×0.53=0.13250.25\times0.53=0.1325, and its gradient with respect to zez_e is 2β(ze−e1)=(−0.1, −0.35)2\beta(z_e-e_1)=(-0.1,\,-0.35), nudging zez_e a little toward e1e_1. The gradient the encoder actually receives is the gg passed along by the straight-through estimator plus this term.

Why split the same distance into two terms? Write only ∥ze−e∥2\|z_e-e\|^2 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 β\beta 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 "zez_e and zqz_q are close enough" that the straight-through estimator relies on.

Every experiment in the paper uses β=0.25\beta=0.25, and the paper says results barely change for β\beta 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:

python
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 ze+(zq−ze)=zqz_e+(z_q-z_e)=z_q; in the backward pass the parenthesized term is cut off by detach, so the gradient of the output with respect to zez_e is 1. The Sonnet version uses mean rather than sum, so its numerical scale differs from the paper's formula by a constant, while β\beta plays the same role. It also returns a perplexity, exp⁡(−∑kpklog⁡pk)\exp(-\sum_k p_k\log p_k), where pkp_k is the fraction of this batch that picked the kk-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, nin_i encoder outputs zi,1,…,zi,niz_{i,1},\dots,z_{i,n_i} picked code eie_i. The codebook term for eie_i is:

∑j=1ni∥zi,j−ei∥22\sum_{j=1}^{n_i}\|z_{i,j}-e_i\|_2^2

The eie_i that minimizes it has a closed-form solution, the mean of these vectors, 1ni∑jzi,j\frac{1}{n_i}\sum_j z_{i,j}, 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:

Ni(t)=γ Ni(t−1)+(1−γ) ni(t)mi(t)=γ mi(t−1)+(1−γ)∑jzi,j(t)ei(t)=mi(t) / Ni(t)\begin{aligned} N_i^{(t)}&=\gamma\,N_i^{(t-1)}+(1-\gamma)\,n_i^{(t)}\\ m_i^{(t)}&=\gamma\,m_i^{(t-1)}+(1-\gamma)\sum_j z_{i,j}^{(t)}\\ e_i^{(t)}&=m_i^{(t)}\,/\,N_i^{(t)} \end{aligned}

NiN_i counts how many times the code was chosen and mim_i sums the vectors that chose it; dividing one by the other gives a moving cluster center, with γ=0.99\gamma=0.99 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 NiN_i, because some codes may never be chosen, which would leave NiN_i 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 32×3232\times32 grid of integers one cell at a time; looking it up gives zqz_q, which goes to the decoder. PixelCNN only has to handle 1,024 positions instead of 128×128×3128\times128\times3 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, log⁡p(x)=log⁡∑kp(x∣zk)p(zk)\log p(x)=\log\sum_k p(x|z_k)p(z_k), requires summing over every possible grid. The authors argue that the decoder has only ever been trained on z=zq(x)z=z_q(x), so after convergence it won't assign probability to other grids, giving log⁡p(x)≈log⁡p(x∣zq(x)) p(zq(x))\log p(x)\approx\log p(x|z_q(x))\,p(z_q(x)); by Jensen's inequality, this approximation is also a lower bound on log⁡p(x)\log p(x).

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 4×44\times4 convolutions followed by two 3×33\times3 residual blocks, all 256 wide, and the decoder mirrors it. Adam with learning rate 2×10−42\times10^{-4}, batch 128, 250,000 steps; VIMCO uses 50 samples.

Modelbits/dim
Continuous VAE4.51
VQ-VAE4.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 (32×32×332\times32\times3), 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 KK or the grid size used for VQ-VAE here, nor any error bars across multiple training runs.

ImageNet: reconstruction first, then generation

Two sets of images, each 2 rows by 4 columns. Left, ImageNet originals: a hand holding a tool, a brake disc, a carved craft piece, a telescope, people on a beach, a sailboat, a long-haired hound, a hyena. Right, the corresponding VQ-VAE reconstructions: composition, colors and main outlines are kept, while fine textures such as fur and carving are slightly blurred.
Original Figure 2, van den Oord et al., from PDF page 5, arXiv license, scholarly quotation.

On the left are the originals; on the right, reconstructions from a 32×3232\times32 grid of integers with K=512K=512. 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.

8 columns of 3 generated 128×128 images each. The classes from left to right are kit fox, gray whale, brown bear, admiral butterfly, coral reef, alp, microwave and pickup: the fox and bear fur colors are roughly right, and the sea surface, coral and mountain scenery have natural textures; the gray whale column mostly shows only sea surface, and the microwave and pickup have rough outlines with fine structure often distorted.
Original Figure 3, van den Oord et al., from PDF page 6, arXiv license, scholarly quotation.

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 84×8484\times84 frames from DeepMind Lab (a 3D maze game environment). The first VQ-VAE compresses each frame into a 21×2121\times21 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 K=512K=512, for 3×9=273\times9=27 bits in total, fewer than a single float32.

Two rows of 10 DeepMind Lab game frames each. Top row, the originals: blue sky, walls in various colors (gray walls with round holes, green, red, yellow and orange walls), yellow or blue floors. Bottom row, the two-stage VQ-VAE's reconstructions from 27 bits: in each one the wall color, floor color and rough layout of the room match the original above, but the angles, positions and texture details of the walls differ.
Original Figure 5, van den Oord et al., from PDF page 7, arXiv license, scholarly quotation.

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, e3=(−1,−1)e_3=(-1,-1) will never be the nearest code. The codebook term updates only codes that get chosen, so e3e_3 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 2112^{11}, and larger codebooks manage to use only about 2102^{10} 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 2162^{16} codebook gets to use more than 2152^{15} codes. The straight-through estimator has been reworked too: the 2024 rotation trick turns zez_e into zqz_q 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 log⁡K\log K, 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. β=0.25\beta=0.25 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 log⁡K\log K, what is actually doing the work during training really is just an autoencoder with a quantization bottleneck.