Skip to content

feat(index)!: add IVF_HNSW_RQ vector index - #10522

Merged
Xuanwo merged 3 commits into
lance-format:mainfrom
cwj0bzxg:feat/ivf-hnsw-rq-v2
Nov 5, 2026
Merged

Xuanwo merged 3 commits into
lance-format:mainfrom
cwj0bzxg:feat/ivf-hnsw-rq-v2

Conversation

@cwj0bzxg

@cwj0bzxg cwj0bzxg commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

IVF_RQ compresses vectors to 1–9 bits with RaBitQ (RQ), but linearly scans every row in each probed partition. This PR adds IVF_HNSW_RQ (num_bits 1–9, default 5) to index each IVF partition with an HNSW graph—matching IVF_HNSW_PQ and IVF_HNSW_SQ—with no on-disk format or protobuf changes.

Instead of adding new storage formats or evaluating expensive multi-bit codes on every graph hop, this PR builds on two key ideas:

  1. Graph build reuses RQPairScorer (bq/pairwise.rs): VectorStore::with_centroid and dist_calculator_from_id wire Lance's existing symmetric code-to-code scorer into HNSW construction. The builder stages rows on a temporary clone and drops them right after building each partition.
  2. Graph search walks on 1-bit sign bits and reranks with full multi-bit codes: Every multi-bit RQ code already embeds 1-bit sign bits. During graph traversal, OneBitWalk (bq/walk.rs) quantizes the rotated query to 4 bits and scores visited nodes with fast bit-plane AND + popcount operations (VectorStore::for_graph_search / graph_dist_calculator). Once the walk collects ef candidates, VectorStore::rerank rescores only those ef finalists with the full multi-bit codes and raw query. This two-stage search delivers 2.2–3.1x higher QPS at equal recall than scoring every visited node with the full multi-bit RQ estimator.

Other Details

  • Exact range filtering: DistCalculator::in_range uses the 1-bit walk's error bound to filter clear hits/misses during traversal and rescores only candidates near [lower_bound, upper_bound), so range bounds apply to the reranked multi-bit distances.
  • Lifecycle & bindings: Supports L2, Cosine, and Dot metrics, Fast and Matrix rotations, optimize, retrain, distributed segment merge, compaction remap, and Python / Java / namespace bindings.
  • Trade-offs: Loaded HNSW partitions keep unpacked sign words in memory (dim / 8 bytes/row). Graph construction stages ~1 byte/dim/row (2 bytes at 9 bits), and 9-bit builds run RQPairScorer's scalar path without AVX-512.

Benchmarks

1M vectors in a single IVF partition, single-threaded queries (recall@10) on an AVX2 CPU (no AVX-512), 5-bit RQ, shared rotation and identical on-disk codes:

Dataset ef Full multi-bit on walk (recall / QPS) 1-bit walk + multi-bit rerank (recall / QPS) Speedup
GIST-1M (960d, L2)
Build: 147s, 822 MB
32
64
128
256
512
0.702 / 193
0.808 / 154
0.883 / 110
0.925 / 71
0.943 / 44
0.632 / 468
0.767 / 412
0.864 / 319
0.917 / 237
0.942 / 163
2.4x
2.7x
2.9x
3.3x
3.7x
Cohere-1M (768d, Cosine)
Build: 118s, 709 MB
32
64
128
256
512
0.921 / 225
0.951 / 184
0.967 / 137
0.976 / 90
0.979 / 56
0.901 / 496
0.944 / 426
0.964 / 357
0.973 / 266
0.978 / 176
2.2x
2.3x
2.6x
3.0x
3.2x

BREAKING CHANGE

IVF_HNSW_RQ writes vector index version 3 and raises IndexType::max_vector_version() from 2 to 3. Older Lance readers support versions up to 2, so they skip version 3 indices and fall back to flat search (verified by IvfHnswRqVectorIndex in the Python compatibility suite).

Supersedes #9771.

Validation

Validated locally on the current source tree (7e6e4bb, macOS arm64):

  • Rust HNSW-RQ and lifecycle regressions: 19 tests passed, plus 12 HNSW final-score bound cases. This includes stable-row-id create/search/append/optimize/reopen.
  • Python: 54 targeted index/search tests passed after rebuilding the extension; full uv run make lint passed.
  • Java: public IVF_RQ/IVF_HNSW_RQ create/query tests passed (2), JNI Rust tests passed (35), and Java/JNI Clippy passed.
  • cargo clippy --profile ci --all --tests --benches -- -D warnings, cargo fmt --all -- --check, and Java Spotless check passed.

Hosted CI results on this revision are reported in the checks tab; this section only describes local verification. The benchmark table above is author-reported and was not rerun for this revision.

@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.

