TL;DR
Vector quantization replaces each continuous vector with the nearest entry of a learned list of vectors, called the codebook. An encoder produces a vector, the code is swapped for its nearest codebook entry, and only that entry's index needs to be stored or sent. Training this discrete bottleneck end to end, as the VQ-VAE does, needs a gradient trick because the snap has no useful gradient.
Where you'll see it: discrete image and audio tokenizers, which turn media into a sequence of integer codes that a Transformer can model one token at a time.
Intuition
Imagine a paint shop that only mixes a fixed palette of 512 colours. You can ask for any colour, but you always get the closest one on the palette. A picture painted this way is described completely by a grid of palette numbers, and the palette itself is shared by all pictures. Vector quantization works the same way, except the palette is a set of learned vectors and the "colours" are the encoder's outputs.
Why bother? A continuous code is a list of real numbers, and a model has no natural way to treat it as a symbol. A discrete code is an integer. Integers can be predicted one by one with the same machinery used for language, and they can be stored compactly. The bottleneck also forces the model to keep only the coarse structure it can afford to encode, which is useful for generation.
The difficulty is that "pick the nearest entry" is a hard decision. A tiny change to the encoder output usually changes nothing, and then suddenly switches the chosen entry. Gradients cannot flow through that switch in the usual way, so the training method has to pretend the switch was not there on the backward pass.
flowchart LR X["Input x"] --> E["Encoder output z_e"] E --> Q["Nearest codebook entry e_k"] Q --> D["Decoder rebuilds x_hat"] C["Codebook of K vectors"] -.-> Q Q -.-> T["Stored token: index k"]
The math
Setup
Let the codebook be a list of vectors , each in . The encoder maps an input to a vector . For images the encoder outputs a grid of such vectors, one per spatial position, and each is quantized separately with the same codebook. is the code dimension and the codebook size. Both are chosen in advance.
The quantizer maps an encoder output to the codebook entry nearest to it in Euclidean distance:
The integer is the discrete code (token), and is the vector the decoder sees. Ties go to the smallest index.
Two things are worth noticing. The quantizer is a k-means-style nearest-centre rule, with the codebook entries playing the role of cluster centres. And the map from to is piecewise constant: it takes only distinct values, so its derivative is zero everywhere except on the boundaries between regions, where it is undefined.
The training objective
The VQ-VAE objective, written with the stop-gradient operator (identity in the forward pass, zero derivative in the backward pass), is
The first term is the usual reconstruction loss. With a Gaussian likelihood it reduces to a squared error between and its reconstruction. The second term moves the chosen codebook entry toward the encoder output, and the third, weighted by , keeps the encoder output close to the entry it was assigned to. Without the commitment term the encoder can wander away from the codebook, and then the codebook cannot follow it.
Gradients through the snap
The quantizer has zero gradient almost everywhere, so the reconstruction loss gives no signal to the encoder by itself. The fix is the straight-through estimator (see Straight-Through Estimator): on the backward pass, copy the gradient from the decoder's input straight to the encoder's output,
The codebook gets its gradient from the second term alone. With the assignments held fixed, a gradient step on that term moves each entry toward the mean of the encoder outputs assigned to it. This is the update step of k-means, done gradually by gradient descent (the paper also describes an exponential-moving-average version).
Worked examples
Take codebook entries in : , and . The encoder outputs .
- Squared distance to : .
- Squared distance to : .
- Squared distance to : .
- The smallest is , so and . The stored token is 2.
Now the backward pass. Suppose the decoder's gradient at is . Straight-through gives the encoder the same gradient, . The codebook term gives . A gradient step with learning rate moves by , which is left and up, toward . With the commitment term adds to the encoder's gradient, so the encoder receives .
Interpretation: the commitment term partly cancels the decoder's gradient in the first coordinate and adds to it in the second, pulling the encoder toward its assigned code. The codebook entry itself moves toward the encoder output it was chosen for.
Take a RGB image with 8 bits per channel. Raw storage is bits, which is bytes.
Now let the encoder downsample the image to a grid of codes, with a codebook of entries. Each token needs bits, so the grid needs bits, or bytes.
The ratio is , so the token grid is about 170 times smaller than the raw image. These figures count only the codes. The decoder must recover the image from them, so the reconstruction is lossy. For a transformer, the model sees tokens instead of pixel positions, which is what makes sequence modelling of images affordable. (The VQ-VAE paper's own image experiment compressed images to a grid with , a bit reduction of about 42.6, and modelled the codes with a PixelCNN prior.)
Tradeoffs and failure modes
| Situation | What goes wrong | Better choice |
|---|---|---|
| Codebook too small for the data | Reconstructions blur, because each code must stand for too much variety | More entries, or a larger code dimension |
| Codebook large, most entries unused | Codebook collapse: a few entries take almost every assignment | Restart unused entries from recent encoder outputs, or lower the code dimension for lookup |
| Need smooth interpolation between codes | Nearest-neighbour output is piecewise constant, so small moves in latent space jump | A continuous latent, as in a Variational Autoencoder |
| Codebook learning is unstable | Entries drift, and assignments flip back and forth | Update the codebook with a moving average, or lower its learning rate |
| Straight-through gradient points the wrong way | The encoder is trained on a gradient that ignores the snap | Soft relaxations of the choice, such as Gumbel-softmax |
| Want no learned codebook at all | Learned codebooks add training complexity | Finite scalar quantization, which rounds each coordinate to a small fixed grid |
The main cost of a discrete bottleneck is information. Each token has bits, and any detail beyond that budget is lost. The main benefit is that the tokens are symbols, which a language-style model can predict with cross-entropy (see Cross-Entropy Loss) and generate one at a time.
History
The idea predates neural networks. Lloyd's algorithm for choosing quantizer levels was written at Bell Labs in 1957 and published in 1982. The vector form, where whole blocks are coded at once, was developed for speech and image compression in the late 1970s and early 1980s. Linde, Buzo and Gray gave a practical design algorithm in 1980, and Robert Gray's 1984 survey in the IEEE ASSP Magazine made vector quantization a standard tool in signal coding.
For deep learning, the step that mattered was training the quantizer inside a neural network. Van den Oord, Vinyals and Kavukcuoglu's 2017 paper, Neural Discrete Representation Learning, combined a learned encoder and decoder with a codebook and the codebook and commitment losses above (the paper used ), and used the straight-through estimator to pass gradients across the discrete choice. It showed that the model could learn discrete codes that kept the main content of images and audio.
Check yourself
QuestionRecall: what does the encoder output become after quantization, and what is stored in its place?Show answer
QuestionComputation: the codebook is and the encoder output is . Which index is chosen?Show answer
QuestionWhy: why does training a vector quantizer need a special gradient rule, and what does the rule assume?Show answer
QuestionApplied: a VQ-VAE trains well, but after a while only 20 of 512 codebook entries are ever chosen. What is happening, and what would you change?Show answer
Sources
- van den Oord, Vinyals and Kavukcuoglu, Neural Discrete Representation Learning (2017): arXiv:1711.00937
- Vector quantization (Wikipedia)
- Gray, "Vector Quantization", IEEE ASSP Magazine (1984)