Search

Search papers and lessons

HNSW: Efficient and Robust Approximate Nearest Neighbor Search

Yu. A. Malkov, D. A. Yashunin · 2016

Malkov and Yashunin's HNSW index stacks nearest-neighbour graphs in layers so that a search takes logarithmic time and stays fast on clustered data.

On this page

  • Colour = topic mix
  • Discrete math
  • Probability
  • Linear algebra
  • Algorithms
  • Calculus
  • Learning basics
  • ReadReady to readNot yet

TL;DR

Finding the nearest stored vector to a query is easy to state and slow to do exactly for millions of items. Approximate nearest-neighbour search trades a little accuracy for speed. HNSW (Hierarchical Navigable Small World) builds a stack of proximity graphs, where the top layers hold a few long-range links and the bottom layer holds every item. A search enters at the top, greedily hops toward the query, and drops a layer when it can go no further. The paper shows that this gives logarithmic scaling and beats earlier open-source indexes, especially on high-dimensional data and on clustered data.

Builds on: Approximate Nearest Neighbor Search, K-Nearest Neighbors, Greedy Algorithm · Leads to: the graph-index family used by most vector databases and retrieval systems

Why it mattered

Retrieval-augmented systems, recommendation engines and image search all need to find similar items among very large sets of embeddings. A linear scan costs one distance computation per stored item. For a million 128-dimensional vectors, that is a million distance calculations per query, which is too slow for interactive use.

The paper's index gave a large speed-up at high recall. It clearly beat the other open-source methods on SIFT, GloVe, DEEP and CoPhIR, and it was the best method on every general-space dataset it tested. The authors also highlight robustness: the same method did well across datasets of very different intrinsic dimensionality, so practitioners did not have to choose a method for each dataset. Its construction is incremental, so new items can be added without rebuilding the index. The abstract notes that the layered structure is similar to a skip list, which the authors say allows a straightforward distributed implementation; Section 6 later qualifies this.

The problem

Exact nearest-neighbour search becomes hopeless in high dimensions, a difficulty usually called the curse of dimensionality. Approximate methods relax the requirement that the answer be exactly right. Their quality is measured by recall: the fraction of the true KK nearest neighbours that the search returns.

Earlier approximate methods used tree structures, locality-sensitive hashing (Locality-Sensitive Hashing) or product quantization. Graph methods were promising. Build a k-nearest-neighbour graph, connect each item to its closest neighbours, and search by greedy routing: from the current node, move to the neighbour closest to the query and repeat. The catch is that the number of hops grows like a power law with dataset size in such graphs, and on clustered data the graph can lose global connectivity, leaving the search stuck in a local cluster.

The navigable small world (NSW) model fixed the scaling by adding long-range links, so that greedy routing needs only polylogarithmically many hops. But NSW still had two problems. A search that starts from a random node spends most of its hops in a "zoom-out" phase, when its links are too short to reach far, and on low-dimensional data it could lose to tree methods by orders of magnitude. The question is how to get logarithmic routing with a structure that stays robust.

How it works

The index is built one item at a time, and a search uses the same descent. The steps below follow a tiny toy index from insertion to query.

flowchart TD
  A["Pick a random top layer for the new item"] --> B["Greedy search from the top entry point"]
  B --> C["Drop one layer, keep the best nodes as entry points"]
  C --> D["At each layer, pick diverse neighbours and link them"]
  D --> E["Repeat until the bottom layer"]
  E --> F["Query: same descent, then return the K best"]
  1. Choose the top layer. Each new item draws a level ll at random, with a probability that falls off geometrically with height. Most items live only on layer 0. A few reach layer 1, and fewer still reach layer 2. Check: with a small mLm_L, almost every draw is 0, so most items stay on layer 0.

  2. Find candidates layer by layer. Starting from the global entry point at the top, the algorithm runs a greedy search on each layer above ll with a list of one candidate. Its result is the entry point for the next layer down. Check: this is the zoom-in phase, and the top layer only holds long links, so the first hops are large.

  3. Gather neighbours at the item's own layers. From layer min⁡(L,l)\min(L, l) down to layer 0, the algorithm runs a wider greedy search with a candidate list of size efConstruction and collects the closest found items.

  4. Choose diverse neighbours. Rather than simply taking the MM closest, the heuristic walks through candidates from nearest to farthest and keeps a candidate only if it is closer to the new item than to any neighbour already kept. In the paper's Fig. 2 example, the heuristic keeps a link into a second cluster, which the closest-neighbour rule would miss. Check: two clusters each with a tight group of close neighbours keep a bridge between them.

  5. Link both ways and prune. Each chosen neighbour gets a link back to the new item. If a neighbour now has more than Mmax⁡M_{\max} links on that layer, its list is shrunk with the same heuristic.

  6. Search. A query runs the same descent with the candidate list at layer 0 set to size KK or larger. The KK closest items in the final list are returned.

The toy index. Take 7 items placed on a line at positions 1,2,…,71, 2, \dots, 7. Suppose the layers are: layer 2 holds {4}\{4\}; layer 1 holds {2,4,6}\{2, 4, 6\}; layer 0 holds all seven items. Each layer links its members to the items next to them on that layer. Search for the query q=7q = 7, keeping one candidate on each layer:

  • Layer 2: the entry point is 4, the only node on this layer, so the search stays at 4. Its distance to the query is ∣4−7∣=3|4 - 7| = 3.
  • Drop to layer 1: from 4, the neighbours are 2 (distance 5) and 6 (distance 1). Move to 6. From 6 the neighbours are 4 (distance 3) and 2 (distance 5). Neither is closer than 6, so stop at 6.
  • Drop to layer 0: start at 6. Its neighbours are 5 (distance 2) and 7 (distance 0). Move to 7, which is the query. The search returns 7.

The search computed five distances (to 4, 2, 6, 5 and 7) instead of seven. On seven items that saving is small, but each layer checks only a few neighbours, so the work stays bounded per layer as the index grows.

The math

The layer distribution is the piece that makes the whole structure work. The paper draws the level as

l=⌊−ln⁡(U)⋅mL⌋,U∼Uniform(0,1),l = \left\lfloor -\ln(U)\cdot m_L \right\rfloor, \qquad U \sim \text{Uniform}(0, 1),

where mLm_L is a normalisation factor. The quantity −ln⁡U-\ln U is exponential with rate 1 (see Exponential Distribution), so E=−ln⁡UE = -\ln U satisfies P(E≥s)=e−sP(E \ge s) = e^{-s}.

Definition: Level distribution

An item reaches at least layer kk when −ln⁡U⋅mL≥k-\ln U \cdot m_L \ge k. Since l=⌊EmL⌋l = \lfloor E m_L \rfloor, this happens with probability P(l≥k)=e−k/mLP(l \ge k) = e^{-k/m_L}. The factor mLm_L sets how fast the layers thin out.

Step 1 in symbols

With the value the paper suggests, mL=1/ln⁡Mm_L = 1/\ln M, the probability becomes

P(l≥k)=e−k/mL=e−kln⁡M=M−k.P(l \ge k) = e^{-k/m_L} = e^{-k\ln M} = M^{-k}.

Each layer up is MM times less likely. Check with M=2M = 2: P(l≥1)=1/2P(l \ge 1) = 1/2 and P(l≥2)=1/4P(l \ge 2) = 1/4.

Step 2 in symbols

Out of NN items, about NM−kN M^{-k} reach layer kk. The top layer is the one holding roughly one item, where NM−k≈1N M^{-k} \approx 1, so the number of layers is about log⁡MN\log_M N. The search descends through about log⁡MN\log_M N layers, and on each layer it looks at a bounded number of links. That is the logarithmic scaling the paper claims: the number of layers grows with log⁡N\log N, and the work per layer does not grow with NN. The paper proves this assuming an exact Delaunay graph on each layer; its simulations on low-dimensional data agree with the result.

Step 4 in symbols

The neighbour heuristic keeps a candidate cc for the new item qq only if

d(q,c)<d(c,e)for every neighbour e already kept,d(q, c) \lt d(c, e) \quad \text{for every neighbour } e \text{ already kept},

where dd is the distance. Without the heuristic, the index would link only to the nearest MM candidates, which can all lie in one cluster. The paper notes that with enough candidates the rule yields the relative neighbourhood graph, a minimal subgraph of the Delaunay graph that can be built from distances alone. That subgraph keeps the graph connected even on clustered data.

Step 6 in symbols

A greedy step from node cc moves to the neighbour ee that minimises d(e,q)d(e, q), and it stops when no neighbour is closer. The search keeps a candidate list of size ef\textit{ef}; a larger ef\textit{ef} gives higher recall at more distance computations.

Results

The results are the paper's benchmark comparisons on standard vector sets, measured by recall against query time.

Datasets. The paper's Table 1 lists the test sets. SIFT has 1 million vectors of dimension 128. GloVe has 1.2 million word embeddings of dimension 100, compared with cosine similarity. DEEP has 1 million vectors of dimension 96. CoPhIR has 2 million vectors of dimension 272. A random set has 30 million vectors of dimension 4, and MNIST has 60 000 images of dimension 784.

Vector benchmarks. On SIFT, GloVe, DEEP and CoPhIR, HNSW "clearly outperforms the rivals by a large margin", according to the paper's comparison against NSW, FLANN, Annoy, VP-trees and FALCONN. On the low-dimensional random set (dimension 4), HNSW is slightly faster than Annoy at high recall and strongly ahead of the other methods.

Against NSW. On 4-dimensional random data, HNSW uses far fewer distance computations than NSW, especially at high recall. On 8-dimensional random data at recall 0.95, the paper reports that HNSW's scaling is no worse than logarithmic and that it beats NSW at every dataset size.

General spaces. On datasets that violate the triangle inequality, where NSW had severe problems on low-dimensional data, HNSW is reported as the best method on every dataset tested. The largest gain over NSW, almost three orders of magnitude, is on the lowest-dimensional set, wiki-8, which uses Jensen-Shannon divergence.

Costs. HNSW uses significantly more memory than the product-quantization methods it was compared with, but it reaches much higher accuracy and is much faster to search and to build.

Limits. The search always starts at the top layer, which the authors note makes the index hard to distribute by the same methods as NSW. The number of links per layer MM still has to be chosen, and the paper suggests it could be inferred by heuristics. The authors also list element updates and removal as future work.

Reading guide

The paper has seven numbered sections. Read them in this order, with these lessons alongside.

Check yourself

QuestionWhy does an item get a top layer only rarely, and what does that do to the search cost?Show answer

The level is ⌊−ln⁡U⋅mL⌋\lfloor -\ln U \cdot m_L\rfloor, so the probability of reaching layer kk is e−k/mLe^{-k/m_L}. With mL=1/ln⁡Mm_L = 1/\ln M that is M−kM^{-k}. Layers are therefore sparse, and the top layers hold few items with long links. That lets the search make big jumps first and keeps the number of layers around log⁡MN\log_M N.

QuestionWith M=4M = 4, what is the probability that a new item reaches layer 2 under the default mLm_L?Show answer

With mL=1/ln⁡4m_L = 1/\ln 4, P(l≥2)=M−2=1/16=0.0625P(l \ge 2) = M^{-2} = 1/16 = 0.0625.

QuestionCompare two ways of choosing neighbours: the MM closest candidates, or the diversity heuristic. Give a case where the first fails.Show answer

If the new item sits at the edge of one dense cluster, its MM closest candidates may all lie in that cluster. The graph then has no link into a second cluster, and a greedy search can get stuck. The heuristic keeps a candidate only if it is closer to the new item than to any neighbour already chosen, so it can keep a link to the second cluster.

QuestionIn the toy index with query q=7q = 7, why does the layer-1 search stop at 6 and not move on to 2?Show answer

From 6 the layer-1 neighbours are 4 and 2, at distances 3 and 5 from the query 7. Node 6 itself is at distance 1. The greedy rule moves only to a strictly closer neighbour, so neither 4 nor 2 is taken, and the search stops at 6 and drops to layer 0.

QuestionWhy does the paper's search always start from the top layer, and why does that limit distribution?Show answer

The top layer is the global entry point, which gives the logarithmic descent. But every query passes through the same few top-layer nodes, so those nodes become a bottleneck if the index is split across machines. The paper says that every query passes through these few top-layer nodes, so the structure cannot be distributed by the same methods as NSW. Splitting the data across machines works but does not scale well with the number of machines, though skip-list techniques might help.

Sources

Read the full paper

Yu. A. Malkov, D. A. Yashunin, 2016. arXiv:1603.09320