Sub topic 7
IVF: partitioning the space into clusters
This chapter assumes you have read the previous chapters on approximate search and recall. It also assumes you can read Python and SQL, and that you know k-means clustering at a basic level. By the end you should be able to explain how an inverted file (IVF) index works, set its two main parameters, and predict where it fails.
The core idea
Exact search compares the query with every vector. IVF avoids most of those comparisons by dividing the data into groups first, then searching only the groups most likely to hold the answer.
The name comes from search engines. A classic inverted index maps a word to the list of documents containing it. An IVF index maps a cluster to the list of vectors assigned to it.
Building the index has three steps:
- Run k-means on a sample of the vectors to produce
nlistcentroids. A centroid is the mean position of one cluster. - Assign every vector to its nearest centroid.
- Store each vector in the inverted list of its centroid.
A query then runs in two stages:
- Compare the query with all
nlistcentroids. This is the coarse search. - Pick the
nprobenearest centroids and scan only their lists. This is the fine search.
The coarse search is cheap because nlist is far smaller than the dataset. The fine search touches roughly nprobe / nlist of the data. With nlist = 1024 and nprobe = 8, you scan about 0.8% of the vectors, plus 1024 centroid comparisons.
Why recall drops
IVF is approximate because the true nearest neighbor can sit in a cluster you did not probe. This happens near cluster borders. Picture a query that falls just inside cluster A, close to the boundary with cluster B. Its true nearest neighbor may be a point just across the line in B. With nprobe = 1 you never look there.
Raising nprobe fixes this by scanning more neighboring clusters. At nprobe = nlist you scan everything, and the result equals exact search, only slower because of the extra centroid step.
So nprobe is the main knob you can change at query time. It trades latency for recall without rebuilding anything.
Parameters
| Parameter | Set when | Effect of increasing it |
|---|---|---|
| `nlist` | Build time | Smaller lists, so a faster fine search. The coarse search costs more, and the index needs more training data. Clusters get finer, so more queries sit near a border. |
| `nprobe` | Query time | Higher recall and higher latency. |
Common starting points for nlist are a multiple of the square root of the row count. FAISS guidance suggests values between about 4√N and 16√N for large collections. pgvector suggests rows / 1000 up to one million rows and sqrt(rows) above that. Treat these as starting values and measure on your own data.
The square root appears because the total work is roughly nlist centroid comparisons plus nprobe × N / nlist vector comparisons. For a fixed nprobe, that sum is smallest when nlist is on the order of √N.
Building an IVF index in FAISS
The code below builds an IndexIVFFlat. "Flat" means the vectors inside each list are stored uncompressed, so distances in the fine search are exact. The only approximation is which lists you visit. It then measures recall against an exact baseline for several nprobe values.
import time
import numpy as np
import faiss
d = 64
n = 50000
rng = np.random.default_rng(0)
xb = rng.normal(size=(n, d)).astype("float32")
xq = (xb[:200] + 0.1 * rng.normal(size=(200, d))).astype("float32")
k = 10
flat = faiss.IndexFlatL2(d)
flat.add(xb)
_, true_ids = flat.search(xq, k)
nlist = 256
quantizer = faiss.IndexFlatL2(d)
ivf = faiss.IndexIVFFlat(quantizer, d, nlist, faiss.METRIC_L2)
ivf.train(xb) # runs k-means to learn the centroids
ivf.add(xb) # assigns each vector to a list
for nprobe in [1, 4, 16, 64, 256]:
ivf.nprobe = nprobe
t0 = time.perf_counter()
_, ids = ivf.search(xq, k)
ms = (time.perf_counter() - t0) * 1000
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} {ms:.1f} ms for 200 queries")Points to notice:
- The
quantizeris a separate index that holds the centroids and answers the coarse search. Here it is an exact flat index. You can replace it with an HNSW index whennlistis very large. trainmust run beforeadd. Callingaddon an untrained IVF index raises an error.- FAISS defaults to
nprobe = 1. If you forget to set it, recall will look poor and you may wrongly blame the index type. - At
nprobe = 256the recall should reach 1.0, which confirms the scan covers all lists.
IVF in a relational database
pgvector offers IVF under the name ivfflat. The settings map directly to the FAISS ones: lists is nlist and probes is nprobe.
CREATE EXTENSION IF NOT EXISTS vector;
-- Build the index after the table already holds representative data.
CREATE INDEX ON items USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 100);
-- Query-time setting, per session or per transaction.
SET ivfflat.probes = 10;
SELECT id
FROM items
ORDER BY embedding <=> '[1, 0, 0]'
LIMIT 5;The ordering matters. pgvector computes the centroids when you run CREATE INDEX, using whatever rows exist at that moment. If you create the index on an empty table, the centroids are meaningless and recall is poor. Insert a representative batch first, then build the index.
Gotchas and failure modes
Untrained or stale centroids. The centroids are fixed after training. New vectors are assigned to the nearest existing centroid, so inserts work without a rebuild. But if the data distribution drifts, for example after you switch embedding models or add a new topic, many vectors pile into a few lists. Those lists get slow, and the clusters no longer represent the data. The fix is to retrain and rebuild, usually on a schedule or when you monitor list sizes and see skew.
Unbalanced lists. K-means does not guarantee equal cluster sizes. Query time depends on the sizes of the probed lists, so a query that lands in a dense cluster is slower than one in a sparse cluster. Check the distribution of list lengths. In FAISS you can read them with faiss.extract_index_ivf(ivf).get_list_size(i), or ivf.invlists.list_size(i) for the index above.
Too little training data. FAISS warns when you train with fewer than a few dozen points per centroid, and recommends about 39 or more per centroid. You can train on a random sample rather than the full set. A sample of a few hundred thousand vectors is often enough for large collections.
Metric mismatch. K-means in FAISS uses L2 distance. If your embeddings are meant for cosine similarity, normalize them first and use the inner product metric. On unit vectors, L2 and cosine give the same ranking. Mixing a cosine query with an L2-trained index on unnormalized vectors gives inconsistent results.
Filters. A metadata filter applied after the probe step can leave you with fewer than k results, because the probed lists may hold few matching items. Raising nprobe helps, as does a database that filters while it scans. The next chapters cover this in detail.
Memory. IVF-Flat stores the full vectors, so memory is about N × d × 4 bytes for float32, plus a small overhead for centroids and ids. IVF does not reduce memory by itself. Compression comes from combining it with product quantization, covered in the next chapter.
IVF compared with HNSW
| Aspect | IVF | HNSW |
|---|---|---|
| Build cost | Low (k-means plus assignment) | Higher (graph construction) |
| Training step | Required | None |
| Memory overhead | Small beyond the vectors | Graph links add a noticeable amount |
| Recall at low latency | Good, needs tuning of `nprobe` | Often better |
| Handling heavy inserts | Drift degrades quality over time | Handles inserts well |
| Combines with compression | Yes, very commonly | Possible but less common |
IVF is a good choice when build time or memory is tight, or when you want to compress vectors. HNSW is usually the better default when memory is plentiful and you need high recall at low latency.
Exercise
A collection has 4,000,000 vectors. You build an IVF-Flat index with nlist = 4000 and query with nprobe = 20. Roughly what fraction of the stored vectors does each query scan in the fine search, assuming equal list sizes? Recall is lower than you want. Name one change that needs no rebuild and one that does.
Show answer
Each list holds about 4,000,000 / 4000 = 1,000 vectors. Probing 20 lists scans about 20,000 vectors, which is 0.5% of the data, plus 4,000 centroid comparisons in the coarse step. Without a rebuild, raise nprobe, which trades latency for recall. With a rebuild, you can change nlist, or retrain the centroids on more representative data. Retraining helps most if the data has drifted or the lists are badly unbalanced.