Skip to content

perf(ivf): speed up Flat batch routing and NEON FastScan - #265

Merged
gouyt13 merged 4 commits into
VectorDB-NTU:mainfrom
ColinLeeo:perf/ivf-batched-flat-routing
Nov 25, 2026
Merged

gouyt13 merged 4 commits into
VectorDB-NTU:mainfrom
ColinLeeo:perf/ivf-batched-flat-routing

Conversation

@ColinLeeo

@ColinLeeo ColinLeeo commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Addresses #218. Flat IVF now shares centroid reads across a block of queries and distributes the resulting cluster scans by query. On ARM64, FastScan also spends less time accumulating the lookup-table values for each 32-vector batch.

  • Screen centroids with a blocked matrix multiply and recompute retained candidates using the existing float distance kernels. A bounded heap selects the closest centroids by returned distance and then by ID. The L2 screening bound accounts for underflow even for small-norm vectors.
  • Route up to one tile per worker, then distribute its queries across workers so a tile that hits large clusters can share its scan workload. Small batches and searches that probe more than a quarter of the centroids use per-query routing.
  • Accumulate the low and high lookup bytes separately in NEON registers. Each chunk spans at most 256 groups (1024 dimensions), so each byte-plane sum fits in 16 bits. GIST's 960 dimensions fit in one chunk. Larger inputs combine chunk totals with an overflow check.
  • The search benchmark reports the stored metric and seed, and calculates Recall@10 using valid ground-truth IDs. Regression tests cover padded ground truth, partial batches and dimensions on both sides of the NEON chunk boundary.

GIST1M on ARM64

Compared upstream main (9121a79) and the current head (b6abb92) on an Apple M5 Pro with AppleClang 17, NEON, OpenMP, Release -O3 and native optimization disabled. Both loaded the same 1M × 960 L2 index (4096 Flat centroids, 5 bits) and searched the same 1000 queries for the top 10. Times below are wall-clock microseconds per query, averaged across the batch for each repetition.

Batch nprobe Threads main µs/query PR µs/query Speedup Recall@10 (both)
1000 64 1 613.1 329.6 1.86× 0.8832
1000 64 4 162.3 88.6 1.83× 0.8832
1 64 1 622.5 458.0 1.36× 0.8832
1000 16 1 328.6 156.4 2.10× 0.6598
1000 128 1 994.2 553.0 1.80× 0.9437

At batch 1000, nprobe 64 and one thread, the median went from 613.1 µs on main to 479.6 µs with the routing and review fixes (24d82f3), then to 329.6 µs with the NEON change. With four threads, throughput went from 6,163 to 11,290 queries/s. All five configurations returned matching ID and distance fingerprints.

Each process ran one warmup and three timed repetitions. The three-way comparison ran all six process orders. Each remaining configuration used four alternating pairs. The table reports medians over timed repetitions, with loading and result checks outside the timer. The host had no CPU pinning.

Where the scan time goes

At nprobe 64, a query visited 27,621 vectors on average and sent only 160 to 4-bit distance refinement. The following times compare the routing fixes with and without the new NEON kernel, using the same workload on one thread.

Stage (µs/query) Before NEON change With NEON change
One-bit distance estimates and lower bounds 344.5 190.9
Candidate filtering, refinement and top-10 maintenance 31.3 31.2
Distance refinement alone (part of the preceding row) 24.4 23.8
Whole cluster stage, including query setup and result copy 389.3 237.3

Stage timings sample approximately one in 32 scan batches and subtract the measured timer overhead. Refinement was sampled in a separate pass. The end-to-end results above use uninstrumented binaries.

Verification

  • Local ARM64 CTest had 630 passes, 14 skips and zero failures. The rebuilt Python wheel had 1,209 passes, 21 skips and zero failures. Formatting, Ruff, clang-tidy and the focused IVF/FastScan regressions passed.
  • At nprobe 16, 64 and 128, a separate bytewise comparison of the two scan revisions matched all 10,000 result IDs and all 10,000 float32 distances per configuration.
  • On ARM64, all translation units use the same ISA flags, so the cross-ISA symbol checker had no pair to compare. The old and new NEON objects exposed the same defined external symbols.
  • Native x86 timings below apply to the earlier routing commit a41d52d. Its repeated single-query measurement was 1.5% slower than main. That configuration still needs a performance rerun on the current head.
Build and test commands

python below is the existing project virtual-environment interpreter. GoogleTest 1.14.0 was reused from the existing local source cache; unused GoogleMock was disabled because a system-installed GoogleTest header interfered with its build.

cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \
  -DRABITQ_BUILD_TESTS=ON -DRABITQ_BUILD_SAMPLES=OFF \
  -DRABITQ_BUILD_BENCHMARKS=ON -DRABITQ_ENABLE_NATIVE_OPTIMIZATION=OFF \
  -DOpenMP_ROOT="$(brew --prefix libomp)" -DBUILD_GMOCK=OFF \
  -DFETCHCONTENT_SOURCE_DIR_GOOGLETEST="$GOOGLETEST_SOURCE"
cmake --build build --parallel 6
OMP_NUM_THREADS=2 ctest --no-tests=error --test-dir build --output-on-failure
python -m pip wheel . --no-deps --no-build-isolation -w build/wheels \
  -Ccmake.define.OpenMP_ROOT="$(brew --prefix libomp)" \
  -Ccmake.define.RABITQ_ENABLE_NATIVE_OPTIMIZATION=OFF -Cbuild-dir=build-wheel
python -m pip install --no-deps --no-index --target build/python build/wheels/*.whl
OMP_NUM_THREADS=2 PYTHONPATH="$PWD/build/python" python -m pytest tests/python -q -rs
./scripts/check-format.sh
./scripts/check-python.sh
./scripts/check-tidy.sh build-wheel
Historical x86 and ARM64 results for routing commit a41d52d

Native x86 correctness follow-up (2026-11-24)

Verified the completed jobs in fork CI run 45357507822 on the exact PR commit a41d52dd5791414fa450ce361efd99d2517863ca:

Native x86 job Full CTest result Evidence
Linux GCC, portable Release, native optimization OFF 622 passed, 8 skipped, 0 failed (630 registered) Job log
Linux Clang 23, OpenMP ON, portable Release, native optimization OFF 629 passed, 1 skipped, 0 failed (630 registered) Job log
Windows x86-64, Visual Studio 2026, Release 617 passed, 9 skipped, 0 failed (626 registered) Job log

All three jobs executed and passed the new IvfFlatRoutingTest cases for tiled top-nprobe parity, float-distance ties, and streamed batch search with removed-ID padding. Skips are explicit platform/runtime/ISA limitations; they are not counted as passes. ASan/UBSan, the Clang OpenMP OFF core/FastScan checks, and benchmark smoke also passed. OpenMP OFF does not build the IVF index.

The GCC host reports an AMD EPYC 7763 (x86-64). Its separate Intel SDE checks passed for AVX2-only and AVX-512 dispatch; those emulation checks are correctness evidence, not native performance measurements. These CI results address the native x86 runtime-validation gap raised by Copilot. Native x86 before/after GIST measurements are now reported in the performance follow-up. The single-query repeat is 1.5% slower, so the no-regression criterion remains unresolved and the PR remains a draft.

Historical performance

Native x86-64 measurements (2026-11-24)

Measured base 9121a79ae0f5e23d3c5f5aef2431e872b89afd92 against PR head a41d52dd5791414fa450ce361efd99d2517863ca on an AMD EPYC 9J14 KVM guest, Ubuntu 24.04.4, 32 vCPUs, approximately 62 GiB RAM, GCC 13.3.0, CMake 3.28.3, Release -O3 -DNDEBUG, C++17, OpenMP ON, native optimization OFF. The guest exposes AVX2 and AVX-512; the library retains its runtime-dispatched kernels. The baseline receives only this PR's identical standalone search benchmark driver and its CMake target, with no changes to its search implementation.

Before timing, the candidate's complete CTest run finished with 644 passed, 1 skipped, 0 failed (645 registered). The sole skip was ThreadCount.BoundParallelForUsesRuntimePlacementAndPropagatesErrors. The ISA symbol check also passed for 49 translation units. No build or other CPU-heavy guest workload ran concurrently with the benchmark.

Workload: GIST1M, 1,000,000 × 960, L2, 4096 Flat centroids, 5 bits, k=10, default high-accuracy scanning. Both revisions read the exact same prebuilt index used by the earlier ARM64 measurements (built at 2122ab2, sample 262144 without replacement using NumPy default_rng(42), seed 42, 10 iterations, 8 construction threads). The transferred index, query file and ground truth were SHA-256 verified. Index SHA-256: 897a89a212b75ff7db681cb55e632bc3568ee9022d7000955e7faf05e0784037.

Pin each process before loading with numactl --physcpubind=0 --membind=0 for one thread, or CPUs 0-3 for four threads; set OMP_PROC_BIND=close, OMP_PLACES=cores, OMP_DYNAMIC=FALSE and the matching OMP_NUM_THREADS. Use 1000 queries, alternating process order, one untimed warmup per process. Batch 1 and 8 use 7 pairs × 7 timed repetitions; other cases use 3 pairs × 3 repetitions. The 4095/4096-probe cases use the first 64 queries. Loading, warmup, hashing and recall are excluded from timing. Report the median over all timed repetitions and its reciprocal QPS. Every before/after comparison has identical ID/distance fingerprints and unchanged Recall@10.

Batch nprobe Threads Before µs/query After µs/query Before QPS After QPS Speedup Recall@10 (both)
1 64 1 615.35 613.45 1625 1630 1.003× 0.8832
8 64 1 606.02 621.05 1650 1610 0.976× 0.8832
64 64 1 603.25 573.76 1658 1743 1.051× 0.8832
1000 64 1 609.41 539.13 1641 1855 1.130× 0.8832
1000 16 1 383.05 308.22 2611 3244 1.243× 0.6598
1000 128 1 896.58 829.58 1115 1205 1.081× 0.9437
64 64 4 171.29 171.79 5838 5821 0.997× 0.8832
1000 64 4 169.88 144.17 5887 6936 1.178× 0.8832
64 4095 1 11407.90 11449.71 88 87 0.996× 0.9750
64 4096 1 11388.79 11449.48 88 87 0.995× 0.9750

The batch-8 control was 2.5% slower in the first sweep, including one unusually slow candidate process. Both controls were therefore repeated, retaining all original results, with the same CPU binding, binaries, data, and 7 pairs × 7 repetitions:

Batch nprobe Threads Before µs/query After µs/query Before QPS After QPS Speedup Recall@10 (both)
1 64 1 613.21 622.58 1631 1606 0.985× 0.8832
8 64 1 606.35 612.92 1649 1632 0.989× 0.8832

The single-query no-regression requirement is not yet established. Its first sweep was essentially flat (1.003×), but the repeat was 1.5% slower, with all seven paired medians slower (speedups 0.959×–0.993×, median 0.987×). Batch 8 was 2.5% slower initially and 1.1% slower on repeat. These control results need investigation; the batch throughput gains do not resolve them. At batch 1000 / nprobe 64, the measured throughput gain is 13.0% with one thread and 17.8% with four threads; nprobe 16 gains 24.3% at its separately reported recall.

Environment limit: this is native x86 instruction execution in a KVM guest, not a dedicated bare-metal result. Bound-vCPU steal time was at most 0.058% over the recorded comparison windows, but guest measurements cannot exclude physical-host cache/frequency or scheduling interference. CPU affinity and an otherwise idle guest improve repeatability without proving zero noise. The PR remains Draft for the control-latency investigation and human review.

x86 reproduction commands

Build both source snapshots with the same compiler/options; install the identical ivf_search.cpp benchmark driver and its target into the baseline only. Set BUILD_TESTS=OFF for the baseline and BUILD_TESTS=ON for the candidate. No Python binding or package installation is required for this C++ benchmark.

cmake -S "$SOURCE" -B "$BUILD" -G Ninja -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_CXX_COMPILER=g++ -DRABITQ_BUILD_SAMPLES=OFF \
  -DRABITQ_BUILD_BENCHMARKS=ON -DRABITQ_ENABLE_NATIVE_OPTIMIZATION=OFF \
  -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
  -DRABITQ_BUILD_TESTS="$BUILD_TESTS" -DBUILD_GMOCK=OFF
cmake --build "$BUILD" --parallel 8
OMP_NUM_THREADS=4 ctest --test-dir "$AFTER_BUILD" --no-tests=error --output-on-failure --parallel 4
# Run in the candidate repository root (the checker uses git rev-parse):
./scripts/check-isa-symbols.sh "$AFTER_BUILD"

export OMP_NUM_THREADS=1 OMP_PROC_BIND=close OMP_PLACES=cores OMP_DYNAMIC=FALSE
python3 benchmarks/hotpaths/compare.py \
  --before "numactl --physcpubind=0 --membind=0 $BEFORE gist.index gist_query.fvecs gist_groundtruth.ivecs 1 64 1 7 1000" \
  --after  "numactl --physcpubind=0 --membind=0 $AFTER gist.index gist_query.fvecs gist_groundtruth.ivecs 1 64 1 7 1000" \
  --pairs 7 --output x86-single-query \
  --notes "9121a79 vs a41d52d; EPYC 9J14 KVM; GCC 13.3 -O3 native OFF; CPU0/memory node0; GIST1M 4096 Flat, 5 bits, k10"

Use batch 8 with the same control settings; for other rows use three pairs and three repetitions. Four-thread rows use OMP_NUM_THREADS=4 and --physcpubind=0-3. Near-all-cluster rows use 64 queries. Repeat controls into a fresh output directory. Raw CSV/stdout/stderr, paired medians, CPU counters, exact compile commands, build/CTest/ISA logs and scripts have been retained.

Earlier ARM64 measurements

GIST1M, 1,000,000 points × 960 dimensions; 4,096 Flat centroids; 5 bits; L2; k=10; default high-accuracy scanning. Both executables load the same prebuilt index and rotation, created with baseline 2122ab2: a 262,144-point training sample drawn without replacement using NumPy default_rng(42), seed 42, 10 iterations, construction with 8 threads. This isolates search changes from training/version differences; the current main and candidate both read this legacy index.

Compare main at 9121a79 against a41d52d using the same driver/compiler/options. Normally 1,000 queries, three alternating before/after process pairs, three timed repetitions per process after warmup; report median per-query time and its reciprocal QPS. The 4095/4096-probe cases use the first 64 queries and two pairs × two repetitions. Loading, warmup, hashing and recall calculation are outside timing. IDs and distance bytes have matching fingerprints in every comparison, and Recall@10 is unchanged (zero allowed quality loss).

Batch nprobe Threads Before µs/query After µs/query Before QPS After QPS Speedup Recall@10 (both)
1 64 1 826.04 862.48 1211 1159 0.958× 0.8832
8 64 1 774.14 818.91 1292 1221 0.945× 0.8832
64 64 1 835.79 697.30 1196 1434 1.199× 0.8832
1000 64 1 878.68 668.00 1138 1497 1.315× 0.8832
1000 16 1 442.51 261.00 2260 3831 1.695× 0.6598
1000 128 1 1300.76 1196.64 769 836 1.087× 0.9437
64 64 4 262.46 259.25 3810 3857 1.012× 0.8832
1000 64 4 254.70 206.67 3926 4839 1.232× 0.8832
64 4095 1 19190.56 18444.07 52 54 1.040× 0.9750
64 4096 1 19845.13 19345.20 50 52 1.026× 0.9750

Shared-host limitation: no CPU affinity on macOS; an unrelated VM was using approximately four CPU cores and the observed 1-minute load average was about 9.8. Small timing changes are not reliable evidence of a gain or regression.

The first sweep showed slower single/small-batch medians, so those cases were repeated with five alternating pairs × five repetitions, using the same binaries and data:

Batch nprobe Threads Before µs/query After µs/query Before QPS After QPS Speedup Recall@10 (both)
1 64 1 821.43 831.03 1217 1203 0.988× 0.8832
8 64 1 789.11 761.71 1267 1313 1.036× 0.8832

The single-query recheck is 1.2% slower by the aggregate median; per-pair speedups range from 0.971× to 1.088× (median 0.996×). The batch-8 aggregate changes direction between sweeps. These measurements do not establish a stable single-query regression or prove zero regression. The additional native x86 measurements above also leave the single-query no-regression criterion unresolved; this PR remains a draft for that investigation and human review.

Benchmark reproduction

Build the new benchmark driver against both revisions without changing the baseline search implementation. Use the same gist.index, query file and ground truth for both:

python benchmarks/hotpaths/compare.py \
  --before "$BEFORE gist.index gist_query.fvecs gist_groundtruth.ivecs 1000 64 1 3 1000" \
  --after  "$AFTER  gist.index gist_query.fvecs gist_groundtruth.ivecs 1000 64 1 3 1000" \
  --pairs 3 --output results-gist-b1000-p64-t1 \
  --notes "main 9121a79 vs this PR; GIST1M L2, 4096 Flat clusters, 5 bits, k10; record CPU/compiler/ISA/affinity"

Sweep the batch/probe/thread combinations in the table. For near-all-cluster searches use 64 4095 1 2 64 and 64 4096 1 2 64 with --pairs 2. For the longer recheck use batch 1 or 8, nprobe 64, one thread, five repetitions and --pairs 5.

Supersedes #264.

@github-actions github-actions Bot added the release:performance Release category managed from the PR title label Nov 24, 2026
@ColinLeeo
ColinLeeo marked this pull request as ready for review November 24, 2026 08:27
@ColinLeeo
ColinLeeo requested a review from gouyt13 as a code owner November 24, 2026 08:27
@ColinLeeo
ColinLeeo marked this pull request as draft November 24, 2026 08:28
@ColinLeeo

ColinLeeo commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Copilot review completed on the fork review PR, using exactly the same base (9121a79ae0f5e23d3c5f5aef2431e872b89afd92) and head (a41d52dd5791414fa450ce361efd99d2517863ca) as this PR.

Copilot's original review reports no open code issues. I checked the review comments endpoint: it contains zero inline findings. The review is COMMENTED, with the assessment “Needs a closer look”, rather than an approval.

Copilot originally identified two validation concerns:

Validation follow-up (2026-11-24): the native x86 GCC, Clang, Windows and sanitizer CI jobs have passed on the same head commit. An additional full C++ run on an AMD EPYC 9J14 KVM guest passed 644 tests with 1 skip, and the ISA symbol check passed for 49 translation units. The updated PR performance section includes the complete GIST1M matrix and repeat controls, with matching ID/distance fingerprints and unchanged Recall@10 throughout.

At batch 1000 / nprobe 64, throughput improves by 13.0% with one thread and 17.8% with four threads. However, the single-query repeat is 1.5% slower, with all seven paired medians slower; batch 8 is 1.1% slower on repeat. The first single-query sweep was essentially flat. Both sweeps are retained, and the KVM measurement limitation is explicit. Thus, the lack of native x86 measurement evidence has been addressed, but the no-single-query-regression criterion remains unresolved. This PR remains a draft for that investigation and human review; Copilot's original assessment is not being represented as approval.

@gouyt13
gouyt13 marked this pull request as ready for review November 24, 2026 09:54
@gouyt13
gouyt13 marked this pull request as draft November 24, 2026 14:18
Schedule cluster scans per query, reuse validated inputs, and bound scalar routing scratch by nprobe. Tighten the L2 screening floor and verify benchmark recall and metadata against persisted fixtures.
Accumulate low and high byte planes separately, then combine them once per chunk. Cover 960 dimensions, the 1024-dimensional chunk boundary and the first supported dimension above it in the scalar-reference test.
@ColinLeeo ColinLeeo changed the title perf(ivf): route batched Flat queries with blocked top-nprobe assignment perf(ivf): speed up Flat batch routing and NEON FastScan Nov 25, 2026
@ColinLeeo
ColinLeeo marked this pull request as ready for review November 25, 2026 07:18
@gouyt13

gouyt13 commented Nov 25, 2026

Copy link
Copy Markdown
Member

Thanks for the update. We reviewed b6abb92, covering the screening bounds, the heap-based FlatInitializer::centroids_distances, the two-phase batch scheduling and the NEON accumulation, and found no correctness issues. We will run the x86 measurements on the current head ourselves, so there is no need to rerun them on your side.

One suggestion: in the library, exact_assign_topn and TopNAssignmentScratch are used only by src/index/ivf.cpp (plus its unit test), but they live in the installed include/rabitqlib/clustering/detail/kmeans.hpp. Could they move to a private header under src/index/? src/index/ivf_search.hpp is an existing example: tests/unit/rabitqlib/index/ivf_test.cpp includes it, and flat_routing_test.cpp is in the same test target. CandidateDistanceIdLess has to stay in include/rabitqlib/index/detail/candidate.hpp, because the installed initializer.hpp uses it.

While moving it, the screen flag (kmeans.hpp:105 and its checks) could also go. The screening bound holds for any nprobe. The nprobe <= num_clusters_ / 4 cutoff is a performance decision that search_batch already makes (src/index/ivf.cpp:1639-1640), so the function could always screen, and the existing tests could stay as they are.

Keep the top-nprobe assignment and scratch in the private IVF search module. Let search_batch own the probe-count policy. For L2 tiles with no rejections and rounding allowances larger than the current cutoffs, finish the remaining centroids directly using the existing heaps. Exercise ties across the tile boundary and selection of the last centroid.
@ColinLeeo

Copy link
Copy Markdown
Contributor Author

@gouyt13 Thanks for the review and for taking the native x86 measurements. Addressed both suggestions in c01722e. The top-nprobe function and its scratch type now live in the private IVF search module. The unit test includes src/index/ivf_search.hpp, and CandidateDistanceIdLess stays in the installed header used by FlatInitializer. The quarter-of-centroids cutoff now lives only in search_batch.

Local testing also turned up an L2 case where a large common coordinate offset made the GEMM error allowance too wide to prune any candidates. When a whole tile rejects nothing and every query's rounding allowance exceeds its squared cutoff, the search keeps the existing heaps and scores the remaining centroids directly. A regression test covers a tie across this transition and a nearest centroid at the very end.

On an Apple M5 Pro (NEON, AppleClang 17, Release, one thread), the translated fixture (4096 centroids, 128 dimensions, batch 256, nprobe 16) went from 44.0 to 31.6 µs/query, versus 33.3 on main. GIST1M at batch 1000 and nprobe 64 measured 330.4 µs/query versus 615.1 on main (1.86×). IDs and distance fingerprints matched across all three revisions in both cases, with Recall@10 of 1.0 and 0.8832 respectively.

Local verification passed with 631 C++ tests and 1,209 Python tests passing (14 and 21 skipped, respectively), plus formatting and clang-tidy.

@gouyt13
gouyt13 merged commit 9868b0e into VectorDB-NTU:main Nov 25, 2026
48 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release:performance Release category managed from the PR title

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants