Repository navigation
feat: support batch vector queries - #6828
Conversation
|
ACTION NEEDED The PR title and description are used as the merge commit message. Please update your PR title and description to match the specification. For details on the error please inspect the "PR Title Check" action. |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
| ); | ||
| } | ||
|
|
||
| fn bench_batch_flat_knn(c: &mut Criterion) { |
There was a problem hiding this comment.
can we port this to be in Python?
There was a problem hiding this comment.
it has been ported to: python/python/benchmarks/test_search.py:227
| DataType::List(_) | DataType::FixedSizeList(_, _) => { | ||
| if !matches!(vector_type, DataType::List(_)) { | ||
| return Err(Error::invalid_input(format!( | ||
| "Query is multivector but column {}({})is not multivector", |
There was a problem hiding this comment.
Can you explain more how this distinguishes between multivector query and query batch?
There was a problem hiding this comment.
Batch-vs-multivector is distinguished by the vector column type: list-like q + List column means one multivector query; list-like q + FixedSizeList column means a batch of single-vector queries.
There was a problem hiding this comment.
batch-vs-multivector is decided by vector column type with comments added in Scanner::nearest lines 1467-1475
BubbleCal
left a comment
There was a problem hiding this comment.
- distance_range param is lost if it's a batch query
- this forces the query to be executed by flat KNN even there's an index, we still need to use the index if there is one (just query the index for each query vector).
plz add tests for verifying they are really fixed
|
if the query is with:
it's expected to return an empty result, but the schema should still contain |
| In that case Lance runs a flat batch KNN query, returns up to ``k`` rows | ||
| for each query vector, and adds ``query_index`` to identify the source | ||
| query for each result row. Indexed/ANN batch search is not used in this | ||
| first implementation. |
There was a problem hiding this comment.
this comments look not correct
There was a problem hiding this comment.
- outdated comments
- there will be a
query_indexfor batch
| q: QueryVectorLike | ||
| The query vector. | ||
| The query vector. For fixed-size vector columns, this may be a 2-D | ||
| array-like batch of query vectors. Batch queries run flat KNN, apply |
There was a problem hiding this comment.
outdated comments were committed with old batch implementation but not being updated by later commits, btw indexed batch & distance_range has been consistent with comments like above
| .into_iter() | ||
| .flat_map(BinaryHeap::into_vec) | ||
| .collect::<Vec<_>>(); | ||
| results.sort_by(|left, right| { |
There was a problem hiding this comment.
I think we need to rethink how to implement this, now the results will be truncated because of SortExec has limit=k.
Say for batch query with 2 vectors, and k=10, this would return 20 rows, but SortExec will keep only 10 results then we will lose the rest results
There was a problem hiding this comment.
introducing Scanner::is_batch_nearest & skipping SortExec on batch flat path, per-query top-k will be handled by KNNVectorDistanceExec::execute_batch
There was a problem hiding this comment.
I don't think this is fixed, plz add a test to verify it
| match t { | ||
| DisplayFormatType::Default | DisplayFormatType::Verbose => { | ||
| write!(f, "KNNVectorDistance: metric={}", self.distance_type,) | ||
| if self.query_count > 1 { |
There was a problem hiding this comment.
I think all checks self.query_count > 1 need to be replaced by self.is_batch_query() which should check by query shape not query count.
Say if the query is a list of vectors but with only 1 vector, it's still a batch query, or the behavior will be hard to predict
There was a problem hiding this comment.
- change batch query judgement
Scanner::is_batch_nearest+KNNVectorDistanceExec::is_batchreplacesself.query_count > 1- indexed batch still leverage existing single query ANN path with
is_batch_nearest=false
99de360 to
bbe534b
Compare
|
Test dedup only — no production or indexed-batch behavior changes.
Net: fewer overlapping assertions, same coverage. |
Add a flat KNN batch query path so callers can submit multiple query vectors and share scan work while preserving per-query top-k results. Co-authored-by: Cursor <[email protected]>
Fold batch flat KNN into the existing nearest and KNN execution paths so the public API and plan nodes stay consistent with reviewer feedback. Co-authored-by: Cursor <[email protected]>
Use a larger local-disk dataset and stream benchmark data generation so batch query gains are measured under a more realistic scan workload. Co-authored-by: Cursor <[email protected]>
Allow the local-disk batch KNN benchmark to vary row count, dimensionality, and query count so PR results can show scaling trends. Co-authored-by: Cursor <[email protected]>
Use the LanceDB-compatible query_index result column and move the batch flat KNN benchmark to Python so benchmark scaling can be reproduced from the binding API. Co-authored-by: Cursor <[email protected]>
Apply rustfmt output expected by CI for the batch query binding change. Co-authored-by: Cursor <[email protected]>
Move batch flat KNN benchmark configuration into pytest parameters so review and reproduction do not rely on environment variables. Co-authored-by: Cursor <[email protected]>
Route batched queries through vector indices when available and apply distance range bounds before per-query top-k selection on the flat path. Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
Update nearest/search docstrings to describe indexed batch queries and add Python tests that batch distance_range matches per-query searches. Co-authored-by: Cursor <[email protected]>
|
@codex review |
Avoid flaky Docker builds for cargo-deny-action when GitHub release downloads fail under curl --silent. Co-authored-by: Cursor <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 20f70a15b6
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if !distance.is_finite() { | ||
| continue; | ||
| }; |
There was a problem hiding this comment.
Keep infinite distances consistent with single-query path
Batch KNN currently drops any non-finite distance via !distance.is_finite(), which excludes +/-inf. The single-query flat path only filters NaN and retains infinite distances, so batched results can diverge from repeated single-query results on large-magnitude vectors (overflowed L2/dot/cosine intermediates). This breaks the intended equivalence between batch and per-query behavior for those inputs; consider matching single-query semantics by filtering only NaN here as well.
Useful? React with 👍 / 👎.
Share flat KNN distance validity rules (drop null/NaN, keep infinity), apply the same _distance not-null filter on batch output, and add a regression test for infinite distance handling. Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
|
@BubbleCal Updated based on feedback. PTAL when you have time. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d28627e535
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| *) echo "unsupported arch: ${arch}" >&2; exit 1 ;; | ||
| esac | ||
| url="https://github.com/EmbarkStudios/cargo-deny/releases/download/${version}/cargo-deny-${version}-${target}.tar.gz" | ||
| curl -fsSL "${url}" | tar -xzf - -C /usr/local/bin --strip-components=1 |
There was a problem hiding this comment.
Write cargo-deny to a writable directory
The new install step extracts cargo-deny directly into /usr/local/bin without sudo, but this workflow runs as a non-root user (as indicated by other steps using sudo for privileged operations). On GitHub-hosted Ubuntu runners this will fail with a permission error, causing the cargo-deny job to stop before cargo deny check runs, so dependency-policy checks are effectively broken until this path/permissions issue is fixed.
Useful? React with 👍 / 👎.
Co-authored-by: Cursor <[email protected]>
Keep this PR focused on batch KNN changes only; the prior direct-install workflow edits are unrelated to the feature. Co-authored-by: Cursor <[email protected]>
|
@codex review |
Use refine(4) so ANN over-fetches candidates before flat re-ranking, avoiding flaky mac-build failures when HNSW returns approximate neighbors. Co-authored-by: Cursor <[email protected]>
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
The mac-build failure was a flaky single-query HNSW test unrelated to batch KNN; keep append.rs unchanged from the batch feature commits. Co-authored-by: Cursor <[email protected]>
…7640) ## Which issue does this PR close? Closes #6822. ## Rationale for this change Batch vector search (#6821, PR #6828) made indexed multi-query search *work* by looping the full single-query plan once per query vector — re-opening the index and rebuilding the prefilter for every query — and unioning the results. That throws away the main opportunity of a batch: query vectors mostly probe overlapping IVF partitions, so the same partition storage is read and decoded many times. This PR shares that index-level state across the batch. ## What changes are included in this PR? The indexed/ANN path now reads each probed IVF partition's storage **once** and scores every query that probes it, with the prefilter built once and shared. - **`VectorIndex` trait** (`lance-index`): defaulted `supports_batch_partition_search()` + `search_partitions_batch(...)` (default returns `not_supported`). Additive — no breaking change. - **`IVFIndex`** (`ivf/v2.rs`): batch search for flat-style sub-indices (IVF_FLAT/PQ/SQ/RQ). Invert per-query partition lists, load each distinct partition once, accumulate one top-k heap per query, reusing `accumulate_prepared_partition_search` / `global_heap_to_batch`. - **`ANNIvfBatchExec`** (`io/exec/knn.rs`): ranks each query against the centroids, runs the shared-scan batch search per delta, merges per-query top-k across deltas, emits `{query_index, _distance, _rowid}`. Prefilter wiring shared with the single-query node via `build_dataset_prefilter`. - Each query vector is normalized **independently** for cosine (`normalize_batch_query_for_index`). **Fallback matrix (no regression):** | Case | Behavior | | --- | --- | | IVF_FLAT/PQ/SQ/RQ, fixed nprobes, fully indexed | shared-scan fast path | | adaptive nprobes / `refine_factor` / IVF_HNSW_* / mixed indexed+unindexed | per-query indexed loop (exact) | **Design notes (anticipating review):** - **Why a new exec node, not a mode on the existing ANN nodes?** The two-node single-query pipeline streams one partition-list per delta through a per-query top-k; sharing the scan requires *inverting* queries onto partitions and keeping one heap **per query** in a single pass — a different dataflow. The new node reuses the underlying primitives (partition load, `build_dataset_prefilter`, the index's per-partition accumulate) and leaves the single-query nodes untouched. - **Why gate on index-type metadata, not `supports_batch_partition_search()`?** The gate is a planning-time decision and the single-query path likewise doesn't open the index there; `derive_vector_index_type` reads metadata with no I/O. The opened index re-checks the trait as a defensive invariant. - **nprobes gate (correctness).** The shared path searches exactly `minimum_nprobes` partitions/query, but the single-query path is adaptive (`early_pruning` floor + late-search expansion), so the two only match when nprobes is fixed. The fast path is gated to `minimum_nprobes == maximum_nprobes`; adaptive nprobes falls back to the per-query loop (verified: an unpinned batch diverged on every query before the gate, 0 divergence after). **Open question:** fixed-nprobes-first with batched early/late as a follow-up, or the full adaptive path in one PR? - **Memory.** Peak = the union of probed partitions held during scoring — the same buffering the existing single-query global-heap path (`search_partitions`) uses, widened to the batch's partition union; per-delta output is k-bounded, so cross-delta accumulation is O(deltas × k). ## Are these changes tested? Yes. - `cargo test -p lance --lib test_batch_knn` — **15 tests**: plan shape, exact batch-vs-repeated-single equivalence (nprobes pinned), cosine regression, shared prefilter, multi-delta cross-delta merge, and explicit fallbacks for **refine, adaptive nprobes, and IVF_HNSW** (acceptance criterion: "unsupported index types have explicit behavior and tests"). - `cargo test -p lance --lib dataset::scanner::test::test_knn` (29) — no single-query regression (exercises the shared `build_dataset_prefilter`). - `cargo fmt --all` && `cargo clippy -p lance -p lance-index --tests --benches -- -D warnings`. - Python: `pytest -k batch` (L2 + cosine × three/single queries); index-type sweep (IVF_FLAT/PQ/SQ/HNSW_PQ/HNSW_SQ) matches repeated single-query; `ruff` clean; `pyright` clean on changed lines. - Benchmark (`benchmarks/test_search.py`): batch vs repeated-single ANN; local run (50k rows, dim 128, IVF_PQ 64 partitions, m=32, k=10, nprobes=10) → **~2.5× faster** (ratio; absolute ms machine-dependent). ## Are there any user-facing changes? No API changes. The batch-query surface (2-D / list query with a `query_index` output column) already shipped in #6828; this PR only changes how indexed batch queries execute, so Python and Java bindings are unaffected. It is a **performance improvement** for fixed-nprobes indexed batch search; results are identical to issuing the queries one at a time. No format or compatibility change. --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Summary
Closes #6821.
Scanner::nearestfor batched queries on fixed-size vector columns (no separatenearest_batchAPI).KNNVectorDistanceExec: one scan per data batch, per-query top-k in a single stream (m × krows max).query_index(0-based) so callers can group results per input query.use_index=true): per-query ANN, union, andquery_indextagging when a vector index exists.distance_rangeapplied before per-query top-k on the flat path; indexed batch uses the same bounds.fast_searchwithout an index returns an empty batch result that still includesquery_index.FixedSizeListcolumn + list-like query → batch of single-vector queries;Listmultivector column → one multivector query.API
FixedSizeListembedding columnkrows per query vector +query_index_rowidBenchmark
Local disk, float32 vectors,
use_index=false. OS page cache accepted. Medians over 15 timed rounds (3 warmup); separate then batch each round.At small
m, the second separate query often hits warm page cache, so speedup is modest (~1.1×). It grows withmas scan work is shared.Query count (1M rows, dim 512, k 10)
Dataset size (m 10, dim 512, k 10)
Test plan
cargo test -p lance --lib test_batch_knncargo test -p lance fast_search_withoutuv run pytest python/tests/test_vector_index.py -k batchcargo clippy -p lance --tests -- -D warningsuv run ruff format --check python/lance/dataset.py python/tests/test_vector_index.py