Repository navigation
perf: make HNSW cheaper to load - #6798
Conversation
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Xuanwo
left a comment
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
I prefer not to use macro_rules.
| 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 { |
There was a problem hiding this comment.
Do we really need such function?
de746e7 to
719460f
Compare
f0cded9 to
24d7099
Compare
| // 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!( |
There was a problem hiding this comment.
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.
b824d9c to
b71d18e
Compare
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]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
b71d18e to
620162c
Compare
…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]>
…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]>
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__neighborsListArrayvalue buffer. This unblocks a future zero-copyCacheCodec(#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
HnswCorenow holds anHnswGraphenum instead ofArc<Vec<GraphBuilderNode>>:Built(in-memory, produced by the online builder /index_vectors— build path untouched) orLoaded(Arrow-backed, search-only).LoadedHnswGraphretains the fullRecordBatchplus per-level zero-copyListArrayneighbor views and a tiny per-upper-levelid -> rowlookup; the geometrically-shrinking upper levels keep these maps negligible.Denselookup (row == __vector_id, asserted in debug); upper levels use aSparsemap keyed by__vector_idvalue, exactly mirroring the old per-nodeload— including the knownlevel_offsetsquirk where the entry-point node is written byto_batchat every level but counted only at level 0, so upper-level slices are off-by-one and duplicate ids resolve last-write-wins.Graph/BorrowingGraphseam; 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 throughlance_arrow::ipcwithout rebuilding the graph.Correctness & compatibility
loadsemantics are preserved bit-for-bit, including duplicate-id last-write-wins across a misaligned slice boundary;build -> to_batch -> load -> to_batchis byte-stable (b1 == b2).HNSW::nodes()now panics on a loaded graph (documented;GraphBuilderNodeis 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_hnswwas measured by running this same bench against the parent commit's reconstruction-basedbuilder.rs(only that file swapped), so it is a like-for-likeHNSW::loadcomparison.load_hnsw(100000x128)search_hnsw100000x128(built, baseline)search_hnsw_loaded100000x128Load drops from ~127 ms (allocating 100k
GraphBuilderNodes + per-nodeOrderedNodeadjacency) 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 fullcargo benchbefore 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-rowto_batch→load→ empty graph round-trip.test_to_batch_roundtrip_loaded— the IVF partition-cache path:to_batchon 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.test_builder_write_load(2048, L2, file round-trip) andtest_builder_write_load_binary_hamming(256, Hamming) continue to pass unchanged.