diff --git a/CMakeLists.txt b/CMakeLists.txt index 0daccf06..e786ef3a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -257,6 +257,7 @@ if(RABITQ_BUILD_INDEX) src/index/ivf_search.cpp src/index/qg.cpp src/index/qg_builder.cpp + src/index/symqg_index.cpp src/index/pipnn.cpp src/index/hnsw_dispatch.cpp src/index/hnsw_search_generic.cpp diff --git a/docs/development.md b/docs/development.md index abda77be..1da66afb 100644 --- a/docs/development.md +++ b/docs/development.md @@ -48,6 +48,7 @@ factors estimate L2 distance or inner product. | `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/index/symqg_index.hpp` | `SymqgIndex`, the supported C++ SymphonyQG API: the Python workflow over `symqg::QuantizedGraph` and `QGBuilder` | | `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 | @@ -576,10 +577,11 @@ 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` 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`. +`IvfIndex`, `HnswIndex` or `SymqgIndex`, 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. diff --git a/docs/docs/releases/unreleased.md b/docs/docs/releases/unreleased.md index 09825653..de9e1ca4 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` and `HnswIndex` use 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`, `HnswIndex` and `SymqgIndex` use 64-bit IDs, as Python does. -- 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. +- An `IvfIndex`, `HnswIndex` or `SymqgIndex` 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`, or for data of the wrong dimension passed to `SymqgIndex.add` after the graph is built. `HnswIndex()` with an invalid `metric` or `seed` and an out-of-range `num_clusters` now reports the metric or seed. `SymqgIndex()` with an invalid `init` and an invalid `dim`, `nbits` or `max_degree` now reports the `init`, and with an invalid `seed` and an invalid `dim`, `nbits`, `max_degree` or `ef_construction` the 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. @@ -80,7 +80,12 @@ - `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. +- New `rabitqlib::SymqgIndex` in `rabitqlib/index/symqg_index.hpp` (#234), which the Python `SymqgIndex` now wraps: + - `SymqgIndex(dim, options)` takes a `SymqgOptions` struct (metric, `nbits` of 32, 4 or 8 with 32 for raw float32, `max_degree`, `ef_construction`, `init`, seed). `add` builds the graph from every vector, once, and a built or loaded index throws `std::logic_error` on `add`. `train` only checks its input. `search`, `save` and the static `load` follow the Python methods. + - A failed `add` leaves the index without a graph. `add` takes a worker count, with 0, the default, for every available CPU. + - `search` takes a `GraphSearchOptions` struct. Without an `ef_search` it uses `max(k, 64)`, a smaller value is raised to `k`, and an explicit 0 throws; `symqg::QuantizedGraph` rejects an `ef_search` below `k`. + - `seed()`, `ef_construction()` and `init()` have no value for a file of a release up to 0.8. +- `ivf::IVF`, `hnsw::HierarchicalNSW`, `symqg::QuantizedGraph` and `symqg::QGBuilder` are otherwise 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`. @@ -98,5 +103,5 @@ - `IVF::seed()`; - `HierarchicalNSW::seed()`; - `QuantizedGraph::seed()`, `ef_construction()` and `initialization()`. -- `symqg::QGInitialization` moves from `qg_builder.hpp` to `qg.hpp`, which `qg_builder.hpp` includes. +- `symqg::QGInitialization` moves from `qg_builder.hpp` to `rabitqlib/index/symqg/types.hpp`, which `qg.hpp`, and through it `qg_builder.hpp`, includes. - The vendored hnswlib adds `saveIndex(std::ostream&)` and `loadIndex(std::istream&, size_t bytes, ...)`; the path overloads are unchanged. diff --git a/include/rabitqlib/index/symqg/qg.hpp b/include/rabitqlib/index/symqg/qg.hpp index 4066b651..b414fba2 100644 --- a/include/rabitqlib/index/symqg/qg.hpp +++ b/include/rabitqlib/index/symqg/qg.hpp @@ -11,6 +11,7 @@ #include "rabitqlib/core/metric.hpp" // IWYU pragma: export #include "rabitqlib/core/types.hpp" // IWYU pragma: export #include "rabitqlib/index/detail/visited_set_fwd.hpp" // IWYU pragma: export +#include "rabitqlib/index/symqg/types.hpp" // IWYU pragma: export #include "rabitqlib/index/types.hpp" // IWYU pragma: export #include "rabitqlib/utils/memory.hpp" #include "rabitqlib/utils/packed.hpp" @@ -28,9 +29,6 @@ class SearchBuffer; namespace rabitqlib::symqg { -// How a builder initializes the graph before refinement. -enum class QGInitialization { PiPNN, Random }; - class QuantizedQuery { private: const float* rotated_query_; diff --git a/include/rabitqlib/index/symqg/types.hpp b/include/rabitqlib/index/symqg/types.hpp new file mode 100644 index 00000000..479dad56 --- /dev/null +++ b/include/rabitqlib/index/symqg/types.hpp @@ -0,0 +1,6 @@ +#pragma once + +namespace rabitqlib::symqg { +// How a builder initializes the graph before refinement. +enum class QGInitialization { PiPNN, Random }; +} // namespace rabitqlib::symqg diff --git a/include/rabitqlib/index/symqg_index.hpp b/include/rabitqlib/index/symqg_index.hpp new file mode 100644 index 00000000..a076ce90 --- /dev/null +++ b/include/rabitqlib/index/symqg_index.hpp @@ -0,0 +1,140 @@ +#pragma once + +#include +#include +#include +#include + +#include "rabitqlib/core/metric.hpp" // IWYU pragma: export +#include "rabitqlib/index/symqg/types.hpp" // IWYU pragma: export +#include "rabitqlib/index/types.hpp" // IWYU pragma: export + +namespace rabitqlib { +namespace symqg { +template +class QuantizedGraph; +} + +// Settings of a new SymqgIndex; set the fields by name. The metric comes first, so a lone +// positional value must be a metric: {4} does not compile. +struct SymqgOptions { + MetricType metric = METRIC_L2; // METRIC_L2, METRIC_IP or METRIC_COSINE + size_t nbits = 32; // 32 keeps raw float32 vectors; 4 or 8 RaBitQ bits + size_t max_degree = 32; // graph degree bound, a positive multiple of 32 + size_t ef_construction = 200; // construction search breadth, from 1 to 2^32 - 1 + symqg::QGInitialization init = symqg::QGInitialization::PiPNN; + std::optional seed; // rotation and construction seed; no value draws one +}; + +/** + * @brief A SymphonyQG index with the workflow of the Python SymqgIndex. + * + * Create it, then add every vector in one call: add builds the graph, and a built + * graph cannot be extended. Search and save need a built or loaded index. There is + * nothing to train; train only checks its input. + * + * IDs are the row numbers of the added data, from 0. + * + * 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 SymqgIndex { + public: + /** + * @param dim Vector dimension, from 64 to 65536 + * @param options Metric, bits, graph settings and seed + */ + explicit SymqgIndex(size_t dim, const SymqgOptions& options = {}); + + SymqgIndex(SymqgIndex&& other) noexcept; + SymqgIndex& operator=(SymqgIndex&& other) noexcept; + SymqgIndex(const SymqgIndex&) = delete; + SymqgIndex& operator=(const SymqgIndex&) = delete; + ~SymqgIndex(); + + // Load an index saved by any release; it is built, so add throws. + static SymqgIndex load(const char* filename); + + // Requires a built or loaded index. Releases up to 0.8 cannot read the file. + void save(const char* filename) const; + + /** + * @brief Check that the vectors are finite and within the coordinate range, as add + * does; the index does not change. The point count is not checked. + * + * @param data num_points * dim values + */ + void train(const float* data, size_t num_points) const; + + /** + * @brief Build the graph from all vectors, once. + * + * Uses the constructor's metric, bits, max_degree, ef_construction, init and seed. + * If it throws, the index stays without a graph. A built or loaded index throws + * std::logic_error; create a new index to rebuild. + * + * @param data num_points * dim values + * @param num_points More than max_degree() + * @param num_threads Worker count; 0 selects every available CPU, capped by + * OMP_NUM_THREADS + * @return ID of the first point, 0; the points have consecutive IDs + */ + Id add(const float* data, size_t num_points, size_t num_threads = 0); + + /** + * @brief Search a batch of queries. + * + * Slots without a result get kNoId and +inf. Distances are squared L2, 1 - dot or + * 1 - cos according to the metric, exact for raw vectors and estimated with 4 or 8 + * bits; 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; + // 32 for raw float32 vectors, or 4 or 8. + [[nodiscard]] size_t nbits() const; + [[nodiscard]] MetricType metric() const; + [[nodiscard]] size_t max_degree() const; + // No value for an index loaded from a file of a release up to 0.8. + [[nodiscard]] std::optional ef_construction() const; + [[nodiscard]] std::optional init() const; + [[nodiscard]] std::optional seed() const; + // Searchable points: 0 until add. + [[nodiscard]] size_t num_points() const; + // Stored points, equal to num_points(); SymphonyQG has no removal. + [[nodiscard]] size_t num_stored_points() const; + // Always true: SymphonyQG needs no training. + [[nodiscard]] bool is_trained() const; + + private: + explicit SymqgIndex(std::unique_ptr> graph); + + void check_built(const char* operation) const; + + size_t dim_; + MetricType metric_; + size_t nbits_; + size_t max_degree_; + // Settings of the current graph or of add; unknown for a file of a release up to 0.8. + std::optional ef_construction_; + std::optional init_; + std::optional seed_; + std::unique_ptr> graph_; // null until add or load +}; + +} // namespace rabitqlib diff --git a/include/rabitqlib/index/types.hpp b/include/rabitqlib/index/types.hpp index 65001d7a..003b7e81 100644 --- a/include/rabitqlib/index/types.hpp +++ b/include/rabitqlib/index/types.hpp @@ -9,8 +9,8 @@ namespace rabitqlib { using PID = uint32_t; inline constexpr PID kPidMax = 0xFFFFFFFF; -// A point ID at the IvfIndex and HnswIndex API: the row number the index assigned to -// the point. +// A point ID at the IvfIndex, HnswIndex and SymqgIndex 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; @@ -28,7 +28,7 @@ struct AddOptions { bool fast_quantization = false; }; -// Settings of a graph index search (HnswIndex). +// Settings of a graph index search (HnswIndex and SymqgIndex). struct GraphSearchOptions { // Search breadth, raised to k. No value selects max(k, 64); 0 throws. std::optional ef_search; diff --git a/python_bindings/bindings_common.hpp b/python_bindings/bindings_common.hpp index 8ea561c8..7f5f36e2 100644 --- a/python_bindings/bindings_common.hpp +++ b/python_bindings/bindings_common.hpp @@ -385,30 +385,6 @@ RowView checked_output_rows( return make_row_view(std::move(array)); } -// Point IDs as Python sees them: int64, with -1 where the index reports kPidMax. -inline py::array_t python_ids(const PID* ids, std::vector shape) { - py::array_t result(std::move(shape)); - int64_t* out = result.mutable_data(); - for (py::ssize_t i = 0; i < result.size(); ++i) { - out[i] = ids[i] == kPidMax ? int64_t{-1} : static_cast(ids[i]); - } - return result; -} - -// (num_queries, k) outputs. The index writes row numbers into ids; slots without a -// neighbor keep kPidMax and +inf. Searches pad slots without a result, so k may exceed -// the number of points. -struct SearchResults { - std::vector shape; - std::vector ids; - py::array_t distances; - - // (ids, distances) for Python, with int64 IDs and -1 for a missing neighbor. - [[nodiscard]] py::tuple to_python() const { - return py::make_tuple(python_ids(ids.data(), shape), distances); - } -}; - 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"); @@ -424,19 +400,6 @@ inline void check_ef_search(std::optional ef_search) { } } -inline SearchResults unfilled_search_results(size_t num_queries, size_t k) { - const auto shape = std::vector{ - static_cast(num_queries), static_cast(k)}; - SearchResults results{ - shape, std::vector(num_queries * k, kPidMax), py::array_t(shape)}; - std::fill( - results.distances.mutable_data(), - results.distances.mutable_data() + results.distances.size(), - std::numeric_limits::infinity() - ); - return results; -} - // Like ensure_1d_array, but refuses input whose dtype is not an integer. forcecast // would otherwise truncate floats and turn booleans or numeric strings into ids, and // callers use these ids to remove points permanently. An empty sequence has no dtype to diff --git a/python_bindings/symqg_bindings.cpp b/python_bindings/symqg_bindings.cpp index c941dc71..5f3569d5 100644 --- a/python_bindings/symqg_bindings.cpp +++ b/python_bindings/symqg_bindings.cpp @@ -6,25 +6,18 @@ #include #include // IWYU pragma: keep; registers std::optional casters -#include #include #include #include -#include #include #include -#include #include #include #include #include #include "bindings_common.hpp" -#include "rabitqlib/core/metric.hpp" -#include "rabitqlib/core/rotator.hpp" -#include "rabitqlib/fastscan/pack_codes.hpp" -#include "rabitqlib/index/symqg/qg.hpp" -#include "rabitqlib/index/symqg/qg_builder.hpp" +#include "rabitqlib/index/symqg_index.hpp" #include "rabitqlib/index/types.hpp" #include "rabitqlib/utils/input_checks.hpp" @@ -43,52 +36,40 @@ class SymqgIndex { const std::string& metric, const py::object& seed ) - : dim_(dim) - , max_degree_(max_degree) - , metric_type_(index_metric_from_string(metric)) - , ef_construction_(ef_construction) - , init_(init) { - // Reject now what add would reject only after converting all the data. - if (dim < 64 || dim > rotator_impl::FhtKacRotator::kMaxDim) { - throw std::invalid_argument("Unsupported dimension for FhtKacRotator"); - } - check_max_degree(max_degree); - if (nbits != 4 && nbits != 8 && nbits != 32) { - throw std::invalid_argument("nbits must be 4, 8, or 32"); - } - quantization_bits_ = nbits == 32 ? 0 : nbits; - check_construction(ef_construction, init); - seed_ = seed.is_none() ? std::random_device{}() - : static_cast(checked_seed( - seed, std::numeric_limits::max() - )); - } + : index_( + dim, index_options(nbits, max_degree, ef_construction, init, metric, seed) + ) {} - // SymphonyQG learns nothing before add: train only checks x as add would, so - // the index is unchanged and a shared guard suffices. + // SymphonyQG learns nothing before add: train only checks the coordinates of x as + // add does, so the index is unchanged and a shared guard suffices. The check names + // x, so it stays here rather than in the native train. void train(py::handle x, std::optional /*num_threads*/) { const auto operation = access_.read(); auto x_array = ensure_2d_array(x, "x"); - ensure_dimension(x_array, dim_, "x dimension does not match index dim"); + const size_t dim = index_.dim(); + ensure_dimension(x_array, dim, "x dimension does not match index dim"); const auto* x_ptr = x_array.data(); const size_t count = static_cast(x_array.size()); py::gil_scoped_release release; - check_coordinates(x_ptr, count, dim_, "x"); + check_coordinates(x_ptr, count, dim, "x"); } py::array_t add(py::handle data, std::optional num_threads) { const auto operation = access_.write(); - if (built()) { - throw std::runtime_error( - "SymqgIndex does not support incremental addition; create a new index " - "and add all vectors at once" - ); - } - build_graph(data, num_threads.value_or(0)); - // Point IDs are the row numbers of data. - const size_t rows = index_->num_points(); + auto data_array = ensure_2d_array(data, "data"); + ensure_dimension( + data_array, index_.dim(), "data dimension does not match index dim" + ); + const auto rows = static_cast(data_array.shape(0)); + // Allocate the returned IDs before the index changes. auto ids = py::array_t(static_cast(rows)); - std::iota(ids.mutable_data(), ids.mutable_data() + rows, int64_t{0}); + const auto* data_ptr = data_array.data(); + Id first = 0; + { + py::gil_scoped_release release; + first = index_.add(data_ptr, rows, num_threads.value_or(0)); + } + std::iota(ids.mutable_data(), ids.mutable_data() + rows, first); return ids; } @@ -100,195 +81,131 @@ class SymqgIndex { ) { const auto operation = access_.read(); auto query_array = ensure_2d_array(queries, "queries"); - check_built("search"); - ensure_dimension(query_array, dim_, "query dimension does not match index dim"); - check_k(k); + ensure_dimension( + query_array, index_.dim(), "query dimension does not match index dim" + ); + check_k(k); // before the outputs are allocated check_ef_search(ef_search); - // As in HnswIndex, None selects max(k, 64); a smaller breadth is raised to k. - const size_t search_breadth = std::max(ef_search.value_or(64), k); - - 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(); + GraphSearchOptions options; + options.ef_search = ef_search; + options.num_threads = num_threads.value_or(1); + + 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_with_ef( - queries_data, - num_queries, - static_cast(k), - ids_data, - distances_data, - search_breadth, - 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_built("save"); py::gil_scoped_release release; - index_->save(filename.c_str()); + index_.save(filename.c_str()); } static SymqgIndex load(py::handle path) { const auto filename = path_string(path); - SymqgIndex wrapper; - wrapper.index_ = std::make_unique>(); - { + auto index = [&filename] { py::gil_scoped_release release; - wrapper.index_->load(filename.c_str()); - } - wrapper.dim_ = wrapper.index_->dimension(); - wrapper.max_degree_ = wrapper.index_->degree_bound(); - wrapper.metric_type_ = wrapper.index_->metric_type(); - wrapper.quantization_bits_ = wrapper.index_->quantization_bits(); - // Format-2 files record the seed and the construction settings; earlier files - // record neither. - wrapper.seed_ = wrapper.index_->seed(); - wrapper.ef_construction_ = wrapper.index_->ef_construction(); - wrapper.init_.reset(); - if (const auto init = wrapper.index_->initialization(); init.has_value()) { - wrapper.init_ = *init == symqg::QGInitialization::PiPNN ? "pipnn" : "random"; - } - return wrapper; + return rabitqlib::SymqgIndex::load(filename.c_str()); + }(); + return SymqgIndex(std::move(index)); } [[nodiscard]] std::string repr() const { const auto operation = access_.read(); - return "SymqgIndex(dim=" + std::to_string(dim_) + ", metric='" + - metric_to_string(metric_type_) + "', nbits=" + std::to_string(nbits()) + - ", num_points=" + std::to_string(built() ? index_->num_points() : 0) + - ", max_degree=" + std::to_string(max_degree_) + ")"; + return "SymqgIndex(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()) + + ", max_degree=" + std::to_string(index_.max_degree()) + ")"; } [[nodiscard]] size_t dim() const { const auto operation = access_.read(); - return dim_; + return index_.dim(); } [[nodiscard]] size_t max_degree() const { const auto operation = access_.read(); - return max_degree_; + return index_.max_degree(); } [[nodiscard]] std::optional ef_construction() const { const auto operation = access_.read(); - return ef_construction_; + return index_.ef_construction(); } [[nodiscard]] std::optional init() const { const auto operation = access_.read(); - return init_; + const auto init = index_.init(); + if (!init.has_value()) { + return std::nullopt; + } + return *init == symqg::QGInitialization::PiPNN ? "pipnn" : "random"; } [[nodiscard]] size_t num_points() const { const auto operation = access_.read(); - return built() ? index_->num_points() : 0; + return index_.num_points(); } [[nodiscard]] size_t num_stored_points() const { const auto operation = access_.read(); - return built() ? index_->num_stored_points() : 0; + return index_.num_stored_points(); } + // Always true and reads no state, so it needs no guard. + [[nodiscard]] bool is_trained() const { return index_.is_trained(); } [[nodiscard]] std::string metric() const { const auto operation = access_.read(); - return metric_to_string(metric_type_); + return metric_to_string(index_.metric()); } - [[nodiscard]] size_t nbits_property() const { + [[nodiscard]] size_t nbits() const { const auto operation = access_.read(); - return nbits(); + return index_.nbits(); } [[nodiscard]] std::optional seed() const { const auto operation = access_.read(); - return seed_; + return index_.seed(); } private: - static constexpr size_t kDefaultEfConstruction = 200; - - SymqgIndex() = default; - - static void check_max_degree(size_t max_degree) { - if (max_degree == 0 || max_degree % fastscan::kBatchSize != 0) { - throw std::invalid_argument("max_degree must be a positive multiple of 32"); - } - } + explicit SymqgIndex(rabitqlib::SymqgIndex index) : index_(std::move(index)) {} - static void check_construction(size_t ef_construction, const std::string& init) { - if (init != "random" && init != "pipnn") { + static SymqgOptions index_options( + size_t nbits, + size_t max_degree, + size_t ef_construction, + const std::string& init, + const std::string& metric, + const py::object& seed + ) { + SymqgOptions options; + options.metric = index_metric_from_string(metric); + if (init == "pipnn") { + options.init = symqg::QGInitialization::PiPNN; + } else if (init == "random") { + options.init = symqg::QGInitialization::Random; + } else { throw std::invalid_argument("init must be 'random' or 'pipnn'"); } - if (ef_construction == 0 || - ef_construction > std::numeric_limits::max()) { - throw std::invalid_argument("ef_construction must be positive and fit uint32"); - } - } - - void check_built(const char* operation) const { - if (!built()) { - throw std::runtime_error( - std::string( - "SymqgIndex has no vectors; add them or load an index before " - ) + - operation - ); - } - } - - // Build the graph from data with the constructor's settings; a failure leaves - // the index without one. Only a loaded index lacks those settings, and it - // already has a graph. Requires the write guard. - void build_graph(py::handle data, size_t num_threads) { - const uint32_t seed = *seed_; - auto data_array = ensure_2d_array(data, "data"); - ensure_dimension(data_array, dim_, "data dimension does not match index dim"); - - const size_t num_points = static_cast(data_array.shape(0)); - auto index = std::make_unique>( - num_points, - dim_, - max_degree_, - metric_type_, - RotatorType::FhtKacRotator, - quantization_bits_, - seed - ); - - const auto initialization = *init_ == "pipnn" ? symqg::QGInitialization::PiPNN - : symqg::QGInitialization::Random; - const auto* data_ptr = data_array.data(); - { - py::gil_scoped_release release; - symqg::QGBuilder builder( - *index, - static_cast(*ef_construction_), - data_ptr, - num_threads, - initialization, - seed + if (!seed.is_none()) { + options.seed = static_cast( + checked_seed(seed, std::numeric_limits::max()) ); - builder.build(); } - index_ = std::move(index); - } - - [[nodiscard]] size_t nbits() const { - return quantization_bits_ == 0 ? 32 : quantization_bits_; + options.nbits = nbits; + options.max_degree = max_degree; + options.ef_construction = ef_construction; + return options; } - [[nodiscard]] bool built() const { return index_ != nullptr; } - - size_t dim_ = 0; - size_t max_degree_ = 0; - MetricType metric_type_ = METRIC_L2; - size_t quantization_bits_ = 0; // 0 stores raw vectors. - // Settings of the current graph, or of the next add; unknown after load. - std::optional ef_construction_ = kDefaultEfConstruction; - std::optional init_ = "pipnn"; - std::optional seed_; // Unknown for files from releases up to 0.8. + rabitqlib::SymqgIndex index_; mutable IndexAccess access_; - std::unique_ptr> index_; }; } // namespace rabitqlib::python_bindings @@ -535,7 +452,7 @@ index : SymqgIndex ) .def_property_readonly( "is_trained", - [](const SymqgIndex&) { return true; }, + &SymqgIndex::is_trained, R"doc(Always True: SymphonyQG needs no training.)doc" ) .def_property_readonly( @@ -545,7 +462,7 @@ index : SymqgIndex ) .def_property_readonly( "nbits", - &SymqgIndex::nbits_property, + &SymqgIndex::nbits, R"doc(Storage bits: 32 for raw float32, or 4 or 8 for RaBitQ.)doc" ) .def_property_readonly( diff --git a/src/index/index_facade.hpp b/src/index/index_facade.hpp index fcefcfdc..73f73794 100644 --- a/src/index/index_facade.hpp +++ b/src/index/index_facade.hpp @@ -12,7 +12,7 @@ #include "rabitqlib/index/detail/buffer.hpp" #include "rabitqlib/index/types.hpp" -// Checks and settings that the IvfIndex and HnswIndex classes share. Their +// Checks and settings that the IvfIndex, HnswIndex and SymqgIndex classes share. Their // messages are the ones the Python classes raise. namespace rabitqlib::index_facade { diff --git a/src/index/symqg_index.cpp b/src/index/symqg_index.cpp new file mode 100644 index 00000000..dd85260d --- /dev/null +++ b/src/index/symqg_index.cpp @@ -0,0 +1,194 @@ +#include "rabitqlib/index/symqg_index.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cosine.hpp" +#include "index_facade.hpp" +#include "rabitqlib/core/rotator.hpp" +#include "rabitqlib/core/types.hpp" +#include "rabitqlib/fastscan/pack_codes.hpp" +#include "rabitqlib/index/symqg/qg.hpp" +#include "rabitqlib/index/symqg/qg_builder.hpp" +#include "rabitqlib/utils/input_checks.hpp" + +namespace rabitqlib { + +namespace { +// The graph stores raw vectors as 0 bits. +size_t graph_bits(size_t nbits) { return nbits == 32 ? 0 : nbits; } +} // namespace + +SymqgIndex::SymqgIndex(size_t dim, const SymqgOptions& options) + : dim_(dim) + , metric_(options.metric) + , nbits_(options.nbits) + , max_degree_(options.max_degree) + , ef_construction_(options.ef_construction) + , init_(options.init) { + validate_metric_type(index_detail::stored_metric(options.metric)); + // Checked now; the graph is created only on add. + if (dim < 64 || dim > rotator_impl::FhtKacRotator::kMaxDim) { + throw std::invalid_argument("Unsupported dimension for FhtKacRotator"); + } + if (options.max_degree == 0 || options.max_degree % fastscan::kBatchSize != 0) { + throw std::invalid_argument("max_degree must be a positive multiple of 32"); + } + if (options.nbits != 4 && options.nbits != 8 && options.nbits != 32) { + throw std::invalid_argument("nbits must be 4, 8, or 32"); + } + if (options.init != symqg::QGInitialization::PiPNN && + options.init != symqg::QGInitialization::Random) { + throw std::invalid_argument("init must be PiPNN or Random"); + } + if (options.ef_construction == 0 || + options.ef_construction > std::numeric_limits::max()) { + throw std::invalid_argument("ef_construction must be positive and fit uint32"); + } + seed_ = options.seed.has_value() ? *options.seed : std::random_device{}(); +} + +SymqgIndex::SymqgIndex(std::unique_ptr> graph) + : dim_(graph->dimension()) + , metric_(graph->metric_type()) + , nbits_(graph->is_quantized() ? graph->quantization_bits() : 32) + , max_degree_(graph->degree_bound()) + , ef_construction_(graph->ef_construction()) + , init_(graph->initialization()) + , seed_(graph->seed()) + , graph_(std::move(graph)) {} + +SymqgIndex::SymqgIndex(SymqgIndex&& other) noexcept = default; +SymqgIndex& SymqgIndex::operator=(SymqgIndex&& other) noexcept = default; +SymqgIndex::~SymqgIndex() = default; + +SymqgIndex SymqgIndex::load(const char* filename) { + auto graph = std::make_unique>(); + graph->load(filename); + return SymqgIndex(std::move(graph)); +} + +void SymqgIndex::save(const char* filename) const { + check_built("save"); + graph_->save(filename); +} + +void SymqgIndex::train(const float* data, size_t num_points) const { + if (num_points != 0 && data == nullptr) { + throw std::invalid_argument("SymqgIndex train data must not be null"); + } + check_coordinates(data, num_points * dim_, dim_, "SymqgIndex train data"); +} + +Id SymqgIndex::add(const float* data, size_t num_points, size_t num_threads) { + if (graph_ != nullptr) { + throw std::logic_error( + "SymqgIndex does not support incremental addition; create a new index and " + "add all vectors at once" + ); + } + if (num_points != 0 && data == nullptr) { + throw std::invalid_argument("SymqgIndex add data must not be null"); + } + // Build a new graph and move it in, so that a failure leaves this index without one. + // Only a loaded index lacks these settings, and it already has a graph. + const uint32_t seed = seed_.value(); + auto graph = std::make_unique>( + num_points, + dim_, + max_degree_, + metric_, + RotatorType::FhtKacRotator, + graph_bits(nbits_), + seed + ); + symqg::QGBuilder builder( + *graph, + static_cast(ef_construction_.value()), + data, + num_threads, + init_.value(), + seed + ); + builder.build(); + graph_ = std::move(graph); + return 0; +} + +void SymqgIndex::search( + const float* queries, + size_t num_queries, + size_t k, + Id* ids, + float* distances, + const GraphSearchOptions& options +) const { + check_built("search"); + index_facade::check_k(k); + index_facade::check_breadth(options.ef_search, "ef_search"); + if (num_queries == 0) { + return; + } + index_facade::check_outputs("SymqgIndex", num_queries, k, ids); + // The graph writes 32-bit row numbers, which are widened afterwards, and always + // writes distances. + std::vector row_ids(num_queries * k); + std::vector unused_distances(distances == nullptr ? num_queries * k : 0); + // Concurrent searches are safe; a search with its own breadth only reads the graph. + graph_->search_batch_with_ef( + queries, + num_queries, + static_cast(k), + row_ids.data(), + distances != nullptr ? distances : unused_distances.data(), + std::max(options.ef_search.value_or(64), k), + options.num_threads + ); + std::transform(row_ids.begin(), row_ids.end(), ids, [](PID id) { + return id == kPidMax ? kNoId : static_cast(id); + }); +} + +size_t SymqgIndex::dim() const { return dim_; } + +size_t SymqgIndex::nbits() const { return nbits_; } + +MetricType SymqgIndex::metric() const { return metric_; } + +size_t SymqgIndex::max_degree() const { return max_degree_; } + +std::optional SymqgIndex::ef_construction() const { return ef_construction_; } + +std::optional SymqgIndex::init() const { return init_; } + +std::optional SymqgIndex::seed() const { return seed_; } + +size_t SymqgIndex::num_points() const { + return graph_ != nullptr ? graph_->num_points() : 0; +} + +size_t SymqgIndex::num_stored_points() const { + return graph_ != nullptr ? graph_->num_stored_points() : 0; +} + +bool SymqgIndex::is_trained() const { return true; } + +void SymqgIndex::check_built(const char* operation) const { + if (graph_ == nullptr) { + throw std::logic_error( + std::string("SymqgIndex has no vectors; add them or load an index before ") + + operation + ); + } +} + +} // namespace rabitqlib diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 5c633161..b800175b 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -53,6 +53,7 @@ set_source_files_properties(unit/rabitqlib/utils/blob_test.cpp 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 + unit/rabitqlib/index/symqg_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 362775c6..089e1eeb 100644 --- a/tests/consumer/CMakeLists.txt +++ b/tests/consumer/CMakeLists.txt @@ -54,10 +54,11 @@ target_include_directories(index_header_boundary BEFORE PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/forbidden") # 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) + index_api_headers_main.cpp hnsw_index_headers.cpp ivf_index_headers.cpp + symqg_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) + index/symqg/qg.hpp index/symqg/qg_builder.hpp clustering/rabitqkmeans.hpp) get_filename_component(directory "${header}" DIRECTORY) file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/index-api-forbidden/rabitqlib/${directory}") file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/index-api-forbidden/rabitqlib/${header}" diff --git a/tests/consumer/index_api_headers_main.cpp b/tests/consumer/index_api_headers_main.cpp index 1bfd25a7..60baac85 100644 --- a/tests/consumer/index_api_headers_main.cpp +++ b/tests/consumer/index_api_headers_main.cpp @@ -1,4 +1,8 @@ int hnsw_index_header_smoke(); int ivf_index_header_smoke(); +int symqg_index_header_smoke(); -int main() { return hnsw_index_header_smoke() + ivf_index_header_smoke(); } +int main() { + return hnsw_index_header_smoke() + ivf_index_header_smoke() + + symqg_index_header_smoke(); +} diff --git a/tests/consumer/symqg_index_headers.cpp b/tests/consumer/symqg_index_headers.cpp new file mode 100644 index 00000000..6d10fcd3 --- /dev/null +++ b/tests/consumer/symqg_index_headers.cpp @@ -0,0 +1,29 @@ +#include +#include +#include + +#include "rabitqlib/index/symqg_index.hpp" + +// The supported SymphonyQG API compiles and works without the existing graph classes or +// any implementation header. +int symqg_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::SymqgOptions options; + options.init = rabitqlib::symqg::QGInitialization::Random; + options.ef_construction = 40; + options.seed = 3; + rabitqlib::SymqgIndex index(kDim, options); + const rabitqlib::Id first = index.add(data.data(), kNumPoints, 1); + 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/construction_failure_test.cpp b/tests/failures/construction_failure_test.cpp index 777ddbdf..3409247a 100644 --- a/tests/failures/construction_failure_test.cpp +++ b/tests/failures/construction_failure_test.cpp @@ -16,6 +16,7 @@ #include "rabitqlib/index/ivf/ivf.hpp" #include "rabitqlib/index/symqg/qg.hpp" #include "rabitqlib/index/symqg/qg_builder.hpp" +#include "rabitqlib/index/symqg_index.hpp" #include "rabitqlib/index/types.hpp" namespace { @@ -284,4 +285,56 @@ TEST_P(ConstructionWorkerFailure, QgRefinementWorkerErrorsReachCaller) { } } } + +// Fail the first, a middle and the last worker allocation of SymqgIndex::add; the last +// is in refinement, after the builder is constructed. The index keeps no graph, so a later +// add builds one. +TEST_P(ConstructionWorkerFailure, FailedSymqgIndexAddKeepsNoGraph) { + using namespace rabitqlib; + const auto data = vectors(); + const size_t threads = GetParam(); + for (const auto init : + {symqg::QGInitialization::Random, symqg::QGInitialization::PiPNN}) { + SymqgOptions options; + options.nbits = 4; + options.ef_construction = 32; + options.init = init; + options.seed = 42; + // The first add of a process also allocates one-time runtime state, so count + // the second. + constexpr size_t kNever = std::numeric_limits::max() / 2; + size_t allocations = 0; + for (int run = 0; run < 2; ++run) { + SymqgIndex counted(64, options); + remaining = kNever; + fail_parallel = true; + counted.add(data.data(), 64, threads); + fail_parallel = false; + allocations = kNever - remaining; + } + ASSERT_GT(allocations, 2U); + size_t failures = 0; + for (const size_t skip : {size_t{0}, allocations / 2, allocations - 1}) { + SCOPED_TRACE(skip); + SymqgIndex index(64, options); + remaining = skip; + fail_parallel = true; + bool failed = false; + try { + index.add(data.data(), 64, threads); + } catch (const std::bad_alloc&) { failed = true; } + fail_parallel = false; + if (!failed) { + // Concurrent workers may allocate a little less than the counted add. + EXPECT_GT(threads, 1U); + continue; + } + ++failures; + ASSERT_EQ(index.num_points(), 0U); + ASSERT_NO_THROW(index.add(data.data(), 64, threads)); + ASSERT_EQ(index.num_points(), 64U); + } + EXPECT_GE(failures, 2U); + } +} } // namespace diff --git a/tests/unit/rabitqlib/index/symqg_index_test.cpp b/tests/unit/rabitqlib/index/symqg_index_test.cpp new file mode 100644 index 00000000..e3a8626d --- /dev/null +++ b/tests/unit/rabitqlib/index/symqg_index_test.cpp @@ -0,0 +1,489 @@ +#include "rabitqlib/index/symqg_index.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rabitqlib/core/metric.hpp" +#include "rabitqlib/core/types.hpp" +#include "rabitqlib/index/symqg/qg.hpp" +#include "rabitqlib/index/symqg/qg_builder.hpp" +#include "rabitqlib/index/types.hpp" +#include "temp_file.hpp" + +namespace rabitqlib { +namespace { + +using symqg::QGInitialization; + +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; + +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; +} + +SymqgOptions options(uint32_t seed) { + SymqgOptions result; + result.ef_construction = 40; + result.seed = seed; + 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 SymqgIndex& 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; +} + +std::vector file_bytes(const std::string& path) { + std::ifstream input(path, std::ios::binary); + return {std::istreambuf_iterator(input), std::istreambuf_iterator()}; +} + +std::vector saved_bytes(const SymqgIndex& index, const std::string& name) { + const rabitq_test::TempFile file(name); + index.save(file.path().c_str()); + return file_bytes(file.path()); +} + +TEST(SymqgIndexTest, DefaultsFollowThePythonClass) { + const SymqgIndex index(kDim); + EXPECT_EQ(index.dim(), kDim); + EXPECT_EQ(index.nbits(), 32U); + EXPECT_EQ(index.max_degree(), 32U); + EXPECT_EQ(index.ef_construction(), std::optional(200)); + EXPECT_EQ(index.init(), std::optional(QGInitialization::PiPNN)); + EXPECT_EQ(index.metric(), METRIC_L2); + EXPECT_TRUE(index.seed().has_value()); + EXPECT_TRUE(index.is_trained()); + EXPECT_EQ(index.num_points(), 0U); + EXPECT_EQ(index.num_stored_points(), 0U); + + SymqgOptions configured; + configured.metric = METRIC_COSINE; + configured.nbits = 4; + configured.max_degree = 64; + configured.ef_construction = 50; + configured.init = QGInitialization::Random; + configured.seed = 9; + const SymqgIndex cosine(65536, configured); + EXPECT_EQ(cosine.dim(), 65536U); + EXPECT_EQ(cosine.metric(), METRIC_COSINE); + EXPECT_EQ(cosine.nbits(), 4U); + EXPECT_EQ(cosine.max_degree(), 64U); + EXPECT_EQ(cosine.ef_construction(), std::optional(50)); + EXPECT_EQ(cosine.init(), std::optional(QGInitialization::Random)); + EXPECT_EQ(cosine.seed(), std::optional(9)); +} + +TEST(SymqgIndexTest, ConstructorRejectsInvalidSettings) { + const auto invalid = [](size_t dim, auto change, const std::string& message) { + SymqgOptions settings; + change(settings); + expect_error([&] { SymqgIndex(dim, settings); }, message); + }; + const auto keep = [](SymqgOptions&) {}; + invalid(63, keep, "Unsupported dimension for FhtKacRotator"); + invalid(65537, keep, "Unsupported dimension for FhtKacRotator"); + for (size_t bad : {size_t{0}, size_t{48}}) { + invalid( + kDim, + [&](SymqgOptions& o) { o.max_degree = bad; }, + "max_degree must be a positive multiple of 32" + ); + } + for (size_t bad : {size_t{0}, size_t{7}, size_t{16}}) { + invalid(kDim, [&](SymqgOptions& o) { o.nbits = bad; }, "nbits must be 4, 8, or 32"); + } + invalid( + kDim, + [](SymqgOptions& o) { o.init = static_cast(7); }, + "init must be PiPNN or Random" + ); + for (size_t bad : {size_t{0}, size_t{std::numeric_limits::max()} + 1}) { + invalid( + kDim, + [&](SymqgOptions& o) { o.ef_construction = bad; }, + "ef_construction must be positive and fit uint32" + ); + } + invalid( + kDim, + [](SymqgOptions& o) { o.metric = static_cast(7); }, + "Metric type must be METRIC_L2 or METRIC_IP" + ); + // The checks run in this order. + SymqgOptions several; + several.max_degree = 48; + several.nbits = 16; + several.ef_construction = 0; + expect_error( + [&] { SymqgIndex(10, several); }, "Unsupported dimension for FhtKacRotator" + ); + expect_error( + [&] { SymqgIndex(kDim, several); }, "max_degree must be a positive multiple of 32" + ); + several.max_degree = 32; + expect_error( + [&] { SymqgIndex(kDim, several); }, "nbits must be 4, 8, or 32" + ); +} + +TEST(SymqgIndexTest, 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 SymqgIndex index(kDim); + ASSERT_TRUE(index.seed().has_value()); + seeds.insert(*index.seed()); + } + EXPECT_GT(seeds.size(), 1U); +} + +TEST(SymqgIndexTest, AddBuildsTheGraphWithTheConstructorSettings) { + const auto data = gaussian(kNumPoints, 1); + SymqgOptions defaults; + defaults.seed = 5; + SymqgOptions quantized; + quantized.metric = METRIC_COSINE; + quantized.nbits = 4; + quantized.max_degree = 64; + quantized.ef_construction = 40; + quantized.init = QGInitialization::Random; + quantized.seed = 9; + SymqgOptions eight_bits; + eight_bits.metric = METRIC_IP; + eight_bits.nbits = 8; + eight_bits.ef_construction = 30; + eight_bits.seed = 2; + for (const auto& settings : {defaults, quantized, eight_bits}) { + SCOPED_TRACE(settings.nbits); + SymqgIndex index(kDim, settings); + EXPECT_EQ(index.add(data.data(), kNumPoints, 1), 0); + EXPECT_EQ(index.num_points(), kNumPoints); + EXPECT_EQ(index.num_stored_points(), kNumPoints); + + // The file records every setting, so equal bytes mean they were all forwarded. + symqg::QuantizedGraph graph( + kNumPoints, + kDim, + settings.max_degree, + settings.metric, + RotatorType::FhtKacRotator, + settings.nbits == 32 ? 0 : settings.nbits, + *settings.seed + ); + symqg::QGBuilder( + graph, + static_cast(settings.ef_construction), + data.data(), + 1, + settings.init, + *settings.seed + ) + .build(); + const rabitq_test::TempFile file("symqg_index_reference.index"); + graph.save(file.path().c_str()); + EXPECT_EQ(saved_bytes(index, "symqg_index_built.index"), file_bytes(file.path())); + } +} + +TEST(SymqgIndexTest, AddBuildsOnlyOnce) { + const auto data = gaussian(kNumPoints, 2); + SymqgIndex index(kDim, options(3)); + expect_error( + [&] { index.add(nullptr, kNumPoints); }, "SymqgIndex add data must not be null" + ); + index.add(data.data(), kNumPoints, 1); + const auto before = search(index, data.data(), 2, 5); + const std::string message = + "SymqgIndex does not support incremental addition; create a new index and add " + "all vectors at once"; + expect_error([&] { index.add(data.data(), 50); }, message); + expect_error([&] { index.add(nullptr, 0); }, message); + EXPECT_EQ(index.num_points(), kNumPoints); + EXPECT_EQ(search(index, data.data(), 2, 5).ids, before.ids); +} + +TEST(SymqgIndexTest, FailedAddLeavesTheIndexWithoutAGraph) { + auto data = gaussian(kNumPoints, 3); + SymqgIndex index(kDim, options(4)); + const std::string too_few = + "QuantizedGraph degree bound must be smaller than the number of points"; + expect_error([&] { index.add(data.data(), 32, 1); }, too_few); + expect_error([&] { index.add(nullptr, 0); }, too_few); + // This failure comes after the new graph exists. + data[7 * kDim + 1] = std::numeric_limits::quiet_NaN(); + expect_error( + [&] { index.add(data.data(), kNumPoints, 1); }, + "QuantizedGraph build data must contain only finite values" + ); + EXPECT_EQ(index.num_points(), 0U); + Id ids[1]; + expect_error( + [&] { index.search(data.data(), 1, 1, ids, nullptr); }, + "SymqgIndex has no vectors; add them or load an index before search" + ); + data[7 * kDim + 1] = 0.5F; + EXPECT_EQ(index.add(data.data(), kNumPoints, 1), 0); + EXPECT_EQ(index.num_points(), kNumPoints); +} + +TEST(SymqgIndexTest, OperationsBeforeAddThrowLogicError) { + const auto data = gaussian(4, 4); + const SymqgIndex index(kDim, options(1)); + const rabitq_test::TempFile file("symqg_index_unbuilt.index"); + Id ids[1]; + const auto message = [](const std::string& operation) { + return "SymqgIndex has no vectors; add them or load an index before " + operation; + }; + expect_error( + [&] { index.search(data.data(), 1, 1, ids, nullptr); }, message("search") + ); + // The state is checked before the arguments. + expect_error( + [&] { index.search(data.data(), 1, 0, nullptr, nullptr); }, message("search") + ); + expect_error( + [&] { index.save(file.path().c_str()); }, message("save") + ); + EXPECT_FALSE(std::filesystem::exists(file.path())); +} + +TEST(SymqgIndexTest, TrainOnlyChecksItsInput) { + auto data = gaussian(kNumPoints, 5); + const SymqgIndex index(kDim, options(1)); + index.train(data.data(), kNumPoints); + index.train(nullptr, 0); + EXPECT_EQ(index.num_points(), 0U); + expect_error( + [&] { index.train(nullptr, 1); }, "SymqgIndex train data must not be null" + ); + data[(kNumPoints - 1) * kDim + 3] = std::numeric_limits::infinity(); + expect_error( + [&] { index.train(data.data(), kNumPoints); }, + "SymqgIndex train data must contain only finite values" + ); + data[(kNumPoints - 1) * kDim + 3] = 1e30F; + expect_error( + [&] { index.train(data.data(), kNumPoints); }, + "SymqgIndex train data exceeds the safe float32 coordinate range" + ); +} + +TEST(SymqgIndexTest, DefaultEfSearchIsMaxOfKAnd64AndSmallerValuesAreRaisedToK) { + constexpr size_t kMany = 4000; + const auto data = gaussian(kMany, 6); + SymqgOptions weak = options(3); + weak.ef_construction = 8; + weak.init = QGInitialization::Random; + SymqgIndex index(kDim, weak); + index.add(data.data(), kMany, 1); + const auto queries = gaussian(200, 7); + 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, and a smaller breadth is raised to k. + EXPECT_EQ(with(std::nullopt, 100).ids, with(100, 100).ids); + EXPECT_EQ(with(5, 10).ids, with(10, 10).ids); + EXPECT_EQ(with(1, 10).distances, with(10, 10).distances); +} + +TEST(SymqgIndexTest, SearchRejectsZeroBreadthAndInvalidK) { + const auto data = gaussian(kNumPoints, 8); + SymqgIndex index(kDim, options(1)); + index.add(data.data(), kNumPoints, 1); + 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); }, + "SymqgIndex search ids must not be null" + ); + index.search(data.data(), 0, 1, nullptr, nullptr); // an empty batch does nothing +} + +TEST(SymqgIndexTest, SearchPadsMissingResults) { + constexpr size_t kFew = 40; + const auto data = gaussian(kFew, 9); + SymqgIndex index(kDim, options(1)); + index.add(data.data(), kFew, 1); + constexpr size_t kK = kFew + 5; + const auto padded = search(index, data.data(), 2, kK); + for (size_t query = 0; query < 2; ++query) { + std::set found; + for (size_t j = 0; j < kK; ++j) { + const Id id = padded.ids[(query * kK) + j]; + const float distance = padded.distances[(query * kK) + j]; + if (j < kFew) { + EXPECT_TRUE(id >= 0 && id < static_cast(kFew)); + EXPECT_TRUE(std::isfinite(distance)); + found.insert(id); + } else { + EXPECT_EQ(id, kNoId); + EXPECT_TRUE(std::isinf(distance) && distance > 0); + } + } + EXPECT_EQ(found.size(), kFew); + } + std::vector ids_only(2 * kK, 0); + index.search(data.data(), 2, kK, ids_only.data(), nullptr); + EXPECT_EQ(ids_only, padded.ids); +} + +TEST(SymqgIndexTest, SaveAndLoadKeepSettingsSeedAndResults) { + const auto data = gaussian(kNumPoints, 10); + SymqgOptions configured = options(21); + configured.metric = METRIC_COSINE; + configured.nbits = 8; + configured.ef_construction = 50; + configured.init = QGInitialization::Random; + SymqgIndex index(kDim, configured); + index.add(data.data(), kNumPoints, 1); + + const rabitq_test::TempFile file("symqg_index_round_trip.index"); + index.save(file.path().c_str()); + SymqgIndex loaded = SymqgIndex::load(file.path().c_str()); + EXPECT_TRUE(loaded.is_trained()); + EXPECT_EQ(loaded.dim(), kDim); + EXPECT_EQ(loaded.nbits(), 8U); + EXPECT_EQ(loaded.max_degree(), 32U); + EXPECT_EQ(loaded.metric(), METRIC_COSINE); + EXPECT_EQ(loaded.ef_construction(), std::optional(50)); + EXPECT_EQ(loaded.init(), std::optional(QGInitialization::Random)); + EXPECT_EQ(loaded.seed(), std::optional(21)); + EXPECT_EQ(loaded.num_points(), kNumPoints); + 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); + expect_error( + [&] { loaded.add(data.data(), kNumPoints); }, + "SymqgIndex does not support incremental addition; create a new index and add " + "all vectors at once" + ); +} + +TEST(SymqgIndexTest, LoadsFilesWithoutASeedOrConstructionSettings) { + // Releases up to 0.8 recorded neither. + const auto path = + std::filesystem::path(RABITQ_TEST_FIXTURE_ROOT) / "v0.8.3" / "qg4_l2.index"; + const SymqgIndex old = SymqgIndex::load(path.string().c_str()); + EXPECT_FALSE(old.seed().has_value()); + EXPECT_FALSE(old.ef_construction().has_value()); + EXPECT_FALSE(old.init().has_value()); + EXPECT_TRUE(old.is_trained()); + EXPECT_EQ(old.nbits(), 4U); + EXPECT_EQ(old.metric(), METRIC_L2); + EXPECT_EQ(old.max_degree(), 32U); + EXPECT_EQ(old.dim(), 65U); + ASSERT_GT(old.num_points(), 0U); + const std::vector query(old.dim(), 0.5F); + Id ids[1]; + old.search(query.data(), 1, 1, ids, nullptr); + EXPECT_TRUE(ids[0] >= 0 && ids[0] < static_cast(old.num_points())); + + // A graph of raw vectors reports 32 bits. + const SymqgIndex raw = SymqgIndex::load( + (std::filesystem::path(RABITQ_TEST_FIXTURE_ROOT) / "v0.8.3" / "qg0_ip.index") + .string() + .c_str() + ); + EXPECT_EQ(raw.nbits(), 32U); + EXPECT_EQ(raw.metric(), METRIC_IP); +} + +TEST(SymqgIndexTest, MovedIndexKeepsItsState) { + const auto data = gaussian(kNumPoints, 11); + SymqgIndex index(kDim, options(4)); + index.add(data.data(), kNumPoints, 1); + const auto expected = search(index, data.data(), 2, 5); + SymqgIndex moved(std::move(index)); + EXPECT_EQ(search(moved, data.data(), 2, 5).ids, expected.ids); + SymqgIndex assigned(kDim, options(1)); + assigned = std::move(moved); + EXPECT_EQ(assigned.seed(), std::optional(4)); + EXPECT_EQ(assigned.num_points(), kNumPoints); + EXPECT_EQ(search(assigned, data.data(), 2, 5).ids, expected.ids); +} + +} // namespace +} // namespace rabitqlib