AI Wiki中文/EN

HNSW: build shortcuts, then search with a budget

HNSW

Build a real layered graph and compare greedy descent with wider candidate search.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Use a few landmarks before walking the neighborhood

An exact nearest-neighbor scan visits every stored vector. A proximity graph instead links vectors to nearby vectors and searches through those links. Starting from the wrong place can take many steps or reach a local dead end. HNSW adds sparse upper layers that act as long-range routing structure, then searches a denser bottom layer with a wider candidate budget.

HNSW means hierarchical navigable small world. Its graph is built incrementally, not supplied as a fixed map. Each insertion searches existing layers, chooses neighbors and may prune old connections. The cited v4 paper presents insertion, layer search, two neighbor-selection rules and query search as separate algorithms. Our implementation follows that version with explicit teaching limits. HNSW, algorithms 1–5

The first manuscript appeared in 2016; the cited v4 is the 2018 revision. Reading an early pseudocode page and a later library README does not establish identical implementation details. The official hnswlib README is used here to distinguish construction and query controls, not to claim our code is the library. hnswlib, API methods

A wider result set can improve recall while spending more distance evaluations.
A wider result set can improve recall while spending more distance evaluations.

A hierarchy sampled once, a budget chosen per search

For each inserted vector, sample a nonnegative maximum level ℓ using a uniform random U in (0,1]. The paper uses a level multiplier; we choose it from M:

ℓ=⌊−ln⁡U mL⌋,mL=1ln⁡M,M>1.\ell=\left\lfloor-\ln U\,m_L\right\rfloor,\qquad m_L=\frac1{\ln M},\quad M>1.

A node at level ℓ is present at every layer from 0 through ℓ. Before our implementation’s level cap, the probability of reaching layer j is:

Pr⁡(ℓ≥j)=e−j/mL=M−j,j=0,1,2,…\Pr(\ell\geq j)=e^{-j/m_L}=M^{-j},\qquad j=0,1,2,\ldots

Thus upper layers become progressively smaller. Summing these discrete survival probabilities gives the expected number of layer memberships:

E[ℓ+1]=∑j=0∞M−j=MM−1.\mathbb E[\ell+1]=\sum_{j=0}^{\infty}M^{-j}=\frac{M}{M-1}.

This derivation is for the uncapped discrete rule. Our cap at level 12 replaces the infinite sum with terms j=0 through 12. Randomness in the level assignment does not guarantee a favorable graph for every insertion order or dataset.

To insert a point q, start at the current entry node’s highest layer. Descend through layers above q’s assigned level with a search budget of one. At each shared lower layer, perform a wider search with efConstruction, select up to M neighbors and add links in both directions. Existing adjacency lists that exceed their layer capacity are pruned. If q becomes the highest-level node, it becomes the entry point. HNSW, algorithm 1

The neighbor heuristic first considers candidates near q. A candidate c is accepted if it is closer to q than to every already selected neighbor r:

d(c,q)<d(c,r)for every r∈R.d(c,q)<d(c,r)\qquad\text{for every }r\in R.

The intent is to keep routes in diverse directions instead of spending all links on one tight cluster. The paper also gives a simple nearest-M rule. Our heuristic disables candidate extension and enables filling unused slots with rejected candidates, matching declared options from algorithm 4. Squared Euclidean distances preserve every comparison used here.

Layer search maintains a visited set, a nearest-first candidate heap and a farthest-first retained-result heap W. The latter holds at most ef nodes. Pop a candidate c, inspect unvisited outgoing neighbors and retain promising results. With a full W, stop when:

d(q,c)>max⁡w∈Wd(q,w),∣W∣=ef.d(q,c)>\max_{w\in W}d(q,w),\qquad |W|=ef.

This is a graph-search stopping rule, not a proof that all unvisited vertices are farther away. A useful neighbor may lie behind a worse intermediate point. The candidate heap and total visited set can exceed ef; ef is not a fixed number of distance evaluations. Query search uses budget one in upper layers and the chosen ef at the bottom, then returns k results with ef at least k. HNSW, algorithms 2 and 5

For exact top-k set E and returned set A, with at least k stored vectors, our search-quality measurement is:

Recall@k=∣A∩E∣k.\mathrm{Recall}@k=\frac{|A\cap E|}{k}.

Exact and graph results use squared Euclidean distance and the same ascending-ID tie rule. This is neighbor agreement, not relevance judgment.

Build the graph before searching it

Run with Python 3.12 and NumPy 1.26. Seed 31 generates 120 four-dimensional database vectors and 20 separate queries; seed 29 controls insertion levels. We use M=4, efConstruction=20, maximum outgoing degree 8 at the bottom and 4 above it, and a level cap of 12. The class is deliberately bounded to 500 vectors and finite coordinates.

"""Original bounded HNSW teaching implementation, following v4 algorithms1–5."""
import heapq
import json
import math
import numpy as np

class HNSW:
    def __init__(self,dimension,m=4,ef_construction=20,seed=29,heuristic=True):
        if type(dimension) is not int or not 1<=dimension<=32 or type(m) is not int or not 2<=m<=32:
            raise ValueError('dimension1..32 and M2..32 required')
        if type(ef_construction) is not int or not m<=ef_construction<=1000:raise ValueError('efConstruction must be M..1000')
        self.dimension=dimension;self.m=m;self.efc=ef_construction;self.heuristic=heuristic
        self.rng=np.random.default_rng(seed);self.vectors=[];self.levels=[];self.graph=[]
        self.entry=None;self.top=-1;self.distance_calls=0
    def vector(self,x):
        x=np.asarray(x,dtype=float)
        if x.shape!=(self.dimension,) or not np.isfinite(x).all() or np.max(np.abs(x))>1e6:raise ValueError('bounded vector of matching dimension required')
        return x.copy()
    def distance(self,a,b):
        self.distance_calls+=1
        return float(np.sum((a-b)**2))
    def layer_search(self,q,entries,ef,level):
        visited=set(entries);candidates=[];best=[]
        for i in sorted(visited):
            d=self.distance(q,self.vectors[i]);heapq.heappush(candidates,(d,i));heapq.heappush(best,(-d,-i))
        while len(best)>ef:heapq.heappop(best)
        while candidates:
            dist,i=heapq.heappop(candidates)
            if len(best)>=ef and dist>-best[0][0]:break
            for j in sorted(self.graph[level][i]):
                if j in visited:continue
                visited.add(j);d=self.distance(q,self.vectors[j]);worst=(-best[0][0],-best[0][1])
                if len(best)<ef or (d,j)<worst:
                    heapq.heappush(candidates,(d,j));heapq.heappush(best,(-d,-j))
                    if len(best)>ef:heapq.heappop(best)
        return [i for _,i in sorted((-d,-i) for d,i in best)]
    def select(self,q,candidates,capacity):
        ordered=sorted(set(candidates),key=lambda i:(self.distance(q,self.vectors[i]),i))
        if not self.heuristic:return ordered[:capacity]
        selected=[];rejected=[]
        for i in ordered:
            if len(selected)>=capacity:break
            dq=self.distance(q,self.vectors[i])
            if all(dq<self.distance(self.vectors[i],self.vectors[j]) for j in selected):selected.append(i)
            else:rejected.append(i)
        # extendCandidates=False; keepPrunedConnections=True.
        selected.extend(rejected[:capacity-len(selected)])
        return selected
    def add(self,x,level=None):
        q=self.vector(x)
        if len(self.vectors)>=500:raise ValueError('teaching capacity500 exceeded')
        if level is None:level=min(12,int(-math.log(1-self.rng.random())/math.log(self.m)))
        if type(level) is not int or not 0<=level<=12:raise ValueError('level must be0..12')
        index=len(self.vectors);self.vectors.append(q);self.levels.append(level)
        while len(self.graph)<=level:self.graph.append({})
        for layer in range(level+1):self.graph[layer][index]=set()
        if self.entry is None:self.entry=index;self.top=level;return index
        entries=[self.entry]
        for layer in range(self.top,level,-1):entries=self.layer_search(q,entries,1,layer)
        for layer in range(min(self.top,level),-1,-1):
            found=self.layer_search(q,entries,self.efc,layer);neighbors=self.select(q,found,self.m)
            self.graph[layer][index].update(neighbors)
            for j in neighbors:
                self.graph[layer][j].add(index)
                capacity=2*self.m if layer==0 else self.m
                if len(self.graph[layer][j])>capacity:
                    self.graph[layer][j]=set(self.select(self.vectors[j],self.graph[layer][j],capacity))
            entries=found
        if level>self.top:self.entry=index;self.top=level
        return index
    def search(self,x,k=5,ef=10):
        q=self.vector(x)
        if type(k) is not int or type(ef) is not int or not 1<=k<=ef<=1000:raise ValueError('1<=k<=ef<=1000 required')
        self.distance_calls=0
        if self.entry is None:return dict(ids=[],distance_calls=0)
        entries=[self.entry]
        for layer in range(self.top,0,-1):entries=self.layer_search(q,entries,1,layer)
        result=self.layer_search(q,entries,ef,0)[:k]
        return dict(ids=result,distance_calls=self.distance_calls)

def fixture():
    rng=np.random.default_rng(31);return rng.normal(size=(120,4)),rng.normal(size=(20,4))

def demo():
    x,queries=fixture();index=HNSW(4);index.distance_calls=0
    for row in x:index.add(row)
    build_calls=index.distance_calls
    exact=[sorted(range(len(x)),key=lambda i:(float(np.sum((q-x[i])**2)),i))[:5] for q in queries]
    rows=[]
    for ef in [5,10,30,120]:
        runs=[index.search(q,5,ef) for q in queries]
        rows.append(dict(ef=ef,recall_at5=float(np.mean([len(set(r['ids'])&set(e))/5 for r,e in zip(runs,exact)])),
                         mean_distance_calls=float(np.mean([r['distance_calls'] for r in runs]))))
    return dict(rows=rows,levels=[len(layer) for layer in index.graph],
                directed_edges=[sum(len(v) for v in layer.values()) for layer in index.graph],
                build_distance_calls=build_calls,
                scope='120 synthetic vectors,20 separate queries; sequential insertion, M4, efConstruction20, level cap12, no deletion/filtering/concurrency.')

if __name__=='__main__':print(json.dumps(demo(),sort_keys=True,allow_nan=False))

The built layers contain [120,29,13,2] nodes. Their outgoing adjacency counts are [765,116,52,2]. A newly selected edge is added in both directions, but later pruning replaces only the pruned node’s outgoing list. Reciprocal edges need not remain reciprocal. That follows the local adjacency update used here; treating every stored edge as permanently undirected would misdescribe this implementation.

Mean recall at five for ef=5,10,30,120 is 0.94,0.99,1,1. Mean distance calls are 38.1,49.3,83.1,134.7. The last value exceeds 120 because upper-layer visits and repeated evaluations across layers count too. Building the graph makes 21,083 distance calls, including neighbor selection and pruning. These are measured calls in this program, not wall-clock speed or claims about hnswlib.

The tests compare a small complete bottom graph with exhaustive search, inspect every layer’s membership and degree, check duplicates and deterministic insertion, and use a three-candidate example where diversification chooses another direction. Search recall reaching 1 on this fixture does not establish exactness for arbitrary graphs; even a large ef cannot recover vertices unreachable from the entry through outgoing links.

Construction quality and query effort are different knobs

