Lesson 22.3 · 3 of 8 · 5 min read · Reviewed 24 Nov 2026
IVF and product quantization
By the end, you can
- Explain IVF clustering and product quantization.
- Know when compression is worth it.
IVF: search only nearby clusters
build: cluster all vectors into, say, 4,096 groups (k-means)
each group has a centroid
query: find the nprobe nearest centroids (for example 16)
search only vectors in those clusters
Searching 16 of 4,096 clusters skips most of the data. Raising nprobe improves recall and costs speed.
Product quantization (PQ)
Split each vector into chunksChunking: Splitting documents into smaller passages before embedding and indexing them., and replace each chunk with the id of its nearest entry in a small codebook:
1,024-dim float vector (4 KB)
-> 64 sub-vectors of 16 dims
-> each replaced by a 1-byte code
-> 64 bytes per vector
That’s a large memory saving. Distances are estimated from the codes, so they’re approximate.
Combining them
| Index | Memory | Speed | Recall |
|---|---|---|---|
| Flat (exact) | Full | Slow at scale | Perfect |
| HNSW | Full plus graph | Fast | High |
| IVF | Full | Fast | Good, tunable |
| IVF-PQ | Small | Fast | Lower; rerank to recover |
A common pattern: retrieve 100 candidates with a compressed index, then rescore them with full vectors (or a rerankerReranking: Re-scoring an initial set of retrieved results with a more accurate model to put the best ones first.) and keep the top 10.
When to bother
Below a few million vectors, a plain HNSWHNSW: Hierarchical navigable small world: a graph-based index for fast approximate nearest neighbour search. index or even exact search is often simplest. Compression matters at hundreds of millions of vectors or tight memory budgets.
Key points
- IVF (inverted file) clusters vectors and searches only the clusters closest to the query.
- Product quantization compresses vectors into short codes, cutting memory many times over at some accuracy cost.
- IVF-PQ combines both for very large collections; rerank top candidates with full vectors to recover accuracy.
Compress vectors with product quantization
Encode vectors as short codebook ids, search with approximate distances, then rescore a shortlist with full vectors.
You will have: A tiny PQ encoder with a memory comparison and recall@5 before and after rescoring.
Steps
- Read the setup: 300 random 8-dimension vectors, split into 4 sub-vectors of 2 dimensions.
- Train a 16-entry codebook per sub-space with a few rounds of k-means (seeded).
- Encode each vector as 4 one-byte codes and compare memory with float32.
- Search with code distances, then rescore the top 20 with full vectors and compare recall@5.
Done when
- Memory per vector drops from 32 bytes to 4 bytes.
- Recall@5 after rescoring is higher than with codes alone.
Open in the Playground No API key needed.
Starter code (Python)
import random
rng = random.Random(7)
DIM, SUB, K = 8, 4, 16 # 4 sub-vectors of 2 dims, 16 centroids each
W = DIM // SUB
VECS = [[rng.gauss(0, 1) for _ in range(DIM)] for _ in range(300)]
QUERIES = [[rng.gauss(0, 1) for _ in range(DIM)] for _ in range(20)]
def sq(a, b):
return sum((x - y) ** 2 for x, y in zip(a, b))
def kmeans(points, k, rounds=6):
cents = [list(p) for p in rng.sample(points, k)]
# TODO: repeat: assign each point to its nearest centroid, move each centroid to its group mean
return cents
books = [kmeans([v[s * W:(s + 1) * W] for v in VECS], K) for s in range(SUB)]
# TODO: codes = for each vector, the index of the nearest centroid in each sub-space
codes = [[0] * SUB for _ in VECS]
print(f"bytes per vector: {DIM * 4} -> {SUB}")
# TODO: approximate distance = sum of sq(query part, centroid) over sub-spaces; compare recall@5
Show a solution
import random
rng = random.Random(7)
DIM, SUB, K = 8, 4, 16 # 4 sub-vectors of 2 dims, 16 centroids each
W = DIM // SUB
VECS = [[rng.gauss(0, 1) for _ in range(DIM)] for _ in range(300)]
QUERIES = [[rng.gauss(0, 1) for _ in range(DIM)] for _ in range(20)]
def sq(a, b):
return sum((x - y) ** 2 for x, y in zip(a, b))
def kmeans(points, k, rounds=6):
cents = [list(p) for p in rng.sample(points, k)]
for _ in range(rounds):
groups = [[] for _ in range(k)]
for p in points:
groups[min(range(k), key=lambda c: sq(p, cents[c]))].append(p)
for c, g in enumerate(groups):
if g:
cents[c] = [sum(col) / len(g) for col in zip(*g)]
return cents
books = [kmeans([v[s * W:(s + 1) * W] for v in VECS], K) for s in range(SUB)]
codes = [[min(range(K), key=lambda c: sq(v[s * W:(s + 1) * W], books[s][c])) for s in range(SUB)] for v in VECS]
print(f"bytes per vector: {DIM * 4} -> {SUB} ({DIM * 4 // SUB}x smaller)")
def approx(q, code):
return sum(sq(q[s * W:(s + 1) * W], books[s][code[s]]) for s in range(SUB))
codes_only = rescored = 0
for q in QUERIES:
truth = set(sorted(range(len(VECS)), key=lambda i: sq(q, VECS[i]))[:5])
by_code = sorted(range(len(VECS)), key=lambda i: approx(q, codes[i]))
codes_only += len(truth & set(by_code[:5]))
short = sorted(by_code[:20], key=lambda i: sq(q, VECS[i]))[:5]
rescored += len(truth & set(short))
n = 5 * len(QUERIES)
print(f"recall@5 with codes only: {codes_only / n:.2f}")
print(f"recall@5 after rescoring top 20: {rescored / n:.2f}")
print("rescoring helps:", rescored > codes_only)