@github-actions github-actions Bot added A-python Python bindings A-index Vector index, linalg, tokenizer A-java Java bindings + JNI A-namespace Namespace impls enhancement New feature or request breaking-change labels Oct 30, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Oct 30, 2026
@cwj0bzxg
cwj0bzxg force-pushed the feat/ivf-hnsw-rq-v2 branch from a8e895b to 5fde86a Compare November 2, 2026 07:39
@lance-gatekeeper lance-gatekeeper Bot removed K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Nov 2, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Nov 2, 2026
Add IVF_HNSW_RQ: each IVF partition links its rows with an HNSW graph over
their RaBitQ codes, with num_bits from 1 to 9 (default 5) and the L2, cosine
and dot metrics.

- Build: HNSW construction scores stored rows against each other with the
  existing RQPairScorer. VectorStore::with_centroid stages a partition's
  rows, and dist_calculator_from_id anchors the calculator on one of them.
- Search: the graph search walks on a 1-bit estimate (bq/walk.rs quantizes
  the rotated query to 4 bits for AND + popcount over bit planes), keeps ef
  candidates on every path, and VectorStore::rerank rescores them with the
  full codes and the raw query. Range bounds apply to the reranked
  distances through DistCalculator::in_range.
- Format: the auxiliary file holds exactly the IVF_RQ raw-query columns and
  the graph uses the existing HNSW layout. The index records index version
  3, the new maximum vector index version, so released readers skip it and
  answer vector queries with a flat search.
- Maintenance: append and optimize, retrain, distributed builds with
  segment merge, compaction remap and initialize_vector_index build or
  repair the graphs with the same scorer.
- Bindings: Python, Java and the directory namespace accept the new type.

BREAKING CHANGE: IndexType::max_vector_version() rises from 2 to 3.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cwj0bzxg
cwj0bzxg force-pushed the feat/ivf-hnsw-rq-v2 branch from 5fde86a to c7bd793 Compare November 4, 2026 09:51
@lance-gatekeeper lance-gatekeeper Bot removed K-risk Latest Gatekeeper recommendation includes a non-blocking risk. K-approved Latest Gatekeeper recommendation permits acceptance. labels Nov 4, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Nov 4, 2026
Add a stable-row-id create/search/append/optimize/reopen regression and exercise the Java public create/query path.
@lance-gatekeeper lance-gatekeeper Bot removed K-risk Latest Gatekeeper recommendation includes a non-blocking risk. K-approved Latest Gatekeeper recommendation permits acceptance. labels Nov 5, 2026

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Gate recommendation: approve with a non-blocking risk.

Estimated RQ pruning can omit eligible matches, including with selective filters. This retains the trade-off the author accepted in the superseded PR; full-code reranking and the final range check keep returned scores within [lower, upper).

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Nov 5, 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.

Reviewed the full delta from the author revision through the current head, including the fresh-main merge and the added stable-row-id and Java public-route coverage.

No blocking findings. All applicable hosted Rust, Python (including compatibility), Java/JNI, lint, license, module-size, and typo checks pass on this revision. The documented estimated-RQ pruning risk remains non-blocking because final scores are range-checked.

@Xuanwo
Xuanwo merged commit 05a128c into lance-format:main Nov 5, 2026
45 of 47 checks passed
Xuanwo added a commit that referenced this pull request Nov 17, 2026
…full multi-bit (#10910)

## Summary

`IVF_HNSW_RQ` landed in #10522 with one way to score HNSW nodes: walk
the graph with the 1-bit sign codes, then rerank the `ef` finalists with
the full multi-bit codes. #10648 implemented the same index but scored
every visited node with the full multi-bit RQ estimator. This PR
combines the two: both scoring paths are kept, behind a new query-time
option, and the full multi-bit path is the default.

- `RqGraphScoring::MultiBit` (default): every visited node is scored
with the full multi-bit RQ estimator. No rerank step. This is the
scoring from #10648.
- `RqGraphScoring::OneBitRerank`: the 1-bit walk plus multi-bit rerank
from #10522.

Graph build is unchanged. Both PRs build the graph with the existing
`RQPairScorer`, and this PR keeps the build path from #10522.

## Why multi-bit is the default

The 1-bit walk is faster per node, but its coarser scores can steer the
beam away from true neighbors, so it needs a larger `ef` to reach the
same recall. Scoring with the full codes gets more recall out of each
`ef`. Users who want the faster walk can opt in for each query.

## API

- Rust: `lance_index::vector::RqGraphScoring`, a
`Query::rq_graph_scoring` field, and `Scanner::rq_graph_scoring(...)`.
- Python: `nearest={..., "rq_graph_scoring": "multi_bit" |
"one_bit_rerank"}`. It is also a keyword argument on
`ScannerBuilder.nearest` and `VectorSearchQuery`. Rust validates the
value; an unknown value raises `ValueError`.
- `ann.proto`: `VectorQueryProto.rq_graph_scoring = 17`, so distributed
plans carry the setting. `MultiBit = 0`, so a producer that doesn't set
the field gets the default. This is an execution wire schema, not a
persisted format.
- Other index types ignore the option.

## Implementation

- `HnswQueryParams` carries `rq_graph_scoring`. In `MultiBit` mode the
HNSW search uses `VectorStore::dist_calculator`, searches with `k`, and
skips `VectorStore::rerank`, which is the search path from before
#10522. In `OneBitRerank` mode it uses `graph_dist_calculator` and keeps
`ef` candidates for `rerank`, as #10522 does.
- Range bounds stay correct in both modes. With no walk, `in_range`
falls back to the plain bound check on the exact multi-bit score.
- Merging current `main` needed only mechanical propagation: the new
field is set to the default at the
`Query` and `HnswQueryParams` literals that `main` added, and
`QuantizedRefinementKey` now binds
`rq_graph_scoring` so a cached quantized refinement is not shared across
scoring modes.

## Benchmarks

IVF vs. IVF-HNSW, from #10648. This chart does not isolate the two
graph-scoring modes, so it doesn't measure the latency cost of changing
the default from the 1-bit walk to multi-bit scoring.

The two modes were also measured against each other on one index: the
first 100,000 base vectors and
1,000 queries of SIFT1M (128-d, L2, recall against an exact oracle on
the same subset), one
`IVF_HNSW_RQ` built once with one partition, 5-bit RQ, `k=10`,
`release-with-debug`,
single-threaded, aggregating 3 paired repeats at `ef=256` and 2 at
`ef=512` on `4b65729c`. Later commits only merge `main` and adjust a
test expectation.

| Scoring | `ef` | recall@10 | mean µs | p95 µs |
|---|---:|---:|---:|---:|
| `MultiBit` (default) | 256 | 0.9343 | 695.5 | 796.0 |
| `OneBitRerank` | 256 | 0.9087 | 622.6 | 678.1 |
| `MultiBit` | 512 | 0.9343 | 831.8 | 935.2 |
| `OneBitRerank` | 512 | 0.9280 | 744.9 | 811.3 |

At `ef=256` the 1-bit walk is about 10% faster and 2.6 points lower in
recall. Raising it to `ef=512`
does not reach `MultiBit` at `ef=256` (0.9280 vs 0.9343) and is slower
(744.9 vs 695.5 µs), so these
two points support keeping the multi-bit default; they do not establish
a recall ceiling or a
matched-recall crossover. The single partition isolates the
graph-scoring path and is not a claim
about multi-partition production workloads.

<img width="3900" height="780" alt="image"
src="https://github.com/user-attachments/assets/29461b95-f9e1-416a-bad2-ea3ce7b7e25f"
/>

## Breaking changes

- `lance_index::vector::Query`,
`lance_index::vector::hnsw::builder::HnswQueryParams`, and
`lance::pb::VectorQueryProto` gain a `rq_graph_scoring` field. Rust
callers that build these with struct literals must set it
(`Default::default()` keeps the new default).
- Existing `IVF_HNSW_RQ` queries now default to multi-bit scoring on
every visited node, which may be slower than the 1-bit walk released in
#10522. Rust and Python callers can keep the old behavior with
`rq_graph_scoring="one_bit_rerank"`. Java only gets the default for now.

## Trade-offs / follow-ups

- Loaded HNSW-RQ partitions still unpack the sign words (`dim / 8`
bytes/row) at load time, as on `main`, so either mode can be picked per
query. A follow-up could skip that work for deployments that never use
`OneBitRerank`.
- The Java binding does not expose the option yet. Java callers get the
default.

## Testing

- `test_rq_graph_scoring_selects_search_calculator`: each mode scores
nodes with the expected calculator, and the two calculators disagree.
- `test_hnsw_range_bounds_apply_to_reranked_distance` now runs in both
modes.
- `assert_ivf_hnsw_rq_search` (used by the stable-row-id lifecycle test)
checks index use and recall >= 0.8 in both modes, before and after
append/optimize/reopen.
- ANN proto round trip, including rejection of an unknown
`rq_graph_scoring` value. Scanner setter test.
- Python: `test_ivf_hnsw_rq_graph_scoring` (recall >= 0.5 in both modes)
and `test_vector_index_invalid_rq_graph_scoring`.
- `test_nearest_preserves_existing_positional_arguments` expects the new
option at the end of the
`ScannerBuilder.nearest` signature, which keeps the existing positional
arguments binding.
- Local lint: `cargo fmt`, workspace clippy (also `lance --features
substrait` and `lance-jni`), and `uv run make lint` pass. Locally,
clippy 1.96 flags a `nonminimal_bool` in
`lance-encoding/src/compression.rs`, which this PR does not touch, so I
allowed that lint for the local runs.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Xuanwo <[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]>
westonpace added a commit that referenced this pull request Dec 1, 2026
The row-address migration was specced at index_version 3 (#10299). Since
then #10522 shipped IVF_HNSW_RQ at version 3, so the migration takes 4.

PCA (#9968) had claimed 4 and described itself as retaining the domain
"introduced by version 3", so it moves to 5. It is not wired into index
creation, so no index records either number yet.

Co-Authored-By: Claude Opus 5 <[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 A-java Java bindings + JNI A-namespace Namespace impls A-python Python bindings breaking-change enhancement New feature or request K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants