Skip to content

feat(index)!: add IVF-HNSW-RQ (build and search) - #10648

Closed
jzheng106 wants to merge 9 commits into
lance-format:mainfrom
jzheng106:jason/hnsw-rq-build-time
Closed

jzheng106 wants to merge 9 commits into
lance-format:mainfrom
jzheng106:jason/hnsw-rq-build-time

Conversation

@jzheng106

@jzheng106 jzheng106 commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds IVF_HNSW_RQ: an IVF index whose partitions are HNSW graphs built over RabitQ (RQ) codes.
It covers index build and search. Dynamic maintenance (append, optimize, remap) is not in this
PR and will follow.

What changed

  • Index type and params
    • New IndexType::IvfHnswRq (value 108, "IVF_HNSW_RQ").
    • New VectorIndexParams::with_ivf_hnsw_rq_params; [Ivf, Hnsw, RQ] stages map to the type.
    • create_index dispatch builds IvfIndexBuilder::<HNSW, RabitQuantizer>.
    • Python binding accepts IVF_HNSW_RQ.
  • Compare phase (the core change). HNSW build compares stored codes with each other, which
    RQ storage could not do (dist_calculator_from_id was unimplemented!).
    • RabitQuantizationStorage now stages its rows once, on first use, and scores a stored row
      against the others with the existing RQPairScorer kernel in bq/pairwise.rs
      (exact integer code products, popcount for 1 bit, integer dots for 2-9 bits). No new math.
    • RabitDistCalculator gets an "anchored on a stored row" mode instead of a new calculator
      type, so the existing query-path callers are untouched.
    • dist_between and prefers_candidate are overridden to bind the kernel once per call.
  • Open and search. Added the IVF_HNSW_RQ arm in index/loading.rs and mapped
    (Hnsw, Rabit) to IvfHnswRq in vector_index_type and IVFIndex::index_type.
  • Build-speed fix. The staged-column lookup used RecordBatch::column_by_name, which clones
    the schema Arc. With ~16 threads sharing one storage, that refcount contention dominated
    the build (about 66% of busy samples). It now uses schema_ref().index_of; this also helps
    the duplicate-pair scorer, which shares the helper.

Scope and limitations

  • Metrics: L2 and cosine (cosine is stored as L2 over normalized vectors). Dot is rejected at
    creation with an error, because the pairwise scorer needs the partition centroid for dot.
  • Not supported yet: append_batch (still unimplemented!), optimize/remap of existing
    IVF_HNSW_RQ segments, distributed builds, and the Java and namespace bindings.
  • Staged rows use about 1 byte per dimension for 2-8 bits, instead of bits/8 bytes. This is a
    memory cost during HNSW build for large partitions.
  • dist_calculator_from_id and the other trait methods cannot return errors, so staging
    failures expect. Staging fails only for non-L2 or old-format storage, which creation
    rejects first.

Testing

  • Storage test: dist_calculator_from_id, distance_all, dist_between and
    prefers_candidate against an independent decode of the codes, for 1, 2, 5 and 9 bits.
  • test_create_ivf_hnsw_rq_index: builds for L2 and cosine, rejects dot.
  • test_ivf_hnsw_rq_search_recall: top-10 recall vs brute force on an L2 index, asserted at
    least 0.5 (0.925 locally).
  • Extended the IndexType conversion tests.
  • Python tests for create and dot rejection are added but I could not run them locally
    (no uv at the time); CI will be the first run. Clippy was not run locally because of an
    existing lint in lance-encoding.

Benchmarks

image

Review pointers

  • rust/lance-index/src/vector/bq/storage.rs: staging, anchored calculator, the two overrides.
  • rust/lance-index/src/vector/pairwise.rs: the column-lookup change.
  • rust/lance/src/index/vector.rs: dispatch, the dot guard and the new tests.

BREAKING CHANGE

jzheng106 and others added 5 commits October 30, 2026 13:39
Register IVF_HNSW_RQ as a recognized vector IndexType (enum value 108,
parsing, display, is_vector, version, details matching) and add
VectorIndexParams::with_ivf_hnsw_rq_params so [Ivf, Hnsw, RQ] stages map
to IndexType::IvfHnswRq. Building such an index is not implemented yet.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Accept IVF_HNSW_RQ in create_index dispatch and build_vector_index_impl,
building IvfIndexBuilder::<HNSW, RabitQuantizer>. HNSW graph construction
still hits RabitQuantizationStorage::dist_calculator_from_id, which is
unimplemented.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Implement RabitQuantizationStorage::dist_calculator_from_id by staging
the partition's rows once and scoring a stored row against the others
with the existing RQ pairwise kernel, so HNSW graph construction over RQ
codes works for l2 and cosine. Dot is rejected up front. Expose
IVF_HNSW_RQ through the Python bindings. Searching the index and
append_batch are not implemented yet.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Open IVF_HNSW_RQ as IVFIndex<HNSW, RabitQuantizer> and map the
(Hnsw, Rabit) sub-index and quantization pair to IndexType::IvfHnswRq.
Add a recall test against brute-force search.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Look up staged RQ columns without cloning the schema Arc, which made
multi-threaded HNSW builds contend on one refcount, and override
dist_between and prefers_candidate on RabitQuantizationStorage so the
kernel is bound once per call instead of once per candidate.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

@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 enhancement New feature or request labels Nov 2, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added K-changes Latest Gatekeeper recommendation requests changes. and removed K-changes Latest Gatekeeper recommendation requests changes. labels Nov 2, 2026
jzheng106 and others added 2 commits November 2, 2026 16:06
Give IVF_HNSW_RQ index version 3 so readers released before the type,
which accept vector versions up to 2, skip it and fall back to a flat
scan instead of failing nearest-neighbor queries. Stage RQ rows inside
OnceLock::get_or_init so concurrent first callers during parallel HNSW
insertion wait for one staging pass instead of each staging the whole
partition.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Nov 3, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Nov 3, 2026
@jzheng106 jzheng106 changed the title feat(index): add IVF-HNSW-RQ (build and search) feat(index)!: add IVF-HNSW-RQ (build and search) Nov 3, 2026
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Nov 3, 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.

No blocking findings remain in the build-and-search scope.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Nov 3, 2026
@cwj0bzxg

cwj0bzxg commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Looking at the benchmark numbers here, scoring the full multi-bit RQ code on every hop along the graph walk gives throughput pretty close to plain IVF_RQ, which makes it hard to justify the extra HNSW build time and memory overhead.

Since every multi-bit RQ code already embeds 1-bit sign bits, we can walk the HNSW graph on a fast 1-bit estimate (AND + popcount) and only rerank the ef finalist candidates with the full multi-bit codes.

I implemented this 1-bit walk + multi-bit rerank search in #10522 (also using RQPairScorer for graph construction). In my benchmarks comparing it against walking with the full multi-bit estimator, it improves search QPS by ~2.5–3x at the same recall on GIST-1M and Cohere-1M.

@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Nov 4, 2026
@jzheng106

Copy link
Copy Markdown
Collaborator Author

Superseded by #10910, which combines this scoring with the 1-bit walk from #10522 behind a query-time option (multi-bit is the default).

@jzheng106 jzheng106 closed this Nov 10, 2026
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]>
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-python Python bindings breaking-change enhancement New feature or request K-approved Latest Gatekeeper recommendation permits acceptance.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants