00-START-HERE · 01-READING-ROUTES · 14_beyond_plain_text_tables_layout_documents · 16_compression_and_index_economics This chapter explains how to choose and defend an Approximate Nearest Neighbor (ANN) index for Retrieval-Augmented Generation (RAG) under recall, latency, memory, build, and update constraints.
TL;DR
- Exhaustive flat search reads every vector once per unbatched query. High ambient dimension can weaken exact-tree pruning, but it does not make every exact index fail on every dataset.
- HNSW uses sparse upper layers and a dense base graph. HNSW-Flat keeps full vectors; graph links add memory and do not shrink automatically when vectors are quantized.
- IVF routes queries to centroid cells. trades routing coverage for list work, while a large can move the bottleneck to coarse search.
- Classical LSH trades sublinear candidate work for superlinear posting space, plus projection and hashing work. Its radius guarantees do not translate into one universal recall number.
- Directional edges, a useful entry point and a wider search frontier can reduce graph traps. Neither a beam-width setting nor geometric layer occupancy alone proves a query-work bound.
- PQ compresses vectors; disk-resident graphs move bulky records to SSD. Disk capacity, useful read concurrency, IOPS and tail latency must all be budgeted.
- The recall/latency/memory triangle is a Pareto-design heuristic, not an impossibility theorem. Compare matched workloads, measured recall, throughput, rebuild policy and full memory scope.
The story
Imagine a fulfillment warehouse with millions of nearly identical boxes. A customer asks for the box most similar to a photo. Exhaustive flat search means a picker opens every box and compares it with the photo. That works in a small warehouse. In a huge warehouse, the picker spends most of the time walking past bytes of inventory, not thinking. A kd-tree is a rulebook that splits the warehouse by one label at each doorway. The rulebook hopes a single label can prove that an entire wing is irrelevant. In a high-dimensional noise example, distances can cluster tightly and a one-label bound can become too weak to exclude many wings. The picker may then visit much more of the warehouse; this is not an inevitable outcome for every dataset or every combined subtree bound. HNSW is a layered network of warehouse walkways. The sparse top floor has long express walkways. Each lower floor adds shorter local walkways. The picker uses greedy progress on upper floors; at the bottom, a best-first search can keep alternative routes open rather than accepting only one improving move. Its query width is a shortlist of promising candidates. A wider shortlist often improves recall at extra cost, but does not by itself fix how many nodes the picker will expand. IVF is a set of learned warehouse zones. Each centroid is the sign at the center of one zone, and each posting list is the inventory assigned to that sign. The picker first finds nearby signs, then searches only their zones. is the number of zone doors opened. One door is fast, but the best box may sit just across the painted boundary. Too many tiny zones create a new problem because reading every sign can cost more than searching the selected shelves. LSH is a collection of yes-or-no stamps placed on every box. One random stamp only weakly distinguishes a matching box from a common box. Concatenating many stamps makes one strict shelf key. Repeating that key across many independent catalogs restores the chance that a true match appears somewhere. Those catalogs consume memory, and short keys flood the picker with false candidates. A graph index is the warehouse walkway plan itself. Connecting each box only to its closest boxes creates dense cul-de-sacs. Directional edge selection reserves walkways that leave a neighborhood. Vamana uses a pruning slack named to decide which longer walkways survive. Annoy uses several fixed tree maps instead of recoverable walkways. A larger query-time search budget can revisit alternative branches; adding trees is another way to buy recall. DiskANN stores the bulky walkway map and full box records on the SSD. It keeps small PQ labels in Random Access Memory (RAM), so the warehouse can be much larger than memory. Now the cost is storage rounds. Every unnecessary hop becomes a random read. The final choice is a triangle drawn on the warehouse budget sheet. You may demand that the picker almost never misses, returns quickly, and uses little floor space. The triangle records a workload-dependent trade-off, not a proof that all three requirements can never be met. Fix the product constraints, compare feasible operating points, and price the remaining resources before naming an index.
Decoder table
| Technical term | Plain-English meaning | Why it matters |
|---|---|---|
| Approximate Nearest Neighbor (ANN) search | Search that may omit candidates or approximate their scores | It can miss true top- items; useful recall must be measured against a defined exact baseline |
| Exact top- search | Return the true top under the stated metric, snapshot, filters, precision and tie rule | Exhaustive scoring is one method; valid-bound exact indexes can prune |
| Inner product | Multiply matching coordinates and add the results | Exact inner-product search performs one multiply and one add per coordinate |
| Cosine similarity | Compare vector direction after normalization | The chapter uses it for semantic similarity and random-hyperplane hashing |
| Euclidean distance | Straight-line distance between vectors | kd-trees, Voronoi cells, graph pruning, and LSH guarantees use it |
| Dimension | Number of components in each vector | Vector bytes and distance work grow linearly in |
| Corpus size | Number of indexed vectors | Scan cost grows linearly in , while index rules often depend on or |
| Floating-point 32-bit (fp32) | Four-byte storage for each vector component | An fp32 vector of dimension 768 occupies bytes |
| Memory bandwidth | Bytes per second available to the bottleneck memory path | is a flat fp32 streaming floor when every query reads every vector independently |
| Arithmetic intensity | Floating-point work divided by transferred bytes | Flat fp32 dots have about for vector traffic; batching can change intensity |
| Memory-bound | Performance limited by data movement | A roofline hypothesis to verify; extra cores, batches and reuse can change the bottleneck |
| Floating-point operation (FLOP) | One arithmetic operation on a floating-point value | Dot products cost approximately FLOPs across vectors |
| Query per second (QPS) | One completed search request per second | It converts per-query bandwidth and storage reads into capacity |
| kd-tree | A coordinate-partitioning tree with region-distance bounds | High ambient dimension can weaken pruning, but the effect is distribution-dependent |
| Pruning radius | Best full-space distance found so far | A one-axis gap above is sufficient for sibling pruning; combined bounding-box tests can also prune |
| Distance concentration | A distribution’s distances cluster near a typical value as dimension grows | It can weaken exact-tree contrast; it does not prove every index must scan every point |
| Coefficient of variation () | Standard deviation divided by mean | Unconditional Gaussian pair distances have ; fixed-query spread differs |
| Curse of dimensionality | Here, distance concentration in high dimension | The chapter excludes other meanings such as density sample complexity and shell volume |
| Intrinsic dimension | An effective dimensional description of the data | Useful structure can aid ANN, but high recall alone does not prove a particular manifold model |
| Contrast ratio | Ratio such as divided by for real queries | It measures whether the representation leaves a neighbor worth finding |
| Sequential scan | Read vectors in contiguous order | It uses hardware bandwidth better than pointer-heavy exact trees |
| Single Instruction, Multiple Data (SIMD) | One instruction applied across several numeric lanes | Flat arrays exploit it while tree pointer chasing does not |
| Skip list | Sorted linked list with geometrically thinning upper levels | It provides the conceptual derivation for HNSW |
| Total order | An order giving a valid before/after stopping test | It enables ordered-list routing, not literally free links or universal graph-search guarantees |
| Promotion probability | Chance that an item appears one level higher | It controls skip-list occupancy and expected height |
| Hierarchical Navigable Small World (HNSW) | Layered proximity graphs searched from sparse top to dense bottom | It replaces a skip list’s total order with stored geometric links |
| Navigable Small World (NSW) | A single-level proximity graph with local and longer links | Entry choice and data affect the cited empirical or model-specific scaling |
| Proximity graph | Nodes are vectors and edges join selected nearby vectors | It supplies the local moves that replace sorted-list steps |
| Entry point | Node where a graph query starts | A poor entry can add hops or trap a greedy walk |
| Greedy descent | Move to the neighbor closest to the query when it improves distance | It is fast but can stop at a false local minimum |
| Local minimum | Node whose stored neighbors are all farther from the query | Pure greedy search halts there even when a better node exists elsewhere |
| Layer 0 | HNSW base layer containing every vector | Most query work and twice- neighbor capacity live here |
| HNSW neighbor limit above the base layer | It controls connectivity, memory, layer occupancy, and rebuild cost | |
| Base-layer HNSW neighbor limit, conventionally | It sets the dominant base-layer expansion cost | |
| Query-time HNSW beam width | Raising it trades latency for recall without rebuilding | |
| HNSW build-time search width | Raising it spends build work to improve the recall ceiling | |
| Beam search | Keep several promising unvisited graph candidates | It can retain a branch that pure greedy search abandons |
| Select-neighbors heuristic | Favor candidates not occluded by already selected neighbors | It encourages directional diversity without certifying connectivity or exact recall |
| Relative Neighborhood Graph (RNG) rule | A geometric occlusion principle for selecting useful neighbors | HNSW/Vamana use related candidate-pruning heuristics, not necessarily the full mathematical RNG |
| Coarse quantizer | Map a vector to its nearest learned centroid | It is the routing layer of IVF |
| Inverted file (IVF) | Centroid-to-posting-list index over vectors | It scans a small number of learned cells instead of the full corpus |
| -means | Iterative algorithm used to fit IVF centroids | It lets the data choose the partition |
| Lloyd’s algorithm | The -means procedure named in the chapter | It trains the coarse quantizer on a corpus sample |
| Centroid | Learned representative point for one partition | Queries pay stage-one distance comparisons against centroids |
| Voronoi cell | Region assigned to one nearest centroid | Queries near its boundary can have a true neighbor in the adjacent cell |
| Posting list | Vectors assigned to one centroid | IVF query work depends on the lengths of the probed lists |
| Number of IVF centroids and cells | More cells shorten lists but raise coarse-search cost | |
| Number of IVF cells opened per query | It is the reversible recall and latency knob for routing misses | |
| Routing loss | Miss because the true neighbor lies in an unprobed cell | Raising PQ fidelity cannot repair it |
| Posting-list imbalance | Some centroid cells hold far more vectors than others | It can create high tail latency at fixed |
| Centroid staleness | Old centroids no longer fit the current topic distribution | Lists swell and recall falls without an explicit error |
| Locality-Sensitive Hashing (LSH) | A hash family with near/far collision bounds | Random hyperplanes are monotone in angle; the general definition leaves intermediate distances unspecified |
| Avalanche property | Ordinary hash behavior that changes many output bits after a tiny input change | It deliberately destroys the locality retrieval needs |
| Sensitive family | An , , , guarantee for near and far pairs | It states collision limits only at the two design radii |
| Random hyperplane hash | Sign of a dot product with a random normal vector | For cosine, collision probability is |
| Collision probability | Chance two vectors receive the same hash outcome | Amplification reshapes it into a useful retrieval probability |
| Amplification | Concatenate bits, then union candidates across tables | The first step improves selectivity and the second restores recall |
| Code length | Independent hash bits in one table key | A longer key reduces spurious candidates sharply |
| Table count | Number of independent LSH tables | More tables raise recall, candidate count, and memory |
| Exponent | in the classical construction | Candidate/probe scaling suppresses projection, dimension, logarithmic factors and success parameters |
| Candidate list | Union of items returned by probed buckets or graph expansion | Its size drives reranking latency |
| SimHash | Short binary fingerprint from random projections | The chapter keeps it for ingest-time near-duplicate removal |
| Hamming distance | Number of differing bits between binary fingerprints | A distance at most 3 marks near duplicates in the cited 64-bit setup |
| MinHash | Hash designed for set overlap | It replaces SimHash when Jaccard similarity over tokens matters |
| Jaccard similarity | Intersection divided by union for token sets | It fits boilerplate overlap better than embedding cosine |
| Multi-probe LSH | Probe extra nearby buckets in fewer tables | It trades query probes for lower table memory |
| -nearest-neighbor graph | Connect each point to its closest points | It can fragment because all edges stay inside a dense cluster |
| Directional edge selection | Preserve edges that leave in distinct directions | It protects reachability with limited degree |
| Cone width | Angular range sharing one directional representative | Narrow cones keep more edges and directions |
| Prefix minimum | Item closer than all earlier items in a random order | One cone keeps about a harmonic number of such edges |
| Harmonic number | It counts expected random prefix minima per cone, not an automatic query-hop theorem | |
| Vamana | A graph builder using candidate search and multiplicative pruning | Ideal shrinkage needs complete target coverage; practical degree caps and candidates change the guarantee |
| Pruning slack | Multiplier in | A larger value makes that fixed deletion test harder; final capped graph topology need not be nested |
| Spread | for the ideal covered-dataset-target proof | With , the bound is at most under the stated assumptions |
| DiskANN | Disk-resident graph with compact codes in memory | It moves full vectors and edges from RAM to SSD |
| Out-degree | Maximum stored outgoing edges per DiskANN node | It controls graph memory and whether one node fits one sector |
| Sector | A storage/read-layout unit, here a -byte page | A record spill doubles page reads only under the aligned full-record-read layout assumed in the toy |
| Non-Volatile Memory Express (NVMe) | SSD interface used for random reads | Its read latency and Input/Output Operations Per Second (IOPS) bound DiskANN |
| Annoy | A forest of random-projection trees with an alternative-branch search budget | Both tree count and query-time exploration can affect recall; a single wrong descent need not be final |
| Product Quantization (PQ) | Replace a full vector with compact subvector codes | It changes memory by an order of magnitude but adds distortion |
| Asymmetric distance computation | Compare a query with reconstructed PQ codes | It can reorder candidates within correctly routed cells |
| Distortion loss | Recall lost because compressed-code distance changes ranking | A larger or exact refine stage can address it |
| Exact refine stage | Rescore admitted candidates with full vectors | It can repair their ordering, not recover omitted candidates or certify global exactness |
| Fraction of the true top- returned by the index | Index latency has meaning only at a stated recall operating point | |
| Resident bytes | Memory that must remain available to answer queries | It usually decides whether HNSW or IVF-PQ is feasible |
| Tail latency | Slow-end latency such as or | List imbalance and storage rounds can dominate it |
| Query-time knob | Parameter changed without rebuilding | and move along recall-latency curves live |
| Build-time knob | Parameter baked into the index | , , , and training choices require a rebuild to change |
| , , , , , , , , , , , , , , , , , and | Corpus and vector sizes, bandwidth, result count, query and corpus vectors, pruning radius and split, standard normal variable, promotion chance and layer, uniform draw and layer multiplier, graph degrees, query beam, and build beam | These symbols size exact scan and derive the HNSW hierarchy, query work, memory, and build work |
| , , , , , , , , , , , , , , , , , out-degree, and PQ | Centroids and cells, coarse assignment, IVF counts and cost, LSH radii, collision probabilities, angle, code length, table count, exponent, graph slack and spread, harmonic number, disk degree, and subvector count | These symbols define IVF routing, hash amplification, graph pruning, storage rounds, and quantization |
Core mechanics
Mathematical conventions
Unless marked binary, storage is decimal: and ; a -byte page is . An exact result is relative to the chosen metric, snapshot, filters, tie convention and numerical precision. Flat exhaustive search is one exact algorithm, not the definition of all exact search. For one unbatched full-vector scan, is an ideal streaming-time floor, not measured end-to-end latency; batching may share the vector read. Rounded performance estimates are not tail-latency guarantees. HNSW controls a retained search width, not a hard count of expansions or distance evaluations. Link budgets below include allocated slots under the stated layer convention, not complete process memory. IVF averages assume balanced or representative probed lists. LSH probabilities use unrounded angular collisions and independent random bits/tables; candidate expectations are not fixed counts. Round required machines, bits and tables upward. Empirical study findings remain reported inputs, not consequences proved by the arithmetic.
15.1 Why exact search dies: the curse of dimensionality
- What flat exact scan does: Score every eligible vector and return the true top under the specified metric and tie convention. Exact tree algorithms may instead prune with valid bounds.
- Why it exists: No learned partition or approximate traversal is needed. The vector store and filters still need correct updates; numerical precision and top- selection remain implementation choices.
- Work: A dense fp32 dot-product scan reads vector bytes and uses approximately FLOPs, counting a multiply and add separately. More exactly, summing products takes scalar operations per vector before scoring/selection overhead.
- Arithmetic intensity: Approximately for vector traffic alone. Under low arithmetic intensity and unbatched streaming, bandwidth is often the bottleneck.
- Ideal roofline: With sustained shared bandwidth and arithmetic rate , . Selection, query reads, normalization, filtering and scheduling add work.
- Throughput scope: is a vector-bandwidth ceiling only when each query requires its own full scan; batching and reuse can amortize the vector read. For , the vector payload is exactly . The ideal unbatched streaming estimate is , with ceiling . Calling this a floor assumes the algorithm really reads all those bytes through that bandwidth bottleneck; exactness alone does not require every exact algorithm to do so.
- What a kd-tree does: Partition coordinates, descend to candidate leaves, and use the current best full-space radius to test unexplored regions.
- Simple sibling test: At a split , is sufficient to exclude the opposite half-space. A subtree’s full bounding-box lower bound can combine several coordinate gaps and prune even when this one-axis test fails.
- Failure mode: For some high-dimensional distributions, these bounds exclude little, so traversal approaches a scan with extra pointer and bookkeeping costs.
- Limit: Expected near-logarithmic behavior requires favorable geometry and balance; it is not a universal exact-query guarantee. For two independent vectors , let . Then , so and . The delta method gives , and for large . Exact moments are
The exact CVs are approximately , and at ; the first-order value at is not exact. At , the unconditional pairwise mean is with standard deviation . Distances to many points share the same query, so they are not independent unconditionally. Conditional on a fixed query , , with mean and variance . At , the local delta-method distance spread is , not . For , the conditional distance quantiles with one-tail probability are approximately and , ratio . These are quantile markers, not expected extrema or hard bounds. They replace the inconsistent independent-pair extreme heuristic. The conditional CDF is evaluated through its Poisson mixture of central chi-square CDFs. A one-coordinate distance to a median split at zero has for ; a difference between two independent point coordinates instead has expected absolute value . Actual tree split gaps depend on the construction.
- Geometric warning, not a no-pruning proof: Coordinate-plane gaps of order can be much smaller than nearest-neighbor radii of order in this noise model. This motivates weak pruning; it does not show every sibling survives every bounding-box test.
- Depth: A roughly balanced binary tree with singleton leaves has a depth scale . Leaf size and imbalance alter it.
- Coordinates: One path has at most split tests, potentially repeated on the same coordinate; it need not constrain distinct axes. Thus is a lower bound on untouched axes only in this limited path-count comparison, not a characterization of the entire search.
- Exponential grid: A complete binary decision tree that branches once on every one of coordinates has leaves. Exact search does not require building that grid. Ball trees, -trees and related schemes can suffer similarly, but behavior depends on the dataset, intrinsic structure, metric and bounds. The cited experiment found sequential scan faster than the tested partitioning indexes above roughly ten dimensions; it is not a modern hardware-independent cutoff. The cited distance-concentration result needs its distributional conditions; convergence of a farthest/nearest ratio does not apply to every learned corpus or every joint scaling of and . Approximation offers query-dependent graph, cell or hash candidates rather than an exact pruning certificate.
- Geometry: Random high-dimensional vectors can have weak distance contrast; exact neighbor ranks still exist, and query-dependent algorithms may exploit structure. Concentration alone does not prove all ANN methods useless.
- Learned representations: Semantic training may produce navigable clusters or lower effective dimension, but this is a hypothesis to inspect, not guaranteed by the embedding width.
- Evidence: Measured recall while scoring of a corpus demonstrates a useful operating point for that graph, dataset and queries. It does not logically refute every independent-noise model or prove a particular manifold dimension.
- Terminology: This section uses the curse of dimensionality for distance concentration and weak pruning, not as a derivation of all sample-complexity or shell-volume phenomena. Worked CPU scan. Use fp32 vectors of width , a search allowance within a pipeline target, and QPS. The vector-read floor is ; dot-product work is FLOPs. A hypothetical core at fp32 FLOPs/cycle offers , or compute time. The ratio is , supporting the bandwidth bottleneck under these assumptions, not an independent timing measurement. The floors are and times the search allowance. Aggregate unbatched bandwidth at QPS needs socket-equivalents, not ; rounding QPS before inversion caused the discrepancy. Independent parallel queries do not by themselves reduce one query’s latency; query sharding adds its own work. Worked GPU batch. On the stated A100 GB example, published gives for one vector read. Batch uses FLOPs; at its compute floor is . An ideal fully shared matrix read therefore has roofline service time at least and throughput ceiling about QPS. This is not measured service or latency. With regular arrivals at QPS and full batches only, the first query waits to fill a batch and mean fill wait is ; dynamic batching must budget that separately. At vectors, payload is . Reading it within requires , at least such peak-bandwidth accelerators before capacity, transfer, selection and interconnect costs—not an implementable latency guarantee. Illustrative graph work. With , assume base-node expansions and no repeated candidate distances: evaluations, of the corpus. The choice does not guarantee this expansion count. Vector reads would be , times less than flat, with streaming time at before graph reads and scattered-access effects. Base-layer link slots use , or of vector bytes; upper layers and other structures are additional. Actual recall, unique evaluations and traversal time must be measured. Sanity check and operations. SIFT1M at has fp32 payload and a scan floor, unbatched QPS at the same shared bandwidth. The cited HNSW benchmark’s two-to-three-order throughput gain at recall is reported evidence under its own setup, not a consequence of the work ratio in the different example. For an otherwise idle unbatched scan, vectors is a bandwidth-only threshold, not a universal flat/ANN crossover. High QPS, selection and measured tail latency can lower it; batching or different hardware can raise it. Halving or component bytes halves this vector-read term, not every index cost. If exactness is required, use a method that certifies it rather than assuming high measured recall is enough. Brute-force representative queries and inspect under a defined distance with . Values such as or near are diagnostics, not universal quality thresholds or impossibility proofs; embeddings and cosine-to-distance conventions matter. Use random vectors only for an explicitly labeled noise stress test. Tenant prefiltering can make flat search feasible, but validate filtered ground truth, per-tenant load, query routing and shared-capacity costs.
15.2 From skip lists to HNSW
- What a skip list is: A sorted linked list with progressively sparser upper levels.
- Why it exists: Upper pointers skip long stretches while preserving a local, certain halting test.
- Search rule: Advance while the next key is below the target, then descend when it is not.
- Example: Searching for 17 advances from the head to 7 on level 2, descends before 29, advances 7 to 16 on level 1, descends again, then reaches 17 on level 0.
- Example cost: Three advances and two descents replace scanning nine values. With independent promotion probability , expected occupancy of level is . The characteristic highest-level scale is , not a deterministic maximum. For example, . Standard skip-list analyses bound expected search comparisons by expressions of the form under their counting convention. At , and this expression is , about comparisons or fewer than a ten-million-step linear lookup. Constants, sentinels and equality tests affect the exact count. A total order makes the local stopping test valid; it does not make storage or updates free.
- Losing alternative: Sort vectors by distance to one pivot.
- Why it fails: Triangle inequality gives only , which is a lower bound.
- Failure: Equal pivot distance says nothing about pairwise distance.
- High-dimensional effect: Distance concentration places most points in a narrow band around the pivot. HNSW replaces ordered-list links with stored geometric neighbors. Upper levels usually use greedy descent; the base search keeps candidates and a retained best set, so it may explore alternatives after a local greedy optimum. Its upper-layer stopping test certifies only a local result, not the global nearest vector. Under the stated layer convention,
Thus . At , the characteristic top-index scale is , with expected occupancies at layer , at layer , and at layer . The number of occupied layers is random and includes layer ; is not literally a six-layer guarantee. Geometric occupancy alone does not prove logarithmic graph-search work.
- Nearest-only links: They can waste degree within one cluster and even form disconnected components, but this is a possible failure, not a theorem for every -NN graph.
- Diversity heuristic: Process candidate neighbors by distance from a new point . One common rule accepts when for every already accepted , subject to tie and degree policies.
- Purpose and limit: This favors additional directions and longer cross-cluster links. It is not a global connectivity or recall certificate, especially with an approximate candidate set and capped degree. Flat NSW combines links on one level. HNSW’s hierarchy often improves entry and observed scaling; the cited polylogarithmic/logarithmic behaviors should be treated as model- or benchmark-scoped, not distribution-free worst-case bounds. Random promotion allows local insertion without renumbering a rigid every-other-node schedule. Deterministic balanced skip structures can also support local updates; a global rebuild is not inherent to determinism. Physical graph deletion may require inbound-neighbor repair, while logical tombstones can defer it. Illustrative query budget. Let , and separately assume five upper levels with two expanded nodes each and expanded base nodes. This gives neighbor-distance evaluations if none are reused, a work reduction versus . It is not a bound implied by . Reading a fresh -byte vector for each evaluation costs bytes; expanded adjacency slots add bytes, total . At an assumed effective scattered-read rate of , this component is . The older model charged an entire base neighbor list per evaluated candidate, rather than per expanded node. Neither model establishes observed latency or recall; metadata, caches and access dependencies matter. Scoped link memory. With four-byte IDs, expected allocated link slots contribute
At , this is : at the base and above. Ten million fp32 vectors plus these slots use , over vector payload. The documented rule omits the upper-slot term; its scoped undercount is about , not a complete allocation audit. Counts, pointers, alignment, external IDs, visited sets, locks and payload remain additional. With -byte PQ codes, the same expected slots give and ; links occupy . The base-only shortcut is bytes and , and must be labeled as such. Graph links are not mathematically incompressible; they simply do not shrink automatically with the vector codes. Build and tuning. Assuming expansions of candidates per insertion would give evaluations over inserts, of the illustrative -evaluation queries. is not a hard per-insert evaluation limit, and this is not a build-time bound. Start with a measured baseline and sweep query ; it changes both recall and work and is reversible. If expansions happened to double from to , the base term would double from to —the parameter alone does not promise that. Increase or build width when the measured runtime curve misses target. Base-slot bytes double from to at ; including expected upper slots, ten million vectors need extra links. Choose query width large enough for and the implementation’s constraints. Build width versus query width is an example, not a requirement that build width always exceed every later query width. Monitor tombstone effects and rebuild or repair according to measured behavior; deleted nodes may remain traversable without occupying result slots. At million vectors, these expected-slot floors are for HNSW-Flat and for HNSW with -byte codes, including of links. IVF-PQ with code bytes and an -byte ID has of entries before fixed terms. If its measured recall/probe curve fails the target, consider more memory, additional machines or disk-resident search; no fixed corpus-size threshold makes one family universally best.
15.3 IVF: coarse quantizers, centroids, Voronoi cells
- IVF: Fit representative centroids, assign each vector to a cell, then score selected posting lists. Storage format and routing are separate choices.
- Why: Candidate scans may be much smaller and more batch-friendly than a full scan.
- Counterexample scope: A grid with two bins on each of axes has cells. This is one impractical grid construction, not a requirement of all data-independent routing.
- Failure modes: Poorly matched boundaries or an uneven distribution can overload lists or miss nearby points. Learned partitions can have these problems too. For Euclidean IVF, fit centroids and set , with a tie rule. Cell membership satisfies
For distinct centroids the separating plane is their perpendicular bisector. A Voronoi cell is an intersection of half-spaces: a convex polyhedron, possibly unbounded, and a polytope only if bounded. Tied boundaries need assignment conventions. Inner-product or other routing choices need their own geometry. The inverted file maps centroid IDs to posting lists, analogous to a text index mapping terms to postings. With flat full-vector centroid comparisons and balanced representative probed lists, a continuous distance-count proxy is
Here and . The minimum assumes fixed , equal-cost centroid and candidate comparisons, and feasible integer . Recall changes with and is not optimized by this derivative. At , , giving work reduction at . PQ scoring, indexed centroids, imbalanced lists and hardware change the model.
- Boundary miss: A true neighbor may be in a different cell, especially near a bisector. It is not inevitable for every boundary-near query.
- Probe behavior: Querying multiple nearby centroids can recover missed cells, but the true neighbor’s cell need not be among a small chosen set.
- Geometry limit: A cell can have at most other-cell face neighbors. “Most volume lies near a face” requires a bounded region, distribution and boundary thickness; unbounded Voronoi cells have no uniform finite-volume distribution. For a cube of side , a boundary band of thickness occupies fraction —an illustrative concentration model, not a theorem about every learned cell.
- Cost: Raising scans more selected lists without retraining; their actual total length, not just their count, determines work. At , the flat vector-read floor is and at . Under the balanced-list/full-vector proxy:
- : mean list length , total equivalent distances, and of vector streaming. Reduction is ; routing loss remains.
- : list work , total , of , and . Flat reduction is , with of distances in the coarse scan.
- : mean list length , list work , total . This is below , not a -fold total-work win; coarse comparisons are of the proxy.
- If a centroid HNSW search is separately budgeted at comparisons, the last total becomes , a comparison-count reduction versus the -cell, -probe case. That centroid approximation can itself miss useful cells; the number is neither guaranteed recall nor measured speedup. Fractional list sizes are averages, not actual per-query counts. Never multiply rounded or and present the unrounded total as an exact product. With flat coarse search, is the continuous cost optimum; nearby integers need comparison. Reported library guidance such as cells in a given scale band or to in another band is empirical guidance. Indexed centroids can make larger viable, but do not alone prove those choices optimal.
- Training: A learned IVF coarse quantizer must be trained before ordinary population. Distribution shift can change list balance and recall; stale centroids do not inevitably reduce every metric.
- Implementation rules: The cited points per centroid is a warning threshold, not a mathematical training lower bound or recall guarantee. A default maximum of training points per centroid is a configurable sampling cap, not a target that must exceed the corpus size.
- Numbers: At centroids, these settings correspond to and training points. For a -vector corpus, the latter is above the available distinct points; do not invent extra samples to satisfy it. Use as a starting heuristic, not a fixed optimum. Measure coarse-stage share before switching to an indexed coarse quantizer; centroids is a workload-specific suggestion, not a universal cutoff. Tune integer against exact-neighbor recall. is a balanced-list scan fraction, not recall and not an exact cost fraction for imbalanced lists. Without task labels, exact search on the same frozen, filtered snapshot can still supply ANN ground truth. A starting and representative queries is an audit heuristic; sweep the parameter and report uncertainty, not an automatic bisection guarantee under noisy estimates. Service tiers such as probes and should satisfy their own latency/recall targets. Inspect selected-list lengths and load: is not unique evidence of imbalance; queuing, cache misses and other effects can cause it. IVFFlat adds IDs and centroids but keeps full vectors. At , -byte IDs plus fp32 centroids add , about of vector payload. This scope excludes list, allocator and external metadata overhead. At million vectors, fp32 payload is . Standard HNSW expected slots at add approximately , not the obtained by assuming links at every node. With centroids, IVFFlat IDs and centroids add . A -byte PQ code reduces vector payload to , a -fold vector-only reduction; IDs, codebooks, centroids and refine vectors remain additional. Quantization often dominates the memory choice at this scale, but no architecture wins independently of recall, rebuild and serving costs.
15.4 LSH and hash-collision retrieval
- Ordinary hashing: Expected bucket lookup can be constant time under a load model, but avalanche-style fingerprints do not preserve approximate vector similarity.
- LSH: A near/far collision guarantee supports candidate retrieval without fitting a coarse partition. The general definition does not require collision to be globally monotone between the design radii; the hyperplane family below is monotone in angle.
- Trade-off: Independent tables can consume superlinear posting space and produce many candidates. Actual competitiveness depends on the metric, data, projection computation and implementation, not only an exponent. A family is -sensitive for if pairs at distance at most collide with probability at least , while pairs at distance at least collide with probability at most . The guarantee leaves the intermediate annulus unspecified. For random-hyperplane cosine hashing, use nonzero normalized vectors and :
At cosine , and ; at cosine , and . The per-bit margin is approximately . Keep these unrounded probabilities for all powers and table counts.
- What AND amplification does: Concatenate independent bits into one table key.
- Probability: One-table collision becomes .
- Why it helps: The smaller shrinks faster than .
- What OR amplification does: Build independent tables and union their candidates.
- Probability: Retrieval becomes .
- Why it helps: It restores near-neighbor recall after the strict key lowers all collisions.
- Cost: Every table stores another full set of corpus identifiers. Classical asymptotic construction. For a real-valued algebraic code length , . Define , so . At , success for a qualifying near point approaches . A real index needs integer ; keeps , and gives at least the corresponding constant-success scale. Target success instead needs
The usual candidate/probe scaling is with posting entries under the model; projection and hashing add work such as for separately computed dense hyperplanes, often suppressed with dimension/log factors or preprocessing assumptions. The construction solves an approximate near-neighbor radius problem, not a universal top- recall guarantee. Its query-work bound uses the model's candidate limits or early acceptance of a qualifying point. Exhaustively unioning and reranking buckets for top- is a different procedure: many points in the intermediate-distance annulus or overloaded buckets can produce linear-size candidate sets even though the far-point collision bound holds. Duplicates, short keys and metric choice also affect actual work. Integer classical example. With and the unrounded cosine-derived , , , hence choose , not . Taking gives qualifying-point success about . If every background point has cosine , expected far candidates per table are and the deduplicated expected far union is approximately ; these are expectations, not guaranteed counts. Projection uses hyperplane dots or MACs at width . Far-candidate reranking adds about MACs, plus any qualifying-point and bookkeeping work. Against brute-force MACs, this arithmetic-only ratio is about , not a measured speedup. Posting IDs alone require , before buckets, keys and of vectors if retained for exact reranking. Rounding the old exponent and using bits produced internally inconsistent table, candidate and memory totals. Short-key, high-success example. Set . At cosine , and the minimum independent-table count for pair retrieval is . The exact model gives near retrieval and retrieval at cosine , not the figure’s former . At cosine , retrieval is ; the decrease is percentage points from the case. Far-candidate expectation is if all background points have cosine . Background cosine gives , or , instead. For heterogeneous background items, expected candidates are the sum of their individual retrieval probabilities; far-radius collision bounds yield an upper bound, not equality. Independent dense projections cost MACs here, and the cosine- expected rerank costs MACs. The combined arithmetic-only ratio versus flat is . IDs occupy . Storing an optional redundant two-byte key per posting adds , yielding for that layout, not mandatory LSH space; bucket-key layouts differ. Full rerank vectors and table metadata remain additional. The HNSW link-slot floor is about times smaller than that optional posting-plus-key budget, but this is neither a whole-index comparison nor a matched-recall benchmark. A beam width is not a measured HNSW candidate count. Theory scope. The cited Euclidean LSH exponents and data-dependent are asymptotic theoretical results under their respective models and resource assumptions. On unit vectors, and , giving , exponents and . The expression is an exponent illustration, not a finite-instance prediction of candidates or a proof that this hyperplane index is a fixed factor from an attainable optimum. The cited graph-versus-hash frontier is a reported benchmark, not a theorem over all datasets. Practice. Default to measured graph/IVF baselines for vector ANN; LSH remains useful for some updates, similarity joins and deduplication. Choose from a stated far-collision model, then price the required at the desired success radius. Instrument deduplicated candidates and all projection work, not recall alone. The cited web-scale SimHash setting uses bits and Hamming distance at most over more than billion pages; it is not an infallible duplicate definition. Use MinHash when set/Jaccard overlap is the intended similarity. State table count and bucket work for multi-probe variants. Inserts and removals touch up to tables, so they are local to postings but not constant work independent of . A hot-slice LSH/cold-graph hybrid is a workload option, not a conclusion from an unmatched -times memory comparison.
15.5 Graph indexes: RNG, Vamana/DiskANN, Annoy
A proximity-graph index stores vector nodes and selected edges. Queries may use greedy upper-level routing, best-first search or wider beams; not every graph search is a pure greedy walk. Candidate generation, edge selection, entry policy and stopping rules jointly determine quality and cost.
- Nearest-only rule: It can trap degree within one cluster, leave disconnected components or create a local greedy optimum; it does not necessarily do so on every corpus.
- Directional selection: Reserve some degree for distinct directions and possible cluster crossings, rather than minimizing every edge’s length.
- Limit: Degree diversity is a useful construction principle, not by itself a certificate of global reachability or exact search. Cone record-minimum toy. Distinguish the randomized cone construction here from the relative-neighborhood-inspired pruning used below. Suppose a fixed collection of cones covers directions around a node. Within one cone, randomly permute distinct candidate distances and retain every new prefix minimum. Position is a record with probability , hence . At fixed cone count, expected edge storage is ; can grow steeply with dimension and narrower cone width. The retained set need not contain only the final nearest point. Enumerating every point pair already requires distance comparisons and approximately coordinate work, before cone tests. Record-count arithmetic alone does not establish logarithmic query hops; any such cited theorem needs its geometric and construction assumptions. Vamana pruning. At node , process a candidate set by choosing the nearest surviving , adding it to neighbors, and deleting candidates satisfying
At , this is a relative-neighborhood-inspired occlusion test closely related to the HNSW diversity heuristic. The algorithms are not identical, and testing only retained candidates need not reproduce the full mathematical relative neighborhood graph. Increasing makes this deletion test harder for a fixed retained point; the final capped greedy construction is not necessarily nested as a whole, because earlier choices can change. More candidates can survive and use the degree budget, often including useful longer edges. Conditional shrinkage proof. Assume the target is itself a dataset point, every other point was available to each node’s pruning step, and no candidate was left uncovered by a degree-cap stop. Then either is retained or was removed by some retained satisfying . For , a greedy choice at least as good as that witness yields . If is the minimum interpoint separation and , the target must be reached by
since one further strictly sub- distance can only be zero. At , the logarithmic scales are for and for , giving conservative integer bounds and in this ideal covered-point setting. At , this multiplicative-shrinkage argument provides no logarithmic bound. It does not prove an arbitrary external query, approximate candidate construction, capped degree or real DiskANN walk obeys those hop counts. On disk, actual dependent I/O rounds—not this ideal formula alone—control latency.
- Annoy: A forest of random-projection trees, often built from approximate two-means/split procedures. A perpendicular-bisector split between two representatives is a simplified model, not every implementation detail.
- Query: Search can keep a priority queue of alternative branches and inspect more leaves within one tree. It is false that a wrong descent can only be repaired by searching another tree.
- Knobs: Tree count adds build work and storage; query-time or an equivalent visited-node budget can also buy recall without rebuilding.
- Use case: A static read-only memory-mapped forest may be operationally useful. Loading lazily does not imply a cold first query has zero page-fault or storage cost. In the illustrated graph, greedy search takes , with numbers denoting distance to . ’s back edge to is uphill, so strict greedy progress stops. The true nearest point has distance and is reached through . At the branch, beats by . A best-first retained set of width , with the shown edges and standard visited-node handling, keeps the alternate branch and expands after . This demonstrates one recovery, not a proof that width always escapes a trap.
- Guarantee limits: Approximate candidates, a degree cap that leaves targets uncovered, external queries, ties and update policies can each invalidate the ideal shrinkage proof.
- Mitigation: Best-first candidates, wider exploration and better entry policies can help empirically, but none automatically restores the missing theorem.
- Entry examples: A sample tree, medoid, multiple entries or a hierarchy may reduce entry cost; choose by the measured workload rather than assuming one is always best. Resident graph floor. At million, and fp32, vectors use . Exactly four-byte outgoing slots per node add , total before degree counters, headers, locks, payload and headroom. Dividing by gives , so at least such memory allocations would be needed under ideal sharding; this is not a complete machine or latency plan. Forest illustration. Suppose a simplified binary forest has exactly leaves per tree and a full -float normal per internal node. It has internal nodes, approximately of normals per tree or for trees. Those normals alone are times the vector payload; normals plus one shared vector payload are about times it. The old claim that the forest alone was times conflated the two. Actual Annoy leaf capacity, node layout, representative construction and mapping overhead differ; measure its file and resident working set. Disk record illustration. -byte PQ codes use RAM at million points, of a decimal machine before cache and other structures. Assume full vectors, four-byte neighbor IDs and a four-byte degree count are stored in separately aligned node records. Then
At a record is bytes, leaving bytes. At it exactly fills a page; at it is bytes, spilling by bytes. The change is in degree. Under this fixed aligned/full-record-read layout it changes one page read to two, not necessarily every real implementation’s physical I/O. Padding one node to one page consumes on disk at this scale, not the unpadded including degree counters. Int8 full-vector storage frees bytes and gives the same arithmetic ceiling ; that is a layout ceiling, not a recommended graph degree. Read rounds and load. Assume uncached one-page reads and at most useful simultaneous reads per query. At least rounds are needed; exactly assumes dependencies never reduce useful concurrency. At per round this component is before queueing, CPU, cache misses and tail effects. A beam setting alone does not establish the read count or that concurrency. At QPS, demand is random IOPS and of read traffic. With mean read service time, Little’s law requires about reads in flight across the workload. Saving ten such sequential rounds saves , one quarter only if a separate I/O budget is assumed. The cited billion-point DiskANN result reports one machine, over QPS, above recall@1 and mean latency below under that study’s SIFT-scale setup. The -million, -dimensional read toy above does not independently reproduce or validate it. In particular, one billion -byte resident codes alone would need , so that code width cannot simply be transplanted to the reported case. Practice. Sweep , degree and I/O beam on the actual data. Values such as or are starting configurations, not hop guarantees; is not mathematically restricted to RAM. Check the actual packed record layout and useful read concurrency before increasing degree. Wider I/O search can help latency or recall but can also raise total reads and saturation. Compare a missed query with exact search under matching filters and snapshot; then distinguish reachability, candidate stopping, distance distortion and representation issues. Cache frequently visited entry neighborhoods in RAM—Vamana is not inherently a layered graph. FreshDiskANN is the named update-oriented variant; tombstones, repair and rebuild cadence remain implementation choices. A single-box design fails its throughput target if peak IOPS, bandwidth or tail latency saturates, regardless of adequate average recall.
15.6 Choosing an index: the recall/latency/memory triangle
Let denote vector count, dimension, bytes per coordinate and result count. The relevant axes are exact-neighbor recall, end-to-end latency/throughput and resident memory, with build/update cost as additional constraints. The triangle is a workload-dependent Pareto picture, not a theorem that no design can meet three numerical requirements. Flat fp32 at stores and has unbatched vector-stream floor at . It can meet all requirements for a smaller corpus or with sufficient batching/hardware. HNSW-Flat at uses of vectors plus expected link slots under the chapter’s convention; useful measured recall and latency require tuning, and full precision at a visited node does not make the traversal exact. The illustrative sub-millisecond work estimates do not prove a sub-millisecond serving curve or . IVF-PQ with one-byte subcodes and an -byte ID has entries, or at ten million. With centroids, add of centroids and bytes of codebook, total before list metadata, precomputed tables, working sets and refine vectors. This is about times smaller than the scoped HNSW-Flat estimate, not an all-in process-memory ratio. At of lists, the balanced-list scan fraction is . Routing loss concerns excluded cells; distortion concerns scoring order within candidates. Diagnose with exact distances in the same probed candidates, as well as full-list and exact-flat controls. Raising can recover routes; more accurate codes or full-vector rescoring can reduce within-candidate errors. Exact refinement cannot recover an item never admitted to the refine pool and does not certify global exactness. DiskANN exchanges RAM for disk records, caching and I/O. At million points, the scoped HNSW-Flat floor is ; -byte IVF-PQ entries alone are . Fixed and operational terms must be added before choosing a fleet.
- Claim limit: HNSW and IVF-PQ are recall-latency curves, not fixed points.
- Runtime dials: and trade latency for recall without rebuilds.
- Comparison rule: Match latency, throughput, or memory before comparing recall. Contract. Take ten million -dimensional vectors, exact-neighbor recall@10 at least , , and decimal RAM. These are targets to benchmark, not outcomes established by a byte formula.
- Flat: fits before other memory, but the unbatched streaming floor is times the latency target. At QPS it demands ideal socket-bandwidth equivalents, hence at least such allocations, not . Replication alone does not fix one-query latency; sharding/batching changes the design.
- HNSW: At , vector-plus-expected-slot memory is . If the base search happened to evaluate fresh vectors, vector traffic is , a flat reduction. Dividing by gives . Adding a hypothetical nonoverlapped penalty per vector gives ; this deliberately simplified model omits upper layers, full cache-line behavior, dependencies, graph work, scoring and queueing. It is not an upper bound, measured or proof of -fold latency headroom. does not cap evaluations at .
- IVF-PQ: Scoped index memory is . Coarse vector traffic is , at the assumed bandwidth. Balanced lists contain entries of bytes, and . The sum is a traffic proxy, with in coarse bytes. It omits distance-table builds, PQ lookup/add work, top-, cache and other costs. Indexed centroids are an option if coarse work is measured to dominate; they introduce another approximation.
- Build: The assumed HNSW evaluations equal of the base-only query-work units. Multiplying by the artificial service model yields hours of equivalent work, not a core-hour lower bound or build-time prediction. Construction has different access patterns and overhead. IVF training and assignment can also be expensive; an orders-of-magnitude rebuild win requires matched measurement, not family names. The cited SIFT1B case uses : its raw payload is versus RAM, an -fold mismatch. Even allocating every byte to one billion points allows only ; caches and bookkeeping reduce the code allowance. It is a different setting from the -dimensional examples. Capacity and rebuilds. Using only the expected vector-plus-link slot floor,
At , this is vectors before overhead, or if two full index copies must coexist. Ten million require for two copies even before other allocations: the stated box does not have exact rebuild headroom. A box has , a different budget. Plan a separate builder/hot swap, fewer resident vectors or more RAM. Small corpora are operationally simple only when their actual latency and QPS meet the target; one million vectors still have a scan floor under these assumptions. For a -million-point floor of , decimal- allocations are needed before replicas/headroom, not . The IVF-PQ entry array may fit one such node at steady state, but centroids, codes, metadata, refine working sets and rebuild copies must fit too. If global exactness is nonnegotiable, approximate candidates plus exact refinement are insufficient; use exhaustive or certified exact search. If a measured recall SLO is acceptable, evaluate overfetch, exact refinement and disk saturation at peak QPS. Freeze snapshots and filters for exact ground truth over a representative query sample, such as queries; report variation and drift. Halving halves full-vector and centroid payload, not fixed-width PQ codes, graph IDs, metadata or every index byte.
Diagrams
Figure 15.1
Panel A shows unconditional Gaussian pair-distance distributions divided by their means. Their exact CVs at are approximately . This is a population distribution, not a fixed-query extrema plot. Panel B marks at most split tests along a balanced-depth toy path; axes can repeat, and full subtree bounds can combine gaps. A coordinate-to-median-plane gap of order is compared only heuristically with a large full-space neighbor radius, not used to prove zero pruning.
| Panel A dimension | Shape after normalization by mean | |
|---|---|---|
| exact; delta-method approximation | Broad Gaussian-pair distance distribution | |
| Narrower unconditional pair-distance distribution | ||
| Concentrated unconditional distribution; not deterministic bounds on fixed-query distances |
Figure : Under the stated Gaussian pair model, relative distance spread decreases approximately as . This can weaken exact-tree pruning but does not prove that every high-dimensional tree visits every leaf. A path’s split-count budget is distinct from a full bounding-box search, and common-query extrema require conditional rather than independent-pair calculations.
Figure 15.2
Diagram description and source
flowchart TB
subgraph SKIP["(a) Skip list"]
direction TB
S2H((H)) --> S27((7)) -->|next key 29 exceeds target 17, descend| S17((7))
S17 --> S116((16)) -->|next key 29 exceeds target 17, descend| S016((16))
S03((3)) --> S07((7)) --> S012((12)) --> S016 --> S017((17)) --> S021((21)) --> S029((29)) --> S038((38)) --> S045((45))
end
subgraph GRAPH["(b) HNSW"]
direction TB
G2A((entry)) --> G2B((closer))
G2B -. descend .-> G1A((same node))
G1A --> G1B((closer))
G1B -. descend .-> G0A((same node))
G0A --> G0B((closer)) --> G0Q((local result; verify recall))
end
Expected occupancies in the displayed three-level sketches are for promotion , and for the stated HNSW layer law. Figure : Ordered skip-list descent uses a valid order test; geometric graph descent uses only a local improvement test before wider base search. Geometric thinning gives a logarithmic characteristic highest-level scale, not a deterministic height bound or a theorem of logarithmic HNSW query work. Base-layer alternatives are omitted from this schematic.
Figure 15.3
Panel A shows two Voronoi cells split by a slanted perpendicular bisector. Query falls in cell near the boundary. Candidate in is away. True nearest lies just across the line in and is away. Centroids and sit deeper inside their cells. Panel B stacks stage-one centroid work and stage-two posting-list work for three configurations.
| Configuration | Stage 1 | Stage 2 | Total distances |
|---|---|---|---|
| IVF4,096 with flat coarse quantizer | |||
| IVF65,536 with flat coarse quantizer | in the balanced-list proxy | ||
| IVF65,536 with HNSW coarse quantizer | assumed evaluations | balanced-list proxy |
Figure : A true neighbor can lie across a cell boundary, motivating multiple probes. Larger partitions can make a flat centroid scan dominate. The table compares a balanced-list distance-count model, not measured latency or matched recall; an approximate centroid index introduces its own routing risk.
Figure 15.4
Panel A is one illustrative outcome of three random hyperplanes: agreement is probabilistic, not determined solely by the drawn near/far labels. Panel B uses . Its retrieval crossing is at and at . Finite curves are smooth, not literal step functions.
| Item | Per-bit | Retrieved with and |
|---|---|---|
| Neighbor at cosine | ||
| Non-neighbor at cosine |
Figure : Independent AND/OR amplification changes a per-bit margin of approximately into radius-dependent retrieval probabilities. The -table construction costs postings, projections, buckets and reranking; its near-pair retrieval is not a universal top- recall rate.
Figure 15.5
Panel A is a schematic nearest-representative-per-cone comparison: the source illustration draws five retained directions at and three at . Without candidate coordinates those counts are illustrated inputs, not derivable from angle alone. This nearest-per-cone sketch is distinct from retaining all random prefix minima in the earlier expected-degree toy. Wider cones can merge distinct departure directions. Panel B below specifies the edges for the greedy-versus-best-first example.
Diagram description and source
flowchart LR
E["E, 63.6"] --> P2["P2, 55.5"]
E --> P5["P5, 50.4"]
P2 --> P1["P1, 38.6"]
P5 --> P1
P1 --> P4["P4, 22.4 returned"]
P1 --> P6["P6, 36.9"]
P6 --> P7["P7, 30.5"] --> P8["P8, 20.0"] --> P9["P9, 5.66 true NN"]
P4 -->|uphill back edge| P1
P4 -.->|distance 22.4| Q((Q))
P9 -.->|distance 5.66| Q
Figure : Cone coverage, edge candidates and degree policy matter jointly; the illustrated edge counts are not a dimension-independent guarantee. In the shown graph, greedy descent stops at with distance instead of at . A retained best set of width preserves , then expands after . The branch-distance gap and four further expansions are properties of this explicit toy, not a general beam-width theorem.
Figure 15.6
Diagram description and source
flowchart TB
R(("exact-neighbor recall"))
M(("resident memory"))
L(("latency and throughput"))
R --- M
R --- L
M --- L
F["Flat exact: 30.72 GB vectors; 614.4 ms unbatched stream floor"] --- R
F --- M
H["HNSW M=16: 32.0427 GB vector + expected link slots; benchmark recall and tails"] --- R
H --- L
I["IVF-PQ m=96: 1.05337 GB scoped index; 0.414 ms traffic-only proxy; benchmark scoring"] --- M
I --- L
D["Disk graph: codes and caches resident; bulky records on SSD; price IOPS"] --- M
D --- L
| Representation at | Resident bytes per vector |
|---|---|
| HNSW, | for vector plus expected allocated link slots |
| fp32, no index | |
| int8 scalar | |
| IVF-PQ, | per entry; fixed centroids, codebook and other terms are additional |
| Binary, 1 bit per dimension |
Figure : These families occupy workload-dependent operating curves, not immutable corners of an impossibility triangle. The byte table is scoped per-vector storage, not total resident process memory. Vector quantization can dominate payload savings, while graph links, IDs, fixed terms, caches, replicas and rebuilds remain. Exact refinement does not turn arbitrary approximate routing into certified exact search.
Whiteboard pack
What to draw
- State the snapshot, filters, metric, tie rule, recall target, QPS, tail-latency target and resident-memory budget.
- Draw flat exact search. Label fp32 vector bytes, approximately FLOPs and unbatched streaming floor ; mark at .
- Draw sparse HNSW upper levels and wider base search. Mark the level law , expected link slots, and query as a width—not a work cap.
- Draw IVF cells with a possible cross-boundary neighbor. Write the balanced-list/full-vector proxy , and circle its assumptions.
- Draw independent hash bits and independent tables. Write , posting space , and the projection work omitted by the candidate exponent.
- Draw a graph trap and the explicit alternate branch. Add the conditional Vamana shrinkage assumption and a disk-record budget.
- Finish with a Pareto triangle, measured operating points, integer capacity requirements and rebuild headroom—not a claim that three product requirements can never all be met.
Spoken script
ANN accepts possible exact-neighbor recall loss by pruning candidates or approximating scores. High dimension can weaken exact-tree bounds, but not every dataset or exact method fails. HNSW trades graph storage and exploration work for a useful measured recall-latency curve. IVF trades coarse routing and probed-list work; PQ adds distortion. LSH provides radius-based collision guarantees with posting and projection costs. Disk graphs exchange RAM for dependent reads and saturation risk. I state the workload and full resource scope, validate against matching exact ground truth, and benchmark throughput and tails rather than promoting a byte calculation into an SLO guarantee.
Interview traps
1. Why not use a kd-tree or exact scan?
A median coordinate-plane gap of order can be small beside full-space radii of order in the Gaussian toy, but combined region bounds and actual data determine pruning. The bandwidth-only flat threshold is fp32 -dimensional vectors at and ; it excludes selection, load and overhead. Use exact search when it meets the measured workload or when approximate misses are unacceptable. Full-vector rescoring of an incomplete candidate set does not supply exactness.
2. When do you choose HNSW, IVF-PQ, LSH, or another graph index?
Use measured HNSW curves when full vectors and graph fit with serving and rebuild headroom. Consider IVF-PQ when memory, batch execution or a measured rebuild advantage dominates; distinguish routing and distortion. Consider disk graphs when records spill to SSD and IOPS plus tails fit. LSH can suit some update, join or deduplication workloads that justify its tables. Annoy can suit a static memory-mapped forest, with both tree count and query exploration budget measured; mapping does not make cold access free.
3. Recall is low. Which knob moves first?
For HNSW, first sweep query against exact-neighbor recall and measured work; do not treat it as a count bound. For IVF-PQ, compare exact scoring within the same selected lists, compressed scoring with all lists on a sample, and exact flat search. Probe all centroids explicitly or use an exact coarse control—an approximate coarse search can otherwise remain a confounder. More probes address routing; more accurate scoring or a larger refine pool addresses admitted-candidate ordering. Exact refine cannot recover an excluded true neighbor.
4. What does the recall-latency-memory triangle actually forbid?
The triangle is not an impossibility theorem. A small corpus or an efficient batch can meet memory, recall and latency simultaneously. Its discipline is to compare full operating curves under the same snapshot, filters, workload, recall definition, hardware and resource scope, including tails, updates and rebuilds. No single byte estimate proves a universal family ranking.
5. When would you not use ANN at all?
Use exact search when it meets the workload or when certified absence of ANN misses is required. If real-query neighbor distances have little contrast, investigate metric and representation quality, but a near- distance ratio alone does not prove ANN impossible or semantically useless. Do not confuse exact-neighbor retrieval recall with downstream factual correctness or legal completeness.
Key numbers
| Topic | Numbers and commitment | Assumptions and limits |
|---|---|---|
| Prototype growth | ; million are times larger | The opening is a proportional example, not a universal measured latency law |
| Exact scan identity | fp32 vector bytes and approximately FLOPs, unbatched | ; is a non-amortized bandwidth QPS ceiling |
| Ten-million flat index | , streaming floor at , ceiling QPS | Not a latency prediction for every exact algorithm or batched implementation |
| Distance concentration | Exact unconditional Gaussian-pair CV: at | Pair mean at is , SD ; is asymptotic |
| Distance extremes | Fixed : distance local SD ; tail markers and , ratio | Conditional model; not expected extrema or hard bounds |
| kd-tree degeneration | Balanced depth scale at singleton leaves; at most distinct tested axes on a path | Repeated axes and full bounding boxes matter; a full grid is not required for exact search |
| Reported dimension crossover | The cited experiment found scan faster than tested partitioning schemes above roughly ten dimensions | Dataset/hardware-scoped evidence, not a universal cutoff |
| CPU sizing example | FLOPs, compute floor versus vector floor, ratio | unbatched QPS requires ideal socket-bandwidth allocations; per-query latency needs its own plan |
| A100 exact example | Published gives vector-read floor; batch compute floor | Ideal throughput ceiling about QPS; regular -QPS batch-fill wait averages |
| Billion-vector flat scale | fp32; implies | At least stated peak-bandwidth A100 equivalents before capacity and overhead |
| HNSW example | Assumed expansions of neighbors: evaluations, vectors | does not enforce that count; base links exclude upper layers |
| SIFT1M check | vectors, stream floor, unbatched QPS at stated bandwidth | Cited HNSW throughput at recall is a separate benchmark, not proved by the work ratio |
| Flat-search threshold | vectors from the bandwidth-only budget | Halving or coordinate bytes halves this vector-read term, not all costs |
| Contrast test | representative exact-query distances; define metric and | thresholds such as are diagnostics, not performance or semantic guarantees |
| Skip-list scale | : characteristic level ; cited expected-cost expression | Random height and comparison convention matter |
| HNSW layers | Characteristic top-index scale at | Expected layer occupancies ; actual occupied-layer count is random |
| HNSW query example | Assumed upper plus base distance evaluations, total | of vectors and expanded link slots, at assumed effective ; not an bound |
| HNSW memory | expected links at ; vectors plus slots | Base-only omits upper-link bytes and all other overhead |
| HNSW build | assumed expansions of candidates per insertion yield evaluations | illustrative full-query work units, not a build bound implied by |
| Compressed HNSW | ; at ten million, links | is the separately labeled base-only shortcut |
| HNSW tuning | Query width affects work and recall, not a fixed expansion count | adds expected link slots at ten million; build parameters need measurement |
| HNSW versus IVF at | HNSW-Flat ; HNSW with -byte codes including links | IVF-PQ -byte entries before fixed/operational terms |
| IVF cost law | Balanced/full-vector proxy ; fixed- continuous minimum | At , work and ratio for , not a recall-constrained optimum |
| IVF4,096 and one probe | Mean list ; proxy total , , | Fractional averages, not a fixed query count |
| IVF4,096 and 32 probes | list distances, total , , vector traffic | coarse work; no measured recall or latency follows |
| IVF65,536 and 32 probes | Flat total versus hybrid assuming coarse distances | comparison-count reduction versus ; approximate coarse routing may change recall |
| IVF rules | Flat proxy optimum for | , – and the coarse-switch suggestion are empirical starting points, not universal optima |
| IVF training | warning threshold; sampling cap | Configurable implementation defaults, not theoretical minima or required distinct sample counts |
| IVF operations | Probe heuristic ; representative queries; example tiers probes | List-length/load histograms and uncertainty matter; is not a unique imbalance diagnosis |
| Two-hundred-million scale | fp32 ; expected HNSW links , not | At centroids IVFFlat IDs+centroids ; PQ96 vector payload |
| LSH single bit | Cosines give collisions | Margin ; compute powers from unrounded probabilities |
| LSH classical law | , ; integer , | Constant near-point success; candidate/probe exponent omits projection and dimension work |
| Figure amplification | : near retrieval , far | crossings at one table and at |
| Radius sensitivity | Cosine gives collision and retrieval | percentage points below cosine- retrieval, not a fixed recall law |
| Classical hyperplane setup | ; choose | Success , expected far union , dots and IDs; arithmetic ratio |
| Affordable LSH setup | : expected far union at cosine ; at | IDs plus optional keys ; vectors extra; arithmetic ratio |
| LSH versus HNSW | optional posting/key layout versus HNSW expected link slots, ratio | Not whole-index or matched-recall memory; actual candidate work must be measured |
| Euclidean LSH check | Asymptotic exponents and ; is not a finite candidate prediction or attainable-optimum benchmark | |
| Deduplication setting | Reported SimHash configuration: bits, Hamming distance at most , more than billion pages | Similarity- and study-specific, not proof that every flagged pair is a duplicate |
| Randomized neighborhood graph | Random prefix records per cone have expectation | Fixed- expected edges ; all-pairs comparisons ; logarithmic hops need additional assumptions |
| Vamana hop bound | Ideal complete-coverage dataset-target case: | At , bounds for ; no such practical hop guarantee from alone |
| Figure walk | ; true NN | Alternate survives width in this explicit toy |
| Hundred-million storage | vectors plus degree- slots = | At least ideal decimal- allocations before counters, overhead, replicas and headroom |
| Annoy example | Simplified -tree, -point-leaf illustration: about normals | Normals are times vectors; normals plus one vector copy are times, not forest alone |
| DiskANN resident codes | million -byte codes = , of decimal | At one billion, the same codes alone are and cannot fit the cited case |
| Disk sector bound | gives at fp32 | uses bytes; uses ; int8 ceiling ; aligned layout and full-read assumptions matter |
| Disk latency and throughput | uncached reads at concurrency at most need at least rounds | rounds imply ms component; QPS demands IOPS and , not a measured tail bound |
| Published DiskANN point | Reported billion-point SIFT setup: one machine, over QPS, over recall@1, mean under ms | Different from the -million/-dimension read toy; no cross-validation claimed |
| Triangle bytes per vector | HNSW-Flat : expected-slot floor; flat ; SQ8 ; PQ96+ID ; binary | Storage scopes and score accuracy differ; not complete process memory |
| Final contract | vectors, , recall@10 , , decimal | Benchmark targets under matching snapshot, filters, load and hardware |
| Final flat result | , unbatched stream floor , times latency target | QPS needs at least ideal bandwidth allocations, not |
| Final HNSW result | scoped steady-state floor; assumed distances read | Artificial additive read model is neither an bound nor measured |
| Final IVF-PQ result | scoped index; coarse traffic plus entries | Total excludes ADC builds, scoring and selection; coarse traffic share |
| Final build result | Assumed distances = base-query work units | Multiplying by the artificial query model gives equivalent hours, not a build-time/core-hour floor |
| SIFT1B resident bound | ; decimal permits at most before overhead | Different dimension and code requirements from the -dimensional examples |
| Capacity rules | Scoped expected-slot capacity vectors on decimal , or for two copies | Ten million copies twice need before overhead; is a different budget |
| Five-hundred-million final branch | HNSW-Flat floor needs at least decimal- allocations; PQ96+ID entries | Add all fixed, rebuild and refine costs. Exact rescoring of approximate candidates does not certify global exactness |
00-START-HERE · 01-READING-ROUTES · 14_beyond_plain_text_tables_layout_documents · 16_compression_and_index_economics