Search without checking everything: a vector index (HNSW) from scratch

For two weeks I built the thing that reads text — a GPT-2 forward pass, then a KV-cache to make it
fast. This week I built the thing that finds it. The “retrieval” in retrieval-augmented generation
is, underneath, one humble operation: given a query vector, find its nearest neighbours among
millions. Do it by brute force and you compare against every single one. So I built HNSW — an
approximate index that finds nearly the same answers while looking at a tiny fraction of the data —
from scratch, and pointed it at GPT-2’s own token embeddings.

What I built

An HNSW index (numpy + a couple of heaps) with build and search, indexing GPT-2’s token
embeddings so a query returns semantically-related tokens:

 ' king'   -> ' King', ' leader', ' president', ' god', ' army'
 ' France' -> ' French', ' Germany', ' Europe', ' England', ' Britain'
 ' three'  -> ' four', ' five', ' six', ' seven', ' nine'

Over 4,000 vectors it hits 95% recall@10 against exact search while comparing against ~770
vectors instead of all 4,000. The accuracy is a dial you turn.

The concepts that made it work

  • Search is a walk on a graph. Pre-connect each vector to its near neighbours, then “walk
    downhill”: from an entry point, keep hopping to whichever neighbour is closer to the query until
    none is. No index scan — just a greedy stroll through a few dozen nodes.
  • A hierarchy makes the walk logarithmic. Most nodes live only on the bottom layer (which holds
    everything); a lucky few also sit on sparse upper layers that act like express lanes. Search starts
    up top for big jumps, then drops down for local precision. It’s a skip-list, generalised to a graph.
  • Recall vs latency is one knob. A single parameter, ef (the search beam width), trades accuracy
    for comparisons: ef=10 gave me 80% recall for ~230 comparisons; ef=256 gave 99.8% for ~2,000.
    The whole accuracy/speed curve, in one dial — which is exactly how you tune a real vector database.
  • Measure comparisons, not the clock. My Python HNSW is actually slower in wall-clock than
    numpy’s brute force at this size — because brute force is a single BLAS matmul, ~100× more efficient
    per comparison than an interpreted graph walk. The honest, scale-independent win is fewer
    comparisons
    (770 vs 4,000); that only turns into a wall-clock win at large N and in compiled
    libraries. A good reminder to benchmark the algorithm, not the implementation.

The thing that bit me

My first index capped out at 73% recall — and turning ef up did nothing. That’s a tell: if more
searching doesn’t help, the graph is broken, not the search. The cause was the data. I’d indexed
GPT-2’s first 2,000 tokens, which include byte-level and rare tokens whose embeddings are hubs —
vectors that sit close to almost everything. A hub shows up in everyone’s neighbour list, the graph
collapses toward it, and greedy search keeps getting sucked into the same dead end. Skipping those
tokens lifted recall to 95% instantly. High-dimensional nearest-neighbour search is littered with
these geometry traps (hubness, anisotropy); the cleverest index is still only as good as the vectors
you feed it.

Tradeoffs & the road not taken

  • Simple neighbour selection. I connect each node to its M closest neighbours. The HNSW paper’s
    Algorithm 4 keeps diverse neighbours instead, which raises recall at the same degree — a clean
    next improvement I left on the table.
  • Build it, don’t persist it. The index lives in memory and is rebuilt each run; real systems
    serialise it and add/delete incrementally.
  • Pure Python, small N. Deliberately — this is to understand the mechanism, not to beat FAISS.

Where this sits in the system

This is the R in RAG. A retrieval-augmented pipeline embeds your documents, loads the vectors into
an index like this, and at query time pulls the nearest chunks to hand the model as context. Weeks 1–2
built the model that reads the context; this week built the thing that finds it. Next week I wire them
together into a RAG pipeline — and face the harder question underneath all of this: how do you actually
measure whether the retrieval helped? Same spine as always — one system, revealed a layer at a time.


Part of a series building a modern AI stack from scratch, told visually. (Last time: making the next token cheap with a KV-cache.)