diff --git a/.clang-tidy b/.clang-tidy index 6ec0d237..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 @@ -65,7 +67,7 @@ CheckOptions: readability-identifier-naming.StructIgnoredRegexp: '^rebind$' readability-identifier-naming.EnumCase: CamelCase readability-identifier-naming.EnumConstantCase: CamelCase - readability-identifier-naming.EnumConstantIgnoredRegexp: '^(METRIC_L2|METRIC_IP|RECONSTRUCTION|UNBIASED_ESTIMATION|PLAIN)$' + readability-identifier-naming.EnumConstantIgnoredRegexp: '^(METRIC_L2|METRIC_IP|METRIC_COSINE|RECONSTRUCTION|UNBIASED_ESTIMATION|PLAIN)$' readability-identifier-naming.TypeAliasCase: CamelCase readability-identifier-naming.TypeAliasIgnoredRegexp: '^(value_type|pointer|reference|difference_type|iterator_category|is_always_equal|other|maxheap|minheap|ex_ipfunc)$' readability-identifier-naming.TypedefCase: CamelCase diff --git a/.github/release.yml b/.github/release.yml index 98db5107..a393bb93 100644 --- a/.github/release.yml +++ b/.github/release.yml @@ -5,6 +5,10 @@ changelog: - invalid categories: + - title: Breaking changes + labels: + - release:breaking + - title: Added labels: - release:added diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index b2526230..2e6f10ea 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -4,7 +4,7 @@ on: push: branches: ["main", "master"] pull_request: - branches: ["main", "master"] + branches: ["main", "master", "dev/0.9"] concurrency: group: ${{ github.event.pull_request.number || github.sha }}-${{ github.workflow }} diff --git a/CMakeLists.txt b/CMakeLists.txt index eb24ddd3..35f155e6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.20) -project(RaBitQLib VERSION 0.8.5 LANGUAGES CXX) +project(RaBitQLib VERSION 0.9.0 LANGUAGES CXX) include(CMakePackageConfigHelpers) include(GNUInstallDirs) @@ -84,6 +84,7 @@ endfunction() set(RABITQ_CORE_SOURCES src/core/api.cpp + src/core/blob.cpp src/core/fast_scale_table.cpp src/core/provisional.cpp src/utils/cpu_features.cpp @@ -247,12 +248,16 @@ if(RABITQ_BUILD_FASTSCAN) endif() 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 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 @@ -261,6 +266,10 @@ if(RABITQ_BUILD_INDEX) ) add_library(rabitqlib::index ALIAS rabitq_index) target_link_libraries(rabitq_index PUBLIC rabitq_fastscan) + # Index files record the library version that wrote them. + target_compile_definitions(rabitq_index PRIVATE + RABITQ_LIBRARY_VERSION="${PROJECT_VERSION}" + ) set_target_properties(rabitq_index PROPERTIES EXPORT_NAME index POSITION_INDEPENDENT_CODE ON @@ -317,7 +326,8 @@ configure_package_config_file( write_basic_package_version_file( "${CMAKE_CURRENT_BINARY_DIR}/rabitqlibConfigVersion.cmake" VERSION "${PROJECT_VERSION}" - COMPATIBILITY SameMajorVersion + # Before 1.0 a minor release may break the API. + COMPATIBILITY SameMinorVersion ) install(EXPORT rabitqlibTargets FILE rabitqlibTargets.cmake diff --git a/README.md b/README.md index 5dffb2e7..5eef47fd 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ PyPI Python versions Documentation - License + License

@@ -27,28 +27,28 @@ approximate nearest-neighbor search. See the [research papers](https://vectordb- ## News +- **v0.9.0:** removes the Python forms 0.8 deprecated, saves index format 2, and adds + the cosine metric, `int64` IDs and C++ index classes that match the Python API + ([notes](https://vectordb-ntu.github.io/RaBitQ-Library/releases/0.9.0/)). - **v0.8.5:** accepts the names 0.9 will use (`capacity`, `routing`, `ef_search`, k-means `nbits`) and deprecates the 0.8 spellings they replace ([notes](https://vectordb-ntu.github.io/RaBitQ-Library/releases/0.8.5/)). - **v0.8.4:** input validation reads each batch once instead of twice ([notes](https://vectordb-ntu.github.io/RaBitQ-Library/releases/0.8.4/)). -- **v0.8.3:** provisional `rabitqlib.quant` module: rotate, quantize, pack and score - RaBitQ codes stored outside an index - ([notes](https://vectordb-ntu.github.io/RaBitQ-Library/releases/0.8.3/)). Earlier versions: [all releases](https://github.com/VectorDB-NTU/RaBitQ-Library/releases). ## Vector indexes Use the included indexes when you want construction, search, and save/load in one -library. All three support L2 and inner product; normalize vectors for cosine -search. Their structures, storage costs, and search parameters offer different +library. All three support L2, inner product and cosine, which normalizes vectors +for you. Their structures, storage costs, and search parameters offer different QPS–recall tradeoffs. | Index | Search approach | Storage and updates | | --- | --- | --- | | [IVF-RaBitQ](https://vectordb-ntu.github.io/RaBitQ-Library/index/ivf/) | Partitioned search with batch scoring. | 1–9-bit codes or raw-vector reranking; add/remove. | -| [HNSW-RaBitQ](https://vectordb-ntu.github.io/RaBitQ-Library/index/hnsw/) | Graph traversal over quantized vectors. | 1–9-bit codes plus graph edges; add/remove and resize. | +| [HNSW-RaBitQ](https://vectordb-ntu.github.io/RaBitQ-Library/index/hnsw/) | Graph traversal over quantized vectors. | 1–9-bit codes plus graph edges; add/remove and reserve. | | [SymphonyQG](https://vectordb-ntu.github.io/RaBitQ-Library/index/qg/) | Graph search with batched distance estimation. | Raw or 4/8-bit storage; updates require rebuilding. | [Native clustering methods](https://vectordb-ntu.github.io/RaBitQ-Library/clustering/) prepare centroids and @@ -62,7 +62,7 @@ settings, and limitations. ### Python ```bash -python -m pip install --upgrade "rabitqlib>=0.8.5" +python -m pip install --upgrade "rabitqlib>=0.9.0" ``` Wheels support CPython 3.11–3.14 on Linux x86-64/ARM64, Windows x86-64, @@ -93,8 +93,8 @@ distance, with smaller values first. Without `nprobe`, search probes Quantization remains approximate even when all clusters are probed. The [complete quick start](https://vectordb-ntu.github.io/RaBitQ-Library/quick_start/) explains result handling, measures recall while varying `nprobe`, and shows save/load. Code written for -0.7 still runs in 0.8 with deprecation warnings; see the -[migration guide](https://vectordb-ntu.github.io/RaBitQ-Library/python_migration/). +0.8 may need changes for 0.9; see the +[migration guide](https://vectordb-ntu.github.io/RaBitQ-Library/python_migration/#from-08-to-09). For other indexes, see the [HNSW-RaBitQ](https://vectordb-ntu.github.io/RaBitQ-Library/index/hnsw/#minimal-workflow) and [SymphonyQG](https://vectordb-ntu.github.io/RaBitQ-Library/index/qg/#minimal-workflow) examples. @@ -159,7 +159,7 @@ listed above. VSAG logo
VSAG
- VectorChord logo
VectorChord
+ VectorChord logo
VectorChord
@@ -184,13 +184,13 @@ listed above. - LanceDB logo
LanceDB
+ LanceDB logo
LanceDB
Databricks logo
Databricks
- ClickHouse logo
ClickHouse
+ ClickHouse logo
ClickHouse
Qdrant logo
Qdrant
@@ -208,7 +208,7 @@ listed above. - [Documentation](https://vectordb-ntu.github.io/RaBitQ-Library/) and [algorithm overview](https://vectordb-ntu.github.io/RaBitQ-Library/rabitq/rabitq/). - [Papers and citations](https://vectordb-ntu.github.io/RaBitQ-Library/papers/) for the research behind the library. -- [Release notes](https://github.com/VectorDB-NTU/RaBitQ-Library/releases) and [0.7 migration guide](https://vectordb-ntu.github.io/RaBitQ-Library/modular_migration/). +- [Release notes](https://github.com/VectorDB-NTU/RaBitQ-Library/releases), the [Python migration guide](https://vectordb-ntu.github.io/RaBitQ-Library/python_migration/) and the [0.7 migration guide](https://vectordb-ntu.github.io/RaBitQ-Library/modular_migration/). - [GPU implementation](https://github.com/Stardust-SJF/cuvs_rabitq/tree/cuvs_ivf_rabitq) in cuVS. ## Contributing diff --git a/benchmarks/hotpaths/README.md b/benchmarks/hotpaths/README.md index 7b7a4bd4..0ffbf635 100644 --- a/benchmarks/hotpaths/README.md +++ b/benchmarks/hotpaths/README.md @@ -11,7 +11,7 @@ Enable `RABITQ_BUILD_BENCHMARKS=ON` in a Release build. Targets follow enabled c | `rabitq_core_hotpaths` | core only | One-bit compact encoding or raw L2 calls | | `rabitq_fastscan_hotpaths` | FastScan | Cached standard/HACC batch scoring | | `rabitq_load_hotpaths` | index | HNSW centroid-sidecar load and validation | -| `rabitq_ivf_add_hotpaths` | index | One IVF `add` call on a freshly loaded index | +| `rabitq_ivf_add_hotpaths` | index | One `IvfIndex::add` call on a freshly loaded index | | `rabitq_ids_benchmark` module + `ids.py` | Python bindings | Production cluster-ID conversion helper | No additional production dependencies are introduced. Core/FastScan benchmarks support @@ -66,7 +66,8 @@ the deterministic input. Original production indexes are not benchmark fixtures. - IVF add verifies the expected point counts and samples new points' self-neighbors outside the timed call, in addition to comparing output hashes across repetitions. - Inputs use an LCG with seed 42 (query/centroid seed 91 where applicable; IVF add uses - seed 91 for added points and seed 7 for centroids), metric L2. + seed 91 for added points and seed 7 for centroids), metric L2. IVF add fixes the + rotation seed at 42, so its hashes match across processes. Dimensions for encoding/scoring are multiples of 32. Use 64, 128 and 960 dimensions; encoding rows 32/4096 and threads 1/4 retain the cases from the original investigation. - Core encoding times the existing serial template at one thread and OpenMP template diff --git a/benchmarks/hotpaths/ivf_add.cpp b/benchmarks/hotpaths/ivf_add.cpp index de99b388..a0d1c690 100644 --- a/benchmarks/hotpaths/ivf_add.cpp +++ b/benchmarks/hotpaths/ivf_add.cpp @@ -1,4 +1,5 @@ -// Times one IVF::add() per repetition, each on a freshly loaded copy of the base index. +// Times one IvfIndex::add() per repetition, each on a freshly loaded copy of the base +// index. #include #include #include @@ -12,7 +13,7 @@ #include "common.hpp" #include "rabitqlib/core/metric.hpp" -#include "rabitqlib/index/ivf/ivf.hpp" +#include "rabitqlib/index/ivf_index.hpp" #include "rabitqlib/index/types.hpp" namespace { @@ -49,47 +50,58 @@ void run(int argc, char** argv) { const std::vector single_ids(add_n, rabitqlib::PID{0}); const rabitqlib::PID* add_cluster_ids = mode == "single" ? single_ids.data() : nullptr; + rabitqlib::AddOptions add_options; + add_options.num_threads = 1; { - rabitqlib::ivf::IVF base(base_n, dim, clusters, 4, rabitqlib::METRIC_L2); - base.construct(base_data.data(), centroids.data(), base_assigned.data(), false, 1); + rabitqlib::IvfOptions options; + options.nbits = 4; + options.seed = 42; // a fixed rotation keeps hashes comparable across processes + rabitqlib::IvfIndex base(dim, clusters, options); + base.set_centroids(centroids.data(), 1); + add_options.cluster_ids = base_assigned.data(); + base.add(base_data.data(), base_n, add_options); base.save(path.c_str()); } + add_options.cluster_ids = add_cluster_ids; + rabitqlib::IvfSearchOptions search_options; + search_options.nprobe = clusters; bench::metadata(dim, base_n, 1); const char* name = mode == "single" ? "add_single_cluster" : "add_routed"; uint64_t expected = 0; for (size_t rep = 0; rep <= reps; ++rep) { - rabitqlib::ivf::IVF index; - index.load(path.c_str()); + auto index = rabitqlib::IvfIndex::load(path.c_str()); const auto start = bench::Clock::now(); - index.add(add_data.data(), add_n, add_cluster_ids, false, 1); + index.add(add_data.data(), add_n, add_options); const double seconds = std::chrono::duration(bench::Clock::now() - start).count(); if (index.num_stored_points() != base_n + add_n || - index.num_points() != base_n + add_n || - index.max_elements() != base_n + add_n) { + index.num_points() != base_n + add_n) { throw std::runtime_error("add() did not append the requested points"); } // Validate known self-neighbors outside timing, independently of prior runs. for (size_t row = 0; row < std::min(add_n, size_t{3}); ++row) { - rabitqlib::PID id = rabitqlib::kPidMax; + rabitqlib::Id id = rabitqlib::kNoId; float distance = 0; - index.search(add_data.data() + row * dim, 1, clusters, &id, &distance); - if (id != base_n + row || !std::isfinite(distance)) { + index.search(add_data.data() + row * dim, 1, 1, &id, &distance, search_options); + if (id != static_cast(base_n + row) || + !std::isfinite(distance)) { throw std::runtime_error("Added point is not searchable with its new ID"); } } uint64_t h = 14695981039346656037ULL; - const size_t total = index.max_elements(); + const size_t total = index.num_stored_points(); h = bench::hash(&total, sizeof(total), h); const size_t k = std::min(size_t{10}, index.num_points()); - std::vector ids(k); + std::vector ids(k); std::vector distances(k); - index.search(base_data.data(), ids.size(), clusters, ids.data(), distances.data()); - h = bench::hash(ids.data(), ids.size() * sizeof(rabitqlib::PID), h); + index.search( + base_data.data(), 1, ids.size(), ids.data(), distances.data(), search_options + ); + h = bench::hash(ids.data(), ids.size() * sizeof(rabitqlib::Id), h); h = bench::hash(distances.data(), distances.size() * sizeof(float), h); if (rep == 0) { diff --git a/benchmarks/hotpaths/load.cpp b/benchmarks/hotpaths/load.cpp index 8e4d0de2..dc1c6c84 100644 --- a/benchmarks/hotpaths/load.cpp +++ b/benchmarks/hotpaths/load.cpp @@ -37,8 +37,11 @@ void run(int argc, char** argv) { if (!std::filesystem::exists(rabitqlib::io_impl::filesystem_path(path + ".hnsw"))) { rabitqlib::ivf::HNSWInitializer index(dim, count); index.add_vectors(data.data(), 1); - std::ofstream unused; - index.save(unused, path.c_str()); + std::ofstream output( + rabitqlib::io_impl::filesystem_path(path + ".hnsw"), std::ios::binary + ); + output.exceptions(std::ios::failbit | std::ios::badbit); + index.write(output); return; } } @@ -46,9 +49,19 @@ void run(int argc, char** argv) { uint64_t expected = 0; for (size_t rep = 0; rep <= reps; ++rep) { rabitqlib::ivf::HNSWInitializer index(dim, count); - std::ifstream unused; const auto start = bench::Clock::now(); - index.load(unused, path.c_str()); + // Open the graph file inside the timing, as loading an index does. + std::ifstream input( + rabitqlib::io_impl::filesystem_path(path + ".hnsw"), + std::ios::binary | std::ios::ate + ); + if (!input) { + throw std::runtime_error("Cannot open the HNSW centroid graph file"); + } + const auto bytes = + static_cast(static_cast(input.tellg())); + input.seekg(0); + index.read(input, bytes); const double seconds = std::chrono::duration(bench::Clock::now() - start).count(); uint64_t h = 14695981039346656037ULL; diff --git a/docs/development.md b/docs/development.md index 7bf6b9c2..983a9051 100644 --- a/docs/development.md +++ b/docs/development.md @@ -45,7 +45,10 @@ factors estimate L2 distance or inner product. | `include/rabitqlib/core/` | Per-vector encoding, query/estimation, rotation and per-vector byte layouts | | `include/rabitqlib/fastscan/` | All 32-vector batch layouts, encoding adapters, packing, LUT/estimation and FastScan/HACC | | `include/rabitqlib/core/types.hpp`, `core/detail/eigen.hpp` | Numerical configuration/types and internal Eigen aliases, respectively | -| `include/rabitqlib/index/types.hpp` | Point IDs and ANN candidate values; no Eigen dependency | +| `include/rabitqlib/index/types.hpp` | Point IDs, add 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 | @@ -462,7 +465,9 @@ parity against a saved pre-change build when changing those shared implementatio Keep `tests/fixtures/core_api_v1/consumer.cpp` unchanged when extending v1; add tests. Changes to v1 names, signatures, aggregate fields, enum values, buffer/code semantics -or allocation guarantees require an explicit API-major decision. The stable header +or allocation guarantees require an explicit API-major decision. Adding a `MetricType` +value that v1 rejects, as `METRIC_COSINE` does, is not such a change; keep v1's rejection +covered by `core_api_test.cpp`. The stable header must not expose Eigen, record maps, ANN or ISA-specific types. Workspace APIs must never silently allocate on the heap or spawn worker threads. @@ -505,12 +510,13 @@ in place of extra-bit codes. #### IVF formats and initialization -New IVF files have a magic/version header, an explicit padded dimension, and a resolved initializer type (v2); v1 files infer the historical -Flat/HNSW choice at 20,000 clusters, independently of current auto selection. -New IVF auto routing uses Flat below 5,000 clusters, Flat RaBitQ below 60,000, -and HNSW otherwise. Flat RaBitQ persists its mean and codes in the main file; -HNSW retains its sidecar. Legacy quantized files and raw v1 files infer -64-dimension padding. +New IVF files use index format 2 (`docs/formats.md`): the resolved initializer type +is in `ivf_params`, and the routing data, including the HNSW graph, is a section of +the one file. Earlier `RABQIDX1` v2 files store the initializer type; v1 files infer +the historical Flat/HNSW choice at 20,000 clusters, independently of current auto +selection. Those layouts keep HNSW routing in the `.hnsw` sidecar. New IVF auto +routing uses Flat below 5,000 clusters, Flat RaBitQ below 60,000, and HNSW otherwise. +Legacy quantized files and raw v1 files infer 64-dimension padding. #### Search defaults @@ -518,10 +524,18 @@ IVF search defaults to HACC for 4–9 bits and standard FastScan for 1–3 bits #### SymphonyQG storage -SymphonyQG supports raw storage (`quantization_bits == 0`) and quantized storage at 4 or 8 bits. +SymphonyQG supports raw storage (`quantization_bits == 0` in `QuantizedGraph`, `nbits == 32` in +`SymqgIndex` and Python) and quantized storage at 4 or 8 bits. ### Change an index API +The supported C++ index API is `IvfIndex`, `HnswIndex` and `SymqgIndex` in +`include/rabitqlib/index/*_index.hpp`, with the names, defaults and behaviour of the Python +classes, and their messages where those do not name Python values; the bindings wrap them. +`ivf::IVF`, `hnsw::HierarchicalNSW`, `symqg::QuantizedGraph` and `QGBuilder` stay installed for +these classes and for `QGAssigner`, without documentation or a compatibility promise. Samples and +docs use the supported classes. + Update the C++ declaration/implementation, the corresponding file in `python_bindings/`, Python type stubs, tests, samples, and the relevant page under `docs/docs/index/`. Preserve public signatures where possible; add a forwarding overload when evolving an API compatibly. Index construction @@ -532,7 +546,7 @@ and buffer changes must also preserve the [ID marker](#search-buffer-id-marker) Filesystem path strings are UTF-8 on Windows and native path bytes on POSIX. Use `io_impl::filesystem_path` from `utils/path.hpp` before opening files or querying -filesystem metadata, including IVF's HNSW sidecar. It converts UTF-8 to native Unicode +filesystem metadata, including the HNSW sidecar of earlier IVF files. It converts UTF-8 to native Unicode on Windows and preserves existing path bytes on Linux/macOS. For path-only changes, check path conversion and the affected I/O operations; the @@ -550,28 +564,40 @@ keep their provenance and hashes, and do not regenerate them with the current wr Index files are trusted input (see the usage guide): validate structure and sizes so that corrupt or mismatched files are reported before allocation, without treating a crafted file as a supported input. +Readers throw `rabitqlib::FormatError` (`include/rabitqlib/index/format_error.hpp`) for +any truncated, corrupt, mismatched or unsupported content, including errors raised by +shared validators while loading; only a file that cannot be opened throws a plain +`std::runtime_error`. Python maps it to `rabitqlib.FormatError`; rejection tests assert it. Do not silently reinterpret an old file. Add a magic/version discriminator, use fixed-width -serialized fields for new formats (the current IVF, HNSW and QG bodies still store several -`size_t` fields; change those only with a format version bump), validate sizes before -allocation, check every read, and retain a -compatibility test fixture or an explicit rejection path. Review each affected format; -changes to shared serialization helpers require auditing every format using them. -IVF-RaBitQ, HNSW-RaBitQ, and SymphonyQG have separate formats. SymphonyQG includes a versioned quantized format plus a legacy -raw-format fallback; preserve both unless a breaking change is explicitly requested. +serialized fields for new formats (earlier layouts store several `size_t` fields; keep their readers unchanged), validate sizes before allocation, check every +read, and retain a compatibility test fixture or an explicit rejection path. Review each affected +format; changes to shared serialization helpers require auditing every format using them. +Every index writes index format 2 ([`docs/formats.md`](formats.md#index-format-2), container in +`src/index/format2.*`) and still reads its earlier layouts: IVF-RaBitQ's `RABQIDX1` versions and +unversioned files, HNSW-RaBitQ's unversioned layout, and SymphonyQG's versioned quantized layout +and raw fallback. Preserve those readers unless a breaking change is explicitly requested. When a writer moves to +a new format, freeze the last files of the old writer as release-produced fixtures first. ### Change Python bindings Shared NumPy and string conversion helpers live in `python_bindings/bindings_common.hpp`. Register index-specific APIs in their own binding file and export public classes from `python_bindings/__init__.py`. Validate rank, dimensionality, state, and parameter ranges before -entering the core. Be deliberate about `py::array::forcecast`: it permits dtype/layout copies and +entering the core. A binding over a class that implements the Python workflow in C++, such as +`IvfIndex`, `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. C-contiguous NumPy storage is not necessarily aligned even to `alignof(T)`. `ensure_2d_array` copies misaligned inputs into an aligned owner; one-dimensional -ID conversion uses packed reads in `checked_cluster_ids` and `checked_removal_ids` -before narrowing to owned PID storage. Reuse these helpers rather than directly +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. @@ -582,6 +608,9 @@ conversion. Acquire and destroy guards with the GIL held, release the GIL only i their lifetime, and keep converted owners alive until reacquisition. Python wrappers use `IndexAccess` for concurrent reads and fail-fast exclusive updates. +Settings that Python changes through a returned reference, such as `cp`, take no guard: keep +them in the wrapper and copy them into the native index or the call's parameters with the GIL +and the write guard held before releasing the GIL. Extract native pointers before releasing the GIL and keep search parameters local to each call. C++ callers synchronize index mutations themselves. @@ -691,22 +720,24 @@ its upper and base layers use `upper_layer_max_degree_` and of 32. These settings are not interchangeable. Public names and Python keywords are compatibility contracts. For example, -`Cluster::num()`, the protected `Initializer::num_cluster_`, QG's -`degree_bound()`/`set_ef()` and `QGKMeansParameters::ef_build` -retain their existing spellings, as do the Python vocabulary `random_seed`/`seed`, -`train`/`build`, `obj`, `nsplit`, `final_obj` and `niter`. Python's search breadth is -`ef_search` since 0.8.5; `ef` is deprecated and removed in 0.9 (#232). Python's `QGKMeans` -and `QGKMeansParameters` take `nbits`, `max_degree` and `ef_construction` since 0.8.5; -`quantization_bits`, `graph_degree` and `ef_build` are deprecated there and removed in -0.9 (#233), while the C++ struct keeps them until 0.9. C++ parameter names may be clarified without -changing types, order or defaults. Keep declarations, definitions and comments -in agreement; do not rename methods or literals by textual substitution. +`Cluster::num()`, the protected `Initializer::num_cluster_`, QG's `degree_bound()` and its +`set_ef()`, which the installed `QGAssigner` calls, retain their existing spellings, as do the +Python vocabulary `seed`, `train`, `obj`, `nsplit`, `final_obj` and `niter`. Since 0.9, Python +spells each concept one way on the index and k-means classes: `ef_search`, +`ef_construction`, `max_degree`, `nbits` (32 for raw storage), `routing` and `capacity` +(#232, #233). The C++ index classes and `QGKMeansParameters` use the same names; the index +classes also take `Id` (`int64_t`) IDs with `kNoId` for an empty result slot, and +`num_threads == 0` for every available CPU, capped by `OMP_NUM_THREADS`. +`QGKMeansParameters` and `SymqgIndex` convert `nbits == 32` to the 0 that `QGAssigner` and +QG take as `quantization_bits`. C++ parameter names may be clarified without changing types, +order or defaults. Keep declarations, definitions and comments in agreement; do not rename +methods or literals by textual substitution. Storage-mode parameters also retain their contracts: IVF/HNSW use `nbits()` with separate internal `ex_bits_`; IVF additionally accepts 32 for raw-vector reranking. QG uses `quantization_bits()` with 0 for raw storage and 4/8 for packed -vectors. Naming work does not change these values, allocation sizes, numeric -operations, serialized field order, or ownership. +vectors; `SymqgIndex::nbits()` reports 32 for raw storage. Naming work does not change +these values, allocation sizes, numeric operations, serialized field order, or ownership. ### Numerical module variable names @@ -722,8 +753,9 @@ public and protected names, Python keywords, field order and numerical operation integer accumulation outputs. Retain `lut` in compact local kernels where its role is clear. - Clustering's private state uses `dim_`, `num_points_`, `num_clusters_`, - `num_workers_` and `data_`. Keep public `d`, `k`, `num_threads` and graph parameter - names compatible. The private graph iteration count is `graph_build_iterations_`. + `num_workers_` and `data_`. Keep public `d`, `k`, `num_threads` and the graph parameter + names (`ef_search`, `graph_build_iterations` and, since 0.9, `max_degree`, + `ef_construction` and `nbits`) compatible. The private graph iteration count is `graph_build_iterations_`. Per-point centroid IDs are `assignments` (arrays) and `cluster_id` (scalars); `label` stays reserved for HNSW's caller-visible labels. - FHT backend arguments use `rotated_data`, `padded_dim`, `trunc_dim` and @@ -844,15 +876,18 @@ Centroids, data, and queries compared by the same estimator must be in the same Rotator state is part of persisted index state. Loading an index must restore the exact rotation used at construction; generating a new random rotator produces silently incorrect distances. -Honor stored padded dimensions instead of recomputing them from current defaults. IVF `RABQIDX1` -v1 and v2 files explicitly store this field; preserve it for both versions. Only legacy unversioned +Honor stored padded dimensions instead of recomputing them from current defaults. Index format 2 +and IVF `RABQIDX1` v1 and v2 files explicitly store this field; preserve it. Only legacy unversioned quantized IVF files and old raw v1 files omit it and infer historical 64-dimension padding. Unreleased pad16 files whose stored dimension is not divisible by 32 are rejected. ### Distance conventions The library supports `METRIC_L2` and `METRIC_IP`. Some internal helpers represent inner-product -distance as `1 - dot_product`, and estimator correction terms differ between metrics. Do not reuse +distance as `1 - dot_product`, and estimator correction terms differ between metrics. +`METRIC_COSINE` exists only at the ANN index boundary: an index stores `METRIC_IP` internally, +normalizes inputs where they enter (`src/index/cosine.hpp`), and records the metric in its file. +Quantizers, FastScan, clustering and the IVF initializers keep rejecting it. Do not reuse an L2 norm/correction formula for IP merely because both paths compile. Test ordering and returned distance semantics separately. @@ -865,9 +900,8 @@ checked-bit manipulation independently. ### Ownership during construction Some index builders retain non-owning access to input vectors only during synchronous construction. -Do not extend such a pointer's lifetime without introducing explicit ownership. The HNSW Python -wrapper copies cluster IDs before calling the mutable C++ construction API; preserve that boundary -unless the C++ contract becomes const-correct. +Do not extend such a pointer's lifetime without introducing explicit ownership. The Python +wrappers pass `add` an owned, validated copy of the cluster IDs. ### Removal markers and search @@ -879,9 +913,9 @@ updates or persistence. These markers affect live search as well as saved files. IVF-RaBitQ `remove` stores a removed point as `f_add = +inf` inside the existing batch data, so it needs no discriminator. No index written before `remove` existed has an infinite `f_add`, so nothing in an old file is reinterpreted. In the legacy file formats readable by release 0.5.0, that reader also -excludes removed points. This compatibility of the removal marker does not extend to the current -writer's `RABQIDX1` v2 format: older releases cannot read current saves, even when resaving a loaded -legacy index. Keep this convention when touching IVF-RaBitQ code: +excludes removed points. This compatibility of the removal marker does not extend to index +format 2, which the current writer uses: releases up to 0.8 cannot read current saves, even when +resaving a loaded legacy index. Keep this convention when touching IVF-RaBitQ code: - Every estimator and scan path must turn `f_add = +inf` into an infinite estimated distance and an infinite lower bound, and never into NaN. A NaN distance would enter the result buffer. diff --git a/docs/docs/clustering.md b/docs/docs/clustering.md index 26f85ec7..ec3bbfe3 100644 --- a/docs/docs/clustering.md +++ b/docs/docs/clustering.md @@ -20,11 +20,12 @@ per centroid; the classes below default to training on every vector. | Class | Assignment | Recommended use | Cluster count | | --- | --- | --- | --- | | [RaBitQKMeans](#rabitqkmeans) | Flat RaBitQ scan | Small cluster counts | `n >= k >= 1` | -| [QGKMeans](#qgkmeans) | SymphonyQG centroid graph | Larger cluster counts | `n >= k > max_degree` (C++ `graph_degree`; default 32) | +| [QGKMeans](#qgkmeans) | SymphonyQG centroid graph | Larger cluster counts | `n >= k > max_degree` (default 32) | ## Python -Both classes have the same training and result interface: +Both classes have the same training and result interface. Here `x` is a float32 +array of shape `(n, d)` and `queries` one of shape `(m, d)`: ```python from rabitqlib import QGKMeans, RaBitQKMeans @@ -164,15 +165,14 @@ encodes new vectors around it. Each iteration compares every training point with every centroid. The batch size of 32 is not a cluster-count limit. This method uses one-bit point codes throughout; -it has no graph parameters or `nbits` (C++ `quantization_bits`) setting. +it has no graph parameters or `nbits` setting. ### QGKMeans QGKMeans builds a SymphonyQG graph over the centroids and uses previous -assignments as search hints. Its additional parameters are below, under their Python -names since 0.8.5. C++ and Python before 0.8.5 name the first three -`quantization_bits` (with `0` for raw storage), `graph_degree` and `ef_build`; in -Python those names still work, with a `DeprecationWarning`, until 0.9. +assignments as search hints. Its additional parameters are below; C++ and Python use +the same names. Before 0.9 the first three were `quantization_bits` (with `0` for raw +storage), `graph_degree` and `ef_build`. | Parameter | Default | Meaning | | --- | --- | --- | @@ -213,15 +213,15 @@ kmeans = RaBitQKMeans(d, 16, final_assignment="exact") kmeans.train(x) ``` -Python takes the strings `'approximate'` and `'exact'` since 0.8.5. The -`FinalAssignmentMode` members `Approximate`, `Exact` and the legacy alias `SymphonyQG` -are still accepted until 0.9, and `cp.final_assignment` reads back as a member -until then; importing `FinalAssignmentMode` raises a `DeprecationWarning`. +Python takes the strings `'approximate'` and `'exact'`, and `cp.final_assignment` +reads back as one of them. 0.9 removed the `FinalAssignmentMode` enum from the Python +package. In C++, set `parameters.final_assignment` to `rabitqlib::rabitqkmeans::FinalAssignmentMode::Exact` or `rabitqlib::qgkmeans::FinalAssignmentMode::Exact`; both names refer to the same -enum. Training still uses the selected approximate assignment algorithm. +enum, whose values are `Approximate` and `Exact` (0.9 removed the alias +`SymphonyQG`). Training still uses the selected approximate assignment algorithm. Exact final assignment screens all centroids with blocked GEMM and refines possible winners in float64; ties select the smallest centroid index. Returned diff --git a/docs/docs/cpp_integration.md b/docs/docs/cpp_integration.md index 686a490d..5d5cccdd 100644 --- a/docs/docs/cpp_integration.md +++ b/docs/docs/cpp_integration.md @@ -44,7 +44,9 @@ for Linux ARM64, Windows, and Apple Silicon. ## C++ examples ANN example executables are written to `bin/`. Their source demonstrates complete -indexing and querying workflows: +indexing and querying workflows with the index classes `IvfIndex`, `HnswIndex` and +`SymqgIndex` from `rabitqlib/index/ivf_index.hpp`, `hnsw_index.hpp` and +`symqg_index.hpp`, which `rabitqlib::index` provides: - [IVF-RaBitQ](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/sample/cpp/ivf_rabitq_indexing.cpp) - [HNSW-RaBitQ](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/sample/cpp/hnsw_rabitq_indexing.cpp) @@ -58,12 +60,12 @@ The core example is built as the `core_example` CMake target. For the GIST bench The [core quantization v1 API](rabitq/core_api.md) has a C++ source-compatibility contract. Other C++ APIs may evolve, and no cross-version C++ binary ABI is promised. -Pin the `v0.8.5` release and include RaBitQ-Library as a Git submodule: +Pin the `v0.9.0` release and include RaBitQ-Library as a Git submodule: ```bash git submodule add https://github.com/VectorDB-NTU/RaBitQ-Library.git third_party/rabitqlib git submodule update --init --recursive -git -C third_party/rabitqlib checkout v0.8.5 +git -C third_party/rabitqlib checkout v0.9.0 git add third_party/rabitqlib ``` @@ -105,6 +107,12 @@ find_package(rabitqlib CONFIG REQUIRED) target_link_libraries(my_program PRIVATE rabitqlib::index) ``` +To require a release, pass its version, for example +`find_package(rabitqlib 0.9 CONFIG REQUIRED)`. Before 1.0 a minor release may break the +API, so only the same minor release, at or above a requested patch, satisfies the request: +0.9.x does, 0.8 and 0.10 do not. A version range must stay within one minor release, for +example `0.9...<0.10`. + For a non-system prefix, point CMake to the installation: ```bash diff --git a/docs/docs/index.md b/docs/docs/index.md index 71a74a18..5546b06c 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -26,7 +26,7 @@ estimation into your own C++ search engine.

```bash -python -m pip install "rabitqlib>=0.8.5" +python -m pip install "rabitqlib>=0.9.0" ``` [Installation and supported platforms](installation.md) · @@ -36,7 +36,7 @@ python -m pip install "rabitqlib>=0.8.5" ## Choose your index -All three indexes support L2 and inner-product search, with save/load support. +All three indexes support L2, inner-product and cosine search, with save/load support. Start with IVF-RaBitQ for the complete introductory example, then compare on your own data.
@@ -112,5 +112,5 @@ on your own dataset when choosing an index. ## Explore further - [Algorithm overview](rabitq/rabitq.md) for the rotation, encoding, and scoring workflow. -- [RaBitQ Library 0.8.5 release notes](releases/0.8.5.md) for the latest changes and upgrade guidance. +- [RaBitQ Library 0.9.0 release notes](releases/0.9.0.md) for the latest changes and upgrade guidance. - [Papers and citations](papers.md) for the original RaBitQ method, its multi-bit extension, and SymphonyQG. diff --git a/docs/docs/index/hnsw.md b/docs/docs/index/hnsw.md index 10a93afa..5f5fe86c 100644 --- a/docs/docs/index/hnsw.md +++ b/docs/docs/index/hnsw.md @@ -1,6 +1,6 @@ # HNSW-RaBitQ -C++ callers include `rabitqlib/index/hnsw/hnsw.hpp` and link `rabitqlib::index`. +C++ callers include `rabitqlib/index/hnsw_index.hpp` and link `rabitqlib::index`. [HNSW](https://arxiv.org/abs/1603.09320) is a popular graph-based index. HNSW-RaBitQ combines HNSW graph traversal with RaBitQ quantization. Under comparable quantization settings, HNSW-RaBitQ typically uses more memory @@ -18,8 +18,8 @@ Run the [Quick start](../quick_start.md#build-and-search-an-ivf-index) to prepar ```python from rabitqlib import HnswIndex -index = HnswIndex(data.shape[1], M=16, ef_construction=100) # nbits=7 by default -index.add(data, num_threads=1) # trains 16 centroids, then links; 1 thread is reproducible +index = HnswIndex(data.shape[1], M=16, ef_construction=100, seed=7) # nbits=7 by default +index.add(data, num_threads=1) # trains 16 centroids, then links; a seed and 1 thread are reproducible ids, distances = index.search(queries, k=10) # ef_search defaults to max(k, 64) index.save("hnsw.index") loaded = HnswIndex.load("hnsw.index") @@ -30,60 +30,67 @@ The first `add` trains an untrained index on the added vectors, as for `num_clusters`, it trains one centroid per row, and `num_clusters` then reports the row count. An empty first `add` raises `RuntimeError`. `train` and `set_centroids` work as for [IVF-RaBitQ](ivf.md#training-centroids-in-python), -with `num_clusters` centroids (default 16) and always RaBitQKMeans; `index.cp` -starts from the same defaults with `seed`'s low 32 bits. The first `add` into the +with `num_clusters` centroids (default 16) and always RaBitQKMeans, but +`set_centroids` takes no `num_threads`; `index.cp` +starts from the same defaults with the index `seed`. The first `add` into the empty index links vectors with their exact coordinates, like the 0.7 `build`; later adds link through the stored codes (see [Recall after `add`](#recall-after-add)), so add most vectors in the first call. ### C++ -Link `rabitqlib::index`. Here `data`, `centroids` and `queries` are row-major -`std::vector` buffers with original dimension `dim`; `cluster_ids` is a -`std::vector` with one centroid ID per data row. Supply at least -ten points for this example. +`rabitqlib::HnswIndex` has the names, defaults and behaviour of the Python class. +Here `data` and `queries` are row-major `std::vector` buffers with +dimension `dim`. ```cpp #include -#include - -// Constructor order: capacity, dimension, total bits, M, ef_construction. -rabitqlib::hnsw::HierarchicalNSW index(data.size() / dim, dim, 4, 16, 100); -index.construct( - centroids.size() / dim, centroids.data(), data.size() / dim, data.data(), - cluster_ids.data(), 1 -); -auto results = index.search(queries.data(), queries.size() / dim, 10, 100, 1); +#include + +rabitqlib::HnswOptions options; // set the fields by name; nbits is 7 by default +options.ef_construction = 100; +options.seed = 7; +rabitqlib::HnswIndex index(dim, options); +rabitqlib::AddOptions add_options; +add_options.num_threads = 1; // with the seed, a reproducible graph +index.add(data.data(), data.size() / dim, add_options); // trains 16 centroids, then links + +const size_t num_queries = queries.size() / dim; +std::vector ids(num_queries * 10); +std::vector distances(num_queries * 10); +index.search(queries.data(), num_queries, 10, ids.data(), distances.data()); index.save("hnsw.index"); -rabitqlib::hnsw::HierarchicalNSW loaded; -loaded.load("hnsw.index"); +auto loaded = rabitqlib::HnswIndex::load("hnsw.index"); ``` -C++ results are per-query vectors of `(distance, ID)` pairs. For build setup, -see [C++ integration](../cpp_integration.md). +For build setup, see [C++ integration](../cpp_integration.md). ## Parameters and limits | Parameter | Contract | | --- | --- | -| `dim` | Original input dimension; Python supports 64–65,536 and pads internally. | -| `nbits` / C++ `total_bits` | 1–9 total bits including the sign bit. Python's keyword-only `nbits` defaults to 7; C++ requires it. Raw-vector storage is not supported. | -| `num_clusters` | Python keyword, default 16: centroids `train` or the first `add` learns, or `set_centroids` supplies; the first `add` caps it at its row count. | -| `M`, `ef_construction` | Graph connectivity and construction search budget; Python defaults are 16 and 200, and the index reports both as properties. `M` must be at least 2 and is capped at 10,000; `ef_construction` is raised to at least `M`. The base layer keeps up to `2 * M` edges per node. | -| `metric`, `seed` | Python defaults are `"l2"` and 100; `"ip"` is also supported. `seed` was called `random_seed` before 0.8. A seed is in `[0, 2**32 - 1]`; larger values are deprecated since 0.8.5, and 0.9 draws a seed when it is omitted. | -| `capacity` (C++ `max_elements()`) | Python reports the current capacity, which `add` grows geometrically (at least doubling) and `reserve` can preallocate; they were named `max_elements` and `resize` before 0.8.5. C++ `add` never grows it. | -| `k`, `ef_search` | Positive result count and search window. `k` may exceed the stored point count; Python pads missing results, while C++ returns fewer pairs. An omitted or `None` `ef_search` uses `max(k, 64)` in Python (0 does the same and is deprecated since 0.8.5), a smaller value is raised to at least `k`, and a value above the stored point count is clamped to it. Python named it `ef` before 0.8.5. | +| `dim` | Original input dimension, 64–65,536; the index pads internally. | +| `nbits` | 1–9 total bits including the sign bit; defaults to 7. Raw-vector storage is not supported. | +| `num_clusters` | Default 16: centroids `train` or the first `add` learns, or `set_centroids` supplies; the first `add` caps it at its row count. | +| `M`, `ef_construction` | Graph connectivity and construction search budget; defaults are 16 and 200, and the index reports both. `M` must be at least 2 and is capped at 10,000; `ef_construction` is raised to at least `M`. The base layer keeps up to `2 * M` edges per node. | +| `metric`, `seed` | `metric` defaults to L2 (Python `"l2"`); inner product and [cosine](usage.md#the-cosine-metric) are also supported. `seed` is the graph and rotation seed in `[0, 2**32 - 1]` and the initial `cp.seed`. The default (Python `None`, an empty C++ `std::optional`) draws one at random (it was 100 before 0.9); `seed` reports it. | +| `capacity` | The current capacity, which `add` grows geometrically (at least doubling) and `reserve` can preallocate; in Python they replace `max_elements` and `resize`, which 0.9 removed. | +| `k`, `ef_search` | Result count, from 1 to 2^31, and search window. `k` may exceed the stored point count; missing results are padded with ID `-1` (C++ `kNoId`) and `+inf`. An omitted `ef_search` (Python `None`) uses `max(k, 64)`, an explicit 0 raises `ValueError` (C++ `std::invalid_argument`), a smaller value is raised to at least `k`, and a value above the stored point count is clamped to it. It replaces `ef`, which 0.9 removed. | + +In C++, the construction settings are fields of `HnswOptions`, and `ef_search` +and `num_threads` fields of `GraphSearchOptions`. `seed` controls graph levels and the FHT/Kac rotation (using its low 32 bits). With identical inputs and parameters, single-threaded construction is reproducible -within the same build environment. Python `train` and `add` default to every -available CPU, so **default builds are not reproducible**: pass `num_threads=1` to -`add` when you need the same graph again. Different toolchains or SIMD backends can +within the same build environment. A seed is drawn unless one is given, and +`train` and `add` default to every available CPU, so **default builds are not +reproducible**: pass a seed to the constructor and one thread to `add` when you +need the same graph again. Different toolchains or SIMD backends can still change results. Loading restores the saved rotation. Results use squared L2 or `1 - dot` estimates, ordered from smallest to largest. -Python fills missing results with ID `2**32 - 1` and distance `+inf`; C++ returns -only the available pairs. See [result handling](../quick_start.md#read-the-results) +IDs are `int64` (C++ `rabitqlib::Id`), and missing results hold ID `-1` and distance +`+inf`. See [result handling](../quick_start.md#read-the-results) and the shared [input, count and concurrency contracts](usage.md). ## Index construction @@ -94,121 +101,110 @@ the links, centroids, cluster IDs, labels, RaBitQ codes, and factors rather than a copy of the raw dataset. Total bit widths from 1 through 9 are supported. -`construct()` is synchronous. Keep its input buffers valid for the entire call; -the index retains no pointers to them after it returns or throws. The borrowed -input pointer and search candidate helpers are private implementation details; -see the [C++ migration guide](../modular_migration.md#public-and-implementation-interfaces). +`add` is synchronous. Keep its input buffers valid for the entire call; the +index retains no pointers to them after it returns or throws. + +To build from centroids computed elsewhere, for example by +[RaBitQKMeans](../clustering.md#rabitqkmeans), set them and pass each vector's +cluster: ```cpp -void HierarchicalNSW::construct( - size_t num_clusters, - const float* centroids, - size_t num_points, - const float* data, - PID* cluster_ids, - size_t num_threads = std::numeric_limits::max(), - bool fast_quantization = false -); +rabitqlib::HnswOptions options; +options.num_clusters = num_clusters; +rabitqlib::HnswIndex index(dim, options); +index.set_centroids(centroids.data()); +rabitqlib::AddOptions add_options; +add_options.cluster_ids = cluster_ids.data(); +index.add(data.data(), num_points, add_options); ``` -- **data**: Vectors in the original input coordinates. -- **num_points**: The number of data vectors. -- **centroids**: Centroids computed by [RaBitQKMeans](../clustering.md#rabitqkmeans); the examples use `num_clusters = 16`. -- **cluster_ids**: Array of length `num_points`; every entry must be in the range `[0, num_clusters)`. -- **num_threads**: Number of threads to use (default: every available thread; `0` also auto-selects). +- **centroids**: `num_clusters` centroids in the original input coordinates; the examples use 16. +- **cluster_ids**: One entry per vector, each in `[0, num_clusters)`. +- **num_threads**: Worker count; no value, the default, uses every available CPU, and `0` also auto-selects. - **fast_quantization**: Use calibrated scaling instead of per-vector scale search; see [encoding paths](../rabitq/quantizer.md#implementations). ### Training centroids in C++ -Instead of passing centroids to `construct`, train or set them on an empty -index, then add the points: +`HnswIndex` trains as the Python class does. `cp()` returns the training +settings; include `rabitqlib/clustering/rabitqkmeans.hpp` to change them: ```cpp -#include -#include +#include +#include -rabitqlib::hnsw::HierarchicalNSW index(max_elements, dim, 4, 16, 200); -index.train(16, num_points, data.data(), - rabitqlib::default_training_parameters(rabitqlib::METRIC_L2, 100)); -// Or supply centroids: index.set_centroids(num_clusters, centroids.data()); +rabitqlib::HnswIndex index(dim); +index.cp().niter = 20; +index.train(sample.data(), num_samples); // no thread count: cp().num_threads +// Or supply centroids: index.set_centroids(centroids.data()); index.add(data.data(), num_points); ``` -- `train(num_clusters, num_points, data, cp)` trains centroids with - [RaBitQKMeans](../clustering.md#rabitqkmeans); `num_points` must be at least - `num_clusters`. Points are assigned by `add`, not by training. See the - [IVF-RaBitQ defaults](ivf.md#training-centroids-in-c) for - `default_training_parameters`. -- The first `add` into an empty graph links points with their exact vectors, as - `construct` does; with one thread it produces the same index as `construct` - with the same centroids and cluster IDs. If it fails, the graph is left empty - and the centroids are kept. Later adds link through the stored codes; see +- `train`, `set_centroids` and the first `add` follow the Python rules above. + Training always uses [RaBitQKMeans](../clustering.md#rabitqkmeans); points are + assigned by `add`, not by training. +- The first `add` into an empty graph links points with their exact vectors. If + it fails, the graph is left empty. Centroids set by `train` or `set_centroids` + are kept, and a first `add` that trained leaves the index untrained. Later adds link + through the stored codes; see [how added points are linked](#how-added-points-are-linked). -- `train` and `set_centroids` replace the centroids only while the index stores - no points, removed ones included; otherwise they throw `std::logic_error`. - A failed call leaves the index unchanged. `construct` needs an untrained index, - so after either call it throws `std::logic_error`; use `add` instead. -- `is_trained()` reports whether centroids are set. Before that, `add` throws - `std::logic_error`; searching an empty index, trained or not, returns no results. -- `save` throws `std::logic_error` for an index without stored points, trained - or not. Earlier releases saved an untrained empty index; such files still load. +- Arguments outside their range throw `std::invalid_argument` (Python + `ValueError`), and a call in the wrong state throws `std::logic_error` (Python + `RuntimeError`), with the Python messages except where those name Python values + such as `None`. +- `is_trained()` reports whether centroids are set. A trained index without + points pads every `search` result slot with `kNoId` and `+inf`; `save` throws + `std::logic_error` until the index stores at least one point. Earlier + releases saved an untrained empty index; such files still load, and without a + recorded seed they need `train` or `set_centroids` before `add`. ## Querying ```cpp -std::vector>> HierarchicalNSW::search( +void HnswIndex::search( const float* queries, size_t num_queries, size_t k, - size_t ef_search, - size_t num_threads -); + Id* ids, + float* distances, + const GraphSearchOptions& options = {} +) const; ``` -- **queries**: Query vectors in the original input coordinates. -- **num_queries**: The number of query vectors. +- **queries**: `num_queries` query vectors in the original input coordinates. - **k**: The number of nearest neighbors to search. -- **ef_search**: The size of the candidate set for searching HNSW-RaBitQ base layer. -- **num_threads**: Number of threads to use. Each query is processed by one thread. +- **ids**, **distances**: Output buffers of `num_queries * k` values; `distances` may be `nullptr`. +- **options.ef_search**: The size of the candidate set for searching the base layer. +- **options.num_threads**: Number of threads to use (default 1). Each query is processed by one thread. -The search window belongs to each call, so concurrent C++ searches can use +The search window belongs to each call, so concurrent searches can use different `ef_search` values and separate outputs while the index is unchanged. -Python follows the shared [concurrency contract](usage.md#threading-and-file-paths). +See the shared [concurrency contract](usage.md#threading-and-file-paths). ## Updating an index -A constructed or loaded index supports `add()`, `resize()` (Python `reserve`), -and `remove()` without the original data; C++ also adds to a -[trained](#training-centroids-in-c) index. Adding points and resizing preserve -the index file format; files with removals have -[compatibility restrictions](#how-removal-is-stored). +A trained index supports `add()`, `reserve()` and `remove()` without the original +data. Every loaded index is trained, except one loaded from a file saved before +training (see below). `save` always writes index format 2; see +[persistence](#persistence). ```c++ -std::vector HierarchicalNSW::add( - const float* data, - size_t num_points, - const PID* cluster_ids = nullptr, - bool fast_quantization = false, - size_t num_threads = 1 -); - -void HierarchicalNSW::resize(size_t new_max_elements); +Id HnswIndex::add(const float* data, size_t num_points, const AddOptions& options = {}); + +void HnswIndex::reserve(size_t num_points); ``` - **data**, **num_points**: `num_points` new vectors in the original coordinates. Vector `i` receives - the label `num_stored_points() + i`, so labels stay dense, and `add` returns them. -- **cluster_ids**: The cluster of each new vector, in `[0, num_clusters)`. When it + the ID `num_stored_points() + i`, so IDs stay dense; `add` returns the first. +- **options.cluster_ids**: The cluster of each new vector, in `[0, num_clusters)`. When it is `nullptr`, each vector goes to its nearest centroid, chosen the same way a query is routed. -- **fast_quantization**, **num_threads**: Same meaning as in `construct`, but `add` defaults - to one thread, which keeps the resulting links deterministic; pass `0` to auto-select. A point keeps the label - `num_stored_points() + i` whatever order the threads finish in, because the slots are - reserved as one block before the inserts start. -- **new_max_elements**: The new capacity. It must be at least `num_stored_points()`. - In C++, initialize the index through its parameterized constructor or `load` - before calling `resize`. +- **options.fast_quantization**, **options.num_threads**: As in [index construction](#index-construction). + With more than one thread the links vary between runs; one thread keeps them + deterministic. A point keeps the ID `num_stored_points() + i` whatever order the + threads finish in, because the slots are reserved as one block before the inserts start. +- **num_points** of `reserve`: The capacity to preallocate; a smaller value changes nothing. -In Python, `add` grows the capacity when needed: +In Python, with `vectors` a float32 array of new vectors of shape `(n, index.dim)`: ```python new_ids = index.add(vectors) # route to the nearest centroids @@ -221,7 +217,7 @@ Updates require exclusive access; see the `add` prepares the result IDs, quantized vectors, and link-list allocations before changing the graph or point count. A failure during preparation leaves those -unchanged. A failure during graph linking can leave the batch counted in +unchanged. A failure while linking a later batch can leave it counted in `num_stored_points()` with only some points reachable through the graph. The index remains safe to search, save, load, and destroy; inspect `num_stored_points()` before retrying, or rebuild to restore full reachability. @@ -231,15 +227,13 @@ retrying, or rebuild to restore full reachability. See the shared [index count contract](usage.md#index-counts). Removed records still occupy capacity. -C++ `add` never grows the index: it rejects a whole batch whose size exceeds -`max_elements() - num_stored_points()`, and `resize` is the only way to raise -that. Python `add` grows the capacity first when the batch does not fit, to at least -double it, and `reserve(num_points)` preallocates it (since 0.8.5; `resize` still works, -with a `DeprecationWarning`, until 0.9, and `capacity` replaces `max_elements`). Reserving capacity avoids reallocating and copying the whole base-layer record storage during `add`. +`add` grows the capacity first when the batch does not fit, to at least +double it, and `reserve(num_points)` preallocates it; `reserve` never shrinks the +capacity. Reserving capacity avoids reallocating and copying the whole base-layer record storage during `add`. It does not make insertion allocation-free: batch scratch, upper-layer link lists, and label-map entries still require allocations, and the label map may rehash. -`resize` rebuilds the base-layer storage and copies it, so it needs memory for +Growing the capacity rebuilds the base-layer storage and copies it, so it needs memory for both copies while it runs and costs time proportional to the whole index. It invalidates every pointer into the index. The per-node upper-layer link lists are not copied, only their pointer table. @@ -255,12 +249,12 @@ of a rebuild. ### Removing points ```c++ -size_t HierarchicalNSW::remove(const PID* labels, size_t num_points); +size_t HnswIndex::remove(const Id* ids, size_t num_ids); ``` -- **labels**, **num_points**: `num_points` labels of the points to remove, as returned by `add` and - `search`. Every label must be in the index; nothing is removed if one is not. - `remove` returns how many points were newly removed, so repeating a label or a +- **ids**, **num_ids**: IDs of the points to remove, as returned by `add` and + `search`. Every ID must be in `[0, num_stored_points())`; nothing is removed if one is not. + `remove` returns how many points were newly removed, so repeating an ID or a call is safe. In Python: @@ -272,18 +266,17 @@ removed = index.remove(new_ids[:10]) # IDs in [0, num_stored_points) A removed point keeps its codes, its links, and its place in the graph. Search still walks through it and `add` may link new points to it, which keeps the graph connected, as in hnswlib. Search never returns it, so a query can get fewer than -`k` results once points are removed: in Python the missing slots hold `kPidMax` -(`2**32 - 1`) with an infinite distance. Removed points still count in +`k` results once points are removed: the missing slots hold ID `-1` (C++ `kNoId`) +with an infinite distance. Removed points still count in `num_stored_points()` and cannot be restored. Removal requires the same exclusive access as other updates. #### Choosing `ef_search` after removals Removed points still take slots in the `ef_search` candidate set, so a search with -`ef_search` close to `k` finds fewer live points as removals accumulate. C++ search -uses `max(ef_search, k)`, clamped to `num_stored_points()`. Python uses `max(k, 64)` -when `ef_search` is omitted (it was named `ef` before 0.8.5); an explicit value is also raised to at least `k`, -and both are clamped to the stored point count. +`ef_search` close to `k` finds fewer live points as removals accumulate. Search uses +`max(k, 64)` when `ef_search` is omitted; an explicit value is raised to at least +`k`, and both are clamped to the stored point count. To keep about the same number of live candidates as before the removals, scale the effective window by the share of live points (search clamps the result to `num_stored_points()`): @@ -298,29 +291,28 @@ Callers that track how many points they removed can apply this directly. ### How removal is stored -`remove` sets the high bit of the point's stored cluster ID. `construct` and `load` -limit the number of clusters to 2^31, so no real cluster ID has that bit, and +`remove` sets the high bit of the point's stored cluster ID. Setting centroids and +`load` limit the number of clusters to 2^31, so no real cluster ID has that bit, and every reader of the cluster ID masks it off. The mark lives in the base layer, so -it survives `save`, `load`, and `resize`, and a file without removals is -unchanged. - -In C++, `cluster_id_of(internal_id)` returns a stored record's cluster with the -mark masked off; removed points keep their cluster. It takes an internal ID from 0 -through `num_stored_points() - 1`, which matches the label only for points added -in order. It throws `std::logic_error` on a default-constructed index that has -not been loaded, and `std::invalid_argument` for an ID not below -`num_stored_points()`, including any ID before `construct`. Python does not -expose it. - -A file that has removals cannot be read by earlier releases. Releases 0.3.7 +it survives `save`, `load`, and capacity growth, and a file without removals +carries no marks. + +In the layout written before 0.9, a file that has removals cannot be read by +releases before 0.5.2. Releases 0.3.7 through 0.5.1 check every cluster ID on `load` and reject the file as invalid instead of returning removed points. Releases before 0.3.7 do not check cluster IDs, so do not open such a file with them. +`save` writes [index format 2](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/docs/formats.md#index-format-2), which also records the construction seed, so +`seed` survives a reload. Releases up to 0.8 cannot read these files; every earlier +file still loads, without a recorded seed, and saving it writes format 2. +The C++ API of earlier releases could also save an index before training it. Such a +file loads untrained, with `num_clusters` 16; without a recorded seed its first `add` +cannot train it, so call `train` or `set_centroids` before `add`. + New HNSW-RaBitQ indexes pad dimensions to multiples of 32 for all supported bit widths. Loading preserves the saved padded dimension and rotation, so older indexes -using multiples of 64 remain readable. Older library versions cannot load new -files whose padded dimension is not a multiple of 64. +using multiples of 64 remain readable. ## Implementation details @@ -396,11 +388,12 @@ is not refined and uses its 1-bit estimate for window admission. ### How added points are linked -`construct` borrows the caller's vectors and links points using exact distances -between them. That pointer is not retained, so `add` cannot use it, and instead -scores candidates with the estimator the search already uses: the vector being -compared against is rebuilt from its stored RaBitQ code, sign bit and extra bits -together, and the other side is scored straight from its codes. This is the same +The first `add` into an empty graph borrows the caller's vectors and links points +using exact distances between them. That pointer is not retained, so later adds +cannot use it, and instead score candidates with the estimator the search already +uses: the vector being compared against is rebuilt from its stored RaBitQ code, +sign bit and extra bits together, and the other side is scored straight from its +codes. This is the same approach quantized SymphonyQG construction takes. Graph quality therefore depends on how a point arrived. diff --git a/docs/docs/index/ivf.md b/docs/docs/index/ivf.md index aa346060..7a377fd5 100644 --- a/docs/docs/index/ivf.md +++ b/docs/docs/index/ivf.md @@ -1,6 +1,6 @@ # IVF-RaBitQ -C++ callers include `rabitqlib/index/ivf/ivf.hpp` and link `rabitqlib::index`. +C++ callers include `rabitqlib/index/ivf_index.hpp` and link `rabitqlib::index`. [IVF](https://doi.org/10.1109/TPAMI.2010.57) is a classical clustering-based ANN method. IVF-RaBitQ stores RaBitQ codes and @@ -20,44 +20,52 @@ clustering options, and the update examples below reuse the Quick Start's `index ### C++ -Link `rabitqlib::index`. In this snippet, `data`, `centroids` and `queries` are -row-major `std::vector` buffers with original dimension `dim`; -`cluster_ids` is a `std::vector` with one centroid ID per data row. -The example requests ten neighbors from five clusters, so supply at least ten -points and five centroids. +`rabitqlib::IvfIndex` has the names, defaults and behaviour of the Python class. +In this snippet, `data` and `queries` are row-major `std::vector` buffers +with dimension `dim`. As in Python, the first `add` trains the 1,024 centroids on +the added vectors, so supply at least 1,024 of them. ```cpp #include -#include +#include + +rabitqlib::IvfOptions options; // set the fields by name +options.nbits = 4; +rabitqlib::IvfIndex index(dim, 1024, options); +index.add(data.data(), data.size() / dim); -rabitqlib::ivf::IVF index(data.size() / dim, dim, centroids.size() / dim, 4); -index.construct(data.data(), centroids.data(), cluster_ids.data(), false, 1); const size_t num_queries = queries.size() / dim; -std::vector ids(num_queries * 10); +std::vector ids(num_queries * 10); std::vector distances(num_queries * 10); -index.search_batch(queries.data(), num_queries, 10, 5, ids.data(), distances.data()); +index.search(queries.data(), num_queries, 10, ids.data(), distances.data()); index.save("ivf.index"); +auto loaded = rabitqlib::IvfIndex::load("ivf.index"); ``` See [C++ integration](../cpp_integration.md) for build setup and -[Index Construction](#index-construction) for loading `.fvecs` inputs. +[Index Construction](#index-construction) for building from precomputed +centroids and cluster IDs. ## Parameters and limits | Parameter | Contract | | --- | --- | -| `dim` | Original input dimension; Python supports 64–65,536 and pads internally. | +| `dim` | Original input dimension, 64–65,536; the index pads internally. | | `num_clusters` | Number of centroids `train` or the first `add` learns, or `set_centroids` supplies; every cluster ID must be in `[0, num_clusters)`. | -| `nbits` / C++ `total_bits` | 1–9 total bits including the sign bit, or 32 for owned raw-vector reranking. Python's keyword-only `nbits` defaults to 7; C++ requires it. | -| `seed` | Rotation seed in `[0, 2**32 - 1]` and the initial `cp.seed`. Python's default `None` draws one at random; `index.seed` reports it, and passing it back reproduces the index. | -| `metric` | Python `"l2"` or `"ip"`; defaults to `"l2"`. | -| `routing` | Defaults to `"auto"`; see [centroid routing](#centroid-routing). Named `initializer` before 0.8.5; the old name still works, with a `DeprecationWarning`, until 0.9. | -| `k`, `nprobe` | Positive result count and cluster probe count. `k` may exceed the stored point count; missing results are padded with `kPidMax` (`2**32 - 1` in Python) and `+inf`. Python's `nprobe` defaults to `num_clusters / 16`, rounded and at least 1, when omitted or `None` (0 does the same and is deprecated since 0.8.5); C++ requires a positive `nprobe`. | -| `high_accuracy` | Python defaults to `None`: HACC for 4–9 bits, standard FastScan otherwise. | +| `nbits` | 1–9 total bits including the sign bit, or 32 for owned raw-vector reranking. Defaults to 7. | +| `seed` | Rotation seed in `[0, 2**32 - 1]` and the initial `cp.seed`. The default (Python `None`, an empty C++ `std::optional`) draws one at random; `seed` reports it, and passing it back reproduces the index. | +| `metric` | Python `"l2"`, `"ip"` or `"cosine"` (C++ `METRIC_L2`, `METRIC_IP` or `METRIC_COSINE`); defaults to L2. See [the cosine metric](usage.md#the-cosine-metric). | +| `routing` | Defaults to `"auto"` (C++ `ivf::Routing::Auto`); see [centroid routing](#centroid-routing). It replaces `initializer`, which 0.9 removed. | +| `k`, `nprobe` | Result count, from 1 to 2^31, and positive cluster probe count. `k` may exceed the stored point count; missing results are padded with ID `-1` (C++ `kNoId`) and `+inf`. `nprobe` defaults to `num_clusters / 16`, rounded and at least 1, when omitted (Python `None`); an explicit 0 raises `ValueError` (C++ `std::invalid_argument`). | +| `high_accuracy` | Defaults to automatic selection (Python `None`): HACC for 4–9 bits, standard FastScan otherwise. | + +In C++, `nbits`, `seed`, `metric` and `routing` are fields of `IvfOptions`, and +`nprobe`, `high_accuracy` and `num_threads` fields of `IvfSearchOptions`. Results contain IDs and squared L2 or `1 - dot` distances, ordered from smallest -to largest. Quantized distances are estimates. Unfilled slots use ID `2**32 - 1` -and distance `+inf`; see [result handling](../quick_start.md#read-the-results). +to largest. Quantized distances are estimates. IDs are `int64` in Python and +`rabitqlib::Id` (`int64_t`) in C++. Unfilled slots use ID `-1` and distance `+inf`; +see [result handling](../quick_start.md#read-the-results). See the shared [input and concurrency contracts](usage.md). ## Index construction @@ -80,11 +88,11 @@ For example, split SIFT into 4,096 clusters using squared L2 distance: After files are prepared, load them into memory. The snippet below uses `const char*` paths `data_file`, `centroids_file`, and `cluster_ids_file`. Include the -Eigen aliases and I/O helpers explicitly; `ivf.hpp` does not import them. +Eigen aliases and I/O helpers explicitly; `ivf_index.hpp` does not import them. ```c++ #include -#include +#include #include #include @@ -104,42 +112,40 @@ rabitqlib::load_vecs(cluster_ids_file, cluster_ids); See the [complete indexing example](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/sample/cpp/ivf_rabitq_indexing.cpp) for argument parsing and the surrounding program. -Then initialize an IVF-RaBitQ object with the number of data points, vector -dimension, number of clusters, and total bits per dimension. The C++ index -accepts total quantized bit widths from 1 through 9, or `total_bits=32` -(Python `nbits=32`) to store raw float32 vectors for reranking. +Then create the index with the vector dimension, the number of clusters and the +total bits per dimension: 1 through 9, or 32 to store raw float32 vectors for +reranking. ```c++ -using index_type = rabitqlib::ivf::IVF; - size_t num_points = data.rows(); size_t dim = data.cols(); size_t num_clusters = centroids.rows(); -index_type ivf(num_points, dim, num_clusters, total_bits); +rabitqlib::IvfOptions options; +options.nbits = total_bits; +rabitqlib::IvfIndex ivf(dim, num_clusters, options); ``` ### Centroid routing -The optional final C++ constructor argument selects `InitializerType::Auto`, -`Flat`, `FlatRaBitQ`, or `HNSW` from the `rabitqlib::ivf` namespace. Python accepts -`routing="auto"`, `"flat"`, `"flat_rabitq"`, or `"hnsw"`: +`IvfOptions::routing` selects `ivf::Routing::Auto`, `Flat`, `FlatRaBitQ`, or +`HNSW`. Python accepts `routing="auto"`, `"flat"`, `"flat_rabitq"`, or `"hnsw"`; here +`dim` and `num_clusters` are the vector dimension and the number of clusters: ```python -index = IvfIndex(dim, num_clusters, nbits=4, routing="flat_rabitq") -print(index.routing) # resolved routing type +routed = IvfIndex(dim, num_clusters, nbits=4, routing="flat_rabitq") +print(routed.routing) # resolved routing type ``` ```c++ -index_type ivf(num_points, dim, num_clusters, total_bits, rabitqlib::METRIC_L2, - rabitqlib::RotatorType::FhtKacRotator, - rabitqlib::ivf::InitializerType::FlatRaBitQ); -auto routing = ivf.initializer_type(); +options.routing = rabitqlib::ivf::Routing::FlatRaBitQ; +rabitqlib::IvfIndex ivf(dim, num_clusters, options); +auto routing = ivf.routing(); // resolved routing type ``` - `auto` selects `flat` below 5,000 clusters, `flat_rabitq` from 5,000 through 59,999 clusters, and `hnsw` from 60,000 clusters onward. These defaults are - practical thresholds; explicitly select a different initializer when it better + practical thresholds; explicitly select a different routing when it better suits your workload. - `flat` computes exact distances to every centroid. - `flat_rabitq` scans one-bit centroid codes with FastScan, prunes candidates @@ -153,17 +159,13 @@ auto routing = ivf.initializer_type(); error instead of probing every cluster. Use `flat` or `flat_rabitq` when a query should probe most clusters. -All choices support L2 and inner product. Flat RaBitQ uses the IVF-RaBitQ rotation and +All choices support every metric. Flat RaBitQ uses the IVF-RaBitQ rotation and padded domain, retains float32 centroids for refinement, and stores its mean and codes in the main index file. Its code precision is independent of the index's `nbits`. It trades additional code storage and an O(cluster count) query work buffer for fewer full-vector distance evaluations. Performance depends on cluster count, dimension, `nprobe`, and data distribution. Measure recall and -latency on your workload, and use an explicit initializer to override `auto`. - -The optional routing argument introduced in 0.6.0 preserves existing constructor -call forms; this does not imply compatibility with all 0.7.0 C++ changes. See the -[migration guide](../modular_migration.md) and rebuild with matching headers and libraries. +latency on your workload, and use an explicit routing to override `auto`. Compared with releases before 0.6.0, `auto` changes routing for 5,000–59,999 clusters. The 5,000–19,999 range changes from exact to approximate selection. @@ -171,33 +173,24 @@ To retain the earlier policy when rebuilding, choose `flat` below 20,000 cluster and `hnsw` otherwise. Loading an old index preserves its historical routing. Routing is fixed for an index and is also used by `add` when cluster IDs are -omitted. `initializer_type()` (Python `routing`) reports the resolved type, +omitted. `routing()` (Python `routing`) reports the resolved type, including after loading; loading never re-runs the current `auto` policy for a new-format file. -Finally, call the construct API: +Finally, set the centroids and add the vectors with their cluster IDs: ```c++ -void IVF::construct( - const float* data, - const float* centroids, - const PID* cluster_ids, - bool fast_quantization = false, - size_t num_threads = std::numeric_limits::max() -); +ivf.set_centroids(centroids.data()); +rabitqlib::AddOptions add_options; +add_options.cluster_ids = cluster_ids.data(); +add_options.fast_quantization = true; +ivf.add(data.data(), num_points, add_options); ``` -- **data**: Vectors in the original input coordinates. - **centroids**: One centroid per configured cluster, in the original input coordinates. - **cluster_ids**: One ID per input vector, in `[0, num_clusters())`. - **fast_quantization**: Use a calibrated scaling factor instead of per-vector scale search; defaults to `false`. See [encoding paths](../rabitq/quantizer.md#implementations). -- **num_threads**: Maximum number of OpenMP threads used to quantize clusters. - -For example: - -```c++ -ivf.construct(data.data(), centroids.data(), cluster_ids.data(), true); -``` +- **num_threads**: Worker count; no value, the default, uses every available CPU. ### Training centroids in Python @@ -208,14 +201,16 @@ and quantizes vectors. On an untrained index, the first `add` without to train on a different sample. Training uses the settings in `index.cp`, a [`RaBitQKMeansParameters`](../clustering.md#rabitqkmeans) whose defaults differ from the k-means classes: 10 iterations, at most 256 sampled vectors per -centroid (`max_points_per_centroid`), spherical k-means for `metric="ip"`, and -`seed` equal to the index seed. Change fields before training: +centroid (`max_points_per_centroid`), spherical k-means for `metric="ip"` and `"cosine"`, and +`seed` equal to the index seed. Change fields before training; in this example +`sample` and `vectors` are float32 arrays of shape `(n, dim)`, and `sample` needs at +least 1024 rows: ```python -index = IvfIndex(dim, 1024, nbits=4, metric="ip") -index.cp.niter = 20 -index.train(sample) # num_threads=None uses index.cp.num_threads (0: all CPUs) -index.add(vectors) +ip_index = IvfIndex(dim, 1024, nbits=4, metric="ip") +ip_index.cp.niter = 20 +ip_index.train(sample) # num_threads=None uses ip_index.cp.num_threads (0: all CPUs) +ip_index.add(vectors) ``` - Up to 2,000 clusters, training uses RaBitQKMeans; above that it uses @@ -230,165 +225,136 @@ index.add(vectors) vectors; once it stores any (including removed ones), both raise `RuntimeError`. A failed call leaves the index unchanged. - Before training, `add` with `cluster_ids`, `search`, `remove`, `reserve_cluster` and - `save` raise `RuntimeError`; `add` without `cluster_ids` trains first, except - on an index created with `max_elements`, which `build` fills. If that + `save` raise `RuntimeError`; `add` without `cluster_ids` trains first. If that first `add` fails, the index stays untrained and empty; an empty first `add` raises `RuntimeError`. A trained index without vectors cannot be saved, and its `search` returns only padded results; add - vectors first. Loaded indexes are trained, and their `seed` is `None`. + vectors first. Loaded indexes are trained; `seed` is `None` for files without + a recorded seed, such as those from releases up to 0.8. - `train` and `add` default to every available CPU; `search` defaults to one thread. ### Training centroids in C++ -Instead of passing centroids to `construct`, create an index without a point -count, train or set its centroids, then add the points: +`IvfIndex` trains as the Python class does. `cp()` returns the training +settings; include `rabitqlib/clustering/rabitqkmeans.hpp` to change them: ```c++ -#include -#include - -rabitqlib::ivf::IVF index(dim, num_clusters, 4, rabitqlib::METRIC_L2, /*seed=*/42); -index.train(num_points, data.data(), - rabitqlib::default_training_parameters(rabitqlib::METRIC_L2, 42)); +#include +#include + +rabitqlib::IvfOptions options; +options.metric = rabitqlib::METRIC_IP; +options.nbits = 4; +rabitqlib::IvfIndex index(dim, 1024, options); +index.cp().niter = 20; +index.train(sample.data(), num_samples); // no thread count: cp().num_threads // Or supply centroids: index.set_centroids(centroids.data()); index.add(data.data(), num_points); ``` -- The constructor takes `dim`, `num_clusters`, `total_bits`, the metric and the - rotation seed, followed by the optional rotator and initializer types. Pass - the seed: without it, four arguments such as `IVF(dim, num_clusters, 4, - METRIC_IP)` select the point-count constructor instead, reading them as - `(num_points, dim, num_clusters, total_bits)` with the metric converted to a - bit count, which may compile and run without an error. The - index starts with no point storage. `construct` rebuilds an index from - `max_elements()` rows, so it fails on this index until `add` has stored points. -- An index created with a point count is built by `construct`: `train` and - `set_centroids` throw `std::logic_error` for it. -- `train` uses [RaBitQKMeans](../clustering.md#rabitqkmeans) for up to - `kMaxRaBitQKMeansClusters` (2,000) clusters and - [QGKMeans](../clustering.md#qgkmeans) above that, copying the fields the two - parameter types share and keeping QGKMeans' default graph settings. The - threshold is provisional and has not been measured. Only centroids are - trained; `add` assigns the points. `cp.num_threads` also limits building the - centroid routing. -- `default_training_parameters(metric, seed)` runs 10 iterations on at most - 256 sampled points per centroid and selects spherical k-means for inner - product. The k-means classes keep their own defaults, which train on every point. -- `train` and `set_centroids` replace the centroids only while the index stores - no points, removed ones included; otherwise they throw `std::logic_error`. - A failed call leaves the index unchanged. -- `is_trained()` reports whether centroids are set. Before that, `add` and - `search` throw `std::logic_error`. A trained index without points pads every - `search` result slot with `kPidMax` and `+inf`; `save` throws +- `train`, `set_centroids` and the first `add` follow the Python rules above, + including the thresholds, the defaults of `cp()` and the state checks. +- Arguments outside their range throw `std::invalid_argument` (Python + `ValueError`), and a call in the wrong state throws `std::logic_error` (Python + `RuntimeError`), with the Python messages except where those name Python values + such as `None`. +- `is_trained()` reports whether centroids are set. A trained index without + points pads every `search` result slot with `kNoId` and `+inf`; `save` throws `std::logic_error` until the index stores at least one point. +- `train` without a thread count and the first `add` without + `AddOptions::num_threads` train, and build the centroid routing, with + `cp().num_threads`; `add` quantizes with every available CPU unless + `num_threads` is set. ## Querying To search a saved index, load it first: ```c++ -using index_type = rabitqlib::ivf::IVF; -index_type ivf; -ivf.load(index_file); +auto ivf = rabitqlib::IvfIndex::load(index_file); ``` -Search a constructed or loaded index with: +Search a trained or loaded index with: ```c++ -void IVF::search( - const float* query, +void IvfIndex::search( + const float* queries, + size_t num_queries, size_t k, - size_t nprobe, - PID* result_ids, - float* distances = nullptr + Id* ids, + float* distances, + const IvfSearchOptions& options = {} ) const; ``` -- **query**: Query vector. -- **k**: Top-k. -- **nprobe**: The number of closest clusters to search. -- **result_ids**: Output ID buffer, size of `k`. -- **distances**: Optional distance buffer, size of `k`. +- **queries**: `num_queries` contiguous row-major float32 vectors of dimension `dim()`. +- **k**: Results per query. +- **ids**, **distances**: Output buffers of `num_queries * k` values; `distances` may be `nullptr`. +- **options**: `nprobe`, `high_accuracy` and `num_threads`; see below. FastScan precision is selected automatically: HACC for 4–9 quantized bits, and standard FastScan for 1–3 bits or raw vectors (`32`). HACC reduces lookup-table error carried into extra-bit distance estimation; raw reranking computes its -final distances directly from floats. Existing C++ overloads with `use_hacc` -and Python's `high_accuracy=True/False` still allow explicit overrides. Python -uses automatic selection when `high_accuracy` is omitted or `None`. +final distances directly from floats. `IvfSearchOptions::high_accuracy` (Python +`high_accuracy=True/False`) overrides the selection; no value (Python `None`) +selects automatically. ```cpp -ivf.search(query, k, nprobe, ids, distances); // Automatic -ivf.search(query, k, nprobe, ids, distances, true); // Force HACC -ivf.search(query, k, nprobe, ids, distances, false); // Force standard FastScan +rabitqlib::IvfSearchOptions options; +options.nprobe = 64; +ivf.search(queries, num_queries, k, ids, distances, options); // Automatic +options.high_accuracy = true; // Force HACC +ivf.search(queries, num_queries, k, ids, distances, options); +options.high_accuracy = false; // Force standard FastScan +ivf.search(queries, num_queries, k, ids, distances, options); ``` -The IDs-only overloads accept the same override without the `distances` -argument. In Python, call `index.search(queries, k, nprobe)` for automatic +In Python, call `index.search(queries, k, nprobe)` for automatic selection, or pass `high_accuracy=True` / `False` to force either mode. The querying examples also default to automatic selection; Python's `--use-hacc` flag forces HACC, and the C++ example accepts an optional final `true` or `false` argument. -C++ `search_batch` distributes queries across workers. -Input queries are contiguous row-major float32 -vectors with shape `(num_queries, dimension())`; output buffers have shape -`(num_queries, k)`. - -```cpp -ivf.search_batch(queries, num_queries, k, nprobe, ids, distances, - std::nullopt, 4); // Automatic precision, up to four workers -``` - -The last two arguments are `std::optional use_hacc` (default -`std::nullopt`) and `size_t num_threads` (default `1`, using OpenMP for parallel -batches). Pass `true` or `false` -for an explicit precision override. Distances may be `nullptr`. An empty batch -does no work. Input and output buffers must not overlap. Simultaneous searches -need separate output buffers, and must not overlap index updates. -Python's existing `index.search(queries, k, nprobe, num_threads=4)` uses this -batch path with the same output and precision rules. +`num_threads` (default 1; 0 selects every available CPU) distributes the +queries across OpenMP workers. An empty batch does no work. Input and output +buffers must not overlap. Simultaneous searches need separate output buffers, +and must not overlap index updates. Python's +`index.search(queries, k, nprobe, num_threads=4)` takes the same settings. Concurrent Python searches may use independent `nprobe`, `high_accuracy`, and `num_threads` values. See the [concurrency contract](usage.md#threading-and-file-paths). ## Updating an index -C++ `IVF` and Python `IvfIndex` support `add()` and `remove()` on a constructed -or loaded index without the original dataset; C++ also adds to a -[trained](#training-centroids-in-c) index. Updates preserve the file format. +`IvfIndex` supports `add()` and `remove()` on a trained or loaded index without +the original dataset. `save` always writes index format 2; see +[how removal is stored](#how-removal-is-stored). ```c++ -void IVF::add( - const float* data, - size_t num_points, - const PID* cluster_ids = nullptr, - bool fast_quantization = false, - size_t num_threads = std::numeric_limits::max() -); +Id IvfIndex::add(const float* data, size_t num_points, const AddOptions& options = {}); -size_t IVF::remove(const PID* ids_to_remove, size_t num_points); +size_t IvfIndex::remove(const Id* ids, size_t num_ids); -void IVF::reserve(PID cluster_id, size_t num_points); +void IvfIndex::reserve_cluster(size_t cluster_id, size_t num_points); ``` -- **data**, **num_points**: `num_points` new vectors, quantized like `construct` does. Vector `i` - receives the PID `num_stored_points() + i`, using the count before the call. Existing - IDs stay unchanged, and removed IDs are never reused. -- **cluster_ids**: The cluster of each new vector, in `[0, num_clusters)`. When +- **data**, **num_points**: `num_points` new vectors. Vector `i` receives the ID + `num_stored_points() + i`, using the count before the call; `add` returns the + first. Existing IDs stay unchanged, and removed IDs are never reused. +- **options.cluster_ids**: The cluster of each new vector, in `[0, num_clusters)`. When it is `nullptr`, each vector goes to its nearest centroid under the index's - routing type, the initializer selected at construction or restored from the + routing type, the one selected at creation or restored from the index file. With Flat routing, `add` assigns exactly and queries scan in float, so near-ties may resolve differently. -- **fast_quantization**, **num_threads**: Same as in `construct`. -- **ids_to_remove**: `num_points` PIDs to remove. Every PID must be below `num_stored_points()`; nothing is +- **options.fast_quantization**, **options.num_threads**: As in [index construction](#index-construction). +- **ids**, **num_ids**: IDs to remove. Every ID must be in `[0, num_stored_points())`; nothing is removed if one is not. `remove` returns how many were newly removed and can be repeated safely. -- **cluster_id**, **num_points**: `reserve` preallocates room for cluster `cluster_id` +- **cluster_id**, **num_points**: `reserve_cluster` preallocates room for cluster `cluster_id` to hold `num_points` vectors in total, counting the ones it already holds. It does nothing if the cluster already has that room. See [Cost of `add`](#cost-of-add). -In Python: +In Python, with `vectors` a float32 array of new vectors: ```python new_ids = index.add(vectors, num_threads=1, fast_quantization=False) @@ -398,20 +364,17 @@ removed = index.remove(new_ids[:10]) index.reserve_cluster(cluster_id, num_points) ``` -Python names this method `reserve_cluster` since 0.8.5; `reserve` still works, with a -`DeprecationWarning`, until 0.9. +In Python, `reserve_cluster` replaces `reserve`, which 0.9 removed. Python `vectors` has shape `(n, index.dim)` and is converted to contiguous float32. -`add()` returns a uint32 array of the new IDs. Optional `cluster_ids` must be a +`add()` returns an int64 array of the new IDs. Optional `cluster_ids` must be a one-dimensional integer array or sequence with one valid cluster ID per vector; `remove()` likewise accepts a one-dimensional integer array or sequence of point IDs and returns the number newly removed. Duplicate IDs count once. Python `num_threads` defaults to `None` (every available CPU) and `fast_quantization` to `False`; pass both by keyword. -After appending, rebuilding with C++ `construct` requires `num_stored_points` -rows, including removed records. Updates require exclusive -access; see the +Updates require exclusive access; see the [concurrency contract](usage.md#threading-and-file-paths). ### Cost of `add` @@ -427,7 +390,7 @@ index is unchanged if `add` throws. As a result: time.** A rebuilt cluster gets exactly the room it needs. To grow a cluster without -copying it, call `reserve` (Python `reserve_cluster`) first: later `add` calls then write into the reserved +copying it, call `reserve_cluster` first: later `add` calls then write into the reserved room in place until the cluster outgrows it. The reserved room is memory the index holds but does not use yet. It is not saved, so a loaded index has none. @@ -455,37 +418,41 @@ enters the result buffer and never triggers reranking. Any code that estimates IVF-RaBitQ distances must keep this behavior and must never turn `+inf` into NaN. Search may return fewer than `k` results once points are removed: the missing slots -hold `kPidMax` (`2**32 - 1` in Python) with an infinite distance, as when the probed +hold ID `-1` (C++ `kNoId`) with an infinite distance, as when the probed clusters hold fewer than `k` points. The removal marker lives in the ordinary batch data and needs no additional format change; removal survives `save` and `load`. No file written before `remove` existed has an infinite `f_add`, so nothing in an old file is reinterpreted. Release 0.5.0 also excludes removed points when reading its -supported legacy formats. However, current saves always use `RABQIDX1` v2, -including when resaving a loaded legacy index. Older releases cannot read these +supported legacy formats. However, current saves always use index format 2, +including when resaving a loaded legacy index. Releases up to 0.8 cannot read these files, regardless of whether they contain removals. ## Persistence -Save a constructed index with: +Save an index that stores at least one point with: ```c++ ivf.save(output_index_file); ``` -New files use the `RABQIDX1` magic, version 2, storage flags, an explicit -padded dimension, and a uint32 initializer type (1 = Flat, 2 = Flat RaBitQ, -3 = HNSW) before the index metadata. `Auto` is resolved before saving. Loading -restores the routing type, storage mode, rotation state, and padded dimension. -Raw files also contain the original vectors, so querying does not require an external dataset. - -Version-1 `RABQIDX1` files remain readable with their stored padding. Legacy -unversioned quantized files and raw v1 files retain their original 64-dimension -padding. All three historical formats infer routing with the original 20,000 -cluster threshold. HNSW routing still requires the accompanying `.hnsw` file. -Flat RaBitQ loads its saved codes without random re-quantization. Saving a loaded -legacy index writes the new header without changing its padded dimension or encoded data. Older library -versions cannot read the new format. +Files are written in +[index format 2](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/docs/formats.md#index-format-2): +one file with a header, a section table, and sections for the rotation, the routing +data, the codes and the IDs. HNSW routing is a section of that file, so there is no +separate sidecar. `Auto` is resolved before saving. Loading restores the routing type, +storage mode, rotation state, and padded dimension. Raw files also contain the original +vectors, so querying does not require an external dataset. Releases up to 0.8 cannot +read format 2. Indexes of more than 65,536 dimensions cannot be saved. + +Files from earlier releases remain readable. `RABQIDX1` version 2 files store their +routing type; version-1 `RABQIDX1` files keep their stored padding; legacy unversioned +quantized files and raw v1 files retain their original 64-dimension padding. These three +older layouts infer routing with the original 20,000 cluster threshold. All of these +layouts keep HNSW routing in the accompanying `.hnsw` file, which loading reads. +Flat RaBitQ loads its saved codes without random re-quantization. Saving a loaded file +writes format 2 without changing its padded dimension or encoded data; a `.hnsw` file +left beside it is not removed and is no longer used. ## Implementation details @@ -493,7 +460,7 @@ versions cannot read the new format. During construction, we process clusters in parallel, rotate their centroids and vectors, and compute one-bit codes and factors. Quantized mode also computes -`total_bits - 1` extra-bit codes and factors; raw mode stores the original +`nbits - 1` extra-bit codes and factors; raw mode stores the original float32 vectors instead. In raw mode, the index owns a copy of the input, so the original data can be released after construction. diff --git a/docs/docs/index/qg.md b/docs/docs/index/qg.md index 76649734..3c054ea5 100644 --- a/docs/docs/index/qg.md +++ b/docs/docs/index/qg.md @@ -2,7 +2,7 @@ [SymphonyQG](https://dl.acm.org/doi/abs/10.1145/3709730) combines the graph search of [QG](https://medium.com/@masajiro.iwasaki/fusion-of-graph-based-indexing-and-product-quantization-for-ann-search-7d1f0336d0d0), -from [NGT](https://github.com/yahoojapan/NGT), with batched RaBitQ distance estimation. +from [NGT](https://github.com/NGT-labs/NGT), with batched RaBitQ distance estimation. FastScan estimates neighbor distances; visited vertices are scored using stored raw vectors or quantized codes. @@ -36,183 +36,140 @@ indexes, but has nothing to train: `train(x)` only checks `x` as `add` would, and `is_trained` is always `True`. `add` builds the graph from every vector at once and can be called only once, as in Faiss's NSG index; a second call, or `add` on a loaded index, raises `RuntimeError`. To index more vectors, create a new index -and add all of them. Point IDs are the row numbers of the added data. Files do -not store the construction settings, so a loaded index reports -`ef_construction`, `init` and `seed` as `None`. +and add all of them. Point IDs are the row numbers of the added data. Files +from releases up to 0.8 do not store the construction settings, so an index +loaded from one reports `ef_construction`, `init` and `seed` as `None`. ### C++ -Link `rabitqlib::index`. Here `data` is a row-major `std::vector` with -`rows * cols` values, and `query` contains `cols` values; use at least 33 rows. -See [C++ integration](../cpp_integration.md) for build setup. +`rabitqlib::SymqgIndex` has the names, defaults and behaviour of the Python +class. Here `data` and `queries` are row-major `std::vector` buffers with +dimension `dim`; use at least 33 data rows. See +[C++ integration](../cpp_integration.md) for build setup. ```cpp #include -#include -#include - -using namespace rabitqlib::symqg; - -// data contains rows * cols floats. -QuantizedGraph qg(rows, cols, 32); -{ - QGBuilder builder(qg, 200, data.data(), 1, QGInitialization::PiPNN); - builder.build(); -} // release builder scratch before saving -qg.set_ef(100); -std::vector ids(10); -std::vector distances(10); -qg.search(query.data(), 10, ids.data(), distances.data()); -qg.save("qg_example.index"); +#include + +rabitqlib::SymqgIndex index(dim); // max_degree 32, ef_construction 200, PiPNN +index.add(data.data(), data.size() / dim); // builds the whole graph +index.save("qg_example.index"); + +auto loaded = rabitqlib::SymqgIndex::load("qg_example.index"); +const size_t num_queries = queries.size() / dim; +std::vector ids(num_queries * 10); +std::vector distances(num_queries * 10); +rabitqlib::GraphSearchOptions options; +options.ef_search = 100; +loaded.search(queries.data(), num_queries, 10, ids.data(), distances.data(), options); ``` +`add` throws `std::logic_error` (Python `RuntimeError`) on a built or loaded +index, and `train` only checks its input. + ## Parameters and limits | Parameter | Contract | | --- | --- | -| `dim` | Original input dimension; Python supports 64–65,536 and pads internally. | -| `nbits` / C++ `quantization_bits` | Python keyword: 32 (default) for owned raw vectors, or 4/8 for quantized storage. C++ uses 0 for raw vectors, as Python's `quantization_bits` did before 0.8. | -| `max_degree` | Python keyword, default 32: a positive multiple of 32, strictly smaller than the point count. It is a hard degree bound, unlike HNSW-RaBitQ's `M`. | -| `ef_construction` | Python keyword, default 200: positive construction search window used by `add`. | -| `init` | Python keyword: `"pipnn"` (default) or `"random"`. | -| `metric` | Python keyword: `"l2"` (default) or `"ip"`. | -| `seed` | Python keyword: rotation and graph-construction seed in `[0, 2**32 - 1]`. The default `None` draws one at random; `index.seed` reports it, and passing it back with `num_threads=1` rebuilds the same graph from the same data. | -| `k`, `ef_search` | `k` is at least 1 and may exceed the point count; slots the graph cannot fill are padded with ID `2**32 - 1` and distance `+inf`. An omitted `ef_search` uses `max(k, 64)` in Python, and smaller values are raised to `k`, as for HNSW-RaBitQ. Python named it `ef` before 0.8.5. | -| `num_threads` | Python `add` defaults to every available logical CPU, capped by `OMP_NUM_THREADS`, and `search` to 1; `None` selects these defaults. | - -Python search returns `(ids, distances)` arrays. Distances are squared +| `dim` | Original input dimension, 64–65,536; the index pads internally. | +| `nbits` | 32 (default) for owned raw vectors, or 4/8 for quantized storage. | +| `max_degree` | Default 32: a positive multiple of 32, strictly smaller than the point count. It is a hard degree bound, unlike HNSW-RaBitQ's `M`. | +| `ef_construction` | Default 200: positive construction search window used by `add`. | +| `init` | `"pipnn"` (default) or `"random"`; C++ `symqg::QGInitialization::PiPNN` or `Random`. | +| `metric` | L2 (default), inner product or [cosine](usage.md#the-cosine-metric): Python `"l2"`, `"ip"` or `"cosine"`. | +| `seed` | Rotation and graph-construction seed in `[0, 2**32 - 1]`. The default (Python `None`, an empty C++ `std::optional`) draws one at random; `seed` reports it, and passing it back with one thread rebuilds the same graph from the same data. | +| `k`, `ef_search` | `k` is from 1 to 2^31 and may exceed the point count; slots the graph cannot fill are padded with ID `-1` (C++ `kNoId`) and distance `+inf`. An omitted `ef_search` (Python `None`) uses `max(k, 64)`, an explicit 0 raises `ValueError` (C++ `std::invalid_argument`), and smaller values are raised to `k`, as for HNSW-RaBitQ. It replaces `ef`, which 0.9 removed. | +| `num_threads` | `add` defaults to every available logical CPU, capped by `OMP_NUM_THREADS`, and `search` to 1; Python `None` and C++ 0 for `add` select the available CPUs. | + +In C++, the construction settings are fields of `SymqgOptions`, and `ef_search` +and `num_threads` fields of `GraphSearchOptions`; `add` takes the thread count. +Search returns IDs and distances (Python `(ids, distances)` arrays). Distances are squared L2 or `1 - dot`, ordered from smallest to largest; quantized storage returns estimates. SymphonyQG has no incremental add/remove API. See shared [input, count and concurrency contracts](usage.md). ## Index construction -See the shared [index count contract](usage.md#index-counts). C++ -`num_vertices()` returns the configured graph size, even before building. +See the shared [index count contract](usage.md#index-counts). `num_points()` is 0 +until `add` builds the graph. [PiPNN](https://dl.acm.org/doi/abs/10.1145/3770855.3817891) is the default initializer for fast indexing, followed by one SymphonyQG refinement iteration. Random initialization remains available and uses three iterations by default. -Include `rabitqlib/index/symqg/qg.hpp` and `qg_builder.hpp` from the same directory, -and link `rabitqlib::index`. The C++ API provides -`rabitqlib::symqg::QuantizedGraph` and `QGBuilder`. -Only float vectors are supported; C++17 declarations may omit `` through -class template argument deduction: +Include `rabitqlib/index/symqg_index.hpp` and link `rabitqlib::index`: ```cpp -QuantizedGraph( - size_t max_elements, size_t dim, size_t max_degree, - MetricType metric_type = METRIC_L2, - RotatorType rotator_type = RotatorType::FhtKacRotator, - size_t quantization_bits = 0, uint32_t seed = std::random_device{}() -); -QGBuilder( - QuantizedGraph& index, uint32_t ef_construction, const float* data, - size_t num_threads = std::numeric_limits::max(), - QGInitialization init = QGInitialization::PiPNN, - uint32_t seed = std::random_device{}(), bool cache_vectors = false -); +rabitqlib::SymqgOptions options; // set the fields by name +options.nbits = 4; +options.init = rabitqlib::symqg::QGInitialization::Random; +options.seed = 42; +rabitqlib::SymqgIndex index(dim, options); +index.add(data.data(), num_points, /*num_threads=*/1); ``` -`data` contains `max_elements * dim` floats. This is the configured point count; -QG has no spare capacity for later appends. `max_degree` has the same constraints -as Python's parameter. C++ defaults to all available threads. `build()` runs one refinement -for PiPNN or three passes for `QGInitialization::Random`; `build(n)` requests -`n >= 2` passes. The older overload with a numeric fifth argument uses that value -as the random-initialization seed. - -### Input lifetime and rebuilds - -The caller can release input vectors after the `QGBuilder` constructor returns. -Python retains the caller's array during `add`. Complete construction before -querying or saving. - -`builder.reset(data)` reinitializes vectors of the same shape and reuses workspace. -Input may be released after reset returns; rebuild before querying or saving. - -### Vector cache - -`cache_vectors=true` retains transformed vectors and query factors -(`4 * max_elements * padded_dim` bytes plus factors). [QGKMeans](../clustering.md#qgkmeans) enables -this for its centroid graph; the cache is not persisted. +`add` builds a graph of exactly `num_points` vertices, so `data` contains +`num_points * dim` floats; there is no spare capacity for later appends. It +runs one refinement for PiPNN or three passes for random initialization. If +`add` throws, the index stays without a graph and a later `add` can build one. +The input may be released after `add` returns. ### Random seeds -The graph seed controls the rotation. An FHT/Kac seed gives the same rotation on -every platform; a MatrixRotator seed reproduces the matrix only with the same -standard library and build, so rely on the saved index rather than the seed. -The builder seed controls random initialization and fallback edges. PiPNN uses -fixed internal seeds. Python's `seed` sets both the graph seed and the builder seed. +The seed controls the FHT/Kac rotation, which is the same on every platform, and +random initialization and fallback edges. PiPNN uses fixed internal seeds. ## Querying -C++ search accepts one vector in the original input dimension and writes `k` IDs -and distances: +C++ search accepts contiguous row-major queries in the original input dimension +and writes `num_queries * k` IDs and distances: ```cpp -QuantizedGraph qg; -qg.load("qg_example.index"); -qg.set_ef(100); - -std::vector ids(10); -std::vector distances(10); -qg.search(query.data(), 10, ids.data(), distances.data()); +void SymqgIndex::search( + const float* queries, + size_t num_queries, + size_t k, + Id* ids, + float* distances, + const GraphSearchOptions& options = {} +) const; ``` -C++ `search_batch()` accepts contiguous row-major batches -and reuses scratch storage within each worker, preserving the results of -independent `search()` calls: - ```cpp -// queries contains num_queries * qg.dimension() floats in the original dimension. -std::vector batch_ids(num_queries * 10); -std::vector batch_distances(num_queries * 10); -qg.search_batch( - queries.data(), num_queries, 10, batch_ids.data(), batch_distances.data(), 4 -); +auto qg = rabitqlib::SymqgIndex::load("qg_example.index"); +rabitqlib::GraphSearchOptions options; +options.ef_search = 100; +options.num_threads = 4; +std::vector ids(num_queries * 10); +std::vector distances(num_queries * 10); +qg.search(queries.data(), num_queries, 10, ids.data(), distances.data(), options); ``` -The C++ signature is `search_batch(queries, num_queries, k, result_ids, distances, -num_threads=1)`. Set `ef_search >= k` with `set_ef()` before searching. Both output -buffers are required and contain `num_queries * k` elements. Empty C++ batches -do no work and may use null buffers. Inputs and outputs must not overlap. -Concurrent searches need separate outputs; do not modify the index or call -`set_ef()` while searches are running. +`distances` may be `nullptr`. Workers reuse scratch storage across their +queries. Empty batches do no work. Inputs and outputs must not overlap. +Concurrent searches may use different `ef_search` values but need separate +outputs and an unchanged index. Python `search(queries, k, ef_search=None, *, num_threads=None)` accepts a two-dimensional query array and returns `(ids, distances)` arrays of shape `(num_queries, k)`, including empty batches. It defaults to one worker; `num_threads=0` selects the -available logical CPU count, capped by the number of queries. The 0.7 name -`search_batch` still works in 0.8 with a `DeprecationWarning`. +available logical CPU count, capped by `OMP_NUM_THREADS` and by the number of queries. Queries use the original dimension, including when the internal rotation pads it. -Python searches use per-call `ef_search` values. For access rules, see the +Python searches also use per-call `ef_search` values. For access rules, see the [concurrency contract](usage.md#threading-and-file-paths). -For C++, use -`search_batch_with_ef(queries, num_queries, k, result_ids, distances, ef_search, num_threads=1)` -to run concurrent calls with independent windows: - -```cpp -qg.search_batch_with_ef( - queries.data(), num_queries, 10, batch_ids.data(), batch_distances.data(), 100, 4 -); -``` - -This method does not read or change the default set by `set_ef()`. The existing -`search()`, `search_batch()`, and `search_with_scratch()` retain that default. -All concurrent searches require separate outputs and an unchanged index. - See `sample/cpp/symqg_indexing.cpp`, `sample/cpp/symqg_querying.cpp`, and their Python counterparts for complete examples. ## Persistence +`save` writes [index format 2](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/docs/formats.md#index-format-2), which also records the seed, `ef_construction` +and `init`, so they survive a reload. Releases up to 0.8 cannot read these files; every +earlier file still loads, without these settings, and saving it writes format 2. + All three modes pad the rotated domain to a multiple of 32. Loading an older index preserves its saved padded dimension, including historical multiples of 64. -Older library versions that enforce 64-dimension padding cannot load new files -whose padded dimension is not a multiple of 64. ## Implementation details diff --git a/docs/docs/index/usage.md b/docs/docs/index/usage.md index 2afe6391..ada320ce 100644 --- a/docs/docs/index/usage.md +++ b/docs/docs/index/usage.md @@ -6,7 +6,8 @@ SymphonyQG. Start with the [Python quick start](../quick_start.md) for a complet ## Input requirements `IvfIndex`, `HnswIndex`, and `SymqgIndex` accept data and query arrays with shape -`(count, dim)`, converted to contiguous float32. Their FHT/Kac rotation requires +`(count, dim)`, converted to contiguous float32; the C++ classes of the same names +take row-major float32 buffers. Their FHT/Kac rotation requires `64 <= dim <= 65536`. Supply the original dimension; the indexes pad internally to a multiple of 32. Queries and centroids must have the same original dimension as the indexed data. @@ -22,20 +23,48 @@ float32. `train`, `set_centroids`, `add` and `search` raise `ValueError` (C++: the index. The C++ `quantize_*` encoders in `core/encoder.hpp` assume their callers have validated the input. -These limits apply to the Python indexes. The C++ [stable core API](../rabitq/core_api.md) +These limits apply to the index classes in both languages. The C++ [stable core API](../rabitq/core_api.md) accepts working dimensions from 2, with multiples of 32 required for `SplitPacked`. C++ [MatrixRotator](../rabitq/rotator.md) has separate dimension and storage requirements; -the Python indexes do not expose a rotator choice. +the index classes do not expose a rotator choice. + +## The cosine metric + +With `metric="cosine"` (C++ `METRIC_COSINE`), every index scales data and queries to +unit length, stores the inner-product codes of the scaled vectors, and returns +`1 - cos` as the distance, the inner-product distance `1 - dot` of unit vectors. +Centroids passed to `set_centroids` are scaled the same way, because the codes are +residuals against them: centroids far from the unit sphere, such as the means of +unscaled data, would ruin the estimates. `train`, and the first `add` that trains, +compute centroids from the scaled vectors with spherical k-means and use them as +computed. Results equal those of a `metric="ip"` index built from the same vectors, +and given the same centroids, after this scaling. A zero vector stays zero, as in +hnswlib and Faiss: its true distance to every vector is 1, which quantized storage +estimates like any other distance. + +The index checks the original coordinates first, as above. Because it then trains on +scaled copies, invalid training data is reported as `IVF training data ...` or +`HNSW training data ...` rather than with the k-means message of the other metrics. +`train`, `add` and construction scale a copy of their whole input, so they briefly +need memory for one more float32 copy of it. To bound that for very large data, call +`train` on a sample and `add` the data in several calls. Queries are scaled one at a +time. + +The metric is stored in the [index file](#index-file-compatibility), so a loaded index +keeps scaling its inputs. Releases up to 0.8 have no cosine metric: there, normalize +vectors yourself and use `metric="ip"`. The core quantization APIs, FastScan queries +and clustering reject `METRIC_COSINE`. ## Index counts -The unified count properties below are introduced in **0.7.0**. In particular, -HNSW-RaBitQ's `num_points` now excludes removed records; see the -[count migration guide](../modular_migration.md#unified-index-counts) when upgrading. +`num_points` and `num_stored_points` were unified in **0.7.0**, when HNSW-RaBitQ's +`num_points` started to exclude removed records; see the +[count migration guide](../modular_migration.md#unified-index-counts) when upgrading +from an earlier release. `capacity` is the property 0.7.0 called `max_elements`: +Python renamed it in 0.8.5, and the C++ `HnswIndex` provides `capacity()` from 0.9. IVF-RaBitQ, HNSW-RaBitQ, and SymphonyQG expose these read-only Python properties -(C++ uses the same names with `()`, and `max_elements()` for the capacity of all -three indexes): +(the C++ classes use the same names with `()`): | Property | Meaning | | --- | --- | @@ -44,11 +73,9 @@ three indexes): | `capacity` (HNSW-RaBitQ only) | Logical record capacity, excluding SIMD padding | `0 <= num_points <= num_stored_points`, and `num_stored_points <= capacity` for -HNSW-RaBitQ. Before 0.8.5 Python named the capacity `max_elements` on all three -classes; that property is deprecated and is removed in 0.9. On `IvfIndex` and -`SymqgIndex` it equals `num_stored_points`, except on an `IvfIndex` created in the -0.7 form before `build`, where it is the declared row count. Before vectors are -added, both point counts are zero; configured capacity may be nonzero. For +HNSW-RaBitQ. Python's `max_elements` property, which 0.9 removed, was this capacity +on `HnswIndex` and equal to `num_stored_points` on the other two classes. Before +vectors are added, both point counts are zero; configured capacity may be nonzero. For all three indexes, `len(index)` equals `num_points`. `is_trained` reports whether IVF-RaBitQ or HNSW-RaBitQ centroids are set (by `train`, `set_centroids`, the first `add`, or `load`), and is always `True` for SymphonyQG. @@ -58,13 +85,13 @@ start at the previous `num_stored_points`. Use this stored count for ID bounds, and `num_points` for a live count. Counts survive save/load. IVF-RaBitQ grows automatically and has no spare logical capacity after an append. -HNSW-RaBitQ's Python `add` grows its capacity geometrically, and `reserve` preallocates -it (`resize` before 0.8.5). SymphonyQG has no incremental +HNSW-RaBitQ's `add` grows its capacity geometrically, and `reserve` preallocates +it. SymphonyQG has no incremental updates: `add` builds the graph once, and both counts are equal afterwards. `repr(index)` shows dimension, metric, quantization bits and live point count, -plus the training state for IVF/HNSW. IVF/HNSW also show stored count, capacity and centroid count; IVF includes -the resolved routing strategy, and SymphonyQG includes its degree bound. The summary +plus the training state for IVF/HNSW. IVF/HNSW also show stored count and centroid count; HNSW includes +its capacity, IVF the resolved routing strategy, and SymphonyQG its degree bound. The summary reads only metadata and follows the same concurrency rules as property reads. ## Estimate storage @@ -93,7 +120,7 @@ IVF-RaBitQ allocates one-bit codes and their three factors in full batches of 32 use the stored point count. Small clusters therefore increase padding overhead. Centroids, routing structures and cluster metadata are additional. -HNSW-RaBitQ allocates base-layer records for `max_elements`, including unused capacity. +HNSW-RaBitQ allocates base-layer records for its whole `capacity`, including unused capacity. Upper-layer edges, label maps, locks, visited lists and other bookkeeping are additional. Removing points does not reclaim their storage in either IVF-RaBitQ or HNSW-RaBitQ. @@ -123,15 +150,15 @@ construction, updates, and file I/O. The following contract applies to | Operation on the same index | Concurrent access | | --- | --- | -| `search`, `search_batch`, `save`, `repr`, and property reads | May run together | -| `train`, `set_centroids`, `build`, `add`, `remove`, `reserve`, `reserve_cluster`, `resize`, and setting `cp`, where available | Require exclusive access, except SymphonyQG's `train`, which only checks its input and may run with reads | +| `search`, `save`, `repr`, and property reads | May run together | +| `train`, `set_centroids`, `add`, `remove`, `reserve`, `reserve_cluster`, and setting `cp`, where available | Require exclusive access, except SymphonyQG's `train`, which only checks its input, and an HNSW-RaBitQ `reserve` within the current capacity, which changes nothing; both may run with reads | A conflicting call immediately raises `RuntimeError("Index is busy: conflicting operation in progress")`. It does not wait or queue an update. Access protection includes Python input conversion and is released when the operation returns or raises an exception. Different index objects can operate independently. Concurrent saves must use -different output paths, including any sidecar files. +different output paths. Search parameters such as `ef_search`, `nprobe`, precision, and `num_threads` belong to each call. When using a Python thread pool, consider `num_threads=1` to avoid @@ -150,12 +177,11 @@ example Faiss or PyTorch wheels) can crash when more than one of them starts worker threads in the same process; set `OMP_NUM_THREADS=1` before the first native call, or pass `num_threads=1`, in such processes. `train` and `add` on every index, and IVF-RaBitQ `set_centroids`, default to all -CPUs (`None` or `0`); the clustering classes default to `0`. `search` defaults to one thread (`None` or `1`), -as do the deprecated `build`, which requires an integer, and `search_batch`. +CPUs (`None` or `0`); the clustering classes default to `0`. `search` defaults to one thread (`None` or `1`). Multithreaded HNSW-RaBitQ `add` links points in a nondeterministic order, and so does a multithreaded build of IVF-RaBitQ's HNSW centroid routing by `train`, -`set_centroids` or the first `add`; pass `num_threads=1` when a build must be -reproducible. +`set_centroids` or the first `add`; pass `num_threads=1`, and `seed=` to the +constructor, when a build must be reproducible. On Linux, CPU detection accounts for affinity and OpenMP binding. Apply binding before starting the program. @@ -163,25 +189,34 @@ C++ paths use UTF-8 on Windows and native path bytes on POSIX. Python `save`/`load` accept strings, `pathlib.Path` and `os.PathLike` objects; existing `bytes` and `bytearray` paths remain supported. POSIX paths preserve native bytes, but non-UTF-8 filenames require filesystem support. Windows byte paths use -UTF-8. Embedded null characters are rejected before file access. IVF HNSW sidecars -use the same path conversion. +UTF-8. Embedded null characters are rejected before file access. The HNSW sidecars +of IVF files from earlier releases use the same path conversion. `save` writes a temporary file beside the destination and renames it into place, so a failed save leaves an existing index unchanged. A replaced file keeps its permission bits, but not its owner or other hard links. Symbolic links and other non-regular -destinations are written in place. IVF renames its HNSW sidecar before the index file; -a failure between the two renames can leave a new sidecar beside the old index. +destinations are written in place. IVF-RaBitQ writes one file that includes its HNSW +routing graph. ## Index file compatibility -The compatibility suite loads frozen files written by v0.5.2, compares search -IDs and distances, and verifies save/load migration and rejection of truncated -or unsupported versions. See the +The compatibility suite loads frozen files written by v0.5.2, v0.8.3 and v0.9.0, compares +search IDs and distances, and verifies save/load migration and rejection of truncated +or unsupported versions. Every index saves in +[index format 2](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/docs/formats.md#index-format-2), +which releases up to 0.8 cannot read, and which records the construction seed. See the [fixture provenance and coverage](https://github.com/VectorDB-NTU/RaBitQ-Library/tree/main/tests/fixtures/persistence). Compatibility is format-specific; preserving old readers' ability to open new files is not guaranteed. Consult each index's format documentation before downgrading the library. +A truncated, corrupt, mismatched or unsupported file raises `rabitqlib.FormatError`, +a subclass of both `ValueError` and `RuntimeError`, so `except RuntimeError` +handlers still catch it. A file that cannot be opened raises a plain `RuntimeError`; +a read that fails after opening looks like truncation and raises `FormatError`. +C++ loaders throw `rabitqlib::FormatError` from `rabitqlib/index/format_error.hpp`, +a subclass of `std::runtime_error`. + Index files are trusted input. Loaders validate structure and reject truncated, inconsistent, or unsupported files so that mistakes are reported, but they are not a security boundary: a crafted file can make `load` allocate its stored diff --git a/docs/docs/installation.md b/docs/docs/installation.md index d907f92f..d365d95e 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -1,6 +1,6 @@ # Installation -Platform requirements and source installation for RaBitQ Library **0.8.5**. +Platform requirements and source installation for RaBitQ Library **0.9.0**. For the first Python example, see [Quick Start](quick_start.md). ## Requirements @@ -40,10 +40,12 @@ build can use scalar kernels without the FastScan CPU baseline. ## Python wheels ```bash -python -m pip install "rabitqlib>=0.8.5" +python -m pip install "rabitqlib>=0.9.0" ``` -For changes from 0.6.0, see the [0.7.0 upgrade notes](releases/0.7.0.md). +To upgrade from 0.8, see the [migration guide](python_migration.md#from-08-to-09) and the +[0.9.0 release notes](releases/0.9.0.md). For changes from 0.6.0, see the +[0.7.0 upgrade notes](releases/0.7.0.md). Wheels target the platforms above and require no compiler or CMake. Every wheel bundles its OpenMP runtime (GNU OpenMP on Linux, LLVM OpenMP on @@ -61,11 +63,11 @@ importing those classes. Array shapes and parameter ranges are still checked at ## Get the source -For Python source builds or C++ use, obtain the 0.8.5 checkout once. With Git +For Python source builds or C++ use, obtain the 0.9.0 checkout once. With Git installed, run: ```bash -git clone --branch v0.8.5 --depth 1 https://github.com/VectorDB-NTU/RaBitQ-Library.git +git clone --branch v0.9.0 --depth 1 https://github.com/VectorDB-NTU/RaBitQ-Library.git cd RaBitQ-Library ``` diff --git a/docs/docs/integrations/txtai.md b/docs/docs/integrations/txtai.md index 000abe6c..a2ed6e97 100644 --- a/docs/docs/integrations/txtai.md +++ b/docs/docs/integrations/txtai.md @@ -5,10 +5,17 @@ embedding-search workflow, while txtai handles the surrounding application API and result conversion. -This walkthrough was checked on October 21, 2026 against txtai commit -[`0ea7cb0d8234`][snapshot]. It describes the downstream adapter at that revision; -it is a source snapshot, not a verification of every published txtai package. -Consult the [current configuration reference][current-config] for later changes. +This walkthrough was checked on November 20, 2026 against txtai commit +[`86f3bad`][snapshot], which moved the adapter to forms that rabitqlib 0.8.5 and 0.9 +accept ([neuml/txtai#1616](https://github.com/neuml/txtai/pull/1616)). It describes +the downstream adapter at that revision; it is a source snapshot, not a verification +of every published txtai package. Consult the [current configuration reference][current-config] +for later changes. + +rabitqlib 0.9 needs txtai 9.15.0 or later. txtai 9.14.0, the first release with +the backend, uses call forms that 0.9 removes and fails with it; rabitqlib 0.8 +still accepts them, with deprecation warnings. Its `ann` extra only declares +`rabitqlib>=0.5.1`, so with txtai 9.14.0 keep `rabitqlib<0.9`. ## Select the backend @@ -25,7 +32,7 @@ rabitq: Keep your existing embedding model and other application settings. Install optional dependencies according to [txtai's installation guide][install]; its adapter imports both `rabitqlib` and scikit-learn. The inspected -[package configuration][dependencies] declares `rabitqlib>=0.7.0` in its `ann` extra. The fragment above selects +[package configuration][dependencies] declares `rabitqlib>=0.8.5` in its `ann` extra. The fragment above selects the backend, rather than providing a complete model-and-data example. `clusters` controls the KMeans centroid count in both modes: IVF-RaBitQ uses these @@ -41,8 +48,8 @@ The [adapter source][adapter] shows the boundary between the projects: | Stage | txtai's role | RaBitQ-Library's role | | --- | --- | --- | -| Build | Converts embeddings to contiguous float32 and uses scikit-learn KMeans to produce centroids and assignments. | Builds `IvfIndex` or `HnswIndex` with the inner-product metric. | -| Search | Selects `nprobe` or `ef`, drops missing-result IDs, and converts returned distances to scores with `1 - distance`. | Searches the native index and returns IDs and distances; quantized modes return estimates, while IVF-RaBitQ raw mode uses original-vector reranking. | +| Build | Converts embeddings to contiguous float32 and uses scikit-learn KMeans to produce centroids and assignments. | Creates `IvfIndex` or `HnswIndex` with the inner-product metric, takes the centroids with `set_centroids`, and adds the embeddings with `add(cluster_ids=...)`. | +| Search | Selects `nprobe` or `efsearch`, drops unfilled result slots by their infinite distance, and converts returned distances to scores with `1 - distance`. | Searches the native index and returns IDs and distances; quantized modes return estimates, while IVF-RaBitQ raw mode uses original-vector reranking. | | Persistence | Calls the backend's save/load methods. | Stores and restores the native index state. | | Updates | Routes IVF-RaBitQ append/delete requests to the backend. | Adds vectors or removes them from search. | @@ -62,9 +69,14 @@ The adapter requests inner-product search and converts its `1 - dot` distance convention back to scores. For normalized database and query embeddings, these are cosine-similarity estimates in quantized modes; normalization does not remove quantization error. -The source inspection establishes the integration path. It does not establish -production deployment scale or a performance gain, and this configuration has -not been exercised end to end in this documentation update. +The first build adds with every available CPU, capped by `OMP_NUM_THREADS`, so an +HNSW-RaBitQ graph built with several threads differs between runs even with the same +`randomseed`. An index saved with rabitqlib 0.9 uses index format 2, which rabitqlib 0.8 +cannot read. + +txtai's RaBitQ tests pass with this adapter on rabitqlib 0.8.5 and on a 0.9 build. +That establishes the integration path, not production deployment scale or a +performance gain. For maintainer checks against future library versions, see the [downstream compatibility procedure](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/docs/development.md#downstream-compatibility-validation). @@ -73,11 +85,11 @@ To use the same indexes directly, follow the library's [Python quick start](../q and [HNSW-RaBitQ guide](../index/hnsw.md). To integrate only quantization into your own index, see the [zvec walkthrough](zvec.md). -[snapshot]: https://github.com/neuml/txtai/tree/0ea7cb0d8234497e8ea9ed1a0f2f58492e00460b -[adapter]: https://github.com/neuml/txtai/blob/0ea7cb0d8234497e8ea9ed1a0f2f58492e00460b/src/python/txtai/ann/dense/rabitq.py -[config]: https://github.com/neuml/txtai/blob/0ea7cb0d8234497e8ea9ed1a0f2f58492e00460b/docs/embeddings/configuration/ann.md#rabitq +[snapshot]: https://github.com/neuml/txtai/tree/86f3bad49de8fe3f1b2cb4b0f3e3166afb84820b +[adapter]: https://github.com/neuml/txtai/blob/86f3bad49de8fe3f1b2cb4b0f3e3166afb84820b/src/python/txtai/ann/dense/rabitq.py +[config]: https://github.com/neuml/txtai/blob/86f3bad49de8fe3f1b2cb4b0f3e3166afb84820b/docs/embeddings/configuration/ann.md#rabitq [current-config]: https://github.com/neuml/txtai/blob/master/docs/embeddings/configuration/ann.md#rabitq [install]: https://neuml.github.io/txtai/install/#ann -[dependencies]: https://github.com/neuml/txtai/blob/0ea7cb0d8234497e8ea9ed1a0f2f58492e00460b/setup.py -[base]: https://github.com/neuml/txtai/blob/0ea7cb0d8234497e8ea9ed1a0f2f58492e00460b/src/python/txtai/ann/base.py +[dependencies]: https://github.com/neuml/txtai/blob/86f3bad49de8fe3f1b2cb4b0f3e3166afb84820b/setup.py +[base]: https://github.com/neuml/txtai/blob/86f3bad49de8fe3f1b2cb4b0f3e3166afb84820b/src/python/txtai/ann/base.py diff --git a/docs/docs/modular_migration.md b/docs/docs/modular_migration.md index 801282f9..d6cd5d7e 100644 --- a/docs/docs/modular_migration.md +++ b/docs/docs/modular_migration.md @@ -168,14 +168,15 @@ in C++ and Python. Compared with the 0.6.0 Python API, IVF-RaBitQ adds `num_points` and `num_stored_points`, HNSW-RaBitQ adds `num_stored_points`, and SymphonyQG adds `max_elements` and -`num_stored_points`. +`num_stored_points`. 0.9 removes the Python `max_elements` property; see the +[migration guide](python_migration.md#from-08-to-09). **HNSW-RaBitQ `num_points` now excludes removed records.** Use `num_stored_points` for ID bounds, append offsets, and minimum resize capacity. Use `num_points` for a live count, without subtracting a separate deletion counter. -The IVF-RaBitQ constructor keyword `max_elements` still specifies the required initial -build size; 0.8 deprecates it (see [Migrating to 0.8](python_migration.md)). SymphonyQG's C++ `num_vertices()` still returns the configured graph +In 0.7, the IVF-RaBitQ constructor keyword `max_elements` still specified the required +initial build size; 0.8 deprecated it and 0.9 removed it (see the [migration guide](python_migration.md)). SymphonyQG's C++ `num_vertices()` still returns the configured graph size for builders. Existing index files need no conversion: loading recovers counts from their removal markers. diff --git a/docs/docs/python_migration.md b/docs/docs/python_migration.md index aa0e72a2..4ad9721f 100644 --- a/docs/docs/python_migration.md +++ b/docs/docs/python_migration.md @@ -1,31 +1,34 @@ -# Migrating Python code from 0.7 to 0.8 +# Migrating Python code to 0.9 -In 0.8, `IvfIndex`, `HnswIndex` and `SymqgIndex` follow a `train` → `add` → +Since 0.8, `IvfIndex`, `HnswIndex` and `SymqgIndex` follow a `train` → `add` → `search` workflow, as Faiss indexes do; since 0.8.2 the first `add` trains, so construct → `add` → `search` is enough, and `train` remains for training on a sample. IVF-RaBitQ and HNSW-RaBitQ learn their own centroids, so you no longer run k-means and pass the centroids and assignments to `build`; SymphonyQG has nothing to train and builds its graph in `add`. Code written for 0.7 -still runs in 0.8. Each old form raises a `DeprecationWarning` at your call site -and will be removed in **0.9**. +still runs in 0.8, where each old form raises a `DeprecationWarning` at your call +site. **0.9 removes those forms**: a removed call raises `TypeError`, and a removed +attribute `AttributeError`. If your code already uses the 0.8 forms, go to -[From 0.8 to 0.9](#from-08-to-09): 0.9 renames some of them, and 0.8.5 accepts -the new names. +[From 0.8 to 0.9](#from-08-to-09): 0.9 renames some of them. 0.8.5 accepts both +spellings, so you can make every change on 0.8.5, with its warnings as a guide, +before upgrading. -Unless an item below says otherwise, a 0.7 call that raises a deprecation -warning keeps its 0.7 behavior. Calls that are valid in both versions, such as -`add(x)` and `search`, follow the 0.8 rules. +The tables below give each replacement in its 0.9 spelling. In 0.8, a 0.7 call +that raises a deprecation warning keeps its 0.7 behavior unless an item says +otherwise, and calls that are valid in both versions, such as `add(x)` and +`search`, follow the 0.8 rules. ## IVF-RaBitQ and HNSW-RaBitQ ### Old and new calls -| 0.7 | 0.8 | +| 0.7 | Since 0.8 | | --- | --- | | `IvfIndex(dim, max_elements, num_clusters, nbits, metric, initializer)` | `IvfIndex(dim, num_clusters, nbits=..., metric=..., routing=..., seed=None)` (`initializer=` before 0.8.5); storage grows on `add` | | `IvfIndex(dim=..., max_elements=..., num_clusters=..., nbits=...)` | the same, without `max_elements` | -| `HnswIndex(dim, max_elements, M=16, ef_construction=200, nbits=8, metric="l2", random_seed=100)` | `HnswIndex(dim, nbits=..., num_clusters=16, M=16, ef_construction=200, metric="l2", seed=100)`; capacity grows on `add`, and `reserve(n)` preallocates it (`resize(n)` before 0.8.5) | +| `HnswIndex(dim, max_elements, M=16, ef_construction=200, nbits=8, metric="l2", random_seed=100)` | `HnswIndex(dim, nbits=..., num_clusters=16, M=16, ef_construction=200, metric="l2", seed=None)` (`seed=100` in 0.8); capacity grows on `add`, and `reserve(n)` preallocates it (`resize(n)` before 0.8.5) | | `HnswIndex(..., random_seed=s)` | `HnswIndex(..., seed=s)` | | `kmeans = RaBitQKMeans(dim, k)`
`kmeans.train(x)`
`index.build(x, kmeans.centroids, kmeans.assignments)` | `index.add(x)`, which trains on `x` first (since 0.8.2; in 0.8.0 and 0.8.1, call `index.train(x)` first) | | `index.build(x, centroids, cluster_ids)` | `index.set_centroids(centroids)`
`index.add(x, cluster_ids=cluster_ids)` | @@ -33,11 +36,11 @@ warning keeps its 0.7 behavior. Calls that are valid in both versions, such as | `index.is_built` | `index.is_trained`, or `len(index) > 0` for "holds vectors" | Except for `dim` and IVF-RaBitQ's `num_clusters`, constructor arguments are -keyword-only in 0.8. Since 0.8.2, `nbits` defaults to 7 (0.8.0 and 0.8.1 required -it). HNSW-RaBitQ used to default to `nbits=8`; the old form keeps that default. +keyword-only since 0.8. Since 0.8.2, `nbits` defaults to 7 (0.8.0 and 0.8.1 required +it). HNSW-RaBitQ used to default to `nbits=8`. `train` uses the settings in `index.cp`: 10 iterations (25 before 0.8.2), at most 256 sampled -vectors per centroid, spherical k-means for `metric="ip"`, and the index seed. +vectors per centroid, spherical k-means for `metric="ip"` (and, from 0.9, `"cosine"`), and the index seed. See [IVF-RaBitQ training](index/ivf.md#training-centroids-in-python) for the details and for `set_centroids`. The [clustering classes](clustering.md) still work if you want to run k-means yourself. @@ -50,11 +53,10 @@ work if you want to run k-means yourself. the same default and takes `num_threads`; before, it always used every CPU and ignored `OMP_NUM_THREADS`. This applies to every `add` call that does not pass `num_threads`, including 0.7 code such as `index.add(x)`, without a - warning. `search` still defaults to one thread, and the deprecated `build` - keeps its default of 1. + warning. `search` still defaults to one thread. - **HNSW-RaBitQ builds are not reproducible by default.** With more than one thread, `add` links points in a nondeterministic order. Pass `num_threads=1` - to `add` for the same graph on every run. With one thread and the same seed, + to `add`, and since 0.9 a `seed`, for the same graph on every run. With one thread and the same seed, `set_centroids` followed by `add` produces exactly the index that 0.7 `build` produced from the same centroids and cluster IDs. - **IVF-RaBitQ HNSW routing builds are not reproducible by default.** 0.7 `build` @@ -65,11 +67,10 @@ work if you want to run k-means yourself. - **`k` above the point count.** 0.8.0 and 0.8.1 raised `ValueError` when `k` exceeded `num_stored_points` (HNSW-RaBitQ) or the point count (IVF-RaBitQ, SymphonyQG). Since 0.8.2, every index accepts any `k >= 1` and fills missing - slots with ID `2**32 - 1` and distance `inf`; test `np.isfinite(distances)`. + slots with ID `2**32 - 1` (`-1` since 0.9) and distance `inf`; test + `np.isfinite(distances)`, which works in both. - **HNSW-RaBitQ capacity grows.** `add` resizes the index, at least doubling it, - instead of raising `ValueError` when the batch does not fit. This also applies - to `add` on indexes created in the old form, and to the deprecated `build`, - which no longer rejects more rows than `max_elements`. + instead of raising `ValueError` when the batch does not fit. - **State errors.** Calling `add` with `cluster_ids`, `search`, `remove`, `reserve_cluster` (`reserve` before 0.8.5) or `save` before training raises `RuntimeError("IvfIndex must be trained or loaded before ...")`; the 0.7 message said "built". Since 0.8.2, @@ -77,52 +78,51 @@ work if you want to run k-means yourself. cannot be saved. `repr` shows `is_trained` instead of `is_built`. - **Seeds.** `IvfIndex` still draws a random rotation seed by default, and now reports it as `index.seed`; pass it back as `seed=` to reproduce an index. - Indexes loaded from files report `seed=None`. + Indexes loaded from files written by releases up to 0.8 report `seed=None`. - **HNSW-RaBitQ `num_clusters`** reports the configured count (16 by default) before training, where 0.7 reported 0 before `build`. -- An `IvfIndex` created with `max_elements` is filled by `build`; `train` and - `set_centroids` raise `RuntimeError` for it. Create the index in the 0.8 form - to train it. ## SymphonyQG -| 0.7 | 0.8 | +| 0.7 | Since 0.8 | | --- | --- | | `SymqgIndex(dim, max_degree, metric, quantization_bits)` | `SymqgIndex(dim, max_degree=..., metric=..., nbits=...)`; every argument after `dim` is keyword-only | | `quantization_bits=0` (raw vectors), `4`, `8` | `nbits=32` (raw vectors, the default), `4`, `8` | | `index.build(x, ef_construction, num_threads, init)` | `SymqgIndex(dim, ef_construction=..., init=..., seed=...)`
`index.add(x, num_threads=...)` | -| `index.search_batch(q, k, ef)` | `index.search(q, k, ef)`; `ef` is now optional | +| `index.search_batch(q, k, ef)` | `index.search(q, k, ef_search)`; the breadth is now optional | | `index.quantization_bits` | `index.nbits` (32 instead of 0 for raw vectors) | | `index.is_built` | `len(index) > 0` | `train(x)` exists for a uniform workflow but only checks `x` as `add` would, and `is_trained` is always `True`. `add` builds the graph from all vectors and can run only once; a second `add`, or `add` on a loaded index, raises `RuntimeError`, as Faiss's -NSG index does. The deprecated `build` keeps its 0.7 behavior: it replaces any -existing graph and, unless you passed `seed`, draws a new random seed each time. +NSG index does; create a new index to rebuild, where 0.7 `build` replaced the +existing graph. `search` now treats its breadth (`ef_search`; `ef` before 0.8.5) like HNSW-RaBitQ: omitted, it uses `max(k, 64)` (`max(k, 10)` before 0.8.2), and a smaller one is raised to `k`. In 0.7, both raised -`ValueError`. `add` uses every CPU by default, while the deprecated `build` -keeps one thread. The seed now also drives graph construction: without `seed`, +`ValueError`. `add` uses every CPU by default, where `build` used one thread. +The seed now also drives graph construction: without `seed`, each index draws one random seed and reports it as `index.seed`; 0.7 drew separate random seeds for the rotation and the graph. Before vectors are added, `search` and `save` raise `RuntimeError("SymqgIndex has no vectors; ...")`. ## Files and C++ -Saved files are unchanged, and so is the `max_elements` property up to 0.8.4 (see +Saved files are unchanged in 0.8, and so is the `max_elements` property up to 0.8.4 (see [From 0.8 to 0.9](#from-08-to-09)). `HnswIndex.search` without a search breadth uses `max(k, 64)` since 0.8.2 (`max(k, 10)` before), which changes its results and latency; pass the breadth as the third argument to keep the old window. Files written by 0.7 load as trained indexes, except empty, untrained HNSW-RaBitQ files, which need `train` before `add`. -For C++, the existing constructors and `construct` are unchanged; see -[IVF-RaBitQ](index/ivf.md#training-centroids-in-c) and -[HNSW-RaBitQ](index/hnsw.md#training-centroids-in-c) for the new training entry -points. C++ behavior changes: since 0.8.0, saving an index without stored points +For C++ in 0.8, the existing index constructors and `construct` are unchanged, and +`IVF::train` and `HierarchicalNSW::train` are the new training entry points; from +0.9 the [IVF-RaBitQ](index/ivf.md#training-centroids-in-c) and +[HNSW-RaBitQ](index/hnsw.md#training-centroids-in-c) pages describe `IvfIndex` and +`HnswIndex` instead, and the [release notes](releases/0.9.0.md#c-changes) map the +0.8 classes to `IvfIndex`, `HnswIndex` and `SymqgIndex`. C++ behavior changes: since 0.8.0, saving an index without stored points throws `std::logic_error`; since 0.8.2, IVF and SymphonyQG searches pad `k` above the point count instead of throwing, and `default_training_parameters` runs 10 iterations. See the [0.8.2 notes](releases/0.8.2.md#c-changes). @@ -132,11 +132,12 @@ iterations. See the [0.8.2 notes](releases/0.8.2.md#c-changes). 0.9 gives the three index classes one name for each concept ([#232](https://github.com/VectorDB-NTU/RaBitQ-Library/issues/232)). Since 0.8.5 the 0.8 form in the first column raises a `DeprecationWarning` at your call site; 0.9 -removes it. +removes it. A removed name or call form then raises `AttributeError` or `TypeError`, +and a zero breadth or an out-of-range seed raises `ValueError`. | 0.8 | Use instead | Works since | | --- | --- | --- | -| `IvfIndex.max_elements`, `SymqgIndex.max_elements` | `num_stored_points` | Every 0.8 release. The two are equal, except on an `IvfIndex` created in the 0.7 form before `build`. | +| `IvfIndex.max_elements`, `SymqgIndex.max_elements` | `num_stored_points` | Every 0.8 release. The two are equal in 0.8, except on an `IvfIndex` created in the 0.7 form before `build`. | | `HnswIndex.max_elements` | `HnswIndex.capacity` | 0.8.5 | | `HnswIndex.resize(n)` | `HnswIndex.reserve(n)`, which only grows the capacity; `resize` could also shrink it | 0.8.5 | | `IvfIndex.reserve(cluster_id, num_points)` | `IvfIndex.reserve_cluster(cluster_id, num_points)` | 0.8.5 | @@ -175,8 +176,42 @@ mode = mode if isinstance(mode, str) else mode.name.lower() Code that must also run on releases before 0.8.5 needs a version check for the rows marked 0.8.5; the other replacements work on every release named. -Three changes come without a warning in 0.9. `HnswIndex()` without `seed=` draws a seed, +In C++, `QGKMeansParameters` takes the same three field renames in 0.9, without a +transition release, and `FinalAssignmentMode::SymphonyQG` and the two statistics +aliases are removed; see the [0.9 notes](releases/0.9.0.md#c-changes). + +Four changes come without a warning in 0.9. `HnswIndex()` without `seed=` draws a seed, as `IvfIndex` and `SymqgIndex` already do, instead of using 100: pass `seed=` (and `num_threads=1` to `add`) if you rely on a reproducible build. `repr(index)` prints -`capacity=` and `routing=` where it prints `max_elements=` and `initializer=`. And -`cp.final_assignment` reads back as a string, as described above. +`capacity=` for `HnswIndex` and `routing=` for `IvfIndex` where it prints `max_elements=` +and `initializer=`, and no longer prints `max_elements=` for `IvfIndex`. The metric +spelling `"innerproduct"` raises `ValueError` on the index classes and in +`rabitqlib.quant`: use `"ip"`, which every release accepts and the `metric` properties +return. And `cp.final_assignment` reads back as a string, as described above. + +0.9 also changes behavior that no warning can announce: + +- `search` and `add` return `int64` IDs, with `-1` instead of `2**32 - 1` for a missing + result. +- `save` writes index format 2, which releases up to 0.8 cannot read, and `load` + restores the seed of such a file. Files from earlier releases still load, without a + recorded seed. +- An `IvfIndex` with HNSW routing stores the routing graph in the index file, so `save` + no longer writes a `.hnsw` sidecar. A sidecar left by an earlier save is not + removed; the new file does not use it. +- `load` raises the new `rabitqlib.FormatError` for a truncated, corrupt, mismatched or + unsupported file. It subclasses `RuntimeError`, which these errors raised before, and + `ValueError`; `rabitqlib.quant.FormatError` is now the same class. A file that cannot + be opened, or the missing sidecar of an earlier file, still raises a plain + `RuntimeError`. The messages for damaged files change, so match the exception class + rather than its text. +- The index classes are the extension's own classes, without Python wrappers. A wrong + argument raises pybind11's `TypeError`, which lists the supported signatures, instead + of messages such as `IvfIndex() got an unexpected keyword argument 'x'`, and + `inspect.signature()` no longer works on their constructors and methods; `help()` and + the type stubs describe them. +- A call with both an invalid argument and the wrong state may report the argument + first, for example `ValueError` instead of `RuntimeError` for `nprobe=0` on an + untrained index. + +See the [0.9 notes](releases/0.9.0.md) for every change. diff --git a/docs/docs/quick_start.md b/docs/docs/quick_start.md index c4ea730c..a7235284 100644 --- a/docs/docs/quick_start.md +++ b/docs/docs/quick_start.md @@ -1,14 +1,14 @@ # Quick start Build, search, save and reload a small IVF-RaBitQ index with Python. This guide describes -**0.8.5** and uses synthetic data, so no dataset download is required. Coming from 0.7? +**0.9.0** and uses synthetic data, so no dataset download is required. Coming from 0.8 or 0.7? See the [migration guide](python_migration.md). For C++, go directly to [C++ integration](cpp_integration.md). ## Install ```bash -python -m pip install "rabitqlib>=0.8.5" +python -m pip install "rabitqlib>=0.9.0" ``` Wheels support CPython 3.11–3.14 on Linux x86-64/ARM64, Windows x86-64 and @@ -45,7 +45,7 @@ print(ids[0]) The first `add` on an untrained index trains it on the added vectors, as `index.train(data)` would, then adds them. Training uses the settings in `index.cp`: 10 k-means iterations on at most 256 sampled vectors per centroid, -spherical k-means for `metric="ip"`, and the index `seed`. Change `index.cp` +spherical k-means for `metric="ip"` and `"cosine"`, and the index `seed`. Change `index.cp` before the first `add` to tune them, call `index.train(sample)` first to train on a sample, or call `index.set_centroids(centroids)` to use centroids you computed elsewhere. `train` and `add` use every available CPU by default, capped by @@ -66,11 +66,12 @@ not exact distances to the original vectors. A search may return fewer than `k` valid neighbors, for example when `k` exceeds the number of points, after removals, or when the probed IVF-RaBitQ clusters contain too -few points. Unfilled slots contain ID `2**32 - 1` and distance `+inf`. Filter them with +few points. IDs are `int64`; unfilled slots contain ID `-1` and distance `+inf`. Filter them with `valid = np.isfinite(distances)` before using IDs to index your data. -The `metric` argument accepts `"l2"` and `"ip"` (also `"innerproduct"`). For -cosine search, normalize database and query vectors first and use `metric="ip"`. +The `metric` argument accepts `"l2"`, `"ip"` and `"cosine"`. +`metric="cosine"` scales database and query vectors to unit length and returns +`1 - cos`; the saved file records it, so a loaded index keeps normalizing. ## Measure recall @@ -122,9 +123,9 @@ with TemporaryDirectory() as directory: np.testing.assert_allclose(loaded_distances, distances) ``` -The loaded index owns its data and restores the saved rotation. IVF-RaBitQ indexes using -HNSW centroid routing also need the accompanying `.hnsw` file; keep it with the -main index. This small example uses Flat routing and has no sidecar. +The loaded index owns its data and restores the saved rotation. IVF-RaBitQ saves one +file, including its HNSW centroid routing; files from releases up to 0.8 with HNSW +routing also need the accompanying `.hnsw` file. See [file compatibility](index/usage.md#index-file-compatibility) before downgrading. ## Next steps diff --git a/docs/docs/rabitq/core_api.md b/docs/docs/rabitq/core_api.md index 9de9cb9f..192d5ac9 100644 --- a/docs/docs/rabitq/core_api.md +++ b/docs/docs/rabitq/core_api.md @@ -119,7 +119,10 @@ and do not persist or hardcode them. Compiler warnings from future compilers are part of the compatibility guarantee. The stable surface is the v1 namespace, its version macros, and the existing -`MetricType` / `METRIC_L2` / `METRIC_IP` values used by it. Other core templates, +`MetricType` / `METRIC_L2` / `METRIC_IP` values used by it. `MetricType` may gain +values that only other modules accept, such as `METRIC_COSINE` for the ANN indexes +from 0.9. v1 rejects them as invalid metrics, so adding one does not change v1 or its +version; a `switch` over `MetricType` without a `default` may warn about the new value. Other core templates, `detail/`, SIMD entry points, rotator implementations, FastScan and ANN interfaces are not implicitly frozen by including this header. Existing interfaces remain available through canonical module headers; old forwarding paths are removed as @@ -135,7 +138,7 @@ automatically apply to them. | --- | --- | | `dim` | Number of coordinates actually supplied, at least 2; no implicit padding | | `total_bits` | 1 through 9, including the sign bit | -| `metric` | `METRIC_L2` or `METRIC_IP` | +| `metric` | `METRIC_L2` or `METRIC_IP`; `METRIC_COSINE`, which only the ANN indexes accept, is rejected like any other value | | `t_const` | Finite, at most `INT_MAX / 2`; nonpositive selects the existing exact search, positive selects the existing fast scaling algorithm | Inputs and a non-null centroid contain at least `dim` aligned float32 values. Pass diff --git a/docs/docs/rabitq/estimator.md b/docs/docs/rabitq/estimator.md index 54817aa9..f7f06596 100644 --- a/docs/docs/rabitq/estimator.md +++ b/docs/docs/rabitq/estimator.md @@ -48,9 +48,9 @@ $$ ## Estimator The following derivation covers squared Euclidean distance and inner product. -The public metric choices are `METRIC_L2` and `METRIC_IP`; there is no separate -cosine metric. For cosine search, normalize both data and query vectors, then -use inner product. The implementation represents inner-product distance as +The estimator supports `METRIC_L2` and `METRIC_IP` and has no cosine metric. For +cosine search, normalize both data and query vectors, then use inner product; +the ANN indexes' `METRIC_COSINE` does this for you. The implementation represents inner-product distance as $1-\langle\mathbf{o}_r,\mathbf{q}_r\rangle$, which preserves the same ranking while keeping the nearest-neighbor convention that smaller values are better. diff --git a/docs/docs/rabitq/quant_python.md b/docs/docs/rabitq/quant_python.md index 12df7922..0716cc8c 100644 --- a/docs/docs/rabitq/quant_python.md +++ b/docs/docs/rabitq/quant_python.md @@ -1,7 +1,7 @@ # Python quantization building blocks !!! warning "Provisional" - `rabitqlib.quant` is provisional in the sense of [PEP 411](https://peps.python.org/pep-0411/): any minor release may change or remove part of its API, with a note in the release notes, until it is declared stable. Byte formats are versioned from the first release, and bytes of an unknown version raise `quant.FormatError` instead of giving wrong results. + `rabitqlib.quant` is provisional in the sense of [PEP 411](https://peps.python.org/pep-0411/): any minor release may change or remove part of its API, with a note in the release notes, until it is declared stable. Byte formats are versioned from the first release, and bytes of an unknown version raise `quant.FormatError` instead of giving wrong results. It is `rabitqlib.FormatError`, which index loads also raise, a subclass of both `ValueError` and `RuntimeError`. `rabitqlib.quant` exposes the pieces the indexes are built from: rotation, quantization, correction factors, packed codes and distance estimation. Use it to store RaBitQ codes in your own database or file format and to score them with your own selection logic. For a ready-made index, use [IVF-RaBitQ](../index/ivf.md), [HNSW-RaBitQ](../index/hnsw.md) or [SymphonyQG](../index/qg.md) instead. diff --git a/docs/docs/rabitq/rabitq.md b/docs/docs/rabitq/rabitq.md index 47c5c355..012a0d8a 100644 --- a/docs/docs/rabitq/rabitq.md +++ b/docs/docs/rabitq/rabitq.md @@ -14,7 +14,8 @@ with a low-bit unsigned integer and store per-vector factors for distance estima 3. **Estimate.** Combine the codes, factors and rotated query to estimate squared L2 or inner-product distance (`1 - dot`). See [Estimation](estimator.md). -For cosine search, normalize data and queries before rotation and use inner product. +For cosine search, normalize data and queries before rotation and use inner product; +the indexes' [cosine metric](../index/usage.md#the-cosine-metric) does this for you. The probabilistic error intervals can guide [reranking](reranking.md), but do not make approximate search exact. Recall depends on the data and search settings. diff --git a/docs/docs/rabitq/rotator.md b/docs/docs/rabitq/rotator.md index ec684581..2c134c1d 100644 --- a/docs/docs/rabitq/rotator.md +++ b/docs/docs/rabitq/rotator.md @@ -92,6 +92,9 @@ This implementation is based on the [FFHT library](https://github.com/FALCONN-LI ## Random orthogonal transformation This method samples a Gaussian matrix and orthogonalizes it with QR decomposition. +Each column of the orthogonal factor takes the sign of the matching diagonal entry +of the triangular factor, which makes the transform Haar distributed, that is, +uniform over orthogonal matrices ([Mezzadri, 2007](https://arxiv.org/abs/math-ph/0609050), Section 5). It then multiplies each vector by the stored transform. The table describes stored space and per-vector rotation work when input and output dimensions are both $D$; QR construction is separate setup work. diff --git a/docs/docs/releases/0.9.0.md b/docs/docs/releases/0.9.0.md new file mode 100644 index 00000000..929e923c --- /dev/null +++ b/docs/docs/releases/0.9.0.md @@ -0,0 +1,152 @@ +# RaBitQ Library 0.9.0 + +This release removes the Python forms that 0.8 deprecated, saves every index in index +format 2, adds the cosine metric and 64-bit IDs, and adds C++ index classes that match +the Python API. Index files from every earlier release still load; files saved by 0.9 +need 0.9 or later. + +## Index files + +- IVF-RaBitQ, HNSW-RaBitQ and SymphonyQG `save` write [index format 2](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/docs/formats.md#index-format-2), a single file with a header, a section table and checksummed metadata. +- Releases up to 0.8 cannot read these files. Keep a copy saved by 0.8 if you may downgrade. +- Files written by every earlier release still load, including the `.hnsw` sidecars of HNSW-routed IVF files. Saving one writes format 2 with the same rotation, codes and results. +- IVF-RaBitQ stores HNSW centroid routing inside the file, so `save` no longer writes a `.hnsw` sidecar. A sidecar left by an earlier save is not removed. +- The saved bytes now include that routing graph. It is reproducible only when `train`, `set_centroids` or the first `add` builds it with `num_threads=1`. Saving the same index twice still gives identical files. +- `save` rejects IVF-RaBitQ indexes of more than 65,536 dimensions. +- A format-2 file that uses read-only-compatible features unknown to this release loads for search only: operations that change or save the index raise. A new index built from the original data is writable. + +## Removed and renamed Python forms + +0.9 removes every Python form that 0.8 deprecated. The [migration guide](../python_migration.md) lists each replacement; all of them work in 0.8.5, where the old forms warn. + +- The 0.7 call forms, deprecated since 0.8.0 (#213): + - `IvfIndex(dim, max_elements, num_clusters, nbits, ...)`, `HnswIndex(dim, max_elements, ...)` and its `random_seed=`, and `SymqgIndex(dim, max_degree, metric, quantization_bits)` and its `quantization_bits=`; + - `build()` and `is_built` on every index, and `SymqgIndex.search_batch()` and `SymqgIndex.quantization_bits`; + - `cluster_ids`, `num_threads` and `fast_quantization` passed to `add` by position. +- The 0.8 index spellings, deprecated since 0.8.5 (#232): + - `max_elements`: read `capacity` on `HnswIndex` and `num_stored_points` on `IvfIndex` and `SymqgIndex`; + - `HnswIndex.resize(n)`: call `reserve(n)`, which only grows the capacity; + - `IvfIndex.reserve(cluster_id, num_points)`: call `reserve_cluster`; + - `IvfIndex(initializer=...)` and `index.initializer`: use `routing`; + - `search(queries, k, ef=...)` on `HnswIndex` and `SymqgIndex`: use `ef_search=`; + - `high_accuracy` and `num_threads` passed to `search` by position: they are keyword-only, and only `nprobe` or `ef_search` stays positional; + - `nprobe=0` and `ef_search=0` for the default: they raise `ValueError`, and `None` selects the default. `num_threads=0` still means every available CPU; + - `HnswIndex` seeds above `2**32 - 1`: they raise `ValueError`, as on the other two classes. +- The 0.8 k-means spellings, deprecated since 0.8.5 (#233): + - `QGKMeans` and `QGKMeansParameters` take `nbits` (32, 4 or 8), `max_degree` and `ef_construction` instead of `quantization_bits` (0, 4 or 8), `graph_degree` and `ef_build`; + - `final_assignment` is `'approximate'` or `'exact'`, also on `index.cp`, and reads back as that string. `FinalAssignmentMode` is no longer in the package; + - `KMeansIterationStats` is the only name of the statistics class; `QGKMeansIterationStats` and `RaBitQKMeansIterationStats` are no longer in the package. +- A removed call form of an index raises `TypeError`, and a removed attribute or name `AttributeError` (`ImportError` when imported), as does a removed `QGKMeans` keyword, like any unknown keyword there; none is read as a different call. For example, `IvfIndex(dim, 1000, 64)` is an error, not an index with 1000 clusters. +- Changes that 0.8.5 could not announce with a warning: + - `metric="innerproduct"` raises `ValueError` on the index classes and in `rabitqlib.quant`. Use `"ip"`, which every release accepts and the `metric` properties return. + - `HnswIndex()` without `seed=` draws a seed, as `IvfIndex` and `SymqgIndex` do, instead of using 100. `index.seed` reports it; pass `seed=`, and `num_threads=1` to `add`, for a reproducible build. + - `repr(index)` prints `capacity=` for `HnswIndex` and `routing=` for `IvfIndex`, and no longer prints `max_elements=` for `IvfIndex`. +- The index classes are now the extension's own, without replaced methods: + - A wrong argument raises pybind11's `TypeError`, which lists the supported signature. Messages such as `IvfIndex() got an unexpected keyword argument 'x'` are gone. + - `inspect.signature()` no longer works on the index constructors and methods; `help()` and the type stubs describe them. +- k-means messages name the new parameters: `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`. As for the other parameters, `train` reports an invalid `nbits`; 0.8.5 rejected it when it was set. +- txtai 9.14.0, the first txtai release with a RaBitQ backend, uses the 0.7 forms and fails with this release. It also filters results with `uid != 0xFFFFFFFF`, which no longer matches a missing result (see `int64` IDs below). txtai 9.15.0, the first release with [neuml/txtai#1616](https://github.com/neuml/txtai/pull/1616), works with this release and with 0.8.5 (#213). With txtai 9.14.0, keep `rabitqlib<0.9`. + +## Python changes + +- New `metric="cosine"` for `IvfIndex`, `HnswIndex` and `SymqgIndex` (#212). The index scales data, queries and centroids passed to `set_centroids` to unit length and returns `1 - cos`; results equal those of a `metric="ip"` index built from the scaled vectors and given the scaled centroids (#259). A zero vector stays zero, so its true distance to every vector is 1. The saved file records the metric, so a loaded index keeps scaling. `index.metric` can now return `"cosine"`, and an invalid metric raises `metric must be 'l2', 'ip' or 'cosine'`. See [the cosine metric](../index/usage.md#the-cosine-metric). +- 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 C++ `IvfIndex`, `HnswIndex` and `SymqgIndex` use 64-bit `rabitqlib::Id` values with `kNoId` (-1) for a missing result, as Python does. The indexes still hold 32-bit row numbers inside, so they keep their limit of 2^31 points; the unsupported `ivf::IVF`, `hnsw::HierarchicalNSW` and `symqg::QuantizedGraph` keep `PID` and `kPidMax`. + +- 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. +- k-means training accepts every coordinate that `add` and `search` accept. For many dimensions, including 64, 100, 256, 960 and 1024, `train` and `assign` of `QGKMeans` and `RaBitQKMeans`, and `train` and the first `add`, which trains, of `IvfIndex` and `HnswIndex` rejected a coordinate whose magnitude equals the float32 coordinate bound with `exceeds the safe float32 coordinate range`, although a trained index accepted it. The C++ `rabitqkmeans::RaBitQKMeans` and `qgkmeans::QGKMeans` change the same way. + +- 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. +- An HNSW-RaBitQ file saved before training, which the C++ API of earlier releases allowed, loads untrained, with `num_clusters` 16. Without a recorded seed its first `add` cannot train it, so `add`, `search`, `remove` and `save` raise `RuntimeError: HnswIndex loaded from an untrained file must be trained before add; call train or set_centroids` (naming the operation) until `train` or `set_centroids` runs. +- A new exception, `rabitqlib.FormatError`, subclasses both `ValueError` and `RuntimeError`: + - Every index `load` raises it for a truncated, corrupt, mismatched or unsupported file, in format 2 and in every earlier layout. These were `RuntimeError`, which still catches them. A file that cannot be opened still raises a plain `RuntimeError`. + - `quant.FormatError` is now the same class. It was a subclass of `ValueError` only, which still catches it. +- Messages for damaged or mismatched files change: + - A format-2 file names the problem, for example `IVF index file is 6916 bytes, but its sections end at 6852` for trailing bytes. + - Errors in an HNSW routing graph name the graph rather than the sidecar: `Truncated HNSW centroid graph` and `HNSW centroid graph changed while loading` replace their `sidecar` forms. + - A missing sidecar of an earlier file still raises `Cannot open HNSW centroid sidecar`. + - A failed HNSW-RaBitQ write raises `HNSW index file cannot be written` instead of `HNSW failed to write index file`. +- `pickle.dumps(obj, protocol=0)` or `protocol=1` on a `rabitqlib` object no longer aborts the Python process. `quant.Rotator` and `quant.Query` now pickle with every protocol; the index, k-means, parameter and iteration-statistics classes raise `TypeError: cannot pickle ...`, as they already did with protocol 2 and higher, which include the default. Protocols 0 and 1 cannot reduce pybind11 objects ([pybind11#3745](https://github.com/pybind/pybind11/issues/3745)), so they now use the protocol-2 reduction. +- `quant.Rotator(method="matrix")` now draws a Haar-distributed rotation, uniform over orthogonal matrices. It used the orthogonal factor of a Householder QR factorization as returned, whose determinant is fixed and whose first entry is always negative; each column now takes the sign of the matching diagonal entry of the triangular factor. RaBitQ's codes and estimator do not change when the same rotated coordinate changes sign in every vector and query, and the old rotation was Haar distributed up to such sign changes, so accuracy is not expected to change. A given `seed` now produces a different matrix; rotators saved with `to_bytes()` and saved indexes keep theirs. + +## C++ changes + +- New `rabitqlib::IvfIndex` in `rabitqlib/index/ivf_index.hpp` (#234), with the workflow and defaults of the Python class, which now wraps it, and its messages where they do not name Python values: + - `IvfIndex(dim, num_clusters, options)` takes an `IvfOptions` struct with an `ivf::Routing`, an alias of `ivf::InitializerType`. A static `load` returns a trained index, and `train`, `set_centroids`, `add`, `remove`, `reserve_cluster`, `search` and `save` follow the Python methods. + - The first `add` trains an untrained index and leaves it untrained and empty if it fails. `add` takes an `AddOptions` struct and returns the first new ID. + - IDs are `rabitqlib::Id` (`int64_t`). A missing search result is `kNoId` (-1) with distance `+inf`. + - `search` takes a batch of queries and an `IvfSearchOptions` struct. Without an `nprobe` it probes `num_clusters / 16` clusters, rounded and at least 1, and an explicit 0 throws. + - A seed is drawn unless given, and `num_threads == 0` means every available CPU, capped by `OMP_NUM_THREADS`. + - Arguments out of range throw `std::invalid_argument`, and calls in the wrong state `std::logic_error`. +- 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. +- 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. +- `IvfIndex`, `HnswIndex` and `SymqgIndex` are the supported and documented C++ index API from 0.9. `ivf::IVF`, `hnsw::HierarchicalNSW`, `symqg::QuantizedGraph` and `symqg::QGBuilder` stay installed at their paths and keep their interfaces apart from the changes listed below, but they leave the documentation and carry no compatibility promise. + +Move to the new classes as follows: + +| 0.8 | 0.9 | +| --- | --- | +| `IVF(num_points, dim, num_clusters, bits, ...)`, then `construct(data, centroids, cluster_ids)` | `IvfIndex(dim, num_clusters, options)`, `set_centroids(centroids)`, then `add(data, num_points, add_options)` with `add_options.cluster_ids` | +| `HierarchicalNSW(max_elements, dim, bits, M, ef_construction, seed, metric)`, then `construct(...)` | `HnswIndex(dim, options)` with `options.num_clusters`, then the same two calls; capacity grows on `add` | +| `QuantizedGraph(num_points, dim, max_degree, ...)` with `quantization_bits` 0 for raw vectors, then `QGBuilder(graph, ef_construction, data).build()` | `SymqgIndex(dim, options)` with `options.nbits` 32 for raw vectors, then `add(data, num_points)` | +| `IVF::search`, `IVF::search_batch`, `HierarchicalNSW::search` (nested vectors), `set_ef` with `QuantizedGraph::search_batch` | `search(queries, num_queries, k, ids, distances, search_options)` | +| `Index index; index.load(filename);` | `auto index = IvfIndex::load(filename);`, and likewise `HnswIndex::load` and `SymqgIndex::load` | +| `PID` results, `kPidMax` for a missing IVF or SymphonyQG result | `Id` results, `kNoId` for a missing result | +| `dimension()`, `metric_type()`, `initializer_type()`, `max_elements()` (HNSW), `degree_bound()`, `quantization_bits()` (0 for raw), `num_vertices()`; `IVF::reserve`, `HierarchicalNSW::resize` | `dim()`, `metric()`, `routing()`, `capacity()`, `max_degree()`, `nbits()` (32 for raw), `num_points()`; `reserve_cluster`, `reserve` | +| `IVF::train(num_points, data, cp)`, `HierarchicalNSW::train(num_clusters, num_points, data, cp)`, `HierarchicalNSW::set_centroids(num_clusters, centroids)`; `add` returning `void` or every label | `train(data, num_points)` with `cp()`, `set_centroids(centroids)`, `add` returning the first `Id` | + +Four differences are not renames: `HnswIndex::add` uses every CPU unless `num_threads` is set; `HnswIndex::search` writes all `k` slots, padding with `kNoId` and `+inf`, where `HierarchicalNSW::search` returns only the pairs found; a seed is drawn unless given, where `HierarchicalNSW` defaults to 100; and default thread counts are capped by `OMP_NUM_THREADS`. The new classes do not offer the matrix rotator, rebuilding with `IVF::construct`, shrinking with `HierarchicalNSW::resize`, `HierarchicalNSW::cluster_id_of`, `QuantizedGraph::search_with_scratch` with its warm-start hint, `QGBuilder`'s multi-pass `build(n)`, `reset`, `refine`, `avg_degree`, `check_dup` and `cache_vectors`, or `padded_dim()`; use the existing classes for them. + +- The C++ examples in `sample/cpp` and the IVF `add` hot-path benchmark use the new classes. `symqg_indexing` takes `nbits` (32 for raw vectors, 4 or 8, default 32) and still reads 0 as raw vectors; it no longer prints stage times or the average degree. Its optional thread count 0 selects every available CPU. The default thread counts of `symqg_indexing` and `ivf_rabitq_indexing` are now capped by `OMP_NUM_THREADS`, which they ignored. `ivf_rabitq_indexing`, `hnsw_rabitq_indexing` and `symqg_indexing` accept `cosine` as the metric and reject unknown metric names; all three used to build an L2 index silently. + +- `qgkmeans::QGKMeansParameters` uses the Python names (#233): `graph_degree` becomes `max_degree`, `ef_build` becomes `ef_construction`, and `quantization_bits` (0, 4 or 8) becomes `nbits` (32, 4 or 8, with 32 for raw float32). The fields keep their order and types. An `nbits` of 0 is rejected, so code that initialized the field positionally with 0 must pass 32. `QGAssigner` keeps its constructor, including `quantization_bits` with 0 for raw storage. +- Messages follow the names: `QGKMeans nbits must be 4, 8, or 32`, `QGKMeans max_degree must be a positive multiple of 32`, `QGKMeans requires more centroids than max_degree` and `QGKMeans ef_construction and ef_search must be positive`. +- `FinalAssignmentMode::SymphonyQG`, an alias of `Approximate`, is removed. +- The aliases `qgkmeans::QGKMeansIterationStats` and `rabitqkmeans::RaBitQKMeansIterationStats` are removed; use `clustering::KMeansIterationStats`. + +- `MetricType` gains `METRIC_COSINE`, which `IVF`, `HierarchicalNSW`, `QuantizedGraph` and `default_training_parameters` accept. The indexes normalize their inputs and store inner-product codes; `metric_type()` returns `METRIC_COSINE`. Entry points that validate the metric reject it with their existing messages: the stable core API v1, factor computation in the encoders, the query classes, FastScan queries, clustering and the IVF initializers. Code with an exhaustive `switch` over `MetricType` may warn about the new value. + +- Loading an index throws `rabitqlib::FormatError`, a subclass of `std::runtime_error` in the new header `rabitqlib/index/format_error.hpp`, for a damaged, mismatched or unsupported file. Failing to open the file still throws `std::runtime_error`. Files of earlier layouts that threw other exceptions for invalid contents now throw `FormatError` too: an IVF-RaBitQ file with an invalid metric or a dimension its rotation does not support, which threw `std::invalid_argument`, and a SymphonyQG file with invalid settings or dimensions, which threw `std::invalid_argument` or `std::length_error`. + +- `ivf::Initializer` and its subclasses: + - `save(std::ofstream&, const char*)` becomes `write(std::ostream&)`, and `load(std::ifstream&, const char*)` becomes `read(std::istream&, uint64_t bytes)`. + - The HNSW initializer no longer writes a sidecar itself. +- New accessors report what format-2 files record, or no value when unknown: + - `IVF::seed()`; + - `HierarchicalNSW::seed()`; + - `QuantizedGraph::seed()`, `ef_construction()` and `initialization()`. +- `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. + +- `rabitqlib::ceil_log2` in `rabitqlib/utils/tools.hpp` shifts a `size_t`, so an input of 2^32 or more is no longer undefined on 64-bit Windows, where `unsigned long` has 32 bits (#247). The library does not call it. +- `rabitqlib::distance_ratio` and `rabitqlib::horizontal_avg` are removed from `rabitqlib/utils/tools.hpp` (#262). They were evaluation helpers for the C++ samples, and the library does not call them. `distance_ratio` read out of bounds for a missing result ID (`kNoId` or `kPidMax`), and `horizontal_avg` read out of bounds for empty or ragged input and averaged negative integer columns wrongly, for example `horizontal_avg` gave 1431655764 for three rows of -1. Code that uses them needs its own version that handles these inputs; the samples now average their measurements with a local helper. `tools.hpp` no longer includes ``, so code that used `std::priority_queue` through RaBitQ headers must include `` itself. + +- `MatrixRotator`, which `choose_rotator` returns for `RotatorType::MatrixRotator` and `IVF` and `QuantizedGraph` use when given it, draws a Haar-distributed rotation, as described for `quant.Rotator` above. A given seed now produces a different matrix; saved rotators and indexes keep theirs. + +- The installed CMake package satisfies `find_package(rabitqlib X.Y[.Z])` only when the major and minor versions match: `find_package(rabitqlib 0.8)` no longer finds 0.9, which `SameMajorVersion` compatibility allowed, and a version range must stay within one minor release, such as `0.9...<0.10`. Before 1.0 a minor release may break the API. + +## Upgrading + +From 0.8, first run your code on 0.8.5 and replace every form that raises a +`DeprecationWarning`, using the [migration guide](../python_migration.md#from-08-to-09); +each replacement also works in 0.9. The same section lists the changes that come without +a warning, including `int64` IDs and index format 2. Files saved by every earlier release +load in 0.9, but releases up to 0.8 cannot read files that 0.9 saves, so keep a copy +saved by 0.8 if you may downgrade. Rebuild C++ consumers with matching headers and +libraries; no cross-version C++ binary ABI is promised. + +When upgrading from 0.7, follow the [0.8.0 release notes](0.8.0.md) and the +[migration guide](../python_migration.md). diff --git a/docs/formats.md b/docs/formats.md index 7aa60efb..09fbc9d0 100644 --- a/docs/formats.md +++ b/docs/formats.md @@ -1,6 +1,6 @@ # Byte formats -This is the specification of the byte formats `rabitqlib.quant` reads and writes. It is shared with the planned index format revision, which will add its own blob kinds. While `rabitqlib.quant` is provisional, a release may stop reading an old format version; reading it then raises `quant.FormatError` instead of returning wrong results. A promise that every released version stays readable comes with stabilisation. +This is the specification of the byte formats `rabitqlib.quant` reads and writes. Index files ([format 2](#index-format-2)) use their own container and nest blobs in its sections. While `rabitqlib.quant` is provisional, a release may stop reading an old format version; reading it then raises `rabitqlib.FormatError` (also `quant.FormatError`) instead of returning wrong results. A promise that every released version stays readable comes with stabilisation. Every format has a version. A change to any layout is a new version, never an edit of an existing one. The golden files in `tests/python/fixtures/quant/` freeze each version and are never regenerated. @@ -59,7 +59,7 @@ A blob is a self-describing byte string, such as `Rotator.to_bytes()`. It starts | Offset | Size | Type | Field | Rule | | --- | --- | --- | --- | --- | | 0 | 8 | ASCII | `magic` = `"RABQBLOB"` | Anything else raises `FormatError` | -| 8 | 4 | u32 | `kind` | 1 = rotator; 2 = codec (reserved); 3 and up reserved for index formats. A kind the reader does not expect raises `FormatError` | +| 8 | 4 | u32 | `kind` | 1 = rotator; 2 = codec (reserved); 3 and up reserved. A kind the reader does not expect raises `FormatError` | | 12 | 4 | u32 | `version` | Layout version of this kind; an unknown version raises `FormatError` | | 16 | 4 | u32 | `header_bytes` | Common header plus kind fields, a multiple of 8; it must equal the size the kind and version define | | 20 | 4 | u32 | `flags` | Kind-specific; unknown bits raise `FormatError` | @@ -92,3 +92,283 @@ The body is what `Rotator::save()` writes, and `body_bytes` must equal it | Matrix | The rotation matrix as row-major float32 | `4 * dim * padded_dim` | The body defines the rotation; `seed` only records where it came from. A seeded FHT/Kac rotation is identical on every platform, while a matrix drawn from a seed is reproducible only with the same standard library and build, which is why the matrix itself is stored. + + + +## Index files, format 2 + +> **Status:** 0.9 is the first release that writes format 2 (#211, #212). IVF-RaBitQ, HNSW-RaBitQ and SymphonyQG read and write it, including the cosine metric; the container is `src/index/format2.*`. IVF-SSD and companion files are not implemented, and their parts of this specification may change until a release writes them. + +Format 2 is one container for IVF-RaBitQ, HNSW-RaBitQ and SymphonyQG, and later for the SSD-resident IVF index from RaBitQ-SSD. It replaces the per-index layouts: IVF-RaBitQ `RABQIDX1` version 2 (readers also accept version 1, which no release wrote), its raw-vector layout `RBFQRAW1` and its unversioned layout, the unversioned HNSW-RaBitQ layout, SymphonyQG's quantized version 1 and its raw layout, and the unversioned hnswlib sidecar `.hnsw` of IVF-RaBitQ. Every released layout stays readable (see [Earlier layouts](#earlier-layouts)); `save` always writes format 2. + +The number continues the name used in #212. An index file is told apart from earlier layouts by its magic, not by the version, so the unrelated IVF-RaBitQ `RABQIDX1` version 2 does not clash. The header is not a [blob](#blobs): a blob checksums its whole body, which is too costly for large index files, so index files have their own container and nest blobs in sections. + +Unlike the provisional `rabitqlib.quant` formats above, index files carry the library's full compatibility promise: every format-2 file written by a release stays readable by every later release. + +### Conventions + +- Multi-byte fields are little-endian; types are fixed-width (`u32`, `u64`, `i32`, `f32`, `f64`). No field is `size_t`. +- Offsets are absolute byte offsets from the start of the file. +- The section table starts at a multiple of 8, and every section starts at a multiple of 64, so a reader can map the file and read sections in place. Writers fill gaps with zero bytes, and readers do not inspect them. +- Reserved fields and undefined flag bits are written as zero. A reader rejects a nonzero value unless a rule below says otherwise. +- Enumerations start at 1, so zero always means unset; their values are never reused or renumbered. +- Checksums are CRC-32 as `zlib.crc32` computes it, the same as in [blobs](#blobs). + +### Layout + +| Part | Position | +| --- | --- | +| Header | Offset 0, `header_bytes` long | +| Section table | `section_table_offset`, `section_count` entries of 32 bytes | +| Sections | Anywhere after the header, each at a multiple of 64 | + +Each section starts at or after `header_bytes` and at or after the end (`offset + size`) of the previous table entry, so the table lists sections in file order and no two overlap. An empty section takes no bytes: several may share an offset, and the next section may start at it. Non-empty sections do not overlap the section table; an empty section's offset may fall inside it. The file ends exactly where the table or the last section ends, whichever is later; an empty section still has an aligned offset, so writers pad up to it. + +### Header + +The fields below take 128 bytes. `header_bytes` is a multiple of 8 and at least 128; a later release may append fields without changing `version`, and a reader skips the bytes past the fields it knows, which `header_crc32` still covers (see [Compatibility rules](#compatibility-rules)). + +| Offset | Size | Type | Field | Rule | +| --- | --- | --- | --- | --- | +| 0 | 8 | ASCII | `magic` = `"RABQINDX"` | Anything else is not a format-2 file; the reader tries [earlier layouts](#earlier-layouts) | +| 8 | 4 | u32 | `version` = 2 | Any other value is rejected | +| 12 | 4 | u32 | `header_bytes` | See above | +| 16 | 8 | u64 | `incompat_features` | See [Feature flags](#feature-flags) | +| 24 | 8 | u64 | `ro_compat_features` | | +| 32 | 8 | u64 | `compat_features` | | +| 40 | 4 | u32 | `index_kind` | 1 = IVF-RaBitQ, 2 = HNSW-RaBitQ, 3 = SymphonyQG; 4 = IVF-SSD (reserved). Unknown values are rejected | +| 44 | 4 | u32 | `metric` | 1 = L2, 2 = inner product, 3 = cosine. See [Metrics](#metrics) | +| 48 | 8 | u64 | `dim` | Original dimension, at least 1 | +| 56 | 8 | u64 | `padded_dim` | Working dimension; a multiple of 32, at least `dim` and at most 65,536 (the rotator's limit). Readers use the stored value and never recompute it | +| 64 | 4 | u32 | `code_bits` | Bits per coordinate of the stored quantized code, 1–9; 0 when the index stores no quantized code of its points | +| 68 | 4 | u32 | `raw_type` | Element type of stored raw vectors: 0 = none, 1 = float32, 2 = uint8 | +| 72 | 4 | u32 | `id_bits` | Width of the point IDs stored in the file: 32 or 64 | +| 76 | 4 | u32 | `flags` | Bit 0, `seed_known`: `seed` is valid | +| 80 | 8 | u64 | `seed` | The index's construction seed. Zero when `seed_known` is clear, which a file migrated from an earlier layout has. IVF-RaBitQ: the rotation and training seed, at most 2^32 − 1. HNSW-RaBitQ: the graph-level and training seed, whose low 32 bits seeded the rotation. SymphonyQG: the rotation seed, at most 2^32 − 1, which Python also uses for graph construction. The rotator blob records the rotation seed again | +| 88 | 8 | u64 | `num_points` | Stored points, including removed ones | +| 96 | 8 | u64 | `section_table_offset` | A multiple of 8, at least `header_bytes` | +| 104 | 4 | u32 | `section_count` | At least 1 | +| 108 | 4 | u32 | `header_crc32` | Over the header with this field taken as zero, followed by the section table | +| 112 | 16 | ASCII | `writer_version` | Library version that wrote the file, printable ASCII, NUL-padded. For error messages only: readers neither branch on it nor validate it, and messages show the bytes before the first NUL, with backslashes and bytes outside printable ASCII as `\xNN` | + +The Python `nbits` maps to these fields as follows. IVF-RaBitQ `nbits` 1–9 is `code_bits`. IVF-RaBitQ `nbits = 32` is `code_bits = 1` with `raw_type = float32`, because it keeps 1-bit FastScan codes and reranks with raw vectors. SymphonyQG `nbits = 32` is `code_bits = 0` with `raw_type = float32`. + +### Section table + +| Offset | Size | Type | Field | Rule | +| --- | --- | --- | --- | --- | +| 0 | 4 | u32 | `kind` | See [Section kinds](#section-kinds) | +| 4 | 4 | u32 | `flags` | Bit 0, `required`; bit 1, `checksummed` | +| 8 | 8 | u64 | `offset` | A multiple of 64 | +| 16 | 8 | u64 | `size` | Bytes; may be 0 | +| 24 | 4 | u32 | `crc32` | Over the section's bytes when `checksummed` is set; zero otherwise | +| 28 | 4 | — | reserved | | + +Kind 0 is reserved, and a kind appears at most once. Section flags other than the two above are rejected; a later version cannot add a section flag without a new `version`. Writers checksum the header-like sections (parameters, cluster sizes, companions), whose values size later allocations, and leave bulk data unchecksummed, so that loading a large index does not read it twice. A reader verifies the checksum of a section it knows exactly when `checksummed` is set. Per-point arrays such as `hnsw_levels` count as bulk data: the header fixes their size, and readers check every value against its limit. + +A section the reader does not know is handled by its `required` bit: a required one rejects the file, and an optional one is skipped without reading it, so its checksum is not verified. A writer marks a section optional only if dropping it leaves a correct index, for example a cache that can be recomputed. `save` drops optional sections it does not know. + +### Feature flags + +The three masks follow the ext4 superblock: they say what an older reader may do with a file that uses something newer than itself. + +| Mask | A reader that does not know a set bit | +| --- | --- | +| `incompat_features` | Rejects the file; reading it would give wrong results | +| `ro_compat_features` | May load and search; operations that change or save the index (`add`, `reserve`, `remove`, `save`) raise, because they would leave the unknown data stale. Rebuilding replaces that data and makes the index writable again: IVF-RaBitQ `construct`, or a new SymphonyQG build; HNSW-RaBitQ cannot be rebuilt in place | +| `compat_features` | Ignores the bit; `save` clears it | + +The error names the unknown bits and `writer_version`, such as "index file uses incompatible features 0x4 that this release does not know; written by rabitqlib 0.10.0". + +A writer sets only the bits it knows. Resaving a file therefore drops the unknown `compat` bits, together with the unknown optional sections and header fields past the writer's `header_bytes`. A `compat` bit may describe only data whose loss on such a resave is harmless. + +No bit is defined in version 2. Bits are assigned when a feature needs one. Examples: + +| Possible feature | Mask | Why | +| --- | --- | --- | +| Caller-provided IDs (`add(x, ids=...)`), an external-ID section | `incompat` | An older reader would return row numbers instead of the caller's IDs | +| A per-cluster statistics section that `add` updates | `ro_compat` | An older reader can search, but its `add` would not update the section | +| A new code layout of an existing section | `incompat`, or a new section kind | The bytes mean something else | + +### Metrics + +L2 and inner product are as in [Distance conventions](development.md#distance-conventions). Cosine stores the codes and factors of inner product over L2-normalized vectors. The index normalizes data on `train`, `add` and construction, centroids given to `set_centroids` or construction, and queries on `search`, and reports `1 - cos` as the distance. It is a stored metric, not a flag of the caller, so a reloaded index keeps normalizing. + +Normalization computes `scale = 1 / sqrt(s)` in double precision, where `s` is the sum of the squared coordinates added in coordinate order in double precision; each coordinate is multiplied by `scale` in double precision and rounded once to float32. The product of two float32 values is exact in double precision, so the sum does not depend on whether a compiler fuses multiply and add. A zero vector stays zero, so its true distance to every vector is 1. Every vector section (codes, raw float32 vectors and the IVF rerank vectors) holds the normalized vectors, so a cosine file equals the inner-product file of the normalized vectors except for `metric`. Centroids are stored as trained, or normalized as above when they were given. + +### Point IDs + +Python `search`, `add` and `remove` use `int64` IDs, and a missing search result is `-1` (#211). `id_bits` records what the file stores. The in-memory indexes keep 32-bit row numbers internally and write `id_bits = 32`; their upper limit stays below 2^31 points (the search-buffer marker bit). IVF-SSD writes `id_bits = 64`. A reader rejects an `id_bits` its index kind does not support. + +### Section kinds + +Kinds 1–255 are shared, 256–511 are IVF-RaBitQ, 512–767 HNSW-RaBitQ, 768–1023 SymphonyQG and 1024–1279 IVF-SSD. Writers mark every section listed here `required`. A reader that knows a kind reads the section whatever its `required` bit says; the bit governs only kinds the reader does not know. + +| Kind | Name | Used by | Content | +| --- | --- | --- | --- | +| 1 | `rotator` | All | A [rotator blob](#rotator-kind-1-version-1), byte for byte what `Rotator.to_bytes()` writes. Its `dim` and `padded_dim` must equal the header's. Not checksummed by the container: the blob carries its own CRC-32 | +| 2 | `companions` | IVF-SSD | The [companion table](#companion-files) | +| 256 | `ivf_params` | IVF | `num_clusters` u64; `initializer` u32 (1 = flat, 2 = FlatRaBitQ, 3 = HNSW); reserved u32 | +| 257 | `ivf_cluster_sizes` | IVF | `num_clusters` × u64; the sum equals `num_points` | +| 258 | `ivf_flat_routing` | IVF, flat | The rotated centroids, `num_clusters × padded_dim` f32 | +| 259 | `ivf_flat_rabitq_routing` | IVF, FlatRaBitQ | The rotated centroids as above, the global centroid (their mean, `padded_dim` f32), then `ceil(num_clusters / 32)` [FastScan blocks](#fastscan-blocks-version-1) of the centroids, quantized against the global centroid under the index metric | +| 260 | `ivf_hnsw_routing` | IVF, HNSW | The [HNSW routing graph](#hnsw-routing-graph), byte for byte the `.hnsw` sidecar of earlier releases | +| 261 | `ivf_codes` | IVF | Per cluster in cluster order, `ceil(size / 32)` [FastScan blocks](#fastscan-blocks-version-1). Removed points have `add = +inf` | +| 262 | `ivf_rerank` | IVF, `code_bits > 1` or raw | Per point in cluster order: a [single-code record](#single-code-record) with `b = code_bits - 1`, or `dim` raw values of `raw_type` | +| 263 | `ivf_ids` | IVF | Per point in cluster order, `id_bits`-wide IDs | +| 512 | `hnsw_params` | HNSW | `max_elements`, `num_clusters`, `M`, `upper_max_degree`, `base_max_degree`, `ef_construction` as u64; `level_multiplier` f64; `max_level` i32; reserved u32; `entry_point` u64. Record sizes are derived, not stored (see [HNSW-RaBitQ records](#hnsw-rabitq-records)) | +| 513 | `hnsw_centroids` | HNSW | `num_clusters × padded_dim` f32 | +| 514 | `hnsw_records` | HNSW | `num_points` [base-layer records](#hnsw-rabitq-records) | +| 515 | `hnsw_levels` | HNSW | `num_points` × u32 levels | +| 516 | `hnsw_upper_links` | HNSW | The upper-layer link lists of points with level > 0 in point order; each is `level × upper_links_bytes` | +| 768 | `qg_params` | SymphonyQG | `max_degree` u64; `entry_point` u64; `ef_construction` u64 (0 = unknown); `init` u32 (0 = unknown, 1 = PiPNN, 2 = random); reserved u32 | +| 769 | `qg_centroid` | SymphonyQG, `code_bits > 0` | `padded_dim` f32 | +| 770 | `qg_records` | SymphonyQG | `num_points` [records](#symphonyqg-records) | + +An IVF file has exactly one routing section, the one that `ivf_params` names; a rerank section exactly when `code_bits > 1` or raw vectors are stored. + +`hnsw_levels` replaces the per-point length prefix of the earlier HNSW-RaBitQ layout, so a reader knows every size before reading the link lists. + +### Record layouts + +These are the in-memory layouts the indexes use today, written as is, so that `load` copies sections without converting them. Record sizes follow from the header and parameter sections; readers derive them and compare them with the section sizes. Floats inside records are not aligned. Reserved bytes inside bulk data are written as zero and ignored by readers, which do not scan bulk data for them. + +The tables use `id_bits = 32`, so an ID takes 4 bytes; this is the only value the in-memory indexes write. + +#### Single-code record + +One vector's `b`-bit code with its two factors. IVF-RaBitQ and HNSW-RaBitQ use it for the extra bits (`b = code_bits - 1`), SymphonyQG for its whole code (`b = code_bits`). + +| Offset | Size | Content | +| --- | --- | --- | +| 0 | `padded_dim * b / 8` | The codes as [packed codes](#packed-codes-version-1) of width `b` | +| `padded_dim * b / 8` | 4 | `add`, f32 | +| `padded_dim * b / 8 + 4` | 4 | `rescale`, f32 | + +The record has no `error` factor. + +#### HNSW sign code + +HNSW-RaBitQ stores the 1-bit code in a different bit order from the `rabitqlib.quant` bitset. Split the `padded_dim` coordinates into groups of 64, where the last group has 32 coordinates when `padded_dim` is not a multiple of 64. A group of `G` bytes, read as a little-endian integer, stores coordinate `t` of the group in bit `8G - 1 - t`. This is what `pack_binary_to_bytes` writes (checked against it for `padded_dim` 32, 64, 96, 160 and 1024); the `PackBinaryTest` cases in `tests/unit/rabitqlib/utils/space_test.cpp` check this bit order. + +#### HNSW-RaBitQ records + +Let `L = 4 * (base_max_degree + 1)` and `U = 4 * (upper_max_degree + 1)`. + +| Offset | Size | Content | +| --- | --- | --- | +| 0 | 2 | Base-layer neighbor count, u16 | +| 2 | 2 | Reserved | +| 4 | `4 * base_max_degree` | Base-layer neighbor IDs; entries past the count are unspecified | +| `L` | 4 | Cluster ID, u32; bit 31 is the removal mark (see [HNSW removal](development.md#hnsw-removal)) | +| `L + 4` | 4 | Row ID of the point, u32 | +| `L + 8` | `padded_dim / 8` | [Sign code](#hnsw-sign-code) | +| `L + 8 + padded_dim / 8` | 12 | `add`, `rescale` and `error`, f32 | +| `L + 20 + padded_dim / 8` | | When `code_bits > 1`, a [single-code record](#single-code-record) with `b = code_bits - 1` | + +A point at level `l > 0` has `l` upper-layer link lists in `hnsw_upper_links`, for levels 1 to `l`, each `U` bytes: a u16 count, 2 reserved bytes, then `upper_max_degree` neighbor IDs. + +#### HNSW routing graph + +The centroid graph of IVF-RaBitQ's HNSW routing is the layout hnswlib's `saveIndex` writes. Unlike the rest of format 2 it is not defined field by field by this library, so it is fixed here as written on the supported 64-bit little-endian platforms (`size_t` is 8 bytes, `int` and `unsigned` 4): + +| Offset | Size | Type | Field | Rule | +| --- | --- | --- | --- | --- | +| 0 | 8 | u64 | `offset_level0` | 0 | +| 8 | 8 | u64 | `max_elements` | At least `count` | +| 16 | 8 | u64 | `count` | `num_clusters` | +| 24 | 8 | u64 | `record_bytes` | `label_offset + 8` | +| 32 | 8 | u64 | `label_offset` | `data_offset + 4 * padded_dim` | +| 40 | 8 | u64 | `data_offset` | `4 + 4 * max_m0` | +| 48 | 4 | i32 | `max_level` | The entry point's level, at least 0 | +| 52 | 4 | u32 | `entry_point` | Below `count` | +| 56 | 8 | u64 | `max_m` | `m` | +| 64 | 8 | u64 | `max_m0` | `2 * m` | +| 72 | 8 | u64 | `m` | 2 to 10,000 | +| 80 | 8 | f64 | `level_multiplier` | Finite and positive | +| 88 | 8 | u64 | `ef_construction` | At least `m` | + +Then `count` base records of `record_bytes`: a u16 neighbor count of at most `max_m0`, a flags byte whose bit 0 (hnswlib's deletion mark) must be clear, a reserved byte, `max_m0` u32 neighbor IDs, the rotated centroid (`padded_dim` f32) and its label (u64). Then, per point in order, a u32 byte length followed by that many bytes of upper-layer link lists: `level` lists of `4 + 4 * max_m` bytes each, laid out as in the base record. Every neighbor ID is below `count` and has at least the level of the list that holds it. + +#### SymphonyQG records + +Every vertex has `max_degree` neighbor slots, a multiple of 32. Let `V` be the size of the vector part: `4 * dim` for raw vectors, or the [single-code record](#single-code-record) size with `b = code_bits` otherwise. + +| Offset | Size | Content | +| --- | --- | --- | +| 0 | `V` | The vector: `dim` float32 values (`raw_type = float32`, `code_bits = 0`), or a single-code record | +| `V` | `(max_degree / 32) * (padded_dim * 4 + 256)` | The neighbors' 1-bit codes, quantized against this vertex, as [FastScan blocks](#fastscan-blocks-version-1) without the `error` factor: sign codes, then 32 `add` and 32 `rescale` values | +| `V + (max_degree / 32) * (padded_dim * 4 + 256)` | `4 * max_degree` | Neighbor IDs | + +Unused lanes of a partial neighbor block have zero factors. Their IDs are left over from construction, but like every ID slot they are below `num_points`, which readers check. + +### IVF-RaBitQ files + +Besides the rules above, an IVF-RaBitQ reader requires: + +- `num_points` from 1 to 2^31, and every stored ID below it; +- `code_bits` from 1 to 9, with `raw_type = float32` only when `code_bits = 1`, and `raw_type` none or float32; +- `id_bits = 32`; +- in `ivf_params`, `num_clusters` from 1 to 2^31, `initializer` 1 to 3, and the reserved field zero; +- cluster sizes that add up to `num_points`; +- a seed, when known, of at most 2^32 − 1. + +### HNSW-RaBitQ files + +An HNSW-RaBitQ reader requires `num_points` from 1 to 2^31, `code_bits` from 1 to 9, `raw_type` none, `id_bits = 32`, `dim` at least 64, and an FHT/Kac rotator. In `hnsw_params`: `max_elements` from `num_points` to 2^31; `num_clusters` from 1 to 2^31; `M` from 2 to 10,000, with `upper_max_degree = M` and `base_max_degree = 2 * M`; `ef_construction` at least `M`; a finite positive `level_multiplier`; `max_level` at least 0; `entry_point` below `num_points`; and the reserved field zero. Every level in `hnsw_levels` is at most `max_level`, and the entry point's level equals it. Every record's cluster ID (without the removal mark) is below `num_clusters`, its labels are distinct, its base-layer neighbor count is at most `base_max_degree` and each upper-layer count at most `M`, and every neighbor ID is below `num_points` with at least the level of the list that holds it. + +### SymphonyQG files + +A SymphonyQG reader requires `id_bits = 32` and either raw vectors (`code_bits = 0`, `raw_type = float32`) or `code_bits` 4 or 8 with `raw_type` none; a seed, when known, of at most 2^32 − 1; `num_points` up to 2^31; in `qg_params`, a `max_degree` that is a positive multiple of 32 and below `num_points`, `entry_point` below `num_points`, `init` 0 to 2 and the reserved field zero; `qg_centroid` exactly when the codes are quantized; and every neighbor ID below `num_points`. + +### Companion files + +Only IVF-SSD uses them. `.ssd` holds the page-packed inverted lists, read with `O_DIRECT` and too large to keep in the main file. The `companions` section lists each one: + +| Offset | Size | Type | Field | +| --- | --- | --- | --- | +| 0 | 4 | u32 | `role`: 1 = SSD inverted lists | +| 4 | 4 | u32 | reserved | +| 8 | 32 | ASCII | `suffix` appended to the main file's path, such as `".ssd"`, NUL-padded; no path separators | +| 40 | 8 | u64 | `size` in bytes | +| 48 | 8 | u64 | `fingerprint` | + +`fingerprint` is the 64-bit FNV-1a hash that RaBitQ-SSD already uses (offset basis 1469598103934665603, prime 1099511628211) over the rotated centroids as f32 bytes. It is deterministic, so saving the same index twice gives identical files. + +A companion starts with a 4,096-byte header page: magic `"RABQSSD\0"`, version, `fingerprint`, `num_points` and `code_bits`, then zeros, with a CRC-32 over the page. Data pages follow at offset 4,096, keeping the 4,096-byte alignment that `O_DIRECT` needs. Loading rejects a missing companion, or one whose size, fingerprint or header does not match the main file. + +RaBitQ-SSD's swappable coarse quantizer is not a companion: the base does not pin one. A coarse-quantizer file is its own file and records the base's fingerprint, so the pairing is checked from the coarse side. Its layout is specified when IVF-SSD moves into the library. + +### Reading + +A reader checks, in order, and validates every size before allocating. The loader of each index knows the index kind it expects, so a file of another kind is reported as such before any section is checked: + +1. The file is at least 128 bytes long, and the magic, `version` and `header_bytes` are valid. +2. The section table is non-empty and lies within the file, and `header_crc32` matches. +3. Feature flags, as in the table above. +4. `index_kind` is the expected one; the fields that every kind shares are valid; then the expecting index's own header rules hold. +5. Each table entry, in order: a nonzero kind, its flags and reserved field, a zero `crc32` unless `checksummed` is set, alignment, bounds, the [layout](#layout) rules (order and overlap) and repetition, then whether its kind is known. An unknown required kind rejects the file here. +6. The file ends where the table or the last section ends. +7. Each known checksummed section matches its `crc32`. +8. The index's required sections are present, and each section's size equals what the header and parameter sections imply, before its content is read. + +Steps 1–7 belong to the container; step 8 and the index's header rules in step 4 belong to each index. Readers read through the stream buffer, so the stream's exception mask does not matter, and need seekable input. + +A file that fails any of these checks, or a damaged file of an [earlier layout](#earlier-layouts), raises `rabitqlib::FormatError` in C++, a subclass of `std::runtime_error`, and `rabitqlib.FormatError` in Python, a subclass of both `ValueError` and `RuntimeError`. `rabitqlib.quant` raises the same class for blobs. A file that cannot be opened raises a plain `std::runtime_error` (Python `RuntimeError`). A read that fails after opening cannot be told from a truncated file, so it raises `FormatError`. + +Index files remain trusted input (see [Index file compatibility](docs/index/usage.md#index-file-compatibility)). These checks report truncated, corrupt or mismatched files; they do not make crafted files safe. + +### Writing + +A writer writes the file once, front to back, so it does not need seekable output (`save` writes devices and FIFOs in place): it buffers the checksummed sections, which are small, to know their checksums before the table. `save` writes to a temporary file and renames it into place, as today. With the routing graph inside the main file, IVF-RaBitQ no longer has a second rename that can leave a new sidecar beside an old index. Resaving a file loaded from an earlier layout writes format 2. IVF-SSD companion files are written before the main file, so a failed save never leaves a main file that points to a missing companion. + +### Earlier layouts + +Readers dispatch on the leading bytes: `"RABQINDX"`, then each index's legacy magic (IVF `RABQIDX1` and `RBFQRAW1`, SymphonyQG quantized), then the unversioned fallbacks the readers accept today. Legacy files have no cosine metric, seed or 64-bit IDs; they load as `seed_known = false` with 32-bit IDs, as they do in 0.8. The frozen fixtures in `tests/fixtures/persistence/` keep covering every layout. + +### Compatibility rules + +- A new release reads every earlier released index file. +- An older release reads a newer format-2 file or rejects it with an error naming the problem; it never misreads it. Older releases reject `version` values other than 2, unknown `index_kind`, `metric` or `id_bits` values, unknown required sections and unknown `incompat` bits. +- An additive change appends header fields (raising `header_bytes`), adds sections, or adds feature bits, chosen by the table in [Feature flags](#feature-flags). A change that an older reader cannot detect from these is not allowed; it needs `version = 3`. +- Every released change adds a frozen fixture. Synthetic "future" fixtures check the rules above: an unknown optional section loads; an unknown required section, an `incompat` bit or a larger `version` is rejected with its message; a `ro_compat` bit loads read-only; a longer header loads. diff --git a/docs/maintaining.md b/docs/maintaining.md index ff9dc959..38aa468f 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -229,6 +229,9 @@ Use lowercase prefixes, a space after the colon and a nonempty summary, for exam `fix(ivf): update only affected clusters`. A scope and a `!` marker before the colon are optional. The marker does not change the category or authorize a breaking change; compatibility decisions still follow the project rules. +Add the manual label `release:breaking` to a merged breaking change: its category, +Breaking changes, comes first, so the PR is listed there instead of under its +automatic category. For dependency-only changes, use `deps:` rather than `chore(deps):`. The workflow creates its repository labels as needed and updates only the diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 65679d7e..fbaf0e3c 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -9,11 +9,13 @@ copyright: Copyright © VectorDB Group, Nanyang Technological University nav: - Home: index.md - Quick start: quick_start.md - - Migrating to 0.8: python_migration.md + - Migrating to 0.9: python_migration.md - Installation: installation.md - C++ Integration: cpp_integration.md # Group by minor version: nested groups stay collapsed except the current page's. - Release notes: + - "0.9": + - "0.9.0": releases/0.9.0.md - "0.8": - "0.8.5": releases/0.8.5.md - "0.8.4": releases/0.8.4.md diff --git a/include/rabitqlib/clustering/detail/kmeans.hpp b/include/rabitqlib/clustering/detail/kmeans.hpp index 809dc689..9257ef39 100644 --- a/include/rabitqlib/clustering/detail/kmeans.hpp +++ b/include/rabitqlib/clustering/detail/kmeans.hpp @@ -25,6 +25,7 @@ #include "rabitqlib/index/detail/parallel_exception.hpp" #include "rabitqlib/index/types.hpp" #include "rabitqlib/utils/cpu_features.hpp" +#include "rabitqlib/utils/input_checks.hpp" #include "rabitqlib/utils/space.hpp" #include "rabitqlib/utils/tools.hpp" @@ -32,7 +33,6 @@ namespace rabitqlib::clustering { enum class FinalAssignmentMode : uint8_t { Approximate = 0, - SymphonyQG = Approximate, // Compatibility name for the graph assignment path. Exact = 1, }; @@ -535,12 +535,8 @@ class LloydKMeans : public Parameters { std::string(Assignment::kName) + " input dimensions overflow ptrdiff_t" ); } - // Leave headroom for products of squared distances in graph pruning, - // as well as quantized reconstruction and rotated residuals. - const double max_coordinate = std::sqrt( - std::sqrt(static_cast(std::numeric_limits::max())) / - (64.0 * static_cast(d)) - ); + // The index bound, so training accepts every point the indexes accept. + const float max_coordinate = max_coordinate_magnitude(d); bool in_range = true; bool finite = true; #pragma omp parallel for num_threads(num_workers) reduction(&& : finite, in_range) \ @@ -549,7 +545,7 @@ class LloydKMeans : public Parameters { ++index) { const size_t i = static_cast(index); finite = finite && std::isfinite(x[i]); - in_range = in_range && std::abs(static_cast(x[i])) <= max_coordinate; + in_range = in_range && std::abs(x[i]) <= max_coordinate; } if (!finite) { throw std::invalid_argument( diff --git a/include/rabitqlib/clustering/qgkmeans.hpp b/include/rabitqlib/clustering/qgkmeans.hpp index 280c75f6..96f112c2 100644 --- a/include/rabitqlib/clustering/qgkmeans.hpp +++ b/include/rabitqlib/clustering/qgkmeans.hpp @@ -29,7 +29,6 @@ namespace rabitqlib::qgkmeans { using clustering::FinalAssignmentMode; -using QGKMeansIterationStats = clustering::KMeansIterationStats; namespace detail { @@ -52,14 +51,14 @@ struct QGKMeansParameters { FinalAssignmentMode final_assignment = FinalAssignmentMode::Approximate; // SymphonyQG assignment parameters. - uint32_t graph_degree = 32; - uint32_t ef_build = 240; + uint32_t max_degree = 32; + uint32_t ef_construction = 240; uint32_t ef_search = 16; // Graph-building passes after PiPNN initialization; the last refines the graph. uint32_t graph_build_iterations = 1; uint32_t num_threads = 0; - // Centroid storage in QG: 0 for raw float32, or 4/8-bit RaBitQ. - uint32_t quantization_bits = 0; + // Centroid storage in QG: 32 for raw float32, or 4/8-bit RaBitQ. + uint32_t nbits = 32; // When positive, train on a random sample of k * max_points_per_centroid // vectors if there are more, then assign all vectors; 0 trains on all vectors. size_t max_points_per_centroid = 0; @@ -67,6 +66,11 @@ struct QGKMeansParameters { namespace detail { +// QG's own storage argument, which is 0 for raw float32. +inline uint32_t qg_quantization_bits(const QGKMeansParameters& cp) { + return cp.nbits == 32 ? 0 : cp.nbits; +} + // One training call owns the storage; the public assign adapter can instead // borrow caller storage for one batch. State is read-only while workers run. class QuerySumCache { @@ -136,8 +140,8 @@ class QGAssigner { QGAssigner( size_t d, size_t k, - uint32_t graph_degree, - uint32_t ef_build, + uint32_t max_degree, + uint32_t ef_construction, uint32_t ef_search, uint32_t graph_build_iterations, uint32_t num_threads = 0, @@ -147,18 +151,21 @@ class QGAssigner { ) : dim_(d) , num_clusters_(k) - , graph_degree_(graph_degree) - , ef_build_(ef_build) + , max_degree_(max_degree) + , ef_construction_(ef_construction) , ef_search_(ef_search) , graph_build_iterations_(graph_build_iterations) , seed_(seed) { validate_configuration(num_threads); + // Cosine belongs to the indexes, which normalize vectors; the assigner's exact + // distances are raw L2 or inner product. + validate_metric_type(metric_type); num_workers_ = static_cast(resolve_num_threads(num_threads)); graph_ = std::make_unique>( num_clusters_, dim_, - graph_degree_, + max_degree_, metric_type, RotatorType::FhtKacRotator, quantization_bits, @@ -170,7 +177,7 @@ class QGAssigner { for (uint32_t thread = 0; thread < num_workers_; ++thread) { scratch_.emplace_back( std::make_unique( - graph_->padded_dim(), graph_degree_, ef_search_, 1 + graph_->padded_dim(), max_degree_, ef_search_, 1 ) ); } @@ -207,7 +214,7 @@ class QGAssigner { ); builder_ = std::make_unique( *graph_, - ef_build_, + ef_construction_, centroids, build_threads, symqg::QGInitialization::PiPNN, @@ -284,7 +291,7 @@ class QGAssigner { for (uint32_t thread = 0; thread < num_workers_; ++thread) { scratch.emplace_back( std::make_unique( - graph_->padded_dim(), graph_degree_, ef_search_, 1 + graph_->padded_dim(), max_degree_, ef_search_, 1 ) ); } @@ -367,19 +374,19 @@ class QGAssigner { "QGKMeans currently requires dimensions in the range [64, 65536]" ); } - if (graph_degree_ == 0 || graph_degree_ % fastscan::kBatchSize != 0) { + if (max_degree_ == 0 || max_degree_ % fastscan::kBatchSize != 0) { throw std::invalid_argument( - "QGKMeans graph degree must be a positive multiple of 32" + "QGKMeans max_degree must be a positive multiple of 32" ); } - if (num_clusters_ <= graph_degree_) { + if (num_clusters_ <= max_degree_) { + throw std::invalid_argument("QGKMeans requires more centroids than max_degree"); + } + if (ef_construction_ == 0 || ef_search_ == 0) { throw std::invalid_argument( - "QGKMeans requires more centroids than the graph degree" + "QGKMeans ef_construction and ef_search must be positive" ); } - if (ef_build_ == 0 || ef_search_ == 0) { - throw std::invalid_argument("QGKMeans ef_build and ef_search must be positive"); - } if (graph_build_iterations_ == 0) { throw std::invalid_argument("QGKMeans graph_build_iterations must be positive"); } @@ -387,8 +394,8 @@ class QGAssigner { size_t dim_; size_t num_clusters_; - uint32_t graph_degree_; - uint32_t ef_build_; + uint32_t max_degree_; + uint32_t ef_construction_; uint32_t ef_search_; uint32_t graph_build_iterations_; uint32_t num_workers_ = 0; @@ -416,14 +423,14 @@ class CentroidGraphCache { , assigner( d, k, - cp.graph_degree, - cp.ef_build, + cp.max_degree, + cp.ef_construction, cp.ef_search, cp.graph_build_iterations, cp.num_threads, cp.seed, cp.spherical ? METRIC_IP : METRIC_L2, - cp.quantization_bits + qg_quantization_bits(cp) ) { // The builder borrows this copy, which lives as long as the graph. assigner.rebuild_centroid_graph(centroids.data()); @@ -436,11 +443,10 @@ class CentroidGraphCache { return centroids.size() == k * d && std::equal(centroids.begin(), centroids.end(), source) && p.spherical == cp.spherical && p.seed == cp.seed && - p.graph_degree == cp.graph_degree && p.ef_build == cp.ef_build && - p.ef_search == cp.ef_search && + p.max_degree == cp.max_degree && + p.ef_construction == cp.ef_construction && p.ef_search == cp.ef_search && p.graph_build_iterations == cp.graph_build_iterations && - p.num_threads == cp.num_threads && - p.quantization_bits == cp.quantization_bits; + p.num_threads == cp.num_threads && p.nbits == cp.nbits; } }; @@ -513,9 +519,8 @@ class QGAssignment { static constexpr const char* kName = "QGKMeans"; static void validate_parameters(size_t, const QGKMeansParameters& cp) { - if (cp.quantization_bits != 0 && cp.quantization_bits != 4 && - cp.quantization_bits != 8) { - throw std::invalid_argument("QGKMeans quantization_bits must be 0, 4, or 8"); + if (cp.nbits != 4 && cp.nbits != 8 && cp.nbits != 32) { + throw std::invalid_argument("QGKMeans nbits must be 4, 8, or 32"); } } @@ -532,18 +537,18 @@ class QGAssignment { , num_points_(n) , num_workers_(num_workers) , metric_type_(cp.spherical ? METRIC_IP : METRIC_L2) - , quantized_(cp.quantization_bits != 0) + , quantized_(cp.nbits != 32) , assigner_( d, k, - cp.graph_degree, - cp.ef_build, + cp.max_degree, + cp.ef_construction, cp.ef_search, cp.graph_build_iterations, cp.num_threads, cp.seed, metric_type_, - cp.quantization_bits + qg_quantization_bits(cp) ) , query_sums_(assigner_.graph_->padded_dim(), cp) {} diff --git a/include/rabitqlib/clustering/rabitqkmeans.hpp b/include/rabitqlib/clustering/rabitqkmeans.hpp index 7550ed4d..a8d37e65 100644 --- a/include/rabitqlib/clustering/rabitqkmeans.hpp +++ b/include/rabitqlib/clustering/rabitqkmeans.hpp @@ -25,7 +25,6 @@ namespace rabitqlib::rabitqkmeans { using clustering::FinalAssignmentMode; -using RaBitQKMeansIterationStats = clustering::KMeansIterationStats; struct RaBitQKMeansParameters { // Number of clustering iterations. diff --git a/include/rabitqlib/core/metric.hpp b/include/rabitqlib/core/metric.hpp index b65a6f08..bb0f49bc 100644 --- a/include/rabitqlib/core/metric.hpp +++ b/include/rabitqlib/core/metric.hpp @@ -4,7 +4,9 @@ #include namespace rabitqlib { -enum MetricType : uint8_t { METRIC_L2, METRIC_IP }; +// METRIC_COSINE is accepted only by the ANN indexes, which normalize vectors and +// store inner-product codes; quantizers, FastScan and clustering reject it. +enum MetricType : uint8_t { METRIC_L2, METRIC_IP, METRIC_COSINE }; inline void validate_metric_type(MetricType metric_type) { if (metric_type != METRIC_L2 && metric_type != METRIC_IP) { diff --git a/include/rabitqlib/core/rotator.hpp b/include/rabitqlib/core/rotator.hpp index 789ba4e0..fc277b05 100644 --- a/include/rabitqlib/core/rotator.hpp +++ b/include/rabitqlib/core/rotator.hpp @@ -101,6 +101,16 @@ class MatrixRotator : public Rotator { qr.householderQ() .transpose(); // The inverse of an orthogonal matrix is its transpose. + // Householder Q alone is not Haar distributed (its determinant is fixed). Giving + // column i of Q, row i of q_inv, the sign of R(i, i) makes it Haar (Mezzadri, + // Notices AMS 2007, Section 5); only the copied rows matter. + const auto r_diag = qr.matrixQR().diagonal(); + for (Eigen::Index i = 0; i < static_cast(dim); ++i) { + if (r_diag(i) < T(0)) { + q_inv.row(i) *= T(-1); + } + } + // the random matrix only need the first dim rows, since we just pad zeros for // the vector to be rotated to padded dimension std::memcpy(&rand_mat_(0, 0), &q_inv(0, 0), sizeof(T) * dim * padded_dim); diff --git a/include/rabitqlib/index/format_error.hpp b/include/rabitqlib/index/format_error.hpp new file mode 100644 index 00000000..104a7374 --- /dev/null +++ b/include/rabitqlib/index/format_error.hpp @@ -0,0 +1,19 @@ +#pragma once + +#include + +namespace rabitqlib { + +/** + * @brief An index file whose contents are invalid, or which this release cannot read. + * + * Loading any index throws it for a damaged, mismatched or unsupported file in every + * layout; failing to open the file is a plain std::runtime_error. Python raises it as + * rabitqlib.FormatError, a subclass of both ValueError and RuntimeError. + */ +class FormatError : public std::runtime_error { + public: + using std::runtime_error::runtime_error; +}; + +} // namespace rabitqlib diff --git a/include/rabitqlib/index/hnsw/hnsw.hpp b/include/rabitqlib/index/hnsw/hnsw.hpp index 001ffc65..b5c6debb 100644 --- a/include/rabitqlib/index/hnsw/hnsw.hpp +++ b/include/rabitqlib/index/hnsw/hnsw.hpp @@ -7,9 +7,11 @@ #include #include #include +#include #include #include #include +#include #include #include #include @@ -69,7 +71,12 @@ class HierarchicalNSW { [[nodiscard]] size_t nbits() const { return ex_bits_ + 1; } [[nodiscard]] size_t M() const { return M_; } [[nodiscard]] size_t ef_construction() const { return ef_construction_; } - [[nodiscard]] MetricType metric_type() const { return metric_type_; } + [[nodiscard]] MetricType metric_type() const { + return cosine_ ? METRIC_COSINE : metric_type_; + } + // The construction seed, or no value for an index loaded from a file that does not + // record it (files from releases up to 0.8). + [[nodiscard]] std::optional seed() const { return seed_; } // Logical capacity, nonremoved points, and stored records (including removals). [[nodiscard]] size_t max_elements() const { return max_elements_; } [[nodiscard]] size_t num_points() const { @@ -105,7 +112,8 @@ class HierarchicalNSW { * these centroids; the first add into the empty graph links like construct. * * @param num_clusters Number of centroids, from 1 through 2^31 - * @param centroids Centroid vectors (num_clusters * dim) in the original coordinates + * @param centroids Centroid vectors (num_clusters * dim) in the original coordinates; + * a cosine index scales them to unit length, as it does data */ void set_centroids(size_t num_clusters, const float* centroids); @@ -128,6 +136,7 @@ class HierarchicalNSW { ); // Centroids and data use the original dimension; cluster_ids has num_points entries. + // A cosine index scales the data and the centroids to unit length. // Input buffers must remain valid until this synchronous call returns or throws; // the index retains no pointers to them afterward. // fast_quantization selects fixed-scale extra-bit quantization instead of exact scale @@ -205,7 +214,8 @@ class HierarchicalNSW { size_t remove(const PID* labels, size_t num_points); // Queries use the original dimension. Each result is (distance, external label), - // where distance estimates squared L2 or 1 - dot according to the index metric. + // where distance estimates squared L2, 1 - dot or 1 - cos according to the index + // metric. // ef_search is raised to k and clamped to the stored point count. An empty index, // trained or not, returns no results. std::vector>> search( @@ -220,6 +230,10 @@ class HierarchicalNSW { // Borrows construct() input only while its workers run; cleared on success or failure. const float* construction_data_{nullptr}; + // set_centroids with given = true scales the centroids of a cosine index to unit + // length, as data and queries are; train passes centroids trained on scaled data. + void set_centroids_impl(size_t num_clusters, const float* centroids, bool given); + friend struct HnswTestAccess; friend struct detail::HnswSearchAccess; @@ -239,7 +253,8 @@ class HierarchicalNSW { size_t upper_layer_max_degree_{0}; size_t base_layer_max_degree_{0}; size_t ef_construction_{0}; - MetricType metric_type_{METRIC_L2}; + MetricType metric_type_{METRIC_L2}; // METRIC_IP for the cosine metric + bool cosine_{false}; // normalize data, queries, given centroids; metric_type_ is IP double level_multiplier_{0.0}; // max_level_ == -1 and entry_point_id_ == kPidMax mark an empty graph. @@ -284,6 +299,10 @@ class HierarchicalNSW { std::unordered_map label_lookup_; std::default_random_engine level_generator_; + std::optional seed_; // the construction seed, when known + // Loaded from a file with read-only-compatible features this release does not know: + // search works, but add, resize, remove and save refuse the index. + bool read_only_ = false; std::unique_ptr visited_set_pool_{nullptr}; @@ -381,9 +400,20 @@ class HierarchicalNSW { int random_level(double multiplier); - // Write the index file at exactly this path. + // Write the index file in format 2 at exactly this path. void write_file(const char* filename) const; + // Read a file into this freshly created index: format 2, or the earlier layout. + void read_format2(std::istream& input); + void read_legacy(std::ifstream& input); + + // Check the loaded records and link lists, and rebuild what they imply: the label + // lookup and the removed-point count. + void validate_graph(); + + // Refuse an operation that would modify or save a read-only index. + void check_writable(const char* operation) const; + // A link list is a count header followed by neighbor IDs. [[nodiscard]] PID* upper_layer_links(PID internal_id, int level) { return reinterpret_cast( diff --git a/include/rabitqlib/index/hnsw_index.hpp b/include/rabitqlib/index/hnsw_index.hpp new file mode 100644 index 00000000..e8cf5103 --- /dev/null +++ b/include/rabitqlib/index/hnsw_index.hpp @@ -0,0 +1,199 @@ +#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. A file saved before training 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. + * A cosine index scales the centroids to unit length, as it does data. + * + * @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. + * An index loaded from a file saved before training has no seed, so add does not + * train it; call train or set_centroids first. + * + * @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/ivf/detail/hnsw_sidecar.hpp b/include/rabitqlib/index/ivf/detail/hnsw_sidecar.hpp index 32bde339..080a42ef 100644 --- a/include/rabitqlib/index/ivf/detail/hnsw_sidecar.hpp +++ b/include/rabitqlib/index/ivf/detail/hnsw_sidecar.hpp @@ -5,37 +5,40 @@ #include #include #include -#include #include +#include #include #include -#include +#include "rabitqlib/index/format_error.hpp" #include "rabitqlib/third/hnswlib/hnswlib.h" -#include "rabitqlib/utils/path.hpp" namespace rabitqlib::ivf::detail { -// The HNSW initializer stores its graph at the index path plus this suffix. Saving, -// loading and atomic replacement must all agree on it. +// Releases before index format 2 stored the HNSW routing graph at the index path plus +// this suffix; loading those files reads it from there. inline constexpr char kHnswSidecarSuffix[] = ".hnsw"; -// hnswlib's native sidecar has no version tag. Check the existing writer's -// header and record lengths before its loader uses offsets or allocates links. -// As with the main index file, callers must not mutate the file during loading. -inline void validate_hnsw_sidecar_file( - const std::string& path, size_t expected_count, size_t vector_bytes +// hnswlib's native layout has no version tag. Check the header and record lengths of +// the `bytes` bytes at the current position of `input` before hnswlib's loader uses +// offsets or allocates links, then restore the position. As with the index file, +// callers must not mutate the data during loading. +inline void validate_hnsw_graph( + std::istream& input, uint64_t bytes, size_t expected_count, size_t vector_bytes ) { - std::ifstream input(io_impl::filesystem_path(path), std::ios::binary | std::ios::ate); - if (!input) { - throw std::runtime_error("Cannot open HNSW centroid sidecar"); + const std::streampos begin = input.tellg(); + if (begin == std::streampos(std::streamoff(-1))) { + throw FormatError("Cannot read HNSW centroid graph"); } - const auto end = input.tellg(); - input.seekg(0); + // Stay within the graph's bytes, as a budget rather than by querying the position: + // in an index file, other data follows them. + auto remaining = static_cast(bytes); const auto read = [&](auto& value) { - if (!input.read(reinterpret_cast(&value), sizeof(value))) { - throw std::runtime_error("Truncated HNSW centroid sidecar"); + if (remaining < static_cast(sizeof(value)) || + !input.read(reinterpret_cast(&value), sizeof(value))) { + throw FormatError("Truncated HNSW centroid graph"); } + remaining -= static_cast(sizeof(value)); }; size_t level0_offset = 0, capacity = 0, count = 0, level0_record_bytes = 0; size_t label_offset = 0, data_offset = 0; @@ -58,12 +61,12 @@ inline void validate_hnsw_sidecar_file( read(ef_construction); if (count != expected_count || count == 0 || capacity < count || count > std::numeric_limits::max()) { - throw std::runtime_error("HNSW centroid count does not match IVF cluster count"); + throw FormatError("HNSW centroid count does not match IVF cluster count"); } constexpr size_t kMaxM = 10000; // hnswlib caps M at this value. if (m < 2 || m > kMaxM || max_m != m || max_m0 != 2 * m || !std::isfinite(mult) || mult <= 0 || ef_construction < m) { - throw std::runtime_error("Invalid HNSW centroid graph parameters"); + throw FormatError("Invalid HNSW centroid graph parameters"); } const size_t upper_layer_links_bytes = sizeof(hnswlib::linklistsizeint) + max_m * sizeof(hnswlib::tableint); @@ -73,14 +76,13 @@ inline void validate_hnsw_sidecar_file( data_offset > label_offset || label_offset > level0_record_bytes || label_offset - data_offset != vector_bytes || level0_record_bytes - label_offset != sizeof(hnswlib::labeltype)) { - throw std::runtime_error("HNSW centroid layout does not match IVF dimension"); + throw FormatError("HNSW centroid layout does not match IVF dimension"); } if (max_level < 0 || entry >= count) { - throw std::runtime_error("Invalid HNSW centroid entry point or maximum level"); + throw FormatError("Invalid HNSW centroid entry point or maximum level"); } - auto remaining = end - input.tellg(); - if (remaining < 0 || count > static_cast(remaining) / level0_record_bytes) { - throw std::runtime_error("Truncated HNSW centroid base records"); + if (count > static_cast(remaining) / level0_record_bytes) { + throw FormatError("Truncated HNSW centroid base records"); } const auto level0_records_bytes = static_cast(count * level0_record_bytes); @@ -89,14 +91,10 @@ inline void validate_hnsw_sidecar_file( size_t highest_level = 0, entry_level = 0; for (size_t i = 0; i < count; ++i) { unsigned int link_bytes = 0; // Native type written by hnswlib::saveIndex. - if (remaining < static_cast(sizeof(link_bytes))) { - throw std::runtime_error("Truncated HNSW centroid sidecar"); - } read(link_bytes); - remaining -= static_cast(sizeof(link_bytes)); if (link_bytes % upper_layer_links_bytes != 0 || link_bytes > static_cast(remaining)) { - throw std::runtime_error("Invalid HNSW centroid upper-link length"); + throw FormatError("Invalid HNSW centroid upper-link length"); } const size_t levels = link_bytes / upper_layer_links_bytes; highest_level = std::max(highest_level, levels); @@ -112,8 +110,10 @@ inline void validate_hnsw_sidecar_file( } if (!input || remaining != 0 || highest_level != static_cast(max_level) || entry_level != highest_level) { - throw std::runtime_error("Invalid HNSW centroid level structure"); + throw FormatError("Invalid HNSW centroid level structure"); } + input.clear(); + input.seekg(begin); } inline void validate_hnsw_centroid_graph(const hnswlib::HierarchicalNSW& graph) { @@ -121,11 +121,11 @@ inline void validate_hnsw_centroid_graph(const hnswlib::HierarchicalNSW& if (graph.enterpoint_node_ >= count || graph.maxlevel_ < 0 || graph.element_levels_[graph.enterpoint_node_] != graph.maxlevel_ || graph.num_deleted_ != 0) { - throw std::runtime_error("Invalid HNSW centroid entry point or deletion state"); + throw FormatError("Invalid HNSW centroid entry point or deletion state"); } for (size_t i = 0; i < count; ++i) { if (graph.element_levels_[i] < 0 || graph.element_levels_[i] > graph.maxlevel_) { - throw std::runtime_error("Invalid HNSW centroid node level"); + throw FormatError("Invalid HNSW centroid node level"); } for (int level = 0; level <= graph.element_levels_[i]; ++level) { const char* links = @@ -136,7 +136,7 @@ inline void validate_hnsw_centroid_graph(const hnswlib::HierarchicalNSW& uint16_t degree = 0; // The high two bytes hold flags, not the degree. std::memcpy(°ree, links, sizeof(degree)); if (degree > (level == 0 ? graph.maxM0_ : graph.maxM_)) { - throw std::runtime_error("Invalid HNSW centroid neighbor count"); + throw FormatError("Invalid HNSW centroid neighbor count"); } for (size_t j = 0; j < degree; ++j) { hnswlib::tableint neighbor = 0; @@ -146,9 +146,7 @@ inline void validate_hnsw_centroid_graph(const hnswlib::HierarchicalNSW& sizeof(neighbor) ); if (neighbor >= count || graph.element_levels_[neighbor] < level) { - throw std::runtime_error( - "Invalid HNSW centroid neighbor or target level" - ); + throw FormatError("Invalid HNSW centroid neighbor or target level"); } } } diff --git a/include/rabitqlib/index/ivf/initializer.hpp b/include/rabitqlib/index/ivf/initializer.hpp index 618d6731..1104965a 100644 --- a/include/rabitqlib/index/ivf/initializer.hpp +++ b/include/rabitqlib/index/ivf/initializer.hpp @@ -3,10 +3,12 @@ #include #include #include +#include #include -#include #include +#include #include +#include #include #include #include @@ -15,6 +17,7 @@ #include "rabitqlib/core/metric.hpp" #include "rabitqlib/index/detail/parallel_for.hpp" +#include "rabitqlib/index/format_error.hpp" #include "rabitqlib/index/ivf/detail/hnsw_sidecar.hpp" #include "rabitqlib/index/ivf/types.hpp" // IWYU pragma: export #include "rabitqlib/index/types.hpp" @@ -61,8 +64,11 @@ class Initializer { virtual void centroids_distances( const float* query, size_t nprobe, std::vector>& candidates ) const = 0; - virtual void load(std::ifstream& input, const char* filename) = 0; - virtual void save(std::ofstream& output, const char* filename) const = 0; + // Write the routing data that read() restores. + virtual void write(std::ostream& output) const = 0; + // Read `bytes` bytes that write() wrote, from the current position of `input`. + // Data that does not fit this initializer raises FormatError. + virtual void read(std::istream& input, uint64_t bytes) = 0; }; inline Initializer::~Initializer() = default; @@ -113,8 +119,8 @@ class FlatInitializer : public Initializer { std::copy_n(centroid_candidates.begin(), num_probes, candidates.begin()); } - // The flat initializer stores its centroids inline in the index file stream. - void save(std::ofstream& output, const char* /*filename*/) const override { + // The flat initializer stores only its centroids. + void write(std::ostream& output) const override { output.write( reinterpret_cast(centroids_.data()), static_cast(sizeof(float) * dim_ * num_cluster_) @@ -124,13 +130,15 @@ class FlatInitializer : public Initializer { } } - void load(std::ifstream& input, const char* /*filename*/) override { + void read(std::istream& input, uint64_t bytes) override { + if (bytes != sizeof(float) * dim_ * num_cluster_) { + throw FormatError("IVF Flat initializer data has the wrong size"); + } input.read( - reinterpret_cast(centroids_.data()), - static_cast(sizeof(float) * dim_ * num_cluster_) + reinterpret_cast(centroids_.data()), static_cast(bytes) ); if (!input) { - throw std::runtime_error("IVF Flat initializer cannot be read"); + throw FormatError("IVF Flat initializer cannot be read"); } } }; @@ -153,8 +161,8 @@ class FlatRaBitQInitializer : public Initializer { void centroids_distances( const float* query, size_t nprobe, std::vector>& candidates ) const override; - void save(std::ofstream& output, const char* filename) const override; - void load(std::ifstream& input, const char* filename) override; + void write(std::ostream& output) const override; + void read(std::istream& input, uint64_t bytes) override; }; // Keep centroid routing on the same runtime-selected distance kernels as flat IVF. @@ -291,28 +299,30 @@ class HNSWInitializer : public Initializer { } } - // The HNSW initializer stores its graph in a separate hnswlib sidecar file. - void save(std::ofstream& /*output*/, const char* filename) const override { - alg_hnsw_->saveIndex(std::string(filename) + detail::kHnswSidecarSuffix); - } + // The HNSW initializer stores its graph in hnswlib's own layout, which earlier + // releases wrote to the sidecar file .hnsw. + void write(std::ostream& output) const override { alg_hnsw_->saveIndex(output); } - void load(std::ifstream& /*input*/, const char* filename) override { - const std::string sidecar = std::string(filename) + detail::kHnswSidecarSuffix; - detail::validate_hnsw_sidecar_file(sidecar, num_cluster_, space_->get_data_size()); - alg_hnsw_->loadIndex(sidecar, space_, num_cluster_); + void read(std::istream& input, uint64_t bytes) override { + detail::validate_hnsw_graph(input, bytes, num_cluster_, space_->get_data_size()); + alg_hnsw_->loadIndex(input, static_cast(bytes), space_, num_cluster_); const auto& graph = *alg_hnsw_; - // validate_hnsw_sidecar_file already checked these header fields, and loadIndex - // reads them again from a second open of the file. Recheck the loaded values so - // a sidecar replaced in between cannot give centroid() an out-of-record offset. + // validate_hnsw_graph already checked these header fields, and loadIndex reads + // them again. Recheck the loaded values so that data changed in between cannot + // give centroid() an out-of-record offset. if (graph.offsetData_ > graph.label_offset_ || graph.label_offset_ > graph.size_data_per_element_ || graph.label_offset_ - graph.offsetData_ != space_->get_data_size() || graph.size_data_per_element_ - graph.label_offset_ != sizeof(hnswlib::labeltype)) { - throw std::runtime_error("HNSW centroid sidecar changed while loading"); + throw FormatError("HNSW centroid graph changed while loading"); } detail::validate_hnsw_centroid_graph(graph); - rebuild_label_lookup(); + try { + rebuild_label_lookup(); + } catch (const std::runtime_error& error) { + throw FormatError(error.what()); // stored labels that do not fit + } } ~HNSWInitializer() override = default; diff --git a/include/rabitqlib/index/ivf/ivf.hpp b/include/rabitqlib/index/ivf/ivf.hpp index 745ed983..f1f16f91 100644 --- a/include/rabitqlib/index/ivf/ivf.hpp +++ b/include/rabitqlib/index/ivf/ivf.hpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -90,11 +91,16 @@ class IVF { size_t num_clusters_ = 0; bool raw_reranking_ = false; // raw vectors replace extra-bit codes bool ready_ = false; // centroids set, construction or loading completed - size_t ex_bits_ = 0; // total bits = ex_bits_ + 1; 0 with raw reranking + // Loaded from a file with read-only-compatible features this release does not know: + // search works, but add, reserve, remove and save refuse the index. + bool read_only_ = false; + std::optional seed_; // the construction seed, when known + size_t ex_bits_ = 0; // total bits = ex_bits_ + 1; 0 with raw reranking RotatorType rotator_type_ = RotatorType::FhtKacRotator; std::unique_ptr> rotator_; std::vector clusters_; - MetricType metric_type_ = METRIC_L2; + MetricType metric_type_ = METRIC_L2; // METRIC_IP for the cosine metric + bool cosine_ = false; // normalize data, queries, given centroids; metric_type_ is IP float (*ip_func_)(const float*, const uint8_t*, size_t) = nullptr; static constexpr uint64_t kRawFormatMagic = 0x3157415251464252ULL; @@ -157,6 +163,10 @@ class IVF { [[nodiscard]] std::unique_ptr make_initializer() const; + // set_centroids with given = true scales the centroids of a cosine index to unit + // length, as data and queries are; train passes centroids trained on scaled data. + void set_centroids_impl(const float* centroids, size_t num_threads, bool given); + // Reset the index and allocate a new initializer and per-cluster storage void allocate_storage(const std::vector& cluster_sizes); @@ -190,9 +200,22 @@ class IVF { const float* query, size_t k, size_t nprobe, const PID* result_ids ) const; - // Write the index file, and any initializer sidecar, at exactly this path. + // Write the index file in format 2 at exactly this path. void write_file(const char* filename) const; + // Load a format-2 file into this freshly created index. + void read_format2(std::istream& input); + + // Bytes of Flat or FlatRaBitQ routing data; HNSW routing has no fixed size. + [[nodiscard]] size_t flat_routing_bytes() const; + + // Check the stored IDs, create the cluster views, count removed points and mark the + // index ready: the end of loading in every format. + void complete_load(const std::vector& cluster_sizes); + + // Refuse an operation that would modify or save a read-only index. + void check_writable(const char* operation) const; + public: explicit IVF() noexcept; // dim is the original input dimension; total_bits is 1-9 for quantized @@ -246,7 +269,12 @@ class IVF { [[nodiscard]] size_t num_stored_points() const { return ready_ ? max_elements_ : 0; } [[nodiscard]] size_t dimension() const { return dim_; } [[nodiscard]] size_t nbits() const { return raw_reranking_ ? 32 : ex_bits_ + 1; } - [[nodiscard]] MetricType metric_type() const { return metric_type_; } + [[nodiscard]] MetricType metric_type() const { + return cosine_ ? METRIC_COSINE : metric_type_; + } + // The rotation seed of the seeded constructor, or no value when it is unknown: the + // point-count constructor draws one, and files from releases up to 0.8 omit it. + [[nodiscard]] std::optional seed() const { return seed_; } [[nodiscard]] RotatorType rotator_type() const { return rotator_type_; } [[nodiscard]] InitializerType initializer_type() const { return initializer_type_; } // Centroids are set, by train, set_centroids, construct or load. @@ -275,7 +303,8 @@ class IVF { * * Builds the centroid initializer and empty clusters, so the index can add points. * An index created with a point count is built by construct instead, so this - * throws std::logic_error for it. The index is unchanged if this throws. + * throws std::logic_error for it. The index is unchanged if this throws. A cosine + * index scales the centroids to unit length, as it does data. * * @param centroids Centroid vectors (num_clusters() * dim) * @param num_threads Threads used to build the centroid initializer @@ -287,7 +316,8 @@ class IVF { /** * @brief Quantize every point into its cluster and build the centroid initializer. * - * Replaces any existing contents of the index. + * Replaces any existing contents of the index. A cosine index scales the data and + * the centroids to unit length. * * @param data Data points (max_elements() * dim) * @param centroids Centroid vectors (num_clusters() * dim) @@ -372,7 +402,7 @@ class IVF { void load(const char* filename); // Automatically use HACC for 4-9 quantized bits; use standard FastScan otherwise. - // Distances estimate squared L2 or 1 - dot according to the index metric. + // Distances estimate squared L2, 1 - dot or 1 - cos according to the index metric. // k may exceed the point count; slots without a result get kPidMax and +inf. void search( const float* query, diff --git a/include/rabitqlib/index/ivf/types.hpp b/include/rabitqlib/index/ivf/types.hpp index f487e693..e1a93f28 100644 --- a/include/rabitqlib/index/ivf/types.hpp +++ b/include/rabitqlib/index/ivf/types.hpp @@ -4,4 +4,6 @@ namespace rabitqlib::ivf { enum class InitializerType : uint32_t { Auto = 0, Flat = 1, FlatRaBitQ = 2, HNSW = 3 }; +// Centroid routing of IvfIndex. Auto resolves by cluster count when the index is created. +using Routing = InitializerType; } // namespace rabitqlib::ivf diff --git a/include/rabitqlib/index/ivf_index.hpp b/include/rabitqlib/index/ivf_index.hpp new file mode 100644 index 00000000..0a132d9f --- /dev/null +++ b/include/rabitqlib/index/ivf_index.hpp @@ -0,0 +1,196 @@ +#pragma once + +#include +#include +#include +#include + +#include "rabitqlib/core/metric.hpp" // IWYU pragma: export +#include "rabitqlib/index/ivf/types.hpp" // IWYU pragma: export +#include "rabitqlib/index/types.hpp" // IWYU pragma: export + +namespace rabitqlib { +namespace ivf { +class IVF; +} +namespace rabitqkmeans { +struct RaBitQKMeansParameters; +} + +// Settings of a new IvfIndex; set the fields by name. The metric comes first, so a lone +// positional value must be a metric: {4} does not compile. +struct IvfOptions { + MetricType metric = METRIC_L2; // METRIC_L2, METRIC_IP or METRIC_COSINE + size_t nbits = 7; // 1-9 quantization bits, or 32 for raw vectors + ivf::Routing routing = ivf::Routing::Auto; + std::optional seed; // rotation seed; no value draws one +}; + +// Settings of IvfIndex::search. +struct IvfSearchOptions { + // Clusters to probe; a value above num_clusters() probes every cluster. No value + // probes num_clusters() / 16, rounded, and at least 1; 0 throws. + std::optional nprobe; + // Worker count; 0 selects every available CPU, capped by OMP_NUM_THREADS. + size_t num_threads = 1; + // HACC reranking. No value selects it for 4-9 bits and standard FastScan otherwise. + std::optional high_accuracy; +}; + +/** + * @brief An IVF-RaBitQ index with the workflow of the Python IvfIndex. + * + * Create it, then add vectors: the first add trains an untrained index on them. Call + * train on a sample, or set_centroids, first to choose the training data or the + * centroids. Search, remove, reserve_cluster and save need a trained index. + * + * IDs are the row numbers the index assigns, consecutive from 0 in the order points are + * added. Removed points keep their IDs. + * + * Const members may run concurrently; a call that changes the index needs exclusive + * access. Arguments outside their documented range throw std::invalid_argument, a call + * in the wrong state std::logic_error, and load rabitqlib::FormatError for a damaged or + * unsupported file. The index is movable and not copyable; a moved-from index may only be + * destroyed or assigned to. + */ +class IvfIndex { + public: + /** + * @param dim Vector dimension + * @param num_clusters Number of centroids, from train, set_centroids or the first add + * @param options Metric, bits, routing and seed + */ + explicit IvfIndex(size_t dim, size_t num_clusters, const IvfOptions& options = {}); + + IvfIndex(IvfIndex&& other) noexcept; + IvfIndex& operator=(IvfIndex&& other) noexcept; + IvfIndex(const IvfIndex&) = delete; + IvfIndex& operator=(const IvfIndex&) = delete; + ~IvfIndex(); + + // Load an index saved by any release, with its rotation; the result is trained. + static IvfIndex load(const char* filename); + + // Requires at least one stored point. Releases up to 0.8 cannot read the file. + void save(const char* filename) const; + + /** + * @brief Clustering parameters of train and of the first add. + * + * Defaults: niter 10, max_points_per_centroid 256, spherical for inner product and + * cosine, and seed equal to the index seed, or the k-means default for a file + * without one. Include rabitqlib/clustering/rabitqkmeans.hpp to read or change the + * fields. + */ + rabitqkmeans::RaBitQKMeansParameters& cp(); + [[nodiscard]] const rabitqkmeans::RaBitQKMeansParameters& cp() const; + + /** + * @brief Train num_clusters() centroids on `data` and set them. + * + * Only centroids are trained; add assigns points. Retraining is allowed while the + * index stores no points. The index is unchanged if this throws. + * + * @param data Training points (num_points * dim) + * @param num_points At least num_clusters() + * @param num_threads Worker count for this call; no value uses cp().num_threads + */ + void train( + const float* data, + size_t num_points, + std::optional num_threads = std::nullopt + ); + + /** + * @brief Use the given centroids instead of training. + * + * Allowed while the index stores no points. The index is unchanged if this throws. + * A cosine index scales the centroids to unit length, as it does data. + * + * @param centroids num_clusters() * dim values + * @param num_threads Worker count for building the centroid routing + */ + void set_centroids(const float* centroids, size_t num_threads = 0); + + /** + * @brief Add points, training an untrained index on them first. + * + * The first add trains num_clusters() centroids on `data` as train does, so it needs + * at least num_clusters() points and no cluster_ids; if it throws, the index stays + * untrained and empty. On a trained index the points are quantized against the + * existing centroids, which do not move, and the index is unchanged if this throws. + * + * @param data New points (num_points * dim) + * @param num_points Number of new points + * @param options Cluster IDs, worker count and quantization speed + * @return ID of the first new point; the batch has consecutive IDs + */ + Id add(const float* data, size_t num_points, const AddOptions& options = {}); + + /** + * @brief Exclude points from later search results. + * + * Removed points keep their IDs and storage, and removal cannot be undone. + * + * @param ids IDs in [0, num_stored_points()); repeats count once + * @param num_ids Number of IDs + * @return Number of points newly removed + */ + size_t remove(const Id* ids, size_t num_ids); + + // Preallocate room for cluster_id to hold num_points points in total, so that later + // adds grow it in place. Reserved room is not saved. + void reserve_cluster(size_t cluster_id, size_t num_points); + + /** + * @brief Search a batch of queries. + * + * Slots without a result get kNoId and +inf. Distances estimate squared L2, 1 - dot + * or 1 - cos according to the metric; lower is better. + * + * @param queries num_queries * dim values + * @param k Results per query, from 1 to 2^31; may exceed the number of points + * @param ids num_queries * k results + * @param distances num_queries * k results, or nullptr + */ + void search( + const float* queries, + size_t num_queries, + size_t k, + Id* ids, + float* distances, + const IvfSearchOptions& options = {} + ) const; + + [[nodiscard]] size_t dim() const; + [[nodiscard]] size_t num_clusters() const; + [[nodiscard]] size_t nbits() const; + [[nodiscard]] MetricType metric() const; + // Never Auto: the routing Auto resolved to. + [[nodiscard]] ivf::Routing routing() const; + // No value for an index loaded from a file of a release up to 0.8. + [[nodiscard]] std::optional seed() const; + // Live, searchable points. + [[nodiscard]] size_t num_points() const; + // Stored points, including removed ones. + [[nodiscard]] size_t num_stored_points() const; + // Whether centroids are set, by train, set_centroids, the first add or load. + [[nodiscard]] bool is_trained() const; + + private: + IvfIndex( + std::unique_ptr index, + std::unique_ptr cp + ); + + void check_trained(const char* operation) const; + void check_trainable() const; + [[nodiscard]] rabitqkmeans::RaBitQKMeansParameters training_parameters( + std::optional num_threads + ) const; + + std::unique_ptr index_; + std::unique_ptr cp_; +}; + +} // namespace rabitqlib diff --git a/include/rabitqlib/index/symqg/qg.hpp b/include/rabitqlib/index/symqg/qg.hpp index 1e82f6d0..b414fba2 100644 --- a/include/rabitqlib/index/symqg/qg.hpp +++ b/include/rabitqlib/index/symqg/qg.hpp @@ -2,13 +2,16 @@ #include #include +#include #include +#include #include #include #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" @@ -88,7 +91,8 @@ class QuantizedGraph { size_t padded_dim_ = 0; float (*raw_dist_func_)(const float*, const float*, size_t) = nullptr; PID entry_point_id_ = 0; - MetricType metric_type_ = METRIC_L2; + MetricType metric_type_ = METRIC_L2; // METRIC_IP for the cosine metric + bool cosine_ = false; // normalize data and queries; metric_type_ is METRIC_IP RotatorType rotator_type_ = RotatorType::FhtKacRotator; size_t quantization_bits_ = 0; // 0: raw vectors, 4/8: packed RaBitQ vectors std::vector centroid_; // rotated global centroid for qg-quant @@ -114,6 +118,13 @@ class QuantizedGraph { size_t default_ef_search_ = 0; bool ready_ = false; uint32_t seed_ = 42; + bool seed_known_ = false; // false for files that do not record the seed + // Construction settings a builder records; unknown (0 and no value) otherwise. + size_t ef_construction_ = 0; + std::optional initialization_; + // Loaded from a file with read-only-compatible features this release does not know: + // search works, but save refuses the graph until a builder rebuilds it. + bool read_only_ = false; [[nodiscard]] static size_t checked_add(size_t lhs, size_t rhs); @@ -127,9 +138,12 @@ class QuantizedGraph { void initialize(bool randomize_rotation = true); - // Write the graph file at exactly this path. + // Write the graph file in index format 2 at exactly this path. void write_file(const char* filename) const; + // Load a format-2 file into this freshly created graph. + void read_format2(std::istream& input); + void copy_vectors(const float* data, size_t num_workers); void set_quantization_centroid(const float* centroid); @@ -279,6 +293,14 @@ class QuantizedGraph { [[nodiscard]] size_t quantization_bits() const; + // The rotation seed, or no value for a graph loaded from a file that does not + // record it (files from releases up to 0.8). + [[nodiscard]] std::optional seed() const; + + // The settings the builder used, or no value when they are unknown. + [[nodiscard]] std::optional ef_construction() const; + [[nodiscard]] std::optional initialization() const; + [[nodiscard]] bool is_quantized() const; void set_ep(PID entry); @@ -343,7 +365,8 @@ class QuantizedGraph { * buffers, including visited sets. * * An optional g_k1xsumq must come from BatchQuery::g_k1xsumq() for the same - * query and this graph's rotation. A null pointer recomputes the sum. + * query and this graph's rotation; with the cosine metric, for the query scaled to + * unit norm. A null pointer recomputes the sum. */ void search_with_scratch( const float* __restrict__ query, diff --git a/include/rabitqlib/index/symqg/qg_builder.hpp b/include/rabitqlib/index/symqg/qg_builder.hpp index e2bf47e7..70e5f4b3 100644 --- a/include/rabitqlib/index/symqg/qg_builder.hpp +++ b/include/rabitqlib/index/symqg/qg_builder.hpp @@ -14,8 +14,6 @@ namespace rabitqlib::symqg { inline constexpr size_t kMaxBsIter = 5; // max iter for binary search of pruning bar using CandidateList = std::vector>; -enum class QGInitialization { PiPNN, Random }; - // Owns temporary state for SymphonyQG initialization and refinement. class QGBuilder { friend struct QGConstructionTestAccess; 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/training.hpp b/include/rabitqlib/index/training.hpp index 5f3a65a9..82eb4106 100644 --- a/include/rabitqlib/index/training.hpp +++ b/include/rabitqlib/index/training.hpp @@ -11,17 +11,19 @@ namespace rabitqlib { /** * Centroid training parameters for IVF::train and HierarchicalNSW::train: 10 * iterations, as in Faiss IVF, on a sample of at most 256 points per centroid, spherical - * k-means for inner product, and the given seed. The k-means classes keep their own - * defaults, which train on all points. + * k-means for inner product and cosine, and the given seed. The k-means classes keep + * their own defaults, which train on all points. */ inline rabitqkmeans::RaBitQKMeansParameters default_training_parameters( MetricType metric_type, uint32_t seed ) { - validate_metric_type(metric_type); + if (metric_type != METRIC_COSINE) { + validate_metric_type(metric_type); + } rabitqkmeans::RaBitQKMeansParameters cp; cp.niter = 10; cp.max_points_per_centroid = 256; - cp.spherical = metric_type == METRIC_IP; + cp.spherical = metric_type != METRIC_L2; cp.seed = seed; return cp; } diff --git a/include/rabitqlib/index/types.hpp b/include/rabitqlib/index/types.hpp index cc94266c..003b7e81 100644 --- a/include/rabitqlib/index/types.hpp +++ b/include/rabitqlib/index/types.hpp @@ -1,12 +1,41 @@ #pragma once +#include #include #include +#include namespace rabitqlib { using PID = uint32_t; inline constexpr PID kPidMax = 0xFFFFFFFF; +// 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; + +// 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. + const PID* cluster_ids = nullptr; + // Worker count. No value trains an untrained index with cp().num_threads and adds + // with every available CPU; 0 selects every available CPU, capped by OMP_NUM_THREADS. + std::optional num_threads; + // Fixed-scale extra-bit quantization: faster, possibly less accurate. No effect on + // one-bit or raw storage. + bool fast_quantization = false; +}; + +// 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; + // 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/include/rabitqlib/third/hnswlib/hnswalg.h b/include/rabitqlib/third/hnswlib/hnswalg.h index c8ff85d1..d6ccf26a 100644 --- a/include/rabitqlib/third/hnswlib/hnswalg.h +++ b/include/rabitqlib/third/hnswlib/hnswalg.h @@ -688,8 +688,14 @@ class HierarchicalNSW : public AlgorithmInterface { if (!output.is_open()) throw std::runtime_error("Cannot open HNSW index file for writing"); output.exceptions(std::ios::failbit | std::ios::badbit); - std::streampos position; + saveIndex(output); + output.close(); + } + + // RaBitQ: the stream overloads let an index embed the graph in a section of its own + // file. The bytes are those of the path overload, which delegates to them. + void saveIndex(std::ostream &output) { writeBinaryPOD(output, offsetLevel0_); writeBinaryPOD(output, max_elements_); writeBinaryPOD(output, cur_element_count); @@ -713,7 +719,6 @@ class HierarchicalNSW : public AlgorithmInterface { if (linkListSize) output.write(linkLists_[i], linkListSize); } - output.close(); } @@ -723,11 +728,20 @@ class HierarchicalNSW : public AlgorithmInterface { if (!input.is_open()) throw std::runtime_error("Cannot open file"); - clear(); // get file size: input.seekg(0, input.end); - std::streampos total_filesize = input.tellg(); + const std::streamoff total_filesize = input.tellg(); input.seekg(0, input.beg); + loadIndex(input, static_cast(total_filesize), s, max_elements_i); + input.close(); + } + + + // RaBitQ: read a graph of `total_bytes` bytes that starts at the current position. + void loadIndex(std::istream &input, size_t total_bytes, SpaceInterface *s, size_t max_elements_i = 0) { + clear(); + const std::streampos begin = input.tellg(); + const std::streampos end = begin + static_cast(total_bytes); readBinaryPOD(input, offsetLevel0_); readBinaryPOD(input, max_elements_); @@ -758,7 +772,7 @@ class HierarchicalNSW : public AlgorithmInterface { /// Optional - check if index is ok: input.seekg(cur_element_count * size_data_per_element_, input.cur); for (size_t i = 0; i < cur_element_count; i++) { - if (input.tellg() < 0 || input.tellg() >= total_filesize) { + if (input.tellg() < begin || input.tellg() >= end) { throw std::runtime_error("Index seems to be corrupted or unsupported"); } @@ -770,13 +784,13 @@ class HierarchicalNSW : public AlgorithmInterface { } // throw exception if it either corrupted or old index - if (input.tellg() != total_filesize) + if (input.tellg() != end) throw std::runtime_error("Index seems to be corrupted or unsupported"); input.clear(); /// Optional check end - input.seekg(pos, input.beg); + input.seekg(pos); data_level0_memory_ = (char *) malloc(max_elements * size_data_per_element_); if (data_level0_memory_ == nullptr) @@ -819,10 +833,6 @@ class HierarchicalNSW : public AlgorithmInterface { if (allow_replace_deleted_) deleted_elements.insert(i); } } - - input.close(); - - return; } diff --git a/include/rabitqlib/utils/tools.hpp b/include/rabitqlib/utils/tools.hpp index 11ea3b29..8b50bee5 100644 --- a/include/rabitqlib/utils/tools.hpp +++ b/include/rabitqlib/utils/tools.hpp @@ -1,16 +1,13 @@ #pragma once #include -#include #include #include #include #include -#include #include #include #include -#include namespace rabitqlib { template @@ -77,7 +74,7 @@ inline size_t floor_log2(size_t x) { inline size_t ceil_log2(size_t x) { size_t ret = floor_log2(x); - return (1UL << ret) < x ? ret + 1 : ret; + return (size_t{1} << ret) < x ? ret + 1 : ret; } inline bool is_powerof2(size_t n) { return n > 0 && (n & (n - 1)) == 0; } @@ -114,60 +111,4 @@ inline int openmp_team_size(size_t requested, size_t work_items) { } } // namespace detail -template -float distance_ratio( - const T* data, - const T* query, - const TP* gt, - const TP* ann_results, - size_t k, - size_t dim, - T (*dist_func)(const T*, const T*, size_t) -) { - std::priority_queue gt_distances; - std::priority_queue ann_distances; - - for (size_t i = 0; i < k; ++i) { - TP gt_id = gt[i]; - TP ann_id = ann_results[i]; - gt_distances.emplace(dist_func(query, data + (gt_id * dim), dim)); - ann_distances.emplace(dist_func(query, data + (ann_id * dim), dim)); - } - - float ret = 0; - size_t valid_k = 0; - - while (!gt_distances.empty()) { - if (gt_distances.top() > 1e-5) { - ret += std::sqrt(ann_distances.top() / gt_distances.top()); - ++valid_k; - } - gt_distances.pop(); - ann_distances.pop(); - } - - if (valid_k == 0) { - return static_cast(k); - } - return ret * static_cast(k) / static_cast(valid_k); -} - -template -std::vector horizontal_avg(const std::vector>& data) { - size_t rows = data.size(); - size_t cols = data[0].size(); - - std::vector avg(cols, 0); - for (auto& row : data) { - for (size_t j = 0; j < cols; ++j) { - avg[j] += row[j]; - } - } - - for (size_t j = 0; j < cols; ++j) { - avg[j] /= rows; - } - - return avg; -} } // namespace rabitqlib diff --git a/pyproject.toml b/pyproject.toml index 795886a0..2d291a9e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "scikit_build_core.build" [project] name = "rabitqlib" -version = "0.8.5" +version = "0.9.0" description = "Official RaBitQ library for vector quantization and approximate nearest-neighbor search" readme = "README.md" requires-python = ">=3.11" diff --git a/python_bindings/__init__.py b/python_bindings/__init__.py index 45aea066..5364678c 100644 --- a/python_bindings/__init__.py +++ b/python_bindings/__init__.py @@ -4,903 +4,21 @@ and adds the clustering wrappers. Import public classes from ``rabitqlib``. """ -import inspect -import operator -import sys -import warnings - -from ._rabitqlib import ( - FinalAssignmentMode as _FinalAssignmentMode, -) from ._rabitqlib import ( + FormatError, HnswIndex, IvfIndex, + KMeansIterationStats, QGKMeansParameters, RaBitQKMeansParameters, SymqgIndex, _QGKMeans, _RaBitQKMeans, ) -from ._rabitqlib import ( - QGKMeansIterationStats as KMeansIterationStats, -) from ._rabitqlib import ( __version__ as __version__, ) -# --- 0.8 compatibility layer; remove in 0.9 -------------------------------- -# The extension classes expose only the 0.8 API. As Faiss does for its SWIG -# classes, the 0.7 call forms are restored by replacing methods on those classes -# at import time, so the public types stay the native ones. - -_MIGRATION = ( - "see https://vectordb-ntu.github.io/RaBitQ-Library/python_migration/; " - "the old form will be removed in 0.9" -) -_MISSING = object() - - -def _is_zero(value): - """Whether an optional integer argument is one the extension reads as 0.""" - if value is None or isinstance(value, (float, str, bytes)): - return False - try: - return operator.index(value) == 0 - except TypeError: - pass - try: - # pybind11 also converts objects that only define __int__, such as - # numpy floating scalars. - return int(value) == 0 - except (TypeError, ValueError, OverflowError): - return False - - -def _exceeds_32_bits(value): - try: - return operator.index(value) > 0xFFFFFFFF - except TypeError: - return False - - -def _deprecated(message): - # Called from a replacement method, so the caller of that method is two up. - warnings.warn(f"{message}; {_MIGRATION}", DeprecationWarning, stacklevel=3) - - -def _bind(signature, name, args, kwargs, hint=""): - try: - bound = signature.bind(*args, **kwargs) - except TypeError as error: - raise TypeError(f"{name}() {error}{hint}") from None - bound.apply_defaults() - arguments = dict(bound.arguments) - del arguments["self"] - return arguments - - -def _ivf_signature( - self, dim, num_clusters, *, nbits=7, metric="l2", routing="auto", seed=None -): ... - - -def _ivf_legacy_signature( - self, dim, max_elements, num_clusters, nbits, metric="l2", initializer="auto" -): ... - - -def _hnsw_signature( - self, - dim, - *, - nbits=7, - num_clusters=16, - M=16, - ef_construction=200, - metric="l2", - seed=100, -): ... - - -def _hnsw_legacy_signature( - self, - dim, - max_elements, - M=16, - ef_construction=200, - nbits=8, - metric="l2", - random_seed=100, -): ... - - -def _add_signature( - self, data, *, cluster_ids=None, num_threads=None, fast_quantization=False -): ... - - -def _patch_ivf_init(cls): - native_init = cls.__init__ - signature = inspect.signature(_ivf_signature) - legacy_signature = inspect.signature(_ivf_legacy_signature) - - def __init__(self, *args, **kwargs): - # A third positional argument, max_elements, or num_clusters by keyword - # after two positional arguments can only be the 0.7 form. - if ( - len(args) > 2 - or "max_elements" in kwargs - or (len(args) == 2 and "num_clusters" in kwargs) - ): - arguments = _bind( - legacy_signature, - "IvfIndex", - (self, *args), - kwargs, - " (read as the 0.7 form IvfIndex(dim, max_elements, num_clusters, " - "nbits, ...); the 0.8 form is IvfIndex(dim, num_clusters, nbits=...))", - ) - _deprecated( - "IvfIndex(dim, max_elements, num_clusters, nbits, ...) is deprecated; " - "use IvfIndex(dim, num_clusters, nbits=...), whose first add() trains it" - ) - native_init( - self, - arguments["dim"], - arguments["num_clusters"], - nbits=arguments["nbits"], - metric=arguments["metric"], - initializer=arguments["initializer"], - _max_elements=arguments["max_elements"], - ) - return - # 0.9 names the routing strategy routing; initializer is its 0.8 spelling. - initializer = kwargs.pop("initializer", _MISSING) - if initializer is not _MISSING: - if "routing" in kwargs: - raise TypeError( - "IvfIndex() got both routing and its old name initializer" - ) - _deprecated("IvfIndex(initializer=...) is deprecated; use routing=") - kwargs["routing"] = initializer - arguments = _bind(signature, "IvfIndex", (self, *args), kwargs) - arguments["initializer"] = arguments.pop("routing") - try: - native_init(self, **arguments) - except ValueError as error: - # The extension names the argument initializer; a caller who wrote - # routing= gets that name back. - message = str(error) - if initializer is not _MISSING or not message.startswith( - "initializer must be" - ): - raise - raise ValueError("routing" + message[len("initializer") :]) from None - - __init__.__doc__ = cls.__doc__ - __init__.__signature__ = signature - cls.__init__ = __init__ - - -def _patch_hnsw_init(cls): - native_init = cls.__init__ - signature = inspect.signature(_hnsw_signature) - legacy_signature = inspect.signature(_hnsw_legacy_signature) - - def __init__(self, *args, **kwargs): - if len(args) > 1 or "max_elements" in kwargs: - arguments = _bind( - legacy_signature, - "HnswIndex", - (self, *args), - kwargs, - " (read as the 0.7 form HnswIndex(dim, max_elements, ...); " - "the 0.8 form is HnswIndex(dim, nbits=...))", - ) - _deprecated( - "HnswIndex(dim, max_elements, ...) is deprecated; use " - "HnswIndex(dim, nbits=...), whose capacity grows on add" - ) - native_init( - self, - arguments["dim"], - _max_elements=arguments["max_elements"], - M=arguments["M"], - ef_construction=arguments["ef_construction"], - nbits=arguments["nbits"], - metric=arguments["metric"], - random_seed=arguments["random_seed"], - ) - return - random_seed = kwargs.pop("random_seed", _MISSING) - if random_seed is not _MISSING: - if "seed" in kwargs: - raise TypeError( - "HnswIndex() got both seed and its old name random_seed" - ) - _deprecated("HnswIndex(random_seed=...) is deprecated; use seed=") - kwargs["seed"] = random_seed - arguments = _bind(signature, "HnswIndex", (self, *args), kwargs) - if _exceeds_32_bits(arguments["seed"]): - _deprecated( - "HnswIndex seeds above 2**32 - 1 are deprecated; 0.9 accepts " - "[0, 2**32 - 1], as the other indexes do" - ) - native_init(self, **arguments) - - __init__.__doc__ = cls.__doc__ - __init__.__signature__ = signature - cls.__init__ = __init__ - - -def _patch_add(cls): - native_add = cls.add - name = cls.__name__ - options = ("cluster_ids", "num_threads", "fast_quantization") - - def add(self, data, *args, **kwargs): - if args: - if len(args) > len(options): - raise TypeError( - f"{name}.add() takes at most {len(options) + 1} positional " - f"arguments ({len(args) + 1} given)" - ) - _deprecated( - f"passing {', '.join(options[: len(args)])} to {name}.add() by " - "position is deprecated; pass them by keyword" - ) - for option, value in zip(options, args, strict=False): - if option in kwargs: - raise TypeError( - f"{name}.add() got multiple values for argument {option!r}" - ) - kwargs[option] = value - return native_add(self, data, **kwargs) - - add.__doc__ = native_add.__doc__ - add.__signature__ = inspect.signature(_add_signature) - cls.add = add - - -def _patch_build(cls): - name = cls.__name__ - - def build( - self, data, centroids, cluster_ids, num_threads=1, fast_quantization=False - ): - """Build the index from vectors and supplied centroid assignments. - - Deprecated since 0.8 and removed in 0.9: use set_centroids() (or - train()) and then add(). The defaults match 0.7, including a single - thread. - - Parameters - ---------- - data : array_like of float, shape (n, dim) - Vectors in the original, unpadded coordinates. Converted to - contiguous float32; a copy may be made. - centroids : array_like of float, shape (num_clusters, dim) - Vectors in the original, unpadded coordinates. Converted to - contiguous float32; a copy may be made. - cluster_ids : array_like of int, shape (n,) - Centroid ID per vector, in [0, num_clusters). Floating-point and - boolean IDs are rejected. - num_threads : int, optional - Worker count. Default is 1; 0 selects the available CPU count, - capped by OMP_NUM_THREADS. - fast_quantization : bool, optional - Use faster quantizer configuration. Default is False. - """ - _deprecated( - f"{name}.build() is deprecated; use set_centroids() or train(), then add()" - ) - self._build(data, centroids, cluster_ids, num_threads, fast_quantization) - - def is_built(self): - """Deprecated since 0.8: whether the index stores points; use len().""" - _deprecated(f"{name}.is_built is deprecated; use is_trained or len()") - return self.num_stored_points != 0 - - cls.build = build - cls.is_built = property(is_built, doc=is_built.__doc__) - - -def _symqg_signature( - self, - dim, - *, - nbits=32, - max_degree=32, - ef_construction=200, - init="pipnn", - metric="l2", - seed=None, -): ... - - -def _symqg_legacy_signature( - self, dim, max_degree, metric="l2", quantization_bits=0 -): ... - - -def _symqg_nbits(quantization_bits): - # 0.7 stored raw vectors as 0 bits; 0.8 calls that 32. - if isinstance(quantization_bits, bool) or quantization_bits not in (0, 4, 8): - raise ValueError("quantization_bits must be 0, 4, or 8") - return 32 if quantization_bits == 0 else quantization_bits - - -def _patch_symqg(cls): - native_init = cls.__init__ - native_search = cls.search - signature = inspect.signature(_symqg_signature) - legacy_signature = inspect.signature(_symqg_legacy_signature) - - def __init__(self, *args, **kwargs): - if len(args) > 1: - arguments = _bind( - legacy_signature, - "SymqgIndex", - (self, *args), - kwargs, - " (read as the 0.7 form SymqgIndex(dim, max_degree, metric, " - "quantization_bits); the 0.8 form is SymqgIndex(dim, max_degree=...))", - ) - _deprecated( - "SymqgIndex(dim, max_degree, metric, quantization_bits) is deprecated; " - "use SymqgIndex(dim, max_degree=..., metric=..., nbits=...)" - ) - nbits = _symqg_nbits(arguments["quantization_bits"]) - native_init( - self, - arguments["dim"], - nbits=nbits, - max_degree=arguments["max_degree"], - metric=arguments["metric"], - ) - return - quantization_bits = kwargs.pop("quantization_bits", _MISSING) - if quantization_bits is not _MISSING: - if "nbits" in kwargs: - raise TypeError( - "SymqgIndex() got both nbits and its old form quantization_bits" - ) - _deprecated( - "SymqgIndex(quantization_bits=...) is deprecated; use nbits=, with 32 " - "instead of 0 for raw vectors" - ) - kwargs["nbits"] = _symqg_nbits(quantization_bits) - native_init(self, **_bind(signature, "SymqgIndex", (self, *args), kwargs)) - - def build(self, data, ef_construction, num_threads=1, init="pipnn"): - """Build the graph from input vectors, replacing any existing graph. - - Deprecated since 0.8 and removed in 0.9: pass ef_construction and init to - the constructor, then call add() once. The defaults match 0.7, including - a single thread. - - Parameters - ---------- - data : array_like of float, shape (n, dim) - Vectors in the original, unpadded coordinates, with n > max_degree. - Converted to contiguous float32; a copy may be made. - ef_construction : int - Positive construction search breadth fitting uint32. - num_threads : int, optional - Worker count. Default is 1; 0 selects the available CPU count, - capped by OMP_NUM_THREADS. - init : {'pipnn', 'random'}, optional - Graph initialization method. Default is 'pipnn'. - """ - _deprecated( - "SymqgIndex.build() is deprecated; pass ef_construction and init to " - "SymqgIndex() and call add()" - ) - self._build(data, ef_construction, num_threads, init) - - def search_batch(self, queries, k, ef, num_threads=1): - """Deprecated since 0.8: the same as search(); use search().""" - _deprecated("SymqgIndex.search_batch() is deprecated; use search()") - return native_search(self, queries, k, ef, num_threads) - - def quantization_bits(self): - """Deprecated since 0.8: storage bits with 0 for raw vectors; use nbits.""" - _deprecated( - "SymqgIndex.quantization_bits is deprecated; use nbits, which is 32 " - "instead of 0 for raw vectors" - ) - return self._quantization_bits - - def is_built(self): - """Deprecated since 0.8: whether the index holds a graph; use len().""" - _deprecated("SymqgIndex.is_built is deprecated; use len()") - return self.num_stored_points != 0 - - __init__.__doc__ = cls.__doc__ - __init__.__signature__ = signature - cls.__init__ = __init__ - cls.build = build - cls.search_batch = search_batch - cls.quantization_bits = property(quantization_bits, doc=quantization_bits.__doc__) - cls.is_built = property(is_built, doc=is_built.__doc__) - - -_patch_ivf_init(IvfIndex) -_patch_hnsw_init(HnswIndex) -for _cls in (IvfIndex, HnswIndex): - _patch_add(_cls) - _patch_build(_cls) -del _cls -_patch_symqg(SymqgIndex) -# --- end of the 0.8 compatibility layer ------------------------------------- - - -# --- 0.9 names; the 0.8 spellings they replace are removed in 0.9 ----------- -# 0.9 renames these members and arguments (issue #232). This release accepts both -# spellings and warns on the old one. The extension classes still carry the 0.8 -# names, so the new ones are added here, again by replacing members on the classes. - - -def _member(cls, function, name=None): - """function named as a member of cls, so errors and help() show the class.""" - if name is not None: - function.__name__ = name - function.__qualname__ = f"{cls.__name__}.{function.__name__}" - function.__module__ = cls.__module__ - return function - - -def _renamed_property(cls, old, new, new_doc, replacement): - """Add property new for the native property old, which then warns.""" - native = vars(cls)[old] - name = cls.__name__ - - def current(self): - return native.__get__(self, cls) - - def former(self): - _deprecated(f"{name}.{old} is deprecated; use {replacement}") - return native.__get__(self, cls) - - _member(cls, former, old) - if new is not None: - _member(cls, current, new) - _set_property(cls, new, current, new_doc) - _set_property(cls, old, former, f"Deprecated since 0.8.5: use {replacement}.") - - -def _set_property(cls, name, getter, documentation, setter=None): - """Assign a property, named as a class body would name it.""" - member = property(getter, setter, doc=documentation) - setattr(cls, name, member) - # Assignment after class creation skips __set_name__, and before Python 3.13 - # a property without it reports errors without its name. - member.__set_name__(cls, name) - - -def _options_from_positions(name, options, args, kwargs): - if len(args) > len(options): - raise TypeError( - f"{name}.search() takes at most {len(options) + 2} positional " - f"arguments ({len(args) + 2} given)" - ) - for option, value in zip(options, args, strict=False): - if option in kwargs: - raise TypeError( - f"{name}.search() got multiple values for argument {option!r}" - ) - kwargs[option] = value - - -def _edited(documentation, replacements): - """A docstring with replacements applied; fails if the native text moved.""" - for old, new in replacements: - if old not in documentation: - raise AssertionError(f"native documentation changed: {old!r}") - documentation = documentation.replace(old, new) - return documentation - - -def _redocumented(native, replacements): - """The native docstring without pybind11's signature line, with edits applied.""" - return _edited(native.__doc__.split("\n\n", 1)[1], replacements) - - -_THREADS_DOC = ( - " Worker count. None (default) selects 1; 0 selects the available CPU\n" - " count, capped by OMP_NUM_THREADS.", - " Keyword-only; passing it by position is deprecated since 0.8.5. Worker\n" - " count. None (default) selects 1; 0 selects the available CPU count,\n" - " capped by OMP_NUM_THREADS.", -) - - -def _ivf_search_signature( - self, queries, k, nprobe=None, *, high_accuracy=None, num_threads=None -): ... - - -def _graph_search_signature(self, queries, k, ef_search=None, *, num_threads=None): ... - - -def _patch_ivf_names(cls): - native_reserve = cls.reserve - native_search = cls.search - options = ("nprobe", "high_accuracy", "num_threads") - - def reserve_cluster(self, cluster_id, num_points): - """Preallocate storage for a cluster. - - Parameters - ---------- - cluster_id : int - Cluster ID in [0, num_clusters). - num_points : int - Nonnegative capacity to reserve for this cluster: the total number - of points it can hold, including its current ones. - - Notes - ----- - Requires a trained or loaded index. Reserved room is not saved. Named - reserve before 0.8.5. - """ - try: - native_reserve(self, cluster_id, num_points) - except RuntimeError as error: - # The extension still names the operation reserve. - if not str(error).endswith("before reserve"): - raise - raise RuntimeError(f"{error}_cluster") from None - - def reserve(self, cluster_id, num_points): - """Deprecated since 0.8.5: the same as reserve_cluster(); use reserve_cluster().""" - _deprecated("IvfIndex.reserve() is deprecated; use reserve_cluster()") - native_reserve(self, cluster_id, num_points) - - def search(self, queries, k, *args, **kwargs): - _options_from_positions("IvfIndex", options, args, kwargs) - if len(args) > 1: - _deprecated( - f"passing {', '.join(options[1 : len(args)])} to IvfIndex.search() " - "by position is deprecated; use keywords" - ) - if _is_zero(kwargs.get("nprobe")): - _deprecated( - "IvfIndex.search(nprobe=0) is deprecated; pass None, or omit nprobe, " - "for the default" - ) - return native_search(self, queries, k, **kwargs) - - search.__doc__ = _redocumented( - native_search, - [ - ( - " Number of clusters to probe, capped at num_clusters. None (default) and\n" - " 0 select num_clusters / 16, rounded to the nearest integer and at least 1.", - " Number of clusters to probe, capped at num_clusters. None (default)\n" - " selects num_clusters / 16, rounded to the nearest integer and at least\n" - " 1; 0 does the same and is deprecated since 0.8.5.", - ), - ( - " Enable HACC. None (default) selects it for 4-9 bits and standard\n" - " FastScan otherwise. Raw storage uses standard FastScan.", - " Keyword-only; passing it by position is deprecated since 0.8.5.\n" - " Enable HACC. None (default) selects it for 4-9 bits and standard\n" - " FastScan otherwise. Raw storage uses standard FastScan.", - ), - _THREADS_DOC, - ], - ) - search.__signature__ = inspect.signature(_ivf_search_signature) - cls.__doc__ = _edited( - cls.__doc__, - [ - ( - "initializer : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional\n" - " Centroid routing strategy. Default is 'auto'.", - "routing : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional\n" - " Centroid routing strategy. Default is 'auto'. Named initializer\n" - " before 0.8.5.", - ) - ], - ) - cls.__init__.__doc__ = cls.__doc__ - cls.add.__doc__ = _edited( - cls.add.__doc__, - [ - ("reserve can preallocate room.", "reserve_cluster can preallocate room."), - ( - "index's configured centroid initializer; routing may be approximate.", - "index's configured routing strategy, which may be approximate.", - ), - ], - ) - cls.reserve_cluster = _member(cls, reserve_cluster) - cls.reserve = _member(cls, reserve) - cls.search = _member(cls, search) - _renamed_property( - cls, - "initializer", - "routing", - "Resolved centroid routing strategy. Named initializer before 0.8.5.", - "routing", - ) - _renamed_property(cls, "max_elements", None, None, "num_stored_points") - - -def _patch_graph_search(cls, breadth_doc): - native_search = cls.search - name = cls.__name__ - options = ("ef_search", "num_threads") - - def search(self, queries, k, *args, **kwargs): - _options_from_positions(name, options, args, kwargs) - if "ef" in kwargs and "ef_search" in kwargs: - raise TypeError(f"{name}.search() got both ef_search and its old name ef") - if len(args) == len(options): - _deprecated( - f"passing num_threads to {name}.search() by position is deprecated; " - "use the keyword" - ) - if "ef" in kwargs: - _deprecated(f"{name}.search(ef=...) is deprecated; use ef_search=") - kwargs["ef_search"] = kwargs.pop("ef") - ef_search = kwargs.pop("ef_search", None) - if _is_zero(ef_search): - _deprecated( - f"{name}.search(ef_search=0) is deprecated; pass None, or omit " - "ef_search, for the default" - ) - return native_search(self, queries, k, ef_search, **kwargs) - - search.__doc__ = _redocumented(native_search, [breadth_doc, _THREADS_DOC]) - search.__signature__ = inspect.signature(_graph_search_signature) - cls.search = _member(cls, search) - - -def _patch_hnsw_names(cls): - native_resize = cls.resize - native_max_elements = vars(cls)["max_elements"] - - def reserve(self, num_points): - """Preallocate room for at least num_points stored points. - - Parameters - ---------- - num_points : int - Nonnegative number of stored points to make room for, including the - current ones. - - Notes - ----- - Capacity only grows: a value at or below capacity changes nothing. add - also grows the capacity when needed, so reserve is an optimization. - """ - needed = operator.index(num_points) - if needed < 0: - raise ValueError("num_points must be non-negative") - if needed > native_max_elements.__get__(self, cls): - native_resize(self, needed) - - def resize(self, max_elements): - """Deprecated since 0.8.5: change the capacity; use reserve(), which only grows it.""" - _deprecated( - "HnswIndex.resize() is deprecated; use reserve(), which only grows the " - "capacity" - ) - native_resize(self, max_elements) - - cls.__doc__ = _edited( - cls.__doc__, - [ - ("resize can preallocate it.", "reserve can preallocate it."), - ( - "32 bits). Default is 100.", - "32 bits), in [0, 2**32 - 1]; larger values are deprecated since\n" - " 0.8.5. Default is 100.", - ), - ], - ) - cls.__init__.__doc__ = cls.__doc__ - cls.reserve = _member(cls, reserve) - cls.resize = _member(cls, resize) - _renamed_property( - cls, - "max_elements", - "capacity", - "Current storage capacity, in stored points. Named max_elements before 0.8.5.", - "capacity", - ) - - -_patch_ivf_names(IvfIndex) -_patch_hnsw_names(HnswIndex) -_renamed_property(SymqgIndex, "max_elements", None, None, "num_stored_points") -_patch_graph_search( - HnswIndex, - ( - "ef : int, optional\n Search breadth. None or 0 (default) selects max(k, 64); values above the stored\n" - " point count are clamped.", - "ef_search : int, optional\n Search breadth. None (default) selects max(k, 64); values above the stored\n" - " point count are clamped. 0 selects the default and is deprecated since\n" - " 0.8.5. Named ef before 0.8.5.", - ), -) -_patch_graph_search( - SymqgIndex, - ( - "ef : int, optional\n Search breadth. None or 0 (default) selects max(k, 64); smaller values\n" - " are raised to k.", - "ef_search : int, optional\n Search breadth. None (default) selects max(k, 64); smaller values\n" - " are raised to k. 0 selects the default and is deprecated since 0.8.5.\n" - " Named ef before 0.8.5.", - ), -) -# k-means (issue #233): the graph parameters take the index names, final_assignment -# takes a string, and the two statistics class names become one. - -KMeansIterationStats.__name__ = KMeansIterationStats.__qualname__ = ( - "KMeansIterationStats" -) -# Pickle and pydoc find a class by its name in its module, which is the extension. -sys.modules[KMeansIterationStats.__module__].KMeansIterationStats = KMeansIterationStats - -_FINAL_ASSIGNMENTS = { - "approximate": _FinalAssignmentMode.Approximate, - "exact": _FinalAssignmentMode.Exact, -} - - -def _patch_final_assignment(cls): - native = vars(cls)["final_assignment"] - - def final_assignment(self): - return native.__get__(self, cls) - - def set_final_assignment(self, value): - if isinstance(value, str): - try: - value = _FINAL_ASSIGNMENTS[value] - except KeyError: - raise ValueError( - "final_assignment must be 'approximate' or 'exact'" - ) from None - elif not isinstance(value, _FinalAssignmentMode): - raise TypeError( - "final_assignment must be 'approximate' or 'exact', not " - f"{type(value).__name__}" - ) - native.__set__(self, value) - - _set_property( - cls, - "final_assignment", - _member(cls, final_assignment), - "'approximate' uses the training assignment method; 'exact' uses exhaustive " - "assignment against final centroids. Default is 'approximate'. Until 0.9 it " - "reads back as the FinalAssignmentMode member, which is still accepted.", - _member(cls, set_final_assignment, "final_assignment"), - ) - - -def _qg_nbits_to_native(value): - bits = operator.index(value) - if bits not in (4, 8, 32): - raise ValueError("nbits must be 4, 8, or 32") - return 0 if bits == 32 else bits - - -def _qg_nbits_from_native(value): - return 32 if value == 0 else value - - -def _rename_parameter(cls, old, new, documentation, to_native=None, from_native=None): - """Add attribute new for the native attribute old, which then warns.""" - native = vars(cls)[old] - name = cls.__name__ - - def current(self): - value = native.__get__(self, cls) - return value if from_native is None else from_native(value) - - def set_current(self, value): - native.__set__(self, value if to_native is None else to_native(value)) - - def former(self): - _deprecated(f"{name}.{old} is deprecated; use {new}") - return native.__get__(self, cls) - - def set_former(self, value): - _deprecated(f"{name}.{old} is deprecated; use {new}") - native.__set__(self, value) - - _set_property( - cls, - new, - _member(cls, current, new), - documentation, - _member(cls, set_current, new), - ) - _set_property( - cls, - old, - _member(cls, former, old), - f"Deprecated since 0.8.5: use {new}.", - _member(cls, set_former, old), - ) - return native - - -# Old keyword and attribute name -> (new name, the native attribute behind both). -_QG_RENAMED = { - "graph_degree": ( - "max_degree", - _rename_parameter( - QGKMeansParameters, - "graph_degree", - "max_degree", - "Centroid graph degree; a positive multiple of 32. Default is 32. Named " - "graph_degree before 0.8.5.", - ), - ), - "ef_build": ( - "ef_construction", - _rename_parameter( - QGKMeansParameters, - "ef_build", - "ef_construction", - "Positive centroid-graph construction search breadth. Default is 240. " - "Named ef_build before 0.8.5.", - ), - ), - "quantization_bits": ( - "nbits", - _rename_parameter( - QGKMeansParameters, - "quantization_bits", - "nbits", - "Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is " - "32. Named quantization_bits, with 0 for raw float32, before 0.8.5.", - _qg_nbits_to_native, - _qg_nbits_from_native, - ), - ), -} -_patch_final_assignment(QGKMeansParameters) -_patch_final_assignment(RaBitQKMeansParameters) - -_RENAMED_EXPORTS = { - "FinalAssignmentMode": ( - _FinalAssignmentMode, - "FinalAssignmentMode is deprecated; pass 'approximate' or 'exact' as " - "final_assignment", - ), - "QGKMeansIterationStats": ( - KMeansIterationStats, - "QGKMeansIterationStats is deprecated; use KMeansIterationStats", - ), - "RaBitQKMeansIterationStats": ( - KMeansIterationStats, - "RaBitQKMeansIterationStats is deprecated; use KMeansIterationStats", - ), -} - - -def __getattr__(name): - try: - value, message = _RENAMED_EXPORTS[name] - except KeyError: - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from None - # "from rabitqlib import " asks twice: importlib checks the name before - # the import statement reads it. Warn for the statement only, at its line. - caller = sys._getframe().f_back # None when no Python code is calling - if caller is None or caller.f_code.co_name != "_handle_fromlist": - warnings.warn(f"{message}; {_MIGRATION}", DeprecationWarning, stacklevel=2) - return value - - -# --- end of the 0.9 names ---------------------------------------------------- - class _KMeans: """Shared result handling for the two clustering methods.""" @@ -909,36 +27,16 @@ def __init__(self, d, k, **kwargs): self.d = int(d) self.k = int(k) self.cp = self._parameters_type() - self._keywords = frozenset(kwargs) for name, value in kwargs.items(): - renamed = self._renamed_parameters.get(name) - if renamed is not None: - new, native = renamed - if new in kwargs: - raise TypeError( - f"{type(self).__name__}() got both {new} and its old name {name}" - ) - _deprecated( - f"{type(self).__name__}({name}=...) is deprecated; use {new}=" - + ( - ", with 32 instead of 0 for raw vectors" - if new == "nbits" - else "" - ) - ) - else: - try: - getattr(self.cp, name) - except AttributeError: - raise AttributeError( - f"{type(self).__name__}() got an unexpected keyword argument " - f"{name!r}" - ) from None try: - if renamed is not None: - native.__set__(self.cp, value) - else: - setattr(self.cp, name, value) + getattr(self.cp, name) + except AttributeError: + raise AttributeError( + f"{type(self).__name__}() got an unexpected keyword argument " + f"{name!r}" + ) from None + try: + setattr(self.cp, name, value) except TypeError as error: raise TypeError( f"{type(self).__name__}() could not convert parameter {name!r} " @@ -967,19 +65,8 @@ def train(self, x): A failed fit preserves the last successful results. Returned arrays are copies. """ - try: - implementation = self._implementation_type(self.d, self.k, self.cp) - objective = implementation.train(x) - except ValueError as error: - # The extension names the 0.8 setting. A caller who wrote the 0.9 - # keyword gets that name back; every 0.8 call keeps its message. A - # subclass may not have run __init__, hence the getattr. - message = str(error) - if "ef_build" not in message or "ef_construction" not in getattr( - self, "_keywords", () - ): - raise - raise ValueError(message.replace("ef_build", "ef_construction")) from None + implementation = self._implementation_type(self.d, self.k, self.cp) + objective = implementation.train(x) self._impl = implementation return objective @@ -1085,14 +172,11 @@ class QGKMeans(_KMeans): capped by OMP_NUM_THREADS. Default is 0. final_assignment : {'approximate', 'exact'}, optional 'approximate' uses the training assignment method; 'exact' uses exhaustive - assignment against final centroids. Default is 'approximate'. A - FinalAssignmentMode member is still accepted until 0.9. + assignment against final centroids. Default is 'approximate'. max_degree : int, optional - Centroid graph degree; a positive multiple of 32. Default is 32. Named - graph_degree before 0.8.5. + Centroid graph degree; a positive multiple of 32. Default is 32. ef_construction : int, optional Positive centroid-graph construction search breadth. Default is 240. - Named ef_build before 0.8.5. ef_search : int, optional Positive centroid-graph assignment search breadth. Default is 16. graph_build_iterations : int, optional @@ -1100,7 +184,7 @@ class QGKMeans(_KMeans): is 1. nbits : int, optional Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is - 32. Named quantization_bits, with 0 for raw float32, before 0.8.5. + 32. Notes ----- @@ -1117,7 +201,6 @@ class QGKMeans(_KMeans): _parameters_type = QGKMeansParameters _implementation_type = _QGKMeans - _renamed_parameters = _QG_RENAMED class RaBitQKMeans(_KMeans): @@ -1153,8 +236,7 @@ class RaBitQKMeans(_KMeans): capped by OMP_NUM_THREADS. Default is 0. final_assignment : {'approximate', 'exact'}, optional 'approximate' uses the training assignment method; 'exact' uses exhaustive - assignment against final centroids. Default is 'approximate'. A - FinalAssignmentMode member is still accepted until 0.9. + assignment against final centroids. Default is 'approximate'. Notes ----- @@ -1181,19 +263,16 @@ class RaBitQKMeans(_KMeans): _parameters_type = RaBitQKMeansParameters _implementation_type = _RaBitQKMeans - _renamed_parameters = {} __all__ = [ - "FinalAssignmentMode", + "FormatError", "HnswIndex", "IvfIndex", "KMeansIterationStats", "QGKMeans", - "QGKMeansIterationStats", "QGKMeansParameters", "RaBitQKMeans", - "RaBitQKMeansIterationStats", "RaBitQKMeansParameters", "SymqgIndex", ] diff --git a/python_bindings/__init__.pyi b/python_bindings/__init__.pyi index f53d8d07..4675a026 100644 --- a/python_bindings/__init__.pyi +++ b/python_bindings/__init__.pyi @@ -5,61 +5,36 @@ Array shapes and numeric ranges are documented runtime constraints. from collections.abc import Sequence from os import PathLike -from typing import Any, ClassVar, Literal, SupportsIndex, TypeAlias, overload +from typing import Any, Literal, SupportsIndex, TypeAlias import numpy as np import numpy.typing as npt -from typing_extensions import deprecated __version__: str __all__ = [ - "FinalAssignmentMode", + "FormatError", "HnswIndex", "IvfIndex", "KMeansIterationStats", "QGKMeans", - "QGKMeansIterationStats", "QGKMeansParameters", "RaBitQKMeans", - "RaBitQKMeansIterationStats", "RaBitQKMeansParameters", "SymqgIndex", ] _Path: TypeAlias = str | bytes | bytearray | PathLike[str] | PathLike[bytes] -_Metric: TypeAlias = Literal["l2", "ip", "innerproduct"] +_Metric: TypeAlias = Literal["l2", "ip", "cosine"] _Routing: TypeAlias = Literal["auto", "flat", "flat_rabitq", "hnsw"] _QGInit: TypeAlias = Literal["pipnn", "random"] _FinalAssignment: TypeAlias = Literal["approximate", "exact"] # Rank, ID ranges and Python bool (an int subtype) are validated at runtime. _IntegerIds: TypeAlias = npt.NDArray[np.integer[Any]] | Sequence[int | np.integer[Any]] -# pybind11 enums are not subclasses of enum.Enum. -@deprecated( - "FinalAssignmentMode is deprecated since 0.8.5; pass 'approximate' or 'exact' " - "as final_assignment" -) -class FinalAssignmentMode: - """Final centroid assignment policy. - - Approximate uses the selected clustering algorithm. SymphonyQG is a - compatibility alias for Approximate. Exact performs exhaustive assignment. - """ - - Approximate: ClassVar[FinalAssignmentMode] - SymphonyQG: ClassVar[FinalAssignmentMode] - Exact: ClassVar[FinalAssignmentMode] - __members__: ClassVar[dict[str, FinalAssignmentMode]] - - def __init__(self, value: SupportsIndex) -> None: ... - @property - def name(self) -> str: ... - @property - def value(self) -> int: ... - def __int__(self) -> int: ... - def __index__(self) -> int: ... +class FormatError(ValueError, RuntimeError): + """A damaged or mismatched index file or serialized byte string, or one this release cannot read. A subclass of both ValueError and RuntimeError.""" class KMeansIterationStats: """Read-only statistics for one completed clustering iteration.""" @@ -77,10 +52,6 @@ class KMeansIterationStats: def nsplit(self) -> int: """Number of empty centroids repaired by splitting.""" -# The two 0.8 names of KMeansIterationStats; deprecated since 0.8.5. -QGKMeansIterationStats = KMeansIterationStats -RaBitQKMeansIterationStats = KMeansIterationStats - class IvfIndex: """An approximate nearest-neighbor index using IVF. @@ -93,12 +64,11 @@ class IvfIndex: nbits : int, optional Keyword-only. Total quantization bits, 1 through 9, or 32 for owned float32 vectors with one-bit filtering and raw reranking. Default is 7. - metric : {'l2', 'ip', 'innerproduct'}, optional - Squared L2 or inner-product distance. Default is 'l2'. Vectors are not - automatically normalized for cosine similarity. + metric : {'l2', 'ip', 'cosine'}, optional + Squared L2, inner-product or cosine distance. Default is 'l2'. 'cosine' + scales data and queries to unit length. routing : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional - Centroid routing strategy. Default is 'auto'. Named initializer before - 0.8.5. + Centroid routing strategy. Default is 'auto'. seed : int, optional Rotation seed in [0, 2**32 - 1], also the initial cp.seed. None (default) draws one at random; the seed property reports it. @@ -111,9 +81,6 @@ class IvfIndex: supported; an overlapping mutation raises RuntimeError. Data, centroids and queries must be finite float32 values within the index coordinate range; other values raise ValueError. - The 0.7 form IvfIndex(dim, max_elements, num_clusters, nbits, ...) and - build() still work in 0.8, raise DeprecationWarning, and will be removed in - 0.9. Examples -------- @@ -127,7 +94,6 @@ class IvfIndex: ((2, 3), (2, 3)) """ - @overload def __init__( self, dim: SupportsIndex, @@ -149,12 +115,11 @@ class IvfIndex: nbits : int, optional Keyword-only. Total quantization bits, 1 through 9, or 32 for owned float32 vectors with one-bit filtering and raw reranking. Default is 7. - metric : {'l2', 'ip', 'innerproduct'}, optional - Squared L2 or inner-product distance. Default is 'l2'. Vectors are not - automatically normalized for cosine similarity. + metric : {'l2', 'ip', 'cosine'}, optional + Squared L2, inner-product or cosine distance. Default is 'l2'. 'cosine' + scales data and queries to unit length. routing : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional - Centroid routing strategy. Default is 'auto'. Named initializer before - 0.8.5. + Centroid routing strategy. Default is 'auto'. seed : int, optional Rotation seed in [0, 2**32 - 1], also the initial cp.seed. None (default) draws one at random; the seed property reports it. @@ -167,36 +132,7 @@ class IvfIndex: supported; an overlapping mutation raises RuntimeError. Data, centroids and queries must be finite float32 values within the index coordinate range; other values raise ValueError. - The 0.7 form IvfIndex(dim, max_elements, num_clusters, nbits, ...) and - build() still work in 0.8, raise DeprecationWarning, and will be removed in - 0.9. """ - @overload - @deprecated( - "IvfIndex(dim, max_elements, num_clusters, nbits, ...) is deprecated since " - "0.8; use IvfIndex(dim, num_clusters, nbits=...), whose first add() trains it" - ) - def __init__( - self, - dim: SupportsIndex, - max_elements: SupportsIndex, - num_clusters: SupportsIndex, - nbits: SupportsIndex, - metric: _Metric = "l2", - initializer: _Routing = "auto", - ) -> None: ... - @overload - @deprecated("IvfIndex(initializer=...) is deprecated since 0.8.5; use routing=") - def __init__( - self, - dim: SupportsIndex, - num_clusters: SupportsIndex, - *, - nbits: SupportsIndex = 7, - metric: _Metric = "l2", - initializer: _Routing, - seed: SupportsIndex | None = None, - ) -> None: ... def __repr__(self) -> str: """Return a one-line summary of configuration, counts and training state.""" @@ -207,13 +143,6 @@ class IvfIndex: def dim(self) -> int: """Original vector dimension.""" - @property - @deprecated( - "IvfIndex.max_elements is deprecated since 0.8.5; use num_stored_points" - ) - def max_elements(self) -> int: - """Deprecated since 0.8.5: use num_stored_points.""" - @property def num_points(self) -> int: """Number of live, searchable points.""" @@ -224,26 +153,21 @@ class IvfIndex: @property def is_trained(self) -> bool: - """Whether centroids are set, by train, set_centroids, the first add, build or load.""" - - @property - @deprecated("IvfIndex.is_built is deprecated since 0.8; use is_trained or len()") - def is_built(self) -> bool: - """Deprecated since 0.8: whether the index stores points; use len().""" + """Whether centroids are set, by train, set_centroids, the first add or load.""" @property def seed(self) -> int | None: - """Rotation seed, or None for an index loaded from disk or created in the 0.7 form.""" + """Rotation seed, or None for an index loaded from a file from a release up to 0.8.""" @property def cp(self) -> RaBitQKMeansParameters: - """Clustering parameters train uses, a RaBitQKMeansParameters. Defaults: niter 10, max_points_per_centroid 256, spherical for inner product, and seed equal to the index seed.""" + """Clustering parameters train uses, a RaBitQKMeansParameters. Defaults: niter 10, max_points_per_centroid 256, spherical for inner product and cosine, and seed equal to the index seed.""" @cp.setter def cp(self, value: RaBitQKMeansParameters) -> None: ... @property - def metric(self) -> Literal["l2", "ip"]: - """Canonical metric name: 'l2' or 'ip'.""" + def metric(self) -> Literal["l2", "ip", "cosine"]: + """Canonical metric name: 'l2', 'ip' or 'cosine'.""" @property def nbits(self) -> int: @@ -265,8 +189,7 @@ class IvfIndex: n >= num_clusters. Converted to contiguous float32; a copy may be made. num_threads : int, optional Keyword-only. Worker count for this call. None (default) uses - cp.num_threads; 0 selects the available CPU count, - capped by OMP_NUM_THREADS. + cp.num_threads; 0 selects the available CPU count, capped by OMP_NUM_THREADS. Notes ----- @@ -286,7 +209,8 @@ class IvfIndex: ---------- centroids : array_like of float, shape (num_clusters, dim) Centroids in the original, unpadded coordinates. Converted to - contiguous float32; a copy may be made. + contiguous float32; a copy may be made. A cosine index scales them + to unit length, as it does data. num_threads : int, optional Keyword-only. Worker count for rotating the centroids and building the centroid routing. None (default) and 0 select the available CPU count, @@ -300,43 +224,6 @@ class IvfIndex: failed call leaves the index unchanged. """ - @deprecated( - "IvfIndex.build() is deprecated since 0.8; use set_centroids() or " - "train(), then add()" - ) - def build( - self, - data: npt.ArrayLike, - centroids: npt.ArrayLike, - cluster_ids: _IntegerIds, - num_threads: SupportsIndex = 1, - fast_quantization: bool | np.bool_ = False, - ) -> None: - """Build the index from vectors and supplied centroid assignments. - - Deprecated since 0.8 and removed in 0.9: use set_centroids() (or - train()) and then add(). The defaults match 0.7, including a single - thread. - - Parameters - ---------- - data : array_like of float, shape (n, dim) - Vectors in the original, unpadded coordinates. Converted to - contiguous float32; a copy may be made. - centroids : array_like of float, shape (num_clusters, dim) - Vectors in the original, unpadded coordinates. Converted to - contiguous float32; a copy may be made. - cluster_ids : array_like of int, shape (n,) - Centroid ID per vector, in [0, num_clusters). Floating-point and - boolean IDs are rejected. - num_threads : int, optional - Worker count. Default is 1; 0 selects the available CPU count, - capped by OMP_NUM_THREADS. - fast_quantization : bool, optional - Use faster quantizer configuration. Default is False. - """ - - @overload def add( self, data: npt.ArrayLike, @@ -344,7 +231,7 @@ class IvfIndex: cluster_ids: _IntegerIds | None = None, num_threads: SupportsIndex | None = None, fast_quantization: bool | np.bool_ = False, - ) -> npt.NDArray[np.uint32]: + ) -> npt.NDArray[np.int64]: """Add vectors, training the index first if needed. Parameters @@ -364,7 +251,7 @@ class IvfIndex: Returns ------- - ids : ndarray of uint32, shape (n,) + ids : ndarray of int64, shape (n,) Assigned point IDs. Notes @@ -373,24 +260,10 @@ class IvfIndex: as train(data) does, so data needs at least num_clusters rows, and an empty first add raises RuntimeError; with num_threads None, training uses cp.num_threads. Passing cluster_ids to an - untrained index raises RuntimeError, as does add on an index created with - max_elements, which build fills. If the call fails, the index stays + untrained index raises RuntimeError. If the call fails, the index stays untrained and empty. Batch additions to reduce repeated cluster copying; - reserve_cluster can preallocate room. Passing the options positionally is - deprecated. + reserve_cluster can preallocate room. """ - @overload - @deprecated( - "Passing options to IvfIndex.add() by position is deprecated since 0.8; " - "pass them by keyword" - ) - def add( - self, - data: npt.ArrayLike, - cluster_ids: _IntegerIds | None, - num_threads: SupportsIndex = ..., - fast_quantization: bool | np.bool_ = ..., - ) -> npt.NDArray[np.uint32]: ... def remove(self, ids: _IntegerIds) -> int: """Exclude point IDs from subsequent search results. @@ -410,7 +283,6 @@ class IvfIndex: Removal does not reclaim storage and cannot be undone. """ - @overload def search( self, queries: npt.ArrayLike, @@ -419,7 +291,7 @@ class IvfIndex: *, high_accuracy: bool | np.bool_ | None = None, num_threads: SupportsIndex | None = None, - ) -> tuple[npt.NDArray[np.uint32], npt.NDArray[np.float32]]: + ) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.float32]]: """Search a batch of query vectors. Parameters @@ -431,45 +303,31 @@ class IvfIndex: Number of neighbors requested, at least 1. It may exceed the number of points; slots without a neighbor are padded as described below. nprobe : int, optional - Number of clusters to probe, capped at num_clusters. None (default) - selects num_clusters / 16, rounded to the nearest integer and at least - 1; 0 does the same and is deprecated since 0.8.5. + Number of clusters to probe, at least 1 and capped at num_clusters. None + (default) selects num_clusters / 16, rounded to the nearest integer and + at least 1. high_accuracy : bool, optional - Keyword-only; passing it by position is deprecated since 0.8.5. - Enable HACC. None (default) selects it for 4-9 bits and standard - FastScan otherwise. Raw storage uses standard FastScan. + Keyword-only. Enable HACC. None (default) selects it for 4-9 bits and + standard FastScan otherwise. Raw storage uses standard FastScan. num_threads : int, optional - Keyword-only; passing it by position is deprecated since 0.8.5. Worker - count. None (default) selects 1; 0 selects the available CPU count, - capped by OMP_NUM_THREADS. + Keyword-only. Worker count. None (default) selects 1; 0 selects the + available CPU count, capped by OMP_NUM_THREADS. Returns ------- - ids : ndarray of uint32, shape (n_queries, k) + ids : ndarray of int64, shape (n_queries, k) Point IDs of the selected neighbors. distances : ndarray of float32, shape (n_queries, k) - Lower values are better; squared L2 estimates for l2 and inner-product - distance estimates for ip. These are distances, not similarity scores. + Lower values are better: squared L2 estimates for l2, 1 - dot for ip and + 1 - cos for cosine. These are distances, not similarity scores. Notes ----- Requires a trained or loaded index. Returns (ids, distances), in that - order. Missing neighbors have ID 4294967295 and distance inf; test + order. Missing neighbors have ID -1 and distance inf; test np.isfinite(distances) to find them. Array shapes and value ranges are checked at runtime, not by static type checkers. """ - @overload - @deprecated( - "Passing high_accuracy or num_threads to IvfIndex.search() by position is deprecated since 0.8.5; use keywords" - ) - def search( - self, - queries: npt.ArrayLike, - k: SupportsIndex, - nprobe: SupportsIndex | None, - high_accuracy: bool | np.bool_ | None, - num_threads: SupportsIndex | None = ..., - ) -> tuple[npt.NDArray[np.uint32], npt.NDArray[np.float32]]: ... def save(self, path: _Path) -> None: """Save an index with stored vectors to disk. @@ -482,7 +340,7 @@ class IvfIndex: Notes ----- A trained index without vectors raises RuntimeError; add vectors first. - IVF with HNSW centroid routing also writes its required sidecar file. + The one file includes HNSW centroid routing; releases up to 0.8 cannot read it. """ @staticmethod @@ -499,16 +357,16 @@ class IvfIndex: ------- index : IvfIndex A trained index ready for search. + + Notes + ----- + Files from releases up to 0.8 with HNSW centroid routing also need the + accompanying ``.hnsw`` file. """ @property def routing(self) -> _Routing: - """Resolved centroid routing strategy. Named initializer before 0.8.5.""" - - @property - @deprecated("IvfIndex.initializer is deprecated since 0.8.5; use routing") - def initializer(self) -> _Routing: - """Deprecated since 0.8.5: use routing.""" + """Resolved centroid routing strategy, never 'auto'.""" def reserve_cluster( self, cluster_id: SupportsIndex, num_points: SupportsIndex @@ -520,19 +378,14 @@ class IvfIndex: cluster_id : int Cluster ID in [0, num_clusters). num_points : int - Nonnegative capacity to reserve for this cluster: the total number - of points it can hold, including its current ones. + Nonnegative capacity to reserve for this cluster: the total number of + points it can hold, including its current ones. Notes ----- - Requires a trained or loaded index. Reserved room is not saved. Named - reserve before 0.8.5. + Requires a trained or loaded index. Reserved room is not saved. """ - @deprecated("IvfIndex.reserve() is deprecated since 0.8.5; use reserve_cluster()") - def reserve(self, cluster_id: SupportsIndex, num_points: SupportsIndex) -> None: - """Deprecated since 0.8.5: the same as reserve_cluster(); use reserve_cluster().""" - class HnswIndex: """An approximate nearest-neighbor index using HNSW. @@ -551,42 +404,38 @@ class HnswIndex: 2 * M edges. Default is 16. ef_construction : int, optional Keyword-only. Construction search breadth. Default is 200. - metric : {'l2', 'ip', 'innerproduct'}, optional - Keyword-only. Squared L2 or inner-product distance. Default is 'l2'. - Vectors are not automatically normalized for cosine similarity. + metric : {'l2', 'ip', 'cosine'}, optional + Keyword-only. Squared L2, inner-product or cosine distance. Default is + 'l2'. 'cosine' scales data and queries to unit length. seed : int, optional - Keyword-only. Graph and rotation seed, also the initial cp.seed (its low - 32 bits), in [0, 2**32 - 1]; larger values are deprecated since 0.8.5. - Default is 100. + Keyword-only. Graph and rotation seed in [0, 2**32 - 1], also the initial + cp.seed. None (default) draws one at random; the seed property reports it. Notes ----- The first add trains an untrained index on the added vectors. Call train on a sample, or set_centroids, first to choose the training data or the - centroids. Loaded indexes are trained, except empty files saved untrained - by 0.7. Capacity grows automatically + centroids. Loaded indexes are trained, except one loaded from a file saved + before training. Capacity grows automatically on add; reserve can preallocate it. Concurrent reads are supported; an overlapping mutation raises RuntimeError. Data, centroids and queries must be finite float32 values within the index coordinate range; other values raise ValueError. With more than one thread, add links points in a nondeterministic order; - pass num_threads=1 for a reproducible graph. - The 0.7 forms HnswIndex(dim, max_elements, ...), random_seed= and build() - still work in 0.8, raise DeprecationWarning, and will be removed in 0.9. + pass num_threads=1 and a seed for a reproducible graph. Examples -------- >>> import numpy as np >>> from rabitqlib import HnswIndex >>> x = np.random.default_rng(42).normal(size=(80, 64)).astype(np.float32) - >>> index = HnswIndex(64, num_clusters=2) + >>> index = HnswIndex(64, num_clusters=2, seed=7) >>> ids = index.add(x, num_threads=1) # trains on x first >>> ids, distances = index.search(x[:2], k=3) >>> ids.shape, distances.shape ((2, 3), (2, 3)) """ - @overload def __init__( self, dim: SupportsIndex, @@ -596,7 +445,7 @@ class HnswIndex: M: SupportsIndex = 16, ef_construction: SupportsIndex = 200, metric: _Metric = "l2", - seed: SupportsIndex = 100, + seed: SupportsIndex | None = None, ) -> None: """An approximate nearest-neighbor index using HNSW. @@ -615,57 +464,26 @@ class HnswIndex: 2 * M edges. Default is 16. ef_construction : int, optional Keyword-only. Construction search breadth. Default is 200. - metric : {'l2', 'ip', 'innerproduct'}, optional - Keyword-only. Squared L2 or inner-product distance. Default is 'l2'. - Vectors are not automatically normalized for cosine similarity. + metric : {'l2', 'ip', 'cosine'}, optional + Keyword-only. Squared L2, inner-product or cosine distance. Default is + 'l2'. 'cosine' scales data and queries to unit length. seed : int, optional - Keyword-only. Graph and rotation seed, also the initial cp.seed (its low - 32 bits), in [0, 2**32 - 1]; larger values are deprecated since 0.8.5. - Default is 100. + Keyword-only. Graph and rotation seed in [0, 2**32 - 1], also the initial + cp.seed. None (default) draws one at random; the seed property reports it. Notes ----- The first add trains an untrained index on the added vectors. Call train on a sample, or set_centroids, first to choose the training data or the - centroids. Loaded indexes are trained, except empty files saved untrained - by 0.7. Capacity grows automatically + centroids. Loaded indexes are trained, except one loaded from a file saved + before training. Capacity grows automatically on add; reserve can preallocate it. Concurrent reads are supported; an overlapping mutation raises RuntimeError. Data, centroids and queries must be finite float32 values within the index coordinate range; other values raise ValueError. With more than one thread, add links points in a nondeterministic order; - pass num_threads=1 for a reproducible graph. - The 0.7 forms HnswIndex(dim, max_elements, ...), random_seed= and build() - still work in 0.8, raise DeprecationWarning, and will be removed in 0.9. + pass num_threads=1 and a seed for a reproducible graph. """ - @overload - @deprecated( - "HnswIndex(dim, max_elements, ...) is deprecated since 0.8; use " - "HnswIndex(dim, nbits=...), whose capacity grows on add" - ) - def __init__( - self, - dim: SupportsIndex, - max_elements: SupportsIndex, - M: SupportsIndex = 16, - ef_construction: SupportsIndex = 200, - nbits: SupportsIndex = 8, - metric: _Metric = "l2", - random_seed: SupportsIndex = 100, - ) -> None: ... - @overload - @deprecated("HnswIndex(random_seed=...) is deprecated since 0.8; use seed=") - def __init__( - self, - dim: SupportsIndex, - *, - nbits: SupportsIndex = 7, - num_clusters: SupportsIndex = 16, - M: SupportsIndex = 16, - ef_construction: SupportsIndex = 200, - metric: _Metric = "l2", - random_seed: SupportsIndex, - ) -> None: ... def __repr__(self) -> str: """Return a one-line summary of configuration, counts and training state.""" @@ -678,12 +496,7 @@ class HnswIndex: @property def capacity(self) -> int: - """Current storage capacity, in stored points. Named max_elements before 0.8.5.""" - - @property - @deprecated("HnswIndex.max_elements is deprecated since 0.8.5; use capacity") - def max_elements(self) -> int: - """Deprecated since 0.8.5: use capacity.""" + """Current storage capacity, in stored points.""" @property def num_points(self) -> int: @@ -695,26 +508,21 @@ class HnswIndex: @property def is_trained(self) -> bool: - """Whether centroids are set, by train, set_centroids, the first add, build or load.""" - - @property - @deprecated("HnswIndex.is_built is deprecated since 0.8; use is_trained or len()") - def is_built(self) -> bool: - """Deprecated since 0.8: whether the index stores points; use len().""" + """Whether centroids are set, by train, set_centroids, the first add or load.""" @property def seed(self) -> int | None: - """Graph and rotation seed, or None for an index loaded from disk.""" + """Graph and rotation seed, or None for an index loaded from a file from a release up to 0.8.""" @property def cp(self) -> RaBitQKMeansParameters: - """Clustering parameters train uses, a RaBitQKMeansParameters. Defaults: niter 10, max_points_per_centroid 256, spherical for inner product, and seed equal to the low 32 bits of the index seed.""" + """Clustering parameters train uses, a RaBitQKMeansParameters. Defaults: niter 10, max_points_per_centroid 256, spherical for inner product and cosine, and seed equal to the index seed.""" @cp.setter def cp(self, value: RaBitQKMeansParameters) -> None: ... @property - def metric(self) -> Literal["l2", "ip"]: - """Canonical metric name: 'l2' or 'ip'.""" + def metric(self) -> Literal["l2", "ip", "cosine"]: + """Canonical metric name: 'l2', 'ip' or 'cosine'.""" @property def nbits(self) -> int: @@ -744,8 +552,7 @@ class HnswIndex: n >= num_clusters. Converted to contiguous float32; a copy may be made. num_threads : int, optional Keyword-only. Worker count for this call. None (default) uses - cp.num_threads; 0 selects the available CPU count, - capped by OMP_NUM_THREADS. + cp.num_threads; 0 selects the available CPU count, capped by OMP_NUM_THREADS. Notes ----- @@ -762,7 +569,8 @@ class HnswIndex: ---------- centroids : array_like of float, shape (num_clusters, dim) Centroids in the original, unpadded coordinates. Converted to - contiguous float32; a copy may be made. + contiguous float32; a copy may be made. A cosine index scales them + to unit length, as it does data. Notes ----- @@ -771,43 +579,6 @@ class HnswIndex: failed call leaves the index unchanged. """ - @deprecated( - "HnswIndex.build() is deprecated since 0.8; use set_centroids() or " - "train(), then add()" - ) - def build( - self, - data: npt.ArrayLike, - centroids: npt.ArrayLike, - cluster_ids: _IntegerIds, - num_threads: SupportsIndex = 1, - fast_quantization: bool | np.bool_ = False, - ) -> None: - """Build the index from vectors and supplied centroid assignments. - - Deprecated since 0.8 and removed in 0.9: use set_centroids() (or - train()) and then add(). The defaults match 0.7, including a single - thread. - - Parameters - ---------- - data : array_like of float, shape (n, dim) - Vectors in the original, unpadded coordinates. Converted to - contiguous float32; a copy may be made. - centroids : array_like of float, shape (num_clusters, dim) - Vectors in the original, unpadded coordinates. Converted to - contiguous float32; a copy may be made. - cluster_ids : array_like of int, shape (n,) - Centroid ID per vector, in [0, num_clusters). Floating-point and - boolean IDs are rejected. - num_threads : int, optional - Worker count. Default is 1; 0 selects the available CPU count, - capped by OMP_NUM_THREADS. - fast_quantization : bool, optional - Use faster quantizer configuration. Default is False. - """ - - @overload def add( self, data: npt.ArrayLike, @@ -815,7 +586,7 @@ class HnswIndex: cluster_ids: _IntegerIds | None = None, num_threads: SupportsIndex | None = None, fast_quantization: bool | np.bool_ = False, - ) -> npt.NDArray[np.uint32]: + ) -> npt.NDArray[np.int64]: """Add vectors, training the index first if needed. Parameters @@ -829,13 +600,14 @@ class HnswIndex: num_threads : int, optional Keyword-only. Worker count. None (default) and 0 select the available CPU count, capped by OMP_NUM_THREADS; more than one thread links - nondeterministically, so pass 1 for a reproducible graph. + nondeterministically, so pass 1, and a seed to the constructor, for a + reproducible graph. fast_quantization : bool, optional Keyword-only. Use faster quantizer configuration. Default is False. Returns ------- - ids : ndarray of uint32, shape (n,) + ids : ndarray of int64, shape (n,) Assigned point IDs. Notes @@ -845,25 +617,13 @@ class HnswIndex: num_clusters then reports the row count. An empty first add raises RuntimeError. With num_threads None, training uses cp.num_threads. Passing cluster_ids to an untrained index raises - RuntimeError, as does add on an untrained index loaded from a 0.7 file; - call train first. If the call fails, the index stays - untrained and empty. The first add into an empty index links vectors with - their exact coordinates; later adds link through the stored codes, so add - most vectors in the first call. Capacity grows geometrically when needed. - Removed IDs are not reused. Passing the options positionally is deprecated. + RuntimeError, as does add on an index loaded from an untrained file; + call train or set_centroids first. If the call fails, the index stays untrained + and empty. The first + add into an empty index links vectors with their exact coordinates; later adds + link through the stored codes, so add most vectors in the first call. Capacity + grows geometrically when needed. Removed IDs are not reused. """ - @overload - @deprecated( - "Passing options to HnswIndex.add() by position is deprecated since 0.8; " - "pass them by keyword" - ) - def add( - self, - data: npt.ArrayLike, - cluster_ids: _IntegerIds | None, - num_threads: SupportsIndex = ..., - fast_quantization: bool | np.bool_ = ..., - ) -> npt.NDArray[np.uint32]: ... def remove(self, ids: _IntegerIds) -> int: """Exclude point IDs from subsequent search results. @@ -883,7 +643,6 @@ class HnswIndex: Removal does not reclaim storage and cannot be undone. """ - @overload def search( self, queries: npt.ArrayLike, @@ -891,7 +650,7 @@ class HnswIndex: ef_search: SupportsIndex | None = None, *, num_threads: SupportsIndex | None = None, - ) -> tuple[npt.NDArray[np.uint32], npt.NDArray[np.float32]]: + ) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.float32]]: """Search a batch of query vectors. Parameters @@ -903,50 +662,27 @@ class HnswIndex: Number of neighbors requested, at least 1. It may exceed the number of points; slots without a neighbor are padded as described below. ef_search : int, optional - Search breadth. None (default) selects max(k, 64); values above the stored - point count are clamped. 0 selects the default and is deprecated since - 0.8.5. Named ef before 0.8.5. + Search breadth, at least 1. None (default) selects max(k, 64); values + above the stored point count are clamped. num_threads : int, optional - Keyword-only; passing it by position is deprecated since 0.8.5. Worker - count. None (default) selects 1; 0 selects the available CPU count, - capped by OMP_NUM_THREADS. + Keyword-only. Worker count. None (default) selects 1; 0 selects the + available CPU count, capped by OMP_NUM_THREADS. Returns ------- - ids : ndarray of uint32, shape (n_queries, k) + ids : ndarray of int64, shape (n_queries, k) Point IDs of the selected neighbors. distances : ndarray of float32, shape (n_queries, k) - Lower values are better; squared L2 estimates for l2 and inner-product - distance estimates for ip. These are distances, not similarity scores. + Lower values are better: squared L2 estimates for l2, 1 - dot for ip and + 1 - cos for cosine. These are distances, not similarity scores. Notes ----- - Requires a trained or loaded index. Returns (ids, distances), in that - order. Missing neighbors have ID 4294967295 and distance inf; test + Requires a trained index. Returns (ids, distances), in that + order. Missing neighbors have ID -1 and distance inf; test np.isfinite(distances) to find them. Array shapes and value ranges are checked at runtime, not by static type checkers. """ - @overload - @deprecated("HnswIndex.search(ef=...) is deprecated since 0.8.5; use ef_search=") - def search( - self, - queries: npt.ArrayLike, - k: SupportsIndex, - *, - ef: SupportsIndex | None, - num_threads: SupportsIndex | None = None, - ) -> tuple[npt.NDArray[np.uint32], npt.NDArray[np.float32]]: ... - @overload - @deprecated( - "Passing num_threads to HnswIndex.search() by position is deprecated since 0.8.5; use the keyword" - ) - def search( - self, - queries: npt.ArrayLike, - k: SupportsIndex, - ef_search: SupportsIndex | None, - num_threads: SupportsIndex | None, - ) -> tuple[npt.NDArray[np.uint32], npt.NDArray[np.float32]]: ... def save(self, path: _Path) -> None: """Save an index with stored vectors to disk. @@ -959,7 +695,8 @@ class HnswIndex: Notes ----- A trained index without vectors raises RuntimeError; add vectors first. - The saved state includes the rotation used to build the index. + The saved state includes the rotation used to build the index and its seed; + releases up to 0.8 cannot read the file. """ @staticmethod @@ -975,7 +712,7 @@ class HnswIndex: Returns ------- index : HnswIndex - A trained index ready for search. + The loaded index, trained unless the file was saved before training. """ def reserve(self, num_points: SupportsIndex) -> None: @@ -989,17 +726,10 @@ class HnswIndex: Notes ----- - Capacity only grows: a value at or below capacity changes nothing. add - also grows the capacity when needed, so reserve is an optimization. + Capacity only grows: a value at or below capacity changes nothing. add also + grows the capacity when needed, so reserve is an optimization. """ - @deprecated( - "HnswIndex.resize() is deprecated since 0.8.5; use reserve(), which only " - "grows the capacity" - ) - def resize(self, max_elements: SupportsIndex) -> None: - """Deprecated since 0.8.5: change the capacity; use reserve(), which only grows it.""" - class SymqgIndex: """An approximate nearest-neighbor index using SymphonyQG. @@ -1018,9 +748,9 @@ class SymqgIndex: Default is 200. init : {'pipnn', 'random'}, optional Keyword-only. Graph initialization method. Default is 'pipnn'. - metric : {'l2', 'ip', 'innerproduct'}, optional - Keyword-only. Squared L2 or inner-product distance. Default is 'l2'. - Vectors are not automatically normalized for cosine similarity. + metric : {'l2', 'ip', 'cosine'}, optional + Keyword-only. Squared L2, inner-product or cosine distance. Default is + 'l2'. 'cosine' scales data and queries to unit length. seed : int, optional Keyword-only. Rotation and graph-construction seed in [0, 2**32 - 1]. None (default) draws one at random; the seed property reports it. @@ -1034,9 +764,6 @@ class SymqgIndex: overlapping mutation raises RuntimeError. Data and queries must be finite float32 values within the index coordinate range; other values raise ValueError. - The 0.7 forms SymqgIndex(dim, max_degree, metric, quantization_bits), - quantization_bits=, build() and search_batch() still work in 0.8, raise - DeprecationWarning, and will be removed in 0.9. Examples -------- @@ -1050,7 +777,6 @@ class SymqgIndex: ((2, 3), (2, 3)) """ - @overload def __init__( self, dim: SupportsIndex, @@ -1079,9 +805,9 @@ class SymqgIndex: Default is 200. init : {'pipnn', 'random'}, optional Keyword-only. Graph initialization method. Default is 'pipnn'. - metric : {'l2', 'ip', 'innerproduct'}, optional - Keyword-only. Squared L2 or inner-product distance. Default is 'l2'. - Vectors are not automatically normalized for cosine similarity. + metric : {'l2', 'ip', 'cosine'}, optional + Keyword-only. Squared L2, inner-product or cosine distance. Default is + 'l2'. 'cosine' scales data and queries to unit length. seed : int, optional Keyword-only. Rotation and graph-construction seed in [0, 2**32 - 1]. None (default) draws one at random; the seed property reports it. @@ -1095,38 +821,7 @@ class SymqgIndex: overlapping mutation raises RuntimeError. Data and queries must be finite float32 values within the index coordinate range; other values raise ValueError. - The 0.7 forms SymqgIndex(dim, max_degree, metric, quantization_bits), - quantization_bits=, build() and search_batch() still work in 0.8, raise - DeprecationWarning, and will be removed in 0.9. """ - @overload - @deprecated( - "SymqgIndex(dim, max_degree, metric, quantization_bits) is deprecated since " - "0.8; use SymqgIndex(dim, max_degree=..., metric=..., nbits=...)" - ) - def __init__( - self, - dim: SupportsIndex, - max_degree: SupportsIndex, - metric: _Metric = "l2", - quantization_bits: SupportsIndex = 0, - ) -> None: ... - @overload - @deprecated( - "SymqgIndex(quantization_bits=...) is deprecated since 0.8; use nbits=, " - "with 32 instead of 0 for raw vectors" - ) - def __init__( - self, - dim: SupportsIndex, - *, - quantization_bits: SupportsIndex, - max_degree: SupportsIndex = 32, - ef_construction: SupportsIndex = 200, - init: _QGInit = "pipnn", - metric: _Metric = "l2", - seed: SupportsIndex | None = None, - ) -> None: ... def __repr__(self) -> str: """Return a one-line summary of configuration and counts.""" @@ -1137,13 +832,6 @@ class SymqgIndex: def dim(self) -> int: """Original vector dimension.""" - @property - @deprecated( - "SymqgIndex.max_elements is deprecated since 0.8.5; use num_stored_points" - ) - def max_elements(self) -> int: - """Deprecated since 0.8.5: use num_stored_points.""" - @property def num_points(self) -> int: """Number of live, searchable points.""" @@ -1157,13 +845,8 @@ class SymqgIndex: """Always True: SymphonyQG needs no training.""" @property - @deprecated("SymqgIndex.is_built is deprecated since 0.8; use len()") - def is_built(self) -> bool: - """Deprecated since 0.8: whether the index holds a graph; use len().""" - - @property - def metric(self) -> Literal["l2", "ip"]: - """Canonical metric name: 'l2' or 'ip'.""" + def metric(self) -> Literal["l2", "ip", "cosine"]: + """Canonical metric name: 'l2', 'ip' or 'cosine'.""" @property def max_degree(self) -> int: @@ -1171,27 +854,19 @@ class SymqgIndex: @property def ef_construction(self) -> int | None: - """Construction search breadth of the current graph or the next add, or None for an index loaded from disk.""" + """Construction search breadth of the current graph or the next add, or None for an index loaded from a file from a release up to 0.8.""" @property def init(self) -> _QGInit | None: - """Graph initialization method of the current graph or the next add, or None for an index loaded from disk.""" + """Graph initialization method of the current graph or the next add, or None for an index loaded from a file from a release up to 0.8.""" @property def nbits(self) -> int: """Storage bits: 32 for raw float32, or 4 or 8 for RaBitQ.""" - @property - @deprecated( - "SymqgIndex.quantization_bits is deprecated since 0.8; use nbits, which is " - "32 instead of 0 for raw vectors" - ) - def quantization_bits(self) -> int: - """Deprecated since 0.8: storage bits with 0 for raw vectors; use nbits.""" - @property def seed(self) -> int | None: - """Rotation and graph-construction seed, or None for an index loaded from disk.""" + """Rotation and graph-construction seed, or None for an index loaded from a file from a release up to 0.8.""" def train( self, x: npt.ArrayLike, *, num_threads: SupportsIndex | None = None @@ -1216,7 +891,7 @@ class SymqgIndex: def add( self, data: npt.ArrayLike, *, num_threads: SupportsIndex | None = None - ) -> npt.NDArray[np.uint32]: + ) -> npt.NDArray[np.int64]: """Build the graph from all vectors. Parameters @@ -1230,7 +905,7 @@ class SymqgIndex: Returns ------- - ids : ndarray of uint32, shape (n,) + ids : ndarray of int64, shape (n,) Point IDs, the row numbers of data. Notes @@ -1241,38 +916,6 @@ class SymqgIndex: data. Input arrays need not be retained after this synchronous call. """ - @deprecated( - "SymqgIndex.build() is deprecated since 0.8; pass ef_construction and init " - "to SymqgIndex() and call add()" - ) - def build( - self, - data: npt.ArrayLike, - ef_construction: SupportsIndex, - num_threads: SupportsIndex = 1, - init: _QGInit = "pipnn", - ) -> None: - """Build the graph from input vectors, replacing any existing graph. - - Deprecated since 0.8 and removed in 0.9: pass ef_construction and init to - the constructor, then call add() once. The defaults match 0.7, including - a single thread. - - Parameters - ---------- - data : array_like of float, shape (n, dim) - Vectors in the original, unpadded coordinates, with n > max_degree. - Converted to contiguous float32; a copy may be made. - ef_construction : int - Positive construction search breadth fitting uint32. - num_threads : int, optional - Worker count. Default is 1; 0 selects the available CPU count, - capped by OMP_NUM_THREADS. - init : {'pipnn', 'random'}, optional - Graph initialization method. Default is 'pipnn'. - """ - - @overload def search( self, queries: npt.ArrayLike, @@ -1280,7 +923,7 @@ class SymqgIndex: ef_search: SupportsIndex | None = None, *, num_threads: SupportsIndex | None = None, - ) -> tuple[npt.NDArray[np.uint32], npt.NDArray[np.float32]]: + ) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.float32]]: """Search a batch of query vectors. Parameters @@ -1292,59 +935,27 @@ class SymqgIndex: Number of neighbors requested, at least 1. It may exceed the number of points; slots without a neighbor are padded as described below. ef_search : int, optional - Search breadth. None (default) selects max(k, 64); smaller values - are raised to k. 0 selects the default and is deprecated since 0.8.5. - Named ef before 0.8.5. + Search breadth, at least 1. None (default) selects max(k, 64); smaller + values are raised to k. num_threads : int, optional - Keyword-only; passing it by position is deprecated since 0.8.5. Worker - count. None (default) selects 1; 0 selects the available CPU count, - capped by OMP_NUM_THREADS. + Keyword-only. Worker count. None (default) selects 1; 0 selects the + available CPU count, capped by OMP_NUM_THREADS. Returns ------- - ids : ndarray of uint32, shape (n_queries, k) + ids : ndarray of int64, shape (n_queries, k) Point IDs of the selected neighbors. distances : ndarray of float32, shape (n_queries, k) - Lower values are better; squared L2 estimates for l2 and inner-product - distance estimates for ip. These are distances, not similarity scores. + Lower values are better: squared L2 estimates for l2, 1 - dot for ip and + 1 - cos for cosine. These are distances, not similarity scores. Notes ----- Returns (ids, distances), in that order. When the graph reaches fewer than k - points, the remaining neighbors have ID 4294967295 and distance inf; test + points, the remaining neighbors have ID -1 and distance inf; test np.isfinite(distances) to find them. Array shapes and value ranges are checked at runtime, not by static type checkers. """ - @overload - @deprecated("SymqgIndex.search(ef=...) is deprecated since 0.8.5; use ef_search=") - def search( - self, - queries: npt.ArrayLike, - k: SupportsIndex, - *, - ef: SupportsIndex | None, - num_threads: SupportsIndex | None = None, - ) -> tuple[npt.NDArray[np.uint32], npt.NDArray[np.float32]]: ... - @overload - @deprecated( - "Passing num_threads to SymqgIndex.search() by position is deprecated since 0.8.5; use the keyword" - ) - def search( - self, - queries: npt.ArrayLike, - k: SupportsIndex, - ef_search: SupportsIndex | None, - num_threads: SupportsIndex | None, - ) -> tuple[npt.NDArray[np.uint32], npt.NDArray[np.float32]]: ... - @deprecated("SymqgIndex.search_batch() is deprecated since 0.8; use search()") - def search_batch( - self, - queries: npt.ArrayLike, - k: SupportsIndex, - ef: SupportsIndex, - num_threads: SupportsIndex = 1, - ) -> tuple[npt.NDArray[np.uint32], npt.NDArray[np.float32]]: - """Deprecated since 0.8: the same as search(); use search().""" def save(self, path: _Path) -> None: """Save an index with vectors to disk. @@ -1357,7 +968,8 @@ class SymqgIndex: Notes ----- - The saved state includes the rotation used to build the index. + The saved state includes the rotation used to build the index and its seed; + releases up to 0.8 cannot read the file. """ @staticmethod @@ -1410,14 +1022,11 @@ class QGKMeans: capped by OMP_NUM_THREADS. Default is 0. final_assignment : {'approximate', 'exact'}, optional 'approximate' uses the training assignment method; 'exact' uses exhaustive - assignment against final centroids. Default is 'approximate'. A - FinalAssignmentMode member is still accepted until 0.9. + assignment against final centroids. Default is 'approximate'. max_degree : int, optional - Centroid graph degree; a positive multiple of 32. Default is 32. Named - graph_degree before 0.8.5. + Centroid graph degree; a positive multiple of 32. Default is 32. ef_construction : int, optional Positive centroid-graph construction search breadth. Default is 240. - Named ef_build before 0.8.5. ef_search : int, optional Positive centroid-graph assignment search breadth. Default is 16. graph_build_iterations : int, optional @@ -1425,7 +1034,7 @@ class QGKMeans: is 1. nbits : int, optional Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is - 32. Named quantization_bits, with 0 for raw float32, before 0.8.5. + 32. Notes ----- @@ -1444,7 +1053,6 @@ class QGKMeans: k: int cp: QGKMeansParameters - @overload def __init__( self, d: SupportsIndex, @@ -1458,7 +1066,7 @@ class QGKMeans: max_points_per_centroid: SupportsIndex = 0, early_stop_threshold: float = 0.0, num_threads: SupportsIndex = 0, - final_assignment: _FinalAssignment | FinalAssignmentMode = "approximate", + final_assignment: _FinalAssignment = "approximate", max_degree: SupportsIndex = 32, ef_construction: SupportsIndex = 240, ef_search: SupportsIndex = 16, @@ -1498,14 +1106,11 @@ class QGKMeans: capped by OMP_NUM_THREADS. Default is 0. final_assignment : {'approximate', 'exact'}, optional 'approximate' uses the training assignment method; 'exact' uses exhaustive - assignment against final centroids. Default is 'approximate'. A - FinalAssignmentMode member is still accepted until 0.9. + assignment against final centroids. Default is 'approximate'. max_degree : int, optional - Centroid graph degree; a positive multiple of 32. Default is 32. Named - graph_degree before 0.8.5. + Centroid graph degree; a positive multiple of 32. Default is 32. ef_construction : int, optional Positive centroid-graph construction search breadth. Default is 240. - Named ef_build before 0.8.5. ef_search : int, optional Positive centroid-graph assignment search breadth. Default is 16. graph_build_iterations : int, optional @@ -1513,7 +1118,7 @@ class QGKMeans: is 1. nbits : int, optional Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is - 32. Named quantization_bits, with 0 for raw float32, before 0.8.5. + 32. Notes ----- @@ -1528,79 +1133,6 @@ class QGKMeans: kinds of objective are not directly comparable. """ - @overload - @deprecated( - "QGKMeans(quantization_bits=...) is deprecated since 0.8.5; use nbits=, with 32 instead of 0 for raw vectors" - ) - def __init__( - self, - d: SupportsIndex, - k: SupportsIndex, - *, - quantization_bits: SupportsIndex, - niter: SupportsIndex = 25, - verbose: bool | np.bool_ = False, - spherical: bool | np.bool_ = False, - seed: SupportsIndex = 42, - min_points_per_centroid: SupportsIndex = 39, - max_points_per_centroid: SupportsIndex = 0, - early_stop_threshold: float = 0.0, - num_threads: SupportsIndex = 0, - final_assignment: _FinalAssignment | FinalAssignmentMode = "approximate", - ef_search: SupportsIndex = 16, - graph_build_iterations: SupportsIndex = 1, - graph_degree: SupportsIndex = ..., - ef_build: SupportsIndex = ..., - max_degree: SupportsIndex = 32, - ef_construction: SupportsIndex = 240, - ) -> None: ... - @overload - @deprecated("QGKMeans(graph_degree=...) is deprecated since 0.8.5; use max_degree=") - def __init__( - self, - d: SupportsIndex, - k: SupportsIndex, - *, - graph_degree: SupportsIndex, - niter: SupportsIndex = 25, - verbose: bool | np.bool_ = False, - spherical: bool | np.bool_ = False, - seed: SupportsIndex = 42, - min_points_per_centroid: SupportsIndex = 39, - max_points_per_centroid: SupportsIndex = 0, - early_stop_threshold: float = 0.0, - num_threads: SupportsIndex = 0, - final_assignment: _FinalAssignment | FinalAssignmentMode = "approximate", - ef_search: SupportsIndex = 16, - graph_build_iterations: SupportsIndex = 1, - ef_build: SupportsIndex = ..., - ef_construction: SupportsIndex = 240, - nbits: SupportsIndex = 32, - ) -> None: ... - @overload - @deprecated( - "QGKMeans(ef_build=...) is deprecated since 0.8.5; use ef_construction=" - ) - def __init__( - self, - d: SupportsIndex, - k: SupportsIndex, - *, - ef_build: SupportsIndex, - niter: SupportsIndex = 25, - verbose: bool | np.bool_ = False, - spherical: bool | np.bool_ = False, - seed: SupportsIndex = 42, - min_points_per_centroid: SupportsIndex = 39, - max_points_per_centroid: SupportsIndex = 0, - early_stop_threshold: float = 0.0, - num_threads: SupportsIndex = 0, - final_assignment: _FinalAssignment | FinalAssignmentMode = "approximate", - ef_search: SupportsIndex = 16, - graph_build_iterations: SupportsIndex = 1, - max_degree: SupportsIndex = 32, - nbits: SupportsIndex = 32, - ) -> None: ... def train(self, x: npt.ArrayLike) -> float: """Train centroids and retain the final assignments. @@ -1732,45 +1264,21 @@ class QGKMeansParameters: @num_threads.setter def num_threads(self, value: SupportsIndex) -> None: ... @property - def final_assignment(self) -> FinalAssignmentMode: - """'approximate' uses the training assignment method; 'exact' uses exhaustive assignment against final centroids. Default is 'approximate'. Until 0.9 it reads back as the FinalAssignmentMode member, which is still accepted.""" + def final_assignment(self) -> _FinalAssignment: + """'approximate' uses the training assignment method; 'exact' uses exhaustive assignment against final centroids. Default is 'approximate'.""" @final_assignment.setter - def final_assignment( - self, value: _FinalAssignment | FinalAssignmentMode - ) -> None: ... + def final_assignment(self, value: _FinalAssignment) -> None: ... @property def max_degree(self) -> int: - """Centroid graph degree; a positive multiple of 32. Default is 32. Named graph_degree before 0.8.5.""" + """Centroid graph degree; a positive multiple of 32. Default is 32.""" @max_degree.setter def max_degree(self, value: SupportsIndex) -> None: ... @property - @deprecated( - "QGKMeansParameters.graph_degree is deprecated since 0.8.5; use max_degree" - ) - def graph_degree(self) -> int: - """Deprecated since 0.8.5: use max_degree.""" - @graph_degree.setter - @deprecated( - "QGKMeansParameters.graph_degree is deprecated since 0.8.5; use max_degree" - ) - def graph_degree(self, value: SupportsIndex) -> None: ... - @property def ef_construction(self) -> int: - """Positive centroid-graph construction search breadth. Default is 240. Named ef_build before 0.8.5.""" + """Positive centroid-graph construction search breadth. Default is 240.""" @ef_construction.setter def ef_construction(self, value: SupportsIndex) -> None: ... @property - @deprecated( - "QGKMeansParameters.ef_build is deprecated since 0.8.5; use ef_construction" - ) - def ef_build(self) -> int: - """Deprecated since 0.8.5: use ef_construction.""" - @ef_build.setter - @deprecated( - "QGKMeansParameters.ef_build is deprecated since 0.8.5; use ef_construction" - ) - def ef_build(self, value: SupportsIndex) -> None: ... - @property def ef_search(self) -> int: """Positive centroid-graph assignment search breadth. Default is 16.""" @ef_search.setter @@ -1782,20 +1290,9 @@ class QGKMeansParameters: def graph_build_iterations(self, value: SupportsIndex) -> None: ... @property def nbits(self) -> int: - """Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is 32. Named quantization_bits, with 0 for raw float32, before 0.8.5.""" + """Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is 32.""" @nbits.setter def nbits(self, value: SupportsIndex) -> None: ... - @property - @deprecated( - "QGKMeansParameters.quantization_bits is deprecated since 0.8.5; use nbits" - ) - def quantization_bits(self) -> int: - """Deprecated since 0.8.5: use nbits.""" - @quantization_bits.setter - @deprecated( - "QGKMeansParameters.quantization_bits is deprecated since 0.8.5; use nbits" - ) - def quantization_bits(self, value: SupportsIndex) -> None: ... def __init__(self) -> None: """Create parameters with their documented defaults.""" @@ -1832,8 +1329,7 @@ class RaBitQKMeans: capped by OMP_NUM_THREADS. Default is 0. final_assignment : {'approximate', 'exact'}, optional 'approximate' uses the training assignment method; 'exact' uses exhaustive - assignment against final centroids. Default is 'approximate'. A - FinalAssignmentMode member is still accepted until 0.9. + assignment against final centroids. Default is 'approximate'. Notes ----- @@ -1875,7 +1371,7 @@ class RaBitQKMeans: max_points_per_centroid: SupportsIndex = 0, early_stop_threshold: float = 0.0, num_threads: SupportsIndex = 0, - final_assignment: _FinalAssignment | FinalAssignmentMode = "approximate", + final_assignment: _FinalAssignment = "approximate", ) -> None: """Cluster vectors using flat RaBitQ assignment. @@ -1909,8 +1405,7 @@ class RaBitQKMeans: capped by OMP_NUM_THREADS. Default is 0. final_assignment : {'approximate', 'exact'}, optional 'approximate' uses the training assignment method; 'exact' uses exhaustive - assignment against final centroids. Default is 'approximate'. A - FinalAssignmentMode member is still accepted until 0.9. + assignment against final centroids. Default is 'approximate'. Notes ----- @@ -1923,16 +1418,6 @@ class RaBitQKMeans: sample chosen by seed. obj and iteration_stats then describe the sample, while assignments, distances and final_obj cover all n vectors, so the two kinds of objective are not directly comparable. - - Examples - -------- - >>> import numpy as np - >>> from rabitqlib import RaBitQKMeans - >>> x = np.random.default_rng(42).normal(size=(64, 64)).astype(np.float32) - >>> model = RaBitQKMeans(64, 2, niter=2, num_threads=1) - >>> objective = model.train(x) - >>> model.centroids.shape - (2, 64) """ def train(self, x: npt.ArrayLike) -> float: @@ -2066,11 +1551,9 @@ class RaBitQKMeansParameters: @num_threads.setter def num_threads(self, value: SupportsIndex) -> None: ... @property - def final_assignment(self) -> FinalAssignmentMode: - """'approximate' uses the training assignment method; 'exact' uses exhaustive assignment against final centroids. Default is 'approximate'. Until 0.9 it reads back as the FinalAssignmentMode member, which is still accepted.""" + def final_assignment(self) -> _FinalAssignment: + """'approximate' uses the training assignment method; 'exact' uses exhaustive assignment against final centroids. Default is 'approximate'.""" @final_assignment.setter - def final_assignment( - self, value: _FinalAssignment | FinalAssignmentMode - ) -> None: ... + def final_assignment(self, value: _FinalAssignment) -> None: ... def __init__(self) -> None: """Create parameters with their documented defaults.""" diff --git a/python_bindings/bindings_common.hpp b/python_bindings/bindings_common.hpp index f88da6fc..7f5f36e2 100644 --- a/python_bindings/bindings_common.hpp +++ b/python_bindings/bindings_common.hpp @@ -72,6 +72,20 @@ class IndexAccess { [[nodiscard]] Guard write() { return Guard(*this, true); } }; +// `__reduce_ex__` for every extension class and enum. Pickle protocols 0 and 1 reduce +// through copyreg._reduce_ex, which calls pybind11_object(self); that constructor throws a +// C++ exception through the C API and aborts the interpreter (pybind11 issue 3745). +// Reducing with protocol 2 instead pickles a class that defines py::pickle with any +// protocol and raises TypeError for the others, as protocol 2 already does. +inline py::object reduce_ex_with_protocol_2(const py::object& self, int protocol) { + const auto object_type = + py::reinterpret_borrow(reinterpret_cast(&PyBaseObject_Type)); + return object_type.attr("__reduce_ex__")(self, std::max(protocol, 2)); +} + +inline constexpr const char* kReduceExDoc = + "Reduce for pickle; protocols 0 and 1 use the protocol-2 reduction."; + // Resolve Python callbacks before index guards and own bytes across GIL release. inline std::string path_string(py::handle value) { // The old std::string caster also accepted bytearray directly. @@ -205,14 +219,32 @@ inline MetricType metric_from_string(const std::string& metric) { if (metric == "l2") { return METRIC_L2; } - if (metric == "ip" || metric == "innerproduct") { + if (metric == "ip") { return METRIC_IP; } throw std::invalid_argument("metric must be 'l2' or 'ip'"); } +// Indexes also accept the cosine metric, which rabitqlib.quant rejects. +inline MetricType index_metric_from_string(const std::string& metric) { + if (metric == "cosine") { + return METRIC_COSINE; + } + if (metric == "l2" || metric == "ip") { + return metric_from_string(metric); + } + throw std::invalid_argument("metric must be 'l2', 'ip' or 'cosine'"); +} + inline std::string metric_to_string(MetricType metric) { - return metric == METRIC_IP ? "ip" : "l2"; + switch (metric) { + case METRIC_IP: + return "ip"; + case METRIC_COSINE: + return "cosine"; + default: + return "l2"; + } } template @@ -353,32 +385,19 @@ RowView checked_output_rows( return make_row_view(std::move(array)); } -struct SearchResults { - py::array_t ids; - py::array_t distances; -}; - -// (num_queries, k) outputs. Slots without a neighbor keep kPidMax and +inf. -// Searches pad slots without a result, so k may exceed the number of points. 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"); } } -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{py::array_t(shape), py::array_t(shape)}; - std::fill( - results.ids.mutable_data(), results.ids.mutable_data() + results.ids.size(), kPidMax - ); - std::fill( - results.distances.mutable_data(), - results.distances.mutable_data() + results.distances.size(), - std::numeric_limits::infinity() - ); - return results; +// A graph search breadth given explicitly is at least 1; None selects the default. +inline void check_ef_search(std::optional ef_search) { + if (ef_search == size_t{0}) { + throw std::invalid_argument( + "ef_search must be at least 1; pass None for the default" + ); + } } // Like ensure_1d_array, but refuses input whose dtype is not an integer. forcecast @@ -404,32 +423,24 @@ 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 +// An aligned copy of IDs whose rank and dtype the caller has validated; the index checks +// their range. +inline std::vector copied_ids( + const py::array_t& ids ) { - std::vector result; - result.reserve(static_cast(ids.shape(0))); + std::vector result(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)); + for (size_t i = 0; i < result.size(); ++i) { + result[i] = values[i]; } return result; } // Validate before narrowing, and own the result for APIs that mutate assignments. inline std::vector checked_cluster_ids( - py::handle value, - size_t rows, - size_t clusters, - const char* range_error = "cluster_ids must be in [0, num_clusters)" + py::handle value, size_t rows, size_t clusters ) { const auto checked_copy = [&](const auto& ids) { if (static_cast(ids.shape(0)) != rows) { @@ -449,7 +460,7 @@ inline std::vector checked_cluster_ids( if (id < 0 || static_cast(id) >= clusters || static_cast(id) > std::numeric_limits::max()) { throw std::invalid_argument( - std::string(range_error) + "; expected [0, " + + "cluster_ids must be in [0, num_clusters); expected [0, " + std::to_string(clusters) + "), invalid entry at index " + std::to_string(i) ); diff --git a/python_bindings/hnsw_bindings.cpp b/python_bindings/hnsw_bindings.cpp index 18297530..397303fb 100644 --- a/python_bindings/hnsw_bindings.cpp +++ b/python_bindings/hnsw_bindings.cpp @@ -6,11 +6,10 @@ #include #include // IWYU pragma: keep; registers std::optional casters -#include #include #include #include -#include +#include #include #include #include @@ -19,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; @@ -39,145 +35,31 @@ 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 = metric_from_string(metric); - const auto graph_seed = checked_seed(seed, std::numeric_limits::max()); - // Capacity grows on add; resize 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, static_cast(graph_seed)); - } - - // The 0.7 form, whose max_elements becomes the initial capacity. - static HnswIndex with_point_count( - size_t dim, - size_t max_elements, - size_t M, - size_t ef_construction, - size_t nbits, - const std::string& metric, - const py::object& random_seed - ) { - const auto metric_type = metric_from_string(metric); - const auto graph_seed = - checked_seed(random_seed, std::numeric_limits::max()); - HnswIndex wrapper; - wrapper.index_ = std::make_unique( - max_elements, dim, nbits, M, ef_construction, graph_seed, metric_type - ); - wrapper.num_clusters_ = kDefaultNumClusters; - wrapper.seed_ = graph_seed; - wrapper.cp_ = - default_training_parameters(metric_type, static_cast(graph_seed)); - return wrapper; - } + ) + : 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); } - // Deprecated: the 0.7 build, which takes any number of centroids. An untrained - // index is constructed; a trained one without points takes the centroids and - // adds the data, which links it the same way. - void build( - py::handle data, - py::handle centroids, - py::handle cluster_ids, - size_t num_threads, - bool fast_quantization - ) { - const auto operation = access_.write(); - auto data_array = ensure_2d_array(data, "data"); - auto centroids_array = ensure_2d_array(centroids, "centroids"); - - ensure_dimension( - data_array, index_->dimension(), "data dimension does not match index dim" - ); - if (data_array.shape(0) == 0) { - throw std::invalid_argument( - "number of data rows must be at least 1; got shape " + - array_shape(data_array) - ); - } - ensure_dimension( - centroids_array, - index_->dimension(), - "centroid dimension does not match index dim" - ); - const size_t num_clusters = static_cast(centroids_array.shape(0)); - if (num_clusters == 0) { - throw std::invalid_argument("at least one centroid is required"); - } - const auto rows = static_cast(data_array.shape(0)); - auto cluster_ids_vec = checked_cluster_ids( - cluster_ids, rows, num_clusters, "cluster_ids contains an out-of-range value" - ); - - const auto* data_ptr = data_array.data(); - const auto* centroids_ptr = centroids_array.data(); - const size_t dim = index_->dimension(); - { - py::gil_scoped_release release; - const bool empty = index_->num_stored_points() == 0; - if (empty) { - // Invalid centroids must not grow or retrain the index first. - check_coordinates( - centroids_ptr, num_clusters * dim, dim, "HNSW construction centroids" - ); - grow_capacity(*index_, rows, data_ptr, "HNSW construction data"); - } - if (empty && index_->is_trained()) { - index_->set_centroids(num_clusters, centroids_ptr); - index_->add( - data_ptr, rows, cluster_ids_vec.data(), fast_quantization, num_threads - ); - } else { - index_->construct( - num_clusters, - centroids_ptr, - rows, - data_ptr, - cluster_ids_vec.data(), - num_threads, - fast_quantization - ); - } - } - num_clusters_ = num_clusters; - } - - py::array_t add( + py::array_t add( py::handle data, const py::object& cluster_ids, std::optional num_threads, @@ -185,214 +67,165 @@ 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. - auto ids = py::array_t(static_cast(rows)); + 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; } - void resize(size_t new_max_elements) { + void reserve(int64_t num_points) { + if (num_points < 0) { + throw std::invalid_argument("num_points must be non-negative"); + } + { + // 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_.capacity()) { + return; + } + } + // The GIL is held from the check above to this guard, so no other call + // can change the capacity in between. const auto operation = access_.write(); py::gil_scoped_release release; - index_->resize(new_max_elements); + 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( py::handle queries, size_t k, - std::optional ef, + std::optional ef_search, std::optional num_threads ) { 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); - // None and 0 select max(k, 64), as SymqgIndex does. - const size_t ef_search = ef.value_or(0) == 0 ? std::max(k, 64) : *ef; - - auto output = unfilled_search_results(static_cast(query_array.shape(0)), k); - auto result_ids_view = output.ids.mutable_unchecked<2>(); - auto distances_view = output.distances.mutable_unchecked<2>(); + check_k(k); // before the outputs are allocated + check_ef_search(ef_search); + 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, ef_search, 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) { - result_ids_view(i, 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 py::make_tuple(output.ids, output.distances); + 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; - wrapper.cp_ = default_training_parameters( - wrapper.index_->metric_type(), 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()) + - ", max_elements=" + 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 max_elements() const { + [[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(); @@ -400,54 +233,34 @@ class HnswIndex { } private: - static constexpr size_t kDefaultNumClusters = 16; - - 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 - ); - } - } + explicit HnswIndex(rabitqlib::HnswIndex index) + : index_(std::move(index)), cp_(index_.cp()) {} - 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 loaded indexes. }; } // namespace rabitqlib::python_bindings @@ -474,34 +287,32 @@ M : int, optional 2 * M edges. Default is 16. ef_construction : int, optional Keyword-only. Construction search breadth. Default is 200. -metric : {'l2', 'ip', 'innerproduct'}, optional - Keyword-only. Squared L2 or inner-product distance. Default is 'l2'. - Vectors are not automatically normalized for cosine similarity. +metric : {'l2', 'ip', 'cosine'}, optional + Keyword-only. Squared L2, inner-product or cosine distance. Default is + 'l2'. 'cosine' scales data and queries to unit length. seed : int, optional - Keyword-only. Graph and rotation seed, also the initial cp.seed (its low - 32 bits). Default is 100. + Keyword-only. Graph and rotation seed in [0, 2**32 - 1], also the initial + cp.seed. None (default) draws one at random; the seed property reports it. Notes ----- The first add trains an untrained index on the added vectors. Call train on a sample, or set_centroids, first to choose the training data or the -centroids. Loaded indexes are trained, except empty files saved untrained -by 0.7. Capacity grows automatically -on add; resize can preallocate it. Concurrent reads are supported; an +centroids. Loaded indexes are trained, except one loaded from a file saved +before training. Capacity grows automatically +on add; reserve can preallocate it. Concurrent reads are supported; an overlapping mutation raises RuntimeError. Data, centroids and queries must be finite float32 values within the index coordinate range; other values raise ValueError. With more than one thread, add links points in a nondeterministic order; -pass num_threads=1 for a reproducible graph. -The 0.7 forms HnswIndex(dim, max_elements, ...), random_seed= and build() -still work in 0.8, raise DeprecationWarning, and will be removed in 0.9. +pass num_threads=1 and a seed for a reproducible graph. Examples -------- >>> import numpy as np >>> from rabitqlib import HnswIndex >>> x = np.random.default_rng(42).normal(size=(80, 64)).astype(np.float32) ->>> index = HnswIndex(64, num_clusters=2) +>>> index = HnswIndex(64, num_clusters=2, seed=7) >>> ids = index.add(x, num_threads=1) # trains on x first >>> ids, distances = index.search(x[:2], k=3) >>> ids.shape, distances.shape @@ -520,13 +331,14 @@ cluster_ids : array_like of int, shape (n,), optional num_threads : int, optional Keyword-only. Worker count. None (default) and 0 select the available CPU count, capped by OMP_NUM_THREADS; more than one thread links - nondeterministically, so pass 1 for a reproducible graph. + nondeterministically, so pass 1, and a seed to the constructor, for a + reproducible graph. fast_quantization : bool, optional Keyword-only. Use faster quantizer configuration. Default is False. Returns ------- -ids : ndarray of uint32, shape (n,) +ids : ndarray of int64, shape (n,) Assigned point IDs. Notes @@ -536,14 +348,20 @@ train(data) does; with fewer rows it trains one centroid per row, and num_clusters then reports the row count. An empty first add raises RuntimeError. With num_threads None, training uses cp.num_threads. Passing cluster_ids to an untrained index raises -RuntimeError, as does add on an untrained index loaded from a 0.7 file; -call train first. If the call fails, the index stays untrained and empty. The first +RuntimeError, as does add on an index loaded from an untrained file; +call train or set_centroids first. If the call fails, the index stays untrained +and empty. The first add into an empty index links vectors with their exact coordinates; later adds link through the stored codes, so add most vectors in the first call. Capacity -grows geometrically when needed. Removed IDs are not reused. Passing the options -positionally is deprecated.)doc"; +grows geometrically when needed. Removed IDs are not reused.)doc"; py::class_(m, "HnswIndex", kIndexDoc) + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) .def( py::init< size_t, @@ -560,21 +378,9 @@ positionally is deprecated.)doc"; py::arg("M") = 16, py::arg("ef_construction") = 200, py::arg("metric") = "l2", - py::arg("seed") = 100, + py::arg("seed") = py::none(), kIndexDoc ) - // Private to the 0.8 compatibility layer in rabitqlib/__init__.py. - .def( - py::init(&HnswIndex::with_point_count), - py::arg("dim"), - py::kw_only(), - py::arg("_max_elements"), - py::arg("M"), - py::arg("ef_construction"), - py::arg("nbits"), - py::arg("metric"), - py::arg("random_seed") - ) .def( "train", &HnswIndex::train, @@ -609,7 +415,8 @@ Parameters ---------- centroids : array_like of float, shape (num_clusters, dim) Centroids in the original, unpadded coordinates. Converted to - contiguous float32; a copy may be made. + contiguous float32; a copy may be made. A cosine index scales them + to unit length, as it does data. Notes ----- @@ -617,21 +424,13 @@ The index counts as trained afterwards. Replacing centroids is allowed while the index stores no vectors and raises RuntimeError afterwards. A failed call leaves the index unchanged.)doc" ) - .def( - "_build", - &HnswIndex::build, - py::arg("data"), - py::arg("centroids"), - py::arg("cluster_ids"), - py::arg("num_threads"), - py::arg("fast_quantization") - ) .def( "search", &HnswIndex::search, py::arg("queries"), py::arg("k"), - py::arg("ef") = py::none(), + py::arg("ef_search") = py::none(), + py::kw_only(), py::arg("num_threads") = py::none(), R"doc(Search a batch of query vectors. @@ -643,25 +442,25 @@ queries : array_like of float, shape (n_queries, dim) k : int Number of neighbors requested, at least 1. It may exceed the number of points; slots without a neighbor are padded as described below. -ef : int, optional - Search breadth. None or 0 (default) selects max(k, 64); values above the stored - point count are clamped. +ef_search : int, optional + Search breadth, at least 1. None (default) selects max(k, 64); values + above the stored point count are clamped. num_threads : int, optional - Worker count. None (default) selects 1; 0 selects the available CPU - count, capped by OMP_NUM_THREADS. + Keyword-only. Worker count. None (default) selects 1; 0 selects the + available CPU count, capped by OMP_NUM_THREADS. Returns ------- -ids : ndarray of uint32, shape (n_queries, k) +ids : ndarray of int64, shape (n_queries, k) Point IDs of the selected neighbors. distances : ndarray of float32, shape (n_queries, k) - Lower values are better; squared L2 estimates for l2 and inner-product - distance estimates for ip. These are distances, not similarity scores. + Lower values are better: squared L2 estimates for l2, 1 - dot for ip and + 1 - cos for cosine. These are distances, not similarity scores. Notes ----- -Requires a trained or loaded index. Returns (ids, distances), in that -order. Missing neighbors have ID 4294967295 and distance inf; test +Requires a trained index. Returns (ids, distances), in that +order. Missing neighbors have ID -1 and distance inf; test np.isfinite(distances) to find them. Array shapes and value ranges are checked at runtime, not by static type checkers.)doc" ) @@ -676,15 +475,21 @@ and value ranges are checked at runtime, not by static type checkers.)doc" kAddDoc ) .def( - "resize", - &HnswIndex::resize, - py::arg("max_elements"), - R"doc(Change the storage capacity, for example to preallocate before add. + "reserve", + &HnswIndex::reserve, + py::arg("num_points"), + R"doc(Preallocate room for at least num_points stored points. Parameters ---------- -max_elements : int - New capacity; must be at least num_stored_points.)doc" +num_points : int + Nonnegative number of stored points to make room for, including the + current ones. + +Notes +----- +Capacity only grows: a value at or below capacity changes nothing. add also +grows the capacity when needed, so reserve is an optimization.)doc" ) .def( "remove", @@ -722,7 +527,8 @@ path : str, bytes, bytearray, or os.PathLike Notes ----- A trained index without vectors raises RuntimeError; add vectors first. -The saved state includes the rotation used to build the index.)doc" +The saved state includes the rotation used to build the index and its seed; +releases up to 0.8 cannot read the file.)doc" ) .def_static( "load", @@ -739,7 +545,7 @@ path : str, bytes, bytearray, or os.PathLike Returns ------- index : HnswIndex - A trained index ready for search.)doc" + The loaded index, trained unless the file was saved before training.)doc" ) .def( "__repr__", @@ -755,7 +561,9 @@ index : HnswIndex "dim", &HnswIndex::dim, R"doc(Original vector dimension.)doc" ) .def_property_readonly( - "max_elements", &HnswIndex::max_elements, R"doc(Current storage capacity.)doc" + "capacity", + &HnswIndex::capacity, + R"doc(Current storage capacity, in stored points.)doc" ) .def_property_readonly( "num_points", @@ -788,21 +596,23 @@ index : HnswIndex .def_property_readonly( "is_trained", &HnswIndex::is_trained, - R"doc(Whether centroids are set, by train, set_centroids, the first add, build or load.)doc" + R"doc(Whether centroids are set, by train, set_centroids, the first add or load.)doc" ) .def_property_readonly( "seed", &HnswIndex::seed, - R"doc(Graph and rotation seed, or None for an index loaded from disk.)doc" + R"doc(Graph and rotation seed, or None for an index loaded from a file from a release up to 0.8.)doc" ) .def_property( "cp", &HnswIndex::cp, &HnswIndex::set_cp, py::return_value_policy::reference_internal, - R"doc(Clustering parameters train uses, a RaBitQKMeansParameters. Defaults: niter 10, max_points_per_centroid 256, spherical for inner product, and seed equal to the low 32 bits of the index seed.)doc" + R"doc(Clustering parameters train uses, a RaBitQKMeansParameters. Defaults: niter 10, max_points_per_centroid 256, spherical for inner product and cosine, and seed equal to the index seed.)doc" ) .def_property_readonly( - "metric", &HnswIndex::metric, R"doc(Canonical metric name: 'l2' or 'ip'.)doc" + "metric", + &HnswIndex::metric, + R"doc(Canonical metric name: 'l2', 'ip' or 'cosine'.)doc" ); } diff --git a/python_bindings/ivf_bindings.cpp b/python_bindings/ivf_bindings.cpp index ad2b76bb..d3b1c731 100644 --- a/python_bindings/ivf_bindings.cpp +++ b/python_bindings/ivf_bindings.cpp @@ -9,28 +9,25 @@ #include #include #include -#include +#include #include -#include #include #include +#include #include #include "bindings_common.hpp" #include "rabitqlib/clustering/rabitqkmeans.hpp" -#include "rabitqlib/core/rotator.hpp" -#include "rabitqlib/index/ivf/initializer.hpp" -#include "rabitqlib/index/ivf/ivf.hpp" -#include "rabitqlib/index/training.hpp" +#include "rabitqlib/index/ivf/types.hpp" +#include "rabitqlib/index/ivf_index.hpp" #include "rabitqlib/index/types.hpp" -#include "rabitqlib/utils/input_checks.hpp" namespace py = pybind11; namespace rabitqlib::python_bindings { namespace { -ivf::InitializerType initializer_from_string(const std::string& value) { +ivf::InitializerType routing_from_string(const std::string& value) { if (value == "auto") { return ivf::InitializerType::Auto; } @@ -43,12 +40,10 @@ ivf::InitializerType initializer_from_string(const std::string& value) { if (value == "hnsw") { return ivf::InitializerType::HNSW; } - throw std::invalid_argument( - "initializer must be 'auto', 'flat', 'flat_rabitq', or 'hnsw'" - ); + throw std::invalid_argument("routing must be 'auto', 'flat', 'flat_rabitq', or 'hnsw'"); } -std::string initializer_to_string(ivf::InitializerType type) { +std::string routing_to_string(ivf::InitializerType type) { switch (type) { case ivf::InitializerType::Auto: return "auto"; @@ -70,140 +65,33 @@ class IvfIndex { size_t num_clusters, size_t nbits, const std::string& metric, - const std::string& initializer, + const std::string& routing, const py::object& seed - ) { - const auto metric_type = metric_from_string(metric); - const auto initializer_type = initializer_from_string(initializer); - const auto rotation_seed = - seed.is_none() ? std::random_device{}() - : static_cast( - checked_seed(seed, std::numeric_limits::max()) - ); - index_ = std::make_unique( - dim, - num_clusters, - nbits, - metric_type, - rotation_seed, - RotatorType::FhtKacRotator, - initializer_type - ); - seed_ = rotation_seed; - cp_ = default_training_parameters(metric_type, rotation_seed); - } - - // The 0.7 point-count form, which build fills with construct. - static IvfIndex with_point_count( - size_t dim, - size_t max_elements, - size_t num_clusters, - size_t nbits, - const std::string& metric, - const std::string& initializer - ) { - const auto metric_type = metric_from_string(metric); - IvfIndex wrapper; - wrapper.index_ = std::make_unique( - max_elements, - dim, - num_clusters, - nbits, - metric_type, - RotatorType::FhtKacRotator, - initializer_from_string(initializer) - ); - wrapper.cp_ = untrainable_parameters(metric_type); - wrapper.builds_by_construct_ = true; - return wrapper; - } + ) + : index_(dim, num_clusters, index_options(nbits, metric, routing, seed)) + , cp_(index_.cp()) {} void train(py::handle x, std::optional num_threads) { const auto operation = access_.write(); auto x_array = ensure_2d_array(x, "x"); - check_trainable(); - ensure_dimension( - x_array, index_->dimension(), "x dimension does not match index dim" - ); - const auto rows = training_rows(x_array, index_->num_clusters()); - const auto cp = training_parameters(cp_, num_threads); + ensure_dimension(x_array, index_.dim(), "x dimension does not match index dim"); + const auto rows = training_rows(x_array, index_.num_clusters()); const auto* x_ptr = x_array.data(); + index_.cp() = cp_; py::gil_scoped_release release; - index_->train(rows, x_ptr, cp); + index_.train(x_ptr, rows, num_threads); } void set_centroids(py::handle centroids, std::optional num_threads) { const auto operation = access_.write(); auto centroids_array = ensure_2d_array(centroids, "centroids"); - check_trainable(); - check_centroid_shape(centroids_array, index_->num_clusters(), index_->dimension()); - const auto* centroids_ptr = centroids_array.data(); - py::gil_scoped_release release; - index_->set_centroids(centroids_ptr, num_threads.value_or(0)); - } - - // Deprecated: the 0.7 build. A point-count index is constructed; any other - // index sets the centroids and adds the data. - void build( - py::handle data, - py::handle centroids, - py::handle cluster_ids, - size_t num_threads, - bool fast_quantization - ) { - const auto operation = access_.write(); - auto data_array = ensure_2d_array(data, "data"); - auto centroids_array = ensure_2d_array(centroids, "centroids"); - - ensure_dimension( - data_array, index_->dimension(), "data dimension does not match index dim" - ); - if (builds_by_construct_ && - static_cast(data_array.shape(0)) != index_->max_elements()) { - throw std::invalid_argument( - "number of data rows must match index max_elements; expected " + - std::to_string(index_->max_elements()) + ", got shape " + - array_shape(data_array) - ); - } - ensure_dimension( - centroids_array, - index_->dimension(), - "centroid dimension does not match index dim" - ); - if (static_cast(centroids_array.shape(0)) != index_->num_clusters()) { - throw std::invalid_argument( - "number of centroid rows must match index num_clusters; expected " + - std::to_string(index_->num_clusters()) + ", got shape " + - array_shape(centroids_array) - ); - } - const auto rows = static_cast(data_array.shape(0)); - auto cluster_ids_vec = - checked_cluster_ids(cluster_ids, rows, index_->num_clusters()); - if (!builds_by_construct_) { - check_trainable(); - } - - const auto* data_ptr = data_array.data(); + check_centroid_shape(centroids_array, index_.num_clusters(), index_.dim()); const auto* centroids_ptr = centroids_array.data(); - const auto* cluster_ids_ptr = cluster_ids_vec.data(); py::gil_scoped_release release; - if (builds_by_construct_) { - index_->construct( - data_ptr, centroids_ptr, cluster_ids_ptr, fast_quantization, num_threads - ); - } else { - // Check the data before replacing the centroids, so that invalid input - // leaves the index unchanged; add repeats the check. - const size_t dim = index_->dimension(); - check_coordinates(data_ptr, rows * dim, dim, "IVF add data"); - index_->set_centroids(centroids_ptr, num_threads); - index_->add(data_ptr, rows, cluster_ids_ptr, fast_quantization, num_threads); - } + index_.set_centroids(centroids_ptr, num_threads.value_or(0)); } - py::array_t add( + py::array_t add( py::handle data, const py::object& cluster_ids, std::optional num_threads, @@ -211,94 +99,48 @@ class IvfIndex { ) { const auto operation = access_.write(); auto data_array = ensure_2d_array(data, "data"); - // The first add on an untrained 0.8-form index trains it on the same data. - const bool trains = !index_->is_trained() && !builds_by_construct_ && - cluster_ids.is_none() && data_array.shape(0) > 0; - if (!trains) { - check_trained("add"); - } ensure_dimension( - data_array, index_->dimension(), "data dimension does not match index dim" + data_array, index_.dim(), "data dimension does not match index dim" ); const auto rows = static_cast(data_array.shape(0)); - if (trains && rows < index_->num_clusters()) { - throw std::invalid_argument( - "the first add trains the index and needs at least num_clusters rows; " - "expected at least " + - std::to_string(index_->num_clusters()) + ", got shape " + - array_shape(data_array) - ); - } - std::vector assigned; + AddOptions options; if (!cluster_ids.is_none()) { - assigned = checked_cluster_ids(cluster_ids, rows, index_->num_clusters()); - } - - const size_t first = index_->num_stored_points(); - // Allocate the returned IDs before committing any changes to the index. - auto ids = py::array_t(static_cast(rows)); - auto* ids_data = ids.mutable_data(); - for (size_t i = 0; i < rows; ++i) { - ids_data[i] = static_cast(first + i); + assigned = checked_cluster_ids(cluster_ids, rows, index_.num_clusters()); + options.cluster_ids = assigned.data(); } - + 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 rotation, then swap it in, - // so that a failure leaves this index untrained and empty. - const auto cp = training_parameters(cp_, num_threads); - auto staged = std::make_unique( - index_->dimension(), - index_->num_clusters(), - index_->nbits(), - index_->metric_type(), - *seed_, - RotatorType::FhtKacRotator, - index_->initializer_type() - ); - { - py::gil_scoped_release release; - staged->train(rows, data_ptr, cp); - staged->add(data_ptr, rows, nullptr, fast_quantization, threads); - } - index_.swap(staged); - return ids; - } + index_.cp() = cp_; // the first add trains with it + Id first = 0; { py::gil_scoped_release release; - index_->add( - data_ptr, - rows, - assigned.empty() ? nullptr : assigned.data(), - fast_quantization, - threads - ); + first = index_.add(data_ptr, rows, options); } + std::iota(ids.mutable_data(), ids.mutable_data() + rows, first); return ids; } - void reserve(int64_t cluster_id, int64_t num_points) { + void reserve_cluster(int64_t cluster_id, int64_t num_points) { const auto operation = access_.write(); - check_trained("reserve"); - if (cluster_id < 0 || static_cast(cluster_id) >= index_->num_clusters()) { - throw std::invalid_argument("cluster_id must be in [0, num_clusters)"); - } if (num_points < 0) { throw std::invalid_argument("num_points must be non-negative"); } py::gil_scoped_release release; - index_->reserve(static_cast(cluster_id), static_cast(num_points)); + // A negative cluster_id converts to a value the index rejects as out of range. + index_.reserve_cluster( + static_cast(cluster_id), static_cast(num_points) + ); } size_t remove(py::handle ids) { const auto operation = access_.write(); - auto ids_array = ensure_1d_integer_array(ids, "ids"); - check_trained("remove"); - auto to_remove = checked_removal_ids(ids_array, index_->num_stored_points()); + const auto to_remove = copied_ids(ensure_1d_integer_array(ids, "ids")); py::gil_scoped_release release; - return index_->remove(to_remove.data(), to_remove.size()); + return index_.remove(to_remove.data(), to_remove.size()); } py::tuple search( @@ -310,118 +152,102 @@ class IvfIndex { ) { const auto operation = access_.read(); auto query_array = ensure_2d_array(queries, "queries"); - check_trained("search"); ensure_dimension( - query_array, index_->dimension(), "query dimension does not match index dim" + query_array, index_.dim(), "query dimension does not match index dim" ); - check_k(k); - // None and 0 probe num_clusters / 16 clusters, rounded, and at least one. - const size_t num_probes = - nprobe.value_or(0) == 0 ? std::max(1, (index_->num_clusters() + 8) / 16) - : *nprobe; - - const size_t num_queries = static_cast(query_array.shape(0)); - auto output = unfilled_search_results(num_queries, k); - auto* ids_data = output.ids.mutable_data(); - auto* distances_data = output.distances.mutable_data(); - + check_k(k); // before the outputs are allocated + if (nprobe == size_t{0}) { + throw std::invalid_argument( + "nprobe must be at least 1; pass None for the default" + ); + } + IvfSearchOptions options; + options.nprobe = nprobe; + options.num_threads = num_threads.value_or(1); + options.high_accuracy = high_accuracy; + + const auto num_queries = static_cast(query_array.shape(0)); + const auto shape = std::vector{ + static_cast(num_queries), static_cast(k)}; + auto ids = py::array_t(shape); + auto distances = py::array_t(shape); const auto* queries_data = query_array.data(); + auto* ids_data = ids.mutable_data(); + auto* distances_data = distances.mutable_data(); { py::gil_scoped_release release; - index_->search_batch( - queries_data, - num_queries, - k, - num_probes, - ids_data, - distances_data, - high_accuracy, - num_threads.value_or(1) - ); + index_.search(queries_data, num_queries, k, ids_data, distances_data, options); } - - return py::make_tuple(output.ids, output.distances); + return py::make_tuple(ids, distances); } void save(py::handle path) const { const auto filename = path_string(path); const auto operation = access_.read(); - check_trained("save"); - if (index_->num_stored_points() == 0) { - throw std::runtime_error("IvfIndex has no points to save; add points first"); - } py::gil_scoped_release release; - index_->save(filename.c_str()); + index_.save(filename.c_str()); } static IvfIndex load(py::handle path) { const auto filename = path_string(path); - IvfIndex wrapper; - wrapper.index_ = std::make_unique(); - { + auto index = [&filename] { py::gil_scoped_release release; - wrapper.index_->load(filename.c_str()); - } - wrapper.cp_ = untrainable_parameters(wrapper.index_->metric_type()); - wrapper.builds_by_construct_ = true; - return wrapper; + return rabitqlib::IvfIndex::load(filename.c_str()); + }(); + return IvfIndex(std::move(index)); } [[nodiscard]] std::string repr() const { const auto operation = access_.read(); - return "IvfIndex(dim=" + std::to_string(index_->dimension()) + ", metric='" + - metric_to_string(index_->metric_type()) + - "', nbits=" + std::to_string(index_->nbits()) + - ", num_points=" + std::to_string(index_->num_points()) + - ", num_stored_points=" + std::to_string(index_->num_stored_points()) + - ", max_elements=" + std::to_string(index_->max_elements()) + - ", num_clusters=" + std::to_string(index_->num_clusters()) + - ", initializer='" + initializer_to_string(index_->initializer_type()) + - "', is_trained=" + (index_->is_trained() ? "True" : "False") + ")"; + return "IvfIndex(dim=" + std::to_string(index_.dim()) + ", metric='" + + metric_to_string(index_.metric()) + + "', nbits=" + std::to_string(index_.nbits()) + + ", num_points=" + std::to_string(index_.num_points()) + + ", num_stored_points=" + std::to_string(index_.num_stored_points()) + + ", num_clusters=" + std::to_string(index_.num_clusters()) + ", routing='" + + routing_to_string(index_.routing()) + + "', is_trained=" + (index_.is_trained() ? "True" : "False") + ")"; } [[nodiscard]] size_t dim() const { const auto operation = access_.read(); - return index_->dimension(); - } - [[nodiscard]] size_t max_elements() const { - const auto operation = access_.read(); - return index_->max_elements(); + return index_.dim(); } [[nodiscard]] size_t num_points() const { const auto operation = access_.read(); - return index_->num_points(); + return index_.num_points(); } [[nodiscard]] size_t num_stored_points() const { const auto operation = access_.read(); - return index_->num_stored_points(); + return index_.num_stored_points(); } [[nodiscard]] size_t num_clusters() const { const auto operation = access_.read(); - return index_->num_clusters(); + return index_.num_clusters(); } [[nodiscard]] size_t nbits() const { const auto operation = access_.read(); - return index_->nbits(); + return index_.nbits(); } [[nodiscard]] bool is_trained() const { const auto operation = access_.read(); - return index_->is_trained(); + return index_.is_trained(); } [[nodiscard]] std::optional seed() const { const auto operation = access_.read(); - return seed_; + return index_.seed(); } - [[nodiscard]] std::string initializer() const { + [[nodiscard]] std::string routing() const { const auto operation = access_.read(); - return initializer_to_string(index_->initializer_type()); + return routing_to_string(index_.routing()); } [[nodiscard]] std::string metric() const { const auto operation = access_.read(); - return metric_to_string(index_->metric_type()); + return metric_to_string(index_.metric()); } - // Parameters are wrapper state that train copies with the GIL held. + // Python reads and writes the fields of cp_ with the GIL held but without a guard, so + // the native index trains with a copy that train and add make with the GIL held. rabitqkmeans::RaBitQKMeansParameters& cp() { return cp_; } void set_cp(const rabitqkmeans::RaBitQKMeansParameters& cp) { const auto operation = access_.write(); @@ -429,41 +255,30 @@ class IvfIndex { } private: - IvfIndex() = default; - - // Parameters of an index that cannot be trained; the k-means default seed. - static rabitqkmeans::RaBitQKMeansParameters untrainable_parameters(MetricType metric) { - return default_training_parameters( - metric, rabitqkmeans::RaBitQKMeansParameters{}.seed - ); - } - - void check_trained(const char* operation) const { - if (!index_->is_trained()) { - throw std::runtime_error( - std::string("IvfIndex must be trained or loaded before ") + operation - ); - } - } + explicit IvfIndex(rabitqlib::IvfIndex index) + : index_(std::move(index)), cp_(index_.cp()) {} - void check_trainable() const { - if (index_->num_stored_points() != 0) { - throw std::runtime_error("IvfIndex cannot be trained once it stores points"); - } - if (builds_by_construct_) { - throw std::runtime_error( - "IvfIndex created with max_elements is filled by build; create " - "IvfIndex(dim, num_clusters, nbits=...) to train or set centroids" + static IvfOptions index_options( + size_t nbits, + const std::string& metric, + const std::string& routing, + const py::object& seed + ) { + IvfOptions options; + options.metric = index_metric_from_string(metric); + options.routing = routing_from_string(routing); + if (!seed.is_none()) { + options.seed = static_cast( + checked_seed(seed, std::numeric_limits::max()) ); } + options.nbits = nbits; + return options; } mutable IndexAccess access_; - std::unique_ptr index_; + rabitqlib::IvfIndex index_; rabitqkmeans::RaBitQKMeansParameters cp_; - std::optional seed_; // Unknown for point-count and loaded indexes. - // Point-count and loaded indexes build by construct, never by training. - bool builds_by_construct_ = false; }; } // namespace rabitqlib::python_bindings @@ -484,10 +299,10 @@ num_clusters : int nbits : int, optional Keyword-only. Total quantization bits, 1 through 9, or 32 for owned float32 vectors with one-bit filtering and raw reranking. Default is 7. -metric : {'l2', 'ip', 'innerproduct'}, optional - Squared L2 or inner-product distance. Default is 'l2'. Vectors are not - automatically normalized for cosine similarity. -initializer : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional +metric : {'l2', 'ip', 'cosine'}, optional + Squared L2, inner-product or cosine distance. Default is 'l2'. 'cosine' + scales data and queries to unit length. +routing : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional Centroid routing strategy. Default is 'auto'. seed : int, optional Rotation seed in [0, 2**32 - 1], also the initial cp.seed. None @@ -501,9 +316,6 @@ centroids. Loaded indexes are already trained. Concurrent reads are supported; an overlapping mutation raises RuntimeError. Data, centroids and queries must be finite float32 values within the index coordinate range; other values raise ValueError. -The 0.7 form IvfIndex(dim, max_elements, num_clusters, nbits, ...) and -build() still work in 0.8, raise DeprecationWarning, and will be removed in -0.9. Examples -------- @@ -525,7 +337,7 @@ data : array_like of float, shape (n, dim) float32; a copy may be made. cluster_ids : array_like of int, shape (n,), optional Keyword-only. Existing centroid IDs. None routes each vector using the - index's configured centroid initializer; routing may be approximate. + index's configured routing strategy, which may be approximate. Centroids do not move. num_threads : int, optional Keyword-only. Worker count. None (default) and 0 select the available @@ -535,7 +347,7 @@ fast_quantization : bool, optional Returns ------- -ids : ndarray of uint32, shape (n,) +ids : ndarray of int64, shape (n,) Assigned point IDs. Notes @@ -544,13 +356,17 @@ On an untrained index, add first trains num_clusters centroids on data, as train(data) does, so data needs at least num_clusters rows, and an empty first add raises RuntimeError; with num_threads None, training uses cp.num_threads. Passing cluster_ids to an -untrained index raises RuntimeError, as does add on an index created with -max_elements, which build fills. If the call fails, the index stays +untrained index raises RuntimeError. If the call fails, the index stays untrained and empty. Batch additions to reduce repeated cluster copying; -reserve can preallocate room. Passing the options positionally is -deprecated.)doc"; +reserve_cluster can preallocate room.)doc"; py::class_(m, "IvfIndex", kIndexDoc) + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) .def( py::init< size_t, @@ -564,30 +380,10 @@ deprecated.)doc"; py::kw_only(), py::arg("nbits") = 7, py::arg("metric") = "l2", - py::arg("initializer") = "auto", + py::arg("routing") = "auto", py::arg("seed") = py::none(), kIndexDoc ) - // Private to the 0.8 compatibility layer in rabitqlib/__init__.py. - .def( - py::init([](size_t dim, - size_t num_clusters, - size_t nbits, - const std::string& metric, - const std::string& initializer, - size_t max_elements) { - return IvfIndex::with_point_count( - dim, max_elements, num_clusters, nbits, metric, initializer - ); - }), - py::arg("dim"), - py::arg("num_clusters"), - py::kw_only(), - py::arg("nbits"), - py::arg("metric"), - py::arg("initializer"), - py::arg("_max_elements") - ) .def( "train", &IvfIndex::train, @@ -625,7 +421,8 @@ Parameters ---------- centroids : array_like of float, shape (num_clusters, dim) Centroids in the original, unpadded coordinates. Converted to - contiguous float32; a copy may be made. + contiguous float32; a copy may be made. A cosine index scales them + to unit length, as it does data. num_threads : int, optional Keyword-only. Worker count for rotating the centroids and building the centroid routing. None (default) and 0 select the available CPU count, @@ -638,15 +435,6 @@ The index counts as trained afterwards. Replacing centroids is allowed while the index stores no vectors and raises RuntimeError afterwards. A failed call leaves the index unchanged.)doc" ) - .def( - "_build", - &IvfIndex::build, - py::arg("data"), - py::arg("centroids"), - py::arg("cluster_ids"), - py::arg("num_threads"), - py::arg("fast_quantization") - ) .def( "add", &IvfIndex::add, @@ -658,8 +446,8 @@ failed call leaves the index unchanged.)doc" kAddDoc ) .def( - "reserve", - &IvfIndex::reserve, + "reserve_cluster", + &IvfIndex::reserve_cluster, py::arg("cluster_id"), py::arg("num_points"), R"doc(Preallocate storage for a cluster. @@ -669,7 +457,8 @@ Parameters cluster_id : int Cluster ID in [0, num_clusters). num_points : int - Nonnegative capacity to reserve for this cluster. + Nonnegative capacity to reserve for this cluster: the total number of + points it can hold, including its current ones. Notes ----- @@ -702,6 +491,7 @@ Removal does not reclaim storage and cannot be undone.)doc" py::arg("queries"), py::arg("k"), py::arg("nprobe") = py::none(), + py::kw_only(), py::arg("high_accuracy") = py::none(), py::arg("num_threads") = py::none(), R"doc(Search a batch of query vectors. @@ -715,27 +505,28 @@ k : int Number of neighbors requested, at least 1. It may exceed the number of points; slots without a neighbor are padded as described below. nprobe : int, optional - Number of clusters to probe, capped at num_clusters. None (default) and - 0 select num_clusters / 16, rounded to the nearest integer and at least 1. + Number of clusters to probe, at least 1 and capped at num_clusters. None + (default) selects num_clusters / 16, rounded to the nearest integer and + at least 1. high_accuracy : bool, optional - Enable HACC. None (default) selects it for 4-9 bits and standard - FastScan otherwise. Raw storage uses standard FastScan. + Keyword-only. Enable HACC. None (default) selects it for 4-9 bits and + standard FastScan otherwise. Raw storage uses standard FastScan. num_threads : int, optional - Worker count. None (default) selects 1; 0 selects the available CPU - count, capped by OMP_NUM_THREADS. + Keyword-only. Worker count. None (default) selects 1; 0 selects the + available CPU count, capped by OMP_NUM_THREADS. Returns ------- -ids : ndarray of uint32, shape (n_queries, k) +ids : ndarray of int64, shape (n_queries, k) Point IDs of the selected neighbors. distances : ndarray of float32, shape (n_queries, k) - Lower values are better; squared L2 estimates for l2 and inner-product - distance estimates for ip. These are distances, not similarity scores. + Lower values are better: squared L2 estimates for l2, 1 - dot for ip and + 1 - cos for cosine. These are distances, not similarity scores. Notes ----- Requires a trained or loaded index. Returns (ids, distances), in that -order. Missing neighbors have ID 4294967295 and distance inf; test +order. Missing neighbors have ID -1 and distance inf; test np.isfinite(distances) to find them. Array shapes and value ranges are checked at runtime, not by static type checkers.)doc" ) @@ -754,7 +545,7 @@ path : str, bytes, bytearray, or os.PathLike Notes ----- A trained index without vectors raises RuntimeError; add vectors first. -IVF with HNSW centroid routing also writes its required sidecar file.)doc" +The one file includes HNSW centroid routing; releases up to 0.8 cannot read it.)doc" ) .def_static( "load", @@ -771,7 +562,12 @@ path : str, bytes, bytearray, or os.PathLike Returns ------- index : IvfIndex - A trained index ready for search.)doc" + A trained index ready for search. + +Notes +----- +Files from releases up to 0.8 with HNSW centroid routing also need the +accompanying ``.hnsw`` file.)doc" ) .def( "__repr__", @@ -784,11 +580,6 @@ index : IvfIndex "Return the number of live, searchable points." ) .def_property_readonly("dim", &IvfIndex::dim, R"doc(Original vector dimension.)doc") - .def_property_readonly( - "max_elements", - &IvfIndex::max_elements, - R"doc(Logical capacity: stored points, or the build row count of a 0.7-form index before build.)doc" - ) .def_property_readonly( "num_points", &IvfIndex::num_points, @@ -810,26 +601,28 @@ index : IvfIndex .def_property_readonly( "is_trained", &IvfIndex::is_trained, - R"doc(Whether centroids are set, by train, set_centroids, the first add, build or load.)doc" + R"doc(Whether centroids are set, by train, set_centroids, the first add or load.)doc" ) .def_property_readonly( "seed", &IvfIndex::seed, - R"doc(Rotation seed, or None for an index loaded from disk or created in the 0.7 form.)doc" + R"doc(Rotation seed, or None for an index loaded from a file from a release up to 0.8.)doc" ) .def_property( "cp", &IvfIndex::cp, &IvfIndex::set_cp, py::return_value_policy::reference_internal, - R"doc(Clustering parameters train uses, a RaBitQKMeansParameters. Defaults: niter 10, max_points_per_centroid 256, spherical for inner product, and seed equal to the index seed.)doc" + R"doc(Clustering parameters train uses, a RaBitQKMeansParameters. Defaults: niter 10, max_points_per_centroid 256, spherical for inner product and cosine, and seed equal to the index seed.)doc" ) .def_property_readonly( - "metric", &IvfIndex::metric, R"doc(Canonical metric name: 'l2' or 'ip'.)doc" + "metric", + &IvfIndex::metric, + R"doc(Canonical metric name: 'l2', 'ip' or 'cosine'.)doc" ) .def_property_readonly( - "initializer", - &IvfIndex::initializer, - R"doc(Resolved centroid routing strategy.)doc" + "routing", + &IvfIndex::routing, + R"doc(Resolved centroid routing strategy, never 'auto'.)doc" ); } diff --git a/python_bindings/kmeans_bindings.cpp b/python_bindings/kmeans_bindings.cpp index 16574b7d..7e7960b6 100644 --- a/python_bindings/kmeans_bindings.cpp +++ b/python_bindings/kmeans_bindings.cpp @@ -73,7 +73,14 @@ py::tuple assign(const Clustering& clustering, py::handle x) { template void bind_training_parameters(py::class_& binding) { - binding.def(py::init<>(), "Create parameters with their documented defaults.") + binding + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) + .def(py::init<>(), "Create parameters with their documented defaults.") .def_readwrite( "niter", &Parameters::niter, @@ -110,16 +117,40 @@ void bind_training_parameters(py::class_& binding) { &Parameters::num_threads, R"doc(Worker count; 0 selects the available CPU count, capped by OMP_NUM_THREADS. Default is 0.)doc" ) - .def_readwrite( + .def_property( "final_assignment", - &Parameters::final_assignment, - R"doc(Approximate uses the training assignment method; Exact uses exhaustive assignment against final centroids. Default is FinalAssignmentMode.Approximate.)doc" + [](const Parameters& parameters) { + return std::string( + parameters.final_assignment == clustering::FinalAssignmentMode::Exact + ? "exact" + : "approximate" + ); + }, + [](Parameters& parameters, const std::string& value) { + if (value == "approximate") { + parameters.final_assignment = + clustering::FinalAssignmentMode::Approximate; + } else if (value == "exact") { + parameters.final_assignment = clustering::FinalAssignmentMode::Exact; + } else { + throw std::invalid_argument( + "final_assignment must be 'approximate' or 'exact'" + ); + } + }, + R"doc('approximate' uses the training assignment method; 'exact' uses exhaustive assignment against final centroids. Default is 'approximate'.)doc" ); } template void bind_clustering(py::module_& m, const char* native_name, const char* public_name) { py::class_(m, native_name) + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) .def(py::init()) .def("train", &train, py::arg("x")) .def("assign", &assign, py::arg("x")) @@ -165,23 +196,12 @@ void bind_clustering(py::module_& m, const char* native_name, const char* public void register_kmeans(py::module_& m) { using namespace rabitqlib::python_bindings; - using rabitqlib::qgkmeans::FinalAssignmentMode; + using rabitqlib::clustering::KMeansIterationStats; using rabitqlib::qgkmeans::QGKMeans; - using rabitqlib::qgkmeans::QGKMeansIterationStats; using rabitqlib::qgkmeans::QGKMeansParameters; using rabitqlib::rabitqkmeans::RaBitQKMeans; using rabitqlib::rabitqkmeans::RaBitQKMeansParameters; - py::enum_( - m, "FinalAssignmentMode", R"doc(Final centroid assignment policy. - -Approximate uses the selected clustering algorithm. SymphonyQG is a -compatibility alias for Approximate. Exact performs exhaustive assignment.)doc" - ) - .value("Approximate", FinalAssignmentMode::Approximate) - .value("SymphonyQG", FinalAssignmentMode::SymphonyQG) - .value("Exact", FinalAssignmentMode::Exact); - py::class_ qg_parameters( m, "QGKMeansParameters", R"doc(Mutable training settings for QGKMeans. @@ -193,13 +213,13 @@ on QGKMeans.)doc" bind_training_parameters(qg_parameters); qg_parameters .def_readwrite( - "graph_degree", - &QGKMeansParameters::graph_degree, + "max_degree", + &QGKMeansParameters::max_degree, R"doc(Centroid graph degree; a positive multiple of 32. Default is 32.)doc" ) .def_readwrite( - "ef_build", - &QGKMeansParameters::ef_build, + "ef_construction", + &QGKMeansParameters::ef_construction, R"doc(Positive centroid-graph construction search breadth. Default is 240.)doc" ) .def_readwrite( @@ -213,9 +233,9 @@ on QGKMeans.)doc" R"doc(Positive number of graph-building passes after initialization. Default is 1.)doc" ) .def_readwrite( - "quantization_bits", - &QGKMeansParameters::quantization_bits, - R"doc(Centroid storage: 0 for raw float32, or 4 or 8 for RaBitQ. Default is 0.)doc" + "nbits", + &QGKMeansParameters::nbits, + R"doc(Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is 32.)doc" ); py::class_ flat_parameters( @@ -228,32 +248,37 @@ on RaBitQKMeans.)doc" ); bind_training_parameters(flat_parameters); - py::class_( + py::class_( m, - "QGKMeansIterationStats", + "KMeansIterationStats", R"doc(Read-only statistics for one completed clustering iteration.)doc" ) + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) .def_readonly( "iteration", - &QGKMeansIterationStats::iteration, + &KMeansIterationStats::iteration, R"doc(Iteration number, starting at 1.)doc" ) .def_readonly( "obj", - &QGKMeansIterationStats::obj, + &KMeansIterationStats::obj, R"doc(Objective measured before the centroid update.)doc" ) .def_readonly( "shift", - &QGKMeansIterationStats::shift, + &KMeansIterationStats::shift, R"doc(Total squared centroid displacement during the update.)doc" ) .def_readonly( "nsplit", - &QGKMeansIterationStats::nsplit, + &KMeansIterationStats::nsplit, R"doc(Number of empty centroids repaired by splitting.)doc" ); - m.attr("RaBitQKMeansIterationStats") = m.attr("QGKMeansIterationStats"); bind_clustering(m, "_QGKMeans", "QGKMeans"); bind_clustering( diff --git a/python_bindings/quant.py b/python_bindings/quant.py index c31cac2b..f11ff978 100644 --- a/python_bindings/quant.py +++ b/python_bindings/quant.py @@ -50,8 +50,9 @@ FASTSCAN_BLOCKS_VERSION = 1 """Version of the pack_fastscan_blocks layout.""" -# Classes report this module, so pickle and help() find them here. -for _public in (FormatError, Query, Rotator): +# Classes report this module, so pickle and help() find them here. FormatError is +# rabitqlib.FormatError, shared with index loading. +for _public in (Query, Rotator): _public.__module__ = __name__ del _public diff --git a/python_bindings/quant.pyi b/python_bindings/quant.pyi index 9cdbf2f6..44e88e8e 100644 --- a/python_bindings/quant.pyi +++ b/python_bindings/quant.pyi @@ -8,6 +8,7 @@ from typing import Any, Literal, overload import numpy as np import numpy.typing as npt +from rabitqlib import FormatError as FormatError __all__ = [ "ESTIMATE_DTYPE", @@ -37,9 +38,6 @@ PACKED_CODES_VERSION: int FACTORS_VERSION: int FASTSCAN_BLOCKS_VERSION: int -class FormatError(ValueError): - """Corrupt or incompatible serialized bytes. A subclass of ValueError.""" - class Rotator: """A seeded rotation from the original dimension to the padded working space.""" @@ -83,7 +81,7 @@ class Rotator: def __deepcopy__(self, memo: Any) -> Rotator: """Return self; rotators are immutable.""" -_Metric = Literal["l2", "ip", "innerproduct"] +_Metric = Literal["l2", "ip"] class Query: """A rotated, padded query for scoring codes in the working space.""" diff --git a/python_bindings/quant_bindings.cpp b/python_bindings/quant_bindings.cpp index a713042d..8f91198d 100644 --- a/python_bindings/quant_bindings.cpp +++ b/python_bindings/quant_bindings.cpp @@ -50,11 +50,14 @@ namespace py = pybind11; namespace rabitqlib::python_bindings { namespace { -// Raised for corrupt or incompatible serialized bytes; a ValueError in Python. +// Raised for corrupt or incompatible serialized bytes; rabitqlib.FormatError in Python. struct FormatError : std::invalid_argument { using std::invalid_argument::invalid_argument; }; +// rabitqlib.FormatError, owned by the parent module. +PyObject* quant_format_error_type = nullptr; + // The blob format and both rotation methods share the FHT/Kac limit. constexpr size_t kMaxRotatorDim = rotator_impl::FhtKacRotator::kMaxDim; constexpr size_t kMaxTotalBits = 9; @@ -1823,11 +1826,20 @@ void register_quant(py::module_& m) { "_quant", "Native backend of rabitqlib.quant. Import rabitqlib.quant instead of this module." ); - py::register_exception( - quant, "FormatError", py::module_::import("builtins").attr("ValueError") - ); - quant.attr("FormatError").attr("__doc__") = - "Corrupt or incompatible serialized bytes. A subclass of ValueError."; + // Rejected bytes raise rabitqlib.FormatError, which the parent module created. + quant.attr("FormatError") = m.attr("FormatError"); + quant_format_error_type = m.attr("FormatError").ptr(); + // pybind11 translators take std::exception_ptr by value. + // NOLINTNEXTLINE(performance-unnecessary-value-param) + py::register_exception_translator([](std::exception_ptr exception) { + try { + if (exception) { + std::rethrow_exception(exception); + } + } catch (const FormatError& error) { + PyErr_SetString(quant_format_error_type, error.what()); + } + }); quant.attr("FACTORS_DTYPE") = factors_dtype(); quant.attr("ESTIMATE_DTYPE") = estimate_dtype(); @@ -2046,6 +2058,12 @@ Examples (2, 128))doc"; py::class_(quant, "Rotator", kRotatorDoc) + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) .def( py::init(), py::arg("dim"), @@ -2152,7 +2170,7 @@ Parameters ---------- rotated_query : array_like of float32, shape (d,) A rotated, padded query; d is a positive multiple of 32. -metric : {'l2', 'ip', 'innerproduct'} +metric : {'l2', 'ip'} The metric the factors were computed for. centroid : array_like of float32, shape (d,), optional The working-space centroid the factors were computed with; None is zero. @@ -2239,7 +2257,7 @@ Parameters ---------- rotated_query : array_like of float32, shape (d,) A rotated, padded query; d is a positive multiple of 32. -metric : {'l2', 'ip', 'innerproduct'} +metric : {'l2', 'ip'} The metric the factors were computed for. centroid : array_like of float32, shape (d,), optional The working-space centroid the factors were computed with; None is zero. @@ -2264,6 +2282,12 @@ num_threads : int, optional OMP_NUM_THREADS.)doc"; py::class_(quant, "Query", kQueryDoc) + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) .def( py::init(&QuantQuery::create), py::arg("rotated_query"), diff --git a/python_bindings/rabitq_bindings.cpp b/python_bindings/rabitq_bindings.cpp index c609ca06..55d2f187 100644 --- a/python_bindings/rabitq_bindings.cpp +++ b/python_bindings/rabitq_bindings.cpp @@ -1,12 +1,23 @@ #include #include +#include "bindings_common.hpp" #include "rabitqlib/core/metric.hpp" #include "rabitqlib/core/rotator.hpp" +#include "rabitqlib/index/format_error.hpp" #include "rabitqlib/utils/tools.hpp" namespace py = pybind11; +namespace { +// rabitqlib.FormatError; the module keeps it alive for the interpreter's lifetime. +PyObject* format_error_type = nullptr; + +constexpr const char* kFormatErrorDoc = + "A damaged or mismatched index file or serialized byte string, or one this release " + "cannot read. A subclass of both ValueError and RuntimeError."; +} // namespace + // Forward declarations of registration functions implemented in other cpp files void register_hnsw(py::module_& m); void register_ivf(py::module_& m); @@ -18,16 +29,55 @@ PYBIND11_MODULE(_rabitqlib, m) { m.doc() = "RabitQ Python bindings combined module"; m.attr("__version__") = RABITQ_VERSION; + + // One exception for every rejected file or byte string, registered before the + // modules that raise it. + { + const py::object builtins = py::module_::import("builtins"); + const py::tuple bases = + py::make_tuple(builtins.attr("ValueError"), builtins.attr("RuntimeError")); + PyObject* type = PyErr_NewExceptionWithDoc( + "rabitqlib.FormatError", kFormatErrorDoc, bases.ptr(), nullptr + ); + if (type == nullptr) { + throw py::error_already_set(); + } + m.attr("FormatError") = py::reinterpret_steal(type); + format_error_type = type; + } + // pybind11 translators take std::exception_ptr by value. + // NOLINTNEXTLINE(performance-unnecessary-value-param) + py::register_exception_translator([](std::exception_ptr exception) { + try { + if (exception) { + std::rethrow_exception(exception); + } + } catch (const rabitqlib::FormatError& error) { + PyErr_SetString(format_error_type, error.what()); + } + }); m.def("_available_cpu_count", &rabitqlib::total_threads); m.def("_default_thread_count", &rabitqlib::default_threads); // Register shared enums once py::enum_(m, "MetricType") + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) .value("L2", rabitqlib::METRIC_L2) .value("IP", rabitqlib::METRIC_IP) .export_values(); py::enum_(m, "RotatorType") + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) .value("FhtKacRotator", rabitqlib::RotatorType::FhtKacRotator) .value("MatrixRotator", rabitqlib::RotatorType::MatrixRotator) .export_values(); diff --git a/python_bindings/symqg_bindings.cpp b/python_bindings/symqg_bindings.cpp index 3dc00723..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,281 +36,176 @@ class SymqgIndex { const std::string& metric, const py::object& seed ) - : dim_(dim) - , max_degree_(max_degree) - , metric_type_(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_given_ = !seed.is_none(); - seed_ = seed_given_ ? static_cast( - checked_seed(seed, std::numeric_limits::max()) - ) - : random_seed(); - } + : 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) { + 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" - ); + 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)); + 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)); } - // Only a loaded index lacks these settings, and it is already built. - build_graph(data, *ef_construction_, num_threads.value_or(0), *init_, *seed_); - // Point IDs are the row numbers of data. - const size_t rows = index_->num_points(); - auto ids = py::array_t(static_cast(rows)); - std::iota(ids.mutable_data(), ids.mutable_data() + rows, PID{0}); + std::iota(ids.mutable_data(), ids.mutable_data() + rows, first); return ids; } - // Deprecated: the 0.7 build, which replaces any existing graph. Without a - // user seed, each build draws a new one, as 0.7 did. - void build( - py::handle data, size_t ef_construction, size_t num_threads, const std::string& init - ) { - const auto operation = access_.write(); - check_construction(ef_construction, init); - const uint32_t seed = seed_given_ ? *seed_ : random_seed(); - build_graph(data, ef_construction, num_threads, init, seed); - ef_construction_ = ef_construction; - init_ = init; - seed_ = seed; - } - py::tuple search( py::handle queries, size_t k, - std::optional ef, + std::optional ef_search, std::optional num_threads ) { const auto operation = access_.read(); auto query_array = ensure_2d_array(queries, "queries"); - check_built("search"); - check_k(k); - // As in HnswIndex: no or zero ef selects max(k, 64), and ef is at least k. - const size_t ef_search = - std::max(ef.value_or(0) == 0 ? std::max(k, 64) : *ef, k); - ensure_dimension(query_array, dim_, "query dimension does not match index dim"); - - const size_t num_queries = static_cast(query_array.shape(0)); + 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); + 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 result_ids = py::array_t(shape); + auto ids = py::array_t(shape); auto distances = py::array_t(shape); - auto* ids_data = result_ids.mutable_data(); - auto* distances_data = distances.mutable_data(); 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, - ef_search, - num_threads.value_or(1) - ); + index_.search(queries_data, num_queries, k, ids_data, distances_data, options); } - - return py::make_tuple(result_ids, distances); + 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(); - // Files store neither the seed nor the construction settings. - wrapper.ef_construction_.reset(); - wrapper.init_.reset(); - 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; - } - [[nodiscard]] size_t max_elements() const { - const auto operation = access_.read(); - return built() ? index_->max_elements() : 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 { - const auto operation = access_.read(); - return nbits(); - } - [[nodiscard]] size_t quantization_bits() const { + [[nodiscard]] size_t nbits() const { const auto operation = access_.read(); - return quantization_bits_; + 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 uint32_t random_seed() { return std::random_device{}(); } - - 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") { - 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 a new graph from data; a failure keeps the previous one. Requires the - // write guard. - void build_graph( - py::handle data, + static SymqgOptions index_options( + size_t nbits, + size_t max_degree, size_t ef_construction, - size_t num_threads, const std::string& init, - uint32_t seed + const std::string& metric, + const py::object& 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 + 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 (!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 loaded indexes. - bool seed_given_ = false; // The user chose the seed. + rabitqlib::SymqgIndex index_; mutable IndexAccess access_; - std::unique_ptr> index_; }; } // namespace rabitqlib::python_bindings @@ -344,9 +232,9 @@ ef_construction : int, optional Default is 200. init : {'pipnn', 'random'}, optional Keyword-only. Graph initialization method. Default is 'pipnn'. -metric : {'l2', 'ip', 'innerproduct'}, optional - Keyword-only. Squared L2 or inner-product distance. Default is 'l2'. - Vectors are not automatically normalized for cosine similarity. +metric : {'l2', 'ip', 'cosine'}, optional + Keyword-only. Squared L2, inner-product or cosine distance. Default is + 'l2'. 'cosine' scales data and queries to unit length. seed : int, optional Keyword-only. Rotation and graph-construction seed in [0, 2**32 - 1]. None (default) draws one at random; the seed property reports it. @@ -360,9 +248,6 @@ vectors before searching or saving. Concurrent reads are supported; an overlapping mutation raises RuntimeError. Data and queries must be finite float32 values within the index coordinate range; other values raise ValueError. -The 0.7 forms SymqgIndex(dim, max_degree, metric, quantization_bits), -quantization_bits=, build() and search_batch() still work in 0.8, raise -DeprecationWarning, and will be removed in 0.9. Examples -------- @@ -385,29 +270,35 @@ queries : array_like of float, shape (n_queries, dim) k : int Number of neighbors requested, at least 1. It may exceed the number of points; slots without a neighbor are padded as described below. -ef : int, optional - Search breadth. None or 0 (default) selects max(k, 64); smaller values - are raised to k. +ef_search : int, optional + Search breadth, at least 1. None (default) selects max(k, 64); smaller + values are raised to k. num_threads : int, optional - Worker count. None (default) selects 1; 0 selects the available CPU - count, capped by OMP_NUM_THREADS. + Keyword-only. Worker count. None (default) selects 1; 0 selects the + available CPU count, capped by OMP_NUM_THREADS. Returns ------- -ids : ndarray of uint32, shape (n_queries, k) +ids : ndarray of int64, shape (n_queries, k) Point IDs of the selected neighbors. distances : ndarray of float32, shape (n_queries, k) - Lower values are better; squared L2 estimates for l2 and inner-product - distance estimates for ip. These are distances, not similarity scores. + Lower values are better: squared L2 estimates for l2, 1 - dot for ip and + 1 - cos for cosine. These are distances, not similarity scores. Notes ----- Returns (ids, distances), in that order. When the graph reaches fewer than k -points, the remaining neighbors have ID 4294967295 and distance inf; test +points, the remaining neighbors have ID -1 and distance inf; test np.isfinite(distances) to find them. Array shapes and value ranges are checked at runtime, not by static type checkers.)doc"; py::class_(m, "SymqgIndex", kIndexDoc) + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) .def( py::init< size_t, @@ -469,7 +360,7 @@ num_threads : int, optional Returns ------- -ids : ndarray of uint32, shape (n,) +ids : ndarray of int64, shape (n,) Point IDs, the row numbers of data. Notes @@ -479,20 +370,13 @@ extended: a second call raises RuntimeError, so add every vector in one call, or create a new index to rebuild. Point IDs are the row numbers of data. Input arrays need not be retained after this synchronous call.)doc" ) - .def( - "_build", - &SymqgIndex::build, - py::arg("data"), - py::arg("ef_construction"), - py::arg("num_threads"), - py::arg("init") - ) .def( "search", &SymqgIndex::search, py::arg("queries"), py::arg("k"), - py::arg("ef") = py::none(), + py::arg("ef_search") = py::none(), + py::kw_only(), py::arg("num_threads") = py::none(), kSearchDoc ) @@ -510,7 +394,8 @@ path : str, bytes, bytearray, or os.PathLike Notes ----- -The saved state includes the rotation used to build the index.)doc" +The saved state includes the rotation used to build the index and its seed; +releases up to 0.8 cannot read the file.)doc" ) .def_static( "load", @@ -548,12 +433,12 @@ index : SymqgIndex .def_property_readonly( "ef_construction", &SymqgIndex::ef_construction, - R"doc(Construction search breadth of the current graph or the next add, or None for an index loaded from disk.)doc" + R"doc(Construction search breadth of the current graph or the next add, or None for an index loaded from a file from a release up to 0.8.)doc" ) .def_property_readonly( "init", &SymqgIndex::init, - R"doc(Graph initialization method of the current graph or the next add, or None for an index loaded from disk.)doc" + R"doc(Graph initialization method of the current graph or the next add, or None for an index loaded from a file from a release up to 0.8.)doc" ) .def_property_readonly( "num_points", @@ -565,26 +450,24 @@ index : SymqgIndex &SymqgIndex::num_stored_points, R"doc(Number of stored points, including removed points.)doc" ) - .def_property_readonly( - "max_elements", &SymqgIndex::max_elements, R"doc(Current storage capacity.)doc" - ) .def_property_readonly( "is_trained", - [](const SymqgIndex&) { return true; }, + &SymqgIndex::is_trained, R"doc(Always True: SymphonyQG needs no training.)doc" ) .def_property_readonly( - "metric", &SymqgIndex::metric, R"doc(Canonical metric name: 'l2' or 'ip'.)doc" + "metric", + &SymqgIndex::metric, + R"doc(Canonical metric name: 'l2', 'ip' or 'cosine'.)doc" ) .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("_quantization_bits", &SymqgIndex::quantization_bits) .def_property_readonly( "seed", &SymqgIndex::seed, - R"doc(Rotation and graph-construction seed, or None for an index loaded from disk.)doc" + R"doc(Rotation and graph-construction seed, or None for an index loaded from a file from a release up to 0.8.)doc" ); } diff --git a/sample/cpp/hnsw_rabitq_indexing.cpp b/sample/cpp/hnsw_rabitq_indexing.cpp index f1e1d540..10e56796 100644 --- a/sample/cpp/hnsw_rabitq_indexing.cpp +++ b/sample/cpp/hnsw_rabitq_indexing.cpp @@ -3,17 +3,16 @@ #include #include #include +#include #include #include "rabitqlib/core/detail/eigen.hpp" #include "rabitqlib/core/metric.hpp" -#include "rabitqlib/index/hnsw/hnsw.hpp" +#include "rabitqlib/index/hnsw_index.hpp" #include "rabitqlib/index/types.hpp" #include "rabitqlib/utils/io.hpp" #include "rabitqlib/utils/stopw.hpp" -using PID = rabitqlib::PID; -using index_type = rabitqlib::hnsw::HierarchicalNSW; using data_type = rabitqlib::RowMajorArray; using cluster_ids_type = rabitqlib::RowMajorArray; @@ -28,7 +27,7 @@ int run(int argc, char* argv[]) { << "arg5: ef for indexing \n" << "arg6: total number of bits for quantization\n" << "arg7: path for saving index\n" - << "arg8: metric type (\"l2\" or \"ip\"), l2 by default\n" + << "arg8: metric type (\"l2\", \"ip\" or \"cosine\"), l2 by default\n" << "arg9: if use faster quantization (\"true\" or \"false\"), false by " "default\n"; return 1; @@ -43,17 +42,18 @@ int run(int argc, char* argv[]) { char* index_file = argv[7]; rabitqlib::MetricType metric_type = rabitqlib::METRIC_L2; - if (argc > 8) { - std::string metric_str(argv[8]); - if (metric_str == "ip" || metric_str == "IP") { - metric_type = rabitqlib::METRIC_IP; - } - } - if (metric_type == rabitqlib::METRIC_IP) { - std::cout << "Metric Type: IP\n"; - } else if (metric_type == rabitqlib::METRIC_L2) { - std::cout << "Metric Type: L2\n"; + const char* metric_name = "L2"; + const std::string metric_str = argc > 8 ? argv[8] : "l2"; + if (metric_str == "ip" || metric_str == "IP") { + metric_type = rabitqlib::METRIC_IP; + metric_name = "IP"; + } else if (metric_str == "cosine" || metric_str == "COSINE") { + metric_type = rabitqlib::METRIC_COSINE; + metric_name = "Cosine"; + } else if (metric_str != "l2" && metric_str != "L2") { + throw std::invalid_argument("Metric type must be l2, ip or cosine"); } + std::cout << "Metric Type: " << metric_name << '\n'; bool faster_quant = false; if (argc > 9) { @@ -75,23 +75,24 @@ int run(int argc, char* argv[]) { size_t num_points = data.rows(); size_t dim = data.cols(); - size_t random_seed = 100; // by default 100 - rabitqlib::hnsw::HierarchicalNSW hnsw( - num_points, dim, total_bits, m, ef, random_seed, metric_type - ); + rabitqlib::HnswOptions options; + options.metric = metric_type; + options.nbits = total_bits; + options.num_clusters = centroids.rows(); + options.M = m; + options.ef_construction = ef; + options.seed = 100; + rabitqlib::HnswIndex hnsw(dim, options); + hnsw.reserve(num_points); // allocate the graph storage outside the timing rabitqlib::StopW stopw; stopw.reset(); - hnsw.construct( - centroids.rows(), - centroids.data(), - num_points, - data.data(), - cluster_ids.data(), - 0, - faster_quant - ); + hnsw.set_centroids(centroids.data()); + rabitqlib::AddOptions add_options; + add_options.cluster_ids = cluster_ids.data(); + add_options.fast_quantization = faster_quant; + hnsw.add(data.data(), num_points, add_options); float total_time = stopw.get_elapsed_micro(); total_time /= 1e6; diff --git a/sample/cpp/hnsw_rabitq_querying.cpp b/sample/cpp/hnsw_rabitq_querying.cpp index 45bfdcde..4820c00d 100644 --- a/sample/cpp/hnsw_rabitq_querying.cpp +++ b/sample/cpp/hnsw_rabitq_querying.cpp @@ -4,15 +4,14 @@ #include #include #include -#include #include +#include "querying_example.hpp" #include "rabitqlib/core/detail/eigen.hpp" -#include "rabitqlib/index/hnsw/hnsw.hpp" +#include "rabitqlib/index/hnsw_index.hpp" #include "rabitqlib/index/types.hpp" #include "rabitqlib/utils/io.hpp" #include "rabitqlib/utils/stopw.hpp" -#include "rabitqlib/utils/tools.hpp" std::vector efs = {10, 20, 40, 50, 60, 80, 100, 150, 170, 190, 200, 250, 300, 400, 500, 600, 700, 800, 1000, 1500, 2000}; @@ -20,8 +19,7 @@ std::vector efs = {10, 20, 40, 50, 60, 80, 100, 150, 170, 190, 2 size_t test_round = 3; size_t topk = 10; -using PID = rabitqlib::PID; -using index_type = rabitqlib::hnsw::HierarchicalNSW; +using index_type = rabitqlib::HnswIndex; using data_type = rabitqlib::RowMajorArray; using gt_type = rabitqlib::RowMajorArray; @@ -45,9 +43,7 @@ int run(int argc, char* argv[]) { size_t nq = query.rows(); size_t total_count = nq * topk; - index_type hnsw; - - hnsw.load(index_file); + auto hnsw = index_type::load(index_file); rabitqlib::StopW stopw; @@ -66,10 +62,13 @@ int run(int argc, char* argv[]) { size_t total_correct = 0; float total_time = 0; + std::vector results(nq * topk); + rabitqlib::GraphSearchOptions options; + options.ef_search = ef; + auto start = std::chrono::high_resolution_clock::now(); - std::vector>> res = - hnsw.search(query.data(), nq, topk, ef, 1); + hnsw.search(query.data(), nq, topk, results.data(), nullptr, options); auto end = std::chrono::high_resolution_clock::now(); @@ -81,8 +80,9 @@ int run(int argc, char* argv[]) { for (size_t i = 0; i < nq; i++) { for (size_t j = 0; j < topk; j++) { for (size_t k = 0; k < topk; k++) { - if (gt(static_cast(i), - static_cast(k)) == res[i][j].second) { + if (static_cast(gt( + static_cast(i), static_cast(k) + )) == results[i * topk + j]) { total_correct++; break; } @@ -100,8 +100,8 @@ int run(int argc, char* argv[]) { } } - auto avg_qps = rabitqlib::horizontal_avg(all_qps); - auto avg_recall = rabitqlib::horizontal_avg(all_recall); + auto avg_qps = querying_example::column_averages(all_qps); + auto avg_recall = querying_example::column_averages(all_recall); std::cout << "EF\tQPS\tRecall\t" diff --git a/sample/cpp/ivf_rabitq_indexing.cpp b/sample/cpp/ivf_rabitq_indexing.cpp index 2f04ebc6..3d832032 100644 --- a/sample/cpp/ivf_rabitq_indexing.cpp +++ b/sample/cpp/ivf_rabitq_indexing.cpp @@ -3,17 +3,17 @@ #include #include #include +#include #include #include "rabitqlib/core/detail/eigen.hpp" #include "rabitqlib/core/metric.hpp" -#include "rabitqlib/index/ivf/ivf.hpp" +#include "rabitqlib/index/ivf_index.hpp" #include "rabitqlib/index/types.hpp" #include "rabitqlib/utils/io.hpp" #include "rabitqlib/utils/stopw.hpp" using PID = rabitqlib::PID; -using index_type = rabitqlib::ivf::IVF; using data_type = rabitqlib::RowMajorArray; using cluster_ids_type = rabitqlib::RowMajorArray; @@ -25,24 +25,25 @@ int run(int argc, char** argv) { << "arg3: path for cluster ids file, format .ivecs\n" << "arg4: total number of bits for quantization\n" << "arg5: path for saving index\n" - << "arg6: metric type (\"l2\" or \"ip\"), l2 by default\n" + << "arg6: metric type (\"l2\", \"ip\" or \"cosine\"), l2 by default\n" << "arg7: if use faster quantization (\"true\" or \"false\"), false by " "default\n"; return 1; } rabitqlib::MetricType metric_type = rabitqlib::METRIC_L2; - if (argc > 6) { - std::string metric_str(argv[6]); - if (metric_str == "ip" || metric_str == "IP") { - metric_type = rabitqlib::METRIC_IP; - } - } - if (metric_type == rabitqlib::METRIC_IP) { - std::cout << "Metric Type: IP\n"; - } else if (metric_type == rabitqlib::METRIC_L2) { - std::cout << "Metric Type: L2\n"; + const char* metric_name = "L2"; + const std::string metric_str = argc > 6 ? argv[6] : "l2"; + if (metric_str == "ip" || metric_str == "IP") { + metric_type = rabitqlib::METRIC_IP; + metric_name = "IP"; + } else if (metric_str == "cosine" || metric_str == "COSINE") { + metric_type = rabitqlib::METRIC_COSINE; + metric_name = "Cosine"; + } else if (metric_str != "l2" && metric_str != "L2") { + throw std::invalid_argument("Metric type must be l2, ip or cosine"); } + std::cout << "Metric Type: " << metric_name << '\n'; bool faster_quant = false; if (argc > 7) { @@ -69,15 +70,22 @@ int run(int argc, char** argv) { size_t num_points = data.rows(); size_t dim = data.cols(); - size_t k = centroids.rows(); + size_t num_clusters = centroids.rows(); std::cout << "data loaded\n"; std::cout << "\tN: " << num_points << '\n'; std::cout << "\tDIM: " << dim << '\n'; rabitqlib::StopW stopw; - index_type ivf(num_points, dim, k, total_bits, metric_type); - ivf.construct(data.data(), centroids.data(), cluster_ids.data(), faster_quant); + rabitqlib::IvfOptions options; + options.metric = metric_type; + options.nbits = total_bits; + rabitqlib::IvfIndex ivf(dim, num_clusters, options); + ivf.set_centroids(centroids.data()); + rabitqlib::AddOptions add_options; + add_options.cluster_ids = cluster_ids.data(); + add_options.fast_quantization = faster_quant; + ivf.add(data.data(), num_points, add_options); float miniutes = stopw.get_elapsed_mili() / 1000 / 60; std::cout << "ivf constructed \n"; ivf.save(index_file); diff --git a/sample/cpp/ivf_rabitq_querying.cpp b/sample/cpp/ivf_rabitq_querying.cpp index acc21a48..40249b9e 100644 --- a/sample/cpp/ivf_rabitq_querying.cpp +++ b/sample/cpp/ivf_rabitq_querying.cpp @@ -6,23 +6,25 @@ #include #include +#include "querying_example.hpp" #include "rabitqlib/core/detail/eigen.hpp" -#include "rabitqlib/index/ivf/ivf.hpp" +#include "rabitqlib/index/ivf_index.hpp" #include "rabitqlib/index/types.hpp" #include "rabitqlib/utils/io.hpp" #include "rabitqlib/utils/stopw.hpp" -#include "rabitqlib/utils/tools.hpp" -using PID = rabitqlib::PID; -using index_type = rabitqlib::ivf::IVF; +using index_type = rabitqlib::IvfIndex; using data_type = rabitqlib::RowMajorArray; using gt_type = rabitqlib::RowMajorArray; static std::vector get_nprobes( const index_type& ivf, const std::vector& all_nprobes, - data_type& query, - gt_type& gt + const data_type& query, + const gt_type& gt +); +static size_t count_correct( + const std::vector& results, const gt_type& gt, size_t nq ); static size_t topk = 100; @@ -60,8 +62,7 @@ int run(int argc, char** argv) { size_t nq = query.rows(); size_t total_count = nq * topk; - index_type ivf; - ivf.load(index_file); + auto ivf = index_type::load(index_file); std::vector all_nprobes; all_nprobes.push_back(5); @@ -98,24 +99,14 @@ int run(int argc, char** argv) { std::cout << "will use nprobe = num_cluster (" << ivf.num_clusters() << ").\n"; } - size_t total_correct = 0; - std::vector results(nq * topk); + std::vector results(nq * topk); + rabitqlib::IvfSearchOptions options; + options.nprobe = nprobe; + options.high_accuracy = use_hacc; stopw.reset(); - ivf.search_batch( - query.data(), nq, topk, nprobe, results.data(), nullptr, use_hacc - ); + ivf.search(query.data(), nq, topk, results.data(), nullptr, options); const float total_time = stopw.get_elapsed_micro(); - for (size_t i = 0; i < nq; i++) { - for (size_t j = 0; j < topk; j++) { - for (size_t k = 0; k < topk; k++) { - if (gt(static_cast(i), - static_cast(k)) == results[i * topk + j]) { - total_correct++; - break; - } - } - } - } + const size_t total_correct = count_correct(results, gt, nq); float qps = static_cast(nq) / (total_time / 1e6F); float recall = static_cast(total_correct) / static_cast(total_count); @@ -125,8 +116,8 @@ int run(int argc, char** argv) { } } - auto avg_qps = rabitqlib::horizontal_avg(all_qps); - auto avg_recall = rabitqlib::horizontal_avg(all_recall); + auto avg_qps = querying_example::column_averages(all_qps); + auto avg_recall = querying_example::column_averages(all_recall); std::cout << "nprobe\tQPS\trecall" << '\n'; @@ -150,11 +141,31 @@ int main(int argc, char** argv) { } } +// Count the results of each query that appear in its top-k ground truth. +static size_t count_correct( + const std::vector& results, const gt_type& gt, size_t nq +) { + size_t total_correct = 0; + for (size_t i = 0; i < nq; i++) { + for (size_t j = 0; j < topk; j++) { + for (size_t k = 0; k < topk; k++) { + if (static_cast( + gt(static_cast(i), static_cast(k)) + ) == results[i * topk + j]) { + total_correct++; + break; + } + } + } + } + return total_correct; +} + static std::vector get_nprobes( const index_type& ivf, const std::vector& all_nprobes, - data_type& query, - gt_type& gt + const data_type& query, + const gt_type& gt ) { size_t nq = query.rows(); size_t total_count = topk * nq; @@ -164,22 +175,11 @@ static std::vector get_nprobes( for (auto nprobe : all_nprobes) { nprobes.push_back(nprobe); - size_t total_correct = 0; - std::vector results(topk); - for (size_t i = 0; i < nq; i++) { - ivf.search( - &query(static_cast(i), 0), topk, nprobe, results.data() - ); - for (size_t j = 0; j < topk; j++) { - for (size_t k = 0; k < topk; k++) { - if (gt(static_cast(i), static_cast(k)) == - results[j]) { - total_correct++; - break; - } - } - } - } + std::vector results(nq * topk); + rabitqlib::IvfSearchOptions options; + options.nprobe = nprobe; + ivf.search(query.data(), nq, topk, results.data(), nullptr, options); + const size_t total_correct = count_correct(results, gt, nq); float recall = static_cast(total_correct) / static_cast(total_count); if (recall > 0.997 || recall - old_recall < 1e-5) { break; diff --git a/sample/cpp/qgkmeans.cpp b/sample/cpp/qgkmeans.cpp index fd84b5e3..473e4ffe 100644 --- a/sample/cpp/qgkmeans.cpp +++ b/sample/cpp/qgkmeans.cpp @@ -26,10 +26,10 @@ int run_demo() { rabitqlib::qgkmeans::QGKMeansParameters parameters; parameters.niter = 5; - parameters.graph_degree = 32; - parameters.ef_build = 64; + parameters.max_degree = 32; + parameters.ef_construction = 64; parameters.ef_search = 32; - parameters.quantization_bits = 8; + parameters.nbits = 8; parameters.verbose = true; rabitqlib::qgkmeans::QGKMeans clustering(kDimension, kNumClusters, parameters); diff --git a/sample/cpp/querying_example.hpp b/sample/cpp/querying_example.hpp new file mode 100644 index 00000000..0e17c668 --- /dev/null +++ b/sample/cpp/querying_example.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include +#include + +namespace querying_example { + +// The average of each column over the rounds. The querying samples store one row per +// round, at least one, with one value per search setting, so every row has the same +// length. +inline std::vector column_averages(const std::vector>& rows) { + std::vector averages(rows.front().size(), 0.0F); + for (const auto& row : rows) { + for (size_t column = 0; column < averages.size(); ++column) { + averages[column] += row[column]; + } + } + for (auto& average : averages) { + average /= static_cast(rows.size()); + } + return averages; +} + +} // namespace querying_example diff --git a/sample/cpp/symqg_indexing.cpp b/sample/cpp/symqg_indexing.cpp index 872614bb..b15c313f 100644 --- a/sample/cpp/symqg_indexing.cpp +++ b/sample/cpp/symqg_indexing.cpp @@ -1,24 +1,16 @@ #include -#include #include #include #include -#include #include #include #include "rabitqlib/core/detail/eigen.hpp" #include "rabitqlib/core/metric.hpp" -#include "rabitqlib/core/rotator.hpp" -#include "rabitqlib/index/symqg/qg.hpp" -#include "rabitqlib/index/symqg/qg_builder.hpp" -#include "rabitqlib/index/types.hpp" +#include "rabitqlib/index/symqg_index.hpp" #include "rabitqlib/utils/io.hpp" #include "rabitqlib/utils/stopw.hpp" -#include "rabitqlib/utils/tools.hpp" -using PID = rabitqlib::PID; -using index_type = rabitqlib::symqg::QuantizedGraph; using data_type = rabitqlib::RowMajorArray; int run(int argc, char** argv) { @@ -28,10 +20,10 @@ int run(int argc, char** argv) { << "arg2: degree bound for symqg, must be a multiple of 32\n" << "arg3: ef for indexing \n" << "arg4: path for saving index\n" - << "arg5: metric type (\"l2\" or \"ip\"), l2 by default\n" - << "arg6: vector quantization bits (0, 4, or 8), 0 by default\n" + << "arg5: metric type (\"l2\", \"ip\" or \"cosine\"), l2 by default\n" + << "arg6: nbits (32 or 0 for raw vectors, 4 or 8), 32 by default\n" << "arg7: init (pipnn or random), pipnn by default\n" - << "arg8: construction threads, all available by default\n"; + << "arg8: threads, 0 or omitted for all (OMP_NUM_THREADS caps it)\n"; return 1; } @@ -41,18 +33,22 @@ int run(int argc, char** argv) { char* index_file = argv[4]; rabitqlib::MetricType metric_type = rabitqlib::METRIC_L2; - if (argc > 5) { - std::string metric_str(argv[5]); - if (metric_str == "ip" || metric_str == "IP") { - metric_type = rabitqlib::METRIC_IP; - } + const char* metric_name = "L2"; + const std::string metric_str = argc > 5 ? argv[5] : "l2"; + if (metric_str == "ip" || metric_str == "IP") { + metric_type = rabitqlib::METRIC_IP; + metric_name = "IP"; + } else if (metric_str == "cosine" || metric_str == "COSINE") { + metric_type = rabitqlib::METRIC_COSINE; + metric_name = "Cosine"; + } else if (metric_str != "l2" && metric_str != "L2") { + throw std::invalid_argument("Metric type must be l2, ip or cosine"); } - if (metric_type == rabitqlib::METRIC_IP) { - std::cout << "Metric Type: IP\n"; - } else if (metric_type == rabitqlib::METRIC_L2) { - std::cout << "Metric Type: L2\n"; + std::cout << "Metric Type: " << metric_name << '\n'; + size_t nbits = argc > 6 ? static_cast(atoi(argv[6])) : 32; + if (nbits == 0) { // the 0.8 spelling of raw vectors + nbits = 32; } - size_t quantization_bits = argc > 6 ? static_cast(atoi(argv[6])) : 0; data_type data; @@ -62,41 +58,19 @@ int run(int argc, char** argv) { if (init != "random" && init != "pipnn") { throw std::invalid_argument("Init must be random or pipnn"); } - const bool pipnn = init == "pipnn"; - const size_t threads = argc > 8 ? std::stoul(argv[8]) : rabitqlib::total_threads(); - if (threads == 0 || ef == 0 || ef > std::numeric_limits::max()) { - throw std::invalid_argument( - "Threads and construction ef must be positive; ef must fit uint32" - ); - } - rabitqlib::StopW stopw; - rabitqlib::StopW stage; - index_type qg( - data.rows(), - data.cols(), - degree, - metric_type, - rabitqlib::RotatorType::FhtKacRotator, - quantization_bits - ); + const size_t threads = argc > 8 ? std::stoul(argv[8]) : 0; - { - const auto initialization = pipnn ? rabitqlib::symqg::QGInitialization::PiPNN - : rabitqlib::symqg::QGInitialization::Random; - rabitqlib::symqg::QGBuilder builder( - qg, static_cast(ef), data.data(), threads, initialization - ); - std::cout << "Initialize and encode " << stage.get_elapsed_sec() << " secs\n"; - - // QG owns its vectors/codes now; release the input before refinement. - data = data_type(); - stage.reset(); - builder.build(); - std::cout << (pipnn ? "One refinement " : "Three iterations ") - << stage.get_elapsed_sec() << " secs\n"; - std::cout << "Average degree " << builder.avg_degree() << '\n'; - } // Release builder scratch before saving. + rabitqlib::SymqgOptions options; + options.metric = metric_type; + options.nbits = nbits; + options.max_degree = degree; + options.ef_construction = ef; + options.init = init == "pipnn" ? rabitqlib::symqg::QGInitialization::PiPNN + : rabitqlib::symqg::QGInitialization::Random; + rabitqlib::SymqgIndex qg(data.cols(), options); + rabitqlib::StopW stopw; + qg.add(data.data(), data.rows(), threads); auto milisecs = stopw.get_elapsed_mili(); std::cout << "Indexing time " << milisecs / 1000.F << " secs\n"; diff --git a/sample/cpp/symqg_querying.cpp b/sample/cpp/symqg_querying.cpp index 6a09e803..51ea1bd3 100644 --- a/sample/cpp/symqg_querying.cpp +++ b/sample/cpp/symqg_querying.cpp @@ -4,15 +4,14 @@ #include #include +#include "querying_example.hpp" #include "rabitqlib/core/detail/eigen.hpp" -#include "rabitqlib/index/symqg/qg.hpp" +#include "rabitqlib/index/symqg_index.hpp" #include "rabitqlib/index/types.hpp" #include "rabitqlib/utils/io.hpp" #include "rabitqlib/utils/stopw.hpp" -#include "rabitqlib/utils/tools.hpp" -using PID = rabitqlib::PID; -using index_type = rabitqlib::symqg::QuantizedGraph; +using index_type = rabitqlib::SymqgIndex; using data_type = rabitqlib::RowMajorArray; using gt_type = rabitqlib::RowMajorArray; @@ -59,8 +58,7 @@ int run(int argc, char** argv) { size_t nq = query.rows(); size_t total_count = nq * topk; - index_type qg; - qg.load(index_file); + auto qg = index_type::load(index_file); rabitqlib::StopW stopw; @@ -72,17 +70,19 @@ int run(int argc, char** argv) { size_t ef = efs[i]; size_t total_correct = 0; float total_time = 0; - qg.set_ef(ef); - std::vector results(total_count); + rabitqlib::GraphSearchOptions options; + options.ef_search = ef; + std::vector results(total_count); std::vector dists(total_count); stopw.reset(); - qg.search_batch(query.data(), nq, topk, results.data(), dists.data()); + qg.search(query.data(), nq, topk, results.data(), dists.data(), options); total_time = stopw.get_elapsed_micro(); for (size_t z = 0; z < nq; z++) { for (size_t y = 0; y < topk; y++) { for (size_t k = 0; k < topk; k++) { - if (gt(static_cast(z), - static_cast(k)) == results[z * topk + y]) { + if (static_cast(gt( + static_cast(z), static_cast(k) + )) == results[z * topk + y]) { total_correct++; break; } @@ -98,8 +98,8 @@ int run(int argc, char** argv) { } } - auto avg_qps = rabitqlib::horizontal_avg(all_qps); - auto avg_recall = rabitqlib::horizontal_avg(all_recall); + auto avg_qps = querying_example::column_averages(all_qps); + auto avg_recall = querying_example::column_averages(all_recall); std::cout << "EF\tQPS\tRecall\n"; for (size_t i = 0; i < avg_qps.size(); ++i) { diff --git a/sample/python/README.md b/sample/python/README.md index 20513d56..0c12a1e6 100644 --- a/sample/python/README.md +++ b/sample/python/README.md @@ -59,8 +59,9 @@ python sample/python/hnsw_rabitq_indexing.py --total-bits 5 --degree 16 \ It also accepts `--clusters` with a file from `kmeans_clustering.py`; use `--method rabitq` there for a small cluster count. With more than one thread -(`--num-threads`), the graph links vectors in a nondeterministic order; pass -`--num-threads 1` for a reproducible index. +(`--num-threads`), the graph links vectors in a nondeterministic order. The script +draws a new seed on every run, so two runs give different indexes even with +`--num-threads 1`; pass `seed=` to `HnswIndex` in your own code for a reproducible index. Query with `hnsw_rabitq_querying.py`. SymphonyQG builds directly from vectors; use `symqg_indexing.py` and `symqg_querying.py` without a clustering stage. diff --git a/sample/python/clustering_cli/ivf.py b/sample/python/clustering_cli/ivf.py index bd20f4b4..62f1aefc 100644 --- a/sample/python/clustering_cli/ivf.py +++ b/sample/python/clustering_cli/ivf.py @@ -17,7 +17,7 @@ nargs="?", default="l2", type=str.lower, - choices=["l2", "ip", "innerproduct"], + choices=["l2", "ip"], ) parser.add_argument( "--method", @@ -30,7 +30,7 @@ K = args.num_clusters centroids_path = args.centroids_path cluster_id_path = args.cluster_id_path - metric = "l2" if args.metric == "l2" else "ip" + metric = args.metric clustering_type = RaBitQKMeans if args.method == "rabitq" else QGKMeans print(f"Using {metric.upper()} metric with {clustering_type.__name__}") diff --git a/src/core/blob.cpp b/src/core/blob.cpp new file mode 100644 index 00000000..3d8132aa --- /dev/null +++ b/src/core/blob.cpp @@ -0,0 +1,232 @@ +#include "blob.hpp" + +#include +#include +#include +#include + +#include "crc32.hpp" + +namespace rabitqlib::detail { +namespace { + +constexpr std::array kBlobMagic = {'R', 'A', 'B', 'Q', 'B', 'L', 'O', 'B'}; +constexpr size_t kCommonHeaderBytes = 40; +constexpr size_t kChecksumOffset = 32; +constexpr uint32_t kRotatorKind = 1; +constexpr uint32_t kRotatorVersion = 1; +constexpr uint32_t kSeedKnown = 1; +constexpr uint32_t kMethodFhtKac = 1; +constexpr uint32_t kMethodMatrix = 2; +constexpr uint32_t kScalarFloat32 = 1; +constexpr uint32_t kScalarFloat64 = 2; +constexpr size_t kMaxRotatorDim = rotator_impl::FhtKacRotator::kMaxDim; + +constexpr std::array make_crc_table() { + std::array table{}; + for (uint32_t i = 0; i < 256; ++i) { + uint32_t value = i; + for (int bit = 0; bit < 8; ++bit) { + value = (value & 1U) != 0 ? 0xEDB88320U ^ (value >> 1) : value >> 1; + } + table[i] = value; + } + return table; +} + +constexpr std::array kCrcTable = make_crc_table(); + +void put_u32(uint8_t* out, uint32_t value) { + for (size_t i = 0; i < 4; ++i) { + out[i] = static_cast(value >> (8 * i)); + } +} + +void put_u64(uint8_t* out, uint64_t value) { + for (size_t i = 0; i < 8; ++i) { + out[i] = static_cast(value >> (8 * i)); + } +} + +uint32_t get_u32(const uint8_t* in) { + uint32_t value = 0; + for (size_t i = 0; i < 4; ++i) { + value |= static_cast(in[i]) << (8 * i); + } + return value; +} + +uint64_t get_u64(const uint8_t* in) { + uint64_t value = 0; + for (size_t i = 0; i < 8; ++i) { + value |= static_cast(in[i]) << (8 * i); + } + return value; +} + +// The blob checksum: the whole blob with its crc32 field taken as zero. +uint32_t blob_checksum(const uint8_t* blob, size_t size) { + constexpr std::array kZero{}; + uint32_t crc = crc32(blob, kChecksumOffset); + crc = crc32(kZero.data(), kZero.size(), crc); + return crc32(blob + kChecksumOffset + 4, size - kChecksumOffset - 4, crc); +} + +// The same rules and messages as rabitqlib.quant's Rotator. +void check_dimensions(RotatorType type, size_t dim, size_t padded_dim) { + if (dim == 0 || dim > kMaxRotatorDim) { + throw std::invalid_argument( + "dim must be in [1, " + std::to_string(kMaxRotatorDim) + "]; got " + + std::to_string(dim) + ); + } + if (type == RotatorType::FhtKacRotator && dim < 64) { + throw std::invalid_argument( + "dim must be at least 64 for method 'fht_kac'; got " + std::to_string(dim) + ); + } + if (padded_dim % 32 != 0 || padded_dim < dim || padded_dim > kMaxRotatorDim) { + throw std::invalid_argument( + "padded_dim must be a multiple of 32 in [dim, " + + std::to_string(kMaxRotatorDim) + "]; got " + std::to_string(padded_dim) + ); + } +} + +size_t body_bytes(RotatorType type, size_t dim, size_t padded_dim) { + return type == RotatorType::FhtKacRotator ? padded_dim / 2 + : sizeof(float) * dim * padded_dim; +} + +} // namespace + +uint32_t crc32(const void* data, size_t size, uint32_t crc) { + const auto* bytes = static_cast(data); + crc = ~crc; + for (size_t i = 0; i < size; ++i) { + crc = kCrcTable[(crc ^ bytes[i]) & 0xFFU] ^ (crc >> 8); + } + return ~crc; +} + +size_t rotator_blob_bytes(RotatorType type, size_t dim, size_t padded_dim) { + return kRotatorBlobHeaderBytes + body_bytes(type, dim, padded_dim); +} + +void encode_rotator_blob( + const Rotator& rotator, + RotatorType type, + size_t dim, + std::optional seed, + uint8_t* out +) { + const size_t padded_dim = rotator.size(); + check_dimensions(type, dim, padded_dim); + const size_t body = body_bytes(type, dim, padded_dim); + if (rotator.dump_bytes() != body) { + throw std::invalid_argument("rotator does not match its type and dimensions"); + } + const size_t size = kRotatorBlobHeaderBytes + body; + std::memset(out, 0, kRotatorBlobHeaderBytes); + std::memcpy(out, kBlobMagic.data(), kBlobMagic.size()); + put_u32(out + 8, kRotatorKind); + put_u32(out + 12, kRotatorVersion); + put_u32(out + 16, static_cast(kRotatorBlobHeaderBytes)); + put_u32(out + 20, seed.has_value() ? kSeedKnown : 0); + put_u64(out + 24, body); + put_u32(out + 40, type == RotatorType::FhtKacRotator ? kMethodFhtKac : kMethodMatrix); + put_u32(out + 44, kScalarFloat32); + put_u32(out + 48, static_cast(dim)); + put_u32(out + 52, static_cast(padded_dim)); + put_u32(out + 56, seed.value_or(0)); + rotator.save(reinterpret_cast(out + kRotatorBlobHeaderBytes)); + put_u32(out + kChecksumOffset, blob_checksum(out, size)); +} + +DecodedRotator decode_rotator_blob(const uint8_t* data, size_t size) { + if (size < kCommonHeaderBytes) { + throw std::invalid_argument("data is too short for a rabitqlib blob"); + } + if (std::memcmp(data, kBlobMagic.data(), kBlobMagic.size()) != 0) { + throw std::invalid_argument("data is not a rabitqlib blob (bad magic)"); + } + const uint32_t kind = get_u32(data + 8); + if (kind != kRotatorKind) { + throw std::invalid_argument( + "data is not a rotator blob; got kind " + std::to_string(kind) + ); + } + const uint32_t version = get_u32(data + 12); + if (version != kRotatorVersion) { + throw std::invalid_argument( + "data has unsupported rotator format version " + std::to_string(version) + + "; this release reads version " + std::to_string(kRotatorVersion) + ); + } + if (get_u32(data + 16) != kRotatorBlobHeaderBytes) { + throw std::invalid_argument( + "data has an invalid header size for rotator version 1" + ); + } + const uint64_t body = get_u64(data + 24); + if (size < kRotatorBlobHeaderBytes || body != size - kRotatorBlobHeaderBytes) { + throw std::invalid_argument( + "data length does not match its header (truncated or padded)" + ); + } + if (get_u32(data + kChecksumOffset) != blob_checksum(data, size)) { + throw std::invalid_argument("data checksum mismatch (corrupt blob)"); + } + const uint32_t flags = get_u32(data + 20); + if ((flags & ~kSeedKnown) != 0) { + throw std::invalid_argument("data has unknown flags"); + } + if (get_u32(data + 36) != 0 || get_u32(data + 60) != 0) { + throw std::invalid_argument("data has non-zero reserved fields"); + } + const uint32_t method = get_u32(data + 40); + if (method != kMethodFhtKac && method != kMethodMatrix) { + throw std::invalid_argument( + "data has an unknown rotator method " + std::to_string(method) + ); + } + const uint32_t scalar = get_u32(data + 44); + if (scalar == kScalarFloat64) { + throw std::invalid_argument( + "data stores a float64 rotator, which version 1 cannot load" + ); + } + if (scalar != kScalarFloat32) { + throw std::invalid_argument( + "data has an unknown scalar type " + std::to_string(scalar) + ); + } + + DecodedRotator result; + result.type = + method == kMethodFhtKac ? RotatorType::FhtKacRotator : RotatorType::MatrixRotator; + result.dim = get_u32(data + 48); + result.padded_dim = get_u32(data + 52); + try { + check_dimensions(result.type, result.dim, result.padded_dim); + } catch (const std::invalid_argument& error) { + throw std::invalid_argument( + std::string("data has invalid rotator dimensions: ") + error.what() + ); + } + const uint32_t seed = get_u32(data + 56); + if ((flags & kSeedKnown) != 0) { + result.seed = seed; + } else if (seed != 0) { + throw std::invalid_argument("data has a seed without the seed_known flag"); + } + if (body != body_bytes(result.type, result.dim, result.padded_dim)) { + throw std::invalid_argument("data body size does not match the rotator parameters"); + } + result.rotator = + rotator_impl::make_rotator_for_loading(result.dim, result.type, result.padded_dim); + result.rotator->load(reinterpret_cast(data + kRotatorBlobHeaderBytes)); + return result; +} + +} // namespace rabitqlib::detail diff --git a/src/core/blob.hpp b/src/core/blob.hpp new file mode 100644 index 00000000..c4c514d2 --- /dev/null +++ b/src/core/blob.hpp @@ -0,0 +1,45 @@ +#pragma once + +#include +#include +#include +#include + +#include "rabitqlib/core/rotator.hpp" +#include "rabitqlib/core/types.hpp" + +// The self-describing blobs of docs/formats.md ("Blobs"), for C++ readers and writers +// such as index files; an implementation detail, not installed. rabitqlib.quant keeps +// its own rotator blob code, which uses zlib's faster checksum; both are tested against +// the same golden files. +namespace rabitqlib::detail { + +inline constexpr size_t kRotatorBlobHeaderBytes = 64; + +// The size of the rotator blob for these parameters, which must be valid. +size_t rotator_blob_bytes(RotatorType type, size_t dim, size_t padded_dim); + +// Write the blob of `rotator`, which has the given type and dimensions, to `out`, +// which holds rotator_blob_bytes(type, dim, rotator.size()) bytes. Dimensions the +// format does not allow raise std::invalid_argument. +void encode_rotator_blob( + const Rotator& rotator, + RotatorType type, + size_t dim, + std::optional seed, + uint8_t* out +); + +struct DecodedRotator { + RotatorType type = RotatorType::FhtKacRotator; + size_t dim = 0; + size_t padded_dim = 0; + std::optional seed; + std::unique_ptr> rotator; +}; + +// Validate and decode a rotator blob of `size` bytes. Invalid data raises +// std::invalid_argument with the messages rabitqlib.quant uses, which start with "data". +DecodedRotator decode_rotator_blob(const uint8_t* data, size_t size); + +} // namespace rabitqlib::detail diff --git a/src/core/crc32.hpp b/src/core/crc32.hpp new file mode 100644 index 00000000..69ad4975 --- /dev/null +++ b/src/core/crc32.hpp @@ -0,0 +1,12 @@ +#pragma once + +#include +#include + +namespace rabitqlib::detail { + +// CRC-32 as zlib.crc32 computes it; pass an earlier result as `crc` to continue it. +// Byte-wise: meant for headers and metadata, not bulk data. +uint32_t crc32(const void* data, size_t size, uint32_t crc = 0); + +} // namespace rabitqlib::detail diff --git a/src/index/cosine.hpp b/src/index/cosine.hpp new file mode 100644 index 00000000..35a3b59e --- /dev/null +++ b/src/index/cosine.hpp @@ -0,0 +1,52 @@ +#pragma once + +#include +#include +#include +#include + +#include "rabitqlib/core/metric.hpp" +#include "rabitqlib/index/detail/parallel_for.hpp" +#include "rabitqlib/utils/tools.hpp" + +namespace rabitqlib::index_detail { + +// The cosine metric stores inner-product codes of unit vectors, so 1 - dot is 1 - cos. +inline MetricType stored_metric(MetricType metric_type) { + return metric_type == METRIC_COSINE ? METRIC_IP : metric_type; +} + +// Scale a vector to unit L2 norm. Callers check coordinates first, so the squared norm +// cannot overflow. A zero vector stays zero: its cosine distance to every vector is 1, +// as in hnswlib and Faiss. +inline void normalize_vector(const float* input, float* output, size_t dim) { + double squared_norm = 0; + for (size_t i = 0; i < dim; ++i) { + squared_norm += static_cast(input[i]) * input[i]; + } + const double scale = squared_norm > 0 ? 1.0 / std::sqrt(squared_norm) : 0.0; + for (size_t i = 0; i < dim; ++i) { + output[i] = static_cast(input[i] * scale); + } +} + +inline std::vector normalized_rows( + const float* data, size_t rows, size_t dim, size_t num_threads +) { + std::vector normalized(rows * dim); + constexpr size_t kRowsPerTask = 256; + parallel_for( + 0, + div_round_up(rows, kRowsPerTask), + num_threads, + [&](size_t task, size_t /*thread*/) { + const size_t end = std::min(rows, (task + 1) * kRowsPerTask); + for (size_t row = task * kRowsPerTask; row < end; ++row) { + normalize_vector(data + (row * dim), normalized.data() + (row * dim), dim); + } + } + ); + return normalized; +} + +} // namespace rabitqlib::index_detail diff --git a/src/index/format2.cpp b/src/index/format2.cpp new file mode 100644 index 00000000..50f543d2 --- /dev/null +++ b/src/index/format2.cpp @@ -0,0 +1,590 @@ +#include "format2.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../core/crc32.hpp" + +namespace rabitqlib::index_detail::format2 { +namespace { + +using rabitqlib::detail::crc32; + +constexpr uint32_t kHeaderFlagSeedKnown = 1U << 0; +constexpr uint32_t kKnownSectionFlags = kSectionRequired | kSectionChecksummed; +constexpr size_t kChecksumOffset = 108; +constexpr size_t kChunkBytes = size_t{1} << 16; + +// Round up to a multiple of kSectionAlignment; the caller has bounded `value`. +uint64_t align_section(uint64_t value) { + return (value + kSectionAlignment - 1) / kSectionAlignment * kSectionAlignment; +} + +std::string hex(uint64_t value) { + std::ostringstream out; + out << "0x" << std::hex << value; + return out.str(); +} + +// The stored writer version for an error message. Readers do not validate the +// field, and Python decodes messages as UTF-8, so bytes outside printable ASCII +// appear as \xNN, and so does a backslash, which keeps the output unambiguous. +std::string printable_writer_version(const std::string& version) { + constexpr std::string_view kDigits = "0123456789abcdef"; + std::string out; + out.reserve(version.size()); + for (const char c : version) { + const auto byte = static_cast(c); + if (byte >= 0x20 && byte <= 0x7E && byte != '\\') { + out.push_back(c); + } else { + out += "\\x"; + out.push_back(kDigits[byte >> 4U]); + out.push_back(kDigits[byte & 0xFU]); + } + } + return out; +} + +// The error-message component of each index, as in docs/development.md. +const char* component(IndexKind kind) { + switch (kind) { + case IndexKind::Ivf: + return "IVF"; + case IndexKind::Hnsw: + return "HNSW"; + case IndexKind::SymphonyQg: + return "QuantizedGraph"; + } + return "Index"; +} + +const char* kind_name(uint32_t kind) { + switch (kind) { + case 1: + return "an IVF-RaBitQ"; + case 2: + return "an HNSW-RaBitQ"; + case 3: + return "a SymphonyQG"; + case 4: + return "an IVF-SSD"; + default: + return nullptr; + } +} + +// The header rules that hold for every index kind, as the text after "index file", +// or an empty string. The index kind itself is checked by the caller. +std::string header_error(const Header& header) { + const auto metric = static_cast(header.metric); + if (metric < 1 || metric > 3) { + return "has unknown metric " + std::to_string(metric); + } + if (header.dim == 0) { + return "has dimension 0"; + } + if (header.padded_dim % 32 != 0 || header.padded_dim < header.dim || + header.padded_dim > kMaxPaddedDim) { + return "has padded dimension " + std::to_string(header.padded_dim) + + ", which must be a multiple of 32 from the dimension " + + std::to_string(header.dim) + " to 65536"; + } + if (header.code_bits > 9) { + return "has " + std::to_string(header.code_bits) + + " code bits; at most 9 are supported"; + } + const auto raw_type = static_cast(header.raw_type); + if (raw_type > 2) { + return "has unknown raw element type " + std::to_string(raw_type); + } + if (header.id_bits != 32 && header.id_bits != 64) { + return "has " + std::to_string(header.id_bits) + + "-bit IDs; only 32 and 64 are valid"; + } + return {}; +} + +void encode_header( + const Header& header, + uint64_t section_count, + std::string_view writer_version, + uint8_t* out +) { + std::memset(out, 0, kHeaderBytes); + std::memcpy(out, kMagic.data(), kMagic.size()); + put_u32(out + 8, kVersion); + put_u32(out + 12, kHeaderBytes); + put_u64(out + 16, header.incompat_features); + put_u64(out + 24, header.ro_compat_features); + put_u64(out + 32, header.compat_features); + put_u32(out + 40, static_cast(header.index_kind)); + put_u32(out + 44, static_cast(header.metric)); + put_u64(out + 48, header.dim); + put_u64(out + 56, header.padded_dim); + put_u32(out + 64, header.code_bits); + put_u32(out + 68, static_cast(header.raw_type)); + put_u32(out + 72, header.id_bits); + put_u32(out + 76, header.seed.has_value() ? kHeaderFlagSeedKnown : 0); + put_u64(out + 80, header.seed.value_or(0)); + put_u64(out + 88, header.num_points); + put_u64(out + 96, kHeaderBytes); + put_u32(out + 104, static_cast(section_count)); + std::memcpy(out + 112, writer_version.data(), writer_version.size()); +} + +void encode_section(const Section& section, uint8_t* out) { + std::memset(out, 0, kSectionEntryBytes); + put_u32(out, section.kind); + put_u32(out + 4, section.flags); + put_u64(out + 8, section.offset); + put_u64(out + 16, section.size); + put_u32(out + 24, section.crc32); +} + +// The header checksum: the header with its checksum field taken as zero, then the table. +uint32_t header_checksum( + const std::vector& header_bytes, const std::vector& table_bytes +) { + constexpr std::array kZero{}; + uint32_t crc = crc32(header_bytes.data(), kChecksumOffset); + crc = crc32(kZero.data(), kZero.size(), crc); + crc = crc32( + header_bytes.data() + kChecksumOffset + 4, + header_bytes.size() - kChecksumOffset - 4, + crc + ); + return crc32(table_bytes.data(), table_bytes.size(), crc); +} + +void write_zeros(std::ostream& output, uint64_t count) { + static const std::array kZeros{}; + while (count > 0) { + const auto chunk = static_cast(std::min(count, kZeros.size())); + output.write(kZeros.data(), static_cast(chunk)); + count -= chunk; + } +} + +} // namespace + +void SectionSink::write(const void* data, size_t size) { + if (size > remaining_) { + throw std::invalid_argument("index section writer wrote more bytes than declared"); + } + output_.write(static_cast(data), static_cast(size)); + remaining_ -= size; +} + +void write_file( + std::ostream& output, + const Header& header, + const std::vector& sections, + std::string_view writer_version +) { + const std::string name = component(header.index_kind); + const auto kind = static_cast(header.index_kind); + if (kind < 1 || kind > 3) { + throw std::invalid_argument( + name + " index file cannot have index kind " + std::to_string(kind) + ); + } + if (const std::string error = header_error(header); !error.empty()) { + throw std::invalid_argument(name + " index file " + error); + } + if ((header.incompat_features & ~kKnownIncompatFeatures) != 0 || + (header.ro_compat_features & ~kKnownRoCompatFeatures) != 0 || + (header.compat_features & ~kKnownCompatFeatures) != 0) { + throw std::invalid_argument(name + " index file cannot use unknown feature bits"); + } + if (sections.empty()) { + throw std::invalid_argument(name + " index file needs at least one section"); + } + const bool printable = + std::all_of(writer_version.begin(), writer_version.end(), [](char c) { + return c >= 0x20 && c <= 0x7E; + }); + if (writer_version.size() > kWriterVersionBytes || !printable) { + throw std::invalid_argument( + name + + " index file writer version must be at most 16 printable ASCII characters" + ); + } + + std::vector
entries(sections.size()); + std::unordered_set kinds; + const uint64_t table_end = kHeaderBytes + (kSectionEntryBytes * sections.size()); + uint64_t position = table_end; + for (size_t i = 0; i < sections.size(); ++i) { + const SectionWrite& section = sections[i]; + if (section.kind == 0) { + throw std::invalid_argument(name + " index file section kind 0 is reserved"); + } + if ((section.flags & ~kKnownSectionFlags) != 0) { + throw std::invalid_argument(name + " index file section has unknown flags"); + } + if (!kinds.insert(section.kind).second) { + throw std::invalid_argument( + name + " index file section kind " + std::to_string(section.kind) + + " is repeated" + ); + } + position = align_section(position); + if (section.size > + std::numeric_limits::max() - kSectionAlignment - position) { + throw std::invalid_argument( + name + " index file sections exceed the offset range" + ); + } + entries[i].kind = section.kind; + entries[i].flags = section.flags; + entries[i].offset = position; + entries[i].size = section.size; + position += section.size; + } + + // Run a section's writer and check that it wrote exactly the declared size. + const auto write_section = [&name](const SectionWrite& section, SectionSink& sink) { + if (section.write) { + section.write(sink); + } + if (sink.remaining() != 0) { + throw std::invalid_argument( + name + " index file section kind " + std::to_string(section.kind) + + " writer wrote fewer bytes than declared" + ); + } + }; + + // Checksummed sections are small: buffer them, so that the header and the table, + // which hold their checksums, can be written first. + std::vector buffered(sections.size()); + for (size_t i = 0; i < sections.size(); ++i) { + if ((entries[i].flags & kSectionChecksummed) == 0) { + continue; + } + std::ostringstream buffer; + SectionSink sink(buffer, entries[i].size); + write_section(sections[i], sink); + buffered[i] = buffer.str(); + entries[i].crc32 = crc32(buffered[i].data(), buffered[i].size()); + } + + std::vector header_bytes(kHeaderBytes); + encode_header(header, sections.size(), writer_version, header_bytes.data()); + std::vector table_bytes(kSectionEntryBytes * sections.size()); + for (size_t i = 0; i < entries.size(); ++i) { + encode_section(entries[i], table_bytes.data() + (i * kSectionEntryBytes)); + } + put_u32( + header_bytes.data() + kChecksumOffset, header_checksum(header_bytes, table_bytes) + ); + + output.write( + reinterpret_cast(header_bytes.data()), + static_cast(header_bytes.size()) + ); + output.write( + reinterpret_cast(table_bytes.data()), + static_cast(table_bytes.size()) + ); + uint64_t written = table_end; + for (size_t i = 0; i < sections.size(); ++i) { + write_zeros(output, entries[i].offset - written); + if ((entries[i].flags & kSectionChecksummed) != 0) { + output.write( + buffered[i].data(), static_cast(buffered[i].size()) + ); + } else { + SectionSink sink(output, entries[i].size); + write_section(sections[i], sink); + } + written = entries[i].offset + entries[i].size; + } + output.flush(); + if (!output) { + throw std::runtime_error(name + " index file cannot be written"); + } +} + +bool has_magic(std::istream& input, IndexKind kind) { + std::streambuf& buffer = *input.rdbuf(); + const auto start = buffer.pubseekoff(0, std::ios::cur, std::ios::in); + if (start == std::streampos(std::streamoff(-1))) { + throw FormatError( + std::string(component(kind)) + " index file input must be seekable" + ); + } + std::array magic{}; + const std::streamsize count = buffer.sgetn(magic.data(), magic.size()); + buffer.pubseekpos(start, std::ios::in); + return count == static_cast(magic.size()) && magic == kMagic; +} + +Reader::Reader( + std::istream& input, + IndexKind expected_kind, + const std::vector& known_kinds, + const std::function& check_header +) + : input_(*input.rdbuf()) + , component_(std::string(component(expected_kind)) + " index file") { + const auto end = input_.pubseekoff(0, std::ios::end, std::ios::in); + if (end == std::streampos(std::streamoff(-1))) { + throw FormatError(component_ + " input must be seekable"); + } + const auto file_size = static_cast(static_cast(end)); + + // 1. Magic, version and header size. + if (file_size < kHeaderBytes) { + throw FormatError(component_ + " is too short for a format-2 header"); + } + std::vector header_bytes(kHeaderBytes); + read_at(0, header_bytes.data(), kHeaderBytes, "header"); + if (std::memcmp(header_bytes.data(), kMagic.data(), kMagic.size()) != 0) { + throw FormatError(component_ + " is not in format 2 (bad magic)"); + } + const uint32_t version = get_u32(header_bytes.data() + 8); + if (version != kVersion) { + throw FormatError( + component_ + " has format version " + std::to_string(version) + + "; this release reads version 2" + ); + } + const uint32_t header_size = get_u32(header_bytes.data() + 12); + if (header_size < kHeaderBytes || header_size % 8 != 0 || header_size > file_size) { + throw FormatError( + component_ + " has an invalid header size " + std::to_string(header_size) + ); + } + header_bytes.resize(header_size); + read_at( + kHeaderBytes, + header_bytes.data() + kHeaderBytes, + header_size - kHeaderBytes, + "header" + ); + + // 2. The section table lies within the file, and the header checksum matches. + const uint8_t* fields = header_bytes.data(); + const uint64_t table_offset = get_u64(fields + 96); + const uint32_t section_count = get_u32(fields + 104); + if (section_count == 0) { + throw FormatError(component_ + " has no sections"); + } + if (table_offset % 8 != 0 || table_offset < header_size || table_offset > file_size || + section_count > (file_size - table_offset) / kSectionEntryBytes) { + throw FormatError(component_ + " section table lies outside the file"); + } + const uint64_t table_end = table_offset + (kSectionEntryBytes * section_count); + std::vector table_bytes(kSectionEntryBytes * section_count); + read_at(table_offset, table_bytes.data(), table_bytes.size(), "section table"); + if (get_u32(fields + kChecksumOffset) != header_checksum(header_bytes, table_bytes)) { + throw FormatError(component_ + " header checksum mismatch (corrupt file)"); + } + + // 3. Feature flags. + const char* const writer = reinterpret_cast(fields + 112); + writer_version_.assign(writer, std::find(writer, writer + kWriterVersionBytes, '\0')); + header_.incompat_features = get_u64(fields + 16); + header_.ro_compat_features = get_u64(fields + 24); + header_.compat_features = get_u64(fields + 32); + const uint64_t unknown_incompat = header_.incompat_features & ~kKnownIncompatFeatures; + if (unknown_incompat != 0) { + throw FormatError( + component_ + " uses incompatible features " + hex(unknown_incompat) + + " that this release does not know; written by rabitqlib " + + printable_writer_version(writer_version_) + ); + } + read_only_ = (header_.ro_compat_features & ~kKnownRoCompatFeatures) != 0; + + // 4. The index kind, the header rules of every kind, then the index's own. + const uint32_t kind = get_u32(fields + 40); + if (kind != static_cast(expected_kind)) { + const char* name = kind_name(kind); + if (name == nullptr) { + throw FormatError( + component_ + " has unknown index kind " + std::to_string(kind) + ); + } + throw FormatError(component_ + " holds " + name + " index"); + } + header_.index_kind = expected_kind; + header_.metric = static_cast(get_u32(fields + 44)); + header_.dim = get_u64(fields + 48); + header_.padded_dim = get_u64(fields + 56); + header_.code_bits = get_u32(fields + 64); + header_.raw_type = static_cast(get_u32(fields + 68)); + header_.id_bits = get_u32(fields + 72); + const uint32_t header_flags = get_u32(fields + 76); + const uint64_t seed = get_u64(fields + 80); + header_.num_points = get_u64(fields + 88); + if ((header_flags & ~kHeaderFlagSeedKnown) != 0) { + throw FormatError(component_ + " has unknown header flags " + hex(header_flags)); + } + if ((header_flags & kHeaderFlagSeedKnown) != 0) { + header_.seed = seed; + } else if (seed != 0) { + throw FormatError(component_ + " has a seed without the seed_known flag"); + } + if (const std::string error = header_error(header_); !error.empty()) { + throw FormatError(component_ + " " + error); + } + if (check_header) { + check_header(header_); + } + + // 5. Each entry in table order: its fields, alignment, bounds, order, overlap and + // repetition, then whether its kind is known. + std::unordered_set kinds; + uint64_t previous_end = 0; + uint64_t content_end = table_end; + for (uint32_t i = 0; i < section_count; ++i) { + const uint8_t* entry = table_bytes.data() + (i * kSectionEntryBytes); + Section section; + section.kind = get_u32(entry); + section.flags = get_u32(entry + 4); + section.offset = get_u64(entry + 8); + section.size = get_u64(entry + 16); + section.crc32 = get_u32(entry + 24); + const std::string name = + component_ + " section kind " + std::to_string(section.kind); + if (section.kind == 0) { + throw FormatError(name + " is reserved"); + } + if ((section.flags & ~kKnownSectionFlags) != 0) { + throw FormatError(name + " has unknown flags " + hex(section.flags)); + } + if (get_u32(entry + 28) != 0) { + throw FormatError(name + " has a non-zero reserved field"); + } + if ((section.flags & kSectionChecksummed) == 0 && section.crc32 != 0) { + throw FormatError(name + " has a checksum but is not checksummed"); + } + if (section.offset % kSectionAlignment != 0) { + throw FormatError(name + " is not aligned to 64 bytes"); + } + if (section.offset > file_size || section.size > file_size - section.offset) { + throw FormatError(name + " lies outside the file"); + } + const uint64_t end_offset = section.offset + section.size; + if (section.offset < previous_end) { + throw FormatError(name + " overlaps the previous section or is out of order"); + } + const bool overlaps_table = + section.size != 0 && section.offset < table_end && table_offset < end_offset; + if (section.offset < header_size || overlaps_table) { + throw FormatError(name + " overlaps the header or the section table"); + } + if (!kinds.insert(section.kind).second) { + throw FormatError(name + " is repeated"); + } + previous_end = end_offset; + content_end = std::max(content_end, end_offset); + + if (std::find(known_kinds.begin(), known_kinds.end(), section.kind) == + known_kinds.end()) { + if ((section.flags & kSectionRequired) != 0) { + throw FormatError( + name + + " is required but unknown to this release; written by rabitqlib " + + printable_writer_version(writer_version_) + ); + } + continue; + } + sections_.push_back(section); + } + + // 6. The file ends where the table or the last section ends. + if (content_end != file_size) { + throw FormatError( + component_ + " is " + std::to_string(file_size) + + " bytes, but its sections end at " + std::to_string(content_end) + ); + } + + // 7. Known checksummed sections, streamed without holding them in memory. + std::vector chunk; + for (const Section& section : sections_) { + if ((section.flags & kSectionChecksummed) == 0) { + continue; + } + chunk.resize(static_cast(std::min(section.size, kChunkBytes))); + uint32_t crc = 0; + for (uint64_t done = 0; done < section.size;) { + const auto count = + static_cast(std::min(section.size - done, kChunkBytes)); + read(section, done, chunk.data(), count); + crc = crc32(chunk.data(), count, crc); + done += count; + } + if (crc != section.crc32) { + throw FormatError( + component_ + " section kind " + std::to_string(section.kind) + + " checksum mismatch (corrupt file)" + ); + } + } +} + +const Section* Reader::find(uint32_t kind) const { + for (const Section& section : sections_) { + if (section.kind == kind) { + return §ion; + } + } + return nullptr; +} + +void Reader::read(const Section& section, uint64_t offset, void* out, size_t size) { + if (offset > section.size || size > section.size - offset) { + throw std::out_of_range(component_ + " read past the end of a section"); + } + read_at( + section.offset + offset, out, size, "section kind " + std::to_string(section.kind) + ); +} + +SectionInput Reader::open(const Section& section) { + const std::string name = component_ + " section kind " + std::to_string(section.kind); + const auto offset = static_cast(section.offset); + if (input_.pubseekpos(offset, std::ios::in) != std::streampos(offset)) { + throw FormatError(name + " cannot be read"); + } + return SectionInput(input_, name, section.size); +} + +void SectionInput::read(void* out, size_t size) { + if (size > remaining_) { + throw std::out_of_range(name_ + " read past its end"); + } + if (size != 0 && + input_.sgetn(static_cast(out), static_cast(size)) != + static_cast(size)) { + throw FormatError(name_ + " cannot be read"); + } + remaining_ -= size; +} + +void Reader::read_at(uint64_t offset, void* out, size_t size, const std::string& what) { + if (size == 0) { + return; + } + const auto position = + input_.pubseekpos(static_cast(offset), std::ios::in); + if (position != std::streampos(static_cast(offset)) || + input_.sgetn(static_cast(out), static_cast(size)) != + static_cast(size)) { + throw FormatError(component_ + " " + what + " cannot be read"); + } +} + +} // namespace rabitqlib::index_detail::format2 diff --git a/src/index/format2.hpp b/src/index/format2.hpp new file mode 100644 index 00000000..174d195f --- /dev/null +++ b/src/index/format2.hpp @@ -0,0 +1,286 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rabitqlib/core/metric.hpp" +#include "rabitqlib/index/format_error.hpp" + +// The index container of format 2, specified in docs/formats.md ("Index files, +// format 2"). This layer reads and writes the header, the section table and section +// bytes; each index defines its own sections and validates their contents. +namespace rabitqlib::index_detail::format2 { + +// A file that is not a valid format-2 container, or uses something this release +// does not support: the library-wide index file error. +using FormatError = ::rabitqlib::FormatError; + +inline constexpr std::array kMagic = {'R', 'A', 'B', 'Q', 'I', 'N', 'D', 'X'}; +inline constexpr uint32_t kVersion = 2; +inline constexpr uint32_t kHeaderBytes = 128; +inline constexpr uint64_t kSectionEntryBytes = 32; +inline constexpr uint64_t kSectionAlignment = 64; +inline constexpr size_t kWriterVersionBytes = 16; +// The rotator blob's limit, which bounds every index's working dimension. +inline constexpr uint64_t kMaxPaddedDim = 65536; + +// Feature bits this release knows. Version 2 defines none. +inline constexpr uint64_t kKnownIncompatFeatures = 0; +inline constexpr uint64_t kKnownRoCompatFeatures = 0; +inline constexpr uint64_t kKnownCompatFeatures = 0; + +enum class IndexKind : uint32_t { Ivf = 1, Hnsw = 2, SymphonyQg = 3 }; +enum class Metric : uint32_t { L2 = 1, InnerProduct = 2, Cosine = 3 }; + +inline Metric header_metric(MetricType metric_type) { + switch (metric_type) { + case METRIC_IP: + return Metric::InnerProduct; + case METRIC_COSINE: + return Metric::Cosine; + default: + return Metric::L2; + } +} + +// The reader has checked the header field. +inline MetricType metric_type(Metric metric) { + switch (metric) { + case Metric::InnerProduct: + return METRIC_IP; + case Metric::Cosine: + return METRIC_COSINE; + default: + return METRIC_L2; + } +} +enum class RawType : uint32_t { None = 0, Float32 = 1, Uint8 = 2 }; + +inline constexpr uint32_t kSectionRequired = 1U << 0; +inline constexpr uint32_t kSectionChecksummed = 1U << 1; + +// Little-endian fields of fixed width, for section contents. +inline void put_u32(uint8_t* out, uint32_t value) { + for (size_t i = 0; i < 4; ++i) { + out[i] = static_cast(value >> (8 * i)); + } +} + +inline void put_u64(uint8_t* out, uint64_t value) { + for (size_t i = 0; i < 8; ++i) { + out[i] = static_cast(value >> (8 * i)); + } +} + +[[nodiscard]] inline uint32_t get_u32(const uint8_t* in) { + uint32_t value = 0; + for (size_t i = 0; i < 4; ++i) { + value |= static_cast(in[i]) << (8 * i); + } + return value; +} + +[[nodiscard]] inline uint64_t get_u64(const uint8_t* in) { + uint64_t value = 0; + for (size_t i = 0; i < 8; ++i) { + value |= static_cast(in[i]) << (8 * i); + } + return value; +} + +// The section kind every index shares: its rotator blob. +inline constexpr uint32_t kRotatorSection = 1; + +struct Header { + uint64_t incompat_features = 0; + uint64_t ro_compat_features = 0; + uint64_t compat_features = 0; + IndexKind index_kind = IndexKind::Ivf; + Metric metric = Metric::L2; + uint64_t dim = 0; + uint64_t padded_dim = 0; + uint32_t code_bits = 0; + RawType raw_type = RawType::None; + uint32_t id_bits = 32; + std::optional seed; + uint64_t num_points = 0; +}; + +// A section table entry. +struct Section { + uint32_t kind = 0; + uint32_t flags = 0; + uint64_t offset = 0; + uint64_t size = 0; + uint32_t crc32 = 0; +}; + +class SectionSink; + +// One section to write: `write` must pass exactly `size` bytes to the sink. Writers +// mark only small sections checksummed: those are buffered in memory before writing. +struct SectionWrite { + uint32_t kind = 0; + uint32_t flags = 0; + uint64_t size = 0; + std::function write; +}; + +// Write a complete file from the current position of `output`, which must be the +// start of the file: the header, the section table right after it, then the sections +// in the given order, each at a multiple of 64. The output is written once, front to +// back, so it need not be seekable. Invalid arguments raise std::invalid_argument and +// write nothing; a section writer that passes the wrong number of bytes raises +// std::invalid_argument after part of the file is written. +void write_file( + std::ostream& output, + const Header& header, + const std::vector& sections, + std::string_view writer_version +); + +// Receives one section's bytes during write_file; it rejects more bytes than declared. +class SectionSink { + public: + void write(const void* data, size_t size); + [[nodiscard]] uint64_t remaining() const { return remaining_; } + + private: + friend void write_file( + std::ostream&, const Header&, const std::vector&, std::string_view + ); + SectionSink(std::ostream& output, uint64_t size) : output_(output), remaining_(size) {} + + std::ostream& output_; + uint64_t remaining_; +}; + +// An output stream that passes its bytes to a section sink, for section writers that +// take a std::ostream. A sink error propagates as an exception. +class SinkStream : public std::ostream { + public: + explicit SinkStream(SectionSink& sink) : std::ostream(nullptr), buffer_(sink) { + rdbuf(&buffer_); + exceptions(std::ios::badbit); + } + + private: + class Buffer : public std::streambuf { + public: + explicit Buffer(SectionSink& sink) : sink_(sink) {} + + private: + int_type overflow(int_type c) override { + if (!traits_type::eq_int_type(c, traits_type::eof())) { + const char value = traits_type::to_char_type(c); + sink_.write(&value, 1); + } + return traits_type::not_eof(c); + } + std::streamsize xsputn(const char* data, std::streamsize count) override { + sink_.write(data, static_cast(count)); + return count; + } + + SectionSink& sink_; + }; + + Buffer buffer_; +}; + +// An output stream that only counts its bytes, to size a section before writing it. +class CountingStream : public std::ostream { + public: + CountingStream() : std::ostream(nullptr) { rdbuf(&buffer_); } + [[nodiscard]] uint64_t count() const { return buffer_.count; } + + private: + class Buffer : public std::streambuf { + public: + uint64_t count = 0; + + private: + int_type overflow(int_type c) override { + count += traits_type::eq_int_type(c, traits_type::eof()) ? 0 : 1; + return traits_type::not_eof(c); + } + std::streamsize xsputn(const char* /*data*/, std::streamsize n) override { + count += static_cast(n); + return n; + } + }; + + Buffer buffer_; +}; + +// Whether the input starts with the format-2 magic. It reads through the stream +// buffer, so the stream's state and exception mask do not matter, and restores the +// position. Input that cannot seek raises FormatError, named for `kind`. +bool has_magic(std::istream& input, IndexKind kind); + +// Reads one section front to back in pieces, seeking only once. Other reads of the +// same input move its position, so finish one section before reading another. +class SectionInput { + public: + // Read the next `size` bytes of the section. + void read(void* out, size_t size); + + private: + friend class Reader; + SectionInput(std::streambuf& input, const std::string& name, uint64_t size) + : input_(input), name_(name), remaining_(size) {} + + std::streambuf& input_; + std::string name_; + uint64_t remaining_; +}; + +class Reader { + public: + // Read and validate the header and the section table, in the order of "Reading" + // in the specification: the generic header rules, then `expected_kind`, then + // `check_header` (the index's own header rules, which throw FormatError), then + // the sections. Sections whose kind is not in `known_kinds` are rejected when + // required and skipped otherwise. The reader reads through the stream buffer of + // `input`, which must outlive it, and ignores the stream's state. + Reader( + std::istream& input, + IndexKind expected_kind, + const std::vector& known_kinds, + const std::function& check_header = {} + ); + + [[nodiscard]] const Header& header() const { return header_; } + // True when the file uses read-only-compatible features this release does not know: + // it may be searched, but add, remove and save must refuse it. + [[nodiscard]] bool read_only() const { return read_only_; } + [[nodiscard]] const std::string& writer_version() const { return writer_version_; } + // The entry of a known section kind, or nullptr when the file has none. + [[nodiscard]] const Section* find(uint32_t kind) const; + // Read `size` bytes starting `offset` bytes into `section`. + void read(const Section& section, uint64_t offset, void* out, size_t size); + // Read `section` from its start in consecutive pieces; for large sections. + SectionInput open(const Section& section); + + private: + void read_at(uint64_t offset, void* out, size_t size, const std::string& what); + + std::streambuf& input_; + std::string component_; + Header header_; + bool read_only_ = false; + std::string writer_version_; + std::vector
sections_; +}; + +} // namespace rabitqlib::index_detail::format2 diff --git a/src/index/hnsw.cpp b/src/index/hnsw.cpp index 72dc4fa8..bceedd5e 100644 --- a/src/index/hnsw.cpp +++ b/src/index/hnsw.cpp @@ -1,6 +1,7 @@ #include "rabitqlib/index/hnsw/hnsw.hpp" #include +#include #include #include #include @@ -14,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -22,7 +24,10 @@ #include #include +#include "../core/blob.hpp" +#include "cosine.hpp" #include "file_replacement.hpp" +#include "format2.hpp" #include "rabitqlib/clustering/rabitqkmeans.hpp" #include "rabitqlib/core/data_layout.hpp" #include "rabitqlib/core/encoder.hpp" @@ -35,6 +40,7 @@ #include "rabitqlib/index/detail/hnsw_dispatch.hpp" #include "rabitqlib/index/detail/parallel_for.hpp" #include "rabitqlib/index/detail/visited_pool.hpp" +#include "rabitqlib/index/format_error.hpp" #include "rabitqlib/index/hnsw/hnsw_quant.hpp" #include "rabitqlib/index/types.hpp" #include "rabitqlib/utils/input_checks.hpp" @@ -45,6 +51,16 @@ namespace rabitqlib::hnsw { +namespace { +// Index format 2 sections of HNSW-RaBitQ (docs/formats.md, "Section kinds"). +constexpr uint32_t kParamsSection = 512; +constexpr uint32_t kCentroidsSection = 513; +constexpr uint32_t kRecordsSection = 514; +constexpr uint32_t kLevelsSection = 515; +constexpr uint32_t kUpperLinksSection = 516; +constexpr size_t kParamsBytes = 72; +} // namespace + HierarchicalNSW::HierarchicalNSW() = default; HierarchicalNSW::~HierarchicalNSW() = default; void HierarchicalNSW::AlignedDeleter::operator()(char* pointer) const noexcept { @@ -68,17 +84,18 @@ HierarchicalNSW::HierarchicalNSW( size_t random_seed, MetricType metric_type ) - : metric_type_(metric_type) + : metric_type_(index_detail::stored_metric(metric_type)) + , cosine_(metric_type == METRIC_COSINE) , link_list_locks_(max_elements) , element_levels_(max_elements) , raw_dist_func_( - (metric_type == METRIC_IP) ? dot_product_dis : euclidean_sqr + (metric_type_ == METRIC_IP) ? dot_product_dis : euclidean_sqr ) { static_assert( buffer::kSearchBufferMaxPointCount <= kRemovedMask, "cluster IDs must leave the removal bit free" ); - validate_metric_type(metric_type); + validate_metric_type(metric_type_); if (M < 2) { throw std::invalid_argument("HNSW M must be at least 2"); } @@ -118,6 +135,7 @@ HierarchicalNSW::HierarchicalNSW( ); level_generator_.seed(random_seed); + seed_ = random_seed; visited_set_pool_ = std::make_unique(1, max_elements_); @@ -149,69 +167,107 @@ void HierarchicalNSW::save(const char* filename) const { if (filename == nullptr || filename[0] == '\0') { throw std::invalid_argument("HNSW index filename must not be empty"); } + check_writable("save"); index_detail::save_replacing(filename, {}, [this](const std::string& path) { write_file(path.c_str()); }); } void HierarchicalNSW::write_file(const char* filename) const { + namespace f2 = index_detail::format2; std::ofstream output(io_impl::filesystem_path(filename), std::ios::binary); if (!output.is_open()) { throw std::runtime_error("HNSW cannot open index file for writing"); } - - // Serialize one count value rather than the bytes of the atomic object. - const size_t num_stored_points = num_stored_points_.load(); - output.write(reinterpret_cast(&max_elements_), sizeof(size_t)); - output.write(reinterpret_cast(&num_stored_points), sizeof(size_t)); - - output.write(reinterpret_cast(&dim_), sizeof(size_t)); - output.write(reinterpret_cast(&padded_dim_), sizeof(size_t)); - output.write(reinterpret_cast(&num_clusters_), sizeof(size_t)); - output.write(reinterpret_cast(&ex_bits_), sizeof(size_t)); - output.write(reinterpret_cast(&metric_type_), sizeof(metric_type_)); - - output.write(reinterpret_cast(&bin_data_bytes_), sizeof(size_t)); - output.write(reinterpret_cast(&ex_data_bytes_), sizeof(size_t)); - output.write(reinterpret_cast(&level0_links_bytes_), sizeof(size_t)); - output.write(reinterpret_cast(&bin_data_offset_), sizeof(size_t)); - output.write(reinterpret_cast(&ex_data_offset_), sizeof(size_t)); - output.write(reinterpret_cast(&label_offset_), sizeof(PID)); - output.write(reinterpret_cast(&level0_record_bytes_), sizeof(size_t)); - output.write(reinterpret_cast(&upper_layer_links_bytes_), sizeof(size_t)); - - output.write(reinterpret_cast(&max_level_), sizeof(int)); - output.write(reinterpret_cast(&entry_point_id_), sizeof(PID)); - - output.write(reinterpret_cast(&M_), sizeof(size_t)); - output.write(reinterpret_cast(&upper_layer_max_degree_), sizeof(size_t)); - output.write(reinterpret_cast(&base_layer_max_degree_), sizeof(size_t)); - output.write(reinterpret_cast(&level_multiplier_), sizeof(double)); - output.write(reinterpret_cast(&ef_construction_), sizeof(size_t)); - - output.write( - reinterpret_cast(centroids_memory_.get()), - static_cast(num_clusters_ * padded_dim_ * sizeof(float)) + const size_t element_count = num_stored_points_.load(); + + f2::Header header; + header.index_kind = f2::IndexKind::Hnsw; + header.metric = f2::header_metric(metric_type()); + header.dim = dim_; + header.padded_dim = padded_dim_; + header.code_bits = static_cast(ex_bits_ + 1); + header.id_bits = 32; + header.seed = seed_; + header.num_points = element_count; + + // The rotation was drawn from the low 32 bits of the seed. + std::vector rotator( + rabitqlib::detail::rotator_blob_bytes(RotatorType::FhtKacRotator, dim_, padded_dim_) ); - - output.write( - reinterpret_cast(data_level0_memory_.get()), - static_cast(num_stored_points * level0_record_bytes_) + rabitqlib::detail::encode_rotator_blob( + *rotator_, + RotatorType::FhtKacRotator, + dim_, + seed_.has_value() ? std::optional(static_cast(*seed_)) + : std::nullopt, + rotator.data() ); - - for (size_t i = 0; i < num_stored_points; ++i) { - uint32_t link_list_bytes = - element_levels_[i] > 0 ? upper_layer_links_bytes_ * element_levels_[i] : 0; - output.write(reinterpret_cast(&link_list_bytes), sizeof(uint32_t)); - if (link_list_bytes != 0) { - output.write(link_lists_[i].get(), link_list_bytes); - } + std::array params{}; + f2::put_u64(params.data(), max_elements_); + f2::put_u64(params.data() + 8, num_clusters_); + f2::put_u64(params.data() + 16, M_); + f2::put_u64(params.data() + 24, upper_layer_max_degree_); + f2::put_u64(params.data() + 32, base_layer_max_degree_); + f2::put_u64(params.data() + 40, ef_construction_); + uint64_t multiplier_bits = 0; + std::memcpy(&multiplier_bits, &level_multiplier_, sizeof(multiplier_bits)); + f2::put_u64(params.data() + 48, multiplier_bits); + f2::put_u32( + params.data() + 56, static_cast(static_cast(max_level_)) + ); + f2::put_u64(params.data() + 64, entry_point_id_); + std::vector levels(sizeof(uint32_t) * element_count); + uint64_t upper_bytes = 0; + for (size_t i = 0; i < element_count; ++i) { + f2::put_u32(levels.data() + (sizeof(uint32_t) * i), element_levels_[i]); + upper_bytes += uint64_t(element_levels_[i]) * upper_layer_links_bytes_; } - rotator_->save(output); + const auto bytes = [](const auto& buffer) { + return + [&buffer](f2::SectionSink& sink) { sink.write(buffer.data(), buffer.size()); }; + }; + const std::vector sections = { + {f2::kRotatorSection, f2::kSectionRequired, rotator.size(), bytes(rotator)}, + {kParamsSection, + f2::kSectionRequired | f2::kSectionChecksummed, + params.size(), + bytes(params)}, + {kCentroidsSection, + f2::kSectionRequired, + sizeof(float) * num_clusters_ * padded_dim_, + [this](f2::SectionSink& sink) { + sink.write( + centroids_memory_.get(), sizeof(float) * num_clusters_ * padded_dim_ + ); + }}, + {kRecordsSection, + f2::kSectionRequired, + element_count * level0_record_bytes_, + [&](f2::SectionSink& sink) { + sink.write(data_level0_memory_.get(), element_count * level0_record_bytes_); + }}, + {kLevelsSection, f2::kSectionRequired, levels.size(), bytes(levels)}, + {kUpperLinksSection, + f2::kSectionRequired, + upper_bytes, + [&](f2::SectionSink& sink) { + for (size_t i = 0; i < element_count; ++i) { + if (element_levels_[i] > 0) { + sink.write( + link_lists_[i].get(), + static_cast(element_levels_[i]) * upper_layer_links_bytes_ + ); + } + } + }}, + }; + // write_file checks the stream after flushing; close reports a late failure. + f2::write_file(output, header, sections, RABITQ_LIBRARY_VERSION); output.close(); if (!output) { - throw std::runtime_error("HNSW failed to write index file"); + throw std::runtime_error("HNSW index file cannot be written"); } } @@ -224,8 +280,69 @@ void HierarchicalNSW::load(const char* filename) { throw std::runtime_error("HNSW cannot open index file"); } + // Keep the current index intact until the complete file has been validated. + HierarchicalNSW loaded; + if (index_detail::format2::has_magic(input, index_detail::format2::IndexKind::Hnsw)) { + loaded.read_format2(input); + } else { + loaded.read_legacy(input); + } + + loaded.visited_set_pool_ = std::make_unique(1, loaded.max_elements_); + loaded.raw_dist_func_ = + (loaded.metric_type_ == METRIC_IP) ? dot_product_dis : euclidean_sqr; + loaded.ip_func_ = select_excode_ipfunc(loaded.ex_bits_); + loaded.query_config_ = + quant::faster_config(loaded.padded_dim_, SplitSingleQuery::kNumBits); + + // All swaps below are non-allocating. The temporary releases the old state. + using std::swap; + swap(construction_data_, loaded.construction_data_); + swap(max_elements_, loaded.max_elements_); + const size_t old_count = num_stored_points_.load(); + num_stored_points_ = loaded.num_stored_points_.load(); + loaded.num_stored_points_ = old_count; + swap(num_removed_, loaded.num_removed_); + swap(level0_record_bytes_, loaded.level0_record_bytes_); + swap(upper_layer_links_bytes_, loaded.upper_layer_links_bytes_); + swap(M_, loaded.M_); + swap(upper_layer_max_degree_, loaded.upper_layer_max_degree_); + swap(base_layer_max_degree_, loaded.base_layer_max_degree_); + swap(ef_construction_, loaded.ef_construction_); + swap(metric_type_, loaded.metric_type_); + swap(cosine_, loaded.cosine_); + swap(level_multiplier_, loaded.level_multiplier_); + swap(max_level_, loaded.max_level_); + link_list_locks_.swap(loaded.link_list_locks_); + swap(entry_point_id_, loaded.entry_point_id_); + swap(level0_links_bytes_, loaded.level0_links_bytes_); + swap(bin_data_offset_, loaded.bin_data_offset_); + swap(ex_data_offset_, loaded.ex_data_offset_); + swap(label_offset_, loaded.label_offset_); + swap(bin_data_bytes_, loaded.bin_data_bytes_); + swap(ex_data_bytes_, loaded.ex_data_bytes_); + swap(ex_bits_, loaded.ex_bits_); + swap(data_level0_memory_, loaded.data_level0_memory_); + swap(link_lists_, loaded.link_lists_); + element_levels_.swap(loaded.element_levels_); + swap(num_clusters_, loaded.num_clusters_); + swap(dim_, loaded.dim_); + swap(padded_dim_, loaded.padded_dim_); + swap(centroids_memory_, loaded.centroids_memory_); + label_lookup_.swap(loaded.label_lookup_); + swap(visited_set_pool_, loaded.visited_set_pool_); + swap(ip_func_, loaded.ip_func_); + swap(rotator_, loaded.rotator_); + swap(query_config_, loaded.query_config_); + swap(raw_dist_func_, loaded.raw_dist_func_); + swap(seed_, loaded.seed_); + swap(read_only_, loaded.read_only_); +} + +// The unversioned layout of releases up to 0.8. +void HierarchicalNSW::read_legacy(std::ifstream& input) { auto invalid_file = []() -> void { - throw std::runtime_error("HNSW index file is invalid or truncated"); + throw FormatError("HNSW index file is invalid or truncated"); }; auto read_header = [&](auto& value) { input.read(reinterpret_cast(&value), sizeof(value)); @@ -240,74 +357,65 @@ void HierarchicalNSW::load(const char* filename) { return left * right; }; - // Keep the current index intact until the complete file has been validated. - HierarchicalNSW loaded; size_t element_count = 0; PID label_offset = 0; - read_header(loaded.max_elements_); + read_header(max_elements_); read_header(element_count); - read_header(loaded.dim_); - read_header(loaded.padded_dim_); - read_header(loaded.num_clusters_); - read_header(loaded.ex_bits_); - read_header(loaded.metric_type_); - read_header(loaded.bin_data_bytes_); - read_header(loaded.ex_data_bytes_); - read_header(loaded.level0_links_bytes_); - read_header(loaded.bin_data_offset_); - read_header(loaded.ex_data_offset_); + read_header(dim_); + read_header(padded_dim_); + read_header(num_clusters_); + read_header(ex_bits_); + read_header(metric_type_); + read_header(bin_data_bytes_); + read_header(ex_data_bytes_); + read_header(level0_links_bytes_); + read_header(bin_data_offset_); + read_header(ex_data_offset_); read_header(label_offset); - loaded.label_offset_ = label_offset; - read_header(loaded.level0_record_bytes_); - read_header(loaded.upper_layer_links_bytes_); - read_header(loaded.max_level_); - read_header(loaded.entry_point_id_); - read_header(loaded.M_); - read_header(loaded.upper_layer_max_degree_); - read_header(loaded.base_layer_max_degree_); - read_header(loaded.level_multiplier_); - read_header(loaded.ef_construction_); - - if (loaded.max_elements_ == 0 || - loaded.max_elements_ > buffer::kSearchBufferMaxPointCount || - element_count > loaded.max_elements_ || - loaded.num_clusters_ > buffer::kSearchBufferMaxPointCount || - (element_count != 0 && loaded.num_clusters_ == 0) || loaded.dim_ < 64 || - loaded.dim_ > rotator_impl::FhtKacRotator::kMaxDim || - loaded.padded_dim_ < loaded.dim_ || loaded.padded_dim_ % 32 != 0 || - loaded.padded_dim_ > rotator_impl::FhtKacRotator::kMaxDim || loaded.ex_bits_ > 8 || - (loaded.metric_type_ != METRIC_L2 && loaded.metric_type_ != METRIC_IP) || - loaded.M_ < 2 || loaded.M_ > kMaxM || loaded.upper_layer_max_degree_ != loaded.M_ || - loaded.base_layer_max_degree_ != 2 * loaded.M_ || - loaded.ef_construction_ < loaded.M_ || - (element_count == 0 && - (loaded.max_level_ != -1 || loaded.entry_point_id_ != kPidMax)) || - (element_count != 0 && - (loaded.max_level_ < 0 || loaded.entry_point_id_ >= element_count))) { + label_offset_ = label_offset; + read_header(level0_record_bytes_); + read_header(upper_layer_links_bytes_); + read_header(max_level_); + read_header(entry_point_id_); + read_header(M_); + read_header(upper_layer_max_degree_); + read_header(base_layer_max_degree_); + read_header(level_multiplier_); + read_header(ef_construction_); + + if (max_elements_ == 0 || max_elements_ > buffer::kSearchBufferMaxPointCount || + element_count > max_elements_ || + num_clusters_ > buffer::kSearchBufferMaxPointCount || + (element_count != 0 && num_clusters_ == 0) || dim_ < 64 || + dim_ > rotator_impl::FhtKacRotator::kMaxDim || padded_dim_ < dim_ || + padded_dim_ % 32 != 0 || padded_dim_ > rotator_impl::FhtKacRotator::kMaxDim || + ex_bits_ > 8 || (metric_type_ != METRIC_L2 && metric_type_ != METRIC_IP) || + M_ < 2 || M_ > kMaxM || upper_layer_max_degree_ != M_ || + base_layer_max_degree_ != 2 * M_ || ef_construction_ < M_ || + (element_count == 0 && (max_level_ != -1 || entry_point_id_ != kPidMax)) || + (element_count != 0 && (max_level_ < 0 || entry_point_id_ >= element_count))) { invalid_file(); } // The stored layout must be the one the validated parameters derive. - const auto stored_layout = loaded.record_layout(); - loaded.set_record_layout(); - if (loaded.record_layout() != stored_layout || - !std::isfinite(loaded.level_multiplier_) || loaded.level_multiplier_ <= 0.0) { + const auto stored_layout = record_layout(); + set_record_layout(); + if (record_layout() != stored_layout || !std::isfinite(level_multiplier_) || + level_multiplier_ <= 0.0) { invalid_file(); } - const size_t centroids_bytes = checked_product( - checked_product(loaded.num_clusters_, loaded.padded_dim_), sizeof(float) - ); - const size_t data_capacity_bytes = - checked_product(loaded.max_elements_, loaded.level0_record_bytes_); - const size_t data_bytes = checked_product(element_count, loaded.level0_record_bytes_); + const size_t centroids_bytes = + checked_product(checked_product(num_clusters_, padded_dim_), sizeof(float)); + const size_t data_capacity_bytes = checked_product(max_elements_, level0_record_bytes_); + const size_t data_bytes = checked_product(element_count, level0_record_bytes_); // Validate pointer-table capacity before allocating it. - (void)checked_product(loaded.max_elements_, sizeof(LinkStorage)); + (void)checked_product(max_elements_, sizeof(LinkStorage)); const size_t link_headers_bytes = checked_product(element_count, sizeof(uint32_t)); - loaded.rotator_ = rotator_impl::make_rotator_for_loading( - loaded.dim_, RotatorType::FhtKacRotator, loaded.padded_dim_ + rotator_ = rotator_impl::make_rotator_for_loading( + dim_, RotatorType::FhtKacRotator, padded_dim_ ); - const size_t rotator_bytes = loaded.rotator_->dump_bytes(); + const size_t rotator_bytes = rotator_->dump_bytes(); const auto payload_start = input.tellg(); input.seekg(0, std::ios::end); @@ -337,85 +445,263 @@ void HierarchicalNSW::load(const char* filename) { }; if (centroids_bytes != 0) { - loaded.centroids_memory_.reset(memory::huge_page_allocate(centroids_bytes)); - read_payload(loaded.centroids_memory_.get(), centroids_bytes); + centroids_memory_.reset(memory::huge_page_allocate(centroids_bytes)); + read_payload(centroids_memory_.get(), centroids_bytes); } - loaded.data_level0_memory_.reset(memory::huge_page_allocate(data_capacity_bytes)); - read_payload(loaded.data_level0_memory_.get(), data_bytes); + data_level0_memory_.reset(memory::huge_page_allocate(data_capacity_bytes)); + read_payload(data_level0_memory_.get(), data_bytes); - loaded.element_levels_ = std::vector(loaded.max_elements_); - loaded.link_list_locks_ = std::vector(loaded.max_elements_); - loaded.link_lists_.reserve(loaded.max_elements_); - loaded.link_lists_.resize(element_count); + element_levels_ = std::vector(max_elements_); + link_list_locks_ = std::vector(max_elements_); + link_lists_.reserve(max_elements_); + link_lists_.resize(element_count); for (size_t i = 0; i < element_count; ++i) { - const char* row = - loaded.data_level0_memory_.get() + i * loaded.level0_record_bytes_; + uint32_t link_list_bytes = 0; + read_payload(reinterpret_cast(&link_list_bytes), sizeof(link_list_bytes)); + if (link_list_bytes != 0) { + if (link_list_bytes % upper_layer_links_bytes_ != 0 || + link_list_bytes / upper_layer_links_bytes_ > + static_cast(max_level_) || + link_list_bytes > remaining) { + invalid_file(); + } + link_lists_[i].reset(static_cast(std::malloc(link_list_bytes))); + if (link_lists_[i] == nullptr) { + throw std::bad_alloc(); + } + element_levels_[i] = + static_cast(link_list_bytes / upper_layer_links_bytes_); + } + num_stored_points_ = i + 1; + if (link_list_bytes != 0) { + read_payload(link_lists_[i].get(), link_list_bytes); + } + } + validate_graph(); + + if (rotator_bytes > remaining) { + invalid_file(); + } + rotator_->load(input); + if (!input) { + invalid_file(); + } + remaining -= rotator_bytes; + if (remaining != 0) { + invalid_file(); + } +} + +void HierarchicalNSW::read_format2(std::istream& input) { + namespace f2 = index_detail::format2; + const std::vector known_kinds = { + f2::kRotatorSection, + kParamsSection, + kCentroidsSection, + kRecordsSection, + kLevelsSection, + kUpperLinksSection}; + f2::Reader reader( + input, f2::IndexKind::Hnsw, known_kinds, [](const f2::Header& header) { + if (header.id_bits != 32 || header.raw_type != f2::RawType::None) { + throw f2::FormatError("HNSW index file stores 64-bit IDs or raw vectors"); + } + if (header.code_bits == 0 || header.dim < 64) { + throw f2::FormatError( + "HNSW index file has an invalid code width or dimension" + ); + } + if (header.num_points == 0 || + header.num_points > buffer::kSearchBufferMaxPointCount) { + throw f2::FormatError( + "HNSW index file has an invalid point count " + + std::to_string(header.num_points) + ); + } + } + ); + const f2::Header& header = reader.header(); + metric_type_ = index_detail::stored_metric(f2::metric_type(header.metric)); + cosine_ = header.metric == f2::Metric::Cosine; + dim_ = static_cast(header.dim); + padded_dim_ = static_cast(header.padded_dim); + ex_bits_ = header.code_bits - 1; + seed_ = header.seed; + const auto element_count = static_cast(header.num_points); + + const auto require = [&reader](uint32_t kind, std::optional size) { + const f2::Section* section = reader.find(kind); + if (section == nullptr) { + throw f2::FormatError( + "HNSW index file has no section kind " + std::to_string(kind) + ); + } + if (size.has_value() && section->size != *size) { + throw f2::FormatError( + "HNSW index file section kind " + std::to_string(kind) + " has " + + std::to_string(section->size) + " bytes; expected " + std::to_string(*size) + ); + } + return section; + }; + const auto read_all = [&reader](const f2::Section& section) { + std::vector bytes(static_cast(section.size)); + reader.read(section, 0, bytes.data(), bytes.size()); + return bytes; + }; + + const std::vector params = read_all(*require(kParamsSection, kParamsBytes)); + max_elements_ = static_cast(f2::get_u64(params.data())); + num_clusters_ = static_cast(f2::get_u64(params.data() + 8)); + M_ = static_cast(f2::get_u64(params.data() + 16)); + upper_layer_max_degree_ = static_cast(f2::get_u64(params.data() + 24)); + base_layer_max_degree_ = static_cast(f2::get_u64(params.data() + 32)); + ef_construction_ = static_cast(f2::get_u64(params.data() + 40)); + const uint64_t multiplier_bits = f2::get_u64(params.data() + 48); + std::memcpy(&level_multiplier_, &multiplier_bits, sizeof(level_multiplier_)); + max_level_ = static_cast(static_cast(f2::get_u32(params.data() + 56))); + const uint64_t entry_point = f2::get_u64(params.data() + 64); + if (max_elements_ < element_count || + max_elements_ > buffer::kSearchBufferMaxPointCount || num_clusters_ == 0 || + num_clusters_ > buffer::kSearchBufferMaxPointCount || M_ < 2 || M_ > kMaxM || + upper_layer_max_degree_ != M_ || base_layer_max_degree_ != 2 * M_ || + ef_construction_ < M_ || !std::isfinite(level_multiplier_) || + level_multiplier_ <= 0.0 || max_level_ < 0 || entry_point >= element_count || + f2::get_u32(params.data() + 60) != 0) { + throw f2::FormatError("HNSW index file has invalid graph parameters"); + } + entry_point_id_ = static_cast(entry_point); + set_record_layout(); + + const std::vector blob = read_all(*require(f2::kRotatorSection, std::nullopt)); + rabitqlib::detail::DecodedRotator rotator; + try { + rotator = rabitqlib::detail::decode_rotator_blob(blob.data(), blob.size()); + } catch (const std::invalid_argument& error) { + throw f2::FormatError( + std::string("HNSW index file has an invalid rotator (") + error.what() + ")" + ); + } + if (rotator.type != RotatorType::FhtKacRotator || rotator.dim != dim_ || + rotator.padded_dim != padded_dim_) { + throw f2::FormatError("HNSW index file rotator does not match its dimensions"); + } + rotator_ = std::move(rotator.rotator); + + const size_t centroids_bytes = sizeof(float) * num_clusters_ * padded_dim_; + const f2::Section* centroids = require(kCentroidsSection, centroids_bytes); + const f2::Section* records = + require(kRecordsSection, element_count * level0_record_bytes_); + const std::vector levels = + read_all(*require(kLevelsSection, sizeof(uint32_t) * element_count)); + uint64_t upper_bytes = 0; + element_levels_ = std::vector(max_elements_); + for (size_t i = 0; i < element_count; ++i) { + const uint32_t level = f2::get_u32(levels.data() + (sizeof(uint32_t) * i)); + if (level > static_cast(max_level_)) { + throw f2::FormatError("HNSW index file has a point above the maximum level"); + } + element_levels_[i] = static_cast(level); + // Guard the sum, so that a wrapped total cannot match the section size. + const uint64_t bytes = uint64_t{level} * upper_layer_links_bytes_; + if (bytes > std::numeric_limits::max() - upper_bytes) { + throw f2::FormatError("HNSW index file has an invalid level structure"); + } + upper_bytes += bytes; + } + const f2::Section* upper = require(kUpperLinksSection, upper_bytes); + + centroids_memory_.reset(memory::huge_page_allocate(centroids_bytes)); + f2::SectionInput centroids_input = reader.open(*centroids); + centroids_input.read(centroids_memory_.get(), centroids_bytes); + data_level0_memory_.reset( + memory::huge_page_allocate(max_elements_ * level0_record_bytes_) + ); + f2::SectionInput records_input = reader.open(*records); + records_input.read(data_level0_memory_.get(), element_count * level0_record_bytes_); + link_list_locks_ = std::vector(max_elements_); + link_lists_.reserve(max_elements_); + link_lists_.resize(element_count); + f2::SectionInput upper_input = reader.open(*upper); + for (size_t i = 0; i < element_count; ++i) { + const size_t bytes = + static_cast(element_levels_[i]) * upper_layer_links_bytes_; + if (bytes == 0) { + continue; + } + link_lists_[i].reset(static_cast(std::malloc(bytes))); + if (link_lists_[i] == nullptr) { + throw std::bad_alloc(); + } + upper_input.read(link_lists_[i].get(), bytes); + } + num_stored_points_ = element_count; + validate_graph(); + read_only_ = reader.read_only(); +} + +void HierarchicalNSW::check_writable(const char* operation) const { + if (read_only_) { + throw std::logic_error( + std::string( + "HNSW index was loaded from a file with features this release " + "cannot update, so it cannot " + ) + + operation + ); + } +} + +void HierarchicalNSW::validate_graph() { + const auto invalid = []() -> void { + throw FormatError("HNSW index file is invalid or truncated"); + }; + const size_t element_count = num_stored_points_; + for (size_t i = 0; i < element_count; ++i) { + const char* row = data_level0_memory_.get() + i * level0_record_bytes_; PID cluster_id = 0; PID label = 0; uint16_t level0_degree = 0; std::memcpy(&level0_degree, row, sizeof(level0_degree)); - std::memcpy(&cluster_id, row + loaded.level0_links_bytes_, sizeof(cluster_id)); - std::memcpy(&label, row + loaded.label_offset_, sizeof(label)); - if ((cluster_id & ~kRemovedMask) >= loaded.num_clusters_ || - level0_degree > loaded.base_layer_max_degree_) { - invalid_file(); + std::memcpy(&cluster_id, row + level0_links_bytes_, sizeof(cluster_id)); + std::memcpy(&label, row + label_offset_, sizeof(label)); + if ((cluster_id & ~kRemovedMask) >= num_clusters_ || + level0_degree > base_layer_max_degree_) { + invalid(); } - loaded.num_removed_ += (cluster_id & kRemovedMask) != 0; + num_removed_ += (cluster_id & kRemovedMask) != 0; for (size_t edge = 0; edge < level0_degree; ++edge) { PID neighbor = 0; std::memcpy(&neighbor, row + sizeof(PID) + edge * sizeof(PID), sizeof(PID)); if (neighbor >= element_count) { - invalid_file(); + invalid(); } } - if (!loaded.label_lookup_.emplace(label, static_cast(i)).second) { - invalid_file(); + if (!label_lookup_.emplace(label, static_cast(i)).second) { + invalid(); } - - uint32_t link_list_bytes = 0; - read_payload(reinterpret_cast(&link_list_bytes), sizeof(link_list_bytes)); - if (link_list_bytes != 0) { - if (link_list_bytes % loaded.upper_layer_links_bytes_ != 0 || - link_list_bytes / loaded.upper_layer_links_bytes_ > - static_cast(loaded.max_level_) || - link_list_bytes > remaining) { - invalid_file(); - } - loaded.link_lists_[i].reset(static_cast(std::malloc(link_list_bytes))); - if (loaded.link_lists_[i] == nullptr) { - throw std::bad_alloc(); + for (int level = 0; level < element_levels_[i]; ++level) { + const char* link = link_lists_[i].get() + level * upper_layer_links_bytes_; + uint16_t degree = 0; + std::memcpy(°ree, link, sizeof(degree)); + if (degree > upper_layer_max_degree_) { + invalid(); } - loaded.element_levels_[i] = - static_cast(link_list_bytes / loaded.upper_layer_links_bytes_); - } - loaded.num_stored_points_ = i + 1; - if (link_list_bytes != 0) { - read_payload(loaded.link_lists_[i].get(), link_list_bytes); - for (int level = 0; level < loaded.element_levels_[i]; ++level) { - const char* link = - loaded.link_lists_[i].get() + level * loaded.upper_layer_links_bytes_; - uint16_t degree = 0; - std::memcpy(°ree, link, sizeof(degree)); - if (degree > loaded.upper_layer_max_degree_) { - invalid_file(); - } - for (size_t edge = 0; edge < degree; ++edge) { - PID neighbor = 0; - std::memcpy( - &neighbor, link + sizeof(PID) + edge * sizeof(PID), sizeof(PID) - ); - if (neighbor >= element_count) { - invalid_file(); - } + for (size_t edge = 0; edge < degree; ++edge) { + PID neighbor = 0; + std::memcpy( + &neighbor, link + sizeof(PID) + edge * sizeof(PID), sizeof(PID) + ); + if (neighbor >= element_count) { + invalid(); } } } } for (size_t i = 0; i < element_count; ++i) { - for (int level = 1; level <= loaded.element_levels_[i]; ++level) { - const char* link = - loaded.link_lists_[i].get() + - (static_cast(level) - 1) * loaded.upper_layer_links_bytes_; + for (int level = 1; level <= element_levels_[i]; ++level) { + const char* link = link_lists_[i].get() + + (static_cast(level) - 1) * upper_layer_links_bytes_; uint16_t degree = 0; std::memcpy(°ree, link, sizeof(degree)); for (size_t edge = 0; edge < degree; ++edge) { @@ -423,75 +709,15 @@ void HierarchicalNSW::load(const char* filename) { std::memcpy( &neighbor, link + sizeof(PID) + edge * sizeof(PID), sizeof(PID) ); - if (loaded.element_levels_[neighbor] < level) { - invalid_file(); + if (element_levels_[neighbor] < level) { + invalid(); } } } } - if (element_count != 0 && - loaded.element_levels_[loaded.entry_point_id_] != loaded.max_level_) { - invalid_file(); - } - - if (rotator_bytes > remaining) { - invalid_file(); - } - loaded.rotator_->load(input); - if (!input) { - invalid_file(); - } - remaining -= rotator_bytes; - if (remaining != 0) { - invalid_file(); + if (element_count != 0 && element_levels_[entry_point_id_] != max_level_) { + invalid(); } - - loaded.visited_set_pool_ = std::make_unique(1, loaded.max_elements_); - loaded.raw_dist_func_ = - (loaded.metric_type_ == METRIC_IP) ? dot_product_dis : euclidean_sqr; - loaded.ip_func_ = select_excode_ipfunc(loaded.ex_bits_); - loaded.query_config_ = - quant::faster_config(loaded.padded_dim_, SplitSingleQuery::kNumBits); - - // All swaps below are non-allocating. The temporary releases the old state. - using std::swap; - swap(construction_data_, loaded.construction_data_); - swap(max_elements_, loaded.max_elements_); - const size_t old_count = num_stored_points_.load(); - num_stored_points_ = loaded.num_stored_points_.load(); - loaded.num_stored_points_ = old_count; - swap(num_removed_, loaded.num_removed_); - swap(level0_record_bytes_, loaded.level0_record_bytes_); - swap(upper_layer_links_bytes_, loaded.upper_layer_links_bytes_); - swap(M_, loaded.M_); - swap(upper_layer_max_degree_, loaded.upper_layer_max_degree_); - swap(base_layer_max_degree_, loaded.base_layer_max_degree_); - swap(ef_construction_, loaded.ef_construction_); - swap(metric_type_, loaded.metric_type_); - swap(level_multiplier_, loaded.level_multiplier_); - swap(max_level_, loaded.max_level_); - link_list_locks_.swap(loaded.link_list_locks_); - swap(entry_point_id_, loaded.entry_point_id_); - swap(level0_links_bytes_, loaded.level0_links_bytes_); - swap(bin_data_offset_, loaded.bin_data_offset_); - swap(ex_data_offset_, loaded.ex_data_offset_); - swap(label_offset_, loaded.label_offset_); - swap(bin_data_bytes_, loaded.bin_data_bytes_); - swap(ex_data_bytes_, loaded.ex_data_bytes_); - swap(ex_bits_, loaded.ex_bits_); - swap(data_level0_memory_, loaded.data_level0_memory_); - swap(link_lists_, loaded.link_lists_); - element_levels_.swap(loaded.element_levels_); - swap(num_clusters_, loaded.num_clusters_); - swap(dim_, loaded.dim_); - swap(padded_dim_, loaded.padded_dim_); - swap(centroids_memory_, loaded.centroids_memory_); - label_lookup_.swap(loaded.label_lookup_); - swap(visited_set_pool_, loaded.visited_set_pool_); - swap(ip_func_, loaded.ip_func_); - swap(rotator_, loaded.rotator_); - swap(query_config_, loaded.query_config_); - swap(raw_dist_func_, loaded.raw_dist_func_); } void HierarchicalNSW::construct( @@ -526,6 +752,15 @@ void HierarchicalNSW::construct( } check_coordinates(data, num_points * dim_, dim_, "HNSW construction data"); check_coordinates(centroids, num_clusters * dim_, dim_, "HNSW construction centroids"); + std::vector normalized; + std::vector scaled_centroids; + if (cosine_) { + normalized = index_detail::normalized_rows(data, num_points, dim_, num_threads); + data = normalized.data(); + scaled_centroids = + index_detail::normalized_rows(centroids, num_clusters, dim_, num_threads); + centroids = scaled_centroids.data(); + } try { num_clusters_ = num_clusters; @@ -584,6 +819,12 @@ void HierarchicalNSW::link_exact( } void HierarchicalNSW::set_centroids(size_t num_clusters, const float* centroids) { + set_centroids_impl(num_clusters, centroids, /*given=*/true); +} + +void HierarchicalNSW::set_centroids_impl( + size_t num_clusters, const float* centroids, bool given +) { if (level0_record_bytes_ == 0) { throw std::logic_error("HNSW index must be initialized before setting centroids"); } @@ -600,6 +841,11 @@ void HierarchicalNSW::set_centroids(size_t num_clusters, const float* centroids) throw std::invalid_argument("HNSW centroids exceed addressable storage"); } check_coordinates(centroids, num_clusters * dim_, dim_, "HNSW centroids"); + std::vector scaled; + if (cosine_ && given) { + scaled = index_detail::normalized_rows(centroids, num_clusters, dim_, 1); + centroids = scaled.data(); + } // construct rotates centroids the same way, so both paths quantize identically. AlignedStorage rotated( @@ -640,10 +886,17 @@ void HierarchicalNSW::train( throw std::invalid_argument("HNSW training data exceeds addressable storage"); } // k-means checks the data for finite, in-range coordinates in parallel with - // the bound check_coordinates uses; set_centroids checks its centroids. + // the bound check_coordinates uses; set_centroids checks its centroids. The cosine + // metric checks the data before normalizing it, as add does. + std::vector normalized; + if (cosine_) { + check_coordinates(data, num_points * dim_, dim_, "HNSW training data"); + normalized = index_detail::normalized_rows(data, num_points, dim_, cp.num_threads); + data = normalized.data(); + } rabitqkmeans::RaBitQKMeans kmeans(dim_, num_clusters, cp); kmeans.train_centroids(num_points, data); - set_centroids(num_clusters, kmeans.centroids.data()); + set_centroids_impl(num_clusters, kmeans.centroids.data(), /*given=*/false); } template @@ -1014,7 +1267,14 @@ std::vector>> HierarchicalNSW::search( num_threads, [&](size_t index, size_t /*thread*/) { std::vector rotated_query(padded_dim_); - rotator_->rotate(queries + (index * dim_), rotated_query.data()); + const float* query = queries + (index * dim_); + std::vector normalized_query; + if (cosine_) { + normalized_query.resize(dim_); + index_detail::normalize_vector(query, normalized_query.data(), dim_); + query = normalized_query.data(); + } + rotator_->rotate(query, rotated_query.data()); results[index] = detail::search_knn_sorted( *this, rotated_query.data(), k, std::max(ef_search, k) ); @@ -1112,6 +1372,7 @@ size_t HierarchicalNSW::remove(const PID* labels, size_t num_points) { rotator_ == nullptr || num_clusters_ == 0) { throw std::logic_error("HNSW index must be constructed or loaded before remove"); } + check_writable("remove"); if (num_points == 0) { return 0; } @@ -1319,6 +1580,7 @@ void HierarchicalNSW::resize(size_t new_max_elements) { if (level0_record_bytes_ == 0) { throw std::logic_error("HNSW index must be initialized before resize"); } + check_writable("resize"); if (new_max_elements == 0) { throw std::invalid_argument("HNSW resize capacity must be greater than zero"); } @@ -1379,6 +1641,7 @@ std::vector HierarchicalNSW::add( "HNSW index must be trained, constructed or loaded before add" ); } + check_writable("add"); if (num_points == 0) { return {}; } @@ -1392,6 +1655,11 @@ std::vector HierarchicalNSW::add( throw std::invalid_argument("HNSW add point count exceeds the supported ID range"); } check_coordinates(data, num_points * dim_, dim_, "HNSW add data"); + std::vector normalized; + if (cosine_) { + normalized = index_detail::normalized_rows(data, num_points, dim_, num_threads); + data = normalized.data(); + } std::vector labels(num_points); // Either the caller names the cluster of every point, or each one goes to its // nearest centroid, ordered the way a query is routed. diff --git a/src/index/hnsw_index.cpp b/src/index/hnsw_index.cpp new file mode 100644 index 00000000..16818dfd --- /dev/null +++ b/src/index/hnsw_index.cpp @@ -0,0 +1,274 @@ +#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 a file saved before training 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()) { + return; + } + // Only a file saved before training loads untrained, and it lacks the seed that + // lets the first add train. + if (!index_->seed().has_value()) { + throw std::logic_error( + std::string("HnswIndex loaded from an untrained file must be trained before ") + + operation + "; call train or set_centroids" + ); + } + 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..73f73794 --- /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, HnswIndex and SymqgIndex 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.cpp b/src/index/ivf.cpp index abc91769..4b0f1a35 100644 --- a/src/index/ivf.cpp +++ b/src/index/ivf.cpp @@ -20,7 +20,10 @@ #include #include +#include "../core/blob.hpp" +#include "cosine.hpp" #include "file_replacement.hpp" +#include "format2.hpp" #include "ivf_search.hpp" #include "rabitqlib/clustering/detail/kmeans.hpp" #include "rabitqlib/clustering/qgkmeans.hpp" @@ -38,6 +41,7 @@ #include "rabitqlib/index/detail/buffer.hpp" #include "rabitqlib/index/detail/parallel_exception.hpp" #include "rabitqlib/index/detail/parallel_for.hpp" +#include "rabitqlib/index/format_error.hpp" #include "rabitqlib/index/ivf/cluster.hpp" #include "rabitqlib/index/ivf/initializer.hpp" #include "rabitqlib/index/training.hpp" @@ -50,6 +54,11 @@ namespace rabitqlib::ivf { namespace { +using index_detail::format2::get_u32; +using index_detail::format2::get_u64; +using index_detail::format2::put_u32; +using index_detail::format2::put_u64; + // remove() marks a point by this f_add; save and load keep the marker. constexpr float kRemovedFAdd = std::numeric_limits::infinity(); // Files without routing metadata used HNSW routing from this many clusters. @@ -59,6 +68,31 @@ constexpr const char* kPointCountConstructOnly = "IVF index created with a point count must be built by construct"; // Scratch for the rows that flat routing in add rotates at a time. constexpr size_t kRoutingBlockBytes = size_t{128} << 20; + +// Index format 2 sections of IVF-RaBitQ (docs/formats.md, "Section kinds"). +constexpr uint32_t kParamsSection = 256; +constexpr uint32_t kClusterSizesSection = 257; +constexpr uint32_t kFlatRoutingSection = 258; +constexpr uint32_t kFlatRaBitQRoutingSection = 259; +constexpr uint32_t kHnswRoutingSection = 260; +constexpr uint32_t kCodesSection = 261; +constexpr uint32_t kRerankSection = 262; +constexpr uint32_t kIdsSection = 263; +constexpr size_t kParamsBytes = 16; +// The rotator blob stores dimensions in 32 bits, up to the FHT/Kac limit. +constexpr size_t kMaxSavedDim = rotator_impl::FhtKacRotator::kMaxDim; + +uint32_t routing_section(InitializerType type) { + switch (type) { + case InitializerType::Flat: + return kFlatRoutingSection; + case InitializerType::FlatRaBitQ: + return kFlatRaBitQRoutingSection; + default: + return kHnswRoutingSection; + } +} + } // namespace IVF::IVF() noexcept = default; @@ -147,11 +181,14 @@ void IVF::swap(IVF& other) noexcept { swap(num_clusters_, other.num_clusters_); swap(raw_reranking_, other.raw_reranking_); swap(ready_, other.ready_); + swap(read_only_, other.read_only_); + swap(seed_, other.seed_); swap(ex_bits_, other.ex_bits_); swap(rotator_type_, other.rotator_type_); swap(rotator_, other.rotator_); swap(clusters_, other.clusters_); swap(metric_type_, other.metric_type_); + swap(cosine_, other.cosine_); swap(ip_func_, other.ip_func_); } @@ -172,7 +209,8 @@ IVF::IVF( , raw_reranking_(total_bits == 32) , ex_bits_(total_bits == 32 ? 0 : total_bits - 1) , rotator_type_(rotator_type) - , metric_type_(metric_type) { + , metric_type_(index_detail::stored_metric(metric_type)) + , cosine_(metric_type == METRIC_COSINE) { configure(total_bits); if (num_points == 0 || num_points > buffer::kSearchBufferMaxPointCount) { throw std::invalid_argument("IVF point count exceeds the supported ID range"); @@ -197,9 +235,11 @@ IVF::IVF( , padded_dim_(dim) , num_clusters_(num_clusters) , raw_reranking_(total_bits == 32) + , seed_(seed) , ex_bits_(total_bits == 32 ? 0 : total_bits - 1) , rotator_type_(rotator_type) - , metric_type_(metric_type) { + , metric_type_(index_detail::stored_metric(metric_type)) + , cosine_(metric_type == METRIC_COSINE) { configure(total_bits); rotator_.reset(choose_rotator(dim, rotator_type, padded_dim_, seed)); } @@ -237,6 +277,10 @@ std::unique_ptr IVF::make_initializer() const { } void IVF::set_centroids(const float* centroids, size_t num_threads) { + set_centroids_impl(centroids, num_threads, /*given=*/true); +} + +void IVF::set_centroids_impl(const float* centroids, size_t num_threads, bool given) { if (rotator_ == nullptr) { throw std::logic_error("IVF must be configured before setting centroids"); } @@ -250,6 +294,11 @@ void IVF::set_centroids(const float* centroids, size_t num_threads) { throw std::invalid_argument("IVF centroids must not be null"); } check_coordinates(centroids, num_clusters_ * dim_, dim_, "IVF centroids"); + std::vector scaled; + if (cosine_ && given) { + scaled = index_detail::normalized_rows(centroids, num_clusters_, dim_, num_threads); + centroids = scaled.data(); + } // construct rotates centroids the same way, so both paths route identically. std::vector rotated_centroids(num_clusters_ * padded_dim_); @@ -309,7 +358,14 @@ void IVF::train( throw std::invalid_argument("IVF training data exceeds addressable storage"); } // k-means checks the data for finite, in-range coordinates in parallel with - // the bound check_coordinates uses; set_centroids checks its centroids. + // the bound check_coordinates uses; set_centroids checks its centroids. The cosine + // metric checks the data before normalizing it, as add does. + std::vector normalized; + if (cosine_) { + check_coordinates(data, num_points * dim_, dim_, "IVF training data"); + normalized = index_detail::normalized_rows(data, num_points, dim_, cp.num_threads); + data = normalized.data(); + } std::vector centroids; if (num_clusters_ <= kMaxRaBitQKMeansClusters) { rabitqkmeans::RaBitQKMeans kmeans(dim_, num_clusters_, cp); @@ -322,7 +378,7 @@ void IVF::train( kmeans.train_centroids(num_points, data); centroids = std::move(kmeans.centroids); } - set_centroids(centroids.data(), cp.num_threads); + set_centroids_impl(centroids.data(), cp.num_threads, /*given=*/false); } void IVF::construct( @@ -352,6 +408,15 @@ void IVF::construct( } check_coordinates(data, max_elements_ * dim_, dim_, "IVF construction data"); check_coordinates(centroids, num_clusters_ * dim_, dim_, "IVF construction centroids"); + std::vector normalized; + std::vector scaled_centroids; + if (cosine_) { + normalized = index_detail::normalized_rows(data, max_elements_, dim_, num_threads); + data = normalized.data(); + scaled_centroids = + index_detail::normalized_rows(centroids, num_clusters_, dim_, num_threads); + centroids = scaled_centroids.data(); + } allocate_storage(cluster_sizes); create_cluster_views(cluster_sizes); @@ -393,6 +458,7 @@ void IVF::construct( void IVF::allocate_storage(const std::vector& cluster_sizes) { ready_ = false; + read_only_ = false; num_removed_ = 0; free_storage(); clusters_.clear(); @@ -477,6 +543,7 @@ void IVF::add( "IVF index must be trained, constructed or loaded before add" ); } + check_writable("add"); if (num_points == 0) { return; } @@ -491,6 +558,11 @@ void IVF::add( throw std::invalid_argument("IVF configuration exceeds addressable storage"); } check_coordinates(data, num_points * dim_, dim_, "IVF add data"); + std::vector normalized; + if (cosine_) { + normalized = index_detail::normalized_rows(data, num_points, dim_, num_threads); + data = normalized.data(); + } // Assign every new point to a cluster std::vector assigned(num_points); @@ -781,6 +853,7 @@ void IVF::reserve(PID cluster_id, size_t num_points) { if (!ready_) { throw std::logic_error("IVF index must be constructed or loaded before reserve"); } + check_writable("reserve"); if (cluster_id >= num_clusters_) { throw std::invalid_argument("IVF cluster ID is out of range"); } @@ -819,6 +892,7 @@ size_t IVF::remove(const PID* ids_to_remove, size_t num_points) { if (!ready_) { throw std::logic_error("IVF index must be constructed or loaded before remove"); } + check_writable("remove"); if (num_points == 0) { return 0; } @@ -869,82 +943,117 @@ void IVF::save(const char* filename) const { if (filename == nullptr || filename[0] == '\0') { throw std::invalid_argument("IVF save filename must not be empty"); } - - // An HNSW initializer writes its sidecar next to the path it is given. - const auto write = [this](const std::string& path) { write_file(path.c_str()); }; - if (initializer_type_ == InitializerType::HNSW) { - index_detail::save_replacing(filename, {detail::kHnswSidecarSuffix}, write); - } else { - index_detail::save_replacing(filename, {}, write); + check_writable("save"); + if (dim_ > kMaxSavedDim) { + throw std::invalid_argument( + "IVF cannot save an index of more than " + std::to_string(kMaxSavedDim) + + " dimensions" + ); } + index_detail::save_replacing(filename, {}, [this](const std::string& path) { + write_file(path.c_str()); + }); } void IVF::write_file(const char* filename) const { + namespace f2 = index_detail::format2; std::ofstream output(io_impl::filesystem_path(filename), std::ios::binary); if (!output.is_open()) { throw std::runtime_error("IVF cannot open index file for writing"); } output.exceptions(std::ios::failbit | std::ios::badbit); - const uint32_t flags = raw_reranking_ ? 1 : 0; - const uint64_t stored_padded_dim = padded_dim_; - output.write(reinterpret_cast(&kFormatMagic), sizeof(kFormatMagic)); - output.write(reinterpret_cast(&kFormatVersion), sizeof(kFormatVersion)); - output.write(reinterpret_cast(&flags), sizeof(flags)); - output.write( - reinterpret_cast(&stored_padded_dim), sizeof(stored_padded_dim) - ); - const auto stored_initializer = static_cast(initializer_type_); - output.write( - reinterpret_cast(&stored_initializer), sizeof(stored_initializer) + f2::Header header; + header.index_kind = f2::IndexKind::Ivf; + header.metric = f2::header_metric(metric_type()); + header.dim = dim_; + header.padded_dim = padded_dim_; + header.code_bits = raw_reranking_ ? 1 : static_cast(ex_bits_ + 1); + header.raw_type = raw_reranking_ ? f2::RawType::Float32 : f2::RawType::None; + header.id_bits = 32; + header.seed = seed_; + header.num_points = max_elements_; + + std::vector rotator( + rabitqlib::detail::rotator_blob_bytes(rotator_type_, dim_, padded_dim_) ); - - // Save metadata - output.write(reinterpret_cast(&max_elements_), sizeof(size_t)); - output.write(reinterpret_cast(&dim_), sizeof(size_t)); - output.write(reinterpret_cast(&num_clusters_), sizeof(size_t)); - output.write(reinterpret_cast(&ex_bits_), sizeof(size_t)); - output.write(reinterpret_cast(&rotator_type_), sizeof(rotator_type_)); - output.write(reinterpret_cast(&metric_type_), sizeof(metric_type_)); - - // Save the number of points in each cluster - std::vector cluster_sizes; - cluster_sizes.reserve(num_clusters_); - for (const auto& cluster : clusters_) { - cluster_sizes.push_back(cluster.num()); - } - output.write( - reinterpret_cast(cluster_sizes.data()), - static_cast(sizeof(size_t) * num_clusters_) + rabitqlib::detail::encode_rotator_blob( + *rotator_, rotator_type_, dim_, seed_, rotator.data() ); - - // Save rotator - rotator_->save(output); - - // Save data: initializer payload, then all batch data, all ex data and all IDs, - // each in cluster order - initializer_->save(output, filename); + std::array params{}; + put_u64(params.data(), num_clusters_); + put_u32(params.data() + 8, static_cast(initializer_type_)); + std::vector cluster_sizes(num_clusters_); + std::vector sizes(sizeof(uint64_t) * num_clusters_); + uint64_t codes_bytes = 0; + uint64_t rerank_bytes = 0; for (size_t i = 0; i < num_clusters_; ++i) { - output.write( - cluster_storage_[i].batch_data(), - static_cast(batch_data_bytes(cluster_sizes[i])) - ); + cluster_sizes[i] = clusters_[i].num(); + put_u64(sizes.data() + (sizeof(uint64_t) * i), cluster_sizes[i]); + codes_bytes += batch_data_bytes(cluster_sizes[i]); + rerank_bytes += has_rerank_data() ? rerank_data_bytes(cluster_sizes[i]) : 0; } + f2::CountingStream routing_size; + initializer_->write(routing_size); + + const auto bytes = [](const auto& buffer) { + return + [&buffer](f2::SectionSink& sink) { sink.write(buffer.data(), buffer.size()); }; + }; + std::vector sections = { + {f2::kRotatorSection, f2::kSectionRequired, rotator.size(), bytes(rotator)}, + {kParamsSection, + f2::kSectionRequired | f2::kSectionChecksummed, + params.size(), + bytes(params)}, + {kClusterSizesSection, + f2::kSectionRequired | f2::kSectionChecksummed, + sizes.size(), + bytes(sizes)}, + {routing_section(initializer_type_), + f2::kSectionRequired, + routing_size.count(), + [this](f2::SectionSink& sink) { + f2::SinkStream stream(sink); + initializer_->write(stream); + }}, + {kCodesSection, + f2::kSectionRequired, + codes_bytes, + [&](f2::SectionSink& sink) { + for (size_t i = 0; i < num_clusters_; ++i) { + sink.write( + cluster_storage_[i].batch_data(), batch_data_bytes(cluster_sizes[i]) + ); + } + }}, + }; if (has_rerank_data()) { - for (size_t i = 0; i < num_clusters_; ++i) { - output.write( - cluster_storage_[i].rerank_data(), - static_cast(rerank_data_bytes(cluster_sizes[i])) - ); - } - } - for (size_t i = 0; i < num_clusters_; ++i) { - output.write( - reinterpret_cast(cluster_storage_[i].ids()), - static_cast(ids_bytes(cluster_sizes[i])) + sections.push_back( + {kRerankSection, + f2::kSectionRequired, + rerank_bytes, + [&](f2::SectionSink& sink) { + for (size_t i = 0; i < num_clusters_; ++i) { + sink.write( + cluster_storage_[i].rerank_data(), + rerank_data_bytes(cluster_sizes[i]) + ); + } + }} ); } - + sections.push_back( + {kIdsSection, + f2::kSectionRequired, + ids_bytes(max_elements_), + [&](f2::SectionSink& sink) { + for (size_t i = 0; i < num_clusters_; ++i) { + sink.write(cluster_storage_[i].ids(), ids_bytes(cluster_sizes[i])); + } + }} + ); + f2::write_file(output, header, sections, RABITQ_LIBRARY_VERSION); output.close(); } @@ -956,14 +1065,27 @@ void IVF::load(const char* filename) { if (!input.is_open()) { throw std::runtime_error("Cannot open IVF index file"); } + if (index_detail::format2::has_magic(input, index_detail::format2::IndexKind::Ivf)) { + IVF loaded; + loaded.read_format2(input); + swap(loaded); + return; + } + // An earlier layout: RABQIDX1, the raw-vector v1 layout or the unversioned one. IVF loaded; - input.exceptions(std::ios::failbit | std::ios::badbit); + // Every group of reads is checked before its values are used. + const auto check_read = [&input] { + if (!input) { + throw FormatError("IVF index file is truncated"); + } + }; input.seekg(0, std::ios::end); const auto file_bytes = static_cast(input.tellg()); input.seekg(0); uint64_t magic = 0; input.read(reinterpret_cast(&magic), sizeof(magic)); + check_read(); const bool explicit_padding = magic == kFormatMagic; if (explicit_padding) { uint32_t version = 0, flags = 0; @@ -971,20 +1093,22 @@ void IVF::load(const char* filename) { input.read(reinterpret_cast(&version), sizeof(version)); input.read(reinterpret_cast(&flags), sizeof(flags)); input.read(reinterpret_cast(&stored_padded_dim), sizeof(stored_padded_dim)); + check_read(); if (version != 1 && version != kFormatVersion) { - throw std::runtime_error("Unsupported IVF index version"); + throw FormatError("Unsupported IVF index version"); } if (flags > 1 || stored_padded_dim > std::numeric_limits::max()) { - throw std::runtime_error("Invalid IVF index metadata"); + throw FormatError("Invalid IVF index metadata"); } loaded.raw_reranking_ = flags == 1; loaded.padded_dim_ = static_cast(stored_padded_dim); if (version >= 2) { uint32_t initializer = 0; input.read(reinterpret_cast(&initializer), sizeof(initializer)); + check_read(); if (initializer < static_cast(InitializerType::Flat) || initializer > static_cast(InitializerType::HNSW)) { - throw std::runtime_error("Invalid IVF initializer type in index file"); + throw FormatError("Invalid IVF initializer type in index file"); } loaded.initializer_type_ = static_cast(initializer); } @@ -992,8 +1116,9 @@ void IVF::load(const char* filename) { loaded.raw_reranking_ = true; uint32_t version = 0; input.read(reinterpret_cast(&version), sizeof(version)); + check_read(); if (version != kRawFormatVersion) { - throw std::runtime_error("Unsupported raw IVF index version"); + throw FormatError("Unsupported raw IVF index version"); } } else { input.seekg(0); @@ -1008,7 +1133,7 @@ void IVF::load(const char* filename) { reinterpret_cast(&loaded.rotator_type_), sizeof(loaded.rotator_type_) ); input.read(reinterpret_cast(&loaded.metric_type_), sizeof(loaded.metric_type_)); - validate_metric_type(loaded.metric_type_); + check_read(); // Missing routing metadata means a historical file. Its payload layout must // follow the original threshold, independently of the current Auto policy. if (loaded.initializer_type_ == InitializerType::Auto) { @@ -1016,13 +1141,14 @@ void IVF::load(const char* filename) { ? InitializerType::Flat : InitializerType::HNSW; } - if (loaded.max_elements_ == 0 || + if ((loaded.metric_type_ != METRIC_L2 && loaded.metric_type_ != METRIC_IP) || + loaded.max_elements_ == 0 || loaded.max_elements_ > buffer::kSearchBufferMaxPointCount || loaded.dim_ == 0 || loaded.num_clusters_ == 0 || loaded.num_clusters_ > buffer::kSearchBufferMaxPointCount || loaded.ex_bits_ > 8 || (loaded.raw_reranking_ && loaded.ex_bits_ != 0) || loaded.dim_ > (std::numeric_limits::max() / 32) - 64) { - throw std::runtime_error("Invalid IVF index metadata"); + throw FormatError("Invalid IVF index metadata"); } if (!explicit_padding) { // Both historical formats omit padded_dim and always used 64-coordinate blocks. @@ -1030,13 +1156,13 @@ void IVF::load(const char* filename) { } if (loaded.padded_dim_ < loaded.dim_ || loaded.padded_dim_ % 32 != 0 || loaded.padded_dim_ > (std::numeric_limits::max() / 32) - 64) { - throw std::runtime_error("Invalid padded dimension in IVF index file"); + throw FormatError("Invalid padded dimension in IVF index file"); } // Bound every payload by the actual file before allocating or multiplying sizes. size_t remaining = file_bytes - static_cast(input.tellg()); const auto consume = [&remaining](size_t count, size_t bytes) { if (bytes != 0 && count > remaining / bytes) { - throw std::runtime_error("Invalid or truncated IVF index payload"); + throw FormatError("Invalid or truncated IVF index payload"); } remaining -= count * bytes; }; @@ -1048,7 +1174,7 @@ void IVF::load(const char* filename) { } else if (loaded.rotator_type_ == RotatorType::FhtKacRotator) { consume(1, loaded.padded_dim_ / 2); } else { - throw std::runtime_error("Invalid IVF rotator type"); + throw FormatError("Invalid IVF rotator type"); } if (loaded.initializer_type_ != InitializerType::HNSW) { consume(loaded.num_clusters_, sizeof(float) * loaded.padded_dim_); @@ -1066,29 +1192,51 @@ void IVF::load(const char* filename) { reinterpret_cast(cluster_sizes.data()), static_cast(sizeof(size_t) * loaded.num_clusters_) ); + check_read(); size_t total = 0; for (size_t size : cluster_sizes) { if (size > loaded.max_elements_ - total) { - throw std::runtime_error("Invalid cluster counts in IVF index file"); + throw FormatError("Invalid cluster counts in IVF index file"); } total += size; consume(div_round_up(size, fastscan::kBatchSize), loaded.batch_bytes()); } if (total != loaded.max_elements_) { - throw std::runtime_error("Invalid cluster counts in IVF index file"); + throw FormatError("Invalid cluster counts in IVF index file"); + } + try { + loaded.rotator_ = rotator_impl::make_rotator_for_loading( + loaded.dim_, loaded.rotator_type_, loaded.padded_dim_ + ); + } catch (const std::invalid_argument& error) { + // Dimensions the stored rotation does not support, such as FHT/Kac below 64. + throw FormatError(std::string("Invalid IVF rotator dimensions: ") + error.what()); } - loaded.rotator_ = rotator_impl::make_rotator_for_loading( - loaded.dim_, loaded.rotator_type_, loaded.padded_dim_ - ); // Load rotator loaded.rotator_->load(input); + check_read(); // Load data: initializer payload, then all batch data, all ex data and all IDs, // each in cluster order loaded.allocate_storage(cluster_sizes); - loaded.initializer_->load(input, filename); + if (loaded.initializer_type_ == InitializerType::HNSW) { + // These layouts kept the routing graph in a sidecar file beside the index. + const std::string sidecar = std::string(filename) + detail::kHnswSidecarSuffix; + std::ifstream graph( + io_impl::filesystem_path(sidecar), std::ios::binary | std::ios::ate + ); + if (!graph) { + throw std::runtime_error("Cannot open HNSW centroid sidecar"); + } + const auto graph_bytes = + static_cast(static_cast(graph.tellg())); + graph.seekg(0); + loaded.initializer_->read(graph, graph_bytes); + } else { + loaded.initializer_->read(input, loaded.flat_routing_bytes()); + } for (size_t i = 0; i < loaded.num_clusters_; ++i) { input.read( loaded.cluster_storage_[i].batch_data(), @@ -1109,37 +1257,243 @@ void IVF::load(const char* filename) { static_cast(ids_bytes(cluster_sizes[i])) ); } - for (size_t i = 0; i < loaded.num_clusters_; ++i) { - for (PID id : loaded.cluster_storage_[i].id_storage) { - if (id >= loaded.max_elements_ || id >= buffer::kSearchBufferCheckedMask) { - throw std::runtime_error("Invalid point ID in IVF index file"); + check_read(); + if (remaining != 0) { + throw FormatError("IVF index file has unexpected trailing data"); + } + loaded.complete_load(cluster_sizes); + + input.close(); + swap(loaded); +} + +void IVF::read_format2(std::istream& input) { + namespace f2 = index_detail::format2; + const std::vector known_kinds = { + f2::kRotatorSection, + kParamsSection, + kClusterSizesSection, + kFlatRoutingSection, + kFlatRaBitQRoutingSection, + kHnswRoutingSection, + kCodesSection, + kRerankSection, + kIdsSection}; + f2::Reader reader(input, f2::IndexKind::Ivf, known_kinds, [](const f2::Header& header) { + if (header.id_bits != 32) { + throw f2::FormatError( + "IVF index file has 64-bit IDs; IVF-RaBitQ stores 32 bits" + ); + } + if (header.raw_type == f2::RawType::Uint8) { + throw f2::FormatError( + "IVF index file has uint8 raw vectors, which IVF-RaBitQ lacks" + ); + } + if (header.code_bits == 0 || + (header.raw_type == f2::RawType::Float32 && header.code_bits != 1)) { + throw f2::FormatError( + "IVF index file has " + std::to_string(header.code_bits) + + " code bits, which its raw vectors do not allow" + ); + } + if (header.num_points == 0 || + header.num_points > buffer::kSearchBufferMaxPointCount) { + throw f2::FormatError( + "IVF index file has an invalid point count " + + std::to_string(header.num_points) + ); + } + if (header.seed.has_value() && + *header.seed > std::numeric_limits::max()) { + throw f2::FormatError("IVF index file has a seed above 32 bits"); + } + }); + const f2::Header& header = reader.header(); + metric_type_ = index_detail::stored_metric(f2::metric_type(header.metric)); + cosine_ = header.metric == f2::Metric::Cosine; + dim_ = static_cast(header.dim); + padded_dim_ = static_cast(header.padded_dim); + raw_reranking_ = header.raw_type == f2::RawType::Float32; + ex_bits_ = raw_reranking_ ? 0 : header.code_bits - 1; + max_elements_ = static_cast(header.num_points); + if (header.seed.has_value()) { + seed_ = static_cast(*header.seed); + } + + // A section of this kind, whose size, when given, must match before it is read. + const auto require = [&reader](uint32_t kind, std::optional size) { + const f2::Section* section = reader.find(kind); + if (section == nullptr) { + throw f2::FormatError( + "IVF index file has no section kind " + std::to_string(kind) + ); + } + if (size.has_value() && section->size != *size) { + throw f2::FormatError( + "IVF index file section kind " + std::to_string(kind) + " has " + + std::to_string(section->size) + " bytes; expected " + std::to_string(*size) + ); + } + return section; + }; + const auto read_all = [&reader](const f2::Section& section) { + std::vector bytes(static_cast(section.size)); + reader.read(section, 0, bytes.data(), bytes.size()); + return bytes; + }; + + const std::vector params = read_all(*require(kParamsSection, kParamsBytes)); + const uint64_t num_clusters = get_u64(params.data()); + const uint32_t initializer = get_u32(params.data() + 8); + if (num_clusters == 0 || num_clusters > buffer::kSearchBufferMaxPointCount) { + throw f2::FormatError( + "IVF index file has an invalid cluster count " + std::to_string(num_clusters) + ); + } + if (initializer < static_cast(InitializerType::Flat) || + initializer > static_cast(InitializerType::HNSW) || + get_u32(params.data() + 12) != 0) { + throw f2::FormatError("IVF index file has invalid routing parameters"); + } + num_clusters_ = static_cast(num_clusters); + initializer_type_ = static_cast(initializer); + + const std::vector sizes = + read_all(*require(kClusterSizesSection, sizeof(uint64_t) * num_clusters_)); + std::vector cluster_sizes(num_clusters_); + uint64_t total = 0; + uint64_t codes_bytes = 0; + uint64_t rerank_bytes = 0; + for (size_t i = 0; i < num_clusters_; ++i) { + const uint64_t size = get_u64(sizes.data() + (sizeof(uint64_t) * i)); + if (size > max_elements_ - total) { + throw f2::FormatError("IVF index file cluster sizes exceed its point count"); + } + total += size; + cluster_sizes[i] = static_cast(size); + codes_bytes += batch_data_bytes(cluster_sizes[i]); + rerank_bytes += has_rerank_data() ? rerank_data_bytes(cluster_sizes[i]) : 0; + } + if (total != max_elements_) { + throw f2::FormatError( + "IVF index file cluster sizes do not add up to its point count" + ); + } + + const std::vector blob = read_all(*require(f2::kRotatorSection, std::nullopt)); + rabitqlib::detail::DecodedRotator rotator; + try { + rotator = rabitqlib::detail::decode_rotator_blob(blob.data(), blob.size()); + } catch (const std::invalid_argument& error) { + throw f2::FormatError( + std::string("IVF index file has an invalid rotator (") + error.what() + ")" + ); + } + if (rotator.dim != dim_ || rotator.padded_dim != padded_dim_) { + throw f2::FormatError("IVF index file rotator does not match its dimensions"); + } + rotator_type_ = rotator.type; + rotator_ = std::move(rotator.rotator); + + const uint32_t routing_kind = routing_section(initializer_type_); + for (const uint32_t kind : + {kFlatRoutingSection, kFlatRaBitQRoutingSection, kHnswRoutingSection}) { + if (kind != routing_kind && reader.find(kind) != nullptr) { + throw f2::FormatError("IVF index file has routing data of another initializer"); + } + } + const f2::Section* routing = require( + routing_kind, + initializer_type_ == InitializerType::HNSW + ? std::nullopt + : std::optional(flat_routing_bytes()) + ); + const f2::Section* codes = require(kCodesSection, codes_bytes); + const f2::Section* rerank = nullptr; + if (has_rerank_data()) { + rerank = require(kRerankSection, rerank_bytes); + } else if (reader.find(kRerankSection) != nullptr) { + throw f2::FormatError( + "IVF index file has rerank data that its code bits do not use" + ); + } + const f2::Section* ids = require(kIdsSection, ids_bytes(max_elements_)); + + allocate_storage(cluster_sizes); + std::istream routing_input(input.rdbuf()); + routing_input.seekg(static_cast(routing->offset)); + initializer_->read(routing_input, routing->size); + // Read each bulk section front to back: a seek per cluster would discard the file + // buffer every time. + f2::SectionInput codes_input = reader.open(*codes); + for (size_t i = 0; i < num_clusters_; ++i) { + codes_input.read( + cluster_storage_[i].batch_data(), batch_data_bytes(cluster_sizes[i]) + ); + } + if (rerank != nullptr) { + f2::SectionInput rerank_input = reader.open(*rerank); + for (size_t i = 0; i < num_clusters_; ++i) { + rerank_input.read( + cluster_storage_[i].rerank_data(), rerank_data_bytes(cluster_sizes[i]) + ); + } + } + f2::SectionInput ids_input = reader.open(*ids); + for (size_t i = 0; i < num_clusters_; ++i) { + ids_input.read(cluster_storage_[i].ids(), ids_bytes(cluster_sizes[i])); + } + complete_load(cluster_sizes); + read_only_ = reader.read_only(); +} + +size_t IVF::flat_routing_bytes() const { + const size_t centroids = sizeof(float) * num_clusters_ * padded_dim_; + if (initializer_type_ == InitializerType::FlatRaBitQ) { + return centroids + (sizeof(float) * padded_dim_) + + (div_round_up(num_clusters_, fastscan::kBatchSize) * batch_bytes()); + } + return centroids; +} + +void IVF::complete_load(const std::vector& cluster_sizes) { + for (size_t i = 0; i < num_clusters_; ++i) { + for (PID id : cluster_storage_[i].id_storage) { + if (id >= max_elements_ || id >= buffer::kSearchBufferCheckedMask) { + throw FormatError("Invalid point ID in IVF index file"); } } } - loaded.create_cluster_views(cluster_sizes); + create_cluster_views(cluster_sizes); // Removal markers are already persisted, including in historical files. // Count only logical rows: FastScan padding lanes are not stored points. - for (const auto& cluster : loaded.clusters_) { + for (const auto& cluster : clusters_) { for (size_t first = 0; first < cluster.num(); first += fastscan::kBatchSize) { ConstBatchDataMap batch( - cluster.batch_data() + - (first / fastscan::kBatchSize) * loaded.batch_bytes(), - loaded.padded_dim_ + cluster.batch_data() + (first / fastscan::kBatchSize) * batch_bytes(), + padded_dim_ ); const size_t batch_size = std::min(fastscan::kBatchSize, cluster.num() - first); for (size_t lane = 0; lane < batch_size; ++lane) { - loaded.num_removed_ += batch.f_add()[lane] == kRemovedFAdd; + num_removed_ += batch.f_add()[lane] == kRemovedFAdd; } } } - if (remaining != 0) { - throw std::runtime_error("IVF index file has unexpected trailing data"); - } - loaded.ready_ = true; + ready_ = true; +} - input.close(); - swap(loaded); +void IVF::check_writable(const char* operation) const { + if (read_only_) { + throw std::logic_error( + std::string( + "IVF index was loaded from a file with features this release " + "cannot update, so it cannot " + ) + + operation + ); + } } void IVF::search( @@ -1168,6 +1522,12 @@ void IVF::search( ) const { validate_search(query, k, nprobe, result_ids); check_coordinates(query, dim_, dim_, "IVF search query"); + std::vector normalized_query; + if (cosine_) { + normalized_query.resize(dim_); + index_detail::normalize_vector(query, normalized_query.data(), dim_); + query = normalized_query.data(); + } nprobe = std::min(nprobe, num_clusters_); // Probe at most every cluster std::vector rotated_query(padded_dim_); diff --git a/src/index/ivf_index.cpp b/src/index/ivf_index.cpp new file mode 100644 index 00000000..d6431c56 --- /dev/null +++ b/src/index/ivf_index.cpp @@ -0,0 +1,225 @@ +#include "rabitqlib/index/ivf_index.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "index_facade.hpp" +#include "rabitqlib/clustering/rabitqkmeans.hpp" +#include "rabitqlib/core/types.hpp" +#include "rabitqlib/index/ivf/ivf.hpp" +#include "rabitqlib/index/training.hpp" + +namespace rabitqlib { + +namespace { +using rabitqkmeans::RaBitQKMeansParameters; + +// num_clusters / 16, rounded, and at least 1. +size_t default_nprobe(size_t num_clusters) { + return std::max(1, (num_clusters + 8) / 16); +} +} // namespace + +IvfIndex::IvfIndex(size_t dim, size_t num_clusters, const IvfOptions& options) { + const uint32_t seed = options.seed.has_value() ? *options.seed : std::random_device{}(); + index_ = std::make_unique( + dim, + num_clusters, + options.nbits, + options.metric, + seed, + RotatorType::FhtKacRotator, + options.routing + ); + cp_ = std::make_unique( + default_training_parameters(options.metric, seed) + ); +} + +IvfIndex::IvfIndex( + std::unique_ptr index, std::unique_ptr cp +) + : index_(std::move(index)), cp_(std::move(cp)) {} + +IvfIndex::IvfIndex(IvfIndex&& other) noexcept = default; +IvfIndex& IvfIndex::operator=(IvfIndex&& other) noexcept = default; +IvfIndex::~IvfIndex() = default; + +IvfIndex IvfIndex::load(const char* filename) { + auto index = std::make_unique(); + index->load(filename); + // Files from releases up to 0.8 do not record the seed. + const auto seed = index->seed().value_or(RaBitQKMeansParameters{}.seed); + auto cp = std::make_unique( + default_training_parameters(index->metric_type(), seed) + ); + return IvfIndex(std::move(index), std::move(cp)); +} + +void IvfIndex::save(const char* filename) const { + check_trained("save"); + if (index_->num_stored_points() == 0) { + throw std::logic_error("IvfIndex has no points to save; add points first"); + } + index_->save(filename); +} + +RaBitQKMeansParameters& IvfIndex::cp() { return *cp_; } + +const RaBitQKMeansParameters& IvfIndex::cp() const { return *cp_; } + +void IvfIndex::train( + const float* data, size_t num_points, std::optional num_threads +) { + check_trainable(); + index_->train(num_points, data, training_parameters(num_threads)); +} + +void IvfIndex::set_centroids(const float* centroids, size_t num_threads) { + check_trainable(); + index_->set_centroids(centroids, num_threads); +} + +Id IvfIndex::add(const float* data, size_t num_points, const AddOptions& options) { + const bool trains = + !index_->is_trained() && options.cluster_ids == nullptr && num_points > 0; + if (!trains) { + check_trained("add"); + } + const auto first = static_cast(index_->num_stored_points()); + const size_t num_threads = options.num_threads.value_or(0); + if (!trains) { + index_->add( + data, num_points, options.cluster_ids, options.fast_quantization, num_threads + ); + return first; + } + if (num_points < index_->num_clusters()) { + throw std::invalid_argument( + "the first add trains the index and needs at least num_clusters rows; " + "expected at least " + + std::to_string(index_->num_clusters()) + ", got shape (" + + std::to_string(num_points) + ", " + std::to_string(index_->dimension()) + ")" + ); + } + // Train and fill a new index with the same settings and rotation seed, then move it + // in, so that a failure leaves this index untrained and empty. Only a loaded index + // lacks a seed, and it is trained. + auto staged = std::make_unique( + index_->dimension(), + index_->num_clusters(), + index_->nbits(), + index_->metric_type(), + index_->seed().value(), + RotatorType::FhtKacRotator, + index_->initializer_type() + ); + staged->train(num_points, data, training_parameters(options.num_threads)); + staged->add(data, num_points, nullptr, options.fast_quantization, num_threads); + index_ = std::move(staged); + return first; +} + +size_t IvfIndex::remove(const Id* ids, size_t num_ids) { + check_trained("remove"); + if (num_ids != 0 && ids == nullptr) { + throw std::invalid_argument("IvfIndex remove ids must not be null"); + } + const size_t num_stored = index_->num_stored_points(); + std::vector row_ids(num_ids); + for (size_t i = 0; i < num_ids; ++i) { + if (ids[i] < 0 || static_cast(ids[i]) >= num_stored) { + throw std::invalid_argument("ids must be in [0, num_stored_points)"); + } + row_ids[i] = static_cast(ids[i]); + } + return index_->remove(row_ids.data(), row_ids.size()); +} + +void IvfIndex::reserve_cluster(size_t cluster_id, size_t num_points) { + check_trained("reserve_cluster"); + if (cluster_id >= index_->num_clusters()) { + throw std::invalid_argument("cluster_id must be in [0, num_clusters)"); + } + index_->reserve(static_cast(cluster_id), num_points); +} + +void IvfIndex::search( + const float* queries, + size_t num_queries, + size_t k, + Id* ids, + float* distances, + const IvfSearchOptions& options +) const { + check_trained("search"); + index_facade::check_k(k); + index_facade::check_breadth(options.nprobe, "nprobe"); + if (num_queries == 0) { + return; + } + 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( + queries, + num_queries, + k, + options.nprobe.value_or(default_nprobe(index_->num_clusters())), + row_ids.data(), + distances, + options.high_accuracy, + options.num_threads + ); + std::transform(row_ids.begin(), row_ids.end(), ids, [](PID id) { + return id == kPidMax ? kNoId : static_cast(id); + }); +} + +size_t IvfIndex::dim() const { return index_->dimension(); } + +size_t IvfIndex::num_clusters() const { return index_->num_clusters(); } + +size_t IvfIndex::nbits() const { return index_->nbits(); } + +MetricType IvfIndex::metric() const { return index_->metric_type(); } + +ivf::Routing IvfIndex::routing() const { return index_->initializer_type(); } + +std::optional IvfIndex::seed() const { return index_->seed(); } + +size_t IvfIndex::num_points() const { return index_->num_points(); } + +size_t IvfIndex::num_stored_points() const { return index_->num_stored_points(); } + +bool IvfIndex::is_trained() const { return index_->is_trained(); } + +void IvfIndex::check_trained(const char* operation) const { + if (!index_->is_trained()) { + throw std::logic_error( + std::string("IvfIndex must be trained or loaded before ") + operation + ); + } +} + +void IvfIndex::check_trainable() const { + if (index_->num_stored_points() != 0) { + throw std::logic_error("IvfIndex cannot be trained once it stores points"); + } +} + +RaBitQKMeansParameters IvfIndex::training_parameters( + std::optional num_threads +) const { + return index_facade::with_num_threads(*cp_, num_threads); +} + +} // namespace rabitqlib diff --git a/src/index/ivf_initializer.cpp b/src/index/ivf_initializer.cpp index cbaf7e00..4fb51a55 100644 --- a/src/index/ivf_initializer.cpp +++ b/src/index/ivf_initializer.cpp @@ -2,10 +2,12 @@ #include #include #include +#include #include -#include #include +#include #include +#include #include #include @@ -17,6 +19,7 @@ #include "rabitqlib/fastscan/query.hpp" #include "rabitqlib/index/detail/buffer.hpp" #include "rabitqlib/index/detail/parallel_for.hpp" +#include "rabitqlib/index/format_error.hpp" #include "rabitqlib/index/ivf/initializer.hpp" #include "rabitqlib/index/types.hpp" #include "rabitqlib/utils/space.hpp" @@ -163,7 +166,7 @@ void FlatRaBitQInitializer::centroids_distances( } } -void FlatRaBitQInitializer::save(std::ofstream& output, const char* /*filename*/) const { +void FlatRaBitQInitializer::write(std::ostream& output) const { output.write( reinterpret_cast(centroids_.data()), static_cast(centroids_.size() * sizeof(float)) @@ -181,7 +184,11 @@ void FlatRaBitQInitializer::save(std::ofstream& output, const char* /*filename*/ } } -void FlatRaBitQInitializer::load(std::ifstream& input, const char* /*filename*/) { +void FlatRaBitQInitializer::read(std::istream& input, uint64_t bytes) { + if (bytes != sizeof(float) * (centroids_.size() + global_centroid_.size()) + + batch_data_.size()) { + throw FormatError("IVF Flat RaBitQ initializer data has the wrong size"); + } input.read( reinterpret_cast(centroids_.data()), static_cast(centroids_.size() * sizeof(float)) @@ -195,7 +202,7 @@ void FlatRaBitQInitializer::load(std::ifstream& input, const char* /*filename*/) static_cast(batch_data_.size()) ); if (!input) { - throw std::runtime_error("IVF Flat RaBitQ initializer cannot be read"); + throw FormatError("IVF Flat RaBitQ initializer cannot be read"); } } } // namespace rabitqlib::ivf diff --git a/src/index/qg.cpp b/src/index/qg.cpp index 02da4bed..f0794b77 100644 --- a/src/index/qg.cpp +++ b/src/index/qg.cpp @@ -1,6 +1,7 @@ #include "rabitqlib/index/symqg/qg.hpp" #include +#include #include #include #include @@ -15,7 +16,10 @@ #include #include +#include "../core/blob.hpp" +#include "cosine.hpp" #include "file_replacement.hpp" +#include "format2.hpp" #include "rabitqlib/core/data_layout.hpp" #include "rabitqlib/core/encoder.hpp" #include "rabitqlib/core/metric.hpp" @@ -29,6 +33,7 @@ #include "rabitqlib/index/detail/buffer.hpp" #include "rabitqlib/index/detail/parallel_exception.hpp" #include "rabitqlib/index/detail/visited_set.hpp" +#include "rabitqlib/index/format_error.hpp" #include "rabitqlib/index/symqg/detail/search_scratch.hpp" #include "rabitqlib/index/types.hpp" #include "rabitqlib/utils/bitops.hpp" @@ -45,6 +50,15 @@ namespace { // Native-endian numeric tag; little-endian files contain the bytes "QTIBARGQ". constexpr uint64_t kFormatMagic = 0x5147524142495451ULL; constexpr uint32_t kFormatVersion = 1; + +// Index format 2 sections of SymphonyQG (docs/formats.md, "Section kinds"). +constexpr uint32_t kParamsSection = 768; +constexpr uint32_t kCentroidSection = 769; +constexpr uint32_t kRecordsSection = 770; +constexpr size_t kParamsBytes = 32; +// The stored initialization: 0 is unknown. +constexpr uint32_t kInitPiPNN = 1; +constexpr uint32_t kInitRandom = 2; } // namespace QuantizedQuery::QuantizedQuery( @@ -101,7 +115,9 @@ size_t QuantizedGraph::degree_bound() const { return max_degree_; } PID QuantizedGraph::entry_point() const { return entry_point_id_; } -MetricType QuantizedGraph::metric_type() const { return metric_type_; } +MetricType QuantizedGraph::metric_type() const { + return cosine_ ? METRIC_COSINE : metric_type_; +} size_t QuantizedGraph::quantization_bits() const { return quantization_bits_; } @@ -136,10 +152,12 @@ QuantizedGraph::QuantizedGraph( , max_degree_(max_degree) , dim_(dim) , padded_dim_(dim) - , metric_type_(metric_type) + , metric_type_(index_detail::stored_metric(metric_type)) + , cosine_(metric_type == METRIC_COSINE) , rotator_type_(rotator_type) , quantization_bits_(quantization_bits) - , seed_(seed) { + , seed_(seed) + , seed_known_(true) { validate_configuration(); padded_dim_ = padded_dimension(dim_); initialize(); @@ -262,54 +280,228 @@ void QuantizedGraph::save(const char* filename) const { if (filename == nullptr || filename[0] == '\0') { throw std::invalid_argument("QuantizedGraph save filename must not be empty"); } + if (read_only_) { + throw std::logic_error( + "QuantizedGraph was loaded from a file with features this release cannot " + "update, so it cannot save" + ); + } index_detail::save_replacing(filename, {}, [this](const std::string& path) { write_file(path.c_str()); }); } void QuantizedGraph::write_file(const char* filename) const { + namespace f2 = index_detail::format2; std::ofstream output(io_impl::filesystem_path(filename), std::ios::binary); if (!output.is_open()) { throw std::runtime_error("QuantizedGraph cannot open file for writing"); } output.exceptions(std::ios::badbit | std::ios::failbit); + f2::Header header; + header.index_kind = f2::IndexKind::SymphonyQg; + header.metric = f2::header_metric(metric_type()); + header.dim = dim_; + header.padded_dim = padded_dim_; + header.code_bits = static_cast(quantization_bits_); + header.raw_type = quantization_bits_ == 0 ? f2::RawType::Float32 : f2::RawType::None; + header.id_bits = 32; + if (seed_known_) { + header.seed = seed_; + } + header.num_points = max_elements_; + + std::vector rotator( + rabitqlib::detail::rotator_blob_bytes(rotator_type_, dim_, padded_dim_) + ); + rabitqlib::detail::encode_rotator_blob( + *rotator_, rotator_type_, dim_, seed(), rotator.data() + ); + std::array params{}; + f2::put_u64(params.data(), max_degree_); + f2::put_u64(params.data() + 8, entry_point_id_); + f2::put_u64(params.data() + 16, ef_construction_); + uint32_t init = 0; + if (initialization_.has_value()) { + init = *initialization_ == QGInitialization::PiPNN ? kInitPiPNN : kInitRandom; + } + f2::put_u32(params.data() + 24, init); + + const auto bytes = [](const auto& buffer) { + return + [&buffer](f2::SectionSink& sink) { sink.write(buffer.data(), buffer.size()); }; + }; + std::vector sections = { + {f2::kRotatorSection, f2::kSectionRequired, rotator.size(), bytes(rotator)}, + {kParamsSection, + f2::kSectionRequired | f2::kSectionChecksummed, + params.size(), + bytes(params)}, + }; if (quantization_bits_ != 0) { - output.write(reinterpret_cast(&kFormatMagic), sizeof(kFormatMagic)); - output.write( - reinterpret_cast(&kFormatVersion), sizeof(kFormatVersion) + sections.push_back( + {kCentroidSection, + f2::kSectionRequired, + padded_dim_ * sizeof(float), + [this](f2::SectionSink& sink) { + sink.write(centroid_.data(), padded_dim_ * sizeof(float)); + }} ); } + const size_t data_bytes = checked_multiply(max_elements_, record_bytes_); + sections.push_back( + {kRecordsSection, + f2::kSectionRequired, + data_bytes, + [this, data_bytes](f2::SectionSink& sink) { + sink.write(get_row_data(0), data_bytes); + }} + ); + f2::write_file(output, header, sections, RABITQ_LIBRARY_VERSION); + output.close(); +} - // Basic variants - output.write(reinterpret_cast(&max_elements_), sizeof(size_t)); - output.write(reinterpret_cast(&max_degree_), sizeof(size_t)); - output.write(reinterpret_cast(&dim_), sizeof(size_t)); - output.write(reinterpret_cast(&padded_dim_), sizeof(size_t)); - output.write(reinterpret_cast(&entry_point_id_), sizeof(PID)); - output.write(reinterpret_cast(&rotator_type_), sizeof(RotatorType)); - output.write(reinterpret_cast(&metric_type_), sizeof(MetricType)); - if (quantization_bits_ != 0) { - output.write( - reinterpret_cast(&quantization_bits_), sizeof(quantization_bits_) +void QuantizedGraph::read_format2(std::istream& input) { + namespace f2 = index_detail::format2; + const std::vector known_kinds = { + f2::kRotatorSection, kParamsSection, kCentroidSection, kRecordsSection}; + f2::Reader reader( + input, f2::IndexKind::SymphonyQg, known_kinds, [](const f2::Header& header) { + const bool raw = + header.code_bits == 0 && header.raw_type == f2::RawType::Float32; + const bool quantized = (header.code_bits == 4 || header.code_bits == 8) && + header.raw_type == f2::RawType::None; + if (header.id_bits != 32 || (!raw && !quantized)) { + throw f2::FormatError( + "QuantizedGraph index file stores neither raw vectors nor 4- or 8-bit " + "codes with 32-bit IDs" + ); + } + if (header.seed.has_value() && + *header.seed > std::numeric_limits::max()) { + throw f2::FormatError("QuantizedGraph index file has a seed above 32 bits"); + } + } + ); + const f2::Header& header = reader.header(); + metric_type_ = index_detail::stored_metric(f2::metric_type(header.metric)); + cosine_ = header.metric == f2::Metric::Cosine; + dim_ = static_cast(header.dim); + padded_dim_ = static_cast(header.padded_dim); + quantization_bits_ = header.code_bits; + max_elements_ = static_cast(header.num_points); + seed_known_ = header.seed.has_value(); + seed_ = static_cast(header.seed.value_or(0)); + + const auto require = [&reader](uint32_t kind, std::optional size) { + const f2::Section* section = reader.find(kind); + if (section == nullptr) { + throw f2::FormatError( + "QuantizedGraph index file has no section kind " + std::to_string(kind) + ); + } + if (size.has_value() && section->size != *size) { + throw f2::FormatError( + "QuantizedGraph index file section kind " + std::to_string(kind) + " has " + + std::to_string(section->size) + " bytes; expected " + std::to_string(*size) + ); + } + return section; + }; + const auto read_all = [&reader](const f2::Section& section) { + std::vector bytes(static_cast(section.size)); + reader.read(section, 0, bytes.data(), bytes.size()); + return bytes; + }; + + const std::vector blob = read_all(*require(f2::kRotatorSection, std::nullopt)); + rabitqlib::detail::DecodedRotator rotator; + try { + rotator = rabitqlib::detail::decode_rotator_blob(blob.data(), blob.size()); + } catch (const std::invalid_argument& error) { + throw f2::FormatError( + std::string("QuantizedGraph index file has an invalid rotator (") + + error.what() + ")" ); - output.write( - reinterpret_cast(centroid_.data()), - static_cast(padded_dim_ * sizeof(float)) + } + if (rotator.dim != dim_ || rotator.padded_dim != padded_dim_) { + throw f2::FormatError( + "QuantizedGraph index file rotator does not match its dimensions" + ); + } + rotator_type_ = rotator.type; + + const std::vector params = read_all(*require(kParamsSection, kParamsBytes)); + const uint64_t max_degree = f2::get_u64(params.data()); + const uint64_t entry_point = f2::get_u64(params.data() + 8); + const uint32_t init = f2::get_u32(params.data() + 24); + if (max_degree > max_elements_ || entry_point >= max_elements_ || init > kInitRandom || + f2::get_u32(params.data() + 28) != 0) { + throw f2::FormatError("QuantizedGraph index file has invalid graph parameters"); + } + max_degree_ = static_cast(max_degree); + entry_point_id_ = static_cast(entry_point); + ef_construction_ = static_cast(f2::get_u64(params.data() + 16)); + if (init != 0) { + initialization_ = + init == kInitPiPNN ? QGInitialization::PiPNN : QGInitialization::Random; + } + try { + validate_configuration(); + } catch (const std::invalid_argument& error) { + throw f2::FormatError( + std::string("QuantizedGraph index file is invalid: ") + error.what() ); } - // Data - output.write( - get_row_data(0), - static_cast(checked_multiply(max_elements_, record_bytes_)) - ); + size_t data_bytes = 0; + try { + initialize_layout(); + data_bytes = checked_multiply(max_elements_, record_bytes_); + } catch (const std::length_error&) { + throw f2::FormatError( + "QuantizedGraph index file describes records too large to address" + ); + } + const f2::Section* centroid = nullptr; + if (quantization_bits_ != 0) { + centroid = require(kCentroidSection, padded_dim_ * sizeof(float)); + } else if (reader.find(kCentroidSection) != nullptr) { + throw f2::FormatError( + "QuantizedGraph index file has a centroid but stores raw vectors" + ); + } + const f2::Section* records = require(kRecordsSection, data_bytes); + + initialize(false); + rotator_ = std::move(rotator.rotator); + if (centroid != nullptr) { + centroid_.resize(padded_dim_); + reader.open(*centroid).read(centroid_.data(), padded_dim_ * sizeof(float)); + } + reader.open(*records).read(get_row_data(0), data_bytes); + read_only_ = reader.read_only(); + for (PID source = 0; source < max_elements_; ++source) { + const auto neighbors = get_neighbors(source); + for (size_t i = 0; i < max_degree_; ++i) { + if (neighbors[i] >= max_elements_) { + throw FormatError("QuantizedGraph neighbor ID is invalid"); + } + } + } +} - // Rotator - rotator_->save(output); +std::optional QuantizedGraph::seed() const { + return seed_known_ ? std::optional(seed_) : std::nullopt; +} - output.flush(); - output.close(); +std::optional QuantizedGraph::ef_construction() const { + return ef_construction_ != 0 ? std::optional(ef_construction_) : std::nullopt; +} + +std::optional QuantizedGraph::initialization() const { + return initialization_; } void QuantizedGraph::load(const char* filename) { @@ -324,16 +516,27 @@ void QuantizedGraph::load(const char* filename) { if (!input.is_open()) { throw std::runtime_error("QuantizedGraph cannot open file"); } + if (index_detail::format2::has_magic( + input, index_detail::format2::IndexKind::SymphonyQg + )) { + QuantizedGraph loaded; + loaded.read_format2(input); + // ef_search is a runtime search setting rather than persisted index state. + loaded.default_ef_search_ = default_ef_search_; + loaded.ready_ = true; + *this = std::move(loaded); + return; + } auto read_exact = [&](void* destination, size_t bytes, const char* field) { if (bytes > static_cast(std::numeric_limits::max())) { - throw std::runtime_error("QuantizedGraph field is too large to read"); + throw FormatError("QuantizedGraph field is too large to read"); } input.read( reinterpret_cast(destination), static_cast(bytes) ); if (!input) { - throw std::runtime_error( + throw FormatError( std::string("QuantizedGraph file is truncated while reading ") + field ); } @@ -348,7 +551,7 @@ void QuantizedGraph::load(const char* filename) { uint32_t version = 0; read_value(version, "format version"); if (version != kFormatVersion) { - throw std::runtime_error("QuantizedGraph file version is unsupported"); + throw FormatError("QuantizedGraph file version is unsupported"); } } else { // Files produced before qg-quant have no header and always contain raw vectors. @@ -371,27 +574,37 @@ void QuantizedGraph::load(const char* filename) { loaded.quantization_bits_ = 0; } - loaded.validate_configuration(); + try { + loaded.validate_configuration(); + } catch (const std::invalid_argument& error) { + throw FormatError(error.what()); // stored settings that do not fit + } if (stored_padded_dim < loaded.dim_ || stored_padded_dim % 32 != 0) { - throw std::runtime_error("QuantizedGraph file has an invalid padded dimension"); + throw FormatError("QuantizedGraph file has an invalid padded dimension"); } // Older files use 64-coordinate padding. Their saved rotation and codes must // retain that dimension, including when initialize() allocates the row storage. loaded.padded_dim_ = stored_padded_dim; - loaded.initialize_layout(); - - const size_t centroid_bytes = loaded.quantization_bits_ == 0 - ? 0 - : checked_multiply(loaded.padded_dim_, sizeof(float)); - const size_t data_bytes = checked_multiply(loaded.max_elements_, loaded.record_bytes_); - const size_t rotator_bytes = - loaded.rotator_type_ == RotatorType::MatrixRotator - ? checked_multiply( - checked_multiply(sizeof(float), loaded.dim_), loaded.padded_dim_ - ) - : checked_multiply(loaded.padded_dim_, size_t{4}) / 8; - const size_t expected_payload_bytes = - checked_add(checked_add(centroid_bytes, data_bytes), rotator_bytes); + size_t centroid_bytes = 0; + size_t data_bytes = 0; + size_t expected_payload_bytes = 0; + try { + loaded.initialize_layout(); + centroid_bytes = loaded.quantization_bits_ == 0 + ? 0 + : checked_multiply(loaded.padded_dim_, sizeof(float)); + data_bytes = checked_multiply(loaded.max_elements_, loaded.record_bytes_); + const size_t rotator_bytes = + loaded.rotator_type_ == RotatorType::MatrixRotator + ? checked_multiply( + checked_multiply(sizeof(float), loaded.dim_), loaded.padded_dim_ + ) + : checked_multiply(loaded.padded_dim_, size_t{4}) / 8; + expected_payload_bytes = + checked_add(checked_add(centroid_bytes, data_bytes), rotator_bytes); + } catch (const std::length_error&) { + throw FormatError("QuantizedGraph file describes records too large to address"); + } const auto payload_position = input.tellg(); if (payload_position < 0) { @@ -401,10 +614,15 @@ void QuantizedGraph::load(const char* filename) { const size_t payload_offset = static_cast(payload_position); if (payload_offset > file_size || file_size - payload_offset != expected_payload_bytes) { - throw std::runtime_error("QuantizedGraph payload size is invalid"); + throw FormatError("QuantizedGraph payload size is invalid"); } - loaded.initialize(false); + try { + loaded.initialize(false); + } catch (const std::invalid_argument& error) { + // Dimensions the stored rotation does not support, such as FHT/Kac below 64. + throw FormatError(std::string("QuantizedGraph file is invalid: ") + error.what()); + } if (loaded.quantization_bits_ != 0) { loaded.centroid_.resize(loaded.padded_dim_); @@ -417,14 +635,14 @@ void QuantizedGraph::load(const char* filename) { const auto neighbors = loaded.get_neighbors(source); for (size_t i = 0; i < loaded.max_degree_; ++i) { if (neighbors[i] >= loaded.max_elements_) { - throw std::runtime_error("QuantizedGraph neighbor ID is invalid"); + throw FormatError("QuantizedGraph neighbor ID is invalid"); } } } loaded.rotator_->load(input); if (!input) { - throw std::runtime_error("QuantizedGraph file is truncated while reading rotator"); + throw FormatError("QuantizedGraph file is truncated while reading rotator"); } input.close(); @@ -854,6 +1072,13 @@ void QuantizedGraph::search_with_scratch_impl( throw std::invalid_argument("QuantizedGraph visited set must be initialized"); } + if (cosine_) { + // Every search path ends here; the buffer is reused across this thread's queries. + thread_local std::vector normalized_query; + normalized_query.resize(dim_); + index_detail::normalize_vector(query, normalized_query.data(), dim_); + query = normalized_query.data(); + } rotator_->rotate(query, scratch.rotated_query); std::optional quantized_query; if (quantization_bits_ != 0) { diff --git a/src/index/qg_builder.cpp b/src/index/qg_builder.cpp index 470a2f78..4204ebee 100644 --- a/src/index/qg_builder.cpp +++ b/src/index/qg_builder.cpp @@ -15,6 +15,7 @@ #include #include +#include "cosine.hpp" #include "rabitqlib/core/rotator.hpp" #include "rabitqlib/fastscan/query.hpp" #include "rabitqlib/index/detail/buffer.hpp" @@ -79,6 +80,11 @@ QGBuilder::QGBuilder( throw std::invalid_argument("QuantizedGraph initialization is invalid"); } initialization_ = init; + // The graph records its construction settings for its index file. Rebuilding replaces + // whatever unknown features a loaded file described. + qg_.ef_construction_ = ef_construction; + qg_.initialization_ = init; + qg_.read_only_ = false; reset(data); } @@ -105,6 +111,13 @@ void QGBuilder::reset(const float* data) { throw std::invalid_argument("QuantizedGraph build data must not be null"); } check_coordinates(data, num_points_ * dim_, dim_, "QuantizedGraph build data"); + // The graph keeps its own copy of the vectors, so the normalized rows can go + // when reset returns. + std::vector normalized; + if (qg_.cosine_) { + normalized = index_detail::normalized_rows(data, num_points_, dim_, num_workers_); + data = normalized.data(); + } if (initialization_ == QGInitialization::PiPNN) { auto initial = detail::build_initial_graph( data, num_points_, dim_, max_degree_, qg_.metric_type_, num_workers_ 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 879b224f..8a11272b 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -40,10 +40,20 @@ add_executable(rabitq_tests ${UNIT_TESTS} ) target_include_directories(rabitq_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/common) +target_include_directories(rabitq_tests PRIVATE ${PROJECT_SOURCE_DIR}/src/core) +target_compile_definitions(rabitq_tests PRIVATE + RABITQ_TEST_LIBRARY_VERSION="${PROJECT_VERSION}" +) if(RABITQ_BUILD_INDEX) target_include_directories(rabitq_tests PRIVATE ${PROJECT_SOURCE_DIR}/src/index) endif() +set_source_files_properties(unit/rabitqlib/utils/blob_test.cpp + PROPERTIES COMPILE_DEFINITIONS + "RABITQ_QUANT_FIXTURE_ROOT=\"${CMAKE_CURRENT_SOURCE_DIR}/python/fixtures/quant\"") set_source_files_properties(unit/rabitqlib/index/historical_persistence_test.cpp + unit/rabitqlib/index/ivf_index_test.cpp + 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) @@ -68,6 +78,11 @@ add_test(NAME CoreOpenMPFlagCheck COMMAND "${CMAKE_COMMAND}" "-DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/openmp-flag-check" -P "${CMAKE_CURRENT_SOURCE_DIR}/core_consumer/check_no_openmp_test.cmake") +add_test(NAME PackageVersionCompatibility COMMAND "${CMAKE_COMMAND}" + "-DVERSION_FILE=${PROJECT_BINARY_DIR}/rabitqlibConfigVersion.cmake" + "-DPROJECT_VERSION=${PROJECT_VERSION}" + -P "${CMAKE_CURRENT_SOURCE_DIR}/core_consumer/check_package_version.cmake") + add_executable(core_api_v1_consumer fixtures/core_api_v1/consumer.cpp) target_link_libraries(core_api_v1_consumer PRIVATE rabitqlib::core) add_test(NAME CoreApiV1Consumer COMMAND core_api_v1_consumer) @@ -134,6 +149,11 @@ if(RABITQ_BUILD_INDEX) rabitq_configure_target(hnsw_add_allocation_test) gtest_discover_tests(hnsw_add_allocation_test DISCOVERY_MODE PRE_TEST) + add_executable(ivf_index_allocation_test failures/ivf_index_allocation_test.cpp) + target_link_libraries(ivf_index_allocation_test PRIVATE GTest::gtest_main rabitqlib::index) + rabitq_configure_target(ivf_index_allocation_test) + gtest_discover_tests(ivf_index_allocation_test DISCOVERY_MODE PRE_TEST) + endif() # Message to verify files are found diff --git a/tests/common/cosine.hpp b/tests/common/cosine.hpp new file mode 100644 index 00000000..401f295c --- /dev/null +++ b/tests/common/cosine.hpp @@ -0,0 +1,64 @@ +#ifndef RABITQ_TEST_COSINE_HPP +#define RABITQ_TEST_COSINE_HPP + +#include + +#include +#include +#include +#include +#include + +#include "format2_file.hpp" + +namespace rabitq_test { + +// The normalization the cosine metric specifies: the squared norm summed in double in +// coordinate order, then each coordinate times 1 / sqrt of it, rounded to float. A zero +// row stays zero. +inline std::vector normalized_rows(const std::vector& rows, size_t dim) { + std::vector normalized(rows.size()); + for (size_t begin = 0; begin < rows.size(); begin += dim) { + double squared_norm = 0; + for (size_t i = begin; i < begin + dim; ++i) { + squared_norm += static_cast(rows[i]) * rows[i]; + } + const double scale = squared_norm > 0 ? 1.0 / std::sqrt(squared_norm) : 0.0; + for (size_t i = begin; i < begin + dim; ++i) { + normalized[i] = static_cast(rows[i] * scale); + } + } + return normalized; +} + +// Scale row i by 1 + i % 7, so that the rows' norms differ. +inline std::vector rescaled_rows(std::vector rows, size_t dim) { + for (size_t i = 0; i < rows.size(); ++i) { + rows[i] *= static_cast(1 + ((i / dim) % 7)); + } + return rows; +} + +// A cosine index stores what an inner-product index of the normalized vectors stores: +// the two files differ only in the header's metric field. +inline void expect_same_sections_except_metric( + const std::string& cosine_path, + const std::string& ip_path, + format2::IndexKind kind, + const std::vector& known_kinds +) { + const auto cosine = read_format2_file(cosine_path, kind, known_kinds); + const auto ip = read_format2_file(ip_path, kind, known_kinds); + EXPECT_EQ(cosine.header.metric, format2::Metric::Cosine); + EXPECT_EQ(ip.header.metric, format2::Metric::InnerProduct); + ASSERT_EQ(cosine.sections.size(), ip.sections.size()); + for (size_t i = 0; i < cosine.sections.size(); ++i) { + EXPECT_EQ(cosine.sections[i].first.kind, ip.sections[i].first.kind); + EXPECT_EQ(cosine.sections[i].second, ip.sections[i].second) + << "section kind " << cosine.sections[i].first.kind; + } +} + +} // namespace rabitq_test + +#endif // RABITQ_TEST_COSINE_HPP diff --git a/tests/common/format2_file.hpp b/tests/common/format2_file.hpp new file mode 100644 index 00000000..5c432532 --- /dev/null +++ b/tests/common/format2_file.hpp @@ -0,0 +1,160 @@ +#ifndef RABITQ_TEST_FORMAT2_FILE_HPP +#define RABITQ_TEST_FORMAT2_FILE_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "crc32.hpp" +#include "format2.hpp" + +namespace rabitq_test { +namespace format2 = rabitqlib::index_detail::format2; + +// Every section kind of each index, for reading back a file in full. +inline const std::vector kIvfSections = { + 1, 256, 257, 258, 259, 260, 261, 262, 263}; +inline const std::vector kHnswSections = {1, 512, 513, 514, 515, 516}; +inline const std::vector kQgSections = {1, 768, 769, 770}; + +// A whole format-2 file: the header and each known section with its bytes, in file order. +struct Format2Contents { + format2::Header header; + std::string writer_version; + std::vector> sections; + + // The bytes of a section; an error if the file has none. + std::string& bytes(uint32_t kind) { + for (auto& [section, data] : sections) { + if (section.kind == kind) { + return data; + } + } + throw std::runtime_error("test file has no such section"); + } + + void remove(uint32_t kind) { + sections.erase( + std::remove_if( + sections.begin(), + sections.end(), + [kind](const auto& entry) { return entry.first.kind == kind; } + ), + sections.end() + ); + } +}; + +inline Format2Contents read_format2_file( + const std::string& path, + format2::IndexKind kind, + const std::vector& known_kinds +) { + Format2Contents contents; + std::ifstream input(path, std::ios::binary); + format2::Reader reader(input, kind, known_kinds); + contents.header = reader.header(); + contents.writer_version = reader.writer_version(); + for (const uint32_t known : known_kinds) { + if (const format2::Section* section = reader.find(known)) { + std::string bytes(section->size, '\0'); + reader.read(*section, 0, bytes.data(), bytes.size()); + contents.sections.emplace_back(*section, std::move(bytes)); + } + } + std::sort( + contents.sections.begin(), + contents.sections.end(), + [](const auto& a, const auto& b) { return a.first.offset < b.first.offset; } + ); + return contents; +} + +// Write `contents` as a structurally valid file, so that a test can damage what a +// section holds rather than the container. +inline void write_format2_file(const std::string& path, const Format2Contents& contents) { + std::vector writes; + for (const auto& [section, bytes] : contents.sections) { + writes.push_back( + {section.kind, + section.flags, + bytes.size(), + [&data = bytes](format2::SectionSink& sink) { + sink.write(data.data(), data.size()); + }} + ); + } + std::ofstream output(path, std::ios::binary | std::ios::trunc); + output.exceptions(std::ios::failbit | std::ios::badbit); + format2::write_file(output, contents.header, writes, contents.writer_version); +} + +// The bytes of one section of a format-2 file. +inline std::string read_format2_section( + const std::string& path, + format2::IndexKind kind, + const std::vector& known_kinds, + uint32_t section_kind +) { + return read_format2_file(path, kind, known_kinds).bytes(section_kind); +} + +// Rewrite a format-2 file with one section's bytes replaced and every other part kept. +inline void replace_format2_section( + const std::string& path, + format2::IndexKind kind, + const std::vector& known_kinds, + uint32_t section_kind, + const std::string& replacement +) { + Format2Contents contents = read_format2_file(path, kind, known_kinds); + contents.bytes(section_kind) = replacement; + write_format2_file(path, contents); +} + +// Overwrite a little-endian header field of `size` bytes and recompute the header +// checksum; the writer refuses some values tests need, such as unknown feature bits. +inline void patch_format2_header( + const std::string& path, size_t offset, uint64_t value, size_t size +) { + std::string bytes; + { + std::ifstream input(path, std::ios::binary); + bytes.assign(std::istreambuf_iterator(input), {}); + } + for (size_t i = 0; i < size; ++i) { + bytes[offset + i] = static_cast(value >> (8 * i)); + } + const auto u32 = [&bytes](size_t at) { + uint32_t result = 0; + for (size_t i = 0; i < 4; ++i) { + result |= static_cast(static_cast(bytes[at + i])) << (8 * i); + } + return result; + }; + uint64_t table_offset = 0; + for (size_t i = 0; i < 8; ++i) { + table_offset |= static_cast(static_cast(bytes[96 + i])) + << (8 * i); + } + std::string header = bytes.substr(0, u32(12)); + header.replace(108, 4, 4, '\0'); + uint32_t crc = rabitqlib::detail::crc32(header.data(), header.size()); + crc = rabitqlib::detail::crc32(bytes.data() + table_offset, size_t{32} * u32(104), crc); + for (size_t i = 0; i < 4; ++i) { + bytes[108 + i] = static_cast(crc >> (8 * i)); + } + std::ofstream output(path, std::ios::binary | std::ios::trunc); + output.write(bytes.data(), static_cast(bytes.size())); +} + +} // namespace rabitq_test + +#endif // RABITQ_TEST_FORMAT2_FILE_HPP diff --git a/tests/consumer/CMakeLists.txt b/tests/consumer/CMakeLists.txt index db8ba4cb..089e1eeb 100644 --- a/tests/consumer/CMakeLists.txt +++ b/tests/consumer/CMakeLists.txt @@ -52,6 +52,20 @@ foreach(header IN ITEMS endforeach() 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 + 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 + 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}" + "#error Index API header imports an implementation dependency\n") +endforeach() +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) @@ -68,6 +82,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 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..60baac85 --- /dev/null +++ b/tests/consumer/index_api_headers_main.cpp @@ -0,0 +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() + + symqg_index_header_smoke(); +} diff --git a/tests/consumer/index_types.cpp b/tests/consumer/index_types.cpp index e829db38..b062dd81 100644 --- a/tests/consumer/index_types.cpp +++ b/tests/consumer/index_types.cpp @@ -5,4 +5,6 @@ static_assert(std::is_same_v); static_assert(rabitqlib::kPidMax == UINT32_MAX); +static_assert(std::is_same_v); +static_assert(rabitqlib::kNoId == -1); static_assert(std::is_trivially_copyable_v>); diff --git a/tests/consumer/ivf_index_headers.cpp b/tests/consumer/ivf_index_headers.cpp new file mode 100644 index 00000000..fe5f0c3d --- /dev/null +++ b/tests/consumer/ivf_index_headers.cpp @@ -0,0 +1,27 @@ +#include +#include +#include + +#include "rabitqlib/index/ivf_index.hpp" + +// The supported IVF API compiles and works without the existing IVF class, k-means or +// any implementation header. +int ivf_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::IvfOptions options; + options.seed = 3; + rabitqlib::IvfIndex index(kDim, 2, options); + const rabitqlib::Id first = index.add(data.data(), kNumPoints); + std::vector ids(kNumPoints + 1); + index.search(data.data(), 1, ids.size(), ids.data(), nullptr); + return first == 0 && index.num_points() == kNumPoints && ids.back() == rabitqlib::kNoId + ? 0 + : 1; +} diff --git a/tests/consumer/main.cpp b/tests/consumer/main.cpp index 13b8696d..8758be51 100644 --- a/tests/consumer/main.cpp +++ b/tests/consumer/main.cpp @@ -82,7 +82,7 @@ int main() { rabitqlib::qgkmeans::QGKMeansParameters graph_parameters; graph_parameters.niter = 2; graph_parameters.num_threads = 2; - graph_parameters.ef_build = 33; + graph_parameters.ef_construction = 33; graph_parameters.ef_search = 33; graph_parameters.final_assignment = rabitqlib::clustering::FinalAssignmentMode::Exact; rabitqlib::qgkmeans::QGKMeans graph(kDimension, 33, graph_parameters); 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/core_consumer/check_package_version.cmake b/tests/core_consumer/check_package_version.cmake new file mode 100644 index 00000000..68215ca2 --- /dev/null +++ b/tests/core_consumer/check_package_version.cmake @@ -0,0 +1,43 @@ +# Run with -DVERSION_FILE= -DPROJECT_VERSION= -P. +# Before 1.0 a minor release may break the API, so find_package(rabitqlib X.Y) +# accepts only the same major and minor version. A policy change at 1.0 must +# update this check deliberately. +cmake_minimum_required(VERSION 3.20) +if(NOT VERSION_FILE OR NOT PROJECT_VERSION) + message(FATAL_ERROR "VERSION_FILE and PROJECT_VERSION are required") +endif() + +string(REPLACE "." ";" version_parts "${PROJECT_VERSION}") +list(GET version_parts 0 major) +list(GET version_parts 1 minor) + +function(check_request requested expected) + string(REPLACE "." ";" parts "${requested}") + list(LENGTH parts PACKAGE_FIND_VERSION_COUNT) + list(APPEND parts 0 0) + list(GET parts 0 PACKAGE_FIND_VERSION_MAJOR) + list(GET parts 1 PACKAGE_FIND_VERSION_MINOR) + list(GET parts 2 PACKAGE_FIND_VERSION_PATCH) + set(PACKAGE_FIND_VERSION "${requested}") + unset(PACKAGE_VERSION_COMPATIBLE) + include("${VERSION_FILE}") + if(expected AND NOT PACKAGE_VERSION_COMPATIBLE) + message(FATAL_ERROR "rabitqlib ${PROJECT_VERSION} rejected a request for ${requested}") + elseif(NOT expected AND PACKAGE_VERSION_COMPATIBLE) + message(FATAL_ERROR "rabitqlib ${PROJECT_VERSION} accepted a request for ${requested}") + endif() +endfunction() + +check_request("${major}.${minor}" TRUE) +check_request("${major}.${minor}.0" TRUE) +# Requests for an older release are what the compatibility mode decides; every +# mode already rejects newer ones. +if(minor GREATER 0) + math(EXPR previous_minor "${minor} - 1") + check_request("${major}.${previous_minor}" FALSE) +endif() +if(major GREATER 0) + math(EXPR previous_major "${major} - 1") + check_request("${previous_major}.${minor}" FALSE) +endif() +message(STATUS "Package version checks passed for ${PROJECT_VERSION}") 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/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/failures/ivf_index_allocation_test.cpp b/tests/failures/ivf_index_allocation_test.cpp new file mode 100644 index 00000000..23abbaf3 --- /dev/null +++ b/tests/failures/ivf_index_allocation_test.cpp @@ -0,0 +1,125 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rabitqlib/clustering/rabitqkmeans.hpp" +#include "rabitqlib/index/ivf_index.hpp" +#include "rabitqlib/index/types.hpp" + +namespace { +std::atomic fail_enabled{false}; +std::atomic allocations_before_failure{0}; + +class AllocationFailure { + public: + explicit AllocationFailure(size_t before_failure) { + allocations_before_failure = before_failure; + fail_enabled = true; + } + AllocationFailure(const AllocationFailure&) = delete; + AllocationFailure& operator=(const AllocationFailure&) = delete; + ~AllocationFailure() { fail_enabled = false; } +}; + +// One-shot, so that cleanup after the failure can allocate. +void maybe_fail() { + if (fail_enabled && allocations_before_failure.fetch_sub(1) == 0) { + fail_enabled = false; + throw std::bad_alloc(); + } +} +} // namespace + +// This executable is separate from the normal suite so fault injection cannot affect +// unrelated tests. +GTEST_NO_INLINE_ void* operator new(size_t size) { + maybe_fail(); + if (void* ptr = std::malloc(size == 0 ? 1 : size)) { + return ptr; + } + throw std::bad_alloc(); +} + +GTEST_NO_INLINE_ void* operator new(size_t size, const std::nothrow_t&) noexcept { + try { + return ::operator new(size); + } catch (...) { return nullptr; } +} + +// The analyzer models delete as freeing before entering these replacements. +GTEST_NO_INLINE_ void operator delete(void* ptr) noexcept { + std::free(ptr); // NOLINT(clang-analyzer-cplusplus.NewDelete) +} +GTEST_NO_INLINE_ void operator delete(void* ptr, size_t) noexcept { + std::free(ptr); // NOLINT(clang-analyzer-cplusplus.NewDelete) +} + +namespace rabitqlib { +namespace { +constexpr size_t kDim = 64; +constexpr size_t kNumPoints = 200; +constexpr size_t kNumClusters = 4; + +IvfIndex new_index() { + IvfOptions options; + options.seed = 11; + IvfIndex index(kDim, kNumClusters, options); + index.cp().niter = 2; + return index; +} + +// The first add trains a staged index and fills it, so a failed operator new anywhere, +// also after training has succeeded, leaves the index untrained and empty, and a retry +// succeeds. Aligned storage and Eigen allocate with malloc-style calls and are not +// injected here. +TEST(IvfIndexFirstAddAllocationTest, EveryOperatorNewFailureLeavesTheIndexUntrained) { + // Runtime startup allocations are not index allocations and must happen before + // the hook starts injecting failures. + (void)omp_get_max_threads(); + std::mt19937 generator(3); + std::normal_distribution normal; + std::vector data(kNumPoints * kDim); + for (auto& value : data) { + value = normal(generator); + } + AddOptions options; + options.num_threads = 1; + + size_t failures = 0; + bool succeeded = false; + for (size_t allocation = 0; allocation < 4096; ++allocation) { + SCOPED_TRACE(allocation); + IvfIndex index = new_index(); + bool failed = false; + { + const AllocationFailure failure(allocation); + try { + index.add(data.data(), kNumPoints, options); + } catch (const std::bad_alloc&) { failed = true; } + } + if (!failed) { + succeeded = true; + break; + } + ++failures; + ASSERT_FALSE(index.is_trained()); + ASSERT_EQ(index.num_stored_points(), 0U); + ASSERT_EQ(index.seed(), std::optional(11)); + ASSERT_EQ(index.add(data.data(), kNumPoints, options), 0); + ASSERT_EQ(index.num_points(), kNumPoints); + } + EXPECT_GT(failures, 0U); + EXPECT_TRUE(succeeded); +} + +} // namespace +} // namespace rabitqlib diff --git a/tests/fixtures/persistence/.gitattributes b/tests/fixtures/persistence/.gitattributes index df5ad8ed..afe6b1ab 100644 --- a/tests/fixtures/persistence/.gitattributes +++ b/tests/fixtures/persistence/.gitattributes @@ -1,3 +1,4 @@ *.index -text +*.hnsw -text *.expected text eol=lf manifest.json text eol=lf diff --git a/tests/fixtures/persistence/README.md b/tests/fixtures/persistence/README.md index ee820cf2..c9805c6a 100644 --- a/tests/fixtures/persistence/README.md +++ b/tests/fixtures/persistence/README.md @@ -28,9 +28,16 @@ interchange format for arbitrary architectures. Python also tests synthetic IVF- v1 headers around the frozen historical payload, unknown versions, and invalid padding. That header test is distinct from release-produced fixtures. -The small IVF-RaBitQ fixtures use Flat centroid routing. Current round-trip and failure -tests exercise explicit HNSW routing and its sidecar; historical auto-selected -HNSW routing at 20,000 clusters is not represented by these small fixtures. +The small IVF-RaBitQ fixtures use Flat centroid routing. The [v0.8.3](v0.8.3/README.md) +set adds the last layouts before index format 2: IVF-RaBitQ with Flat RaBitQ and HNSW +routing (with its `.hnsw` sidecar), HNSW-RaBitQ at 1, 5 and 9 bits, and SymphonyQG raw, +4- and 8-bit with FHT/Kac and matrix rotation. Historical auto-selected HNSW routing at 20,000 clusters is +not represented by fixtures; Python tests cover it with headers built around the +v0.8.3 layout. +The [v0.9.0](v0.9.0/README.md) set freezes index format 2 as its first release wrote it, +for every index type and metric, including cosine, and every section kind 0.9 writes. +The [v0.7.2](v0.7.2/README.md) file is an HNSW-RaBitQ index saved before training, +which the C++ API of releases before 0.8 could write and later releases refuse to. ## Deliberate regeneration diff --git a/tests/fixtures/persistence/pre-ivf-per-cluster-storage/README.md b/tests/fixtures/persistence/pre-ivf-per-cluster-storage/README.md index 3e7c742d..89b1ea05 100644 --- a/tests/fixtures/persistence/pre-ivf-per-cluster-storage/README.md +++ b/tests/fixtures/persistence/pre-ivf-per-cluster-storage/README.md @@ -13,10 +13,12 @@ single-point cluster, a full FastScan batch and a partial tail batch. Point 0 is removed. The `.expected` files hold reference results of a search that probes every cluster. -The tests load each file, compare search results, and require that saving it -again reproduces the original bytes. Because the clusters differ in size, a -reader or writer that orders the batch data, extra-bit data and IDs differently -from the shared-buffer layout fails these checks. +The tests load each file and compare search results. Until index format 2, they also +required that saving it again reproduces the original bytes; saving now writes format +2, and the tests require that the migrated file gives the same results and that saving +it again reproduces it. Because the clusters differ in size, a reader that orders the +batch data, extra-bit data and IDs differently from the shared-buffer layout fails +these checks. ## Deliberate regeneration diff --git a/tests/fixtures/persistence/v0.7.2/CMakeLists.txt b/tests/fixtures/persistence/v0.7.2/CMakeLists.txt new file mode 100644 index 00000000..f43d12cf --- /dev/null +++ b/tests/fixtures/persistence/v0.7.2/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) +project(rabitq_v072_fixtures LANGUAGES CXX) + +if(NOT IS_DIRECTORY "${RABITQ_HISTORICAL_SOURCE}") + message(FATAL_ERROR "Set RABITQ_HISTORICAL_SOURCE to the pinned v0.7.2 checkout") +endif() +set(RABITQ_BUILD_TESTS OFF CACHE BOOL "" FORCE) +set(RABITQ_BUILD_SAMPLES OFF CACHE BOOL "" FORCE) +set(RABITQ_BUILD_PYTHON_BINDINGS OFF CACHE BOOL "" FORCE) +set(RABITQ_ENABLE_NATIVE_OPTIMIZATION OFF CACHE BOOL "" FORCE) +add_subdirectory("${RABITQ_HISTORICAL_SOURCE}" historical) +add_executable(generate_fixtures generate.cpp) +target_link_libraries(generate_fixtures PRIVATE rabitqlib::index) diff --git a/tests/fixtures/persistence/v0.7.2/README.md b/tests/fixtures/persistence/v0.7.2/README.md new file mode 100644 index 00000000..051b4af3 --- /dev/null +++ b/tests/fixtures/persistence/v0.7.2/README.md @@ -0,0 +1,30 @@ +# Index fixture from v0.7.2 + +This file was written by release **v0.7.2**, commit +`655c9c6656318e9726e3a3908d0abe0563f7630c`, using [generate.cpp](generate.cpp). +[manifest.json](manifest.json) records the producer and SHA-256 hash. +Keep it unchanged; tests never regenerate it with the current writer. + +`hnsw4_empty_l2.index` is an HNSW-RaBitQ index that was constructed and saved without +points or training: capacity 130, 65 original dimensions, 4 bits, L2, M = 8, +`ef_construction` 64, seed 42. The C++ API of releases before 0.8 allowed this; 0.8 +and later releases refuse to save an empty index. Such a file has no +centroids and does not record its seed, so it loads untrained. + +## Deliberate regeneration + +Build the generator only against an isolated copy of the release: + +```bash +mkdir -p build/fixtures/v0.7.2 +git archive v0.7.2 | tar -x -C build/fixtures/v0.7.2 +cmake -S tests/fixtures/persistence/v0.7.2 -B build/fixtures/v0.7.2-generator \ + -DRABITQ_HISTORICAL_SOURCE="$PWD/build/fixtures/v0.7.2" \ + -DCMAKE_BUILD_TYPE=Release +cmake --build build/fixtures/v0.7.2-generator --target generate_fixtures +``` + +Run it with a new output directory. The file has no points, and its rotation is seeded +with 42, so the generator writes the same bytes on every run with the same toolchain +(the manifest records it); record a new hash in the manifest before adopting a +different file. diff --git a/tests/fixtures/persistence/v0.7.2/generate.cpp b/tests/fixtures/persistence/v0.7.2/generate.cpp new file mode 100644 index 00000000..161405f0 --- /dev/null +++ b/tests/fixtures/persistence/v0.7.2/generate.cpp @@ -0,0 +1,20 @@ +// Build only against the pinned v0.7.2 source, never the current checkout. Writes an +// HNSW-RaBitQ index that was constructed and saved without points, which the 0.7.x +// C++ API allowed (0.8 and later refuse to save an empty index). +#include +#include + +#include "rabitqlib/core/metric.hpp" +#include "rabitqlib/index/hnsw/hnsw.hpp" + +int main(int argc, char** argv) { + if (argc != 2) { + throw std::invalid_argument("Pass the fixture output directory"); + } + const std::filesystem::path directory(argv[1]); + std::filesystem::create_directories(directory); + // Capacity 130, 65 dimensions, 4 bits, M 8, ef_construction 64, seed 42. + rabitqlib::hnsw::HierarchicalNSW index(130, 65, 4, 8, 64, 42, rabitqlib::METRIC_L2); + index.save((directory / "hnsw4_empty_l2.index").string().c_str()); + return 0; +} diff --git a/tests/fixtures/persistence/v0.7.2/hnsw4_empty_l2.index b/tests/fixtures/persistence/v0.7.2/hnsw4_empty_l2.index new file mode 100644 index 00000000..a911eacb Binary files /dev/null and b/tests/fixtures/persistence/v0.7.2/hnsw4_empty_l2.index differ diff --git a/tests/fixtures/persistence/v0.7.2/manifest.json b/tests/fixtures/persistence/v0.7.2/manifest.json new file mode 100644 index 00000000..05ed0ef5 --- /dev/null +++ b/tests/fixtures/persistence/v0.7.2/manifest.json @@ -0,0 +1,11 @@ +{ + "source_tag": "v0.7.2", + "source_commit": "655c9c6656318e9726e3a3908d0abe0563f7630c", + "writer": "tests/fixtures/persistence/v0.7.2/generate.cpp", + "producer": "Linux x86-64, g++ 14.3.0, Release, one thread, native optimization OFF", + "byte_order": "little", + "size_t_bytes": 8, + "sha256": { + "v0.7.2/hnsw4_empty_l2.index": "0177215c1b20f127be7b8bff1027b366f7faaf76022efeabe2336a96da093603" + } +} diff --git a/tests/fixtures/persistence/v0.8.3/CMakeLists.txt b/tests/fixtures/persistence/v0.8.3/CMakeLists.txt new file mode 100644 index 00000000..4fd4b3e5 --- /dev/null +++ b/tests/fixtures/persistence/v0.8.3/CMakeLists.txt @@ -0,0 +1,15 @@ +cmake_minimum_required(VERSION 3.20) +project(rabitq_v083_fixtures LANGUAGES CXX) + +if(NOT IS_DIRECTORY "${RABITQ_HISTORICAL_SOURCE}") + message(FATAL_ERROR "Set RABITQ_HISTORICAL_SOURCE to the pinned v0.8.3 checkout") +endif() +set(RABITQ_BUILD_TESTS OFF CACHE BOOL "" FORCE) +set(RABITQ_BUILD_SAMPLES OFF CACHE BOOL "" FORCE) +set(RABITQ_BUILD_PYTHON_BINDINGS OFF CACHE BOOL "" FORCE) +set(RABITQ_ENABLE_NATIVE_OPTIMIZATION OFF CACHE BOOL "" FORCE) +add_subdirectory("${RABITQ_HISTORICAL_SOURCE}" historical) +add_executable(generate_fixtures generate.cpp) +target_link_libraries(generate_fixtures PRIVATE rabitqlib::index) +add_executable(generate_graph_fixtures generate_graphs.cpp) +target_link_libraries(generate_graph_fixtures PRIVATE rabitqlib::index) diff --git a/tests/fixtures/persistence/v0.8.3/README.md b/tests/fixtures/persistence/v0.8.3/README.md new file mode 100644 index 00000000..74091fa0 --- /dev/null +++ b/tests/fixtures/persistence/v0.8.3/README.md @@ -0,0 +1,57 @@ +# Index fixtures from v0.8.3 + +These files were written by release **v0.8.3**, commit +`dabfdb8c200a6f155df4edd0b9c825e6728b14a1`, using [generate.cpp](generate.cpp) for +IVF-RaBitQ and [generate_graphs.cpp](generate_graphs.cpp) for HNSW-RaBitQ and SymphonyQG. +[manifest.json](manifest.json) records the producer and SHA-256 hashes. +Keep these files unchanged; tests never regenerate them with the current writer. + +They freeze the last IVF-RaBitQ layout before index format 2: `RABQIDX1` version 2, +which stores the centroid-routing type, and the hnswlib sidecar `.hnsw` that +HNSW routing writes beside the index. The five cases are: + +| File | Bits | Metric | Rotator | Routing | +| --- | --- | --- | --- | --- | +| `ivf4_flat_l2` | 4 | L2 | FHT/Kac | Flat | +| `ivf7_flatrabitq_ip` | 7 | inner product | FHT/Kac | FlatRaBitQ | +| `ivf4_hnsw_l2` | 4 | L2 | FHT/Kac | HNSW, with sidecar | +| `ivf32_hnsw_ip` | raw (`nbits=32`) | inner product | FHT/Kac | HNSW, with sidecar | +| `ivf1_flat_matrix_l2` | 1 | L2 | matrix | Flat | + +The graph generator, run separately, adds the last HNSW-RaBitQ and SymphonyQG layouts +before index format 2: + +| File | Bits | Metric | Rotator | Notes | +| --- | --- | --- | --- | --- | +| `hnsw1_l2` | 1 | L2 | FHT/Kac | M = 8, `ef_construction` 64, seed 42, point 0 removed | +| `hnsw5_ip` | 5 | inner product | FHT/Kac | As above | +| `hnsw9_l2` | 9 | L2 | FHT/Kac | As above | +| `qg0_ip` | raw | inner product | FHT/Kac | Degree 32, PiPNN, `ef_construction` 64, seed 42 | +| `qg4_l2` | 4 | L2 | FHT/Kac | As above | +| `qg8_ip` | 8 | inner product | FHT/Kac | As above | +| `qg4_matrix_l2` | 4 | L2 | matrix | As above | + +Each index holds 130 points in 65 original dimensions (96 padded); the IVF-RaBitQ and +HNSW-RaBitQ files use four clusters of 0, 1, 32 and 97 points, with point 0 removed, as in +[pre-ivf-per-cluster-storage](../pre-ivf-per-cluster-storage/README.md). The +`.expected` files hold reference results: IVF-RaBitQ probes every cluster, and the graph +indexes search with `ef` 64. + +## Deliberate regeneration + +Build the generator only against an isolated copy of the release: + +```bash +mkdir -p build/fixtures/v0.8.3 +git archive v0.8.3 | tar -x -C build/fixtures/v0.8.3 +cmake -S tests/fixtures/persistence/v0.8.3 -B build/fixtures/v0.8.3-generator \ + -DRABITQ_HISTORICAL_SOURCE="$PWD/build/fixtures/v0.8.3" \ + -DCMAKE_BUILD_TYPE=Release +cmake --build build/fixtures/v0.8.3-generator --target generate_fixtures generate_graph_fixtures +``` + +Run either generator with a new output directory and `OMP_NUM_THREADS=1`. +IVF-RaBitQ rotation is seeded from `random_device`, so those bytes differ on every run; +the graph indexes use seed 42. Each index, its sidecar and its `.expected` file form a +fixed set. Record new hashes in the manifest +before adopting them. diff --git a/tests/fixtures/persistence/v0.8.3/generate.cpp b/tests/fixtures/persistence/v0.8.3/generate.cpp new file mode 100644 index 00000000..ff2441d5 --- /dev/null +++ b/tests/fixtures/persistence/v0.8.3/generate.cpp @@ -0,0 +1,111 @@ +// Build only against the pinned v0.8.3 source, never the current checkout. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rabitqlib/core/metric.hpp" +#include "rabitqlib/core/types.hpp" +#include "rabitqlib/index/ivf/ivf.hpp" +#include "rabitqlib/index/ivf/types.hpp" +#include "rabitqlib/index/types.hpp" + +int main(int argc, char** argv) { + if (argc != 2) { + throw std::invalid_argument("Pass the fixture output directory"); + } + using namespace rabitqlib; + // Cluster sizes 0, 1, 32 and 97 cover empty, single, full-batch and tail clusters. + constexpr size_t kCount = 130, kDim = 65, kClusters = 4, kQueries = 3, kTopK = 5; + const std::filesystem::path directory(argv[1]); + std::filesystem::create_directories(directory); + uint32_t state = 713; + const auto next = [&state] { + state = state * 1664525U + 1013904223U; + return static_cast(static_cast((state >> 8) % 2001) - 1000) / 256.0F; + }; + std::vector data(kCount * kDim), queries(kQueries * kDim); + std::vector centroids(kClusters * kDim); + for (auto& value : data) { + value = next(); + } + for (auto& value : queries) { + value = next(); + } + for (auto& value : centroids) { + value = next(); + } + std::vector clusters(kCount, 3); + clusters[0] = 1; + for (size_t i = 1; i < 33; ++i) { + clusters[i] = 2; + } + + const struct { + const char* name; + size_t total_bits; + MetricType metric; + RotatorType rotator; + ivf::InitializerType initializer; + } cases[] = { + {"ivf4_flat_l2", + 4, + METRIC_L2, + RotatorType::FhtKacRotator, + ivf::InitializerType::Flat}, + {"ivf7_flatrabitq_ip", + 7, + METRIC_IP, + RotatorType::FhtKacRotator, + ivf::InitializerType::FlatRaBitQ}, + {"ivf4_hnsw_l2", + 4, + METRIC_L2, + RotatorType::FhtKacRotator, + ivf::InitializerType::HNSW}, + {"ivf32_hnsw_ip", + 32, + METRIC_IP, + RotatorType::FhtKacRotator, + ivf::InitializerType::HNSW}, + {"ivf1_flat_matrix_l2", + 1, + METRIC_L2, + RotatorType::MatrixRotator, + ivf::InitializerType::Flat}, + }; + for (const auto& c : cases) { + const std::string name = c.name; + const auto path = (directory / (name + ".index")).string(); + std::vector ids(kQueries * kTopK); + std::vector distances(ids.size()); + ivf::IVF index( + kCount, kDim, kClusters, c.total_bits, c.metric, c.rotator, c.initializer + ); + index.construct(data.data(), centroids.data(), clusters.data(), false, 1); + const PID removed = 0; + index.remove(&removed, 1); + index.save(path.c_str()); + index.search_batch( + queries.data(), kQueries, kTopK, kClusters, ids.data(), distances.data() + ); + std::ofstream expected(directory / (name + ".expected"), std::ios::binary); + expected.exceptions(std::ios::failbit | std::ios::badbit); + expected << std::setprecision(std::numeric_limits::max_digits10); + expected << kCount << ' ' << kDim << ' ' << kQueries << ' ' << kTopK << '\n'; + for (size_t i = 0; i < queries.size(); ++i) { + expected << queries[i] << (i + 1 == queries.size() ? '\n' : ' '); + } + for (size_t i = 0; i < ids.size(); ++i) { + expected << ids[i] << ' ' << distances[i] << '\n'; + } + expected.close(); + } + return 0; +} diff --git a/tests/fixtures/persistence/v0.8.3/generate_graphs.cpp b/tests/fixtures/persistence/v0.8.3/generate_graphs.cpp new file mode 100644 index 00000000..abe912cb --- /dev/null +++ b/tests/fixtures/persistence/v0.8.3/generate_graphs.cpp @@ -0,0 +1,129 @@ +// Build only against the pinned v0.8.3 source, never the current checkout. Writes the +// HNSW-RaBitQ and SymphonyQG fixtures; generate.cpp writes the IVF-RaBitQ ones. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rabitqlib/core/metric.hpp" +#include "rabitqlib/core/types.hpp" +#include "rabitqlib/index/hnsw/hnsw.hpp" +#include "rabitqlib/index/symqg/qg.hpp" +#include "rabitqlib/index/symqg/qg_builder.hpp" +#include "rabitqlib/index/types.hpp" + +int main(int argc, char** argv) { + if (argc != 2) { + throw std::invalid_argument("Pass the fixture output directory"); + } + using namespace rabitqlib; + // The IVF fixtures' data: cluster sizes 0, 1, 32 and 97. + constexpr size_t kCount = 130, kDim = 65, kClusters = 4, kQueries = 3, kTopK = 5; + const std::filesystem::path directory(argv[1]); + std::filesystem::create_directories(directory); + uint32_t state = 713; + const auto next = [&state] { + state = state * 1664525U + 1013904223U; + return static_cast(static_cast((state >> 8) % 2001) - 1000) / 256.0F; + }; + std::vector data(kCount * kDim), queries(kQueries * kDim); + std::vector centroids(kClusters * kDim); + for (auto& value : data) { + value = next(); + } + for (auto& value : queries) { + value = next(); + } + for (auto& value : centroids) { + value = next(); + } + std::vector clusters(kCount, 3); + clusters[0] = 1; + for (size_t i = 1; i < 33; ++i) { + clusters[i] = 2; + } + + const auto write_expected = [&](const std::string& name, + const std::vector& ids, + const std::vector& distances) { + std::ofstream expected(directory / (name + ".expected"), std::ios::binary); + expected.exceptions(std::ios::failbit | std::ios::badbit); + expected << std::setprecision(std::numeric_limits::max_digits10); + expected << kCount << ' ' << kDim << ' ' << kQueries << ' ' << kTopK << '\n'; + for (size_t i = 0; i < queries.size(); ++i) { + expected << queries[i] << (i + 1 == queries.size() ? '\n' : ' '); + } + for (size_t i = 0; i < ids.size(); ++i) { + expected << ids[i] << ' ' << distances[i] << '\n'; + } + expected.close(); + }; + + const struct { + const char* name; + size_t total_bits; + MetricType metric; + } hnsw_cases[] = { + {"hnsw1_l2", 1, METRIC_L2}, + {"hnsw5_ip", 5, METRIC_IP}, + {"hnsw9_l2", 9, METRIC_L2}, + }; + for (const auto& c : hnsw_cases) { + const std::string name = c.name; + hnsw::HierarchicalNSW index(kCount, kDim, c.total_bits, 8, 64, 42, c.metric); + std::vector assigned = clusters; + index.construct( + kClusters, centroids.data(), kCount, data.data(), assigned.data(), 1 + ); + const PID removed = 0; + index.remove(&removed, 1); + index.save((directory / (name + ".index")).string().c_str()); + std::vector ids(kQueries * kTopK); + std::vector distances(ids.size()); + const auto result = index.search(queries.data(), kQueries, kTopK, 64, 1); + for (size_t i = 0; i < kQueries; ++i) { + for (size_t j = 0; j < kTopK; ++j) { + ids[i * kTopK + j] = result[i][j].second; + distances[i * kTopK + j] = result[i][j].first; + } + } + write_expected(name, ids, distances); + } + + const struct { + const char* name; + size_t bits; // 0 stores raw vectors + MetricType metric; + RotatorType rotator; + } qg_cases[] = { + {"qg0_ip", 0, METRIC_IP, RotatorType::FhtKacRotator}, + {"qg4_l2", 4, METRIC_L2, RotatorType::FhtKacRotator}, + {"qg8_ip", 8, METRIC_IP, RotatorType::FhtKacRotator}, + {"qg4_matrix_l2", 4, METRIC_L2, RotatorType::MatrixRotator}, + }; + for (const auto& c : qg_cases) { + const std::string name = c.name; + symqg::QuantizedGraph index( + kCount, kDim, 32, c.metric, c.rotator, c.bits, 42 + ); + symqg::QGBuilder builder( + index, 64, data.data(), 1, symqg::QGInitialization::PiPNN, 42 + ); + builder.build(); + index.save((directory / (name + ".index")).string().c_str()); + std::vector ids(kQueries * kTopK); + std::vector distances(ids.size()); + index.set_ef(64); + index.search_batch( + queries.data(), kQueries, kTopK, ids.data(), distances.data(), 1 + ); + write_expected(name, ids, distances); + } + return 0; +} diff --git a/tests/fixtures/persistence/v0.8.3/hnsw1_l2.expected b/tests/fixtures/persistence/v0.8.3/hnsw1_l2.expected new file mode 100644 index 00000000..96a62dad --- /dev/null +++ b/tests/fixtures/persistence/v0.8.3/hnsw1_l2.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +59 457.198364 +94 473.985107 +92 476.936432 +13 481.009399 +1 482.431854 +71 283.250702 +120 364.552856 +102 403.540588 +50 411.44928 +28 413.655273 +119 332.883972 +48 336.432617 +12 339.079712 +100 404.918793 +105 407.847778 diff --git a/tests/fixtures/persistence/v0.8.3/hnsw1_l2.index b/tests/fixtures/persistence/v0.8.3/hnsw1_l2.index new file mode 100644 index 00000000..fae1c705 Binary files /dev/null and b/tests/fixtures/persistence/v0.8.3/hnsw1_l2.index differ diff --git a/tests/fixtures/persistence/v0.8.3/hnsw5_ip.expected b/tests/fixtures/persistence/v0.8.3/hnsw5_ip.expected new file mode 100644 index 00000000..193d8d0d --- /dev/null +++ b/tests/fixtures/persistence/v0.8.3/hnsw5_ip.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +128 -94.5418472 +46 -83.159584 +92 -80.4502106 +50 -75.6382751 +13 -72.0860596 +128 -75.1309814 +11 -73.6424179 +112 -73.1209106 +31 -65.0838242 +14 -64.2643051 +32 -69.4516983 +106 -66.4129791 +3 -62.6622734 +87 -57.6153526 +127 -55.5868149 diff --git a/tests/fixtures/persistence/v0.8.3/hnsw5_ip.index b/tests/fixtures/persistence/v0.8.3/hnsw5_ip.index new file mode 100644 index 00000000..2e69c115 Binary files /dev/null and b/tests/fixtures/persistence/v0.8.3/hnsw5_ip.index differ diff --git a/tests/fixtures/persistence/v0.8.3/hnsw9_l2.expected b/tests/fixtures/persistence/v0.8.3/hnsw9_l2.expected new file mode 100644 index 00000000..38c4ce7a --- /dev/null +++ b/tests/fixtures/persistence/v0.8.3/hnsw9_l2.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +92 420.362671 +46 471.622772 +128 481.912445 +43 495.599579 +3 497.779449 +31 412.638641 +112 416.755554 +129 460.20517 +71 463.54837 +128 464.295135 +32 423.867615 +3 448.949097 +87 462.59491 +12 477.650421 +48 481.020172 diff --git a/tests/fixtures/persistence/v0.8.3/hnsw9_l2.index b/tests/fixtures/persistence/v0.8.3/hnsw9_l2.index new file mode 100644 index 00000000..194e5d64 Binary files /dev/null and b/tests/fixtures/persistence/v0.8.3/hnsw9_l2.index differ diff --git a/tests/fixtures/persistence/v0.8.3/ivf1_flat_matrix_l2.expected b/tests/fixtures/persistence/v0.8.3/ivf1_flat_matrix_l2.expected new file mode 100644 index 00000000..c7b534ad --- /dev/null +++ b/tests/fixtures/persistence/v0.8.3/ivf1_flat_matrix_l2.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +83 361.387726 +36 367.132172 +46 399.009552 +50 400.204742 +65 405.736511 +31 288.149902 +112 353.039429 +129 425.505188 +40 444.491913 +95 452.522827 +84 289.657135 +72 334.618195 +87 337.608826 +50 342.41745 +100 356.274933 diff --git a/tests/fixtures/persistence/v0.8.3/ivf1_flat_matrix_l2.index b/tests/fixtures/persistence/v0.8.3/ivf1_flat_matrix_l2.index new file mode 100644 index 00000000..269d4966 Binary files /dev/null and b/tests/fixtures/persistence/v0.8.3/ivf1_flat_matrix_l2.index differ diff --git a/tests/fixtures/persistence/v0.8.3/ivf32_hnsw_ip.expected b/tests/fixtures/persistence/v0.8.3/ivf32_hnsw_ip.expected new file mode 100644 index 00000000..d0f55dd7 --- /dev/null +++ b/tests/fixtures/persistence/v0.8.3/ivf32_hnsw_ip.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +128 -94.8744507 +92 -82.2540436 +46 -80.8800812 +50 -71.6611023 +5 -69.8279419 +112 -73.9705811 +128 -73.9433899 +11 -71.4328156 +14 -64.1144104 +31 -59.65448 +32 -72.5804443 +106 -66.686676 +3 -59.7108917 +87 -57.427536 +127 -53.9758759 diff --git a/tests/fixtures/persistence/v0.8.3/ivf32_hnsw_ip.index b/tests/fixtures/persistence/v0.8.3/ivf32_hnsw_ip.index new file mode 100644 index 00000000..2929eafe Binary files /dev/null and b/tests/fixtures/persistence/v0.8.3/ivf32_hnsw_ip.index differ diff --git a/tests/fixtures/persistence/v0.8.3/ivf32_hnsw_ip.index.hnsw b/tests/fixtures/persistence/v0.8.3/ivf32_hnsw_ip.index.hnsw new file mode 100644 index 00000000..59f96bf2 Binary files /dev/null and b/tests/fixtures/persistence/v0.8.3/ivf32_hnsw_ip.index.hnsw differ diff --git a/tests/fixtures/persistence/v0.8.3/ivf4_flat_l2.expected b/tests/fixtures/persistence/v0.8.3/ivf4_flat_l2.expected new file mode 100644 index 00000000..2adbbb05 --- /dev/null +++ b/tests/fixtures/persistence/v0.8.3/ivf4_flat_l2.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +92 421.434753 +46 460.21283 +128 473.936279 +13 483.826019 +3 495.024872 +31 406.883026 +112 410.993774 +129 454.92041 +71 455.203857 +128 456.861572 +32 436.845459 +3 452.321411 +87 459.564636 +12 475.835114 +48 481.350098 diff --git a/tests/fixtures/persistence/v0.8.3/ivf4_flat_l2.index b/tests/fixtures/persistence/v0.8.3/ivf4_flat_l2.index new file mode 100644 index 00000000..581ded95 Binary files /dev/null and b/tests/fixtures/persistence/v0.8.3/ivf4_flat_l2.index differ diff --git a/tests/fixtures/persistence/v0.8.3/ivf4_hnsw_l2.expected b/tests/fixtures/persistence/v0.8.3/ivf4_hnsw_l2.expected new file mode 100644 index 00000000..e91a5bbe --- /dev/null +++ b/tests/fixtures/persistence/v0.8.3/ivf4_hnsw_l2.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +92 431.944397 +128 470.540405 +46 476.507202 +3 490.621582 +13 493.916656 +112 412.643494 +31 416.188904 +128 453.381653 +129 459.386047 +90 459.440277 +32 424.608551 +3 457.105835 +87 463.820557 +48 464.434967 +12 477.980652 diff --git a/tests/fixtures/persistence/v0.8.3/ivf4_hnsw_l2.index b/tests/fixtures/persistence/v0.8.3/ivf4_hnsw_l2.index new file mode 100644 index 00000000..8e1426b2 Binary files /dev/null and b/tests/fixtures/persistence/v0.8.3/ivf4_hnsw_l2.index differ diff --git a/tests/fixtures/persistence/v0.8.3/ivf4_hnsw_l2.index.hnsw b/tests/fixtures/persistence/v0.8.3/ivf4_hnsw_l2.index.hnsw new file mode 100644 index 00000000..06c069f5 Binary files /dev/null and b/tests/fixtures/persistence/v0.8.3/ivf4_hnsw_l2.index.hnsw differ diff --git a/tests/fixtures/persistence/v0.8.3/ivf7_flatrabitq_ip.expected b/tests/fixtures/persistence/v0.8.3/ivf7_flatrabitq_ip.expected new file mode 100644 index 00000000..3f2607f1 --- /dev/null +++ b/tests/fixtures/persistence/v0.8.3/ivf7_flatrabitq_ip.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +128 -94.6611481 +92 -82.9637375 +46 -81.7006149 +13 -72.5498047 +50 -71.9551773 +112 -74.3031998 +128 -74.0310822 +11 -72.1495819 +14 -64.1889343 +71 -59.4696617 +32 -72.5847778 +106 -67.2913208 +3 -59.6324234 +87 -56.3743286 +127 -54.9878922 diff --git a/tests/fixtures/persistence/v0.8.3/ivf7_flatrabitq_ip.index b/tests/fixtures/persistence/v0.8.3/ivf7_flatrabitq_ip.index new file mode 100644 index 00000000..da3ca3b9 Binary files /dev/null and b/tests/fixtures/persistence/v0.8.3/ivf7_flatrabitq_ip.index differ diff --git a/tests/fixtures/persistence/v0.8.3/manifest.json b/tests/fixtures/persistence/v0.8.3/manifest.json new file mode 100644 index 00000000..15790eb6 --- /dev/null +++ b/tests/fixtures/persistence/v0.8.3/manifest.json @@ -0,0 +1,36 @@ +{ + "source_tag": "v0.8.3", + "source_commit": "dabfdb8c200a6f155df4edd0b9c825e6728b14a1", + "writer": "tests/fixtures/persistence/v0.8.3/generate.cpp (IVF-RaBitQ) and generate_graphs.cpp (HNSW-RaBitQ, SymphonyQG)", + "producer": "Linux x86-64, g++ 14.3.0, Release, one thread, native optimization OFF", + "byte_order": "little", + "size_t_bytes": 8, + "sha256": { + "v0.8.3/hnsw1_l2.expected": "00af920380168a49f0739b9f180a764c3fac3bbc3a7b31b6acbbf0ecd621f62a", + "v0.8.3/hnsw1_l2.index": "cb89a17e02c04233b599d9077d81b030586eba9bc32fe1ead9ea30271be0b7e1", + "v0.8.3/hnsw5_ip.expected": "199106ce08b2667df5b4cbc47bc06309564637e6790cf74448324c27e377b2f2", + "v0.8.3/hnsw5_ip.index": "5780fb6ad6843df24cfa0b9a545e5251505e50040e3ac73593e1f897d29b5967", + "v0.8.3/hnsw9_l2.expected": "ef0fa91553a6effcdbba13bf0fc5263fa75a3af5ac37acc948809ef051d93ab3", + "v0.8.3/hnsw9_l2.index": "116d2496789bfb392f0cb03aca6d0163985298c71aa0a8259f4e3092efc8a47f", + "v0.8.3/ivf1_flat_matrix_l2.expected": "f1616ce0a6f59a57984e62eda1a16b92a54f603434e163ce5a2f33c336a0a252", + "v0.8.3/ivf1_flat_matrix_l2.index": "c864c367f4eaac449984694402d42ba81706391c61405f3fcdcf233a7f4d92f4", + "v0.8.3/ivf32_hnsw_ip.expected": "8280cf8c79e396c94ddb0a3bf77d69f45f7261b1ea71e90e5522395286376f89", + "v0.8.3/ivf32_hnsw_ip.index": "61935ec5f4a5c3b2aeb990ccb9bafa25e7323658c65a20f0344e79e0c8df7194", + "v0.8.3/ivf32_hnsw_ip.index.hnsw": "320c644a727fa94f7e5ced3821d8fcca6562c22904acfbd158fc5b3f6c3c5eb4", + "v0.8.3/ivf4_flat_l2.expected": "c2d41f4b7c18332d94f01ebdf493658b8f468b5c517bc9961cbfea2ffdb33dbe", + "v0.8.3/ivf4_flat_l2.index": "d324a9df508c32fee0a862868d3f7b2fcd7acc999db4e7bd5761b4f6cd1d07be", + "v0.8.3/ivf4_hnsw_l2.expected": "4235ed49a3d008e34b646358ec0de0649c63122b3f5f60e813df8a0d494c3a88", + "v0.8.3/ivf4_hnsw_l2.index": "88b5b7d1b7e5be99506421cd36ad6bb1785490446f55788d5b39a1069d5b304c", + "v0.8.3/ivf4_hnsw_l2.index.hnsw": "1797edb3eb1fb16a20684d8873cbc2c0713bdf1623ff31f366e8f016f5e616cf", + "v0.8.3/ivf7_flatrabitq_ip.expected": "c602bd98139b597532067094b001ff992d4498ea07ad7ddaf6762b8261f67d83", + "v0.8.3/ivf7_flatrabitq_ip.index": "54c11bcb813395eed099c8e8f65cdd96d97ca1ed684703e66abe27fd06887929", + "v0.8.3/qg0_ip.expected": "3ecb6604dce2108556e5e48130d4e9902d7ef7f0ef81aba39a3caa40b62230fe", + "v0.8.3/qg0_ip.index": "5b48546797a13825d27f0296b3c21c9c79fcf80ce44121fa5e9540358bb5762f", + "v0.8.3/qg4_l2.expected": "e973d22674ccde5c5afe4cf916e7c9271a79e8b6230c2da11bbc304218f488cf", + "v0.8.3/qg4_l2.index": "9f61d0570b75e67f101bc8e50e9af9db35194fa51187317d92a831db1a00d1e1", + "v0.8.3/qg4_matrix_l2.expected": "8f7d74551eb36226a89b195d23b69eac2d7194fbfe8f47b73caee8364757730e", + "v0.8.3/qg4_matrix_l2.index": "f60b01bb2e6b670eb63a0ed108346cc5c3cde0614b5178462b9a117b3c563484", + "v0.8.3/qg8_ip.expected": "46b4b3bd3e0b6ad1ec7e00df843e679977a7092fd3dcca78eb85a5239293cfe5", + "v0.8.3/qg8_ip.index": "5519fecdbde73515940de91d213ca4ab7ad3c486cd97a773fe02927c121ce879" + } +} diff --git a/tests/fixtures/persistence/v0.8.3/qg0_ip.expected b/tests/fixtures/persistence/v0.8.3/qg0_ip.expected new file mode 100644 index 00000000..750cfd52 --- /dev/null +++ b/tests/fixtures/persistence/v0.8.3/qg0_ip.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +128 -94.8744507 +92 -82.2540436 +46 -80.8800812 +13 -71.9051971 +50 -71.6611023 +112 -73.9705811 +128 -73.9433899 +11 -71.4328156 +14 -64.1144104 +31 -59.65448 +32 -72.5804443 +106 -66.686676 +3 -59.7108917 +87 -57.427536 +127 -53.9758759 diff --git a/tests/fixtures/persistence/v0.8.3/qg0_ip.index b/tests/fixtures/persistence/v0.8.3/qg0_ip.index new file mode 100644 index 00000000..c25390c8 Binary files /dev/null and b/tests/fixtures/persistence/v0.8.3/qg0_ip.index differ diff --git a/tests/fixtures/persistence/v0.8.3/qg4_l2.expected b/tests/fixtures/persistence/v0.8.3/qg4_l2.expected new file mode 100644 index 00000000..24704b89 --- /dev/null +++ b/tests/fixtures/persistence/v0.8.3/qg4_l2.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +92 426.139954 +46 474.039948 +128 487.332336 +43 495.476349 +3 501.042847 +31 412.692932 +112 417.631104 +71 458.311768 +129 460.74765 +14 467.755432 +32 428.727905 +87 450.430389 +3 451.144958 +12 467.519897 +0 474.705017 diff --git a/tests/fixtures/persistence/v0.8.3/qg4_l2.index b/tests/fixtures/persistence/v0.8.3/qg4_l2.index new file mode 100644 index 00000000..74b0b7b6 Binary files /dev/null and b/tests/fixtures/persistence/v0.8.3/qg4_l2.index differ diff --git a/tests/fixtures/persistence/v0.8.3/qg4_matrix_l2.expected b/tests/fixtures/persistence/v0.8.3/qg4_matrix_l2.expected new file mode 100644 index 00000000..8529804a --- /dev/null +++ b/tests/fixtures/persistence/v0.8.3/qg4_matrix_l2.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +92 422.084595 +46 478.977295 +128 487.529175 +43 493.764648 +3 502.006531 +31 412.601593 +112 417.63501 +128 451.895691 +71 463.59549 +129 465.134125 +32 430.10022 +3 447.459839 +87 459.170197 +48 465.867981 +106 471.233765 diff --git a/tests/fixtures/persistence/v0.8.3/qg4_matrix_l2.index b/tests/fixtures/persistence/v0.8.3/qg4_matrix_l2.index new file mode 100644 index 00000000..3e1736ad Binary files /dev/null and b/tests/fixtures/persistence/v0.8.3/qg4_matrix_l2.index differ diff --git a/tests/fixtures/persistence/v0.8.3/qg8_ip.expected b/tests/fixtures/persistence/v0.8.3/qg8_ip.expected new file mode 100644 index 00000000..328daa94 --- /dev/null +++ b/tests/fixtures/persistence/v0.8.3/qg8_ip.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +128 -94.953392 +92 -82.2493134 +46 -81.0288467 +13 -71.8557434 +50 -71.6811447 +112 -74.0330429 +128 -73.8238602 +11 -71.6039658 +14 -64.0551224 +31 -59.4229736 +32 -72.4512024 +106 -66.6851273 +3 -59.6906853 +87 -57.5236473 +127 -53.835289 diff --git a/tests/fixtures/persistence/v0.8.3/qg8_ip.index b/tests/fixtures/persistence/v0.8.3/qg8_ip.index new file mode 100644 index 00000000..09e1ffa2 Binary files /dev/null and b/tests/fixtures/persistence/v0.8.3/qg8_ip.index differ diff --git a/tests/fixtures/persistence/v0.9.0/CMakeLists.txt b/tests/fixtures/persistence/v0.9.0/CMakeLists.txt new file mode 100644 index 00000000..56f41598 --- /dev/null +++ b/tests/fixtures/persistence/v0.9.0/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) +project(rabitq_v090_fixtures LANGUAGES CXX) + +if(NOT IS_DIRECTORY "${RABITQ_HISTORICAL_SOURCE}") + message(FATAL_ERROR "Set RABITQ_HISTORICAL_SOURCE to the pinned v0.9.0 checkout") +endif() +set(RABITQ_BUILD_TESTS OFF CACHE BOOL "" FORCE) +set(RABITQ_BUILD_SAMPLES OFF CACHE BOOL "" FORCE) +set(RABITQ_BUILD_PYTHON_BINDINGS OFF CACHE BOOL "" FORCE) +set(RABITQ_ENABLE_NATIVE_OPTIMIZATION OFF CACHE BOOL "" FORCE) +add_subdirectory("${RABITQ_HISTORICAL_SOURCE}" historical) +add_executable(generate_fixtures generate.cpp) +target_link_libraries(generate_fixtures PRIVATE rabitqlib::index) diff --git a/tests/fixtures/persistence/v0.9.0/README.md b/tests/fixtures/persistence/v0.9.0/README.md new file mode 100644 index 00000000..8d22c0d5 --- /dev/null +++ b/tests/fixtures/persistence/v0.9.0/README.md @@ -0,0 +1,54 @@ +# Index fixtures from v0.9.0 + +These files were written by release **v0.9.0** using [generate.cpp](generate.cpp), built +from commit `9c7c4a5` on the release branch, whose sources the `v0.9.0` tag contains. +[manifest.json](manifest.json) records the producer and SHA-256 hashes. +Keep these files unchanged; tests never regenerate them with the current writer. + +They freeze [index format 2](../../../../docs/formats.md#index-files-format-2) as its +first release wrote it: each file records the seed (42) and the writer version, and +together they use every section kind 0.9 writes and each metric, including cosine, +for every index type. `generate.cpp` writes them through `IvfIndex`, `HnswIndex` and +`SymqgIndex`, and through `ivf::IVF` and `symqg::QuantizedGraph` for the matrix rotator, +which the new classes do not offer. + +| File | Bits | Metric | Rotator | Notes | +| --- | --- | --- | --- | --- | +| `ivf4_flat_l2` | 4 | L2 | FHT/Kac | Flat routing | +| `ivf7_flatrabitq_cosine` | 7 | cosine | FHT/Kac | FlatRaBitQ routing | +| `ivf32_hnsw_ip` | raw (`nbits=32`) | inner product | FHT/Kac | HNSW routing graph stored in the file | +| `ivf1_flat_matrix_l2` | 1 | L2 | matrix | Flat routing, written by `ivf::IVF` | +| `hnsw1_l2` | 1 | L2 | FHT/Kac | M = 8, `ef_construction` 64 | +| `hnsw5_cosine` | 5 | cosine | FHT/Kac | As above | +| `hnsw9_ip` | 9 | inner product | FHT/Kac | As above | +| `qg32_ip` | raw (`nbits=32`) | inner product | FHT/Kac | Degree 32, PiPNN, `ef_construction` 64 | +| `qg4_cosine` | 4 | cosine | FHT/Kac | As above | +| `qg8_l2` | 8 | L2 | FHT/Kac | As above | +| `qg4_matrix_l2` | 4 | L2 | matrix | As above, written by `symqg::QuantizedGraph` | + +Each index holds the 130 points in 65 original dimensions (96 padded) of the +[v0.8.3](../v0.8.3/README.md) fixtures. The IVF-RaBitQ and HNSW-RaBitQ files use its four +clusters of 0, 1, 32 and 97 points, with points 0 and 32 removed: point 0 is the only +point of its cluster, and point 32 is the nearest neighbour of the third query, so the +SymphonyQG results, which have no removal, include it. The cosine indexes get the +centroids scaled to unit length, as their data is. The `.expected` files hold +reference results: IVF-RaBitQ probes every cluster, and the graph indexes search with +`ef_search` 64. + +## Deliberate regeneration + +Build the generator only against an isolated copy of the release: + +```bash +mkdir -p build/fixtures/v0.9.0 +git archive v0.9.0 | tar -x -C build/fixtures/v0.9.0 +cmake -S tests/fixtures/persistence/v0.9.0 -B build/fixtures/v0.9.0-generator \ + -DRABITQ_HISTORICAL_SOURCE="$PWD/build/fixtures/v0.9.0" \ + -DCMAKE_BUILD_TYPE=Release +cmake --build build/fixtures/v0.9.0-generator --target generate_fixtures +``` + +Run it with a new output directory and `OMP_NUM_THREADS=1`. Every index is seeded and +built with one thread, so two runs on the producer in the manifest write identical +bytes; another compiler or ISA may change the results. Each index and its `.expected` +file form a fixed pair. Record new hashes in the manifest before adopting them. diff --git a/tests/fixtures/persistence/v0.9.0/generate.cpp b/tests/fixtures/persistence/v0.9.0/generate.cpp new file mode 100644 index 00000000..2861da60 --- /dev/null +++ b/tests/fixtures/persistence/v0.9.0/generate.cpp @@ -0,0 +1,219 @@ +// Build only against the pinned v0.9.0 source, never the current checkout. Writes index +// format 2 through the 0.9 index classes, and through ivf::IVF and QuantizedGraph for the +// matrix rotator, which the new classes do not offer. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rabitqlib/core/metric.hpp" +#include "rabitqlib/core/types.hpp" +#include "rabitqlib/index/hnsw_index.hpp" +#include "rabitqlib/index/ivf/ivf.hpp" +#include "rabitqlib/index/ivf/types.hpp" +#include "rabitqlib/index/ivf_index.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" + +int main(int argc, char** argv) { + if (argc != 2) { + throw std::invalid_argument("Pass the fixture output directory"); + } + using namespace rabitqlib; + // The v0.8.3 fixtures' data: cluster sizes 0, 1, 32 and 97. + constexpr size_t kCount = 130, kDim = 65, kClusters = 4, kQueries = 3, kTopK = 5; + constexpr uint32_t kSeed = 42; + const std::filesystem::path directory(argv[1]); + std::filesystem::create_directories(directory); + uint32_t state = 713; + const auto next = [&state] { + state = state * 1664525U + 1013904223U; + return static_cast(static_cast((state >> 8) % 2001) - 1000) / 256.0F; + }; + std::vector data(kCount * kDim), queries(kQueries * kDim); + std::vector centroids(kClusters * kDim); + for (auto& value : data) { + value = next(); + } + for (auto& value : queries) { + value = next(); + } + for (auto& value : centroids) { + value = next(); + } + // Cosine indexes scale data and queries to unit length; give them unit centroids too. + std::vector unit_centroids(centroids); + for (size_t c = 0; c < kClusters; ++c) { + float* row = unit_centroids.data() + (c * kDim); + double norm = 0; + for (size_t j = 0; j < kDim; ++j) { + norm += static_cast(row[j]) * row[j]; + } + const auto scale = static_cast(1.0 / std::sqrt(norm)); + for (size_t j = 0; j < kDim; ++j) { + row[j] *= scale; + } + } + const auto centroids_for = [&](MetricType metric) { + return metric == METRIC_COSINE ? unit_centroids.data() : centroids.data(); + }; + std::vector clusters(kCount, 3); + clusters[0] = 1; + for (size_t i = 1; i < 33; ++i) { + clusters[i] = 2; + } + // Point 0 is the only point of cluster 1. Point 32 is the nearest neighbour of the + // third query, so search results show whether removal markers are honoured. + const Id removed[] = {0, 32}; + const auto path_of = [&](const std::string& name) { + return (directory / (name + ".index")).string(); + }; + std::vector ids(kQueries * kTopK); + std::vector distances(ids.size()); + const auto write_expected = [&](const std::string& name) { + std::ofstream expected(directory / (name + ".expected"), std::ios::binary); + expected.exceptions(std::ios::failbit | std::ios::badbit); + expected << std::setprecision(std::numeric_limits::max_digits10); + expected << kCount << ' ' << kDim << ' ' << kQueries << ' ' << kTopK << '\n'; + for (size_t i = 0; i < queries.size(); ++i) { + expected << queries[i] << (i + 1 == queries.size() ? '\n' : ' '); + } + for (size_t i = 0; i < ids.size(); ++i) { + expected << ids[i] << ' ' << distances[i] << '\n'; + } + expected.close(); + }; + AddOptions add_options; + add_options.cluster_ids = clusters.data(); + add_options.num_threads = 1; + + const struct { + const char* name; + size_t nbits; + MetricType metric; + ivf::Routing routing; + } ivf_cases[] = { + {"ivf4_flat_l2", 4, METRIC_L2, ivf::Routing::Flat}, + {"ivf7_flatrabitq_cosine", 7, METRIC_COSINE, ivf::Routing::FlatRaBitQ}, + {"ivf32_hnsw_ip", 32, METRIC_IP, ivf::Routing::HNSW}, + }; + for (const auto& c : ivf_cases) { + IvfOptions options; + options.metric = c.metric; + options.nbits = c.nbits; + options.routing = c.routing; + options.seed = kSeed; + IvfIndex index(kDim, kClusters, options); + index.set_centroids(centroids_for(c.metric), 1); + index.add(data.data(), kCount, add_options); + index.remove(removed, 2); + index.save(path_of(c.name).c_str()); + IvfSearchOptions search; + search.nprobe = kClusters; + index.search(queries.data(), kQueries, kTopK, ids.data(), distances.data(), search); + write_expected(c.name); + } + { + ivf::IVF index( + kDim, + kClusters, + 1, + METRIC_L2, + kSeed, + RotatorType::MatrixRotator, + ivf::InitializerType::Flat + ); + index.set_centroids(centroids.data(), 1); + index.add(data.data(), kCount, clusters.data(), false, 1); + const PID legacy_removed[] = {0, 32}; + index.remove(legacy_removed, 2); + index.save(path_of("ivf1_flat_matrix_l2").c_str()); + std::vector legacy_ids(ids.size()); + index.search_batch( + queries.data(), kQueries, kTopK, kClusters, legacy_ids.data(), distances.data() + ); + ids.assign(legacy_ids.begin(), legacy_ids.end()); + write_expected("ivf1_flat_matrix_l2"); + } + + GraphSearchOptions graph_search; + graph_search.ef_search = 64; + const struct { + const char* name; + size_t nbits; + MetricType metric; + } hnsw_cases[] = { + {"hnsw1_l2", 1, METRIC_L2}, + {"hnsw5_cosine", 5, METRIC_COSINE}, + {"hnsw9_ip", 9, METRIC_IP}, + }; + for (const auto& c : hnsw_cases) { + HnswOptions options; + options.metric = c.metric; + options.nbits = c.nbits; + options.num_clusters = kClusters; + options.M = 8; + options.ef_construction = 64; + options.seed = kSeed; + HnswIndex index(kDim, options); + index.set_centroids(centroids_for(c.metric)); + index.add(data.data(), kCount, add_options); + index.remove(removed, 2); + index.save(path_of(c.name).c_str()); + index.search( + queries.data(), kQueries, kTopK, ids.data(), distances.data(), graph_search + ); + write_expected(c.name); + } + + const struct { + const char* name; + size_t nbits; + MetricType metric; + } qg_cases[] = { + {"qg32_ip", 32, METRIC_IP}, + {"qg4_cosine", 4, METRIC_COSINE}, + {"qg8_l2", 8, METRIC_L2}, + }; + for (const auto& c : qg_cases) { + SymqgOptions options; + options.metric = c.metric; + options.nbits = c.nbits; + options.ef_construction = 64; + options.seed = kSeed; + SymqgIndex index(kDim, options); + index.add(data.data(), kCount, 1); + index.save(path_of(c.name).c_str()); + index.search( + queries.data(), kQueries, kTopK, ids.data(), distances.data(), graph_search + ); + write_expected(c.name); + } + { + symqg::QuantizedGraph index( + kCount, kDim, 32, METRIC_L2, RotatorType::MatrixRotator, 4, kSeed + ); + symqg::QGBuilder builder( + index, 64, data.data(), 1, symqg::QGInitialization::PiPNN, kSeed + ); + builder.build(); + index.save(path_of("qg4_matrix_l2").c_str()); + std::vector legacy_ids(ids.size()); + index.set_ef(64); + index.search_batch( + queries.data(), kQueries, kTopK, legacy_ids.data(), distances.data(), 1 + ); + ids.assign(legacy_ids.begin(), legacy_ids.end()); + write_expected("qg4_matrix_l2"); + } + return 0; +} diff --git a/tests/fixtures/persistence/v0.9.0/hnsw1_l2.expected b/tests/fixtures/persistence/v0.9.0/hnsw1_l2.expected new file mode 100644 index 00000000..96a62dad --- /dev/null +++ b/tests/fixtures/persistence/v0.9.0/hnsw1_l2.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +59 457.198364 +94 473.985107 +92 476.936432 +13 481.009399 +1 482.431854 +71 283.250702 +120 364.552856 +102 403.540588 +50 411.44928 +28 413.655273 +119 332.883972 +48 336.432617 +12 339.079712 +100 404.918793 +105 407.847778 diff --git a/tests/fixtures/persistence/v0.9.0/hnsw1_l2.index b/tests/fixtures/persistence/v0.9.0/hnsw1_l2.index new file mode 100644 index 00000000..a59fc563 Binary files /dev/null and b/tests/fixtures/persistence/v0.9.0/hnsw1_l2.index differ diff --git a/tests/fixtures/persistence/v0.9.0/hnsw5_cosine.expected b/tests/fixtures/persistence/v0.9.0/hnsw5_cosine.expected new file mode 100644 index 00000000..d2f59785 --- /dev/null +++ b/tests/fixtures/persistence/v0.9.0/hnsw5_cosine.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +128 0.714526892 +92 0.715393543 +46 0.738908947 +13 0.764322877 +5 0.782529056 +112 0.736054361 +128 0.750433564 +11 0.771253109 +31 0.774589837 +14 0.788271546 +106 0.772841275 +3 0.785391212 +87 0.792515814 +49 0.819440484 +127 0.825468898 diff --git a/tests/fixtures/persistence/v0.9.0/hnsw5_cosine.index b/tests/fixtures/persistence/v0.9.0/hnsw5_cosine.index new file mode 100644 index 00000000..0439e409 Binary files /dev/null and b/tests/fixtures/persistence/v0.9.0/hnsw5_cosine.index differ diff --git a/tests/fixtures/persistence/v0.9.0/hnsw9_ip.expected b/tests/fixtures/persistence/v0.9.0/hnsw9_ip.expected new file mode 100644 index 00000000..0e7a70b7 --- /dev/null +++ b/tests/fixtures/persistence/v0.9.0/hnsw9_ip.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +128 -95.0039978 +92 -82.1838989 +46 -80.9703903 +13 -72.1300278 +50 -71.5017166 +128 -73.8795013 +112 -73.7232742 +11 -71.3241043 +14 -64.0636902 +31 -59.805809 +106 -66.4059906 +3 -59.8741341 +87 -57.3470726 +127 -54.1831055 +49 -53.0662918 diff --git a/tests/fixtures/persistence/v0.9.0/hnsw9_ip.index b/tests/fixtures/persistence/v0.9.0/hnsw9_ip.index new file mode 100644 index 00000000..64cd5feb Binary files /dev/null and b/tests/fixtures/persistence/v0.9.0/hnsw9_ip.index differ diff --git a/tests/fixtures/persistence/v0.9.0/ivf1_flat_matrix_l2.expected b/tests/fixtures/persistence/v0.9.0/ivf1_flat_matrix_l2.expected new file mode 100644 index 00000000..6ade77de --- /dev/null +++ b/tests/fixtures/persistence/v0.9.0/ivf1_flat_matrix_l2.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +3 340.210754 +46 346.327026 +67 439.798828 +92 448.488617 +13 468.278442 +14 383.365326 +20 424.577423 +31 426.885254 +46 432.350494 +95 460.964569 +87 255.314728 +12 318.823303 +39 326.600342 +66 340.024689 +3 413.702972 diff --git a/tests/fixtures/persistence/v0.9.0/ivf1_flat_matrix_l2.index b/tests/fixtures/persistence/v0.9.0/ivf1_flat_matrix_l2.index new file mode 100644 index 00000000..98497b05 Binary files /dev/null and b/tests/fixtures/persistence/v0.9.0/ivf1_flat_matrix_l2.index differ diff --git a/tests/fixtures/persistence/v0.9.0/ivf32_hnsw_ip.expected b/tests/fixtures/persistence/v0.9.0/ivf32_hnsw_ip.expected new file mode 100644 index 00000000..3b15626c --- /dev/null +++ b/tests/fixtures/persistence/v0.9.0/ivf32_hnsw_ip.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +128 -94.8744507 +92 -82.2540436 +46 -80.8800812 +13 -71.9051971 +50 -71.6611023 +112 -73.9705811 +128 -73.9433899 +11 -71.4328156 +14 -64.1144104 +31 -59.65448 +106 -66.686676 +3 -59.7108917 +87 -57.427536 +127 -53.9758759 +49 -53.0118713 diff --git a/tests/fixtures/persistence/v0.9.0/ivf32_hnsw_ip.index b/tests/fixtures/persistence/v0.9.0/ivf32_hnsw_ip.index new file mode 100644 index 00000000..da9e8c9e Binary files /dev/null and b/tests/fixtures/persistence/v0.9.0/ivf32_hnsw_ip.index differ diff --git a/tests/fixtures/persistence/v0.9.0/ivf4_flat_l2.expected b/tests/fixtures/persistence/v0.9.0/ivf4_flat_l2.expected new file mode 100644 index 00000000..c30f3dd3 --- /dev/null +++ b/tests/fixtures/persistence/v0.9.0/ivf4_flat_l2.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +92 424.068817 +46 476.773743 +128 490.13501 +3 492.354584 +43 495.325928 +112 407.699097 +31 414.629272 +129 450.556732 +90 458.903687 +14 466.167603 +3 450.073029 +87 452.585632 +48 469.897736 +106 471.257629 +45 479.921021 diff --git a/tests/fixtures/persistence/v0.9.0/ivf4_flat_l2.index b/tests/fixtures/persistence/v0.9.0/ivf4_flat_l2.index new file mode 100644 index 00000000..57e6d651 Binary files /dev/null and b/tests/fixtures/persistence/v0.9.0/ivf4_flat_l2.index differ diff --git a/tests/fixtures/persistence/v0.9.0/ivf7_flatrabitq_cosine.expected b/tests/fixtures/persistence/v0.9.0/ivf7_flatrabitq_cosine.expected new file mode 100644 index 00000000..7def5280 --- /dev/null +++ b/tests/fixtures/persistence/v0.9.0/ivf7_flatrabitq_cosine.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +92 0.713346362 +128 0.715776801 +46 0.740080595 +13 0.77520448 +50 0.786955357 +112 0.734882593 +128 0.753938615 +11 0.772555351 +31 0.774727821 +14 0.777464151 +106 0.778710485 +3 0.786773443 +87 0.798561811 +49 0.817374527 +127 0.821094155 diff --git a/tests/fixtures/persistence/v0.9.0/ivf7_flatrabitq_cosine.index b/tests/fixtures/persistence/v0.9.0/ivf7_flatrabitq_cosine.index new file mode 100644 index 00000000..f48969a0 Binary files /dev/null and b/tests/fixtures/persistence/v0.9.0/ivf7_flatrabitq_cosine.index differ diff --git a/tests/fixtures/persistence/v0.9.0/manifest.json b/tests/fixtures/persistence/v0.9.0/manifest.json new file mode 100644 index 00000000..cd1707fd --- /dev/null +++ b/tests/fixtures/persistence/v0.9.0/manifest.json @@ -0,0 +1,32 @@ +{ + "source_tag": "v0.9.0", + "source_commit": "9c7c4a5a391c46ee17b51bd4a8844bf374d63cea", + "writer": "tests/fixtures/persistence/v0.9.0/generate.cpp", + "producer": "Linux x86-64, g++ 14.3.0, Release, one thread, native optimization OFF", + "byte_order": "little", + "size_t_bytes": 8, + "sha256": { + "v0.9.0/hnsw1_l2.expected": "00af920380168a49f0739b9f180a764c3fac3bbc3a7b31b6acbbf0ecd621f62a", + "v0.9.0/hnsw1_l2.index": "6b094315dfeab27b648dac74cfd5ec3f6378134a42b8538ff871944422205afd", + "v0.9.0/hnsw5_cosine.expected": "12959b3bbb531adac752e05d08970952302ce9132bd471011b79db7fcef17a23", + "v0.9.0/hnsw5_cosine.index": "95145b67d0c30247641b7c03c9de3d318e51e6e7be051ab8b8c90eebda4270b7", + "v0.9.0/hnsw9_ip.expected": "d675cb061e65df4699e27cf44c0ca6d66c33c2bf4794a1a34937756c00b2ea6e", + "v0.9.0/hnsw9_ip.index": "01d930e926a654759640f799d782f882c3fd49ebea13bcf36ef32f4c1c7e578d", + "v0.9.0/ivf1_flat_matrix_l2.expected": "56c05f0d88de854c4d5d2dd7791b1e925b81db7584d398478b323f18066c5994", + "v0.9.0/ivf1_flat_matrix_l2.index": "e1f658f16baa4a89ff3a53ece7314b732c3efbb3bddd42e9d002ab05f4df8165", + "v0.9.0/ivf32_hnsw_ip.expected": "1e08fd7ae0e84825b6e85bd2ff36c45f1e5670a97798ade5de2cf8c94c4ff992", + "v0.9.0/ivf32_hnsw_ip.index": "c0748368bea15a1505e8205636a032dff1f956386f5d21567ecc280fc63df6d1", + "v0.9.0/ivf4_flat_l2.expected": "ba1cc9f717d5273cd89fee5d4ce535f1e8c4df085a2095aff51f5cd4717f8d17", + "v0.9.0/ivf4_flat_l2.index": "eb9da556a6c81a6242aeda5d5e255d857182697a087c1074e6a84a058e130320", + "v0.9.0/ivf7_flatrabitq_cosine.expected": "4d14d9304617f07cc23ced5277a31ce8936ec7aab8662e319ab143ba2336095c", + "v0.9.0/ivf7_flatrabitq_cosine.index": "e7dfe8f31f9df5a82b72124434c57d5524a6503637a3ff223380348fec92667c", + "v0.9.0/qg32_ip.expected": "3ecb6604dce2108556e5e48130d4e9902d7ef7f0ef81aba39a3caa40b62230fe", + "v0.9.0/qg32_ip.index": "1910a45675b90dd0d08700ba01e365179f6de10e0365ef3696571ad667ecd8c9", + "v0.9.0/qg4_cosine.expected": "07b1be3375afa7746cb74ca2c69410c59c6adfb479e4fbb861db9dad6f01ed30", + "v0.9.0/qg4_cosine.index": "131f62a461b0b627c82d8b58ba9f54b13a7a53853390c51d5d799c175c7fecb1", + "v0.9.0/qg4_matrix_l2.expected": "b892c11a3138e9f7590bb22806ad870f0f24957be5f2ccd604823dd997b2ec6c", + "v0.9.0/qg4_matrix_l2.index": "c4f93a05d44e6952fec1d0af1206cb6a17456ef6ce4e96522ae8ad2ce55dc556", + "v0.9.0/qg8_l2.expected": "85b16ad29dbf84336415217c94e343834c9072db05702add532b72802904bc1e", + "v0.9.0/qg8_l2.index": "b09e7044dc71ea81e0ceb5c170bb69c766a10f517b0f970000b57d7d7270cb10" + } +} diff --git a/tests/fixtures/persistence/v0.9.0/qg32_ip.expected b/tests/fixtures/persistence/v0.9.0/qg32_ip.expected new file mode 100644 index 00000000..750cfd52 --- /dev/null +++ b/tests/fixtures/persistence/v0.9.0/qg32_ip.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +128 -94.8744507 +92 -82.2540436 +46 -80.8800812 +13 -71.9051971 +50 -71.6611023 +112 -73.9705811 +128 -73.9433899 +11 -71.4328156 +14 -64.1144104 +31 -59.65448 +32 -72.5804443 +106 -66.686676 +3 -59.7108917 +87 -57.427536 +127 -53.9758759 diff --git a/tests/fixtures/persistence/v0.9.0/qg32_ip.index b/tests/fixtures/persistence/v0.9.0/qg32_ip.index new file mode 100644 index 00000000..7c6c0449 Binary files /dev/null and b/tests/fixtures/persistence/v0.9.0/qg32_ip.index differ diff --git a/tests/fixtures/persistence/v0.9.0/qg4_cosine.expected b/tests/fixtures/persistence/v0.9.0/qg4_cosine.expected new file mode 100644 index 00000000..71c69a97 --- /dev/null +++ b/tests/fixtures/persistence/v0.9.0/qg4_cosine.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +128 0.720068216 +92 0.730652094 +46 0.745972335 +13 0.775076568 +50 0.781755328 +112 0.740919471 +128 0.76514554 +11 0.765724301 +31 0.777403355 +14 0.784168839 +32 0.752260208 +106 0.775019646 +87 0.776548266 +3 0.79023689 +12 0.817582071 diff --git a/tests/fixtures/persistence/v0.9.0/qg4_cosine.index b/tests/fixtures/persistence/v0.9.0/qg4_cosine.index new file mode 100644 index 00000000..5a5200c2 Binary files /dev/null and b/tests/fixtures/persistence/v0.9.0/qg4_cosine.index differ diff --git a/tests/fixtures/persistence/v0.9.0/qg4_matrix_l2.expected b/tests/fixtures/persistence/v0.9.0/qg4_matrix_l2.expected new file mode 100644 index 00000000..b04a3199 --- /dev/null +++ b/tests/fixtures/persistence/v0.9.0/qg4_matrix_l2.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +92 419.694672 +46 479.768677 +128 486.59967 +13 500.980713 +43 501.949097 +112 415.956085 +31 419.644714 +129 448.679504 +128 457.285095 +71 464.834045 +32 425.477539 +3 443.738098 +87 469.713196 +12 472.3125 +48 478.444855 diff --git a/tests/fixtures/persistence/v0.9.0/qg4_matrix_l2.index b/tests/fixtures/persistence/v0.9.0/qg4_matrix_l2.index new file mode 100644 index 00000000..5a44f8dd Binary files /dev/null and b/tests/fixtures/persistence/v0.9.0/qg4_matrix_l2.index differ diff --git a/tests/fixtures/persistence/v0.9.0/qg8_l2.expected b/tests/fixtures/persistence/v0.9.0/qg8_l2.expected new file mode 100644 index 00000000..ef948425 --- /dev/null +++ b/tests/fixtures/persistence/v0.9.0/qg8_l2.expected @@ -0,0 +1,17 @@ +130 65 3 5 +0.7734375 -1.265625 2.28125 -3.40234375 -1.609375 0.91796875 2.7109375 -0.20703125 0.31640625 0.62890625 1.296875 2.8203125 -1.46484375 -0.171875 -1.53515625 2.46875 3.79296875 -3.61328125 0.52734375 -3.21484375 2.94921875 2.4453125 0.7265625 -1.44921875 2.546875 -2.00390625 -2.8125 -1.609375 -2.1953125 -3.625 2.00390625 -1.5 -0.57421875 3.296875 -2.828125 -3.30078125 -3.03515625 3.25 -2.89453125 0.54296875 1.21875 -2.16015625 -3.34375 2.84765625 -2.24609375 -1.34765625 -0.1484375 -3.7265625 -3.87109375 -0.2890625 1.7421875 -3.08203125 0.66015625 -1.3359375 1.62109375 2.5 -2.8828125 1.203125 -2.82421875 2.0703125 1.05078125 -2.21875 -0.7578125 -1.1796875 1.86328125 -1.00390625 -2.02734375 -2.69140625 3.0703125 -0.796875 -0.78515625 -2.34375 3.60546875 -1.81640625 -1.3671875 -0.80078125 3.63671875 2.00390625 -3.828125 1.8125 1.34765625 0.5234375 0.8359375 3.71484375 1.19140625 0.54296875 -0.06640625 3.25390625 1.68359375 -1.59375 3.03515625 1.22265625 -3.2734375 0.05859375 -0.84765625 -0.96484375 1.046875 -2.58984375 -0.3828125 -1.765625 0.00390625 3.5 0.1484375 0.234375 -1.9609375 -0.375 -3.37109375 -0.40234375 1.34765625 -3.12109375 1 -1.16015625 1.83984375 2.46484375 1.25 -1.3125 -3.7734375 -0.9765625 -1.390625 -0.16015625 -1.6484375 -2.6015625 2.40234375 3.03515625 2.64453125 -1.49609375 -1.9765625 -2.3515625 -1.57421875 -0.18359375 1.37109375 1.4765625 2.46875 -0.75390625 -0.6171875 1.484375 2.1328125 -0.73046875 -1.640625 3.1875 0.6484375 2.80859375 2.79296875 -1.578125 -3.72265625 -3.0546875 -3.57421875 -3.1953125 -3.51171875 -0.9921875 1.171875 0.7734375 -3.08984375 -0.07421875 1.25390625 1.55078125 -2.6171875 -0.5703125 0.21484375 -0.90234375 -0.65234375 0.44140625 1.62109375 0.76171875 2.58984375 -2.8046875 0.90625 -3.09375 -1.3515625 0.5625 1.84765625 1.8515625 2.03125 1.51171875 -3.25 -1.32421875 0.94140625 -1.0390625 2.3984375 -3.0546875 -3.3828125 3.109375 0.01171875 -1.3203125 -0.328125 -0.94140625 0.4296875 2.43359375 -1.5390625 -2.58203125 2.53515625 -2.578125 0.0703125 2.79296875 -1.49609375 +92 420.231934 +46 471.50592 +128 482.013702 +43 495.519135 +3 497.544495 +31 413.404266 +112 416.135986 +129 460.688141 +71 463.832886 +128 464.406372 +32 424.081055 +3 449.31604 +87 462.241821 +12 477.63147 +48 481.300659 diff --git a/tests/fixtures/persistence/v0.9.0/qg8_l2.index b/tests/fixtures/persistence/v0.9.0/qg8_l2.index new file mode 100644 index 00000000..0a2df916 Binary files /dev/null and b/tests/fixtures/persistence/v0.9.0/qg8_l2.index differ diff --git a/tests/integration/cpp_example_index_check.cpp b/tests/integration/cpp_example_index_check.cpp index 9a613046..ffe03410 100644 --- a/tests/integration/cpp_example_index_check.cpp +++ b/tests/integration/cpp_example_index_check.cpp @@ -8,8 +8,8 @@ #include "rabitqlib/core/detail/eigen.hpp" #include "rabitqlib/core/metric.hpp" -#include "rabitqlib/index/hnsw/hnsw.hpp" -#include "rabitqlib/index/ivf/ivf.hpp" +#include "rabitqlib/index/hnsw_index.hpp" +#include "rabitqlib/index/ivf_index.hpp" #include "rabitqlib/index/types.hpp" #include "rabitqlib/utils/io.hpp" @@ -19,45 +19,44 @@ int main(int argc, char** argv) { throw std::invalid_argument("Expected kind, index, data, metric and bits"); } const std::string kind(argv[1]); - const auto metric = - std::string(argv[4]) == "ip" ? rabitqlib::METRIC_IP : rabitqlib::METRIC_L2; + const std::string metric_name(argv[4]); + const auto metric = metric_name == "ip" ? rabitqlib::METRIC_IP + : metric_name == "cosine" ? rabitqlib::METRIC_COSINE + : rabitqlib::METRIC_L2; const size_t bits = std::stoull(argv[5]); rabitqlib::RowMajorArray data; rabitqlib::load_vecs(argv[3], data); const size_t count = data.rows(); const size_t dim = data.cols(); const auto check = [&](const auto& index, const auto& search) { - if (index.dimension() != dim || index.num_stored_points() != count || - index.num_points() != count || index.metric_type() != metric || + if (index.dim() != dim || index.num_stored_points() != count || + index.num_points() != count || index.metric() != metric || index.nbits() != bits) { throw std::runtime_error("Example index metadata does not match input"); } - // Unit vectors make self the exact winner for the IP fixture as well. + // Unit vectors make self the exact winner for the IP and cosine fixtures too. for (size_t row : std::array{0, count / 2, count - 1}) { - rabitqlib::PID id = rabitqlib::kPidMax; + rabitqlib::Id id = rabitqlib::kNoId; float distance = 0; search(data.data() + row * dim, id, distance); - if (id != row || !std::isfinite(distance)) { + if (id != static_cast(row) || !std::isfinite(distance)) { throw std::runtime_error("Example index did not retrieve its input"); } } }; if (kind == "ivf") { - rabitqlib::ivf::IVF index; - index.load(argv[2]); - check(index, [&](const float* query, rabitqlib::PID& id, float& distance) { - index.search(query, 1, index.num_clusters(), &id, &distance); + const auto index = rabitqlib::IvfIndex::load(argv[2]); + rabitqlib::IvfSearchOptions options; + options.nprobe = index.num_clusters(); + check(index, [&](const float* query, rabitqlib::Id& id, float& distance) { + index.search(query, 1, 1, &id, &distance, options); }); } else if (kind == "hnsw") { - rabitqlib::hnsw::HierarchicalNSW index; - index.load(argv[2]); - check(index, [&](const float* query, rabitqlib::PID& id, float& distance) { - const auto hits = index.search(query, 1, 1, count, 1); - if (hits.size() != 1 || hits[0].size() != 1) { - throw std::runtime_error("Example index returned no neighbor"); - } - distance = hits[0][0].first; - id = hits[0][0].second; + const auto index = rabitqlib::HnswIndex::load(argv[2]); + rabitqlib::GraphSearchOptions options; + options.ef_search = count; + check(index, [&](const float* query, rabitqlib::Id& id, float& distance) { + index.search(query, 1, 1, &id, &distance, options); }); } else { throw std::invalid_argument("Expected ivf or hnsw"); diff --git a/tests/python/format2_file.py b/tests/python/format2_file.py new file mode 100644 index 00000000..8887df5e --- /dev/null +++ b/tests/python/format2_file.py @@ -0,0 +1,93 @@ +"""Read, patch and convert index format 2 files in tests (docs/formats.md).""" + +from __future__ import annotations + +import struct +import zlib + +MAGIC = b"RABQINDX" +ROTATOR = 1 +IVF_PARAMS = 256 +IVF_CLUSTER_SIZES = 257 +IVF_ROUTING = {1: 258, 2: 259, 3: 260} # by stored initializer: flat, flat_rabitq, hnsw +IVF_HNSW_ROUTING = 260 +IVF_CODES = 261 +IVF_RERANK = 262 +IVF_IDS = 263 +HNSW_PARAMS = 512 +QG_PARAMS = 768 +QG_CENTROID = 769 +QG_RECORDS = 770 + + +def sections(data: bytes) -> dict[int, tuple[int, int]]: + """Map each section kind of a format-2 file to its (offset, size).""" + table, count = struct.unpack_from(" bytes: + offset, size = sections(data)[kind] + return bytes(data[offset : offset + size]) + + +def padded_dim(data: bytes) -> int: + return struct.unpack_from(" None: + """Recompute section and header checksums after a same-size edit in place.""" + table, count = struct.unpack_from(" tuple[bytes, bytes | None]: + """Convert an IVF-RaBitQ format-2 file to the layout releases up to 0.8 wrote. + + Returns the RABQIDX1 version 2 index and, for HNSW routing, its ``.hnsw`` + sidecar. Tests use it to build earlier layouts that no fixture covers. + """ + assert data[:8] == MAGIC + present = sections(data) + metric = struct.unpack_from("= hnsw.num_stored_points - assert message.startswith("HnswIndex.max_elements is deprecated; use capacity") - - -def test_hnsw_reserve_only_grows(base_data): - index = HnswIndex(DIM, nbits=4, num_clusters=4, seed=3) - silently(lambda: index.reserve(500)) - assert index.capacity == 500 - index.add(base_data, num_threads=1) - for smaller in (0, len(base_data), 499, np.int64(500)): - silently(lambda smaller=smaller: index.reserve(smaller)) - assert index.capacity == 500 - silently(lambda: index.reserve(600)) - assert index.capacity == 600 - with pytest.raises(ValueError, match="^num_points must be non-negative$"): - index.reserve(-1) - with pytest.raises(TypeError): - index.reserve(1.5) - # resize still shrinks, as in 0.8, and warns. - _, message = single_deprecation(lambda: index.resize(len(base_data))) - assert message.startswith("HnswIndex.resize() is deprecated; use reserve()") - assert index.capacity == len(base_data) - - -def test_reserve_cluster_replaces_ivf_reserve(base_data): - index = IvfIndex(DIM, 4, nbits=4, routing="flat", seed=3) - index.train(base_data, num_threads=1) - silently(lambda: index.reserve_cluster(0, 500)) - silently(lambda: index.reserve_cluster(cluster_id=1, num_points=np.int64(500))) - _, message = single_deprecation(lambda: index.reserve(2, 500)) - assert message.startswith("IvfIndex.reserve() is deprecated; use reserve_cluster()") - index.add(base_data, num_threads=1) - assert len(index) == len(base_data) - # Both names reach the extension: it rejects the same arguments for each. - for reserve in (index.reserve_cluster, index.reserve): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - with pytest.raises(ValueError, match="^cluster_id must be in"): - reserve(4, 1) - with pytest.raises(ValueError, match="^num_points must be non-negative$"): - reserve(0, -1) - untrained = IvfIndex(DIM, 4) - with pytest.raises( - RuntimeError, - match="^IvfIndex must be trained or loaded before reserve_cluster$", - ): - untrained.reserve_cluster(0, 1) - with ( - pytest.warns(DeprecationWarning), - pytest.raises( - RuntimeError, match="^IvfIndex must be trained or loaded before reserve$" - ), - ): - untrained.reserve(0, 1) - - -@pytest.mark.parametrize("kind", ["hnsw", "symqg"]) -def test_ef_search_replaces_ef(kind, request, query_data): - index = request.getfixturevalue(kind) - name = type(index).__name__ - queries = query_data - # A breadth of k finds other neighbors than the default of max(k, 64), so a - # wrapper that dropped the argument would fail the comparisons below. - expected = silently(lambda: index.search(queries, 3, ef_search=3)) - assert not np.array_equal(expected[0], index.search(queries, 3)[0]) - assert_same(silently(lambda: index.search(queries, 3, 3)), expected) - assert_same( - silently(lambda: index.search(queries, k=3, ef_search=3, num_threads=1)), - expected, - ) - actual, message = single_deprecation(lambda: index.search(queries, 3, ef=3)) - assert message.startswith(f"{name}.search(ef=...) is deprecated; use ef_search=") - assert_same(actual, expected) - actual, message = single_deprecation(lambda: index.search(queries, 3, 3, 1)) - assert message.startswith( - f"passing num_threads to {name}.search() by position is deprecated" - ) - assert_same(actual, expected) - # Every spelling reaches the extension, which rejects a negative value. - for call in ( - lambda: index.search(queries, 3, -1), - lambda: index.search(queries, 3, ef_search=-1), - lambda: index.search(queries, 3, ef=-1), - lambda: index.search(queries, 3, num_threads=-1), - lambda: index.search(queries, 3, 3, -1), - ): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - with pytest.raises(TypeError): - call() - parameters = inspect.signature(type(index).search).parameters - assert list(parameters) == ["self", "queries", "k", "ef_search", "num_threads"] - assert parameters["num_threads"].kind is inspect.Parameter.KEYWORD_ONLY - - -@pytest.mark.parametrize("kind", ["ivf", "hnsw", "symqg"]) -def test_malformed_search_calls_raise_before_any_warning(kind, request, query_data): - index = request.getfixturevalue(kind) - name = type(index).__name__ - queries = query_data - breadth = "nprobe" if kind == "ivf" else "ef_search" - calls = [ - (lambda: index.search(queries, 3, 4, **{breadth: 4}), "multiple values"), - (lambda: index.search(queries, 3, 4, 1, 2, 3), "positional arguments"), - ] - if kind == "ivf": - calls.append( - ( - lambda: index.search(queries, 3, 4, False, high_accuracy=False), - "got multiple values for argument 'high_accuracy'", - ) - ) - calls.append( - ( - lambda: index.search(queries, 3, 4, False, 1, num_threads=1), - "got multiple values for argument 'num_threads'", - ) - ) - else: - calls.append( - ( - lambda: index.search(queries, 3, 4, 1, num_threads=1), - "got multiple values for argument 'num_threads'", - ) - ) - calls.append( - ( - lambda: index.search(queries, 3, ef=4, ef_search=4), - "got both ef_search and its old name ef", - ) - ) - calls.append( - ( - lambda: index.search(queries, 3, 4, ef=4), - "got both ef_search and its old name ef", - ) - ) - for call, message in calls: - # silently turns a warning into an error, so a TypeError here means the - # call was rejected first. - with pytest.raises(TypeError, match=f"^{name}\\.search\\(\\) .*{message}"): - silently(call) - - -@pytest.mark.parametrize("kind", ["hnsw", "symqg"]) -@pytest.mark.parametrize("zero", [0, np.int64(0), False, np.float32(0)]) -def test_zero_breadth_selects_the_default_and_warns(kind, zero, request, base_data): - index = request.getfixturevalue(kind) - queries = base_data[:5] - expected = silently(lambda: index.search(queries, 3)) - assert_same(silently(lambda: index.search(queries, 3, None)), expected) - for call in ( - lambda: index.search(queries, 3, zero), - lambda: index.search(queries, 3, ef_search=zero), - ): - actual, message = single_deprecation(call) - assert message.startswith( - f"{type(index).__name__}.search(ef_search=0) is deprecated; pass None" - ) - assert_same(actual, expected) - - -def test_ivf_search_options_become_keyword_only(ivf, base_data): - queries = base_data[:5] - expected = silently( - lambda: ivf.search(queries, 3, 4, high_accuracy=False, num_threads=1) - ) - assert_same( - silently(lambda: ivf.search(queries, 3, nprobe=4, high_accuracy=False)), - expected, - ) - actual, message = single_deprecation(lambda: ivf.search(queries, 3, 4, False)) - assert message.startswith( - "passing high_accuracy to IvfIndex.search() by position is deprecated" - ) - assert_same(actual, expected) - actual, message = single_deprecation(lambda: ivf.search(queries, 3, 4, False, 1)) - assert message.startswith( - "passing high_accuracy, num_threads to IvfIndex.search() by position" - ) - assert_same(actual, expected) - parameters = inspect.signature(IvfIndex.search).parameters - assert [ - name - for name, parameter in parameters.items() - if parameter.kind is inspect.Parameter.KEYWORD_ONLY - ] == ["high_accuracy", "num_threads"] - - -@pytest.mark.parametrize("zero", [0, np.int64(0), False, np.float32(0)]) -def test_zero_nprobe_selects_the_default_and_warns(ivf, zero, base_data): - queries = base_data[:5] - expected = silently(lambda: ivf.search(queries, 3)) - for call in ( - lambda: ivf.search(queries, 3, zero), - lambda: ivf.search(queries, 3, nprobe=zero), - ): - actual, message = single_deprecation(call) - assert message.startswith("IvfIndex.search(nprobe=0) is deprecated; pass None") - assert_same(actual, expected) - - -def test_hnsw_seed_above_32_bits_warns(): - for seed in (0, 100, 2**32 - 1, np.uint32(7)): - assert silently(lambda seed=seed: HnswIndex(DIM, seed=seed)).seed == seed - index, message = single_deprecation(lambda: HnswIndex(DIM, seed=2**40 + 5)) - assert message.startswith("HnswIndex seeds above 2**32 - 1 are deprecated") - assert index.seed == 2**40 + 5 - assert index.cp.seed == 5 # the low 32 bits, as before - - -def test_deprecated_search_batch_warns_once(symqg, query_data): - expected = silently(lambda: symqg.search(query_data, 3, 3)) - assert not np.array_equal(expected[0], symqg.search(query_data, 3)[0]) - actual, message = single_deprecation( - lambda: symqg.search_batch(query_data, 3, 3, 1) - ) - assert message.startswith("SymqgIndex.search_batch() is deprecated; use search()") - assert_same(actual, expected) - - -def test_unchanged_forms_stay_silent(ivf, hnsw, symqg, query_data): - # 0.9 changes the HnswIndex default seed without a warning in this release. - assert silently(lambda: HnswIndex(DIM)).seed == 100 - # num_threads=0 keeps meaning every available CPU. - for index in (ivf, hnsw, symqg): - silently(lambda index=index: index.search(query_data, 3, num_threads=0)) - - -def test_old_spelling_keeps_its_error_message(): - with ( - pytest.warns(DeprecationWarning, match="use routing="), - pytest.raises(ValueError, match="^initializer must be 'auto', 'flat'"), - ): - IvfIndex(DIM, 8, initializer="unknown") - - -def test_new_members_are_named_after_their_class(ivf, hnsw): - assert HnswIndex.reserve.__qualname__ == "HnswIndex.reserve" - assert IvfIndex.reserve_cluster.__qualname__ == "IvfIndex.reserve_cluster" - for cls in (IvfIndex, HnswIndex, SymqgIndex): - assert cls.search.__qualname__ == f"{cls.__name__}.search" - with pytest.raises( - TypeError, match="^HnswIndex\\.reserve\\(\\) missing 1 required" - ): - hnsw.reserve() - with pytest.raises(AttributeError, match="'routing' of 'IvfIndex'"): - ivf.routing = "flat" - with pytest.raises(AttributeError, match="'capacity' of 'HnswIndex'"): - hnsw.capacity = 1 - - -def test_new_members_are_documented(): - for member in ( - IvfIndex.reserve_cluster, - HnswIndex.reserve, - IvfIndex.search, - HnswIndex.search, - SymqgIndex.search, - ): - assert member.__doc__.strip() - assert "(self:" not in member.__doc__ # no stale native signature line - for cls in (HnswIndex, SymqgIndex): - assert "ef_search : int, optional" in cls.search.__doc__ - assert "\nef : int" not in cls.search.__doc__ - assert "routing : {'auto'" in IvfIndex.__doc__ - assert "initializer :" not in IvfIndex.__doc__ - assert "reserve can preallocate it" in HnswIndex.__doc__ - assert "reserve_cluster can preallocate room" in IvfIndex.add.__doc__ - assert "centroid initializer" not in IvfIndex.add.__doc__ - - -# --- k-means: the names of issue #233 ----------------------------------------- - - -def qg_kmeans(**parameters): - return QGKMeans(DIM, 80, niter=2, num_threads=1, seed=1, **parameters) - - -def test_qgkmeans_takes_the_index_parameter_names(base_data): - new = silently(lambda: qg_kmeans(nbits=4, max_degree=64, ef_construction=100)) - assert (new.cp.nbits, new.cp.max_degree, new.cp.ef_construction) == (4, 64, 100) - for keyword, value, hint, current in ( - ("quantization_bits", 4, "use nbits=, with 32 instead of 0", "nbits"), - ("graph_degree", 64, "use max_degree=", "max_degree"), - ("ef_build", 100, "use ef_construction=", "ef_construction"), - ): - model, message = single_deprecation( - lambda keyword=keyword, value=value: qg_kmeans(**{keyword: value}), - at=qg_kmeans, - ) - assert message.startswith(f"QGKMeans({keyword}=...) is deprecated; {hint}") - # The old keyword reaches the same setting, which differs from its default. - assert ( - getattr(model.cp, current) - == value - != getattr(QGKMeans(DIM, 80).cp, current) - ) - with pytest.raises( - TypeError, - match=f"^QGKMeans\\(\\) got both {current} and its old name {keyword}$", - ): - silently( - lambda keyword=keyword, value=value, current=current: qg_kmeans( - **{keyword: value, current: value} - ) - ) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - old = qg_kmeans(quantization_bits=4, graph_degree=64, ef_build=100) - new.train(base_data) - old.train(base_data) - np.testing.assert_array_equal(new.centroids, old.centroids) - np.testing.assert_array_equal(new.assignments, old.assignments) - - -def test_qgkmeans_nbits_uses_32_for_raw_vectors(): - assert silently(lambda: QGKMeans(DIM, 80).cp.nbits) == 32 - for nbits, stored in ((32, 0), (4, 4), (8, 8), (np.int64(32), 0)): - model = silently(lambda nbits=nbits: qg_kmeans(nbits=nbits)) - assert model.cp.nbits == nbits - with pytest.warns(DeprecationWarning, match="use nbits"): - assert model.cp.quantization_bits == stored - raw, _ = single_deprecation(lambda: qg_kmeans(quantization_bits=0), at=qg_kmeans) - assert raw.cp.nbits == 32 - for invalid in (0, 16, 33, True): - with pytest.raises(ValueError, match="^nbits must be 4, 8, or 32$"): - qg_kmeans(nbits=invalid) - with pytest.raises(ValueError, match="^nbits must be 4, 8, or 32$"): - QGKMeans(DIM, 80).cp.nbits = invalid - with pytest.raises(TypeError, match="could not convert parameter 'nbits'"): - qg_kmeans(nbits="4") - - -def test_qgkmeans_parameter_attributes_are_renamed(): - cp = QGKMeans(DIM, 80).cp - for old, new, value in ( - ("graph_degree", "max_degree", 64), - ("ef_build", "ef_construction", 100), - ("quantization_bits", "nbits", 8), - ): - silently(lambda new=new, value=value: setattr(cp, new, value)) - assert silently(lambda new=new: getattr(cp, new)) == value - read, message = single_deprecation(lambda old=old: getattr(cp, old)) - assert read == value - assert message.startswith(f"QGKMeansParameters.{old} is deprecated; use {new}") - _, message = single_deprecation( - lambda old=old: setattr(cp, old, 4 if new == "nbits" else 32) - ) - assert message.startswith(f"QGKMeansParameters.{old} is deprecated; use {new}") - assert getattr(cp, new) == (4 if new == "nbits" else 32) - for name in ("nbits", "max_degree", "ef_construction", "graph_degree"): - with pytest.raises(AttributeError, match="unexpected keyword argument"): - RaBitQKMeans(DIM, 4, **{name: 32}) - - -@pytest.mark.parametrize("cls", [QGKMeans, RaBitQKMeans]) -def test_final_assignment_takes_a_string(cls, base_data): - def trained(final_assignment): - model = cls( - DIM, 80, niter=2, num_threads=1, seed=1, final_assignment=final_assignment - ) - model.train(base_data) - return model - - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - modes = rabitqlib.FinalAssignmentMode - for text, member in (("exact", modes.Exact), ("approximate", modes.Approximate)): - by_text = silently(lambda text=text: trained(text)) - # A member is still accepted, silently: its name warned where it was read. - by_member = silently(lambda member=member: trained(member)) - assert by_text.cp.final_assignment == member # reads back as the member - np.testing.assert_array_equal(by_text.assignments, by_member.assignments) - np.testing.assert_array_equal(by_text.distances, by_member.distances) - cp = cls(DIM, 80).cp - silently(lambda cp=cp, text=text: setattr(cp, "final_assignment", text)) - assert cp.final_assignment == member - for invalid in ("Exact", "EXACT", "", "symphonyqg"): - with pytest.raises( - ValueError, match="^final_assignment must be 'approximate' or 'exact'$" - ): - cls(DIM, 80, final_assignment=invalid) - with pytest.raises( - TypeError, match="could not convert parameter 'final_assignment'" - ): - cls(DIM, 80, final_assignment=1) - - -def test_index_training_parameters_take_the_string(base_data): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - modes = rabitqlib.FinalAssignmentMode - for index in (IvfIndex(DIM, 8, seed=3), HnswIndex(DIM, num_clusters=8, seed=3)): - for value, member in ( - ("exact", modes.Exact), - ("approximate", modes.Approximate), - (modes.Exact, modes.Exact), - (modes.SymphonyQG, modes.Approximate), - ): - silently( - lambda index=index, value=value: setattr( - index.cp, "final_assignment", value - ) - ) - assert index.cp.final_assignment == member - with pytest.raises( - ValueError, match="^final_assignment must be 'approximate' or 'exact'$" - ): - index.cp.final_assignment = "Exact" - with pytest.raises( - TypeError, - match="^final_assignment must be 'approximate' or 'exact', not int$", - ): - index.cp.final_assignment = 1 - assert index.cp.final_assignment == modes.Approximate # unchanged by failures - silently(lambda index=index: index.train(base_data, num_threads=1)) - assert index.is_trained - - -def _import_final_assignment_mode(): - from rabitqlib import FinalAssignmentMode - - return FinalAssignmentMode - - -def _import_qg_stats(): - from rabitqlib import QGKMeansIterationStats - - return QGKMeansIterationStats - - -def _import_rabitq_stats(): - from rabitqlib import RaBitQKMeansIterationStats - - return RaBitQKMeansIterationStats - - -@pytest.mark.parametrize( - "name,importer,message", - [ - ( - "FinalAssignmentMode", - _import_final_assignment_mode, - "FinalAssignmentMode is deprecated; pass 'approximate'", - ), - ( - "QGKMeansIterationStats", - _import_qg_stats, - "QGKMeansIterationStats is deprecated; use KMeansIterationStats", - ), - ( - "RaBitQKMeansIterationStats", - _import_rabitq_stats, - "RaBitQKMeansIterationStats is deprecated; use KMeansIterationStats", - ), - ], -) -def test_names_that_leave_the_package_warn_once(name, importer, message): - value, text = single_deprecation(lambda: getattr(rabitqlib, name)) - assert text.startswith(message) - imported, text = single_deprecation(importer, at=importer) - assert text.startswith(message) - assert imported is value - assert name in rabitqlib.__all__ - # hasattr reads the name too. - found, text = single_deprecation(lambda: hasattr(rabitqlib, name)) - assert found and text.startswith(message) - - -def test_old_names_can_be_read_without_a_python_caller(): - # A thread whose entry point is a builtin has no Python frame for the warning - # to point at; the read must still succeed. list.extend and map are builtins, - # so getattr runs in the new thread with no Python code calling it. - read = [] - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - expected = rabitqlib.FinalAssignmentMode - _thread.start_new_thread( - read.extend, (map(getattr, [rabitqlib], ["FinalAssignmentMode"]),) - ) - # A failed read leaves the list empty, so this waits out the deadline. - deadline = time.monotonic() + 5 - while not read and time.monotonic() < deadline: - time.sleep(0.01) - assert read == [expected] - - -def test_kmeans_iteration_stats_is_one_class(base_data): - stats = silently(lambda: rabitqlib.KMeansIterationStats) - assert stats.__name__ == stats.__qualname__ == "KMeansIterationStats" - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - assert rabitqlib.QGKMeansIterationStats is stats - assert rabitqlib.RaBitQKMeansIterationStats is stats - for cls in (QGKMeans, RaBitQKMeans): - model = cls(DIM, 80, niter=2, num_threads=1, seed=1) - model.train(base_data) - assert all(type(item) is stats for item in model.iteration_stats) - with pytest.raises( - AttributeError, match="^module 'rabitqlib' has no attribute 'missing'$" - ): - rabitqlib.missing - - -def test_star_import_still_provides_the_old_names(): - namespace = {} - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - exec("from rabitqlib import *", namespace) - assert set(rabitqlib.__all__) <= set(namespace) - assert [w.category for w in caught] == [DeprecationWarning] * 3 - - -def test_old_attribute_keeps_the_08_encoding(): - cp = QGKMeans(DIM, 80).cp - cp.nbits = 8 - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - cp.quantization_bits = 0 # raw vectors in the 0.8 encoding - assert cp.quantization_bits == 0 - assert cp.nbits == 32 - - -def test_subclass_warnings_name_the_subclass(): - class Clustering(QGKMeans): - pass - - def make(): - return Clustering(DIM, 80, graph_degree=64) - - model, message = single_deprecation(make, at=make) - assert message.startswith( - "Clustering(graph_degree=...) is deprecated; use max_degree=" - ) - assert model.cp.max_degree == 64 - - -@pytest.mark.parametrize("cls", [QGKMeans, RaBitQKMeans]) -@pytest.mark.parametrize("name", ["unknown", "mro", "__dict__"]) -def test_unknown_kmeans_keyword_message_is_unchanged(cls, name): - with pytest.raises( - AttributeError, - match=f"^{cls.__name__}\\(\\) got an unexpected keyword argument '{name}'$", - ): - cls(DIM, 80, **{name: 1}) - - -def test_train_error_names_the_keyword_the_caller_used(base_data): - old_message = "^QGKMeans ef_build and ef_search must be positive$" - with pytest.raises( - ValueError, match="^QGKMeans ef_construction and ef_search must be positive$" - ): - QGKMeans(DIM, 80, niter=1, ef_construction=0).train(base_data) - # Every call that 0.8 accepts keeps the message 0.8 gave it. - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - old = QGKMeans(DIM, 80, niter=1, ef_build=0) - with pytest.raises(ValueError, match=old_message): - old.train(base_data) - with pytest.raises(ValueError, match=old_message): - QGKMeans(DIM, 80, niter=1, ef_search=0).train(base_data) - - class WithoutInit(QGKMeans): - def __init__(self): - self.d, self.k, self._impl = DIM, 80, None - self.cp = rabitqlib.QGKMeansParameters() - self.cp.ef_search = 0 - - with pytest.raises(ValueError, match=old_message): - WithoutInit().train(base_data) - # Other errors pass through as the extension raised them. - with pytest.raises( - ValueError, match="^QGKMeans graph_build_iterations must be positive$" - ) as raised: - QGKMeans(DIM, 80, niter=1, ef_construction=100, graph_build_iterations=0).train( - base_data - ) - assert raised.value.__context__ is None # not re-raised as a new object - # The 0.8 name with a value only nbits would accept is still rejected at train. - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - wrong = QGKMeans(DIM, 80, niter=1, quantization_bits=32) - with pytest.raises(ValueError, match="quantization_bits must be 0, 4, or 8"): - wrong.train(base_data) - - -def test_statistics_class_pickles_by_reference(): - stats = rabitqlib.KMeansIterationStats - assert pickle.loads(pickle.dumps(stats)) is stats - assert stats.__module__ == "rabitqlib._rabitqlib" - assert getattr(sys.modules[stats.__module__], "KMeansIterationStats") is stats diff --git a/tests/python/test_concurrent_indexes.py b/tests/python/test_concurrent_indexes.py index 787caf04..a5c53f28 100644 --- a/tests/python/test_concurrent_indexes.py +++ b/tests/python/test_concurrent_indexes.py @@ -31,7 +31,7 @@ def make_index(kind, bits=4, metric="l2", fill=True): centroids = np.stack([data[labels == i].mean(axis=0) for i in range(5)]) if kind.startswith("ivf"): initializer = kind.removeprefix("ivf_") if "_" in kind else "flat" - index = IvfIndex(65, 5, nbits=bits, metric=metric, initializer=initializer) + index = IvfIndex(65, 5, nbits=bits, metric=metric, routing=initializer) elif kind == "hnsw": index = HnswIndex( 65, @@ -58,7 +58,7 @@ def make_index(kind, bits=4, metric="l2", fill=True): def parameters(kind, wide): if kind.startswith("ivf"): return {"nprobe": 5 if wide else 1, "high_accuracy": wide} - return {"ef": 96 if wide else 5} + return {"ef_search": 96 if wide else 5} @pytest.mark.parametrize("kind,bits", CASES) @@ -127,7 +127,13 @@ def test_active_search_allows_reads_and_rejects_mutations(kind, tmp_path): lambda: index.set_centroids(data[:5]), ] if kind == "hnsw": - mutations.append(lambda: index.resize(256)) + # A reserve within the capacity changes nothing and is a read. + capacity = index.capacity + assert capacity < 256 + for within in (0, capacity): + index.reserve(within) + assert index.capacity == capacity + mutations.append(lambda: index.reserve(256)) for mutate in mutations: with pytest.raises(RuntimeError, match=f"^{BUSY}$"): mutate() @@ -136,7 +142,7 @@ def test_active_search_allows_reads_and_rejects_mutations(kind, tmp_path): running.result(timeout=10) # Failed conflicts must not leave the access state busy. if kind == "hnsw": - index.resize(256) + index.reserve(256) elif kind == "qg": # add takes write access before it rejects a second graph. with pytest.raises(RuntimeError, match="does not support incremental addition"): @@ -171,7 +177,7 @@ def test_active_mutation_rejects_reads_and_other_mutations(kind, tmp_path): lambda: index.set_centroids(data[:5]), ] if kind == "hnsw": - calls.append(lambda: index.resize(256)) + calls.append(lambda: index.reserve(256)) for call in calls: with pytest.raises(RuntimeError, match=f"^{BUSY}$"): call() @@ -229,9 +235,9 @@ def test_native_exception_reacquires_gil_and_releases_access(): queries[1, 0] = np.nan # The native search checks coordinates after releasing the GIL. with pytest.raises(ValueError, match="must contain only finite values"): - index.search(queries, 5, ef=64) + index.search(queries, 5, ef_search=64) # add takes write access before it rejects a second graph. with pytest.raises(RuntimeError, match="does not support incremental addition"): index.add(data) - ids, distances = index.search(data[:2], 5, ef=64) + ids, distances = index.search(data[:2], 5, ef_search=64) assert ids.shape == distances.shape == (2, 5) diff --git a/tests/python/test_cosine.py b/tests/python/test_cosine.py new file mode 100644 index 00000000..3f818ae3 --- /dev/null +++ b/tests/python/test_cosine.py @@ -0,0 +1,129 @@ +import numpy as np +import pytest +from rabitqlib import HnswIndex, IvfIndex, SymqgIndex + +DIM = 65 +COUNT = 300 + + +def normalized(rows): + """Normalize as the cosine metric specifies: the squared norm summed in float64 + in coordinate order (cumsum is sequential), then each coordinate times its + reciprocal square root, rounded to float32. Zero rows stay zero.""" + wide = np.asarray(rows, dtype=np.float64) + squared_norm = np.cumsum(wide * wide, axis=1)[:, -1] + scale = np.zeros_like(squared_norm) + nonzero = squared_norm > 0 + scale[nonzero] = 1.0 / np.sqrt(squared_norm[nonzero]) + return (wide * scale[:, None]).astype(np.float32) + + +@pytest.fixture(scope="module") +def vectors(): + rng = np.random.default_rng(17) + rows = rng.standard_normal((COUNT + 5, DIM), dtype=np.float32) + rows *= (1 + np.arange(len(rows)) % 7)[:, None].astype(np.float32) + return rows[:COUNT], rows[COUNT:] + + +def make_index(kind, metric, nbits): + if kind == "ivf": + return IvfIndex(DIM, 4, nbits=nbits, metric=metric, seed=7) + if kind == "hnsw": + return HnswIndex(DIM, nbits=nbits, num_clusters=4, M=8, metric=metric, seed=7) + return SymqgIndex(DIM, nbits=nbits, ef_construction=40, metric=metric, seed=7) + + +CASES = [ + ("ivf", 1), + ("ivf", 5), + ("ivf", 32), + ("hnsw", 1), + ("hnsw", 5), + ("symqg", 4), + ("symqg", 32), +] + + +@pytest.mark.parametrize("kind,nbits", CASES) +def test_cosine_matches_inner_product_over_normalized_vectors( + kind, nbits, vectors, tmp_path +): + data, queries = vectors + cosine = make_index(kind, "cosine", nbits) + ip = make_index(kind, "ip", nbits) + # One thread, so that training and IVF HNSW routing are reproducible. + cosine.add(data, num_threads=1) + ip.add(normalized(data), num_threads=1) + assert cosine.metric == "cosine" + assert "metric='cosine'" in repr(cosine) + + expected = ip.search(normalized(queries), 10) + path = tmp_path / f"{kind}.index" + cosine.save(path) + loaded = type(cosine).load(path) + assert loaded.metric == "cosine" + for index in (cosine, loaded): + ids, distances = index.search(queries, 10, num_threads=2) + np.testing.assert_array_equal(ids, expected[0]) + np.testing.assert_array_equal(distances, expected[1]) + + +@pytest.mark.parametrize("kind,nbits", [("ivf", 32), ("symqg", 32)]) +def test_cosine_distance_of_a_zero_vector_is_one(kind, nbits, vectors): + # Raw vectors give exact distances. + data = vectors[0].copy() + data[0] = 0 + index = make_index(kind, "cosine", nbits) + index.add(data, num_threads=1) + _, distances = index.search(np.zeros((1, DIM), dtype=np.float32), 10) + np.testing.assert_array_equal(distances, np.ones((1, 10), dtype=np.float32)) + breadth = {"nprobe": 4} if kind == "ivf" else {"ef_search": COUNT} + ids, distances = index.search(data[1:2], COUNT, **breadth) + assert distances[0, list(ids[0]).index(0)] == 1.0 + + +def test_cosine_distances_are_one_minus_cosine(vectors): + data, queries = vectors + index = make_index("ivf", "cosine", 32) + index.add(data, num_threads=1) + ids, distances = index.search(queries, 10, nprobe=4) + exact = 1.0 - normalized(queries) @ normalized(data).T + np.testing.assert_allclose( + distances, np.take_along_axis(exact, ids, axis=1), rtol=0, atol=1e-6 + ) + + +@pytest.mark.parametrize("kind", ["ivf", "hnsw"]) +@pytest.mark.parametrize("setup", ["train", "set_centroids"]) +def test_cosine_trained_or_given_centroids_match_inner_product(kind, setup, vectors): + data, queries = vectors + cosine = make_index(kind, "cosine", 5) + ip = make_index(kind, "ip", 5) + if setup == "train": + cosine.train(data[:200], num_threads=1) + ip.train(normalized(data[:200]), num_threads=1) + else: + # Given centroids are scaled to unit length, as the data is, so centroids far + # from the unit sphere match their scaled copies. + centroids = data[:4] * np.float32(50) + cosine.set_centroids(centroids) + ip.set_centroids(normalized(centroids)) + cosine.add(data, num_threads=1) + ip.add(normalized(data), num_threads=1) + ids, distances = cosine.search(queries, 10) + expected_ids, expected_distances = ip.search(normalized(queries), 10) + np.testing.assert_array_equal(ids, expected_ids) + np.testing.assert_array_equal(distances, expected_distances) + + +@pytest.mark.parametrize("kind,label", [("ivf", "IVF"), ("hnsw", "HNSW")]) +def test_cosine_training_checks_the_original_data(kind, label, vectors): + data = vectors[0].copy() + data[3, 5] = np.nan + index = make_index(kind, "cosine", 5) + with pytest.raises( + ValueError, match=rf"^{label} training data must contain only finite values$" + ): + index.train(data) + assert not index.is_trained diff --git a/tests/python/test_cpp_clustering_examples.py b/tests/python/test_cpp_clustering_examples.py index bf9860b0..c797d2cb 100644 --- a/tests/python/test_cpp_clustering_examples.py +++ b/tests/python/test_cpp_clustering_examples.py @@ -33,8 +33,10 @@ def read_vecs(path, rows, cols, dtype): @pytest.mark.parametrize("method,k", [("qgkmeans", 33), ("rabitqkmeans", 16)]) -@pytest.mark.parametrize("metric", ["l2", "ip"]) -def test_cpp_clustering_file_outputs(tmp_path, method, k, metric): +@pytest.mark.parametrize("index_metric", ["l2", "ip", "cosine"]) +def test_cpp_clustering_file_outputs(tmp_path, method, k, index_metric): + # The clustering examples take l2 or ip; unit vectors cluster alike for cosine. + metric = "l2" if index_metric == "l2" else "ip" data = np.random.default_rng(42).standard_normal((512, 65)).astype(np.float32) if metric == "ip": data /= np.linalg.norm(data, axis=1, keepdims=True) @@ -75,7 +77,7 @@ def test_cpp_clustering_file_outputs(tmp_path, method, k, metric): labels_path, 3, index_path, - metric, + index_metric, ) else: result = run_cpp( @@ -87,7 +89,7 @@ def test_cpp_clustering_file_outputs(tmp_path, method, k, metric): 32, 5, index_path, - metric, + index_metric, ) assert result.returncode == 0, result.stdout + result.stderr result = run_cpp( @@ -95,12 +97,31 @@ def test_cpp_clustering_file_outputs(tmp_path, method, k, metric): "ivf" if method == "qgkmeans" else "hnsw", index_path, source, - metric, + index_metric, 3 if method == "qgkmeans" else 5, ) assert result.returncode == 0, result.stdout + result.stderr +@pytest.mark.parametrize( + "example,args", + [ + ("ivf_rabitq_indexing", ["data.fvecs", "c.fvecs", "ids.ivecs", 3, "index"]), + ( + "hnsw_rabitq_indexing", + ["data.fvecs", "c.fvecs", "ids.ivecs", 16, 32, 5, "index"], + ), + ("symqg_indexing", ["data.fvecs", 32, 64, "index"]), + ], +) +def test_cpp_indexing_examples_reject_unknown_metric(tmp_path, example, args): + args = [tmp_path / arg if isinstance(arg, str) else arg for arg in args] + result = run_cpp(example, *args, "dot") + assert result.returncode == 1 + assert "Metric type must be l2, ip or cosine" in result.stderr + assert not (tmp_path / "index").exists() + + @pytest.mark.parametrize("method", ["qgkmeans", "rabitqkmeans"]) def test_cpp_clustering_synthetic_demo(method): result = run_cpp(method) diff --git a/tests/python/test_editor_support.py b/tests/python/test_editor_support.py index 64098788..c00f751e 100644 --- a/tests/python/test_editor_support.py +++ b/tests/python/test_editor_support.py @@ -2,7 +2,6 @@ import ast import doctest -import inspect import re from pathlib import Path @@ -54,9 +53,6 @@ def test_installed_public_declarations(): if isinstance(node, ast.AnnAssign): assert isinstance(node.target, ast.Name) members.add(node.target.id) - if name == "FinalAssignmentMode": - assert {"Approximate", "SymphonyQG", "Exact", "name", "value"} <= members - continue public = {key for key in vars(runtime) if not key.startswith("_")} assert public <= members, (name, public - members) for member in members - {"d", "k", "cp"}: @@ -85,15 +81,6 @@ def test_editor_docs_match_runtime_help(): assert normalized(documentation) in normalized(actual), (name, node.name) -def is_deprecated(node): - return any( - isinstance(d, ast.Call) - and isinstance(d.func, ast.Name) - and d.func.id == "deprecated" - for d in node.decorator_list - ) - - def stub_parameters(node): """Names, keyword-only names and literal defaults declared in the stub.""" args = node.args @@ -114,14 +101,7 @@ def stub_parameters(node): def runtime_parameters(member): - """The same, from a Python replacement's signature or pybind11's first doc line.""" - if inspect.isfunction(member): - parameters = inspect.signature(member).parameters.values() - return ( - [p.name for p in parameters], - [p.name for p in parameters if p.kind is inspect.Parameter.KEYWORD_ONLY], - {p.name: p.default for p in parameters if p.default is not p.empty}, - ) + """The same, from pybind11's first doc line.""" signature = member.__doc__.splitlines()[0] names = re.findall(r"(?:\(|, )([A-Za-z_]\w*):", signature) _, star, keyword_part = signature.partition(", *, ") @@ -138,9 +118,7 @@ def test_native_signature_names_and_defaults(name): cls = declarations()[name] runtime = getattr(rabitqlib, name) for node in cls.body: - if not isinstance(node, ast.FunctionDef) or is_deprecated(node): - # Deprecated overloads describe the 0.7 forms the compatibility layer - # accepts; the runtime signature documents only the current form. + if not isinstance(node, ast.FunctionDef): continue if any( (isinstance(d, ast.Name) and d.id == "property") @@ -157,23 +135,13 @@ def test_native_signature_names_and_defaults(name): def test_clustering_keyword_defaults(name): cls = declarations()[name] init = next( - n - for n in cls.body - if isinstance(n, ast.FunctionDef) - and n.name == "__init__" - and not is_deprecated(n) + n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "__init__" ) instance = getattr(rabitqlib, name)(64, 40) for arg, default in zip(init.args.kwonlyargs, init.args.kw_defaults): assert default is not None, (name, arg.arg) expected = ast.literal_eval(default) - actual = getattr(instance.cp, arg.arg) - if arg.arg == "final_assignment": - # Reads back as the enum member until 0.9: compare with what passing - # the declared default explicitly gives. - explicit = getattr(rabitqlib, name)(64, 40, final_assignment=expected) - expected = explicit.cp.final_assignment - assert actual == expected + assert getattr(instance.cp, arg.arg) == expected for name in ( "centroids", "assignments", @@ -219,7 +187,7 @@ def test_documented_search_result_types(kind): result = index.search(data[:2], 3, ef_search=20) ids, distances = result assert ids.shape == distances.shape == (2, 3) - assert ids.dtype == np.uint32 + assert ids.dtype == np.int64 assert distances.dtype == np.float32 @@ -240,7 +208,7 @@ def test_documented_training_result_types(name): assert isinstance(model.final_obj, float) -def test_numpy_scalar_inputs_and_enum_members(): +def test_numpy_scalar_inputs(): import runpy fixture = Path(__file__).parent / "typing" / "public_api.py" diff --git a/tests/python/test_examples.py b/tests/python/test_examples.py index b988eb28..f1931639 100644 --- a/tests/python/test_examples.py +++ b/tests/python/test_examples.py @@ -156,7 +156,6 @@ def search(prepared, *args, **kwargs): return ids, np.zeros((2, 1)) index = SimpleNamespace(dim=2, num_clusters=2, search=search) - index.search_batch = index.search index_name = {"ivf": "IvfIndex", "hnsw": "HnswIndex", "symqg": "SymqgIndex"}[kind] monkeypatch.setattr(module, index_name, SimpleNamespace(load=lambda path: index)) monkeypatch.setattr(module, "read_fvecs", lambda path: queries) @@ -294,10 +293,8 @@ def test_separate_clustering_and_indexing( @pytest.mark.parametrize("metric", ["l2", "ip"]) @pytest.mark.parametrize("kind", ["ivf", "hnsw"]) def test_indexing_trains_without_a_clustering_file( - tmp_path, example_data, metric, kind, monkeypatch + tmp_path, example_data, metric, kind ): - # The samples teach the 0.8 API, so they must not hit the compatibility layer. - monkeypatch.setenv("PYTHONWARNINGS", "error::DeprecationWarning") data_path, data = example_data output = run_example( f"{kind}_rabitq_indexing.py", @@ -329,7 +326,7 @@ def check_exact_cluster_labels(data, centroids, labels, metric): np.testing.assert_array_equal(labels, np.argmin(distances, axis=1)) -@pytest.mark.parametrize("argument", [None, "l2", "ip", "innerproduct"]) +@pytest.mark.parametrize("argument", [None, "l2", "ip"]) def test_legacy_clustering_formats_without_faiss(tmp_path, example_data, argument): data_path, data = example_data centroids_path = tmp_path / "centroids.fvecs" @@ -352,7 +349,7 @@ def test_legacy_clustering_formats_without_faiss(tmp_path, example_data, argumen labels = label_words[:, 1] assert np.isfinite(centroids).all() assert ((0 <= labels) & (labels < 16)).all() - metric = "ip" if argument in ("ip", "innerproduct") else "l2" + metric = argument or "l2" check_exact_cluster_labels(data, centroids, labels, metric) @@ -379,16 +376,12 @@ def test_clustering_default_requires_graph_compatible_cluster_count(monkeypatch) ) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) - with pytest.raises(ValueError, match="more centroids than the graph degree"): + with pytest.raises(ValueError, match="more centroids than max_degree"): module.cluster_data(np.zeros((65, 64), dtype=np.float32), 2, "l2", 1) @pytest.mark.parametrize("metric", ["l2", "ip"]) -def test_symqg_examples_do_not_import_faiss( - tmp_path, example_data, metric, monkeypatch -): - # The samples teach the 0.8 API, so they must not hit the compatibility layer. - monkeypatch.setenv("PYTHONWARNINGS", "error::DeprecationWarning") +def test_symqg_examples_do_not_import_faiss(tmp_path, example_data, metric): data_path, data = example_data run_example( "symqg_indexing.py", diff --git a/tests/python/test_historical_persistence.py b/tests/python/test_historical_persistence.py index d6318af8..58479f9e 100644 --- a/tests/python/test_historical_persistence.py +++ b/tests/python/test_historical_persistence.py @@ -5,9 +5,11 @@ import struct from pathlib import Path +import format2_file import numpy as np import pytest -from rabitqlib import HnswIndex, IvfIndex, SymqgIndex +import rabitqlib +from rabitqlib import HnswIndex, IvfIndex, SymqgIndex, quant FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "persistence" NAMES = [ @@ -30,7 +32,7 @@ def reference(name): if name.startswith("ivf") else (HnswIndex if name.startswith("hnsw") else SymqgIndex) ) - options = {"nprobe": 1} if name.startswith("ivf") else {"ef": 64} + options = {"nprobe": 1} if name.startswith("ivf") else {"ef_search": 64} return path, cls, count, queries, ids, distances, options @@ -47,7 +49,7 @@ def test_fixture_hashes_match_pinned_manifest(): ), filename expected = { path.relative_to(FIXTURES).as_posix() - for suffix in ("*.index", "*.expected") + for suffix in ("*.index", "*.hnsw", "*.expected") for path in FIXTURES.rglob(suffix) } assert expected @@ -65,7 +67,8 @@ def test_historical_load_search_and_resave(name, tmp_path): assert index.metric == name.rsplit("_", 1)[1] assert index.num_stored_points == count assert index.num_points == count - (0 if cls is SymqgIndex else 1) - assert index.max_elements >= index.num_stored_points + if cls is HnswIndex: + assert index.capacity >= index.num_stored_points actual_ids, actual_distances = index.search(queries, 5, **options) np.testing.assert_array_equal(actual_ids, ids) # Distances may differ across AVX2, AVX-512, NEON, and compiler reductions. @@ -106,10 +109,9 @@ def test_ivf_v1_header_uses_historical_payload_and_padding(name, tmp_path): destination = tmp_path / "ivf-v1.index" destination.write_bytes(header + payload) index = cls.load(str(destination)) - assert index.initializer == "flat" + assert index.routing == "flat" assert index.num_stored_points == count assert index.num_points == count - 1 - assert index.max_elements == count actual_ids, actual_distances = index.search(queries, 5, **options) np.testing.assert_array_equal(actual_ids, ids) np.testing.assert_allclose(actual_distances, distances, rtol=2e-4, atol=2e-4) @@ -125,3 +127,220 @@ def test_ivf_v1_header_uses_historical_payload_and_padding(name, tmp_path): RuntimeError, match="^Invalid padded dimension in IVF index file$" ): cls.load(str(destination)) + + +# The last IVF layout before format 2: RABQIDX1 version 2 and the HNSW sidecar. +V083_IVF = [ + ("ivf4_flat_l2", "flat"), + ("ivf7_flatrabitq_ip", "flat_rabitq"), + ("ivf4_hnsw_l2", "hnsw"), + ("ivf32_hnsw_ip", "hnsw"), + ("ivf1_flat_matrix_l2", "flat"), +] + + +@pytest.mark.parametrize("name,initializer", V083_IVF) +def test_v083_ivf_loads_and_migrates_without_loss(name, initializer, tmp_path): + path = FIXTURES / "v0.8.3" / f"{name}.index" + lines = path.with_suffix(".expected").read_text().splitlines() + count, dim, nq, k = map(int, lines[0].split()) + queries = np.fromstring(lines[1], sep=" ", dtype=np.float32).reshape(nq, dim) + results = np.loadtxt(lines[2:]) + ids = results[:, 0].astype(np.uint32).reshape(nq, k) + distances = results[:, 1].astype(np.float32).reshape(nq, k) + + index = IvfIndex.load(str(path)) + assert index.routing == initializer + assert index.num_stored_points == count + assert index.num_points == count - 1 + destination = tmp_path / "migrated.index" + index.save(str(destination)) + assert not Path(str(destination) + ".hnsw").exists() + for loaded in (index, IvfIndex.load(str(destination))): + actual_ids, actual_distances = loaded.search(queries, k, nprobe=4) + np.testing.assert_array_equal(actual_ids, ids) + np.testing.assert_allclose(actual_distances, distances, rtol=2e-4, atol=2e-4) + + # Format 2 keeps every byte: converting back reproduces the 0.8.3 files, which + # also checks the converter that other tests use to build earlier layouts. + main, sidecar = format2_file.to_rabqidx1(destination.read_bytes()) + assert main == path.read_bytes() + original_sidecar = Path(str(path) + ".hnsw") + if initializer == "hnsw": + assert sidecar == original_sidecar.read_bytes() + else: + assert sidecar is None and not original_sidecar.exists() + + +# The last HNSW-RaBitQ and SymphonyQG layouts before format 2. +V083_GRAPHS = ["hnsw1_l2", "hnsw5_ip", "hnsw9_l2", "qg0_ip", "qg4_l2", "qg8_ip"] +V083_GRAPHS += ["qg4_matrix_l2"] + + +@pytest.mark.parametrize("name", V083_GRAPHS) +def test_v083_graphs_load_and_migrate(name, tmp_path): + path = FIXTURES / "v0.8.3" / f"{name}.index" + lines = path.with_suffix(".expected").read_text().splitlines() + count, dim, nq, k = map(int, lines[0].split()) + queries = np.fromstring(lines[1], sep=" ", dtype=np.float32).reshape(nq, dim) + results = np.loadtxt(lines[2:]) + ids = results[:, 0].astype(np.uint32).reshape(nq, k) + distances = results[:, 1].astype(np.float32).reshape(nq, k) + cls = HnswIndex if name.startswith("hnsw") else SymqgIndex + + original = cls.load(str(path)) + assert original.seed is None # earlier layouts do not record it + if cls is SymqgIndex: + assert (original.ef_construction, original.init) == (None, None) + destination = tmp_path / "migrated.index" + original.save(str(destination)) + assert destination.read_bytes()[:8] == format2_file.MAGIC + for index in (original, cls.load(str(destination))): + assert index.num_stored_points == count + assert index.num_points == count - (1 if cls is HnswIndex else 0) + assert index.seed is None + actual_ids, actual_distances = index.search(queries, k, ef_search=64) + np.testing.assert_array_equal(actual_ids, ids) + np.testing.assert_allclose(actual_distances, distances, rtol=2e-4, atol=2e-4) + + +# Index format 2 as release v0.9.0 wrote it; the bits follow the kind and the metric +# ends each name. IVF-RaBitQ and HNSW-RaBitQ files have points 0 and 32 removed. +V090 = { + "ivf4_flat_l2": "flat", + "ivf7_flatrabitq_cosine": "flat_rabitq", + "ivf32_hnsw_ip": "hnsw", + "ivf1_flat_matrix_l2": "flat", + "hnsw1_l2": None, + "hnsw5_cosine": None, + "hnsw9_ip": None, + "qg32_ip": None, + "qg4_cosine": None, + "qg8_l2": None, + "qg4_matrix_l2": None, +} + + +@pytest.mark.parametrize("name", V090) +def test_v090_format2_loads_with_recorded_settings(name, tmp_path): + path = FIXTURES / "v0.9.0" / f"{name}.index" + lines = path.with_suffix(".expected").read_text().splitlines() + count, dim, nq, k = map(int, lines[0].split()) + queries = np.fromstring(lines[1], sep=" ", dtype=np.float32).reshape(nq, dim) + results = np.loadtxt(lines[2:]) + ids = results[:, 0].astype(np.int64).reshape(nq, k) + distances = results[:, 1].astype(np.float32).reshape(nq, k) + if name.startswith("ivf"): + cls, options, removed = IvfIndex, {"nprobe": 4}, 2 + elif name.startswith("hnsw"): + cls, options, removed = HnswIndex, {"ef_search": 64}, 2 + else: + cls, options, removed = SymqgIndex, {"ef_search": 64}, 0 + + resaved = tmp_path / "resaved.index" + original = cls.load(str(path)) + original.save(str(resaved)) + assert not path.with_name(path.name + ".hnsw").exists() + assert not resaved.with_name(resaved.name + ".hnsw").exists() + for index in (original, cls.load(str(resaved))): + assert (index.dim, index.metric, index.seed) == (dim, name.split("_")[-1], 42) + assert index.nbits == int(name.split("_")[0].lstrip("ivfhnswqg")) + assert index.num_stored_points == count + assert index.num_points == count - removed + if cls is IvfIndex: + assert index.routing == V090[name] + elif cls is HnswIndex: + assert (index.M, index.ef_construction) == (8, 64) + else: + assert (index.ef_construction, index.init) == (64, "pipnn") + actual_ids, actual_distances = index.search(queries, k, **options) + np.testing.assert_array_equal(actual_ids, ids) + np.testing.assert_allclose(actual_distances, distances, rtol=2e-4, atol=2e-4) + + +def test_rejected_files_raise_format_error(tmp_path): + assert issubclass(rabitqlib.FormatError, ValueError) + assert issubclass(rabitqlib.FormatError, RuntimeError) + assert rabitqlib.FormatError.__module__ == "rabitqlib" + assert quant.FormatError is rabitqlib.FormatError + for name, cls in [ + ("ivf4_flat_l2", IvfIndex), + ("hnsw1_l2", HnswIndex), + ("qg4_l2", SymqgIndex), + ]: + legacy = (FIXTURES / "v0.8.3" / f"{name}.index").read_bytes() + damaged = tmp_path / f"{name}.index" + damaged.write_bytes(legacy[: len(legacy) // 2]) + with pytest.raises(rabitqlib.FormatError): + cls.load(str(damaged)) + migrated = tmp_path / f"{name}-format2.index" + cls.load(str(FIXTURES / "v0.8.3" / f"{name}.index")).save(str(migrated)) + payload = migrated.read_bytes() + migrated.write_bytes(payload[:-1]) + with pytest.raises(rabitqlib.FormatError, match="index file"): + cls.load(str(migrated)) + # Damaged headers that pass the size checks, as in the C++ historical tests. + ivf = (FIXTURES / "v0.8.3" / "ivf4_flat_l2.index").read_bytes() + qg = bytearray((FIXTURES / "v0.8.3" / "qg4_l2.index").read_bytes()) + struct.pack_into("= 0.5, f"Recall {r:.3f} too low" @@ -216,7 +230,7 @@ def test_save_rejects_unopenable_destination(built_hnsw, tmp_path): @pytest.mark.skipif(not Path("/dev/full").exists(), reason="/dev/full is unavailable") def test_save_reports_write_or_close_failure(built_hnsw): - with pytest.raises(RuntimeError, match="HNSW failed to write index file"): + with pytest.raises(RuntimeError, match="HNSW index file cannot be written"): built_hnsw.save("/dev/full") @@ -229,8 +243,8 @@ def test_save_load_roundtrip(built_hnsw, query_data, tmp_path): assert loaded.dim == built_hnsw.dim assert loaded.nbits == built_hnsw.nbits - ids_orig, dists_orig = built_hnsw.search(query_data, k=_TOPK, ef=_EF) - ids_load, dists_load = loaded.search(query_data, k=_TOPK, ef=_EF) + ids_orig, dists_orig = built_hnsw.search(query_data, k=_TOPK, ef_search=_EF) + ids_load, dists_load = loaded.search(query_data, k=_TOPK, ef_search=_EF) np.testing.assert_array_equal(ids_orig, ids_load) np.testing.assert_allclose(dists_orig, dists_load, rtol=1e-5) @@ -238,22 +252,30 @@ def test_save_load_roundtrip(built_hnsw, query_data, tmp_path): def test_load_rejects_count_larger_than_capacity(built_hnsw, tmp_path): path = tmp_path / "hnsw-invalid-count.index" built_hnsw.save(str(path)) - with path.open("r+b") as index_file: - index_file.write((1).to_bytes(np.dtype(np.uintp).itemsize, byteorder="little")) - with pytest.raises(RuntimeError, match="HNSW"): + # The capacity is the first field of the graph parameters, which are checksummed. + payload = bytearray(path.read_bytes()) + offset, _ = format2_file.sections(payload)[format2_file.HNSW_PARAMS] + payload[offset : offset + 8] = (1).to_bytes(8, "little") + format2_file.reseal(payload) + path.write_bytes(payload) + with pytest.raises( + RuntimeError, match="^HNSW index file has invalid graph parameters$" + ): HnswIndex.load(str(path)) -# ── add and resize ──────────────────────────────────────────────────────────── +# ── add and reserve ─────────────────────────────────────────────────────────── @pytest.fixture def partial_hnsw(base_data, clusters): """Built from the first 400 vectors, with room for the remaining 100.""" centroids, cluster_ids = clusters - idx = HnswIndex(DIM, M=8, ef_construction=50, nbits=4, num_clusters=len(centroids)) + idx = HnswIndex( + DIM, M=8, ef_construction=50, nbits=4, num_clusters=len(centroids), seed=100 + ) idx.set_centroids(centroids) - idx.resize(N_VECTORS) + idx.reserve(N_VECTORS) idx.add(base_data[:400], cluster_ids=cluster_ids[:400], num_threads=1) return idx @@ -263,7 +285,7 @@ def test_add_returns_dense_labels_and_preserves_search( ): _, cluster_ids = clusters assert partial_hnsw.num_points == 400 - before, _ = partial_hnsw.search(base_data[:10], k=1, ef=N_VECTORS) + before, _ = partial_hnsw.search(base_data[:10], k=1, ef_search=N_VECTORS) # One thread, as the build used, so the grown graph and `after` are reproducible. ids = partial_hnsw.add( base_data[400:], cluster_ids=cluster_ids[400:], num_threads=1 @@ -272,11 +294,11 @@ def test_add_returns_dense_labels_and_preserves_search( assert partial_hnsw.num_points == N_VECTORS # A sparse graph can isolate the odd point, as it can after build, so this # asks for near-perfect self-retrieval rather than exact. - ids, distances = partial_hnsw.search(base_data[400:], k=1, ef=N_VECTORS) + ids, distances = partial_hnsw.search(base_data[400:], k=1, ef_search=N_VECTORS) found = np.count_nonzero(ids[:, 0] == np.arange(400, N_VECTORS)) assert found >= 0.95 * (N_VECTORS - 400) assert np.isfinite(distances).all() - after, _ = partial_hnsw.search(base_data[:10], k=1, ef=N_VECTORS) + after, _ = partial_hnsw.search(base_data[:10], k=1, ef_search=N_VECTORS) np.testing.assert_array_equal(before[:, 0], after[:, 0]) @@ -293,7 +315,7 @@ def test_add_into_a_dense_graph_retrieves_every_point(base_data, clusters): nbits=4, ) idx.add(base_data[400:], cluster_ids=cluster_ids[400:]) - ids, _ = idx.search(base_data[400:], k=1, ef=N_VECTORS) + ids, _ = idx.search(base_data[400:], k=1, ef_search=N_VECTORS) np.testing.assert_array_equal(ids[:, 0], np.arange(400, N_VECTORS)) @@ -302,16 +324,16 @@ def test_add_without_cluster_ids_preserves_self_retrieval(partial_hnsw, base_dat np.testing.assert_array_equal(ids, np.arange(400, N_VECTORS)) # Automatically routed points must remain searchable even though nearest-centroid # routing need not reproduce the round-robin assignments used during construction. - found, _ = partial_hnsw.search(base_data[400:], k=1, ef=N_VECTORS) + found, _ = partial_hnsw.search(base_data[400:], k=1, ef_search=N_VECTORS) assert np.count_nonzero(found[:, 0] == np.arange(400, N_VECTORS)) >= 0.95 * 100 def test_add_beyond_capacity_grows_it(partial_hnsw, base_data): - capacity = partial_hnsw.max_elements + capacity = partial_hnsw.capacity partial_hnsw.add(base_data) assert partial_hnsw.num_points == 400 + N_VECTORS # Geometric growth: at least double, so repeated small adds stay cheap. - assert partial_hnsw.max_elements == max(400 + N_VECTORS, 2 * capacity) + assert partial_hnsw.capacity == max(400 + N_VECTORS, 2 * capacity) def test_add_rejects_bad_cluster_ids(partial_hnsw, base_data): @@ -343,32 +365,39 @@ def test_add_before_build_trains_first(base_data): ) -def test_resize_grows_capacity_and_allows_more(base_data, clusters): +def test_reserve_grows_capacity_and_allows_more(base_data, clusters): centroids, cluster_ids = clusters idx = _built( base_data[:400], centroids, cluster_ids[:400], M=8, ef_construction=50, nbits=4 ) - assert idx.max_elements == 400 # the first add allocates exactly its rows + assert idx.capacity == 400 # the first add allocates exactly its rows - idx.resize(N_VECTORS) - assert idx.max_elements == N_VECTORS + idx.reserve(N_VECTORS) + assert idx.capacity == N_VECTORS assert idx.num_points == 400 idx.add(base_data[400:], cluster_ids=cluster_ids[400:], num_threads=1) assert idx.num_points == N_VECTORS - ids, _ = idx.search(base_data[:10], k=1, ef=N_VECTORS) + ids, _ = idx.search(base_data[:10], k=1, ef_search=N_VECTORS) np.testing.assert_array_equal(ids[:, 0], np.arange(10)) -def test_resize_below_element_count_raises(partial_hnsw): - with pytest.raises(ValueError, match="element count"): - partial_hnsw.resize(10) - assert partial_hnsw.max_elements == N_VECTORS +def test_reserve_never_shrinks(partial_hnsw): + # 450 lies between the 400 stored points and the capacity, where the + # resize of 0.8 shrank the index. + for smaller in (0, 10, 450, N_VECTORS): + partial_hnsw.reserve(smaller) + assert partial_hnsw.capacity == N_VECTORS + with pytest.raises(ValueError, match="^num_points must be non-negative$"): + partial_hnsw.reserve(-1) + with pytest.raises(TypeError): + partial_hnsw.reserve(1.5) + assert partial_hnsw.capacity == N_VECTORS @pytest.mark.parametrize("nbits", [1, 9]) @pytest.mark.parametrize("metric", ["l2", "ip"]) -def test_resize_across_allocation_threshold_preserves_search(tmp_path, nbits, metric): +def test_reserve_across_allocation_threshold_preserves_search(tmp_path, nbits, metric): rng = np.random.default_rng(73) data = rng.standard_normal((97, 65)).astype(np.float32) queries = rng.standard_normal((7, 65)).astype(np.float32) @@ -381,19 +410,19 @@ def test_resize_across_allocation_threshold_preserves_search(tmp_path, nbits, me nbits=nbits, metric=metric, ) - expected_ids, expected_distances = index.search(queries, k=7, ef=97) - - # The level-0 allocation moves from below 2 MiB to above it and back. - for capacity in [32768, len(data)]: - index.resize(capacity) - path = str(tmp_path / "resized.index") - index.save(path) - index = HnswIndex.load(path) - assert index.max_elements == capacity - assert index.num_points == len(data) - ids, distances = index.search(queries, k=7, ef=97) - np.testing.assert_array_equal(ids, expected_ids) - np.testing.assert_array_equal(distances, expected_distances) + expected_ids, expected_distances = index.search(queries, k=7, ef_search=97) + + # The level-0 allocation moves from below 2 MiB to above it. + capacity = 32768 + index.reserve(capacity) + path = str(tmp_path / "reserved.index") + index.save(path) + index = HnswIndex.load(path) + assert index.capacity == capacity + assert index.num_points == len(data) + ids, distances = index.search(queries, k=7, ef_search=97) + np.testing.assert_array_equal(ids, expected_ids) + np.testing.assert_array_equal(distances, expected_distances) def test_added_points_survive_save_and_load( @@ -401,22 +430,22 @@ def test_added_points_survive_save_and_load( ): _, cluster_ids = clusters partial_hnsw.add(base_data[400:], cluster_ids=cluster_ids[400:]) - before_ids, before_dists = partial_hnsw.search(base_data, k=_TOPK, ef=_EF) + before_ids, before_dists = partial_hnsw.search(base_data, k=_TOPK, ef_search=_EF) path = str(tmp_path / "hnsw-added.index") partial_hnsw.save(path) loaded = HnswIndex.load(path) assert loaded.num_points == N_VECTORS - assert loaded.max_elements == N_VECTORS - after_ids, after_dists = loaded.search(base_data, k=_TOPK, ef=_EF) + assert loaded.capacity == N_VECTORS + after_ids, after_dists = loaded.search(base_data, k=_TOPK, ef_search=_EF) np.testing.assert_array_equal(before_ids, after_ids) np.testing.assert_allclose(before_dists, after_dists, rtol=1e-5) # ── remove ──────────────────────────────────────────────────────────────────── -_NO_ID = np.iinfo(np.uint32).max +_NO_ID = -1 def _removable(nbits=4, metric="l2", count=120, dim=64, seed=61): @@ -438,7 +467,9 @@ def _removable(nbits=4, metric="l2", count=120, dim=64, seed=61): def _everything(index, queries): """With k and ef at the point count, search visits every reachable point.""" - return index.search(queries, k=index.num_stored_points, ef=index.num_stored_points) + return index.search( + queries, k=index.num_stored_points, ef_search=index.num_stored_points + ) # C++ HnswRemoveTest covers intermediate widths; keep both storage endpoints here. @@ -468,7 +499,7 @@ def check(index): np.testing.assert_array_equal(dists[q, :alive], before_dists[q][keep]) assert np.all(ids[q, alive:] == _NO_ID) assert np.all(np.isinf(dists[q, alive:])) - top, top_dists = index.search(queries, k=10, ef=10) + top, top_dists = index.search(queries, k=10, ef_search=10) assert not np.isin(top, removed).any() assert np.isfinite(top_dists).all() @@ -485,7 +516,7 @@ def check(index): # graph, with a different set of reachable points. plain = HnswIndex.load(str(plain_path)) for index in (idx, loaded, plain): - index.resize(count + len(new)) + index.reserve(count + len(new)) # One thread: graphs grown in parallel differ, and the searches compare them. index.add(new, num_threads=1) assert index.num_stored_points == count + len(new) @@ -536,7 +567,7 @@ def test_remove_rejects_invalid_ids_without_removing_anything(): def test_removing_every_point_returns_only_sentinels(): idx, old, new = _removable() assert idx.remove(np.arange(len(old))) == len(old) - ids, dists = idx.search(new[:2], k=5, ef=10) + ids, dists = idx.search(new[:2], k=5, ef_search=10) assert np.all(ids == _NO_ID) assert np.all(np.isinf(dists)) @@ -575,21 +606,21 @@ def test_legacy_padding_round_trip_and_add(tmp_path): fixture = Path(__file__).parent / "fixtures" / "hnsw_legacy_padding65_4bit.index" index = HnswIndex.load(str(fixture)) query = np.zeros((1, 65), dtype=np.float32) - ids, distances = index.search(query, k=3, ef=8) + ids, distances = index.search(query, k=3, ef_search=8) np.testing.assert_array_equal(ids, [[0, 1, 2]]) np.testing.assert_allclose(distances, [[0, 14, 14]], atol=1e-5) # Expected distances were recorded with the old 64-padding implementation. nonzero_query = ((np.arange(65) % 9 - 4) / 4).astype(np.float32)[None, :] - nonzero_ids, nonzero_distances = index.search(nonzero_query, k=3, ef=8) + nonzero_ids, nonzero_distances = index.search(nonzero_query, k=3, ef_search=8) np.testing.assert_array_equal(nonzero_ids, [[0, 2, 1]]) np.testing.assert_allclose( nonzero_distances, [[27.81249809, 33.36483002, 50.26016998]], rtol=2e-6 ) path = tmp_path / "migrated.index" index.save(str(path)) - assert int.from_bytes(path.read_bytes()[24:32], "little") == 128 + assert format2_file.padded_dim(path.read_bytes()) == 128 loaded = HnswIndex.load(str(path)) - actual = loaded.search(query, k=3, ef=8) + actual = loaded.search(query, k=3, ef_search=8) np.testing.assert_array_equal(actual[0], ids) np.testing.assert_array_equal(actual[1], distances) loaded.add(np.ones((1, 65), dtype=np.float32)) @@ -601,7 +632,7 @@ def test_huge_ef_is_clamped_to_the_stored_point_count(): index = _built( data, data.mean(axis=0, keepdims=True), np.zeros(80, dtype=np.uint32), nbits=4 ) - exhaustive_ids, exhaustive_distances = index.search(data[:3], k=5, ef=80) - ids, distances = index.search(data[:3], k=5, ef=2**40) + exhaustive_ids, exhaustive_distances = index.search(data[:3], k=5, ef_search=80) + ids, distances = index.search(data[:3], k=5, ef_search=2**40) np.testing.assert_array_equal(ids, exhaustive_ids) np.testing.assert_array_equal(distances, exhaustive_distances) diff --git a/tests/python/test_import.py b/tests/python/test_import.py index 099129ec..dc5085cc 100644 --- a/tests/python/test_import.py +++ b/tests/python/test_import.py @@ -48,5 +48,5 @@ def test_constructor_contract(cls, args, kwargs, expected): ], ) def test_invalid_metric_raises(cls, args): - with pytest.raises(ValueError, match=r"^metric must be 'l2' or 'ip'$"): - cls(*args, metric="cosine") + with pytest.raises(ValueError, match=r"^metric must be 'l2', 'ip' or 'cosine'$"): + cls(*args, metric="cos") diff --git a/tests/python/test_index_counts.py b/tests/python/test_index_counts.py index fc48a184..71cae07d 100644 --- a/tests/python/test_index_counts.py +++ b/tests/python/test_index_counts.py @@ -1,4 +1,4 @@ -"""All index wrappers distinguish capacity, stored records and live points.""" +"""All index wrappers distinguish stored records and live points; HNSW adds capacity.""" import numpy as np import pytest @@ -6,12 +6,13 @@ def check_counts(index, capacity, stored, active): - assert (index.max_elements, index.num_stored_points, index.num_points) == ( - capacity, - stored, - active, - ) - assert 0 <= index.num_points <= index.num_stored_points <= index.max_elements + """capacity is None for the indexes without one.""" + assert (index.num_stored_points, index.num_points) == (stored, active) + assert 0 <= index.num_points <= index.num_stored_points + assert getattr(index, "capacity", None) == capacity + assert not hasattr(index, "max_elements") + if capacity is not None: + assert index.num_stored_points <= capacity # Metric forwarding is covered by portable-index tests; counts are metric-independent. @@ -29,33 +30,30 @@ def test_count_contract_through_lifecycle(tmp_path, kind, bits): assignments = np.zeros(count + 4, np.uint32) if kind == "ivf": index = IvfIndex(dim, 1, nbits=bits, metric=metric) - capacity = 0 + capacity = None elif kind == "hnsw": index = HnswIndex( dim, num_clusters=1, M=8, ef_construction=40, nbits=bits, metric=metric ) - index.resize(64) + index.reserve(64) capacity = 64 else: index = SymqgIndex( dim, max_degree=32, ef_construction=40, nbits=bits, metric=metric ) - capacity = 0 + capacity = None check_counts(index, capacity, 0, 0) if kind == "symqg": index.add(data[:count], num_threads=1) - capacity = count else: index.set_centroids(centroid) index.add(data[:count], cluster_ids=assignments[:count], num_threads=1) - if kind == "ivf": - capacity = count check_counts(index, capacity, count, count) path = tmp_path / "counts.index" if kind == "symqg": index.save(str(path)) - check_counts(SymqgIndex.load(str(path)), count, count, count) + check_counts(SymqgIndex.load(str(path)), None, count, count) return assert index.remove([0, 1, 0]) == 2 @@ -68,17 +66,15 @@ def test_count_contract_through_lifecycle(tmp_path, kind, bits): index.remove([2, count]) check_counts(index, capacity, count, count - 3) if kind == "hnsw": - with pytest.raises(ValueError): - index.resize(count - 3) - index.resize(80) + index.reserve(count - 3) # never shrinks + check_counts(index, capacity, count, count - 3) + index.reserve(80) capacity = 80 check_counts(index, capacity, count, count - 3) ids = index.add(data[count : count + 3], cluster_ids=assignments[:3]) np.testing.assert_array_equal(ids, np.arange(count, count + 3)) stored = count + 3 - if kind == "ivf": - capacity = stored check_counts(index, capacity, stored, count) index.save(str(path)) index = type(index).load(str(path)) @@ -91,16 +87,14 @@ def test_count_contract_through_lifecycle(tmp_path, kind, bits): index.save(str(path)) index = type(index).load(str(path)) check_counts(index, capacity, stored, 0) - args = {"nprobe": 1} if kind == "ivf" else {"ef": stored} + args = {"nprobe": 1} if kind == "ivf" else {"ef_search": stored} hits, _ = index.search(data[:1], k=1, **args) - assert np.all(hits == np.iinfo(np.uint32).max) + assert np.all(hits == -1) np.testing.assert_array_equal( index.add(data[-1:], cluster_ids=assignments[:1]), [stored] ) stored += 1 - if kind == "ivf": - capacity = stored check_counts(index, capacity, stored, 1) index.save(str(path)) check_counts(type(index).load(str(path)), capacity, stored, 1) diff --git a/tests/python/test_index_repr.py b/tests/python/test_index_repr.py index cc7c32ac..7118902b 100644 --- a/tests/python/test_index_repr.py +++ b/tests/python/test_index_repr.py @@ -7,12 +7,12 @@ SUMMARIES = { "ivf": ( "IvfIndex(dim=64, metric='ip', nbits={bits}, num_points={live}, " - "num_stored_points={stored}, max_elements={capacity}, " - "num_clusters={clusters}, initializer='flat', is_trained={built})" + "num_stored_points={stored}, num_clusters={clusters}, routing='flat', " + "is_trained={built})" ), "hnsw": ( "HnswIndex(dim=64, metric='ip', nbits={bits}, num_points={live}, " - "num_stored_points={stored}, max_elements={capacity}, " + "num_stored_points={stored}, capacity={capacity}, " "num_clusters={clusters}, is_trained={built})" ), "symqg": ( @@ -29,15 +29,13 @@ def vectors(): def unbuilt_index(kind, bits): if kind == "ivf": - return IvfIndex(64, 1, nbits=bits, metric="innerproduct") + return IvfIndex(64, 1, nbits=bits, metric="ip") if kind == "hnsw": - index = HnswIndex(64, nbits=bits, num_clusters=1, metric="innerproduct") + index = HnswIndex(64, nbits=bits, num_clusters=1, metric="ip") # Keep capacity distinct from the 80 stored points. - index.resize(96) + index.reserve(96) return index - return SymqgIndex( - 64, max_degree=32, ef_construction=40, metric="innerproduct", nbits=bits - ) + return SymqgIndex(64, max_degree=32, ef_construction=40, metric="ip", nbits=bits) def build_index(index, vectors): @@ -57,19 +55,18 @@ def test_repr_lifecycle(kind, bits, vectors, tmp_path): bits=bits, live=0, stored=0, - capacity=96 if kind == "hnsw" else 0, + capacity=96, # HnswIndex only clusters=1, built=False, ) assert repr(index) == str(index) == before build_index(index, vectors) - capacity = 96 if kind == "hnsw" else 80 after = SUMMARIES[kind].format( bits=bits, live=80, stored=80, - capacity=capacity, + capacity=96, clusters=1, built=True, ) @@ -92,19 +89,15 @@ def test_repr_tracks_live_stored_and_capacity(kind, vectors, tmp_path): assert isinstance(index, (IvfIndex, HnswIndex)) build_index(index, vectors) assert index.remove([0]) == 1 - capacity = 96 if kind == "hnsw" else 80 assert repr(index) == SUMMARIES[kind].format( - bits=4, live=79, stored=80, capacity=capacity, clusters=1, built=True + bits=4, live=79, stored=80, capacity=96, clusters=1, built=True ) index.add(vectors[:1]) if isinstance(index, HnswIndex): - index.resize(128) - capacity = 128 - else: - capacity = 81 + index.reserve(128) expected = SUMMARIES[kind].format( - bits=4, live=80, stored=81, capacity=capacity, clusters=1, built=True + bits=4, live=80, stored=81, capacity=128, clusters=1, built=True ) assert repr(index) == expected path = tmp_path / "updated.index" diff --git a/tests/python/test_input_boundaries.py b/tests/python/test_input_boundaries.py index 1178e913..def77dcc 100644 --- a/tests/python/test_input_boundaries.py +++ b/tests/python/test_input_boundaries.py @@ -28,7 +28,7 @@ def built_index(request): else: if request.param.startswith("ivf"): initializer = "hnsw" if request.param == "ivf_hnsw" else "flat" - index = IvfIndex(64, 1, nbits=4, initializer=initializer) + index = IvfIndex(64, 1, nbits=4, routing=initializer) else: index = HnswIndex(64, nbits=4, num_clusters=1) index.set_centroids(data.mean(axis=0, keepdims=True)) @@ -54,8 +54,8 @@ def test_path_roundtrip(built_index, tmp_path, kind): assert filename.is_file() if isinstance(value, FilesystemPath): assert value.calls == 1 - if isinstance(index, IvfIndex) and index.initializer == "hnsw": - assert Path(str(filename) + ".hnsw").is_file() + # Index format 2 keeps the HNSW routing graph inside the index file. + assert not Path(str(filename) + ".hnsw").exists() restored = type(index).load(value) if isinstance(value, FilesystemPath): assert value.calls == 2 @@ -70,7 +70,7 @@ def test_save_replaces_existing_files_without_leftovers(built_index, tmp_path): filename = tmp_path / "replaced.index" filename.write_bytes(b"stale") expected_files = {filename.name} - if isinstance(index, IvfIndex) and index.initializer == "hnsw": + if isinstance(index, IvfIndex) and index.routing == "hnsw": Path(str(filename) + ".hnsw").write_bytes(b"stale") expected_files.add(filename.name + ".hnsw") for _ in range(2): @@ -104,8 +104,7 @@ def test_path_preserves_undecodable_bytes(built_index, tmp_path): np.testing.assert_array_equal( restored.search(queries, 3, 32)[0], index.search(queries, 3, 32)[0] ) - if isinstance(index, IvfIndex) and index.initializer == "hnsw": - assert os.path.isfile(raw + b".hnsw") + assert not os.path.exists(raw + b".hnsw") @pytest.mark.parametrize("built_index", ["ivf_hnsw"], indirect=True) @@ -203,6 +202,32 @@ def test_query_rank_diagnostics(built_index, shape): assert str(error.value) == f"queries must be a 2D NumPy array; got shape {shape}" +def test_query_dimension_is_reported_before_k_and_breadth(built_index): + index, queries = built_index + narrow = queries[:, :-1] + for call in ( + lambda: index.search(narrow, 0), + lambda: index.search(narrow, 1, 0), + ): + with pytest.raises( + ValueError, match="^query dimension does not match index dim" + ): + call() + + +def test_negative_search_options_raise_type_error(built_index): + index, queries = built_index + breadth = "nprobe" if isinstance(index, IvfIndex) else "ef_search" + for call in ( + lambda: index.search(queries, -1), + lambda: index.search(queries, 1, -1), + lambda: index.search(queries, 1, **{breadth: -1}), + lambda: index.search(queries, 1, num_threads=-1), + ): + with pytest.raises(TypeError, match="incompatible function arguments"): + call() + + @pytest.mark.parametrize("built_index", ["ivf_hnsw", "hnsw", "symqg"], indirect=True) def test_path_callback_runs_before_access_guard(built_index, tmp_path): index, queries = built_index @@ -210,9 +235,11 @@ def test_path_callback_runs_before_access_guard(built_index, tmp_path): class UpdatingPath: def __fspath__(self): if isinstance(index, IvfIndex): - index.reserve(0, index.num_stored_points) + index.reserve_cluster(0, index.num_stored_points) elif isinstance(index, HnswIndex): - index.resize(index.max_elements) + # An empty add still takes the write guard; a reserve within the + # capacity would only read. + index.add(np.empty((0, 64), dtype=np.float32)) else: # add is SymphonyQG's only write. It takes the write guard and then # refuses a built graph; a guard still held would raise "busy". @@ -317,3 +344,41 @@ def test_build_rejects_bad_coordinates_without_building(index_kind, value): with pytest.raises(ValueError): index.add(bad_data, cluster_ids=ids, num_threads=1) assert len(index) == 0 + + +@pytest.mark.parametrize("model", ["ivf", "hnsw", "qgkmeans", "rabitqkmeans"]) +def test_training_accepts_coordinates_at_the_index_bound(model): + # At dim 64 the float32 bound rounds above the exact real bound. + exact = np.sqrt(np.sqrt(np.float64(np.finfo(np.float32).max)) / (64.0 * 64)) + bound = np.float32(exact) + assert np.float64(bound) > exact + data = np.random.default_rng(5).normal(size=(400, 64)).astype(np.float32) + data[5, 3] = bound + data[6, 4] = -bound + + def fresh(): + if model == "ivf": + return IvfIndex(64, 4, nbits=4) + if model == "hnsw": + return HnswIndex(64, nbits=4, num_clusters=4) + return (QGKMeans if model == "qgkmeans" else RaBitQKMeans)(64, 40, niter=2) + + trained = fresh() + if model in ("ivf", "hnsw"): + trained.add(data, num_threads=1) # the first add trains + assert len(trained) == 400 + else: + trained.train(data) + trained.assign(data[5:7]) + + data[5, 3] = np.nextafter(bound, np.float32(np.inf)) + message = "KMeans x exceeds the safe float32 coordinate range$" + # Index train reaches the k-means check first; HNSW add checks before training. + with pytest.raises(ValueError, match=message): + if model in ("ivf", "hnsw"): + fresh().train(data, num_threads=1) + else: + fresh().train(data) + if model not in ("ivf", "hnsw"): + with pytest.raises(ValueError, match=message): + trained.assign(data[5:7]) diff --git a/tests/python/test_ivf.py b/tests/python/test_ivf.py index 32cbdbf9..1584fb08 100644 --- a/tests/python/test_ivf.py +++ b/tests/python/test_ivf.py @@ -3,6 +3,7 @@ import re from pathlib import Path +import format2_file import numpy as np import pytest from conftest import DIM, N_CLUSTERS, N_QUERIES, N_VECTORS, brute_force_knn, recall_at_k @@ -52,7 +53,7 @@ def test_properties(built_ivf): assert built_ivf.num_clusters == N_CLUSTERS assert built_ivf.nbits == 4 assert built_ivf.metric == "l2" - assert built_ivf.max_elements == N_VECTORS + assert built_ivf.num_stored_points == N_VECTORS # ── search output shape and dtype ───────────────────────────────────────────── @@ -65,7 +66,7 @@ def test_properties(built_ivf): def test_search_output_contract(built_ivf, query_data, nq, k, nprobe): ids, dists = built_ivf.search(query_data[:nq], k=k, nprobe=nprobe) assert ids.shape == dists.shape == (nq, k) - assert ids.dtype == np.uint32 + assert ids.dtype == np.int64 assert dists.dtype == np.float32 assert np.all(ids < N_VECTORS) assert np.isfinite(dists).all() @@ -104,7 +105,7 @@ def test_batch_search_matches_individual_queries(bits, metric): assert empty_ids.shape == empty_distances.shape == (0, 7) index.remove(np.arange(len(data))) ids, distances = index.search(queries, k=7, nprobe=4, num_threads=4) - assert np.all(ids == np.iinfo(np.uint32).max) + assert np.all(ids == -1) assert np.all(np.isinf(distances)) @@ -117,7 +118,7 @@ def test_unfilled_results_use_sentinels(): ids, dists = idx.search(data[:1], k=3, nprobe=1) assert ids[0, 0] == 0 - np.testing.assert_array_equal(ids[0, 1:], np.iinfo(np.uint32).max) + np.testing.assert_array_equal(ids[0, 1:], -1) assert np.all(np.isinf(dists[0, 1:])) @@ -322,8 +323,9 @@ def test_raw_reranking(metric, high_accuracy, fast_quantization, tmp_path): assert loaded.dim == dim assert loaded.metric == metric for k in (5, len(data)): - ids, distances = idx.search(queries, k, 3, high_accuracy, 2) - loaded_ids, loaded_distances = loaded.search(queries, k, 3, high_accuracy, 2) + options = {"high_accuracy": high_accuracy, "num_threads": 2} + ids, distances = idx.search(queries, k, 3, **options) + loaded_ids, loaded_distances = loaded.search(queries, k, 3, **options) np.testing.assert_array_equal(loaded_ids, ids) np.testing.assert_array_equal(loaded_distances, distances) np.testing.assert_allclose( @@ -336,11 +338,10 @@ def test_raw_reranking(metric, high_accuracy, fast_quantization, tmp_path): # The reranking region contains precisely original floats in cluster order, # with no extra-bit codes/factors or padded coordinates. payload = path.read_bytes() - ids_bytes = len(data) * np.dtype(np.uint32).itemsize - raw_bytes = original.nbytes stored = np.frombuffer( - payload[-ids_bytes - raw_bytes : -ids_bytes], dtype=np.float32 + format2_file.section(payload, format2_file.IVF_RERANK), dtype=np.float32 ) + assert stored.nbytes == original.nbytes order = np.argsort(cluster_ids, kind="stable") np.testing.assert_array_equal(stored.reshape(original.shape), original[order]) one_bit = _built( @@ -352,7 +353,13 @@ def test_raw_reranking(metric, high_accuracy, fast_quantization, tmp_path): ) one_bit_path = tmp_path / "one-bit.index" one_bit.save(str(one_bit_path)) - assert len(payload) - one_bit_path.stat().st_size == raw_bytes + # Raw storage adds only the rerank section; every other section is the same size. + raw_sections = format2_file.sections(payload) + one_bit_sections = format2_file.sections(one_bit_path.read_bytes()) + assert raw_sections.pop(format2_file.IVF_RERANK)[1] == original.nbytes + assert {kind: size for kind, (_, size) in raw_sections.items()} == { + kind: size for kind, (_, size) in one_bit_sections.items() + } @pytest.mark.parametrize( @@ -372,7 +379,13 @@ def test_raw_reranking(metric, high_accuracy, fast_quantization, tmp_path): def test_legacy_ivf_fixture(tmp_path, filename, dim, bits, padded, nonzero_distances): path = Path(__file__).parent / "fixtures" / filename idx = IvfIndex.load(str(path)) - assert (idx.dim, idx.max_elements, idx.num_clusters, idx.nbits, idx.metric) == ( + assert ( + idx.dim, + idx.num_stored_points, + idx.num_clusters, + idx.nbits, + idx.metric, + ) == ( dim, 3, 1, @@ -391,8 +404,8 @@ def test_legacy_ivf_fixture(tmp_path, filename, dim, bits, padded, nonzero_dista saved = tmp_path / "legacy.index" idx.save(str(saved)) payload = saved.read_bytes() - assert payload[:8] == b"RABQIDX1" - assert int.from_bytes(payload[16:24], "little") == padded + assert payload[:8] == format2_file.MAGIC + assert format2_file.padded_dim(payload) == padded loaded_ids, loaded_distances = IvfIndex.load(str(saved)).search(queries, 3, 1) np.testing.assert_array_equal(loaded_ids, ids) np.testing.assert_array_equal(loaded_distances, distances) @@ -419,7 +432,11 @@ def test_raw_index_rejects_invalid_files(tmp_path, damage): idx = _built(data, data[:1], np.zeros(2, dtype=np.uint32), nbits=32) path = tmp_path / "invalid.index" idx.save(str(path)) - payload = bytearray(path.read_bytes()) + # Damage the RABQIDX1 layout that releases up to 0.8 wrote, which loading still reads. + payload = bytearray(format2_file.to_rabqidx1(path.read_bytes())[0]) + assert payload[:8] == b"RABQIDX1" + path.write_bytes(payload) + IvfIndex.load(str(path)) # undamaged, the converted file loads if damage == "version": payload[8:12] = (99).to_bytes(4, "little") elif damage == "flags": @@ -477,31 +494,21 @@ def test_automatic_high_accuracy(nbits, tmp_path): np.testing.assert_array_equal(actual[1], expected[1]) -@pytest.mark.parametrize("failure", ["open", "write"]) -def test_hnsw_sidecar_save_failures(tmp_path, failure): - if failure == "write" and not Path("/dev/full").exists(): +@pytest.mark.parametrize("initializer", ["flat", "flat_rabitq", "hnsw"]) +def test_save_failure_keeps_the_index(tmp_path, initializer): + if not Path("/dev/full").exists(): pytest.skip("requires a device that rejects writes") data = np.zeros((2, 64), dtype=np.float32) data[1, 0] = 1 idx = _built( - data, data, np.arange(2, dtype=np.uint32), nbits=32, initializer="hnsw" + data, data, np.arange(2, dtype=np.uint32), nbits=32, routing=initializer ) expected = idx.search(data, 1, 1) - path = tmp_path / "sidecar_failure.index" - sidecar = Path(str(path) + ".hnsw") - if failure == "open": - sidecar.mkdir() - message = "Cannot open HNSW index file for writing" - else: - sidecar.symlink_to("/dev/full") - message = None # The stream failure message depends on the standard library. - with pytest.raises(RuntimeError, match=message): - idx.save(str(path)) - if failure == "open": - sidecar.rmdir() - else: - sidecar.unlink() + # /dev/full is not a regular file, so save writes it in place and the write fails. + with pytest.raises(RuntimeError): + idx.save("/dev/full") # Failure does not invalidate the in-memory index, and saving can be retried. + path = tmp_path / "retried.index" idx.save(str(path)) for obj in (idx, IvfIndex.load(str(path))): actual = obj.search(data, 1, 1) @@ -509,6 +516,25 @@ def test_hnsw_sidecar_save_failures(tmp_path, failure): np.testing.assert_array_equal(actual[1], expected[1]) +def test_hnsw_routing_is_saved_inside_the_index_file(tmp_path): + data = np.zeros((2, 64), dtype=np.float32) + data[1, 0] = 1 + idx = _built(data, data, np.arange(2, dtype=np.uint32), nbits=32, routing="hnsw") + expected = idx.search(data, 1, 1) + path = tmp_path / "embedded.index" + # A path where releases up to 0.8 wrote the sidecar is neither used nor needed. + sidecar = Path(str(path) + ".hnsw") + sidecar.mkdir() + idx.save(str(path)) + assert sidecar.is_dir() + payload = path.read_bytes() + assert format2_file.IVF_HNSW_ROUTING in format2_file.sections(payload) + for obj in (idx, IvfIndex.load(str(path))): + actual = obj.search(data, 1, 1) + np.testing.assert_array_equal(actual[0], expected[0]) + np.testing.assert_array_equal(actual[1], expected[1]) + + def test_hnsw_centroid_routing_roundtrip(tmp_path): # Explicit routing keeps HNSW coverage independent of the auto thresholds. # One vector per centroid makes nearest-centroid IDs and distances exact. @@ -516,7 +542,7 @@ def test_hnsw_centroid_routing_roundtrip(tmp_path): count, dim = 128, 64 centroids = rng.standard_normal((count, dim)).astype(np.float32) labels = np.arange(count, dtype=np.uint32) - idx = IvfIndex(dim, count, nbits=1, initializer="hnsw", seed=7) + idx = IvfIndex(dim, count, nbits=1, routing="hnsw", seed=7) # A seeded single-thread routing build gives the same graph on every run; a # parallel build may leave a centroid unreachable (#216). idx.set_centroids(centroids, num_threads=1) @@ -552,7 +578,7 @@ def test_hnsw_inner_product_routing_roundtrip(tmp_path): nbits=32, num_threads=4, metric="ip", - initializer="hnsw", + routing="hnsw", ) path = str(tmp_path / "hnsw_ip_centroid.index") @@ -587,9 +613,9 @@ def _dynamic_index(nbits=4, metric="l2", count=120, dim=65, clusters=3, seed=61) def test_add_returns_ids_and_makes_points_searchable(): idx, old, new, _ = _dynamic_index(nbits=32) added = idx.add(new) - assert added.dtype == np.uint32 + assert added.dtype == np.int64 np.testing.assert_array_equal(added, np.arange(len(old), len(old) + len(new))) - assert idx.max_elements == len(old) + len(new) + assert idx.num_stored_points == len(old) + len(new) # k may now exceed the original point count; raw storage makes the ranking exact. ids, dists = idx.search(new[:3], k=len(old) + len(new), nprobe=3) np.testing.assert_array_equal(ids[:, 0], added[:3]) @@ -645,7 +671,7 @@ def test_reserved_adds_match_a_single_add(tmp_path, nbits): whole.add(new, cluster_ids=assigned) parts = IvfIndex.load(str(base)) for cluster in range(parts.num_clusters): - parts.reserve(cluster, len(old) + len(new)) + parts.reserve_cluster(cluster, len(old) + len(new)) for chunk in np.array_split(np.arange(len(new)), [1, 33, 34, 90]): parts.add(new[chunk], cluster_ids=assigned[chunk]) a, b = tmp_path / "a.index", tmp_path / "b.index" @@ -654,29 +680,29 @@ def test_reserved_adds_match_a_single_add(tmp_path, nbits): assert a.read_bytes() == b.read_bytes() -def test_reserve_rejects_invalid_arguments(): +def test_reserve_cluster_rejects_invalid_arguments(): idx, old, _, _ = _dynamic_index() for bad in (-1, 3, 2**32): with pytest.raises(ValueError, match="cluster_id"): - idx.reserve(bad, 10) + idx.reserve_cluster(bad, 10) with pytest.raises(ValueError, match="num_points"): - idx.reserve(0, -1) + idx.reserve_cluster(0, -1) with pytest.raises(ValueError, match="supported ID range"): - idx.reserve(0, 2**40) - idx.reserve(0, 0) - assert idx.max_elements == len(old) + idx.reserve_cluster(0, 2**40) + idx.reserve_cluster(0, 0) + assert idx.num_stored_points == len(old) unbuilt = IvfIndex(65, 1, nbits=4) with pytest.raises(RuntimeError, match="trained or loaded"): - unbuilt.reserve(0, 1) + unbuilt.reserve_cluster(0, 1) def test_add_accepts_fast_quantization_and_other_dtypes(): idx, _, new, _ = _dynamic_index() idx.add(new[:10].astype(np.float64), fast_quantization=True) - assert idx.max_elements == 130 + assert idx.num_stored_points == 130 assert len(idx.add(new[:0])) == 0 - assert idx.max_elements == 130 + assert idx.num_stored_points == 130 def test_add_rejects_invalid_arguments(): @@ -692,7 +718,7 @@ def test_add_rejects_invalid_arguments(): cluster_ids[0] = bad with pytest.raises(ValueError, match="cluster_ids"): idx.add(new, cluster_ids=cluster_ids) - assert idx.max_elements == len(old) + assert idx.num_stored_points == len(old) # Without cluster IDs, the first add trains the index; with them, it needs centroids. unbuilt = IvfIndex(65, 1, nbits=4) @@ -718,7 +744,7 @@ def test_remove_excludes_points_and_survives_reload( assert idx.remove(removed) == 4 assert idx.remove(removed) == 0 assert idx.remove([]) == 0 - assert idx.max_elements == count + assert idx.num_stored_points == count def check(index): ids, dists = index.search( @@ -729,7 +755,7 @@ def check(index): keep = ~np.isin(before_ids[q], removed) np.testing.assert_array_equal(ids[q, :alive], before_ids[q][keep]) np.testing.assert_array_equal(dists[q, :alive], before_dists[q][keep]) - assert np.all(ids[q, alive:] == np.iinfo(np.uint32).max) + assert np.all(ids[q, alive:] == -1) assert np.all(np.isinf(dists[q, alive:])) top, top_dists = index.search( queries, k=10, nprobe=3, high_accuracy=high_accuracy @@ -751,7 +777,7 @@ def check(index): queries, k=count + len(new), nprobe=3, high_accuracy=high_accuracy ) assert not np.isin(ids, removed).any() - assert np.count_nonzero(ids[0] != np.iinfo(np.uint32).max) == count + len(new) - 4 + assert np.count_nonzero(ids[0] != -1) == count + len(new) - 4 # A reloaded index grows exactly like the original. expected_ids, expected_dists = idx.search( @@ -784,7 +810,7 @@ def test_removing_every_point_leaves_a_searchable_index(): idx, old, new, _ = _dynamic_index() assert idx.remove(np.arange(len(old))) == len(old) ids, dists = idx.search(new[:2], k=5, nprobe=3) - assert np.all(ids == np.iinfo(np.uint32).max) + assert np.all(ids == -1) assert np.all(np.isinf(dists)) @@ -811,7 +837,7 @@ def test_remove_and_add_refuse_non_integer_ids(bad): idx.add(new[:2], cluster_ids=bad) after = idx.search(new[:3], k=len(old), nprobe=3) np.testing.assert_array_equal(before[0], after[0]) - assert idx.max_elements == len(old) + assert idx.num_stored_points == len(old) def test_remove_and_add_accept_any_integer_dtype_and_empty_input(): diff --git a/tests/python/test_ivf_initializers.py b/tests/python/test_ivf_initializers.py index 09c45ff8..75e532d8 100644 --- a/tests/python/test_ivf_initializers.py +++ b/tests/python/test_ivf_initializers.py @@ -4,6 +4,7 @@ from concurrent.futures import ThreadPoolExecutor from pathlib import Path +import format2_file import numpy as np import pytest from rabitqlib import IvfIndex @@ -15,7 +16,7 @@ def test_hnsw_parallel_build_routes_and_reloads(tmp_path, metric, threads): count, dim = 1024, 65 data = np.random.default_rng(42).standard_normal((count, dim)).astype(np.float32) data /= np.linalg.norm(data, axis=1, keepdims=True) - index = IvfIndex(dim, count, nbits=4, metric=metric, initializer="hnsw") + index = IvfIndex(dim, count, nbits=4, metric=metric, routing="hnsw") index.set_centroids(data, num_threads=threads) index.add(data, cluster_ids=np.arange(count, dtype=np.uint32), num_threads=threads) # A parallel build may leave a centroid unreachable in the routing graph, so @@ -41,7 +42,7 @@ def test_single_thread_set_centroids_builds_reproducible_hnsw_routing(tmp_path, data = np.random.default_rng(42).standard_normal((count, dim)).astype(np.float32) saved = [] for run in range(2): - index = IvfIndex(dim, count, nbits=1, metric=metric, initializer="hnsw", seed=7) + index = IvfIndex(dim, count, nbits=1, metric=metric, routing="hnsw", seed=7) index.set_centroids(data, num_threads=1) index.add(data, cluster_ids=np.arange(count, dtype=np.uint32), num_threads=4) path = tmp_path / f"run-{run}.index" @@ -59,7 +60,7 @@ def test_hnsw_concurrent_routing_windows_match_serial(tmp_path, metric): rng = np.random.default_rng(42) data = rng.standard_normal((count, dim)).astype(np.float32) queries = rng.standard_normal((4, dim)).astype(np.float32) - index = IvfIndex(dim, count, nbits=1, metric=metric, initializer="hnsw") + index = IvfIndex(dim, count, nbits=1, metric=metric, routing="hnsw") index.set_centroids(data) index.add(data, cluster_ids=np.arange(count, dtype=np.uint32), num_threads=1) probes = (1, 16, 400, 500) @@ -79,17 +80,19 @@ def test_hnsw_concurrent_routing_windows_match_serial(tmp_path, metric): @pytest.mark.parametrize("metric", ["l2", "ip"]) @pytest.mark.parametrize("damage", ["entry", "neighbor", "level"]) -def test_hnsw_rejects_corrupt_sidecar(tmp_path, metric, damage): +def test_hnsw_rejects_corrupt_routing_graph(tmp_path, metric, damage): count, dim = 64, 64 data = np.random.default_rng(42).standard_normal((count, dim)).astype(np.float32) - index = IvfIndex(dim, count, nbits=4, metric=metric, initializer="hnsw") + index = IvfIndex(dim, count, nbits=4, metric=metric, routing="hnsw") index.set_centroids(data) index.add(data, cluster_ids=np.arange(count, dtype=np.uint32), num_threads=1) expected = index.search(data[:2], 1, 4, num_threads=1) path = tmp_path / "centroids.index" index.save(str(path)) - sidecar = Path(str(path) + ".hnsw") - original = sidecar.read_bytes() + saved = path.read_bytes() + # The graph is hnswlib's layout, in a section that has no checksum. + graph_offset, _ = format2_file.sections(saved)[format2_file.IVF_HNSW_ROUTING] + original = format2_file.section(saved, format2_file.IVF_HNSW_ROUTING) damaged = bytearray(original) # hnswlib writes native POD fields individually, with no inter-field padding. size_t_bytes = struct.calcsize("@N") @@ -108,10 +111,12 @@ def test_hnsw_rejects_corrupt_sidecar(tmp_path, metric, damage): max_level = struct.unpack_from("@i", original, level_offset)[0] struct.pack_into("@i", damaged, level_offset, max_level + 1) message = "Invalid HNSW centroid level structure" - sidecar.write_bytes(damaged) + file = bytearray(saved) + file[graph_offset : graph_offset + len(damaged)] = damaged + path.write_bytes(file) with pytest.raises(RuntimeError, match=f"^{message}$"): IvfIndex.load(str(path)) - sidecar.write_bytes(original) + path.write_bytes(saved) loaded = IvfIndex.load(str(path)) actual = loaded.search(data[:2], 1, 4, num_threads=1) for left, right in zip(expected, actual): @@ -134,9 +139,9 @@ def test_initializer_roundtrip_and_updates(tmp_path, metric, bits, initializer): dim, count = 65, 33 data = rng.standard_normal((count + 1, dim)).astype(np.float32) data /= np.linalg.norm(data, axis=1, keepdims=True) - index = IvfIndex(dim, count, nbits=bits, metric=metric, initializer=initializer) + index = IvfIndex(dim, count, nbits=bits, metric=metric, routing=initializer) resolved = "flat" if initializer == "auto" else initializer - assert index.initializer == resolved + assert index.routing == resolved index.set_centroids(data[:count]) index.add( data[:count], cluster_ids=np.arange(count, dtype=np.uint32), num_threads=2 @@ -147,18 +152,14 @@ def test_initializer_roundtrip_and_updates(tmp_path, metric, bits, initializer): path = tmp_path / "索引.index" index.save(str(path)) payload = path.read_bytes() - assert int.from_bytes(payload[8:12], "little") == 2 - assert ( - int.from_bytes(payload[24:28], "little") - == { - "flat": 1, - "flat_rabitq": 2, - "hnsw": 3, - }[resolved] - ) - assert Path(str(path) + ".hnsw").exists() == (resolved == "hnsw") + assert payload[:8] == format2_file.MAGIC + params = format2_file.section(payload, format2_file.IVF_PARAMS) + stored = {"flat": 1, "flat_rabitq": 2, "hnsw": 3}[resolved] + assert int.from_bytes(params[8:12], "little") == stored + assert format2_file.IVF_ROUTING[stored] in format2_file.sections(payload) + assert not Path(str(path) + ".hnsw").exists() loaded = IvfIndex.load(str(path)) - assert loaded.initializer == resolved + assert loaded.routing == resolved actual = loaded.search(queries, 3, 7, num_threads=2) for left, right in zip(expected, actual): np.testing.assert_array_equal(left, right) @@ -167,11 +168,11 @@ def test_initializer_roundtrip_and_updates(tmp_path, metric, bits, initializer): for obj in (index, loaded): obj.add(data[count:], num_threads=2) obj.remove(np.array([0], dtype=np.uint32)) - assert obj.initializer == resolved + assert obj.routing == resolved for left, right in zip(index.search(queries, 3, 7), loaded.search(queries, 3, 7)): np.testing.assert_array_equal(left, right) loaded.save(str(path)) - assert IvfIndex.load(str(path)).initializer == resolved + assert IvfIndex.load(str(path)).routing == resolved @pytest.mark.parametrize( @@ -186,9 +187,9 @@ def test_initializer_roundtrip_and_updates(tmp_path, metric, bits, initializer): ], ) def test_auto_initializer_thresholds(clusters, expected): - assert IvfIndex(64, clusters, nbits=1).initializer == expected + assert IvfIndex(64, clusters, nbits=1).routing == expected for mode in ("flat", "flat_rabitq", "hnsw"): - assert IvfIndex(64, clusters, nbits=1, initializer=mode).initializer == mode + assert IvfIndex(64, clusters, nbits=1, routing=mode).routing == mode # Historical routing depends only on the cluster count, and both storage widths' @@ -212,7 +213,7 @@ def historical_ivf(request): np.random.default_rng(43).standard_normal((clusters, 64)).astype(np.float32) ) historical = "flat" if clusters < 20000 else "hnsw" - index = IvfIndex(64, clusters, nbits=bits, initializer=historical) + index = IvfIndex(64, clusters, nbits=bits, routing=historical) index.set_centroids(centroids) index.add(centroids[:3], cluster_ids=np.arange(3, dtype=np.uint32), num_threads=2) return index, centroids[:3].copy() @@ -225,9 +226,17 @@ def test_legacy_formats_infer_historical_initializer( index, queries = historical_ivf path = tmp_path / "v1.index" index.save(str(path)) - # v2 must honor the stored type even when today's Auto would choose differently. - assert IvfIndex.load(str(path)).initializer == index.initializer - payload = bytearray(path.read_bytes()) + # Format 2 honors the stored type even when today's Auto would choose differently. + assert IvfIndex.load(str(path)).routing == index.routing + # Build the earlier layouts from the RABQIDX1 version 2 layout of 0.8. HNSW + # routing, chosen from 20000 clusters, lives in the sidecar of all three. + main, sidecar = format2_file.to_rabqidx1(path.read_bytes()) + if sidecar is not None: + Path(str(path) + ".hnsw").write_bytes(sidecar) + path.write_bytes(main) + # RABQIDX1 version 2 also records the routing type. + assert IvfIndex.load(str(path)).routing == index.routing + payload = bytearray(main) if format_version == "v1": # v1 has the same payload but no initializer field after padded_dim. del payload[24:28] @@ -239,7 +248,7 @@ def test_legacy_formats_infer_historical_initializer( payload = b"RBFQRAW1" + (1).to_bytes(4, "little") + payload path.write_bytes(payload) loaded = IvfIndex.load(str(path)) - assert loaded.initializer == index.initializer + assert loaded.routing == index.routing for left, right in zip(index.search(queries, 1, 2), loaded.search(queries, 1, 2)): np.testing.assert_array_equal(left, right) @@ -253,14 +262,14 @@ def test_initializer_rejects_invalid_argument(): def test_explicit_flat_routing_above_historical_threshold(tmp_path, initializer): centroids = np.zeros((20000, 64), dtype=np.float32) centroids[17, 0] = 1 - index = IvfIndex(64, len(centroids), nbits=32, initializer=initializer) + index = IvfIndex(64, len(centroids), nbits=32, routing=initializer) index.set_centroids(centroids) index.add(centroids[17:18], cluster_ids=np.array([17], np.uint32), num_threads=2) path = tmp_path / "large.index" index.save(str(path)) assert not Path(str(path) + ".hnsw").exists() for obj in (index, IvfIndex.load(str(path))): - assert obj.initializer == initializer + assert obj.routing == initializer ids, distances = obj.search(centroids[17:18], 1, 1) np.testing.assert_array_equal(ids, [[0]]) np.testing.assert_array_equal(distances, [[0]]) @@ -269,19 +278,38 @@ def test_explicit_flat_routing_above_historical_threshold(tmp_path, initializer) @pytest.mark.parametrize("damage", ["auto", "unknown", "truncated_initializer"]) def test_initializer_rejects_invalid_persistence(tmp_path, damage): data = np.zeros((3, 65), dtype=np.float32) - index = IvfIndex(65, 1, nbits=1, initializer="flat_rabitq") + index = IvfIndex(65, 1, nbits=1, routing="flat_rabitq") index.set_centroids(data[:1]) index.add(data, cluster_ids=np.zeros(3, dtype=np.uint32), num_threads=1) path = tmp_path / "bad.index" index.save(str(path)) payload = bytearray(path.read_bytes()) if damage in ("auto", "unknown"): - payload[24:28] = (0 if damage == "auto" else 99).to_bytes(4, "little") + offset, _ = format2_file.sections(payload)[format2_file.IVF_PARAMS] + value = 0 if damage == "auto" else 99 + payload[offset + 8 : offset + 12] = value.to_bytes(4, "little") + format2_file.reseal(payload) + message = "IVF index file has invalid routing parameters" else: - # The rotator is followed by raw centroids, mean, and the physical code batch. - payload = payload[: 28 + 4 * 8 + 2 + 8 + 96 // 2 + 96 * 4 + 1] + # The routing data holds the centroids, the mean and the physical code batch. + offset, size = format2_file.sections(payload)[259] + payload = payload[: offset + size - 1] + message = "IVF index file section kind 259 lies outside the file" path.write_bytes(payload) - with pytest.raises(RuntimeError): + with pytest.raises(RuntimeError, match=f"^{message}$"): + IvfIndex.load(str(path)) + + # The RABQIDX1 layout of earlier releases rejects the same damage. + index.save(str(path)) + legacy = bytearray(format2_file.to_rabqidx1(path.read_bytes())[0]) + if damage in ("auto", "unknown"): + legacy[24:28] = (0 if damage == "auto" else 99).to_bytes(4, "little") + message = "^Invalid IVF initializer type in index file$" + else: + legacy = legacy[: 28 + 4 * 8 + 2 + 8 + 96 // 2 + 96 * 4 + 1] + message = None # the stream failure message depends on the standard library + path.write_bytes(legacy) + with pytest.raises(RuntimeError, match=message): IvfIndex.load(str(path)) @@ -296,7 +324,7 @@ def test_auto_flat_rabitq_persists_actual_routing(tmp_path, clusters): index.save(str(path)) assert not Path(str(path) + ".hnsw").exists() for obj in (index, IvfIndex.load(str(path))): - assert obj.initializer == "flat_rabitq" + assert obj.routing == "flat_rabitq" ids, distances = obj.search(centroids[17:18], 1, 1) np.testing.assert_array_equal(ids, [[0]]) np.testing.assert_array_equal(distances, [[0]]) diff --git a/tests/python/test_kmeans_sampling.py b/tests/python/test_kmeans_sampling.py index 09c4de9c..adcbc4a9 100644 --- a/tests/python/test_kmeans_sampling.py +++ b/tests/python/test_kmeans_sampling.py @@ -3,7 +3,6 @@ import numpy as np import pytest from rabitqlib import ( - FinalAssignmentMode, IvfIndex, QGKMeans, QGKMeansParameters, @@ -14,7 +13,7 @@ DIM = 64 # QGKMeans requires more centroids than its default graph degree of 32. CLUSTERS = {QGKMeans: 33, RaBitQKMeans: 4} -MODES = [FinalAssignmentMode.Approximate, FinalAssignmentMode.Exact] +MODES = ["approximate", "exact"] def make_model(model_type, **kwargs): @@ -129,7 +128,7 @@ def test_assign_returns_documented_types_for_new_vectors(model_type, mode): rtol=1e-5, atol=1e-5, ) - if mode == FinalAssignmentMode.Exact: + if mode == "exact": all_distances = np.stack( [ selected_distances(queries, model.centroids, np.full(45, cluster)) @@ -165,9 +164,7 @@ def test_assign_on_training_data_matches_final_assignment( ) model.train(x) assignments, distances = model.assign(x) - reproducible = ( - sampled or mode == FinalAssignmentMode.Exact or model_type is RaBitQKMeans - ) + reproducible = sampled or mode == "exact" or model_type is RaBitQKMeans if reproducible: np.testing.assert_array_equal(assignments, model.assignments) np.testing.assert_array_equal(distances, model.distances) diff --git a/tests/python/test_large_dimensions.py b/tests/python/test_large_dimensions.py index 708680b2..90e954c1 100644 --- a/tests/python/test_large_dimensions.py +++ b/tests/python/test_large_dimensions.py @@ -24,13 +24,14 @@ def test_large_dimension_round_trip(tmp_path, dim, metric, kind): ef_construction=count, nbits=4, metric=metric, + seed=42, ) - search_args = {"ef": count} + search_args = {"ef_search": count} else: index = SymqgIndex( dim, max_degree=32, ef_construction=count, nbits=4, metric=metric, seed=42 ) - search_args = {"ef": count} + search_args = {"ef_search": count} # A seeded single-thread build is reproducible, so every self-query must succeed. if kind == "qg": diff --git a/tests/python/test_persistence_paths.py b/tests/python/test_persistence_paths.py index b03a7923..5489afc3 100644 --- a/tests/python/test_persistence_paths.py +++ b/tests/python/test_persistence_paths.py @@ -19,11 +19,11 @@ def test_unicode_path_round_trip(tmp_path, kind, unicode_directory): if kind.startswith("qg"): index.add(data, num_threads=1) - search_args = {"ef": 64} + search_args = {"ef_search": 64} else: index.set_centroids(data.mean(axis=0, keepdims=True)) index.add(data, cluster_ids=np.zeros(64, np.uint32), num_threads=1) - search_args = {"nprobe": 1} if kind.startswith("ivf") else {"ef": 64} + search_args = {"nprobe": 1} if kind.startswith("ivf") else {"ef_search": 64} directory = tmp_path / "\u6d4b\u8bd5_\U0001f680" if unicode_directory else tmp_path directory.mkdir(exist_ok=True) diff --git a/tests/python/test_pickle_protocols.py b/tests/python/test_pickle_protocols.py new file mode 100644 index 00000000..3fb271e0 --- /dev/null +++ b/tests/python/test_pickle_protocols.py @@ -0,0 +1,112 @@ +"""Pickle protocols 0 and 1 raise or round-trip instead of aborting the interpreter. + +Those protocols reduce through copyreg, which calls the constructor of pybind11's base +class; that throws through the C API and aborts the process (pybind11 issue 3745) +unless the class defines __reduce_ex__. The calls therefore run in a child process. +""" + +import subprocess +import sys +import textwrap + +import rabitqlib +from rabitqlib import _rabitqlib + +CHILD = textwrap.dedent( + """ + import pickle + import sys + + import numpy as np + import rabitqlib + from rabitqlib import _rabitqlib, quant + + if rabitqlib.__file__ != sys.argv[1]: + raise SystemExit(f"child imported {rabitqlib.__file__}, not {sys.argv[1]}") + x = np.random.default_rng(0).normal(size=(64, 64)).astype(np.float32) + flat = rabitqlib.RaBitQKMeans(64, 2, niter=1, num_threads=1, seed=1) + flat.train(x) + graph = rabitqlib.QGKMeans(64, 33, niter=1, num_threads=1, seed=1) + graph.train(x) + + def state(value): + return pickle.dumps(value, protocol=2) + + picklable = { + "Rotator": quant.Rotator(64, seed=1), + "Query": quant.Query(x[0], metric="ip"), + "Query with centroid": quant.Query(x[0], metric="l2", centroid=x[1]), + "MetricType": _rabitqlib.MetricType.IP, + "RotatorType": _rabitqlib.RotatorType.FhtKacRotator, + } + unpicklable = { + "IvfIndex": rabitqlib.IvfIndex(64, 2, seed=1), + "HnswIndex": rabitqlib.HnswIndex(64, seed=1), + "SymqgIndex": rabitqlib.SymqgIndex(64, seed=1), + "QGKMeansParameters": rabitqlib.QGKMeansParameters(), + "RaBitQKMeansParameters": rabitqlib.RaBitQKMeansParameters(), + "KMeansIterationStats": flat.iteration_stats[0], + "_RaBitQKMeans": flat._impl, + "_QGKMeans": graph._impl, + "RaBitQKMeans": flat, + } + for protocol in (0, 1): + for name, value in picklable.items(): + copy = pickle.loads(pickle.dumps(value, protocol=protocol)) + if state(copy) != state(value): + raise SystemExit(f"{name} changed in a protocol {protocol} round trip") + print(name, protocol, "round-trip", flush=True) + for name, value in unpicklable.items(): + try: + pickle.dumps(value, protocol=protocol) + except TypeError as error: + if "cannot pickle" not in str(error): + raise SystemExit(f"{name}: {error}") + print(name, protocol, "TypeError", flush=True) + else: + raise SystemExit(f"{name} pickled with protocol {protocol}") + print(len(picklable) + len(unpicklable), "cases", flush=True) + """ +) + + +def test_old_protocols_round_trip_or_raise_in_a_child_process(): + result = subprocess.run( + [sys.executable, "-c", CHILD, rabitqlib.__file__], + capture_output=True, + text=True, + timeout=300, + ) + assert result.returncode == 0, result.stdout + result.stderr + lines = result.stdout.splitlines() + cases = int(lines[-1].split()[0]) + assert len(lines) == 1 + 2 * cases, lines + assert "Query with centroid 0 round-trip" in lines + assert "_QGKMeans 1 TypeError" in lines + + +def extension_classes(): + """Every pybind11 class that rabitqlib registered, found through the subclass tree.""" + pending = [ + base + for base in type(_rabitqlib.MetricType.IP).__mro__ + if base.__name__ == "pybind11_object" + ] + found = [] + while pending: + cls = pending.pop() + pending.extend(cls.__subclasses__()) + # quant.py renames its classes' module to rabitqlib.quant when imported. + if cls.__module__.split(".")[0] == "rabitqlib": + found.append(cls) + return found + + +def test_every_extension_class_defines_reduce_ex(): + classes = extension_classes() + names = {cls.__name__ for cls in classes} + assert {"IvfIndex", "Query", "_QGKMeans", "MetricType"} <= names, names + assert ( + sorted(cls.__name__ for cls in classes if "__reduce_ex__" not in vars(cls)) + == [] + ) diff --git a/tests/python/test_portable_indexes.py b/tests/python/test_portable_indexes.py index 8bed52a1..a87339c9 100644 --- a/tests/python/test_portable_indexes.py +++ b/tests/python/test_portable_indexes.py @@ -1,5 +1,6 @@ """Portable kernels preserve metric, padded-domain, and persistence contracts.""" +import format2_file import numpy as np import pytest from rabitqlib import HnswIndex, IvfIndex, SymqgIndex @@ -23,7 +24,7 @@ def check_index_round_trip(tmp_path, metric, dim, kind, bits): metric=metric, seed=42, ) - search_args = {"ef": 96} + search_args = {"ef_search": 96} else: # Seeded and single-threaded, so every self-query below must succeed (#216). index = SymqgIndex( @@ -34,7 +35,7 @@ def check_index_round_trip(tmp_path, metric, dim, kind, bits): metric=metric, seed=42, ) - search_args = {"ef": 96} + search_args = {"ef_search": 96} if kind == "qg": index.add(data, num_threads=1) else: @@ -58,18 +59,8 @@ def check_index_round_trip(tmp_path, metric, dim, kind, bits): path = tmp_path / "portable.index" index.save(str(path)) payload = path.read_bytes() - if kind == "ivf": - assert payload[:8] == b"RABQIDX1" - multiple = 32 - stored_padded = int.from_bytes(payload[16:24], "little") - elif kind == "qg": - multiple = 32 - offset = (12 if bits else 0) + 3 * np.dtype(np.uintp).itemsize - stored_padded = int.from_bytes(payload[offset : offset + 8], "little") - else: - multiple = 32 - stored_padded = int.from_bytes(payload[24:32], "little") - assert stored_padded == (dim + multiple - 1) // multiple * multiple + assert payload[:8] == format2_file.MAGIC + assert format2_file.padded_dim(payload) == (dim + 31) // 32 * 32 loaded = type(index).load(str(path)) assert loaded.dim == dim assert loaded.metric == metric @@ -122,15 +113,15 @@ def test_rejects_development_only_padding(tmp_path, kind, bits): check_index_round_trip(tmp_path, "l2", 65, kind, bits) path = tmp_path / "portable.index" payload = bytearray(path.read_bytes()) - offset = {"ivf": 16, "hnsw": 24, "qg": 12 + 3 * np.dtype(np.uintp).itemsize}[kind] # 80 is a valid pad16 dimension but unsupported by the pad32 kernels. - payload[offset : offset + 8] = (80).to_bytes(8, "little") + payload[56:64] = (80).to_bytes(8, "little") + format2_file.reseal(payload) path.write_bytes(payload) cls = {"ivf": IvfIndex, "hnsw": HnswIndex, "qg": SymqgIndex}[kind] - message = { - "ivf": "Invalid padded dimension in IVF index file", - "hnsw": "HNSW index file is invalid or truncated", - "qg": "QuantizedGraph file has an invalid padded dimension", - }[kind] + component = {"ivf": "IVF", "hnsw": "HNSW", "qg": "QuantizedGraph"}[kind] + message = ( + f"{component} index file has padded dimension 80, which must be a multiple of " + "32 from the dimension 65 to 65536" + ) with pytest.raises(RuntimeError, match=f"^{message}$"): cls.load(str(path)) diff --git a/tests/python/test_qgkmeans.py b/tests/python/test_qgkmeans.py index 25980235..02cbda0f 100644 --- a/tests/python/test_qgkmeans.py +++ b/tests/python/test_qgkmeans.py @@ -5,7 +5,7 @@ import numpy as np import pytest from conftest import DIM -from rabitqlib import FinalAssignmentMode, QGKMeans, QGKMeansParameters, RaBitQKMeans +from rabitqlib import QGKMeans, QGKMeansParameters, RaBitQKMeans K = 33 @@ -26,7 +26,7 @@ def qgkmeans(**kwargs): "niter": 2, "num_threads": 1, "min_points_per_centroid": 1, - "ef_build": K, + "ef_construction": K, "ef_search": K, "graph_build_iterations": 2, } @@ -40,7 +40,7 @@ def test_parameters_use_faiss_names_and_defaults(): assert cp.graph_build_iterations == 1 assert cp.min_points_per_centroid == 39 assert cp.early_stop_threshold == 0.0 - assert cp.quantization_bits == 0 + assert cp.nbits == 32 def test_constructor_accepts_faiss_style_keyword_parameters(): @@ -77,11 +77,9 @@ def test_parameters_can_be_changed_through_cp(base_data): assert len(clustering.iteration_stats) == 1 -@pytest.mark.parametrize("bits", [0, 8]) +@pytest.mark.parametrize("bits", [32, 8]) def test_exact_final_assignment_has_no_nearest_centroid_violations(base_data, bits): - clustering = qgkmeans( - final_assignment=FinalAssignmentMode.Exact, quantization_bits=bits - ) + clustering = qgkmeans(final_assignment="exact", nbits=bits) clustering.train(base_data) differences = ( @@ -109,11 +107,11 @@ def test_exact_final_assignment_handles_matrix_tile_tails(spherical, threads): niter=1, num_threads=threads, min_points_per_centroid=1, - ef_build=40, + ef_construction=40, ef_search=40, graph_build_iterations=1, spherical=spherical, - final_assignment=FinalAssignmentMode.Exact, + final_assignment="exact", ) clustering.train(x) @@ -142,7 +140,7 @@ def test_exact_final_assignment_preserves_shifted_l2_accuracy(): niter=1, num_threads=4, min_points_per_centroid=1, - final_assignment=FinalAssignmentMode.Exact, + final_assignment="exact", ) clustering.train(x) @@ -169,7 +167,7 @@ def test_exact_final_assignment_uses_first_duplicate_centroid(spherical, model_t num_threads=4, min_points_per_centroid=1, spherical=spherical, - final_assignment=FinalAssignmentMode.Exact, + final_assignment="exact", ) clustering.train(x) @@ -183,7 +181,7 @@ def test_spherical_mode_returns_normalized_centroids(base_data): normalized = base_data / np.linalg.norm(base_data, axis=1, keepdims=True) clustering = qgkmeans( spherical=True, - final_assignment=FinalAssignmentMode.Exact, + final_assignment="exact", ) clustering.train(normalized) @@ -202,7 +200,7 @@ def test_spherical_mode_returns_normalized_centroids(base_data): np.testing.assert_allclose(clustering.distances, selected_distances, atol=1e-6) -@pytest.mark.parametrize("bits", [0, 4, 8]) +@pytest.mark.parametrize("bits", [32, 4, 8]) @pytest.mark.parametrize("spherical", [False, True]) def test_graph_returns_exact_selected_distances(bits, spherical): x = np.random.default_rng(42).standard_normal((100, 65)).astype(np.float32) @@ -211,12 +209,12 @@ def test_graph_returns_exact_selected_distances(bits, spherical): clustering = QGKMeans( 65, K, - quantization_bits=bits, + nbits=bits, spherical=spherical, niter=2, num_threads=2, min_points_per_centroid=1, - ef_build=K, + ef_construction=K, ef_search=K, graph_build_iterations=2, ) @@ -237,12 +235,10 @@ def test_graph_returns_exact_selected_distances(bits, spherical): np.testing.assert_allclose(clustering.distances, expected, rtol=1e-6, atol=1e-6) -@pytest.mark.parametrize("bits", [1, 7, 9, 32]) -def test_train_rejects_unsupported_quantization_bits(base_data, bits): - clustering = qgkmeans(quantization_bits=bits) - with pytest.raises( - ValueError, match="^QGKMeans quantization_bits must be 0, 4, or 8$" - ): +@pytest.mark.parametrize("bits", [0, 1, 7, 9]) +def test_train_rejects_unsupported_nbits(base_data, bits): + clustering = qgkmeans(nbits=bits) + with pytest.raises(ValueError, match="^QGKMeans nbits must be 4, 8, or 32$"): clustering.train(base_data) @@ -305,9 +301,9 @@ def test_zero_input_converges_without_exhausting_iterations(): np.testing.assert_array_equal(clustering.distances, 0) -@pytest.mark.parametrize("bits", [0, 4, 8]) +@pytest.mark.parametrize("bits", [32, 4, 8]) def test_final_objective_measures_returned_assignments(base_data, bits): - clustering = qgkmeans(niter=1, quantization_bits=bits) + clustering = qgkmeans(niter=1, nbits=bits) assert clustering.final_obj is None returned = clustering.train(base_data) assert returned == clustering.obj[-1] @@ -334,7 +330,7 @@ def test_empty_cluster_recovery_preserves_constant_data(spherical): np.testing.assert_array_equal(clustering.centroids, x[:K]) -@pytest.mark.parametrize("bits", [0, 4, 8]) +@pytest.mark.parametrize("bits", [32, 4, 8]) @pytest.mark.parametrize("threads", [1, 4]) def test_single_empty_cluster_preserves_duplicate_centroids(bits, threads): # n == k includes every input row in initialization. Exactly one duplicate @@ -344,8 +340,8 @@ def test_single_empty_cluster_preserves_duplicate_centroids(bits, threads): clustering = qgkmeans( niter=1, num_threads=threads, - quantization_bits=bits, - final_assignment=FinalAssignmentMode.Exact, + nbits=bits, + final_assignment="exact", ) clustering.train(x) @@ -368,7 +364,7 @@ def test_final_objective_does_not_regress_after_last_update(spherical): num_threads=2, min_points_per_centroid=1, # C++ checks every storage width with a genuinely approximate graph. - quantization_bits=4, + nbits=4, spherical=spherical, ) clustering.train(x) @@ -376,7 +372,7 @@ def test_final_objective_does_not_regress_after_last_update(spherical): assert clustering.final_obj == clustering.distances.sum(dtype=np.float64) -@pytest.mark.parametrize("bits", [0, 4, 8]) +@pytest.mark.parametrize("bits", [32, 4, 8]) @pytest.mark.parametrize("spherical", [False, True]) def test_pipnn_default_rebuilds_and_returns_exact_selected_distances(bits, spherical): x = np.random.default_rng(73).standard_normal((100, 65)).astype(np.float32) @@ -388,7 +384,7 @@ def test_pipnn_default_rebuilds_and_returns_exact_selected_distances(bits, spher niter=3, num_threads=2, min_points_per_centroid=1, - quantization_bits=bits, + nbits=bits, spherical=spherical, ) for shift in (0.0, 0.02): @@ -407,9 +403,9 @@ def test_pipnn_default_rebuilds_and_returns_exact_selected_distances(bits, spher np.testing.assert_allclose(model.final_obj, expected.sum(), rtol=1e-6) -@pytest.mark.parametrize("bits", [0, 4, 8]) +@pytest.mark.parametrize("bits", [32, 4, 8]) def test_finite_out_of_range_input_preserves_previous_fit(base_data, bits): - model = qgkmeans(quantization_bits=bits) + model = qgkmeans(nbits=bits) model.train(base_data) expected = model.centroids with pytest.raises( @@ -428,7 +424,7 @@ def test_training_size_warning_is_opt_in(capfd, verbose): # C++ covers each dimension/storage layout; check binding outputs here. -@pytest.mark.parametrize("dim,bits", [(4097, 0), (65535, 4), (65536, 8)]) +@pytest.mark.parametrize("dim,bits", [(4097, 32), (65535, 4), (65536, 8)]) def test_large_dimensions(dim, bits): x = np.zeros((33, dim), dtype=np.float32) x[np.arange(33), np.arange(33)] = 1 @@ -438,7 +434,7 @@ def test_large_dimensions(dim, bits): 33, niter=1, num_threads=2, - quantization_bits=bits, + nbits=bits, ) model.train(x) assert model.centroids.shape == (33, dim) @@ -446,7 +442,7 @@ def test_large_dimensions(dim, bits): np.testing.assert_array_equal(x, model.centroids[model.assignments]) -@pytest.mark.parametrize("bits", [0, 4, 8]) +@pytest.mark.parametrize("bits", [32, 4, 8]) @pytest.mark.parametrize("threads", [1, 4]) def test_grouped_training_preserves_centroid_means_with_dimension_tail(bits, threads): x = np.repeat(np.eye(K, 65, dtype=np.float32) * 16, 3, axis=0) @@ -457,8 +453,8 @@ def test_grouped_training_preserves_centroid_means_with_dimension_tail(bits, thr niter=8, num_threads=threads, min_points_per_centroid=1, - quantization_bits=bits, - ef_build=K, + nbits=bits, + ef_construction=K, ef_search=K, ) model.train(x) @@ -472,7 +468,7 @@ def test_grouped_training_preserves_centroid_means_with_dimension_tail(bits, thr np.testing.assert_array_equal(model.centroids, expected) -@pytest.mark.parametrize("bits", [0, 4, 8]) +@pytest.mark.parametrize("bits", [32, 4, 8]) @pytest.mark.parametrize("spherical", [False, True]) @pytest.mark.parametrize("dim", [511, 960, 1024]) def test_refit_recomputes_sums_for_mutated_storage_seed_and_count(bits, spherical, dim): @@ -489,9 +485,9 @@ def make_model(seed): num_threads=1, seed=seed, min_points_per_centroid=1, - ef_build=128, + ef_construction=128, ef_search=1, - quantization_bits=bits, + nbits=bits, spherical=spherical, ) @@ -523,9 +519,31 @@ def make_model(seed): np.testing.assert_array_equal(data, before) -def test_approximate_final_assignment_keeps_graph_mode_alias(): - assert FinalAssignmentMode.Approximate == FinalAssignmentMode.SymphonyQG - assert QGKMeansParameters().final_assignment == FinalAssignmentMode.Approximate +@pytest.mark.parametrize( + "parameters,message", + [ + ({"max_degree": 48}, "QGKMeans max_degree must be a positive multiple of 32"), + ({"max_degree": 0}, "QGKMeans max_degree must be a positive multiple of 32"), + ( + {"ef_construction": 0}, + "QGKMeans ef_construction and ef_search must be positive", + ), + ({"ef_search": 0}, "QGKMeans ef_construction and ef_search must be positive"), + ( + {"graph_build_iterations": 0}, + "QGKMeans graph_build_iterations must be positive", + ), + ], +) +def test_train_rejects_invalid_graph_parameters(base_data, parameters, message): + model = QGKMeans(DIM, 80, niter=1, **parameters) + with pytest.raises(ValueError, match=f"^{message}$"): + model.train(base_data) + assert model.centroids is None + + +def test_final_assignment_is_approximate_by_default(): + assert QGKMeansParameters().final_assignment == "approximate" @pytest.mark.parametrize( @@ -534,14 +552,12 @@ def test_approximate_final_assignment_keeps_graph_mode_alias(): # and propagation of a non-default graph degree through Python. [(1, 32), (32, 32), (64, 64)], ) -@pytest.mark.parametrize( - "mode", [FinalAssignmentMode.Approximate, FinalAssignmentMode.Exact] -) -def test_graph_rejects_clusters_at_or_below_graph_degree(clusters, degree, mode): +@pytest.mark.parametrize("mode", ["approximate", "exact"]) +def test_graph_rejects_clusters_at_or_below_max_degree(clusters, degree, mode): model = QGKMeans( - 64, clusters, niter=1, num_threads=1, graph_degree=degree, final_assignment=mode + 64, clusters, niter=1, num_threads=1, max_degree=degree, final_assignment=mode ) with pytest.raises( - ValueError, match="^QGKMeans requires more centroids than the graph degree$" + ValueError, match="^QGKMeans requires more centroids than max_degree$" ): model.train(np.zeros((65, 64), dtype=np.float32)) diff --git a/tests/python/test_quant_editor_support.py b/tests/python/test_quant_editor_support.py index 65462890..7f77b44b 100644 --- a/tests/python/test_quant_editor_support.py +++ b/tests/python/test_quant_editor_support.py @@ -71,6 +71,13 @@ def test_module_docs_and_exports(): n.name for n in tree.body if isinstance(n, (ast.ClassDef, ast.FunctionDef)) } declared.update(n.target.id for n in tree.body if isinstance(n, ast.AnnAssign)) + declared.update( # explicit re-exports such as FormatError + alias.asname + for n in tree.body + if isinstance(n, ast.ImportFrom) + for alias in n.names + if alias.asname == alias.name + ) assert set(quant.__all__) == declared for name in quant.__all__: assert hasattr(quant, name), name @@ -98,8 +105,18 @@ def test_function_signatures_and_docs(name): def test_classes_match_runtime(): - classes = {n.name: n for n in installed_stub().body if isinstance(n, ast.ClassDef)} - assert set(classes) == {"FormatError", "Query", "Rotator"} + stub = installed_stub().body + classes = {n.name: n for n in stub if isinstance(n, ast.ClassDef)} + assert set(classes) == {"Query", "Rotator"} + # FormatError is rabitqlib.FormatError, which the stub re-exports. + assert quant.FormatError is rabitqlib.FormatError + reexports = { + alias.name: alias.asname + for node in stub + if isinstance(node, ast.ImportFrom) and node.module == "rabitqlib" + for alias in node.names + } + assert reexports.get("FormatError") == "FormatError" for name, cls in classes.items(): runtime = getattr(quant, name) assert runtime.__module__ == "rabitqlib.quant" diff --git a/tests/python/test_quant_rotator.py b/tests/python/test_quant_rotator.py index d96a0686..52a45072 100644 --- a/tests/python/test_quant_rotator.py +++ b/tests/python/test_quant_rotator.py @@ -63,6 +63,19 @@ def test_seeds_threads_and_out(): assert first.rotate(np.empty((0, 64), np.float32)).shape == (0, 64) +def test_matrix_rotation_takes_both_signs(): + # An unadjusted Householder Q has a fixed determinant and a negative first entry; + # a Haar-distributed matrix takes either sign of both across seeds. + first_negative, det_negative = set(), set() + for seed in range(64): + rotator = quant.Rotator(32, method="matrix", seed=seed) + q_t = rotator.rotate(np.eye(32, dtype=np.float32)).astype(np.float64) + first_negative.add(bool(q_t[0, 0] < 0)) + det_negative.add(bool(np.linalg.det(q_t) < 0)) + assert first_negative == {False, True} + assert det_negative == {False, True} + + def test_golden_blobs(): for name, rotator in ( ("rotator_fht_kac_dim64_seed0.bin", quant.Rotator(64, seed=0)), @@ -123,6 +136,7 @@ def test_corrupt_and_unsupported_blobs(): with pytest.raises(quant.FormatError, match=message): quant.Rotator.from_bytes(data) assert issubclass(quant.FormatError, ValueError) + assert issubclass(quant.FormatError, RuntimeError) unknown_seed = quant.Rotator.from_bytes(patched(patched(blob, 20, 0), 56, 0)) assert unknown_seed.seed is None with pytest.raises(TypeError, match="contiguous bytes-like"): diff --git a/tests/python/test_rabitqkmeans.py b/tests/python/test_rabitqkmeans.py index ab1c198f..d34395c4 100644 --- a/tests/python/test_rabitqkmeans.py +++ b/tests/python/test_rabitqkmeans.py @@ -3,11 +3,10 @@ import numpy as np import pytest from rabitqlib import ( - FinalAssignmentMode, + KMeansIterationStats, QGKMeans, QGKMeansParameters, RaBitQKMeans, - RaBitQKMeansIterationStats, RaBitQKMeansParameters, ) @@ -19,7 +18,7 @@ def test_flat_parameters_and_outputs(): assert parameters.niter == 25 assert parameters.min_points_per_centroid == 39 assert parameters.early_stop_threshold == 0.0 - assert parameters.final_assignment == FinalAssignmentMode.Approximate + assert parameters.final_assignment == "approximate" model = RaBitQKMeans(65, 33, niter=2, num_threads=1, seed=123) assert model.cp.seed == 123 assert model.centroids is None @@ -35,17 +34,17 @@ def test_flat_parameters_and_outputs(): assert model.obj.shape == (1,) assert objective == model.obj[-1] assert model.final_obj == model.distances.sum(dtype=np.float64) - assert isinstance(model.iteration_stats[0], RaBitQKMeansIterationStats) + assert isinstance(model.iteration_stats[0], KMeansIterationStats) @pytest.mark.parametrize( "parameter", [ - "graph_degree", - "ef_build", + "max_degree", + "ef_construction", "ef_search", "graph_build_iterations", - "quantization_bits", + "nbits", ], ) def test_flat_rejects_graph_only_parameters(parameter): @@ -80,7 +79,7 @@ def test_flat_train_refit_and_return_exact_selected_distances( ): rng = np.random.default_rng(573) x = rng.standard_normal((97, 65), dtype=np.float32) - mode = FinalAssignmentMode.Exact if exact else FinalAssignmentMode.Approximate + mode = "exact" if exact else "approximate" parameters = dict( niter=3, num_threads=2, @@ -133,7 +132,7 @@ def test_flat_duplicates_and_zero(clusters, spherical): num_threads=2, spherical=spherical, min_points_per_centroid=1, - final_assignment=FinalAssignmentMode.Approximate, + final_assignment="approximate", ) model.train(x) np.testing.assert_array_equal(model.centroids, x[:clusters]) diff --git a/tests/python/test_remove_arrays.py b/tests/python/test_remove_arrays.py index e746561b..e817cce1 100644 --- a/tests/python/test_remove_arrays.py +++ b/tests/python/test_remove_arrays.py @@ -20,7 +20,7 @@ def test_remove_integer_views_preserve_input_and_validate_atomically( ) index.set_centroids(np.zeros((1, dim), np.float32)) index.add(data, cluster_ids=np.zeros(count, np.uint32), num_threads=1) - search_args = {"nprobe": 1} if kind == "ivf" else {"ef": count} + search_args = {"nprobe": 1} if kind == "ivf" else {"ef_search": count} before = index.search(data, k=1, **search_args) def make_ids(values): diff --git a/tests/python/test_removed_forms.py b/tests/python/test_removed_forms.py new file mode 100644 index 00000000..3501479f --- /dev/null +++ b/tests/python/test_removed_forms.py @@ -0,0 +1,334 @@ +"""The call forms that 0.9 removed fail plainly; none is read as something else. + +Covers the 0.7 forms (issue #213), the 0.8 index spellings (#232), including the +"innerproduct" metric spelling, and the 0.8 k-means spellings (#233). +""" + +import pickle + +import numpy as np +import pytest +import rabitqlib +from conftest import DIM, N_VECTORS +from rabitqlib import ( + HnswIndex, + IvfIndex, + QGKMeans, + QGKMeansParameters, + RaBitQKMeans, + RaBitQKMeansParameters, + SymqgIndex, + quant, +) + + +@pytest.fixture(scope="module") +def ivf(base_data): + index = IvfIndex(DIM, 8, nbits=4, routing="flat", seed=3) + index.add(base_data, num_threads=1) + return index + + +@pytest.fixture(scope="module") +def hnsw(base_data): + index = HnswIndex(DIM, nbits=4, num_clusters=4, seed=3) + index.add(base_data, num_threads=1) + return index + + +@pytest.fixture(scope="module") +def symqg(base_data): + index = SymqgIndex(DIM, ef_construction=60, seed=3) + index.add(base_data, num_threads=1) + return index + + +@pytest.mark.parametrize( + "make", + [ + # IvfIndex(dim, max_elements, num_clusters, nbits, metric, initializer) + lambda: IvfIndex(DIM, 1000, 64), + lambda: IvfIndex(DIM, N_VECTORS, 4, 4), + lambda: IvfIndex(DIM, N_VECTORS, 4, 4, "l2", "flat"), + lambda: IvfIndex(dim=DIM, max_elements=N_VECTORS, num_clusters=4, nbits=4), + lambda: IvfIndex(DIM, N_VECTORS, num_clusters=4, nbits=4), + lambda: IvfIndex(DIM, 4, initializer="flat"), + # HnswIndex(dim, max_elements, M, ef_construction, nbits, metric, random_seed) + lambda: HnswIndex(DIM, N_VECTORS), + lambda: HnswIndex(DIM, N_VECTORS, 16, 200, 4, "l2", 100), + lambda: HnswIndex(DIM, max_elements=N_VECTORS), + lambda: HnswIndex(DIM, random_seed=5), + # SymqgIndex(dim, max_degree, metric, quantization_bits) + lambda: SymqgIndex(DIM, 32), + lambda: SymqgIndex(DIM, 32, "l2", 4), + lambda: SymqgIndex(DIM, quantization_bits=0), + ], +) +def test_removed_constructor_forms_raise_type_error(make): + with pytest.raises(TypeError, match="incompatible constructor arguments") as error: + make() + # Only the public constructor is offered as the alternative. + assert "\n 1. " in str(error.value) + assert "\n 2. " not in str(error.value) + + +@pytest.mark.parametrize("kind", ["ivf", "hnsw"]) +def test_add_options_are_keyword_only(kind, request, base_data): + index = request.getfixturevalue(kind) + cluster_ids = np.zeros(4, dtype=np.uint32) + stored = index.num_stored_points + for call in ( + lambda: index.add(base_data[:4], cluster_ids), + lambda: index.add(base_data[:4], cluster_ids, 1), + lambda: index.add(base_data[:4], cluster_ids, 1, False), + ): + with pytest.raises(TypeError, match="incompatible function arguments"): + call() + assert index.num_stored_points == stored + + +def test_ivf_search_keeps_only_nprobe_positional(ivf, query_data): + expected = ivf.search(query_data, 3, 4, high_accuracy=False, num_threads=1) + # Four probes find other neighbors than the default of one, so a dropped + # argument would fail the comparison below. + assert not np.array_equal( + expected[0], ivf.search(query_data, 3, high_accuracy=False)[0] + ) + for call in ( + lambda: ivf.search(query_data, 3, 4, False), + lambda: ivf.search(query_data, 3, 4, False, 1), + ): + with pytest.raises(TypeError, match="incompatible function arguments"): + call() + actual = ivf.search(query_data, 3, nprobe=4, high_accuracy=False) + np.testing.assert_array_equal(actual[0], expected[0]) + np.testing.assert_array_equal(actual[1], expected[1]) + + +@pytest.mark.parametrize("kind", ["hnsw", "symqg"]) +def test_graph_search_takes_ef_search_and_keyword_threads(kind, request, query_data): + index = request.getfixturevalue(kind) + # A breadth of k finds other neighbors than the default of max(k, 64), so a + # dropped argument would fail the comparison below. + expected = index.search(query_data, 3, ef_search=3) + assert not np.array_equal(expected[0], index.search(query_data, 3)[0]) + for call in ( + lambda: index.search(query_data, 3, ef=3), + lambda: index.search(query_data, 3, 3, 1), + lambda: index.search(query_data, 3, 3, ef=3), + ): + with pytest.raises(TypeError, match="incompatible function arguments"): + call() + actual = index.search(query_data, 3, 3, num_threads=1) + np.testing.assert_array_equal(actual[0], expected[0]) + np.testing.assert_array_equal(actual[1], expected[1]) + + +@pytest.mark.parametrize("zero", [0, np.int64(0), False, np.float32(0)]) +def test_zero_breadth_is_rejected(zero, ivf, hnsw, symqg, query_data): + message = "^nprobe must be at least 1; pass None for the default$" + for call in ( + lambda: ivf.search(query_data, 3, zero), + lambda: ivf.search(query_data, 3, nprobe=zero), + ): + with pytest.raises(ValueError, match=message): + call() + message = "^ef_search must be at least 1; pass None for the default$" + for index in (hnsw, symqg): + for call in ( + lambda index=index: index.search(query_data, 3, zero), + lambda index=index: index.search(query_data, 3, ef_search=zero), + ): + with pytest.raises(ValueError, match=message): + call() + + +def test_none_and_zero_threads_are_still_accepted(ivf, hnsw, symqg, query_data): + for index in (ivf, hnsw, symqg): + expected = index.search(query_data, 3) + for options in ({"num_threads": None}, {"num_threads": 0}): + actual = index.search(query_data, 3, None, **options) + np.testing.assert_array_equal(actual[0], expected[0]) + + +REMOVED_MEMBERS = { + "ivf": [ + "build", + "_build", + "is_built", + "max_elements", + "capacity", + "initializer", + "reserve", + ], + "hnsw": ["build", "_build", "is_built", "max_elements", "resize"], + "symqg": [ + "build", + "_build", + "search_batch", + "quantization_bits", + "_quantization_bits", + "is_built", + "max_elements", + "capacity", + ], +} + + +@pytest.mark.parametrize( + "kind,name", + [(kind, name) for kind, names in REMOVED_MEMBERS.items() for name in names], +) +def test_removed_index_members_raise_attribute_error(kind, name, request): + index = request.getfixturevalue(kind) + assert not hasattr(type(index), name) + with pytest.raises(AttributeError, match=f"has no attribute '{name}'"): + getattr(index, name) + # An assignment must not create the attribute either. + with pytest.raises(AttributeError): + setattr(index, name, 1) + + +def test_renamed_index_members(ivf, hnsw): + assert ivf.routing == "flat" + assert hnsw.capacity >= hnsw.num_stored_points == N_VECTORS + for index, name in ((ivf, "routing"), (hnsw, "capacity")): + with pytest.raises(AttributeError): + setattr(index, name, getattr(index, name)) + assert f"capacity={hnsw.capacity}" in repr(hnsw) + assert "routing='flat'" in repr(ivf) + for index in (ivf, hnsw): + assert "max_elements" not in repr(index) + assert "initializer" not in repr(index) + with pytest.raises(ValueError, match="^routing must be 'auto', 'flat'"): + IvfIndex(DIM, 8, routing="unknown") + untrained = IvfIndex(DIM, 4) + with pytest.raises( + RuntimeError, + match="^IvfIndex must be trained or loaded before reserve_cluster$", + ): + untrained.reserve_cluster(0, 1) + + +@pytest.mark.parametrize("name", ["quantization_bits", "graph_degree", "ef_build"]) +def test_removed_kmeans_parameters(name): + with pytest.raises( + AttributeError, + match=f"^QGKMeans\\(\\) got an unexpected keyword argument '{name}'$", + ): + QGKMeans(DIM, 80, **{name: 32}) + cp = QGKMeansParameters() + with pytest.raises(AttributeError): + getattr(cp, name) + with pytest.raises(AttributeError): + setattr(cp, name, 32) + + +def test_qgkmeans_parameters_use_the_index_names(base_data): + cp = QGKMeansParameters() + assert (cp.nbits, cp.max_degree, cp.ef_construction) == (32, 32, 240) + model = QGKMeans(DIM, 80, nbits=4, max_degree=64, ef_construction=100) + assert (model.cp.nbits, model.cp.max_degree, model.cp.ef_construction) == ( + 4, + 64, + 100, + ) + for name in ("nbits", "max_degree", "ef_construction"): + with pytest.raises(AttributeError, match="unexpected keyword argument"): + RaBitQKMeans(DIM, 4, **{name: 32}) + # 0 was raw storage in 0.8; it is not read as 32. + with pytest.raises(ValueError, match="^QGKMeans nbits must be 4, 8, or 32$"): + QGKMeans(DIM, 80, niter=1, nbits=0).train(base_data) + with pytest.raises( + ValueError, match="^QGKMeans ef_construction and ef_search must be positive$" + ): + QGKMeans(DIM, 80, niter=1, ef_construction=0).train(base_data) + + +@pytest.mark.parametrize("cls", [QGKMeans, RaBitQKMeans]) +def test_final_assignment_is_a_string(cls, base_data): + assert cls(DIM, 80).cp.final_assignment == "approximate" + for mode in ("exact", "approximate"): + model = cls(DIM, 80, niter=2, num_threads=1, seed=1, final_assignment=mode) + assert model.cp.final_assignment == mode + model.train(base_data) + cp = cls(DIM, 80).cp + for invalid in ("Exact", "EXACT", "", "symphonyqg"): + with pytest.raises( + ValueError, match="^final_assignment must be 'approximate' or 'exact'$" + ): + cls(DIM, 80, final_assignment=invalid) + with pytest.raises( + ValueError, match="^final_assignment must be 'approximate' or 'exact'$" + ): + cp.final_assignment = invalid + # The 0.8 enum members were integers underneath. + with pytest.raises( + TypeError, match="could not convert parameter 'final_assignment' from int" + ): + cls(DIM, 80, final_assignment=1) + with pytest.raises(TypeError): + cp.final_assignment = 1 + assert cp.final_assignment == "approximate" + + +def test_index_training_parameters_take_the_string(base_data): + for index in (IvfIndex(DIM, 8, seed=3), HnswIndex(DIM, num_clusters=8, seed=3)): + assert isinstance(index.cp, RaBitQKMeansParameters) + index.cp.final_assignment = "exact" + assert index.cp.final_assignment == "exact" + with pytest.raises(ValueError, match="^final_assignment must be"): + index.cp.final_assignment = "Exact" + with pytest.raises(TypeError): + index.cp.final_assignment = 1 + assert index.cp.final_assignment == "exact" # unchanged by the failures + index.train(base_data, num_threads=1) + assert index.is_trained + + +@pytest.mark.parametrize( + "name", + ["FinalAssignmentMode", "QGKMeansIterationStats", "RaBitQKMeansIterationStats"], +) +def test_names_that_left_the_package(name): + assert name not in rabitqlib.__all__ + assert not hasattr(rabitqlib, name) + with pytest.raises(ImportError): + exec(f"from rabitqlib import {name}") + + +def test_kmeans_iteration_stats_is_one_class(base_data): + stats = rabitqlib.KMeansIterationStats + assert stats.__name__ == stats.__qualname__ == "KMeansIterationStats" + for cls in (QGKMeans, RaBitQKMeans): + model = cls(DIM, 80, niter=2, num_threads=1, seed=1) + model.train(base_data) + assert len(model.iteration_stats) == 2 + assert all(type(item) is stats for item in model.iteration_stats) + # Pickle and pydoc find the class by this name in its module. + assert stats.__module__ == "rabitqlib._rabitqlib" + assert pickle.loads(pickle.dumps(stats)) is stats + + +def test_innerproduct_is_no_longer_a_metric_name(): + # The inner-product metric is spelled "ip" only, as index.metric reports it. + index_message = r"^metric must be 'l2', 'ip' or 'cosine'$" + for make in ( + lambda: IvfIndex(DIM, 8, metric="innerproduct"), + lambda: HnswIndex(DIM, metric="innerproduct"), + lambda: SymqgIndex(DIM, metric="innerproduct"), + ): + with pytest.raises(ValueError, match=index_message): + make() + query = np.zeros(DIM, dtype=np.float32) + codes = np.zeros((0, DIM), dtype=np.uint8) + for call in ( + lambda: quant.Query(query, metric="innerproduct"), + lambda: quant.query_terms(query, metric="innerproduct"), + lambda: quant.code_factors( + codes.astype(np.float32), codes, nbits=4, metric="innerproduct" + ), + ): + with pytest.raises(ValueError, match=r"^metric must be 'l2' or 'ip'$"): + call() + assert IvfIndex(DIM, 8, metric="ip").metric == "ip" diff --git a/tests/python/test_symqg.py b/tests/python/test_symqg.py index 3fbc22cf..a8d2524b 100644 --- a/tests/python/test_symqg.py +++ b/tests/python/test_symqg.py @@ -1,10 +1,9 @@ """Tests for SymqgIndex: construction, search, properties, error handling, save/load.""" -import inspect import os import re -import struct +import format2_file import numpy as np import pytest from conftest import DIM, N_QUERIES, N_VECTORS, brute_force_knn, recall_at_k @@ -45,9 +44,9 @@ def test_properties(built_symqg): @pytest.mark.parametrize("nq,k", [(N_QUERIES, _TOPK), (1, 1)]) def test_search_output_contract(built_symqg, query_data, nq, k): - ids, dists = built_symqg.search(query_data[:nq], k=k, ef=_EF) + ids, dists = built_symqg.search(query_data[:nq], k=k, ef_search=_EF) assert ids.shape == dists.shape == (nq, k) - assert ids.dtype == np.uint32 + assert ids.dtype == np.int64 assert dists.dtype == np.float32 assert np.all(ids < N_VECTORS) assert np.isfinite(dists).all() @@ -82,31 +81,33 @@ def test_batch_search_matches_individual_queries(tmp_path, bits, metric): (1, 64, 8), ]: individual = [ - index.search(query.copy()[None, :], k=k, ef=ef) for query in queries + index.search(query.copy()[None, :], k=k, ef_search=ef) for query in queries ] expected_ids = np.concatenate([result[0] for result in individual]) expected_distances = np.concatenate([result[1] for result in individual]) - ids, distances = restored.search(queries, k=k, ef=ef, num_threads=threads) + ids, distances = restored.search( + queries, k=k, ef_search=ef, num_threads=threads + ) np.testing.assert_array_equal(ids, expected_ids) np.testing.assert_array_equal( distances.view(np.uint32), expected_distances.view(np.uint32) ) empty_ids, empty_distances = restored.search( - queries[:0], k=k, ef=ef, num_threads=threads + queries[:0], k=k, ef_search=ef, num_threads=threads ) assert empty_ids.shape == empty_distances.shape == (0, k) def test_search_validates_inputs(built_symqg, query_data): with pytest.raises(ValueError, match="queries must be a 2D NumPy array"): - built_symqg.search(query_data[0], k=1, ef=_EF) + built_symqg.search(query_data[0], k=1, ef_search=_EF) with pytest.raises(ValueError, match="query dimension does not match index dim"): - built_symqg.search(query_data[:, :-1], k=1, ef=_EF) + built_symqg.search(query_data[:, :-1], k=1, ef_search=_EF) with pytest.raises(ValueError, match=r"k must be between 1 and 2\*\*31"): - built_symqg.search(query_data, k=0, ef=_EF) + built_symqg.search(query_data, k=0, ef_search=_EF) unbuilt = SymqgIndex(DIM, max_degree=_MAX_DEGREE) with pytest.raises(RuntimeError, match="add them or load an index before search"): - unbuilt.search(query_data, k=1, ef=_EF) + unbuilt.search(query_data, k=1, ef_search=_EF) # ── search correctness ──────────────────────────────────────────────────────── @@ -115,15 +116,15 @@ def test_search_validates_inputs(built_symqg, query_data): def test_self_retrieval(built_symqg, base_data): """Each database vector must be its own nearest neighbor at high ef.""" probes = base_data[:10] - ids, _ = built_symqg.search(probes, k=1, ef=200) + ids, _ = built_symqg.search(probes, k=1, ef_search=200) for i in range(10): assert i in ids[i], f"Vector {i} not found in its own top-1 result" def test_recall_vs_brute_force(built_symqg, base_data, query_data): - """Approximate recall should exceed 0.5 at ef=50 on a small dataset.""" + """Approximate recall should exceed 0.5 at ef_search=50 on a small dataset.""" k = 5 - approx_ids, _ = built_symqg.search(query_data, k=k, ef=_EF) + approx_ids, _ = built_symqg.search(query_data, k=k, ef_search=_EF) exact_ids, _ = brute_force_knn(base_data, query_data, k) r = recall_at_k(approx_ids, exact_ids, k) assert r >= 0.5, f"Recall {r:.3f} too low" @@ -156,7 +157,7 @@ def test_wrong_query_dim_raises(built_symqg): ) + "$", ): - built_symqg.search(bad_queries, k=1, ef=_EF) + built_symqg.search(bad_queries, k=1, ef_search=_EF) def test_save_before_build_raises(tmp_path): @@ -175,21 +176,24 @@ def test_search_before_build_raises(): RuntimeError, match="^SymqgIndex has no vectors; add them or load an index before search$", ): - idx.search(queries, k=1, ef=_EF) + idx.search(queries, k=1, ef_search=_EF) def test_search_raises_ef_to_k_and_defaults_it(built_symqg, query_data): - # As in HnswIndex: no or zero ef selects max(k, 64), and ef is at least k. - at_k = built_symqg.search(query_data, k=10, ef=10) + # As in HnswIndex: no ef_search selects max(k, 64), and it is at least k. + at_k = built_symqg.search(query_data, k=10, ef_search=10) for ef in (9, 1): - raised = built_symqg.search(query_data, k=10, ef=ef) + raised = built_symqg.search(query_data, k=10, ef_search=ef) np.testing.assert_array_equal(raised[0], at_k[0]) - default = built_symqg.search(query_data, k=3, ef=64) - for ef in (None, 0): - np.testing.assert_array_equal( - built_symqg.search(query_data, 3, ef)[0], default[0] - ) + default = built_symqg.search(query_data, k=3, ef_search=64) + np.testing.assert_array_equal( + built_symqg.search(query_data, 3, None)[0], default[0] + ) np.testing.assert_array_equal(built_symqg.search(query_data, 3)[0], default[0]) + with pytest.raises( + ValueError, match="^ef_search must be at least 1; pass None for the default$" + ): + built_symqg.search(query_data, 3, 0) def test_invalid_degree_raises(): @@ -212,7 +216,7 @@ def test_qg_quant_build_search_and_roundtrip(bits, base_data, query_data, tmp_pa idx.add(base_data, num_threads=1) assert idx.nbits == bits - ids, dists = idx.search(query_data, k=5, ef=_EF) + ids, dists = idx.search(query_data, k=5, ef_search=_EF) assert np.all(ids < N_VECTORS) assert np.all(np.isfinite(dists)) @@ -220,7 +224,7 @@ def test_qg_quant_build_search_and_roundtrip(bits, base_data, query_data, tmp_pa idx.save(path) loaded = SymqgIndex.load(path) assert loaded.nbits == bits - loaded_ids, loaded_dists = loaded.search(query_data, k=5, ef=_EF) + loaded_ids, loaded_dists = loaded.search(query_data, k=5, ef_search=_EF) np.testing.assert_array_equal(loaded_ids, ids) np.testing.assert_allclose(loaded_dists, dists, rtol=1e-5) @@ -238,15 +242,15 @@ def test_save_load_roundtrip(built_symqg, query_data, tmp_path): assert loaded.max_degree == built_symqg.max_degree assert loaded.num_points == built_symqg.num_points - ids_orig, dists_orig = built_symqg.search(query_data, k=_TOPK, ef=_EF) - ids_load, dists_load = loaded.search(query_data, k=_TOPK, ef=_EF) + ids_orig, dists_orig = built_symqg.search(query_data, k=_TOPK, ef_search=_EF) + ids_load, dists_load = loaded.search(query_data, k=_TOPK, ef_search=_EF) np.testing.assert_array_equal(ids_orig, ids_load) np.testing.assert_allclose(dists_orig, dists_load, rtol=1e-5) @pytest.mark.parametrize("bits", [4, 8]) @pytest.mark.parametrize("metric", ["l2", "ip"]) -def test_code_only_build_preserves_v1_format(bits, metric, tmp_path): +def test_code_only_build_saves_the_specified_layout(bits, metric, tmp_path): rng = np.random.default_rng(851) data = rng.normal(size=(65, 65)).astype(np.float32) queries = rng.normal(size=(3, 65)).astype(np.float32) @@ -256,12 +260,19 @@ def test_code_only_build_preserves_v1_format(bits, metric, tmp_path): path = tmp_path / "code_only.index" index.save(str(path)) payload = path.read_bytes() - assert struct.unpack_from(" None") -@pytest.mark.parametrize( - "make,message", - [ - ( - lambda: IvfIndex(DIM, 4, nbits=4, max_degree=8), - r"^IvfIndex\(\) got an unexpected keyword argument 'max_degree'$", - ), - ], -) -def test_constructor_argument_errors(make, message): - with pytest.raises(TypeError, match=message): - make() +def test_unknown_constructor_keyword_raises_type_error(): + with pytest.raises(TypeError, match="incompatible constructor arguments"): + IvfIndex(DIM, 4, nbits=4, max_degree=8) -def test_positional_nbits_is_read_as_the_old_form_and_explained(): +def test_hnsw_seed_is_drawn_like_the_other_indexes(): + drawn = [HnswIndex(DIM).seed for _ in range(4)] + assert all(isinstance(seed, int) and 0 <= seed < 2**32 for seed in drawn) + assert len(set(drawn)) > 1 + for accepted in (0, 2**32 - 1, np.uint32(7)): + index = HnswIndex(DIM, seed=accepted) + assert index.seed == index.cp.seed == accepted with pytest.raises( - TypeError, match=r"missing a required argument: 'nbits' \(read as the 0\.7 form" + ValueError, match=r"^seed must be an integer in \[0, 4294967295\]$" ): - IvfIndex(DIM, 4, 4) + HnswIndex(DIM, seed=2**32) @pytest.mark.parametrize("cls", [IvfIndex, HnswIndex]) @@ -207,7 +184,8 @@ def test_retraining_is_allowed_only_while_empty(kind, base_data, tmp_path): index.save(tmp_path / "trained.index") loaded = type(index).load(tmp_path / "trained.index") assert loaded.is_trained - assert loaded.seed is None + assert loaded.seed == index.seed # format-2 files record it + assert loaded.cp.seed == index.seed & 0xFFFFFFFF # as for a new index with pytest.raises(RuntimeError, match=message): loaded.set_centroids(base_data[:4]) @@ -285,18 +263,34 @@ def test_search_pads_k_beyond_the_stored_points(kind, base_data): index = new_index(kind) index.train(base_data) ids, distances = search(index, base_data[:1], 3) - np.testing.assert_array_equal(ids, np.full((1, 3), 2**32 - 1)) + np.testing.assert_array_equal(ids, np.full((1, 3), -1)) assert np.isinf(distances).all() index.add(base_data[:10]) index.add(base_data[10:11]) ids, distances = search(index, base_data[:1], 13) assert np.isfinite(distances).sum() == 11 np.testing.assert_array_equal(np.sort(ids[np.isfinite(distances)]), np.arange(11)) - np.testing.assert_array_equal(ids[~np.isfinite(distances)], [2**32 - 1] * 2) + np.testing.assert_array_equal(ids[~np.isfinite(distances)], [-1] * 2) with pytest.raises(ValueError, match=r"^k must be between 1 and 2\*\*31$"): search(index, base_data[:1], 0) +@pytest.mark.parametrize("kind", KINDS) +def test_int64_ids_round_trip_from_add_and_search_to_remove(kind, base_data): + index = new_index(kind) + added = index.add(base_data[:10]) + assert added.dtype == np.int64 + ids, _ = search(index, base_data[:1], 12) + assert ids.dtype == np.int64 + assert (ids == -1).sum() == 2 + # The missing marker is not a point, so passing it to remove changes nothing. + with pytest.raises(ValueError, match=r"^ids must be in \[0, num_stored_points\)$"): + index.remove(ids[0]) + assert len(index) == 10 + assert index.remove(ids[0][ids[0] >= 0][:3]) == 3 + assert len(index) == 7 + + @pytest.mark.parametrize("kind", KINDS) def test_len_counts_live_points(kind, base_data): index = new_index(kind) @@ -319,19 +313,6 @@ def test_same_seed_reproduces_an_ivf_index(base_data, tmp_path): ) -def test_ivf_point_count_index_cannot_be_trained(base_data): - with pytest.warns(DeprecationWarning): - index = IvfIndex(DIM, N_VECTORS, 4, 4) - message = r"^IvfIndex created with max_elements is filled by build; create IvfIndex\(dim, num_clusters, nbits=\.\.\.\) to train or set centroids$" - with pytest.raises(RuntimeError, match=message): - index.train(base_data) - with pytest.raises(RuntimeError, match=message): - index.set_centroids(base_data[:4]) - assert index.num_stored_points == 0 - with pytest.warns(DeprecationWarning): - assert index.max_elements == N_VECTORS # the declared row count is kept - - def test_hnsw_capacity_grows_and_reserve_preallocates(base_data): index = HnswIndex(DIM, nbits=4, num_clusters=4) assert index.capacity == 1 @@ -377,23 +358,6 @@ def test_hnsw_num_clusters_is_validated(): HnswIndex(DIM, nbits=4, num_clusters=0) -def test_hnsw_first_add_matches_deprecated_build(base_data, clusters, tmp_path): - # The first add into an empty index links like the 0.7 build, so the two - # paths give the same bytes when single-threaded. - centroids, cluster_ids = clusters - added = HnswIndex( - DIM, nbits=4, num_clusters=len(centroids), M=8, ef_construction=50 - ) - added.set_centroids(centroids) - added.add(base_data, cluster_ids=cluster_ids, num_threads=1) - with pytest.warns(DeprecationWarning): - built = HnswIndex(DIM, N_VECTORS, M=8, ef_construction=50, nbits=4) - built.build(base_data, centroids, cluster_ids) - assert saved_bytes(added, tmp_path / "a.index") == saved_bytes( - built, tmp_path / "b.index" - ) - - @pytest.mark.parametrize("kind", KINDS) def test_add_without_cluster_ids_routes_to_trained_centroids(kind, base_data): index = new_index(kind) @@ -497,9 +461,11 @@ def make(): return index implicit = make() - implicit.add(base_data, num_threads=1) + implicit.add(base_data, num_threads=1) # trains with the add's single thread explicit = make() - explicit.train(base_data) + # The saved file includes HNSW routing, whose graph is reproducible only when + # it is built with one thread. + explicit.train(base_data, num_threads=1) explicit.add(base_data, num_threads=1) assert saved_bytes(implicit, tmp_path / "implicit.index") == saved_bytes( explicit, tmp_path / "explicit.index" @@ -519,12 +485,25 @@ def test_ivf_first_add_uses_the_drawn_seed(base_data, tmp_path): ) -def test_hnsw_first_add_keeps_a_preallocated_capacity(base_data, tmp_path): +def test_hnsw_first_add_uses_the_drawn_seed(base_data, tmp_path): implicit = HnswIndex(DIM, num_clusters=4, M=8, ef_construction=50) + seed = implicit.seed + implicit.add(base_data, num_threads=1) + assert implicit.seed == implicit.cp.seed == seed + explicit = HnswIndex(DIM, num_clusters=4, M=8, ef_construction=50, seed=seed) + explicit.train(base_data) + explicit.add(base_data, num_threads=1) + assert saved_bytes(implicit, tmp_path / "implicit.index") == saved_bytes( + explicit, tmp_path / "explicit.index" + ) + + +def test_hnsw_first_add_keeps_a_preallocated_capacity(base_data, tmp_path): + implicit = HnswIndex(DIM, num_clusters=4, M=8, ef_construction=50, seed=7) implicit.reserve(2 * N_VECTORS) implicit.add(base_data, num_threads=1) assert implicit.capacity == 2 * N_VECTORS - explicit = HnswIndex(DIM, num_clusters=4, M=8, ef_construction=50) + explicit = HnswIndex(DIM, num_clusters=4, M=8, ef_construction=50, seed=7) explicit.reserve(2 * N_VECTORS) explicit.train(base_data) explicit.add(base_data, num_threads=1) @@ -542,3 +521,33 @@ def test_empty_first_add_requires_training(kind, base_data): ): index.add(base_data[:0]) assert not index.is_trained + + +@pytest.mark.parametrize("kind", KINDS + ["qg"]) +def test_unknown_read_only_features_allow_search_only(kind, base_data, tmp_path): + if kind == "qg": + index = SymqgIndex(DIM, ef_construction=40, seed=2) + index.add(base_data) + else: + index = new_index(kind) + index.add(base_data, num_threads=1) + path = tmp_path / "read_only.index" + index.save(path) + payload = bytearray(path.read_bytes()) + payload[24:32] = (1).to_bytes(8, "little") # an unknown ro_compat feature bit + format2_file.reseal(payload) + path.write_bytes(payload) + + loaded = type(index).load(path) + np.testing.assert_array_equal( + search(loaded, base_data[:5], 3)[0], search(index, base_data[:5], 3)[0] + ) + message = "cannot update, so it cannot save$" + with pytest.raises(RuntimeError, match=message): + loaded.save(tmp_path / "copy.index") + if kind != "qg": + # HNSW-RaBitQ grows its capacity before adding, which is refused first. + with pytest.raises( + RuntimeError, match="cannot update, so it cannot (add|resize)$" + ): + loaded.add(base_data[:1]) diff --git a/tests/python/test_txtai_compat.py b/tests/python/test_txtai_compat.py index 91257889..256a9bba 100644 --- a/tests/python/test_txtai_compat.py +++ b/tests/python/test_txtai_compat.py @@ -1,9 +1,12 @@ -"""txtai's rabitqlib backend, call for call, must keep working in 0.8. - -Mirrors txtai.ann.dense.rabitq.RabitQ at neuml/txtai 4d5e05f (index, append, -delete, search, count, save, load). txtai trains centroids with scikit-learn; -any centroids exercise the same calls, so these come from the data. The only -warnings allowed are the compatibility layer's DeprecationWarnings. +"""The calls txtai's rabitq backend makes (issue #213). + +Follows txtai.ann.dense.rabitq.RabitQ (index, append, delete, search, count, +save, load) as merged in neuml/txtai#1616 (commit 86f3bad): set_centroids() and +add(cluster_ids=...) instead of build(), no max_elements or random_seed, an +infinite distance to find missing results, and None instead of 0 for an unset +ef. The same calls run without warnings on 0.8.5. txtai trains centroids with +scikit-learn; any centroids exercise the same calls, so these come from the +data. No call may warn. """ import math @@ -13,8 +16,6 @@ import pytest from rabitqlib import HnswIndex, IvfIndex -SENTINEL = 0xFFFFFFFF - @pytest.fixture def embeddings(): @@ -31,20 +32,19 @@ def index_like_txtai(mode, vectors): ) dim = vectors.shape[1] if mode == "ivf": - backend = IvfIndex( - dim=dim, max_elements=rows, num_clusters=clusters, nbits=1, metric="ip" - ) + backend = IvfIndex(dim, clusters, nbits=1, metric="ip") else: backend = HnswIndex( - dim=dim, - max_elements=rows, + dim, + nbits=1, + num_clusters=clusters, M=16, ef_construction=200, - nbits=1, metric="ip", - random_seed=100, + seed=100, ) - backend.build(vectors, centroids, clusterids) + backend.set_centroids(centroids) + backend.add(vectors, cluster_ids=clusterids) return backend @@ -68,12 +68,12 @@ def search_like_txtai(backend, mode, queries, limit): nprobe = max(1, round(backend.num_clusters / 16)) ids, distances = backend.search(queries, k, nprobe) else: - ids, distances = backend.search(queries, k, None or 0) + ids, distances = backend.search(queries, k, None) return [ [ (int(uid), float(1.0 - dist)) for uid, dist in zip(uids, dists) - if uid != SENTINEL + if math.isfinite(dist) ] for uids, dists in zip(ids.tolist(), distances.tolist()) ] @@ -88,6 +88,16 @@ def test_txtai_calls(mode, embeddings, tmp_path): assert [hits[0][0] for hits in results] == list(range(5)) if mode == "ivf": + # The default nprobe probes few clusters, so long result lists have + # unfilled slots, which the filter must drop. + results = search_like_txtai(backend, mode, embeddings[:5], 300) + assert any(len(hits) < 300 for hits in results) + assert all( + uid >= 0 and math.isfinite(score) + for hits in results + for uid, score in hits + ) + # append and delete exist for ivf only. assert append_like_txtai(backend, embeddings[300:]) == 400 delete_like_txtai(backend, [0, 1, 399, 1000]) @@ -101,5 +111,4 @@ def test_txtai_calls(mode, embeddings, tmp_path): assert search_like_txtai(loaded, mode, embeddings[:5], 3) == ( search_like_txtai(backend, mode, embeddings[:5], 3) ) - categories = {w.category for w in caught} - assert categories == {DeprecationWarning}, [str(w.message) for w in caught] + assert not caught, [str(w.message) for w in caught] diff --git a/tests/python/typing/public_api.py b/tests/python/typing/public_api.py index 6cab83a4..80a29039 100644 --- a/tests/python/typing/public_api.py +++ b/tests/python/typing/public_api.py @@ -8,15 +8,12 @@ import numpy.typing as npt import rabitqlib from rabitqlib import ( - FinalAssignmentMode, HnswIndex, IvfIndex, KMeansIterationStats, QGKMeans, - QGKMeansIterationStats, QGKMeansParameters, RaBitQKMeans, - RaBitQKMeansIterationStats, RaBitQKMeansParameters, SymqgIndex, quant, @@ -37,16 +34,16 @@ def check(x: npt.NDArray[np.float32], labels: npt.NDArray[np.uint32]) -> None: index.set_centroids(x[:2]) assert_type(index.is_trained, bool) assert_type(index.seed, int | None) - assert_type(index.add(x, cluster_ids=labels), npt.NDArray[np.uint32]) + assert_type(index.add(x, cluster_ids=labels), npt.NDArray[np.int64]) assert_type(index.remove([0, 1]), int) assert_type(index.dim, int) assert_type(len(index), int) index.save("index.bin") ids, distances = ivf.search(x, k=5, nprobe=2) - assert_type(ids, npt.NDArray[np.uint32]) + assert_type(ids, npt.NDArray[np.int64]) assert_type(distances, npt.NDArray[np.float32]) assert_type( - hnsw.search(x, 5), tuple[npt.NDArray[np.uint32], npt.NDArray[np.float32]] + hnsw.search(x, 5), tuple[npt.NDArray[np.int64], npt.NDArray[np.float32]] ) graph.train(x) graph.add(x, num_threads=1) @@ -55,15 +52,22 @@ def check(x: npt.NDArray[np.float32], labels: npt.NDArray[np.uint32]) -> None: assert_type(len(graph), int) assert_type( graph.search(x, 5), - tuple[npt.NDArray[np.uint32], npt.NDArray[np.float32]], + tuple[npt.NDArray[np.int64], npt.NDArray[np.float32]], ) assert_type(IvfIndex.load("index.bin"), IvfIndex) assert_type(HnswIndex.load("index.bin"), HnswIndex) assert_type(SymqgIndex.load("index.bin"), SymqgIndex) ivf.reserve_cluster(0, 128) hnsw.reserve(256) - qg = QGKMeans(64, 40, niter=2, nbits=4) + assert_type(hnsw.capacity, int) + assert_type(ivf.num_stored_points, int) + ivf.search(x, 5, 1, high_accuracy=None, num_threads=1) + hnsw.search(x, 5, 32, num_threads=1) + graph.search(x, 5, ef_search=32, num_threads=1) + qg = QGKMeans(64, 40, niter=2, nbits=4, max_degree=32, ef_construction=100) flat = RaBitQKMeans(64, 2, final_assignment="exact") + assert_type(qg.cp.nbits, int) + assert_type(flat.cp.final_assignment, Literal["approximate", "exact"]) assert_type(qg.cp, QGKMeansParameters) assert_type(flat.cp, RaBitQKMeansParameters) for model in (qg, flat): @@ -80,33 +84,64 @@ def check(x: npt.NDArray[np.float32], labels: npt.NDArray[np.uint32]) -> None: if model.iteration_stats is not None: assert_type(model.iteration_stats[0], KMeansIterationStats) qg.cp.final_assignment = "approximate" - ivf.search(x, "five", 2) # type: ignore[call-overload] + ivf.search(x, "five", 2) # type: ignore[arg-type] ivf.dim = 16 # type: ignore[misc] qg.cp.niter = "two" # type: ignore[assignment] RaBitQKMeans(64, 2, graph_degree=32) # type: ignore[call-arg] - hnsw.search(x, 5, nprobe=2) # type: ignore[call-overload] - IvfIndex(64, 2, 4) # type: ignore[call-overload] + hnsw.search(x, 5, nprobe=2) # type: ignore[call-arg] + IvfIndex(64, 2, 4) # type: ignore[call-arg] hnsw.train(x, 1) # type: ignore[call-arg] qg.cp.final_assignment = "Exact" # type: ignore[assignment] - QGKMeans(64, 40, ef_build=1, bogus=1) # type: ignore[call-overload] + QGKMeans(64, 40, ef_build=1, bogus=1) # type: ignore[call-arg] -def deprecated_forms_still_type_check(qg: QGKMeans, flat: RaBitQKMeans) -> None: - # Accepted until 0.9; the stubs mark them deprecated without rejecting them. - RaBitQKMeans(64, 2, final_assignment=FinalAssignmentMode.Exact) - QGKMeans(64, 40, final_assignment=FinalAssignmentMode.Approximate) - qg.cp.final_assignment = FinalAssignmentMode.Exact - assert_type(flat.cp.final_assignment, FinalAssignmentMode) - QGKMeans(64, 40, quantization_bits=4, niter=2) - QGKMeans(64, 40, graph_degree=32, ef_build=100) - - -def stats_alias(stats: RaBitQKMeansIterationStats) -> QGKMeansIterationStats: - return stats - - -def stats_name(stats: QGKMeansIterationStats) -> KMeansIterationStats: - return stats +def reject_removed_forms( + ivf: IvfIndex, + hnsw: HnswIndex, + graph: SymqgIndex, + qg: QGKMeans, + x: npt.NDArray[np.float32], + labels: npt.NDArray[np.uint32], +) -> None: + # The 0.7 call forms and the 0.8 spellings that 0.9 removed. + IvfIndex(64, 80, 1, 4) # type: ignore[arg-type, call-arg] + IvfIndex(dim=64, max_elements=80, num_clusters=1, nbits=4) # type: ignore[call-arg] + IvfIndex(64, 1, initializer="flat") # type: ignore[call-arg] + IvfIndex(64, 1, metric="innerproduct") # type: ignore[arg-type] + HnswIndex(64, 80) # type: ignore[call-arg] + HnswIndex(64, max_elements=80) # type: ignore[call-arg] + HnswIndex(64, random_seed=5) # type: ignore[call-arg] + SymqgIndex(64, 32, "l2", 4) # type: ignore[arg-type, call-arg] + SymqgIndex(64, quantization_bits=0) # type: ignore[call-arg] + ivf.build(x, x[:1], labels) # type: ignore[attr-defined] + hnsw.build(x, x[:1], labels) # type: ignore[attr-defined] + graph.build(x, 40) # type: ignore[attr-defined] + ivf.add(x, labels) # type: ignore[call-arg] + hnsw.add(x, labels) # type: ignore[call-arg] + ivf.is_built # type: ignore[attr-defined] + graph.is_built # type: ignore[attr-defined] + ivf.max_elements # type: ignore[attr-defined] + hnsw.max_elements # type: ignore[attr-defined] + graph.max_elements # type: ignore[attr-defined] + ivf.initializer # type: ignore[attr-defined] + ivf.reserve(0, 8) # type: ignore[attr-defined] + hnsw.resize(128) # type: ignore[attr-defined] + graph.quantization_bits # type: ignore[attr-defined] + graph.search_batch(x, 5, 32) # type: ignore[attr-defined] + ivf.search(x, 5, 1, None) # type: ignore[call-arg] + hnsw.search(x, 5, ef=32) # type: ignore[call-arg] + hnsw.search(x, 5, 32, 1) # type: ignore[call-arg] + graph.search(x, 5, ef=32) # type: ignore[call-arg] + graph.search(x, 5, 32, 1) # type: ignore[call-arg] + QGKMeans(64, 40, quantization_bits=4) # type: ignore[call-arg] + QGKMeans(64, 40, graph_degree=32) # type: ignore[call-arg] + QGKMeans(64, 40, ef_build=100) # type: ignore[call-arg] + qg.cp.quantization_bits = 4 # type: ignore[attr-defined] + qg.cp.graph_degree = 32 # type: ignore[attr-defined] + qg.cp.ef_build = 100 # type: ignore[attr-defined] + rabitqlib.FinalAssignmentMode # type: ignore[attr-defined] + rabitqlib.QGKMeansIterationStats # type: ignore[attr-defined] + rabitqlib.RaBitQKMeansIterationStats # type: ignore[attr-defined] def check_parameter_reads( @@ -152,7 +187,7 @@ def check_numpy_scalars() -> None: ids, distances = ivf.search( x[:2], k=np.int64(3), nprobe=np.int64(1), high_accuracy=np.bool_(True) ) - assert_type(ids, npt.NDArray[np.uint32]) + assert_type(ids, npt.NDArray[np.int64]) assert_type(distances, npt.NDArray[np.float32]) hnsw.reserve(np.int64(100)) hnsw.search(x[:2], np.int64(3), ef_search=np.int64(10)) @@ -189,12 +224,9 @@ def check_numpy_scalars() -> None: qg.cp.ef_search = np.int64(16) qg.cp.graph_build_iterations = np.int64(1) qg.cp.nbits = np.int64(4) - members = FinalAssignmentMode.__members__ - assert_type(members, dict[str, FinalAssignmentMode]) - assert_type(members["Exact"], FinalAssignmentMode) - assert members["Exact"] == FinalAssignmentMode.Exact - assert members["SymphonyQG"] == members["Approximate"] - assert FinalAssignmentMode(np.int64(1)) == members["Exact"] + for mode in ("approximate", "exact"): + qg.cp.final_assignment = mode + assert qg.cp.final_assignment == mode def check_input_contracts() -> None: @@ -203,11 +235,7 @@ def check_input_contracts() -> None: centroids = x.mean(axis=0, keepdims=True) signed = np.zeros(80, dtype=np.int64) unsigned = np.zeros(80, dtype=np.uint32) - metrics: tuple[Literal["l2", "ip", "innerproduct"], ...] = ( - "l2", - "ip", - "innerproduct", - ) + metrics: tuple[Literal["l2", "ip", "cosine"], ...] = ("l2", "ip", "cosine") for metric in metrics: ivf = IvfIndex(64, 1, nbits=4, metric=metric) HnswIndex(64, nbits=4, metric=metric) @@ -244,6 +272,7 @@ def check_input_contracts() -> None: graph.add(x) # Returned option values must be usable as inputs without casts. IvfIndex(64, 1, nbits=4, metric=ivf.metric, routing=ivf.routing) + assert_type(ivf.metric, Literal["l2", "ip", "cosine"]) def reject_invalid_inputs(x: npt.NDArray[np.float32]) -> None: @@ -253,11 +282,11 @@ def reject_invalid_inputs(x: npt.NDArray[np.float32]) -> None: ivf = IvfIndex(64, 1, nbits=4) hnsw = HnswIndex(64, nbits=4) graph = SymqgIndex(64) - IvfIndex(64, 1, nbits=4, metric="cosine") # type: ignore[call-overload] - HnswIndex(64, nbits=4, metric="L2") # type: ignore[call-overload] - SymqgIndex(64, metric="inner_product") # type: ignore[call-overload] - IvfIndex(64, 1, nbits=4, routing="flat_rabit") # type: ignore[call-overload] - SymqgIndex(64, init="pippn") # type: ignore[call-overload] + IvfIndex(64, 1, nbits=4, metric="cos") # type: ignore[arg-type] + HnswIndex(64, nbits=4, metric="L2") # type: ignore[arg-type] + SymqgIndex(64, metric="inner_product") # type: ignore[arg-type] + IvfIndex(64, 1, nbits=4, routing="flat_rabit") # type: ignore[arg-type] + SymqgIndex(64, init="pippn") # type: ignore[arg-type] graph.add(x, 1) # type: ignore[call-arg] ivf.add(x, cluster_ids=[0.0] * 80) # type: ignore[list-item] hnsw.add(x, cluster_ids=float_ids) # type: ignore[arg-type] diff --git a/tests/test_mypy.py b/tests/test_mypy.py index 3ab2d3eb..224de9a0 100644 --- a/tests/test_mypy.py +++ b/tests/test_mypy.py @@ -56,129 +56,3 @@ def test_static_public_usage(tmp_path): ) } assert error_lines == expected_lines, result.stdout - - -# Each 0.7 call form the compatibility layer accepts, and each 0.8 spelling that 0.9 -# renames, is marked deprecated in the stubs, so editors flag it while it still -# type-checks. Deprecations that depend on a value (a breadth of 0, a seed above -# 2**32 - 1) cannot be declared and are documented in the docstrings only. The two -# old statistics class names are plain aliases, which PEP 702 cannot mark; only the -# runtime warns for them. -DEPRECATED_USAGE = """\ -import numpy as np -import rabitqlib -from rabitqlib import HnswIndex, IvfIndex, QGKMeans, SymqgIndex - -x = np.zeros((80, 64), dtype=np.float32) -labels = np.zeros(80, dtype=np.uint32) -ivf = IvfIndex(dim=64, max_elements=80, num_clusters=1, nbits=4, metric="ip") -hnsw = HnswIndex(dim=64, max_elements=80, M=16, ef_construction=200, nbits=4) -seeded = HnswIndex(64, nbits=4, random_seed=5) -ivf.build(x, x[:1], labels) -hnsw.build(x, x[:1], labels) -ivf.add(x, labels) -flag = ivf.is_built -graph = SymqgIndex(64, 32, "l2", 4) -alias = SymqgIndex(64, quantization_bits=0) -graph.build(x, 40) -graph.search_batch(x, 5, 32) -bits = graph.quantization_bits -built = graph.is_built -routed = IvfIndex(64, 1, initializer="flat") -strategy = routed.initializer -stored = routed.max_elements -routed.reserve(0, 8) -routed.search(x, 5, 1, None) -capacity = seeded.max_elements -seeded.resize(128) -seeded.search(x, 5, ef=32) -seeded.search(x, 5, 32, 1) -count = graph.max_elements -graph.search(x, 5, ef=32) -graph.search(x, 5, 32, 1) -kmeans = QGKMeans(64, 40, quantization_bits=4) -kmeans = QGKMeans(64, 40, graph_degree=32) -kmeans = QGKMeans(64, 40, ef_build=100) -kmeans.cp.quantization_bits = 4 -kmeans.cp.graph_degree = 32 -kmeans.cp.ef_build = 100 -mode = rabitqlib.FinalAssignmentMode.Exact -storage = kmeans.cp.quantization_bits -degree = kmeans.cp.graph_degree -breadth = kmeans.cp.ef_build -""" - -# The forms 0.9 keeps: none may be flagged as deprecated. -CURRENT_USAGE = """\ -import numpy as np -from rabitqlib import HnswIndex, IvfIndex, QGKMeans, RaBitQKMeans, SymqgIndex - -x = np.zeros((80, 64), dtype=np.float32) -ivf = IvfIndex(64, 1, nbits=4, routing="flat") -strategy = ivf.routing -stored = ivf.num_stored_points -ivf.reserve_cluster(0, 8) -ivf.search(x, 5, 1, high_accuracy=None, num_threads=1) -hnsw = HnswIndex(64, nbits=4, seed=5) -capacity = hnsw.capacity -hnsw.reserve(128) -hnsw.search(x, 5, 32, num_threads=1) -hnsw.search(x, 5, ef_search=32) -graph = SymqgIndex(64) -graph.search(x, 5, ef_search=32, num_threads=1) -kmeans = QGKMeans( - 64, 40, nbits=4, max_degree=32, ef_construction=100, final_assignment="exact" -) -kmeans.cp.nbits = 8 -kmeans.cp.max_degree = 32 -kmeans.cp.ef_construction = 100 -kmeans.cp.final_assignment = "approximate" -width = kmeans.cp.nbits -flat = RaBitQKMeans(64, 2, final_assignment="exact") -""" - - -def deprecated_lines(tmp_path, source): - """Line numbers mypy flags as deprecated in source, and its whole output.""" - usage = tmp_path / "usage.py" - usage.write_text(source) - result = subprocess.run( - [ - sys.executable, - "-m", - "mypy", - "--strict", - "--enable-error-code", - "deprecated", - "--no-incremental", - "--cache-dir", - str(tmp_path / "cache"), - str(usage), - ], - text=True, - capture_output=True, - check=False, - ) - flagged = { - int(number) - for number in re.findall( - rf"{re.escape(str(usage))}:(\d+): error: .*\[deprecated\]", result.stdout - ) - } - return flagged, result.stdout - - -def test_deprecated_forms_are_flagged(tmp_path): - flagged, output = deprecated_lines(tmp_path, DEPRECATED_USAGE) - old_forms = set(range(7, 42)) - # mypy 2.4 reports assignments to a deprecated settable property, not reads of - # it: the last three lines, which read QGKMeansParameters attributes, may go - # unreported. Each of those attributes is also assigned above. - settable_reads = {39, 40, 41} - assert old_forms - settable_reads <= flagged <= old_forms, output - - -def test_current_forms_are_not_flagged(tmp_path): - flagged, output = deprecated_lines(tmp_path, CURRENT_USAGE) - assert not flagged, output - assert "Success: no issues found" in output, output diff --git a/tests/unit/rabitqlib/clustering/kmeans_sampling_test.cpp b/tests/unit/rabitqlib/clustering/kmeans_sampling_test.cpp index 93b73fb5..62dcc2c3 100644 --- a/tests/unit/rabitqlib/clustering/kmeans_sampling_test.cpp +++ b/tests/unit/rabitqlib/clustering/kmeans_sampling_test.cpp @@ -17,6 +17,7 @@ #include "rabitqlib/clustering/qgkmeans.hpp" #include "rabitqlib/clustering/rabitqkmeans.hpp" #include "rabitqlib/index/types.hpp" +#include "rabitqlib/utils/input_checks.hpp" namespace rabitqlib { namespace { @@ -57,7 +58,7 @@ qgkmeans::QGKMeansParameters test_parameters(const qgkmeans::QGKMeans*) { parameters.niter = 4; parameters.num_threads = 1; parameters.min_points_per_centroid = 1; - parameters.ef_build = 64; + parameters.ef_construction = 64; parameters.ef_search = 16; return parameters; } @@ -234,6 +235,43 @@ void check_assign_requires_training_and_valid_input(const std::string& name) { ); } +// Training and assignment accept exactly the coordinates the indexes accept. +// At kDim the float32 bound rounds above the exact real bound, so a value equal +// to it is the one an exact double comparison would wrongly reject. +template +void check_coordinate_bound_matches_index_check(const std::string& name) { + constexpr size_t kClusterCount = kClusters; + const float bound = max_coordinate_magnitude(kDim); + ASSERT_GT( + static_cast(bound), + std::sqrt( + std::sqrt(static_cast(std::numeric_limits::max())) / + (64.0 * static_cast(kDim)) + ) + ); + const size_t num_points = 2 * kClusterCount; + auto points = clustered_points(num_points, 67); + points[1] = bound; + points[kDim + 2] = -bound; + Clustering clustering(kDim, kClusterCount, test_parameters()); + ASSERT_NO_THROW(clustering.train(num_points, points.data())); + PID assignment = kPidMax; + float distance = 0; + EXPECT_NO_THROW(clustering.assign(1, points.data(), &assignment, &distance)); + EXPECT_LT(assignment, kClusterCount); + + const std::string message = name + " x exceeds the safe float32 coordinate range"; + points[1] = std::nextafter(bound, std::numeric_limits::infinity()); + try { + clustering.assign(1, points.data(), &assignment, &distance); + FAIL() << "Assigned a coordinate above the bound"; + } catch (const std::invalid_argument& error) { EXPECT_EQ(error.what(), message); } + try { + clustering.train(num_points, points.data()); + FAIL() << "Trained on a coordinate above the bound"; + } catch (const std::invalid_argument& error) { EXPECT_EQ(error.what(), message); } +} + // With sampling, train's final pass is assign() itself, including QGKMeans' // cached graph. Without it, Exact assignment and RaBitQKMeans' scan around the // stored training center also reproduce train(); graph training uses hints. @@ -244,7 +282,7 @@ void check_assign_matches_final_training_assignment() { constexpr size_t kMaxPoints = 2; for (const uint32_t threads : {1U, 4U}) { for (const uint32_t bits : - kGraph ? std::vector{0, 4, 8} : std::vector{0}) { + kGraph ? std::vector{32, 4, 8} : std::vector{32}) { for (const size_t num_points : {kClusterCount * kMaxPoints, 3 * kClusterCount * kMaxPoints + 1}) { const auto points = clustered_points(num_points, 67); @@ -257,7 +295,7 @@ void check_assign_matches_final_training_assignment() { auto parameters = test_parameters(); parameters.num_threads = threads; if constexpr (kGraph) { - parameters.quantization_bits = bits; + parameters.nbits = bits; } parameters.final_assignment = mode; parameters.max_points_per_centroid = kMaxPoints; @@ -323,10 +361,10 @@ void check_graph_cache_follows_centroids_and_settings() { constexpr size_t kClusterCount = kClusters; const auto points = clustered_points(6 * kClusterCount, 83); const auto queries = clustered_points(60, 89); - for (const uint32_t bits : {0U, 4U}) { + for (const uint32_t bits : {32U, 4U}) { SCOPED_TRACE(bits); auto parameters = test_parameters(); - parameters.quantization_bits = bits; + parameters.nbits = bits; QGKMeans clustering(kDim, kClusterCount, parameters); clustering.train(6 * kClusterCount, points.data()); QGKMeans fresh = clustering; // Copied before any graph is cached. @@ -602,6 +640,14 @@ TEST(KMeansAssignTest, QGRequiresTrainingAndValidInput) { check_assign_requires_training_and_valid_input("QGKMeans"); } +TEST(KMeansAssignTest, RaBitQCoordinateBoundMatchesIndexCheck) { + check_coordinate_bound_matches_index_check("RaBitQKMeans"); +} + +TEST(KMeansAssignTest, QGCoordinateBoundMatchesIndexCheck) { + check_coordinate_bound_matches_index_check("QGKMeans"); +} + TEST(KMeansAssignTest, RaBitQMatchesFinalTrainingAssignment) { check_assign_matches_final_training_assignment(); } @@ -693,11 +739,11 @@ TEST(KMeansParametersTest, CopySharedParametersCopiesOnlySharedFields) { from.spherical = true; from.verbose = true; qgkmeans::QGKMeansParameters to; - to.graph_degree = 64; - to.ef_build = 99; + to.max_degree = 64; + to.ef_construction = 99; to.ef_search = 33; to.graph_build_iterations = 2; - to.quantization_bits = 4; + to.nbits = 4; clustering::detail::copy_shared_parameters(from, to); EXPECT_EQ(to.early_stop_threshold, from.early_stop_threshold); @@ -709,11 +755,11 @@ TEST(KMeansParametersTest, CopySharedParametersCopiesOnlySharedFields) { EXPECT_EQ(to.seed, from.seed); EXPECT_EQ(to.spherical, from.spherical); EXPECT_EQ(to.verbose, from.verbose); - EXPECT_EQ(to.graph_degree, 64U); - EXPECT_EQ(to.ef_build, 99U); + EXPECT_EQ(to.max_degree, 64U); + EXPECT_EQ(to.ef_construction, 99U); EXPECT_EQ(to.ef_search, 33U); EXPECT_EQ(to.graph_build_iterations, 2U); - EXPECT_EQ(to.quantization_bits, 4U); + EXPECT_EQ(to.nbits, 4U); } TEST(KMeansTrainCentroidsTest, RaBitQSkipsFinalAssignment) { diff --git a/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp b/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp index a529b9c1..d1336ddd 100644 --- a/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp +++ b/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp @@ -134,15 +134,15 @@ TEST(QGKMeansTest, UsesTwentyFiveIterationsByDefault) { } TEST(QGKMeansTest, UsesRawGraphStorageByDefaultAndRejectsUnsupportedBits) { - EXPECT_EQ(QGKMeansParameters{}.quantization_bits, 0U); - for (const uint32_t bits : {1U, 7U, 9U, 32U}) { + EXPECT_EQ(QGKMeansParameters{}.nbits, 32U); + for (const uint32_t bits : {0U, 1U, 7U, 9U}) { QGKMeansParameters parameters; - parameters.quantization_bits = bits; + parameters.nbits = bits; try { QGKMeans clustering(65, 33, parameters); - FAIL() << "Accepted unsupported quantization bits " << bits; + FAIL() << "Accepted unsupported nbits " << bits; } catch (const std::invalid_argument& error) { - EXPECT_STREQ(error.what(), "QGKMeans quantization_bits must be 0, 4, or 8"); + EXPECT_STREQ(error.what(), "QGKMeans nbits must be 4, 8, or 32"); } } } @@ -294,8 +294,8 @@ TEST(QGAssignerTest, GroupedQueriesPreserveIndependentSearchHintsAcrossRebuilds) } } -TEST(QGKMeansTest, UsesSymphonyQGForFinalAssignmentByDefault) { - EXPECT_EQ(QGKMeansParameters{}.final_assignment, FinalAssignmentMode::SymphonyQG); +TEST(QGKMeansTest, UsesApproximateFinalAssignmentByDefault) { + EXPECT_EQ(QGKMeansParameters{}.final_assignment, FinalAssignmentMode::Approximate); } TEST(QGKMeansTest, UsesFaissTrainingSizeWarningThresholdByDefault) { @@ -305,8 +305,8 @@ TEST(QGKMeansTest, UsesFaissTrainingSizeWarningThresholdByDefault) { QGKMeansParameters exact_search_parameters() { QGKMeansParameters parameters; parameters.niter = 4; - parameters.graph_degree = 32; - parameters.ef_build = 33; + parameters.max_degree = 32; + parameters.ef_construction = 33; parameters.ef_search = 33; parameters.graph_build_iterations = 2; parameters.num_threads = 1; @@ -791,9 +791,9 @@ TEST(QGKMeansTest, TrainsAndReturnsAssignmentsForFinalCentroids) { TEST(QGKMeansTest, RetrainsOnOwnedCentroidsLikeAnIndependentCopy) { constexpr size_t kDim = 65, kInitialClusters = 35, kClusters = 33; const auto data = separated_points(kInitialClusters, kDim); - for (const uint32_t bits : {0U, 4U, 8U}) { + for (const uint32_t bits : {32U, 4U, 8U}) { for (const auto mode : - {FinalAssignmentMode::SymphonyQG, FinalAssignmentMode::Exact}) { + {FinalAssignmentMode::Approximate, FinalAssignmentMode::Exact}) { for (const size_t offset : {0U, 1U}) { SCOPED_TRACE( ::testing::Message() @@ -801,7 +801,7 @@ TEST(QGKMeansTest, RetrainsOnOwnedCentroidsLikeAnIndependentCopy) { ); auto parameters = exact_search_parameters(); parameters.niter = 2; - parameters.quantization_bits = bits; + parameters.nbits = bits; parameters.final_assignment = mode; QGKMeans clustering(kDim, kInitialClusters, parameters); clustering.train(kInitialClusters, data.data()); @@ -1163,7 +1163,7 @@ TEST(QGKMeansTest, FinalAssignmentsRetainACloserPreviousCluster) { parameters.num_threads = 1; parameters.min_points_per_centroid = 1; parameters.spherical = spherical; - parameters.quantization_bits = bits; + parameters.nbits = bits == 0 ? 32 : bits; QGKMeans clustering(kDim, kClusters, parameters); clustering.train(kPoints, data.data()); const auto distance = spherical ? dot_product_dis : euclidean_sqr; @@ -1209,20 +1209,20 @@ TEST(QGKMeansTest, TrainsWithMovingCentroidsAndAnApproximateGraph) { } } } - for (uint32_t bits : {0U, 4U, 8U}) { + for (uint32_t bits : {32U, 4U, 8U}) { SCOPED_TRACE(::testing::Message() << spherical << "/" << bits); QGKMeansParameters parameters; parameters.niter = 5; parameters.num_threads = 2; parameters.min_points_per_centroid = 1; parameters.spherical = spherical; - parameters.quantization_bits = bits; + parameters.nbits = bits; QGKMeans clustering(kDim, kClusters, parameters); clustering.train(kCount, data.data()); double previous = std::numeric_limits::infinity(); for (const auto& stats : clustering.iteration_stats) { EXPECT_TRUE(std::isfinite(stats.obj)); - if (bits == 0) { + if (bits == 32) { EXPECT_LE(stats.obj, previous + 1e-6 * std::abs(previous)); } previous = stats.obj; @@ -1236,6 +1236,18 @@ TEST(QGAssignerTest, RejectsTooFewClustersForGraphDegree) { EXPECT_THROW(QGAssigner(64, 32, 32, 64, 16, 1, 1), std::invalid_argument); } +// Like the quantizers and FastScan, clustering takes only L2 and inner product. +TEST(QGAssignerTest, RejectsTheCosineMetric) { + try { + const QGAssigner assigner(64, 33, 32, 64, 16, 1, 1, 42, METRIC_COSINE); + ADD_FAILURE() << "accepted METRIC_COSINE"; + } catch (const std::invalid_argument& error) { + EXPECT_STREQ(error.what(), "Metric type must be METRIC_L2 or METRIC_IP"); + } + EXPECT_NO_THROW(QGAssigner(64, 33, 32, 64, 16, 1, 1, 42, METRIC_L2)); + EXPECT_NO_THROW(QGAssigner(64, 33, 32, 64, 16, 1, 1, 42, METRIC_IP)); +} + TEST(QGKMeansTest, RejectsTooFewClustersForGraphDegreeInBothFinalModes) { constexpr size_t kDim = 64, kPoints = 65; const std::vector data(kPoints * kDim, 0.0F); @@ -1248,7 +1260,7 @@ TEST(QGKMeansTest, RejectsTooFewClustersForGraphDegreeInBothFinalModes) { QGKMeansParameters parameters; parameters.niter = 1; parameters.num_threads = 1; - parameters.graph_degree = degree; + parameters.max_degree = degree; parameters.final_assignment = mode; try { QGKMeans model(kDim, clusters, parameters); @@ -1256,8 +1268,7 @@ TEST(QGKMeansTest, RejectsTooFewClustersForGraphDegreeInBothFinalModes) { FAIL() << "Accepted k=" << clusters << " for degree=" << degree; } catch (const std::invalid_argument& error) { EXPECT_STREQ( - error.what(), - "QGKMeans requires more centroids than the graph degree" + error.what(), "QGKMeans requires more centroids than max_degree" ); } } @@ -1312,11 +1323,11 @@ TEST(QGAssignerTest, PropagatesSearchFailureFromWorkers) { } TEST(QGKMeansTest, RejectsFiniteOutOfRangeInputBeforeConstruction) { - for (uint32_t bits : {0U, 4U, 8U}) { + for (uint32_t bits : {32U, 4U, 8U}) { QGKMeansParameters parameters; parameters.niter = 1; parameters.num_threads = 2; - parameters.quantization_bits = bits; + parameters.nbits = bits; QGKMeans model(64, 33, parameters); const std::vector data(66 * 64, 1e19F); EXPECT_THROW(model.train(66, data.data()), std::invalid_argument); @@ -1335,16 +1346,16 @@ TEST(QGKMeansTest, SupportsLargerPaddedDimensions) { data[i * d + i] = 1.0F; data[i * d + d - 1] = static_cast(i) / 64.0F; } - for (uint32_t bits : {0U, 4U, 8U}) { + for (uint32_t bits : {32U, 4U, 8U}) { // Quantized rows of 65535 and 65536 inputs share the 65536-wide padded // layout; the exact maximum only adds unpadded raw storage. - if (d == 65536 && bits != 0) { + if (d == 65536 && bits != 32) { continue; } QGKMeansParameters parameters; parameters.niter = 1; parameters.num_threads = 2; - parameters.quantization_bits = bits; + parameters.nbits = bits; QGKMeans model(d, kClusters, parameters); model.train(kClusters, data.data()); EXPECT_DOUBLE_EQ(model.final_obj, 0.0); @@ -1396,9 +1407,9 @@ void check_uncached_reference(size_t clusters, uint32_t ef_search, size_t intrin parameters.num_threads = threads; parameters.seed = 42; parameters.min_points_per_centroid = 1; - parameters.quantization_bits = bits; + parameters.nbits = bits == 0 ? 32 : bits; parameters.spherical = spherical; - parameters.ef_build = 128; + parameters.ef_construction = 128; parameters.ef_search = ef_search; QGKMeans model(kDim, clusters, parameters); model.train(kPoints, x.data()); @@ -1423,7 +1434,7 @@ void check_uncached_reference(size_t clusters, uint32_t ef_search, size_t intrin kDim, clusters, 32, - parameters.ef_build, + parameters.ef_construction, ef_search, 1, threads, diff --git a/tests/unit/rabitqlib/index/flat_rabitq_initializer_test.cpp b/tests/unit/rabitqlib/index/flat_rabitq_initializer_test.cpp index 17daef67..6d0a007a 100644 --- a/tests/unit/rabitqlib/index/flat_rabitq_initializer_test.cpp +++ b/tests/unit/rabitqlib/index/flat_rabitq_initializer_test.cpp @@ -5,16 +5,17 @@ #include #include #include -#include +#include #include -#include #include +#include #include #include #include #include #include +#include "format2_file.hpp" #include "rabitqlib/core/metric.hpp" #include "rabitqlib/core/rotator.hpp" #include "rabitqlib/index/ivf/initializer.hpp" @@ -127,11 +128,15 @@ TEST(IvfInitializerTest, ReloadChangesRoutingAndFailedLoadPreservesExistingIndex EXPECT_EQ(actual_ids, expected_ids); EXPECT_EQ(actual_distances, expected_distances); { - std::fstream file(path, std::ios::binary | std::ios::in | std::ios::out); - // A persisted v2 file must contain a concrete initializer, never Auto. - file.seekp(24); - const uint32_t invalid = 0; - file.write(reinterpret_cast(&invalid), sizeof(invalid)); + // A persisted file must contain a concrete initializer, never Auto. + using rabitq_test::format2::IndexKind; + std::string params = rabitq_test::read_format2_section( + path, IndexKind::Ivf, rabitq_test::kIvfSections, 256 + ); + std::memset(params.data() + 8, 0, sizeof(uint32_t)); + rabitq_test::replace_format2_section( + path, IndexKind::Ivf, rabitq_test::kIvfSections, 256, params + ); } EXPECT_THROW(target.load(path.c_str()), std::runtime_error); EXPECT_EQ(target.initializer_type(), type); @@ -223,19 +228,18 @@ TEST(IvfFlatRaBitQInitializerTest, PersistsCodesAndSupportsConcurrentSearch) { std::vector centroids(kDim * kCount), queries(8 * kDim); std::generate(centroids.begin(), centroids.end(), [&] { return normal(generator); }); std::generate(queries.begin(), queries.end(), [&] { return normal(generator); }); - const rabitq_test::TempFile path_file("flat_rabitq_initializer.bin"); - const std::string& path = path_file.path(); for (auto metric : {METRIC_L2, METRIC_IP}) { FlatRaBitQInitializer index(kDim, kCount, metric), loaded(kDim, kCount, metric); index.add_vectors(centroids.data(), 2); + std::stringstream stored; + index.write(stored); + const std::string bytes = stored.str(); { - std::ofstream out(path, std::ios::binary); - index.save(out, nullptr); - } - { - std::ifstream input(path, std::ios::binary); - loaded.load(input, nullptr); + FlatRaBitQInitializer wrong_size(kDim, kCount, metric); + std::stringstream copy(bytes); + EXPECT_THROW(wrong_size.read(copy, bytes.size() - 1), std::runtime_error); } + loaded.read(stored, bytes.size()); for (size_t i = 0; i < kCount; ++i) { EXPECT_TRUE( std::equal(index.centroid(i), index.centroid(i) + kDim, loaded.centroid(i)) @@ -259,15 +263,9 @@ TEST(IvfFlatRaBitQInitializerTest, PersistsCodesAndSupportsConcurrentSearch) { EXPECT_FLOAT_EQ(actual[i][j].distance, expected[i][j].distance); } } - std::ifstream before(path, std::ios::binary); - const std::string bytes{std::istreambuf_iterator(before), {}}; - before.close(); - { - std::ofstream out(path, std::ios::binary); - loaded.save(out, nullptr); - } - std::ifstream after(path, std::ios::binary); - EXPECT_EQ((std::string{std::istreambuf_iterator(after), {}}), bytes); + std::ostringstream resaved; + loaded.write(resaved); + EXPECT_EQ(resaved.str(), bytes); } } } // namespace diff --git a/tests/unit/rabitqlib/index/format2_test.cpp b/tests/unit/rabitqlib/index/format2_test.cpp new file mode 100644 index 00000000..de71a136 --- /dev/null +++ b/tests/unit/rabitqlib/index/format2_test.cpp @@ -0,0 +1,670 @@ +#include "format2.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "crc32.hpp" + +namespace { +namespace f2 = rabitqlib::index_detail::format2; +using rabitqlib::detail::crc32; + +constexpr uint32_t kParams = 256; +constexpr uint32_t kBulk = 261; +constexpr uint32_t kEmpty = 263; +const std::vector kKnown = {kParams, kBulk, kEmpty}; + +uint32_t get_u32(const std::string& bytes, size_t offset) { + uint32_t value = 0; + for (size_t i = 0; i < 4; ++i) { + value |= static_cast(static_cast(bytes[offset + i])) << (8 * i); + } + return value; +} + +uint64_t get_u64(const std::string& bytes, size_t offset) { + uint64_t value = 0; + for (size_t i = 0; i < 8; ++i) { + value |= static_cast(static_cast(bytes[offset + i])) << (8 * i); + } + return value; +} + +void put_u32(std::string& bytes, size_t offset, uint32_t value) { + for (size_t i = 0; i < 4; ++i) { + bytes[offset + i] = static_cast(value >> (8 * i)); + } +} + +void put_u64(std::string& bytes, size_t offset, uint64_t value) { + for (size_t i = 0; i < 8; ++i) { + bytes[offset + i] = static_cast(value >> (8 * i)); + } +} + +// Recompute the header checksum after a test edits the header or the table, so that +// the check under test fires rather than the checksum. +void reseal(std::string& bytes) { + const uint32_t header_bytes = get_u32(bytes, 12); + const uint64_t table_offset = get_u64(bytes, 96); + const uint32_t count = get_u32(bytes, 104); + std::string header = bytes.substr(0, header_bytes); + put_u32(header, 108, 0); + uint32_t crc = crc32(header.data(), header.size()); + crc = crc32(bytes.data() + table_offset, size_t{32} * count, crc); + put_u32(bytes, 108, crc); +} + +f2::Header test_header() { + f2::Header header; + header.index_kind = f2::IndexKind::Ivf; + header.metric = f2::Metric::InnerProduct; + header.dim = 100; + header.padded_dim = 128; + header.code_bits = 7; + header.raw_type = f2::RawType::None; + header.id_bits = 32; + header.seed = 42; + header.num_points = 3; + return header; +} + +const std::string kParamBytes = "params!!"; + +std::string bulk_bytes() { + std::string bulk(1000, '\0'); + for (size_t i = 0; i < bulk.size(); ++i) { + bulk[i] = static_cast(i * 7); + } + return bulk; +} + +// A checksummed parameter section, an unchecksummed bulk section written in two +// pieces, and an empty section. Layout: header 0-127, table 128-223, parameters at +// 256, bulk at 320 (1000 bytes), the empty section at 1344, which ends the file. +std::vector test_sections() { + const std::string bulk = bulk_bytes(); + return { + {kParams, + f2::kSectionRequired | f2::kSectionChecksummed, + kParamBytes.size(), + [](f2::SectionSink& sink) { sink.write(kParamBytes.data(), kParamBytes.size()); }}, + {kBulk, + f2::kSectionRequired, + bulk.size(), + [bulk](f2::SectionSink& sink) { + sink.write(bulk.data(), 400); + sink.write(bulk.data() + 400, bulk.size() - 400); + }}, + {kEmpty, f2::kSectionRequired, 0, nullptr}}; +} + +std::string write(const f2::Header& header, const std::vector& sections) { + std::ostringstream out; + f2::write_file(out, header, sections, "0.9.0"); + return out.str(); +} + +std::string valid_file() { return write(test_header(), test_sections()); } + +// Byte offset of section table entry `i` when the table follows a 128-byte header. +size_t entry(size_t i) { return 128 + (32 * i); } + +f2::Reader open_reader(std::istream& stream, f2::IndexKind kind = f2::IndexKind::Ivf) { + return f2::Reader(stream, kind, kKnown); +} + +void expect_format_error( + const std::string& bytes, + const std::string& message, + f2::IndexKind kind = f2::IndexKind::Ivf +) { + std::istringstream stream(bytes); + try { + f2::Reader reader(stream, kind, kKnown); + ADD_FAILURE() << "expected FormatError containing: " << message; + } catch (const f2::FormatError& error) { + EXPECT_NE(std::string(error.what()).find(message), std::string::npos) + << "message: " << error.what(); + } +} + +// Input and output buffers that cannot seek, like pipes. +class SequentialInput : public std::streambuf { + public: + explicit SequentialInput(std::string bytes) : bytes_(std::move(bytes)) { + setg(bytes_.data(), bytes_.data(), bytes_.data() + bytes_.size()); + } + + private: + std::string bytes_; +}; + +class SequentialOutput : public std::streambuf { + public: + std::string bytes; + + private: + int_type overflow(int_type c) override { + if (!traits_type::eq_int_type(c, traits_type::eof())) { + bytes.push_back(traits_type::to_char_type(c)); + } + return traits_type::not_eof(c); + } + std::streamsize xsputn(const char* data, std::streamsize count) override { + bytes.append(data, static_cast(count)); + return count; + } +}; + +TEST(Format2ContainerTest, RoundTripsHeaderAndSections) { + const std::string bytes = valid_file(); + std::istringstream stream(bytes); + f2::Reader reader = open_reader(stream); + + const f2::Header& header = reader.header(); + EXPECT_EQ(header.index_kind, f2::IndexKind::Ivf); + EXPECT_EQ(header.metric, f2::Metric::InnerProduct); + EXPECT_EQ(header.dim, 100U); + EXPECT_EQ(header.padded_dim, 128U); + EXPECT_EQ(header.code_bits, 7U); + EXPECT_EQ(header.raw_type, f2::RawType::None); + EXPECT_EQ(header.id_bits, 32U); + ASSERT_TRUE(header.seed.has_value()); + EXPECT_EQ(*header.seed, 42U); + EXPECT_EQ(header.num_points, 3U); + EXPECT_FALSE(reader.read_only()); + EXPECT_EQ(reader.writer_version(), "0.9.0"); + + const f2::Section* params = reader.find(kParams); + const f2::Section* bulk = reader.find(kBulk); + const f2::Section* empty = reader.find(kEmpty); + ASSERT_NE(params, nullptr); + ASSERT_NE(bulk, nullptr); + ASSERT_NE(empty, nullptr); + EXPECT_EQ(reader.find(999), nullptr); + EXPECT_EQ(params->offset, 256U); + EXPECT_EQ(bulk->offset, 320U); + EXPECT_EQ(bulk->crc32, 0U); + EXPECT_EQ(empty->offset, 1344U); // 320 + 1000, padded to 64 + EXPECT_EQ(bytes.size(), 1344U); // the empty section ends the file + + std::string read_params(params->size, '\0'); + reader.read(*params, 0, read_params.data(), read_params.size()); + EXPECT_EQ(read_params, kParamBytes); + std::string read_bulk(bulk->size - 10, '\0'); + reader.read(*bulk, 10, read_bulk.data(), read_bulk.size()); + EXPECT_EQ(read_bulk, bulk_bytes().substr(10)); + EXPECT_THROW( + reader.read(*bulk, 10, read_bulk.data(), read_bulk.size() + 1), std::out_of_range + ); +} + +TEST(Format2ContainerTest, WritesIdenticalBytesTwice) { + EXPECT_EQ(valid_file(), valid_file()); +} + +TEST(Format2ContainerTest, WritesAnUnknownSeed) { + f2::Header header = test_header(); + header.seed.reset(); + const std::string bytes = write(header, {{kEmpty, f2::kSectionRequired, 0, nullptr}}); + EXPECT_EQ(get_u32(bytes, 76), 0U); + EXPECT_EQ(get_u64(bytes, 80), 0U); + std::istringstream stream(bytes); + EXPECT_FALSE(open_reader(stream).header().seed.has_value()); +} + +TEST(Format2ContainerTest, WritesAndReadsWithoutSeeking) { + SequentialOutput output_buffer; + std::ostream output(&output_buffer); + f2::write_file(output, test_header(), test_sections(), "0.9.0"); + EXPECT_EQ(output_buffer.bytes, valid_file()); + + SequentialInput input_buffer(valid_file()); + std::istream input(&input_buffer); + EXPECT_THROW(f2::has_magic(input, f2::IndexKind::Ivf), f2::FormatError); + try { + f2::Reader reader(input, f2::IndexKind::Ivf, kKnown); + ADD_FAILURE() << "expected FormatError"; + } catch (const f2::FormatError& error) { + EXPECT_STREQ(error.what(), "IVF index file input must be seekable"); + } +} + +TEST(Format2ContainerTest, DetectsTheMagicAndRestoresThePosition) { + std::istringstream good(valid_file()); + EXPECT_TRUE(f2::has_magic(good, f2::IndexKind::Ivf)); + EXPECT_EQ(good.tellg(), std::streampos(0)); + std::istringstream legacy(std::string("RABQIDX1") + std::string(200, '\0')); + EXPECT_FALSE(f2::has_magic(legacy, f2::IndexKind::Ivf)); + + std::istringstream short_file("RABQ"); + short_file.exceptions(std::ios::failbit | std::ios::badbit); + EXPECT_FALSE(f2::has_magic(short_file, f2::IndexKind::Ivf)); + EXPECT_EQ(short_file.tellg(), std::streampos(0)); +} + +TEST(Format2ContainerTest, IgnoresTheStreamExceptionMask) { + // Truncated in the padding before the last section: the header and the table are + // read, then a section check fails. + std::istringstream stream(valid_file().substr(0, 1336)); + stream.exceptions(std::ios::failbit | std::ios::badbit | std::ios::eofbit); + EXPECT_THROW(open_reader(stream), f2::FormatError); + std::istringstream valid(valid_file()); + valid.exceptions(std::ios::failbit | std::ios::badbit | std::ios::eofbit); + EXPECT_NO_THROW(open_reader(valid)); +} + +TEST(Format2ContainerTest, WriterRejectsInvalidArgumentsBeforeWriting) { + const f2::SectionWrite empty{kEmpty, f2::kSectionRequired, 0, nullptr}; + const auto expect_rejected = [](const f2::Header& header, + const std::vector& sections, + const char* version = "0.9.0") { + std::ostringstream out; + EXPECT_THROW(f2::write_file(out, header, sections, version), std::invalid_argument); + EXPECT_TRUE(out.str().empty()); + }; + + f2::Header header = test_header(); + header.padded_dim = 100; + expect_rejected(header, {empty}); + header = test_header(); + header.index_kind = static_cast(4); + expect_rejected(header, {empty}); + for (const int mask : {0, 1, 2}) { + header = test_header(); + (mask == 0 ? header.incompat_features + : mask == 1 ? header.ro_compat_features + : header.compat_features) = 1; + expect_rejected(header, {empty}); + } + expect_rejected(test_header(), {}); + expect_rejected(test_header(), {empty, empty}); + expect_rejected(test_header(), {{0, f2::kSectionRequired, 0, nullptr}}); + expect_rejected(test_header(), {{kEmpty, 4, 0, nullptr}}); + expect_rejected( + test_header(), + {{kBulk, 0, 1, nullptr}, + {kEmpty, 0, std::numeric_limits::max() - 10, nullptr}} + ); + expect_rejected(test_header(), {empty}, "a version longer than 16"); + expect_rejected(test_header(), {empty}, "0.9\n"); +} + +TEST(Format2ContainerTest, WriterChecksSectionSizesAndPropagatesFailures) { + const auto two_bytes = [](f2::SectionSink& sink) { sink.write("ab", 2); }; + for (const uint32_t flags : {0U, f2::kSectionChecksummed}) { + EXPECT_THROW( + write(test_header(), {{kBulk, flags, 1, two_bytes}}), std::invalid_argument + ); + EXPECT_THROW( + write(test_header(), {{kBulk, flags, 3, two_bytes}}), std::invalid_argument + ); + } + const auto fails = [](f2::SectionSink&) { throw std::runtime_error("section failed"); }; + EXPECT_THROW(write(test_header(), {{kBulk, 0, 1, fails}}), std::runtime_error); + + std::ostringstream broken; + broken.setstate(std::ios::badbit); + try { + f2::write_file(broken, test_header(), test_sections(), "0.9.0"); + ADD_FAILURE() << "expected runtime_error"; + } catch (const std::runtime_error& error) { + EXPECT_STREQ(error.what(), "IVF index file cannot be written"); + } +} + +TEST(Format2ContainerTest, RejectsBrokenHeaders) { + const std::string good = valid_file(); + expect_format_error(good.substr(0, 127), "IVF index file is too short"); + + std::string bytes = good; + bytes[0] = 'X'; + expect_format_error(bytes, "IVF index file is not in format 2 (bad magic)"); + + bytes = good; + put_u32(bytes, 8, 3); + reseal(bytes); + expect_format_error(bytes, "format version 3; this release reads version 2"); + + for (const uint32_t size : {120U, 132U, 4096U}) { + bytes = good; + put_u32(bytes, 12, size); + expect_format_error(bytes, "invalid header size " + std::to_string(size)); + } + + bytes = good; + bytes[50] ^= 1; // dim, without resealing + expect_format_error(bytes, "header checksum mismatch"); + + bytes = good; + put_u32(bytes, 104, 0); + reseal(bytes); + expect_format_error(bytes, "has no sections"); + + for (const uint64_t table_offset : {uint64_t{132}, uint64_t{120}, uint64_t{1344}}) { + bytes = good; + put_u64(bytes, 96, table_offset); + expect_format_error(bytes, "section table lies outside the file"); + } + bytes = good; + put_u32(bytes, 104, 1000); + expect_format_error(bytes, "section table lies outside the file"); +} + +TEST(Format2ContainerTest, ChecksTheIndexKindBeforeTheSections) { + std::string bytes = valid_file(); + put_u32(bytes, entry(1), 777); // an unknown required section + reseal(bytes); + expect_format_error( + bytes, "HNSW index file holds an IVF-RaBitQ index", f2::IndexKind::Hnsw + ); + expect_format_error( + bytes, + "QuantizedGraph index file holds an IVF-RaBitQ index", + f2::IndexKind::SymphonyQg + ); + + const struct { + uint32_t kind; + const char* message; + } cases[] = { + {4, "IVF index file holds an IVF-SSD index"}, + {9, "IVF index file has unknown index kind 9"}, + {0, "IVF index file has unknown index kind 0"}, + }; + for (const auto& c : cases) { + bytes = valid_file(); + put_u32(bytes, 40, c.kind); + reseal(bytes); + expect_format_error(bytes, c.message); + } + + // The index's own header rules also run before the sections. + bytes = valid_file(); + put_u32(bytes, entry(1), 777); + reseal(bytes); + std::istringstream stream(bytes); + try { + f2::Reader reader(stream, f2::IndexKind::Ivf, kKnown, [](const f2::Header& header) { + if (header.id_bits != 64) { + throw f2::FormatError("IVF index file needs 64-bit IDs"); + } + }); + ADD_FAILURE() << "expected FormatError"; + } catch (const f2::FormatError& error) { + EXPECT_STREQ(error.what(), "IVF index file needs 64-bit IDs"); + } +} + +TEST(Format2ContainerTest, RejectsInvalidHeaderFields) { + const std::string good = valid_file(); + const struct { + size_t offset; + uint64_t value; + const char* message; + } cases[] = { + {44, 7, "IVF index file has unknown metric 7"}, + {44, 0, "IVF index file has unknown metric 0"}, + {48, 0, "IVF index file has dimension 0"}, + {56, 100, "has padded dimension 100, which must be a multiple of 32"}, + {56, + 96, + "has padded dimension 96, which must be a multiple of 32 from the dimension 100"}, + {56, 65568, "has padded dimension 65568, which must be a multiple of 32"}, + {64, 10, "has 10 code bits; at most 9 are supported"}, + {68, 5, "has unknown raw element type 5"}, + {72, 16, "has 16-bit IDs; only 32 and 64 are valid"}, + {76, 3, "has unknown header flags 0x3"}, + }; + for (const auto& c : cases) { + std::string bytes = good; + if (c.offset == 48 || c.offset == 56) { + put_u64(bytes, c.offset, c.value); + } else { + put_u32(bytes, c.offset, static_cast(c.value)); + } + reseal(bytes); + expect_format_error(bytes, c.message); + } + + std::string bytes = good; + put_u32(bytes, 76, 0); // seed 42 without seed_known + reseal(bytes); + expect_format_error(bytes, "has a seed without the seed_known flag"); +} + +TEST(Format2ContainerTest, AppliesFeatureFlags) { + const std::string good = valid_file(); + + std::string bytes = good; + put_u64(bytes, 16, 4); + reseal(bytes); + expect_format_error( + bytes, + "IVF index file uses incompatible features 0x4 that this release does not know; " + "written by rabitqlib 0.9.0" + ); + + bytes = good; + put_u64(bytes, 24, 1); + reseal(bytes); + std::istringstream read_only(bytes); + EXPECT_TRUE(open_reader(read_only).read_only()); + + bytes = good; + put_u64(bytes, 32, 0x80); + reseal(bytes); + std::istringstream compat(bytes); + const f2::Reader reader = open_reader(compat); + EXPECT_FALSE(reader.read_only()); + EXPECT_EQ(reader.header().compat_features, 0x80U); +} + +TEST(Format2ContainerTest, SkipsUnknownOptionalSectionsAndRejectsUnknownRequiredOnes) { + std::string bytes = valid_file(); + put_u32(bytes, entry(1), 777); + put_u32(bytes, entry(1) + 4, 0); // optional + reseal(bytes); + std::istringstream optional(bytes); + const f2::Reader reader = open_reader(optional); + EXPECT_EQ(reader.find(kBulk), nullptr); + EXPECT_EQ(reader.find(777), nullptr); + EXPECT_NE(reader.find(kParams), nullptr); + + put_u32(bytes, entry(1) + 4, f2::kSectionRequired); + reseal(bytes); + expect_format_error( + bytes, + "IVF index file section kind 777 is required but unknown to this release; written " + "by " + "rabitqlib 0.9.0" + ); + + // An unknown optional section is not read, so its checksum is not verified. + bytes = valid_file(); + put_u32(bytes, entry(0), 778); + put_u32(bytes, entry(0) + 4, f2::kSectionChecksummed); + reseal(bytes); + bytes[256] ^= 1; + std::istringstream unverified(bytes); + EXPECT_EQ(open_reader(unverified).find(kParams), nullptr); +} + +// The valid file with a 136-byte header whose extra bytes come from a later version. +std::string longer_header_file() { + const std::string good = valid_file(); + std::string bytes = good.substr(0, 128) + std::string(8, '\x5A'); + put_u32(bytes, 12, 136); + put_u64(bytes, 96, 136); + bytes += good.substr(128, 96); // the table + bytes.resize(256, '\0'); // sections start at 256 in both layouts + bytes += good.substr(256); + reseal(bytes); + return bytes; +} + +TEST(Format2ContainerTest, LoadsALongerHeaderAndChecksumsItsExtension) { + std::string bytes = longer_header_file(); + std::istringstream stream(bytes); + const f2::Reader reader = open_reader(stream); + EXPECT_EQ(reader.header().dim, 100U); + EXPECT_NE(reader.find(kBulk), nullptr); + + bytes[130] ^= 1; + expect_format_error(bytes, "header checksum mismatch"); +} + +TEST(Format2ContainerTest, LoadsATableAfterTheSections) { + const std::string good = valid_file(); + std::string bytes = good.substr(0, 128) + std::string(128, '\0') + good.substr(256); + put_u64(bytes, 96, bytes.size()); // 1344, a multiple of 8 + bytes += good.substr(128, 96); + reseal(bytes); + std::istringstream stream(bytes); + EXPECT_NE(open_reader(stream).find(kBulk), nullptr); + + // The empty last section now grows into the table. + put_u64(bytes, 1344 + 64 + 16, 50); + reseal(bytes); + expect_format_error(bytes, "section kind 263 overlaps the header or the section table"); +} + +TEST(Format2ContainerTest, RejectsBrokenSectionEntries) { + const std::string good = valid_file(); + const struct { + size_t offset; + uint64_t value; + bool wide; + const char* message; + } cases[] = { + {entry(0), 0, false, "IVF index file section kind 0 is reserved"}, + {entry(0) + 4, 0x7, false, "section kind 256 has unknown flags 0x7"}, + {entry(0) + 28, 1, false, "section kind 256 has a non-zero reserved field"}, + {entry(1) + 24, 5, false, "section kind 261 has a checksum but is not checksummed"}, + {entry(1) + 8, 328, true, "section kind 261 is not aligned to 64 bytes"}, + {entry(1) + 16, 1344, true, "section kind 261 lies outside the file"}, + {entry(1) + 16, + std::numeric_limits::max(), + true, + "261 lies outside the file"}, + {entry(1) + 8, + std::numeric_limits::max() - 63, + true, + "261 lies outside the file"}, + {entry(1) + 8, 256, true, "section kind 261 overlaps the previous section"}, + {entry(0) + 8, + 128, + true, + "section kind 256 overlaps the header or the section table"}, + {entry(0) + 8, + 0, + true, + "section kind 256 overlaps the header or the section table"}, + {entry(2), kBulk, false, "section kind 261 is repeated"}, + }; + for (const auto& c : cases) { + std::string bytes = good; + if (c.wide) { + put_u64(bytes, c.offset, c.value); + } else { + put_u32(bytes, c.offset, static_cast(c.value)); + } + reseal(bytes); + expect_format_error(bytes, c.message); + } +} + +// Every entry, empty or not, starts at or after the end of the previous one, so an +// empty section shares its offset only with entries that follow it. +TEST(Format2ContainerTest, PlacesEmptySectionsByTheLayoutRule) { + // Empty, parameters, bulk: the empty section and the parameters share 256. + auto sections = test_sections(); + std::rotate(sections.begin(), sections.begin() + 2, sections.end()); + const std::string shared = write(test_header(), sections); + EXPECT_EQ(get_u64(shared, entry(0) + 8), 256U); + EXPECT_EQ(get_u64(shared, entry(1) + 8), 256U); + std::istringstream shared_stream(shared); + const f2::Reader reader = open_reader(shared_stream); + ASSERT_NE(reader.find(kEmpty), nullptr); + EXPECT_EQ(reader.find(kEmpty)->offset, 256U); + ASSERT_NE(reader.find(kParams), nullptr); + EXPECT_EQ(reader.find(kParams)->offset, 256U); + + // Two empty sections may share an offset too (an empty checksummed section + // has CRC-32 zero). + std::string bytes = shared; + put_u64(bytes, entry(1) + 16, 0); + put_u32(bytes, entry(1) + 24, 0); + reseal(bytes); + std::istringstream two_empty(bytes); + EXPECT_EQ(open_reader(two_empty).find(kParams)->size, 0U); + + // After a non-empty section, an empty one may not start at its offset or + // inside it. The file ends with the bulk section, so only the order check fails. + for (const uint64_t offset : {uint64_t{320}, uint64_t{1280}}) { + bytes = valid_file().substr(0, 1320); + put_u64(bytes, entry(2) + 8, offset); + reseal(bytes); + expect_format_error( + bytes, "section kind 263 overlaps the previous section or is out of order" + ); + } +} + +// Readers do not validate the stored writer version; messages escape bytes outside +// printable ASCII, and the accessor returns the stored bytes. +TEST(Format2ContainerTest, EscapesTheStoredWriterVersionInMessages) { + const std::string version = "0.9\xff\\"; + std::string marked = valid_file(); + std::memcpy(&marked[112], version.data(), version.size()); // over "0.9.0" + reseal(marked); + std::istringstream stream(marked); + EXPECT_EQ(open_reader(stream).writer_version(), version); + + std::string bytes = marked; + put_u64(bytes, 16, 4); + reseal(bytes); + expect_format_error( + bytes, "that this release does not know; written by rabitqlib 0.9\\xff\\x5c" + ); + + bytes = marked; + put_u32(bytes, entry(1), 777); + reseal(bytes); + expect_format_error( + bytes, "is required but unknown to this release; written by rabitqlib 0.9\\xff\\x5c" + ); +} + +TEST(Format2ContainerTest, RejectsTruncatedTrailingAndCorruptFiles) { + const std::string good = valid_file(); + expect_format_error( + good + std::string(64, '\0'), + "IVF index file is 1408 bytes, but its sections end at 1344" + ); + // Truncated inside the padding before the empty last section. + expect_format_error(good.substr(0, 1336), "section kind 263 lies outside the file"); + + std::string bytes = good; + bytes[256 + 2] ^= 1; // inside the checksummed parameters + expect_format_error(bytes, "section kind 256 checksum mismatch (corrupt file)"); + + bytes = good; + bytes[320 + 2] ^= 1; // bulk data is not checksummed + std::istringstream stream(bytes); + EXPECT_NO_THROW(open_reader(stream)); +} + +} // namespace diff --git a/tests/unit/rabitqlib/index/historical_persistence_test.cpp b/tests/unit/rabitqlib/index/historical_persistence_test.cpp index e8d8156b..470497c4 100644 --- a/tests/unit/rabitqlib/index/historical_persistence_test.cpp +++ b/tests/unit/rabitqlib/index/historical_persistence_test.cpp @@ -3,20 +3,27 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include +#include #include #include "rabitqlib/core/metric.hpp" +#include "rabitqlib/index/format_error.hpp" #include "rabitqlib/index/hnsw/hnsw.hpp" +#include "rabitqlib/index/hnsw_index.hpp" #include "rabitqlib/index/ivf/initializer.hpp" #include "rabitqlib/index/ivf/ivf.hpp" +#include "rabitqlib/index/ivf_index.hpp" #include "rabitqlib/index/symqg/qg.hpp" +#include "rabitqlib/index/symqg_index.hpp" #include "rabitqlib/index/types.hpp" #include "temp_file.hpp" @@ -34,7 +41,7 @@ struct HistoricalFixtureCase { size_t padded_dim; size_t count = 33; size_t ivf_nprobe = 1; - bool resave_identical = false; // the current writer must reproduce the file + ivf::InitializerType initializer = ivf::InitializerType::Flat; }; void PrintTo(const HistoricalFixtureCase& value, std::ostream* output) { @@ -82,6 +89,8 @@ TEST_P(HistoricalPersistenceTest, LoadsSearchesResavesAndPreservesStateAfterFail const auto exercise = [&](auto& index, const auto& search) { const size_t removed = name.find("qg") == 0 ? 0 : 1; const auto check_counts = [&] { + // Earlier layouts do not record the seed, and migrating them invents none. + EXPECT_FALSE(index.seed().has_value()); EXPECT_EQ(index.num_stored_points(), count); EXPECT_EQ(index.num_points(), count - removed); EXPECT_GE(index.max_elements(), index.num_stored_points()); @@ -94,15 +103,18 @@ TEST_P(HistoricalPersistenceTest, LoadsSearchesResavesAndPreservesStateAfterFail search(); compare(); index.save(output.string().c_str()); - if (GetParam().resave_identical) { - EXPECT_TRUE(read_bytes(output) == read_bytes(path)); - } + // Every index saves format 2. + EXPECT_EQ(read_bytes(output).substr(0, 8), "RABQINDX"); index.load(output.string().c_str()); check_counts(); search(); compare(); + // Reading format 2 back and saving again reproduces the file. + const std::string saved = read_bytes(output); + index.save(output.string().c_str()); + EXPECT_TRUE(read_bytes(output) == saved); std::filesystem::resize_file(output, std::filesystem::file_size(output) - 1); - EXPECT_THROW(index.load(output.string().c_str()), std::runtime_error); + EXPECT_THROW(index.load(output.string().c_str()), FormatError); check_counts(); search(); compare(); @@ -112,7 +124,7 @@ TEST_P(HistoricalPersistenceTest, LoadsSearchesResavesAndPreservesStateAfterFail ivf::IVF index; exercise(index, [&] { EXPECT_EQ(index.padded_dim(), expected_padded_dim); - EXPECT_EQ(index.initializer_type(), ivf::InitializerType::Flat); + EXPECT_EQ(index.initializer_type(), GetParam().initializer); index.search_batch( queries.data(), nq, k, GetParam().ivf_nprobe, ids.data(), distances.data() ); @@ -133,6 +145,9 @@ TEST_P(HistoricalPersistenceTest, LoadsSearchesResavesAndPreservesStateAfterFail symqg::QuantizedGraph index; exercise(index, [&] { EXPECT_EQ(index.padded_dim(), expected_padded_dim); + // Earlier layouts do not record the construction settings either. + EXPECT_FALSE(index.ef_construction().has_value()); + EXPECT_FALSE(index.initialization().has_value()); index.set_ef(64); index.search_batch(queries.data(), nq, k, ids.data(), distances.data(), 1); }); @@ -164,10 +179,443 @@ INSTANTIATE_TEST_SUITE_P( PreIvfPerClusterStorage, HistoricalPersistenceTest, ::testing::Values( - HistoricalFixtureCase{"pre-ivf-per-cluster-storage", "ivf4_l2", 96, 130, 4, true}, - HistoricalFixtureCase{"pre-ivf-per-cluster-storage", "ivf32_l2", 96, 130, 4, true} + HistoricalFixtureCase{"pre-ivf-per-cluster-storage", "ivf4_l2", 96, 130, 4}, + HistoricalFixtureCase{"pre-ivf-per-cluster-storage", "ivf32_l2", 96, 130, 4} ), [](const auto& info) { return info.param.name; } ); + +// The last IVF layout before format 2: RABQIDX1 version 2 and the HNSW sidecar. +INSTANTIATE_TEST_SUITE_P( + V083, + HistoricalPersistenceTest, + ::testing::Values( + HistoricalFixtureCase{"v0.8.3", "ivf4_flat_l2", 96, 130, 4}, + HistoricalFixtureCase{ + "v0.8.3", "ivf7_flatrabitq_ip", 96, 130, 4, ivf::InitializerType::FlatRaBitQ}, + HistoricalFixtureCase{ + "v0.8.3", "ivf4_hnsw_l2", 96, 130, 4, ivf::InitializerType::HNSW}, + HistoricalFixtureCase{ + "v0.8.3", "ivf32_hnsw_ip", 96, 130, 4, ivf::InitializerType::HNSW}, + HistoricalFixtureCase{"v0.8.3", "ivf1_flat_matrix_l2", 96, 130, 4}, + HistoricalFixtureCase{"v0.8.3", "hnsw1_l2", 96, 130}, + HistoricalFixtureCase{"v0.8.3", "hnsw5_ip", 96, 130}, + HistoricalFixtureCase{"v0.8.3", "hnsw9_l2", 96, 130}, + HistoricalFixtureCase{"v0.8.3", "qg0_ip", 96, 130}, + HistoricalFixtureCase{"v0.8.3", "qg4_l2", 96, 130}, + HistoricalFixtureCase{"v0.8.3", "qg8_ip", 96, 130}, + HistoricalFixtureCase{"v0.8.3", "qg4_matrix_l2", 96, 130} + ), + [](const auto& info) { return info.param.name; } +); + +// Index format 2 as release v0.9.0 wrote it, read through the supported index classes. +// The metric ends each name; IVF-RaBitQ and HNSW-RaBitQ files have points 0 and 32 removed. +class Format2FixtureTest : public ::testing::TestWithParam {}; + +TEST_P(Format2FixtureTest, LoadsSearchesAndResavesWithRecordedSettings) { + namespace fs = std::filesystem; + const std::string name = GetParam(); + const fs::path directory = fs::path(RABITQ_TEST_FIXTURE_ROOT) / "v0.9.0"; + const auto path = (directory / (name + ".index")).string(); + std::ifstream expected(directory / (name + ".expected")); + ASSERT_TRUE(expected.is_open()); + size_t count = 0, dim = 0, nq = 0, k = 0; + expected >> count >> dim >> nq >> k; + ASSERT_EQ(count, 130U); + ASSERT_EQ(dim, 65U); + ASSERT_EQ(nq, 3U); + ASSERT_EQ(k, 5U); + std::vector queries(nq * dim), distances(nq * k), reference_distances(nq * k); + std::vector ids(nq * k), reference_ids(nq * k); + for (auto& value : queries) { + expected >> value; + } + for (size_t i = 0; i < ids.size(); ++i) { + expected >> reference_ids[i] >> reference_distances[i]; + } + ASSERT_TRUE(expected.good()); + const auto ends_with = [&name](const std::string& suffix) { + return name.size() >= suffix.size() && + name.compare(name.size() - suffix.size(), suffix.size(), suffix) == 0; + }; + const MetricType metric = + ends_with("_cosine") ? METRIC_COSINE : (ends_with("_ip") ? METRIC_IP : METRIC_L2); + const rabitq_test::TempFile output("format2_" + name); + const fs::path output_path = fs::u8path(output.path()); + // Loads the fixture, then the file it saves, and checks both. + const auto exercise = [&](const auto& load, const auto& check, size_t removed) { + for (const auto& source : {path, output.path()}) { + const auto index = load(source.c_str()); + EXPECT_EQ(index.dim(), dim); + EXPECT_EQ(index.metric(), metric); + ASSERT_TRUE(index.seed().has_value()); + EXPECT_EQ(*index.seed(), 42U); + EXPECT_EQ(index.num_stored_points(), count); + EXPECT_EQ(index.num_points(), count - removed); + check(index); + EXPECT_EQ(ids, reference_ids); + for (size_t i = 0; i < ids.size(); ++i) { + EXPECT_NEAR( + distances[i], + reference_distances[i], + 2e-4F * std::max(1.0F, std::abs(reference_distances[i])) + ); + } + if (source == path) { + index.save(output.path().c_str()); + const std::string saved = read_bytes(output_path); + EXPECT_EQ(saved.substr(0, 8), "RABQINDX"); + index.save(output.path().c_str()); + EXPECT_TRUE(read_bytes(output_path) == saved); + } + } + // The HNSW routing graph stays inside the file. + EXPECT_FALSE(fs::exists(path + ".hnsw")); + EXPECT_FALSE(fs::exists(fs::u8path(output.path() + ".hnsw"))); + }; + if (name.find("ivf") == 0) { + const auto routing = + name.find("_flatrabitq_") != std::string::npos + ? ivf::Routing::FlatRaBitQ + : (name.find("_hnsw_") != std::string::npos ? ivf::Routing::HNSW + : ivf::Routing::Flat); + exercise( + [](const char* file) { return IvfIndex::load(file); }, + [&](const IvfIndex& index) { + EXPECT_EQ(index.routing(), routing); + IvfSearchOptions options; + options.nprobe = 4; + index.search(queries.data(), nq, k, ids.data(), distances.data(), options); + }, + 2 + ); + } else { + GraphSearchOptions options; + options.ef_search = 64; + if (name.find("hnsw") == 0) { + exercise( + [](const char* file) { return HnswIndex::load(file); }, + [&](const HnswIndex& index) { + EXPECT_EQ(index.M(), 8U); + EXPECT_EQ(index.ef_construction(), 64U); + index.search( + queries.data(), nq, k, ids.data(), distances.data(), options + ); + }, + 2 + ); + } else { + exercise( + [](const char* file) { return SymqgIndex::load(file); }, + [&](const SymqgIndex& index) { + ASSERT_TRUE(index.ef_construction().has_value()); + EXPECT_EQ(*index.ef_construction(), 64U); + ASSERT_TRUE(index.init().has_value()); + EXPECT_EQ(*index.init(), symqg::QGInitialization::PiPNN); + index.search( + queries.data(), nq, k, ids.data(), distances.data(), options + ); + }, + 0 + ); + } + } +} + +INSTANTIATE_TEST_SUITE_P( + V090, + Format2FixtureTest, + ::testing::Values( + "ivf4_flat_l2", + "ivf7_flatrabitq_cosine", + "ivf32_hnsw_ip", + "ivf1_flat_matrix_l2", + "hnsw1_l2", + "hnsw5_cosine", + "hnsw9_ip", + "qg32_ip", + "qg4_cosine", + "qg8_l2", + "qg4_matrix_l2" + ), + [](const auto& info) { return std::string(info.param); } +); +// Damaged headers of the earlier layouts that pass the size checks raise FormatError +// rather than the errors of the code that would use them. +TEST(HistoricalPersistenceTest, MalformedEarlierHeadersRaiseFormatError) { + namespace fs = std::filesystem; + const fs::path path = + fs::temp_directory_path() / rabitq_test::process_unique("historical_header"); + struct Case { + const char* fixture; + size_t keep_bytes; // 0 keeps the whole file + std::vector> patches; // little-endian u64 fields + const char* message; + }; + const uint64_t huge = uint64_t{1} << 62; + const Case cases[] = { + // RABQIDX1 v2: the stream fails inside the fixed header. + {"ivf4_flat_l2", 20, {}, "IVF index file is truncated"}, + // An FHT/Kac dimension below 64 at offset 36. + {"ivf4_flat_l2", + 0, + {{36, 32}}, + "Invalid IVF rotator dimensions: Unsupported dimension for FhtKacRotator"}, + // SymphonyQG quantized layout: dimension at 28, padded dimension at 36. + {"qg4_l2", + 0, + {{28, 33}}, + "QuantizedGraph file is invalid: Unsupported dimension for FhtKacRotator"}, + {"qg4_l2", + 0, + {{28, huge}, {36, huge}}, + "QuantizedGraph file describes records too large to address"}, + // The headerless raw layout: dimension at 16, padded dimension at 24. + {"qg0_ip", + 0, + {{16, huge}, {24, huge}}, + "QuantizedGraph file describes records too large to address"}, + }; + for (const auto& c : cases) { + SCOPED_TRACE(c.message); + fs::copy_file( + fs::path(RABITQ_TEST_FIXTURE_ROOT) / "v0.8.3" / + (std::string(c.fixture) + ".index"), + path, + fs::copy_options::overwrite_existing + ); + if (c.keep_bytes != 0) { + fs::resize_file(path, c.keep_bytes); + } + { + std::fstream file(path, std::ios::binary | std::ios::in | std::ios::out); + for (const auto& [offset, value] : c.patches) { + file.seekp(static_cast(offset)); + for (size_t i = 0; i < sizeof(uint64_t); ++i) { + file.put(static_cast(value >> (8 * i))); + } + } + } + const std::string file = path.string(); + try { + if (c.fixture[0] == 'i') { + ivf::IVF index; + index.load(file.c_str()); + } else { + symqg::QuantizedGraph index; + index.load(file.c_str()); + } + ADD_FAILURE() << "accepted"; + } catch (const FormatError& error) { EXPECT_STREQ(error.what(), c.message); } + } + fs::remove(path); +} + +// Truncated files of the earlier layouts raise FormatError like format-2 files. +TEST(HistoricalPersistenceTest, TruncatedEarlierFilesRaiseFormatError) { + namespace fs = std::filesystem; + const fs::path path = + fs::temp_directory_path() / rabitq_test::process_unique("historical_truncated"); + for (const char* name : {"ivf4_flat_l2", "hnsw1_l2", "qg4_l2"}) { + SCOPED_TRACE(name); + fs::copy_file( + fs::path(RABITQ_TEST_FIXTURE_ROOT) / "v0.8.3" / (std::string(name) + ".index"), + path, + fs::copy_options::overwrite_existing + ); + fs::resize_file(path, fs::file_size(path) / 2); + const std::string file = path.string(); + if (name[0] == 'i') { + ivf::IVF index; + EXPECT_THROW(index.load(file.c_str()), FormatError); + } else if (name[0] == 'h') { + hnsw::HierarchicalNSW index; + EXPECT_THROW(index.load(file.c_str()), FormatError); + } else { + symqg::QuantizedGraph index; + EXPECT_THROW(index.load(file.c_str()), FormatError); + } + } + // A metric byte that is neither L2 nor IP, at offset 61 of an RABQIDX1 v2 file. + fs::copy_file( + fs::path(RABITQ_TEST_FIXTURE_ROOT) / "v0.8.3" / "ivf4_flat_l2.index", + path, + fs::copy_options::overwrite_existing + ); + { + std::fstream file(path, std::ios::binary | std::ios::in | std::ios::out); + file.seekp(61); + file.put(static_cast(2)); + } + ivf::IVF bad_metric; + try { + bad_metric.load(path.string().c_str()); + ADD_FAILURE() << "an invalid metric was loaded"; + } catch (const FormatError& error) { + EXPECT_STREQ(error.what(), "Invalid IVF index metadata"); + } + // Metric byte 2, METRIC_COSINE in memory, never appears in these layouts. + const struct { + const char* name; + std::streamoff offset; + const char* message; + } graph_metrics[] = { + {"hnsw5_ip", 48, "HNSW index file is invalid or truncated"}, + {"qg8_ip", 49, "Metric type must be METRIC_L2 or METRIC_IP"}, + {"qg0_ip", 37, "Metric type must be METRIC_L2 or METRIC_IP"}, + }; + for (const auto& c : graph_metrics) { + SCOPED_TRACE(c.name); + fs::copy_file( + fs::path(RABITQ_TEST_FIXTURE_ROOT) / "v0.8.3" / + (std::string(c.name) + ".index"), + path, + fs::copy_options::overwrite_existing + ); + { + std::fstream file(path, std::ios::binary | std::ios::in | std::ios::out); + file.seekg(c.offset); + ASSERT_EQ(file.get(), 1); // the IP metric byte + file.seekp(c.offset); + file.put(static_cast(2)); + } + try { + if (c.name[0] == 'h') { + hnsw::HierarchicalNSW index; + index.load(path.string().c_str()); + } else { + symqg::QuantizedGraph index; + index.load(path.string().c_str()); + } + ADD_FAILURE() << "an invalid metric was loaded"; + } catch (const FormatError& error) { EXPECT_STREQ(error.what(), c.message); } + } + fs::remove(path); + ivf::IVF missing; + try { + missing.load((path.string() + ".missing").c_str()); + ADD_FAILURE() << "a missing file was loaded"; + } catch (const FormatError&) { + ADD_FAILURE() << "a missing file is not a format error"; + } catch (const std::runtime_error&) { // "Cannot open IVF index file" + } +} + +// The checks of the SymphonyQG layout before format 2, on a copy of its v0.8.3 file. +TEST(HistoricalPersistenceTest, RejectsMalformedEarlierGraphFilesWithoutChangingTarget) { + namespace fs = std::filesystem; + const fs::path fixture = fs::path(RABITQ_TEST_FIXTURE_ROOT) / "v0.8.3" / "qg4_l2.index"; + const fs::path path = + fs::temp_directory_path() / rabitq_test::process_unique("historical_qg_malformed"); + symqg::QuantizedGraph target(65, 64, 32, METRIC_IP); + const auto load_patched = [&](std::streamoff offset, size_t value) { + fs::copy_file(fixture, path, fs::copy_options::overwrite_existing); + { + std::fstream file(path, std::ios::binary | std::ios::in | std::ios::out); + ASSERT_TRUE(file.is_open()); + file.seekp(offset); + file.write(reinterpret_cast(&value), sizeof(value)); + ASSERT_TRUE(file.good()); + } + target.load(path.string().c_str()); + }; + // After the magic and version: point count, degree, dimension, padded dimension. + constexpr std::streamoff kPointCountOffset = sizeof(uint64_t) + sizeof(uint32_t); + constexpr std::streamoff kPaddedDimensionOffset = + kPointCountOffset + 3 * sizeof(size_t); + try { + load_patched(kPaddedDimensionOffset, 100); + ADD_FAILURE() << "an invalid padded dimension was accepted"; + } catch (const std::runtime_error& error) { + EXPECT_STREQ(error.what(), "QuantizedGraph file has an invalid padded dimension"); + } + EXPECT_THROW( + load_patched(kPointCountOffset, std::numeric_limits::max()), FormatError + ); + EXPECT_EQ(target.num_vertices(), 65U); + EXPECT_EQ(target.metric_type(), METRIC_IP); + fs::remove(path); +} + +// The checks of the HNSW-RaBitQ layout before format 2, on a copy of its v0.8.3 file. +TEST(HistoricalPersistenceTest, RejectsMalformedEarlierHnswFilesWithoutChangingTarget) { + namespace fs = std::filesystem; + const fs::path fixture = + fs::path(RABITQ_TEST_FIXTURE_ROOT) / "v0.8.3" / "hnsw5_ip.index"; + const fs::path path = fs::temp_directory_path() / + rabitq_test::process_unique("historical_hnsw_malformed"); + hnsw::HierarchicalNSW target; + target.load(fixture.string().c_str()); + const auto expect_rejected = [&](const auto& damage) { + fs::copy_file(fixture, path, fs::copy_options::overwrite_existing); + damage(); + try { + target.load(path.string().c_str()); + ADD_FAILURE() << "a damaged file was accepted"; + } catch (const std::runtime_error& error) { + EXPECT_STREQ(error.what(), "HNSW index file is invalid or truncated"); + } + EXPECT_EQ(target.num_stored_points(), 130U); + }; + // The capacity is the first field. + expect_rejected([&] { + std::fstream file(path, std::ios::binary | std::ios::in | std::ios::out); + const size_t capacity = 1; + file.write(reinterpret_cast(&capacity), sizeof(capacity)); + }); + expect_rejected([&] { fs::resize_file(path, fs::file_size(path) - 1); }); + fs::remove(path); +} + +// Files before format 2 keep the HNSW routing graph in .hnsw; loading reads it +// from there, through the same path conversion as the index file. +TEST(HistoricalPersistenceTest, LoadsTheHnswSidecarOfEarlierLayouts) { + namespace fs = std::filesystem; + const fs::path fixture = + fs::path(RABITQ_TEST_FIXTURE_ROOT) / "v0.8.3" / "ivf4_hnsw_l2.index"; + const fs::path directory = + fs::temp_directory_path() / + fs::u8path(rabitq_test::process_unique(u8"historical_sidecar_\u6d4b\u8bd5")); + fs::create_directories(directory); + const fs::path index_path = directory / fs::u8path(u8"\u7d22\u5f15.index"); + const fs::path sidecar = fs::path(index_path.native() + fs::path(".hnsw").native()); + fs::copy_file(fixture, index_path); + const std::string path = index_path.u8string(); + + ivf::IVF index; + try { + index.load(path.c_str()); + ADD_FAILURE() << "an HNSW-routed file without its sidecar was accepted"; + } catch (const std::runtime_error& error) { + EXPECT_STREQ(error.what(), "Cannot open HNSW centroid sidecar"); + } + + // A graph of another dimension does not fit the index. + { + std::vector centroids(4 * 128, 0.5F); + ivf::HNSWInitializer other(128, 4); + other.add_vectors(centroids.data(), 1); + std::ofstream output(sidecar, std::ios::binary); + other.write(output); + } + try { + index.load(path.c_str()); + ADD_FAILURE() << "a mismatched sidecar was accepted"; + } catch (const std::runtime_error& error) { + EXPECT_STREQ(error.what(), "HNSW centroid layout does not match IVF dimension"); + } + + fs::copy_file( + fs::path(fixture.native() + fs::path(".hnsw").native()), + sidecar, + fs::copy_options::overwrite_existing + ); + ASSERT_NO_THROW(index.load(path.c_str())); + EXPECT_EQ(index.initializer_type(), ivf::InitializerType::HNSW); + EXPECT_EQ(index.num_points(), 129U); + fs::remove_all(directory); +} + } // namespace } // namespace rabitqlib 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..4d744d51 --- /dev/null +++ b/tests/unit/rabitqlib/index/hnsw_index_test.cpp @@ -0,0 +1,611 @@ +#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, LoadsAnUntrainedFileSavedBy07) { + // The C++ API of releases before 0.8 could save an index before training it. The + // file has no centroids and no seed, so the first add cannot train it. + constexpr size_t kFileDim = 65; + const auto path = + std::filesystem::path(RABITQ_TEST_FIXTURE_ROOT) / "v0.7.2" / "hnsw4_empty_l2.index"; + HnswIndex index = HnswIndex::load(path.string().c_str()); + EXPECT_FALSE(index.is_trained()); + EXPECT_FALSE(index.seed().has_value()); + EXPECT_EQ(index.dim(), kFileDim); + EXPECT_EQ(index.nbits(), 4U); + EXPECT_EQ(index.metric(), METRIC_L2); + EXPECT_EQ(index.capacity(), 130U); + EXPECT_EQ(index.num_points(), 0U); + EXPECT_EQ(index.num_clusters(), 16U); + + std::mt19937 rng(21); + std::normal_distribution normal; + std::vector data(kNumPoints * kFileDim); + for (auto& value : data) { + value = normal(rng); + } + const auto message = [](const std::string& operation) { + return "HnswIndex loaded from an untrained file must be trained before " + + operation + "; call train or set_centroids"; + }; + expect_error( + [&] { index.add(data.data(), kNumPoints, single_thread()); }, message("add") + ); + Id ids[1]; + const Id remove_ids[] = {0}; + expect_error( + [&] { index.search(data.data(), 1, 1, ids, nullptr); }, message("search") + ); + expect_error([&] { index.remove(remove_ids, 1); }, message("remove")); + const rabitq_test::TempFile file("hnsw_index_untrained_07.index"); + expect_error( + [&] { index.save(file.path().c_str()); }, message("save") + ); + EXPECT_EQ(index.num_points(), 0U); + + index.train(data.data(), kNumPoints, 1); + EXPECT_EQ(index.num_clusters(), 16U); + EXPECT_EQ(index.add(data.data(), kNumPoints, single_thread()), 0); + const auto expected = search(index, data.data(), 3, 5); + EXPECT_EQ(count_found(expected), 15U); + index.save(file.path().c_str()); + const HnswIndex reloaded = HnswIndex::load(file.path().c_str()); + EXPECT_TRUE(reloaded.is_trained()); + EXPECT_EQ(reloaded.num_points(), kNumPoints); + EXPECT_EQ(reloaded.num_clusters(), 16U); + EXPECT_EQ(search(reloaded, data.data(), 3, 5).ids, expected.ids); + + // Setting centroids makes it trained as well. + HnswIndex other = HnswIndex::load(path.string().c_str()); + other.set_centroids(data.data()); // the first 16 points + EXPECT_EQ(other.add(data.data(), kNumPoints, single_thread()), 0); + EXPECT_EQ(other.num_points(), kNumPoints); +} + +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 diff --git a/tests/unit/rabitqlib/index/hnsw_sidecar_test.cpp b/tests/unit/rabitqlib/index/hnsw_sidecar_test.cpp index 3937f905..1ab304ab 100644 --- a/tests/unit/rabitqlib/index/hnsw_sidecar_test.cpp +++ b/tests/unit/rabitqlib/index/hnsw_sidecar_test.cpp @@ -6,15 +6,14 @@ #include #include #include -#include #include -#include #include #include #include #include #include +#include "format2_file.hpp" #include "rabitqlib/core/metric.hpp" #include "rabitqlib/core/rotator.hpp" #include "rabitqlib/index/ivf/initializer.hpp" @@ -75,8 +74,11 @@ struct Fixture { ); index.construct(data.data(), data.data(), ids.data(), false, 1); index.save(path.c_str()); - std::ifstream file(path + ".hnsw", std::ios::binary); - original.assign(std::istreambuf_iterator(file), {}); + // The routing graph is the HNSW-routing section of the format-2 index file. + const std::string graph = rabitq_test::read_format2_section( + path, rabitq_test::format2::IndexKind::Ivf, rabitq_test::kIvfSections, 260 + ); + original.assign(graph.begin(), graph.end()); level0_record_bytes = read_at(original, 3 * sizeof(size_t)); max_m = read_at(original, kMaxMOffset); max_m0 = read_at(original, kMaxMOffset + sizeof(size_t)); @@ -104,15 +106,20 @@ struct Fixture { ~Fixture() { std::error_code ignored; std::filesystem::remove(path, ignored); - std::filesystem::remove(path + ".hnsw", ignored); } + // Store `bytes` as the index file's routing graph. void save(const std::vector& bytes) const { - std::ofstream file(path + ".hnsw", std::ios::binary | std::ios::trunc); - file.write(bytes.data(), static_cast(bytes.size())); + rabitq_test::replace_format2_section( + path, + rabitq_test::format2::IndexKind::Ivf, + rabitq_test::kIvfSections, + 260, + std::string(bytes.begin(), bytes.end()) + ); } }; -TEST(IvfHnswSidecarGraphTest, PublicLoadRejectsCorruptStructureAndCanRetry) { +TEST(IvfHnswRoutingGraphTest, PublicLoadRejectsCorruptStructureAndCanRetry) { for (const auto metric : {METRIC_L2, METRIC_IP}) { Fixture fixture(metric); const auto reject = [&](const char* name, auto corrupt, const char* message) { @@ -123,7 +130,7 @@ TEST(IvfHnswSidecarGraphTest, PublicLoadRejectsCorruptStructureAndCanRetry) { ivf::IVF loaded; try { loaded.load(fixture.path.c_str()); - FAIL() << "damaged sidecar was accepted"; + FAIL() << "damaged routing graph was accepted"; } catch (const std::runtime_error& error) { EXPECT_STREQ(error.what(), message); } @@ -257,7 +264,7 @@ TEST(IvfHnswSidecarGraphTest, PublicLoadRejectsCorruptStructureAndCanRetry) { reject( "truncated upper length", [&](auto& b) { b.resize(fixture.upper_offsets.back() + 2); }, - "Truncated HNSW centroid sidecar" + "Truncated HNSW centroid graph" ); reject( "truncated upper links", @@ -287,7 +294,7 @@ TEST(IvfHnswSidecarGraphTest, PublicLoadRejectsCorruptStructureAndCanRetry) { reject( "truncated header", [](auto& b) { b.resize(4); }, - "Truncated HNSW centroid sidecar" + "Truncated HNSW centroid graph" ); reject( "trailing byte", @@ -297,7 +304,7 @@ TEST(IvfHnswSidecarGraphTest, PublicLoadRejectsCorruptStructureAndCanRetry) { } } -TEST(IvfHnswSidecarGraphTest, DisconnectedGraphCannotReadEmptyResults) { +TEST(IvfHnswRoutingGraphTest, DisconnectedGraphCannotReadEmptyResults) { for (const auto metric : {METRIC_L2, METRIC_IP}) { Fixture fixture(metric); auto bytes = fixture.original; diff --git a/tests/unit/rabitqlib/index/hnsw_test.cpp b/tests/unit/rabitqlib/index/hnsw_test.cpp index 1d778ff1..d91e91bd 100644 --- a/tests/unit/rabitqlib/index/hnsw_test.cpp +++ b/tests/unit/rabitqlib/index/hnsw_test.cpp @@ -21,6 +21,8 @@ #include #include +#include "cosine.hpp" +#include "format2_file.hpp" #include "rabitqlib/clustering/rabitqkmeans.hpp" #include "rabitqlib/core/encoder.hpp" #include "rabitqlib/core/metric.hpp" @@ -679,6 +681,33 @@ TEST(HnswResizeTest, GrowsCapacityAndKeepsTheGraph) { } } +TEST(HnswResizeTest, ShrinksUnusedCapacityAndKeepsSearchResults) { + constexpr size_t kBuilt = 128; + AddFixture fixture(kBuilt, 37); + + HierarchicalNSW index(kBuilt, AddFixture::kDim, 4, 8, 50); + index.construct( + 1, + fixture.centroid.data(), + kBuilt, + fixture.data.data(), + fixture.cluster_ids.data(), + 1, + false + ); + const auto expected = index.search(fixture.data.data(), kBuilt, 4, kBuilt, 1); + + // Grow past the 2 MiB level-0 allocation threshold, then shrink back to the + // stored count. + for (const size_t capacity : {size_t{32768}, kBuilt + 1, kBuilt}) { + SCOPED_TRACE(capacity); + index.resize(capacity); + EXPECT_EQ(index.max_elements(), capacity); + EXPECT_EQ(index.num_points(), kBuilt); + EXPECT_EQ(index.search(fixture.data.data(), kBuilt, 4, kBuilt, 1), expected); + } +} + TEST(HnswResizeTest, SurvivesSaveAndLoad) { constexpr size_t kBuilt = 64; constexpr size_t kTotal = 96; @@ -907,7 +936,7 @@ TEST_F(HnswSaveTest, ReportsWriteOrCloseFailure) { index_.save("/dev/full"); FAIL() << "Saving to a full destination must fail"; } catch (const std::runtime_error& error) { - EXPECT_STREQ(error.what(), "HNSW failed to write index file"); + EXPECT_STREQ(error.what(), "HNSW index file cannot be written"); } } @@ -926,25 +955,181 @@ TEST_F(HnswSaveTest, SuccessfulSavePreservesSearchAfterLoading) { TEST_F(HnswSaveTest, RejectsPointCountLargerThanCapacity) { index_.save(path_.c_str()); - { - std::fstream file(path_, std::ios::binary | std::ios::in | std::ios::out); - const size_t invalid_capacity = 1; - file.write( - reinterpret_cast(&invalid_capacity), sizeof(invalid_capacity) - ); - ASSERT_TRUE(file.good()); - } + // The capacity is the first field of the graph parameters. + std::string params = rabitq_test::read_format2_section( + path_, rabitq_test::format2::IndexKind::Hnsw, rabitq_test::kHnswSections, 512 + ); + rabitq_test::format2::put_u64(reinterpret_cast(params.data()), 1); + rabitq_test::replace_format2_section( + path_, + rabitq_test::format2::IndexKind::Hnsw, + rabitq_test::kHnswSections, + 512, + params + ); HierarchicalNSW loaded; try { loaded.load(path_.c_str()); FAIL() << "Invalid HNSW point count must be rejected"; } catch (const std::runtime_error& error) { - EXPECT_NE(std::string(error.what()).find("HNSW"), std::string::npos); + EXPECT_STREQ(error.what(), "HNSW index file has invalid graph parameters"); } } -TEST_F(HnswSaveTest, RejectsTruncatedRotatorWithoutLosingExistingIndex) { +// A graph with upper layers, saved in format 2 with a known seed. +class HnswFormat2Test : public ::testing::Test { + protected: + static constexpr size_t kDim = 64; + static constexpr size_t kCount = 200; + static constexpr size_t kSeed = 9; + std::vector data_{std::vector(kCount * kDim)}; + std::vector centroids_{std::vector(2 * kDim)}; + std::vector cluster_ids_{std::vector(kCount)}; + HierarchicalNSW index_{kCount, kDim, 5, 4, 16, kSeed, METRIC_IP}; + std::string path_; + + void SetUp() override { + path_ = ::testing::TempDir() + "rabitq_hnsw_format2_" + + ::testing::UnitTest::GetInstance()->current_test_info()->name() + ".index"; + std::mt19937 generator(3); + std::normal_distribution normal; + for (auto& value : data_) { + value = normal(generator); + } + for (size_t i = 0; i < kCount; ++i) { + cluster_ids_[i] = static_cast(i % 2); + } + index_.construct( + 2, centroids_.data(), kCount, data_.data(), cluster_ids_.data(), 1, false + ); + const PID removed = 5; + index_.remove(&removed, 1); + index_.save(path_.c_str()); + } + + void TearDown() override { std::remove(path_.c_str()); } + + [[nodiscard]] rabitq_test::Format2Contents contents() const { + return rabitq_test::read_format2_file( + path_, rabitq_test::format2::IndexKind::Hnsw, rabitq_test::kHnswSections + ); + } + + void expect_rejected( + const rabitq_test::Format2Contents& damaged, const std::string& message + ) { + rabitq_test::write_format2_file(path_, damaged); + HierarchicalNSW loaded; + try { + loaded.load(path_.c_str()); + ADD_FAILURE() << "accepted: " << message; + } catch (const std::runtime_error& error) { + EXPECT_EQ(std::string(error.what()), message); + } + } +}; + +TEST_F(HnswFormat2Test, RoundTripsTheGraphAndRecordsTheSeed) { + const auto saved = contents(); + EXPECT_EQ(saved.header.index_kind, rabitq_test::format2::IndexKind::Hnsw); + EXPECT_EQ(saved.header.metric, rabitq_test::format2::Metric::InnerProduct); + EXPECT_EQ(saved.header.code_bits, 5U); + EXPECT_EQ(saved.header.num_points, kCount); + ASSERT_TRUE(saved.header.seed.has_value()); + EXPECT_EQ(*saved.header.seed, kSeed); + std::vector kinds; + for (const auto& entry : saved.sections) { + kinds.push_back(entry.first.kind); + } + EXPECT_EQ(kinds, (std::vector{1, 512, 513, 514, 515, 516})); + EXPECT_FALSE(rabitq_test::Format2Contents(saved).bytes(516).empty()); // upper layers + + HierarchicalNSW loaded; + loaded.load(path_.c_str()); + EXPECT_EQ(loaded.seed(), std::optional(kSeed)); + EXPECT_EQ(loaded.num_points(), kCount - 1); + EXPECT_EQ(loaded.max_elements(), kCount); + EXPECT_EQ( + loaded.search(data_.data(), 4, 5, 32, 1), index_.search(data_.data(), 4, 5, 32, 1) + ); + const std::string first = rabitq_test::Format2Contents(saved).bytes(514); + loaded.save(path_.c_str()); + EXPECT_EQ(contents().bytes(514), first); +} + +TEST_F(HnswFormat2Test, RejectsContentsThatDoNotFitTheGraph) { + const auto saved = contents(); + auto damaged = saved; + damaged.remove(515); + expect_rejected(damaged, "HNSW index file has no section kind 515"); + + damaged = saved; + damaged.bytes(516).pop_back(); + const size_t upper_bytes = rabitq_test::Format2Contents(saved).bytes(516).size(); + expect_rejected( + damaged, + "HNSW index file section kind 516 has " + std::to_string(upper_bytes - 1) + + " bytes; expected " + std::to_string(upper_bytes) + ); + + damaged = saved; + rabitq_test::format2::put_u32( + reinterpret_cast(damaged.bytes(515).data()), 1000 + ); + expect_rejected(damaged, "HNSW index file has a point above the maximum level"); + + damaged = saved; + rabitq_test::format2::put_u32( + reinterpret_cast(damaged.bytes(512).data()) + 60, 1 + ); + expect_rejected(damaged, "HNSW index file has invalid graph parameters"); + + damaged = saved; + damaged.bytes(515).resize(4 * (kCount - 1)); + expect_rejected( + damaged, + "HNSW index file section kind 515 has " + std::to_string(4 * (kCount - 1)) + + " bytes; expected " + std::to_string(4 * kCount) + ); + + // A neighbor beyond the stored points, in the first base-layer record. + damaged = saved; + char* record = damaged.bytes(514).data(); + rabitq_test::format2::put_u32(reinterpret_cast(record), 1); // one neighbor + rabitq_test::format2::put_u32(reinterpret_cast(record) + 4, kCount); + expect_rejected(damaged, "HNSW index file is invalid or truncated"); +} + +TEST_F(HnswFormat2Test, UnknownReadOnlyFeaturesAllowSearchButNoChanges) { + rabitq_test::patch_format2_header(path_, 24, 1, 8); // an unknown ro_compat bit + HierarchicalNSW loaded; + ASSERT_NO_THROW(loaded.load(path_.c_str())); + EXPECT_EQ( + loaded.search(data_.data(), 2, 5, 32, 1), index_.search(data_.data(), 2, 5, 32, 1) + ); + const auto expect_refused = [](const auto& operation, const std::string& name) { + try { + operation(); + ADD_FAILURE() << name << " was allowed"; + } catch (const std::logic_error& error) { + EXPECT_EQ( + std::string(error.what()), + "HNSW index was loaded from a file with features this release cannot " + "update, so it cannot " + + name + ); + } + }; + const PID label = 7; + expect_refused([&] { loaded.add(data_.data(), 1, &label, false, 1); }, "add"); + expect_refused([&] { loaded.resize(kCount + 10); }, "resize"); + expect_refused([&] { loaded.remove(&label, 1); }, "remove"); + expect_refused([&] { loaded.save((path_ + ".copy").c_str()); }, "save"); + EXPECT_EQ(loaded.num_points(), kCount - 1); +} + +TEST_F(HnswSaveTest, RejectsTruncatedFileWithoutLosingExistingIndex) { index_.save(path_.c_str()); HierarchicalNSW loaded; loaded.load(path_.c_str()); @@ -953,13 +1138,156 @@ TEST_F(HnswSaveTest, RejectsTruncatedRotatorWithoutLosingExistingIndex) { std::filesystem::resize_file(path_, std::filesystem::file_size(path_) - 1); try { loaded.load(path_.c_str()); - FAIL() << "Truncated HNSW rotator must be rejected"; + FAIL() << "A truncated HNSW file must be rejected"; } catch (const std::runtime_error& error) { EXPECT_NE(std::string(error.what()).find("HNSW"), std::string::npos); } EXPECT_EQ(loaded.search(data_.data(), 1, 2, kCount, 1), expected); } +TEST(HnswCosineTest, MatchesInnerProductOverNormalizedVectors) { + constexpr size_t kDim = 65, kCount = 200, kQueries = 4, kClusters = 4; + std::mt19937 generator(41); + std::normal_distribution normal; + std::vector raw((kCount + kQueries) * kDim); + for (auto& value : raw) { + value = normal(generator); + } + const auto rows = rabitq_test::rescaled_rows(raw, kDim); + const std::vector points(rows.begin(), rows.begin() + kCount * kDim); + const std::vector queries(rows.begin() + kCount * kDim, rows.end()); + const auto unit_points = rabitq_test::normalized_rows(points, kDim); + const auto unit_queries = rabitq_test::normalized_rows(queries, kDim); + auto cp = default_training_parameters(METRIC_COSINE, 7); + cp.num_threads = 1; + const rabitq_test::TempFile cosine_file("rabitq_hnsw_cosine.index"); + const rabitq_test::TempFile ip_file("rabitq_hnsw_cosine_ip.index"); + const rabitq_test::TempFile damaged_file("rabitq_hnsw_cosine_damaged.index"); + for (const size_t total_bits : {size_t{1}, size_t{5}}) { + SCOPED_TRACE(total_bits); + HierarchicalNSW cosine(kCount, kDim, total_bits, 8, 50, 7, METRIC_COSINE); + cosine.train(kClusters, kCount, points.data(), cp); + cosine.add(points.data(), kCount, nullptr, false, 1); + HierarchicalNSW ip(kCount, kDim, total_bits, 8, 50, 7, METRIC_IP); + ip.train(kClusters, kCount, unit_points.data(), cp); + ip.add(unit_points.data(), kCount, nullptr, false, 1); + EXPECT_EQ(cosine.metric_type(), METRIC_COSINE); + + cosine.save(cosine_file.path().c_str()); + ip.save(ip_file.path().c_str()); + rabitq_test::expect_same_sections_except_metric( + cosine_file.path(), + ip_file.path(), + rabitq_test::format2::IndexKind::Hnsw, + rabitq_test::kHnswSections + ); + HierarchicalNSW loaded; + loaded.load(cosine_file.path().c_str()); + EXPECT_EQ(loaded.metric_type(), METRIC_COSINE); + const auto expected = ip.search(unit_queries.data(), kQueries, 10, 64, 1); + EXPECT_EQ(cosine.search(queries.data(), kQueries, 10, 64, 1), expected); + EXPECT_EQ(loaded.search(queries.data(), kQueries, 10, 64, 2), expected); + + // A failed load keeps the metric; loading an inner-product file replaces it. + { + std::ofstream damaged(damaged_file.path(), std::ios::binary); + damaged << "not an index"; + } + EXPECT_THROW(loaded.load(damaged_file.path().c_str()), std::runtime_error); + EXPECT_EQ(loaded.metric_type(), METRIC_COSINE); + loaded.load(ip_file.path().c_str()); + EXPECT_EQ(loaded.metric_type(), METRIC_IP); + EXPECT_EQ( + loaded.search(queries.data(), kQueries, 10, 64, 1), + ip.search(queries.data(), kQueries, 10, 64, 1) + ); + } + + // construct and set_centroids scale given centroids to unit length, as the data is, + // so centroids far from the unit sphere match their scaled copies. + std::vector centroids(points.begin(), points.begin() + (kClusters * kDim)); + for (auto& value : centroids) { + value *= 100.0F; // like cluster means of unscaled data + } + const auto unit_centroids = rabitq_test::normalized_rows(centroids, kDim); + std::vector cosine_ids(kCount); + for (size_t i = 0; i < kCount; ++i) { + cosine_ids[i] = static_cast(i % kClusters); + } + std::vector ip_ids = cosine_ids; + HierarchicalNSW cosine(kCount, kDim, 5, 8, 50, 7, METRIC_COSINE); + cosine.construct( + kClusters, centroids.data(), kCount, points.data(), cosine_ids.data(), 1 + ); + HierarchicalNSW ip(kCount, kDim, 5, 8, 50, 7, METRIC_IP); + ip.construct( + kClusters, unit_centroids.data(), kCount, unit_points.data(), ip_ids.data(), 1 + ); + const auto expected = ip.search(unit_queries.data(), kQueries, 10, 64, 1); + EXPECT_EQ(cosine.search(queries.data(), kQueries, 10, 64, 1), expected); + + HierarchicalNSW given(kCount, kDim, 5, 8, 50, 7, METRIC_COSINE); + given.set_centroids(kClusters, centroids.data()); + given.add(points.data(), kCount, cosine_ids.data(), false, 1); + HierarchicalNSW given_ip(kCount, kDim, 5, 8, 50, 7, METRIC_IP); + given_ip.set_centroids(kClusters, unit_centroids.data()); + given_ip.add(unit_points.data(), kCount, ip_ids.data(), false, 1); + given.save(cosine_file.path().c_str()); + given_ip.save(ip_file.path().c_str()); + rabitq_test::expect_same_sections_except_metric( + cosine_file.path(), + ip_file.path(), + rabitq_test::format2::IndexKind::Hnsw, + rabitq_test::kHnswSections + ); + EXPECT_EQ( + given.search(queries.data(), kQueries, 10, 64, 1), + given_ip.search(unit_queries.data(), kQueries, 10, 64, 1) + ); +} + +TEST(HnswCosineTest, ChecksTrainingDataAndEstimatesZeroVectors) { + constexpr size_t kDim = 64, kCount = 100; + std::mt19937 generator(45); + std::normal_distribution normal; + std::vector points(kCount * kDim); + for (auto& value : points) { + value = normal(generator); + } + auto bad = points; + bad[3] = std::numeric_limits::infinity(); + HierarchicalNSW untrained(kCount, kDim, 9, 8, 50, 7, METRIC_COSINE); + try { + untrained.train( + 2, kCount, bad.data(), default_training_parameters(METRIC_COSINE, 7) + ); + ADD_FAILURE() << "trained on an infinite value"; + } catch (const std::invalid_argument& error) { + EXPECT_STREQ(error.what(), "HNSW training data must contain only finite values"); + } + + // Point 0 is zero. At 9 bits, estimates of its true distance 1 are close to 1. + std::fill(points.begin(), points.begin() + kDim, 0.0F); + HierarchicalNSW index(kCount, kDim, 9, 8, 50, 7, METRIC_COSINE); + index.train(2, kCount, points.data(), default_training_parameters(METRIC_COSINE, 7)); + index.add(points.data(), kCount, nullptr, false, 1); + const std::vector zero(kDim, 0.0F); + const auto from_zero = index.search(zero.data(), 1, 10, 64, 1); + ASSERT_EQ(from_zero[0].size(), 10U); + for (const auto& [distance, id] : from_zero[0]) { + EXPECT_NEAR(distance, 1.0F, 0.05F) << id; + } + const auto from_point = index.search(points.data() + kDim, 1, kCount, kCount, 1); + bool found = false; + for (const auto& [distance, id] : from_point[0]) { + if (id == 0) { + found = true; + EXPECT_NEAR(distance, 1.0F, 0.05F); + } + } + EXPECT_TRUE(found); +} + using Results = std::vector>>; struct RemoveCase { diff --git a/tests/unit/rabitqlib/index/initializer_test.cpp b/tests/unit/rabitqlib/index/initializer_test.cpp index 93e20555..d25432c2 100644 --- a/tests/unit/rabitqlib/index/initializer_test.cpp +++ b/tests/unit/rabitqlib/index/initializer_test.cpp @@ -10,10 +10,10 @@ #include #include #include -#include #include #include #include +#include #include #include #include @@ -24,58 +24,33 @@ #include "rabitqlib/index/types.hpp" #include "rabitqlib/utils/space.hpp" #include "rabitqlib/utils/tools.hpp" -#include "temp_file.hpp" namespace rabitqlib::ivf { namespace { -TEST(IvfHnswInitializerTest, PersistsUtf8SidecarPaths) { - const auto directory = std::filesystem::temp_directory_path() / - std::filesystem::u8path(u8"rabitq_\u6d4b\u8bd5_\U0001f680"); - std::filesystem::create_directories(directory); - const auto path = (directory / std::filesystem::u8path(u8"\u7d22\u5f15")).u8string(); +TEST(IvfHnswInitializerTest, RoundTripsThroughAStreamAndChecksItsSize) { const std::array centroids{0.0F, 0.0F, 3.0F, 4.0F}; HNSWInitializer initializer(2, 2); initializer.add_vectors(centroids.data(), 1); - std::ofstream ignored_output; - initializer.save(ignored_output, path.c_str()); - EXPECT_TRUE(std::filesystem::is_regular_file(std::filesystem::u8path(path + ".hnsw"))); - HNSWInitializer loaded(2, 2); - std::ifstream ignored_input; - loaded.load(ignored_input, path.c_str()); - std::vector> candidates(1); - loaded.centroids_distances(centroids.data() + 2, 1, candidates); - EXPECT_EQ(candidates[0].id, 1U); - EXPECT_FLOAT_EQ(candidates[0].distance, 0.0F); - std::filesystem::remove(std::filesystem::u8path(path + ".hnsw")); - std::filesystem::remove(directory); -} - -TEST(IvfHnswInitializerTest, ReportsSidecarOpenFailureAndCanRetry) { - const std::string path = ::testing::TempDir() + "rabitq_hnsw_save_failure"; - const std::filesystem::path sidecar(path + ".hnsw"); - std::filesystem::create_directory(sidecar); - const std::array centroids{0.0F, 0.0F, 3.0F, 4.0F}; - HNSWInitializer initializer(2, 2); - initializer.add_vectors(centroids.data(), 1); - std::ofstream ignored_output; - try { - initializer.save(ignored_output, path.c_str()); - FAIL() << "Saving the HNSW sidecar to a directory must fail"; - } catch (const std::runtime_error& error) { - EXPECT_STREQ(error.what(), "Cannot open HNSW index file for writing"); - } - std::filesystem::remove(sidecar); + std::stringstream graph; + initializer.write(graph); + const std::string bytes = graph.str(); - initializer.save(ignored_output, path.c_str()); HNSWInitializer loaded(2, 2); - std::ifstream ignored_input; - loaded.load(ignored_input, path.c_str()); + loaded.read(graph, bytes.size()); std::vector> candidates(1); loaded.centroids_distances(centroids.data() + 2, 1, candidates); EXPECT_EQ(candidates[0].id, 1U); EXPECT_FLOAT_EQ(candidates[0].distance, 0.0F); - std::filesystem::remove(sidecar); + + // The graph is read from the current position and only within its byte count. + std::stringstream shifted("xyz" + bytes); + shifted.seekg(3); + HNSWInitializer offset(2, 2); + EXPECT_NO_THROW(offset.read(shifted, bytes.size())); + std::stringstream short_input(bytes); + HNSWInitializer truncated(2, 2); + EXPECT_THROW(truncated.read(short_input, bytes.size() - 1), std::runtime_error); } TEST(IvfHnswInitializerTest, ReportsBufferedWriteFailure) { @@ -222,16 +197,13 @@ TEST(IvfHnswInitializerTest, ParallelInsertionPreservesCentroidLabelsAfterReload centroids[label * kDim + dim] = static_cast(label * kDim + dim); } } - const rabitq_test::TempFile path_file("rabitq_initializer_labels"); - const std::string& path = path_file.path(); HNSWInitializer initializer(kDim, kCount); initializer.add_vectors(centroids.data(), 4); - std::ofstream ignored_output; - initializer.save(ignored_output, path.c_str()); + std::stringstream graph; + initializer.write(graph); HNSWInitializer loaded(kDim, kCount); - std::ifstream ignored_input; - loaded.load(ignored_input, path.c_str()); + loaded.read(graph, graph.str().size()); for (size_t label = 0; label < kCount; ++label) { for (size_t dim = 0; dim < kDim; ++dim) { EXPECT_FLOAT_EQ( @@ -251,16 +223,13 @@ TEST(IvfHnswInitializerTest, ReloadsInnerProductGraphForRouting) { std::vector centroids(kCount * kDim, 0.0F); centroids[0] = 0.9F; centroids[kDim] = 100.0F; - const rabitq_test::TempFile path_file("rabitq_initializer_ip"); - const std::string& path = path_file.path(); HNSWInitializer initializer(kDim, kCount, METRIC_IP); initializer.add_vectors(centroids.data(), 4); - std::ofstream ignored_output; - initializer.save(ignored_output, path.c_str()); + std::stringstream graph; + initializer.write(graph); HNSWInitializer loaded(kDim, kCount, METRIC_IP); - std::ifstream ignored_input; - loaded.load(ignored_input, path.c_str()); + loaded.read(graph, graph.str().size()); std::array query{}; query[0] = 1.0F; std::vector> candidates(1); @@ -393,31 +362,28 @@ TEST(ParallelForTest, JoinsWorkersBeforeRethrowingFunctionException) { TEST(IvfInitializerTest, FlatInitializerReportsStreamFailures) { constexpr size_t kDim = 8; constexpr size_t kCount = 3; + constexpr size_t kBytes = sizeof(float) * kDim * kCount; std::vector centroids(kCount * kDim, 1.5F); FlatInitializer flat(kDim, kCount); flat.add_vectors(centroids.data(), 1); - const rabitq_test::TempFile path_file("rabitq_flat_initializer.bin"); - const std::string& path = path_file.path(); - { - std::ofstream output(path, std::ios::binary); - ASSERT_NO_THROW(flat.save(output, path.c_str())); - } - { - // A stream that failed to open cannot be written. - std::ofstream unopened(path + ".missing/initializer.bin", std::ios::binary); - EXPECT_THROW(flat.save(unopened, path.c_str()), std::runtime_error); - } - { - std::ifstream input(path, std::ios::binary); - FlatInitializer restored(kDim, kCount); - ASSERT_NO_THROW(restored.load(input, path.c_str())); - } - std::filesystem::resize_file( - std::filesystem::u8path(path), sizeof(float) * kDim * kCount - 1 - ); - std::ifstream truncated(path, std::ios::binary); + std::stringstream stored; + ASSERT_NO_THROW(flat.write(stored)); + ASSERT_EQ(stored.str().size(), kBytes); + + std::ostringstream broken; + broken.setstate(std::ios::badbit); + EXPECT_THROW(flat.write(broken), std::runtime_error); + + FlatInitializer restored(kDim, kCount); + ASSERT_NO_THROW(restored.read(stored, kBytes)); + EXPECT_FLOAT_EQ(restored.centroid(2)[kDim - 1], 1.5F); + + FlatInitializer wrong_size(kDim, kCount); + std::stringstream copy(stored.str()); + EXPECT_THROW(wrong_size.read(copy, kBytes - 1), std::runtime_error); + std::stringstream truncated(stored.str().substr(0, kBytes - 1)); FlatInitializer partial(kDim, kCount); - EXPECT_THROW(partial.load(truncated, path.c_str()), std::runtime_error); + EXPECT_THROW(partial.read(truncated, kBytes), std::runtime_error); } } // namespace diff --git a/tests/unit/rabitqlib/index/ivf_index_test.cpp b/tests/unit/rabitqlib/index/ivf_index_test.cpp new file mode 100644 index 00000000..36d2841c --- /dev/null +++ b/tests/unit/rabitqlib/index/ivf_index_test.cpp @@ -0,0 +1,493 @@ +#include "rabitqlib/index/ivf_index.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rabitqlib/clustering/rabitqkmeans.hpp" +#include "rabitqlib/core/metric.hpp" +#include "rabitqlib/index/ivf/types.hpp" +#include "rabitqlib/index/types.hpp" +#include "temp_file.hpp" + +namespace rabitqlib { +namespace { + +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_assignable_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(!std::is_default_constructible_v); + +constexpr size_t kDim = 64; +constexpr size_t kNumPoints = 400; +constexpr size_t kNumClusters = 8; + +std::vector gaussian(size_t num_points, uint32_t seed) { + std::mt19937 rng(seed); + std::normal_distribution normal; + std::vector data(num_points * kDim); + for (auto& value : data) { + value = normal(rng); + } + return data; +} + +IvfOptions seeded(uint32_t seed) { + IvfOptions options; + options.seed = seed; + return options; +} + +AddOptions single_thread() { + AddOptions options; + options.num_threads = 1; + return options; +} + +// Throws exactly Error, not a subclass, with exactly this message. +template +void expect_error(const Call& call, const std::string& message) { + try { + call(); + ADD_FAILURE() << "no exception; expected: " << message; + } catch (const std::exception& error) { + EXPECT_EQ(typeid(error), typeid(Error)) << error.what(); + EXPECT_EQ(error.what(), message); + } +} + +struct Results { + std::vector ids; + std::vector distances; +}; + +Results search( + const IvfIndex& index, + const float* queries, + size_t num_queries, + size_t k, + const IvfSearchOptions& options = {} +) { + Results results{ + std::vector(num_queries * k, 0), std::vector(num_queries * k, 0.0F)}; + index.search( + queries, num_queries, k, results.ids.data(), results.distances.data(), options + ); + return results; +} + +size_t count_found(const Results& results) { + size_t found = 0; + for (size_t i = 0; i < results.ids.size(); ++i) { + if (results.ids[i] != kNoId) { + EXPECT_TRUE(std::isfinite(results.distances[i])); + ++found; + } else { + EXPECT_TRUE(std::isinf(results.distances[i])); + } + } + return found; +} + +std::vector saved_bytes(const IvfIndex& index, const std::string& name) { + const rabitq_test::TempFile file(name); + index.save(file.path().c_str()); + std::ifstream input(file.path(), std::ios::binary); + return {std::istreambuf_iterator(input), std::istreambuf_iterator()}; +} + +TEST(IvfIndexTest, DefaultsFollowThePythonClass) { + const IvfIndex index(kDim, kNumClusters); + EXPECT_EQ(index.dim(), kDim); + EXPECT_EQ(index.num_clusters(), kNumClusters); + EXPECT_EQ(index.nbits(), 7U); + EXPECT_EQ(index.metric(), METRIC_L2); + EXPECT_EQ(index.routing(), ivf::Routing::Flat); // Auto below 5,000 clusters + ASSERT_TRUE(index.seed().has_value()); + EXPECT_FALSE(index.is_trained()); + EXPECT_EQ(index.num_points(), 0U); + EXPECT_EQ(index.num_stored_points(), 0U); + + const auto& cp = index.cp(); + EXPECT_EQ(cp.niter, 10U); + EXPECT_EQ(cp.max_points_per_centroid, 256U); + EXPECT_FALSE(cp.spherical); + EXPECT_EQ(cp.seed, *index.seed()); + + IvfOptions inner_product; + inner_product.metric = METRIC_IP; + const IvfIndex ip(kDim, kNumClusters, inner_product); + EXPECT_EQ(ip.metric(), METRIC_IP); + EXPECT_TRUE(ip.cp().spherical); + + IvfOptions options; + options.metric = METRIC_COSINE; + options.nbits = 32; + options.routing = ivf::Routing::HNSW; + options.seed = 9; + const IvfIndex configured(kDim, kNumClusters, options); + EXPECT_EQ(configured.metric(), METRIC_COSINE); + EXPECT_EQ(configured.nbits(), 32U); + EXPECT_EQ(configured.routing(), ivf::Routing::HNSW); + EXPECT_EQ(configured.seed(), std::optional(9)); + EXPECT_EQ(configured.cp().seed, 9U); + EXPECT_TRUE(configured.cp().spherical); +} + +TEST(IvfIndexTest, UnsetSeedsAreDrawn) { + // Four equal draws of 32 bits would be a coincidence of probability 2^-96. + std::set seeds; + for (int i = 0; i < 4; ++i) { + const IvfIndex index(kDim, kNumClusters); + ASSERT_TRUE(index.seed().has_value()); + EXPECT_EQ(index.cp().seed, *index.seed()); + seeds.insert(*index.seed()); + } + EXPECT_GT(seeds.size(), 1U); +} + +TEST(IvfIndexTest, FirstAddTrainsLikeTrainThenAdd) { + const auto data = gaussian(kNumPoints, 1); + IvfIndex implicit(kDim, kNumClusters, seeded(7)); + IvfIndex explicit_train(kDim, kNumClusters, seeded(7)); + IvfIndex other_cp(kDim, kNumClusters, seeded(7)); + // The first add trains with cp(), like train, and rotates with the index seed. + for (IvfIndex* index : {&implicit, &explicit_train}) { + index->cp().niter = 3; + index->cp().seed = 99; + } + + EXPECT_EQ(implicit.add(data.data(), kNumPoints, single_thread()), 0); + EXPECT_TRUE(implicit.is_trained()); + EXPECT_EQ(implicit.num_points(), kNumPoints); + explicit_train.train(data.data(), kNumPoints, 1); + EXPECT_EQ(explicit_train.add(data.data(), kNumPoints, single_thread()), 0); + other_cp.add(data.data(), kNumPoints, single_thread()); + + const auto bytes = saved_bytes(implicit, "ivf_index_implicit.index"); + EXPECT_EQ(bytes, saved_bytes(explicit_train, "ivf_index_explicit.index")); + EXPECT_NE(bytes, saved_bytes(other_cp, "ivf_index_other_cp.index")); + + // Later batches continue the IDs. + EXPECT_EQ(implicit.add(data.data(), 5, single_thread()), static_cast(kNumPoints)); + EXPECT_EQ(implicit.add(data.data(), 0), static_cast(kNumPoints + 5)); + EXPECT_EQ(implicit.num_stored_points(), kNumPoints + 5); +} + +TEST(IvfIndexTest, FailedFirstAddLeavesTheIndexUntrainedAndEmpty) { + auto data = gaussian(kNumPoints, 2); + IvfIndex index(kDim, kNumClusters, seeded(11)); + expect_error( + [&] { index.add(data.data(), kNumClusters - 1); }, + "the first add trains the index and needs at least num_clusters rows; " + "expected at least 8, got shape (7, 64)" + ); + data[5 * kDim] = std::numeric_limits::quiet_NaN(); + EXPECT_THROW(index.add(data.data(), kNumPoints), std::invalid_argument); + EXPECT_FALSE(index.is_trained()); + EXPECT_EQ(index.num_stored_points(), 0U); + EXPECT_EQ(index.seed(), std::optional(11)); + + data[5 * kDim] = 0.0F; + EXPECT_EQ(index.add(data.data(), kNumPoints, single_thread()), 0); + IvfIndex fresh(kDim, kNumClusters, seeded(11)); + fresh.add(data.data(), kNumPoints, single_thread()); + EXPECT_EQ( + saved_bytes(index, "ivf_index_retried.index"), + saved_bytes(fresh, "ivf_index_fresh.index") + ); +} + +TEST(IvfIndexTest, OperationsBeforeTrainingThrowLogicError) { + const auto data = gaussian(kNumPoints, 3); + IvfIndex index(kDim, kNumClusters, seeded(1)); + const rabitq_test::TempFile file("ivf_index_untrained.index"); + const std::vector cluster_ids(kNumPoints, 0); + AddOptions with_ids; + with_ids.cluster_ids = cluster_ids.data(); + const Id remove_ids[] = {0}; + Id ids[1]; + + const auto message = [](const std::string& operation) { + return "IvfIndex must be trained or loaded before " + operation; + }; + // With cluster IDs, or without points, add needs centroids instead of training. + expect_error( + [&] { index.add(data.data(), kNumPoints, with_ids); }, message("add") + ); + expect_error([&] { index.add(data.data(), 0); }, message("add")); + expect_error( + [&] { index.search(data.data(), 1, 1, ids, nullptr); }, message("search") + ); + expect_error([&] { index.remove(remove_ids, 1); }, message("remove")); + expect_error( + [&] { index.save(file.path().c_str()); }, message("save") + ); + expect_error( + [&] { index.reserve_cluster(0, 10); }, message("reserve_cluster") + ); + EXPECT_FALSE(std::filesystem::exists(file.path())); + EXPECT_FALSE(index.is_trained()); + + index.train(data.data(), kNumPoints); + expect_error( + [&] { index.save(file.path().c_str()); }, + "IvfIndex has no points to save; add points first" + ); + EXPECT_FALSE(std::filesystem::exists(file.path())); +} + +TEST(IvfIndexTest, RetrainingIsAllowedOnlyWhileEmpty) { + const auto data = gaussian(kNumPoints, 4); + IvfIndex index(kDim, kNumClusters, seeded(5)); + index.cp().num_threads = 3; + index.train(data.data(), kNumPoints, 1); + EXPECT_EQ(index.cp().num_threads, 3U); // the override is for the call only + index.set_centroids(data.data(), 1); + index.train(data.data(), kNumPoints); + index.add(data.data(), 50); + + const auto before = search(index, data.data(), 2, 5); + const std::string message = "IvfIndex cannot be trained once it stores points"; + expect_error([&] { index.train(data.data(), kNumPoints); }, message); + expect_error([&] { index.set_centroids(data.data()); }, message); + const auto after = search(index, data.data(), 2, 5); + EXPECT_EQ(before.ids, after.ids); +} + +TEST(IvfIndexTest, DefaultNprobeIsOneSixteenthOfTheClustersRounded) { + constexpr size_t kManyClusters = 24; // 1.5 rounds to 2 + const auto data = gaussian(kNumPoints, 5); + IvfIndex index(kDim, kManyClusters, seeded(3)); + index.add(data.data(), kNumPoints, single_thread()); + const auto probe = [&](std::optional nprobe) { + IvfSearchOptions options; + options.nprobe = nprobe; + return search(index, data.data(), 1, kNumPoints, options); + }; + const auto by_default = probe(std::nullopt); + const auto two = probe(2); + EXPECT_EQ(by_default.ids, two.ids); + EXPECT_EQ(by_default.distances, two.distances); + EXPECT_LT(count_found(probe(1)), count_found(two)); + EXPECT_LT(count_found(two), count_found(probe(3))); + + // At least one cluster. + IvfIndex small(kDim, 4, seeded(3)); + small.add(data.data(), kNumPoints, single_thread()); + IvfSearchOptions one; + one.nprobe = 1; + EXPECT_EQ( + search(small, data.data(), 1, kNumPoints).ids, + search(small, data.data(), 1, kNumPoints, one).ids + ); +} + +TEST(IvfIndexTest, SearchRejectsZeroBreadthAndInvalidK) { + const auto data = gaussian(kNumPoints, 6); + IvfIndex index(kDim, kNumClusters, seeded(1)); + index.add(data.data(), kNumPoints, single_thread()); + std::vector ids(kNumPoints); + IvfSearchOptions zero; + zero.nprobe = 0; + expect_error( + [&] { index.search(data.data(), 1, 1, ids.data(), nullptr, zero); }, + "nprobe must be at least 1; leave it unset for the default" + ); + for (size_t k : {size_t{0}, (size_t{1} << 31) + 1}) { + expect_error( + [&] { index.search(data.data(), 1, k, ids.data(), nullptr); }, + "k must be between 1 and 2^31" + ); + } + expect_error( + [&] { index.search(data.data(), 1, 1, nullptr, nullptr); }, + "IvfIndex search ids must not be null" + ); + index.search(data.data(), 0, 1, nullptr, nullptr); // an empty batch does nothing +} + +TEST(IvfIndexTest, SearchPadsMissingResults) { + const auto data = gaussian(kNumPoints, 7); + IvfIndex index(kDim, kNumClusters, seeded(1)); + index.train(data.data(), kNumPoints, 1); + const auto empty = search(index, data.data(), 2, 3); + EXPECT_EQ(count_found(empty), 0U); + EXPECT_EQ(empty.ids, std::vector(6, kNoId)); + + index.add(data.data(), 5); + IvfSearchOptions every_cluster; + every_cluster.nprobe = kNumClusters; + const auto padded = search(index, data.data(), 1, 8, every_cluster); + EXPECT_EQ(count_found(padded), 5U); + for (size_t i = 5; i < 8; ++i) { + EXPECT_EQ(padded.ids[i], kNoId); + } + std::vector ids_only(8, 0); + index.search(data.data(), 1, 8, ids_only.data(), nullptr, every_cluster); + EXPECT_EQ(ids_only, padded.ids); +} + +TEST(IvfIndexTest, RemoveChecksIdsBeforeNarrowingThem) { + const auto data = gaussian(kNumPoints, 8); + IvfIndex index(kDim, kNumClusters, seeded(1)); + index.add(data.data(), kNumPoints, single_thread()); + const std::string message = "ids must be in [0, num_stored_points)"; + // (2^32 + 1) would remove point 1 if it were narrowed first. + for (Id bad : {kNoId, static_cast(kNumPoints), (Id{1} << 32) + 1}) { + const Id ids[] = {0, bad}; + expect_error([&] { index.remove(ids, 2); }, message); + } + EXPECT_EQ(index.num_points(), kNumPoints); + expect_error( + [&] { index.remove(nullptr, 1); }, "IvfIndex remove ids must not be null" + ); + EXPECT_EQ(index.remove(nullptr, 0), 0U); + + const Id ids[] = {0, 1, 1}; + EXPECT_EQ(index.remove(ids, 3), 2U); + EXPECT_EQ(index.num_points(), kNumPoints - 2); + EXPECT_EQ(index.num_stored_points(), kNumPoints); + IvfSearchOptions every_cluster; + every_cluster.nprobe = kNumClusters; + const auto results = search(index, data.data(), 2, kNumPoints, every_cluster); + EXPECT_EQ(count_found(results), 2 * (kNumPoints - 2)); + for (const Id id : results.ids) { + EXPECT_TRUE(id != 0 && id != 1); + } +} + +TEST(IvfIndexTest, ReserveClusterChecksTheCluster) { + const auto data = gaussian(kNumPoints, 9); + IvfIndex index(kDim, kNumClusters, seeded(1)); + index.add(data.data(), kNumPoints, single_thread()); + expect_error( + [&] { index.reserve_cluster(kNumClusters, 10); }, + "cluster_id must be in [0, num_clusters)" + ); + index.reserve_cluster(0, 1000); + EXPECT_EQ(index.num_stored_points(), kNumPoints); +} + +TEST(IvfIndexTest, SaveAndLoadKeepSettingsSeedAndResults) { + const auto data = gaussian(kNumPoints, 10); + IvfOptions options; + options.metric = METRIC_COSINE; + options.nbits = 4; + options.seed = 21; + IvfIndex index(kDim, kNumClusters, options); + index.add(data.data(), kNumPoints); + const Id removed[] = {3}; + index.remove(removed, 1); + + const rabitq_test::TempFile file("ivf_index_round_trip.index"); + index.save(file.path().c_str()); + const IvfIndex loaded = IvfIndex::load(file.path().c_str()); + EXPECT_TRUE(loaded.is_trained()); + EXPECT_EQ(loaded.dim(), kDim); + EXPECT_EQ(loaded.num_clusters(), kNumClusters); + EXPECT_EQ(loaded.nbits(), 4U); + EXPECT_EQ(loaded.metric(), METRIC_COSINE); + EXPECT_EQ(loaded.routing(), index.routing()); + EXPECT_EQ(loaded.seed(), std::optional(21)); + EXPECT_EQ(loaded.cp().seed, 21U); + EXPECT_TRUE(loaded.cp().spherical); + EXPECT_EQ(loaded.num_points(), kNumPoints - 1); + EXPECT_EQ(loaded.num_stored_points(), kNumPoints); + + const auto expected = search(index, data.data(), 3, 10); + const auto actual = search(loaded, data.data(), 3, 10); + EXPECT_EQ(actual.ids, expected.ids); + EXPECT_EQ(actual.distances, expected.distances); +} + +TEST(IvfIndexTest, AddAndSearchApplyTheirOptions) { + const auto data = gaussian(kNumPoints, 12); + const auto trained = [&] { + IvfIndex index(kDim, kNumClusters, seeded(6)); + index.set_centroids(data.data(), 1); + return index; + }; + IvfIndex routed = trained(); + routed.add(data.data(), kNumPoints, single_thread()); + const auto routed_bytes = saved_bytes(routed, "ivf_index_routed.index"); + + const std::vector first_cluster(kNumPoints, 0); + AddOptions assigned = single_thread(); + assigned.cluster_ids = first_cluster.data(); + IvfIndex one_cluster = trained(); + one_cluster.add(data.data(), kNumPoints, assigned); + EXPECT_NE(saved_bytes(one_cluster, "ivf_index_one_cluster.index"), routed_bytes); + IvfSearchOptions first_probe; + first_probe.nprobe = 1; + // Every point is in cluster 0, so probing the one nearest cluster finds all or none. + const size_t found = + count_found(search(one_cluster, data.data(), 1, kNumPoints, first_probe)); + EXPECT_TRUE(found == 0 || found == kNumPoints) << found; + + AddOptions fast = single_thread(); + fast.fast_quantization = true; + IvfIndex fast_index = trained(); + fast_index.add(data.data(), kNumPoints, fast); + EXPECT_NE(saved_bytes(fast_index, "ivf_index_fast.index"), routed_bytes); + + IvfSearchOptions standard; + standard.high_accuracy = false; + IvfSearchOptions hacc; + hacc.high_accuracy = true; + EXPECT_NE( + search(routed, data.data(), 20, 10, standard).distances, + search(routed, data.data(), 20, 10, hacc).distances + ); + EXPECT_EQ( + search(routed, data.data(), 20, 10).distances, + search(routed, data.data(), 20, 10, hacc).distances + ); // 7 bits select HACC +} + +TEST(IvfIndexTest, LoadsAFileWithoutASeed) { + // Releases up to 0.8 did not record the seed; training defaults to the k-means seed. + const auto path = + std::filesystem::path(RABITQ_TEST_FIXTURE_ROOT) / "v0.8.3" / "ivf4_flat_l2.index"; + IvfIndex index = IvfIndex::load(path.string().c_str()); + EXPECT_TRUE(index.is_trained()); + EXPECT_FALSE(index.seed().has_value()); + EXPECT_EQ(index.cp().seed, rabitqkmeans::RaBitQKMeansParameters{}.seed); + EXPECT_FALSE(index.cp().spherical); + const size_t stored = index.num_stored_points(); + ASSERT_GT(stored, 0U); + const std::vector data(3 * index.dim(), 0.5F); + EXPECT_EQ(index.add(data.data(), 3, single_thread()), static_cast(stored)); +} + +TEST(IvfIndexTest, MovedIndexKeepsItsState) { + const auto data = gaussian(kNumPoints, 11); + IvfIndex index(kDim, kNumClusters, seeded(4)); + index.add(data.data(), kNumPoints); + const auto expected = search(index, data.data(), 2, 5); + IvfIndex moved(std::move(index)); + EXPECT_EQ(search(moved, data.data(), 2, 5).ids, expected.ids); + IvfIndex assigned(kDim, 2); + assigned = std::move(moved); + EXPECT_EQ(assigned.seed(), std::optional(4)); + EXPECT_EQ(search(assigned, data.data(), 2, 5).ids, expected.ids); +} + +} // namespace +} // namespace rabitqlib diff --git a/tests/unit/rabitqlib/index/ivf_test.cpp b/tests/unit/rabitqlib/index/ivf_test.cpp index cfce20c4..8919d95a 100644 --- a/tests/unit/rabitqlib/index/ivf_test.cpp +++ b/tests/unit/rabitqlib/index/ivf_test.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -17,10 +18,14 @@ #include #include #include +#include #include #include #include +#include "blob.hpp" +#include "cosine.hpp" +#include "format2_file.hpp" #include "ivf_search.hpp" #include "rabitqlib/clustering/qgkmeans.hpp" #include "rabitqlib/clustering/rabitqkmeans.hpp" @@ -49,6 +54,8 @@ struct IvfTestAccess { static std::unique_ptr>& rotator(IVF& index) { return index.rotator_; } + static std::optional& seed(IVF& index) { return index.seed_; } + // Rotated centroid as the initializer routes with it. static std::vector centroid(const IVF& index, PID i) { const float* centroid = index.initializer_->centroid(i); @@ -544,7 +551,12 @@ TEST(IvfPersistenceTest, RejectsPointIdsUsingTheSearchBufferMarker) { file.close(); IVF loaded; - EXPECT_THROW(loaded.load(path.c_str()), std::runtime_error); + try { + loaded.load(path.c_str()); + ADD_FAILURE() << "a marked point ID was accepted"; + } catch (const std::runtime_error& error) { + EXPECT_STREQ(error.what(), "Invalid point ID in IVF index file"); + } } // ── add / remove ──────────────────────────────────────────────────────────────────────── @@ -1687,7 +1699,9 @@ TEST(IvfPersistenceTest, RejectsTrailingBytesAndReportsUnopenableDestination) { loaded.load(path.c_str()); ADD_FAILURE() << "trailing bytes were accepted"; } catch (const std::runtime_error& error) { - EXPECT_STREQ(error.what(), "IVF index file has unexpected trailing data"); + const std::string message = error.what(); + EXPECT_EQ(message.rfind("IVF index file is ", 0), 0U) << message; + EXPECT_NE(message.find(" bytes, but its sections end at "), std::string::npos); } // The failed load leaves the previously loaded index intact. EXPECT_EQ(loaded.num_points(), kCount); @@ -1797,13 +1811,15 @@ TEST(IvfTrainTest, SetCentroidsAndAddMatchConstructByteForByte) { << "metric=" << (metric == METRIC_L2 ? "l2" : "ip") << " bits=" << bits ); IVF constructed(kCount, kDynDim, kDynNumClusters, bits, metric); - // Give the point-count constructor the rotation the seed selects. + // Give the point-count constructor the rotation the seed selects, and the + // seed itself, which the file records. IvfTestAccess::rotator(constructed) .reset( choose_rotator( kDynDim, RotatorType::FhtKacRotator, constructed.padded_dim(), kSeed ) ); + IvfTestAccess::seed(constructed) = kSeed; constructed.construct( points.data(), centroids.data(), assigned.data(), false, 1 ); @@ -1990,13 +2006,13 @@ TEST(IvfTrainTest, DefaultsUseSphericalKMeansForInnerProduct) { for (auto& value : points) { value *= 10.0F; // Means of these points are far from unit norm. } - for (auto metric : {METRIC_L2, METRIC_IP}) { - SCOPED_TRACE(metric == METRIC_L2 ? "l2" : "ip"); + for (auto metric : {METRIC_L2, METRIC_IP, METRIC_COSINE}) { + SCOPED_TRACE(static_cast(metric)); const auto cp = default_training_parameters(metric, 5); EXPECT_EQ(cp.niter, 10U); EXPECT_EQ(cp.max_points_per_centroid, 256U); EXPECT_EQ(cp.seed, 5U); - EXPECT_EQ(cp.spherical, metric == METRIC_IP); + EXPECT_EQ(cp.spherical, metric != METRIC_L2); IVF index(kDynDim, kDynNumClusters, 4, metric, 5); index.train(kCount, points.data(), cp); @@ -2007,7 +2023,7 @@ TEST(IvfTrainTest, DefaultsUseSphericalKMeansForInnerProduct) { for (const float value : centroid) { norm_sqr += static_cast(value) * value; } - if (metric == METRIC_IP) { + if (metric != METRIC_L2) { EXPECT_NEAR(std::sqrt(norm_sqr), 1.0, 1e-3); } else { EXPECT_GT(std::sqrt(norm_sqr), 2.0); @@ -2016,10 +2032,617 @@ TEST(IvfTrainTest, DefaultsUseSphericalKMeansForInnerProduct) { } } +TEST(IvfCosineTest, MatchesInnerProductOverNormalizedVectors) { + constexpr size_t kCount = 300; + constexpr size_t kQueries = 4; + const auto points = rabitq_test::rescaled_rows(random_rows(kCount, 31), kDynDim); + const auto queries = rabitq_test::rescaled_rows(random_rows(kQueries, 32), kDynDim); + const auto unit_points = rabitq_test::normalized_rows(points, kDynDim); + const auto unit_queries = rabitq_test::normalized_rows(queries, kDynDim); + const rabitq_test::TempFile cosine_file("rabitq_ivf_cosine.index"); + const rabitq_test::TempFile ip_file("rabitq_ivf_cosine_ip.index"); + const rabitq_test::TempFile damaged_file("rabitq_ivf_cosine_damaged.index"); + for (const size_t total_bits : {size_t{1}, size_t{5}, size_t{32}}) { + for (const auto initializer : {InitializerType::Flat, InitializerType::HNSW}) { + SCOPED_TRACE( + std::to_string(total_bits) + " bits, initializer " + + std::to_string(static_cast(initializer)) + ); + // One thread, so that the HNSW routing graph is reproducible. + auto cp = default_training_parameters(METRIC_COSINE, 7); + cp.num_threads = 1; + IVF cosine( + kDynDim, + kDynNumClusters, + total_bits, + METRIC_COSINE, + 7, + RotatorType::FhtKacRotator, + initializer + ); + cosine.train(kCount, points.data(), cp); + cosine.add(points.data(), kCount, nullptr, false, 1); + IVF ip( + kDynDim, + kDynNumClusters, + total_bits, + METRIC_IP, + 7, + RotatorType::FhtKacRotator, + initializer + ); + ip.train(kCount, unit_points.data(), cp); + ip.add(unit_points.data(), kCount, nullptr, false, 1); + EXPECT_EQ(cosine.metric_type(), METRIC_COSINE); + + // The files differ only in the metric field. + cosine.save(cosine_file.path().c_str()); + ip.save(ip_file.path().c_str()); + rabitq_test::expect_same_sections_except_metric( + cosine_file.path(), + ip_file.path(), + rabitq_test::format2::IndexKind::Ivf, + rabitq_test::kIvfSections + ); + + IVF loaded; + loaded.load(cosine_file.path().c_str()); + EXPECT_EQ(loaded.metric_type(), METRIC_COSINE); + for (size_t q = 0; q < kQueries; ++q) { + const auto expected = + search_everything(ip, unit_queries.data() + q * kDynDim); + for (const IVF* index : {&cosine, &loaded}) { + const auto actual = + search_everything(*index, queries.data() + q * kDynDim); + EXPECT_EQ(actual.ids, expected.ids); + EXPECT_EQ(actual.distances, expected.distances); + } + } + std::vector ids(kQueries * 5); + std::vector expected_ids(ids.size()); + std::vector distances(ids.size()); + std::vector expected_distances(ids.size()); + loaded.search_batch( + queries.data(), + kQueries, + 5, + kDynNumClusters, + ids.data(), + distances.data(), + {}, + 2 + ); + ip.search_batch( + unit_queries.data(), + kQueries, + 5, + kDynNumClusters, + expected_ids.data(), + expected_distances.data() + ); + EXPECT_EQ(ids, expected_ids); + EXPECT_EQ(distances, expected_distances); + + // A failed load keeps the metric; loading an inner-product file replaces it. + { + std::ofstream damaged(damaged_file.path(), std::ios::binary); + damaged << "not an index"; + } + EXPECT_THROW(loaded.load(damaged_file.path().c_str()), std::runtime_error); + EXPECT_EQ(loaded.metric_type(), METRIC_COSINE); + loaded.load(ip_file.path().c_str()); + EXPECT_EQ(loaded.metric_type(), METRIC_IP); + const auto reloaded = search_everything(loaded, queries.data()); + EXPECT_EQ(reloaded.distances, search_everything(ip, queries.data()).distances); + } + } +} + +TEST(IvfCosineTest, ChecksTrainingDataBeforeNormalizing) { + auto points = random_rows(40, 35); + points[7] = std::numeric_limits::quiet_NaN(); + IVF index(kDynDim, kDynNumClusters, 4, METRIC_COSINE, 7); + try { + index.train(40, points.data(), default_training_parameters(METRIC_COSINE, 7)); + ADD_FAILURE() << "trained on a NaN"; + } catch (const std::invalid_argument& error) { + EXPECT_STREQ(error.what(), "IVF training data must contain only finite values"); + } + EXPECT_FALSE(index.is_trained()); +} + +TEST(IvfCosineTest, ZeroVectorsHaveDistanceOne) { + constexpr size_t kCount = 40; + auto points = random_rows(kCount, 33); + std::fill(points.begin(), points.begin() + kDynDim, 0.0F); // point 0 is zero + const auto centroids = random_rows(kDynNumClusters, 34); + const std::vector assigned(kCount, 0); + // Raw reranking returns exact distances. + IVF index(kCount, kDynDim, kDynNumClusters, 32, METRIC_COSINE); + index.construct(points.data(), centroids.data(), assigned.data(), false, 1); + const std::vector zero(kDynDim, 0.0F); + const auto from_zero = search_everything(index, zero.data()); + EXPECT_EQ(from_zero.distances, std::vector(kCount, 1.0F)); + const auto from_point = search_everything(index, points.data() + kDynDim); + EXPECT_EQ(from_point.ids.front(), 1U); + EXPECT_NEAR(from_point.distances.front(), 0.0F, 1e-6F); + const auto zero_rank = std::find(from_point.ids.begin(), from_point.ids.end(), 0U); + ASSERT_NE(zero_rank, from_point.ids.end()); + EXPECT_EQ(from_point.distances[zero_rank - from_point.ids.begin()], 1.0F); +} + +// Given centroids are scaled to unit length, as data and queries are: a cosine index given +// centroids far from the unit sphere matches an inner-product index given the scaled +// centroids, and construct estimates distances as accurately. +TEST(IvfCosineTest, ScalesGivenCentroidsToUnitLength) { + constexpr size_t kCount = 300; + constexpr size_t kQueries = 4; + const auto points = rabitq_test::rescaled_rows(random_rows(kCount, 36), kDynDim); + const auto queries = rabitq_test::rescaled_rows(random_rows(kQueries, 37), kDynDim); + auto centroids = random_rows(kDynNumClusters, 38); + for (auto& value : centroids) { + value *= 100.0F; // like cluster means of unscaled data + } + const auto unit_points = rabitq_test::normalized_rows(points, kDynDim); + const auto unit_queries = rabitq_test::normalized_rows(queries, kDynDim); + const auto unit_centroids = rabitq_test::normalized_rows(centroids, kDynDim); + std::vector assigned(kCount); + for (size_t i = 0; i < kCount; ++i) { + assigned[i] = static_cast(i % kDynNumClusters); + } + const rabitq_test::TempFile cosine_file("rabitq_ivf_given_cosine.index"); + const rabitq_test::TempFile ip_file("rabitq_ivf_given_ip.index"); + for (const size_t total_bits : {size_t{1}, size_t{5}}) { + for (const auto initializer : {InitializerType::Flat, InitializerType::HNSW}) { + SCOPED_TRACE( + std::to_string(total_bits) + " bits, initializer " + + std::to_string(static_cast(initializer)) + ); + IVF cosine( + kDynDim, + kDynNumClusters, + total_bits, + METRIC_COSINE, + 7, + RotatorType::FhtKacRotator, + initializer + ); + cosine.set_centroids(centroids.data(), 1); + cosine.add(points.data(), kCount, assigned.data(), false, 1); + IVF ip( + kDynDim, + kDynNumClusters, + total_bits, + METRIC_IP, + 7, + RotatorType::FhtKacRotator, + initializer + ); + ip.set_centroids(unit_centroids.data(), 1); + ip.add(unit_points.data(), kCount, assigned.data(), false, 1); + // The files differ only in the metric field, centroids included. + cosine.save(cosine_file.path().c_str()); + ip.save(ip_file.path().c_str()); + rabitq_test::expect_same_sections_except_metric( + cosine_file.path(), + ip_file.path(), + rabitq_test::format2::IndexKind::Ivf, + rabitq_test::kIvfSections + ); + for (size_t q = 0; q < kQueries; ++q) { + const auto expected = + search_everything(ip, unit_queries.data() + (q * kDynDim)); + const auto actual = + search_everything(cosine, queries.data() + (q * kDynDim)); + EXPECT_EQ(actual.ids, expected.ids); + EXPECT_EQ(actual.distances, expected.distances); + } + } + } + + // construct draws its rotation, so compare its estimates with exact distances. + IVF built(kCount, kDynDim, kDynNumClusters, 5, METRIC_COSINE); + built.construct(points.data(), centroids.data(), assigned.data(), false, 1); + double worst = 0; + for (size_t q = 0; q < kQueries; ++q) { + const auto hits = search_everything(built, queries.data() + (q * kDynDim)); + for (size_t r = 0; r < hits.ids.size(); ++r) { + const float* point = unit_points.data() + (size_t{hits.ids[r]} * kDynDim); + const float* query = unit_queries.data() + (q * kDynDim); + double dot = 0; + for (size_t i = 0; i < kDynDim; ++i) { + dot += static_cast(point[i]) * query[i]; + } + worst = std::max(worst, std::abs(hits.distances[r] - (1.0 - dot))); + } + } + // Scaled centroids keep the worst error below 0.06 over many rotations; unscaled + // centroids give errors near 19. + EXPECT_LT(worst, 0.5); +} + +uint32_t get_size(const std::string& bytes, size_t offset) { + uint32_t value = 0; + std::memcpy(&value, bytes.data() + offset, sizeof(value)); + return value; +} + +// ── index format 2 ────────────────────────────────────────────────────────────────── + +using rabitq_test::format2::IndexKind; +namespace f2 = rabitq_test::format2; + +// An index of 33 points over four clusters, with point 3 removed, saved at `path`. +std::unique_ptr saved_format2_index( + const std::string& path, + size_t total_bits, + MetricType metric, + InitializerType initializer, + RotatorType rotator = RotatorType::FhtKacRotator +) { + constexpr size_t kCount = 33; + const auto points = random_rows(kCount, 951); + const auto centroids = random_rows(kDynNumClusters, 952); + const auto assigned = nearest_centroids(centroids, points.data(), kCount, metric); + auto index = std::make_unique( + kCount, kDynDim, kDynNumClusters, total_bits, metric, rotator, initializer + ); + index->construct(points.data(), centroids.data(), assigned.data(), false, 1); + const PID removed = 3; + index->remove(&removed, 1); + index->save(path.c_str()); + return index; +} + +TEST(IvfFormat2Test, WritesOneFileWithTheSpecifiedHeaderAndSections) { + const rabitq_test::TempFile path_file("rabitq_ivf_format2_layout.index"); + const std::string& path = path_file.path(); + const struct { + size_t total_bits; + MetricType metric; + InitializerType initializer; + f2::Metric stored_metric; + uint32_t code_bits; + f2::RawType raw_type; + uint32_t routing; + bool rerank; + } cases[] = { + {5, + METRIC_L2, + InitializerType::HNSW, + f2::Metric::L2, + 5, + f2::RawType::None, + 260, + true}, + {1, + METRIC_IP, + InitializerType::Flat, + f2::Metric::InnerProduct, + 1, + f2::RawType::None, + 258, + false}, + {32, + METRIC_L2, + InitializerType::FlatRaBitQ, + f2::Metric::L2, + 1, + f2::RawType::Float32, + 259, + true}, + }; + for (const auto& c : cases) { + const auto index = saved_format2_index(path, c.total_bits, c.metric, c.initializer); + EXPECT_FALSE(std::filesystem::exists(path + ".hnsw")); + const auto contents = + rabitq_test::read_format2_file(path, IndexKind::Ivf, rabitq_test::kIvfSections); + const f2::Header& header = contents.header; + EXPECT_EQ(header.metric, c.stored_metric); + EXPECT_EQ(header.dim, kDynDim); + EXPECT_EQ(header.padded_dim, 96U); + EXPECT_EQ(header.code_bits, c.code_bits); + EXPECT_EQ(header.raw_type, c.raw_type); + EXPECT_EQ(header.id_bits, 32U); + EXPECT_FALSE(header.seed.has_value()); + EXPECT_EQ(header.num_points, 33U); + std::vector kinds; + for (const auto& entry : contents.sections) { + kinds.push_back(entry.first.kind); + } + std::vector expected = {1, 256, 257, c.routing, 261}; + if (c.rerank) { + expected.push_back(262); + } + expected.push_back(263); + EXPECT_EQ(kinds, expected); + + IVF loaded; + loaded.load(path.c_str()); + EXPECT_EQ(loaded.initializer_type(), c.initializer); + EXPECT_EQ(loaded.num_points(), 32U); + std::vector expected_ids(5), ids(5); + std::vector expected_distances(5), distances(5); + const auto query = random_rows(1, 953); + index->search( + query.data(), 5, kDynNumClusters, expected_ids.data(), expected_distances.data() + ); + loaded.search(query.data(), 5, kDynNumClusters, ids.data(), distances.data()); + EXPECT_EQ(ids, expected_ids); + EXPECT_EQ(distances, expected_distances); + } +} + +TEST(IvfFormat2Test, RejectsContentsThatDoNotFitAnIvfIndex) { + const rabitq_test::TempFile path_file("rabitq_ivf_format2_reject.index"); + const std::string& path = path_file.path(); + saved_format2_index(path, 5, METRIC_L2, InitializerType::HNSW); + const auto original = + rabitq_test::read_format2_file(path, IndexKind::Ivf, rabitq_test::kIvfSections); + IVF loaded; + loaded.load(path.c_str()); + + const auto expect_rejected = + [&](const char* name, auto edit, const std::string& message) { + SCOPED_TRACE(name); + auto contents = original; + edit(contents); + rabitq_test::write_format2_file(path, contents); + try { + loaded.load(path.c_str()); + ADD_FAILURE() << "accepted"; + } catch (const std::runtime_error& error) { + EXPECT_EQ(std::string(error.what()), message); + } + EXPECT_EQ(loaded.num_points(), 32U); // the failed load keeps the loaded index + }; + const auto set_u32 = [](std::string& bytes, size_t offset, uint32_t value) { + std::memcpy(bytes.data() + offset, &value, sizeof(value)); + }; + expect_rejected( + "64-bit IDs", + [](auto& c) { c.header.id_bits = 64; }, + "IVF index file has 64-bit IDs; IVF-RaBitQ stores 32 bits" + ); + expect_rejected( + "uint8 raw vectors", + [](auto& c) { c.header.raw_type = f2::RawType::Uint8; }, + "IVF index file has uint8 raw vectors, which IVF-RaBitQ lacks" + ); + expect_rejected( + "raw vectors with extra bits", + [](auto& c) { c.header.raw_type = f2::RawType::Float32; }, + "IVF index file has 5 code bits, which its raw vectors do not allow" + ); + expect_rejected( + "no points", + [](auto& c) { c.header.num_points = 0; }, + "IVF index file has an invalid point count 0" + ); + expect_rejected( + "missing codes", + [](auto& c) { c.remove(261); }, + "IVF index file has no section kind 261" + ); + expect_rejected( + "short parameters", + [](auto& c) { c.bytes(256).pop_back(); }, + "IVF index file section kind 256 has 15 bytes; expected 16" + ); + expect_rejected( + "unknown routing", + [&](auto& c) { set_u32(c.bytes(256), 8, 9); }, + "IVF index file has invalid routing parameters" + ); + expect_rejected( + "cluster sizes above the point count", + [&](auto& c) { set_u32(c.bytes(257), 0, get_size(c.bytes(257), 0) + 1); }, + "IVF index file cluster sizes exceed its point count" + ); + expect_rejected( + "cluster sizes below the point count", + [&](auto& c) { + std::string& sizes = c.bytes(257); + for (size_t offset = 0; offset < sizes.size(); offset += sizeof(uint64_t)) { + if (get_size(sizes, offset) != 0) { + set_u32(sizes, offset, get_size(sizes, offset) - 1); + break; + } + } + }, + "IVF index file cluster sizes do not add up to its point count" + ); + expect_rejected( + "routing of another initializer", + [](auto& c) { + f2::Section flat; + flat.kind = 258; + flat.flags = f2::kSectionRequired; + c.sections.insert( + c.sections.begin() + 4, {flat, std::string(4 * 4 * 96, '\0')} + ); + }, + "IVF index file has routing data of another initializer" + ); + expect_rejected( + "corrupt rotator", + [](auto& c) { c.bytes(1)[70] ^= 1; }, + "IVF index file has an invalid rotator (data checksum mismatch (corrupt blob))" + ); + expect_rejected( + "rotator of another dimension", + [](auto& c) { + const std::unique_ptr> other( + choose_rotator(64, RotatorType::FhtKacRotator, 96, 1) + ); + std::string blob( + rabitqlib::detail::rotator_blob_bytes(RotatorType::FhtKacRotator, 64, 96), + '\0' + ); + rabitqlib::detail::encode_rotator_blob( + *other, + RotatorType::FhtKacRotator, + 64, + std::nullopt, + reinterpret_cast(blob.data()) + ); + c.bytes(1) = blob; + }, + "IVF index file rotator does not match its dimensions" + ); + expect_rejected( + "point ID out of range", + [&](auto& c) { set_u32(c.bytes(263), 0, 33); }, + "Invalid point ID in IVF index file" + ); + expect_rejected( + "missing rerank data", + [](auto& c) { c.remove(262); }, + "IVF index file has no section kind 262" + ); + expect_rejected( + "short IDs", + [](auto& c) { c.bytes(263).resize(128); }, + "IVF index file section kind 263 has 128 bytes; expected 132" + ); + expect_rejected( + "reserved routing field", + [&](auto& c) { set_u32(c.bytes(256), 12, 1); }, + "IVF index file has invalid routing parameters" + ); + + // One-bit codes have no rerank data, so a rerank section is rejected. + saved_format2_index(path, 1, METRIC_L2, InitializerType::Flat); + auto one_bit = + rabitq_test::read_format2_file(path, IndexKind::Ivf, rabitq_test::kIvfSections); + f2::Section rerank; + rerank.kind = 262; + rerank.flags = f2::kSectionRequired; + one_bit.sections.insert(one_bit.sections.end() - 1, {rerank, std::string(64, '\0')}); + rabitq_test::write_format2_file(path, one_bit); + try { + loaded.load(path.c_str()); + ADD_FAILURE() << "accepted"; + } catch (const std::runtime_error& error) { + EXPECT_STREQ( + error.what(), "IVF index file has rerank data that its code bits do not use" + ); + } +} + +TEST(IvfFormat2Test, UnknownReadOnlyFeaturesAllowSearchButNoChanges) { + const rabitq_test::TempFile path_file("rabitq_ivf_format2_read_only.index"); + const std::string& path = path_file.path(); + const auto index = saved_format2_index(path, 5, METRIC_L2, InitializerType::Flat); + rabitq_test::patch_format2_header(path, 24, 1, 8); // an unknown ro_compat bit + IVF loaded; + ASSERT_NO_THROW(loaded.load(path.c_str())); + const auto query = random_rows(1, 954); + std::vector expected_ids(5), ids(5); + std::vector distances(5); + index->search(query.data(), 5, kDynNumClusters, expected_ids.data(), distances.data()); + loaded.search(query.data(), 5, kDynNumClusters, ids.data(), distances.data()); + EXPECT_EQ(ids, expected_ids); + + const auto expect_refused = [](const auto& operation, const std::string& name) { + try { + operation(); + ADD_FAILURE() << name << " was allowed"; + } catch (const std::logic_error& error) { + EXPECT_EQ( + std::string(error.what()), + "IVF index was loaded from a file with features this release cannot " + "update, so it cannot " + + name + ); + } + }; + const auto row = random_rows(1, 955); + const PID cluster = 0; + const PID removed = 0; + expect_refused([&] { loaded.add(row.data(), 1, &cluster, false, 1); }, "add"); + expect_refused([&] { loaded.reserve(0, 64); }, "reserve"); + expect_refused([&] { loaded.remove(&removed, 1); }, "remove"); + expect_refused([&] { loaded.save((path + ".copy").c_str()); }, "save"); + EXPECT_EQ(loaded.num_points(), 32U); + + // Rebuilding replaces the data the unknown features described, so it is writable. + const auto points = random_rows(33, 951); + const auto centroids = random_rows(kDynNumClusters, 952); + const auto assigned = nearest_centroids(centroids, points.data(), 33, METRIC_L2); + loaded.construct(points.data(), centroids.data(), assigned.data(), false, 1); + EXPECT_NO_THROW(loaded.save(path.c_str())); + + // An unknown incompatible feature is rejected outright. + rabitq_test::patch_format2_header(path, 16, 2, 8); + try { + loaded.load(path.c_str()); + ADD_FAILURE() << "an unknown incompatible feature was accepted"; + } catch (const std::runtime_error& error) { + EXPECT_EQ( + std::string(error.what()), + std::string( + "IVF index file uses incompatible features 0x2 that this release " + "does not know; written by rabitqlib " + ) + RABITQ_TEST_LIBRARY_VERSION + ); + } +} + +TEST(IvfFormat2Test, RecordsTheWriterAndSkipsUnknownOptionalSections) { + const rabitq_test::TempFile path_file("rabitq_ivf_format2_optional.index"); + const std::string& path = path_file.path(); + const auto index = saved_format2_index(path, 4, METRIC_IP, InitializerType::FlatRaBitQ); + auto contents = + rabitq_test::read_format2_file(path, IndexKind::Ivf, rabitq_test::kIvfSections); + EXPECT_EQ(contents.writer_version, RABITQ_TEST_LIBRARY_VERSION); + // A later release may add an optional section; this one skips it. + f2::Section future; + future.kind = 900; + contents.sections.emplace_back(future, std::string(100, 'x')); + rabitq_test::write_format2_file(path, contents); + IVF loaded; + ASSERT_NO_THROW(loaded.load(path.c_str())); + const auto query = random_rows(1, 956); + std::vector expected_ids(5), ids(5); + std::vector distances(5); + index->search(query.data(), 5, kDynNumClusters, expected_ids.data(), distances.data()); + loaded.search(query.data(), 5, kDynNumClusters, ids.data(), distances.data()); + EXPECT_EQ(ids, expected_ids); + // save drops the section it does not know. + loaded.save(path.c_str()); + std::vector kinds = rabitq_test::kIvfSections; + kinds.push_back(900); + const auto resaved = rabitq_test::read_format2_file(path, IndexKind::Ivf, kinds); + EXPECT_EQ(resaved.sections.size(), contents.sections.size() - 1); + EXPECT_THROW( + static_cast(rabitq_test::Format2Contents(resaved).bytes(900)), + std::runtime_error + ); +} + +TEST(IvfFormat2Test, FailedWriteReportsAnErrorAndKeepsTheIndex) { + if (!std::filesystem::exists("/dev/full")) { + GTEST_SKIP() << "Requires a device that rejects writes"; + } + const rabitq_test::TempFile path_file("rabitq_ivf_format2_write_failure.index"); + const std::string& path = path_file.path(); + for (const auto initializer : + {InitializerType::Flat, InitializerType::FlatRaBitQ, InitializerType::HNSW}) { + const auto index = saved_format2_index(path, 5, METRIC_L2, initializer); + // /dev/full is not a regular file, so save writes it in place and the write fails. + EXPECT_ANY_THROW(index->save("/dev/full")); + index->save(path.c_str()); + IVF loaded; + ASSERT_NO_THROW(loaded.load(path.c_str())); + EXPECT_EQ(loaded.num_points(), 32U); + } +} + } // namespace } // namespace rabitqlib::ivf -TEST(IvfSidecarValidationTest, RejectsMismatchedVectorStorage) { +TEST(IvfRoutingGraphValidationTest, RejectsMismatchedVectorStorage) { using namespace rabitqlib; for (const auto metric : {METRIC_L2, METRIC_IP}) { for (const size_t sidecar_dim : {64U, 128U}) { @@ -2034,12 +2657,19 @@ TEST(IvfSidecarValidationTest, RejectsMismatchedVectorStorage) { original.save(path.c_str()); ivf::HNSWInitializer other(sidecar_dim, 1, metric); other.add_vectors(center.data(), 1); - std::ofstream ignored; - other.save(ignored, path.c_str()); + std::ostringstream graph; + other.write(graph); + rabitq_test::replace_format2_section( + path, + rabitq_test::format2::IndexKind::Ivf, + rabitq_test::kIvfSections, + 260, + graph.str() + ); ivf::IVF loaded; try { loaded.load(path.c_str()); - FAIL() << "mismatched sidecar must be rejected"; + FAIL() << "mismatched routing graph must be rejected"; } catch (const std::runtime_error& error) { EXPECT_STREQ( error.what(), "HNSW centroid layout does not match IVF dimension" diff --git a/tests/unit/rabitqlib/index/qg_test.cpp b/tests/unit/rabitqlib/index/qg_test.cpp index a35edca4..53819733 100644 --- a/tests/unit/rabitqlib/index/qg_test.cpp +++ b/tests/unit/rabitqlib/index/qg_test.cpp @@ -23,6 +23,8 @@ #include #include +#include "cosine.hpp" +#include "format2_file.hpp" #include "rabitqlib/core/data_layout.hpp" #include "rabitqlib/core/metric.hpp" #include "rabitqlib/core/rotator.hpp" @@ -36,6 +38,7 @@ #include "rabitqlib/index/detail/buffer.hpp" #include "rabitqlib/index/detail/exact_nn.hpp" #include "rabitqlib/index/detail/visited_set.hpp" +#include "rabitqlib/index/format_error.hpp" #include "rabitqlib/index/symqg/detail/pipnn.hpp" #include "rabitqlib/index/symqg/qg_builder.hpp" #include "rabitqlib/index/types.hpp" @@ -1398,6 +1401,304 @@ TEST(QgConfigurationTest, RejectsOutOfRangeEntryPoint) { EXPECT_EQ(graph.entry_point(), 32U); } +TEST(QgFormat2Test, RecordsTheSeedAndConstructionSettings) { + constexpr size_t kCount = 65, kDim = 64, kDegree = 32; + std::vector data(kCount * kDim); + std::mt19937 generator(5); + std::normal_distribution normal; + for (auto& value : data) { + value = normal(generator); + } + const rabitq_test::TempFile path_file("rabitq_qg_format2.index"); + const std::string& path = path_file.path(); + for (const size_t bits : {0UL, 4UL, 8UL}) { + SCOPED_TRACE(bits); + QuantizedGraph source( + kCount, kDim, kDegree, METRIC_L2, RotatorType::FhtKacRotator, bits, 7 + ); + QGBuilder builder(source, 40, data.data(), 1, QGInitialization::Random, 7); + builder.build(); + source.save(path.c_str()); + + const auto saved = rabitq_test::read_format2_file( + path, rabitq_test::format2::IndexKind::SymphonyQg, rabitq_test::kQgSections + ); + EXPECT_EQ(saved.header.code_bits, bits); + EXPECT_EQ( + saved.header.raw_type, + bits == 0 ? rabitq_test::format2::RawType::Float32 + : rabitq_test::format2::RawType::None + ); + std::vector kinds; + for (const auto& entry : saved.sections) { + kinds.push_back(entry.first.kind); + } + const std::vector expected_kinds = + bits == 0 ? std::vector{1, 768, 770} + : std::vector{1, 768, 769, 770}; + EXPECT_EQ(kinds, expected_kinds); + + QuantizedGraph loaded; + loaded.load(path.c_str()); + EXPECT_EQ(loaded.seed(), std::optional(7)); + EXPECT_EQ(loaded.ef_construction(), std::optional(40)); + EXPECT_EQ(loaded.initialization(), std::optional(QGInitialization::Random)); + EXPECT_EQ(loaded.quantization_bits(), bits); + std::vector expected(5), actual(5); + std::vector expected_distances(5), actual_distances(5); + source.set_ef(64); + loaded.set_ef(64); + source.search(data.data(), 5, expected.data(), expected_distances.data()); + loaded.search(data.data(), 5, actual.data(), actual_distances.data()); + EXPECT_EQ(actual, expected); + EXPECT_EQ(actual_distances, expected_distances); + + // A graph without a builder or a recorded seed stores them as unknown. + QuantizedGraph unknown; + EXPECT_FALSE(unknown.seed().has_value()); + EXPECT_FALSE(unknown.ef_construction().has_value()); + EXPECT_FALSE(unknown.initialization().has_value()); + } +} + +TEST(QgCosineTest, MatchesInnerProductOverNormalizedVectors) { + constexpr size_t kCount = 130, kDim = 65, kDegree = 32, kQueries = 4, kTopK = 10; + std::vector raw((kCount + kQueries) * kDim); + std::mt19937 generator(43); + std::normal_distribution normal; + for (auto& value : raw) { + value = normal(generator); + } + const auto rows = rabitq_test::rescaled_rows(raw, kDim); + const std::vector points(rows.begin(), rows.begin() + kCount * kDim); + const std::vector queries(rows.begin() + kCount * kDim, rows.end()); + const auto unit_points = rabitq_test::normalized_rows(points, kDim); + const auto unit_queries = rabitq_test::normalized_rows(queries, kDim); + const rabitq_test::TempFile cosine_file("rabitq_qg_cosine.index"); + const rabitq_test::TempFile ip_file("rabitq_qg_cosine_ip.index"); + const rabitq_test::TempFile damaged_file("rabitq_qg_cosine_damaged.index"); + for (const size_t bits : {0UL, 4UL, 8UL}) { + for (const auto init : {QGInitialization::PiPNN, QGInitialization::Random}) { + SCOPED_TRACE(std::to_string(bits) + " bits, init " + std::to_string(int(init))); + QuantizedGraph cosine( + kCount, kDim, kDegree, METRIC_COSINE, RotatorType::FhtKacRotator, bits, 7 + ); + QGBuilder(cosine, 40, points.data(), 1, init, 7).build(); + QuantizedGraph ip( + kCount, kDim, kDegree, METRIC_IP, RotatorType::FhtKacRotator, bits, 7 + ); + QGBuilder(ip, 40, unit_points.data(), 1, init, 7).build(); + EXPECT_EQ(cosine.metric_type(), METRIC_COSINE); + + cosine.save(cosine_file.path().c_str()); + ip.save(ip_file.path().c_str()); + rabitq_test::expect_same_sections_except_metric( + cosine_file.path(), + ip_file.path(), + rabitq_test::format2::IndexKind::SymphonyQg, + rabitq_test::kQgSections + ); + QuantizedGraph loaded; + loaded.load(cosine_file.path().c_str()); + EXPECT_EQ(loaded.metric_type(), METRIC_COSINE); + + std::vector expected(kQueries * kTopK); + std::vector expected_distances(expected.size()); + ip.search_batch_with_ef( + unit_queries.data(), + kQueries, + kTopK, + expected.data(), + expected_distances.data(), + 64, + 1 + ); + for (QuantizedGraph* index : {&cosine, &loaded}) { + std::vector ids(expected.size()); + std::vector distances(expected.size()); + index->search_batch_with_ef( + queries.data(), kQueries, kTopK, ids.data(), distances.data(), 64, 2 + ); + EXPECT_EQ(ids, expected); + EXPECT_EQ(distances, expected_distances); + index->set_ef(64); + index->search(queries.data(), kTopK, ids.data(), distances.data()); + EXPECT_TRUE(std::equal(ids.begin(), ids.begin() + kTopK, expected.begin())); + EXPECT_TRUE( + std::equal( + distances.begin(), + distances.begin() + kTopK, + expected_distances.begin() + ) + ); + } + + // A failed load keeps the metric; loading an inner-product file replaces it. + { + std::ofstream damaged(damaged_file.path(), std::ios::binary); + damaged << "not an index"; + } + EXPECT_THROW(loaded.load(damaged_file.path().c_str()), std::runtime_error); + EXPECT_EQ(loaded.metric_type(), METRIC_COSINE); + loaded.load(ip_file.path().c_str()); + EXPECT_EQ(loaded.metric_type(), METRIC_IP); + } + } +} + +TEST(QgCosineTest, ZeroQueryHasDistanceOne) { + constexpr size_t kCount = 65, kDim = 64, kDegree = 32; + std::vector data(kCount * kDim); + std::mt19937 generator(44); + std::normal_distribution normal; + for (auto& value : data) { + value = normal(generator); + } + // Raw vectors give exact distances. + QuantizedGraph index( + kCount, kDim, kDegree, METRIC_COSINE, RotatorType::FhtKacRotator, 0, 7 + ); + QGBuilder(index, 40, data.data(), 1, QGInitialization::Random, 7).build(); + const std::vector zero(kDim, 0.0F); + std::vector ids(10); + std::vector distances(10); + index.search_batch_with_ef(zero.data(), 1, 10, ids.data(), distances.data(), 64, 1); + EXPECT_EQ(distances, std::vector(10, 1.0F)); +} + +TEST(QgFormat2Test, RejectsContentsThatDoNotFitTheGraph) { + constexpr size_t kCount = 65, kDim = 64, kDegree = 32; + std::vector data(kCount * kDim, 0.5F); + for (size_t i = 0; i < data.size(); ++i) { + data[i] = static_cast((i * 13) % 17) / 8.0F; + } + const rabitq_test::TempFile path_file("rabitq_qg_format2_reject.index"); + const std::string& path = path_file.path(); + QuantizedGraph source( + kCount, kDim, kDegree, METRIC_IP, RotatorType::FhtKacRotator, 4, 3 + ); + QGBuilder builder(source, 40, data.data(), 1, QGInitialization::PiPNN, 3); + builder.build(); + source.save(path.c_str()); + const auto saved = rabitq_test::read_format2_file( + path, rabitq_test::format2::IndexKind::SymphonyQg, rabitq_test::kQgSections + ); + QuantizedGraph target; + target.load(path.c_str()); + const auto expect_rejected = + [&](const char* name, auto edit, const std::string& message) { + SCOPED_TRACE(name); + auto damaged = saved; + edit(damaged); + rabitq_test::write_format2_file(path, damaged); + try { + target.load(path.c_str()); + ADD_FAILURE() << "accepted"; + } catch (const std::runtime_error& error) { + EXPECT_EQ(std::string(error.what()), message); + } + EXPECT_EQ(target.num_vertices(), kCount); + }; + const auto params = [](auto& c) { + return reinterpret_cast(c.bytes(768).data()); + }; + expect_rejected( + "missing centroid", + [](auto& c) { c.remove(769); }, + "QuantizedGraph index file has no section kind 769" + ); + expect_rejected( + "raw vectors with a centroid", + [](auto& c) { + c.header.code_bits = 0; + c.header.raw_type = rabitq_test::format2::RawType::Float32; + }, + "QuantizedGraph index file has a centroid but stores raw vectors" + ); + expect_rejected( + "unknown initialization", + [&](auto& c) { rabitq_test::format2::put_u32(params(c) + 24, 3); }, + "QuantizedGraph index file has invalid graph parameters" + ); + expect_rejected( + "entry point out of range", + [&](auto& c) { rabitq_test::format2::put_u64(params(c) + 8, kCount); }, + "QuantizedGraph index file has invalid graph parameters" + ); + expect_rejected( + "degree bound", + [&](auto& c) { rabitq_test::format2::put_u64(params(c), 48); }, + "QuantizedGraph index file is invalid: QuantizedGraph degree bound must be a " + "positive multiple of 32" + ); + expect_rejected( + "seed above 32 bits", + [](auto& c) { c.header.seed = uint64_t{1} << 40; }, + "QuantizedGraph index file has a seed above 32 bits" + ); + expect_rejected( + "short records", + [](auto& c) { c.bytes(770).pop_back(); }, + "QuantizedGraph index file section kind 770 has " + + std::to_string(rabitq_test::Format2Contents(saved).bytes(770).size() - 1) + + " bytes; expected " + + std::to_string(rabitq_test::Format2Contents(saved).bytes(770).size()) + ); + expect_rejected( + "neighbor out of range", + [&](auto& c) { + std::string& records = c.bytes(770); + // The last 4 bytes are the last vertex's last neighbor ID. + rabitq_test::format2::put_u32( + reinterpret_cast(records.data()) + records.size() - 4, kCount + ); + }, + "QuantizedGraph neighbor ID is invalid" + ); + expect_rejected( + "1-bit codes", + [](auto& c) { c.header.code_bits = 1; }, + "QuantizedGraph index file stores neither raw vectors nor 4- or 8-bit codes with " + "32-bit IDs" + ); +} + +TEST(QgFormat2Test, UnknownReadOnlyFeaturesAllowSearchUntilRebuilt) { + constexpr size_t kCount = 65, kDim = 64, kDegree = 32; + std::vector data(kCount * kDim); + for (size_t i = 0; i < data.size(); ++i) { + data[i] = static_cast((i * 7) % 23) / 8.0F; + } + const rabitq_test::TempFile path_file("rabitq_qg_format2_read_only.index"); + const std::string& path = path_file.path(); + QuantizedGraph source( + kCount, kDim, kDegree, METRIC_L2, RotatorType::FhtKacRotator, 8, 2 + ); + QGBuilder(source, 40, data.data(), 1, QGInitialization::PiPNN, 2).build(); + source.save(path.c_str()); + rabitq_test::patch_format2_header(path, 24, 1, 8); // an unknown ro_compat bit + + QuantizedGraph loaded; + ASSERT_NO_THROW(loaded.load(path.c_str())); + std::vector ids(5); + std::vector distances(5); + loaded.set_ef(64); + ASSERT_NO_THROW(loaded.search(data.data(), 5, ids.data(), distances.data())); + try { + loaded.save(path.c_str()); + ADD_FAILURE() << "save was allowed"; + } catch (const std::logic_error& error) { + EXPECT_STREQ( + error.what(), + "QuantizedGraph was loaded from a file with features this release cannot " + "update, so it cannot save" + ); + } + // A builder replaces the data the unknown features described. + QGBuilder(loaded, 40, data.data(), 1, QGInitialization::PiPNN, 2).build(); + EXPECT_NO_THROW(loaded.save(path.c_str())); +} + TEST(QgPersistenceTest, RejectsMalformedPayloadWithoutChangingTarget) { constexpr size_t kCount = 33; constexpr size_t kDim = 64; @@ -1419,38 +1720,57 @@ TEST(QgPersistenceTest, RejectsMalformedPayloadWithoutChangingTarget) { EXPECT_EQ(target.num_vertices(), 65U); EXPECT_EQ(target.metric_type(), METRIC_IP); - source.save(path.c_str()); - { - std::fstream file(path, std::ios::binary | std::ios::in | std::ios::out); - ASSERT_TRUE(file.is_open()); - constexpr std::streamoff kPaddedDimensionOffset = - sizeof(uint64_t) + sizeof(uint32_t) + (3 * sizeof(size_t)); - file.seekp(kPaddedDimensionOffset); - const size_t invalid_padded_dim = kDim * 2; - file.write( - reinterpret_cast(&invalid_padded_dim), sizeof(invalid_padded_dim) - ); - ASSERT_TRUE(file.good()); - } - EXPECT_THROW(target.load(path.c_str()), std::runtime_error); - EXPECT_EQ(target.num_vertices(), 65U); - EXPECT_EQ(target.metric_type(), METRIC_IP); + // Format-2 header fields that do not fit the graph; the earlier layout's are covered + // by the historical persistence tests. + const auto expect_rejected = + [&](size_t offset, uint64_t value, const std::string& message) { + source.save(path.c_str()); + rabitq_test::patch_format2_header(path, offset, value, sizeof(uint64_t)); + try { + target.load(path.c_str()); + ADD_FAILURE() << "accepted: " << message; + } catch (const std::runtime_error& error) { + EXPECT_EQ(std::string(error.what()), message); + } + EXPECT_EQ(target.num_vertices(), 65U); + EXPECT_EQ(target.metric_type(), METRIC_IP); + }; + expect_rejected( + 56, kDim * 2, "QuantizedGraph index file rotator does not match its dimensions" + ); + expect_rejected( + 88, + uint64_t{1} << 32, + "QuantizedGraph index file is invalid: QuantizedGraph point count exceeds the " + "search-buffer ID limit" + ); + // Settings within their limits whose records exceed size_t: 2**31 points with a + // degree bound of 2**30. source.save(path.c_str()); - { - std::fstream file(path, std::ios::binary | std::ios::in | std::ios::out); - ASSERT_TRUE(file.is_open()); - constexpr std::streamoff kPointCountOffset = sizeof(uint64_t) + sizeof(uint32_t); - file.seekp(kPointCountOffset); - const size_t invalid_point_count = std::numeric_limits::max(); - file.write( - reinterpret_cast(&invalid_point_count), sizeof(invalid_point_count) + std::string params = rabitq_test::read_format2_section( + path, rabitq_test::format2::IndexKind::SymphonyQg, rabitq_test::kQgSections, 768 + ); + rabitq_test::format2::put_u64( + reinterpret_cast(params.data()), uint64_t{1} << 30 + ); + rabitq_test::replace_format2_section( + path, + rabitq_test::format2::IndexKind::SymphonyQg, + rabitq_test::kQgSections, + 768, + params + ); + rabitq_test::patch_format2_header(path, 88, uint64_t{1} << 31, sizeof(uint64_t)); + try { + target.load(path.c_str()); + ADD_FAILURE() << "accepted records too large to address"; + } catch (const FormatError& error) { + EXPECT_STREQ( + error.what(), "QuantizedGraph index file describes records too large to address" ); - ASSERT_TRUE(file.good()); } - EXPECT_THROW(target.load(path.c_str()), std::invalid_argument); EXPECT_EQ(target.num_vertices(), 65U); - EXPECT_EQ(target.metric_type(), METRIC_IP); if (std::filesystem::exists("/dev/full")) { EXPECT_THROW(source.save("/dev/full"), std::ios_base::failure); 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 diff --git a/tests/unit/rabitqlib/quantization/core_api_test.cpp b/tests/unit/rabitqlib/quantization/core_api_test.cpp index 696db310..9ab6f932 100644 --- a/tests/unit/rabitqlib/quantization/core_api_test.cpp +++ b/tests/unit/rabitqlib/quantization/core_api_test.cpp @@ -376,6 +376,8 @@ TEST(CoreApiTest, RejectsBadParametersAndBuffersBeforeWritingCodes) { auto bad = p; bad.metric = static_cast(255); EXPECT_THROW(api::requirements(bad, out.layout), std::invalid_argument); + bad.metric = rabitqlib::METRIC_COSINE; // only the ANN indexes accept it + EXPECT_THROW(api::requirements(bad, out.layout), std::invalid_argument); bad = p; bad.t_const = std::numeric_limits::infinity(); EXPECT_THROW(api::requirements(bad, out.layout), std::invalid_argument); diff --git a/tests/unit/rabitqlib/quantization/factor_test.cpp b/tests/unit/rabitqlib/quantization/factor_test.cpp index 184146ba..b9f0d54d 100644 --- a/tests/unit/rabitqlib/quantization/factor_test.cpp +++ b/tests/unit/rabitqlib/quantization/factor_test.cpp @@ -159,7 +159,7 @@ TEST(RabitqFactorTest, ForeignCodeIsRejectedDouble) { TEST(RabitqFactorTest, InvalidMetricMessagesArePreserved) { constexpr size_t kDim = 64; - const auto invalid_metric = static_cast(2); + const auto invalid_metric = METRIC_COSINE; // only the ANN indexes accept it std::vector data(kDim), centroid(kDim, 0), residual(kDim), centered(kDim); std::vector codes(kDim); float add, rescale, error; diff --git a/tests/unit/rabitqlib/utils/blob_test.cpp b/tests/unit/rabitqlib/utils/blob_test.cpp new file mode 100644 index 00000000..b7d61100 --- /dev/null +++ b/tests/unit/rabitqlib/utils/blob_test.cpp @@ -0,0 +1,206 @@ +#include "blob.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "crc32.hpp" +#include "rabitqlib/core/rotator.hpp" +#include "rabitqlib/core/types.hpp" + +namespace { +using rabitqlib::RotatorType; +namespace detail = rabitqlib::detail; + +std::vector read_fixture(const std::string& name) { + std::ifstream input( + std::string(RABITQ_QUANT_FIXTURE_ROOT) + "/" + name, std::ios::binary + ); + EXPECT_TRUE(input.is_open()) << name; + return {std::istreambuf_iterator(input), std::istreambuf_iterator()}; +} + +std::vector encode( + const rabitqlib::Rotator& rotator, + RotatorType type, + size_t dim, + std::optional seed +) { + std::vector blob(detail::rotator_blob_bytes(type, dim, rotator.size())); + detail::encode_rotator_blob(rotator, type, dim, seed, blob.data()); + return blob; +} + +std::vector rotate(const rabitqlib::Rotator& rotator, size_t dim) { + std::vector input(dim); + for (size_t i = 0; i < dim; ++i) { + input[i] = static_cast(i % 7) - 3.0F; + } + std::vector output(rotator.size()); + rotator.rotate(input.data(), output.data()); + return output; +} + +void put_u32(std::vector& blob, size_t offset, uint32_t value) { + for (size_t i = 0; i < 4; ++i) { + blob[offset + i] = static_cast(value >> (8 * i)); + } +} + +// Recompute the checksum after an edit, so that the check under test fires. +void reseal(std::vector& blob) { + put_u32(blob, 32, 0); + put_u32(blob, 32, detail::crc32(blob.data(), blob.size())); +} + +void expect_rejected(const std::vector& blob, const std::string& message) { + try { + detail::decode_rotator_blob(blob.data(), blob.size()); + ADD_FAILURE() << "expected std::invalid_argument: " << message; + } catch (const std::invalid_argument& error) { + EXPECT_EQ(std::string(error.what()), message); + } +} + +TEST(CoreBlobTest, Crc32MatchesZlib) { + EXPECT_EQ(detail::crc32("", 0), 0U); + EXPECT_EQ(detail::crc32("123456789", 9), 0xCBF43926U); + std::vector data(1024); + for (size_t i = 0; i < data.size(); ++i) { + data[i] = static_cast(i); + } + EXPECT_EQ(detail::crc32(data.data(), data.size()), 0xB70B4C26U); // zlib.crc32 + const uint32_t first = detail::crc32(data.data(), 100); + EXPECT_EQ(detail::crc32(data.data() + 100, data.size() - 100, first), 0xB70B4C26U); +} + +// The golden files rabitqlib.quant writes: the C++ codec reads and rewrites them +// byte for byte, and they hold the same rotation as a freshly seeded rotator. +TEST(CoreBlobTest, ReadsAndRewritesTheQuantGoldenRotators) { + const struct { + const char* name; + size_t dim; + size_t padded_dim; + uint32_t seed; + } cases[] = { + {"rotator_fht_kac_dim64_seed0.bin", 64, 64, 0}, + {"rotator_fht_kac_dim100_padded128_seed42.bin", 100, 128, 42}, + }; + for (const auto& c : cases) { + const std::vector golden = read_fixture(c.name); + const detail::DecodedRotator decoded = + detail::decode_rotator_blob(golden.data(), golden.size()); + EXPECT_EQ(decoded.type, RotatorType::FhtKacRotator); + EXPECT_EQ(decoded.dim, c.dim); + EXPECT_EQ(decoded.padded_dim, c.padded_dim); + ASSERT_TRUE(decoded.seed.has_value()); + EXPECT_EQ(*decoded.seed, c.seed); + EXPECT_EQ( + encode(*decoded.rotator, decoded.type, decoded.dim, decoded.seed), golden + ); + + const std::unique_ptr> fresh( + rabitqlib::choose_rotator( + c.dim, RotatorType::FhtKacRotator, c.padded_dim, c.seed + ) + ); + EXPECT_EQ(rotate(*decoded.rotator, c.dim), rotate(*fresh, c.dim)); + } +} + +TEST(CoreBlobTest, RoundTripsAMatrixRotatorWithoutASeed) { + const std::unique_ptr> rotator( + rabitqlib::choose_rotator(40, RotatorType::MatrixRotator, 64, 7) + ); + const std::vector blob = encode(*rotator, RotatorType::MatrixRotator, 40, {}); + EXPECT_EQ(blob.size(), 64 + (4 * 40 * 64)); + const detail::DecodedRotator decoded = + detail::decode_rotator_blob(blob.data(), blob.size()); + EXPECT_EQ(decoded.type, RotatorType::MatrixRotator); + EXPECT_EQ(decoded.dim, 40U); + EXPECT_EQ(decoded.padded_dim, 64U); + EXPECT_FALSE(decoded.seed.has_value()); + EXPECT_EQ(rotate(*decoded.rotator, 40), rotate(*rotator, 40)); +} + +TEST(CoreBlobTest, EncoderRejectsDimensionsTheFormatDoesNotAllow) { + const std::unique_ptr> rotator( + rabitqlib::choose_rotator(40, RotatorType::MatrixRotator, 64, 7) + ); + std::vector blob( + detail::rotator_blob_bytes(RotatorType::MatrixRotator, 40, 64) + ); + EXPECT_THROW( + detail::encode_rotator_blob( + *rotator, RotatorType::FhtKacRotator, 40, {}, blob.data() + ), + std::invalid_argument + ); + EXPECT_THROW( + detail::encode_rotator_blob( + *rotator, RotatorType::MatrixRotator, 41, {}, blob.data() + ), + std::invalid_argument + ); +} + +TEST(CoreBlobTest, RejectsInvalidBlobsWithTheQuantMessages) { + const std::vector golden = read_fixture("rotator_fht_kac_dim64_seed0.bin"); + const auto edited = [&golden](size_t offset, uint32_t value) { + std::vector blob = golden; + put_u32(blob, offset, value); + reseal(blob); + return blob; + }; + + expect_rejected( + std::vector(golden.begin(), golden.begin() + 39), + "data is too short for a rabitqlib blob" + ); + std::vector blob = golden; + blob[0] = 'X'; + expect_rejected(blob, "data is not a rabitqlib blob (bad magic)"); + expect_rejected(edited(8, 3), "data is not a rotator blob; got kind 3"); + expect_rejected( + edited(12, 2), + "data has unsupported rotator format version 2; this release reads version 1" + ); + expect_rejected( + edited(16, 72), "data has an invalid header size for rotator version 1" + ); + expect_rejected( + std::vector(golden.begin(), golden.end() - 1), + "data length does not match its header (truncated or padded)" + ); + blob = golden; + blob[70] ^= 1; + expect_rejected(blob, "data checksum mismatch (corrupt blob)"); + expect_rejected(edited(20, 2), "data has unknown flags"); + expect_rejected(edited(60, 1), "data has non-zero reserved fields"); + expect_rejected(edited(40, 3), "data has an unknown rotator method 3"); + expect_rejected( + edited(44, 2), "data stores a float64 rotator, which version 1 cannot load" + ); + expect_rejected(edited(44, 9), "data has an unknown scalar type 9"); + expect_rejected( + edited(48, 32), + "data has invalid rotator dimensions: dim must be at least 64 for method " + "'fht_kac'; got 32" + ); + std::vector seeded = + read_fixture("rotator_fht_kac_dim100_padded128_seed42.bin"); + put_u32(seeded, 20, 0); // seed 42 without seed_known + reseal(seeded); + expect_rejected(seeded, "data has a seed without the seed_known flag"); + expect_rejected(edited(52, 96), "data body size does not match the rotator parameters"); +} + +} // namespace diff --git a/tests/unit/rabitqlib/utils/rotator_test.cpp b/tests/unit/rabitqlib/utils/rotator_test.cpp index 0a773fc7..1814c93e 100644 --- a/tests/unit/rabitqlib/utils/rotator_test.cpp +++ b/tests/unit/rabitqlib/utils/rotator_test.cpp @@ -712,6 +712,35 @@ TEST(MatrixRotatorFactoryTest, SeedReproducesTheMatrix) { EXPECT_EQ(rotator_state(direct), first); } +// An unadjusted Householder Q has a fixed determinant and a negative first entry. A +// Haar-distributed matrix takes either sign of both, so over 64 seeds each sign must +// occur; a correct rotator fails this only with probability about 2^-62. +TEST(MatrixRotatorFactoryTest, SeededMatricesTakeBothSignsAsHaarRequires) { + constexpr size_t kDim = 3; + constexpr uint32_t kSeeds = 64; + uint32_t negative_first = 0; + uint32_t negative_det = 0; + for (uint32_t seed = 0; seed < kSeeds; ++seed) { + const rotator_impl::MatrixRotator rotator(kDim, kDim, seed); + std::array m{}; + ASSERT_EQ(rotator.dump_bytes(), sizeof(m)); + rotator.save(reinterpret_cast(m.data())); + const double det = (static_cast(m[0]) * m[4] * m[8]) + + (static_cast(m[1]) * m[5] * m[6]) + + (static_cast(m[2]) * m[3] * m[7]) - + (static_cast(m[2]) * m[4] * m[6]) - + (static_cast(m[1]) * m[3] * m[8]) - + (static_cast(m[0]) * m[5] * m[7]); + ASSERT_NEAR(std::abs(det), 1.0, 1e-5) << "seed " << seed; + negative_first += m[0] < 0 ? 1U : 0U; + negative_det += det < 0 ? 1U : 0U; + } + EXPECT_GT(negative_first, 0U); + EXPECT_LT(negative_first, kSeeds); + EXPECT_GT(negative_det, 0U); + EXPECT_LT(negative_det, kSeeds); +} + TEST(MatrixRotatorFactoryTest, DoublePreservesNormAndRejectsFloatOnlyRotation) { const size_t dim = 64; std::unique_ptr> rotator( diff --git a/tests/unit/rabitqlib/utils/tools_test.cpp b/tests/unit/rabitqlib/utils/tools_test.cpp new file mode 100644 index 00000000..bc012cf7 --- /dev/null +++ b/tests/unit/rabitqlib/utils/tools_test.cpp @@ -0,0 +1,28 @@ +#include "rabitqlib/utils/tools.hpp" + +#include + +#include +#include + +namespace rabitqlib { +namespace { + +TEST(ToolsTest, CeilLog2RoundsUpAcrossSizeTWidth) { + EXPECT_EQ(ceil_log2(0), 0U); + EXPECT_EQ(ceil_log2(1), 0U); + EXPECT_EQ(ceil_log2(3), 2U); + + // Exponents of 32 and above exceed the width of a 32-bit shift operand + // (unsigned long on LLP64). + constexpr size_t kDigits = std::numeric_limits::digits; + for (size_t bit = 1; bit < kDigits; ++bit) { + const size_t power = size_t{1} << bit; + EXPECT_EQ(ceil_log2(power), bit) << bit; + EXPECT_EQ(ceil_log2(power + 1), bit + 1) << bit; + } + EXPECT_EQ(ceil_log2(std::numeric_limits::max()), kDigits); +} + +} // namespace +} // namespace rabitqlib