HNSW from scratch: vector search in about 100 lines of Python

· Tech

Imagine a help centre with a million articles.

A user types: “How do I cancel my subscription?”

The perfect answer exists. It’s titled “End Your Membership Today”. It doesn’t contain the word cancel, or the word subscription.

Keyword search misses it. Embeddings find it, because they turn meaning into geometry: similar ideas land close together.

But that creates a new problem. To find the closest vectors, you’d compare the question with all one million of them. For every query. Every second.

HNSW (Hierarchical Navigable Small World) is how vector databases avoid that. Let’s build one, step by step, and see how little work a query really needs.

Prefer pictures first? I explain the same idea visually in this video:

The idea in one picture

Think of a road network.

To drive somewhere, you don’t explore every street. You take the highway towards the right region, exit onto a main road, then find the exact street.

HNSW stores vectors the same way, in layers:

A search starts at the top, hops greedily towards the query, and drops a layer whenever it can’t get any closer.

Step 1: Setup and distance

The whole index is a list of vectors and, for each layer, a dictionary from each vector to its neighbours.

class HNSW:
    def __init__(self, M=16, ef_construction=100, seed=0):
        self.M, self.M0 = M, 2 * M          # max links per node; layer 0 gets twice as many
        self.ef_construction = ef_construction
        self.mL = 1 / math.log(M)           # makes each layer up roughly M times sparser
        self.rng = random.Random(seed)
        self.vectors, self.layers = [], []  # layers[l] = {node: [neighbour nodes]}
        self.entry, self.top = None, -1
        self.distance_calls = 0

We store every vector at length 1. Then the cosine distance is just one minus a dot product.

def _dist(self, q, node):               # cosine distance on unit vectors
    self.distance_calls += 1
    return 1.0 - float(self.vectors[node] @ q)

The counter is how we’ll measure the work a search does.

Step 2: The biased coin

Which vectors get to be highways? It’s random.

Each new vector flips a biased coin. Heads, with probability about 1 in M, means it’s promoted a layer. It keeps flipping until it gets tails.

That’s what mL in the setup is for:

def _random_level(self):                # the biased coin: most nodes stay on layer 0
    return int(-math.log(1.0 - self.rng.random()) * self.mL)

With M = 16 and 10,000 vectors, my layers came out as 10,000 → 587 → 33 → 4.

Most vectors are local streets. A rare few become the highways.

Step 3: Search one layer

This is the engine. It’s a beam search with two heaps:

def _search_layer(self, q, entries, ef, layer):
    visited = set(entries)
    candidates = [(self._dist(q, e), e) for e in entries]
    heapq.heapify(candidates)
    best = [(-d, e) for d, e in candidates]
    heapq.heapify(best)
    while candidates:
        d, node = heapq.heappop(candidates)
        if d > -best[0][0]:
            break                       # nothing left to explore can beat our worst result
        for n in self.layers[layer][node]:
            if n in visited:
                continue
            visited.add(n)
            dn = self._dist(q, n)
            if len(best) < ef or dn < -best[0][0]:
                heapq.heappush(candidates, (dn, n))
                heapq.heappush(best, (-dn, n))
                if len(best) > ef:
                    heapq.heappop(best)
    return sorted((-d, e) for d, e in best)

ef is the width of the beam. With ef = 1, it’s a plain greedy walk. That’s all we need on the highways.

Step 4: Insert

To add a vector:

  1. Flip the coin to pick its top layer.
  2. Above that layer, take one greedy hop per layer: highway driving.
  3. From its top layer down, beam-search with a wide beam (ef_construction), and link it to the best neighbours.
  4. Link back the other way too. If a node now has too many links, re-pick them.
def add(self, vector):
    q = np.asarray(vector, dtype=np.float32)
    q /= np.linalg.norm(q)
    node = len(self.vectors)
    self.vectors.append(q)
    level = self._random_level()
    while len(self.layers) <= level:
        self.layers.append({})
    for layer in range(level + 1):
        self.layers[layer][node] = []
    if self.entry is None:
        self.entry, self.top = node, level
        return
    entries = [self.entry]
    for layer in range(self.top, level, -1):       # highways: one greedy hop per layer
        entries = [self._search_layer(q, entries, 1, layer)[0][1]]
    for layer in range(min(level, self.top), -1, -1):
        found = self._search_layer(q, entries, self.ef_construction, layer)
        limit = self.M0 if layer == 0 else self.M
        self.layers[layer][node] = self._select(found, self.M)
        for n in self.layers[layer][node]:         # links go both ways
            links = self.layers[layer][n]
            links.append(node)
            if len(links) > limit:                 # too many: re-pick with the same rule
                near = sorted((1.0 - float(self.vectors[x] @ self.vectors[n]), x) for x in links)
                links[:] = self._select(near, limit)
        entries = [n for _, n in found]
    if level > self.top:
        self.entry, self.top = node, level

Layer 0 allows twice as many links (M0 = 2 * M). It’s where the precise work happens.

The bug that taught me the most

My first version linked each vector to its M closest neighbours. Simple, and obviously right.

Even with a wide beam (ef = 100), recall topped out at 92%.

The reason: real embeddings come in clusters, like topics. If every link points to the closest neighbours, each cluster links only to itself. It becomes an island. A search that starts on the wrong island can never leave.

The HNSW paper has a fix. Pick a neighbour only if it’s closer to you than to any neighbour you’ve already picked.

Think of it like making friends in a new city. Sixteen friends on your own street don’t help you get across town. A few friends in other neighbourhoods do.

def _select(self, candidates, m):
    chosen = []
    for d, c in candidates:                         # (distance, node), nearest first
        if all(d < 1.0 - float(self.vectors[c] @ self.vectors[s]) for s in chosen):
            chosen.append(c)
            if len(chosen) == m:
                break
    return chosen

Same data, same settings. Recall went from 92% to 100%.

Searching is the insert without the linking: highways first, then a wide beam on the local streets.

def search(self, vector, k=10, ef=50):
    q = np.asarray(vector, dtype=np.float32)
    q /= np.linalg.norm(q)
    entries = [self.entry]
    for layer in range(self.top, 0, -1):           # highway, main road...
        entries = [self._search_layer(q, entries, 1, layer)[0][1]]
    return [n for _, n in self._search_layer(q, entries, max(ef, k), 0)[:k]]  # ...local streets

How much work did we save?

I built an index of 10,000 vectors (64 dimensions, grouped into 50 topics), then ran 200 queries. Brute force compares every query with all 10,000 vectors.

ef (search beam) Recall@10 Distances per query
10 95.9% 193
20 99.2% 255
50 100.0% 352
100 100.0% 449

At ef = 50, every query found its true 10 nearest neighbours, while computing 352 distances instead of 10,000. That’s 3.5% of the work.

The gap grows with size. Brute force grows with every vector you add. HNSW’s work grows roughly with the logarithm.

One honest caveat: this is pure Python, so it isn’t fast in seconds. Libraries like hnswlib and FAISS run the same algorithm in optimised C++. What carries over is the work saved.

The three knobs

Wider beam, better answers, more work. It’s a dial, not a switch.

The full code

All of it in one file, with the demo that produced the table above. You only need NumPy: save it as hnsw.py and run python hnsw.py.

"""HNSW (Hierarchical Navigable Small World) from scratch, for learning. Run: python hnsw.py"""
import heapq
import math
import random

import numpy as np


class HNSW:
    def __init__(self, M=16, ef_construction=100, seed=0):
        self.M, self.M0 = M, 2 * M          # max links per node; layer 0 gets twice as many
        self.ef_construction = ef_construction
        self.mL = 1 / math.log(M)           # makes each layer up roughly M times sparser
        self.rng = random.Random(seed)
        self.vectors, self.layers = [], []  # layers[l] = {node: [neighbour nodes]}
        self.entry, self.top = None, -1
        self.distance_calls = 0

    def _dist(self, q, node):               # cosine distance on unit vectors
        self.distance_calls += 1
        return 1.0 - float(self.vectors[node] @ q)

    def _random_level(self):                # the biased coin: most nodes stay on layer 0
        return int(-math.log(1.0 - self.rng.random()) * self.mL)

    def _search_layer(self, q, entries, ef, layer):
        """Beam search on one layer: returns up to ef (distance, node) pairs, nearest first."""
        visited = set(entries)
        candidates = [(self._dist(q, e), e) for e in entries]      # min-heap: what to explore
        heapq.heapify(candidates)
        best = [(-d, e) for d, e in candidates]                    # max-heap: the ef closest
        heapq.heapify(best)
        while candidates:
            d, node = heapq.heappop(candidates)
            if d > -best[0][0]:
                break                       # nothing left to explore can beat our worst result
            for n in self.layers[layer][node]:
                if n in visited:
                    continue
                visited.add(n)
                dn = self._dist(q, n)
                if len(best) < ef or dn < -best[0][0]:
                    heapq.heappush(candidates, (dn, n))
                    heapq.heappush(best, (-dn, n))
                    if len(best) > ef:
                        heapq.heappop(best)
        return sorted((-d, e) for d, e in best)

    def _select(self, candidates, m):
        """The paper's heuristic: skip a candidate that sits closer to a neighbour we already
        picked than to us. That keeps a few long links between clusters, so a search can't get
        stuck on an island."""
        chosen = []
        for d, c in candidates:                         # (distance, node), nearest first
            if all(d < 1.0 - float(self.vectors[c] @ self.vectors[s]) for s in chosen):
                chosen.append(c)
                if len(chosen) == m:
                    break
        return chosen

    def add(self, vector):
        q = np.asarray(vector, dtype=np.float32)
        q /= np.linalg.norm(q)
        node = len(self.vectors)
        self.vectors.append(q)
        level = self._random_level()
        while len(self.layers) <= level:
            self.layers.append({})
        for layer in range(level + 1):
            self.layers[layer][node] = []
        if self.entry is None:
            self.entry, self.top = node, level
            return
        entries = [self.entry]
        for layer in range(self.top, level, -1):       # highways: one greedy hop per layer
            entries = [self._search_layer(q, entries, 1, layer)[0][1]]
        for layer in range(min(level, self.top), -1, -1):
            found = self._search_layer(q, entries, self.ef_construction, layer)
            limit = self.M0 if layer == 0 else self.M
            self.layers[layer][node] = self._select(found, self.M)
            for n in self.layers[layer][node]:         # links go both ways
                links = self.layers[layer][n]
                links.append(node)
                if len(links) > limit:                 # too many: re-pick with the same rule
                    near = sorted((1.0 - float(self.vectors[x] @ self.vectors[n]), x) for x in links)
                    links[:] = self._select(near, limit)
            entries = [n for _, n in found]
        if level > self.top:
            self.entry, self.top = node, level

    def search(self, vector, k=10, ef=50):
        q = np.asarray(vector, dtype=np.float32)
        q /= np.linalg.norm(q)
        entries = [self.entry]
        for layer in range(self.top, 0, -1):           # highway, main road...
            entries = [self._search_layer(q, entries, 1, layer)[0][1]]
        return [n for _, n in self._search_layer(q, entries, max(ef, k), 0)[:k]]  # ...local streets


if __name__ == "__main__":
    import time

    rng = np.random.default_rng(1)
    n, dim, topics = 10_000, 64, 50
    centres = rng.normal(size=(topics, dim))           # fake "embeddings": 50 topics, with noise
    data = centres[rng.integers(topics, size=n)] + 0.6 * rng.normal(size=(n, dim))
    unit = data / np.linalg.norm(data, axis=1, keepdims=True)

    index = HNSW(M=16, ef_construction=100)
    t = time.time()
    for v in data:
        index.add(v)
    print(f"built {n} vectors in {time.time() - t:.1f}s, {index.top + 1} layers, "
          f"layer sizes {[len(layer) for layer in index.layers]}")

    queries = data[rng.choice(n, 200, replace=False)] + 0.3 * rng.normal(size=(200, dim))
    qunit = queries / np.linalg.norm(queries, axis=1, keepdims=True)
    truth = np.argsort(-(qunit @ unit.T), axis=1)[:, :10]  # brute force: every distance
    for ef in (10, 20, 50, 100):
        index.distance_calls, hits = 0, 0
        for q, true in zip(queries, truth):
            hits += len(set(index.search(q, k=10, ef=ef)) & set(true))
        print(f"ef={ef:3d}: recall@10 {hits / (10 * len(queries)):.1%}, "
              f"{index.distance_calls / len(queries):,.0f} distances per query (brute force: {n:,})")

Recap

That’s HNSW. The hard part of vector search isn’t defining nearest. It’s finding it fast, for every user, every second.

Paper: Malkov and Yashunin, Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs.