33. Vector database I: HNSW

Why this layer exists

Chapter 32’s search scores every stored vector: ndn\,d multiply-adds per query. A million memories at the fixture’s width of 1,024 is 106×1024=1.024×10910^6 \times 1024 = 1.024 \times 10^9 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 kk 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 kk 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 pp towards a query qq computes d(q,x)d(q, x) for pp and each of its neighbours, moves to the nearest, and stops when the current node is nearer to qq than all of its neighbours. Each move strictly decreases d(q,⋅)d(q, \cdot) over a finite set, so the walk terminates; after ss moves it has computed at most ss 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 d(q,⋅)d(q, \cdot) over the graph. That is the true nearest neighbour only if the graph has the right edges. Two clusters AA and BB, each node joined only to its near neighbours inside its own cluster, and a query in BB entered from a node of AA: the walk descends through AA to the node of AA nearest the query and stops, since every neighbour of that node is in AA and farther. The edge that would cross to BB 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 efef 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 MM 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 ll of a new element:

l=⌊−lnu⋅mL⌋,u∼U(0,1). l = \lfloor -\ln u \cdot m_L \rfloor, \qquad u \sim U(0, 1).

For an integer k≥1k \ge 1, ⌊x⌋≥k\lfloor x \rfloor \ge k exactly when x≥kx \ge k, so

P(l≥k)=P(−lnu⋅mL≥k)=P(lnu≤−k/mL)=P(u≤e−k/mL)=e−k/mL, P(l \ge k) = P(-\ln u \cdot m_L \ge k) = P(\ln u \le -k/m_L) = P(u \le e^{-k/m_L}) = e^{-k/m_L},

the last step because P(u≤a)=aP(u \le a) = a for a∈[0,1]a \in [0, 1]. The paper’s “simple choice for the optimal mLm_L” is 1/lnM1/\ln M, and then e−k/mL=e−klnM=M−ke^{-k/m_L} = e^{-k \ln M} = M^{-k}: the share of elements that reach layer kk falls by a factor MM per layer. That is the skip list’s p=1/Mp = 1/M, as the paper says, and DefaultParams sets ML to it.

The expected top layer follows from writing l=∑k≥11[l≥k]l = \sum_{k \ge 1} \mathbf{1}[l \ge k] and taking expectations term by term:

E[l]=∑k=1∞P(l≥k)=∑k=1∞M−k=M−11−M−1=1M−1. E[l] = \sum_{k=1}^{\infty} P(l \ge k) = \sum_{k=1}^{\infty} M^{-k} = \frac{M^{-1}}{1 - M^{-1}} = \frac{1}{M - 1}.

An element is in l+1l + 1 layers, so the expected number of layers per element is 1+1/(M−1)1 + 1/(M-1): 1.0667 at M=16M = 16. The paper’s equation (1) writes the same expectation as E[l+1]=E[−lnu]mL+1=mL+1E[l + 1] = E[-\ln u]\, m_L + 1 = m_L + 1: an equality that drops the floor, and as an equality it is false, 1.3607 at M=16M = 16 against the exact 1.0667. With the floor restored what holds is an inequality. Since ⌊x⌋≤x\lfloor x \rfloor \le x and E[−lnu]=∫01−lnudu=1E[-\ln u] = \int_0^1 -\ln u \, du = 1,

E[l+1]≤E[−lnu]mL+1=mL+1, E[l + 1] \le E[-\ln u]\, m_L + 1 = m_L + 1,

