Search

Search papers and lessons

Product Quantization

Level 3 · 12 min read

Product quantization cuts each long vector into short pieces, replaces every piece with the index of its nearest codebook entry, and estimates distances by table lookup, so billions of vectors fit in memory.

On this page

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

TL;DR

Product quantization stores a large collection of vectors in a very small amount of memory, and still lets you find the vectors closest to a query. It splits each vector into short pieces, replaces each piece with the index of its nearest entry in a small codebook, and estimates the distance from a query to every stored vector by adding up table lookups. A vector that took 512 bytes can be stored in 8 bytes, at the cost of approximate distances.

Builds on: Euclidean Distance, Vector Quantization · Leads to: FAISS, ScaNN

Where it's used

  • Billion-scale search. The FAISS library, described in its paper, uses product quantization to hold collections of about a billion vectors on GPUs and search them quickly. Without compression, a billion 128-dimensional vectors would need hundreds of gigabytes of memory.
  • Retrieval for language models. Retrieval-augmented generation systems feed documents to a language model and store one embedding per passage. For a large corpus, compressing those embeddings decides whether the index fits on one machine or must be split across many.
  • Recommendation and ad matching. Systems that run maximum inner product search of a user vector against millions of item vectors per request use compressed codes so that each lookup touches a few bytes per item rather than a full float vector.

How it works

Take one small vector and trace it through encoding and then a search. The vector has six numbers, split into three pieces of two numbers each. Each piece has its own codebook with two entries.

  1. Split the vector. Let x=(0,1,5,5,1,0)x = (0, 1, 5, 5, 1, 0). Cut it into three pieces: x1=(0,1)x_1 = (0, 1), x2=(5,5)x_2 = (5, 5), x3=(1,0)x_3 = (1, 0). Check: the pieces, put back together, give the original six numbers.
  2. Look up the nearest codebook entry for each piece. The codebooks are C1={(0,0),(2,2)}C_1 = \{(0,0), (2,2)\}, C2={(6,5),(3,3)}C_2 = \{(6,5), (3,3)\} and C3={(0,1),(2,0)}C_3 = \{(0,1), (2,0)\}. For x1=(0,1)x_1 = (0, 1), the squared distance to (0,0)(0,0) is 1 and to (2,2)(2,2) is 5, so the code is entry 0. Check: the code is the entry with the smaller distance.
  3. Finish encoding. For x2=(5,5)x_2 = (5,5) the code is entry 0, since (6,5)(6,5) is at distance 1 and (3,3)(3,3) is at distance 8. For x3=(1,0)x_3 = (1,0) the code is entry 1, since (2,0)(2,0) is at distance 1 and (0,1)(0,1) is at distance 2. The stored vector is the code (0,0,1)(0, 0, 1): three small indices instead of six numbers.
  4. Measure the error. Rebuild the vector from the codes: x~=(0,0,  6,5,  2,0)\tilde{x} = (0,0,\; 6,5,\; 2,0). The difference from the original is (0,1,−1,0,−1,0)(0, 1, -1, 0, -1, 0), whose squared length is 33. The stored code is an approximation, and this is the price of compression.
  5. Prepare the lookup tables for a query. A query q=(1,0,5,4,0,0)q = (1, 0, 5, 4, 0, 0) is not compressed. For each piece, compute its squared distance to every codebook entry. For the first piece q1=(1,0)q_1 = (1,0): entry 0 gives 1 and entry 1 gives 5. For the second piece q2=(5,4)q_2 = (5,4): entry 0 gives 2 and entry 1 gives 5. For the third piece q3=(0,0)q_3 = (0,0): entry 0 gives 1 and entry 1 gives 4. Check: each piece has one number per codebook entry, six numbers in all.
  6. Estimate the distance by lookup. For the stored code (0,0,1)(0,0,1), read the tables at those indices and add: 1+2+4=71 + 2 + 4 = 7. Check: the exact squared distance from qq to the rebuilt vector x~\tilde{x} is 1+1+1+4=71 + 1 + 1 + 4 = 7, the same number. For a second stored vector with code (1,0,0)(1,0,0), the lookups give 5+2+1=85 + 2 + 1 = 8, so the search ranks the first vector closer.

The search never touches the original vectors. It only reads the codes and the tables, which is why it is fast and small.

flowchart LR
  A["Database vector"] --> B["Split into pieces"]
  B --> C["Nearest codebook index per piece"]
  C --> D["Stored code: a few small integers"]
  Q["Query vector"] --> E["Distance from each piece to every codebook entry"]
  E --> F["Lookup tables, computed once per query"]
  D --> G["Sum table entries for each stored code"]
  F --> G
  G --> H["Approximate distances, then the nearest"]

The math

Definition: Product quantizer

A product quantizer splits each vector x∈Rdx \in \mathbb{R}^d into mm pieces of d/md/m numbers each, x=[x1,…,xm]x = [x_1, \ldots, x_m]. For each piece jj it learns a codebook CjC_j of kk vectors, usually by k-means clustering on a training sample. A vector is stored as mm indices, one per piece, which take mlog⁡2km \log_2 k bits in total.

Split

A vector xx with dd numbers becomes mm pieces, and the pieces are taken in order: the first d/md/m numbers form piece 1, the next d/md/m form piece 2, and so on. In the trace, d=6d = 6, m=3m = 3, so each piece has two numbers. In the realistic case below, d=128d = 128 and m=8m = 8, so each piece has 16 numbers.

Encode

The code for piece jj is the index of its nearest codebook entry:

ij(x)=arg⁡min⁡i∈{1,…,k}∥xj−cj,i∥2i_j(x) = \arg\min_{i \in \{1, \ldots, k\}} \lVert x_j - c_{j,i} \rVert^2

Here cj,ic_{j,i} is entry ii of codebook CjC_j, and ∥⋅∥2\lVert \cdot \rVert^2 is the squared Euclidean distance. The full code is (i1(x),…,im(x))(i_1(x), \ldots, i_m(x)). In step 2 of the trace, ∥x1−(0,0)∥2=1\lVert x_1 - (0,0) \rVert^2 = 1 and ∥x1−(2,2)∥2=5\lVert x_1 - (2,2) \rVert^2 = 5, so i1=0i_1 = 0.

Reconstruct

The approximation of xx is the concatenation of the chosen entries:

x~=[c1,i1(x),…,cm,im(x)]\tilde{x} = \left[c_{1, i_1(x)}, \ldots, c_{m, i_m(x)}\right]

Step 4 of the trace computes ∥x−x~∥2=3\lVert x - \tilde{x} \rVert^2 = 3.

Estimate distance by lookup

For a query qq, split it the same way and precompute, for each piece and each codebook entry, the table value Tj[i]=∥qj−cj,i∥2T_j[i] = \lVert q_j - c_{j,i} \rVert^2. Because squared Euclidean distance over concatenated pieces is the sum of the distances over the pieces, the distance to the reconstruction is

∥q−x~∥2=∑j=1m∥qj−cj,ij(x)∥2=∑j=1mTj[ij(x)]\lVert q - \tilde{x} \rVert^2 = \sum_{j=1}^{m} \lVert q_j - c_{j, i_j(x)} \rVert^2 = \sum_{j=1}^{m} T_j\big[i_j(x)\big]

This identity is exact for the reconstruction. The only approximation is replacing xx by x~\tilde{x}. Step 6 of the trace gives T1[0]+T2[0]+T3[1]=1+2+4=7T_1[0] + T_2[0] + T_3[1] = 1 + 2 + 4 = 7, which equals ∥q−x~∥2\lVert q - \tilde{x} \rVert^2.

The cost per stored vector is mm table reads and m−1m - 1 additions, which does not depend on the vector's original length dd.

Worked examples

Example
Tiny: size of one code

A 6-number vector split into 3 pieces, each with a codebook of 2 entries.

  1. Each piece needs one index, and an index into 2 entries takes log⁡22=1\log_2 2 = 1 bit.
  2. Three pieces need 3×1=33 \times 1 = 3 bits.
  3. The original vector needs 6 numbers. If each is a 32-bit float, that is 6×32=1926 \times 32 = 192 bits.
  4. The code is 192/3=64192 / 3 = 64 times smaller.

Interpretation: the compression ratio depends on how many bits each piece's index takes compared with the bits of the numbers it replaces.

Example
Standard: a 128-dimensional vector with 8 pieces of 256 entries

This is a common setting for image and text embeddings.

  1. A 128-number vector stored as 32-bit floats takes 128×4=512128 \times 4 = 512 bytes.
  2. Split it into m=8m = 8 pieces of 128/8=16128/8 = 16 numbers each.
  3. Use k=256k = 256 entries per codebook. An index into 256 entries takes log⁡2256=8\log_2 256 = 8 bits, which is one byte.
  4. The code takes 8×1=88 \times 1 = 8 bytes.
  5. The compression ratio is 512/8=64512 / 8 = 64.
  6. The codebooks are shared by all vectors, so their cost is paid once: 8×256×16×4=131,0728 \times 256 \times 16 \times 4 = 131{,}072 bytes, about 128 kilobytes.
  7. For each query, the lookup tables hold 8×256=20488 \times 256 = 2048 numbers. That is cheap to build compared with comparing the query to every stored vector.

Interpretation: 64 times less memory per vector, and a query costs about 2000 table entries plus 8 reads per stored vector.

Example
Realistic: a billion vectors on one machine

A collection of a billion vectors, each with 128 floats.

  1. Uncompressed, the collection is 109×51210^9 \times 512 bytes =512= 512 gigabytes.
  2. With the 8-byte codes from the standard example, the codes take 109×810^9 \times 8 bytes =8= 8 gigabytes.
  3. The codebooks add about 128 kilobytes, which is negligible.
  4. A search that scans all codes reads 8 bytes per vector instead of 512, and does 8 lookups per vector instead of 128 multiplications and additions.
  5. Try it: suppose you use 16 pieces instead of 8, each still with 256 entries. How many gigabytes do the codes take for a billion vectors, and what is the compression ratio?

Answer: 16 bytes per vector, so 109×1610^9 \times 16 bytes =16= 16 gigabytes, and the compression ratio is 512/16=32512 / 16 = 32. Doubling the pieces halves the compression, but it doubles the bits per vector, which is what buys back accuracy.

Common mistakes and tradeoffs

It is tempting to think that compressed vectors give the same distances as the originals. In fact the distance is to the reconstruction x~\tilde{x}, not to xx, so two vectors can swap order when their distances are close. The standard fix is to re-rank: use the codes to shortlist a few hundred candidates, then compute exact distances to the original vectors for those candidates only.

It is tempting to think that each piece of the vector is independent of the others. In fact the method assumes that the distance adds up over the pieces, which is exact for the reconstruction, but a codebook built on one piece cannot exploit correlations between pieces. When features are strongly correlated across pieces, the codebooks waste entries. Optimized product quantization fixes this by learning a rotation of the vectors before the split, so that the pieces are closer to independent.

It is tempting to think that more pieces are always better. More pieces means more bits per vector and bigger lookup tables, so memory and per-query cost grow. For a fixed bit budget the opposite can happen: shorter codes with more pieces and fewer entries per codebook can approximate worse. The right number balances the memory budget against the accuracy the application needs. Scalar quantization, which rounds each number to a few bits, compresses by a factor of about 4 to 8 with little loss and needs no codebook training. Graph-based indexes such as HNSW are more accurate at a given speed, but they keep the full vectors in memory, so they cannot shrink the collection.

MethodTypical compressionAccuracyBest when
Scalar quantization4 to 8 timesHighMemory is tight but the collection is moderate
Product quantization16 to 64 times or moreLower; re-ranking recovers much of itThe collection is very large and must fit in memory
Graph index (HNSW)None: full vectors keptVery highThe collection fits in memory and speed matters most

History

Vector quantization, which replaces a vector by the nearest entry of a list, came out of signal compression work in the 1980s. Its codebooks are trained with the k-means procedure, whose basic idea dates to the 1950s.

In 2011, Jégou, Douze and Schmid published product quantization for nearest neighbor search, showing that splitting vectors into pieces made large codebooks affordable and that distances could be estimated by table lookup. It became the standard way to compress vectors for search.

In 2017, Johnson, Douze and Jégou published the FAISS library and its paper on billion-scale similarity search on GPUs. FAISS combined product quantization with fast GPU search, and it made searching a billion vectors practical for many teams. ScaNN, published in 2019, refined the idea by training the codebooks to minimize the errors that matter most for maximum inner product search, which is the form of search used in many recommendation and retrieval systems.

Recap

  • Product quantization splits each vector into mm pieces and stores one codebook index per piece.
  • Distances are estimated by adding mm table lookups, with the tables built once per query.
  • A 128-number float vector (512 bytes) can shrink to 8 bytes with 8 pieces and 256 entries each.
  • The estimate is to the reconstruction, not the original, so re-ranking a shortlist with exact distances is standard practice.
  • Read next: Billion-scale similarity search with GPUs for the system that made billion-scale search practical, and Approximate Nearest Neighbor Search for the wider family of methods this belongs to.

Check yourself

QuestionA vector has 64 numbers. It is split into 8 pieces of 8 numbers, each with a codebook of 16 entries. How many bits does the code for one vector take?Show answer

Each piece needs an index into 16 entries, which takes log⁡216=4\log_2 16 = 4 bits. Eight pieces take 8×4=328 \times 4 = 32 bits, or 4 bytes. The original 64 floats take 64×32=204864 \times 32 = 2048 bits, so the code is 64 times smaller.

QuestionIn the trace, the query's table values for the stored code (0,0,1)(0,0,1) are T1[0]=1T_1[0] = 1, T2[0]=2T_2[0] = 2 and T3[1]=4T_3[1] = 4. What is the estimated squared distance, and why is it exact for the reconstruction?Show answer

The estimate is 1+2+4=71 + 2 + 4 = 7. It equals the exact squared distance from the query to the reconstructed vector x~=(0,0,6,5,2,0)\tilde{x} = (0,0,6,5,2,0), because squared Euclidean distance over the concatenated pieces is the sum of the squared distances over the pieces. The estimate differs from the distance to the original xx only because xx was replaced by x~\tilde{x}.

QuestionWhy might a search engine using product quantization return a slightly wrong nearest neighbor, and what is the usual remedy?Show answer

The distances are computed to the reconstructed vectors, not the originals, so two candidates whose true distances are close can swap places. The usual remedy is to shortlist a few hundred candidates with the compressed codes, then recompute exact distances to the original vectors for only that shortlist.

QuestionA team has 50 million embeddings of 768 [[floating-point-numbers|floats]] each, stored as 32-bit floats, and must fit them on a machine with 16 gigabytes of memory for search. Roughly how many bytes per vector can they spend, and is product quantization a natural choice?Show answer

Uncompressed, each vector takes 768×4=3072768 \times 4 = 3072 bytes, so 50 million vectors take about 154 gigabytes. Sixteen gigabytes over 50 million vectors leaves about 320 bytes per vector. That is a compression of roughly 10 times, comfortably within what product quantization gives (for example 96 pieces with 1 byte each is 96 bytes per vector). Product quantization is a natural choice here, and re-ranking a shortlist with the original vectors would need them on disk rather than in memory.

Sources