Lab: HNSW Recall Versus Latency
Build FAISS HNSW indexes over 10,000 vectors, measure recall@10 against the exact baseline and latency per query, sweep the search and build settings, and pick the cheapest setting that meets a recall target.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: create the data and the exact baseline
- Step 2: build one HNSW index
- Step 3: measure one setting against the baseline
- Step 4: sweep the search breadth
- Step 5: vary M and choose a setting
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of Vector Search Foundations
- Nearest-Neighbor Search Explained Concept · 15 min
- Brute-Force kNN as a Baseline Worked example · 20 min
- Approximate Indexes and Their Knobs Concept · 15 min
- Lab: HNSW Recall Versus Latency Lab · 25 min
- Filters and Hybrid Search with Rank Fusion Lab · 25 min
- Check: Pick an Index for a Workload Knowledge check · 6 questions
What you will learn
- Configure an approximate index (for example HNSW) and measure its recall against latency.
Prerequisites: Embeddings
01. Goal and setup
By the end of this lab you will have a small benchmark that builds HNSW indexes with different settings, measures each against the exact baseline from lesson 2, and prints recall@10 next to milliseconds per query. You will use it to choose a setting from evidence rather than from defaults, and you can point it at your own embeddings afterwards.
You need: Python 3.12 or later, NumPy 2 and faiss-cpu (tested with NumPy 2.5.5 and faiss-cpu 1.16.0). The faiss-cpu package on PyPI is a community-built wheel for Linux, macOS and Windows; the FAISS project itself supports installation through conda, which is the route to take if the wheel does not install on your platform. The lab runs on a laptop in a few minutes, with no GPU.
mkdir hnsw-lab && cd hnsw-lab
python3 -m venv .venv # Windows: py -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install numpy faiss-cpu
python -c "import faiss, numpy; print(faiss.__version__, numpy.__version__)"1.16.0 2.5.5hnsw-lab/
├── vectors.py make_dataset() from lesson 2
├── knn.py exact_knn() from lesson 2
├── prepare.py step 1: data and exact baseline, saved as .npy
├── bench.py step 2: build, measure and size helpers
├── build_one.py step 2
├── measure_one.py step 3
├── sweep_ef.py step 4
└── sweep_m.py step 502. Step 1: create the data and the exact baseline
Copy vectors.py and knn.py from lesson 2 into the folder unchanged. The script below creates 10,000 documents and 200 held-out queries, computes the exact top 10 for each query once, and saves everything, so the later steps compare every index against the same answers.
"""Create the corpus, the queries and the exact top-10 baseline, once."""
import time
import numpy as np
from knn import exact_knn
from vectors import make_dataset
docs, queries = make_dataset(n_docs=10_000, n_queries=200)
start = time.perf_counter()
gt_ids, _ = exact_knn(docs, queries, k=10)
elapsed = time.perf_counter() - start
np.save("docs.npy", docs)
np.save("queries.npy", queries)
np.save("gt_ids.npy", gt_ids)
print(f"docs {docs.shape}, queries {queries.shape}, ground truth {gt_ids.shape}")
print(f"exact search: {elapsed * 1000 / len(queries):.3f} ms per query (batched)")python prepare.pydocs (10000, 384), queries (200, 384), ground truth (200, 10)
exact search: 1.023 ms per query (batched)03. Step 2: build one HNSW index
bench.py holds everything the later steps share. Three decisions in it shape every number you will see:
- One thread. FAISS uses all cores by default, spreading a batch of queries across them. Pinning it to one thread makes the time per query comparable between settings and closer to what one request sees in a server that handles many requests at once.
- Inner product. The vectors are unit length, so
METRIC_INNER_PRODUCTranks by cosine, matching the baseline. The FAISS default metric is L2, which would rank the same here but report distances instead of similarities. - Best of three. Each measurement repeats the search and keeps the fastest run, which filters out pauses caused by other programs.
"""Build FAISS indexes and measure them against the exact baseline."""
import time
import faiss
import numpy as np
faiss.omp_set_num_threads(1) # one thread: latency per query, comparable runs
docs = np.load("docs.npy")
queries = np.load("queries.npy")
gt_ids = np.load("gt_ids.npy")
K = 10
def build_hnsw(m: int, ef_construction: int = 100) -> tuple[faiss.Index, float]:
"""An HNSW index over docs, scored by inner product; returns (index, seconds)."""
index = faiss.IndexHNSWFlat(docs.shape[1], m, faiss.METRIC_INNER_PRODUCT)
index.hnsw.efConstruction = ef_construction
start = time.perf_counter()
index.add(docs)
return index, time.perf_counter() - start
def recall_at_k(found: np.ndarray, truth: np.ndarray) -> float:
"""Share of the exact top k that the index also returned, over all queries."""
hits = sum(len(set(f) & set(t)) for f, t in zip(found, truth))
return hits / truth.size
def measure(index: faiss.Index, ef_search: int | None = None) -> tuple[float, float]:
"""Recall@K against the baseline, and the best of 3 runs in ms per query."""
if ef_search is not None:
index.hnsw.efSearch = ef_search
best = float("inf")
for _ in range(3):
start = time.perf_counter()
_, found = index.search(queries, K)
best = min(best, time.perf_counter() - start)
return recall_at_k(found, gt_ids[:, :K]), best * 1000 / len(queries)
def size_mib(index: faiss.Index) -> float:
"""Size of the serialised index: vectors plus graph links."""
return faiss.serialize_index(index).nbytes / 2**20from bench import build_hnsw, docs, size_mib
index, seconds = build_hnsw(m=16)
print(f"indexed {index.ntotal} vectors in {seconds:.2f} s")
raw_mib = docs.nbytes / 2**20
print(f"index size {size_mib(index):.1f} MiB (raw vectors {raw_mib:.1f} MiB)")
print(f"levels in the graph: {index.hnsw.max_level + 1}")python build_one.pyindexed 10000 vectors in 3.95 s
index size 16.0 MiB (raw vectors 14.6 MiB)
levels in the graph: 4The size matches the formula from lesson 3: 10,000 × (384 × 4 + 16 × 2 × 4) bytes is about 15.9 MiB, plus a little bookkeeping. Only a handful of nodes reach the top of the four levels, which is what lets a query cross the collection in a few hops. The build took seconds on one thread for 10,000 vectors; it grows faster than linearly with the collection, so building is the step to plan for at scale.
04. Step 3: measure one setting against the baseline
import faiss
from bench import build_hnsw, docs, measure
flat = faiss.IndexFlatIP(docs.shape[1]) # FAISS's own brute-force index
flat.add(docs)
recall, ms = measure(flat)
print(f"exact (flat): recall@10 {recall:.3f} {ms:.3f} ms/query")
hnsw, _ = build_hnsw(m=16)
recall, ms = measure(hnsw, ef_search=16)
print(f"HNSW ef=16: recall@10 {recall:.3f} {ms:.3f} ms/query")python measure_one.pyexact (flat): recall@10 1.000 1.201 ms/query
HNSW ef=16: recall@10 0.765 0.092 ms/queryThe first line is a check of the harness, not of HNSW. FAISS's flat index is another exact search, so it must agree with the NumPy baseline completely. If it does not, the bug is in the data, the metric or the baseline, and every later number would be wrong.
The second line is the FAISS default search breadth, efSearch = 16. In the run shown it is about thirteen times faster than the flat index, and it misses almost a quarter of the true neighbours. Whether that is acceptable depends on your target; for retrieval feeding an LLM it usually is not.
05. Step 4: sweep the search breadth
from bench import build_hnsw, measure
index, _ = build_hnsw(m=16)
print("efSearch recall@10 ms/query")
for ef in (16, 32, 64, 128, 256):
recall, ms = measure(index, ef_search=ef)
print(f"{ef:>8} {recall:>9.3f} {ms:>8.3f}")python sweep_ef.pyefSearch recall@10 ms/query
16 0.765 0.101
32 0.905 0.146
64 0.978 0.270
128 0.999 0.452
256 1.000 0.917One index, built once, gives five operating points. Recall rises steeply at first and then flattens, while latency keeps climbing at every step. Going from 64 to 256 buys the last 2% of recall for more than three times the latency, and at 256 the index costs most of what exact search costs at this size. This curve is the main result of the lab: a recall target picks a point on it, and the latency at that point is what you pay.
06. Step 5: vary M and choose a setting
M is fixed at build time, so each value means a new index. The script builds three, measures each at three search breadths, and then picks the fastest combination that reaches the recall target.
from bench import build_hnsw, measure, size_mib
TARGET = 0.97
results = []
print(" M build s MiB efSearch recall@10 ms/query")
for m in (8, 16, 32):
index, seconds = build_hnsw(m=m)
for ef in (32, 64, 128):
recall, ms = measure(index, ef_search=ef)
results.append((ms, m, ef, recall))
print(f"{m:>4} {seconds:>7.2f} {size_mib(index):>4.1f} {ef:>8} "
f"{recall:>9.3f} {ms:>8.3f}")
ms, m, ef, recall = min(r for r in results if r[3] >= TARGET)
print(f"chosen (recall@10 >= {TARGET}): M={m}, efSearch={ef}, "
f"recall {recall:.3f}, {ms:.3f} ms/query")python sweep_m.py M build s MiB efSearch recall@10 ms/query
8 2.55 15.4 32 0.739 0.094
8 2.55 15.4 64 0.886 0.167
8 2.55 15.4 128 0.963 0.294
16 4.23 16.0 32 0.905 0.148
16 4.23 16.0 64 0.978 0.284
16 4.23 16.0 128 0.999 0.466
32 4.81 17.2 32 0.950 0.221
32 4.81 17.2 64 0.995 0.407
32 4.81 17.2 128 1.000 0.688
chosen (recall@10 >= 0.97): M=16, efSearch=64, recall 0.978, 0.284 ms/queryRead the table along both axes. At a fixed search breadth, a larger M gives higher recall, because the denser graph offers more routes to the true neighbours, but each step of the search compares more links, so latency rises too. The index also grows and takes longer to build. What matters is the best latency for a given recall: here M = 8 needs breadth 128 to come near the target and is then no faster than M = 16 at 64, while M = 32 reaches the target at 64 but pays for its extra links on every query.
The min() call works because each tuple starts with the latency. On your machine the timings will differ and the winner may change between close candidates; that is the point of measuring on the hardware you will deploy to. Write the result down with the date, versions and data size, because a larger collection needs a larger search breadth for the same recall.
07. Check your understanding
08. Apply it: stretch tasks
Complete the practice project measurement, then go further:
- Your embeddings. Replace
docs.npyandqueries.npywith your own 10,000 embeddings and held-out queries (float32, unit length), rerunprepare.py-style ground truth, and runsweep_ef.py. Report recall@10 and latency for three settings and the one you would ship. - Scale. Rerun the lab with
n_docs=100_000. Expect the build to take over a minute on one thread; for building only, raise the thread count withfaiss.omp_set_num_threads()and set it back to 1 before measuring. Compare how far exact and HNSW latency each grew, and how much search breadth the same recall now needs. - Build breadth. At M = 16 and efSearch = 32, compare
ef_constructionvalues of 40, 100 and 200 for build time and recall. - Honest tuning. Generate 200 more queries, tune on the first set and confirm the chosen setting on the second, so the choice is not fitted to one query sample.
- Another library. Repeat step 4 with hnswlib, using the snippet below. It installs from source, so it needs a C++ compiler. Its
ipspace reports distance as 1 minus the dot product, so smaller is closer.
import hnswlib
import numpy as np
from bench import docs, gt_ids, queries, recall_at_k
index = hnswlib.Index(space="ip", dim=docs.shape[1]) # distance = 1 - dot product
index.init_index(max_elements=len(docs), M=16, ef_construction=100, random_seed=0)
index.set_num_threads(1)
index.add_items(docs, np.arange(len(docs)))
for ef in (16, 32, 64, 128):
index.set_ef(ef) # query-time breadth
labels, _ = index.knn_query(queries, k=10)
print(ef, round(recall_at_k(labels, gt_ids), 3))09. Review prompt
Without looking back:
- What three numbers does the benchmark report for each setting, and how is each one measured?
- Why does the lab check the flat index against the NumPy baseline before measuring HNSW?
- Sketch the shape of the recall-versus-latency curve as efSearch grows, and explain why the last few points of recall are the most expensive.
- Which result would you need to measure again after the collection grows tenfold, and why?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.