HNSW Python Search: 99% Recall on Held-Out Words

Build HNSW Python vector search, compare it with hnswlib and exact search, and measure recall against distance computations on held-out words.

Cover Image for HNSW Python Search: 99% Recall on Held-Out Words

You've trained a set of word vectors and want to use them to find related words. To answer a query such as "computer", the simplest search compares its vector with every word in the collection. That works, but adding more words means more comparisons on every query. A graph index can follow connections between nearby vectors to reach promising candidates. You can then measure how much work that route saves and which neighbours it misses.

Vectors from the preceding tutorial provide a test of that search route. Our Python HNSW reaches 99% recall@10 while evaluating 1.86% of indexed vectors. We use 100 held-out query words. Comparisons with exhaustive search and hnswlib measure its work and overhead. On Gaussian data, a KD-tree scans every point at 50 and 100 dimensions.

Quick Win

Open In Colab

Start with the library version. The saved file contains word strings in exactly the same row order as the 100-dimensional matrix. We normalise the matrix because the tutorial uses cosine similarity, then choose hnswlib's squared Euclidean distance. Those rankings agree for unit vectors.

The notebook accepts an uploaded file from the word2vec notebook. If that file is absent, it recreates the NumPy embeddings from the pinned corpus. The compact example below downloads the frozen tutorial matrix.

Actual HNSW distance evaluations progress across three layers of a two-dimensional example.

import io
import urllib.request
import numpy as np
import hnswlib

url = "https://raw.githubusercontent.com/zhubarb/sesen_ai_ml_tutorials/main/notebooks/nlp/data/word2vec_vectors.npz"
raw = urllib.request.urlopen(url, timeout=60).read()
data = np.load(io.BytesIO(raw))
vectors, words = data["vectors"], data["vocab"]
vectors = vectors / np.maximum(np.linalg.norm(vectors, axis=1, keepdims=True), 1e-12)
index = hnswlib.Index(space="l2", dim=vectors.shape[1])
index.init_index(max_elements=len(vectors), M=12, ef_construction=80, random_seed=110)
index.set_num_threads(1)
index.add_items(vectors, np.arange(len(vectors)))
index.set_ef(40)
word_id = np.flatnonzero(words == "computer")[0]
ids, distances = index.knn_query(vectors[word_id], k=6)
print(words[ids[0]][words[ids[0]] != "computer"][:5])

The source word is removed from the displayed neighbour list. That display convention differs from the benchmark below, where the query words are absent from the index altogether. Including a stored vector as its own nearest neighbour would make part of the scored retrieval task trivial.

The library example builds an index over the entire saved vocabulary. The scored experiment reserves 100 words, leaving 21,581 indexed vectors. The matrix comes from one small word2vec training run, so high index recall establishes fidelity to that matrix's exact neighbours. It does not establish that those neighbours satisfy a user's semantic intent.

For unit vectors, cosine similarity and squared Euclidean distance obey:

∥x−q∥2=2−2x⊤q.\|x-q\|^2=2-2x^\top q.

Exact cosine search can consequently use a matrix multiplication followed by a top-k selection. It is simple, easy to check and often competitive on modest datasets. It also supplies the ground truth needed to score an approximate index.

scores = queries @ vectors.T
exact_ids = np.argsort(-scores, axis=1)[:, :10]

This code sorts the full candidate list. argpartition can select a short list more cheaply, followed by a sort of those selected candidates. The tutorial's timing uses the explicit full-sort baseline shown above, so a production exact implementation may be faster.

A KD-tree partitions space with axis-aligned splits. Exact search can skip a branch when the query's distance to its bounding region exceeds the current tenth-best neighbour distance. That pruning works well when a low-dimensional query lies close to relatively few regions.

As dimension grows, the search often cannot reject most branches. We measure this on 4,000 independent Gaussian points and 100 independent Gaussian queries at each dimension. Scikit-learn's KDTree.get_n_calls() supplies the distance count, and SciPy's cKDTree independently verifies the returned exact distances. SciPy does not expose this count, so assigning the instrumentation to cKDTree would misdescribe the experiment.

An exact KD-tree evaluates about 2% of points at two dimensions, 70% at ten, and all points at fifty and one hundred.

DimensionFraction of points evaluated
22.02%
1069.65%
50100.00%
100100.00%

These measurements are specific to the distribution, query positions, leaf size and neighbour count. Correlated embeddings can have lower intrinsic dimension than their matrix width suggests. The experiment demonstrates a failure regime for exact pruning, rather than a universal threshold after which every tree fails.

Graph Routing

HNSW stores neighbours as graph edges. Search starts at an entry point and follows edges to points closer to the query. A graph with only short local edges can trap a greedy route in the wrong neighbourhood. Connections spanning different regions provide alternative routes.

The hierarchy places a diminishing subset of points on successive upper layers. Every point appears at the base; a few also appear above it. The upper graph supplies sparse routing across the collection, while the base explores a wider candidate frontier to obtain the final neighbours.

Search moves through sparse upper layers and expands a candidate frontier at the base.

We draw a node's highest level with:

L=⌊−log⁡Ulog⁡M⌋,U∼Uniform⁡(0,1).L=\left\lfloor\frac{-\log U}{\log M}\right\rfloor, \qquad U\sim\operatorname{Uniform}(0,1).

The probability of appearing at level one or higher is approximately 1/M1/M, and at level two or higher approximately 1/M21/M^2. This is a geometric thinning rule. It creates a small routing graph without requiring an explicit clustering stage.

The recorded index has layer sizes 21,581, 1,818, 155, 6, 1 and 1. Random assignment creates variation around the expected counts. The top two layers happen to contain one point each, so those layers cannot move horizontally but still define entry descent.

The upper-layer search is greedy. It evaluates adjacent nodes and moves whenever one is closer to the query. It repeats until no adjacent point improves the distance. Descending a layer keeps the best point found so far as the next entry.

At the base, a single greedy route is too restrictive. The algorithm keeps two heaps. A min-heap holds candidates to explore, ordered from closest to farthest. A max-heap holds the best retained results, allowing the worst retained distance to be checked quickly.

Python's heapq supplies a min-heap. Negating distances makes the result heap behave as a max-heap. The search also keeps a visited set to avoid exploring the same node repeatedly through different edges.

distance, node = heapq.heappop(candidates)
if len(results) >= ef and distance > -results[0][0]:
    break
for other in graph[node]:
    if other in visited:
        continue
    visited.add(other)
    d = squared_distance(query, vectors[other])
    if len(results) < ef or d < -results[0][0]:
        heapq.heappush(candidates, (d, other))
        heapq.heappush(results, (-d, other))
        if len(results) > ef:
            heapq.heappop(results)

The notebook contains the complete class, including upper-layer descent, insertion and neighbour pruning. ef_search bounds the retained search frontier, rather than the total number of distances computed. A search with ef_search=40 can evaluate several hundred nodes.

Increasing this frontier generally improves recall because more routes can remain eligible. The cost is additional distances, heap operations and adjacency traversal. The exact count depends on graph structure and the query, so it is measured instead of inferred from the parameter value.

The implementation caches query-to-node distances across layers. A node encountered at the top and again at the base therefore counts as one vector distance evaluation. Graph traversal still costs work on both encounters. Our distance-budget metric captures numerical distance work, while the latency measurement includes the rest of the implementation.

Graph Construction

Insertion searches from the current entry point down to the new point's highest layer. At each occupied layer it searches with the wider ef_construction frontier, selects neighbours and adds connections in both directions. If the new point reaches a higher level than the existing entry, it becomes the entry point.

The neighbour-selection heuristic matters. Keeping only the nearest available points can fill all edges with one dense local group. HNSW instead favours candidates that add a distinct route. Our selection rejects a candidate when it is closer to an already selected neighbour than to the point being connected.

chosen = []
for centre_distance, candidate in sorted(candidates):
    if all(squared_distance(vectors[candidate], vectors[j]) >= centre_distance
           for j in chosen):
        chosen.append(candidate)
        if len(chosen) == limit:
            break

This heuristic encourages diversity of directions, subject to the candidates found by construction search. It does not guarantee connectivity or optimal routing. Candidate quality, insertion order and the edge limit still affect the result.

The tutorial uses M=12 and ef_construction=80. New nodes select at most 12 neighbours per occupied layer. Reverse connections can grow an existing base-layer list to 24, while upper-layer lists are pruned at 12. These different limits follow the common HNSW distinction between the denser base and upper routing layers.

Construction took 65.8 seconds in the final held-out-query run. An earlier full-vocabulary run and the final run both fit the compute ceiling. Construction time depends on the collection, parameter settings and hardware; the recorded time describes this development CPU.

The class stores Python lists and dictionaries, making its operations easy to inspect. It omits deletion, persistence, concurrent mutation, metadata filtering and memory-efficient adjacency storage. Those features change the engineering requirements of a deployed vector index substantially.

Recall and Work

Recall@10 is the fraction of exact top-ten neighbour IDs returned by approximate search. We compute the exact list independently for every held-out query, then average the overlap fractions across 100 queries. Equal-distance ties can require an explicit tie policy. The scored floating-point embedding results have no material tie problem.

Recall rises with distance budget, while Python and hnswlib give similar recall at matched search widths.

ef_searchPython recall@10Distance budgethnswlib recall@10
1089.3%0.84%89.9%
2096.6%1.23%96.8%
4099.0%1.86%99.0%
8099.9%2.90%99.9%
160100.0%4.46%100.0%
320100.0%6.83%100.0%

The two indexes have matched principal parameters but different random level draws and implementation details. Similar recall curves check the educational implementation at this scale. They do not imply that its graph is identical to hnswlib's graph.

The planned 90%-recall result at a 5% distance budget holds here. The stronger observed result reaches 99% with less than 2%. A larger collection, more diverse queries or better-trained embeddings can change that curve. The relatively weak one-epoch matrix from the word2vec tutorial is part of this experimental setting.

Probe-word neighbour tables supply a readable cross-check. They use indexed probe words, remove the source word from display and search at ef_search=80. That protocol is stated separately from the held-out benchmark to avoid blending the two tasks.

Exact and approximate neighbour words agree for the displayed probes.

Timing

Reducing vector-distance work does not automatically reduce latency in Python. Each small NumPy distance call, heap update and dictionary access has overhead. A large exact matrix multiplication can use efficient contiguous numerical operations even though it touches every vector.

hnswlib is much faster than the educational Python graph, while batched vectorised exact search remains competitive with Python at this collection size.

At ef_search=40, the measured Python index handles about 817 queries per second, hnswlib about 18,881, and the batched exact baseline about 1,553. These are single timing runs over 100 queries, using one thread for hnswlib and single-threaded numerical libraries. They establish the order of magnitude in this run, with ordinary timing noise.

The exact baseline processes a batch of queries, while the Python class loops over queries. Batching favours matrix multiplication. A latency-sensitive application should also measure single-query response time, warm-up effects, different batch sizes and a larger query sample.

For this collection, choosing the educational graph solely from its distance-count reduction would select a slower implementation than vectorised exact search at the 99%-recall setting. The optimised library converts the algorithmic reduction into a substantial timing advantage. The notebook keeps those two conclusions separate.

Foundations

Malkov and Yashunin's HNSW paper combines a proximity graph, probabilistic hierarchy and neighbour-selection heuristic. Its construction algorithm inserts a point by searching existing layers, selecting neighbours and updating affected connections. The query algorithm routes greedily through upper layers and performs a wider search at the base.

The hierarchy resembles the probabilistic levels in a skip list. Sparse high levels allow larger movements, while dense lower levels resolve nearby candidates. Vector geometry replaces the ordered-key relation of a skip list, so graph quality and local minima become part of the analysis.

The neighbour heuristic adds a useful constraint beyond taking the nearest M candidates. A point whose closest candidates all lie in one local group benefits from retaining a route toward another region. Our select method implements the candidate-diversification test, but omits some optional extensions and production optimisations.

The hnswlib repository documents the practical parameters and exposes an optimised implementation. M controls graph connections, construction width affects the quality and cost of the built graph, and search width adjusts recall after construction. Increasing search width cannot entirely repair a graph built with poor candidates or too few useful connections.

Exact spatial trees solve a different problem because they preserve exactness through geometric bounds. Our Gaussian experiment makes their distance work visible, while ANN-Benchmarks provides a broader setting for comparing approximate indexes across datasets and recall targets. A single tutorial matrix cannot replace that diversity.

The experiment also separates representation error from index error. Word2vec's analogy weakness belongs to the representation. Missing one of that representation's exact nearest neighbours belongs to the index. A retrieval system can suffer both, so improving recall against an exact index may leave the end task unchanged.

The hybrid retrieval tutorial supplies the next evaluation layer by comparing lexical and vector scores against relevance. The index built here can accelerate vector candidate generation, after which a relevance evaluation determines whether those candidates help.

The paper describes the index as:

“fully graph-based”

That description identifies the routing structure. Our implementation's dictionaries store adjacency lists at each layer, so a search reaches a vector through its connections rather than a separate spatial partition. The vectors themselves remain necessary for evaluating candidates.

A small geometric example explains the neighbour-selection rule. Put the point being inserted at the origin and consider candidate A at (1, 0) and candidate B at (1.1, 0). After selecting A, B contributes a nearby route already covered by A: their mutual squared distance is 0.01, smaller than B's squared distance of 1.21 from the origin. The diversity test rejects B. A candidate C at (0, 1.2) has squared distance 1.44 from the origin and 2.44 from A, so it survives that test and supplies another direction.

Selection operates on the candidates discovered during insertion. If construction search never reaches C's region, the heuristic cannot select it. Wider construction search can improve the available choices, while increasing M allows more of those choices to remain connected. These are separate changes to the graph built before a query arrives. The search-width sweep then explores one fixed graph and changes only its query-time frontier.

The base search stopping rule also deserves a careful reading. It stops when the closest remaining frontier candidate is farther away than the worst retained result, once the result heap is full. That candidate may have an unseen neighbour closer to the query. Graph edges provide no exact lower bound on all reachable distances, so this termination rule trades work for recall. It cannot certify the exact top ten the way an exhaustive scan can.

Our query procedure can be summarised as the following adaptation of the paper's search:

entry = highest-layer entry point
for each upper layer, descending:
    entry = greedy improvement from entry
results = base-layer search(entry, ef_search)
return the closest k retained results

Each vector belongs to every layer up to its sampled highest level. With the level law used here, its expected number of memberships is the geometric sum 1 + 1/M + 1/M**2 + ..., or M/(M - 1). Most memberships therefore sit at the base. The degree limits bound adjacency storage per membership, but Python object overhead and temporary construction candidates add costs beyond that simple edge count.

Interactive Tools

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions