Product Quantization For Nearest Neighbor Search
On this page
Searching through millions of high-dimensional vectors is slow and memory-hungry. Product Quantization is a technique that makes it practical.
Introduction
The problem is simple to state. We have $n$ vectors in $\mathbb{R}^D$ and a query $x$, and we want the vector $y$ closest to $x$.
When the dataset is small, this is easy: compare the query with every vector and keep the closest. At the scale of millions or billions of high-dimensional vectors, such as 128-dimensional SIFT or 960-dimensional GIST image descriptors, that approach stops working. It’s too slow, and the raw vectors take up far too much memory.
In Product Quantization for Nearest Neighbor Search (IEEE TPAMI, 2011), Hervé Jégou, Matthijs Douze and Cordelia Schmid set out to make approximate nearest-neighbor search both fast and memory-efficient. Their idea is to compress each database vector into a short code, such as 64 bits, by replacing it with the nearest of a fixed set of “centroid” points. The query itself isn’t compressed. It’s compared directly against the centroids, which keeps the error lower and the results more accurate.
To get accurate distances, the compression error has to be small, which means using a very large number of centroids $k$. For 64-bit codes, that’s $k = 2^{64}$. With plain k-means, this causes three problems:
- Learning the centroids needs a training set several times larger than $k$.
- Running k-means with that many centroids would take far too long.
- Storing the centroids would take an enormous amount of memory.
Product quantization solves this by building the huge codebook out of a few small ones. Even with compressed codes, comparing the query with every code is still too slow at this scale. So the paper also adds an inverted file: a coarse quantizer groups the vectors into cells, and a query only scans the cells closest to it. Inside each cell, vectors are stored as short product-quantization codes of their offset from the cell’s center.
About the visuals
The images, animations and worked examples in this post were created with Claude Code.
Background
Quantization
Quantization maps values from a large, often continuous, range to a small set of representative values. Each data item is replaced by its closest representative. The set of representative values is called the codebook, and each value in it is a codeword. In this post, “centroid” means the same thing as codeword.
K-Means
The k-means clustering problem is to split the data into $k$ groups so that the sum of squared distances from each point to the center of its group is as small as possible.
Lloyd’s Algorithm
Stuart Lloyd developed an algorithm for representing a continuous signal with a few discrete values. It started out in pulse-code modulation, but today it’s best known as the standard way to solve the k-means clustering problem.
The algorithm is iterative. It keeps refining the centroids until they stop moving. Here is how it works:
- Initialize: Pick $k$ initial codewords (also called reconstruction levels or seeds).
// Pick k random centers and assign empty cluster to each centroid
n := len(data)
seen := make(map[int]any)
for i := 0; i < k; i++ {
var randCenter int
for {
randCenter = data[rand.Intn(n)]
if _, ok := seen[randCenter]; !ok {
break
}
}
seen[randCenter] = true
centroids = append(centroids, randCenter)
}
- Partition: Assign every data point to its nearest codeword. This splits the data into regions.
// Assign data elements to the clusters with closest centroids.
findDistance := func(data int, center int) int {
return int(math.Abs(float64(data) - float64(center)))
}
for i, elem := range data {
var minDistance, bestSet int
for j := 0; j < k; j++ {
d := findDistance(elem, centroids[j])
if j == 0 || minDistance > d {
minDistance = d
bestSet = j
}
}
sets[i] = bestSet
}
- Update: Move each codeword to the mean (centroid) of its region. The new means become the updated codebook.
// Adjust the center to the mean of the set.
updatedCenter := func(elems []int, sets []int, s int) (int, error) {
var sum, l int
for i := 0; i < len(elems); i++ {
if sets[i] == s {
sum += elems[i]
l++
}
}
if l == 0 { // Zero sized set
return -1, emptySet
}
return int(math.Round(float64(sum) / float64(l))), nil
}
for i := 0; i < k; i++ {
nc, err := updatedCenter(data, sets, i)
if err != nil {
nc = data[rand.Intn(n)]
}
centroids[i] = nc
}
- Convergence: Repeat the partition and update steps until the codewords stop moving, or move by a negligible amount.
Lloyd’s algorithm always converges, but only to a local optimum. Different starting codewords can give different results.
Note
The snippets above are simplified. They work on 1-D integer data and show a single iteration. A full implementation works on float vectors and repeats the partition and update steps until convergence. The complete Go implementation is available as a gist.
Simulation
This animation runs Lloyd’s algorithm on a small 2-D dataset with five codewords:

Product Quantizers
The idea is to cut each $D$-dimensional vector into $m$ subvectors $u_1(x), \dots, u_m(x)$ of $D^* = D/m$ dimensions each, and quantize each subvector separately. Each subvector position gets its own small codebook $q_j$ with $k^*$ centroids, learned with k-means on just that slice of the training data. The code for $x$ is the list of $m$ centroid indices.

The full codebook is the Cartesian product of the small ones:
$$ \mathcal{C} = \mathcal{C}_1 \times \mathcal{C}_2 \times \dots \times \mathcal{C}_m, \qquad k = (k^*)^m $$Every combination of one centroid per subvector is a valid centroid of the full space, but you never store those combinations.
Worked Example
128 dimensions is too many to follow by hand, so let’s shrink everything. Here are 8 vectors with 4 dimensions each:
| dim 1 | dim 2 | dim 3 | dim 4 | |
|---|---|---|---|---|
| $y_1$ | 1.2 | 0.8 | 3.1 | 4.2 |
| $y_2$ | 0.7 | 1.4 | 5.8 | 2.3 |
| $y_3$ | 1.1 | 5.3 | 0.4 | 2.2 |
| $y_4$ | 1.6 | 4.6 | 2.7 | 0.3 |
| $y_5$ | 4.8 | 1.3 | 3.4 | 3.6 |
| $y_6$ | 5.4 | 0.6 | 0.2 | 1.7 |
| $y_7$ | 4.6 | 5.2 | 6.3 | 1.6 |
| $y_8$ | 5.3 | 4.7 | 3.3 | 0.6 |
We’ll use $m = 2$, so each vector is split into two halves: dims 1–2 and dims 3–4. Each half gets a codebook with $k^* = 4$ centroids. That’s two codebooks with four centroids each, not one centroid per vector.
Split: Cut every vector in half. $y_1$ becomes $(1.2, 0.8)$ and $(3.1, 4.2)$.
Train one codebook per half: Take the first half of all 8 vectors, which gives 8 points in 2-D, and run k-means with $k = 4$. Then do the same, separately, for the 8 second halves.
Each centroid ends up as the mean of the points in its cluster, which is why the centroids are floats. For example, $y_1$ and $y_2$ end up in the same cluster for the first half, so that centroid is
$$ \frac{(1.2, 0.8) + (0.7, 1.4)}{2} = (0.95,\ 1.10) $$Here are both codebooks:
| Centroid | Built from | Centroid | Built from | ||
|---|---|---|---|---|---|
| $q_1$ #0 | (0.95, 1.10) | $y_1, y_2$ | $q_2$ #0 | (0.30, 1.95) | $y_3, y_6$ |
| $q_1$ #1 | (1.35, 4.95) | $y_3, y_4$ | $q_2$ #1 | (3.00, 0.45) | $y_4, y_8$ |
| $q_1$ #2 | (4.95, 4.95) | $y_7, y_8$ | $q_2$ #2 | (3.25, 3.90) | $y_1, y_5$ |
| $q_1$ #3 | (5.10, 0.95) | $y_5, y_6$ | $q_2$ #3 | (6.05, 1.95) | $y_2, y_7$ |
Two things stand out. Every centroid is shared by more than one vector. And the groups are different in each half: $y_1$ and $y_2$ share a centroid in $q_1$ but end up in different clusters in $q_2$. The two codebooks know nothing about each other.
Encoding: For each half of a vector, find the nearest centroid in that half’s codebook and keep only its number. For $y_1$, the squared distances are:
| Distance to #0 | #1 | #2 | #3 | Nearest | |
|---|---|---|---|---|---|
| first half (1.2, 0.8) vs. $q_1$ | 0.15 | 17.24 | 31.28 | 15.23 | 0 |
| second half (3.1, 4.2) vs. $q_2$ | 12.90 | 14.07 | 0.11 | 13.76 | 2 |
For example, the distance from $(1.2, 0.8)$ to $q_1$’s centroid #0 at $(0.95, 1.10)$ is $(1.2 - 0.95)^2 + (0.8 - 1.10)^2 = 0.0625 + 0.09 = 0.15$.
So $y_1$ is stored as the code $(0, 2)$. Each number is between 0 and 3, so it fits in 2 bits, and the whole vector becomes 4 bits: 00 10. This is the quantized code for $y_1$. Repeating the same step for every vector gives:
| Code | Bits | Reconstructed vector | Squared error | |
|---|---|---|---|---|
| $y_1$ | (0, 2) | 0010 | (0.95, 1.10, 3.25, 3.90) | 0.26 |
| $y_2$ | (0, 3) | 0011 | (0.95, 1.10, 6.05, 1.95) | 0.34 |
| $y_3$ | (1, 0) | 0100 | (1.35, 4.95, 0.30, 1.95) | 0.26 |
| $y_4$ | (1, 1) | 0101 | (1.35, 4.95, 3.00, 0.45) | 0.30 |
| $y_5$ | (3, 2) | 1110 | (5.10, 0.95, 3.25, 3.90) | 0.33 |
| $y_6$ | (3, 0) | 1100 | (5.10, 0.95, 0.30, 1.95) | 0.29 |
| $y_7$ | (2, 3) | 1011 | (4.95, 4.95, 6.05, 1.95) | 0.37 |
| $y_8$ | (2, 1) | 1001 | (4.95, 4.95, 3.00, 0.45) | 0.30 |
Here the codes match the clusters k-means found while training, because these 8 vectors are also the training data. In practice, k-means runs once on a training sample, and this encoding step is how every other vector gets its code, including vectors added later.
Decoding: Take the code, fetch each centroid from its codebook, and put the halves back together. That’s the “Reconstructed vector” column. It isn’t exactly the original vector, and the difference is the quantization error, but it’s close.
Notice that every vector got a different code, even though each codebook has only 4 centroids. Two codebooks of 4 give $4 \times 4 = 16$ possible codes. That’s the whole trick of product quantization, and it scales up fast: with $m = 8$ codebooks of 256 centroids each, there are $256^8 = 2^{64}$ possible codes, while you only ever store 2,048 centroids.
Choosing m and k*
For a fixed code length, the paper found it’s better to use fewer subquantizers with more centroids each. A bigger $k^*$ isn’t free, though: quantization gets slower and the lookup tables may stop fitting in cache. The authors settle on $k^* = 256$ and $m = 8$ as “often a reasonable choice”.
They also looked at rotating vectors with a random orthogonal matrix to spread energy evenly across subvectors. For most data they don’t recommend it, because neighboring dimensions tend to be correlated and are better quantized together.
Searching with Quantization
Computing Distances from Codes
Once the database is stored as codes, there are two ways to estimate $d(x, y)$. With symmetric distance computation (SDC), the query is quantized too and you compute $d(q(x), q(y))$. With asymmetric distance computation (ADC), the query stays as it is and you compute $d(x, q(y))$.
SDC pays for quantization twice, and the error bounds reflect that. For a quantizer that satisfies Lloyd’s conditions, the mean squared distance error of ADC is bounded by the quantizer’s MSE (mean squared error), while for SDC the bound is twice that.
Worked Example with ADC
Let’s run a query against the 8 vectors from the worked example above. At this point the original vectors are gone. All we have are the two codebooks and the codes:
| Centroid | $q_1$ (dims 1–2) | $q_2$ (dims 3–4) |
|---|---|---|
| #0 | (0.95, 1.10) | (0.30, 1.95) |
| #1 | (1.35, 4.95) | (3.00, 0.45) |
| #2 | (4.95, 4.95) | (3.25, 3.90) |
| #3 | (5.10, 0.95) | (6.05, 1.95) |
The query is $x = (1.0,\ 4.8,\ 2.9,\ 0.6)$, and we want the stored vector closest to it.
Split the query: Split it the same way as the data: $(1.0, 4.8)$ and $(2.9, 0.6)$. The query is not encoded. We keep its exact values, which is what makes this asymmetric.
Build the lookup tables: Every stored vector’s first half is one of the 4 centroids in $q_1$, so there are only 4 possible first halves in the whole database. Compute the squared distance from the query’s first half to each of them. Then do the same for the second half against $q_2$.
It’s important to compute all of them, not just the closest one. We don’t know yet which centroids the stored vectors use, so we need every answer ready.
$T_1$: the query’s first half, $(1.0, 4.8)$, against each centroid of $q_1$.
| Entry | Centroid | Difference | Squared distance |
|---|---|---|---|
| $T_1[0]$ | (0.95, 1.10) | (0.05, 3.70) | 0.0025 + 13.6900 = 13.6925 |
| $T_1[1]$ | (1.35, 4.95) | (−0.35, −0.15) | 0.1225 + 0.0225 = 0.1450 |
| $T_1[2]$ | (4.95, 4.95) | (−3.95, −0.15) | 15.6025 + 0.0225 = 15.6250 |
| $T_1[3]$ | (5.10, 0.95) | (−4.10, 3.85) | 16.8100 + 14.8225 = 31.6325 |
$T_2$: the query’s second half, $(2.9, 0.6)$, against each centroid of $q_2$.
| Entry | Centroid | Difference | Squared distance |
|---|---|---|---|
| $T_2[0]$ | (0.30, 1.95) | (2.60, −1.35) | 6.7600 + 1.8225 = 8.5825 |
| $T_2[1]$ | (3.00, 0.45) | (−0.10, 0.15) | 0.0100 + 0.0225 = 0.0325 |
| $T_2[2]$ | (3.25, 3.90) | (−0.35, −3.30) | 0.1225 + 10.8900 = 11.0125 |
| $T_2[3]$ | (6.05, 1.95) | (−3.15, −1.35) | 9.9225 + 1.8225 = 11.7450 |
The difference is the query half minus the centroid, and the squared distance is the sum of the squared differences. Put together, the two lookup tables are:
| #0 | #1 | #2 | #3 | |
|---|---|---|---|---|
| $T_1$ | 13.6925 | 0.1450 | 15.6250 | 31.6325 |
| $T_2$ | 8.5825 | 0.0325 | 11.0125 | 11.7450 |
That’s 8 small distance calculations, done once per query. It’s the only real arithmetic the query needs, and it doesn’t depend on how many vectors are stored.
Score every code with lookups: For a code $(i, j)$, the estimated squared distance is $T_1[i] + T_2[j]$. The first number in the code picks a column of $T_1$, and the second picks a column of $T_2$:
| Code | $T_1[i] + T_2[j]$ | Estimate | |
|---|---|---|---|
| $y_1$ | (0, 2) | 13.6925 + 11.0125 | 24.7050 |
| $y_2$ | (0, 3) | 13.6925 + 11.7450 | 25.4375 |
| $y_3$ | (1, 0) | 0.1450 + 8.5825 | 8.7275 |
| $y_4$ | (1, 1) | 0.1450 + 0.0325 | 0.1775 |
| $y_5$ | (3, 2) | 31.6325 + 11.0125 | 42.6450 |
| $y_6$ | (3, 0) | 31.6325 + 8.5825 | 40.2150 |
| $y_7$ | (2, 3) | 15.6250 + 11.7450 | 27.3700 |
| $y_8$ | (2, 1) | 15.6250 + 0.0325 | 15.6575 |
There’s no subtraction or squaring in this step, just two reads and one addition per vector. Notice that $y_1$ and $y_2$ both start with index 0, so both reuse $T_1[0]$. Every entry in both tables ends up being used by some vector, which is why we fill the tables completely.
Rank: Sorting by the estimate gives $y_4$, $y_3$, $y_8$, $y_1$, $y_2$, $y_7$, $y_6$, $y_5$. The nearest neighbor of $x$ is $y_4$.
Why adding two table entries gives a distance: The code $(1, 1)$ stands for the vector you’d get by decoding $y_4$: $q_1$’s #1 followed by $q_2$’s #1, which is $(1.35, 4.95, 3.00, 0.45)$. The squared distance from $x$ to that vector, worked out the long way, is
$$ \underbrace{(1.0 - 1.35)^2 + (4.8 - 4.95)^2}_{T_1[1] \,=\, 0.1450} + \underbrace{(2.9 - 3.00)^2 + (0.6 - 0.45)^2}_{T_2[1] \,=\, 0.0325} = 0.1775 $$A squared distance is a sum over dimensions, so it splits into one piece per subvector. The tables just hold every piece we might need, computed in advance.
How close is it? In a real system you can’t check, because the original vectors are gone. Here we still have them, so we can compare the estimates with the true squared distances:
| Estimate (from codes) | True (from original vectors) | |
|---|---|---|
| $y_4$ | 0.18 | 0.53 |
| $y_3$ | 8.73 | 9.07 |
| $y_8$ | 15.66 | 18.66 |
| $y_1$ | 24.71 | 29.04 |
| $y_2$ | 25.44 | 22.95 |
| $y_7$ | 27.37 | 25.68 |
| $y_6$ | 40.22 | 45.50 |
| $y_5$ | 42.65 | 35.94 |
The estimates measure the distance to each vector’s decoded version, not the original, so none of them is exact. The top three are still right, and in the right order. Further down, $y_1$ and $y_2$ swap places, and so do $y_5$ and $y_6$. That’s the accuracy you give up for storing 4 bits per vector instead of 16 bytes.
Note
This toy example only shows the mechanics. The paper analyzes the distance error of ADC and SDC in detail. It shows that both underestimate distances on average, and derives a corrected estimator.
Non-exhaustive Search: IVFADC
ADC is cheap per vector, but it still looks at every vector. With billions of vectors, a full scan is too slow. The paper’s answer is to put an inverted file in front of ADC.
First, a coarse quantizer $q_c$ (k-means with $k'$ centroids, typically between a thousand and a million for SIFT) assigns each vector to a cell. Then, instead of encoding the vector itself, PQ encodes the residual $r(y) = y - q_c(y)$, which is where the vector sits inside its cell. The paper describes the coarse cell as the “most significant bits” and the PQ code as the “least significant bits”.
Residuals are much smaller than the original vectors, so the same 8 bytes describe them more precisely.
To add a vector, find its coarse centroid, compute the residual, PQ-encode it, and append (id, code) to that cell’s list. To search:
- Find the query’s $w$ nearest coarse centroids. Looking at more than one cell catches neighbors that sit just across a cell boundary. This only applies to the query, so the index doesn’t grow.
- For each of those cells, compute the query’s residual and build the ADC tables.
- Scan the cells’ lists, adding up $m$ table lookups per entry.
- Keep the best $K$ results in a fixed-size max-heap.
With balanced lists, a search scans about $n \cdot w / k'$ entries.
Results
Refer to the paper for the results.
References
- H. Jégou, M. Douze, C. Schmid. Product Quantization for Nearest Neighbor Search. IEEE Transactions on Pattern Analysis and Machine Intelligence, 33(1), 2011.
- Lloyd’s algorithm, Wikipedia.