06.4 Vector Indexes: HNSW, IVF, Quantization and Trade-offs
06.3 ended with a promise and a problem: brute-force search over every stored vector gives perfect answers but costs one distance computation per vector per query, which stops being acceptable somewhere in the hundreds of thousands of vectors. Approximate nearest-neighbour (ANN) indexes are how every real vector system answers queries at millions or billions of vectors: they trade a little accuracy (measured as recall) for orders of magnitude less work. This lesson is the complete engineering guide to those indexes. You will learn how the two great families — inverted-file (IVF) indexes that partition the space, and graph indexes such as HNSW that connect nearby points — actually work, every knob that tunes them, how quantization compresses vectors to fit more of them in memory, how to measure and tune recall on your own data, and what updates, deletes and scale do to all of it.
What you'll learn
- Why indexes exist, the brute-force baseline, and the recall–latency–memory triangle every ANN index lives inside
- IVF from first principles: k-means cells,
nlist,nprobe, training, and a working IVF index you build in NumPy - HNSW from first principles: navigable small worlds, layers,
M,efConstruction,efSearch, plus a working graph search in pure Python - Every major index family — flat, IVF, HNSW, PQ, scalar and binary quantization, IVF-PQ, LSH, Annoy trees, DiskANN/Vamana, ScaNN-style quantization, RaBitQ and the pgvectorscale add-on — and which real systems implement which
- The full quantization ladder (float32 → float16 → int8 → binary → product quantization), with working code and measured recall on synthetic data
- Oversampling and rescoring: how compressed indexes recover accuracy cheaply
- A repeatable tuning procedure: build ground truth, sweep the main knob, pick an operating point from your SLA
- Index memory formulas, build-time vs query-time costs, and what "reindex" means operationally
- Updates, deletes, tombstones, segments and read-after-write behaviour
- How to read (and not be fooled by) benchmarks: ann-benchmarks, VIBE, vendor numbers
- Scale regimes, hardware notes (CPU SIMD, GPU, RAM vs NVMe), and cost per million vectors
- A short practical guide to choosing index settings: the few knobs that matter, what pgvector, Qdrant, Chroma, Elasticsearch, OpenSearch and hnswlib default to (as of 2 December 2026), and a measure-first checklist (Part 10)
What you don't need
- A vector database or API keys. Every algorithm is demonstrated on synthetic vectors you generate yourself; the pgvector, Qdrant, FAISS, hnswlib and Elasticsearch samples are written carefully against official docs but their outputs are labelled illustrative — you can run the pure-Python and NumPy parts today with no services at all.
- Deep linear algebra. Cosine similarity, dot products and "nearest" are all you need; 02.3 covered them.
- How to choose a vector database product — that's 06.5. This lesson is about the index algorithms inside them.
Setup
The runnable parts need Python 3.11+ and NumPy only. First time? Create a project, then add NumPy:
uv init vector-indexes --bare --python 3.13
cd vector-indexes
uv add numpy # or: pip install numpyRun scripts with uv run python file.py.
One structural note before the code: the runnable NumPy snippets in this lesson — the IVF demo in 2.4, the toy graph in 3.4, all of Part 4, and the tuning harness in 5.2–5.3 — are one cumulative script, vector_indexes_numpy.py. Copy each python block in lesson order into a single file (the toy-graph block deliberately uses different variable names so it can't clobber the shared data). The complete assembled file is in the appendix at the end of the lesson, so you can also just copy that once. The FAISS, hnswlib, pgvector, Qdrant, Annoy and Elasticsearch samples are independent and their outputs are labelled illustrative — you may install the libraries to experiment but no output here depends on them:
uv add faiss-cpu hnswlibThese install the newest release of each package. The comparisons in this lesson were checked against faiss-cpu 1.15.1 and hnswlib 0.8.0 as of November 2026; a newer major version may change names or defaults, so check the library's changelog if a call does not match.
The samples assume the vectors are already L2-normalised (unit length), which is what OpenAI and Voyage embeddings return and what 02.3, 4.4 explains. Where a model doesn't normalise, normalise once at write time — the indexes in this lesson assume it.
What you must be able to do after this lesson#
- Explain what a vector index does and why it is approximate
- Tune IVF and HNSW parameters against ground truth
- Explain how quantization saves memory and what it costs
- Measure recall against latency with a parameter sweep
- Describe what happens to an index on updates and deletes
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Just use HNSW, it's the default everywhere." | Part 3 |
"Our recall is bad — did you tune ef_search?" |
5.3 The sweep procedure |
| "IVF needs training — what happens when data drifts?" | 2.6 IVF's dirty secret: training and drift |
| "Why is the index bigger than the vectors?" | 4.7 Compression ratios and index memory |
| "Enable product quantization to fit it all in RAM." | Part 4 |
| "Rescore the top candidates with full vectors." | 4.5 Oversampling and rescoring |
| "Deleted vectors still show up in results." | 6.2 Deletes: tombstones and compaction |
| "When do we outgrow pgvector?" | Part 8: Scale regimes |
| "The vendor benchmark says 99% recall at 2 ms." | Part 9: Benchmarks |
Part 1: What an index actually does#
1.1 Recap: exact search and the recall it guarantees#
06.3 defined the operation precisely: for a query vector q, exact k-NN scores q against every stored vector and returns the k best. Its only cost is N distance computations per query — N × d multiply-adds. It returns perfect recall@k: all k true nearest neighbours, every time. 02.3, Part 4 covered the metrics; recall@k — the fraction of the true top-k an approximate search returns — is defined in 06.3.
Everything in this lesson is about answering the same query while touching fewer than all N vectors, and being honest about what you lose.
1.2 When brute force is the right answer#
Before reaching for an index, know when you shouldn't:
- Small corpora. Under roughly 10⁴–10⁵ vectors (depending on dimension and hardware — 06.3 works through the arithmetic), exact search in NumPy or a flat index is faster and perfect. An IVF or HNSW index on 5,000 chunks adds build time, memory overhead and a recall knob for no benefit.
- Very selective filters. If a metadata filter leaves only a few hundred candidates, scoring all of them exactly beats any ANN index (06.6 covers filtering in depth).
- You need determinism. ANN indexes can return different results across runs and versions; tests and audits sometimes need the exact answer.
A flat index (FAISS IndexFlatL2, a NumPy matrix, pgvector with no index) is the baseline every ANN number is measured against. Keep it in your back pocket: it's also the escape hatch when an approximate index misbehaves.
1.3 Two strategies for avoiding the full scan#
Every ANN family answers "which vectors could possibly be nearest?" differently:
flowchart TB
Q["query vector"] --> S{"search strategy"}
S -->|"partition the space"| IVF["IVF / cell-probe<br/>k-means cells, probe nprobe lists"]
S -->|"connect the points"| G["graph indexes<br/>HNSW, NSW, DiskANN, Annoy trees"]
S -->|"compress then scan"| QTZ["quantized flat / IVF-PQ<br/>score codes, rescore survivors"]
IVF --> R["top-k candidates"]
G --> R
QTZ --> R
R --> RS["optional: rescore with full vectors"]- Partition methods (IVF, LSH, Annoy's trees) divide the vector space into regions and search only the regions near the query. The risk: the true nearest neighbour lives in a region you didn't probe — a miss, not a slower answer.
- Graph methods (HNSW, NSW, DiskANN) build a navigable graph where each vector links to its approximate nearest neighbours, then walk it greedily. The risk: the walk gets stuck in a local optimum — a dense cluster that isn't where the query belongs.
- Quantization is orthogonal: it doesn't choose which vectors to compare, it makes each comparison cheaper and the storage smaller, usually followed by rescoring the survivors with full-precision vectors.
Most production systems combine them: IVF-PQ (partition + compress), HNSW over quantized vectors, or a graph index plus a quantized rerank stage.
1.4 The tuning triangle#
Every index exposes the same three-way trade-off, and every parameter you'll meet is a dial on it:
flowchart LR
subgraph tri ["The ANN trade-off triangle"]
REC["recall@k<br/>(quality)"]
LAT["query latency / QPS<br/>(speed)"]
MEM["index memory<br/>(cost)"]
end
REC <-->|"trade"| LAT
LAT <-->|"trade"| MEM
MEM <-->|"trade"| REC- Recall — fraction of the true top-
kreturned. The only quality metric that matters for a retriever's first stage; downstream rerankers (06.9) can only reorder what you retrieved, so recall is the ceiling on everything after it. - Latency / throughput — how fast a query is. p50 matters for UX; p99 matters for capacity planning because ANN latency has a long tail (graph walks that wander, disk reads on cold pages).
- Memory — index bytes on RAM, disk or both. This is usually the binding constraint at scale: an index that doesn't fit in RAM spills to disk and latency jumps by orders of magnitude.
Every parameter table in this lesson says which corner of the triangle it pushes. The rest of the lesson takes each family in turn, then Part 5 gives you the procedure for finding your operating point on your own data.
Part 2: Inverted-file indexes (IVF)#
Reference
2.1 The idea: partition the space into cells#
An inverted-file index is the vector analogue of a database index on a column: instead of one sorted structure, you cluster the vectors into nlist cells with k-means, store each vector in the list of its nearest centroid, and at query time compare the query only against the vectors in the nprobe cells whose centroids are closest to it.
The name comes from the structure: for each cell you keep an inverted list — the IDs of every vector assigned to it. At query time:
- Compute the query's distance to all
nlistcentroids (nlist × dwork — cheap ifnlistis a few hundred to a few thousand). - Pick the
nprobenearest centroids. - Score every vector in those lists exactly, return top-
k.
Work per query ≈ nlist × d (centroid scan) + nprobe/nlist × N × d (list scan), versus N × d for brute force. The speedup is roughly nlist/nprobe, degraded by uneven list sizes — lists aren't equal because k-means cells have different populations.
2.2 The knobs: nlist, nprobe, and training#
| Knob | When set | Effect |
|---|---|---|
nlist |
Build time | Number of k-means cells. More cells → smaller lists → faster queries, but the query must scan more centroids and the chance the true neighbour sits in an unprobed cell rises. Also raises build time and memory slightly (centroids are nlist × d). |
nprobe |
Query time | How many cells to scan. Higher → better recall, slower. nprobe = nlist degenerates to exact search. |
Two properties matter operationally:
- IVF requires training. The k-means centroids are computed once over (a sample of) the data. You cannot
addvectors beforetrainin FAISS; in pgvector theCREATE INDEXitself runs k-means. Train on data that represents what you'll search — a small or biased sample produces bad centroids. - The lists go stale as data grows. Vectors added after training are still assigned to the nearest centroid (the assignment function exists), but if the data distribution shifts — new product categories, a new language, a model change — the cells no longer match the data and recall decays silently. This is IVF's dirty secret; 2.6 covers it.
A useful rule of thumb for nlist, from the FAISS documentation: aim for nlist ≈ C × √n where n is the number of vectors and C is a small constant (the FAISS wiki's "Guidelines to choose an index" give 4 × √n to 16 × √n clusters, and say to train on between 30 × nlist and 256 × nlist vectors); pgvector's docs suggest rows / 1000 up to ~1M rows and √rows beyond. Both are starting points — your sweep in Part 5 decides. The matching query-time rule of thumb is nprobe ≈ √nlist — probe roughly the square root of the cell count (pgvector's docs give √lists as the suggested starting point for ivfflat.probes).
2.3 IVF variants: what's stored in the lists#
The "IVF" part only chooses which vectors to compare; a second choice — how each vector is stored — gives the family its variants:
| Variant | What's in each list | Bytes/vector (approx.) | Recall vs speed |
|---|---|---|---|
IVF-Flat (IndexIVFFlat, pgvector ivfflat) |
Full-precision vectors + IDs | 4d + 8 |
Best recall for a given nprobe; biggest memory |
IVF-SQ (IndexIVFScalarQuantizer) |
int8/uint8 quantized vectors | d + 8 |
~4× smaller; small recall loss, fixable by rescoring |
IVF-PQ (IndexIVFPQ) |
Product-quantized codes | M × nbits/8 + 8 |
Largest compression (16–64×); needs rescoring for top quality |
| IVF-ADC / IVFADC+R | PQ codes on residuals (vector minus centroid) | similar to IVF-PQ | The FAISS default recipe for very large data |
The pattern to remember: IVF picks the candidates, the inner encoding decides how cheaply you score them, and rescoring restores what the encoding lost. Part 4 takes the encodings apart.
2.4 Build an IVF index in NumPy — and measure recall#
Here is a complete, runnable IVF index: k-means for the cells, inverted lists for storage, and nprobe-bounded queries. All vectors are unit-length, so cosine similarity is just the dot product and "nearest centroid" is argmax of X @ C.T.
# vector_indexes_numpy.py — PART 1 (this section): shared data + helpers + IVF demo
# Everything below is one cumulative file; later sections append to it.
import numpy as np
rng = np.random.default_rng(42)
N, D, K_TRUE = 4000, 64, 8
centers = rng.normal(size=(K_TRUE, D))
centers /= np.linalg.norm(centers, axis=1, keepdims=True)
X = centers[rng.integers(0, K_TRUE, N)] + 0.15 * rng.normal(size=(N, D))
X /= np.linalg.norm(X, axis=1, keepdims=True)
Qc = np.repeat(centers, 3, axis=0)
Q = Qc + 0.10 * rng.normal(size=(K_TRUE * 3, D))
Q /= np.linalg.norm(Q, axis=1, keepdims=True)
K = 10
def exact_topk(X, Q, k):
return np.argsort(-(Q @ X.T), axis=1)[:, :k]
def recall_at_k(approx, exact, k):
return np.mean([len(set(a) & set(e)) / k for a, e in zip(approx, exact)])
def kmeans(X, k, iters=25, seed=0):
"""Lloyd's algorithm on unit vectors: assign by argmax dot product."""
r = np.random.default_rng(seed)
C = X[r.choice(len(X), k, replace=False)].copy()
for _ in range(iters):
assign = np.argmax(X @ C.T, axis=1)
for j in range(k):
members = X[assign == j]
if len(members):
c = members.mean(axis=0)
C[j] = c / (np.linalg.norm(c) + 1e-12)
return C
def build_ivf(X, nlist, seed=0):
C = kmeans(X, nlist, seed=seed)
assign = np.argmax(X @ C.T, axis=1)
lists = [np.where(assign == j)[0] for j in range(nlist)]
return C, lists
def ivf_query(q, X, C, lists, nprobe, k):
order = np.argsort(-(q @ C.T))[:nprobe]
cand = np.concatenate([lists[j] for j in order])
# may return fewer than k ids if the probed lists are small — recall just scores lower
return cand[np.argsort(-(X[cand] @ q))[:k]]
exact = exact_topk(X, Q, K)
C, lists = build_ivf(X, nlist=64)
print("nlist=64, sweep nprobe:")
for nprobe in [1, 2, 4, 8, 16, 32, 64]:
approx = [ivf_query(q, X, C, lists, nprobe, K) for q in Q] # a list, not np.array: rows can differ in length
print(f" nprobe={nprobe:3d} recall@{K}={recall_at_k(approx, exact, K):.3f}")nlist=64, sweep nprobe:
nprobe= 1 recall@10=0.250
nprobe= 2 recall@10=0.463
nprobe= 4 recall@10=0.771
nprobe= 8 recall@10=0.979
nprobe= 16 recall@10=1.000
nprobe= 32 recall@10=1.000
nprobe= 64 recall@10=1.000Read it like an engineer:
nprobe=1— the default in several systems — finds only a quarter of the true top-10. If your retrieval "works" atnprobe=1on easy queries it will fail on hard ones.- Recall saturates at
nprobe=16here (25% of the cells), but the cost keeps rising linearly withnprobe. The operating point is the smallestnprobemeeting your recall target — Part 5 formalises this. nprobe=nlist=64is exact search: recall 1.000 by definition. Notice IVF's failure mode is silent — no error, just missing neighbours.
The same data with different nlist shows why nlist is a build-time decision — rebuild the index, then probe a few cell counts at each size:
# same data; vary nlist at build time (continues the same file)
for nlist, probes in [(16, [1, 4]), (64, [1, 16]), (256, [13, 26])]:
Cn, ln = build_ivf(X, nlist=nlist, seed=0)
cells = ", ".join(
f"nprobe={p} → recall {recall_at_k([ivf_query(q, X, Cn, ln, p, K) for q in Q], exact, K):.3f}"
for p in probes)
print(f" nlist={nlist:3d}: {cells}") nlist= 16: nprobe=1 → recall 0.763, nprobe=4 → recall 1.000
nlist= 64: nprobe=1 → recall 0.250, nprobe=16 → recall 1.000
nlist=256: nprobe=13 → recall 0.908, nprobe=26 → recall 0.992More cells means each query needs more probes in absolute terms for the same recall: nlist=16 reaches 1.000 with 4 probes, nlist=64 with 16, and nlist=256 is still at 0.908 with 13 and reaches 0.992 with 26. The fractions of cells probed tell a different story: about 6% of the cells (nlist=16, nprobe=1 or nlist=64, nprobe=4 from the sweep above) gives recall 0.76–0.77, and about 5% of 256 cells gives 0.908, so on this data the fraction needed does not grow with nlist. Finer partitions make each list smaller (less to scan per probe), but they also cost a bigger centroid scan (nlist × d per query) and more probes to cover the same neighbourhood. That's the nlist trade-off in one table.
2.5 IVF in production: FAISS and pgvector#
The same algorithm appears under different names and parameters. FAISS first (illustrative — outputs depend on your build):
# s2_5_faiss_ivf.py — FAISS 1.15.x API (independent illustrative snippet)
import faiss
import numpy as np
d = 1536 # e.g. a text-embedding-3-large vector, truncated
xb = np.random.randn(1_000_000, d).astype(np.float32)
faiss.normalize_L2(xb) # unit vectors -> inner product == cosine
quantizer = faiss.IndexFlatIP(d) # coarse quantizer: assigns vectors to cells
index = faiss.IndexIVFFlat(quantizer, d, nlist=4096, metric=faiss.METRIC_INNER_PRODUCT)
index.train(xb) # k-means over the data — required before add()
index.add(xb)
index.nprobe = 32 # query-time dial
D, I = index.search(xb[:5], 10) # (distances, ids); inner product, higher = closerD shape (5, 10), values in [-1, 1]; I shape (5, 10) of int64 row idsKey FAISS facts (from the official wiki, verified November 2026): IndexIVFFlat stores 4d + 8 bytes per vector, requires train() before add(), takes nprobe at query time, and supports remove_ids. Its factory string is "IVF4096,Flat" — or build it via faiss.index_factory(d, "IVF4096,PQ16") for the compressed variant. When nprobe reaches nlist the search is exhaustive and a flat index is faster — the wiki's FAQ says exactly that.
In Postgres + pgvector (0.8.7, illustrative SQL — 06.5 covers pgvector operations in depth):
-- Build AFTER loading data; lists ≈ rows/1000 up to ~1M rows, sqrt(rows) beyond
CREATE INDEX ON chunks USING ivfflat (embedding vector_cosine_ops) WITH (lists = 1000);
-- Query-time dial (default 1 — almost certainly too low)
SET ivfflat.probes = 10;
SELECT id, content, embedding <=> $1 AS distance
FROM chunks
ORDER BY distance
LIMIT 10;Setting probes = lists scans every list, which is exact search done the slow way — the planner may then prefer a sequential scan, so it is self-defeating. For probes, the README's suggested starting point is √lists (so lists = 1000 → probes ≈ 32), then measure recall on your own queries. For filtered queries, SET ivfflat.iterative_scan = relaxed_order (since 0.8.0) auto-expands the probe count when a WHERE clause leaves too few rows; that's a preview of 06.6.
2.6 IVF's dirty secret: training and drift#
Because the partition is learned, IVF has a lifecycle IVF-flat users feel and HNSW users mostly don't:
- Train once, serve until it hurts. New vectors are assigned to the nearest existing centroid — they don't move the centroids. As the corpus grows or its distribution shifts (a new document type, a new tenant, an embedding-model upgrade — 06.1 covers re-embedding), cells become unbalanced and recall degrades without any error.
- Retraining means rebuilding. There is no cheap "re-cluster": you rebuild the index (FAISS
index.train+addagain; pgvectorREINDEXorCREATE INDEXanew). Plan it like a migration, not a tweak — see 6.4. - IVF is weaker on skewed data. k-means assumes roughly spherical, balanced clusters. Embedding spaces are notoriously anisotropic (02.3, 4.6); on heavily skewed corpora IVF needs more probes than the rules of thumb suggest. Measure, don't assume.
Part 3: Graph indexes and HNSW#
Reference
3.1 The idea: connect neighbours, then walk#
Graph indexes flip IVF's approach. Instead of partitioning space, they build a graph: every vector is a node, and each node holds links to a small set of other nodes that are (approximately) its nearest neighbours. At query time you greedily walk the graph from an entry point: at each node, look at its linked neighbours, move to the one closest to the query, repeat until no neighbour improves — then return the best nodes you visited.
The ancestor is the navigable small world (NSW) graph: in social networks, anyone can reach anyone in ~6 hops because hubs connect distant clusters. The same property makes a nearest-neighbour graph searchable — greedy walks converge quickly if the graph is well connected. Pure NSW has one flaw: from a random entry point, the walk can get stuck in a local cluster far from the query's true neighbourhood. HNSW (Hierarchical NSW, Malkov & Yashunin, 2016/2020) fixes this by stacking the graph into layers: a sparse top layer of long-range "highway" links, denser layers below, and a full layer at the bottom holding every vector.
flowchart TB
subgraph L2 ["Layer 2 (sparse): a few hub nodes, long-range links"]
A((•)) --- B((•))
end
subgraph L1 ["Layer 1 (medium)"]
C((•)) --- D((•)) --- E((•))
end
subgraph L0 ["Layer 0 (every vector)"]
F((•)) --- G((•)) --- H((•)) --- I((•))
end
A -.-> C
B -.-> D
C -.-> F
D -.-> G
E -.-> H
Q(["query"]) ==> AA query enters at the top layer, greedily descends to a local optimum on that layer, drops to the layer below at that point, and repeats — ending with a careful search on the bottom layer. The upper layers cost almost nothing (few nodes) and prevent the local-optimum trap; the bottom layer does the fine work.
3.2 Why HNSW became the default#
HNSW dominates the ANN landscape for good reasons:
- No training step. Vectors are inserted one at a time; there are no centroids to go stale. (This is IVF's biggest operational advantage in reverse — see 2.6.)
- Excellent recall per unit of work across dimensionalities, especially on the 384–3072-dim embeddings used in RAG.
- Online inserts. New vectors slot into the graph as they arrive (with caveats — 6.1).
- Simple mental model once you see the greedy walk.
Its weaknesses: deletions are expensive (removing a node can fragment the graph — 6.2); memory overhead (each node stores vectors plus neighbour lists); build time grows superlinearly; and it assumes vectors live in RAM (disk-resident variants exist — 7.3).
3.3 The knobs: M, efConstruction, efSearch/ef#
| Knob | When set | Effect |
|---|---|---|
M |
Build | Max graph degree (links per node per layer; layer 0 often allows ~2M). Higher M → better connectivity → better recall, at ~M × 8–10 bytes/vector of link overhead (hnswlib docs) and slower builds/queries. Typical range 12–48; hnswlib defaults M=16, pgvector m=16, Qdrant m=16, FAISS examples often use 32–64. |
efConstruction (FAISS efConstruction, hnswlib ef_construction, pgvector ef_construction, Qdrant ef_construct) |
Build | Candidate-list size during insertion — how thoroughly each new node searches for its neighbours. Higher → better graph quality → better recall ceiling, slower and more expensive builds. Defaults: hnswlib 200, pgvector 64, Qdrant 100, FAISS unset (you set it). |
efSearch / ef (FAISS efSearch, hnswlib ef via set_ef, pgvector hnsw.ef_search, Qdrant ef, Elasticsearch num_candidates) |
Query | The dynamic candidate list size during the walk — the main recall/latency dial. Must be ≥ k. Higher → better recall, slower. Defaults vary widely: pgvector 40, Qdrant = ef_construct, Elasticsearch 1.5 × k capped at 10,000, hnswlib you set it. |
The relationship to know: efConstruction sets the recall ceiling; efSearch is how close to it you get at query time. If efSearch is high but recall is still bad, the graph itself is weak — raise efConstruction (or M) and rebuild. hnswlib's docs give a neat diagnostic: measure recall with ef = ef_construction; below ~0.9 means the construction quality has room to improve.
3.4 Build a tiny NSW graph in pure Python — and measure recall#
To see the mechanism, here is a complete navigable-small-world index in ~70 lines: greedy insertion (each new point links to its M nearest already-inserted nodes, found by a greedy walk), then greedy best-first search. This is the bottom layer of HNSW — the hierarchy on top is an optimisation for scale, not a different idea.
# vector_indexes_numpy.py — PART 2 (this section): toy NSW graph.
# Uses its own dataset (names suffixed _n) so the shared s2_4 data stays intact;
# recall_at_k is reused from Part 1.
import numpy as np
rng_n = np.random.default_rng(7)
N_n, D_n, K_TRUE_n = 2000, 32, 8
centers_n = rng_n.normal(size=(K_TRUE_n, D_n))
centers_n /= np.linalg.norm(centers_n, axis=1, keepdims=True)
X_n = centers_n[rng_n.integers(0, K_TRUE_n, N_n)] + 0.15 * rng_n.normal(size=(N_n, D_n))
X_n /= np.linalg.norm(X_n, axis=1, keepdims=True)
Qc_n = np.repeat(centers_n, 3, axis=0)
Q_n = Qc_n + 0.10 * rng_n.normal(size=(K_TRUE_n * 3, D_n))
Q_n /= np.linalg.norm(Q_n, axis=1, keepdims=True)
K_n = 10
_evals = [0] # distance computations; a list so dist() can mutate it without `global`
def dist(i, v): # cosine distance on unit vectors = 1 - dot
_evals[0] += 1
return 1.0 - float(X_n[i] @ v)
def build_nsw(X, M=8, ef_construction=40, seed=1):
n = len(X)
adj = [set() for _ in range(n)]
inserted = []
order = np.random.default_rng(seed).permutation(n)
def greedy(v, ef, allowed):
ep = inserted[np.random.default_rng(0).integers(len(inserted))]
cand = {ep: dist(ep, v)}
res = {ep: dist(ep, v)}
while cand:
c = min(cand, key=cand.get)
if len(res) > ef and cand[c] >= max(res.values()):
break
del cand[c]
for e in adj[c]:
if e not in res and e in allowed:
d = dist(e, v)
res[e] = d
cand[e] = d
if len(res) > ef:
worst = max(res, key=res.get)
del res[worst]
cand.pop(worst, None)
return sorted(res, key=res.get)[:ef]
for pos, i in enumerate(order):
if pos == 0:
inserted.append(i)
continue
allowed = set(inserted)
for j in greedy(X[i], ef_construction, allowed)[:M]:
adj[i].add(j)
adj[j].add(i)
if len(adj[j]) > 2 * M: # layer-0 degree cap ~2M
keep = sorted(adj[j], key=lambda t: dist(t, X[j]))[:2 * M]
adj[j] = set(keep)
inserted.append(i)
return adj
def nsw_search(adj, q, ef, k, entry=0):
cand = {entry: dist(entry, q)}
res = {entry: dist(entry, q)}
while cand:
c = min(cand, key=cand.get)
if len(res) > ef and cand[c] >= max(res.values()):
break
del cand[c]
for e in adj[c]:
if e not in res:
d = dist(e, q)
res[e] = d
cand[e] = d
if len(res) > ef:
worst = max(res, key=res.get)
del res[worst]
cand.pop(worst, None)
return sorted(res, key=res.get)[:k]
exact_n = [set(np.argsort(-(X_n @ q))[:K_n].tolist()) for q in Q_n]
adj = build_nsw(X_n, M=8, ef_construction=40)
print("avg degree:", round(np.mean([len(a) for a in adj]), 1))
for ef in [10, 20, 40, 80, 160, 320]:
approx = [nsw_search(adj, q, ef=ef, k=K_n) for q in Q_n]
print(f" ef={ef:4d} recall@{K_n}={recall_at_k(approx, exact_n, K_n):.3f}")avg degree: 12.1
ef= 10 recall@10=0.588
ef= 20 recall@10=0.821
ef= 40 recall@10=0.950
ef= 80 recall@10=0.996
ef= 160 recall@10=1.000
ef= 320 recall@10=1.000Three things to notice:
- Recall climbs smoothly with
ef— the same shape you'll see sweepingefSearch/ef/nprobeon any system. There is no cliff; you pick the point that meets your target. - The walk is cheap relative to brute force. The
_evalscounter (the script does not print it; reset it before a search and print_evals[0]after, as exercise 2 asks) counted roughly 190–630 distance computations per query across thisefrange in the author's runs (seed-dependent, so yours will differ), versus 2,000 for exact — and the ratio improves withN(the walk's cost grows slowly while brute force grows linearly). efis the only query-time dial.Mandef_constructionwere fixed at build; if recall plateaus below target no matter how highefgoes, the graph itself needs rebuilding with better construction parameters — exactly the diagnostic from 3.3.
3.5 HNSW in production#
The same index appears everywhere with different names for the same knobs. hnswlib (0.8.0 — Chroma uses its own fork, chroma-hnswlib; the library underlies many other wrappers):
# s3_5_hnswlib.py — hnswlib 0.8.x API (independent illustrative snippet)
import hnswlib
import numpy as np
d = 1536
xb = np.random.randn(100_000, d).astype(np.float32)
xb /= np.linalg.norm(xb, axis=1, keepdims=True)
index = hnswlib.Index(space='cosine', dim=d) # 'l2', 'cosine' or 'ip'
index.init_index(max_elements=len(xb), M=16, ef_construction=200)
index.add_items(xb, np.arange(len(xb)))
index.set_ef(100) # query-time dial; must be >= k
labels, distances = index.knn_query(xb[:5], k=10)
index.save_index('index.bin') # mmap-able, shareable across processeslabels shape (5, 10) int; distances shape (5, 10) float, cosine distance in [0, 2]Note max_elements must be declared upfront (it can be raised later via resize_index or load_index(..., max_elements=...)), ef is not persisted with the index — you must set_ef after every load — and mark_deleted(label)/unmark_deleted(label) implement tombstones (6.2). space='cosine' means distances are cosine distance; for inner product use 'ip' on normalised vectors.
FAISS (IndexHNSWFlat, 1.15.x):
# s3_5_faiss_hnsw.py
import faiss
import numpy as np
d = 1536
xb = np.random.randn(1_000_000, d).astype(np.float32)
faiss.normalize_L2(xb)
index = faiss.IndexHNSWFlat(d, 32) # M = 32 links per node
index.hnsw.efConstruction = 80 # build quality (set BEFORE add)
index.hnsw.efSearch = 64 # query-time dial
index.add(xb) # sequential adds only — wrap in IDMap for ids
D, I = index.search(xb[:5], 10)FAISS's wiki gives the memory formula: 4d + x·M·2·4 bytes per vector, where x is the number of layers the node participates in (grows slowly, ~log N). HNSW variants IndexHNSWSQ and IndexHNSWPQ store quantized vectors inside the graph — 4.6. HNSW cannot remove vectors (the wiki is explicit: it would destroy the graph structure), and add is sequential — use IndexIDMap/IndexHNSW+IDMap wrappers when you need stable IDs.
pgvector (0.8.7, illustrative SQL):
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
SET hnsw.ef_search = 100; -- query-time dial, default 40
SELECT id, content, embedding <=> $1 AS distance
FROM chunks ORDER BY distance LIMIT 10;pgvector's docs note an HNSW index "can be created without any data in the table since there isn't a training step like IVFFlat", that m/ef_construction are index-time only (rebuild to change), and that maintenance_work_mem controls build speed. Deletes are handled by PostgreSQL's normal MVCC — dead tuples linger until VACUUM, which is why pgvector docs recommend REINDEX INDEX CONCURRENTLY + VACUUM for HNSW maintenance (6.2).
Qdrant configures the same graph per collection (defaults m=16, ef_construct=100, ef defaults to ef_construct at search, full_scan_threshold=10000 KB below which it prefers brute force — note "1Kb = 1 vector of size 256"). Its distinguishing feature is the filter-aware HNSW: extra graph edges built from indexed payload values so filtered search doesn't destroy recall (06.6 covers this; Qdrant docs, v1.1.1+).
3.6 Deletes and updates in graph indexes — preview#
Graph indexes are built on connectivity, so removal is their weak point. hnswlib offers mark_deleted (tombstone: excluded from results but still in the graph, and allow_replace_deleted=True lets new inserts reuse the slot); FAISS HNSW offers nothing; pgvector relies on MVCC + VACUUM. The full treatment — tombstones, compaction, segments, read-after-write — is Part 6.
Part 4: Quantization#
Reference
4.1 The compression ladder#
02.3, 10.2 introduced quantization at the embedding-model level (asking the API for int8 or binary vectors); this part is quantization inside the index — compressing vectors after they've been stored, usually transparently. The ladder, from lossless to aggressive:
| Level | Storage | Bytes/dim | Compression vs fp32 | Typical recall impact | Notes |
|---|---|---|---|---|---|
| float32 | raw | 4 | 1× | none | the baseline everything is measured against |
| float16 / bfloat16 | half precision | 2 | 2× | tiny | pgvector halfvec, FAISS QT_fp16, most GPU indexes; often free accuracy-wise |
| int8 / uint8 (scalar quantization, SQ) | 256 levels per dim | 1 | 4× | small, usually <1–2% recall loss | needs per-dimension or global scale calibration |
| product quantization (PQ) | M chunk codes, 8 bits each | M/d |
8–64× | moderate; needs rescoring | FAISS IndexPQ, Qdrant PQ, IVF-PQ |
| binary (1 bit/dim) | sign bits | 1/8 | 32× | large alone; fine with rescore | Hamming distance, SIMD-friendly |
| 1.5/2-bit binary, TurboQuant | few bits/dim | ~0.2 | 16–32× | between binary and SQ | newer methods (Qdrant docs, November 2026: 1.5-bit and 2-bit binary since v1.15.0, TurboQuant since v1.18.0 with 1- to 8-bit depths) |
The crucial insight: compression and candidate selection are independent. You can quantize vectors inside an IVF index (IVF-SQ, IVF-PQ), inside a graph (HNSW-SQ, HNSW-PQ), or in a flat scan — and you can always keep the original vectors aside for rescoring. What you give up is distance fidelity; what you buy is memory and bandwidth, which at scale is usually the binding constraint.
The runnable snippets below continue vector_indexes_numpy.py from 2.4 — they reuse its X, Q, exact, recall_at_k and K, so run them in order in the same file (the appendix has the whole thing assembled).
4.2 Scalar quantization in NumPy#
Scalar quantization stores each dimension as an 8-bit integer. The simplest scheme maps each dimension's observed [min, max] range to 0–255; production systems often use per-dimension percentiles or a single global scale for speed.
# vector_indexes_numpy.py — PART 3 (this section): scalar quantization.
# Reuses X, Q, exact, recall_at_k, K, D from Part 1.
import numpy as np
def quantize_scalar(X):
"""Per-dimension min/max -> uint8 codes."""
lo = X.min(axis=0)
hi = X.max(axis=0)
span = np.where(hi > lo, hi - lo, 1.0)
q = np.clip(np.round((X - lo) / span * 255), 0, 255).astype(np.uint8)
return q, lo, span
def dequant_scalar(q, lo, span):
return q.astype(np.float32) / 255.0 * span + lo
def oversample_rescore(Q, candidate_lists, k):
"""Rescore every candidate with full-precision vectors; keep top-k.
Shared helper for the rest of Part 4 — used by the PQ demo (4.4) and the
oversampling sweep (4.5); the idea is explained properly in 4.5."""
out = []
for qi, cands in zip(Q, candidate_lists):
scores = X[cands] @ qi
out.append(np.sort(cands[np.argsort(-scores)[:k]]))
return out
q8, lo, span = quantize_scalar(X)
Xq = dequant_scalar(q8, lo, span)
approx = [set(np.argsort(-(Xq @ q))[:K].tolist()) for q in Q]
print(f"bytes/vector: {D*4} -> {D} recall@{K}: {recall_at_k(approx, exact, K):.3f}")bytes/vector: 256 -> 64 recall@10: 0.9884× smaller, recall 0.988 — scalar quantization is the "free" compression for most embedding workloads. The catch: it still costs d bytes per vector and d multiply-adds per comparison; it buys memory, not asymptotic speed. (For cosine on unit vectors you can do even better with a shared scale — that's what several engines do internally.)
4.3 Binary quantization and Hamming scoring#
Binary quantization keeps only the sign of each dimension: + → 1, − → 0. Distance becomes the Hamming distance — the count of differing bits — which CPUs evaluate with XOR + popcount over whole machine words, making it the fastest similarity primitive in existence. The catch: it discards magnitude entirely, so it works best on high-dimensional, centred distributions (Qdrant's docs recommend it for ≥~1,000-dim embeddings; 02.3, 10.2 measured 80% top-1 on a small 384-dim model).
# vector_indexes_numpy.py — PART 3 (continued): binary quantization + Hamming.
# Reuses X, Q, exact, recall_at_k, K, D from Part 1.
import numpy as np
def quantize_binary(X):
return (X > 0).astype(np.uint8) # 1 bit per dim; real systems bit-pack (np.packbits)
def hamming_topk(Qb, Db, k):
out = []
for q in Qb:
agree = (Db == q).sum(axis=1) # matching bits = similarity
out.append(np.argsort(-agree)[:k])
return out
Xb, Qb = quantize_binary(X), quantize_binary(Q)
approx_bin = hamming_topk(Qb, Xb, K)
# the printed size assumes bit-packing; this array keeps one byte per dim for clarity
print(f"bytes/vector: {D*4} -> {D//8} (packed) recall@{K}: {recall_at_k(approx_bin, exact, K):.3f}")bytes/vector: 256 -> 8 (packed) recall@10: 0.150On our 64-dim synthetic data, binary alone is poor (0.150) — expected at this dimensionality, and an honest demonstration that the compressed score is only a candidate generator. Nobody ships binary without rescoring; the next sections show why that still wins.
4.4 Product quantization in NumPy#
Product quantization (PQ) splits each vector into M contiguous chunks and quantizes each chunk independently to one of 2^nbits centroids learned by k-means on that chunk. A vector becomes M bytes (with nbits=8) — e.g. a 1,536-dim vector becomes 96 bytes at M=96, a 64× compression. Distance is approximated by summing per-chunk distances to the assigned centroids — computable via lookup tables, which is why PQ is fast in compressed domain.
# vector_indexes_numpy.py — PART 3 (continued): product quantization.
# Reuses the shared data/helpers; oversample_rescore was defined in 4.2.
import numpy as np
def make_pq(X, M, nbits, iters=20, seed=0):
"""Split d into M chunks; k-means 2**nbits centroids per chunk (Euclidean)."""
n, d = X.shape
assert d % M == 0, "d must be divisible by M" # same constraint as FAISS PQ
m = d // M
r = np.random.default_rng(seed)
centroids = np.zeros((M, 2**nbits, m), dtype=np.float32)
codes = np.zeros((n, M), dtype=np.uint8)
for j in range(M):
sub = X[:, j*m:(j+1)*m]
C = sub[r.choice(n, 2**nbits, replace=False)].copy()
for _ in range(iters):
# Euclidean k-means: assign each chunk to its nearest centroid, then move
# centroids to the member mean. PQ chunks are NOT unit-normalised, so the
# argmax-dot-product trick from 2.4's kmeans does not apply here.
d2 = ((sub[:, None, :] - C[None, :, :]) ** 2).sum(axis=2)
a = np.argmin(d2, axis=1)
for c in range(2**nbits):
mem = sub[a == c]
if len(mem):
C[c] = mem.mean(axis=0)
d2 = ((sub[:, None, :] - C[None, :, :]) ** 2).sum(axis=2)
codes[:, j] = np.argmin(d2, axis=1)
centroids[j] = C
return centroids, codes
def pq_topk(Q, Db_codes, centroids, k):
"""Asymmetric distance: query stays full-precision, stored vectors are codes."""
n = len(Db_codes)
M, _, m = centroids.shape # (M chunks, 2**nbits centroids, m dims per chunk)
out = []
for q in Q:
scores = np.zeros(n, dtype=np.float32)
for j in range(M):
d_cent = ((centroids[j] - q[j*m:(j+1)*m]) ** 2).sum(axis=1)
scores += d_cent[Db_codes[:, j]]
out.append(np.argsort(scores)[:k])
return out
for M in [8, 16]:
centroids, codes = make_pq(X, M=M, nbits=8)
wide = pq_topk(Q, codes, centroids, K * 8)
topk = [set(a[:K]) for a in wide]
resc = oversample_rescore(Q, [w[:80] for w in wide], K)
print(f"M={M}: bytes/vector={M} ({D*4//M}x) "
f"raw recall@{K}={recall_at_k(topk, exact, K):.3f} "
f"rescore-80 recall@{K}={recall_at_k(resc, exact, K):.3f}")M=8: bytes/vector=8 (32x) raw recall@10=0.400 rescore-80 recall@10=0.912
M=16: bytes/vector=16 (16x) raw recall@10=0.596 rescore-80 recall@10=1.000Read it carefully — this is the whole PQ story in two lines:
- Raw PQ recall is modest (0.4–0.6 here) because each chunk's centroid is a crude summary. That's fine: PQ's job is to propose candidates cheaply.
- Rescoring recovers nearly all of the loss (0.91–1.00) because the true top-10 usually survives inside a wider candidate net.
M=16buys recall with bytes;M=8buys memory with recall. That's the PQ dial. - Real systems improve on this toy: PQ is normally trained on residuals (vector minus its IVF centroid —
IndexIVFPQ), often with a rotation (OPQ) and a second refinement stage (IndexIVFPQR), and its k-means is mini-batch for speed. Our toy skips IVF entirely and runs full Lloyd iterations, which is why the absolute numbers differ — the mechanism is identical.
4.5 Oversampling and rescoring#
Oversampling means: retrieve factor × k candidates with the cheap compressed index, then rescore those candidates with the full-precision vectors and keep the true top-k. It exploits an asymmetry — compressed search is fast but slightly wrong; full-precision rescoring of 50–200 vectors is cheap because it's only factor × k × d work, not N × d.
# vector_indexes_numpy.py — PART 3 (continued): oversampling sweep on binary codes.
# quantize_binary (4.3) and oversample_rescore (4.2) are already defined above.
import numpy as np
Xb, Qb = quantize_binary(X), quantize_binary(Q)
print("binary index, vary oversampling factor (k=10):")
for f in [1.0, 2.0, 4.0, 8.0]:
wide = []
for qi, qb in zip(Q, Qb):
agree = (Xb == qb).sum(axis=1)
wide.append(np.argsort(-agree)[: int(np.ceil(K * f))])
rescored = oversample_rescore(Q, wide, K)
print(f" factor={f:3.1f}x candidates={int(np.ceil(K*f)):3d} recall@{K}={recall_at_k(rescored, exact, K):.3f}")binary index, vary oversampling factor (k=10):
factor=1.0x candidates= 10 recall@10=0.150
factor=2.0x candidates= 20 recall@10=0.254
factor=4.0x candidates= 40 recall@10=0.438
factor=8.0x candidates= 80 recall@10=0.629This is the single most important quantization result in the lesson:
- At 32× compression (8 bytes/vector), binary+8×-oversample+rescore reaches recall 0.629 — still below par at 64 dims, because binary is weak here. On a real 1,024+ dim embedding, the same recipe typically recovers >0.9 (measure on your data — 06.10).
- Oversampling has diminishing returns and a hard ceiling: rescoring can only reorder candidates the cheap index already found. If the true neighbour never made the candidate list, no factor helps. That ceiling is why oversampling complements — never replaces — a decent candidate generator.
- The production knobs are exactly this idea: Qdrant's
oversampling(e.g.2.4withlimit=100pre-selects 240), Elasticsearch'srescore_vector, pgvector's re-rank SQL pattern (README example usesORDER BY binary_quantize(...) LIMIT 20then re-orders by the real distance).
4.6 Combos in production: IVF-PQ, HNSW-SQ, and friends#
Quantization and partitioning/graphing compose — that's how you fit hundreds of millions of vectors in RAM:
- IVF-PQ (
IndexIVFPQ; pgvector has no native PQ): partition with IVF, store PQ codes in each list, probenprobelists in compressed domain, rescore survivors. FAISS calls it "probably the most useful indexing structure for large-scale search". - IVFADC+R (
IndexIVFPQR): PQ on residuals plus a second refinement quantizer — the FAISS recipe for maximum compression. - HNSW-SQ / HNSW-PQ (
IndexHNSWSQ,IndexHNSWPQin FAISS): quantized vectors inside the graph — the walk itself runs on compressed distances, so both memory and per-step cost drop. Qdrant keeps originals alongside quantized vectors and rescores at query time. - DiskANN/Vamana + PQ: the graph lives on SSD, vectors are PQ-compressed — billion-scale on one node (7.3).
- Elasticsearch 9.x:
dense_vectorindex_optionsoffer the graph typeshnsw,int8_hnsw,int4_hnswandbbq_hnsw(withm/ef_construction, andnum_candidatesat search), brute-forceflat/int8_flat/int4_flat/bbq_flattypes, andbbq_disk(DiskBBQ: k-means clustering plus binary quantization, since 9.2, Enterprise subscription), and float vectors ship with managed quantization — in 9.0 they defaulted toint8_hnsw; from 9.1bbq_hnswis the default for ≥384-dim vectors (int8_hnswbelow), and from 9.4bbq_diskis the default when your licence allows it (Elastic mapping reference, November 2026).rescore_vectorrecovers quantized recall — the whole Part 4 pipeline as managed defaults. OpenSearch is a different stack:knn_vectorfields run on the Faiss or Lucene engines (hnswon both,ivfon Faiss) with its own quantization menu — Lucene scalar quantization, Faiss SQ/PQ/binary (1/2/4-bit) and anon_diskmode that pairs compression with rescoring. - ScaNN-style anisotropic quantization: quantize harder where it hurts less — Google's approach, concept in 7.4.
# s4_6_faiss_combos.py — FAISS 1.15.x, illustrative
import faiss
import numpy as np
d = 1536
xb = np.random.randn(50_000_000, d).astype(np.float32) # too big for RAM uncompressed
faiss.normalize_L2(xb[:100_000]) # train on a sample
# IVF-PQ: 4096 cells, 96-byte PQ codes per vector
index = faiss.index_factory(d, "IVF4096,PQ96")
index.train(xb[:100_000])
index.add(xb)
index.nprobe = 32
# IVFADC+R refinement: "IVF4096,PQ96+48"
# HNSW over scalar-quantized vectors
hnsw_sq = faiss.IndexHNSWSQ(d, 32, faiss.ScalarQuantizer.QT_8bit)
hnsw_sq.hnsw.efConstruction = 80
hnsw_sq.add(xb)
hnsw_sq.hnsw.efSearch = 64IndexIVFPQ stores ~ceil(96*8/8)+8 = 104 bytes/vector vs 6144 for fp32 (~59x)4.7 Compression ratios and index memory#
Worked example — 10M chunks at d=1536, the rough size of a mid-size RAG corpus:
| Representation | Bytes/vector | Vector bytes | + IVF/HNSW overhead | Total (approx.) |
|---|---|---|---|---|
| fp32 flat | 6,144 | 61 GB | — | ~61 GB |
| fp16 | 3,072 | 31 GB | — | ~31 GB |
| int8 (SQ) | 1,536 | 15 GB | — | ~15 GB |
| binary | 192 | 1.9 GB | — | ~1.9 GB |
PQ M=96 codes |
96 + ids | ~1 GB | codebook 96×256×16×4 ≈ 1.6 MB — negligible |
~1 GB |
HNSW fp32 (M=16) |
6,144 + links | ~61 GB | links ~16×8–10 ≈ 130 B/vec → +1.3 GB |
~63 GB |
(All figures are estimates from the formulas in this lesson — N × d × bytes plus index overhead; verify against your engine's docs.)
Two lessons: the vectors dominate memory, so quantization is the highest-leverage cost decision; and graph links are cheap relative to vectors — HNSW's overhead is a few percent, not a doubling. PQ's hidden cost is the codebook and the rescoring pass, which needs the original vectors somewhere (RAM, disk, or re-fetchable from your document store — a real architectural choice).
4.8 Matryoshka truncation meets quantization#
There is a second, orthogonal way to shrink vectors: shrink their dimensionality. Matryoshka embeddings are trained so that a prefix of the vector is itself a usable embedding — truncate to the first d' dimensions, renormalise, and quality degrades gracefully instead of collapsing. OpenAI's text-embedding-3-* models expose this directly through the dimensions parameter (the API returns the truncated vector); 06.1 covers which models support it, and 02.3, 10.1 explains the training trick and the manual-truncation-plus-renormalise recipe.
The two techniques multiply. Bytes per vector ≈ d' × bytes_per_dim:
| Recipe | Dims | Quantization | Bytes/vector | vs fp32-1536 |
|---|---|---|---|---|
| Full | 1536 | fp32 | 6,144 | 1× |
| Truncate only | 512 | fp32 | 2,048 | 3× |
| Quantize only | 1536 | int8 | 1,536 | 4× |
| Truncate + int8 | 512 | int8 | 512 | 12× |
| Truncate + int8 | 256 | int8 | 256 | 24× |
Three caveats:
- Truncation only works on Matryoshka-trained models. Chopping dimensions off a non-Matryoshka embedding — or applying PCA blindly — silently degrades recall, because the leading dimensions of an ordinary embedding are not a nested representation. Check the model card before assuming.
- Renormalise after truncating when you score with cosine or dot product — a truncated vector no longer has unit length. (The
dimensionsAPI parameter already returns a normalised vector; manual truncation does not.) dimsis fixed when the index is created, so truncation is a data-pipeline decision made before indexing, not a per-query knob. That's why it's cleaner to ask the embedding API for the shorter vector up front — one less thing to keep consistent between your stored vectors and your queries.
The storage tiers fall out naturally: the small quantized/truncated vectors that the index and the rescoring pass touch belong in RAM or fast NVMe; the full-precision originals can live in a cheaper tier — object storage, or re-fetchable from your document store — needed only for rescoring, audits and re-embedding. Quantization decides what must be fast; Matryoshka decides how small the fast copy can be.
Part 5: The tuning triangle — knobs, ground truth, and the sweep#
5.1 Every knob on one page#
| Family | Build-time knobs | Query-time knobs | Pushes which corner |
|---|---|---|---|
| Flat / brute force | — | k |
recall=1.0 always; latency & memory worst |
| IVF | nlist, k-means iterations, training sample |
nprobe |
nlist↑ → faster queries, more build time & memory; nprobe↑ → recall↑ latency↑ |
| HNSW | M, efConstruction (a.k.a. ef_construction, ef_construct) |
efSearch/ef/num_candidates |
M,efC↑ → recall ceiling↑, build time/memory↑; ef↑ → recall↑ latency↑ |
| PQ / SQ / binary | codebook size (M, nbits), calibration sample |
none (codes fixed) | compression↑ → memory↓ speed↑, recall ceiling↓ |
| Quantized combos | IVF/HNSW knobs + quantization params | nprobe/ef + oversampling/rescore |
oversample↑ → recall↑ (bounded), rescore cost↑ |
| Annoy | n_trees |
search_k |
trees↑ → recall↑ build time↑; search_k↑ → recall↑ latency↑ |
| DiskANN/Vamana | R (degree), Lbuild |
Lsearch |
same shape as HNSW |
The universal pattern: build knobs set the ceiling, query knobs trade speed for recall within it. Tune build knobs once (they're expensive to change — rebuild), then tune query knobs continuously.
5.2 Build ground truth first#
You cannot tune what you cannot measure. Ground truth = the exact top-k for a set of queries, computed by brute force:
# vector_indexes_numpy.py — PART 4 (this section): build ground truth.
# Reuses X, centers, K_TRUE, D, K from Part 1. The demo Q has only 24 queries —
# too few for stable recall estimates — so we synthesise ~200 eval queries here
# (a real eval set is ~200-1000 queries; see the guidelines below).
import numpy as np
eval_rng = np.random.default_rng(123) # fresh rng: eval queries stay independent of Q
eval_queries = centers[eval_rng.integers(0, K_TRUE, 200)] \
+ 0.12 * eval_rng.normal(size=(200, D))
eval_queries /= np.linalg.norm(eval_queries, axis=1, keepdims=True)
eval_exact = np.argsort(-(eval_queries @ X.T), axis=1)[:, :K] # (200, k) true neighbours
np.save("ground_truth.npy", eval_exact)
print(f"ground truth saved: {eval_exact.shape[0]} queries x top-{K}")ground truth saved: 200 queries x top-10Guidelines for a useful ground truth:
- Queries must look like production queries — real user questions or your Module-05-generated eval set (10A.2), not random vectors. The cluster-centre queries in this script (both
Qandeval_queries) are easier than real ones; add hard cases (ambiguous, out-of-corpus, keyword-style). - Sample, don't exhaust. Exact search on 10M vectors × 1,000 queries is 10¹⁰ distance computations — fine on GPU, painful on CPU. A few hundred queries is usually enough to see the recall curve's shape; the 06.10 lesson covers statistical rigour.
- Compute it once, cache it. Ground truth doesn't change when you retune
ef/nprobe— that's the whole point of separating build knobs from query knobs.
5.3 The sweep procedure#
The procedure, applied to any index:
- Fix the build configuration (
nlist,M,efConstruction, quantization). - For each value of the query knob (
nprobe,ef,oversampling): run all eval queries, compute recall@k vs ground truth, and measure latency (time per query, report p50 and p99). - Plot/tabulate recall vs latency; pick the smallest knob value meeting your recall SLA.
- If the ceiling is too low, go back to step 1 and improve the build.
Here's the harness — it works with any search function, including the FAISS/hnswlib indexes from earlier (wrap their search/knn_query to return ID lists):
# vector_indexes_numpy.py — PART 4 (continued): the sweep harness.
# Reuses ivf_query/C/lists/X/Q/K/exact_topk/recall_at_k from earlier parts.
import numpy as np
import time
def sweep(search_fn, queries, exact, k, knob_values):
"""search_fn(q, knob) -> iterable of top-k ids. Returns recall + latency table."""
rows = []
for knob in knob_values:
t0 = time.perf_counter()
approx = [set(search_fn(q, knob)[:k]) for q in queries]
elapsed = (time.perf_counter() - t0) / len(queries)
rec = recall_at_k(approx, [set(e.tolist()) for e in exact], k)
rows.append((knob, rec, elapsed * 1000)) # ms per query
return rows
# IVF: search_fn = lambda q, nprobe: ivf_query(q, X, C, lists, nprobe, K)
# NSW: search_fn = lambda q, ef: nsw_search(adj, q, ef=ef, k=K)
# FAISS: search_fn = lambda q, ef: index.search(q[None,:].astype('f32'), K)[1][0].tolist()
# (set index.hnsw.efSearch = ef inside the lambda)
for knob, rec, ms in sweep(
lambda q, nprobe: ivf_query(q, X, C, lists, nprobe, K),
Q, exact_topk(X, Q, K), K, [1, 2, 4, 8, 16]):
print(f"nprobe={knob:3d} recall@{K}={rec:.3f} ~{ms:.3f} ms/query")nprobe= 1 recall@10=0.250 ~0.4 ms/query
nprobe= 2 recall@10=0.463 ~0.7 ms/query
nprobe= 4 recall@10=0.771 ~1.2 ms/query
nprobe= 8 recall@10=0.979 ~2.3 ms/query
nprobe= 16 recall@10=1.000 ~4.1 ms/queryThe shape is universal: recall rises steeply then saturates; latency rises ~linearly. Your job is picking the "knee" — the point where recall meets target at minimum cost.
5.4 Choosing the operating point#
Translate your SLA into a recall target first, then find the cheapest knob value that meets it:
| Your constraint | Start with | Then |
|---|---|---|
| Latency budget (e.g. p99 < 50 ms) | mid-range ef/nprobe, measure |
raise until recall target met or budget exhausted |
| Recall target (e.g. recall@10 ≥ 0.95) | smallest ef/nprobe meeting it |
verify p99 latency is affordable |
| Memory-bound (index must fit RAM) | quantize (SQ → PQ → binary+rescore) | re-tune ef/nprobe/oversampling on the compressed index |
| Build-time-bound (frequent reindex) | HNSW with moderate efConstruction, or IVF |
avoid PQ training cost; prefer SQ |
| Both recall and latency tight | quantized HNSW/IVF + rescore, or DiskANN | this is the hard case — measure on your data |
5.5 Build cost vs query cost, and index size#
The other half of tuning is when you pay:
- Build knobs are one-time but expensive. HNSW
efConstruction=200on 10M vectors can take hours on CPU; IVF k-means on the same is faster but still minutes-to-hours. Budget builds like batch jobs, not requests. - Query knobs are per-request but cheap to change.
ef/nprobe/oversamplingare runtime parameters in every system — tune them live, per traffic class (interactive vs batch can use different values). - Index size formulas (estimates — verify per engine):
- IVF-Flat:
N × (4d + 8)bytes +nlist × 4dcentroids - HNSW-Flat:
N × (4d + ~M × 8–10)bytes (FAISS:4d + x·M·2·4) - PQ codes:
N × (M_pq × nbits/8 + 8)bytes +M_pq × 2^nbits × (d/M_pq) × 4codebook - Binary:
N × d/8bytes
- IVF-Flat:
Part 6: Updates, deletes and consistency#
Deep-dive
6.1 Inserts into HNSW and IVF#
- HNSW: inserts are native and online — each new vector is greedily inserted into the graph like a build-time insert. Cost per insert is roughly a search (
efConstruction-ish work), so bulk loads are much faster as a batch build than N individual inserts. hnswlibadd_items, FAISSadd, pgvectorINSERT(which updates the index incrementally), Qdrant upserts all do this. - IVF: new vectors are assigned to the nearest existing centroid and appended to that list — cheap, but they never improve the partition. After enough drift, recall decays until you retrain/rebuild (2.6).
- Quantized indexes: new vectors must be encoded with the existing codebooks/centroids — you can't add raw vectors to a PQ index; the engine quantizes on insert (Qdrant does this transparently; FAISS requires you encode or use the index's
addwhich handles it forIndexIVFPQ).
6.2 Deletes: tombstones and compaction#
Deletes are where index families diverge hardest:
| Engine | Delete mechanism | Cost |
|---|---|---|
| hnswlib | mark_deleted(label) tombstone; allow_replace_deleted=True reuses slots |
cheap mark; tombstones accumulate until rebuild |
| FAISS HNSW | none — removal unsupported | rebuild or IDMap-filter workaround |
| FAISS IVF/Flat | remove_ids(selector) rewrites lists |
moderate; list compaction |
| pgvector (HNSW) | MVCC DELETE; dead tuples cleaned by VACUUM; REINDEX INDEX CONCURRENTLY rebuilds clean |
deletes are "free" but index bloat lingers; periodic VACUUM/REINDEX needed |
| Qdrant / managed DBs | segment-based: deletes mark points; background optimizers merge/compact segments | eventual — deleted points can appear in results briefly |
The pattern-level truth: no ANN index deletes eagerly. Tombstones and segment merges trade immediate consistency for write speed. If your use case needs hard real-time deletes (GDPR erasure, "this doc must never appear"), you need either a system with synchronous delete semantics or an application-level guard (filter deleted IDs at query time — cheap insurance, see 06.6).
6.3 Segments and LSM-style merging#
Managed vector databases (Qdrant, Pinecone, Elasticsearch, OpenSearch, LanceDB) don't keep one monolithic index — they keep segments: immutable chunks of vectors+payload, each with its own index, merged in the background LSM-tree style. Writes go to a small active segment (fast); queries fan out to all segments and merge results; a background optimizer merges small segments into bigger ones and drops tombstoned vectors.
Consequences you must internalise:
- Read-after-write is usually but not always immediate — your point is searchable as soon as it's in a segment the query path sees, but consistency across replicas is eventual.
- Many small segments = slower queries (more graphs to walk, more lists to probe) until the optimizer merges them. A freshly bulk-loaded collection can be slower than a compacted one.
- Deletes propagate on the optimizer's schedule, not yours — plan erasure SLAs accordingly.
- You can't tune per-segment — index parameters are collection-level; segment merging is the engine's job.
6.4 What "reindex" means operationally#
"Reindex" covers three distinct operations people conflate:
- Rebuild the index structure (same vectors, new graph/lists) — needed after tuning
M/efConstruction/nlist, after heavy deletes, or after an engine upgrade. Cost: full build time + double storage during rebuild (blue/green or shadow index). - Re-embed and re-index (new vectors) — model change, dimension change, preprocessing change. Cost: embedding API spend + full reindex; plan as a migration (06.1, 05.9 cover the pipeline side).
- Compact/merge segments — engine-internal housekeeping; usually automatic, occasionally manual.
The operational rule: index rebuilds are batch jobs with a maintenance window or a shadow-index strategy, never an online ALTER. pgvector's REINDEX INDEX CONCURRENTLY exists precisely so a rebuild doesn't block writes; managed services hide this behind their compaction schedules.
Part 7: The wider landscape#
Reference
7.1 Annoy: trees, mmap, and no updates#
Annoy (Spotify, annoy 1.17.3 on PyPI) builds a forest of random-projection trees: each tree recursively splits the space with a random hyperplane, and a query descends all trees collecting candidates. Its distinctive feature is operational, not algorithmic — indexes are static, mmap-able files shared across processes with near-zero load time.
# s7_1_annoy.py — annoy 1.17.x API (illustrative)
import numpy as np
from annoy import AnnoyIndex
d = 1536
xb = np.random.randn(1_000_000, d).astype(np.float32)
xb /= np.linalg.norm(xb, axis=1, keepdims=True)
t = AnnoyIndex(d, 'angular') # 'angular', 'euclidean', 'manhattan', 'hamming', 'dot'
for i, v in enumerate(xb):
t.add_item(i, v.tolist())
t.build(50) # 50 trees; more = better recall, slower build/load
t.save('index.ann') # static file; mmap'd by every process that loads it
u = AnnoyIndex(d, 'angular')
u.load('index.ann')
ids = u.get_nns_by_vector(xb[0].tolist(), 10, search_k=1000) # search_k = runtime recall/speed dialids: list of 10 int item ids, approximate nearest neighboursAnnoy's constraints: no adds after build, integer IDs only (you map your own IDs), and search_k (default n_trees × n) is the query-time recall dial. It's a solid choice for read-heavy, immutable corpora — Spotify's original use case — but it has been superseded by HNSW for most new work because it can't update and its recall-per-byte is weaker. Chroma doesn't use Annoy at all: it indexes with its own fork of hnswlib, chroma-hnswlib.
7.2 LSH: the historical ancestor#
Locality-sensitive hashing was the first practical ANN family: hash vectors so that similar vectors collide in the same bucket with high probability, then only compare within buckets. FAISS still ships IndexLSH (binary codes, nbits parameter) and it's exhaustive over the codes.
LSH is mostly historical for embeddings today: it needs many hash tables for decent recall (memory-hungry), its recall curve is worse than IVF or HNSW at the same cost, and data-dependent methods (k-means, learned graphs) dominate. You'll still meet it in classics (the original "ann-benchmarks" included it), in some specialist systems, and as the conceptual ancestor of both IVF (coarse quantization ≈ a learned hash) and binary quantization. Teach it as history, not as a recommendation.
7.3 DiskANN and Vamana: indexes built for disk#
When vectors exceed RAM, you can't keep the whole index in memory — but you also can't afford a disk seek per graph hop. DiskANN (Microsoft, microsoft/DiskANN, diskannpy on PyPI) solves this with the Vamana graph algorithm: a graph laid out on SSD so that each node's neighbours are stored together, plus a search beam (Lsearch) that tolerates the latency of a few page reads per hop. The 2019 NeurIPS paper demonstrated billion-point search on a single node; the library now also supports filtered search and fresh (incrementally updated) indices, and the main branch has been rewritten in Rust — v0.61.x as of October 2026 (check github.com/microsoft/DiskANN releases for the current version).
The pattern generalises: graph-on-disk with PQ-compressed vectors is the standard recipe for "too big for RAM" — used by DiskANN, Elasticsearch's bbq_disk (DiskBBQ), and Qdrant's on_disk payload/vector options. The rule of thumb: keep the graph structure and hot vectors in RAM, let cold vector data live on NVMe, and let the beam width absorb the I/O latency.
7.4 ScaNN and anisotropic quantization#
ScaNN (Google, google-research/scann) is a quantization-first engine: it partitions the data, scores with asymmetric hashing (a product-quantization variant), then rescores — the same IVF-PQ shape, but with a twist called anisotropic quantization. Instead of minimising average quantization error, it penalises error parallel to the query direction more, preserving accuracy exactly where inner products are large (i.e. for the top results that matter). Google's ICML 2020 paper reports ~2× throughput over other libraries on ann-benchmarks at equal recall.
ScaNN is a research release (x86/AVX-optimized, TensorFlow/Python APIs), not a product — but its idea shipped: anisotropic loss is why modern quantizers (including Qdrant's TurboQuant lineage) weight quantization error by direction. When you see "anisotropic" in a vector DB's docs, this is the concept.
7.5 Filtered-graph approaches — preview#
A graph walk ignores metadata, so "only return chunks from tenant X" used to mean post-filtering (walk, then discard — recall collapses when the filter is selective). The fix is filter-aware graphs: extra edges connecting nodes that share filter values, so the walk stays inside the allowed set. Qdrant's filterable HNSW (v1.1.1+, enable_hnsw on payload fields), Elasticsearch's per-segment filtered kNN, pgvector's iterative_scan (auto-expands the scan when filters leave too few rows), and DiskANN's filtered indices are all implementations. This is 06.6's core topic — here you just need to know the index side exists.
7.6 Which systems implement which — the map#
| System | Index families | Quantization | Notes |
|---|---|---|---|
| FAISS (faiss-cpu 1.15.1) | Flat, IVF*, HNSW*, NSG, LSH, DiskANN-style (SVS-Vamana) | SQ, PQ, OPQ, binary, IVFADC+R | the reference library; GPU via faiss-gpu |
| hnswlib (0.8.0) | HNSW only | none built-in (store fp32) | Chroma uses its fork chroma-hnswlib; mmap-able |
| pgvector (0.8.7) | HNSW, IVFFlat | halfvec, bit (binary_quantize), sparsevec |
inside Postgres; MVCC deletes |
| Qdrant | HNSW only (dense) | TurboQuant, SQ int8, binary 1/1.5/2-bit, PQ | filter-aware HNSW; segments |
| Chroma | HNSW (via chroma-hnswlib fork) |
— | embedded/local-first |
| Redis (Query Engine) | FLAT, HNSW (SVS-VAMANA in recent releases) | fp32 by default; compressed types in newer releases | in-memory; check current docs for quantization options |
| Pinecone | proprietary, managed (no index-type choice) | managed | serverless; you tune namespaces/filters, not graph parameters |
| AWS S3 Vectors | managed, no index parameters exposed | managed | vectors in S3 vector buckets/indexes; cost-first, higher latency than in-memory |
| Elasticsearch (9.x) | HNSW (Lucene) | int8_hnsw/bbq_hnsw/int4_hnsw/bbq_disk (DiskBBQ) |
num_candidates, rescore_vector; quantized defaults since 9.0 |
| OpenSearch | HNSW (Lucene/Faiss), IVF (Faiss) | Lucene SQ, Faiss SQ/PQ, binary 1/2/4-bit, on_disk+rescore |
separate quantization stack — no BBQ/DiskBBQ |
| USearch (2.26.6) | HNSW | many dtypes incl. fp16/int8/binary | single-file C++; external-memory serving |
| Annoy (1.17.3) | random trees | — | static mmap files; no updates |
| ScaNN | IVF + AH | anisotropic quantization | research release |
| DiskANN | Vamana graph | PQ on disk | SSD-native; billion-scale |
| sqlite-vec | exact KNN in stable releases; ANN indexes (rescore, IVF, DiskANN) landing in the v0.1.10 alpha line (2026) |
int8/bit rescore codes (alpha) | embedded; brute force is the right default to ~10⁵–10⁶ vectors |
| LanceDB / DuckDB VSS | HNSW / IVF-PQ variants | SQ/PQ/RQ (LanceDB) | embedded/analytical |
(Rows verified against each project's docs/PyPI as of November 2026; the dedicated-database decision is 06.5.)
7.7 RaBitQ, and Postgres extensions beyond pgvector#
Two more names appear in 2026 vendor documentation and are worth recognising before you meet them in a table.
RaBitQ (Gao and Long, SIGMOD 2024, arXiv:2405.12497) is a binary-quantization scheme that maps each vector to a D-bit code and, unlike product quantization, comes with a theoretical bound on the distance-estimation error; distance estimates run on bitwise or SIMD operations. Its practical face is IVF cells plus 1-bit codes for a 32× compression ratio, usually paired with an optional refine stage that rescores candidates with higher-precision data, and a candidate multiplier (refine_k-style) that controls how many survivors are rescored. That is the Part 4 recipe (cheap candidate pass, then rescore) delivered as one index option, with the usual rule: turn refinement on when you need recall of roughly 0.9 or more, and sweep nprobe, refine and refine_k on your own queries as in Part 5.
Postgres extensions beyond pgvector. pgvector gives Postgres HNSW and IVFFlat. pgvectorscale (Timescale, PostgreSQL licence) is an add-on that requires pgvector (CREATE EXTENSION vectorscale CASCADE installs both) and adds a StreamingDiskANN index inspired by Microsoft's DiskANN, a compression method called Statistical Binary Quantization (SBQ), and label-based filtering (a smallint[] labels column filtered with the && overlap operator, while other WHERE conditions are applied as post-filters). It is the Postgres answer to "pgvector's HNSW no longer fits in RAM but I want to stay in Postgres"; check its repository for supported Postgres versions and releases before adopting it, as the README does not state them. Managed Postgres services differ in which extensions they allow, so confirm availability on your host first (06.5 covers where pgvector runs).
Part 8: Scale regimes, hardware and cost#
Deep-dive
8.1 Scale regimes — a decision table#
Thresholds are approximate (they depend on d, hardware, latency target and recall needs) — treat them as starting points, not laws:
| Corpus size | Typical choice | Why |
|---|---|---|
| < ~10⁴–10⁵ | Brute force / flat index | exact, fast enough, zero tuning |
| 10⁵–10⁷ | HNSW in RAM (hnswlib, pgvector, Qdrant) or IVF | the sweet spot; both fit comfortably |
| 10⁷–10⁸ | Quantized HNSW/IVF-PQ, or DiskANN if RAM-bound | memory forces compression or disk |
| > 10⁸ | Distributed/sharded (Pinecone, Elasticsearch/OpenSearch clusters, Qdrant distributed mode), or DiskANN-class single node | sharding by tenant/time/vector-id; or accept disk latency |
The decision is rarely "which algorithm" — it's "does the working set fit in RAM, and what's my latency budget". A 10M×1536 fp32 index is ~61 GB: fits a big-memory node uncompressed, needs quantization or disk on anything smaller.
8.2 Hardware notes#
- CPU is the default. Modern x86 (AVX-512) and ARM (NEON) accelerate the distance kernels; FAISS, hnswlib, USearch and Qdrant all have SIMD paths. Single-thread performance matters more than core count for latency-sensitive queries; use threads for build and batch queries.
- GPU indexing exists (FAISS GPU, NVIDIA cuVS, Qdrant's GPU HNSW build tutorial) — mainly for build speed and huge-batch queries; serving latency is often CPU-fine. Pattern-level only; not needed until you're at serious scale.
- RAM is the budget. The index working set should fit in RAM (or page cache) — spilling to disk turns µs hops into ms seeks. Size it with the formulas in 4.7 and 5.5.
- NVMe for cold data. DiskANN-style indexes and
mmap'd flat indexes (Annoy, hnswlibload_index, FAISSOnDiskInvertedLists) trade latency for capacity — fine for batch/analytical workloads, risky for interactive p99. - Warm-up matters. First queries after boot/restart hit cold pages — graph walks and postings lists are random-access, so cold-cache latency is brutal. Warm the index (run representative queries) before opening traffic; some engines prefetch on load.
8.3 Cost per million vectors#
No hard-coded prices (they change), but the formula is stable:
monthly_cost ≈ N/1e6 × (storage_bytes_per_vector × $GB_month
+ qps × query_cost_per_vector_scan)storage_bytes_per_vectorfrom 4.7: fp32 1536-dim ≈ 6 KB → 10M vectors ≈ 61 GB; int8 ≈ 15 GB; PQ-96 ≈ ~1 GB.- Query cost depends on candidates touched per query (
nprobe/nlist × Nfor IVF, walk length for HNSW) × your compute price — or the managed service's memory-bound pricing (many charge per GB of RAM provisioned, which is why quantization is a cost feature, not just a speed one). - The dominant cost is usually memory, then build/reindex compute, then query compute. Embedding generation cost lives upstream in 06.2.
Part 9: Benchmarks and how to read them#
Reference
9.1 ann-benchmarks and VIBE#
ann-benchmarks (erikbern/ann-benchmarks, ann-benchmarks.com) was the standard public ANN benchmark for a decade — recall vs QPS curves across datasets (GloVe, SIFT, GIST, DEEP, MNIST) and algorithms. Important as of November 2026: the project is no longer actively maintained and its README now recommends VIBE (vector-index-bench/vibe, vector-index-bench.github.io) — a newer benchmark built on modern embedding datasets (including out-of-distribution sets and quantized int8/binary variants), with GPU support and a published paper. If someone cites an ann-benchmarks number, check the date and the dataset.
What these benchmarks measure: recall@k against precomputed ground truth, queries-per-second (single-threaded CPU), index build time, and index size — the exact triangle from Part 1. What they don't tell you: performance on your embedding model, your dimensionality, your query distribution, your filters, or your hardware.
9.2 Vendor benchmarks — read with suspicion#
Every vector database publishes recall/latency charts. They're usually real but always favourable: tuned on the vendor's own dataset and hardware, single-node, no filters, warm cache, batch-of-1 queries. Use them to shortlist, never to finalise — the only benchmark that matters is on your data with your queries (06.10 is the evaluation lesson).
9.3 Benchmarking your own data#
The methodology is the same as Part 5's sweep, scaled up:
- Representative queries — your real question set, not synthetic neighbours.
- Ground truth once — exact search on a sample if full is too slow; note the approximation in your ground truth itself.
- Sweep each candidate index across its query knob; record recall@k, p50/p99 latency, throughput under concurrency, index size, and build time.
- Include your real filters — filtered recall is a different (usually worse) number; test the ACL/metadata path too (06.6).
- Repeat after changes — corpus growth, model swaps, and compaction all move the numbers; make it a regression test, not a one-off.
Part 10: Choosing index settings in practice#
This is the short version for someone who has to ship a retriever this week. If a word is new, the bridge at the start of Part 5 explains it in a few lines.
10.1 The few knobs that matter#
An index has many parameters. Six of them do almost all of the work.
| Knob | Set when | Plain explanation |
|---|---|---|
HNSW M |
build | How many neighbour links each vector keeps. More links make a denser graph: better recall ceiling, more memory, slower build. 16 is the usual default. |
HNSW ef_construction |
build | How hard the build searches for each new vector's neighbours. Higher means a better graph and a slower build. It sets the recall ceiling and costs nothing at query time. |
HNSW ef_search (ef, num_candidates) |
query | How wide the walk is for one query. This is the knob you will turn most. Higher means better recall and slower queries. It must be at least k. |
IVF nlist |
build | How many cells the vectors are split into. More cells make each list shorter, but a query must probe more of them to find the same neighbours. |
IVF nprobe |
query | How many cells one query scans. The IVF equivalent of ef_search. Higher means better recall and slower queries. |
| Quantization (on or off) | build | Store compressed vectors (int8, binary, product codes). A big memory saving, a small to moderate recall loss, mostly recovered by oversampling and rescoring. |
Build knobs need a rebuild to change, so choose them once and carefully. Query knobs are plain runtime parameters, so you can sweep them in minutes. That is why the advice is always the same: sweep the query knob first.
10.2 What the databases default to (as of 2 December 2026)#
These are the defaults of the stores taught in 06.5, read from each project's official documentation or source on 2 December 2026. Defaults change between releases, so treat this table as a snapshot and re-check the version you run.
| Store | M |
ef_construction |
Query-time width | IVF | Quantization by default |
|---|---|---|---|---|---|
| pgvector (0.8.7) | m 16 |
64 | hnsw.ef_search 40 |
lists is your choice (start at rows / 1000 up to 1M rows, sqrt(rows) beyond); ivfflat.probes 1 |
none; opt in with halfvec or a binary_quantize expression index |
| Qdrant | m 16 |
ef_construct 100 |
hnsw_ef: the API reference states no default; the source falls back to the collection's ef_construct |
not offered | none; opt in with quantization_config |
| Chroma (single node) | max_neighbors 16 |
100 | ef_search 100 |
not offered | none |
| Elasticsearch 9.x | m 16 |
100 | num_candidates defaults to 1.5 × k, at most 10,000 |
not offered | yes: int8_hnsw in 9.0, bbq_hnsw from 9.1 for 384+ dimensions, bbq_disk from 9.4 where your licence allows |
| OpenSearch (Faiss engine, the default) | m 16 |
100 | ef_search 100 (the Lucene engine ignores it and uses k) |
ivf method available, you set its parameters |
none (flat encoder) |
| hnswlib (library) | M 16 |
200 | ef 10 |
not offered | none |
Four things stand out:
Mis 16 almost everywhere. You rarely need to touch it.ef_constructionvaries from 64 to 200. The graphs are not equally good out of the box, so do not compare stores on their defaults.- The query-time width is often small. pgvector's 40 and hnswlib's 10 are fine for a toy corpus and too narrow for filtered queries or a large corpus. This is the default most likely to cost you recall.
- Elasticsearch quantizes for you. Its recall at defaults is the recall of a compressed index with rescoring, not of a full-precision one. Distributed Chroma and Chroma Cloud use a different index (SPANN) with no settable parameters.
The other stores in 06.5 Part 8 (FAISS, sqlite-vec, DuckDB VSS, LanceDB, Redis, Pinecone, S3 Vectors) leave these values to you or hide them. Read their docs first.
10.3 The trade-off in one table#
Read each row as "if I turn this up (or on)". An up arrow means more, a down arrow means less. Directions are general; the size of each effect depends on your data, so measure.
| Change | Recall | Query latency | Index memory | Build time | Cost note |
|---|---|---|---|---|---|
ef_search or nprobe up |
up, then flat | up, roughly linear | no change | no change | Free to try. First thing to sweep. |
ef_construction up |
ceiling up | no change | no change | up | A rebuild. Worth it only if recall stalls at a high ef_search. |
M up |
ceiling up | up a little | up (about M × 8 to 10 bytes per vector) |
up | A rebuild. Links are small next to the vectors themselves. |
nlist up |
about the same at equal fraction probed | down per list, up for centroid scan | up a little | up | You need a larger nprobe in absolute terms. |
| Quantization on (int8) | down a little | down (cheaper scans) | down about 4 times | up a little | Usually the biggest cost saving per unit of effort. |
| Quantization on (binary or PQ) | down more | down | down 8 to 32 times and more | up (PQ trains codebooks) | Needs oversampling and rescoring, and the full vectors stored somewhere. |
| Oversampling up (with rescoring) | up, bounded | up a little | no change | no change | Cannot find what the compressed pass missed. |
10.4 See one knob work: recall against nprobe#
This sample is standalone (it is not part of the cumulative vector_indexes_numpy.py). It builds a tiny IVF index by hand, measures recall@10 against brute force while nprobe grows, then compares float32 with int8 storage. The data is deliberately noisy so topics overlap and the knob matters. Needs NumPy only, no services and no keys. The latency column is machine-dependent; the recall and scanned-fraction columns are fixed by the seed.
# ivf_knobs.py: brute-force recall vs nprobe on synthetic data. NumPy only, offline.
import time
import numpy as np
rng = np.random.default_rng(7)
N, D, K, NLIST = 20_000, 64, 10, 128
# Synthetic "documents": 100 topics with plenty of spread, so topics overlap a little.
topics = rng.normal(size=(100, D))
X = topics[rng.integers(0, 100, N)] + 2.0 * rng.normal(size=(N, D))
X /= np.linalg.norm(X, axis=1, keepdims=True)
Q = topics[rng.integers(0, 100, 200)] + 2.0 * rng.normal(size=(200, D))
Q /= np.linalg.norm(Q, axis=1, keepdims=True)
X, Q = X.astype(np.float32), Q.astype(np.float32) # real indexes store float32
# Ground truth: exact top-10 for every query (brute force, the baseline).
truth = np.argsort(-(Q @ X.T), axis=1)[:, :K]
# A tiny IVF: a few rounds of k-means, then one inverted list per cell.
C = X[rng.choice(N, NLIST, replace=False)].copy()
for _ in range(8):
assign = np.argmax(X @ C.T, axis=1)
for c in range(NLIST):
members = X[assign == c]
if len(members):
C[c] = members.mean(axis=0)
C /= np.linalg.norm(C, axis=1, keepdims=True)
assign = np.argmax(X @ C.T, axis=1)
lists = [np.where(assign == c)[0] for c in range(NLIST)]
def ivf_search(q, nprobe):
cells = np.argsort(-(C @ q))[:nprobe] # nprobe closest centroids
ids = np.concatenate([lists[c] for c in cells]) # only scan those lists
top = ids[np.argsort(-(X[ids] @ q))[:K]]
return top, len(ids)
print(f"N={N} d={D} nlist={NLIST} k={K}; queries={len(Q)}")
print("nprobe recall@10 scanned ms/query")
for nprobe in [1, 2, 4, 8, 16, 32, 128]:
hits, scanned = 0, 0
t0 = time.perf_counter()
for q, t in zip(Q, truth):
top, n = ivf_search(q, nprobe)
hits += len(set(top.tolist()) & set(t.tolist()))
scanned += n
ms = (time.perf_counter() - t0) / len(Q) * 1000
print(f"{nprobe:6d} {hits / (K * len(Q)):9.3f} {scanned / (N * len(Q)):6.1%} {ms:9.2f}")
# Quantization on or off: store int8 codes (4x smaller), score with them, then rescore.
scale = 127 / np.abs(X).max()
Xq = np.round(X * scale).astype(np.int8)
approx = (Q @ Xq.T.astype(np.float32)) # scores from the int8 codes
def recall(cands):
return np.mean([len(set(c) & set(t)) / K for c, t in zip(cands.tolist(), truth.tolist())])
raw = np.argsort(-approx, axis=1)[:, :K]
wide = np.argsort(-approx, axis=1)[:, :5 * K] # oversample 5x, then rescore
rescored = np.array([w[np.argsort(-(X[w] @ q))[:K]] for w, q in zip(wide, Q)])
print(f"\nfloat32 bytes: {X.nbytes:,} int8 bytes: {Xq.nbytes:,}")
print(f"int8 scores only: recall@10={recall(raw):.3f} int8 + 5x oversample + rescore: {recall(rescored):.3f}")N=20000 d=64 nlist=128 k=10; queries=200
nprobe recall@10 scanned ms/query
1 0.387 0.9% 0.03
2 0.482 1.6% 0.03
4 0.580 3.1% 0.06
8 0.695 6.3% 0.11
16 0.805 12.6% 0.22
32 0.906 24.9% 0.64
128 1.000 100.0% 2.45
float32 bytes: 5,120,000 int8 bytes: 1,280,000
int8 scores only: recall@10=0.980 int8 + 5x oversample + rescore: 1.000How to read it:
- At
nprobe=1the query scans under 1% of the vectors and finds 39% of the true neighbours. Atnprobe=32it scans a quarter of them and finds 91%. Atnprobe=128it scans everything and is exact, which is brute force again. Work grows about in step with the fraction scanned; recall rises fast, then slowly. Your job is to find the cheapest point that meets your target. - The curve is steep here because the data is noisy on purpose. Do not copy these numbers. Real embeddings give different curves, which is exactly why you sweep on your own data.
- int8 storage is 4 times smaller and still finds 98% of the true neighbours on its own. With 5 times oversampling and a rescore from the float vectors, this run reaches 100%. That is a typical shape: scalar quantization is close to free, and rescoring closes the rest.
10.5 When to leave the defaults alone#
Not tuning is a valid choice. Leave the defaults when:
- The corpus is small. Under roughly 10⁵ vectors, use exact search (1.2). There is nothing to tune.
- Measured recall already meets your target. If recall@10 on your eval queries is at or above the target and p99 latency is inside budget, stop. An extra 0.5% recall that you cannot measure in answer quality is not worth a rebuild.
- The bottleneck is elsewhere. If answers are wrong because of chunking, the embedding model or the reranker, no index knob will fix it. Check recall against exact search first: if the index matches exact search, the index is not your problem.
- You cannot measure yet. Without ground truth (see 5.2), any change is a guess. Build the eval set before you touch a knob.
Do not leave one thing alone: the query-time width (ef_search, nprobe). Its default is the most likely to be wrong for your corpus size, your k and your filters, and changing it needs no rebuild.
10.6 A measure-first checklist#
- Write down the target. A recall@k goal (for example recall@10 of at least 0.95) and a latency budget (for example p99 under 50 ms). Part 5 shows how to translate an SLA (5.4).
- Build ground truth with exact search on a few hundred real queries, including hard ones and your real filters (5.2). Save it.
- Run the store at its defaults and record recall@k, p50 and p99 latency, index size and build time. This is your baseline.
- Sweep the query knob only (
ef_search,nprobe, oversampling) over a spread of values and tabulate recall against latency (5.3). Pick the smallest value that meets the target. - If the ceiling is too low, raise
ef_constructionorM(ornlistand the training sample for IVF) and rebuild once. Repeat step 4. - If memory is the problem, turn quantization on, starting with int8, and re-sweep with oversampling and rescoring. Check the size with the formulas in 4.7 and 5.5.
- Record the settings and the date next to the eval set, and re-run the sweep when the corpus doubles, the embedding model changes, or you add filters.
Failure gallery#
| Symptom | Likely cause | Fix |
|---|---|---|
| Recall "fine" in dev, bad in prod | Tuning on easy queries / ef/nprobe at default |
Sweep on real query set; raise query knob |
| Recall drops over time, no deploy | IVF lists went stale; HNSW tombstones accumulated | Retrain/rebuild IVF; compact/rebuild HNSW |
Queries return fewer than k results |
Post-filtering after ANN; filter too selective | iterative_scan/filtered-graph; raise ef/nprobe; exact search for tiny candidate sets |
| Index "forgot" new documents | Writes went to a segment not yet merged; read-your-writes lag | Check segment/optimizer state; refresh interval |
| OOM at scale | fp32 vectors × N exceeds RAM | halfvec/SQ → PQ → binary+rescore; or disk-based index |
| Build takes forever | efConstruction/nlist too high for the data |
Lower build knobs; train IVF on a sample; parallel workers |
| Results differ run-to-run | ANN nondeterminism (graph walk ties, segment order) | Expected — test recall distributions, not exact IDs |
| Quantized scores look "better" than float | Comparing compressed scores to real scores | Always rescore with full vectors before ranking |
| Deletes still appear | Tombstone/segment lag; backup restore | Application-level deleted-ID filter; wait for compaction |
| IVF recall collapses after model change | Centroids trained on old embedding space | Re-embed + retrain + rebuild (full migration) |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "ANN gives you the same results as exact search, just faster." | It gives approximately the same results — recall@k is a measured fraction, typically 0.9–0.99 when tuned, never guaranteed. |
| "HNSW is always better than IVF." | HNSW wins on recall-per-query and needs no training, but IVF can be faster at very high nprobe fractions, is easier to partition/shard, and IVF-PQ compresses better at extreme scale. Match to your constraints. |
"Set ef/nprobe once and forget it." |
They're per-query runtime knobs; optimal values differ for interactive vs batch traffic, filtered vs unfiltered queries, and after corpus growth. Re-tune periodically. |
"A higher efConstruction fixes bad recall." |
It raises the recall ceiling; efSearch/ef/nprobe is what you actually dial at query time. If recall is bad at max ef, the build knobs are the problem. |
| "Quantization loses so much quality it's not worth it." | Scalar quantization typically costs <1–2% recall for 4× memory; binary+rescore can hold >0.9 on high-dim embeddings. Measure on your data before dismissing it. |
| "Rescoring makes quantization free." | It recovers recall only for candidates the cheap index already found — the ceiling is set by the compressed pass. Oversampling helps up to a point, then plateaus. |
| "Deleting a vector removes it immediately everywhere." | Deletes are tombstones/segment marks; they propagate on the engine's compaction schedule. Plan erasure SLAs around it. |
| "The default parameters are sane for my data." | Defaults are conservative (pgvector ef_search=40, ivfflat.probes=1, Qdrant ef=ef_construct). Sweep on your own queries — defaults are a starting point, not a tuning. |
| "Benchmarks tell me which index to use." | They tell you what's fast on their dataset/hardware. Your embedding model, dimensionality, filters and query mix decide it — benchmark your own. |
| "I need a dedicated vector database for anything serious." | pgvector inside Postgres you already run handles millions of vectors well; start there before adding a new system (06.5). |
Key takeaways#
- ANN indexes trade recall for speed. Every family exposes the same triangle: recall vs latency vs memory. Build knobs (
nlist,M,efConstruction, codebook size) set the ceiling; query knobs (nprobe,ef/efSearch,oversampling) trade speed for recall within it. - IVF partitions space with k-means cells; HNSW connects points in a layered graph you greedily walk. IVF needs training and goes stale; HNSW doesn't train but deletes are hard.
- Quantization compresses vectors — fp32→fp16→int8→binary→PQ — usually transparently inside the index. Scalar quantization is nearly free; binary and PQ need oversampling + rescoring with full vectors to recover recall.
- Tune on your data: build ground truth once (exact search on a query sample), sweep the query knob, pick the smallest value meeting your recall SLA. Don't trust defaults or vendor benchmarks.
- Memory dominates cost —
N × d × bytesplus index overhead. Quantization is the highest-leverage cost decision; the formulas in 4.7 and 5.5 size it. - Deletes are eventual — tombstones and segment merges, not eager removal. Plan GDPR/consistency SLAs around compaction, and keep an application-level deleted-ID filter for hard guarantees.
- Reindex is a batch job — rebuild the structure (tuning/maintenance), re-embed (model change), or compact segments (housekeeping). Never an online
ALTER; useCONCURRENTLYor shadow indexes. - Scale regimes are rules of thumb — brute force under ~10⁵, HNSW/IVF to ~10⁷–10⁸, quantized or disk-based beyond; the real question is whether the working set fits in RAM.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| ANN index | Data structure returning approximately-nearest vectors without scanning all of them |
| recall@k | Fraction of the true top-k an approximate search returns |
| IVF / inverted-file index | Partition vectors into k-means cells; search only the nprobe nearest cells |
nlist / nprobe |
IVF cell count (build) / cells probed per query (query-time recall dial) |
| HNSW | Hierarchical navigable small world — layered graph of nearest-neighbour links |
| NSW | Navigable small world — the single-layer ancestor of HNSW |
M |
HNSW max links per node per layer |
efConstruction / ef_construction / ef_construct |
HNSW candidate-list size at build time |
efSearch / ef / num_candidates |
HNSW candidate-list size at query time (same idea, different names) |
| Greedy walk / greedy search | Following the closest neighbour until no improvement — the HNSW query algorithm |
| Scalar quantization (SQ) | Storing each dimension as an int8/uint8 instead of float32 |
| Product quantization (PQ) | Splitting vectors into chunks, each replaced by a centroid code |
| Binary quantization | Keeping only the sign of each dimension; Hamming distance scoring |
| Hamming distance | Count of differing bits between two binary vectors |
| Oversampling | Retrieving factor × k candidates with a cheap index before rescoring |
| Rescoring / re-ranking | Re-scoring candidates with full-precision vectors to restore recall |
| IVF-PQ / IVFADC | IVF partition + PQ-compressed vectors (on residuals for ADC) |
| Tombstone | A deleted-but-still-present index entry, excluded from results |
| Segment | Immutable chunk of vectors+index in LSM-style vector stores, merged in background |
| Vamana / DiskANN | SSD-friendly graph algorithm for indexes larger than RAM |
| Anisotropic quantization | Penalising quantization error along the query direction (ScaNN) |
| Matryoshka embedding | An embedding trained so that prefixes of the vector are usable embeddings themselves, enabling dimension truncation |
| RaBitQ | A 1-bit-per-dimension quantizer with a theoretical error bound on its distance estimates and the inspiration for Elasticsearch's BBQ quantization |
| ann-benchmarks / VIBE | Public ANN benchmark suites (the former is no longer maintained, the latter is current) |
All terms are also collected in the glossary.
Exercises#
- IVF recall curve: run
vector_indexes_numpy.py(or just the Part-1 block) and plot recall@10 vsnprobefornlist ∈ {16, 64, 256}. At whatnprobe/nlistratio does each reach 0.95? Explain why finer partitions need more absolute probes even when the fraction of cells scanned stays small. - Graph walk cost: measure distance computations per query with the prototype's
_evalscounter (reset it before eachnsw_searchcall, read it after) acrossef ∈ {10, 40, 160}. How does the ratio of graph-walk evaluations toNchange if you doubleN? What does that imply for scaling? - Quantization ladder: extend
s4_2–s4_5to also tryfloat16(X.astype(np.float16)) and per-dimension percentile calibration for SQ instead of min/max. Which changes recall most? - Rescoring ceiling: for the binary index, compute recall@10 after rescoring all 4000 candidates (the theoretical ceiling of that candidate generator). How much of the gap between raw (0.150) and ceiling does 8× oversampling close?
- Production parameters: given pgvector defaults (
m=16,ef_construction=64,hnsw.ef_search=40) and hnswlib defaults (M=16,ef_construction=200,efunset), write theCREATE INDEXandSETstatements you'd use for a 2M-chunk corpus needing recall@10 ≥ 0.95 at p99 < 30 ms — and explain which knob you'd sweep first. - Memory sizing: for 50M chunks at
d=1024, compute total index memory for fp32 flat, int8, PQ-64, and binary+rescore (keep fp32 for rescoring on disk). Which fits in 64 GB RAM? Show your arithmetic. - Delete semantics: design the application-level guard that guarantees a deleted document never appears in results even while the engine's tombstones haven't compacted — where does the deleted-ID check go in the query path, and what's its cost?
Hints and what you should see
(Numbers below are read from the outputs this lesson already prints, or are plain arithmetic, or are marked "expected"; your own run of vector_indexes_numpy.py supplies the rest.)
- From the printed outputs: with
nlist=16,nprobe=1gives 0.763 andnprobe=4gives 1.000, so 0.95 is crossed at 2 to 4 probes (12.5% to 25% of cells). Withnlist=64the sweep gives 0.771 at 4 and 0.979 at 8, so 0.95 is crossed at 8 probes (12.5%) or slightly before. Withnlist=256, 13 probes (5.1%) gives 0.908 and 26 probes (10.2%) gives 0.992, so 0.95 sits at roughly 17 to 22 probes (7% to 9%). Your plot should show three S-curves that shift right in absolutenprobeasnlistgrows (about 3, 8, 20), while the fraction needed does not grow on this data (it shrinks a little). Why more probes: each true neighbour's cell is one of many small cells around the query, and the query's top-10 now spreads over several of them, so you have to visit more cells to collect them, even though each cell is cheaper. Work per query isnlist × dfor the centroid scan plus(nprobe/nlist) × N × dfor the lists, so a largernlistis not free: it moves cost from list scans to the centroid scan. - The lesson reports about 190 to 630 distance computations per query for
effrom 10 to 320 atN=2,000, against 2,000 for an exact scan. Expected shape (not run here): the count rises withefbut sub-linearly, and when you doubleNthe exact scan doubles while the walk grows much less than 2x, so the ratioevals/Nfalls. The implication is the reason graph indexes win at scale: query cost grows slowly with corpus size, at the price of build time, memory and the need to re-tuneefasNgrows. Report your own numbers for bothN; they depend on the seed. - Expected shape, not run here:
float16halves memory (2x, not 4x) and typically loses almost nothing, so expect recall within a fraction of a point of exact and a bit better than the 0.988 of int8. Percentile calibration (clip each dimension to, say, its 1st to 99th percentile before mapping to 0 to 255) spends the 256 levels on the bulk of the distribution instead of a few outliers; it helps most on data with heavy tails and matters little on this near-Gaussian synthetic data, so a small change is the honest expectation. If your numbers disagree, trust them and say what in the data explains it. - Rescoring all 4,000 candidates is exact search, so the ceiling is recall 1.000. From the 4.5 output, 8x oversampling (80 candidates) reaches 0.629 from a raw 0.150, so it closes
(0.629 - 0.150) / (1.000 - 0.150) = 56%of the gap. The lesson to take: the missing 44% is neighbours that binary codes ranked below position 80 of 4,000, and no rescoring of the 80 can bring them back. - A defensible answer (starting points, your sweep decides). pgvector:
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 128);thenSET hnsw.ef_search = 100;(inside the transaction,SET LOCAL). hnswlib:M=16, ef_construction=200, thenindex.set_ef(100). Sweepef_search(hnswlibef) first: it is query-time, free to change and needs no rebuild; measure recall@10 against exact search and p99 at each value, and pick the smallest that meets 0.95. Only if recall plateaus below 0.95 while p99 is still under budget do you raiseef_constructionormand rebuild, per the diagnostic in 3.3 (measure recall atef = ef_construction; below about 0.9 means the graph is the problem). Also state the memory check: 2M chunks times your dims times bytes must fit in RAM. - Arithmetic for 50M chunks at
d=1024(ran): fp32 flat is50M × 1024 × 4 = 204.8 GB; int8 is51.2 GB; PQ with 64 bytes per vector is3.2 GBof codes (about 3.6 GB with 8-byte ids; the codebook is64 × 256 × 16 × 4bytes, about 1 MB, negligible); binary is 128 bytes per vector,6.4 GB, plus the fp32 originals for rescoring,204.8 GBon disk or in a document store. In 64 GB of RAM: fp32 does not fit; int8 at 51.2 GB fits only with little room (HNSW links at about 130 B per vector, from the 4.7 table, add about 6.5 GB, and you still need payload and OS cache); PQ-64 fits easily but needs rescoring vectors somewhere; binary + rescore fits easily in RAM (6.4 GB) with the originals on fast disk. State which of these you would pick and the recall you would have to measure first. - Put the check at the end of the query path, before reranking, caching and context assembly: over-fetch (ask for
kplus slack, as with post-filtering), drop every id found in an authoritative deleted-set (a Redis set, a database table, or adeletedflag on the document store), and return the firstksurvivors. Deleting must write that set synchronously, before the delete call returns, even if the vector engine compacts later. The cost is one set lookup per candidate (microseconds) plus the over-fetch; if deletions are frequent, raise the slack, and keep cached results from outliving the delete (key caches by document version or purge on delete).
Check yourself#
- What does recall@k measure, and why is it the ceiling on downstream reranking quality?The fraction of the true top-k nearest neighbours an approximate search returns. Rerankers can only reorder retrieved candidates, so if recall misses the right document, nothing downstream can recover it.
- Name the two strategies ANN indexes use to avoid scanning all vectors, with one example each.Partition the space (IVF/k-means cells, Annoy trees) vs connect points in a graph (HNSW/NSW, DiskANN/Vamana).
- What are IVF's
nlistandnprobe, and which is a build-time vs query-time knob?nlist= number of k-means cells (build-time);nprobe= cells scanned per query (query-time recall/latency dial). - Why does IVF require a training step, and what goes wrong as data drifts?IVF's cells are learned centroids; they go stale as the corpus grows or shifts, silently degrading recall until retrained/rebuilt.
- What are HNSW's
M,efConstructionandefSearch, and which sets the recall ceiling vs the query-time dial?M= links per node;efConstruction= build-time candidate depth (sets recall ceiling);efSearch/ef= query-time candidate depth (the dial). - Why does HNSW not need training while IVF does?HNSW inserts vectors one at a time into a graph — no centroids to learn. IVF must cluster the data first.
- List the quantization ladder from fp32 to binary, with approximate compression ratios.fp32 (1×) → fp16/bf16 (2×) → int8/SQ (4×) → PQ (8–64×) → binary (32×).
- What is oversampling + rescoring, and why does it have a ceiling?Retrieve
factor × kcandidates with a cheap compressed index, rescore with full vectors, keep top-k. Ceiling: rescoring only reorders candidates the cheap pass already found. - Why is binary quantization usually paired with rescoring rather than used alone?Binary discards magnitude, so its raw ranking is weak — especially at low dimensions. Rescoring restores precision cheaply.
- What's the difference between a tombstone delete and a segment merge?Tombstone = mark deleted but keep in index until compaction; segment merge = background consolidation of immutable index chunks.
- When is brute-force/flat search the right answer rather than a fallback?Small corpora (~<10⁵), very selective filters, or when exactness/determinism is required.
- What does ann-benchmarks measure, and why is it no longer the go-to benchmark?Recall vs QPS across datasets/algorithms; it's unmaintained (as of Nov 2026) and superseded by VIBE for modern embedding datasets.
- Name two hardware factors that dominate ANN latency at scale.Whether the index fits in RAM (memory bandwidth) and disk I/O for cold/mmap'd data — plus SIMD CPU kernels.
- What are the three distinct things "reindex" can mean?Rebuild index structure (same vectors), re-embed+reindex (new vectors), compact/merge segments (housekeeping).
Appendix: the complete vector_indexes_numpy.py#
Every runnable NumPy snippet in this lesson, assembled in order — this is exactly what you get by copying each python block into one file. Save it as vector_indexes_numpy.py and run uv run python vector_indexes_numpy.py (NumPy only; takes a few seconds — the PQ k-means is the slow part).
# vector_indexes_numpy.py — PART 1 (this section): shared data + helpers + IVF demo
# Everything below is one cumulative file; later sections append to it.
import numpy as np
rng = np.random.default_rng(42)
N, D, K_TRUE = 4000, 64, 8
centers = rng.normal(size=(K_TRUE, D))
centers /= np.linalg.norm(centers, axis=1, keepdims=True)
X = centers[rng.integers(0, K_TRUE, N)] + 0.15 * rng.normal(size=(N, D))
X /= np.linalg.norm(X, axis=1, keepdims=True)
Qc = np.repeat(centers, 3, axis=0)
Q = Qc + 0.10 * rng.normal(size=(K_TRUE * 3, D))
Q /= np.linalg.norm(Q, axis=1, keepdims=True)
K = 10
def exact_topk(X, Q, k):
return np.argsort(-(Q @ X.T), axis=1)[:, :k]
def recall_at_k(approx, exact, k):
return np.mean([len(set(a) & set(e)) / k for a, e in zip(approx, exact)])
def kmeans(X, k, iters=25, seed=0):
"""Lloyd's algorithm on unit vectors: assign by argmax dot product."""
r = np.random.default_rng(seed)
C = X[r.choice(len(X), k, replace=False)].copy()
for _ in range(iters):
assign = np.argmax(X @ C.T, axis=1)
for j in range(k):
members = X[assign == j]
if len(members):
c = members.mean(axis=0)
C[j] = c / (np.linalg.norm(c) + 1e-12)
return C
def build_ivf(X, nlist, seed=0):
C = kmeans(X, nlist, seed=seed)
assign = np.argmax(X @ C.T, axis=1)
lists = [np.where(assign == j)[0] for j in range(nlist)]
return C, lists
def ivf_query(q, X, C, lists, nprobe, k):
order = np.argsort(-(q @ C.T))[:nprobe]
cand = np.concatenate([lists[j] for j in order])
# may return fewer than k ids if the probed lists are small — recall just scores lower
return cand[np.argsort(-(X[cand] @ q))[:k]]
exact = exact_topk(X, Q, K)
C, lists = build_ivf(X, nlist=64)
print("nlist=64, sweep nprobe:")
for nprobe in [1, 2, 4, 8, 16, 32, 64]:
approx = [ivf_query(q, X, C, lists, nprobe, K) for q in Q] # a list, not np.array: rows can differ in length
print(f" nprobe={nprobe:3d} recall@{K}={recall_at_k(approx, exact, K):.3f}")
# same data; vary nlist at build time (continues the same file)
for nlist, probes in [(16, [1, 4]), (64, [1, 16]), (256, [13, 26])]:
Cn, ln = build_ivf(X, nlist=nlist, seed=0)
cells = ", ".join(
f"nprobe={p} → recall {recall_at_k([ivf_query(q, X, Cn, ln, p, K) for q in Q], exact, K):.3f}"
for p in probes)
print(f" nlist={nlist:3d}: {cells}")
# vector_indexes_numpy.py — PART 2 (this section): toy NSW graph.
# Uses its own dataset (names suffixed _n) so the shared s2_4 data stays intact;
# recall_at_k is reused from Part 1.
import numpy as np
rng_n = np.random.default_rng(7)
N_n, D_n, K_TRUE_n = 2000, 32, 8
centers_n = rng_n.normal(size=(K_TRUE_n, D_n))
centers_n /= np.linalg.norm(centers_n, axis=1, keepdims=True)
X_n = centers_n[rng_n.integers(0, K_TRUE_n, N_n)] + 0.15 * rng_n.normal(size=(N_n, D_n))
X_n /= np.linalg.norm(X_n, axis=1, keepdims=True)
Qc_n = np.repeat(centers_n, 3, axis=0)
Q_n = Qc_n + 0.10 * rng_n.normal(size=(K_TRUE_n * 3, D_n))
Q_n /= np.linalg.norm(Q_n, axis=1, keepdims=True)
K_n = 10
_evals = [0] # distance computations; a list so dist() can mutate it without `global`
def dist(i, v): # cosine distance on unit vectors = 1 - dot
_evals[0] += 1
return 1.0 - float(X_n[i] @ v)
def build_nsw(X, M=8, ef_construction=40, seed=1):
n = len(X)
adj = [set() for _ in range(n)]
inserted = []
order = np.random.default_rng(seed).permutation(n)
def greedy(v, ef, allowed):
ep = inserted[np.random.default_rng(0).integers(len(inserted))]
cand = {ep: dist(ep, v)}
res = {ep: dist(ep, v)}
while cand:
c = min(cand, key=cand.get)
if len(res) > ef and cand[c] >= max(res.values()):
break
del cand[c]
for e in adj[c]:
if e not in res and e in allowed:
d = dist(e, v)
res[e] = d
cand[e] = d
if len(res) > ef:
worst = max(res, key=res.get)
del res[worst]
cand.pop(worst, None)
return sorted(res, key=res.get)[:ef]
for pos, i in enumerate(order):
if pos == 0:
inserted.append(i)
continue
allowed = set(inserted)
for j in greedy(X[i], ef_construction, allowed)[:M]:
adj[i].add(j)
adj[j].add(i)
if len(adj[j]) > 2 * M: # layer-0 degree cap ~2M
keep = sorted(adj[j], key=lambda t: dist(t, X[j]))[:2 * M]
adj[j] = set(keep)
inserted.append(i)
return adj
def nsw_search(adj, q, ef, k, entry=0):
cand = {entry: dist(entry, q)}
res = {entry: dist(entry, q)}
while cand:
c = min(cand, key=cand.get)
if len(res) > ef and cand[c] >= max(res.values()):
break
del cand[c]
for e in adj[c]:
if e not in res:
d = dist(e, q)
res[e] = d
cand[e] = d
if len(res) > ef:
worst = max(res, key=res.get)
del res[worst]
cand.pop(worst, None)
return sorted(res, key=res.get)[:k]
exact_n = [set(np.argsort(-(X_n @ q))[:K_n].tolist()) for q in Q_n]
adj = build_nsw(X_n, M=8, ef_construction=40)
print("avg degree:", round(np.mean([len(a) for a in adj]), 1))
for ef in [10, 20, 40, 80, 160, 320]:
approx = [nsw_search(adj, q, ef=ef, k=K_n) for q in Q_n]
print(f" ef={ef:4d} recall@{K_n}={recall_at_k(approx, exact_n, K_n):.3f}")
# vector_indexes_numpy.py — PART 3 (this section): scalar quantization.
# Reuses X, Q, exact, recall_at_k, K, D from Part 1.
import numpy as np
def quantize_scalar(X):
"""Per-dimension min/max -> uint8 codes."""
lo = X.min(axis=0)
hi = X.max(axis=0)
span = np.where(hi > lo, hi - lo, 1.0)
q = np.clip(np.round((X - lo) / span * 255), 0, 255).astype(np.uint8)
return q, lo, span
def dequant_scalar(q, lo, span):
return q.astype(np.float32) / 255.0 * span + lo
def oversample_rescore(Q, candidate_lists, k):
"""Rescore every candidate with full-precision vectors; keep top-k.
Shared helper for the rest of Part 4 — used by the PQ demo (4.4) and the
oversampling sweep (4.5); the idea is explained properly in 4.5."""
out = []
for qi, cands in zip(Q, candidate_lists):
scores = X[cands] @ qi
out.append(np.sort(cands[np.argsort(-scores)[:k]]))
return out
q8, lo, span = quantize_scalar(X)
Xq = dequant_scalar(q8, lo, span)
approx = [set(np.argsort(-(Xq @ q))[:K].tolist()) for q in Q]
print(f"bytes/vector: {D*4} -> {D} recall@{K}: {recall_at_k(approx, exact, K):.3f}")
# vector_indexes_numpy.py — PART 3 (continued): binary quantization + Hamming.
# Reuses X, Q, exact, recall_at_k, K, D from Part 1.
import numpy as np
def quantize_binary(X):
return (X > 0).astype(np.uint8) # 1 bit per dim; real systems bit-pack (np.packbits)
def hamming_topk(Qb, Db, k):
out = []
for q in Qb:
agree = (Db == q).sum(axis=1) # matching bits = similarity
out.append(np.argsort(-agree)[:k])
return out
Xb, Qb = quantize_binary(X), quantize_binary(Q)
approx_bin = hamming_topk(Qb, Xb, K)
# the printed size assumes bit-packing; this array keeps one byte per dim for clarity
print(f"bytes/vector: {D*4} -> {D//8} (packed) recall@{K}: {recall_at_k(approx_bin, exact, K):.3f}")
# vector_indexes_numpy.py — PART 3 (continued): product quantization.
# Reuses the shared data/helpers; oversample_rescore was defined in 4.2.
import numpy as np
def make_pq(X, M, nbits, iters=20, seed=0):
"""Split d into M chunks; k-means 2**nbits centroids per chunk (Euclidean)."""
n, d = X.shape
assert d % M == 0, "d must be divisible by M" # same constraint as FAISS PQ
m = d // M
r = np.random.default_rng(seed)
centroids = np.zeros((M, 2**nbits, m), dtype=np.float32)
codes = np.zeros((n, M), dtype=np.uint8)
for j in range(M):
sub = X[:, j*m:(j+1)*m]
C = sub[r.choice(n, 2**nbits, replace=False)].copy()
for _ in range(iters):
# Euclidean k-means: assign each chunk to its nearest centroid, then move
# centroids to the member mean. PQ chunks are NOT unit-normalised, so the
# argmax-dot-product trick from 2.4's kmeans does not apply here.
d2 = ((sub[:, None, :] - C[None, :, :]) ** 2).sum(axis=2)
a = np.argmin(d2, axis=1)
for c in range(2**nbits):
mem = sub[a == c]
if len(mem):
C[c] = mem.mean(axis=0)
d2 = ((sub[:, None, :] - C[None, :, :]) ** 2).sum(axis=2)
codes[:, j] = np.argmin(d2, axis=1)
centroids[j] = C
return centroids, codes
def pq_topk(Q, Db_codes, centroids, k):
"""Asymmetric distance: query stays full-precision, stored vectors are codes."""
n = len(Db_codes)
M, _, m = centroids.shape # (M chunks, 2**nbits centroids, m dims per chunk)
out = []
for q in Q:
scores = np.zeros(n, dtype=np.float32)
for j in range(M):
d_cent = ((centroids[j] - q[j*m:(j+1)*m]) ** 2).sum(axis=1)
scores += d_cent[Db_codes[:, j]]
out.append(np.argsort(scores)[:k])
return out
for M in [8, 16]:
centroids, codes = make_pq(X, M=M, nbits=8)
wide = pq_topk(Q, codes, centroids, K * 8)
topk = [set(a[:K]) for a in wide]
resc = oversample_rescore(Q, [w[:80] for w in wide], K)
print(f"M={M}: bytes/vector={M} ({D*4//M}x) "
f"raw recall@{K}={recall_at_k(topk, exact, K):.3f} "
f"rescore-80 recall@{K}={recall_at_k(resc, exact, K):.3f}")
# vector_indexes_numpy.py — PART 3 (continued): oversampling sweep on binary codes.
# quantize_binary (4.3) and oversample_rescore (4.2) are already defined above.
import numpy as np
Xb, Qb = quantize_binary(X), quantize_binary(Q)
print("binary index, vary oversampling factor (k=10):")
for f in [1.0, 2.0, 4.0, 8.0]:
wide = []
for qi, qb in zip(Q, Qb):
agree = (Xb == qb).sum(axis=1)
wide.append(np.argsort(-agree)[: int(np.ceil(K * f))])
rescored = oversample_rescore(Q, wide, K)
print(f" factor={f:3.1f}x candidates={int(np.ceil(K*f)):3d} recall@{K}={recall_at_k(rescored, exact, K):.3f}")
# vector_indexes_numpy.py — PART 4 (this section): build ground truth.
# Reuses X, centers, K_TRUE, D, K from Part 1. The demo Q has only 24 queries —
# too few for stable recall estimates — so we synthesise ~200 eval queries here
# (a real eval set is ~200-1000 queries; see the guidelines below).
import numpy as np
eval_rng = np.random.default_rng(123) # fresh rng: eval queries stay independent of Q
eval_queries = centers[eval_rng.integers(0, K_TRUE, 200)] \
+ 0.12 * eval_rng.normal(size=(200, D))
eval_queries /= np.linalg.norm(eval_queries, axis=1, keepdims=True)
eval_exact = np.argsort(-(eval_queries @ X.T), axis=1)[:, :K] # (200, k) true neighbours
np.save("ground_truth.npy", eval_exact)
print(f"ground truth saved: {eval_exact.shape[0]} queries x top-{K}")
# vector_indexes_numpy.py — PART 4 (continued): the sweep harness.
# Reuses ivf_query/C/lists/X/Q/K/exact_topk/recall_at_k from earlier parts.
import numpy as np
import time
def sweep(search_fn, queries, exact, k, knob_values):
"""search_fn(q, knob) -> iterable of top-k ids. Returns recall + latency table."""
rows = []
for knob in knob_values:
t0 = time.perf_counter()
approx = [set(search_fn(q, knob)[:k]) for q in queries]
elapsed = (time.perf_counter() - t0) / len(queries)
rec = recall_at_k(approx, [set(e.tolist()) for e in exact], k)
rows.append((knob, rec, elapsed * 1000)) # ms per query
return rows
# IVF: search_fn = lambda q, nprobe: ivf_query(q, X, C, lists, nprobe, K)
# NSW: search_fn = lambda q, ef: nsw_search(adj, q, ef=ef, k=K)
# FAISS: search_fn = lambda q, ef: index.search(q[None,:].astype('f32'), K)[1][0].tolist()
# (set index.hnsw.efSearch = ef inside the lambda)
for knob, rec, ms in sweep(
lambda q, nprobe: ivf_query(q, X, C, lists, nprobe, K),
Q, exact_topk(X, Q, K), K, [1, 2, 4, 8, 16]):
print(f"nprobe={knob:3d} recall@{K}={rec:.3f} ~{ms:.3f} ms/query")Further resources#
- HNSW paper: Malkov & Yashunin, "Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs" (IEEE TPAMI 2020; arXiv:1603.09320)
- PQ paper: Jégou, Douze & Schmid, "Product Quantization for Nearest Neighbor Search" (IEEE TPAMI 2011)
- DiskANN paper: Subramanya et al., "DiskANN: Fast Accurate Billion-point Nearest Neighbor Search on a Single Node" (NeurIPS 2019)
- ScaNN: Guo et al., "Accelerating Large-Scale Inference with Anisotropic Vector Quantization" (ICML 2020) + github.com/google-research/scann
- FAISS: github.com/facebookresearch/faiss — wiki "Faiss indexes", "Guidelines to choose an index", "How to make Faiss run faster"; faiss.ai docs
- hnswlib: github.com/nmslib/hnswlib — ALGO_PARAMS.md, TESTING_RECALL.md, README
- pgvector: github.com/pgvector/pgvector README (index options, iterative scans, quantization)
- Qdrant: qdrant.tech/documentation — "Indexing", "Quantization" pages
- Elasticsearch: elastic.co/docs — dense_vector mapping, kNN search, quantization/rescoring
- Annoy: github.com/spotify/annoy README
- USearch: github.com/unum-cloud/usearch
- DiskANN: github.com/microsoft/DiskANN (+ diskannpy on PyPI)
- Benchmarks: github.com/erikbern/ann-benchmarks (unmaintained), github.com/vector-index-bench/vibe
- Module links: 06.3 similarity · 06.5 vector databases · 06.6 filtering · 06.9 reranking · 06.10 evaluation
← 06.3 — Similarity Metrics and Nearest-Neighbour Search | Module 06 overview | 06.5 — Vector Databases: Choosing and Using One →