advanced24 min studyLesson 655 in Engineering

Build useful routes instead of only short edges

Explain neighbor diversity, construction search, degree accounting, and why graph quality limits later queries.

On this page

What you’ll understand

  • Compare nearest-only and diverse neighbor choices on clustered points.
  • Separate construction effort from query effort.
  • Account for directed adjacency entries without assuming uniform HNSW degree.

A proximity graph is a stored collection of choices about which points should lead to which other points. Those choices affect future queries long after construction finishes. Keeping only the numerically closest links can waste every slot inside one dense cluster and leave a poor route toward another region. A useful construction procedure balances local proximity with diverse directions and reachability. This is why doubling query exploration is not always a substitute for rebuilding: search can follow only the links that exist, and some construction mistakes impose a lasting navigation cost.

Diversify connections at cluster boundaries

The original HNSW neighbor-selection heuristic considers relationships among candidates, rather than simply taking the closest candidates to the inserted point. A candidate that offers a direction already well covered by a selected neighbor can be pruned in favor of another route. This encourages useful inter-region links, especially for clustered data. It is a heuristic with implementation details, not a guarantee that every cluster has a bridge or that each node has the same degree.

A small one-dimensional example makes the issue concrete. From a new point at zero, candidates near one and two are individually closer than a candidate at minus nine. A nearest-two rule spends both links on the same direction and nearby group. A diversity test can reject the point at two because it is even closer to the point at one than to the insertion point, leaving room for a candidate in the opposite direction. Geometry between candidates matters, not just their independent distances to the insertion.

accept⁡(v) ⟺ D(v,x)<D(v,r)for every r∈R\operatorname{accept}(v)\ \Longleftrightarrow\ D(v,x)<D(v,r)\quad\text{for every }r\in R
This is the core diverse-neighbor comparison with insertion point x, selected set R, and lower-is-better distance D; candidates are considered in increasing distance from x. It omits optional candidate extension, refill, and degree-pruning details of full HNSW construction.↔ Scroll wide equations horizontally.

Spend construction work where it changes the graph

hnswlib 0.8.0 distinguishes M, which influences connection count and memory, from ef_construction, which controls candidate exploration while building. A larger construction frontier can find more useful neighbors before pruning, at greater build cost. Search-time ef explores the already constructed graph. Tuning those parameters answers different questions, so preserve separate records for build duration, peak memory, graph size, and the later recall-latency curve.

Insertion order, level sampling, and parallel scheduling can affect the resulting graph. A fixed random seed helps define an experiment but does not automatically establish byte-identical graphs across all parallel executions or library versions. Save the actual built artifact when reproducibility matters. Compare several construction runs when measuring variability, and retain a held-out query set so the graph is not judged solely on queries used to select its build parameters.

Badjacency=sid∑v∈Vdeg⁡+(v)B_{\rm adjacency}=s_{\rm id}\sum_{v\in V}\deg^{+}(v)
This is adjacency-ID payload only, with bytes per stored neighbor identifier sid and directed adjacency-entry count deg⁺. It excludes vector payloads, per-list headers, unused capacity, higher-level metadata, and allocator overhead; an undirected edge stored twice contributes two entries.↔ Scroll wide equations horizontally.

Inspect the graph you built

Degree distributions and connected-component checks reveal failures that a single recall number can hide. A connected graph can still have poor greedy routes, so connectivity is necessary for some traversal guarantees but insufficient for fast high-recall navigation. Conversely, a disconnected component is unreachable from an entry point confined to another component regardless of how often the same local walk repeats. Examine difficult clusters and compare visited nodes with exact neighbors before attributing every miss to insufficient query budget.

A rebuild decision should connect an observed failure to a mechanism. If recall improves sharply when query effort rises, the graph may be adequate but underexplored. If a broad effort sweep plateaus on the same slice, inspect missing bridges, deletions, duplicates, and changes in the embedding distribution. Building a fresh graph with improved construction settings can test that hypothesis. Report the extra build and memory costs alongside any faster queries, because the system pays for both phases.

One redundant edge versus an opposite-direction route

Use insertion point x=0, candidates a=1, b=2, and c=−9, and Euclidean distance. Select at most two neighbors. Compare nearest-two selection with the stated diversity test, processing candidates in increasing distance from x and without refilling rejected candidates.

  1. Distances from x are 1, 2, and 9, so nearest-two selection keeps {a,b}. Both selected edges head toward positive coordinates; the farther candidate c offers a different direction but loses under proximity alone.

  2. The diversity procedure first accepts a because the selected set is empty. For b, D(b,x)=2 while D(b,a)=1, so the required 2<1 comparison fails and b is rejected.

  3. For c, D(c,x)=9 and D(c,a)=10, so 9<10 succeeds. The final selected set is {a,c}, using two slots with one route in each direction. This verifies the local comparison, not a global search guarantee.

The result

The farther candidate can provide useful diversity because the nearer alternative is redundant with an existing edge. Full HNSW construction includes additional search, capacity, and optional refill rules beyond this isolated test.

Explore the model

Interactive lab

Interactive lab · modular

A transition rule can isolate a subset

Reset, set Modulus m to 12 and Additive step a to 4. Predict period 3 and residue 4 after Step, then 8 after another Step. Reset, set m to 12 and a to 5, predict period 12 and residue 5 after one Step. This deterministic additive orbit shows reachable subsets only; it does not construct diverse neighbors or measure HNSW connectivity.

A transition rule can isolate a subsetAddition modulo m starts at zero: rₙ = na mod m. Playback advances two additions per second. The orbit has period m/gcd(m,a), including period one for a = 0. This is not a cryptographic security test or a primality algorithm. Current readings: Residue r0: 0; Orbit period · m/gcd(m,a): 12; Distinct residues visited: 1 of 12. All parameters are adjustable with the labeled controls below.Repeated addition modulo 12: the current residue is 0, and the orbit period is 12.01234567891011+ 5mod 12An additive orbitn = 0rₙ = 0Period = 12Cycle starts at 0:0 → 5 → 10 → 3 →8 → 1 → 6 → 11 →4 → 9 → 2 → 7 → 0Exact residues · two additions per second
Additive orbitCurrent residue / next edge
Residue r0
0
Orbit period · m/gcd(m,a)
12
Distinct residues visited
1 of 12
t = 0 s

Addition modulo m starts at zero: rₙ = na mod m. Playback advances two additions per second. The orbit has period m/gcd(m,a), including period one for a = 0. This is not a cryptographic security test or a primality algorithm. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forReachability follows the stored transition rule; repeated execution does not add a missing route.

Check your understanding

Which change directly changes candidate exploration while building a hnswlib 0.8.0 graph?

Try it yourself

A toy graph has four vertices, each storing three directed neighbor IDs of four bytes. Compute adjacency-ID payload. Would three undirected edges stored in both directions occupy the same payload?

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Count stored adjacency entries, not just unique vertex pairs.

Compare with the solution

The first graph stores 4×3=12 adjacency entries and therefore 12×4=48 bytes of neighbor-ID payload. Three undirected edges stored in both directions produce 6 entries and 24 bytes, so the payload is different. Neither number includes vector values, list headers, reserved capacity, or allocator overhead, which must be measured separately for a real index.

Take it with you

  • Neighbor diversity can preserve routes that nearest-only selection discards.
  • Construction effort and query exploration are separate budgets.
  • Connectivity and adjacency payload are measurable properties, not automatic degree assumptions.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.