Search

Search papers and lessons

Neural Discrete Representation Learning

Aaron van den Oord, Oriol Vinyals, Koray Kavukcuoglu · 2017

The VQ-VAE paper replaces a VAE's continuous code with a discrete one picked from a learned codebook, then fits a separate autoregressive prior so the model can generate new data.

On this page

  • Colour = topic mix
  • Probability
  • Calculus
  • Discrete math
  • Generative models
  • Neural network basics
  • Linear algebra
  • ReadReady to readNot yet

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.

  1. Input. An image or audio clip x goes into the encoder. The encoder outputs a continuous vector, here z_e(x) = (0.9, 0.2). Check: it is still just two decimal numbers, nothing discrete yet.
  2. 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.
  3. Nearest entry. Measure the squared distance from z_e(x) to each entry. To e1: 0.81 + 0.04 = 0.85. To e2: 0.01 + 0.04 = 0.05. To e3: 0.01 + 0.64 = 0.65. To e4: 0.81 + 0.64 = 1.45. The smallest is e2, so the code is k = 2. Check: 0.05 is the smallest of the four sums.
  4. 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.
  5. Decode. The decoder turns (1, 0) into a reconstruction x_hat. Its error gives a reconstruction loss.
  6. 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.
  7. 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 e2 toward the encoder output z_e(x). Check: e2 moves from (1, 0) toward (0.9, 0.2).
  8. 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.
  9. 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 e∈RK×De \in \mathbb{R}^{K \times D} with K rows ei∈RDe_i \in \mathbb{R}^{D}. 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:

q(z=k∣x)={1for k=arg⁡min⁡j ∥ze(x)−ej∥20otherwiseq(z=k \mid x)=\begin{cases}1 & \text{for } k = \arg\min_{j}\,\|z_e(x)-e_j\|_2 \\ 0 & \text{otherwise}\end{cases}

Here ze(x)z_e(x) 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

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

The decoder receives zq(x)z_q(x).

Why the KL term is a constant

The prior over codes is uniform, p(z=k)=1/Kp(z=k)=1/K. Since qq is one-hot on a single kk, the KL divergence reduces to

KL(q ∥ p)=∑kq(k∣x)log⁡q(k∣x)1/K=1⋅log⁡K=log⁡K.\mathrm{KL}\big(q \,\|\, p\big)=\sum_{k} q(k\mid x)\log\frac{q(k\mid x)}{1/K}=1\cdot\log K = \log K.

The value log⁡K\log K does not depend on the encoder, so it drops out of training.

Step 6 in symbols: the straight-through gradient

The map from zez_e to zqz_q has zero gradient almost everywhere, so the paper uses

∂L∂ze(x)≈∂L∂zq(x).\frac{\partial L}{\partial z_e(x)} \approx \frac{\partial L}{\partial z_q(x)}.

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

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

The paper writes the reconstruction term as log⁡p\log p; in training it acts as a reconstruction error to be made small, so read its sign as the usual negative log-likelihood. The symbol sg\mathrm{sg} 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 β\beta, 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 ii with ni(t)n_i^{(t)} outputs at step tt, the paper's updates are

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

with γ=0.99\gamma = 0.99. 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 p(z)p(z) 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

Example
Example 1: one encoder output, four codebook entries

Use the codebook from the walkthrough: e1=(0,0)e_1=(0,0), e2=(1,0)e_2=(1,0), e3=(1,1)e_3=(1,1), e4=(0,1)e_4=(0,1). The encoder output is ze(x)=(0.5,0.5)z_e(x)=(0.5, 0.5).

  1. Squared distance to e1e_1: (0.5−0)2+(0.5−0)2=0.25+0.25=0.5(0.5-0)^2+(0.5-0)^2 = 0.25+0.25 = 0.5.
  2. Squared distance to e2e_2: (0.5−1)2+(0.5−0)2=0.25+0.25=0.5(0.5-1)^2+(0.5-0)^2 = 0.25+0.25 = 0.5.
  3. Squared distance to e3e_3: (0.5−1)2+(0.5−1)2=0.25+0.25=0.5(0.5-1)^2+(0.5-1)^2 = 0.25+0.25 = 0.5.
  4. Squared distance to e4e_4: (0.5−0)2+(0.5−1)2=0.25+0.25=0.5(0.5-0)^2+(0.5-1)^2 = 0.25+0.25 = 0.5.
  5. All four distances tie, so the arg-min is ambiguous. Pick the smallest index, k=1k=1, which is a convention, not a property of the method.
  6. The decoder receives zq(x)=e1=(0,0)z_q(x)=e_1=(0,0). 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.

Example
Example 2: the size of a discrete code

The paper's image model uses K = 512 codebook entries.

  1. A single code index can take 512 values.
  2. The bits needed to store one index are log⁡2512\log_2 512.
  3. Since 29=5122^9 = 512, log⁡2512=9\log_2 512 = 9, so each code costs 9 bits.
  4. The paper's second-stage model uses three latents of 9 bits each: 3×9=273 \times 9 = 27 bits in total, which the paper gives as 27 bits.
  5. 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.

Example
Example 3: compressing a 128 by 128 colour image

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.

  1. Original bits: 128×128×3×8=393,216128 \times 128 \times 3 \times 8 = 393{,}216, taking 8 bits per channel value.
  2. Code bits: 32×32×132 \times 32 \times 1 codes, each 9 bits, gives 32×32×9=9,21632 \times 32 \times 9 = 9{,}216 bits.
  3. Ratio: 393,216/9,216≈42.67393{,}216 / 9{,}216 \approx 42.67.
  4. 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.
  5. 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 log⁡2128=7\log_2 128 = 7 bits, and 25 codes per second gives 25×7=17525 \times 7 = 175 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

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 zqz_q onto zez_e, 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 log⁡2256=8\log_2 256 = 8 bits, since 28=2562^8 = 256. Sixty-four codes carry 64×8=51264 \times 8 = 512 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 log⁡K\log K 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 β∥ze−sg[e]∥2\beta\|z_e - \mathrm{sg}[e]\|^2, 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

Read the full paper

Aaron van den Oord, Oriol Vinyals, Koray Kavukcuoglu, 2017. arXiv:1711.00937