Sub topic 7
IVF: partitioning the space into clusters
This chapter assumes you know what approximate nearest neighbor (ANN) search and recall are, and that you can read short Python with NumPy. FAISS is a vector search library. You will use it here.
The idea
An inverted file (IVF) index splits the vectors into groups, then searches only the groups most likely to hold the answer. Exact search compares the query with every vector. IVF compares it with a small fraction.
The name comes from search engines. A text inverted index maps each word to the documents containing it. An IVF index maps each cluster to the vectors assigned to it.
How it works
Building the index has two steps:
- Train. Run k-means clustering on a sample of vectors. This produces
nlistcentroids, which are the cluster centers. - Add. Assign each vector to its nearest centroid and store it in that centroid's list.
Searching has three steps:
- Compare the query with all
nlistcentroids. - Pick the
nprobeclosest centroids. - Scan only the vectors in those lists and return the best
k.
If clusters are balanced, one search scans about nprobe / nlist of the data. With nlist = 1000 and nprobe = 10, that is about 1%.
Running it
This script compares IVF with an exact flat index at several nprobe values.
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
flat = faiss.IndexFlatL2(d)
flat.add(xb)
_, true_ids = flat.search(xq, k)
nlist = 128
quantizer = faiss.IndexFlatL2(d)
ivf = faiss.IndexIVFFlat(quantizer, d, nlist)
ivf.train(xb)
ivf.add(xb)
for nprobe in (1, 8, 32, 128):
ivf.nprobe = nprobe
_, ids = ivf.search(xq, k)
recall = np.mean([len(set(a) & set(t)) / k for a, t in zip(ids, true_ids)])
print(f"nprobe={nprobe:3d} recall@{k}: {recall:.3f}")Recall rises with nprobe. At nprobe = nlist every list is scanned, so recall reaches 1.0 and the search is exact again. Random Gaussian data has no real cluster structure, so recall here is lower than on real embeddings. Treat the numbers as a demonstration of the trend, not a benchmark.
Parameters
| Parameter | Set when | Effect of increasing it |
|---|---|---|
| `nlist` | Build time | Smaller lists, faster scans, but more centroid comparisons and a higher risk of missing neighbors that sit near a boundary |
| `nprobe` | Query time | Higher recall, higher latency |
A common starting point is nlist near the square root of the dataset size, then tune nprobe against a recall target. Because nprobe is a query-time setting, you can change it without rebuilding.
Common errors
- Searching before training. An IVF index needs
trainbeforeadd. FAISS raises an error otherwise. - Training on unrepresentative data. Centroids learned from a sample that differs from your real data give unbalanced lists. Some lists become huge and slow, and others are nearly empty.
- Boundary misses. A true neighbor can sit in a different cluster than the query, just across a cluster boundary. Raising
nprobeis the fix. - Data drift. Centroids are fixed after training. If new vectors come from a different distribution, lists become skewed and you should retrain.
IVF compared with HNSW
IVF builds faster and uses less memory than HNSW. It also gives you one clear speed and recall control, nprobe. HNSW usually reaches higher recall at the same latency, but it costs more memory and build time.
Exercise
An IVF index has nlist = 1000 and balanced lists over 1,000,000 vectors. You search with nprobe = 20. Roughly how many vectors are scanned, and how many centroid comparisons are made? What do you change if recall is too low?
Show answer
About 20,000 vectors are scanned (20/1000 of the data), plus 1,000 centroid comparisons. To raise recall, increase nprobe at query time. This costs more latency, and no rebuild is needed.