Sub topic 8
Compressing vectors with product quantization
This chapter assumes you know what an IVF index is, how recall is measured against an exact baseline, and that a float32 vector of dimension d takes 4·d bytes.
Why compress vectors
A graph or IVF index still stores every full vector. One hundred million 768-dimensional float32 vectors take about 307 GB. Compression stores a short code per vector instead, which cuts memory by 10x to 100x. The cost is that distances computed from codes are approximate, so recall drops.
How product quantization works
Product quantization (PQ) splits each vector into m equal sub-vectors. For each sub-space, k-means learns a codebook of 256 centroids. A vector is then stored as m one-byte centroid ids.
- Split a d-dimensional vector into m sub-vectors of d/m dimensions.
- Train a 256-entry codebook per sub-space on a sample of the data.
- Replace each sub-vector with the id of its nearest centroid.
With d = 768 and m = 96, each vector shrinks from 3072 bytes to 96 bytes, a 32x reduction. The codebooks are small and shared by all vectors.
Searching compressed vectors
At query time the query is not compressed. For each sub-space, you compute the distance from the query's sub-vector to all 256 centroids and keep the results in a lookup table. The distance to a stored vector is then the sum of m table lookups. This is called asymmetric distance computation, and it is fast because it never touches the original floats.
PQ is commonly combined with IVF as IVFPQ. IVF narrows the search to a few clusters, and PQ makes scanning each cluster cheap and small.
Example with FAISS
import numpy as np
import faiss
d, nlist, m = 64, 100, 8
rng = np.random.default_rng(0)
xb = rng.normal(size=(20000, d)).astype("float32")
xq = xb[:100]
k = 10
flat = faiss.IndexFlatL2(d)
flat.add(xb)
_, true_ids = flat.search(xq, k)
quantizer = faiss.IndexFlatL2(d)
index = faiss.IndexIVFPQ(quantizer, d, nlist, m, 8) # 8 bits per code
index.train(xb)
index.add(xb)
index.nprobe = 10
_, ann_ids = index.search(xq, k)
recall = np.mean([len(set(a) & set(t)) / k for a, t in zip(ann_ids, true_ids)])
print(f"recall@{k}: {recall:.3f}")
print("bytes per vector:", m, "vs", d * 4)Each vector uses 8 bytes instead of 256. Expect noticeably lower recall than an uncompressed index on this random data. Random Gaussian vectors have no cluster structure, so they are a hard case for PQ. Real embeddings usually do better.
Tuning and common errors
| Parameter | Effect of raising it |
|---|---|
| m (sub-vectors) | Higher recall, larger codes, slower scans |
| Bits per code | Higher recall, larger codebooks and codes |
| nprobe (IVF) | Higher recall, higher latency |
Common mistakes:
- Training on too few vectors. Each codebook has 256 centroids, so use at least tens of thousands of training vectors.
- Choosing an m that does not divide d. FAISS requires d to be a multiple of m.
- Training on data that differs from production data. After a shift in the embedding model or data, retrain the codebooks.
- Using PQ output as the final ranking. A common fix is to retrieve more candidates with PQ, such as the top 100, then re-rank them with the original full vectors.
Exercise
A collection holds 50 million vectors with d = 1024 in float32. You use PQ with m = 128 and 8 bits per sub-vector. How many bytes does each code take, and what is the compression ratio?
Show answer
Each code takes 128 bytes (128 sub-vectors at 1 byte each). The original vector takes 1024 × 4 = 4096 bytes, so the ratio is 4096 / 128 = 32x. The codes for 50 million vectors take about 6.4 GB.