From a41d52dd5791414fa450ce361efd99d2517863ca Mon Sep 17 00:00:00 2001 From: co-stack Date: Tue, 24 Nov 2026 16:06:42 +0800 Subject: [PATCH 1/4] perf(ivf): route batched Flat queries with blocked top-nprobe assignment --- benchmarks/hotpaths/CMakeLists.txt | 1 + benchmarks/hotpaths/README.md | 19 ++ benchmarks/hotpaths/ivf_search.cpp | 90 ++++++++ .../rabitqlib/clustering/detail/kmeans.hpp | 99 ++++++++ include/rabitqlib/index/detail/candidate.hpp | 15 ++ include/rabitqlib/index/ivf/initializer.hpp | 4 +- include/rabitqlib/index/ivf/ivf.hpp | 11 + src/index/ivf.cpp | 126 +++++++++- tests/python/test_ivf.py | 33 +++ .../rabitqlib/index/flat_routing_test.cpp | 218 ++++++++++++++++++ 10 files changed, 612 insertions(+), 4 deletions(-) create mode 100644 benchmarks/hotpaths/ivf_search.cpp create mode 100644 include/rabitqlib/index/detail/candidate.hpp create mode 100644 tests/unit/rabitqlib/index/flat_routing_test.cpp diff --git a/benchmarks/hotpaths/CMakeLists.txt b/benchmarks/hotpaths/CMakeLists.txt index 3feda7b7..2ad87b2d 100644 --- a/benchmarks/hotpaths/CMakeLists.txt +++ b/benchmarks/hotpaths/CMakeLists.txt @@ -23,6 +23,7 @@ if(RABITQ_BUILD_INDEX) set_tests_properties(SidecarHotpathLoad PROPERTIES FIXTURES_REQUIRED sidecar_hotpath) rabitq_hotpath_target(ivf_add index) + rabitq_hotpath_target(ivf_search index) add_test(NAME IvfAddHotpathSingle COMMAND rabitq_ivf_add_hotpaths "${CMAKE_CURRENT_BINARY_DIR}/ivf-add-smoke-single" 64 8 256 16 1 single) add_test(NAME IvfAddHotpathRouted COMMAND rabitq_ivf_add_hotpaths diff --git a/benchmarks/hotpaths/README.md b/benchmarks/hotpaths/README.md index 0ffbf635..d513ec9c 100644 --- a/benchmarks/hotpaths/README.md +++ b/benchmarks/hotpaths/README.md @@ -63,6 +63,25 @@ the deterministic input. Original production indexes are not benchmark fixtures. ## Timing and correctness contract +`rabitq_ivf_search_hotpaths` measures batched search against a previously built +L2 IVF index and reports Recall@10 using external `.fvecs` queries and `.ivecs` +ground truth (the first ten ground-truth IDs per query). Build the index once and +use the same file in both revisions. For example, with a 4096-cluster GIST1M index: + +```bash +build/benchmarks/hotpaths/rabitq_ivf_search_hotpaths \ + gist.index gist_query.fvecs gist_groundtruth.ivecs 64 64 1 5 1000 +``` + +The last five arguments are batch size, `nprobe`, threads, repetitions, and maximum +query count. Sweep batch sizes 1, 8, 64 and 1000, and include `nprobe` near the +cluster count. Loading, warmup, output hashing and recall calculation are outside +timing; rotation, centroid routing and scanning are included. Use `compare.py` +below to alternate revisions and check matching result fingerprints. Record the +index's training settings, storage bits and routing initializer alongside the +dataset, CPU, compiler, ISA and thread settings. This benchmark uses external +data and is not registered as a unit test. + - IVF add verifies the expected point counts and samples new points' self-neighbors outside the timed call, in addition to comparing output hashes across repetitions. - Inputs use an LCG with seed 42 (query/centroid seed 91 where applicable; IVF add uses diff --git a/benchmarks/hotpaths/ivf_search.cpp b/benchmarks/hotpaths/ivf_search.cpp new file mode 100644 index 00000000..6b4a59d7 --- /dev/null +++ b/benchmarks/hotpaths/ivf_search.cpp @@ -0,0 +1,90 @@ +// Load one fixed IVF index; time only search_batch and verify Recall@10 outside timing. +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common.hpp" +#include "rabitqlib/core/detail/eigen.hpp" +#include "rabitqlib/index/ivf/ivf.hpp" +#include "rabitqlib/index/types.hpp" +#include "rabitqlib/utils/io.hpp" + +namespace { +void run(int argc, char** argv) { + if (argc != 9) { + throw std::invalid_argument( + "Usage: rabitq_ivf_search_hotpaths index queries.fvecs truth.ivecs " + "batch nprobe threads reps max_queries" + ); + } + const size_t batch = bench::number(argv[4]); + const size_t nprobe = bench::number(argv[5]); + const size_t threads = bench::number(argv[6]); + const size_t reps = bench::number(argv[7]); + // Last argument bounds queries without changing the input files; useful for + // expensive all-cluster scans. A larger limit uses every available query. + const size_t limit = bench::number(argv[8]); + rabitqlib::ivf::IVF index; + index.load(argv[1]); + rabitqlib::RowMajorMatrix queries; + rabitqlib::RowMajorMatrix truth; + rabitqlib::load_vecs(argv[2], queries); + rabitqlib::load_vecs(argv[3], truth); + constexpr size_t k = 10; + if (static_cast(queries.cols()) != index.dimension() || + queries.rows() != truth.rows() || truth.cols() < static_cast(k)) { + throw std::invalid_argument("Query dimensions or ground-truth shape do not match"); + } + const size_t rows = std::min(limit, static_cast(queries.rows())); + std::vector ids(bench::product(rows, k)); + std::vector distances(ids.size()); + std::cout << "# index=" << argv[1] << " queries=" << argv[2] + << " clusters=" << index.num_clusters() << " batch=" << batch + << " nprobe=" << nprobe << '\n'; + bench::metadata(index.dimension(), rows, threads); + const auto work = [&] { + for (size_t first = 0; first < rows; first += batch) { + index.search_batch( + queries.data() + first * index.dimension(), + std::min(batch, rows - first), + k, + nprobe, + ids.data() + first * k, + distances.data() + first * k, + std::nullopt, + threads + ); + } + }; + bench::measure("ivf_search", rows, reps, work, [&] { + return bench::hash( + distances.data(), + distances.size() * sizeof(float), + bench::hash(ids.data(), ids.size() * sizeof(rabitqlib::PID)) + ); + }); + size_t hits = 0; + for (size_t row = 0; row < rows; ++row) { + const auto* expected = truth.data() + row * static_cast(truth.cols()); + for (size_t i = 0; i < k; ++i) { + hits += std::find(expected, expected + k, ids[row * k + i]) != expected + k; + } + } + std::cout << "# recall_at_10=" + << static_cast(hits) / static_cast(rows * k) << '\n'; +} +} // namespace + +int main(int argc, char** argv) { + try { + run(argc, argv); + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/include/rabitqlib/clustering/detail/kmeans.hpp b/include/rabitqlib/clustering/detail/kmeans.hpp index 9257ef39..f2f2f09a 100644 --- a/include/rabitqlib/clustering/detail/kmeans.hpp +++ b/include/rabitqlib/clustering/detail/kmeans.hpp @@ -22,6 +22,7 @@ #include "rabitqlib/core/detail/simd/matrix_dispatch.hpp" #include "rabitqlib/core/rotator.hpp" +#include "rabitqlib/index/detail/candidate.hpp" #include "rabitqlib/index/detail/parallel_exception.hpp" #include "rabitqlib/index/types.hpp" #include "rabitqlib/utils/cpu_features.hpp" @@ -75,6 +76,104 @@ namespace detail { return result; } +struct TopNAssignmentScratch { + std::vector products; + std::vector point_norms; +}; + +// Inputs are validated, contiguous rows in the same padded/rotated domain. +// centroid_norms contains k double-precision squared norms, computed once per +// batch. The caller bounds n and reuses scratch across blocks on each worker. +// Run inside an OpenMP task with omp_set_num_threads(1), even for one worker, +// so Eigen cannot start a nested team or change the caller's thread settings. +// Unlike exact_assign's clustering objective, return the existing float metric +// (sqrt for L2) and break ties by ID, exactly as FlatInitializer does. +inline void exact_assign_topn( + const float* x, + const float* centroids, + size_t n, + size_t d, + size_t k, + size_t nprobe, + bool spherical, + const double* centroid_norms, + AnnCandidate* candidates, + TopNAssignmentScratch& scratch +) { + assert(nprobe > 0 && nprobe <= k); + constexpr size_t kCentroidBlock = 256; + const bool screen = nprobe <= k / 4; + const index_detail::CandidateDistanceIdLess less; + if (screen) { + scratch.products.resize(n * std::min(k, kCentroidBlock)); + scratch.point_norms.resize(n); + } + const auto distance = [d, spherical](const float* vector, const float* centroid) { + return spherical ? dot_product_dis(vector, centroid, d) + : std::sqrt(euclidean_sqr(vector, centroid, d)); + }; + for (size_t row = 0; row < n; ++row) { + const float* vector = x + row * d; + auto* heap = candidates + row * nprobe; + if (screen) { + scratch.point_norms[row] = l2norm_sqr_f64(vector, d); + } + for (size_t cluster = 0; cluster < nprobe; ++cluster) { + heap[cluster].id = static_cast(cluster); + heap[cluster].distance = distance(vector, centroids + cluster * d); + } + std::make_heap(heap, heap + nprobe, less); + } + + // For validated d <= 65536, this conservatively covers the GEMM dot product, + // float distance accumulation, and rounding of sqrt / (1 - dot). The floor + // includes float epsilon because IP's subtraction can round near one even + // when both vectors have tiny norms. Widened arithmetic is screening only. + const double error_scale = 8.0 * static_cast(d) * + static_cast(std::numeric_limits::epsilon()); + const double error_floor = + 8.0 * static_cast(d) * std::numeric_limits::min() + + 8.0 * std::numeric_limits::epsilon(); + for (size_t first = nprobe; first < k; first += kCentroidBlock) { + const size_t cols = std::min(kCentroidBlock, k - first); + if (screen) { + simd::matrix_product_transposed( + x, centroids + first * d, scratch.products.data(), n, d, cols + ); + } + for (size_t row = 0; row < n; ++row) { + const float* vector = x + row * d; + auto* heap = candidates + row * nprobe; + for (size_t col = 0; col < cols; ++col) { + const size_t cluster = first + col; + if (screen) { + const double norm_sum = + scratch.point_norms[row] + centroid_norms[cluster]; + const double dot = scratch.products[row * cols + col]; + const double estimate = spherical ? 1.0 - dot : norm_sum - 2.0 * dot; + const double worst = heap[0].distance; + const double cutoff = spherical ? worst : worst * worst; + if (estimate > cutoff + error_scale * norm_sum + error_floor) { + continue; + } + } + AnnCandidate candidate; + candidate.id = static_cast(cluster); + candidate.distance = distance(vector, centroids + cluster * d); + if (less(candidate, heap[0])) { + std::pop_heap(heap, heap + nprobe, less); + heap[nprobe - 1] = candidate; + std::push_heap(heap, heap + nprobe, less); + } + } + } + } + for (size_t row = 0; row < n; ++row) { + auto* heap = candidates + row * nprobe; + std::sort_heap(heap, heap + nprobe, less); + } +} + // Inputs have already passed clustering validation. GEMM only screens candidates; // final distances and tie breaking retain the scalar double-precision arithmetic. // Optional previous assignments contain n valid centroid IDs and may alias the diff --git a/include/rabitqlib/index/detail/candidate.hpp b/include/rabitqlib/index/detail/candidate.hpp new file mode 100644 index 00000000..7563ac51 --- /dev/null +++ b/include/rabitqlib/index/detail/candidate.hpp @@ -0,0 +1,15 @@ +#pragma once + +#include "rabitqlib/index/types.hpp" + +namespace rabitqlib::index_detail { + +// Flat routing orders by the returned float distance, including sqrt rounding +// for L2, then by centroid ID. Use the same ordering for scalar and batched search. +struct CandidateDistanceIdLess { + bool operator()(const AnnCandidate& a, const AnnCandidate& b) const { + return a.distance < b.distance || (a.distance == b.distance && a.id < b.id); + } +}; + +} // namespace rabitqlib::index_detail diff --git a/include/rabitqlib/index/ivf/initializer.hpp b/include/rabitqlib/index/ivf/initializer.hpp index 1104965a..4e72a283 100644 --- a/include/rabitqlib/index/ivf/initializer.hpp +++ b/include/rabitqlib/index/ivf/initializer.hpp @@ -16,6 +16,7 @@ #include #include "rabitqlib/core/metric.hpp" +#include "rabitqlib/index/detail/candidate.hpp" #include "rabitqlib/index/detail/parallel_for.hpp" #include "rabitqlib/index/format_error.hpp" #include "rabitqlib/index/ivf/detail/hnsw_sidecar.hpp" @@ -112,7 +113,8 @@ class FlatInitializer : public Initializer { std::partial_sort( centroid_candidates.begin(), centroid_candidates.begin() + static_cast(num_probes), - centroid_candidates.end() + centroid_candidates.end(), + index_detail::CandidateDistanceIdLess{} ); candidates.resize(num_probes); diff --git a/include/rabitqlib/index/ivf/ivf.hpp b/include/rabitqlib/index/ivf/ivf.hpp index f1f16f91..3296a183 100644 --- a/include/rabitqlib/index/ivf/ivf.hpp +++ b/include/rabitqlib/index/ivf/ivf.hpp @@ -177,6 +177,17 @@ class IVF { void swap(IVF& other) noexcept; + inline void search_preassigned( + const float* query, + const float* rotated_query, + const AnnCandidate* centroid_candidates, + size_t k, + size_t nprobe, + PID* result_ids, + float* distances, + bool use_hacc + ) const; + inline void search_cluster( const Cluster& cluster, const SplitBatchQuery& query_wrapper, diff --git a/src/index/ivf.cpp b/src/index/ivf.cpp index 4b0f1a35..1b11af4b 100644 --- a/src/index/ivf.cpp +++ b/src/index/ivf.cpp @@ -46,6 +46,7 @@ #include "rabitqlib/index/ivf/initializer.hpp" #include "rabitqlib/index/training.hpp" #include "rabitqlib/index/types.hpp" +#include "rabitqlib/utils/cpu_features.hpp" #include "rabitqlib/utils/input_checks.hpp" #include "rabitqlib/utils/path.hpp" #include "rabitqlib/utils/space.hpp" @@ -1537,11 +1538,33 @@ void IVF::search( std::vector> centroid_candidates(nprobe); initializer_->centroids_distances(rotated_query.data(), nprobe, centroid_candidates); + search_preassigned( + query, + rotated_query.data(), + centroid_candidates.data(), + k, + nprobe, + result_ids, + distances, + use_hacc + ); +} + +inline void IVF::search_preassigned( + const float* query, + const float* rotated_query, + const AnnCandidate* centroid_candidates, + size_t k, + size_t nprobe, + PID* result_ids, + float* distances, + bool use_hacc +) const { // The pool never needs more slots than points; the rest of k is padded. buffer::SearchBuffer result_pool(std::min(k, max_elements_)); SplitBatchQuery query_wrapper( - rotated_query.data(), padded_dim_, ex_bits_, metric_type_, use_hacc + rotated_query, padded_dim_, ex_bits_, metric_type_, use_hacc ); for (size_t i = 0; i < nprobe; ++i) { @@ -1553,10 +1576,10 @@ void IVF::search( query_wrapper.set_g_add(dist); } else { const float residual_norm = std::sqrt(euclidean_sqr( - rotated_query.data(), initializer_->centroid(cluster_id), padded_dim_ + rotated_query, initializer_->centroid(cluster_id), padded_dim_ )); auto query_centroid_ip = dot_product( - rotated_query.data(), initializer_->centroid(cluster_id), padded_dim_ + rotated_query, initializer_->centroid(cluster_id), padded_dim_ ); query_wrapper.set_g_add(residual_norm, query_centroid_ip); } @@ -1598,6 +1621,103 @@ void IVF::search_batch( num_queries == 1 || num_threads == 1 ? 1 : std::min(resolve_num_threads(num_threads), num_queries); + // GEMM needs enough rows to amortize packing and the per-call norms. Near + // all-cluster scans cannot prune enough candidates to recover that cost. + if (initializer_type_ == InitializerType::Flat && num_clusters_ >= 256 && + num_queries / num_workers >= 32 && nprobe <= num_clusters_ / 4) { + size_t max_query_block = 64; + if (num_workers == 1 && cpu::has_neon()) { + // Larger serial tiles amortize Eigen packing on NEON. Bound each + // rotated/candidate buffer, retaining the existing 64-row minimum + // for wide inputs. Parallel workers keep small scheduling blocks. + constexpr size_t kBufferBudget = size_t{2} << 20; + max_query_block = std::max( + max_query_block, + std::min( + {size_t{512}, + kBufferBudget / sizeof(float) / padded_dim_, + kBufferBudget / sizeof(AnnCandidate) / nprobe} + ) + ); + } + const size_t query_block = + std::min(max_query_block, 1 + (num_queries - 1) / num_workers); + const size_t blocks = 1 + (num_queries - 1) / query_block; + const size_t workers = std::min(num_workers, blocks); + struct QueryScratch { + std::vector normalized; + std::vector rotated; + std::vector> candidates; + clustering::detail::TopNAssignmentScratch assignment; + }; + std::vector scratch(workers); + for (auto& worker : scratch) { + if (cosine_) { + worker.normalized.resize(query_block * dim_); + } + worker.rotated.resize(query_block * padded_dim_); + worker.candidates.resize(query_block * nprobe); + } + const float* centroids = initializer_->centroid(0); + std::vector centroid_norms(num_clusters_); + index_detail::omp_for_dynamic( + num_clusters_, workers, [&](size_t cluster, size_t /*thread*/) { + centroid_norms[cluster] = clustering::detail::l2norm_sqr_f64( + centroids + cluster * padded_dim_, padded_dim_ + ); + } + ); + index_detail::omp_for_dynamic(blocks, workers, [&](size_t block, size_t thread) { + // omp_for_dynamic creates a task even with one worker, so this ICV + // remains local and cannot change the caller's subsequent team size. + omp_set_num_threads(1); + auto& worker = scratch[thread]; + const size_t first = block * query_block; + const size_t rows = std::min(query_block, num_queries - first); + const float* block_queries = queries + first * dim_; + if (cosine_) { + for (size_t row = 0; row < rows; ++row) { + index_detail::normalize_vector( + block_queries + row * dim_, + worker.normalized.data() + row * dim_, + dim_ + ); + } + block_queries = worker.normalized.data(); + } + for (size_t row = 0; row < rows; ++row) { + rotator_->rotate( + block_queries + row * dim_, worker.rotated.data() + row * padded_dim_ + ); + } + clustering::detail::exact_assign_topn( + worker.rotated.data(), + centroids, + rows, + padded_dim_, + num_clusters_, + nprobe, + metric_type_ == METRIC_IP, + centroid_norms.data(), + worker.candidates.data(), + worker.assignment + ); + for (size_t row = 0; row < rows; ++row) { + const size_t i = first + row; + search_preassigned( + block_queries + row * dim_, + worker.rotated.data() + row * padded_dim_, + worker.candidates.data() + row * nprobe, + k, + nprobe, + result_ids + i * k, + distances == nullptr ? nullptr : distances + i * k, + hacc + ); + } + }); + return; + } if (num_workers == 1) { for (size_t i = 0; i < num_queries; ++i) { search( diff --git a/tests/python/test_ivf.py b/tests/python/test_ivf.py index 1584fb08..09b7be09 100644 --- a/tests/python/test_ivf.py +++ b/tests/python/test_ivf.py @@ -109,6 +109,39 @@ def test_batch_search_matches_individual_queries(bits, metric): assert np.all(np.isinf(distances)) +@pytest.mark.parametrize("bits", [1, 5, 32]) +@pytest.mark.parametrize("metric", ["l2", "ip", "cosine"]) +def test_flat_batch_routing_across_tiles(bits, metric, tmp_path): + rng = np.random.default_rng(218) + data = rng.standard_normal((577, 65)).astype(np.float32) + centroids = data[:513].copy() + centroids[1::2] = centroids[0] + labels = np.arange(len(data), dtype=np.uint32) % 512 + queries = rng.standard_normal((513, 65)).astype(np.float32) + queries[0] = 0 + index = _built(data, centroids, labels, nbits=bits, metric=metric) + index.remove(np.array([0, 17, 255, 511], dtype=np.uint32)) + path = tmp_path / "flat-batch.index" + index.save(path) + index = IvfIndex.load(path) + for nprobe in [17, 512, 999]: + k = len(data) + 3 if nprobe == 17 else 10 + expected = [index.search(q[None, :], k=k, nprobe=nprobe) for q in queries] + expected_ids = np.concatenate([result[0] for result in expected]) + expected_distances = np.concatenate([result[1] for result in expected]) + for rows in [8, 64, 129, 513]: + for threads in [1, 4]: + ids, distances = index.search( + queries[:rows], k=k, nprobe=nprobe, num_threads=threads + ) + np.testing.assert_array_equal(ids, expected_ids[:rows]) + np.testing.assert_array_equal(distances, expected_distances[:rows]) + index.remove(np.arange(len(data), dtype=np.uint32)) + ids, distances = index.search(queries, k=10, nprobe=17, num_threads=4) + assert np.all(ids == -1) + assert np.all(np.isinf(distances)) + + def test_unfilled_results_use_sentinels(): data = np.zeros((4, DIM), dtype=np.float32) data[1:] = 100.0 diff --git a/tests/unit/rabitqlib/index/flat_routing_test.cpp b/tests/unit/rabitqlib/index/flat_routing_test.cpp new file mode 100644 index 00000000..54fdb617 --- /dev/null +++ b/tests/unit/rabitqlib/index/flat_routing_test.cpp @@ -0,0 +1,218 @@ +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "rabitqlib/clustering/detail/kmeans.hpp" +#include "rabitqlib/core/metric.hpp" +#include "rabitqlib/index/ivf/initializer.hpp" +#include "rabitqlib/index/ivf/ivf.hpp" +#include "rabitqlib/index/types.hpp" +#include "rabitqlib/utils/space.hpp" + +namespace rabitqlib::ivf { +namespace { + +TEST(IvfFlatRoutingTest, TopNMatchesScalarAcrossTilesAndTies) { + constexpr size_t kClusters = 513, kQueries = 129; + std::mt19937 rng(218); + std::uniform_real_distribution random(-1, 1); + clustering::detail::TopNAssignmentScratch scratch; + for (size_t dim : {65U, 960U}) { + for (float scale : {1.0F, 1.0e-8F, 1000.0F}) { + std::vector centroids(kClusters * dim), queries(kQueries * dim); + // Large common offsets exercise cancellation in norm_sum - 2*dot. + const float offset = scale == 1000.0F ? 100000.0F : 0.0F; + std::generate(centroids.begin(), centroids.end(), [&] { + return offset + scale * random(rng); + }); + std::generate(queries.begin(), queries.end(), [&] { + return offset + scale * random(rng); + }); + for (size_t cluster = 1; cluster < kClusters; cluster += 2) { + std::copy_n(centroids.data(), dim, centroids.data() + cluster * dim); + } + std::copy_n(centroids.data(), dim, queries.data()); + std::vector norms(kClusters); + for (size_t cluster = 0; cluster < kClusters; ++cluster) { + norms[cluster] = clustering::detail::l2norm_sqr_f64( + centroids.data() + cluster * dim, dim + ); + } + for (auto metric : {METRIC_L2, METRIC_IP}) { + FlatInitializer scalar(dim, kClusters, metric); + scalar.add_vectors(centroids.data(), 1); + for (size_t nprobe : {1U, 17U, 128U, 512U, 513U}) { + SCOPED_TRACE( + ::testing::Message() + << dim << ' ' << scale << ' ' << metric << ' ' << nprobe + ); + std::vector> actual(kQueries * nprobe), expected; +#pragma omp parallel num_threads(1) + { + omp_set_num_threads(1); + clustering::detail::exact_assign_topn( + queries.data(), + centroids.data(), + kQueries, + dim, + kClusters, + nprobe, + metric == METRIC_IP, + norms.data(), + actual.data(), + scratch + ); + } + for (size_t row = 0; row < kQueries; ++row) { + scalar.centroids_distances( + queries.data() + row * dim, nprobe, expected + ); + for (size_t i = 0; i < nprobe; ++i) { + ASSERT_EQ(actual[row * nprobe + i].id, expected[i].id); + ASSERT_EQ( + actual[row * nprobe + i].distance, expected[i].distance + ); + } + } + } + } + } + } +} + +TEST(IvfFlatRoutingTest, L2TiesUseReturnedFloatDistance) { + constexpr size_t kDim = 64, kClusters = 257; + std::vector query(kDim), centroids(kDim * kClusters, 10.0F); + std::fill_n(centroids.data(), 2 * kDim, 0.0F); + centroids[0] = centroids[kDim] = 1.0F; + centroids[1] = std::sqrt(std::numeric_limits::epsilon()); + const float farther = euclidean_sqr(query.data(), centroids.data(), kDim); + const float nearer = euclidean_sqr(query.data(), centroids.data() + kDim, kDim); + ASSERT_GT(farther, nearer); + ASSERT_EQ(std::sqrt(farther), std::sqrt(nearer)); + std::vector norms(kClusters); + for (size_t i = 0; i < kClusters; ++i) { + norms[i] = clustering::detail::l2norm_sqr_f64(centroids.data() + i * kDim, kDim); + } + FlatInitializer scalar(kDim, kClusters); + scalar.add_vectors(centroids.data(), 1); + std::vector> expected; + scalar.centroids_distances(query.data(), 1, expected); + EXPECT_EQ(expected[0].id, 0U); + AnnCandidate actual; + clustering::detail::TopNAssignmentScratch scratch; +#pragma omp parallel num_threads(1) + { + omp_set_num_threads(1); + clustering::detail::exact_assign_topn( + query.data(), + centroids.data(), + 1, + kDim, + kClusters, + 1, + false, + norms.data(), + &actual, + scratch + ); + } + EXPECT_EQ(actual.id, 0U); + EXPECT_EQ(actual.distance, expected[0].distance); +} + +TEST(IvfFlatRoutingTest, BatchSearchStreamsBlocksAndPreservesRemovedPadding) { + constexpr size_t kCount = 577, kDim = 65, kClusters = 513, kQueries = 513; + std::mt19937 rng(218); + std::uniform_real_distribution random(-1, 1); + std::vector data(kCount * kDim), centroids(kClusters * kDim); + std::vector queries(kQueries * kDim); + std::generate(data.begin(), data.end(), [&] { return random(rng); }); + std::generate(centroids.begin(), centroids.end(), [&] { return random(rng); }); + std::generate(queries.begin(), queries.end(), [&] { return random(rng); }); + std::fill_n(queries.data(), kDim, 0.0F); + for (size_t i = 1; i < kClusters; i += 2) { + std::copy_n(centroids.data(), kDim, centroids.data() + i * kDim); + } + std::vector labels(kCount); + for (size_t i = 0; i < kCount; ++i) { + labels[i] = static_cast(i % (kClusters - 1)); + } + for (auto metric : {METRIC_L2, METRIC_IP, METRIC_COSINE}) { + for (size_t bits : {1U, 5U, 32U}) { + IVF index(kCount, kDim, kClusters, bits, metric); + index.construct(data.data(), centroids.data(), labels.data(), false, 1); + std::vector removed{0, 17, 255, 511}; + ASSERT_EQ(index.remove(removed.data(), removed.size()), removed.size()); + for (size_t nprobe : {1U, 17U, 512U, 999U}) { + const size_t k = nprobe == 17 ? kCount + 3 : 11; + std::vector expected(kQueries * k), actual(kQueries * k); + std::vector expected_distances(kQueries * k), + distances(kQueries * k); + for (bool hacc : {false, true}) { + for (size_t row = 0; row < kQueries; ++row) { + index.search( + queries.data() + row * kDim, + k, + nprobe, + expected.data() + row * k, + expected_distances.data() + row * k, + hacc + ); + } + for (size_t threads : {1U, 4U}) { + const int previous_threads = omp_get_max_threads(); + index.search_batch( + queries.data(), + kQueries, + k, + nprobe, + actual.data(), + distances.data(), + hacc, + threads + ); + EXPECT_EQ(omp_get_max_threads(), previous_threads); + EXPECT_EQ(actual, expected); + EXPECT_EQ(distances, expected_distances); + index.search_batch( + queries.data(), + kQueries, + k, + nprobe, + actual.data(), + nullptr, + hacc, + threads + ); + EXPECT_EQ(actual, expected); + } + } + } + removed.resize(kCount); + std::iota(removed.begin(), removed.end(), PID{0}); + index.remove(removed.data(), removed.size()); + std::vector actual(kQueries); + std::vector distances(kQueries); + index.search_batch( + queries.data(), kQueries, 1, 17, actual.data(), distances.data(), false, 4 + ); + EXPECT_TRUE(std::all_of(actual.begin(), actual.end(), [](PID id) { + return id == kPidMax; + })); + EXPECT_TRUE(std::all_of(distances.begin(), distances.end(), [](float distance) { + return std::isinf(distance); + })); + } + } +} + +} // namespace +} // namespace rabitqlib::ivf From 24d82f317c57bac5326b35ced6976cfd64a95e20 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Wed, 25 Nov 2026 14:49:18 +0800 Subject: [PATCH 2/4] perf(ivf): balance cluster scans and tighten Flat routing 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. --- benchmarks/hotpaths/CMakeLists.txt | 7 + benchmarks/hotpaths/README.md | 12 +- benchmarks/hotpaths/common.hpp | 14 +- benchmarks/hotpaths/ivf_search.cpp | 35 +++- benchmarks/hotpaths/test_ivf_search.py | 56 +++++++ .../rabitqlib/clustering/detail/kmeans.hpp | 8 +- include/rabitqlib/index/ivf/initializer.hpp | 52 ++++-- include/rabitqlib/index/ivf/ivf.hpp | 9 + src/index/ivf.cpp | 157 +++++++++++------- 9 files changed, 256 insertions(+), 94 deletions(-) create mode 100644 benchmarks/hotpaths/test_ivf_search.py diff --git a/benchmarks/hotpaths/CMakeLists.txt b/benchmarks/hotpaths/CMakeLists.txt index 2ad87b2d..5f91e851 100644 --- a/benchmarks/hotpaths/CMakeLists.txt +++ b/benchmarks/hotpaths/CMakeLists.txt @@ -24,6 +24,13 @@ if(RABITQ_BUILD_INDEX) rabitq_hotpath_target(ivf_add index) rabitq_hotpath_target(ivf_search index) + find_package(Python3 QUIET COMPONENTS Interpreter) + if(Python3_Interpreter_FOUND) + add_test(NAME IvfSearchHotpathReport COMMAND "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/test_ivf_search.py" + "$" + "${PROJECT_SOURCE_DIR}/tests/fixtures/persistence") + endif() add_test(NAME IvfAddHotpathSingle COMMAND rabitq_ivf_add_hotpaths "${CMAKE_CURRENT_BINARY_DIR}/ivf-add-smoke-single" 64 8 256 16 1 single) add_test(NAME IvfAddHotpathRouted COMMAND rabitq_ivf_add_hotpaths diff --git a/benchmarks/hotpaths/README.md b/benchmarks/hotpaths/README.md index d513ec9c..24577b51 100644 --- a/benchmarks/hotpaths/README.md +++ b/benchmarks/hotpaths/README.md @@ -64,8 +64,12 @@ the deterministic input. Original production indexes are not benchmark fixtures. ## Timing and correctness contract `rabitq_ivf_search_hotpaths` measures batched search against a previously built -L2 IVF index and reports Recall@10 using external `.fvecs` queries and `.ivecs` -ground truth (the first ten ground-truth IDs per query). Build the index once and +IVF index and reports Recall@10 using external `.fvecs` queries and `.ivecs` +ground truth for the index metric. For each query, it counts matches among the +first ten ground-truth IDs, ignoring `-1` padding, divides by the number of valid +IDs, and averages across queries. Each row must have at least one valid ID. +The report includes the stored metric and rotation seed (`unknown` for older +indexes without a saved seed). Build the index once and use the same file in both revisions. For example, with a 4096-cluster GIST1M index: ```bash @@ -79,8 +83,8 @@ cluster count. Loading, warmup, output hashing and recall calculation are outsid timing; rotation, centroid routing and scanning are included. Use `compare.py` below to alternate revisions and check matching result fingerprints. Record the index's training settings, storage bits and routing initializer alongside the -dataset, CPU, compiler, ISA and thread settings. This benchmark uses external -data and is not registered as a unit test. +dataset, CPU, compiler, ISA and thread settings. The timing sweep uses external +data. When Python is available, CTest checks the report with small saved indexes. - IVF add verifies the expected point counts and samples new points' self-neighbors outside the timed call, in addition to comparing output hashes across repetitions. diff --git a/benchmarks/hotpaths/common.hpp b/benchmarks/hotpaths/common.hpp index 9de5ddb5..9b7954c5 100644 --- a/benchmarks/hotpaths/common.hpp +++ b/benchmarks/hotpaths/common.hpp @@ -8,7 +8,9 @@ #include #include #include +#include #include +#include #include #include @@ -54,9 +56,17 @@ inline uint64_t hash( return seed; } -inline void metadata(size_t dim, size_t rows, size_t threads) { +inline void metadata( + size_t dim, + size_t rows, + size_t threads, + std::optional seed = 42, + const char* metric = "L2" +) { std::cout << std::setprecision(12) << "# dim=" << dim << " rows=" << rows - << " threads=" << threads << " seed=42 metric=L2 openmp=" << RABITQ_USE_OPENMP + << " threads=" << threads + << " seed=" << (seed ? std::to_string(*seed) : "unknown") + << " metric=" << metric << " openmp=" << RABITQ_USE_OPENMP << " avx2=" << rabitqlib::cpu::has_avx2() << " avx512=" << rabitqlib::cpu::has_avx512_core() << " neon=" << rabitqlib::cpu::has_neon() << '\n'; diff --git a/benchmarks/hotpaths/ivf_search.cpp b/benchmarks/hotpaths/ivf_search.cpp index 6b4a59d7..fe071c24 100644 --- a/benchmarks/hotpaths/ivf_search.cpp +++ b/benchmarks/hotpaths/ivf_search.cpp @@ -10,11 +10,24 @@ #include "common.hpp" #include "rabitqlib/core/detail/eigen.hpp" +#include "rabitqlib/core/metric.hpp" #include "rabitqlib/index/ivf/ivf.hpp" #include "rabitqlib/index/types.hpp" #include "rabitqlib/utils/io.hpp" namespace { +const char* metric_name(rabitqlib::MetricType metric) { + switch (metric) { + case rabitqlib::METRIC_L2: + return "L2"; + case rabitqlib::METRIC_IP: + return "IP"; + case rabitqlib::METRIC_COSINE: + return "cosine"; + } + throw std::invalid_argument("Unknown index metric"); +} + void run(int argc, char** argv) { if (argc != 9) { throw std::invalid_argument( @@ -46,7 +59,9 @@ void run(int argc, char** argv) { std::cout << "# index=" << argv[1] << " queries=" << argv[2] << " clusters=" << index.num_clusters() << " batch=" << batch << " nprobe=" << nprobe << '\n'; - bench::metadata(index.dimension(), rows, threads); + bench::metadata( + index.dimension(), rows, threads, index.seed(), metric_name(index.metric_type()) + ); const auto work = [&] { for (size_t first = 0; first < rows; first += batch) { index.search_batch( @@ -68,15 +83,25 @@ void run(int argc, char** argv) { bench::hash(ids.data(), ids.size() * sizeof(rabitqlib::PID)) ); }); - size_t hits = 0; + double recall_sum = 0.0; for (size_t row = 0; row < rows; ++row) { const auto* expected = truth.data() + row * static_cast(truth.cols()); + const auto* found = ids.data() + row * k; + size_t hits = 0, valid = 0; for (size_t i = 0; i < k; ++i) { - hits += std::find(expected, expected + k, ids[row * k + i]) != expected + k; + if (expected[i] != rabitqlib::kPidMax) { + ++valid; + hits += std::find(found, found + k, expected[i]) != found + k; + } + } + if (valid == 0) { + throw std::invalid_argument( + "Recall requires a valid ground-truth ID for every query" + ); } + recall_sum += static_cast(hits) / static_cast(valid); } - std::cout << "# recall_at_10=" - << static_cast(hits) / static_cast(rows * k) << '\n'; + std::cout << "# recall_at_10=" << recall_sum / static_cast(rows) << '\n'; } } // namespace diff --git a/benchmarks/hotpaths/test_ivf_search.py b/benchmarks/hotpaths/test_ivf_search.py new file mode 100644 index 00000000..96bf0749 --- /dev/null +++ b/benchmarks/hotpaths/test_ivf_search.py @@ -0,0 +1,56 @@ +"""Check the search benchmark report against small persisted IVF fixtures.""" + +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + + +def check(executable, fixtures, directory): + query_file = directory / "queries.fvecs" + truth_file = directory / "truth.ivecs" + + def run(fixture, nprobe, truth, *, success=True): + reference = ( + (fixtures / fixture).with_suffix(".expected").read_text().splitlines() + ) + dim = int(reference[0].split()[1]) + query = list(map(float, reference[1].split()[:dim])) + query_file.write_bytes(struct.pack(f"(d) * static_cast(std::numeric_limits::epsilon()); const double error_floor = 8.0 * static_cast(d) * std::numeric_limits::min() + - 8.0 * std::numeric_limits::epsilon(); + (spherical ? 8.0 * std::numeric_limits::epsilon() : 0.0); for (size_t first = nprobe; first < k; first += kCentroidBlock) { const size_t cols = std::min(kCentroidBlock, k - first); if (screen) { diff --git a/include/rabitqlib/index/ivf/initializer.hpp b/include/rabitqlib/index/ivf/initializer.hpp index 4e72a283..3f9e08ec 100644 --- a/include/rabitqlib/index/ivf/initializer.hpp +++ b/include/rabitqlib/index/ivf/initializer.hpp @@ -101,24 +101,44 @@ class FlatInitializer : public Initializer { void centroids_distances( const float* query, size_t nprobe, std::vector>& candidates ) const override { - std::vector> centroid_candidates(num_cluster_); - for (PID i = 0; i < num_cluster_; ++i) { - centroid_candidates[i].id = i; - centroid_candidates[i].distance = - metric_type_ == METRIC_IP - ? dot_product_dis(query, centroid(i), dim_) - : std::sqrt(euclidean_sqr(query, centroid(i), dim_)); - } const size_t num_probes = std::min(nprobe, num_cluster_); - std::partial_sort( - centroid_candidates.begin(), - centroid_candidates.begin() + static_cast(num_probes), - centroid_candidates.end(), - index_detail::CandidateDistanceIdLess{} - ); - candidates.resize(num_probes); - std::copy_n(centroid_candidates.begin(), num_probes, candidates.begin()); + if (num_probes == 0) { + return; + } + const bool l2 = metric_type_ == METRIC_L2; + const auto score = [&](PID id) { + return l2 ? euclidean_sqr(query, centroid(id), dim_) + : dot_product_dis(query, centroid(id), dim_); + }; + for (PID id = 0; id < num_probes; ++id) { + const float value = score(id); + candidates[id] = AnnCandidate(id, l2 ? std::sqrt(value) : value); + } + const index_detail::CandidateDistanceIdLess less; + std::make_heap(candidates.begin(), candidates.end(), less); + // The square of a float cutoff is exact in double. Beyond it an L2 + // candidate cannot improve the returned float distance, even after sqrt. + const auto cutoff = [&] { + const double worst = candidates.front().distance; + return l2 ? worst * worst : worst; + }; + double worst_score = cutoff(); + for (PID id = static_cast(num_probes); id < num_cluster_; ++id) { + const float value = score(id); + if (value >= worst_score) { + continue; + } + const float dist = l2 ? std::sqrt(value) : value; + // IDs increase, so ties after sqrt cannot displace the heap root. + if (dist < candidates.front().distance) { + std::pop_heap(candidates.begin(), candidates.end(), less); + candidates.back() = AnnCandidate(id, dist); + std::push_heap(candidates.begin(), candidates.end(), less); + worst_score = cutoff(); + } + } + std::sort_heap(candidates.begin(), candidates.end(), less); } // The flat initializer stores only its centroids. diff --git a/include/rabitqlib/index/ivf/ivf.hpp b/include/rabitqlib/index/ivf/ivf.hpp index 3296a183..0e9a62eb 100644 --- a/include/rabitqlib/index/ivf/ivf.hpp +++ b/include/rabitqlib/index/ivf/ivf.hpp @@ -177,6 +177,15 @@ class IVF { void swap(IVF& other) noexcept; + void search_validated( + const float* query, + size_t k, + size_t nprobe, + PID* result_ids, + float* distances, + bool use_hacc + ) const; + inline void search_preassigned( const float* query, const float* rotated_query, diff --git a/src/index/ivf.cpp b/src/index/ivf.cpp index 1b11af4b..b80a06ab 100644 --- a/src/index/ivf.cpp +++ b/src/index/ivf.cpp @@ -1523,6 +1523,19 @@ void IVF::search( ) const { validate_search(query, k, nprobe, result_ids); check_coordinates(query, dim_, dim_, "IVF search query"); + search_validated( + query, k, std::min(nprobe, num_clusters_), result_ids, distances, use_hacc + ); +} + +void IVF::search_validated( + const float* query, + size_t k, + size_t nprobe, + PID* result_ids, + float* distances, + bool use_hacc +) const { std::vector normalized_query; if (cosine_) { normalized_query.resize(dim_); @@ -1530,7 +1543,6 @@ void IVF::search( query = normalized_query.data(); } - nprobe = std::min(nprobe, num_clusters_); // Probe at most every cluster std::vector rotated_query(padded_dim_); rotator_->rotate(query, rotated_query.data()); @@ -1617,10 +1629,11 @@ void IVF::search_batch( check_coordinates(queries, num_queries * dim_, dim_, "IVF search queries"); nprobe = std::min(nprobe, num_clusters_); const bool hacc = use_hacc.value_or(!raw_reranking_ && ex_bits_ > 2); - const size_t num_workers = - num_queries == 1 || num_threads == 1 - ? 1 - : std::min(resolve_num_threads(num_threads), num_queries); + if (num_queries == 1) { + search_validated(queries, k, nprobe, result_ids, distances, hacc); + return; + } + const size_t num_workers = std::min(resolve_num_threads(num_threads), num_queries); // GEMM needs enough rows to amortize packing and the per-call norms. Near // all-cluster scans cannot prune enough candidates to recover that cost. if (initializer_type_ == InitializerType::Flat && num_clusters_ >= 256 && @@ -1660,67 +1673,84 @@ void IVF::search_batch( } const float* centroids = initializer_->centroid(0); std::vector centroid_norms(num_clusters_); - index_detail::omp_for_dynamic( - num_clusters_, workers, [&](size_t cluster, size_t /*thread*/) { - centroid_norms[cluster] = clustering::detail::l2norm_sqr_f64( - centroids + cluster * padded_dim_, padded_dim_ - ); - } - ); - index_detail::omp_for_dynamic(blocks, workers, [&](size_t block, size_t thread) { - // omp_for_dynamic creates a task even with one worker, so this ICV - // remains local and cannot change the caller's subsequent team size. - omp_set_num_threads(1); - auto& worker = scratch[thread]; - const size_t first = block * query_block; - const size_t rows = std::min(query_block, num_queries - first); - const float* block_queries = queries + first * dim_; - if (cosine_) { - for (size_t row = 0; row < rows; ++row) { - index_detail::normalize_vector( - block_queries + row * dim_, - worker.normalized.data() + row * dim_, - dim_ +#pragma omp parallel for num_threads(workers) schedule(static) + for (std::ptrdiff_t cluster = 0; + cluster < static_cast(num_clusters_); + ++cluster) { + const auto id = static_cast(cluster); + centroid_norms[id] = clustering::detail::l2norm_sqr_f64( + centroids + id * padded_dim_, padded_dim_ + ); + } + // Route at most one tile per worker before sharing all of its rows for + // scanning. Queries in the same tile can hit very different cluster sizes. + for (size_t first_block = 0; first_block < blocks; first_block += workers) { + const size_t tiles = std::min(workers, blocks - first_block); + const size_t first_query = first_block * query_block; + const size_t wave_rows = + std::min(tiles * query_block, num_queries - first_query); + index_detail::omp_for_dynamic( + tiles, workers, [&](size_t slot, size_t /*thread*/) { + // The implicit OpenMP task keeps this setting local, even with one + // worker. + omp_set_num_threads(1); + auto& tile = scratch[slot]; + const size_t first = first_query + slot * query_block; + const size_t rows = std::min(query_block, num_queries - first); + const float* block_queries = queries + first * dim_; + if (cosine_) { + for (size_t row = 0; row < rows; ++row) { + index_detail::normalize_vector( + block_queries + row * dim_, + tile.normalized.data() + row * dim_, + dim_ + ); + } + block_queries = tile.normalized.data(); + } + for (size_t row = 0; row < rows; ++row) { + rotator_->rotate( + block_queries + row * dim_, + tile.rotated.data() + row * padded_dim_ + ); + } + clustering::detail::exact_assign_topn( + tile.rotated.data(), + centroids, + rows, + padded_dim_, + num_clusters_, + nprobe, + metric_type_ == METRIC_IP, + centroid_norms.data(), + tile.candidates.data(), + tile.assignment ); } - block_queries = worker.normalized.data(); - } - for (size_t row = 0; row < rows; ++row) { - rotator_->rotate( - block_queries + row * dim_, worker.rotated.data() + row * padded_dim_ - ); - } - clustering::detail::exact_assign_topn( - worker.rotated.data(), - centroids, - rows, - padded_dim_, - num_clusters_, - nprobe, - metric_type_ == METRIC_IP, - centroid_norms.data(), - worker.candidates.data(), - worker.assignment ); - for (size_t row = 0; row < rows; ++row) { - const size_t i = first + row; - search_preassigned( - block_queries + row * dim_, - worker.rotated.data() + row * padded_dim_, - worker.candidates.data() + row * nprobe, - k, - nprobe, - result_ids + i * k, - distances == nullptr ? nullptr : distances + i * k, - hacc - ); - } - }); + index_detail::omp_for_dynamic( + wave_rows, workers, [&](size_t offset, size_t /*thread*/) { + const auto& tile = scratch[offset / query_block]; + const size_t row = offset % query_block; + const size_t i = first_query + offset; + search_preassigned( + cosine_ ? tile.normalized.data() + row * dim_ : queries + i * dim_, + tile.rotated.data() + row * padded_dim_, + tile.candidates.data() + row * nprobe, + k, + nprobe, + result_ids + i * k, + distances == nullptr ? nullptr : distances + i * k, + hacc + ); + } + ); + } return; } if (num_workers == 1) { for (size_t i = 0; i < num_queries; ++i) { - search( + search_validated( queries + i * dim_, k, nprobe, @@ -1733,7 +1763,7 @@ void IVF::search_batch( } index_detail::omp_for_dynamic( num_queries, num_workers, [&](size_t i, size_t /*thread*/) { - search( + search_validated( queries + i * dim_, k, nprobe, @@ -1851,25 +1881,26 @@ inline void IVF::scan_one_batch( // Refine candidates passing the probabilistic one-bit filter. Quantized storage // reuses ip_x0_qr with the extra bits; raw storage scores the original vector. + const size_t stride = rerank_vector_bytes(); for (size_t i = 0; i < batch_size; ++i) { float lower_bound = lower_bounds[i]; if (lower_bound < dist_k) { PID id = ids[i]; + const char* record = rerank_data + i * stride; float refined_distance; if (raw_reranking_) { - const auto* vector = reinterpret_cast(rerank_data); + const auto* vector = reinterpret_cast(record); refined_distance = metric_type_ == METRIC_L2 ? euclidean_sqr(query, vector, dim_) : dot_product_dis(query, vector, dim_); } else { refined_distance = split_distance_boosting( - rerank_data, ip_func_, query_wrapper, padded_dim_, ex_bits_, ip_x0_qr[i] + record, ip_func_, query_wrapper, padded_dim_, ex_bits_, ip_x0_qr[i] ); } result_pool.insert(id, refined_distance); dist_k = result_pool.top_dist(); } - rerank_data += rerank_vector_bytes(); } } From b6abb925383f2e5408991272ff164ebd20fd86de Mon Sep 17 00:00:00 2001 From: ColinLee Date: Wed, 25 Nov 2026 14:49:27 +0800 Subject: [PATCH 3/4] perf(fastscan): accumulate NEON lookup bytes in bounded chunks 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. --- src/fastscan/fastscan_neon.cpp | 100 +++++++++++------- .../unit/rabitqlib/fastscan/fastscan_test.cpp | 4 +- 2 files changed, 62 insertions(+), 42 deletions(-) diff --git a/src/fastscan/fastscan_neon.cpp b/src/fastscan/fastscan_neon.cpp index b98d2385..f5cb4621 100644 --- a/src/fastscan/fastscan_neon.cpp +++ b/src/fastscan/fastscan_neon.cpp @@ -12,49 +12,69 @@ namespace rabitqlib::fastscan::simd { namespace { +// Each chunk has at most 256 groups, so each byte plane sums to at most 65280. +constexpr size_t kChunkGroups = 256; + template -void accumulate_impl( - const uint8_t* codes, - const uint8_t* lookup_table, - int32_t* accumulated_values, - size_t dim +void accumulate_chunk( + const uint8_t* codes, const uint8_t* lut, int32_t* output, size_t groups ) { - std::array totals{}; - // Bound each uint32 lane to 256*65535, then widen across chunks. - constexpr size_t kChunkGroups = 256; - for (size_t start = 0; start < dim / 4; start += kChunkGroups) { - uint32x4_t sums[8]; - for (auto& sum : sums) { - sum = vdupq_n_u32(0); - } - const size_t end = std::min(start + kChunkGroups, dim / 4); - for (size_t group = start; group < end; ++group) { - const uint8x16_t packed = vld1q_u8(codes + group * 16); - const uint8x16_t indices[2] = { - vandq_u8(packed, vdupq_n_u8(15)), vshrq_n_u8(packed, 4)}; - const size_t offset = - HighAccuracy ? group / 2 * 64 + group % 2 * 16 : group * 16; - const uint8x16_t low = vld1q_u8(lookup_table + offset); - for (size_t half = 0; half < 2; ++half) { - const uint8x16_t values = vqtbl1q_u8(low, indices[half]); - uint16x8_t lo = vmovl_u8(vget_low_u8(values)); - uint16x8_t hi = vmovl_u8(vget_high_u8(values)); - if constexpr (HighAccuracy) { - const uint8x16_t high = - vqtbl1q_u8(vld1q_u8(lookup_table + offset + 32), indices[half]); - lo = vorrq_u16(lo, vshlq_n_u16(vmovl_u8(vget_low_u8(high)), 8)); - hi = vorrq_u16(hi, vshlq_n_u16(vmovl_u8(vget_high_u8(high)), 8)); - } - sums[half * 4] = vaddw_u16(sums[half * 4], vget_low_u16(lo)); - sums[half * 4 + 1] = vaddw_u16(sums[half * 4 + 1], vget_high_u16(lo)); - sums[half * 4 + 2] = vaddw_u16(sums[half * 4 + 2], vget_low_u16(hi)); - sums[half * 4 + 3] = vaddw_u16(sums[half * 4 + 3], vget_high_u16(hi)); + uint16x8_t low_sums[4]{}, high_sums[4]{}; + for (size_t group = 0; group < groups; ++group) { + const uint8x16_t packed = vld1q_u8(codes + group * 16); + const uint8x16_t indices[2] = { + vandq_u8(packed, vdupq_n_u8(15)), vshrq_n_u8(packed, 4)}; + // Pair32 stores low0, low1, high0, high1 as four 16-byte tables. + const size_t offset = HighAccuracy ? group / 2 * 64 + group % 2 * 16 : group * 16; + const uint8x16_t low = vld1q_u8(lut + offset); + for (size_t half = 0; half < 2; ++half) { + const uint8x16_t values = vqtbl1q_u8(low, indices[half]); + low_sums[2 * half] = vaddw_u8(low_sums[2 * half], vget_low_u8(values)); + low_sums[2 * half + 1] = vaddw_high_u8(low_sums[2 * half + 1], values); + if constexpr (HighAccuracy) { + const uint8x16_t high = + vqtbl1q_u8(vld1q_u8(lut + offset + 32), indices[half]); + high_sums[2 * half] = vaddw_u8(high_sums[2 * half], vget_low_u8(high)); + high_sums[2 * half + 1] = vaddw_high_u8(high_sums[2 * half + 1], high); } } - uint32_t chunk[kBatchSize]; - for (size_t i = 0; i < 8; ++i) { - vst1q_u32(chunk + i * 4, sums[i]); + } + for (size_t half = 0; half < 2; ++half) { + // kPerm0 interleaves rows 0..7 with 8..15 in each half of the batch. + const auto low = vuzpq_u16(low_sums[2 * half], low_sums[2 * half + 1]); + const auto high = vuzpq_u16(high_sums[2 * half], high_sums[2 * half + 1]); + for (size_t i = 0; i < 2; ++i) { + uint32x4_t first = vmovl_u16(vget_low_u16(low.val[i])); + uint32x4_t last = vmovl_high_u16(low.val[i]); + if constexpr (HighAccuracy) { + first = vaddq_u32(first, vshll_n_u16(vget_low_u16(high.val[i]), 8)); + last = vaddq_u32(last, vshll_high_n_u16(high.val[i], 8)); + } + int32_t* dst = output + half * 16 + i * 8; + vst1q_s32(dst, vreinterpretq_s32_u32(first)); + vst1q_s32(dst + 4, vreinterpretq_s32_u32(last)); } + } +} + +template +void accumulate_impl( + const uint8_t* codes, const uint8_t* lut, int32_t* accumulated_values, size_t dim +) { + const size_t groups = dim / 4; + if (groups <= kChunkGroups) { + accumulate_chunk(codes, lut, accumulated_values, groups); + return; + } + std::array totals{}; + for (size_t start = 0; start < groups; start += kChunkGroups) { + std::array chunk; + accumulate_chunk( + codes + start * 16, + lut + start * (HighAccuracy ? 32 : 16), + chunk.data(), + std::min(kChunkGroups, groups - start) + ); for (size_t i = 0; i < kBatchSize; ++i) { totals[i] += chunk[i]; } @@ -67,8 +87,8 @@ void accumulate_impl( ); } } - for (size_t i = 0; i < kBatchSize; ++i) { - accumulated_values[kPerm0[i % 16] + i / 16 * 16] = static_cast(totals[i]); + for (size_t lane = 0; lane < kBatchSize; ++lane) { + accumulated_values[lane] = static_cast(totals[lane]); } } } // namespace diff --git a/tests/unit/rabitqlib/fastscan/fastscan_test.cpp b/tests/unit/rabitqlib/fastscan/fastscan_test.cpp index 4e02cd5d..b868f647 100644 --- a/tests/unit/rabitqlib/fastscan/fastscan_test.cpp +++ b/tests/unit/rabitqlib/fastscan/fastscan_test.cpp @@ -249,10 +249,10 @@ TEST(FastScanPackingTest, UnpackInvertsPackIncludingTailsAndDoesNotOverrun) { } } -constexpr size_t kMaxDim = 768; +constexpr size_t kMaxDim = 1040; TEST(FastScanPackingTest, AccumulatesReferenceLutValuesOnEverySupportedBackend) { - for (size_t dim : {16U, 64U, 128U, 768U}) { + for (size_t dim : {16U, 64U, 128U, 768U, 960U, 1024U, 1040U}) { for (size_t num : {1U, 17U, 31U, 32U}) { SCOPED_TRACE(::testing::Message() << "dim=" << dim << " num=" << num); std::vector input(num * dim / 8); From c01722ec420227e9785db297cbeefd2084252ba0 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Wed, 25 Nov 2026 16:34:06 +0800 Subject: [PATCH 4/4] perf(ivf): keep Flat routing private and avoid redundant L2 scoring 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. --- .../rabitqlib/clustering/detail/kmeans.hpp | 99 ---------------- src/index/ivf.cpp | 4 +- src/index/ivf_search.cpp | 108 ++++++++++++++++++ src/index/ivf_search.hpp | 26 +++++ .../rabitqlib/index/flat_routing_test.cpp | 49 +++++++- 5 files changed, 181 insertions(+), 105 deletions(-) diff --git a/include/rabitqlib/clustering/detail/kmeans.hpp b/include/rabitqlib/clustering/detail/kmeans.hpp index 397033cb..9257ef39 100644 --- a/include/rabitqlib/clustering/detail/kmeans.hpp +++ b/include/rabitqlib/clustering/detail/kmeans.hpp @@ -22,7 +22,6 @@ #include "rabitqlib/core/detail/simd/matrix_dispatch.hpp" #include "rabitqlib/core/rotator.hpp" -#include "rabitqlib/index/detail/candidate.hpp" #include "rabitqlib/index/detail/parallel_exception.hpp" #include "rabitqlib/index/types.hpp" #include "rabitqlib/utils/cpu_features.hpp" @@ -76,104 +75,6 @@ namespace detail { return result; } -struct TopNAssignmentScratch { - std::vector products; - std::vector point_norms; -}; - -// Inputs are validated, contiguous rows in the same padded/rotated domain. -// centroid_norms contains k double-precision squared norms, computed once per -// batch. The caller bounds n and reuses scratch across blocks on each worker. -// Run inside an OpenMP task with omp_set_num_threads(1), even for one worker, -// so Eigen cannot start a nested team or change the caller's thread settings. -// Unlike exact_assign's clustering objective, return the existing float metric -// (sqrt for L2) and break ties by ID, exactly as FlatInitializer does. -inline void exact_assign_topn( - const float* x, - const float* centroids, - size_t n, - size_t d, - size_t k, - size_t nprobe, - bool spherical, - const double* centroid_norms, - AnnCandidate* candidates, - TopNAssignmentScratch& scratch -) { - assert(nprobe > 0 && nprobe <= k); - constexpr size_t kCentroidBlock = 256; - const bool screen = nprobe <= k / 4; - const index_detail::CandidateDistanceIdLess less; - if (screen) { - scratch.products.resize(n * std::min(k, kCentroidBlock)); - scratch.point_norms.resize(n); - } - const auto distance = [d, spherical](const float* vector, const float* centroid) { - return spherical ? dot_product_dis(vector, centroid, d) - : std::sqrt(euclidean_sqr(vector, centroid, d)); - }; - for (size_t row = 0; row < n; ++row) { - const float* vector = x + row * d; - auto* heap = candidates + row * nprobe; - if (screen) { - scratch.point_norms[row] = l2norm_sqr_f64(vector, d); - } - for (size_t cluster = 0; cluster < nprobe; ++cluster) { - heap[cluster].id = static_cast(cluster); - heap[cluster].distance = distance(vector, centroids + cluster * d); - } - std::make_heap(heap, heap + nprobe, less); - } - - // For validated d <= 65536, this conservatively covers the GEMM dot product, - // float distance accumulation, and sqrt rounding when the cutoff is squared. - // Both metrics need an underflow allowance. Only IP subtracts the dot from - // one and can incur absolute rounding error near one even for tiny norms. - const double error_scale = 8.0 * static_cast(d) * - static_cast(std::numeric_limits::epsilon()); - const double error_floor = - 8.0 * static_cast(d) * std::numeric_limits::min() + - (spherical ? 8.0 * std::numeric_limits::epsilon() : 0.0); - for (size_t first = nprobe; first < k; first += kCentroidBlock) { - const size_t cols = std::min(kCentroidBlock, k - first); - if (screen) { - simd::matrix_product_transposed( - x, centroids + first * d, scratch.products.data(), n, d, cols - ); - } - for (size_t row = 0; row < n; ++row) { - const float* vector = x + row * d; - auto* heap = candidates + row * nprobe; - for (size_t col = 0; col < cols; ++col) { - const size_t cluster = first + col; - if (screen) { - const double norm_sum = - scratch.point_norms[row] + centroid_norms[cluster]; - const double dot = scratch.products[row * cols + col]; - const double estimate = spherical ? 1.0 - dot : norm_sum - 2.0 * dot; - const double worst = heap[0].distance; - const double cutoff = spherical ? worst : worst * worst; - if (estimate > cutoff + error_scale * norm_sum + error_floor) { - continue; - } - } - AnnCandidate candidate; - candidate.id = static_cast(cluster); - candidate.distance = distance(vector, centroids + cluster * d); - if (less(candidate, heap[0])) { - std::pop_heap(heap, heap + nprobe, less); - heap[nprobe - 1] = candidate; - std::push_heap(heap, heap + nprobe, less); - } - } - } - } - for (size_t row = 0; row < n; ++row) { - auto* heap = candidates + row * nprobe; - std::sort_heap(heap, heap + nprobe, less); - } -} - // Inputs have already passed clustering validation. GEMM only screens candidates; // final distances and tie breaking retain the scalar double-precision arithmetic. // Optional previous assignments contain n valid centroid IDs and may alias the diff --git a/src/index/ivf.cpp b/src/index/ivf.cpp index b80a06ab..ec27b697 100644 --- a/src/index/ivf.cpp +++ b/src/index/ivf.cpp @@ -1661,7 +1661,7 @@ void IVF::search_batch( std::vector normalized; std::vector rotated; std::vector> candidates; - clustering::detail::TopNAssignmentScratch assignment; + detail::TopNAssignmentScratch assignment; }; std::vector scratch(workers); for (auto& worker : scratch) { @@ -1714,7 +1714,7 @@ void IVF::search_batch( tile.rotated.data() + row * padded_dim_ ); } - clustering::detail::exact_assign_topn( + detail::exact_assign_topn( tile.rotated.data(), centroids, rows, diff --git a/src/index/ivf_search.cpp b/src/index/ivf_search.cpp index 1abd8d55..627020d3 100644 --- a/src/index/ivf_search.cpp +++ b/src/index/ivf_search.cpp @@ -1,9 +1,17 @@ #include "ivf_search.hpp" +#include +#include +#include #include +#include +#include "rabitqlib/clustering/detail/kmeans.hpp" +#include "rabitqlib/core/detail/simd/matrix_dispatch.hpp" #include "rabitqlib/index/detail/buffer.hpp" +#include "rabitqlib/index/detail/candidate.hpp" #include "rabitqlib/index/types.hpp" +#include "rabitqlib/utils/space.hpp" namespace rabitqlib::ivf::detail { // Keep the scalar top-k loop out of the large inlined IVF search body. This avoids @@ -18,4 +26,104 @@ void insert_candidates( result_pool.insert(ids[i], distances[i]); } } + +void exact_assign_topn( + const float* x, + const float* centroids, + size_t n, + size_t d, + size_t k, + size_t nprobe, + bool spherical, + const double* centroid_norms, + AnnCandidate* candidates, + TopNAssignmentScratch& scratch +) { + assert(nprobe > 0 && nprobe <= k); + constexpr size_t kCentroidBlock = 256; + const index_detail::CandidateDistanceIdLess less; + scratch.products.resize(n * std::min(k, kCentroidBlock)); + scratch.point_norms.resize(n); + const auto distance = [d, spherical](const float* vector, const float* centroid) { + return spherical ? dot_product_dis(vector, centroid, d) + : std::sqrt(euclidean_sqr(vector, centroid, d)); + }; + const auto consider = [&](AnnCandidate* heap, size_t cluster, float dist) { + // Centroid IDs increase, so an equal returned distance cannot improve the heap. + if (dist < heap[0].distance) { + std::pop_heap(heap, heap + nprobe, less); + heap[nprobe - 1] = AnnCandidate(static_cast(cluster), dist); + std::push_heap(heap, heap + nprobe, less); + } + }; + for (size_t row = 0; row < n; ++row) { + const float* vector = x + row * d; + auto* heap = candidates + row * nprobe; + scratch.point_norms[row] = clustering::detail::l2norm_sqr_f64(vector, d); + for (size_t cluster = 0; cluster < nprobe; ++cluster) { + heap[cluster].id = static_cast(cluster); + heap[cluster].distance = distance(vector, centroids + cluster * d); + } + std::make_heap(heap, heap + nprobe, less); + } + + // For validated d <= 65536, this conservatively covers the GEMM dot product, + // float distance accumulation, and sqrt rounding when the cutoff is squared. + // Both metrics need an underflow allowance. Only IP subtracts the dot from + // one and can incur absolute rounding error near one even for tiny norms. + const double error_scale = 8.0 * static_cast(d) * + static_cast(std::numeric_limits::epsilon()); + const double error_floor = + 8.0 * static_cast(d) * std::numeric_limits::min() + + (spherical ? 8.0 * std::numeric_limits::epsilon() : 0.0); + for (size_t first = nprobe; first < k; first += kCentroidBlock) { + const size_t cols = std::min(kCentroidBlock, k - first); + simd::matrix_product_transposed( + x, centroids + first * d, scratch.products.data(), n, d, cols + ); + bool use_direct_l2 = !spherical; + for (size_t row = 0; row < n; ++row) { + const float* vector = x + row * d; + auto* heap = candidates + row * nprobe; + for (size_t col = 0; col < cols; ++col) { + const size_t cluster = first + col; + const double norm_sum = scratch.point_norms[row] + centroid_norms[cluster]; + const double dot = scratch.products[row * cols + col]; + const double estimate = spherical ? 1.0 - dot : norm_sum - 2.0 * dot; + const double worst = heap[0].distance; + const double cutoff = spherical ? worst : worst * worst; + if (estimate > cutoff + error_scale * norm_sum + error_floor) { + use_direct_l2 = false; + continue; + } + consider(heap, cluster, distance(vector, centroids + cluster * d)); + } + // Switch only when the tile rejected nothing and every query's own + // rounding allowance is already larger than its squared cutoff. + const double worst = heap[0].distance; + use_direct_l2 = + use_direct_l2 && error_scale * scratch.point_norms[row] > worst * worst; + } + if (use_direct_l2) { + // With a large common offset, GEMM and exact scoring would visit the + // same pairs. Keep the current heaps and score the remaining centroids once. + for (size_t row = 0; row < n; ++row) { + auto* heap = candidates + row * nprobe; + const float* vector = x + row * d; + for (size_t cluster = first + cols; cluster < k; ++cluster) { + const float squared = euclidean_sqr(vector, centroids + cluster * d, d); + const double worst = heap[0].distance; + if (squared < worst * worst) { + consider(heap, cluster, std::sqrt(squared)); + } + } + } + break; + } + } + for (size_t row = 0; row < n; ++row) { + auto* heap = candidates + row * nprobe; + std::sort_heap(heap, heap + nprobe, less); + } +} } // namespace rabitqlib::ivf::detail diff --git a/src/index/ivf_search.hpp b/src/index/ivf_search.hpp index bb495671..a2a8af4a 100644 --- a/src/index/ivf_search.hpp +++ b/src/index/ivf_search.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include "rabitqlib/index/detail/buffer.hpp" #include "rabitqlib/index/types.hpp" @@ -12,4 +13,29 @@ void insert_candidates( const float* distances, size_t count ); + +struct TopNAssignmentScratch { + std::vector products; + std::vector point_norms; +}; + +// Inputs are validated, contiguous rows in the same padded/rotated domain. +// centroid_norms contains k double-precision squared norms, computed once per +// batch. The caller bounds n and reuses scratch across blocks on each worker. +// Run inside an OpenMP task with omp_set_num_threads(1), even for one worker, +// so Eigen cannot start a nested team or change the caller's thread settings. +// Unlike exact_assign's clustering objective, return the existing float metric +// (sqrt for L2) and break ties by ID, exactly as FlatInitializer does. +void exact_assign_topn( + const float* x, + const float* centroids, + size_t n, + size_t d, + size_t k, + size_t nprobe, + bool spherical, + const double* centroid_norms, + AnnCandidate* candidates, + TopNAssignmentScratch& scratch +); } // namespace rabitqlib::ivf::detail diff --git a/tests/unit/rabitqlib/index/flat_routing_test.cpp b/tests/unit/rabitqlib/index/flat_routing_test.cpp index 54fdb617..d2bcaffa 100644 --- a/tests/unit/rabitqlib/index/flat_routing_test.cpp +++ b/tests/unit/rabitqlib/index/flat_routing_test.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -9,6 +10,7 @@ #include #include +#include "ivf_search.hpp" #include "rabitqlib/clustering/detail/kmeans.hpp" #include "rabitqlib/core/metric.hpp" #include "rabitqlib/index/ivf/initializer.hpp" @@ -23,7 +25,7 @@ TEST(IvfFlatRoutingTest, TopNMatchesScalarAcrossTilesAndTies) { constexpr size_t kClusters = 513, kQueries = 129; std::mt19937 rng(218); std::uniform_real_distribution random(-1, 1); - clustering::detail::TopNAssignmentScratch scratch; + detail::TopNAssignmentScratch scratch; for (size_t dim : {65U, 960U}) { for (float scale : {1.0F, 1.0e-8F, 1000.0F}) { std::vector centroids(kClusters * dim), queries(kQueries * dim); @@ -57,7 +59,7 @@ TEST(IvfFlatRoutingTest, TopNMatchesScalarAcrossTilesAndTies) { #pragma omp parallel num_threads(1) { omp_set_num_threads(1); - clustering::detail::exact_assign_topn( + detail::exact_assign_topn( queries.data(), centroids.data(), kQueries, @@ -107,11 +109,11 @@ TEST(IvfFlatRoutingTest, L2TiesUseReturnedFloatDistance) { scalar.centroids_distances(query.data(), 1, expected); EXPECT_EQ(expected[0].id, 0U); AnnCandidate actual; - clustering::detail::TopNAssignmentScratch scratch; + detail::TopNAssignmentScratch scratch; #pragma omp parallel num_threads(1) { omp_set_num_threads(1); - clustering::detail::exact_assign_topn( + detail::exact_assign_topn( query.data(), centroids.data(), 1, @@ -128,6 +130,45 @@ TEST(IvfFlatRoutingTest, L2TiesUseReturnedFloatDistance) { EXPECT_EQ(actual.distance, expected[0].distance); } +TEST(IvfFlatRoutingTest, CommonL2OffsetRetainsTiesAndFindsLateCentroids) { + constexpr size_t kDim = 64, kClusters = 515, kProbes = 2; + std::vector query(kDim, 1024.0F), centroids(kDim * kClusters, 1024.0F); + std::vector norms(kClusters); + for (size_t id = 0; id < kClusters; ++id) { + float* centroid = centroids.data() + id * kDim; + centroid[0] += 1.0F; + } + // IDs 257 and 258 tie across the end of the first 256-centroid screening + // block. The closest centroid is the very last one in the direct scan. + centroids[257 * kDim] = centroids[258 * kDim] = 1024.5F; + centroids[(kClusters - 1) * kDim] = 1024.25F; + for (size_t id = 0; id < kClusters; ++id) { + norms[id] = clustering::detail::l2norm_sqr_f64(centroids.data() + id * kDim, kDim); + } + std::array, kProbes> actual{}; + detail::TopNAssignmentScratch scratch; +#pragma omp parallel num_threads(1) + { + omp_set_num_threads(1); + detail::exact_assign_topn( + query.data(), + centroids.data(), + 1, + kDim, + kClusters, + kProbes, + false, + norms.data(), + actual.data(), + scratch + ); + } + EXPECT_EQ(actual[0].id, kClusters - 1); + EXPECT_EQ(actual[0].distance, 0.25F); + EXPECT_EQ(actual[1].id, 257U); + EXPECT_EQ(actual[1].distance, 0.5F); +} + TEST(IvfFlatRoutingTest, BatchSearchStreamsBlocksAndPreservesRemovedPadding) { constexpr size_t kCount = 577, kDim = 65, kClusters = 513, kQueries = 513; std::mt19937 rng(218);