Sub topic 9
Scaling up: approximate nearest-neighbor search (IVF, HNSW)
This chapter assumes you can run the exact top-k search from the previous chapters and that you have NumPy and faiss-cpu installed. You should also be comfortable with unit-length vectors and cosine similarity.
Why exact search stops working
Exact search compares the query with every stored vector. For N vectors of dimension d, each query costs about N × d multiplications. With 10,000 vectors, that is instant. With 50 million vectors of 384 dimensions, each query reads about 77 GB of float32 data. That is too slow for interactive use.
Approximate nearest-neighbor (ANN) indexes trade a small loss in accuracy for a large gain in speed. They sometimes miss a true top-k neighbor, but they examine only a small part of the collection.
IVF: search only nearby clusters
An inverted file index (IVF) groups vectors into clusters.
- Train: k-means finds
nlistcluster centers (centroids). - Add: each vector goes into the list of its nearest centroid.
- Query: the query is compared with the centroids, and only the
nprobeclosest lists are scanned.
Raising nprobe improves recall and slows queries. With nlist=100 and nprobe=10, you scan roughly 10% of the data.
A failure mode specific to IVF: if the true neighbor sits in a cluster that is not among the nprobe closest, it is never seen.
HNSW: walk a graph
Hierarchical Navigable Small World (HNSW) builds a layered graph. Each vector links to nearby vectors. Upper layers are sparse and allow long jumps. Lower layers are dense and allow fine steps. A query starts at the top, moves greedily toward the query, and descends layer by layer.
Three parameters matter:
M: links per node. Higher values improve recall and use more memory.efConstruction: search width while building. Higher values give a better graph and slower builds.efSearch: search width at query time. Higher values improve recall and slow queries.
Comparing both against exact search
The code below measures recall against the exact index. Recall here means the share of the true top-10 that the approximate index returns.
import numpy as np
import faiss
d, k = 384, 10
rng = np.random.default_rng(0)
vectors = rng.standard_normal((10000, d)).astype("float32")
queries = rng.standard_normal((100, d)).astype("float32")
faiss.normalize_L2(vectors)
faiss.normalize_L2(queries)
flat = faiss.IndexFlatIP(d)
flat.add(vectors)
_, truth = flat.search(queries, k)
hnsw = faiss.IndexHNSWFlat(d, 32, faiss.METRIC_INNER_PRODUCT)
hnsw.hnsw.efConstruction = 200
hnsw.add(vectors)
hnsw.hnsw.efSearch = 64
quantizer = faiss.IndexFlatIP(d)
ivf = faiss.IndexIVFFlat(quantizer, d, 100, faiss.METRIC_INNER_PRODUCT)
ivf.train(vectors) # IVF must be trained before adding
ivf.add(vectors)
ivf.nprobe = 10
def recall(found, truth):
return float(np.mean([len(set(f) & set(t)) / len(t)
for f, t in zip(found, truth)]))
_, h_ids = hnsw.search(queries, k)
_, i_ids = ivf.search(queries, k)
print("HNSW recall:", recall(h_ids, truth))
print("IVF recall: ", recall(i_ids, truth))Random vectors have no cluster structure, so recall here is lower than on real text embeddings. Try raising efSearch and nprobe and watch recall climb.
Choosing an index
| Collection size | Typical choice | Reason |
|---|---|---|
| Under about 100,000 vectors | Flat (exact) | Fast enough, and results are exact |
| Hundreds of thousands to millions | HNSW | High recall and low latency, at the cost of memory |
| Tens of millions or more | IVF, often with compression | Smaller memory footprint, and training scales |
Common errors
- Forgetting to call
trainon an IVF index. Adding vectors then raises an error. - Mixing metrics. Use inner product on normalized vectors for cosine ranking.
- Tuning without ground truth. Always measure recall against a flat index on a sample.
- Expecting HNSW to support cheap deletes. Most implementations handle deletions poorly, so plan periodic rebuilds.
Exercise
An IVF index with nlist=1000 has nprobe=1. Queries are fast but recall is low. What are two ways to improve recall, and what does each cost?
Show answer
Raise nprobe, which scans more clusters and makes each query slower. Or use fewer, larger clusters (a smaller nlist), which also means each probe scans more vectors. Raising nprobe is usually the first choice because it needs no rebuild.