M affects connectivity and memory, efConstruction affects insertion exploration, and query ef affects bottom-layer search effort. hnswlib exposes construction through init_index and query effort through set_ef. Its filtering, deletion, update and threading behavior is additional engineering that this teaching implementation omits. hnswlib, init_index and set_ef

Each distance evaluation costs O(D) for D coordinates; heap work and neighbor-selection comparisons add overhead. Stored vectors cost O(ND), with adjacency storage depending on degree caps and layer memberships. The paper’s logarithmic scaling discussion uses geometric assumptions and empirical evidence; it explicitly distinguishes an ideal Delaunay argument from the actual approximate graph. It is not an unconditional worst-case O(log N) guarantee for arbitrary high-dimensional data. Search may visit a linear number of stored points. HNSW, section 4.2

Choose construction and search settings on development queries, then measure held-out recall, latency, memory and update cost. Test clustered data, duplicates, insertion order and distribution shifts. Raising query ef can spend more effort in the graph that exists; it does not rebuild missing useful links. Preserve the vector version and metric used to build the index.

Follow the queue and the edge

  1. With M=4 and no level cap, what fraction of nodes is expected to reach layer 2?

Answer: 4⁻²=1/16. The expected count in 120 nodes is 7.5, but an individual random construction need not equal the expectation; this seed produces 13.

  1. Why can ef=120 require more than 120 distance calls in a 120-vector index?

Answer: ef bounds the retained result set at a layer. Distances are also computed during upper-layer routing, and a node can be evaluated again at a lower layer. Our mean is 134.7 across all query layers.

  1. Query point is [0,0]; candidate points are [1,0], [1.1,0], [0,2]. With capacity two, how does the heuristic differ from nearest-two selection?

Answer: It first keeps [1,0]. The point [1.1,0] is closer to that selected neighbor than to the query, so it is deferred. [0,2] offers a different direction and is accepted. Simple nearest-two selection takes both points on the positive horizontal axis.

  1. Does a large ef guarantee exact search? Propose a revealing test.

Answer: No. An unreachable component cannot be visited, and the early-stop rule is not a global lower bound. Compare against exhaustive results on adversarial clusters and insertion orders, inspect reachability, and vary construction parameters separately from query ef.

Keep the pseudocode version and options visible

The v4 algorithms expose choices that a short “graph plus greedy search” summary hides: entry replacement, construction breadth, result-heap bounds, neighbor diversification and pruning. Our level cap, deterministic tie rule, finite input limits and omitted update features are explicit. The small program demonstrates real incremental construction and querying, not the paper’s performance benchmarks or a complete vector database.

Make a prediction, then check

Does ef=30 mean exactly30 distance evaluations?

Choose one answer

Learning objectives

  • Trace insertion, neighbor diversification, layer search and distinct build/query budgets.
  • Run the original example and diagnose its approximation error.

Prerequisites & connections

Explore related knowledge →

References

  1. Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs — arXiv v4
    Yu. A. Malkov; D. A. Yashunin · 2018
  2. hnswlib README — commit d9b3608c83d83b46c96e25088cb1d729b29dcfe9
    nmslib/hnswlib contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author. Viewed physical PDF4/5/7: algorithms1–5, level sampling, neighbor heuristic, construction/search parameters and conditional complexity discussion. v1 PDF5 separately compared; implementation follows v4 with declared limits. Read opening25 lines and init_index/set_ef/knn_query excerpts; build versus query controls and filtering behavior. License first8 lines identify Apache2.0; no upstream code copied or run. 6 paired equations and four explained exercises. Checked real incremental hierarchy, layer membership and degrees, diversified neighbor selection, complete small graph against exhaustive search, duplicate ties and query distance calls.

  • Checked real incremental hierarchy, layer membership and degrees, diversified neighbor selection, complete small graph against exhaustive search, duplicate ties and query distance calls.
  • Four computed SVG variants per topic;9 numeric/geometry tests and24 responsive cases passed. Eight selected final captures directly viewed. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.