diff --git a/.clang-tidy b/.clang-tidy index c9978ef4..63dd90a9 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -54,6 +54,8 @@ CheckOptions: readability-identifier-naming.ProtectedMemberCase: lower_case readability-identifier-naming.ProtectedMemberSuffix: '_' readability-identifier-naming.PublicMemberCase: lower_case + # HnswOptions::M, the same HNSW graph-degree setting. + readability-identifier-naming.PublicMemberIgnoredRegexp: '^M$' # Functions, types, namespaces, constants and macros follow AGENTS.md. The # ignored names are retained public API or names the standard library requires. readability-identifier-naming.FunctionCase: lower_case diff --git a/CMakeLists.txt b/CMakeLists.txt index 2c9988b9..0daccf06 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -250,6 +250,7 @@ if(RABITQ_BUILD_INDEX) add_library(rabitq_index STATIC src/index/format2.cpp src/index/hnsw.cpp + src/index/hnsw_index.cpp src/index/ivf.cpp src/index/ivf_index.cpp src/index/ivf_initializer.cpp diff --git a/docs/development.md b/docs/development.md index 811e7f9d..abda77be 100644 --- a/docs/development.md +++ b/docs/development.md @@ -45,8 +45,9 @@ 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, add options and ANN candidate values; no Eigen dependency | +| `include/rabitqlib/index/types.hpp` | Point IDs, add and graph search 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/index/hnsw_index.hpp` | `HnswIndex`, the supported C++ HNSW API: the Python workflow over `hnsw::HierarchicalNSW` | | `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 | @@ -575,18 +576,18 @@ Shared NumPy and string conversion helpers live in `python_bindings/bindings_com 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. 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`. +`IvfIndex` or `HnswIndex`, leaves the state checks and the removal-ID range to that class, and +for IVF the `reserve_cluster` cluster-ID range. 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, and in `copied_ids` for an aligned `Id` copy -whose range the index checks. Reuse these helpers rather than directly +ID conversion uses packed reads in `checked_cluster_ids`, which validates cluster IDs +before narrowing them to owned PID storage, and in `copied_ids`, which makes 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. diff --git a/docs/docs/releases/unreleased.md b/docs/docs/releases/unreleased.md index 4ffe7c67..09825653 100644 --- a/docs/docs/releases/unreleased.md +++ b/docs/docs/releases/unreleased.md @@ -48,9 +48,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. 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. + - 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` and `HnswIndex` use 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`. +- An `IvfIndex` or `HnswIndex` 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`. `HnswIndex()` with an invalid `metric` or `seed` and an out-of-range `num_clusters` now reports the metric or seed. - 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. @@ -73,7 +73,14 @@ - `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. +- New `rabitqlib::HnswIndex` in `rabitqlib/index/hnsw_index.hpp` (#234), built the same way, which the Python `HnswIndex` now wraps: + - `HnswIndex(dim, options)` takes an `HnswOptions` struct (metric, `nbits`, `num_clusters`, `M`, `ef_construction`, seed). `train`, `set_centroids`, `add`, `remove`, `reserve`, `search`, `save` and the static `load` follow the Python methods. + - The first `add` trains `min(num_clusters, number of points)` centroids and leaves the index untrained, empty and with its capacity if it fails. + - Capacity starts at one point and grows on `add`, at least doubling, after the points and cluster IDs are checked; `reserve` only grows it. + - `add` uses every available CPU unless `num_threads` is set, whereas `hnsw::HierarchicalNSW::add` uses one; pass `num_threads = 1` and a seed for a reproducible graph. + - `search` takes a `GraphSearchOptions` struct. Without an `ef_search` it uses `max(k, 64)`, and an explicit 0 throws. + - `seed()` is a `std::optional`, because a file written by `hnsw::HierarchicalNSW` may record a seed above 32 bits. +- `ivf::IVF` and `hnsw::HierarchicalNSW` are 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`. diff --git a/include/rabitqlib/index/hnsw_index.hpp b/include/rabitqlib/index/hnsw_index.hpp new file mode 100644 index 00000000..25377f54 --- /dev/null +++ b/include/rabitqlib/index/hnsw_index.hpp @@ -0,0 +1,196 @@ +#pragma once + +#include +#include +#include +#include + +#include "rabitqlib/core/metric.hpp" // IWYU pragma: export +#include "rabitqlib/index/types.hpp" // IWYU pragma: export + +namespace rabitqlib { +namespace hnsw { +class HierarchicalNSW; +} +namespace rabitqkmeans { +struct RaBitQKMeansParameters; +} + +// Settings of a new HnswIndex; set the fields by name. The metric comes first, so a lone +// positional value must be a metric: {4} does not compile. +struct HnswOptions { + MetricType metric = METRIC_L2; // METRIC_L2, METRIC_IP or METRIC_COSINE + size_t nbits = 7; // 1-9 quantization bits + // Centroids from train, set_centroids or the first add, which caps the count at its + // number of points. From 1 to 2^31. + size_t num_clusters = 16; + size_t M = + 16; // graph connectivity, at least 2; the base layer keeps up to 2 * M edges + size_t ef_construction = 200; // construction search breadth + std::optional seed; // graph and rotation seed; no value draws one +}; + +/** + * @brief An HNSW-RaBitQ index with the workflow of the Python HnswIndex. + * + * 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 and save need a trained index. Capacity grows on add, at + * least doubling; reserve preallocates it. + * + * 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 HnswIndex { + public: + /** + * @param dim Vector dimension + * @param options Metric, bits, cluster count, graph settings and seed + */ + explicit HnswIndex(size_t dim, const HnswOptions& options = {}); + + HnswIndex(HnswIndex&& other) noexcept; + HnswIndex& operator=(HnswIndex&& other) noexcept; + HnswIndex(const HnswIndex&) = delete; + HnswIndex& operator=(const HnswIndex&) = delete; + ~HnswIndex(); + + // Load an index saved by any release. An empty, untrained file saved by 0.7 loads + // untrained, with 16 clusters to train; without a recorded seed, it needs train or + // set_centroids before add. + static HnswIndex 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 low 32 bits of 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 + */ + void set_centroids(const float* centroids); + + /** + * @brief Add points, training an untrained index on them first. + * + * The first add trains min(num_clusters(), num_points) centroids on `data` as train + * does, so it needs no cluster_ids; if it throws, the index stays untrained and + * empty, with its capacity. On a trained index the points are quantized against the + * existing centroids, which do not move. Capacity grows to fit the points, at least + * doubling, after the points and cluster IDs are checked. A failure while linking may + * leave part of the batch in the index, which stays safe to search, save and destroy. + * + * @param data New points (num_points * dim) + * @param num_points Number of new points + * @param options Cluster IDs, worker count and quantization speed. With more than one + * worker the graph links vary between runs; use one, and a seed, for a reproducible + * graph. + * @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, storage and place in the graph, 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); + + // Grow the capacity to num_points; a smaller value changes nothing. + void reserve(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 GraphSearchOptions& options = {} + ) const; + + [[nodiscard]] size_t dim() const; + // The configured count until centroids are set, then the trained count. + [[nodiscard]] size_t num_clusters() const; + [[nodiscard]] size_t nbits() const; + [[nodiscard]] MetricType metric() const; + [[nodiscard]] size_t M() const; + [[nodiscard]] size_t ef_construction() const; + // No value for an index loaded from a file of a release up to 0.8. A file written by + // the C++ HierarchicalNSW class may hold a seed above 32 bits. + [[nodiscard]] std::optional seed() const; + // Points the index can hold before it grows, including removed ones. + [[nodiscard]] size_t capacity() 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: + HnswIndex( + std::unique_ptr index, + std::unique_ptr cp, + size_t num_clusters + ); + + void check_trained(const char* operation) const; + void check_trainable() const; + + std::unique_ptr index_; + std::unique_ptr cp_; + size_t num_clusters_; // centroid count train and set_centroids expect when untrained +}; + +} // namespace rabitqlib diff --git a/include/rabitqlib/index/types.hpp b/include/rabitqlib/index/types.hpp index 07aa3ea7..65001d7a 100644 --- a/include/rabitqlib/index/types.hpp +++ b/include/rabitqlib/index/types.hpp @@ -9,12 +9,13 @@ 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. +// A point ID at the IvfIndex and HnswIndex 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. +// Settings of IvfIndex::add and HnswIndex::add. struct AddOptions { // Cluster of each point, or nullptr to route each point with the index's routing, // which may be approximate. @@ -27,6 +28,14 @@ struct AddOptions { bool fast_quantization = false; }; +// Settings of a graph index search (HnswIndex). +struct GraphSearchOptions { + // Search breadth, raised to k. No value selects max(k, 64); 0 throws. + std::optional ef_search; + // Worker count; 0 selects every available CPU, capped by OMP_NUM_THREADS. + size_t num_threads = 1; +}; + template struct AnnCandidate { TP id = 0; diff --git a/python_bindings/bindings_common.hpp b/python_bindings/bindings_common.hpp index 1ffbcaf5..8ea561c8 100644 --- a/python_bindings/bindings_common.hpp +++ b/python_bindings/bindings_common.hpp @@ -460,26 +460,6 @@ ensure_1d_integer_array(py::handle value, const char* name) { return ensure_1d_array(value, name); } -// The caller has already validated rank/dtype. Removed points still occupy IDs. -inline std::vector checked_removal_ids( - const py::array_t& ids, - size_t num_stored_points -) { - std::vector result; - result.reserve(static_cast(ids.shape(0))); - const detail::ConstPackedArrayView values( - reinterpret_cast(ids.data()) - ); - for (py::ssize_t i = 0; i < ids.shape(0); ++i) { - const int64_t id = values[static_cast(i)]; - if (id < 0 || static_cast(id) >= num_stored_points) { - throw std::invalid_argument("ids must be in [0, num_stored_points)"); - } - result.push_back(static_cast(id)); - } - 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( diff --git a/python_bindings/hnsw_bindings.cpp b/python_bindings/hnsw_bindings.cpp index 17b8ad3c..62701cf6 100644 --- a/python_bindings/hnsw_bindings.cpp +++ b/python_bindings/hnsw_bindings.cpp @@ -6,13 +6,11 @@ #include #include // IWYU pragma: keep; registers std::optional casters -#include #include #include #include -#include +#include #include -#include #include #include #include @@ -20,11 +18,8 @@ #include "bindings_common.hpp" #include "rabitqlib/clustering/rabitqkmeans.hpp" -#include "rabitqlib/index/detail/buffer.hpp" -#include "rabitqlib/index/hnsw/hnsw.hpp" -#include "rabitqlib/index/training.hpp" +#include "rabitqlib/index/hnsw_index.hpp" #include "rabitqlib/index/types.hpp" -#include "rabitqlib/utils/input_checks.hpp" namespace py = pybind11; @@ -40,52 +35,28 @@ class HnswIndex { size_t ef_construction, const std::string& metric, const py::object& seed - ) { - if (num_clusters == 0 || num_clusters > buffer::kSearchBufferMaxPointCount) { - throw std::invalid_argument( - "num_clusters must be in [1, " + - std::to_string(buffer::kSearchBufferMaxPointCount) + "]" - ); - } - const auto metric_type = index_metric_from_string(metric); - const auto graph_seed = - seed.is_none() ? std::random_device{}() - : static_cast( - checked_seed(seed, std::numeric_limits::max()) - ); - // Capacity grows on add; reserve preallocates. - index_ = std::make_unique( - 1, dim, nbits, M, ef_construction, graph_seed, metric_type - ); - num_clusters_ = num_clusters; - seed_ = graph_seed; - cp_ = default_training_parameters(metric_type, graph_seed); - } + ) + : index_(dim, index_options(nbits, num_clusters, M, ef_construction, metric, 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, 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(); - const size_t num_clusters = num_clusters_; + index_.cp() = cp_; py::gil_scoped_release release; - index_->train(num_clusters, rows, x_ptr, cp); + index_.train(x_ptr, rows, num_threads); } void set_centroids(py::handle centroids) { const auto operation = access_.write(); auto centroids_array = ensure_2d_array(centroids, "centroids"); - check_trainable(); - check_centroid_shape(centroids_array, num_clusters_, index_->dimension()); + check_centroid_shape(centroids_array, index_.num_clusters(), index_.dim()); const auto* centroids_ptr = centroids_array.data(); - const size_t num_clusters = num_clusters_; py::gil_scoped_release release; - index_->set_centroids(num_clusters, centroids_ptr); + index_.set_centroids(centroids_ptr); } py::array_t add( @@ -96,64 +67,28 @@ class HnswIndex { ) { 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. Only a - // loaded file lacks the seed that recreates the rotation and graph levels. - const bool trains = !index_->is_trained() && cluster_ids.is_none() && - seed_.has_value() && 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)); - 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(); } - - // Allocated before the index is touched. + 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)); 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 seed, then swap it in, so - // that a failure leaves this index untrained and empty. Fewer rows than - // num_clusters train one centroid per row. - const size_t num_clusters = std::min(num_clusters_, rows); - const auto cp = training_parameters(cp_, num_threads); - auto staged = std::make_unique( - index_->max_elements(), - index_->dimension(), - index_->nbits(), - index_->M(), - index_->ef_construction(), - *seed_, - index_->metric_type() - ); - const auto labels = [&] { - py::gil_scoped_release release; - staged->train(num_clusters, rows, data_ptr, cp); - grow_capacity(*staged, rows, data_ptr, "HNSW add data"); - return staged->add(data_ptr, rows, nullptr, fast_quantization, threads); - }(); - index_.swap(staged); - std::copy(labels.begin(), labels.end(), ids.mutable_data()); - return ids; - } - const auto labels = [&] { + index_.cp() = cp_; // the first add trains with it + Id first = 0; + { py::gil_scoped_release release; - grow_capacity(*index_, rows, data_ptr, "HNSW add data"); - return index_->add( - data_ptr, - rows, - assigned.empty() ? nullptr : assigned.data(), - fast_quantization, - threads - ); - }(); - std::copy(labels.begin(), labels.end(), ids.mutable_data()); + first = index_.add(data_ptr, rows, options); + } + std::iota(ids.mutable_data(), ids.mutable_data() + rows, first); return ids; } @@ -165,7 +100,7 @@ class HnswIndex { // Capacity only grows, and a request within it changes nothing, so it // may run alongside searches. const auto reading = access_.read(); - if (static_cast(num_points) <= index_->max_elements()) { + if (static_cast(num_points) <= index_.capacity()) { return; } } @@ -173,25 +108,23 @@ class HnswIndex { // can change the capacity in between. const auto operation = access_.write(); py::gil_scoped_release release; - index_->resize(static_cast(num_points)); + index_.reserve(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()); } [[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(); } py::tuple search( @@ -202,128 +135,97 @@ class HnswIndex { ) { 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 check_ef_search(ef_search); - // None selects max(k, 64), as in SymqgIndex. - const size_t search_breadth = ef_search.value_or(std::max(k, 64)); - - auto output = unfilled_search_results(static_cast(query_array.shape(0)), k); - auto distances_view = output.distances.mutable_unchecked<2>(); + GraphSearchOptions options; + options.ef_search = ef_search; + options.num_threads = num_threads.value_or(1); - const auto* queries_data = query_array.data(); const auto num_queries = static_cast(query_array.shape(0)); - std::vector>> results; + 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; - results = index_->search( - queries_data, num_queries, k, search_breadth, num_threads.value_or(1) - ); - } - - for (py::ssize_t i = 0; i < static_cast(results.size()); ++i) { - for (py::ssize_t j = 0; j < static_cast(std::min( - k, results[static_cast(i)].size() - )); - ++j) { - output.ids[(static_cast(i) * k) + static_cast(j)] = - results[static_cast(i)][static_cast(j)].second; - distances_view(i, j) = - results[static_cast(i)][static_cast(j)].first; - } + 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("HnswIndex has no points to save; add points first"); - } py::gil_scoped_release release; - index_->save(filename.c_str()); + index_.save(filename.c_str()); } static HnswIndex load(py::handle path) { const auto filename = path_string(path); - HnswIndex wrapper; - wrapper.index_ = std::make_unique(); - { + auto index = [&filename] { py::gil_scoped_release release; - wrapper.index_->load(filename.c_str()); - } - // Untrained, empty files from 0.7 have no clusters; train them with the default. - wrapper.num_clusters_ = wrapper.index_->is_trained() - ? wrapper.index_->num_clusters() - : kDefaultNumClusters; - // Format-2 files record the seed; files from releases up to 0.8 do not. - const std::optional seed = wrapper.index_->seed(); - if (seed.has_value()) { - wrapper.seed_ = static_cast(*seed); - } - wrapper.cp_ = default_training_parameters( - wrapper.index_->metric_type(), - seed.has_value() ? static_cast(*seed) - : rabitqkmeans::RaBitQKMeansParameters{}.seed - ); - return wrapper; + return rabitqlib::HnswIndex::load(filename.c_str()); + }(); + return HnswIndex(std::move(index)); } [[nodiscard]] std::string repr() const { const auto operation = access_.read(); - return "HnswIndex(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()) + - ", capacity=" + std::to_string(index_->max_elements()) + - ", num_clusters=" + std::to_string(current_num_clusters()) + - ", is_trained=" + (index_->is_trained() ? "True" : "False") + ")"; + return "HnswIndex(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()) + + ", capacity=" + std::to_string(index_.capacity()) + + ", num_clusters=" + std::to_string(index_.num_clusters()) + + ", 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 capacity() const { const auto operation = access_.read(); - return index_->max_elements(); + return index_.capacity(); } [[nodiscard]] size_t nbits() const { const auto operation = access_.read(); - return index_->nbits(); + return index_.nbits(); } [[nodiscard]] size_t M() const { const auto operation = access_.read(); - return index_->M(); + return index_.M(); } [[nodiscard]] size_t ef_construction() const { const auto operation = access_.read(); - return index_->ef_construction(); + return index_.ef_construction(); } [[nodiscard]] bool is_trained() const { const auto operation = access_.read(); - return index_->is_trained(); + return index_.is_trained(); } [[nodiscard]] size_t num_clusters() const { const auto operation = access_.read(); - return current_num_clusters(); + return index_.num_clusters(); } - [[nodiscard]] std::optional seed() const { + [[nodiscard]] std::optional seed() const { const auto operation = access_.read(); - return seed_; + return index_.seed(); } [[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(); @@ -331,54 +233,34 @@ class HnswIndex { } private: - static constexpr size_t kDefaultNumClusters = 16; + explicit HnswIndex(rabitqlib::HnswIndex index) + : index_(std::move(index)), cp_(index_.cp()) {} - HnswIndex() = default; - - // The configured count until centroids are set, then the trained count. - [[nodiscard]] size_t current_num_clusters() const { - return index_->is_trained() ? index_->num_clusters() : num_clusters_; - } - - void check_trained(const char* operation) const { - if (!index_->is_trained()) { - throw std::runtime_error( - std::string("HnswIndex must be trained or loaded before ") + operation - ); - } - } - - void check_trainable() const { - if (index_->num_stored_points() != 0) { - throw std::runtime_error("HnswIndex cannot be trained once it stores points"); - } - } - - // Grow capacity geometrically to fit `rows` more points from `data`, checked - // first so that invalid input leaves the capacity unchanged. Leaves IDs beyond - // the supported range for add to reject. Called without the GIL. - static void grow_capacity( - hnsw::HierarchicalNSW& index, size_t rows, const float* data, const char* what + static HnswOptions index_options( + size_t nbits, + size_t num_clusters, + size_t M, + size_t ef_construction, + const std::string& metric, + const py::object& seed ) { - const size_t capacity = index.max_elements(); - const size_t stored = index.num_stored_points(); - if (rows <= capacity - stored || - rows > buffer::kSearchBufferMaxPointCount - stored) { - return; + HnswOptions options; + options.metric = index_metric_from_string(metric); + if (!seed.is_none()) { + options.seed = static_cast( + checked_seed(seed, std::numeric_limits::max()) + ); } - const size_t dim = index.dimension(); - check_coordinates(data, rows * dim, dim, what); - const size_t needed = stored + rows; - const size_t doubled = - std::min(capacity * 2, static_cast(buffer::kSearchBufferMaxPointCount)); - index.resize(std::max(needed, doubled)); + options.nbits = nbits; + options.num_clusters = num_clusters; + options.M = M; + options.ef_construction = ef_construction; + return options; } mutable IndexAccess access_; - std::unique_ptr index_; + rabitqlib::HnswIndex index_; rabitqkmeans::RaBitQKMeansParameters cp_; - size_t num_clusters_ = 0; // Centroid count train and set_centroids expect. - std::optional seed_; // Unknown for files from releases up to 0.8. }; } // namespace rabitqlib::python_bindings diff --git a/src/index/hnsw_index.cpp b/src/index/hnsw_index.cpp new file mode 100644 index 00000000..14104af9 --- /dev/null +++ b/src/index/hnsw_index.cpp @@ -0,0 +1,265 @@ +#include "rabitqlib/index/hnsw_index.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "index_facade.hpp" +#include "rabitqlib/clustering/rabitqkmeans.hpp" +#include "rabitqlib/index/detail/buffer.hpp" +#include "rabitqlib/index/hnsw/hnsw.hpp" +#include "rabitqlib/index/training.hpp" +#include "rabitqlib/utils/input_checks.hpp" + +namespace rabitqlib { + +namespace { +using rabitqkmeans::RaBitQKMeansParameters; + +// What an empty, untrained file saved by 0.7 trains, as a new index does by default. +constexpr size_t kDefaultNumClusters = 16; + +// Grow the capacity to fit num_points more points, at least doubling it. The points are +// checked first, so that invalid input leaves the capacity unchanged. A count beyond the +// supported ID range is left for add to reject. +void grow_capacity(hnsw::HierarchicalNSW& index, const float* data, size_t num_points) { + const size_t capacity = index.max_elements(); + const size_t stored = index.num_stored_points(); + if (num_points <= capacity - stored || + num_points > buffer::kSearchBufferMaxPointCount - stored) { + return; + } + const size_t dim = index.dimension(); + check_coordinates(data, num_points * dim, dim, "HNSW add data"); + const size_t doubled = + std::min(capacity * 2, static_cast(buffer::kSearchBufferMaxPointCount)); + index.resize(std::max(stored + num_points, doubled)); +} +} // namespace + +HnswIndex::HnswIndex(size_t dim, const HnswOptions& options) + : num_clusters_(options.num_clusters) { + if (options.num_clusters == 0 || + options.num_clusters > buffer::kSearchBufferMaxPointCount) { + throw std::invalid_argument( + "num_clusters must be in [1, " + + std::to_string(buffer::kSearchBufferMaxPointCount) + "]" + ); + } + const uint32_t seed = options.seed.has_value() ? *options.seed : std::random_device{}(); + // A capacity of one point; add grows it and reserve preallocates. + index_ = std::make_unique( + 1, dim, options.nbits, options.M, options.ef_construction, seed, options.metric + ); + cp_ = std::make_unique( + default_training_parameters(options.metric, seed) + ); +} + +HnswIndex::HnswIndex( + std::unique_ptr index, + std::unique_ptr cp, + size_t num_clusters +) + : index_(std::move(index)), cp_(std::move(cp)), num_clusters_(num_clusters) {} + +HnswIndex::HnswIndex(HnswIndex&& other) noexcept = default; +HnswIndex& HnswIndex::operator=(HnswIndex&& other) noexcept = default; +HnswIndex::~HnswIndex() = default; + +HnswIndex HnswIndex::load(const char* filename) { + auto index = std::make_unique(); + index->load(filename); + const size_t num_clusters = + index->is_trained() ? index->num_clusters() : kDefaultNumClusters; + // Files from releases up to 0.8 do not record the seed. + const std::optional seed = index->seed(); + auto cp = std::make_unique(default_training_parameters( + index->metric_type(), + seed.has_value() ? static_cast(*seed) : RaBitQKMeansParameters{}.seed + )); + return HnswIndex(std::move(index), std::move(cp), num_clusters); +} + +void HnswIndex::save(const char* filename) const { + check_trained("save"); + if (index_->num_stored_points() == 0) { + throw std::logic_error("HnswIndex has no points to save; add points first"); + } + index_->save(filename); +} + +RaBitQKMeansParameters& HnswIndex::cp() { return *cp_; } + +const RaBitQKMeansParameters& HnswIndex::cp() const { return *cp_; } + +void HnswIndex::train( + const float* data, size_t num_points, std::optional num_threads +) { + check_trainable(); + index_->train( + num_clusters(), num_points, data, index_facade::with_num_threads(*cp_, num_threads) + ); +} + +void HnswIndex::set_centroids(const float* centroids) { + check_trainable(); + index_->set_centroids(num_clusters(), centroids); +} + +Id HnswIndex::add(const float* data, size_t num_points, const AddOptions& options) { + // Only a loaded file lacks the seed that recreates the rotation and graph levels. + const bool trains = !index_->is_trained() && options.cluster_ids == nullptr && + index_->seed().has_value() && num_points > 0; + if (!trains) { + check_trained("add"); + } + if (num_points != 0 && data == nullptr) { + throw std::invalid_argument("HnswIndex add data must not be null"); + } + const auto first = static_cast(index_->num_stored_points()); + const size_t num_threads = options.num_threads.value_or(0); + if (!trains) { + // Checked before the capacity grows, as the points are. + if (options.cluster_ids != nullptr) { + for (size_t i = 0; i < num_points; ++i) { + if (options.cluster_ids[i] >= index_->num_clusters()) { + throw std::invalid_argument("HNSW cluster ID is out of range"); + } + } + } + grow_capacity(*index_, data, num_points); + index_->add( + data, num_points, options.cluster_ids, options.fast_quantization, num_threads + ); + return first; + } + // Train and fill a new index with the same settings, seed and capacity, then move it + // in, so that a failure leaves this index untrained and empty. Fewer points than + // num_clusters() train one centroid per point. + auto staged = std::make_unique( + index_->max_elements(), + index_->dimension(), + index_->nbits(), + index_->M(), + index_->ef_construction(), + index_->seed().value(), + index_->metric_type() + ); + staged->train( + std::min(num_clusters_, num_points), + num_points, + data, + index_facade::with_num_threads(*cp_, options.num_threads) + ); + grow_capacity(*staged, data, num_points); + staged->add(data, num_points, nullptr, options.fast_quantization, num_threads); + index_ = std::move(staged); + return first; +} + +size_t HnswIndex::remove(const Id* ids, size_t num_ids) { + check_trained("remove"); + if (num_ids != 0 && ids == nullptr) { + throw std::invalid_argument("HnswIndex remove ids must not be null"); + } + const size_t num_stored = index_->num_stored_points(); + std::vector labels(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)"); + } + labels[i] = static_cast(ids[i]); + } + return index_->remove(labels.data(), labels.size()); +} + +void HnswIndex::reserve(size_t num_points) { + if (num_points > index_->max_elements()) { + index_->resize(num_points); + } +} + +void HnswIndex::search( + const float* queries, + size_t num_queries, + size_t k, + Id* ids, + float* distances, + const GraphSearchOptions& options +) const { + check_trained("search"); + index_facade::check_k(k); + index_facade::check_breadth(options.ef_search, "ef_search"); + if (num_queries == 0) { + return; + } + index_facade::check_outputs("HnswIndex", num_queries, k, ids); + // Concurrent searches are safe; the graph search only reads the index. + const auto results = index_->search( + queries, + num_queries, + k, + options.ef_search.value_or(std::max(k, 64)), + options.num_threads + ); + for (size_t i = 0; i < num_queries; ++i) { + const auto& found = results[i]; + for (size_t j = 0; j < k; ++j) { + const bool filled = j < found.size(); + ids[(i * k) + j] = filled ? static_cast(found[j].second) : kNoId; + if (distances != nullptr) { + distances[(i * k) + j] = + filled ? found[j].first : std::numeric_limits::infinity(); + } + } + } +} + +size_t HnswIndex::dim() const { return index_->dimension(); } + +size_t HnswIndex::num_clusters() const { + return index_->is_trained() ? index_->num_clusters() : num_clusters_; +} + +size_t HnswIndex::nbits() const { return index_->nbits(); } + +MetricType HnswIndex::metric() const { return index_->metric_type(); } + +size_t HnswIndex::M() const { return index_->M(); } + +size_t HnswIndex::ef_construction() const { return index_->ef_construction(); } + +std::optional HnswIndex::seed() const { return index_->seed(); } + +size_t HnswIndex::capacity() const { return index_->max_elements(); } + +size_t HnswIndex::num_points() const { return index_->num_points(); } + +size_t HnswIndex::num_stored_points() const { return index_->num_stored_points(); } + +bool HnswIndex::is_trained() const { return index_->is_trained(); } + +void HnswIndex::check_trained(const char* operation) const { + if (!index_->is_trained()) { + throw std::logic_error( + std::string("HnswIndex must be trained or loaded before ") + operation + ); + } +} + +void HnswIndex::check_trainable() const { + if (index_->num_stored_points() != 0) { + throw std::logic_error("HnswIndex cannot be trained once it stores points"); + } +} + +} // namespace rabitqlib diff --git a/src/index/index_facade.hpp b/src/index/index_facade.hpp new file mode 100644 index 00000000..fcefcfdc --- /dev/null +++ b/src/index/index_facade.hpp @@ -0,0 +1,60 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "rabitqlib/clustering/rabitqkmeans.hpp" +#include "rabitqlib/index/detail/buffer.hpp" +#include "rabitqlib/index/types.hpp" + +// Checks and settings that the IvfIndex and HnswIndex classes share. Their +// messages are the ones the Python classes raise. +namespace rabitqlib::index_facade { + +// The parameters of one training call: an explicit num_threads overrides cp's. +inline rabitqkmeans::RaBitQKMeansParameters with_num_threads( + rabitqkmeans::RaBitQKMeansParameters cp, std::optional num_threads +) { + if (num_threads.has_value()) { + cp.num_threads = static_cast( + std::min(*num_threads, std::numeric_limits::max()) + ); + } + return cp; +} + +inline void check_k(size_t k) { + if (k == 0 || k > buffer::kSearchBufferMaxPointCount) { + throw std::invalid_argument("k must be between 1 and 2^31"); + } +} + +// A search breadth (nprobe or ef_search) is either unset, for the default, or at least 1. +inline void check_breadth(std::optional breadth, const char* name) { + if (breadth == size_t{0}) { + throw std::invalid_argument( + std::string(name) + " must be at least 1; leave it unset for the default" + ); + } +} + +// The output of a nonempty batch: ids is required and num_queries * k results fit. +inline void check_outputs( + const char* class_name, size_t num_queries, size_t k, const Id* ids +) { + if (ids == nullptr) { + throw std::invalid_argument( + std::string(class_name) + " search ids must not be null" + ); + } + if (num_queries > std::numeric_limits::max() / sizeof(Id) / k) { + throw std::length_error(std::string(class_name) + " query batch is too large"); + } +} + +} // namespace rabitqlib::index_facade diff --git a/src/index/ivf_index.cpp b/src/index/ivf_index.cpp index 103624c7..d6431c56 100644 --- a/src/index/ivf_index.cpp +++ b/src/index/ivf_index.cpp @@ -3,7 +3,6 @@ #include #include #include -#include #include #include #include @@ -12,9 +11,9 @@ #include #include +#include "index_facade.hpp" #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" @@ -162,23 +161,12 @@ void IvfIndex::search( 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" - ); - } + index_facade::check_k(k); + index_facade::check_breadth(options.nprobe, "nprobe"); 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"); - } + index_facade::check_outputs("IvfIndex", num_queries, k, ids); // The index writes 32-bit row numbers, which are widened afterwards. std::vector row_ids(num_queries * k); index_->search_batch( @@ -231,13 +219,7 @@ void IvfIndex::check_trainable() const { 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; + return index_facade::with_num_threads(*cp_, num_threads); } } // namespace rabitqlib diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index b05e0f61..5c633161 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -52,6 +52,7 @@ set_source_files_properties(unit/rabitqlib/utils/blob_test.cpp "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 + unit/rabitqlib/index/hnsw_index_test.cpp PROPERTIES COMPILE_DEFINITIONS "RABITQ_TEST_FIXTURE_ROOT=\"${CMAKE_CURRENT_SOURCE_DIR}/fixtures/persistence\"") rabitq_configure_target(rabitq_tests) diff --git a/tests/consumer/CMakeLists.txt b/tests/consumer/CMakeLists.txt index 629b70ba..362775c6 100644 --- a/tests/consumer/CMakeLists.txt +++ b/tests/consumer/CMakeLists.txt @@ -52,17 +52,19 @@ 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) +# The supported index classes also hide the existing index classes and k-means. +add_executable(index_api_header_boundary + index_api_headers_main.cpp hnsw_index_headers.cpp ivf_index_headers.cpp) +target_link_libraries(index_api_header_boundary PRIVATE rabitqlib::index) +foreach(header IN ITEMS index/ivf/ivf.hpp index/ivf/cluster.hpp index/hnsw/hnsw.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") + file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/index-api-forbidden/rabitqlib/${directory}") + file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/index-api-forbidden/rabitqlib/${header}" + "#error Index API 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") +target_include_directories(index_api_header_boundary BEFORE PRIVATE + "${CMAKE_CURRENT_BINARY_DIR}/forbidden" "${CMAKE_CURRENT_BINARY_DIR}/index-api-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) @@ -79,7 +81,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) +add_test(NAME index_api_header_boundary COMMAND index_api_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/hnsw_index_headers.cpp b/tests/consumer/hnsw_index_headers.cpp new file mode 100644 index 00000000..8a68c55b --- /dev/null +++ b/tests/consumer/hnsw_index_headers.cpp @@ -0,0 +1,28 @@ +#include +#include +#include + +#include "rabitqlib/index/hnsw_index.hpp" + +// The supported HNSW API compiles and works without the existing HNSW class, k-means or +// any implementation header. +int hnsw_index_header_smoke() { + 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::HnswOptions options; + options.num_clusters = 2; + options.seed = 3; + rabitqlib::HnswIndex index(kDim, 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/consumer/index_api_headers_main.cpp b/tests/consumer/index_api_headers_main.cpp new file mode 100644 index 00000000..1bfd25a7 --- /dev/null +++ b/tests/consumer/index_api_headers_main.cpp @@ -0,0 +1,4 @@ +int hnsw_index_header_smoke(); +int ivf_index_header_smoke(); + +int main() { return hnsw_index_header_smoke() + ivf_index_header_smoke(); } diff --git a/tests/consumer/ivf_index_headers.cpp b/tests/consumer/ivf_index_headers.cpp index 6bbf81f4..fe5f0c3d 100644 --- a/tests/consumer/ivf_index_headers.cpp +++ b/tests/consumer/ivf_index_headers.cpp @@ -6,7 +6,7 @@ // The supported IVF API compiles and works without the existing IVF class, k-means or // any implementation header. -int main() { +int ivf_index_header_smoke() { constexpr size_t kDim = 64; constexpr size_t kNumPoints = 40; std::mt19937 rng(1); diff --git a/tests/failures/hnsw_add_allocation_test.cpp b/tests/failures/hnsw_add_allocation_test.cpp index 6f28f99e..1acc9509 100644 --- a/tests/failures/hnsw_add_allocation_test.cpp +++ b/tests/failures/hnsw_add_allocation_test.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -9,11 +10,14 @@ #include #include #include +#include #include #include #include +#include "rabitqlib/clustering/rabitqkmeans.hpp" #include "rabitqlib/index/hnsw/hnsw.hpp" +#include "rabitqlib/index/hnsw_index.hpp" #include "rabitqlib/index/types.hpp" namespace { @@ -397,5 +401,66 @@ TEST(HnswRemoveAllocationTest, FailureRemovesNothing) { ); EXPECT_EQ(index.remove(labels.data(), labels.size()), labels.size()); } + +// HnswIndex trains a staged index and fills it on the first add, so a failed operator new +// anywhere, also after training has succeeded, leaves the index untrained, empty and with +// its capacity, and a retry succeeds. Aligned storage and Eigen allocate with +// malloc-style calls and are not injected here. +TEST(HnswIndexFirstAddAllocationTest, EveryOperatorNewFailureLeavesTheIndexUntrained) { + (void)omp_get_max_threads(); + constexpr size_t kPoints = 40; + std::mt19937 generator(3); + std::normal_distribution normal; + std::vector data(kPoints * kDim); + for (auto& value : data) { + value = normal(generator); + } + AddOptions options; + options.num_threads = 1; + // With a reserved capacity, and with the initial capacity of one point that the + // first add must grow. + for (const size_t reserved : {size_t{64}, size_t{0}}) { + SCOPED_TRACE(reserved); + const size_t capacity = std::max(reserved, 1); + const auto new_index = [reserved] { + HnswOptions settings; + settings.num_clusters = 2; + settings.M = 4; + settings.ef_construction = 10; + settings.seed = 11; + HnswIndex index(kDim, settings); + index.cp().niter = 2; + index.reserve(reserved); + return index; + }; + + size_t failures = 0; + bool succeeded = false; + for (size_t allocation = 0; allocation < 8192; ++allocation) { + SCOPED_TRACE(allocation); + HnswIndex index = new_index(); + bool failed = false; + { + AllocationFailure failure(allocation); + try { + index.add(data.data(), kPoints, 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.capacity(), capacity); + ASSERT_EQ(index.seed(), std::optional(11)); + ASSERT_EQ(index.add(data.data(), kPoints, options), 0); + ASSERT_EQ(index.num_points(), kPoints); + } + EXPECT_GT(failures, 0U); + EXPECT_TRUE(succeeded); + } +} } // namespace } // namespace rabitqlib::hnsw diff --git a/tests/unit/rabitqlib/index/hnsw_index_test.cpp b/tests/unit/rabitqlib/index/hnsw_index_test.cpp new file mode 100644 index 00000000..3ea2f19e --- /dev/null +++ b/tests/unit/rabitqlib/index/hnsw_index_test.cpp @@ -0,0 +1,551 @@ +#include "rabitqlib/index/hnsw_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/hnsw/hnsw.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; +} + +HnswOptions options(uint32_t seed, size_t num_clusters = kNumClusters) { + HnswOptions result; + result.num_clusters = num_clusters; + result.seed = seed; + return result; +} + +AddOptions single_thread() { + AddOptions result; + result.num_threads = 1; + return result; +} + +// 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 HnswIndex& index, + const float* queries, + size_t num_queries, + size_t k, + const GraphSearchOptions& search_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(), + search_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 HnswIndex& 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(HnswIndexTest, DefaultsFollowThePythonClass) { + const HnswIndex index(kDim); + EXPECT_EQ(index.dim(), kDim); + EXPECT_EQ(index.num_clusters(), 16U); + EXPECT_EQ(index.nbits(), 7U); + EXPECT_EQ(index.M(), 16U); + EXPECT_EQ(index.ef_construction(), 200U); + EXPECT_EQ(index.metric(), METRIC_L2); + EXPECT_EQ(index.capacity(), 1U); + 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()); + + HnswOptions configured; + configured.metric = METRIC_COSINE; + configured.nbits = 4; + configured.num_clusters = 5; + configured.M = 8; + configured.ef_construction = 50; + configured.seed = 9; + const HnswIndex cosine(kDim, configured); + EXPECT_EQ(cosine.metric(), METRIC_COSINE); + EXPECT_EQ(cosine.nbits(), 4U); + EXPECT_EQ(cosine.num_clusters(), 5U); + EXPECT_EQ(cosine.M(), 8U); + EXPECT_EQ(cosine.ef_construction(), 50U); + EXPECT_EQ(cosine.seed(), std::optional(9)); + EXPECT_EQ(cosine.cp().seed, 9U); + EXPECT_TRUE(cosine.cp().spherical); + + for (size_t bad : {size_t{0}, (size_t{1} << 31) + 1}) { + HnswOptions invalid; + invalid.num_clusters = bad; + expect_error( + [&] { HnswIndex(kDim, invalid); }, "num_clusters must be in [1, 2147483648]" + ); + } +} + +TEST(HnswIndexTest, 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 HnswIndex index(kDim); + ASSERT_TRUE(index.seed().has_value()); + EXPECT_EQ(index.cp().seed, *index.seed()); + seeds.insert(*index.seed()); + } + EXPECT_GT(seeds.size(), 1U); +} + +TEST(HnswIndexTest, FirstAddTrainsLikeTrainThenAdd) { + const auto data = gaussian(kNumPoints, 1); + HnswIndex implicit(kDim, options(7)); + HnswIndex explicit_train(kDim, options(7)); + HnswIndex other_cp(kDim, options(7)); + // The first add trains with cp(), like train, and builds with the index seed. + for (HnswIndex* 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); + EXPECT_EQ(implicit.num_clusters(), kNumClusters); + 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, "hnsw_index_implicit.index"); + EXPECT_EQ(bytes, saved_bytes(explicit_train, "hnsw_index_explicit.index")); + EXPECT_NE(bytes, saved_bytes(other_cp, "hnsw_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(HnswIndexTest, FirstAddRejectsNullDataAndAppliesFastQuantization) { + const auto data = gaussian(kNumPoints, 16); + HnswIndex untrained(kDim, options(8)); + expect_error( + [&] { untrained.add(nullptr, kNumPoints); }, "HnswIndex add data must not be null" + ); + EXPECT_FALSE(untrained.is_trained()); + + HnswIndex plain(kDim, options(8)); + plain.add(data.data(), kNumPoints, single_thread()); + AddOptions fast = single_thread(); + fast.fast_quantization = true; + HnswIndex fast_index(kDim, options(8)); + fast_index.add(data.data(), kNumPoints, fast); + EXPECT_NE( + saved_bytes(fast_index, "hnsw_index_first_fast.index"), + saved_bytes(plain, "hnsw_index_first_plain.index") + ); +} + +TEST(HnswIndexTest, FirstAddWithFewPointsTrainsOneCentroidPerPoint) { + const auto data = gaussian(4, 2); + HnswIndex index(kDim, options(5)); + EXPECT_EQ(index.add(data.data(), 4, single_thread()), 0); + EXPECT_TRUE(index.is_trained()); + EXPECT_EQ(index.num_clusters(), 4U); +} + +TEST(HnswIndexTest, FailedFirstAddLeavesTheIndexUntrainedEmptyAndItsCapacity) { + auto data = gaussian(kNumPoints, 3); + HnswIndex index(kDim, options(11)); + index.reserve(1000); + 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.num_clusters(), kNumClusters); + EXPECT_EQ(index.capacity(), 1000U); + EXPECT_EQ(index.seed(), std::optional(11)); + + data[5 * kDim] = 0.0F; + EXPECT_EQ(index.add(data.data(), kNumPoints, single_thread()), 0); + EXPECT_EQ(index.capacity(), 1000U); // the first add keeps a reserved capacity + HnswIndex fresh(kDim, options(11)); + fresh.reserve(1000); + fresh.add(data.data(), kNumPoints, single_thread()); + EXPECT_EQ( + saved_bytes(index, "hnsw_index_retried.index"), + saved_bytes(fresh, "hnsw_index_fresh.index") + ); +} + +TEST(HnswIndexTest, CapacityGrowsByAtLeastDoublingAndReserveOnlyGrows) { + auto data = gaussian(kNumPoints, 4); + HnswIndex index(kDim, options(1)); + index.train(data.data(), kNumPoints, 1); + index.add(data.data(), 100, single_thread()); + EXPECT_EQ(index.capacity(), 100U); + index.add(data.data() + (100 * kDim), 250, single_thread()); + EXPECT_EQ(index.capacity(), 350U); // what the points need, above double + index.add(data.data() + (350 * kDim), 10, single_thread()); + EXPECT_EQ(index.capacity(), 700U); // doubled + constexpr size_t kStored = 360; + + // Invalid points leave the capacity and the points unchanged. + data[3 * kDim] = std::numeric_limits::infinity(); + EXPECT_THROW(index.add(data.data(), 400), std::invalid_argument); + EXPECT_EQ(index.capacity(), 700U); + EXPECT_EQ(index.num_points(), kStored); + + // So do invalid cluster IDs and a missing data pointer. + const std::vector out_of_range(400, kNumClusters); + AddOptions bad_ids = single_thread(); + bad_ids.cluster_ids = out_of_range.data(); + data[3 * kDim] = 0.0F; + expect_error( + [&] { index.add(data.data(), 400, bad_ids); }, "HNSW cluster ID is out of range" + ); + expect_error( + [&] { index.add(nullptr, 400); }, "HnswIndex add data must not be null" + ); + EXPECT_EQ(index.capacity(), 700U); + EXPECT_EQ(index.num_points(), kStored); + + for (size_t smaller : {size_t{0}, size_t{10}, kStored, size_t{700}}) { + index.reserve(smaller); + EXPECT_EQ(index.capacity(), 700U); + } + index.reserve(1000); + EXPECT_EQ(index.capacity(), 1000U); + EXPECT_EQ(index.num_points(), kStored); +} + +TEST(HnswIndexTest, OperationsBeforeTrainingThrowLogicError) { + const auto data = gaussian(kNumPoints, 5); + HnswIndex index(kDim, options(1)); + const rabitq_test::TempFile file("hnsw_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 "HnswIndex 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_FALSE(std::filesystem::exists(file.path())); + index.reserve(50); // allowed before training + EXPECT_EQ(index.capacity(), 50U); + EXPECT_FALSE(index.is_trained()); + + index.train(data.data(), kNumPoints, 1); + expect_error( + [&] { index.save(file.path().c_str()); }, + "HnswIndex has no points to save; add points first" + ); + EXPECT_FALSE(std::filesystem::exists(file.path())); +} + +TEST(HnswIndexTest, RetrainingIsAllowedOnlyWhileEmpty) { + const auto data = gaussian(kNumPoints, 6); + HnswIndex index(kDim, options(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()); + index.train(data.data(), kNumPoints, 1); + index.add(data.data(), 50, single_thread()); + + const auto before = search(index, data.data(), 2, 5); + const std::string message = "HnswIndex cannot be trained once it stores points"; + expect_error([&] { index.train(data.data(), kNumPoints); }, message); + expect_error([&] { index.set_centroids(data.data()); }, message); + EXPECT_EQ(search(index, data.data(), 2, 5).ids, before.ids); +} + +TEST(HnswIndexTest, DefaultEfSearchIsKOrAtLeast64) { + constexpr size_t kMany = 4000; + const auto data = gaussian(kMany, 7); + HnswOptions weak = options(3, 4); + weak.M = 4; + weak.ef_construction = 8; + HnswIndex index(kDim, weak); + index.add(data.data(), kMany, single_thread()); + const auto queries = gaussian(200, 8); + const auto with = [&](std::optional ef_search, size_t k) { + GraphSearchOptions search_options; + search_options.ef_search = ef_search; + return search(index, queries.data(), 200, k, search_options); + }; + const auto by_default = with(std::nullopt, 10); + EXPECT_EQ(by_default.ids, with(64, 10).ids); + EXPECT_EQ(by_default.distances, with(64, 10).distances); + EXPECT_NE(by_default.ids, with(10, 10).ids); + EXPECT_NE(by_default.ids, with(200, 10).ids); + // Above 64, the default is k itself. + EXPECT_EQ(with(std::nullopt, 100).ids, with(100, 100).ids); +} + +TEST(HnswIndexTest, SearchRejectsZeroBreadthAndInvalidK) { + const auto data = gaussian(kNumPoints, 9); + HnswIndex index(kDim, options(1)); + index.add(data.data(), kNumPoints, single_thread()); + std::vector ids(kNumPoints); + GraphSearchOptions zero; + zero.ef_search = 0; + expect_error( + [&] { index.search(data.data(), 1, 1, ids.data(), nullptr, zero); }, + "ef_search 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); }, + "HnswIndex search ids must not be null" + ); + index.search(data.data(), 0, 1, nullptr, nullptr); // an empty batch does nothing +} + +TEST(HnswIndexTest, SearchPadsMissingResults) { + const auto data = gaussian(kNumPoints, 10); + HnswIndex index(kDim, options(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, single_thread()); + const auto padded = search(index, data.data(), 1, 8); + 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); + EXPECT_EQ(ids_only, padded.ids); +} + +TEST(HnswIndexTest, RemoveChecksIdsBeforeNarrowingThem) { + const auto data = gaussian(kNumPoints, 11); + HnswIndex index(kDim, options(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); }, "HnswIndex 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); + GraphSearchOptions wide; + wide.ef_search = kNumPoints; + const auto results = search(index, data.data(), 2, kNumPoints, wide); + for (const Id id : results.ids) { + EXPECT_TRUE(id != 0 && id != 1); + } +} + +TEST(HnswIndexTest, AddAndSearchApplyTheirOptions) { + const auto data = gaussian(kNumPoints, 12); + const auto trained = [&] { + HnswIndex index(kDim, options(6)); + index.set_centroids(data.data()); + return index; + }; + HnswIndex routed = trained(); + routed.add(data.data(), kNumPoints, single_thread()); + const auto routed_bytes = saved_bytes(routed, "hnsw_index_routed.index"); + + const std::vector first_cluster(kNumPoints, 0); + AddOptions assigned = single_thread(); + assigned.cluster_ids = first_cluster.data(); + HnswIndex one_cluster = trained(); + one_cluster.add(data.data(), kNumPoints, assigned); + EXPECT_NE(saved_bytes(one_cluster, "hnsw_index_one_cluster.index"), routed_bytes); + + AddOptions fast = single_thread(); + fast.fast_quantization = true; + HnswIndex fast_index = trained(); + fast_index.add(data.data(), kNumPoints, fast); + EXPECT_NE(saved_bytes(fast_index, "hnsw_index_fast.index"), routed_bytes); +} + +TEST(HnswIndexTest, SaveAndLoadKeepSettingsSeedAndResults) { + const auto data = gaussian(kNumPoints, 13); + HnswOptions configured = options(21); + configured.metric = METRIC_COSINE; + configured.nbits = 4; + configured.M = 8; + HnswIndex index(kDim, configured); + index.add(data.data(), kNumPoints, single_thread()); + const Id removed[] = {3}; + index.remove(removed, 1); + + const rabitq_test::TempFile file("hnsw_index_round_trip.index"); + index.save(file.path().c_str()); + const HnswIndex loaded = HnswIndex::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.M(), 8U); + EXPECT_EQ(loaded.ef_construction(), 200U); + EXPECT_EQ(loaded.metric(), METRIC_COSINE); + 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(HnswIndexTest, LoadsFilesWithoutASeedAndWithA64BitSeed) { + // 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" / "hnsw1_l2.index"; + HnswIndex old = HnswIndex::load(path.string().c_str()); + EXPECT_TRUE(old.is_trained()); + EXPECT_FALSE(old.seed().has_value()); + EXPECT_EQ(old.cp().seed, rabitqkmeans::RaBitQKMeansParameters{}.seed); + const size_t stored = old.num_stored_points(); + ASSERT_GT(stored, 0U); + const std::vector point(old.dim(), 0.5F); + EXPECT_EQ(old.add(point.data(), 1, single_thread()), static_cast(stored)); + + // The C++ HierarchicalNSW class can record a seed above 32 bits; cp takes its low + // 32 bits. + constexpr uint64_t kWideSeed = (uint64_t{1} << 40) + 5; + const auto data = gaussian(kNumPoints, 14); + hnsw::HierarchicalNSW wide(kNumPoints, kDim, 7, 16, 200, kWideSeed); + wide.train( + kNumClusters, kNumPoints, data.data(), rabitqkmeans::RaBitQKMeansParameters{} + ); + wide.add(data.data(), kNumPoints); + const rabitq_test::TempFile file("hnsw_index_wide_seed.index"); + wide.save(file.path().c_str()); + const HnswIndex loaded = HnswIndex::load(file.path().c_str()); + EXPECT_EQ(loaded.seed(), std::optional(kWideSeed)); + EXPECT_EQ(loaded.cp().seed, 5U); +} + +TEST(HnswIndexTest, MovedIndexKeepsItsState) { + const auto data = gaussian(kNumPoints, 15); + HnswIndex index(kDim, options(4)); + index.add(data.data(), kNumPoints, single_thread()); + const auto expected = search(index, data.data(), 2, 5); + HnswIndex moved(std::move(index)); + EXPECT_EQ(search(moved, data.data(), 2, 5).ids, expected.ids); + HnswIndex assigned(kDim, options(1, 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