which at M=16M = 16 is 1+1/ln16=1.36071 + 1/\ln 16 = 1.3607. 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 M=16M = 16 gave a mean of 0.06675 against 1/15=0.066671/15 = 0.06667 (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 nn elements is the largest level drawn. Level kk is empty when none of the nn draws reaches it:

P(maxl<k)=(1−M−k)n≈e−nM−k, P(\max l < k) = (1 - M^{-k})^n \approx e^{-n M^{-k}},

using ln(1−x)≈−x\ln(1 - x) \approx -x for small xx. The expected number of elements at level kk or above is nM−kn M^{-k}, which falls below one at k=logMnk = \log_M n. For the fixture’s n=1018n = 1018 that is ln1018/lnM\ln 1018 / \ln M, which is 2.50 at M=16M = 16. The probability that a layer exists, from the formula above:

MM P(max≥2)P(\text{max} \ge 2) P(max≥3)P(\text{max} \ge 3) P(max≥4)P(\text{max} \ge 4) 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 M=16M = 16.

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 ℓ\ell contained the Delaunay graph of its elements, so that the walk on it reaches the nearest element to qq. The walk on layer ℓ\ell starts at the element where the walk on layer ℓ+1\ell + 1 stopped, which is the nearest layer-(ℓ+1)(\ell+1) element to qq, x∗x^*. Every step of the layer-ℓ\ell walk is strictly nearer to qq than x∗x^*, so it never visits another layer-(ℓ+1)(\ell+1) element: those are all at least as far as x∗x^*. Layer membership is independent of position, so each node a walk could step to is a layer-(ℓ+1)(\ell+1) element with probability

p=P(l≥ℓ+1∣l≥ℓ)=M−(ℓ+1)M−ℓ=1M, p = P(l \ge \ell + 1 \mid l \ge \ell) = \frac{M^{-(\ell+1)}}{M^{-\ell}} = \frac{1}{M},

and a walk of ss steps is possible only if none of its ss nodes was one: P(T≥s)≤(1−p)sP(T \ge s) \le (1 - p)^s. Then

E[T]=∑s≥1P(T≥s)≤∑s≥1(1−p)s=1−pp=M−1, E[T] = \sum_{s \ge 1} P(T \ge s) \le \sum_{s \ge 1} (1 - p)^s = \frac{1 - p}{p} = M - 1,

a bound that does not mention nn. With at most MM links per node on a layer above 0, a layer costs at most M(M−1+1)=M2M (M - 1 + 1) = M^2 distance computations in expectation (each expansion looks at up to MM links, and a walk of TT steps expands T+1T + 1 nodes, so the expected number of expansions is at most MM), and there are about logMn\log_M n layers.

The correction is to the paper’s own constants. It writes the probability that the next node belongs to the upper layer as p=exp(−mL)p = \exp(-m_L) and bounds the non-termination probability by exp(−smL)\exp(-s\, m_L), giving a step bound S=1/(1−exp(−mL))S = 1/(1 - \exp(-m_L)). With the paper’s own choice mL=1/lnMm_L = 1/\ln M that is p=e−1/lnMp = e^{-1/\ln M}, which is 0.697 at M=16M = 16, whereas its level law, derived above, gives p=e−1/mL=1/M=0.0625p = e^{-1/m_L} = 1/M = 0.0625. The statement is also internally inconsistent as read here: if the chance of stepping onto an upper-layer node were e−mLe^{-m_L}, the chance of surviving a step would be 1−e−mL1 - e^{-m_L}, not e−mLe^{-m_L}. The paper’s sum is S=∑s≥0e−smL=3.30S = \sum_{s \ge 0} e^{-s m_L} = 3.30 at M=16M = 16. With the survival chance per step corrected to 1−1/M1 - 1/M the same sum from s=0s = 0 is M=16M = 16, and the M−1=15M - 1 = 15 derived above is that sum without its s=0s = 0 term, since it counts the steps taken and a walk of no steps is the start. Both are independent of nn, 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, M=16M = 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 M2=256M^2 = 256; 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.

One query through a three-layer HNSW graph Three horizontal bands from top to bottom: layer 2 with two elements, layer 1 with six, layer 0 with twenty, every element of a higher layer also present below it, joined by dashed vertical lines. Edges join neighbours within each layer; layer 0 is the densest. The search enters at the enter point on layer 2, moves greedily with ef equal to one to the element nearest the query, drops to the same element on layer 1, moves again, drops to layer 0, and there runs the beam search with ef at least k, whose candidate list ends at the query's true neighbours. The path is drawn in amber; the query is a diamond at the lower right. A caption gives the level law: the probability that an element reaches level l is M to the minus l when mL is one over the natural log of M, and layer 0 allows 2M connections where the others allow M. Layer 2greedy, ef = 1: step to the nearest neighbour until none is nearer Layer 1greedy, ef = 1, from the element the layer above stopped at Layer 0the beam, ef ≥ k: expand the nearest candidate while it beats the worst kept enter point q W: the ef nearest found; the k best are returned level l = ⌊−ln(u) · mL⌋ with mL = 1 / ln M, so P(level ≥ l) = M⁻ˡ: layer 1 holds about n/M elements, layer 2 about n/M². Each element keeps at most M neighbours per layer above 0 and Mmax0 = 2M on layer 0. A tombstone keeps its edges and routes.

Layer 0 is a different cost. It does not stop at a local minimum; it keeps a beam of the efef 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 ll: ef=1, and only the nearest of WW 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 lclc 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 ee 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 ee drops its link to a node, that node’s link to ee 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 WW 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
}

CC is a min-heap, so line 5 is a pop, and WW 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 vv 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 nn entries between searches would cost nn. The counter wraps after 2322^{32} 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 WW, even when WW is not full. In the paper’s setting that cannot happen with ∣W∣<ef|W| < ef: nothing has been removed from WW, 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 WW. Candidates then outnumber the results, and a rejected nearest candidate can be farther than every element of a small WW while the accepted nodes lie beyond it. So the code breaks only when ∣W∣≥ef|W| \ge ef. 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: ee is kept when d(e,q)<d(e,r)d(e, q) < d(e, r) for every rr already in RR. A candidate that is at least as close to some kept neighbour as to qq is reachable through that neighbour and is not needed as a link. Take q=(0,0)q = (0,0) and candidates e1=(1,0)e_1 = (1, 0), e2=(2,0.1)e_2 = (2, 0.1) and e3=(−1.5,0)e_3 = (-1.5, 0), at distances 1.0000, 2.0025 and 1.5000 from qq (ex.py, talos). Algorithm 3 with M=2M = 2 keeps e1e_1 and e3e_3 by distance alone, and so does the heuristic here, but not for the same reason: e2e_2 is rejected because d(e2,e1)=1.0050<d(e2,q)=2.0025d(e_2, e_1) = 1.0050 < d(e_2, q) = 2.0025 (it lies behind e1e_1 and is reached through it), and e3e_3 is kept because d(e3,e1)=2.5000>d(e3,q)=1.5000d(e_3, e_1) = 2.5000 > d(e_3, q) = 1.5000 (it lies in another direction). Move e3e_3 to (−2.5,0)(-2.5, 0) and the two rules part: Algorithm 3 keeps e1e_1 and e2e_2, at 1.0000 and 2.0025, while the heuristic still rejects e2e_2 and keeps e3e_3, since d(e3,q)=2.5<d(e3,e1)=3.5d(e_3, q) = 2.5 < d(e_3, e_1) = 3.5, 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 RR up from the discarded ones so that nodes are not left with fewer than MM 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 ∣W∣|W| candidates is up to ∣W∣⋅M|W| \cdot M 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 M=6M = 6 and ef=10ef = 10, 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 KK elements from a list that line 7 limited to efef, so a search with ef<Kef < K cannot return KK elements; Search uses max(ef,k)\max(ef, k). SetEf accepts any ef≥1ef \ge 1 and the raise happens at search time, so a caller may set efef below kk without knowing kk and still gets kk results, from a beam of width kk. The returned list is W cut to kk, 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 kk 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 ±0.01\pm 0.01, 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 q=(MaxFloat32,−MaxFloat32)q = (\mathrm{MaxFloat32}, -\mathrm{MaxFloat32}) the row (MaxFloat32,MaxFloat32)(\mathrm{MaxFloat32}, \mathrm{MaxFloat32}) gives ∞+(−∞)\infty + (-\infty) 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 efef 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 efef accepted nodes have been found or the reachable graph is exhausted. It is not cheap. If a share ss of the nodes is accepted, independently of position, the walk must visit about ef/sef / s nodes before WW fills, and WW never fills, so the walk never stops early, if fewer than efef 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 efef 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 efef and costs 1,044 distances from ef=50ef = 50, more than the 1,018 points: the descent plus every node of layer 0. At ef=50ef = 50, ef/s=1,542ef / s = 1{,}542 exceeds nn, so the walk was always going to visit everything. The post-filter is cheap and wrong: at ef=200ef = 200 it keeps 4.09 hits on average, and at ef=10ef = 10 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 nn 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 MmaxM_{max}, the cap on the layers above 0, open; this book takes MM, so the cap and the number of links made per insertion are one number. Its other choices are the ones DefaultParams takes: Mmax0=2MM_{max0} = 2M, “simulations also suggest that 2∙M is a good choice for Mmax0”, and mL=1/lnMm_L = 1/\ln M. On MM 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 efef at every MM, and reaches 1.0000 at ef=50ef = 50 for M=16M = 16 and M=32M = 32. M=8M = 8 stops at 0.9969 at ef=100ef = 100 and ef=200ef = 200: 1 of the 320 true neighbours (32 queries by 10) is not found, and doubling efef 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 Mmax0=MM_{max0} = M graph. The cost is the other column. At ef=200ef = 200 and M=16M = 16 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 ef=50ef = 50, 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 M=16M = 16:

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 kk as well as efef, as chapter 32 warned: a list that swaps rank kk with rank k+1k+1 loses 1/k1/k. The same fixture at M=16M = 16 with k=1k = 1 and k=100k = 100 (straylight; the tables are -k 1 and -k 100 runs of the command above restricted to -M 16) gives, with the k=10k = 10 column repeated from above:

efef recall@1 recall@10 recall@100 dist/q at k=100k = 100
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 k=100k = 100 every efef below 100 is raised to 100, so the rows for ef=10ef = 10 to 100100 are one search (672 distances, the same recall), and only ef=200ef = 200 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 M=16M = 16:

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 M=16M = 16 agree with straylight’s to four digits, so the largest difference is 0.0000 and inside the ±0.01\pm 0.01 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 efef and MM. On the 100,000-point corpus recall is 0.2475 to 0.6931 at ef=10ef = 10 and 0.9691 to 0.9953 at ef=200ef = 200, and no row reaches 1. At ef=100ef = 100 the graphs with M=16M = 16 and M=32M = 32 clear 0.98 (0.9846 and 0.9910) and M=8M = 8 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 0.15128=1.700.15\sqrt{128} = 1.70, 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 ef=50ef = 50.

The cost of recall. dist/q is the table’s cost measure. At M=16M = 16 and ef=100ef = 100 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 efef column at M=16M = 16 the distances are 407, 583, 943, 1,312 and 1,825: 17.6 more per unit of efef 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 efef falls as the beam widens.

MM is memory and build time as well. The edges are 1,328,665, 2,513,356 and 4,259,954 for M=8,16,32M = 8, 16, 32, 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 (Mmax0+mLMmax)⋅4(M_{max0} + m_L M_{max}) \cdot 4 bytes per element (79.4, 151.1 and 292.9, derive.py, talos) and well below it for M=32M = 32: the average out-degree over all layers is 13.3, 25.1 and 42.6 against caps of 2M2M = 16, 32 and 64 on layer 0 alone. The vectors are 512 bytes per node, so at M=16M = 16 the graph adds about a fifth. Build time is 47.1, 93.1 and 120.6 s, one thread, each insertion a search at efConstructionefConstruction 200: at M=16M = 16, 0.93 ms and 3,338 distance computations per element on average. Doubling MM from 16 to 32 raised the recall at ef=100ef = 100 from 0.9846 to 0.9910 and the distances from 1,312 to 2,270; and M=32M = 32 at ef=100ef = 100 buys 0.0005 over M=16M = 16 at ef=200ef = 200 (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 M=8M = 8, ef=10ef = 10 and recall 0.9094, and at ef=200ef = 200 it is no faster (1.0 times at M=8M = 8, 0.9 at M=16M = 16 and M=32M = 32). 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 Mmax0=MM_{max0} = M. On straylight, at M=16M = 16:

corpus build recall@10 at efef 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
Mmax0=MM_{max0} = M 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
Mmax0=MM_{max0} = M 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 ef=10ef = 10) and wins above it, 1.0000 against 0.9875 at ef=100ef = 100, with 21% fewer links (393,851 against 501,205). On the fixture it is better at every efef (0.9312 against 0.9281 at ef=10ef = 10) 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 efef, and the clustered corpus at the wider beams and not at ef=10ef = 10. Mmax0=MM_{max0} = M is lower at equal efef everywhere, with 28% fewer links on the clustered corpus and 24% fewer on the fixture, and set against dist/q instead of efef the two builds are close at the high end of the clustered corpus: 0.9985 at 731 distances for Mmax0=MM_{max0} = M, 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 ef=50ef = 50 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 Mmax0=MM_{max0} = M 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 M=16M = 16 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 efef grows. It fails below 0.95 at ef=100ef = 100 and below 0.999 at ef=200ef = 200. 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 M=16M = 16 and at M=8M = 8, and say why the table’s P(max≥4)P(\text{max} \ge 4) for M=8M = 8 equals its P(max≥3)P(\text{max} \ge 3) for M=16M = 16.

Answer

Level kk is empty when none of the nn draws reaches it, so P(layer 3 exists)=1−(1−M−3)nP(\text{layer } 3 \text{ exists}) = 1 - (1 - M^{-3})^n. At M=16M = 16, 16−3=1/409616^{-3} = 1/4096 and (1−1/4096)1018=e1018ln(1−1/4096)≈e−0.2486=0.7799(1 - 1/4096)^{1018} = e^{1018 \ln(1 - 1/4096)} \approx e^{-0.2486} = 0.7799, so the probability is 0.2201. At M=8M = 8, 8−3=1/5128^{-3} = 1/512 and (1−1/512)1018≈e−1.990=0.1367(1 - 1/512)^{1018} \approx e^{-1.990} = 0.1367, so it is 0.8633. Both agree with the exact values the table prints (facts.py, talos). The M=8M = 8 entry for level 4 is 1−(1−8−4)10181 - (1 - 8^{-4})^{1018}, and 84=4096=1638^4 = 4096 = 16^3: the two parameters give the same per-draw probability for those two levels, so the same number, 0.2201.

(b) Set Mmax0=MM_{max0} = M (-mmax0-mult 1) and rerun the fixture bench at M=16M = 16. 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 efef, and fewer links to expand mean fewer distances; the walkthrough’s table shows both. The new part is the ceiling. At ef≥50ef \ge 50 the recall stops at 0.9969 and stays there up to ef=200ef = 200: one true neighbour in 320 is never returned. A scratch test that builds both graphs (talos; seed 1, M=16M = 16) 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 Mmax0=MM_{max0} = M; 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 ef<Kef < K not return KK elements, and what does Search do about it? Then take k=100k = 100 and ef=150ef = 150 on the fixture at M=16M = 16: is it one of the searches in the k=100k = 100 table, and between which two rows’ dist/q must its cost lie?

Answer

Lines 16 and 17 of Algorithm 2 trim WW to efef at every admission, so at most efef elements survive to line 8 of Algorithm 5. Search uses max(ef,k)\max(ef, k), and TestHNSWEfBelowK asks for 20 hits at ef=1ef = 1 and requires 20. For ef=150ef = 150 the beam is max(150,100)=150\max(150, 100) = 150, 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 k=10k = 10 compare post-filtering, pre-filtering and filtering during traversal.

Answer

Post-filtering searches for efef results and keeps those that match. A returned result matches with probability 0.01 if the filter is independent of position, so ef=1,000ef = 1{,}000 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 ef=200ef = 200 row kept 4.09 of a possible 5 hits at a 3.2% filter. Pre-filtering scans the accepted 1,000 records exactly: 0.01nd=128,0000.01\,n\,d = 128{,}000 multiply-adds, plus the nn 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 kk accepted hits whenever the reachable graph holds kk. To fill WW with efef accepted nodes it must visit about ef/0.01=100efef / 0.01 = 100\,ef nodes, which at ef=50ef = 50 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 ef=efConstructionef = efConstruction, and by about how much. Check against both tables.

Answer

An insertion’s layer-0 search is Algorithm 2 at ef=200ef = 200 on the graph built so far, the same procedure as a query at ef=200ef = 200, 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 1/(M−1)=0.0671/(M-1) = 0.067 of them, from the level law), the selection (the heuristic compares each popped candidate with the kept neighbours, up to ∣W∣⋅M|W| \cdot M distances), and a shrink for each neighbour whose list overflowed, which recomputes that neighbour’s link distances and selects again. The measurements, at M=16M = 16: the fixture builds with 854,095 distances for 1,018 insertions, 839 each, against 878 for a query at ef=200ef = 200 (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 ef=200ef = 200 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 efef 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;
  • efef below kk;
  • 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 Mmax0M_{max0} on layer 0, more than MM somewhere on it, at most MM above;
  • the heuristic, through its effect: on a clustered corpus Algorithm 4 keeps fewer links than Algorithm 3;
  • ErrNonFinite on Add and Search;
  • 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

results matching ""

    No results matching ""