Search

Search papers and lessons

Vector Quantization

Level 4 · 9 min read

Vector quantization snaps each encoder output to its nearest entry in a learned codebook, so every input becomes a discrete token.

On this page

  • Colour = topic mix
  • Calculus
  • Probability
  • Linear algebra
  • Neural network basics
  • Generative models
  • Losses & regularization
  • Sign in to see your progress

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 KK vectors {e1,…,eK}\{\mathbf{e}_1, \dots, \mathbf{e}_K\}, each in RD\mathbb{R}^D. The encoder maps an input x\mathbf{x} to a vector ze(x)∈RD\mathbf{z}_e(\mathbf{x}) \in \mathbb{R}^D. For images the encoder outputs a grid of such vectors, one per spatial position, and each is quantized separately with the same codebook. DD is the code dimension and KK the codebook size. Both are chosen in advance.

Definition: Vector quantizer

The quantizer maps an encoder output z\mathbf{z} to the codebook entry nearest to it in Euclidean distance:

k∗=argmin⁡j∥z−ej∥2,zq=ek∗.k^\ast = \operatorname*{argmin}_{j} \lVert \mathbf{z} - \mathbf{e}_j \rVert^2, \qquad \mathbf{z}_q = \mathbf{e}_{k^\ast}.

The integer k∗k^\ast is the discrete code (token), and zq\mathbf{z}_q 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 z\mathbf{z} to zq\mathbf{z}_q is piecewise constant: it takes only KK 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 sg[⋅]\mathrm{sg}[\cdot] (identity in the forward pass, zero derivative in the backward pass), is

L=−log⁡pθ(x∣zq)⏟reconstruction+∥sg[ze]−ek∗∥2⏟codebook+β∥ze−sg[ek∗]∥2⏟commitment.\mathcal{L} = \underbrace{-\log p_\theta(\mathbf{x} \mid \mathbf{z}_q)}_{\text{reconstruction}} + \underbrace{\lVert \mathrm{sg}[\mathbf{z}_e] - \mathbf{e}_{k^\ast} \rVert^2}_{\text{codebook}} + \beta \underbrace{\lVert \mathbf{z}_e - \mathrm{sg}[\mathbf{e}_{k^\ast}] \rVert^2}_{\text{commitment}}.

The first term is the usual reconstruction loss. With a Gaussian likelihood it reduces to a squared error between x\mathbf{x} and its reconstruction. The second term moves the chosen codebook entry toward the encoder output, and the third, weighted by β≥0\beta \ge 0, 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,

∂L∂ze:=∂L∂zq.\frac{\partial \mathcal{L}}{\partial \mathbf{z}_e} := \frac{\partial \mathcal{L}}{\partial \mathbf{z}_q}.

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

Example
One quantization step with a tiny codebook

Take K=3K = 3 codebook entries in D=2D = 2: e1=(0,0)\mathbf{e}_1 = (0, 0), e2=(2,0)\mathbf{e}_2 = (2, 0) and e3=(1,3)\mathbf{e}_3 = (1, 3). The encoder outputs ze=(1.2,1.0)\mathbf{z}_e = (1.2, 1.0).

  1. Squared distance to e1\mathbf{e}_1: (1.2)2+(1.0)2=1.44+1.00=2.44(1.2)^2 + (1.0)^2 = 1.44 + 1.00 = 2.44.
  2. Squared distance to e2\mathbf{e}_2: (−0.8)2+(1.0)2=0.64+1.00=1.64(-0.8)^2 + (1.0)^2 = 0.64 + 1.00 = 1.64.
  3. Squared distance to e3\mathbf{e}_3: (0.2)2+(−2.0)2=0.04+4.00=4.04(0.2)^2 + (-2.0)^2 = 0.04 + 4.00 = 4.04.
  4. The smallest is 1.641.64, so k∗=2k^\ast = 2 and zq=(2,0)\mathbf{z}_q = (2, 0). The stored token is 2.

