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
8 changes: 8 additions & 0 deletions benchmarks/hotpaths/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ 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)
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"
"$<TARGET_FILE:rabitq_ivf_search_hotpaths>"
"${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
Expand Down
23 changes: 23 additions & 0 deletions benchmarks/hotpaths/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,29 @@ 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
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
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. 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.
- Inputs use an LCG with seed 42 (query/centroid seed 91 where applicable; IVF add uses
Expand Down
14 changes: 12 additions & 2 deletions benchmarks/hotpaths/common.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
#include <iomanip>
#include <iostream>
#include <limits>
#include <optional>
#include <stdexcept>
#include <string>
#include <system_error>
#include <vector>

Expand Down Expand Up @@ -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<uint32_t> 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';
Expand Down
115 changes: 115 additions & 0 deletions benchmarks/hotpaths/ivf_search.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// 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/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(
"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, index.seed(), metric_name(index.metric_type())
);
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))
);
});
double recall_sum = 0.0;
for (size_t row = 0; row < rows; ++row) {
const auto* expected = truth.data() + row * static_cast<size_t>(truth.cols());
const auto* found = ids.data() + row * k;
size_t hits = 0, valid = 0;
for (size_t i = 0; i < k; ++i) {
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<double>(hits) / static_cast<double>(valid);
}
std::cout << "# recall_at_10=" << recall_sum / static_cast<double>(rows) << '\n';
}
} // namespace

int main(int argc, char** argv) {
try {
run(argc, argv);
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
56 changes: 56 additions & 0 deletions benchmarks/hotpaths/test_ivf_search.py
Original file line number Diff line number Diff line change
@@ -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"<i{dim}f", dim, *query))
truth_file.write_bytes(struct.pack("<11i", 10, *truth))
return subprocess.run(
[
executable,
(fixtures / fixture).with_suffix(".index"),
query_file,
truth_file,
"1",
str(nprobe),
"1",
"1",
"1",
],
capture_output=True,
text=True,
check=success,
)

# The first reference query probes an empty/removed cluster with nprobe=1.
fixture = "v0.9.0/ivf4_flat_l2"
truth = [92] + [-1] * 9
assert "# recall_at_10=0" in run(fixture, 1, truth).stdout.splitlines()
# With all clusters probed it finds the sole valid reference ID.
assert "# recall_at_10=1" in run(fixture, 4, truth).stdout.splitlines()
empty = run(fixture, 1, [-1] * 10, success=False)
assert empty.returncode and "valid ground-truth ID" in empty.stderr
for fixture, metadata in [
("v0.9.0/ivf7_flatrabitq_cosine", "seed=42 metric=cosine"),
("v0.5.2/ivf32_ip", "seed=unknown metric=IP"),
]:
assert metadata in run(fixture, 1, truth).stdout


if __name__ == "__main__":
with tempfile.TemporaryDirectory() as tmp:
check(sys.argv[1], Path(sys.argv[2]), Path(tmp))
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
52 changes: 37 additions & 15 deletions 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 @@ -100,23 +101,44 @@ class FlatInitializer : public Initializer {
void centroids_distances(
const float* query, size_t nprobe, std::vector<AnnCandidate<float>>& candidates
) const override {
std::vector<AnnCandidate<float>> 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<std::ptrdiff_t>(num_probes),
centroid_candidates.end()
);

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<float>(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<PID>(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<float>(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.
Expand Down
20 changes: 20 additions & 0 deletions include/rabitqlib/index/ivf/ivf.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,26 @@ 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,
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