Skip to content

perf: make HNSW cheaper to load - #6798

Merged
Xuanwo merged 3 commits into
lance-format:mainfrom
wombatu-kun:perf/hnsw-cheaper-load
Jun 3, 2026
Merged

Xuanwo merged 3 commits into
lance-format:mainfrom
wombatu-kun:perf/hnsw-cheaper-load

Conversation

@wombatu-kun

@wombatu-kun wombatu-kun commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #6746. Loading an HNSW partition no longer reconstructs a per-node Vec<GraphBuilderNode> / Vec<OrderedNode> graph. The loaded graph is now backed directly by the on-disk Arrow buffers, with neighbor adjacency served as zero-copy &[u32] slices straight out of the __neighbors ListArray value buffer. This unblocks a future zero-copy CacheCodec (#6745).

Motivation

Per #6746, loading an HNSW partition required expensive per-node reconstruction, which makes a zero-copy IPC CacheCodec (#6745) infeasible. The fix is to keep the Arrow data and offsets as the graph's backing store while preserving current search behavior and performance.

What changed

  • HnswCore now holds an HnswGraph enum instead of Arc<Vec<GraphBuilderNode>>: Built (in-memory, produced by the online builder / index_vectors — build path untouched) or Loaded (Arrow-backed, search-only).
  • LoadedHnswGraph retains the full RecordBatch plus per-level zero-copy ListArray neighbor views and a tiny per-upper-level id -> row lookup; the geometrically-shrinking upper levels keep these maps negligible.
  • Level 0 uses a Dense lookup (row == __vector_id, asserted in debug); upper levels use a Sparse map keyed by __vector_id value, exactly mirroring the old per-node load — including the known level_offsets quirk where the entry-point node is written by to_batch at every level but counted only at level 0, so upper-level slices are off-by-one and duplicate ids resolve last-write-wins.
  • The search loop is single-sourced across both backends via a local macro, keeping the existing Graph / BorrowingGraph seam; search is unchanged.
  • to_batch() on a loaded graph is a verbatim passthrough (re-stamped metadata only), so the IVF partition cache (ivf/partition_serde.rs, which re-serializes loaded indices) round-trips losslessly and Implement CacheCode for HNSW indices #6745 can write/read it through lance_arrow::ipc without rebuilding the graph.

Correctness & compatibility

  • Loaded-graph search is bit-identical to the in-memory build across L2 / Dot / Hamming and graph sizes (single node, pair, multi-level 2048).
  • Old load semantics are preserved bit-for-bit, including duplicate-id last-write-wins across a misaligned slice boundary; build -> to_batch -> load -> to_batch is byte-stable (b1 == b2).
  • No public API signature change. HNSW::nodes() now panics on a loaded graph (documented; GraphBuilderNode is internal API and there are no in-tree callers).

Benchmarks

criterion --quick, 100000×128, L2, k=100, ef=300 (rust/lance-index/benches/hnsw.rs). The "before" load_hnsw was measured by running this same bench against the parent commit's reconstruction-based builder.rs (only that file swapped), so it is a like-for-like HNSW::load comparison.

Benchmark Before (reconstruction load) After (Arrow-backed) Δ
load_hnsw(100000x128) ~127 ms ~90.8 µs ~1,400× faster
search_hnsw100000x128 (built, baseline) ~700.7 µs ~700.7 µs unchanged
search_hnsw_loaded100000x128 n/a ~690.4 µs on par with built (within noise)

Load drops from ~127 ms (allocating 100k GraphBuilderNodes + per-node OrderedNode adjacency) to ~91 µs (batch slice + tiny upper-level sparse maps), while search on the Arrow-backed graph stays on par with the in-memory build. Numbers are --quick/indicative; the ~3-orders-of-magnitude load delta is well outside noise. Re-run a full cargo bench before merge for headline figures.

Tests

All in rust/lance-index/src/vector/hnsw/builder.rs:

  • test_loaded_search_parity_and_recall (rstest: L2 single / L2 pair / L2 2048 / Dot 2048) — built vs loaded parity plus recall ≥ 0.5.
  • test_loaded_level_offsets_misalignment_invariant — pins the entry-point-written-at-every-level surplus (batch.num_rows() > sum(level_count)), the Dense level-0 precondition, and loaded↔built search parity despite the misalignment.
  • test_loaded_empty_index — 0-row to_batch → load → empty graph round-trip.
  • test_to_batch_roundtrip_loaded — the IVF partition-cache path: to_batch on a loaded index is byte-stable and reloads/searches identically.
  • test_loaded_graph_is_arrow_backed — loaded graph is strictly lighter than the built representation.
  • Pre-existing test_builder_write_load (2048, L2, file round-trip) and test_builder_write_load_binary_hamming (256, Hamming) continue to pass unchanged.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@codecov

codecov Bot commented May 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.98837% with 31 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
rust/lance-index/src/vector/hnsw/builder.rs 90.98% 24 Missing and 7 partials ⚠️

📢 Thoughts on this report? Let us know!

@wjones127 wjones127 self-assigned this May 15, 2026

@Xuanwo Xuanwo left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for working on this!

match &self.inner.graph {
HnswGraph::Built(nodes) => nodes.clone(),
HnswGraph::Loaded(_) => {
panic!("HNSW::nodes() is only available on a freshly built graph, not a loaded one")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it safe to panic here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good question. The census found no in-tree callers of nodes() anywhere (rust/, python/, java/), and nodes() was already being modified in this PR. Rather than rely on the panic being unreachable, I changed the signature to Option<Arc<Vec<GraphBuilderNode>>> — it now returns None for a disk-loaded (Arrow-backed) graph instead of panicking. Done in 719460f.

// backends; only the view types differ. A local macro keeps the
// search loop single-sourced without a generic helper whose return
// type would have to name the view lifetime.
macro_rules! run_search {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer not to use macro_rules.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 719460f

impl HNSW {
/// Whether the graph is the Arrow-backed (disk-loaded) representation
/// rather than the in-memory `Vec<GraphBuilderNode>` build representation.
pub(crate) fn is_loaded_graph(&self) -> bool {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really need such function?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No. Removed it in 719460f

@wombatu-kun
wombatu-kun force-pushed the perf/hnsw-cheaper-load branch from de746e7 to 719460f Compare May 16, 2026 00:44
@wombatu-kun
wombatu-kun requested a review from Xuanwo May 16, 2026 01:09
@wombatu-kun
wombatu-kun force-pushed the perf/hnsw-cheaper-load branch 3 times, most recently from f0cded9 to 24d7099 Compare May 20, 2026 07:47
// ascending `__vector_id` (== node id) order, and the level-0
// slice is exactly `[0, N)`, so the row index *is* the node
// id.
debug_assert!(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be a runtime validation instead of a debug_assert!. The new Dense lookup makes row == __vector_id a required persisted-format invariant; otherwise release builds can load the batch and silently search against the wrong neighbor lists. Please reject invalid level-0 ids in load() with Error::index and validate entry_point < N as part of the same invariant check.

@wombatu-kun wombatu-kun Jun 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed b71d18e

@github-actions github-actions Bot added the A-index Vector index, linalg, tokenizer label Jun 3, 2026
@wombatu-kun
wombatu-kun force-pushed the perf/hnsw-cheaper-load branch from b824d9c to b71d18e Compare June 3, 2026 09:23
wombatu-kun and others added 3 commits June 3, 2026 16:30
Back the loaded HNSW graph directly by the on-disk Arrow buffers instead of reconstructing per-node Vec<GraphBuilderNode>/Vec<OrderedNode> on every load. Search is unchanged (same Graph/BorrowingGraph seam), the build path is untouched, and to_batch() on a loaded graph is a verbatim passthrough so the IVF partition-cache round-trip is preserved. This unblocks a future zero-copy CacheCodec (lance-format#6745).

Add a load_hnsw / search_hnsw_loaded benchmark (load latency plus search on the Arrow-backed graph, directly comparable to the existing built-graph search bench) and a test_loaded_level_offsets_misalignment_invariant regression test that pins the entry-point-written-at-every-level surplus the loaded path's Sparse upper-level lookup depends on.

Closes lance-format#6746

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@wombatu-kun
wombatu-kun force-pushed the perf/hnsw-cheaper-load branch from b71d18e to 620162c Compare June 3, 2026 09:32
@wombatu-kun
wombatu-kun requested a review from Xuanwo June 3, 2026 09:35

@Xuanwo Xuanwo left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you!

@Xuanwo
Xuanwo merged commit e7cbad9 into lance-format:main Jun 3, 2026
29 of 30 checks passed
Xuanwo pushed a commit that referenced this pull request Aug 1, 2026
…rtitions (#8136)

Closes #8135

## Summary

HNSW index partitions no longer fetch the `_distance` column from
storage. `IvfSubIndex` gains an optional `read_columns()` projection
naming the columns `load` actually consumes; `HNSW` declares
`__vector_id` and `__neighbors`, and `load_partition_entry` reads
through `FileReader::read_stream_projected` when a sub-index declares
one.

This is the second half of #6798. That PR stopped materializing
`_distance` in memory but left it being fetched from storage, because
changing the on-disk schema was out of scope for a load-path performance
fix.

## Why a read projection and not a schema change

Dropping the column from `to_batch()` would break forward compatibility:
readers older than v8.0.0 access it as `batch[DIST_COL]`, a panicking
indexer rather than an `Option`. Gating that behind an index version
bump would silently disable the index for every older reader and send
those queries to a full scan. A read projection has no such cost: the
file still carries the column, readers of every version keep working,
and no index version is bumped. Removing it from the format stays
available as a separate, versioned change later.

## Results

All figures are bytes fetched from storage, measured with
`ObjectStore::io_stats_incremental` and summed over every partition.
Both projections are exercised against the same row ranges in one
binary, so nothing is confounded by build layout, and the projected read
is taken first so it pays any first-touch cost rather than benefiting
from it.

**End-to-end, one cold partition load.** `IVF_HNSW_SQ`, 100,000 rows at
dim 768, `nlist = 2`, `m = 20`. This is the number that matters in
practice: it includes the auxiliary quantized storage the load also has
to fetch.

| Cold partition load | Bytes |
| --- | --- |
| Before | 93,932,846 |
| After | 83,379,448 |
| Saved | 10,553,398 (11.2%) |

**The graph read itself** drops 16,882,542 -> 6,329,144, a 62.5% cut. It
is 18.0% of the partition at this dimension, which is where the 11.2%
comes from.

That 62.5% is stable across configurations: an index over 500,000 rows
at dim 32 with `nlist = 4` (525,902 graph rows, ~131k nodes per
partition) gives 102,548,810 -> 38,706,238, or 62.3%, and 50,000 rows
gives 66.7%. The saving is a property of the graph encoding, not of one
benchmark: neighbor ids bitpack against the partition's node count while
f32 distances do not compress, so the column nothing reads is also the
one that stays wide.

What does vary is how much of a partition the graph accounts for,
because graph cost per vector depends on `m` and the id bit-width while
quantized storage scales with dimension. At dim 768 storage is 770
B/vector against 169 B/vector of graph, giving the 18.0% share above; at
low dimensions the graph dominates and the end-to-end saving approaches
the 62% figure. So 11.2% is the conservative end of the range, not the
typical one. The same bytes also stop occupying `LanceCache`.

## Tests

All in `rust/lance/src/index/vector/ivf/v2.rs`. The first three fail
without the change.

- `test_hnsw_partition_load_reads_only_graph_columns` - the written
index file still declares all three columns while every loaded partition
carries only two, re-checked after an append plus a delta merge.
- `test_hnsw_projected_read_matches_full_read` - the two surviving
columns are identical to the same columns of a full-schema read, per
partition. `__neighbors.item` and `_distance.item` are both 4-byte
`List` children named `item`, so a mis-mapped column index would
reinterpret distances as neighbor ids with no type error to catch it.
- `test_hnsw_read_projection_moves_fewer_bytes` - the declared
projection moves strictly fewer bytes than the full read over a real
partition range, measured with `io_stats_incremental`. The projected
read is taken first so it pays any first-touch cost.
- `test_prewarm_and_query_with_serializing_backend` - extended with an
`IVF_HNSW_SQ` case alongside the existing IVF_PQ one, so the narrowed
batch round-trips through cache serialization, reloads, and still meets
the recall bar with no extra I/O.

Co-authored-by: Vova Kolmakov <[email protected]>
Xuanwo pushed a commit that referenced this pull request Nov 30, 2026
…m test (#11629)

Closes #6745.

## Summary

Most of #6745 had already been done by earlier PRs. This PR adds no new
codec or serialization logic. It only extends test coverage to the two
IVF+HNSW variants that weren't tested yet.

The issue asked for two things. Both were already on `main`:

1. **Zero-copy Arrow IPC serde for HNSW cache entries.** HNSW partitions
go through the generic IVF `PartitionEntry<S, Q>` codecs in
`rust/lance/src/index/vector/ivf/partition_serde.rs`. Those write the
sub-index with `write_ipc(index.to_batch())` and read it back through
`HNSW::load`. Since #6798, `HNSW::load` keeps the Arrow batch and serves
neighbor lists zero-copy (`LoadedHnswGraph`). `to_batch()` hands that
batch back unchanged, so a loaded graph round-trips through the cache
without being rebuilt.
2. **A test showing that, after prewarm, a serializing backend serves
HNSW queries with no IO.**
`test_prewarm_and_query_with_serializing_backend` prewarms through
`SerializingCacheBackend`, restarts the backend so only serialized
entries survive, queries, checks recall, and asserts `read_iops == 0`.
It already covered IVF_HNSW_SQ and IVF_HNSW_RQ.

Earlier PRs that did the work:

- #6090: prewarm for IVF indices and the no-IO assertion
- #6223: `CacheCodec` and the IVF partition codecs, which are generic
over the sub-index
- #6798: zero-copy HNSW loading
- #8136: the IVF_HNSW_SQ case
- #10522: the IVF_HNSW_RQ case

## Changes

Adds `ivf_hnsw_pq` (`PartitionEntry<HNSW, ProductQuantizer>`) and
`ivf_hnsw_flat` (`PartitionEntry<HNSW, FlatQuantizer>`) cases to
`test_prewarm_and_query_with_serializing_backend`. Every IVF+HNSW
variant is now covered by the prewarm, restart and no-IO check.

## Testing

- `cargo test --profile ci -p lance --lib
test_prewarm_and_query_with_serializing_backend`: all 5 cases pass
(`ivf_pq`, `ivf_hnsw_sq`, `ivf_hnsw_rq`, and the new `ivf_hnsw_pq` and
`ivf_hnsw_flat`) in 1.55s.
- `cargo fmt --all -- --check`: clean.
- `cargo clippy --profile ci -p lance --tests --benches -- -D warnings`:
clean. Clippy was run on the touched crate only, not with `--all`.

---
_Generated by [Claude Code](https://claude.ai/code)_

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-index Vector index, linalg, tokenizer performance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Make HNSW cheaper to load

3 participants