diff --git a/CMakeLists.txt b/CMakeLists.txt index 1c1d2e72..2c9988b9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -251,6 +251,7 @@ if(RABITQ_BUILD_INDEX) src/index/format2.cpp src/index/hnsw.cpp src/index/ivf.cpp + src/index/ivf_index.cpp src/index/ivf_initializer.cpp src/index/ivf_search.cpp src/index/qg.cpp diff --git a/docs/development.md b/docs/development.md index fcc448d6..811e7f9d 100644 --- a/docs/development.md +++ b/docs/development.md @@ -45,7 +45,8 @@ factors estimate L2 distance or inner product. | `include/rabitqlib/core/` | Per-vector encoding, query/estimation, rotation and per-vector byte layouts | | `include/rabitqlib/fastscan/` | All 32-vector batch layouts, encoding adapters, packing, LUT/estimation and FastScan/HACC | | `include/rabitqlib/core/types.hpp`, `core/detail/eigen.hpp` | Numerical configuration/types and internal Eigen aliases, respectively | -| `include/rabitqlib/index/types.hpp` | Point IDs and ANN candidate values; no Eigen dependency | +| `include/rabitqlib/index/types.hpp` | Point IDs, add options and ANN candidate values; no Eigen dependency | +| `include/rabitqlib/index/ivf_index.hpp` | `IvfIndex`, the supported C++ IVF API: the Python workflow over `ivf::IVF` | | `include/rabitqlib/clustering/` | RaBitQKMeans flat assignment, QGKMeans graph assignment, and shared Lloyd training | | `include/rabitqlib/index/{ivf,hnsw,symqg}/` | Index construction, persistence, and search | | `include/rabitqlib/{core,fastscan,index}/detail/` | Module-owned implementation headers; no public stability promise | @@ -573,13 +574,19 @@ a new format, freeze the last files of the old writer as release-produced fixtur Shared NumPy and string conversion helpers live in `python_bindings/bindings_common.hpp`. Register index-specific APIs in their own binding file and export public classes from `python_bindings/__init__.py`. Validate rank, dimensionality, state, and parameter ranges before -entering the core. Be deliberate about `py::array::forcecast`: it permits dtype/layout copies and +entering the core. A binding over a class that implements the Python workflow in C++, such as +`IvfIndex`, leaves the state checks and the removal-ID and `reserve_cluster` cluster-ID ranges +to that class. It keeps the conversions and shape checks, the `add` cluster-ID range and the +`num_points` sign checked before narrowing, the `k` range checked before allocating outputs, and +checks whose messages name Python values such as `None`. +Be deliberate about `py::array::forcecast`: it permits dtype/layout copies and must not be used where callers expect in-place mutation or pointer identity. C-contiguous NumPy storage is not necessarily aligned even to `alignof(T)`. `ensure_2d_array` copies misaligned inputs into an aligned owner; one-dimensional ID conversion uses packed reads in `checked_cluster_ids` and `checked_removal_ids` -before narrowing to owned PID storage. Reuse these helpers rather than directly +before narrowing to owned PID storage, and in `copied_ids` for an aligned `Id` copy +whose range the index checks. Reuse these helpers rather than directly dereferencing a possibly misaligned typed pointer. Removal IDs are checked against stored count, including removed records, rather than live count. @@ -590,6 +597,9 @@ conversion. Acquire and destroy guards with the GIL held, release the GIL only i their lifetime, and keep converted owners alive until reacquisition. Python wrappers use `IndexAccess` for concurrent reads and fail-fast exclusive updates. +Settings that Python changes through a returned reference, such as `cp`, take no guard: keep +them in the wrapper and copy them into the native index or the call's parameters with the GIL +and the write guard held before releasing the GIL. Extract native pointers before releasing the GIL and keep search parameters local to each call. C++ callers synchronize index mutations themselves. diff --git a/docs/docs/releases/unreleased.md b/docs/docs/releases/unreleased.md index b1b7bd03..f28c28f8 100644 --- a/docs/docs/releases/unreleased.md +++ b/docs/docs/releases/unreleased.md @@ -47,7 +47,9 @@ - Point IDs are `int64` at the Python boundary (#211): - `search` returns `int64` IDs, and slots without a neighbor hold `-1` instead of `2**32 - 1`; their distance is still `inf`. Code that compares IDs with `2**32 - 1`, `0xFFFFFFFF` or `np.iinfo(np.uint32).max` must change; `np.isfinite(distances)`, recommended since 0.8.2, works before and after. - `add` returns `int64` IDs. `remove` already took any integer IDs and still rejects `-1` and other out-of-range values without removing anything. - - IDs remain the row numbers the index assigns, and C++ point IDs remain 32-bit `PID` values with `kPidMax` for a missing result. + - IDs remain the row numbers the index assigns. The existing C++ index classes keep 32-bit `PID` values with `kPidMax` for a missing result; the new C++ `IvfIndex` uses 64-bit IDs, as Python does. + +- An `IvfIndex` call with both an invalid argument and the wrong state may now report the argument first, for example `ValueError` for `nprobe=0` on an untrained index, which raised `RuntimeError`. - Loading a format-2 file keeps the `seed` of every index, and `ef_construction` and `init` of SymphonyQG. They were `None` after `load`, and still are for files from releases up to 0.8. - With a recorded seed, `cp.seed` after `load` follows it as for a new index; for an HNSW-RaBitQ file whose seed exceeds 32 bits, which only C++ can write, it is the low 32 bits. It was the k-means default. @@ -62,6 +64,15 @@ ## C++ changes +- New `rabitqlib::IvfIndex` in `rabitqlib/index/ivf_index.hpp` (#234), with the workflow and defaults of the Python class, which now wraps it, and its messages where they do not name Python values: + - `IvfIndex(dim, num_clusters, options)` takes an `IvfOptions` struct with an `ivf::Routing`, an alias of `ivf::InitializerType`. A static `load` returns a trained index, and `train`, `set_centroids`, `add`, `remove`, `reserve_cluster`, `search` and `save` follow the Python methods. + - The first `add` trains an untrained index and leaves it untrained and empty if it fails. `add` takes an `AddOptions` struct and returns the first new ID. + - IDs are `rabitqlib::Id` (`int64_t`). A missing search result is `kNoId` (-1) with distance `+inf`. + - `search` takes a batch of queries and an `IvfSearchOptions` struct. Without an `nprobe` it probes `num_clusters / 16` clusters, rounded and at least 1, and an explicit 0 throws. + - A seed is drawn unless given, and `num_threads == 0` means every available CPU, capped by `OMP_NUM_THREADS`. + - Arguments out of range throw `std::invalid_argument`, and calls in the wrong state `std::logic_error`. +- `ivf::IVF` is unchanged. + - `qgkmeans::QGKMeansParameters` uses the Python names (#233): `graph_degree` becomes `max_degree`, `ef_build` becomes `ef_construction`, and `quantization_bits` (0, 4 or 8) becomes `nbits` (32, 4 or 8, with 32 for raw float32). The fields keep their order and types. An `nbits` of 0 is rejected, so code that initialized the field positionally with 0 must pass 32. `QGAssigner` keeps its constructor, including `quantization_bits` with 0 for raw storage. - Messages follow the names: `QGKMeans nbits must be 4, 8, or 32`, `QGKMeans max_degree must be a positive multiple of 32`, `QGKMeans requires more centroids than max_degree` and `QGKMeans ef_construction and ef_search must be positive`. - `FinalAssignmentMode::SymphonyQG`, an alias of `Approximate`, is removed. diff --git a/include/rabitqlib/index/ivf/types.hpp b/include/rabitqlib/index/ivf/types.hpp index f487e693..e1a93f28 100644 --- a/include/rabitqlib/index/ivf/types.hpp +++ b/include/rabitqlib/index/ivf/types.hpp @@ -4,4 +4,6 @@ namespace rabitqlib::ivf { enum class InitializerType : uint32_t { Auto = 0, Flat = 1, FlatRaBitQ = 2, HNSW = 3 }; +// Centroid routing of IvfIndex. Auto resolves by cluster count when the index is created. +using Routing = InitializerType; } // namespace rabitqlib::ivf diff --git a/include/rabitqlib/index/ivf_index.hpp b/include/rabitqlib/index/ivf_index.hpp new file mode 100644 index 00000000..840a0374 --- /dev/null +++ b/include/rabitqlib/index/ivf_index.hpp @@ -0,0 +1,195 @@ +#pragma once + +#include +#include +#include +#include + +#include "rabitqlib/core/metric.hpp" // IWYU pragma: export +#include "rabitqlib/index/ivf/types.hpp" // IWYU pragma: export +#include "rabitqlib/index/types.hpp" // IWYU pragma: export + +namespace rabitqlib { +namespace ivf { +class IVF; +} +namespace rabitqkmeans { +struct RaBitQKMeansParameters; +} + +// Settings of a new IvfIndex; set the fields by name. The metric comes first, so a lone +// positional value must be a metric: {4} does not compile. +struct IvfOptions { + MetricType metric = METRIC_L2; // METRIC_L2, METRIC_IP or METRIC_COSINE + size_t nbits = 7; // 1-9 quantization bits, or 32 for raw vectors + ivf::Routing routing = ivf::Routing::Auto; + std::optional seed; // rotation seed; no value draws one +}; + +// Settings of IvfIndex::search. +struct IvfSearchOptions { + // Clusters to probe; a value above num_clusters() probes every cluster. No value + // probes num_clusters() / 16, rounded, and at least 1; 0 throws. + std::optional nprobe; + // Worker count; 0 selects every available CPU, capped by OMP_NUM_THREADS. + size_t num_threads = 1; + // HACC reranking. No value selects it for 4-9 bits and standard FastScan otherwise. + std::optional high_accuracy; +}; + +/** + * @brief An IVF-RaBitQ index with the workflow of the Python IvfIndex. + * + * Create it, then add vectors: the first add trains an untrained index on them. Call + * train on a sample, or set_centroids, first to choose the training data or the + * centroids. Search, remove, reserve_cluster and save need a trained index. + * + * IDs are the row numbers the index assigns, consecutive from 0 in the order points are + * added. Removed points keep their IDs. + * + * Const members may run concurrently; a call that changes the index needs exclusive + * access. Arguments outside their documented range throw std::invalid_argument, a call + * in the wrong state std::logic_error, and load rabitqlib::FormatError for a damaged or + * unsupported file. The index is movable and not copyable; a moved-from index may only be + * destroyed or assigned to. + */ +class IvfIndex { + public: + /** + * @param dim Vector dimension + * @param num_clusters Number of centroids, from train, set_centroids or the first add + * @param options Metric, bits, routing and seed + */ + explicit IvfIndex(size_t dim, size_t num_clusters, const IvfOptions& options = {}); + + IvfIndex(IvfIndex&& other) noexcept; + IvfIndex& operator=(IvfIndex&& other) noexcept; + IvfIndex(const IvfIndex&) = delete; + IvfIndex& operator=(const IvfIndex&) = delete; + ~IvfIndex(); + + // Load an index saved by any release, with its rotation; the result is trained. + static IvfIndex load(const char* filename); + + // Requires at least one stored point. Releases up to 0.8 cannot read the file. + void save(const char* filename) const; + + /** + * @brief Clustering parameters of train and of the first add. + * + * Defaults: niter 10, max_points_per_centroid 256, spherical for inner product and + * cosine, and seed equal to the index seed, or the k-means default for a file + * without one. Include rabitqlib/clustering/rabitqkmeans.hpp to read or change the + * fields. + */ + rabitqkmeans::RaBitQKMeansParameters& cp(); + [[nodiscard]] const rabitqkmeans::RaBitQKMeansParameters& cp() const; + + /** + * @brief Train num_clusters() centroids on `data` and set them. + * + * Only centroids are trained; add assigns points. Retraining is allowed while the + * index stores no points. The index is unchanged if this throws. + * + * @param data Training points (num_points * dim) + * @param num_points At least num_clusters() + * @param num_threads Worker count for this call; no value uses cp().num_threads + */ + void train( + const float* data, + size_t num_points, + std::optional num_threads = std::nullopt + ); + + /** + * @brief Use the given centroids instead of training. + * + * Allowed while the index stores no points. The index is unchanged if this throws. + * + * @param centroids num_clusters() * dim values + * @param num_threads Worker count for building the centroid routing + */ + void set_centroids(const float* centroids, size_t num_threads = 0); + + /** + * @brief Add points, training an untrained index on them first. + * + * The first add trains num_clusters() centroids on `data` as train does, so it needs + * at least num_clusters() points and no cluster_ids; if it throws, the index stays + * untrained and empty. On a trained index the points are quantized against the + * existing centroids, which do not move, and the index is unchanged if this throws. + * + * @param data New points (num_points * dim) + * @param num_points Number of new points + * @param options Cluster IDs, worker count and quantization speed + * @return ID of the first new point; the batch has consecutive IDs + */ + Id add(const float* data, size_t num_points, const AddOptions& options = {}); + + /** + * @brief Exclude points from later search results. + * + * Removed points keep their IDs and storage, and removal cannot be undone. + * + * @param ids IDs in [0, num_stored_points()); repeats count once + * @param num_ids Number of IDs + * @return Number of points newly removed + */ + size_t remove(const Id* ids, size_t num_ids); + + // Preallocate room for cluster_id to hold num_points points in total, so that later + // adds grow it in place. Reserved room is not saved. + void reserve_cluster(size_t cluster_id, size_t num_points); + + /** + * @brief Search a batch of queries. + * + * Slots without a result get kNoId and +inf. Distances estimate squared L2, 1 - dot + * or 1 - cos according to the metric; lower is better. + * + * @param queries num_queries * dim values + * @param k Results per query, from 1 to 2^31; may exceed the number of points + * @param ids num_queries * k results + * @param distances num_queries * k results, or nullptr + */ + void search( + const float* queries, + size_t num_queries, + size_t k, + Id* ids, + float* distances, + const IvfSearchOptions& options = {} + ) const; + + [[nodiscard]] size_t dim() const; + [[nodiscard]] size_t num_clusters() const; + [[nodiscard]] size_t nbits() const; + [[nodiscard]] MetricType metric() const; + // Never Auto: the routing Auto resolved to. + [[nodiscard]] ivf::Routing routing() const; + // No value for an index loaded from a file of a release up to 0.8. + [[nodiscard]] std::optional seed() const; + // Live, searchable points. + [[nodiscard]] size_t num_points() const; + // Stored points, including removed ones. + [[nodiscard]] size_t num_stored_points() const; + // Whether centroids are set, by train, set_centroids, the first add or load. + [[nodiscard]] bool is_trained() const; + + private: + IvfIndex( + std::unique_ptr index, + std::unique_ptr cp + ); + + void check_trained(const char* operation) const; + void check_trainable() const; + [[nodiscard]] rabitqkmeans::RaBitQKMeansParameters training_parameters( + std::optional num_threads + ) const; + + std::unique_ptr index_; + std::unique_ptr cp_; +}; + +} // namespace rabitqlib diff --git a/include/rabitqlib/index/types.hpp b/include/rabitqlib/index/types.hpp index cc94266c..07aa3ea7 100644 --- a/include/rabitqlib/index/types.hpp +++ b/include/rabitqlib/index/types.hpp @@ -1,12 +1,32 @@ #pragma once +#include #include #include +#include namespace rabitqlib { using PID = uint32_t; inline constexpr PID kPidMax = 0xFFFFFFFF; +// A point ID at the IvfIndex API: the row number the index assigned to the point. +using Id = int64_t; +// A search result slot without a point. +inline constexpr Id kNoId = -1; + +// Settings of IvfIndex::add. +struct AddOptions { + // Cluster of each point, or nullptr to route each point with the index's routing, + // which may be approximate. + const PID* cluster_ids = nullptr; + // Worker count. No value trains an untrained index with cp().num_threads and adds + // with every available CPU; 0 selects every available CPU, capped by OMP_NUM_THREADS. + std::optional num_threads; + // Fixed-scale extra-bit quantization: faster, possibly less accurate. No effect on + // one-bit or raw storage. + bool fast_quantization = false; +}; + template struct AnnCandidate { TP id = 0; diff --git a/python_bindings/bindings_common.hpp b/python_bindings/bindings_common.hpp index 92bbceb7..17592aaf 100644 --- a/python_bindings/bindings_common.hpp +++ b/python_bindings/bindings_common.hpp @@ -466,6 +466,21 @@ inline std::vector checked_removal_ids( return result; } +// An aligned copy of IDs whose rank and dtype the caller has validated; the index checks +// their range. +inline std::vector copied_ids( + const py::array_t& ids +) { + std::vector result(static_cast(ids.shape(0))); + const detail::ConstPackedArrayView values( + reinterpret_cast(ids.data()) + ); + for (size_t i = 0; i < result.size(); ++i) { + result[i] = values[i]; + } + return result; +} + // Validate before narrowing, and own the result for APIs that mutate assignments. inline std::vector checked_cluster_ids( py::handle value, size_t rows, size_t clusters diff --git a/python_bindings/ivf_bindings.cpp b/python_bindings/ivf_bindings.cpp index 77e5dbaa..7531364f 100644 --- a/python_bindings/ivf_bindings.cpp +++ b/python_bindings/ivf_bindings.cpp @@ -9,19 +9,17 @@ #include #include #include -#include +#include #include -#include #include #include +#include #include #include "bindings_common.hpp" #include "rabitqlib/clustering/rabitqkmeans.hpp" -#include "rabitqlib/core/rotator.hpp" -#include "rabitqlib/index/ivf/initializer.hpp" -#include "rabitqlib/index/ivf/ivf.hpp" -#include "rabitqlib/index/training.hpp" +#include "rabitqlib/index/ivf/types.hpp" +#include "rabitqlib/index/ivf_index.hpp" #include "rabitqlib/index/types.hpp" namespace py = pybind11; @@ -69,49 +67,28 @@ class IvfIndex { const std::string& metric, const std::string& routing, const py::object& seed - ) { - const auto metric_type = index_metric_from_string(metric); - const auto initializer_type = routing_from_string(routing); - const auto rotation_seed = - seed.is_none() ? std::random_device{}() - : static_cast( - checked_seed(seed, std::numeric_limits::max()) - ); - index_ = std::make_unique( - dim, - num_clusters, - nbits, - metric_type, - rotation_seed, - RotatorType::FhtKacRotator, - initializer_type - ); - seed_ = rotation_seed; - cp_ = default_training_parameters(metric_type, rotation_seed); - } + ) + : index_(dim, num_clusters, index_options(nbits, metric, routing, seed)) + , cp_(index_.cp()) {} void train(py::handle x, std::optional num_threads) { const auto operation = access_.write(); auto x_array = ensure_2d_array(x, "x"); - check_trainable(); - ensure_dimension( - x_array, index_->dimension(), "x dimension does not match index dim" - ); - const auto rows = training_rows(x_array, index_->num_clusters()); - const auto cp = training_parameters(cp_, num_threads); + ensure_dimension(x_array, index_.dim(), "x dimension does not match index dim"); + const auto rows = training_rows(x_array, index_.num_clusters()); const auto* x_ptr = x_array.data(); + index_.cp() = cp_; py::gil_scoped_release release; - index_->train(rows, x_ptr, cp); + index_.train(x_ptr, rows, num_threads); } void set_centroids(py::handle centroids, std::optional num_threads) { const auto operation = access_.write(); auto centroids_array = ensure_2d_array(centroids, "centroids"); - check_trainable(); - check_centroid_shape(centroids_array, index_->num_clusters(), index_->dimension()); + check_centroid_shape(centroids_array, index_.num_clusters(), index_.dim()); const auto* centroids_ptr = centroids_array.data(); py::gil_scoped_release release; - index_->set_centroids(centroids_ptr, num_threads.value_or(0)); + index_.set_centroids(centroids_ptr, num_threads.value_or(0)); } py::array_t add( @@ -122,95 +99,48 @@ class IvfIndex { ) { const auto operation = access_.write(); auto data_array = ensure_2d_array(data, "data"); - // The first add on an untrained index trains it on the same data. A loaded - // index is trained, so an untrained one knows its seed. - const bool trains = - !index_->is_trained() && cluster_ids.is_none() && data_array.shape(0) > 0; - if (!trains) { - check_trained("add"); - } ensure_dimension( - data_array, index_->dimension(), "data dimension does not match index dim" + data_array, index_.dim(), "data dimension does not match index dim" ); const auto rows = static_cast(data_array.shape(0)); - if (trains && rows < index_->num_clusters()) { - throw std::invalid_argument( - "the first add trains the index and needs at least num_clusters rows; " - "expected at least " + - std::to_string(index_->num_clusters()) + ", got shape " + - array_shape(data_array) - ); - } - std::vector assigned; + AddOptions options; if (!cluster_ids.is_none()) { - assigned = checked_cluster_ids(cluster_ids, rows, index_->num_clusters()); + assigned = checked_cluster_ids(cluster_ids, rows, index_.num_clusters()); + options.cluster_ids = assigned.data(); } - - const size_t first = index_->num_stored_points(); - // Allocate the returned IDs before committing any changes to the index. + options.num_threads = num_threads; + options.fast_quantization = fast_quantization; + // Allocate the returned IDs before the index changes. auto ids = py::array_t(static_cast(rows)); - auto* ids_data = ids.mutable_data(); - for (size_t i = 0; i < rows; ++i) { - ids_data[i] = static_cast(first + i); - } - const auto* data_ptr = data_array.data(); - const size_t threads = num_threads.value_or(0); - if (trains) { - // Train and fill a fresh index with the same rotation, then swap it in, - // so that a failure leaves this index untrained and empty. - const auto cp = training_parameters(cp_, num_threads); - auto staged = std::make_unique( - index_->dimension(), - index_->num_clusters(), - index_->nbits(), - index_->metric_type(), - *seed_, - RotatorType::FhtKacRotator, - index_->initializer_type() - ); - { - py::gil_scoped_release release; - staged->train(rows, data_ptr, cp); - staged->add(data_ptr, rows, nullptr, fast_quantization, threads); - } - index_.swap(staged); - return ids; - } + index_.cp() = cp_; // the first add trains with it + Id first = 0; { py::gil_scoped_release release; - index_->add( - data_ptr, - rows, - assigned.empty() ? nullptr : assigned.data(), - fast_quantization, - threads - ); + first = index_.add(data_ptr, rows, options); } + std::iota(ids.mutable_data(), ids.mutable_data() + rows, first); return ids; } void reserve_cluster(int64_t cluster_id, int64_t num_points) { const auto operation = access_.write(); - check_trained("reserve_cluster"); - if (cluster_id < 0 || static_cast(cluster_id) >= index_->num_clusters()) { - throw std::invalid_argument("cluster_id must be in [0, num_clusters)"); - } if (num_points < 0) { throw std::invalid_argument("num_points must be non-negative"); } py::gil_scoped_release release; - index_->reserve(static_cast(cluster_id), static_cast(num_points)); + // A negative cluster_id converts to a value the index rejects as out of range. + index_.reserve_cluster( + static_cast(cluster_id), static_cast(num_points) + ); } size_t remove(py::handle ids) { const auto operation = access_.write(); - auto ids_array = ensure_1d_integer_array(ids, "ids"); - check_trained("remove"); - auto to_remove = checked_removal_ids(ids_array, index_->num_stored_points()); + const auto to_remove = copied_ids(ensure_1d_integer_array(ids, "ids")); py::gil_scoped_release release; - return index_->remove(to_remove.data(), to_remove.size()); + return index_.remove(to_remove.data(), to_remove.size()); } py::tuple search( @@ -222,120 +152,102 @@ class IvfIndex { ) { const auto operation = access_.read(); auto query_array = ensure_2d_array(queries, "queries"); - check_trained("search"); ensure_dimension( - query_array, index_->dimension(), "query dimension does not match index dim" + query_array, index_.dim(), "query dimension does not match index dim" ); - check_k(k); + check_k(k); // before the outputs are allocated if (nprobe == size_t{0}) { throw std::invalid_argument( "nprobe must be at least 1; pass None for the default" ); } - // None probes num_clusters / 16 clusters, rounded, and at least one. - const size_t num_probes = - nprobe.value_or(std::max(1, (index_->num_clusters() + 8) / 16)); - - const size_t num_queries = static_cast(query_array.shape(0)); - auto output = unfilled_search_results(num_queries, k); - auto* ids_data = output.ids.data(); - auto* distances_data = output.distances.mutable_data(); - + IvfSearchOptions options; + options.nprobe = nprobe; + options.num_threads = num_threads.value_or(1); + options.high_accuracy = high_accuracy; + + const auto num_queries = static_cast(query_array.shape(0)); + const auto shape = std::vector{ + static_cast(num_queries), static_cast(k)}; + auto ids = py::array_t(shape); + auto distances = py::array_t(shape); const auto* queries_data = query_array.data(); + auto* ids_data = ids.mutable_data(); + auto* distances_data = distances.mutable_data(); { py::gil_scoped_release release; - index_->search_batch( - queries_data, - num_queries, - k, - num_probes, - ids_data, - distances_data, - high_accuracy, - num_threads.value_or(1) - ); + index_.search(queries_data, num_queries, k, ids_data, distances_data, options); } - - return output.to_python(); + return py::make_tuple(ids, distances); } void save(py::handle path) const { const auto filename = path_string(path); const auto operation = access_.read(); - check_trained("save"); - if (index_->num_stored_points() == 0) { - throw std::runtime_error("IvfIndex has no points to save; add points first"); - } py::gil_scoped_release release; - index_->save(filename.c_str()); + index_.save(filename.c_str()); } static IvfIndex load(py::handle path) { const auto filename = path_string(path); - IvfIndex wrapper; - wrapper.index_ = std::make_unique(); - { + auto index = [&filename] { py::gil_scoped_release release; - wrapper.index_->load(filename.c_str()); - } - wrapper.seed_ = wrapper.index_->seed(); // recorded by format-2 files - wrapper.cp_ = default_training_parameters( - wrapper.index_->metric_type(), - wrapper.seed_.value_or(rabitqkmeans::RaBitQKMeansParameters{}.seed) - ); - return wrapper; + return rabitqlib::IvfIndex::load(filename.c_str()); + }(); + return IvfIndex(std::move(index)); } [[nodiscard]] std::string repr() const { const auto operation = access_.read(); - return "IvfIndex(dim=" + std::to_string(index_->dimension()) + ", metric='" + - metric_to_string(index_->metric_type()) + - "', nbits=" + std::to_string(index_->nbits()) + - ", num_points=" + std::to_string(index_->num_points()) + - ", num_stored_points=" + std::to_string(index_->num_stored_points()) + - ", num_clusters=" + std::to_string(index_->num_clusters()) + ", routing='" + - routing_to_string(index_->initializer_type()) + - "', is_trained=" + (index_->is_trained() ? "True" : "False") + ")"; + return "IvfIndex(dim=" + std::to_string(index_.dim()) + ", metric='" + + metric_to_string(index_.metric()) + + "', nbits=" + std::to_string(index_.nbits()) + + ", num_points=" + std::to_string(index_.num_points()) + + ", num_stored_points=" + std::to_string(index_.num_stored_points()) + + ", num_clusters=" + std::to_string(index_.num_clusters()) + ", routing='" + + routing_to_string(index_.routing()) + + "', is_trained=" + (index_.is_trained() ? "True" : "False") + ")"; } [[nodiscard]] size_t dim() const { const auto operation = access_.read(); - return index_->dimension(); + return index_.dim(); } [[nodiscard]] size_t num_points() const { const auto operation = access_.read(); - return index_->num_points(); + return index_.num_points(); } [[nodiscard]] size_t num_stored_points() const { const auto operation = access_.read(); - return index_->num_stored_points(); + return index_.num_stored_points(); } [[nodiscard]] size_t num_clusters() const { const auto operation = access_.read(); - return index_->num_clusters(); + return index_.num_clusters(); } [[nodiscard]] size_t nbits() const { const auto operation = access_.read(); - return index_->nbits(); + return index_.nbits(); } [[nodiscard]] bool is_trained() const { const auto operation = access_.read(); - return index_->is_trained(); + return index_.is_trained(); } [[nodiscard]] std::optional seed() const { const auto operation = access_.read(); - return seed_; + return index_.seed(); } [[nodiscard]] std::string routing() const { const auto operation = access_.read(); - return routing_to_string(index_->initializer_type()); + return routing_to_string(index_.routing()); } [[nodiscard]] std::string metric() const { const auto operation = access_.read(); - return metric_to_string(index_->metric_type()); + return metric_to_string(index_.metric()); } - // Parameters are wrapper state that train copies with the GIL held. + // Python reads and writes the fields of cp_ with the GIL held but without a guard, so + // the native index trains with a copy that train and add make with the GIL held. rabitqkmeans::RaBitQKMeansParameters& cp() { return cp_; } void set_cp(const rabitqkmeans::RaBitQKMeansParameters& cp) { const auto operation = access_.write(); @@ -343,26 +255,30 @@ class IvfIndex { } private: - IvfIndex() = default; + explicit IvfIndex(rabitqlib::IvfIndex index) + : index_(std::move(index)), cp_(index_.cp()) {} - void check_trained(const char* operation) const { - if (!index_->is_trained()) { - throw std::runtime_error( - std::string("IvfIndex must be trained or loaded before ") + operation + static IvfOptions index_options( + size_t nbits, + const std::string& metric, + const std::string& routing, + const py::object& seed + ) { + IvfOptions options; + options.metric = index_metric_from_string(metric); + options.routing = routing_from_string(routing); + if (!seed.is_none()) { + options.seed = static_cast( + checked_seed(seed, std::numeric_limits::max()) ); } - } - - void check_trainable() const { - if (index_->num_stored_points() != 0) { - throw std::runtime_error("IvfIndex cannot be trained once it stores points"); - } + options.nbits = nbits; + return options; } mutable IndexAccess access_; - std::unique_ptr index_; + rabitqlib::IvfIndex index_; rabitqkmeans::RaBitQKMeansParameters cp_; - std::optional seed_; // Unknown for files from releases up to 0.8. }; } // namespace rabitqlib::python_bindings diff --git a/src/index/ivf_index.cpp b/src/index/ivf_index.cpp new file mode 100644 index 00000000..103624c7 --- /dev/null +++ b/src/index/ivf_index.cpp @@ -0,0 +1,243 @@ +#include "rabitqlib/index/ivf_index.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rabitqlib/clustering/rabitqkmeans.hpp" +#include "rabitqlib/core/types.hpp" +#include "rabitqlib/index/detail/buffer.hpp" +#include "rabitqlib/index/ivf/ivf.hpp" +#include "rabitqlib/index/training.hpp" + +namespace rabitqlib { + +namespace { +using rabitqkmeans::RaBitQKMeansParameters; + +// num_clusters / 16, rounded, and at least 1. +size_t default_nprobe(size_t num_clusters) { + return std::max(1, (num_clusters + 8) / 16); +} +} // namespace + +IvfIndex::IvfIndex(size_t dim, size_t num_clusters, const IvfOptions& options) { + const uint32_t seed = options.seed.has_value() ? *options.seed : std::random_device{}(); + index_ = std::make_unique( + dim, + num_clusters, + options.nbits, + options.metric, + seed, + RotatorType::FhtKacRotator, + options.routing + ); + cp_ = std::make_unique( + default_training_parameters(options.metric, seed) + ); +} + +IvfIndex::IvfIndex( + std::unique_ptr index, std::unique_ptr cp +) + : index_(std::move(index)), cp_(std::move(cp)) {} + +IvfIndex::IvfIndex(IvfIndex&& other) noexcept = default; +IvfIndex& IvfIndex::operator=(IvfIndex&& other) noexcept = default; +IvfIndex::~IvfIndex() = default; + +IvfIndex IvfIndex::load(const char* filename) { + auto index = std::make_unique(); + index->load(filename); + // Files from releases up to 0.8 do not record the seed. + const auto seed = index->seed().value_or(RaBitQKMeansParameters{}.seed); + auto cp = std::make_unique( + default_training_parameters(index->metric_type(), seed) + ); + return IvfIndex(std::move(index), std::move(cp)); +} + +void IvfIndex::save(const char* filename) const { + check_trained("save"); + if (index_->num_stored_points() == 0) { + throw std::logic_error("IvfIndex has no points to save; add points first"); + } + index_->save(filename); +} + +RaBitQKMeansParameters& IvfIndex::cp() { return *cp_; } + +const RaBitQKMeansParameters& IvfIndex::cp() const { return *cp_; } + +void IvfIndex::train( + const float* data, size_t num_points, std::optional num_threads +) { + check_trainable(); + index_->train(num_points, data, training_parameters(num_threads)); +} + +void IvfIndex::set_centroids(const float* centroids, size_t num_threads) { + check_trainable(); + index_->set_centroids(centroids, num_threads); +} + +Id IvfIndex::add(const float* data, size_t num_points, const AddOptions& options) { + const bool trains = + !index_->is_trained() && options.cluster_ids == nullptr && num_points > 0; + if (!trains) { + check_trained("add"); + } + const auto first = static_cast(index_->num_stored_points()); + const size_t num_threads = options.num_threads.value_or(0); + if (!trains) { + index_->add( + data, num_points, options.cluster_ids, options.fast_quantization, num_threads + ); + return first; + } + if (num_points < index_->num_clusters()) { + throw std::invalid_argument( + "the first add trains the index and needs at least num_clusters rows; " + "expected at least " + + std::to_string(index_->num_clusters()) + ", got shape (" + + std::to_string(num_points) + ", " + std::to_string(index_->dimension()) + ")" + ); + } + // Train and fill a new index with the same settings and rotation seed, then move it + // in, so that a failure leaves this index untrained and empty. Only a loaded index + // lacks a seed, and it is trained. + auto staged = std::make_unique( + index_->dimension(), + index_->num_clusters(), + index_->nbits(), + index_->metric_type(), + index_->seed().value(), + RotatorType::FhtKacRotator, + index_->initializer_type() + ); + staged->train(num_points, data, training_parameters(options.num_threads)); + staged->add(data, num_points, nullptr, options.fast_quantization, num_threads); + index_ = std::move(staged); + return first; +} + +size_t IvfIndex::remove(const Id* ids, size_t num_ids) { + check_trained("remove"); + if (num_ids != 0 && ids == nullptr) { + throw std::invalid_argument("IvfIndex remove ids must not be null"); + } + const size_t num_stored = index_->num_stored_points(); + std::vector row_ids(num_ids); + for (size_t i = 0; i < num_ids; ++i) { + if (ids[i] < 0 || static_cast(ids[i]) >= num_stored) { + throw std::invalid_argument("ids must be in [0, num_stored_points)"); + } + row_ids[i] = static_cast(ids[i]); + } + return index_->remove(row_ids.data(), row_ids.size()); +} + +void IvfIndex::reserve_cluster(size_t cluster_id, size_t num_points) { + check_trained("reserve_cluster"); + if (cluster_id >= index_->num_clusters()) { + throw std::invalid_argument("cluster_id must be in [0, num_clusters)"); + } + index_->reserve(static_cast(cluster_id), num_points); +} + +void IvfIndex::search( + const float* queries, + size_t num_queries, + size_t k, + Id* ids, + float* distances, + const IvfSearchOptions& options +) const { + check_trained("search"); + if (k == 0 || k > buffer::kSearchBufferMaxPointCount) { + throw std::invalid_argument("k must be between 1 and 2^31"); + } + if (options.nprobe == size_t{0}) { + throw std::invalid_argument( + "nprobe must be at least 1; leave it unset for the default" + ); + } + if (num_queries == 0) { + return; + } + if (ids == nullptr) { + throw std::invalid_argument("IvfIndex search ids must not be null"); + } + if (num_queries > std::numeric_limits::max() / sizeof(Id) / k) { + throw std::length_error("IvfIndex query batch is too large"); + } + // The index writes 32-bit row numbers, which are widened afterwards. + std::vector row_ids(num_queries * k); + index_->search_batch( + queries, + num_queries, + k, + options.nprobe.value_or(default_nprobe(index_->num_clusters())), + row_ids.data(), + distances, + options.high_accuracy, + options.num_threads + ); + std::transform(row_ids.begin(), row_ids.end(), ids, [](PID id) { + return id == kPidMax ? kNoId : static_cast(id); + }); +} + +size_t IvfIndex::dim() const { return index_->dimension(); } + +size_t IvfIndex::num_clusters() const { return index_->num_clusters(); } + +size_t IvfIndex::nbits() const { return index_->nbits(); } + +MetricType IvfIndex::metric() const { return index_->metric_type(); } + +ivf::Routing IvfIndex::routing() const { return index_->initializer_type(); } + +std::optional IvfIndex::seed() const { return index_->seed(); } + +size_t IvfIndex::num_points() const { return index_->num_points(); } + +size_t IvfIndex::num_stored_points() const { return index_->num_stored_points(); } + +bool IvfIndex::is_trained() const { return index_->is_trained(); } + +void IvfIndex::check_trained(const char* operation) const { + if (!index_->is_trained()) { + throw std::logic_error( + std::string("IvfIndex must be trained or loaded before ") + operation + ); + } +} + +void IvfIndex::check_trainable() const { + if (index_->num_stored_points() != 0) { + throw std::logic_error("IvfIndex cannot be trained once it stores points"); + } +} + +RaBitQKMeansParameters IvfIndex::training_parameters( + std::optional num_threads +) const { + RaBitQKMeansParameters cp = *cp_; + if (num_threads.has_value()) { + cp.num_threads = static_cast( + std::min(*num_threads, std::numeric_limits::max()) + ); + } + return cp; +} + +} // namespace rabitqlib diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 62ff0125..b05e0f61 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -51,6 +51,7 @@ set_source_files_properties(unit/rabitqlib/utils/blob_test.cpp PROPERTIES COMPILE_DEFINITIONS "RABITQ_QUANT_FIXTURE_ROOT=\"${CMAKE_CURRENT_SOURCE_DIR}/python/fixtures/quant\"") set_source_files_properties(unit/rabitqlib/index/historical_persistence_test.cpp + unit/rabitqlib/index/ivf_index_test.cpp PROPERTIES COMPILE_DEFINITIONS "RABITQ_TEST_FIXTURE_ROOT=\"${CMAKE_CURRENT_SOURCE_DIR}/fixtures/persistence\"") rabitq_configure_target(rabitq_tests) @@ -141,6 +142,11 @@ if(RABITQ_BUILD_INDEX) rabitq_configure_target(hnsw_add_allocation_test) gtest_discover_tests(hnsw_add_allocation_test DISCOVERY_MODE PRE_TEST) + add_executable(ivf_index_allocation_test failures/ivf_index_allocation_test.cpp) + target_link_libraries(ivf_index_allocation_test PRIVATE GTest::gtest_main rabitqlib::index) + rabitq_configure_target(ivf_index_allocation_test) + gtest_discover_tests(ivf_index_allocation_test DISCOVERY_MODE PRE_TEST) + endif() # Message to verify files are found diff --git a/tests/consumer/CMakeLists.txt b/tests/consumer/CMakeLists.txt index db8ba4cb..629b70ba 100644 --- a/tests/consumer/CMakeLists.txt +++ b/tests/consumer/CMakeLists.txt @@ -52,6 +52,17 @@ foreach(header IN ITEMS endforeach() target_include_directories(index_header_boundary BEFORE PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/forbidden") +# The supported IVF API also hides the existing IVF class and k-means. +add_executable(ivf_index_header_boundary ivf_index_headers.cpp) +target_link_libraries(ivf_index_header_boundary PRIVATE rabitqlib::index) +foreach(header IN ITEMS index/ivf/ivf.hpp index/ivf/cluster.hpp clustering/rabitqkmeans.hpp) + get_filename_component(directory "${header}" DIRECTORY) + file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/ivf-index-forbidden/rabitqlib/${directory}") + file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/ivf-index-forbidden/rabitqlib/${header}" + "#error IvfIndex public header imports an implementation dependency\n") +endforeach() +target_include_directories(ivf_index_header_boundary BEFORE PRIVATE + "${CMAKE_CURRENT_BINARY_DIR}/forbidden" "${CMAKE_CURRENT_BINARY_DIR}/ivf-index-forbidden") add_library(hnsw_quant_header_boundary OBJECT hnsw_quant_headers.cpp) target_link_libraries(hnsw_quant_header_boundary PRIVATE rabitqlib::index) add_library(symqg_scratch_header_boundary OBJECT symqg_scratch_headers.cpp) @@ -68,6 +79,7 @@ target_include_directories(index_types_boundary BEFORE PRIVATE enable_testing() add_test(NAME rabitqlib_consumer COMMAND rabitqlib_consumer) add_test(NAME index_header_boundary COMMAND index_header_boundary) +add_test(NAME ivf_index_header_boundary COMMAND ivf_index_header_boundary) # Inspect evaluated, transitive usage requirements rather than just the direct # properties of the public interface target. This works with multi-config builds. diff --git a/tests/consumer/index_types.cpp b/tests/consumer/index_types.cpp index e829db38..b062dd81 100644 --- a/tests/consumer/index_types.cpp +++ b/tests/consumer/index_types.cpp @@ -5,4 +5,6 @@ static_assert(std::is_same_v); static_assert(rabitqlib::kPidMax == UINT32_MAX); +static_assert(std::is_same_v); +static_assert(rabitqlib::kNoId == -1); static_assert(std::is_trivially_copyable_v>); diff --git a/tests/consumer/ivf_index_headers.cpp b/tests/consumer/ivf_index_headers.cpp new file mode 100644 index 00000000..6bbf81f4 --- /dev/null +++ b/tests/consumer/ivf_index_headers.cpp @@ -0,0 +1,27 @@ +#include +#include +#include + +#include "rabitqlib/index/ivf_index.hpp" + +// The supported IVF API compiles and works without the existing IVF class, k-means or +// any implementation header. +int main() { + constexpr size_t kDim = 64; + constexpr size_t kNumPoints = 40; + std::mt19937 rng(1); + std::normal_distribution normal; + std::vector data(kNumPoints * kDim); + for (auto& value : data) { + value = normal(rng); + } + rabitqlib::IvfOptions options; + options.seed = 3; + rabitqlib::IvfIndex index(kDim, 2, options); + const rabitqlib::Id first = index.add(data.data(), kNumPoints); + std::vector ids(kNumPoints + 1); + index.search(data.data(), 1, ids.size(), ids.data(), nullptr); + return first == 0 && index.num_points() == kNumPoints && ids.back() == rabitqlib::kNoId + ? 0 + : 1; +} diff --git a/tests/failures/ivf_index_allocation_test.cpp b/tests/failures/ivf_index_allocation_test.cpp new file mode 100644 index 00000000..23abbaf3 --- /dev/null +++ b/tests/failures/ivf_index_allocation_test.cpp @@ -0,0 +1,125 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rabitqlib/clustering/rabitqkmeans.hpp" +#include "rabitqlib/index/ivf_index.hpp" +#include "rabitqlib/index/types.hpp" + +namespace { +std::atomic fail_enabled{false}; +std::atomic allocations_before_failure{0}; + +class AllocationFailure { + public: + explicit AllocationFailure(size_t before_failure) { + allocations_before_failure = before_failure; + fail_enabled = true; + } + AllocationFailure(const AllocationFailure&) = delete; + AllocationFailure& operator=(const AllocationFailure&) = delete; + ~AllocationFailure() { fail_enabled = false; } +}; + +// One-shot, so that cleanup after the failure can allocate. +void maybe_fail() { + if (fail_enabled && allocations_before_failure.fetch_sub(1) == 0) { + fail_enabled = false; + throw std::bad_alloc(); + } +} +} // namespace + +// This executable is separate from the normal suite so fault injection cannot affect +// unrelated tests. +GTEST_NO_INLINE_ void* operator new(size_t size) { + maybe_fail(); + if (void* ptr = std::malloc(size == 0 ? 1 : size)) { + return ptr; + } + throw std::bad_alloc(); +} + +GTEST_NO_INLINE_ void* operator new(size_t size, const std::nothrow_t&) noexcept { + try { + return ::operator new(size); + } catch (...) { return nullptr; } +} + +// The analyzer models delete as freeing before entering these replacements. +GTEST_NO_INLINE_ void operator delete(void* ptr) noexcept { + std::free(ptr); // NOLINT(clang-analyzer-cplusplus.NewDelete) +} +GTEST_NO_INLINE_ void operator delete(void* ptr, size_t) noexcept { + std::free(ptr); // NOLINT(clang-analyzer-cplusplus.NewDelete) +} + +namespace rabitqlib { +namespace { +constexpr size_t kDim = 64; +constexpr size_t kNumPoints = 200; +constexpr size_t kNumClusters = 4; + +IvfIndex new_index() { + IvfOptions options; + options.seed = 11; + IvfIndex index(kDim, kNumClusters, options); + index.cp().niter = 2; + return index; +} + +// The first add trains a staged index and fills it, so a failed operator new anywhere, +// also after training has succeeded, leaves the index untrained and empty, and a retry +// succeeds. Aligned storage and Eigen allocate with malloc-style calls and are not +// injected here. +TEST(IvfIndexFirstAddAllocationTest, EveryOperatorNewFailureLeavesTheIndexUntrained) { + // Runtime startup allocations are not index allocations and must happen before + // the hook starts injecting failures. + (void)omp_get_max_threads(); + std::mt19937 generator(3); + std::normal_distribution normal; + std::vector data(kNumPoints * kDim); + for (auto& value : data) { + value = normal(generator); + } + AddOptions options; + options.num_threads = 1; + + size_t failures = 0; + bool succeeded = false; + for (size_t allocation = 0; allocation < 4096; ++allocation) { + SCOPED_TRACE(allocation); + IvfIndex index = new_index(); + bool failed = false; + { + const AllocationFailure failure(allocation); + try { + index.add(data.data(), kNumPoints, options); + } catch (const std::bad_alloc&) { failed = true; } + } + if (!failed) { + succeeded = true; + break; + } + ++failures; + ASSERT_FALSE(index.is_trained()); + ASSERT_EQ(index.num_stored_points(), 0U); + ASSERT_EQ(index.seed(), std::optional(11)); + ASSERT_EQ(index.add(data.data(), kNumPoints, options), 0); + ASSERT_EQ(index.num_points(), kNumPoints); + } + EXPECT_GT(failures, 0U); + EXPECT_TRUE(succeeded); +} + +} // namespace +} // namespace rabitqlib diff --git a/tests/unit/rabitqlib/index/ivf_index_test.cpp b/tests/unit/rabitqlib/index/ivf_index_test.cpp new file mode 100644 index 00000000..36d2841c --- /dev/null +++ b/tests/unit/rabitqlib/index/ivf_index_test.cpp @@ -0,0 +1,493 @@ +#include "rabitqlib/index/ivf_index.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rabitqlib/clustering/rabitqkmeans.hpp" +#include "rabitqlib/core/metric.hpp" +#include "rabitqlib/index/ivf/types.hpp" +#include "rabitqlib/index/types.hpp" +#include "temp_file.hpp" + +namespace rabitqlib { +namespace { + +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_assignable_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(!std::is_default_constructible_v); + +constexpr size_t kDim = 64; +constexpr size_t kNumPoints = 400; +constexpr size_t kNumClusters = 8; + +std::vector gaussian(size_t num_points, uint32_t seed) { + std::mt19937 rng(seed); + std::normal_distribution normal; + std::vector data(num_points * kDim); + for (auto& value : data) { + value = normal(rng); + } + return data; +} + +IvfOptions seeded(uint32_t seed) { + IvfOptions options; + options.seed = seed; + return options; +} + +AddOptions single_thread() { + AddOptions options; + options.num_threads = 1; + return options; +} + +// Throws exactly Error, not a subclass, with exactly this message. +template +void expect_error(const Call& call, const std::string& message) { + try { + call(); + ADD_FAILURE() << "no exception; expected: " << message; + } catch (const std::exception& error) { + EXPECT_EQ(typeid(error), typeid(Error)) << error.what(); + EXPECT_EQ(error.what(), message); + } +} + +struct Results { + std::vector ids; + std::vector distances; +}; + +Results search( + const IvfIndex& index, + const float* queries, + size_t num_queries, + size_t k, + const IvfSearchOptions& options = {} +) { + Results results{ + std::vector(num_queries * k, 0), std::vector(num_queries * k, 0.0F)}; + index.search( + queries, num_queries, k, results.ids.data(), results.distances.data(), options + ); + return results; +} + +size_t count_found(const Results& results) { + size_t found = 0; + for (size_t i = 0; i < results.ids.size(); ++i) { + if (results.ids[i] != kNoId) { + EXPECT_TRUE(std::isfinite(results.distances[i])); + ++found; + } else { + EXPECT_TRUE(std::isinf(results.distances[i])); + } + } + return found; +} + +std::vector saved_bytes(const IvfIndex& index, const std::string& name) { + const rabitq_test::TempFile file(name); + index.save(file.path().c_str()); + std::ifstream input(file.path(), std::ios::binary); + return {std::istreambuf_iterator(input), std::istreambuf_iterator()}; +} + +TEST(IvfIndexTest, DefaultsFollowThePythonClass) { + const IvfIndex index(kDim, kNumClusters); + EXPECT_EQ(index.dim(), kDim); + EXPECT_EQ(index.num_clusters(), kNumClusters); + EXPECT_EQ(index.nbits(), 7U); + EXPECT_EQ(index.metric(), METRIC_L2); + EXPECT_EQ(index.routing(), ivf::Routing::Flat); // Auto below 5,000 clusters + ASSERT_TRUE(index.seed().has_value()); + EXPECT_FALSE(index.is_trained()); + EXPECT_EQ(index.num_points(), 0U); + EXPECT_EQ(index.num_stored_points(), 0U); + + const auto& cp = index.cp(); + EXPECT_EQ(cp.niter, 10U); + EXPECT_EQ(cp.max_points_per_centroid, 256U); + EXPECT_FALSE(cp.spherical); + EXPECT_EQ(cp.seed, *index.seed()); + + IvfOptions inner_product; + inner_product.metric = METRIC_IP; + const IvfIndex ip(kDim, kNumClusters, inner_product); + EXPECT_EQ(ip.metric(), METRIC_IP); + EXPECT_TRUE(ip.cp().spherical); + + IvfOptions options; + options.metric = METRIC_COSINE; + options.nbits = 32; + options.routing = ivf::Routing::HNSW; + options.seed = 9; + const IvfIndex configured(kDim, kNumClusters, options); + EXPECT_EQ(configured.metric(), METRIC_COSINE); + EXPECT_EQ(configured.nbits(), 32U); + EXPECT_EQ(configured.routing(), ivf::Routing::HNSW); + EXPECT_EQ(configured.seed(), std::optional(9)); + EXPECT_EQ(configured.cp().seed, 9U); + EXPECT_TRUE(configured.cp().spherical); +} + +TEST(IvfIndexTest, UnsetSeedsAreDrawn) { + // Four equal draws of 32 bits would be a coincidence of probability 2^-96. + std::set seeds; + for (int i = 0; i < 4; ++i) { + const IvfIndex index(kDim, kNumClusters); + ASSERT_TRUE(index.seed().has_value()); + EXPECT_EQ(index.cp().seed, *index.seed()); + seeds.insert(*index.seed()); + } + EXPECT_GT(seeds.size(), 1U); +} + +TEST(IvfIndexTest, FirstAddTrainsLikeTrainThenAdd) { + const auto data = gaussian(kNumPoints, 1); + IvfIndex implicit(kDim, kNumClusters, seeded(7)); + IvfIndex explicit_train(kDim, kNumClusters, seeded(7)); + IvfIndex other_cp(kDim, kNumClusters, seeded(7)); + // The first add trains with cp(), like train, and rotates with the index seed. + for (IvfIndex* index : {&implicit, &explicit_train}) { + index->cp().niter = 3; + index->cp().seed = 99; + } + + EXPECT_EQ(implicit.add(data.data(), kNumPoints, single_thread()), 0); + EXPECT_TRUE(implicit.is_trained()); + EXPECT_EQ(implicit.num_points(), kNumPoints); + explicit_train.train(data.data(), kNumPoints, 1); + EXPECT_EQ(explicit_train.add(data.data(), kNumPoints, single_thread()), 0); + other_cp.add(data.data(), kNumPoints, single_thread()); + + const auto bytes = saved_bytes(implicit, "ivf_index_implicit.index"); + EXPECT_EQ(bytes, saved_bytes(explicit_train, "ivf_index_explicit.index")); + EXPECT_NE(bytes, saved_bytes(other_cp, "ivf_index_other_cp.index")); + + // Later batches continue the IDs. + EXPECT_EQ(implicit.add(data.data(), 5, single_thread()), static_cast(kNumPoints)); + EXPECT_EQ(implicit.add(data.data(), 0), static_cast(kNumPoints + 5)); + EXPECT_EQ(implicit.num_stored_points(), kNumPoints + 5); +} + +TEST(IvfIndexTest, FailedFirstAddLeavesTheIndexUntrainedAndEmpty) { + auto data = gaussian(kNumPoints, 2); + IvfIndex index(kDim, kNumClusters, seeded(11)); + expect_error( + [&] { index.add(data.data(), kNumClusters - 1); }, + "the first add trains the index and needs at least num_clusters rows; " + "expected at least 8, got shape (7, 64)" + ); + data[5 * kDim] = std::numeric_limits::quiet_NaN(); + EXPECT_THROW(index.add(data.data(), kNumPoints), std::invalid_argument); + EXPECT_FALSE(index.is_trained()); + EXPECT_EQ(index.num_stored_points(), 0U); + EXPECT_EQ(index.seed(), std::optional(11)); + + data[5 * kDim] = 0.0F; + EXPECT_EQ(index.add(data.data(), kNumPoints, single_thread()), 0); + IvfIndex fresh(kDim, kNumClusters, seeded(11)); + fresh.add(data.data(), kNumPoints, single_thread()); + EXPECT_EQ( + saved_bytes(index, "ivf_index_retried.index"), + saved_bytes(fresh, "ivf_index_fresh.index") + ); +} + +TEST(IvfIndexTest, OperationsBeforeTrainingThrowLogicError) { + const auto data = gaussian(kNumPoints, 3); + IvfIndex index(kDim, kNumClusters, seeded(1)); + const rabitq_test::TempFile file("ivf_index_untrained.index"); + const std::vector cluster_ids(kNumPoints, 0); + AddOptions with_ids; + with_ids.cluster_ids = cluster_ids.data(); + const Id remove_ids[] = {0}; + Id ids[1]; + + const auto message = [](const std::string& operation) { + return "IvfIndex must be trained or loaded before " + operation; + }; + // With cluster IDs, or without points, add needs centroids instead of training. + expect_error( + [&] { index.add(data.data(), kNumPoints, with_ids); }, message("add") + ); + expect_error([&] { index.add(data.data(), 0); }, message("add")); + expect_error( + [&] { index.search(data.data(), 1, 1, ids, nullptr); }, message("search") + ); + expect_error([&] { index.remove(remove_ids, 1); }, message("remove")); + expect_error( + [&] { index.save(file.path().c_str()); }, message("save") + ); + expect_error( + [&] { index.reserve_cluster(0, 10); }, message("reserve_cluster") + ); + EXPECT_FALSE(std::filesystem::exists(file.path())); + EXPECT_FALSE(index.is_trained()); + + index.train(data.data(), kNumPoints); + expect_error( + [&] { index.save(file.path().c_str()); }, + "IvfIndex has no points to save; add points first" + ); + EXPECT_FALSE(std::filesystem::exists(file.path())); +} + +TEST(IvfIndexTest, RetrainingIsAllowedOnlyWhileEmpty) { + const auto data = gaussian(kNumPoints, 4); + IvfIndex index(kDim, kNumClusters, seeded(5)); + index.cp().num_threads = 3; + index.train(data.data(), kNumPoints, 1); + EXPECT_EQ(index.cp().num_threads, 3U); // the override is for the call only + index.set_centroids(data.data(), 1); + index.train(data.data(), kNumPoints); + index.add(data.data(), 50); + + const auto before = search(index, data.data(), 2, 5); + const std::string message = "IvfIndex cannot be trained once it stores points"; + expect_error([&] { index.train(data.data(), kNumPoints); }, message); + expect_error([&] { index.set_centroids(data.data()); }, message); + const auto after = search(index, data.data(), 2, 5); + EXPECT_EQ(before.ids, after.ids); +} + +TEST(IvfIndexTest, DefaultNprobeIsOneSixteenthOfTheClustersRounded) { + constexpr size_t kManyClusters = 24; // 1.5 rounds to 2 + const auto data = gaussian(kNumPoints, 5); + IvfIndex index(kDim, kManyClusters, seeded(3)); + index.add(data.data(), kNumPoints, single_thread()); + const auto probe = [&](std::optional nprobe) { + IvfSearchOptions options; + options.nprobe = nprobe; + return search(index, data.data(), 1, kNumPoints, options); + }; + const auto by_default = probe(std::nullopt); + const auto two = probe(2); + EXPECT_EQ(by_default.ids, two.ids); + EXPECT_EQ(by_default.distances, two.distances); + EXPECT_LT(count_found(probe(1)), count_found(two)); + EXPECT_LT(count_found(two), count_found(probe(3))); + + // At least one cluster. + IvfIndex small(kDim, 4, seeded(3)); + small.add(data.data(), kNumPoints, single_thread()); + IvfSearchOptions one; + one.nprobe = 1; + EXPECT_EQ( + search(small, data.data(), 1, kNumPoints).ids, + search(small, data.data(), 1, kNumPoints, one).ids + ); +} + +TEST(IvfIndexTest, SearchRejectsZeroBreadthAndInvalidK) { + const auto data = gaussian(kNumPoints, 6); + IvfIndex index(kDim, kNumClusters, seeded(1)); + index.add(data.data(), kNumPoints, single_thread()); + std::vector ids(kNumPoints); + IvfSearchOptions zero; + zero.nprobe = 0; + expect_error( + [&] { index.search(data.data(), 1, 1, ids.data(), nullptr, zero); }, + "nprobe must be at least 1; leave it unset for the default" + ); + for (size_t k : {size_t{0}, (size_t{1} << 31) + 1}) { + expect_error( + [&] { index.search(data.data(), 1, k, ids.data(), nullptr); }, + "k must be between 1 and 2^31" + ); + } + expect_error( + [&] { index.search(data.data(), 1, 1, nullptr, nullptr); }, + "IvfIndex search ids must not be null" + ); + index.search(data.data(), 0, 1, nullptr, nullptr); // an empty batch does nothing +} + +TEST(IvfIndexTest, SearchPadsMissingResults) { + const auto data = gaussian(kNumPoints, 7); + IvfIndex index(kDim, kNumClusters, seeded(1)); + index.train(data.data(), kNumPoints, 1); + const auto empty = search(index, data.data(), 2, 3); + EXPECT_EQ(count_found(empty), 0U); + EXPECT_EQ(empty.ids, std::vector(6, kNoId)); + + index.add(data.data(), 5); + IvfSearchOptions every_cluster; + every_cluster.nprobe = kNumClusters; + const auto padded = search(index, data.data(), 1, 8, every_cluster); + EXPECT_EQ(count_found(padded), 5U); + for (size_t i = 5; i < 8; ++i) { + EXPECT_EQ(padded.ids[i], kNoId); + } + std::vector ids_only(8, 0); + index.search(data.data(), 1, 8, ids_only.data(), nullptr, every_cluster); + EXPECT_EQ(ids_only, padded.ids); +} + +TEST(IvfIndexTest, RemoveChecksIdsBeforeNarrowingThem) { + const auto data = gaussian(kNumPoints, 8); + IvfIndex index(kDim, kNumClusters, seeded(1)); + index.add(data.data(), kNumPoints, single_thread()); + const std::string message = "ids must be in [0, num_stored_points)"; + // (2^32 + 1) would remove point 1 if it were narrowed first. + for (Id bad : {kNoId, static_cast(kNumPoints), (Id{1} << 32) + 1}) { + const Id ids[] = {0, bad}; + expect_error([&] { index.remove(ids, 2); }, message); + } + EXPECT_EQ(index.num_points(), kNumPoints); + expect_error( + [&] { index.remove(nullptr, 1); }, "IvfIndex remove ids must not be null" + ); + EXPECT_EQ(index.remove(nullptr, 0), 0U); + + const Id ids[] = {0, 1, 1}; + EXPECT_EQ(index.remove(ids, 3), 2U); + EXPECT_EQ(index.num_points(), kNumPoints - 2); + EXPECT_EQ(index.num_stored_points(), kNumPoints); + IvfSearchOptions every_cluster; + every_cluster.nprobe = kNumClusters; + const auto results = search(index, data.data(), 2, kNumPoints, every_cluster); + EXPECT_EQ(count_found(results), 2 * (kNumPoints - 2)); + for (const Id id : results.ids) { + EXPECT_TRUE(id != 0 && id != 1); + } +} + +TEST(IvfIndexTest, ReserveClusterChecksTheCluster) { + const auto data = gaussian(kNumPoints, 9); + IvfIndex index(kDim, kNumClusters, seeded(1)); + index.add(data.data(), kNumPoints, single_thread()); + expect_error( + [&] { index.reserve_cluster(kNumClusters, 10); }, + "cluster_id must be in [0, num_clusters)" + ); + index.reserve_cluster(0, 1000); + EXPECT_EQ(index.num_stored_points(), kNumPoints); +} + +TEST(IvfIndexTest, SaveAndLoadKeepSettingsSeedAndResults) { + const auto data = gaussian(kNumPoints, 10); + IvfOptions options; + options.metric = METRIC_COSINE; + options.nbits = 4; + options.seed = 21; + IvfIndex index(kDim, kNumClusters, options); + index.add(data.data(), kNumPoints); + const Id removed[] = {3}; + index.remove(removed, 1); + + const rabitq_test::TempFile file("ivf_index_round_trip.index"); + index.save(file.path().c_str()); + const IvfIndex loaded = IvfIndex::load(file.path().c_str()); + EXPECT_TRUE(loaded.is_trained()); + EXPECT_EQ(loaded.dim(), kDim); + EXPECT_EQ(loaded.num_clusters(), kNumClusters); + EXPECT_EQ(loaded.nbits(), 4U); + EXPECT_EQ(loaded.metric(), METRIC_COSINE); + EXPECT_EQ(loaded.routing(), index.routing()); + EXPECT_EQ(loaded.seed(), std::optional(21)); + EXPECT_EQ(loaded.cp().seed, 21U); + EXPECT_TRUE(loaded.cp().spherical); + EXPECT_EQ(loaded.num_points(), kNumPoints - 1); + EXPECT_EQ(loaded.num_stored_points(), kNumPoints); + + const auto expected = search(index, data.data(), 3, 10); + const auto actual = search(loaded, data.data(), 3, 10); + EXPECT_EQ(actual.ids, expected.ids); + EXPECT_EQ(actual.distances, expected.distances); +} + +TEST(IvfIndexTest, AddAndSearchApplyTheirOptions) { + const auto data = gaussian(kNumPoints, 12); + const auto trained = [&] { + IvfIndex index(kDim, kNumClusters, seeded(6)); + index.set_centroids(data.data(), 1); + return index; + }; + IvfIndex routed = trained(); + routed.add(data.data(), kNumPoints, single_thread()); + const auto routed_bytes = saved_bytes(routed, "ivf_index_routed.index"); + + const std::vector first_cluster(kNumPoints, 0); + AddOptions assigned = single_thread(); + assigned.cluster_ids = first_cluster.data(); + IvfIndex one_cluster = trained(); + one_cluster.add(data.data(), kNumPoints, assigned); + EXPECT_NE(saved_bytes(one_cluster, "ivf_index_one_cluster.index"), routed_bytes); + IvfSearchOptions first_probe; + first_probe.nprobe = 1; + // Every point is in cluster 0, so probing the one nearest cluster finds all or none. + const size_t found = + count_found(search(one_cluster, data.data(), 1, kNumPoints, first_probe)); + EXPECT_TRUE(found == 0 || found == kNumPoints) << found; + + AddOptions fast = single_thread(); + fast.fast_quantization = true; + IvfIndex fast_index = trained(); + fast_index.add(data.data(), kNumPoints, fast); + EXPECT_NE(saved_bytes(fast_index, "ivf_index_fast.index"), routed_bytes); + + IvfSearchOptions standard; + standard.high_accuracy = false; + IvfSearchOptions hacc; + hacc.high_accuracy = true; + EXPECT_NE( + search(routed, data.data(), 20, 10, standard).distances, + search(routed, data.data(), 20, 10, hacc).distances + ); + EXPECT_EQ( + search(routed, data.data(), 20, 10).distances, + search(routed, data.data(), 20, 10, hacc).distances + ); // 7 bits select HACC +} + +TEST(IvfIndexTest, LoadsAFileWithoutASeed) { + // Releases up to 0.8 did not record the seed; training defaults to the k-means seed. + const auto path = + std::filesystem::path(RABITQ_TEST_FIXTURE_ROOT) / "v0.8.3" / "ivf4_flat_l2.index"; + IvfIndex index = IvfIndex::load(path.string().c_str()); + EXPECT_TRUE(index.is_trained()); + EXPECT_FALSE(index.seed().has_value()); + EXPECT_EQ(index.cp().seed, rabitqkmeans::RaBitQKMeansParameters{}.seed); + EXPECT_FALSE(index.cp().spherical); + const size_t stored = index.num_stored_points(); + ASSERT_GT(stored, 0U); + const std::vector data(3 * index.dim(), 0.5F); + EXPECT_EQ(index.add(data.data(), 3, single_thread()), static_cast(stored)); +} + +TEST(IvfIndexTest, MovedIndexKeepsItsState) { + const auto data = gaussian(kNumPoints, 11); + IvfIndex index(kDim, kNumClusters, seeded(4)); + index.add(data.data(), kNumPoints); + const auto expected = search(index, data.data(), 2, 5); + IvfIndex moved(std::move(index)); + EXPECT_EQ(search(moved, data.data(), 2, 5).ids, expected.ids); + IvfIndex assigned(kDim, 2); + assigned = std::move(moved); + EXPECT_EQ(assigned.seed(), std::optional(4)); + EXPECT_EQ(search(assigned, data.data(), 2, 5).ids, expected.ids); +} + +} // namespace +} // namespace rabitqlib