Skip to content

perf(index): compile IVF shuffle and split/join once, not per S×Q - #10442

Merged
zhangyue19921010 merged 1 commit into
mainfrom
perf/ivf-builder-type-erasure
Oct 29, 2026
Merged

zhangyue19921010 merged 1 commit into
mainfrom
perf/ivf-builder-type-erasure

Conversation

@wjones127

Copy link
Copy Markdown
Contributor

Summary

IvfIndexBuilder<S, Q> is compiled for 9 sub-index × quantizer pairs. Two of its stages don't depend on S or Q: the shuffle transform, and the partition split/join passes that run during optimize. They only route rows and re-quantize them through the Quantizer enum, but they were still compiled once per pair. This PR moves them off the generic builder so each is compiled once:

IvfIndexBuilder<S, Q>
  shuffle_data(data)            -> shuffle_transformed(data.boxed(), ...)   # free fn
  build_partitions()            -> self.partition_adjuster()                # PartitionAdjuster: holds Quantizer, not Q
                                     .split_partitions_streaming / .join_partitions

Only orchestration code moves: kmeans, transforms, distance kernels and sub-index builds are unchanged and stay monomorphized. The moved method bodies are otherwise unchanged.

Evidence

lance crate, dev profile, same base commit (113876a):

main this PR change
LLVM IR lines (cargo llvm-lines --lib) 7,972,391 7,132,840 -839,551 (-10.5%)
Monomorphized copies 257,702 226,827 -12.0%
Cold cargo rustc -p lance --lib (-Z time-passes total, 2 runs) 108.6s, 108.7s 104.8s, 105.4s -3.6s (-3.3%)
… of which codegen_crate + LLVM_passes 40.0s, 40.2s 35.6s, 36.0s -4.3s

The moved families (shuffle transform, split/join, raw-vector takes) went from 940K IR lines to 106K.

Runtime, bench profile. The dataset has 500K × 128-d f32 rows in 500 clusters, with 256 partitions and target_partition_size=1024. "Optimize" appends 20K rows to one cluster and runs optimize_indices, which splits that partition. Each cell is the median of 6 runs (main and branch interleaved, ±sd). Recall is recall@10 over 100 queries, nprobes=16, refine=10, against brute force. Run on a 16-vCPU host.

index build (s) main / PR optimize w/ split (s) main / PR recall@10 after build, after optimize: main / PR
IVF_PQ (PQ64) 4.05 ±0.21 / 4.04 ±0.49 0.70 ±0.08 / 0.71 ±0.04 1.000, 0.999 / 1.000, 1.000
IVF_HNSW_SQ 6.45 ±0.91 / 6.34 ±2.30 6.87 ±0.92 / 6.50 ±1.83 1.000, 1.000 / 1.000, 1.000
IVF_FLAT 0.62 ±0.06 / 0.64 ±0.05 0.65 ±0.06 / 0.67 ±0.04 1.000, 1.000 / 1.000, 1.000

All differences are within noise. The existing benches/ivf_pq.rs could not be used: it panics on main with RetryableCommitConflict in its second iteration.

Merge Risk

Door: two-way. This is an internal refactor with no format or API change.
Blast Radius: vector index build and optimize (shuffle, split/join).

🤖 Generated with Claude Code

The shuffle transform and the partition split/join passes only route and
re-quantize rows, yet as methods of `IvfIndexBuilder<S, Q>` they were
monomorphized for every sub-index and quantizer pair. Move the split/join
passes onto a non-generic `PartitionAdjuster` that holds the erased
`Quantizer`, and the shuffle transform into a free function that takes a
boxed stream.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@wjones127
wjones127 marked this pull request as ready for review October 28, 2026 23:38

@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 repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.

Tip: disable this comment in your organization's Code Review settings.

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

The extraction addresses redundant compilation and preserves the existing indexing contract. Shuffle and split/join regressions passed, including a multivector PQ split and HNSW-SQ recall checks.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 28, 2026

@zhangyue19921010 zhangyue19921010 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nice change!

@zhangyue19921010

Copy link
Copy Markdown
Collaborator

LGTM, approved. The extraction reduces redundant monomorphization while preserving the existing shuffle and split/join behavior. I checked the quantizer conversion, error propagation, and empty-stream handling, and all 21 builder regression tests passed locally.

@zhangyue19921010
zhangyue19921010 merged commit 5037631 into main Oct 29, 2026
40 of 41 checks passed
@zhangyue19921010
zhangyue19921010 deleted the perf/ivf-builder-type-erasure branch October 29, 2026 03:49
Xuanwo added a commit that referenced this pull request Nov 12, 2026
…10727)

## Summary

`IVFIndex<S, Q>` and `IvfIndexBuilder<S, Q>` are compiled for every
sub-index × quantizer pair. #10442 moved shuffle and split/join off the
generic builder. This PR moves the rest of the orchestration that does
not touch vectors, so it is compiled once:

```text
IVFIndex<S, Q>
  search_partitions / search_partitions_batch -> partition_search.rs (PartitionSearchSource,
                                                 PreparedPartition, BatchPartition trait objects)
  prewarm_partitions / prewarm_partition_window -> free fns over PrewarmWindows / PrewarmCache
  search_in_partition_with_candidates,
  score_partition_candidates                  -> only on IVFIndex<FlatIndex, RabitQuantizer> (downcast)
IvfIndexBuilder<S, Q>
  build stream yields BuiltPartition (storage/index already as batches)
  build_fresh_partitions_windowed, optimize build loop,
  take_partition_batches, merge_partitions    -> free fns; the S×Q step is a BuildPartitionFn closure
```

Per-vector scoring and partition building stay monomorphized. The only
new dynamic boundary is per (partition, query) probe, not per vector:
the batch path reads a partition once but dispatches once for every
query that probes it. Storage/index → batch conversion now runs inside
the build's `spawn_cpu` instead of in the merge loop.

## Evidence

### Result correctness

The temporary harness gates on the full logical output, not on row
counts. For each probe setting it captures the ordered top-10 `(_rowid,
_distance)` pairs of all 64 queries (640 pairs) and compares them,
before any timing, against an independent oracle built by running every
query on its own:

- exactly 64 × 10 = 640 result rows (the workload guarantees k results:
24,576 indexed rows ≫ 10)
- per-query group identity: each query's 10 `(_rowid, _distance)` pairs
equal that query's single-query top-10
- query grouping and order: the batch output is exactly the
concatenation of the per-query results in query order
- distances non-decreasing within each group; no duplicate row id within
a group

All of these hold on both revisions. The three timed rounds produced
twelve captures (2 revisions × 3 rounds × 2 probe settings), and the
initial exploration added four more (2 revisions × 2 probe settings);
all 16 captures are byte-identical: `sha256
6654cece4916c903b9a2d9e402e38dca33d177417d222a4d40789cb3069675ed` over
7,680 bytes (640 × `u64` row id + `f32` distance bits). The head
exploration run still had a relaxed assertion; the six formal rounds
validated per-query identity, grouping and order, unique row ids within
a group, and distance monotonicity, and the post-timing recapture
matched the pre-timing oracle. nprobes=8 and nprobes=16 also produced
identical output, which shows the two probe settings agree on this
dataset, not that either equals exhaustive nearest-neighbor ground
truth: the per-query oracle is a separate execution of the same query,
not a brute-force scan.

### Runtime

Small partitions with a wide query batch — the shape that pays the
per-(partition, query) boundary most often. Realized workload, counted
from the dataset rather than assumed: 24,576 rows (one fragment, three
8,192-row groups), 128-d, IVF16 → 1,536 rows/partition on average, PQ
16×8 bit, L2, 64 queries, k=10. The golden dataset and index were built
once and copied in for every run from a single retained snapshot (its
data-file sha256 is recorded in each run log), so both revisions read
the same bytes; `[profile.bench]`, three alternating rounds per side,
criterion point estimates:

| workload | main `05a401f` (median) | this PR (median) | ratio of
medians | paired deltas |
|---|---|---|---|---|
| nprobes=8 — 512 (partition, query) calls | 12.194 ms | 12.310 ms |
**+0.95 %** | +2.13 / +0.79 / +1.08 %, median **+1.08 %** |
| nprobes=16 — 1024 (partition, query) calls | 12.105 ms | 12.189 ms |
**+0.69 %** | +1.28 / +1.07 / +0.50 %, median **+1.07 %** |

The `ratio of medians` figures (+0.95 % / +0.69 %) are ratios of the two
per-revision median times; the median of the three paired percentage
deltas is +1.08 % / +1.07 %. Both are reported because they answer
slightly different questions.

All six paired rounds point the same way, at roughly +0.5 to +2 %, and
four of the six pairs have non-overlapping criterion confidence
intervals. That is small but it is not cleanly dismissible as noise, and
it is not something this evidence can attribute: the rounds were not
counter-balanced (main always ran before this PR within a round), the
host was shared and heavily loaded (32 cores, load average ≈ 20
throughout), and the same binary's own point estimate moved about 2 %
between its first and third round in this session — larger than the A/B
gap itself. A residual, workload-dependent cost of the new boundary
cannot be ruled out for this shape.

Absolute numbers are not comparable across sessions: the same `05a401f`
binary measured ~11.0–11.2 ms here in the previous session and
~12.0–12.2 ms in this one, so only the paired comparison above carries
information.

Earlier runs are discarded, not superseded by quieter numbers: they
printed inside the timed iteration (so they measured stdout as well as
the query) and asserted only a row count, which cannot distinguish
identical results from merely equal cardinality. Runs against re-created
datasets (freshly trained k-means, different partition assignment) were
also discarded as non-comparable across revisions.

This is one workload shape on one host. It does not bound IVF search
cost in general — large partitions, few queries, filters and heavy
prefilter paths are outside what was measured.

### Review scope

The code reviewed row-by-row is `3c90bdca…` (original head) →
`e9ae7567…` (main merge), five files. The later bump to `15.0.0-beta.19`
touches 8 files and changes only version strings: `git diff e9ae756
f33c250 -- rust/` is empty, and the whole workspace diff is
`.bumpversion.toml`, the three crate manifests, `java/pom.xml`, and the
three lockfiles. Unit/integration coverage from `e9ae7567` is reused for
this tree because the semantic inputs are unchanged: 655 `index::vector`
library tests (1 ignored child-process helper) and 417
`dataset_scanner_knn`/`dataset_index` tests pass, plus a full-workspace
clippy run with `-D warnings`; `rust/` is identical between that head
and this one. No test was rerun for the version-only advance.

The earlier measurement in the author's benchmark comment was taken
against `c58d019`, before #10480 and later main changes, so it is not
directly comparable to current main.

## Merge Risk

**Door:** two-way. Internal refactor; no format or API change.
**Blast Radius:** IVF search (streaming and batch), prewarm, index
build/optimize/remap.

---------

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

K-approved Latest Gatekeeper recommendation permits acceptance. performance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants