Skip to content
mlmentorship

Approximate nearest neighbors: HNSW, IVF, and product quantization

Separate candidate routing from vector compression, then measure neighbor recall, task quality, latency and complete index memory against exact search.

Published · 9 min read ·Role-specific ·Intermediate

Visual quick review

Trace how an IVF-PQ query first narrows the partitions to scan and then replaces full-vector distance work with one lookup per product-quantized subvector.

Learning objective

IVF selects two of four vector partitions

IVF selects two of four vector partitions A diamond query Q is closest to centroids C1 and C2. With nprobe equal to two, their solid partitions are scanned. The dashed C3 and C4 partitions are skipped, reducing how many stored vectors become candidates. 1 · IVF NARROWS WHERE TO SEARCH query Q C1 · SCAN C2 · SCAN C3 · skip C4 · skip nprobe = 2
PQ scores each selected candidate with lookup tables One selected candidate is stored as four codebook identifiers rather than its full vector. For query Q, four precomputed subvector-to-codeword distances, 0.04, 0.31, 0.08, and 0.22, are looked up and summed to an approximate distance of 0.65. 2 · PQ MAKES EACH SCORE CHEAPER candidate code 2 7 1 5 IDs query lookup 0.04 0.31 0.08 0.22 LUT approx. distance = 0.65
IVF selects lists; dashed lists are skipped. PQ sums the four selected lookup entries to 0.65 for each retained candidate. Candidate omission and distance distortion are separate failure paths.
Check: Can a better PQ score recover a vector in an IVF partition that was never scanned?
Full explanation 9 min read
Reading depth

Approximate nearest-neighbor indexes save routing work or vector bytes, creating different errors that need separate checks.

Summary

Which neighbors disappear because routing skipped them, and which change order because distances were approximated? First define the eligible catalog, metric, query distribution, and deterministic tie policy. Exact top- under that same contract is the neighbor-recall reference, not a relevance oracle.

The three families

HNSW (Hierarchical Navigable Small World)

Route through sparse upper graph layers, then search a broader bottom-layer frontier. Neighbor selection is heuristic, not an exact nearest-neighbor guarantee. Record degree parameter , construction breadth and query breadth efSearch.

IVF (Inverted File Index)

Assign stored vectors to coarse centroids, then scan selected inverted lists. nlist controls partitioning; nprobe controls lists visited. A nearby point can belong to a skipped list.

PQ (Product Quantization)

Split a vector into subvectors and store one -bit code per subvector. For squared Euclidean search, build query-to-codeword distance tables and sum selected entries. The original query need not be quantized. A 1024-dimensional float32 payload uses 4096 bytes; sixty-four eight-bit codes use 64 bytes.

OPQ (Optimized PQ)

Learn a rotation before PQ to redistribute quantization difficulty across subvectors. Measure improvement; it is not guaranteed for every dataset, query or trained codebook.

Production combinations

IVF-PQ combines routing and compression. Graph routing can also use compressed distances or supply candidates for exact reranking. An IVF-HNSW index may use a graph over coarse centroids; inspect its actual implementation roles.

Learning objective

Graph and cluster routing choose candidates; vector codes change their representation

Graph and cluster routing choose candidates; vector codes change their representationHNSW follows graph links; IVF scans selected clusters. Broader search reaches more candidates. PQ splits vectors and stores shared codebook choices instead of full coordinates. Distances become approximate, and codebook memory still counts. Better codes cannot expose an unscanned cluster. Evaluate recall, latency, and total memory separately; neither routing nor compression guarantees the exact neighbor.HNSW: visit linked candidates nearerthe queryA short graph-search example, not arecall guaranteeQABCQuery distances: 3, 2.236, 0.3606A scan route reaches members, notexcluded partitionsABCC contains the true neighbor but isnot scanned.PQ changes representation, not themissing scan route.PQ: split the vector into twocoordinate slices0.20.8code01.81.2code1Shared codebook: code 0 holds (0,1);code 1 holds (2,1)Reconstructed coordinates: 0, 1, 2, 1Two stored choices replace fourcoordinates; the shared codebook alsoconsumes memory.
Read it this way: HNSW follows graph links; IVF scans selected clusters. Broader search reaches more candidates. PQ splits vectors and stores shared codebook choices instead of full coordinates. Distances become approximate, and codebook memory still counts. Better codes cannot expose an unscanned cluster. Evaluate recall, latency, and total memory separately; neither routing nor compression guarantees the exact neighbor. Does better compression open the unscanned partition?
Reference drawing

Learning objective

Graph and cluster routing choose candidates; vector codes change their representation

Graph and cluster routing choose candidates; vector codes change their representationHNSW follows graph links; IVF scans selected clusters. Broader search reaches more candidates. PQ splits vectors and stores shared codebook choices instead of full coordinates. Distances become approximate, and codebook memory still counts. Better codes cannot expose an unscanned cluster. Evaluate recall, latency, and total memory separately; neither routing nor compression guarantees the exact neighbor.HNSW: visit linked candidates nearerthe queryA short graph-search example, not arecall guaranteeQABCQuery distances: 3, 2.236, 0.3606A scan route reaches members, notexcluded partitionsABCC contains the true neighbor but isnot scanned.PQ changes representation, not themissing scan route.PQ: split the vector into twocoordinate slices0.20.8code01.81.2code1Shared codebook: code 0 holds (0,1);code 1 holds (2,1)Reconstructed coordinates: 0, 1, 2, 1Two stored choices replace fourcoordinates; the shared codebook alsoconsumes memory.
Derivation
IVF selects two of four vector partitions A diamond query Q is closest to centroids C1 and C2. With nprobe equal to two, their solid partitions are scanned. The dashed C3 and C4 partitions are skipped, reducing how many stored vectors become candidates. 1 · IVF NARROWS WHERE TO SEARCH query Q C1 · SCAN C2 · SCAN C3 · skip C4 · skip nprobe = 2
PQ scores each selected candidate with lookup tables One selected candidate is stored as four codebook identifiers rather than its full vector. For query Q, four precomputed subvector-to-codeword distances, 0.04, 0.31, 0.08, and 0.22, are looked up and summed to an approximate distance of 0.65. 2 · PQ MAKES EACH SCORE CHEAPER candidate code 2 7 1 5 IDs query lookup 0.04 0.31 0.08 0.22 LUT approx. distance = 0.65
IVF selects lists; dashed lists are skipped. PQ sums the four selected lookup entries to 0.65 for each retained candidate. Candidate omission and distance distortion are separate failure paths.
Check: Can a better PQ score recover a vector in an IVF partition that was never scanned?
Read it this way: HNSW follows graph links; IVF scans selected clusters. Broader search reaches more candidates. PQ splits vectors and stores shared codebook choices instead of full coordinates. Distances become approximate, and codebook memory still counts. Better codes cannot expose an unscanned cluster. Evaluate recall, latency, and total memory separately; neither routing nor compression guarantees the exact neighbor. Does better compression open the unscanned partition?

The lookup sum is . Now compare returned IDs with exact neighbors:

SetIDs
Exact top-fiveA, B, C, D, E
ANN top-fiveA, C, D, F, G
Retained exact IDsA, C, D
Missing exact IDsB, E

Neighbor recall@5 is . Exact reranking cannot recover B or E from this fixed set.

Change the resource constraint

Increase search breadth

New task: raise neighbor recall above this floor.

Picture and change: increase efSearch or nprobe, holding queries, filters and catalog fixed.

Check: if broader routing adds B but not E, exact reranking can achieve here. It still cannot produce the missing E. Record candidate recall and tail latency, not only reranking accuracy.

Use when: omission, rather than retained-candidate ordering, dominates.

Reduce stored bytes

New task: one million raw vectors exceed the memory budget.

Picture and change: raw payload is 4.096 decimal GB; the stated PQ codes use 64 MB.

Check: eight-byte IDs add another 8 MB before codebooks, lists, graph links and allocator overhead. Keeping raw vectors for reranking retains their storage cost somewhere. The 64-fold payload reduction is not a whole-service memory or speed guarantee.

Use when: storage or vector transfer is binding; evaluate compression, encoder dimension or tiering with quality controls.

Reconstruct the error

Could neighbor recall decrease without changing useful-document recall?

Reasoned answer

Yes, if omitted neighbors are irrelevant or redundant. Alternatively one missing ID can remove the only useful item. Measure neighbor approximation and task relevance separately.

Recall vs latency vs memory

Measure a workload-specific frontier, not a universal pick-two rule. Include query concurrency, filters, vector distribution, build/update cost and resident plus peak memory. Graph links, IDs, codebooks, deletions and optional originals all contribute. Exact search has finite work and can be preferable for small or highly filtered candidate sets. For dot products, state whether a multiply-add counts as one operation or two FLOPs. Bandwidth may dominate arithmetic. ANN does not guarantee sublinear worst-case work.

Common pitfalls

Report , ground-truth metric, ties and filtered eligibility with recall. Normalize vectors consistently when cosine is implemented through inner product. Check versioned insertion, deletion, tombstone, retraining and filter behavior rather than inferring it from a family name. Strong static unfiltered recall does not qualify a frequently updated filtered service. Original algorithms: HNSW and product quantization.