Now the backward pass. Suppose the decoder's gradient at zq\mathbf{z}_q is (0.5,−0.2)(0.5, -0.2). Straight-through gives the encoder the same gradient, (0.5,−0.2)(0.5, -0.2). The codebook term gives ∂/∂e2 ∥ze−e2∥2=−2(ze−e2)=−2(−0.8,1.0)=(1.6,−2.0)\partial/\partial \mathbf{e}_2 \, \lVert \mathbf{z}_e - \mathbf{e}_2 \rVert^2 = -2(\mathbf{z}_e - \mathbf{e}_2) = -2(-0.8, 1.0) = (1.6, -2.0). A gradient step with learning rate η\eta moves e2\mathbf{e}_2 by −η(1.6,−2.0)-\eta(1.6, -2.0), which is left and up, toward ze\mathbf{z}_e. With β=0.25\beta = 0.25 the commitment term adds 2β(ze−e2)=0.5⋅(−0.8,1.0)=(−0.4,0.5)2\beta(\mathbf{z}_e - \mathbf{e}_2) = 0.5 \cdot (-0.8, 1.0) = (-0.4, 0.5) to the encoder's gradient, so the encoder receives (0.5,−0.2)+(−0.4,0.5)=(0.1,0.3)(0.5, -0.2) + (-0.4, 0.5) = (0.1, 0.3).

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.

Example
How many bits a token grid saves

Take a 256×256256 \times 256 RGB image with 8 bits per channel. Raw storage is 256⋅256⋅3⋅8=1,572,864256 \cdot 256 \cdot 3 \cdot 8 = 1{,}572{,}864 bits, which is 196,608196{,}608 bytes.

Now let the encoder downsample the image to a 32×3232 \times 32 grid of codes, with a codebook of K=512K = 512 entries. Each token needs log⁡2512=9\log_2 512 = 9 bits, so the grid needs 32⋅32⋅9=9,21632 \cdot 32 \cdot 9 = 9{,}216 bits, or 1,1521{,}152 bytes.

The ratio is 1,572,864/9,216≈170.71{,}572{,}864 / 9{,}216 \approx 170.7, 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 1,0241{,}024 tokens instead of 65,53665{,}536 pixel positions, which is what makes sequence modelling of images affordable. (The VQ-VAE paper's own image experiment compressed 128×128×3128 \times 128 \times 3 images to a 32×3232 \times 32 grid with K=512K = 512, a bit reduction of about 42.6, and modelled the codes with a PixelCNN prior.)

Tradeoffs and failure modes

SituationWhat goes wrongBetter choice
Codebook too small for the dataReconstructions blur, because each code must stand for too much varietyMore entries, or a larger code dimension DD
Codebook large, most entries unusedCodebook collapse: a few entries take almost every assignmentRestart unused entries from recent encoder outputs, or lower the code dimension for lookup
Need smooth interpolation between codesNearest-neighbour output is piecewise constant, so small moves in latent space jumpA continuous latent, as in a Variational Autoencoder
Codebook learning is unstableEntries drift, and assignments flip back and forthUpdate the codebook with a moving average, or lower its learning rate
Straight-through gradient points the wrong wayThe encoder is trained on a gradient that ignores the snapSoft relaxations of the choice, such as Gumbel-softmax
Want no learned codebook at allLearned codebooks add training complexityFinite scalar quantization, which rounds each coordinate to a small fixed grid

The main cost of a discrete bottleneck is information. Each token has log⁡2K\log_2 K 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 β=0.25\beta = 0.25), 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
The encoder output is replaced by its nearest codebook entry, which is the vector the decoder sees. In place of the vector, the model stores or transmits only the entry's integer index.
QuestionComputation: the codebook is {(0,0),(1,2),(3,3)}\{(0, 0), (1, 2), (3, 3)\} and the encoder output is z=(0.4,2.1)\mathbf{z} = (0.4, 2.1). Which index is chosen?Show answer
Squared distances: to (0,0)(0, 0) it is 0.16+4.41=4.570.16 + 4.41 = 4.57; to (1,2)(1, 2) it is 0.36+0.01=0.370.36 + 0.01 = 0.37; to (3,3)(3, 3) it is 6.76+0.81=7.576.76 + 0.81 = 7.57. The smallest is 0.370.37, so the chosen entry is (1,2)(1, 2), which is index 2 counting from 1.
QuestionWhy: why does training a vector quantizer need a special gradient rule, and what does the rule assume?Show answer
The quantizer maps many inputs to the same entry, so its derivative is zero almost everywhere and the reconstruction loss gives the encoder no signal. The straight-through rule copies the decoder's gradient at the quantized vector onto the encoder output. It assumes that the encoder output and the chosen entry are close, so that the copied gradient is a reasonable guess for the direction that would reduce the loss.
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
This is codebook collapse. Entries that start far from the encoder outputs never win the nearest-neighbour test, so they never receive a codebook gradient and stay unused. A reasonable fix is to reinitialise unused entries to recent encoder outputs, which puts them back in the data. Lowering the code dimension, or updating the codebook with a moving average instead of gradients, also reduces collapse. Checking the usage histogram during training shows whether the fix worked.

Sources