Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions benchmarks/hotpaths/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions benchmarks/hotpaths/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
90 changes: 90 additions & 0 deletions benchmarks/hotpaths/ivf_search.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// Load one fixed IVF index; time only search_batch and verify Recall@10 outside timing.
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <exception>
#include <iostream>
#include <optional>
#include <stdexcept>
#include <vector>

#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<float> queries;
rabitqlib::RowMajorMatrix<rabitqlib::PID> truth;
rabitqlib::load_vecs<float>(argv[2], queries);
rabitqlib::load_vecs<rabitqlib::PID>(argv[3], truth);
constexpr size_t k = 10;
if (static_cast<size_t>(queries.cols()) != index.dimension() ||
queries.rows() != truth.rows() || truth.cols() < static_cast<int>(k)) {
throw std::invalid_argument("Query dimensions or ground-truth shape do not match");
}
const size_t rows = std::min(limit, static_cast<size_t>(queries.rows()));
std::vector<rabitqlib::PID> ids(bench::product(rows, k));
std::vector<float> 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<size_t>(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<double>(hits) / static_cast<double>(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;
}
}
99 changes: 99 additions & 0 deletions include/rabitqlib/clustering/detail/kmeans.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -75,6 +76,104 @@ namespace detail {
return result;
}

struct TopNAssignmentScratch {
std::vector<float> products;
std::vector<double> 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<float>* 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<PID>(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<double>(d) *
static_cast<double>(std::numeric_limits<float>::epsilon());
const double error_floor =
8.0 * static_cast<double>(d) * std::numeric_limits<float>::min() +
8.0 * std::numeric_limits<float>::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<float> candidate;
candidate.id = static_cast<PID>(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
Expand Down
15 changes: 15 additions & 0 deletions include/rabitqlib/index/detail/candidate.hpp
Original file line number Diff line number Diff line change
@@ -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<float>& a, const AnnCandidate<float>& b) const {
return a.distance < b.distance || (a.distance == b.distance && a.id < b.id);
}
};

} // namespace rabitqlib::index_detail
4 changes: 3 additions & 1 deletion include/rabitqlib/index/ivf/initializer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#include <vector>

#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"
Expand Down Expand Up @@ -112,7 +113,8 @@ class FlatInitializer : public Initializer {
std::partial_sort(
centroid_candidates.begin(),
centroid_candidates.begin() + static_cast<std::ptrdiff_t>(num_probes),
centroid_candidates.end()
centroid_candidates.end(),
index_detail::CandidateDistanceIdLess{}
);

candidates.resize(num_probes);
Expand Down
11 changes: 11 additions & 0 deletions include/rabitqlib/index/ivf/ivf.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,17 @@ class IVF {

void swap(IVF& other) noexcept;

inline void search_preassigned(
const float* query,
const float* rotated_query,
const AnnCandidate<float>* 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<float>& query_wrapper,
Expand Down
Loading
Loading