33. Vector database I: HNSW
Why this layer exists
Chapter 32’s search scores every stored vector: multiply-adds per query. A million memories at the fixture’s width of 1,024 is multiply-adds for every recall the agent makes, and a memory service recalls on every turn. On straylight, Flat over 100,000 vectors of width 128 takes 7.387 ms at the median of 1,000 queries, which is the number the rest of this chapter is trying to beat and the number every claim here is measured against.
What can be given up is certainty. An approximate nearest-neighbour index may fail to return one of the true nearest in exchange for touching a small fraction of the vectors. The loss is measured exactly as chapter 32 defined it: recall@k against Flat’s answer, whose ties are broken by ID so that the baseline is a function of the data. The index is paid for in two currencies at once, recall and the distance computations per query, and a single number for either is meaningless without the other; the tables below pair them.
The failure that makes this chapter different from the last is silence. A wrong exact index returns wrong scores, and a test finds it. A wrong graph returns results with correct scores, in the right order, from a graph that is merely worse than it should be, and nothing in the output says so. Hence the chapter transcribes the paper’s five algorithms with their line numbers, maps each to the Go that implements it, and tests the graph against the exact index; and hence the lab asks you to write the graph from the paper, against the same tests.
Mechanism
Greedy search on a proximity graph, and where it fails
Make the stored vectors the nodes of a graph and join each to some of its near neighbours. Greedy routing from an enter point towards a query computes for and each of its neighbours, moves to the nearest, and stops when the current node is nearer to than all of its neighbours. Each move strictly decreases over a finite set, so the walk terminates; after moves it has computed at most times the node degree distances, and has not looked at the rest of the corpus, which is the point.
The walk stops at a local minimum of over the graph. That is the true nearest neighbour only if the graph has the right edges. Two clusters and , each node joined only to its near neighbours inside its own cluster, and a query in entered from a node of : the walk descends through to the node of nearest the query and stops, since every neighbour of that node is in and farther. The edge that would cross to is missing, and nothing in the walk can tell. The paper’s complexity analysis assumes the graph is the exact Delaunay graph, for which greedy routing does reach the nearest neighbour; an index with a bounded number of links per node is an approximation of it, and the part of the algorithm that is not greedy, the beam of width on layer 0, is what makes up for the missing edges.
The Navigable Small World graph of Malkov, Ponomarenko, Logvinov and Krylov (2014) builds one graph by inserting the elements in random order, each joined bidirectionally to its nearest among those already inserted. The paper describes why that routes well: links made early, when the graph is small, become bridges between the hubs that keep it connected, and so the number of hops grows logarithmically. It also describes why it is not enough: the number of distance computations is about the product of the hops and the degree of the nodes on the path, and the degree on the path also grows logarithmically because the walk keeps passing through the same hubs, so the cost is polylogarithmic. Malkov and Yashunin’s observation is that long links and short links do different jobs, so the structure should keep them apart: the long links on sparse upper layers, which a walk uses to cross the space, and the short links on the full lower layers, which it uses to home in. Every element is in layer 0; each is in higher layers with a probability that falls off geometrically, as in a skip list, where the linked list is replaced by a proximity graph.
The level law
Algorithm 1, line 4, draws the top layer of a new element:
For an integer , exactly when , so
the last step because for . The paper’s “simple choice for the optimal ” is , and then : the share of elements that reach layer falls by a factor per layer. That is the skip list’s , as the paper says, and DefaultParams sets ML to it.
The expected top layer follows from writing and taking expectations term by term:
An element is in layers, so the expected number of layers per element is : 1.0667 at . The paper’s equation (1) writes the same expectation as : an equality that drops the floor, and as an equality it is false, 1.3607 at against the exact 1.0667. With the floor restored what holds is an inequality. Since and ,
which at is . The bound holds and is loose by the floor, which discards the fractional part of an exponential variable and so lands on the geometric law above; the exact value is the first. A Monte Carlo draw of 2,000,000 levels at gave a mean of 0.06675 against (facts.py, talos), and TestLevelDistribution draws 200,000 through the code’s own generator:
=== RUN TestLevelDistribution
hnsw_test.go:252: 200000 draws at M=16, max level 5
hnsw_test.go:253: P(level >= 1) = 0.0620 (1/16 = 0.0625)
hnsw_test.go:254: P(level >= 2) = 0.00389 (1/256 = 0.00391)
hnsw_test.go:255: mean level = 0.0662 (1/15 = 0.0667)
--- PASS: TestLevelDistribution (0.00s)
PASS
ok aec/internal/vecdb 0.007s
(talos). The top layer of elements is the largest level drawn. Level is empty when none of the draws reaches it:
using for small . The expected number of elements at level or above is , which falls below one at . For the fixture’s that is , which is 2.50 at . The probability that a layer exists, from the formula above:
max_layer built (seed 1) |
||||
|---|---|---|---|---|
| 8 | 1.0000 | 0.8633 | 0.2201 | 4 |
| 16 | 0.9814 | 0.2201 | 0.0154 | 3 |
| 32 | 0.6301 | 0.0306 | 0.0010 | 2 |
(facts.py, talos, for the table’s probabilities; the last column is the # M=… line of Step “The fixture” below.) One draw per row cannot test a distribution, and none of the three outcomes is improbable. The lab’s graph, at seed 0, has max_layer=2 at .
Why a descent costs a bounded number of steps per layer
The structure is useful only if the walk down the upper layers costs about the same on a large corpus as on a small one. The paper’s argument (§4.2.1) is this, with one correction to be made below. Suppose layer contained the Delaunay graph of its elements, so that the walk on it reaches the nearest element to . The walk on layer starts at the element where the walk on layer stopped, which is the nearest layer- element to , . Every step of the layer- walk is strictly nearer to than , so it never visits another layer- element: those are all at least as far as . Layer membership is independent of position, so each node a walk could step to is a layer- element with probability
and a walk of steps is possible only if none of its nodes was one: . Then
a bound that does not mention . With at most links per node on a layer above 0, a layer costs at most distance computations in expectation (each expansion looks at up to links, and a walk of steps expands nodes, so the expected number of expansions is at most ), and there are about layers.
The correction is to the paper’s own constants. It writes the probability that the next node belongs to the upper layer as and bounds the non-termination probability by , giving a step bound . With the paper’s own choice that is , which is 0.697 at , whereas its level law, derived above, gives . The statement is also internally inconsistent as read here: if the chance of stepping onto an upper-layer node were , the chance of surviving a step would be , not . The paper’s sum is at . With the survival chance per step corrected to the same sum from is , and the derived above is that sum without its term, since it counts the steps taken and a walk of no steps is the start. Both are independent of , which is the claim that matters, and the paper’s is tighter than the argument supports. What the code does is measured, not bounded: TestHNSWDescentCost replays the descent through the layers above 0 for 500 queries and reads the graph’s distance counter around each layer.
=== RUN TestHNSWDescentCost
hnsw_test.go:460: mean distances per descent, by layer
hnsw_test.go:493: n=500 top=2 L2 2.0 L1 16.8
hnsw_test.go:493: n=2000 top=3 L3 1.0 L2 3.5 L1 25.2
hnsw_test.go:493: n=8000 top=3 L3 2.0 L2 12.7 L1 22.2
--- PASS: TestHNSWDescentCost (0.54s)
PASS
ok aec/internal/vecdb 0.544s
(talos; clustered synthetic points of width 16, , efConstruction 64, seed 1; top is the graph’s top layer.) Sixteen times more points moved no layer’s mean past 25.2, against the bound of ; what grew was the number of layers, from two to three. The total over layers rose from 18.8 to 36.9, by the layers added and not by any layer’s cost.
Layer 0 is a different cost. It does not stop at a local minimum; it keeps a beam of the nearest nodes found and stops when its nearest unexpanded candidate is farther than the farthest of them. The paper’s analysis treats this as an additive term, “the backtracking complexity is an additive term in respect to the final complexity”, measured rather than proved (its Fig. 11, at width 4). The distance computations per query that bench reports, dist/q, are the sum of the descent and the beam.
The five algorithms
The paper’s pseudocode follows, transcribed as it writes it, spelling errors included, with its line numbers; the Go listing that implements each follows it.
Algorithm 1. INSERT(hnsw, q, M, Mmax, efConstruction, mL)
1 W ← ∅ // list for the currently found nearest elements
2 ep ← get enter point for hnsw
3 L ← level of ep // top layer for hnsw
4 l ← ⌊-ln(unif(0..1))∙mL⌋ // new element's level
5 for lc ← L … l+1
6 W ← SEARCH-LAYER(q, ep, ef=1, lc)
7 ep ← get the nearest element from W to q
8 for lc ← min(L, l) … 0
9 W ← SEARCH-LAYER(q, ep, efConstruction, lc)
10 neighbors ← SELECT-NEIGHBORS(q, W, M, lc) // alg. 3 or alg. 4
11 add bidirectionall connectionts from neighbors to q at layer lc
12 for each e ∈ neighbors // shrink connections if needed
13 eConn ← neighbourhood(e) at layer lc
14 if │eConn│ > Mmax // shrink connections of e
// if lc = 0 then Mmax = Mmax0
15 eNewConn ← SELECT-NEIGHBORS(e, eConn, Mmax, lc)
// alg. 3 or alg. 4
16 set neighbourhood(e) at layer lc to eNewConn
17 ep ← W
18 if l > L
19 set enter point for hnsw to q
// Add is Algorithm 1, INSERT(hnsw, q, M, Mmax, efConstruction, mL). A record
// whose ID is present is replaced: the old node becomes a tombstone and the
// new one is inserted. The tombstone keeps its edges, so nothing it routed is
// cut off, but it is never chosen as a neighbour of the new node.
func (h *HNSW) Add(r Record) error {
if r.ID == "" {
return ErrEmptyID
}
if len(r.Vector) != h.dim {
return ErrDim
}
if !finite(r.Vector) { // refused before anything changes, so no level is drawn
return ErrNonFinite
}
if old, ok := h.where[r.ID]; ok {
h.nodes[old].deleted = true
h.tombs++
delete(h.where, r.ID)
}
v := append([]float32(nil), r.Vector...)
// line 4: l ← ⌊−ln(unif(0,1)) · mL⌋. Float64 is in [0,1); 1−u is in (0,1], so the log is finite.
l := h.drawLevel()
n := &node{id: r.ID, vec: v, norm: norm(v), meta: copyMeta(r.Meta), text: r.Text, level: l, links: make([][]int32, l+1)}
ix := len(h.nodes)
h.nodes = append(h.nodes, n)
h.where[r.ID] = ix
h.visited = append(h.visited, 0)
if h.entry < 0 { // the first element is the enter point at its level
h.entry, h.maxLayer = ix, l
return nil
}
ep := []cand{{h.dist(v, n.norm, h.nodes[h.entry]), int32(h.entry)}}
L := h.maxLayer
// lines 5–7: greedy descent with ef = 1 through the layers above l.
for lc := L; lc > l; lc-- {
ep = h.searchLayer(v, n.norm, ep, 1, lc, nil, false)[:1]
}
// lines 8–17: on each layer from min(L, l) down to 0, find efConstruction
// candidates, select M neighbours, link both ways, shrink what overflows.
for lc := min(L, l); lc >= 0; lc-- {
// Tombstones are expanded but not collected (strict), so the candidates
// are efConstruction live nodes however many tombstones lie between; a
// graph with no live node in reach falls back to the plain search.
W := h.searchLayer(v, n.norm, ep, h.p.EfConstruction, lc, nil, true)
if len(W) == 0 {
W = h.searchLayer(v, n.norm, ep, h.p.EfConstruction, lc, nil, false)
}
neighbors := h.selectNeighbors(int32(ix), v, n.norm, W, h.p.M, lc)
for _, e := range neighbors {
n.links[lc] = append(n.links[lc], e.ix)
en := h.nodes[e.ix]
en.links[lc] = append(en.links[lc], int32(ix))
mmax := h.p.M
if lc == 0 {
mmax = h.p.Mmax0 // "if lc = 0 then Mmax = Mmax0"
}
if len(en.links[lc]) > mmax { // line 14: shrink e's connections
conns := make([]cand, len(en.links[lc]))
for i, c := range en.links[lc] {
conns[i] = cand{h.dist(en.vec, en.norm, h.nodes[c]), c}
}
kept := h.selectNeighbors(e.ix, en.vec, en.norm, conns, mmax, lc)
en.links[lc] = en.links[lc][:0]
for _, k := range kept {
en.links[lc] = append(en.links[lc], k.ix)
}
}
}
ep = W // line 17: the candidates found are the enter points of the next layer
}
if l > L { // lines 18–19
h.entry, h.maxLayer = ix, l
}
return nil
}
Lines 5 to 7 are the greedy descent through the layers above : ef=1, and only the nearest of is kept as the next enter point ([:1] of a list sorted nearest first). Lines 8 to 17 are the layers the new element joins. The candidates found on layer are all handed down as the enter points of the next layer (line 17, ep = W), not just the nearest. Line 11 is the loop over neighbors, which appends in both directions; line 14’s parenthetical, “if lc = 0 then Mmax = Mmax0”, is the mmax variable. Shrinking recomputes the distances from to each of its current links, since the graph stores no distances, and passes them to the same selection function, so the shrink under Algorithm 4 keeps links that span directions and not only the nearest ones. Links are made bidirectionally but pruned one side at a time: when drops its link to a node, that node’s link to stays, so the graph is directed, and Stats.Edges counts directed links.
The search at line 9 differs from the paper’s in the same way as a query’s: it expands tombstones and collects only live nodes, so holds efConstruction live candidates however many tombstones lie between them (a graph in which no live node is reachable falls back to the plain search, so that the new node is linked somewhere). Selection then never offers the new node a tombstone, which is the subject of the deletion section below.
The level is drawn before anything else is done and after the record is validated. A refused record draws nothing, which is what lets a graph built with a refused insert at any position encode to the same bytes as the graph built without it (below). The first element has nothing to search; it becomes the enter point at its own level. Lines 18 and 19 move the enter point when the new element’s level exceeds the old top.
Algorithm 2. SEARCH-LAYER(q, ep, ef, lc)
1 v ← ep // set of visited elements
2 C ← ep // set of candidates
3 W ← ep // dynamic list of found nearest neighbors
4 while │C│ > 0
5 c ← extract nearest element from C to q
6 f ← get furthest element from W to q
7 if distance(c, q) > distance(f, q)
8 break // all elements in W are evaluated
9 for each e ∈ neighbourhood(c) at layer lc // update C and W
10 if e ∉ v
11 v ← v ⋃ e
12 f ← get furthest element from W to q
13 if distance(e, q) < distance(f, q) or │W│ < ef
14 C ← C ⋃ e
15 W ← W ⋃ e
16 if │W│ > ef
17 remove furthest element from W to q
18 return W
// searchLayer is Algorithm 2, SEARCH-LAYER(q, ep, ef, lc), with the one
// extension a store needs: with strict set (a query on layer 0, and every
// layer an insertion searches), a node that is a tombstone or that fl
// rejects is still expanded (its edges are followed) but never enters the result list W, so a selective filter cannot cut the
// search off from the region it is looking for. C is a min-heap of
// candidates, W a max-heap of results whose root is the furthest kept; the
// loop stops when the nearest candidate is further than that root and W is
// full (line 7). Ties are broken by ID in both heaps.
func (h *HNSW) searchLayer(q []float32, qn float32, eps []cand, ef, lc int, fl Filter, strict bool) []cand {
h.epoch++
if h.epoch == 0 { // wrapped: clear the marks
clear(h.visited)
h.epoch = 1
}
accept := func(n *node) bool {
return !strict || (!n.deleted && (fl == nil || fl(n.meta)))
}
C := &candHeap{h: h, min: true}
W := &candHeap{h: h}
for _, e := range eps {
if h.visited[e.ix] == h.epoch {
continue
}
h.visited[e.ix] = h.epoch
heap.Push(C, e)
if accept(h.nodes[e.ix]) {
heap.Push(W, e)
}
}
for C.Len() > 0 {
c := heap.Pop(C).(cand)
if W.Len() >= ef {
f := W.items[0]
if closer(f.d, h.nodes[f.ix].id, c.d, h.nodes[c.ix].id) { // every element of W is nearer than c
break
}
}
for _, e := range h.nodes[c.ix].links[lc] {
if h.visited[e] == h.epoch {
continue
}
h.visited[e] = h.epoch
en := h.nodes[e]
d := h.dist(q, qn, en)
if W.Len() < ef || closer(d, en.id, W.items[0].d, h.nodes[W.items[0].ix].id) {
heap.Push(C, cand{d, e})
if accept(en) {
heap.Push(W, cand{d, e})
if W.Len() > ef {
heap.Pop(W)
}
}
}
}
}
out := make([]cand, W.Len())
for i := len(out) - 1; i >= 0; i-- {
out[i] = heap.Pop(W).(cand)
}
return out // nearest first
}
// candHeap orders by closer; min is a min-heap (nearest at the root), else
// a max-heap (furthest at the root).
type candHeap struct {
h *HNSW
items []cand
min bool
}
func (c *candHeap) Len() int { return len(c.items) }
func (c *candHeap) Less(i, j int) bool {
a, b := c.items[i], c.items[j]
if c.min {
return closer(a.d, c.h.nodes[a.ix].id, b.d, c.h.nodes[b.ix].id)
}
return closer(b.d, c.h.nodes[b.ix].id, a.d, c.h.nodes[a.ix].id)
}
func (c *candHeap) Swap(i, j int) { c.items[i], c.items[j] = c.items[j], c.items[i] }
func (c *candHeap) Push(x any) { c.items = append(c.items, x.(cand)) }
func (c *candHeap) Pop() any {
old := c.items
x := old[len(old)-1]
c.items = old[:len(old)-1]
return x
}
is a min-heap, so line 5 is a pop, and is a max-heap, so line 6 is a peek at the root and line 17 a pop; both order by closer. The visited set is an array of epoch counters, one per node: a search increments the epoch and a node is visited when its entry equals it. A map would allocate on every search, and clearing an array of entries between searches would cost . The counter wraps after searches, where the array is cleared once. A shared visited array is also why HNSW is not safe for concurrent use and the store in chapter 34 serialises access to it.
Line 7 differs from the Go in one condition. The paper breaks whenever the nearest candidate is farther than the farthest element of , even when is not full. In the paper’s setting that cannot happen with : nothing has been removed from , so every candidate is in it, and the nearest candidate is no farther than the farthest element. In this code it can, and then breaking would be wrong. The tombstones and filter of a store are one extension to the algorithm: with strict set (a query’s layer 0, and every layer an insertion searches), a node that is deleted or that the filter rejects is expanded, so its links are followed, but never enters . Candidates then outnumber the results, and a rejected nearest candidate can be farther than every element of a small while the accepted nodes lie beyond it. So the code breaks only when . The descent through the layers above 0, in a query and in an insertion (lines 5 to 7 of Algorithm 1 and lines 4 to 6 of Algorithm 5), runs with strict unset, ignores the filter and the tombstones, and so is line for line the paper’s.
A filter that rejects everything terminates, because the visited set is finite and every node is visited at most once; it does so after visiting every node reachable from the enter point on layer 0, and returns nothing.
Algorithm 3. SELECT-NEIGHBORS-SIMPLE(q, C, M)
Input: base element q, candidate elements C, number of neighbors to return M
Output: M nearest elements to q
return M nearest elements from C to q
Algorithm 4. SELECT-NEIGHBORS-HEURISTIC(q, C, M, lc, extendCandidates, keepPrunedConnections)
1 R ← ∅
2 W ← C // working queue for the candidates
3 if extendCandidates // extend candidates by their neighbors
4 for each e ∈ C
5 for each eadj ∈ neighbourhood(e) at layer lc
6 if eadj ∉ W
7 W ← W ⋃ eadj
8 Wd ← ∅ // queue for the discarded candidates
9 while │W│ > 0 and │R│< M
10 e ← extract nearest element from W to q
11 if e is closer to q compared to any element from R
12 R ← R ⋃ e
13 else
14 Wd ← Wd ⋃ e
15 if keepPrunedConnections // add some of the discarded
// connections from Wd
16 while │Wd│> 0 and │R│< M
17 R ← R ⋃ extract nearest element from Wd to q
18 return R
// selectNeighbors is Algorithm 3 (SELECT-NEIGHBORS-SIMPLE: the M nearest)
// or, with Heuristic set, Algorithm 4 (SELECT-NEIGHBORS-HEURISTIC): take
// candidates nearest first and keep one only if it is closer to the base
// element than to every neighbour already kept, so the kept set spans
// directions instead of crowding one cluster; extendCandidates first adds
// the candidates' own neighbours, keepPrunedConnections tops the result up
// from the discarded ones. cands carry their distance to the base element q,
// whose own index is base: it is never a neighbour of itself, and a tombstone
// is never chosen over a live node (see eligible).
func (h *HNSW) selectNeighbors(base int32, q []float32, qn float32, cands []cand, m, lc int) []cand {
cands = h.eligible(base, cands)
if !h.p.Heuristic { // Algorithm 3
s := append([]cand(nil), cands...)
sortCands(h, s)
if len(s) > m {
s = s[:m]
}
return s
}
W := &candHeap{h: h, min: true}
seen := map[int32]bool{}
for _, c := range cands {
if !seen[c.ix] {
seen[c.ix] = true
heap.Push(W, c)
}
}
if h.p.ExtendCandidates { // lines 3–7
for _, c := range cands {
for _, adj := range h.nodes[c.ix].links[lc] {
if adj == base || h.nodes[adj].deleted {
continue
}
if !seen[adj] {
seen[adj] = true
heap.Push(W, cand{h.dist(q, qn, h.nodes[adj]), adj})
}
}
}
}
var R, Wd []cand
for W.Len() > 0 && len(R) < m { // lines 9–14
e := heap.Pop(W).(cand)
en := h.nodes[e.ix]
good := true
for _, r := range R {
rn := h.nodes[r.ix]
if !(e.d < h.dist(en.vec, en.norm, rn)) { // e is not closer to q than to r
good = false
break
}
}
if good {
R = append(R, e)
} else {
Wd = append(Wd, e)
}
}
if h.p.KeepPruned { // lines 15–17: Wd was popped nearest first, so it is already ordered
for _, e := range Wd {
if len(R) >= m {
break
}
R = append(R, e)
}
}
return R
}
// eligible drops the base element and the tombstones from cands. A tombstone
// keeps its links and routes searches, but a new link to it is wasted, and a
// replaced record's tombstone sits at distance 0 from its own replacement,
// where the heuristic would keep it first and reject every other candidate.
// When nothing live is left the tombstones stay candidates, so a node that
// has to be linked somewhere is.
func (h *HNSW) eligible(base int32, cands []cand) []cand {
live := make([]cand, 0, len(cands))
rest := make([]cand, 0, len(cands))
for _, c := range cands {
switch {
case c.ix == base:
case h.nodes[c.ix].deleted:
rest = append(rest, c)
default:
live = append(live, c)
}
}
if len(live) == 0 {
return rest
}
return live
}
func sortCands(h *HNSW, s []cand) {
// insertion sort: candidate lists are short (efConstruction at most)
for i := 1; i < len(s); i++ {
for j := i; j > 0 && closer(s[j].d, h.nodes[s[j].ix].id, s[j-1].d, h.nodes[s[j-1].ix].id); j-- {
s[j], s[j-1] = s[j-1], s[j]
}
}
}
Line 11 is ambiguous as pseudocode. The paper’s prose resolves it: the heuristic “creates a connection to a candidate only if it is closer to the base (inserted) element compared to any of the already connected candidates”. The code reads it as: is kept when for every already in . A candidate that is at least as close to some kept neighbour as to is reachable through that neighbour and is not needed as a link. Take and candidates , and , at distances 1.0000, 2.0025 and 1.5000 from (ex.py, talos). Algorithm 3 with keeps and by distance alone, and so does the heuristic here, but not for the same reason: is rejected because (it lies behind and is reached through it), and is kept because (it lies in another direction). Move to and the two rules part: Algorithm 3 keeps and , at 1.0000 and 2.0025, while the heuristic still rejects and keeps , since , so the new node keeps an edge to the far side. That is the paper’s Fig. 2, two isolated clusters with an element on the boundary of one: the nearest candidates all lie in one cluster, and the heuristic is what keeps the edge across.
The two flags are the paper’s. extendCandidates adds each candidate’s own neighbours to the working queue, and the paper says it is “useful only for extremely clustered data” and defaults it to false. keepPrunedConnections tops up from the discarded ones so that nodes are not left with fewer than links. DefaultParams turns the heuristic on and both flags off. The paper gives a default only for extendCandidates; the other is this book’s choice. The heuristic’s price is in the selection: every candidate popped is compared with every kept neighbour, so one selection from candidates is up to distance computations, where Algorithm 3 is a sort. The code breaks out of the inner loop at the first kept neighbour that rejects the candidate.
selectNeighbors takes the index of the base element as well, and never offers a node to itself. With extendCandidates the pool grows by the candidates’ own links, and when a node’s list is shrunk (line 15 of Algorithm 1) those links lead back to the node: at distance 0 it would be kept first and, being as close to every other candidate as they are to it, reject all of them. The paper’s pseudocode has the same hole; in its insertion path at line 10 the new element is not yet in the graph, and line 15 is where it bites. On the fixture at and , TestHNSWExtendCandidates (talos) logs recall 0.8750 without the flag and 0.8562 with it, and 10,399 edges against 9,976; with the self-offer left in, the same test measured 0.5594 and 8,212 edges, in a scratch copy with that one condition removed. The flag is not promised to raise recall, and here it did not; the test requires no self-link and recall within 0.02 of the flag-off build. eligible also drops tombstones from the pool, for the reason given under deletion.
Algorithm 5. K-NN-SEARCH(hnsw, q, K, ef)
1 W ← ∅ // set for the current nearest elements
2 ep ← get enter point for hnsw
3 L ← level of ep // top layer for hnsw
4 for lc ← L … 1
5 W ← SEARCH-LAYER(q, ep, ef=1, lc)
6 ep ← get nearest element from W to q
7 W ← SEARCH-LAYER(q, ep, ef, lc =0)
8 return K nearest elements from W to q
// Search is Algorithm 5, K-NN-SEARCH(hnsw, q, K, ef): greedy descent with
// ef = 1 from the top layer to layer 1, then SEARCH-LAYER on layer 0 with
// ef = max(ef, k), the filter and the tombstones applied, and the k nearest
// of W returned. Score is the metric's similarity (the negated distance).
func (h *HNSW) Search(q []float32, k int, fl Filter) ([]Hit, error) {
if len(q) != h.dim {
return nil, ErrDim
}
if !finite(q) {
return nil, ErrNonFinite
}
if k <= 0 || h.entry < 0 {
return nil, nil
}
ef := max(h.ef, k)
qn := norm(q)
ep := []cand{{h.dist(q, qn, h.nodes[h.entry]), int32(h.entry)}}
for lc := h.maxLayer; lc >= 1; lc-- {
ep = h.searchLayer(q, qn, ep, 1, lc, nil, false)[:1]
}
W := h.searchLayer(q, qn, ep, ef, 0, fl, true)
if len(W) > k {
W = W[:k]
}
hits := make([]Hit, len(W))
for i, c := range W {
n := h.nodes[c.ix]
hits[i] = Hit{ID: n.id, Score: -c.d, Meta: copyMeta(n.meta)}
}
return hits, nil
}
Line 8 returns elements from a list that line 7 limited to , so a search with cannot return elements; Search uses . SetEf accepts any and the raise happens at search time, so a caller may set below without knowing and still gets results, from a beam of width . The returned list is W cut to , nearest first: ordered by closer, which is Flat’s better on the negated distance, so the hits come back in the order chapter 32 defined, higher score first and equal scores by ID. Every score is computed by the metric against the stored vector, not estimated, and TestHNSWHitsSortedAndExact checks both for all three metrics against Flat’s scores for every ID. The approximation is in which records are found, never in how those found are scored or ordered. That is why chapter 32 could say that order inside the top is not scored.
Ties, determinism and what a snapshot must carry
Both heaps order by (distance, ID), through closer. A build is then a function of three things: the data, the order of insertion, and the seed. The seed fixes the level draws, which come from a PCG generator seeded with Params.Seed. Two builds with one seed encode to the same bytes (TestHNSWDeterministicBuild), and so does a build that was saved halfway, decoded and continued, which is why the generator’s state is part of the encoding (a snapshot that dropped it would continue with a different random sequence, so a restored store would build a different graph from a store that had not been interrupted). A different seed builds a different graph. Seed 0 is a valid seed.
decodeHNSW trusts nothing it reads. A snapshot whose bytes are intact can still describe a graph a search would crash on, so the decoder returns ErrCorrupt, and never panics, for: an enter point that is not on the top layer, a link whose target does not reach the link’s layer, a node list longer than the stream (counts are checked as the stream is read, and nothing is allocated from a header’s count: a header claiming 2,000,000,000 nodes or a width of 2,000,000,000 is refused having allocated under 32 MB), a list longer than its layer’s cap, a tombstone count that disagrees with the nodes, two live records with one ID, and a non-finite vector. TestHNSWDecodeRejectsInconsistent builds each of these; TestHNSWDecodeEveryByteFlip flips every byte of a small encoding two ways and cuts it at every offset, and requires ErrCorrupt or a graph that can be searched and encoded again; FuzzDecodeHNSW seeds the same. Run for 20 seconds on talos in a scratch copy it made 731,819 executions and found no failing input.
What is not promised is agreement across hosts. The float32 sums behind a distance depend on the order and width of the additions the CPU uses, so two hosts may differ in the last bit of a distance, a tie may flip, and an edge may differ. Chapter 32 fixed the consequence: cross-host comparisons are of recall, with a tolerance of , never of graph bytes. The measured comparison is below.
Non-finite values
Add and Search refuse a vector with a NaN or infinite component, with vecdb.ErrNonFinite, as Flat does. A refusal changes nothing: TestHNSWRefusesNonFinite inserts a refused row at every one of 40 positions in a build, for three shapes of bad row, and checks that the encoded graph is byte-identical to the build without it; and that a refused replacement leaves the old record live. A finite row can still score NaN: with the row gives under a dot product. closer is better on the negated distance, so a NaN distance ranks after every number whatever the metric, and two NaNs by ID. That keeps both heaps strict weak orders; a comparison written da < db is false in both directions for NaN and lets one such row displace real results depending on where it was inserted. TestHNSWNaNScoreAtEveryPosition inserts that row at each position among four others, including the first, which makes it the enter point, and checks that the top two are the right two and the NaN row comes last of all.
Deletion and replacement
Delete marks the node as a tombstone. The node keeps its links and keeps routing, never comes back from Search, and is counted in Stats.Nodes and Stats.Tombstones and not in Len. Add with an ID that is present is a delete followed by an insert, so replacement adds a node and a tombstone. Delete unlinks nothing. If it did, the regions the node joined would come apart: the node may be the only bridge, and the enter point is a node like any other. A later insertion does treat a tombstone differently from a live node, in two ways: its candidate search expands tombstones and collects only live nodes, and neither the new node’s neighbour selection nor a neighbour’s shrink chooses a tombstone while a live node is on offer. So a tombstone’s incoming links fade as the lists they sit in are shrunk, and its outgoing links stay for routing. The second rule exists for replacement. A replaced record’s tombstone sits at distance 0 from its replacement, and if selection could choose it the heuristic would keep it first and reject every other candidate, each being as close to the tombstone as to the new node: a store that re-adds a record with an unchanged vector (a metadata or text edit) would collapse the new node to one link. TestHNSWReplaceSameVector re-adds every one of 2,000 records twice with the vector it already has:
=== RUN TestHNSWReplaceSameVector
hnsw_fix_test.go:225: round 1: 0 live nodes with layer-0 out-degree <= 1, mean degree 12.96 (was 16.54), recall@10 1.0000 (was 1.0000)
hnsw_fix_test.go:225: round 2: 0 live nodes with layer-0 out-degree <= 1, mean degree 12.93 (was 16.54), recall@10 1.0000 (was 1.0000)
--- PASS: TestHNSWReplaceSameVector (0.73s)
PASS
ok aec/internal/vecdb 0.732s
(talos.) With both rules removed, in a scratch copy, the same test logs 1,980 live nodes with at most one layer-0 link after the first round, a mean degree of 1.03, and recall@10 of 0.9550, then 0.9450 after the second.
TestHNSWDeleteKeepsRouting deletes the enter point and every tenth node and checks that recall against the exact index without them stays above 0.9 and that no tombstone is returned. Tombstones are never compacted in this chapter; a store that has accumulated enough of them rebuilds the graph, which is chapter 34’s.
Filters during traversal
Flat applies a filter before scoring: it still visits every row. HNSW applies it on layer 0 during the traversal, with the extension described under Algorithm 2: a rejected node is expanded but not returned. The alternative orders are to filter after the search, taking the results and dropping what does not match, and to filter before, scanning the accepted records exactly. The filtered search is correct where a post-filter is not, since it keeps walking until accepted nodes have been found or the reachable graph is exhausted. It is not cheap. If a share of the nodes is accepted, independently of position, the walk must visit about nodes before fills, and never fills, so the walk never stops early, if fewer than nodes are accepted. TestHNSWFilterCostOnFixture measures it on the fixture with a filter that accepts the 33 paragraphs of book 6, 3.2% of 1,018 (recall@5 is against Flat with the same filter):
=== RUN TestHNSWFilterCostOnFixture
hnsw_test.go:524: book 6: 33 of 1018 paragraphs; k=5; M=16 seed=1
hnsw_test.go:525: ef trav rec trav d post rec post n post d
hnsw_test.go:553: 10 1.0000 919 0.0813 0.41 168
hnsw_test.go:553: 50 1.0000 1044 0.3250 1.62 458
hnsw_test.go:553: 100 1.0000 1044 0.4813 2.41 672
hnsw_test.go:553: 200 1.0000 1044 0.8125 4.09 878
--- PASS: TestHNSWFilterCostOnFixture (0.69s)
PASS
ok aec/internal/vecdb 0.690s
(talos. trav is the filter applied during traversal and post the filter applied after an unfiltered search for results; rec is recall@5, d the distances per query and post n the hits left after the filter.) The traversal filter has recall 1.0000 at every and costs 1,044 distances from , more than the 1,018 points: the descent plus every node of layer 0. At , exceeds , so the walk was always going to visit everything. The post-filter is cheap and wrong: at it keeps 4.09 hits on average, and at it keeps 0.41. For a filter this selective on a corpus this small, the exact index with the filter applied first (chapter 32: 33 distances and 1,018 calls of the filter) is cheaper than the graph. Traversal-time filtering is what keeps recall when the graph has to be used, which is when is large enough that the scan costs too much; it does not make a selective filter fast.
Walkthrough
The listings so far are the graph. The remaining ones are the parameters (ch33-params), the clustered corpus the large sweep runs on (ch33-synthetic), and the bench that produced every table.
// HNSWParams are the paper's (Malkov and Yashunin, arXiv 1603.09320,
// Algorithm 1's arguments): M connections made per inserted element, and a
// cap on each layer above 0 of Mmax = M (the paper leaves Mmax open and this
// book takes M; the cap and the links made are the same number), Mmax0 on
// layer 0 (the paper's "autoselected value" is 2·M), the
// candidate list size efConstruction while building and Ef while searching,
// and the level normalisation mL = 1/ln(M) that makes the level draw
// floor(−ln(unif(0,1)) · mL) a geometric distribution with ratio 1/M, the
// skip list's. Heuristic selects neighbours by Algorithm 4 with its two
// flags instead of Algorithm 3's "M nearest". Seed fixes the level draws,
// so two builds of one corpus in one order are identical.
type HNSWParams struct {
M, Mmax0, EfConstruction, Ef int
ML float64
Heuristic, ExtendCandidates, KeepPruned bool
Seed int64
}
// DefaultParams are the paper's Mmax0 = 2M and mL = 1/ln(M) for a given M,
// with the heuristic on and both flags off. efConstruction 200 and ef 50 are
// this book's starting points: the paper sizes efConstruction by
// construction recall near 0.95 and names no default ef.
func DefaultParams(m int) HNSWParams {
if m < 2 {
m = 2
}
return HNSWParams{M: m, Mmax0: 2 * m, EfConstruction: 200, Ef: 50, ML: 1 / math.Log(float64(m)), Heuristic: true}
}
// IsZero reports a zero value, which Options reads as "no graph".
func (p HNSWParams) IsZero() bool { return p == HNSWParams{} }
efConstruction 200 and ef 50 are this book’s starting points. The paper does not give them. It sizes efConstruction by what the construction searches achieve: “large enough to produce K-ANNS recall close to unity during the construction process (0.95 is enough for the most use-cases)”, and it gives no default for the search-time ef, which is the knob this chapter’s tables sweep. The paper leaves , the cap on the layers above 0, open; this book takes , so the cap and the number of links made per insertion are one number. Its other choices are the ones DefaultParams takes: , “simulations also suggest that 2∙M is a good choice for Mmax0”, and . On it says “a reasonable range of M is from 5 to 48”.
// Synthetic draws a clustered corpus of unit vectors by seed: clusters
// centres uniform on the sphere, n points as centre + Gaussian noise of
// per-coordinate spread, renormalised, and nq queries drawn the same way
// around the same centres. Two hosts build the same points from one seed;
// their float32 sums may still differ in the last bit, which is why the
// recall tables compare across hosts within a tolerance.
func Synthetic(seed uint64, n, nq, dim, clusters int, spread float64) (points, queries [][]float32) {
r := rand.New(rand.NewPCG(seed, 0xc0ffee))
centres := make([][]float64, clusters)
for i := range centres {
c := make([]float64, dim)
var s float64
for j := range c {
c[j] = r.NormFloat64()
s += c[j] * c[j]
}
s = math.Sqrt(s)
for j := range c {
c[j] /= s
}
centres[i] = c
}
draw := func(count int) [][]float32 {
out := make([][]float32, count)
for i := range out {
c := centres[r.IntN(clusters)]
v := make([]float64, dim)
var s float64
for j := range v {
v[j] = c[j] + spread*r.NormFloat64()
s += v[j] * v[j]
}
s = math.Sqrt(s)
row := make([]float32, dim)
for j := range row {
row[j] = float32(v[j] / s)
}
out[i] = row
}
return out
}
return draw(n), draw(nq)
}
// bench measures recall@k and query latency of HNSW against Flat over a
// list of ef values, on either the committed Iliad fixture (-vectors,
// -qvec) or a synthetic clustered corpus: -clusters Gaussian centres on the
// unit sphere, -n points drawn around them with -spread, all by seed, so
// two hosts build the same points; their float32 sums can differ in the last
// bit and so can the graphs they build, which is why the chapter compares
// recall within a tolerance across hosts, never bit for bit. -heuristic=false
// builds with Algorithm 3 and -mmax0-mult 1 sets Mmax0 = M, the two ablations
// of the chapter's exercises. Latency is the median and the 99th percentile
// over the queries of one Search call, in one thread; the output names the
// host's CPU count and nothing else about it, so whoever runs it says which
// machine it was.
func benchCmd(args []string) error {
fs := flag.NewFlagSet("bench", flag.ExitOnError)
n := fs.Int("n", 100000, "synthetic points")
dim := fs.Int("dim", 128, "synthetic width")
clusters := fs.Int("clusters", 100, "synthetic centres")
spread := fs.Float64("spread", 0.15, "synthetic per-coordinate noise around a centre")
nq := fs.Int("queries", 1000, "synthetic queries (drawn the same way)")
seed := fs.Uint64("seed", 1, "seed for points, queries and the graph")
vectors := fs.String("vectors", "", "fixture vectors (float16); with -qvec, replaces the synthetic corpus")
qvec := fs.String("qvec", "", "fixture query vectors (float16)")
fpPath := fs.String("fingerprint", filepath.Join(fixtureDir(), "iliad-fingerprint.json"), "fingerprint, for the fixture's dim")
ms := fs.String("M", "16", "comma-separated M values")
efs := fs.String("ef", "10,20,50,100,200", "comma-separated ef values")
k := fs.Int("k", 10, "k")
heuristic := fs.Bool("heuristic", true, "select neighbours by Algorithm 4 (false: Algorithm 3, the M nearest)")
mmax0 := fs.Int("mmax0-mult", 2, "Mmax0 as a multiple of M (the paper's choice is 2)")
fs.Parse(args)
var pts, qs [][]float32
if *vectors != "" {
fp, err := vecdb.ReadFingerprint(*fpPath)
if err != nil {
return err
}
if pts, err = vecdb.ReadF16File(*vectors, fp.Dim); err != nil {
return err
}
if *qvec == "" {
return errors.New("-vectors needs -qvec")
}
if qs, err = vecdb.ReadF16File(*qvec, fp.Dim); err != nil {
return err
}
*dim = fp.Dim
fmt.Printf("corpus: fixture, %d vectors, %d queries, dim %d\n", len(pts), len(qs), *dim)
} else {
pts, qs = vecdb.Synthetic(*seed, *n, *nq, *dim, *clusters, *spread)
fmt.Printf("corpus: synthetic, %d points, %d queries, dim %d, %d clusters, spread %.2f, seed %d\n", len(pts), len(qs), *dim, *clusters, *spread, *seed)
}
fmt.Printf("runtime: %s/%s, %d cpus, k=%d\n", runtime.GOOS, runtime.GOARCH, runtime.NumCPU(), *k)
flat := vecdb.NewFlat(*dim, vecdb.Cosine)
for i, v := range pts {
flat.Add(vecdb.Record{ID: fmt.Sprintf("%07d", i), Vector: v})
}
exact := make([][]vecdb.Hit, len(qs))
t0 := time.Now()
for i, q := range qs {
exact[i], _ = flat.Search(q, *k, nil)
}
fmt.Printf("flat: %.3f ms per query (median of %d: %.3f ms)\n", msf(time.Since(t0))/float64(len(qs)), len(qs), medianLatency(func(i int) { flat.Search(qs[i], *k, nil) }, len(qs)))
fmt.Println()
fmt.Printf("%-4s %-5s %-10s %-12s %-10s %-10s %-9s\n", "M", "ef", "recall@k", "p50 ms", "p99 ms", "dist/q", "build s")
for _, mstr := range strings.Split(*ms, ",") {
m, err := strconv.Atoi(strings.TrimSpace(mstr))
if err != nil {
return err
}
p := vecdb.DefaultParams(m)
p.Seed = int64(*seed)
p.Mmax0 = *mmax0 * m
p.Heuristic = *heuristic
h := vecdb.NewHNSW(*dim, vecdb.Cosine, p)
t0 = time.Now()
for i, v := range pts {
h.Add(vecdb.Record{ID: fmt.Sprintf("%07d", i), Vector: v})
}
build := time.Since(t0)
st := h.Stats()
fmt.Printf("# M=%d: nodes=%d edges=%d max_layer=%d build=%.1fs distances during build=%d\n", m, st.Nodes, st.Edges, st.MaxLayer, build.Seconds(), st.Distances)
for _, efstr := range strings.Split(*efs, ",") {
ef, err := strconv.Atoi(strings.TrimSpace(efstr))
if err != nil {
return err
}
h.SetEf(ef)
before := h.Stats().Distances
sum := 0.0
lat := make([]float64, len(qs))
for i, q := range qs {
t1 := time.Now()
hits, _ := h.Search(q, *k, nil)
lat[i] = msf(time.Since(t1))
sum += vecdb.Recall(exact[i], hits)
}
sort.Float64s(lat)
dist := float64(h.Stats().Distances-before) / float64(len(qs))
fmt.Printf("%-4d %-5d %-10.4f %-12.3f %-10.3f %-10.0f %-9.1f\n", m, ef, sum/float64(len(qs)), lat[len(lat)/2], lat[len(lat)*99/100], dist, build.Seconds())
}
}
return nil
}
func msf(d time.Duration) float64 { return float64(d) / float64(time.Millisecond) }
func medianLatency(f func(i int), n int) float64 {
lat := make([]float64, n)
for i := 0; i < n; i++ {
t := time.Now()
f(i)
lat[i] = msf(time.Since(t))
}
sort.Float64s(lat)
return lat[n/2]
}
Latency is the median and the 99th percentile over the queries of one Search call each, in a single thread, after the graph is built. With 32 queries the 99th percentile is the maximum. dist/q is the mean over the queries of the distance computations the graph’s counter records, the descent and the beam together.
The fixture
Run on straylight, over the 1,018 Iliad paragraphs and 32 queries chapter 32 committed, with the Mmax0, heuristic and efConstruction defaults, seed 1:
tools/remote/straylight.sh 5b-t3 -- go -C go run ./cmd/aec-vecdb bench -vectors internal/vecdb/testdata/iliad-vectors.f16 -qvec internal/vecdb/testdata/iliad-query-vectors.f16 -M 8,16,32 -ef 10,20,50,100,200
corpus: fixture, 1018 vectors, 32 queries, dim 1024
runtime: linux/amd64, 32 cpus, k=10
flat: 0.415 ms per query (median of 32: 0.414 ms)
M ef recall@k p50 ms p99 ms dist/q build s
# M=8: nodes=1018 edges=12322 max_layer=4 build=0.4s distances during build=683477
8 10 0.9094 0.060 0.074 127 0.4
8 20 0.9750 0.090 0.124 191 0.4
8 50 0.9906 0.168 0.191 347 0.4
8 100 0.9969 0.265 0.300 540 0.4
8 200 0.9969 0.400 0.437 775 0.4
# M=16: nodes=1018 edges=17315 max_layer=3 build=0.5s distances during build=854095
16 10 0.9312 0.077 0.106 168 0.5
16 20 0.9875 0.120 0.149 257 0.5
16 50 1.0000 0.217 0.253 458 0.5
16 100 1.0000 0.331 0.362 672 0.5
16 200 1.0000 0.447 0.479 878 0.5
# M=32: nodes=1018 edges=17852 max_layer=2 build=0.4s distances during build=861382
32 10 0.9469 0.083 0.110 180 0.4
32 20 0.9938 0.121 0.161 271 0.4
32 50 1.0000 0.219 0.266 477 0.4
32 100 1.0000 0.338 0.367 690 0.4
32 200 1.0000 0.452 0.495 887 0.4
Recall rises with at every , and reaches 1.0000 at for and . stops at 0.9969 at and : 1 of the 320 true neighbours (32 queries by 10) is not found, and doubling does not find it. A neighbour that is in the graph and that a wider beam still does not return is the stuck walk of the first section, at the scale of the beam; exercise (b) examines one such miss, in the graph. The cost is the other column. At and the graph computes 878 distances per query against Flat’s 1,018, and its median latency, 0.447 ms, is 0.9 times as fast as Flat’s 0.414 ms: slower. On 1,018 points the graph is not an acceleration, and at , the first row with recall 1.0000, it is 1.9 times faster (0.217 ms against 0.414 ms). The fixture exists to test correctness against a real embedder’s geometry, not to show the speed.
The same fixture and the same sweep on orion, restricted to :
AEC_REMOTE=orion tools/remote/straylight.sh 5b-t3o -- go -C go run ./cmd/aec-vecdb bench -vectors internal/vecdb/testdata/iliad-vectors.f16 -qvec internal/vecdb/testdata/iliad-query-vectors.f16 -M 16 -ef 10,20,50,100,200
corpus: fixture, 1018 vectors, 32 queries, dim 1024
runtime: linux/amd64, 8 cpus, k=10
flat: 1.059 ms per query (median of 32: 1.009 ms)
M ef recall@k p50 ms p99 ms dist/q build s
# M=16: nodes=1018 edges=17315 max_layer=3 build=1.0s distances during build=854095
16 10 0.9312 0.181 0.252 168 1.0
16 20 0.9875 0.276 0.374 257 1.0
16 50 1.0000 0.503 0.584 458 1.0
16 100 1.0000 0.760 0.815 672 1.0
16 200 1.0000 1.014 1.086 878 1.0
The five recall values agree with straylight’s to four digits, so the largest difference is 0.0000, inside chapter 32’s tolerance of 0.01; the edge count (17,315) and the build’s distance count (854,095) agree too. This says that on these two hosts, for this input, no tie flipped. It does not say the graphs would agree on a third host. Latencies are not compared across hosts.
Recall depends on as well as , as chapter 32 warned: a list that swaps rank with rank loses . The same fixture at with and (straylight; the tables are -k 1 and -k 100 runs of the command above restricted to -M 16) gives, with the column repeated from above:
| recall@1 | recall@10 | recall@100 | dist/q at |
|
|---|---|---|---|---|
| 10 | 0.9688 | 0.9312 | 0.9969 | 672 |
| 20 | 1.0000 | 0.9875 | 0.9969 | 672 |
| 50 | 1.0000 | 1.0000 | 0.9969 | 672 |
| 100 | 1.0000 | 1.0000 | 0.9969 | 672 |
| 200 | 1.0000 | 1.0000 | 0.9997 | 878 |
The last two columns show the rule of Algorithm 5 without a line of argument: at every below 100 is raised to 100, so the rows for to are one search (672 distances, the same recall), and only is different.
A hundred thousand points
The large sweep runs on the synthetic corpus: 100,000 points of width 128 around 100 centres on the unit sphere, with per-coordinate noise 0.15, 1,000 queries drawn the same way, seed 1. Straylight:
tools/remote/straylight.sh 5b-t3 -- go -C go run ./cmd/aec-vecdb bench -n 100000 -dim 128 -clusters 100 -queries 1000 -seed 1 -M 8,16,32 -ef 10,20,50,100,200
corpus: synthetic, 100000 points, 1000 queries, dim 128, 100 clusters, spread 0.15, seed 1
runtime: linux/amd64, 32 cpus, k=10
flat: 7.524 ms per query (median of 1000: 7.387 ms)
M ef recall@k p50 ms p99 ms dist/q build s
# M=8: nodes=100000 edges=1328665 max_layer=5 build=47.1s distances during build=159651878
8 10 0.2475 0.064 0.142 224 47.1
8 20 0.4007 0.109 0.248 353 47.1
8 50 0.6897 0.238 0.527 647 47.1
8 100 0.8794 0.385 0.877 961 47.1
8 200 0.9691 0.578 1.261 1270 47.1
# M=16: nodes=100000 edges=2513356 max_layer=4 build=93.1s distances during build=333783019
16 10 0.5674 0.127 0.246 407 93.1
16 20 0.7599 0.198 0.380 583 93.1
16 50 0.9431 0.352 0.608 943 93.1
16 100 0.9846 0.529 0.889 1312 93.1
16 200 0.9905 0.775 1.165 1825 93.1
# M=32: nodes=100000 edges=4259954 max_layer=3 build=120.6s distances during build=593440085
32 10 0.6931 0.192 0.347 629 120.6
32 20 0.8571 0.296 0.462 893 120.6
32 50 0.9725 0.551 0.750 1508 120.6
32 100 0.9910 0.858 1.189 2270 120.6
32 200 0.9953 1.364 1.952 3597 120.6
Orion, restricted to :
AEC_REMOTE=orion tools/remote/straylight.sh 5b-t3o -- go -C go run ./cmd/aec-vecdb bench -n 100000 -dim 128 -clusters 100 -queries 1000 -seed 1 -M 16 -ef 10,20,50,100,200
corpus: synthetic, 100000 points, 1000 queries, dim 128, 100 clusters, spread 0.15, seed 1
runtime: linux/amd64, 8 cpus, k=10
flat: 10.563 ms per query (median of 1000: 10.502 ms)
M ef recall@k p50 ms p99 ms dist/q build s
# M=16: nodes=100000 edges=2513356 max_layer=4 build=101.8s distances during build=333783019
16 10 0.5674 0.153 0.283 407 101.8
16 20 0.7599 0.229 0.421 583 101.8
16 50 0.9431 0.397 0.678 943 101.8
16 100 0.9846 0.593 0.926 1312 101.8
16 200 0.9905 0.878 1.297 1825 101.8
The five recall values at agree with straylight’s to four digits, so the largest difference is 0.0000 and inside the that chapter 32 promised; the graph’s edge count (2,513,356) and the build’s distance count (333,783,019) agree as well. As with the fixture, that is two hosts and one input; it is not a claim that the graph is the same on any host. Orion’s latencies are slower than straylight’s at every row (flat: 10.502 ms against 7.387 ms) and are not compared.
Reading the tables
Recall against and . On the 100,000-point corpus recall is 0.2475 to 0.6931 at and 0.9691 to 0.9953 at , and no row reaches 1. At the graphs with and clear 0.98 (0.9846 and 0.9910) and does not (0.8794). The corpus is a hard one for a graph, and deliberately: each point is a unit centre plus noise of norm , and a numpy simulation of the same recipe (cos.py, talos; 200 clusters of 1,000 points) gives a mean cosine of 0.2537 between a query and the points of its own cluster, standard deviation 0.0726, the tenth-best 0.4173 and the median 0.2550. The ten true neighbours are about two standard deviations out of a thousand nearly indistinguishable points, which is why the beam has to be wide. The fixture, whose neighbours are paragraphs of an epic about its own subjects, has far more contrast, and reaches 1.0000 at .
The cost of recall. dist/q is the table’s cost measure. At and it is 1,312 distances out of 100,000, 1.31% of the corpus, with recall 0.9846 and a median latency of 0.529 ms against Flat’s 7.387 ms: 14.0 times faster. Fewer distances by a factor of 76 became a speedup of 14; the difference is what a distance costs in the graph (a random row of 512 bytes, a heap operation) compared with a scan that streams rows in order, and this chapter does not separate those. Across the column at the distances are 407, 583, 943, 1,312 and 1,825: 17.6 more per unit of between 10 and 20, 12.0 between 20 and 50, 7.4 between 50 and 100 and 5.1 between 100 and 200. The cost of a unit of falls as the beam widens.
is memory and build time as well. The edges are 1,328,665, 2,513,356 and 4,259,954 for , which at four bytes per directed link is 5.3, 10.1 and 17.0 MB: 53.1, 100.5 and 170.4 bytes per node, within the paper’s bound of bytes per element (79.4, 151.1 and 292.9, derive.py, talos) and well below it for : the average out-degree over all layers is 13.3, 25.1 and 42.6 against caps of = 16, 32 and 64 on layer 0 alone. The vectors are 512 bytes per node, so at the graph adds about a fifth. Build time is 47.1, 93.1 and 120.6 s, one thread, each insertion a search at 200: at , 0.93 ms and 3,338 distance computations per element on average. Doubling from 16 to 32 raised the recall at from 0.9846 to 0.9910 and the distances from 1,312 to 2,270; and at buys 0.0005 over at (0.9910 against 0.9905) for 445 more distances (2,270 against 1,825).
The 1,018-point fixture is a correctness test, not a speed test. Against Flat it is never more than 6.9 times faster, at , and recall 0.9094, and at it is no faster (1.0 times at , 0.9 at and ). A graph pays for itself where the distances it skips outweigh the pointer-chasing it does instead, which on these hosts is between 1,018 and 100,000 points; this chapter does not locate the break-even.
What each design choice costs
Two of the choices above are the paper’s claims about the build, and the bench can switch each. -heuristic=false selects with Algorithm 3, and -mmax0-mult 1 sets . On straylight, at :
| corpus | build | recall@10 at | dist/q |
edges |
|---|---|---|---|---|
| 20,000 points, width 32, 20 clusters (200 queries) | default | 0.8090, 0.9960, 1.0000 (10, 50, 100) | 269, 642, 875 | 393,851 |
| Algorithm 3 | 0.8435, 0.9820, 0.9875 | 271, 599, 782 | 501,205 | |
| 0.7145, 0.9815, 0.9985 | 210, 508, 731 | 282,202 | ||
| fixture | default | 0.9312, 0.9875, 1.0000, 1.0000, 1.0000 (10, 20, 50, 100, 200) | 168, 257, 458, 672, 878 | 17,315 |
| Algorithm 3 | 0.9281, 0.9688, 0.9812, 0.9969, 0.9969 | 175, 251, 417, 617, 835 | 26,933 | |
| 0.9125, 0.9844, 0.9969, 0.9969, 0.9969 | 138, 212, 382, 585, 811 | 13,112 |
(Files abl-*.txt in the task’s scratch; the bench run is -n 20000 -dim 32 -clusters 20 -queries 200 -seed 1 -M 16 -ef 10,50,100 and the fixture command above with -M 16.) The heuristic gives up recall at the narrowest beam on the clustered corpus (0.8090 against 0.8435 at ) and wins above it, 1.0000 against 0.9875 at , with 21% fewer links (393,851 against 501,205). On the fixture it is better at every (0.9312 against 0.9281 at ) and ends at 1.0000 against 0.9969. The paper’s statement is that its use “leads to a higher or similar search performance”; the fixture agrees with it at every , and the clustered corpus at the wider beams and not at . is lower at equal everywhere, with 28% fewer links on the clustered corpus and 24% fewer on the fixture, and set against dist/q instead of the two builds are close at the high end of the clustered corpus: 0.9985 at 731 distances for , against 0.9960 at 642 and 1.0000 at 875 for the default. What it costs is the ceiling: on the fixture the recall stops at 0.9969 from upward, one neighbour in 320 that no beam of width up to 200 returned. The paper reports a “very strong performance penalty at high recall” for on 5 million SIFT vectors; at 20,000 points of width 32 this bench shows the direction and the ceiling, not a strong penalty.
The lab’s test on the fixture
TestRecallOnFixture in go/labs/ch33 builds the graph over the fixture at with efConstruction 100, the lab’s build budget, which keeps the test inside the time a lab test should take, and measures recall@10 of the 32 queries as grows. It fails below 0.95 at and below 0.999 at . Seed 0, so the graph differs from the bench’s seed 1 (max_layer=2 against 3):
=== RUN TestRecallOnFixture
lab_test.go:76: graph: nodes=1018 edges=15341 max_layer=2
lab_test.go:81: ef=10 recall@10=0.9344
lab_test.go:81: ef=20 recall@10=0.9844
lab_test.go:81: ef=50 recall@10=1.0000
lab_test.go:81: ef=100 recall@10=1.0000
lab_test.go:81: ef=200 recall@10=1.0000
--- PASS: TestRecallOnFixture (0.52s)
PASS
ok aec/labs/ch33 0.522s
(talos.) The same build with a book filter, recall@5 against Flat filtered the same way for the paragraphs of book 1, is the test’s last assertion (at least 0.9).
Exercises
(a) Compute the probability that the 1,018 fixture elements produce a layer 3 at and at , and say why the table’s for equals its for .
Answer
Level is empty when none of the draws reaches it, so . At , and , so the probability is 0.2201. At , and , so it is 0.8633. Both agree with the exact values the table prints (facts.py, talos). The entry for level 4 is , and : the two parameters give the same per-draw probability for those two levels, so the same number, 0.2201.
(b) Set (-mmax0-mult 1) and rerun the fixture bench at . Predict the direction of the change in recall and in dist/q before you run it, then explain what you see. Then find the record the graph misses.
Answer
Fewer links per node on layer 0 mean fewer routes to each neighbour, so recall falls at equal , and fewer links to expand mean fewer distances; the walkthrough’s table shows both. The new part is the ceiling. At the recall stops at 0.9969 and stays there up to : one true neighbour in 320 is never returned. A scratch test that builds both graphs (talos; seed 1, ) counts the layer-0 nodes with no incoming link and the nodes unreachable from the enter point: both are zero in both graphs. The missed record, p0012, has six incoming links on layer 0. So the graph is connected and the record is not isolated; the beam’s stop rule ends the search before it reaches it. Reachability is necessary and not sufficient, which is the local-minimum failure of the first section moved to the scale of the beam. The paper reports a “very strong performance penalty at high recall” for ; on the 20,000-point clustered corpus of the table the cost at similar distances was small, and on the fixture it is this ceiling.
(c) Why can K-NN-SEARCH with not return elements, and what does Search do about it? Then take and on the fixture at : is it one of the searches in the table, and between which two rows’ dist/q must its cost lie?
Answer
Lines 16 and 17 of Algorithm 2 trim to at every admission, so at most elements survive to line 8 of Algorithm 5. Search uses , and TestHNSWEfBelowK asks for 20 hits at and requires 20. For the beam is , which no row of the table uses, so it is a new search. Expect its cost between the rows with beams 100 and 200 (672 and 878 distances): a wider beam admits more candidates and stops later, so it computes more distances than a narrower one in practice. That is an expectation and not a theorem, since the extra candidates change the order in which nodes are expanded, and the table has no row to confirm it, so the number would have to be measured.
(d) Delete the enter point and every tenth element, then search. Why does recall stay high, and what could go wrong if deletion unlinked the nodes?
Answer
The tombstones keep their links, so the graph the beam walks is the graph that was built: the deleted nodes are expanded and never returned, and every region they joined is still joined. TestHNSWDeleteKeepsRouting requires recall at least 0.9 against the exact index without the deleted records, and that no tombstone comes back. Unlinking removes edges in both directions. A node that was the only bridge between two clusters takes the bridge with it, and the greedy walk from an enter point in one cluster can no longer cross; the enter point is the same kind of node, and removing it needs a new one chosen from the top layer, which may have been that node alone. A repair that reconnects the removed node’s neighbours among themselves (by Algorithm 4) exists, and costs a selection per neighbour on every layer; tombstones defer that cost, at the price of the memory and the expansions they keep.
(e) A filter accepts 1% of the records of a 100,000-point corpus of width 128. For compare post-filtering, pre-filtering and filtering during traversal.
Answer
Post-filtering searches for results and keeps those that match. A returned result matches with probability 0.01 if the filter is independent of position, so gives 10 matches on average, and 46% of the queries get fewer than 10 (a Poisson variable of mean 10 is at most 9 with probability 0.458); the fixture’s row kept 4.09 of a possible 5 hits at a 3.2% filter. Pre-filtering scans the accepted 1,000 records exactly: multiply-adds, plus the calls of the filter that chapter 32 measured at about 32 ns each. Filtering during traversal keeps the rejected nodes in the candidate heap, so the beam walks through them, and returns accepted hits whenever the reachable graph holds . To fill with accepted nodes it must visit about nodes, which at is 5,000 distances: more than pre-filtering’s 1,000, and 5% of the corpus. Traversal-time filtering buys correctness at the graph’s price; pre-filtering is cheaper at this selectivity, and the walk is cheaper only when the accepted share is large.
(f) Predict whether the distance computations per insertion exceed those of a query at , and by about how much. Check against both tables.
Answer
An insertion’s layer-0 search is Algorithm 2 at on the graph built so far, the same procedure as a query at , so its cost is about the table’s dist/q there, less for a graph that is on average half its final size. On top come the greedy descent through the layers above the element’s own level (a few tens of distances, from the descent test), the same search on each upper layer the element joins (on average of them, from the level law), the selection (the heuristic compares each popped candidate with the kept neighbours, up to distances), and a shrink for each neighbour whose list overflowed, which recomputes that neighbour’s link distances and selects again. The measurements, at : the fixture builds with 854,095 distances for 1,018 insertions, 839 each, against 878 for a query at (ratio 0.96); the 100,000-point corpus builds with 333,783,019 distances, 3,338 each, against 1,825 (ratio 1.83). On 1,018 points a search at touches 86% of the graph however it is run, and the extra work is hidden; on 100,000 the beam is the same size and the selection and shrinks are visible: if the smaller graph made the search cost no more than 1,825, they cost at least 1,513 distances per insertion.
Lab
go/labs/ch33 declares Impl{New}; you write mine/hnsw.go, the graph of Algorithms 1 to 5, with the tombstone and filter rules the Mechanism states, and run
make lab CH=33 IMPL=mine
Provided: the exact index (vecdb.Flat), recall@k, the committed fixture, the seeded clustered corpus, and the types and errors. Two accessors beyond vecdb.Index are part of the interface the tests read: EntryID(), the enter point’s ID, and MaxDegree(layer), the largest out-degree on a layer. The thirteen tests pin:
- recall@10 on the fixture at 100 and 200, the latter at least 0.999 (the lab builds at efConstruction 100 to stay inside the test time budget, where the bench keeps 200), and a filtered recall;
- recall on 1,200 clustered points under cosine and L2;
- ties by ID, and two seeded builds identical in their statistics and in every answer;
- below ;
- tombstones routing with the enter point itself deleted (found through
EntryID), and replacement; - the selective filter, the filter that rejects everything (which must return empty and not hang), and a filter that accepts only ten records ranked 300 to 309 by distance, which the walk must find in full;
- the level law through
MaxLayer; - the degree bounds through
MaxDegree: at most on layer 0, more than somewhere on it, at most above; - the heuristic, through its effect: on a clustered corpus Algorithm 4 keeps fewer links than Algorithm 3;
ErrNonFiniteonAddandSearch;- re-adding every record twice with its own vector keeps recall.
Under IMPL=mine the starter fails all thirteen, and make lab CH=33 passes against the reference. What these tests do not pin, found by changing the reference one line at a time in a scratch copy: line 17 of Algorithm 1 passing only the nearest candidate down as the next layer’s enter point (ep = W[:1]) builds the identical graph on the fixture, 15,341 edges either way, so no test here can tell the two apart.
Further reading
- Yu. A. Malkov and D. A. Yashunin, Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs, 2016, revised 2018: Algorithms 1 to 5, , , §4.2.1’s complexity argument (and its constants, discussed above).
- Yury Malkov, Alexander Ponomarenko, Andrey Logvinov and Vladimir Krylov, Approximate nearest neighbor algorithm based on navigable small world graphs, Information Systems 45 (2014): the single-layer predecessor.
- Piotr Indyk and Rajeev Motwani, Approximate nearest neighbors: towards removing the curse of dimensionality, STOC 1998: the approximate problem and locality-sensitive hashing, the other family.
- Martin Aumüller, Erik Bernhardsson and Alexander Faithfull, ANN-Benchmarks: A Benchmarking Tool for Approximate Nearest Neighbor Algorithms, 2018: recall against queries per second, the form this chapter’s tables take.
- Matthijs Douze et al., The Faiss library, 2024: a production HNSW beside the flat index of chapter 32.