From a41d52dd5791414fa450ce361efd99d2517863ca Mon Sep 17 00:00:00 2001 From: co-stack Date: Tue, 24 Nov 2026 16:06:42 +0800 Subject: [PATCH] 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