Sub topic 8
Compressing vectors with product quantization
Earlier chapters showed that HNSW and IVF cut the number of distance computations per query. They do not shrink the vectors. A graph or cluster index still has to keep every full-precision vector in memory. This chapter covers product quantization (PQ), which shrinks the vectors themselves, usually by 8x to 64x or more, at the cost of some accuracy.
This chapter assumes you know what an IVF index does (centroids, nlist, nprobe), what k-means clustering is, and how recall is measured against an exact baseline. It also assumes basic NumPy.
Why memory becomes the limit
A float32 vector stores 4 bytes per dimension. The table below shows what that costs for a common embedding size of 768 dimensions.
| Vectors | Raw float32 size | With PQ at 96 bytes per vector |
|---|---|---|
| 1 million | about 3.1 GB | about 96 MB |
| 100 million | about 307 GB | about 9.6 GB |
| 1 billion | about 3 TB | about 96 GB |
The raw sizes exclude index overhead. HNSW adds a link list per vector on top of them. Once the data no longer fits in RAM, queries must read from disk or the index must be split across machines. Both cost latency and money. Compression is the main way to keep a large index on one machine.
The core idea: quantize pieces, not the whole vector
Quantization means replacing a value with the nearest member of a small, fixed set of representatives. The simplest vector version is k-means. You cluster the vectors, store each vector as the ID of its nearest centroid, and use the centroid as an approximation.
That does not work well for high-dimensional vectors. To get a reasonable approximation of 768-dimensional data you would need millions of centroids. With 2^64 possible codes, which is what an 8-byte code gives you, you could never train or store the centroid table.
PQ avoids this by splitting each vector into m equal subvectors and quantizing each one independently:
- Split a
d-dimensional vector intomsubvectors ofd/mdimensions each. - For each subvector position, run k-means on the training data to learn a codebook of
2^nbitscentroids. Withnbits = 8this is 256 centroids. - Encode a vector by replacing each subvector with the index of its nearest centroid in that position's codebook.
The code for one vector is m small integers. With m = 8 and nbits = 8, a vector takes 8 bytes. The effective number of representable points is 256^8, about 1.8 × 10^19. Yet you only stored 8 codebooks of 256 small centroids each.
Training and parameters
PQ has a training step. The codebooks are learned from a sample of your data, so the sample should look like the data you will later add and query. If the data distribution drifts, for example you switch embedding models, the codebooks become poor fits and you must retrain and re-encode.
| Parameter | Meaning | Effect of increasing it |
|---|---|---|
| `m` | Number of subvectors. `d` must be divisible by `m`. | Larger codes, better accuracy, slower scans |
| `nbits` | Bits per subvector code. Typically 8. | Finer codebooks, larger codes, longer training |
| Training set size | Vectors used for k-means | Better codebooks, longer training |
The compression ratio for float32 input is 4d / (m · nbits / 8). For d = 768, m = 96, and nbits = 8, that is 3072 / 96 = 32x.
As a rule of thumb, FAISS needs several dozen training vectors per centroid. For 256 centroids per codebook, at least about 10,000 training vectors is a reasonable floor. Fewer than 256 raises warnings or errors.
How search works on compressed codes
You never decompress the stored vectors during search. Instead, PQ uses asymmetric distance computation (ADC). The query stays at full precision, and only the database vectors are quantized.
- Split the query into
msubvectors. - For each subvector position, compute the distance from the query subvector to all 256 centroids in that codebook. This builds a lookup table of
m × 256numbers. - For each stored code, the approximate squared distance is the sum of
mtable lookups, one per code byte.
Step 2 happens once per query. Step 3 replaces a d-dimensional distance with m additions and memory lookups, and the lookups hit a small table that fits in CPU cache. That is why PQ speeds up scanning as well as saving memory.
Symmetric distance computation (SDC) quantizes the query too. It is slightly faster but less accurate, so ADC is the usual choice.
The error you introduce
Each stored vector is replaced by a point built from centroids. The distance between the original and the reconstruction is the quantization error. PQ distances are therefore noisy estimates. This has three consequences:
- A true neighbor can rank below position
kbecause its estimated distance was too high. Recall drops. - Errors are largest for vectors near the boundary between centroids.
- Ranking noise matters most when many candidates have similar distances, which is common in high dimensions.
Two techniques reduce this:
- Re-ranking. Retrieve more candidates than you need, for example
4k, using PQ distances. Then load the full-precision vectors for those candidates only and re-score them exactly. The full vectors can live on disk or in a slower store because only a few are read per query. - Optimized product quantization (OPQ). Learn a rotation of the vector space before splitting, so information is spread more evenly across subvectors. This typically improves recall at the same code size.
PQ combined with IVF
PQ alone still scans every code, which is a linear scan with a cheap distance. Combining it with IVF restricts the scan to a few clusters. This is the classic IVF-PQ index.
A detail matters here. IVF-PQ usually quantizes the residual, which is the vector minus its cluster centroid. Residuals have a smaller range than raw vectors, so the same codebook size encodes them more precisely. FAISS does this automatically in IndexIVFPQ.
The next example builds an IVF-PQ index and a version with exact re-ranking. It measures recall@10 against an exact baseline.
import numpy as np
import faiss
d = 64
rng = np.random.default_rng(0)
xb = rng.normal(size=(20000, d)).astype("float32")
xq = xb[:100]
k = 10
# Exact baseline
flat = faiss.IndexFlatL2(d)
flat.add(xb)
_, true_ids = flat.search(xq, k)
def recall(ids):
return np.mean([len(set(a) & set(t)) / k for a, t in zip(ids, true_ids)])
# IVF-PQ: 128 clusters, 8 subvectors, 8 bits each (8 bytes per vector)
nlist, m, nbits = 128, 8, 8
quantizer = faiss.IndexFlatL2(d)
ivfpq = faiss.IndexIVFPQ(quantizer, d, nlist, m, nbits)
ivfpq.train(xb)
ivfpq.add(xb)
ivfpq.nprobe = 16
_, ids = ivfpq.search(xq, k)
print(f"IVF-PQ recall@{k}: {recall(ids):.3f}")
# Same index, re-ranked with exact distances on 4x as many candidates
quantizer2 = faiss.IndexFlatL2(d)
base = faiss.IndexIVFPQ(quantizer2, d, nlist, m, nbits)
base.nprobe = 16
refined = faiss.IndexRefineFlat(base)
refined.train(xb)
refined.add(xb)
refined.k_factor = 4
_, ids = refined.search(xq, k)
print(f"IVF-PQ + refine recall@{k}: {recall(ids):.3f}")
print("bytes per vector, raw:", d * 4, " compressed code:", m * nbits // 8)This data is random Gaussian noise, which has no cluster structure for PQ to exploit. Expect lower recall here than on real embeddings, and treat the numbers as a demonstration of the method rather than a benchmark. The refined index should score higher than the plain one. Note that IndexRefineFlat keeps the full vectors in memory, so this version saves no RAM. In production you would store the full vectors on slower storage.
Other compression methods
PQ is one option. The others trade differently.
| Method | Compression | Accuracy loss | Notes |
|---|---|---|---|
| Scalar quantization (int8) | 4x | Small | No training of codebooks, only value ranges. Fast and simple. |
| Half precision (float16) | 2x | Very small | Often a safe first step. |
| Product quantization | 8x to 64x or more | Moderate, needs re-ranking | Needs training. Fast table-based scoring. |
| Binary quantization | 32x | Larger | One bit per dimension, Hamming distance. Works best on high-dimensional embeddings with re-ranking. |
Many vector databases expose these as index options. Some use PQ-like codes inside the index and keep original vectors for re-ranking.
Common errors
- Training on too little data. Codebooks from a few hundred vectors are poor. Use a representative sample of at least tens of thousands.
- A
dnot divisible bym. FAISS raises an error. Pickmas a divisor ofd, or pad the vectors. - Tuning only
nprobe. If recall plateaus asnproberises, the limit is quantization error, not cluster coverage. Raisem, add OPQ, or add re-ranking. - Judging by compression alone. Always measure recall@k against an exact baseline on your own data, as in the evaluation chapter.
- Ignoring metric choice. PQ approximates Euclidean distance directly. For cosine similarity, normalize vectors before training and encoding.
Exercise
You have 50 million 512-dimensional float32 vectors. You choose PQ with m = 64 and nbits = 8. How many bytes does each code take, what is the compression ratio, and roughly how much memory do the codes use? Also, what is the lookup table size per query?
Show answer
Each code takes 64 × 8 bits = 64 bytes. The raw vector takes 512 × 4 = 2048 bytes, so the ratio is 2048 / 64 = 32x. The codes use 50,000,000 × 64 bytes = 3.2 GB, versus about 102 GB raw. The per-query lookup table has m × 256 = 64 × 256 = 16,384 entries, which is 64 KB as float32. This excludes the codebooks and any IVF or re-ranking storage.
Exercise
After switching to IVF-PQ, recall@10 stays at 0.70 even when you raise nprobe from 16 to 128. What is the likely cause, and name two changes that could raise recall.
Show answer
The limit is quantization error, not coverage of clusters. Raising nprobe only scans more codes, and those codes' distances are still noisy. Two changes: add exact re-ranking of a larger candidate set (for example 4x k) using full-precision vectors, or increase m (or use OPQ) so each code preserves more information.