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/docs/development.md b/docs/development.md index 1da66afb..983a9051 100644 --- a/docs/development.md +++ b/docs/development.md @@ -524,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 @@ -712,21 +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_` and QG's -`degree_bound()`/`set_ef()` retain their existing spellings, as do the Python -vocabulary `seed`, `train`, `obj`, `nsplit`, `final_obj` and `niter`. Since 0.9, Python +`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). `QGKMeansParameters` has the same field names in C++, converting -`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. +(#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 diff --git a/docs/docs/cpp_integration.md b/docs/docs/cpp_integration.md index 686a490d..9df80b68 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) diff --git a/docs/docs/index/hnsw.md b/docs/docs/index/hnsw.md index d19ce90e..63a67406 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 @@ -38,53 +38,58 @@ 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` | `metric` defaults to `"l2"` in Python; `"ip"` 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`. Python's default `None` draws one at random (it was 100 before 0.9); `index.seed` reports it. | -| `capacity` (C++ `max_elements()`) | Python reports the current capacity, which `add` grows geometrically (at least doubling) and `reserve` can preallocate; they replace `max_elements` and `resize`, which 0.9 removed. 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 raises `ValueError`), 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. | +| `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` | Positive result count 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 draws a seed unless `seed=` is given, and +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 `seed=` to the constructor and `num_threads=1` to `add` when you +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 returns `int64` IDs and fills missing results with ID `-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 @@ -95,121 +100,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 +A trained or loaded index supports `add()`, `reserve()` and `remove()` without +the original data. Adding points and reserving capacity preserve the index file +format; files with removals have [compatibility restrictions](#how-removal-is-stored). ```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: ```python new_ids = index.add(vectors) # route to the nearest centroids @@ -222,7 +216,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. @@ -232,15 +226,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 +`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. @@ -256,12 +248,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: @@ -273,7 +265,7 @@ 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 ID `-1` +`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. @@ -281,10 +273,9 @@ 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; 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()`): @@ -299,20 +290,12 @@ 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 +it survives `save`, `load`, and capacity growth, 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 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 @@ -401,11 +384,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 16874e22..7f897282 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"`, `"ip"` or `"cosine"`; defaults to `"l2"`. See [the cosine metric](usage.md#the-cosine-metric). | -| `routing` | Defaults to `"auto"`; see [centroid routing](#centroid-routing). It replaces `initializer`, which 0.9 removed. | -| `k`, `nprobe` | Positive result count and cluster probe count. `k` may exceed the stored point count; missing results are padded with `kPidMax` (`-1` in Python) and `+inf`. Python's `nprobe` defaults to `num_clusters / 16`, rounded and at least 1, when omitted or `None` (0 raises `ValueError`); 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` | Positive result count and 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. IDs are `int64` in Python. Unfilled slots use ID `-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,26 +112,24 @@ 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"`: ```python index = IvfIndex(dim, num_clusters, nbits=4, routing="flat_rabitq") @@ -131,15 +137,14 @@ print(index.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 @@ -159,11 +164,7 @@ 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 +172,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 @@ -234,156 +226,127 @@ index.add(vectors) 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 and cosine. 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. Updates preserve the file format. ```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). @@ -397,7 +360,7 @@ removed = index.remove(new_ids[:10]) index.reserve_cluster(cluster_id, num_points) ``` -Python names this method `reserve_cluster`; it replaces `reserve`, which 0.9 removed. +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 an int64 array of the new IDs. Optional `cluster_ids` must be a @@ -407,9 +370,7 @@ 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` @@ -425,7 +386,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. @@ -453,7 +414,7 @@ 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` (`-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 @@ -466,7 +427,7 @@ 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); @@ -495,7 +456,7 @@ left beside it is not removed and is no longer used. 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 d2dc0933..075e5ccb 100644 --- a/docs/docs/index/qg.md +++ b/docs/docs/index/qg.md @@ -36,149 +36,119 @@ 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. | -| `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), `"ip"` or [`"cosine"`](usage.md#the-cosine-metric). | -| `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 `-1` in Python (`kPidMax` in C++) and distance `+inf`. An omitted or `None` `ef_search` uses `max(k, 64)` in Python (0 raises `ValueError`), and smaller values are raised to `k`, as for HNSW-RaBitQ. It replaces `ef`, which 0.9 removed. | -| `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 at least 1 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)`, @@ -186,23 +156,9 @@ including empty batches. It defaults to one worker; `num_threads=0` selects the available logical CPU count, capped 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. diff --git a/docs/docs/index/usage.md b/docs/docs/index/usage.md index 462fd50e..1e55838b 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,10 +23,10 @@ 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 @@ -35,7 +36,7 @@ unit length, stores the inner-product codes of the scaled vectors, and returns Results equal those of a `metric="ip"` index built from the same vectors 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. Centroids -passed to `set_centroids` or C++ `construct` are used as given; `train`, and the first +passed to `set_centroids` are used as given; `train`, and the first `add` that trains, compute them from the scaled vectors with spherical k-means. The index checks the original coordinates first, as above. Because it then trains on @@ -58,8 +59,7 @@ HNSW-RaBitQ's `num_points` now excludes removed records; see the [count migration guide](../modular_migration.md#unified-index-counts) when upgrading. 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 | | --- | --- | @@ -80,7 +80,7 @@ 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 +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. @@ -115,7 +115,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. diff --git a/docs/docs/python_migration.md b/docs/docs/python_migration.md index b9ed55d3..e6bacb61 100644 --- a/docs/docs/python_migration.md +++ b/docs/docs/python_migration.md @@ -117,10 +117,12 @@ its results and latency; pass the breadth as the third argument to keep the old load as trained indexes, except empty, untrained HNSW-RaBitQ files, which need `train` before `add`. -For C++, the existing index 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/unreleased.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). diff --git a/docs/docs/releases/unreleased.md b/docs/docs/releases/unreleased.md index de9e1ca4..90d121fb 100644 --- a/docs/docs/releases/unreleased.md +++ b/docs/docs/releases/unreleased.md @@ -8,7 +8,7 @@ - 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. Rebuilding with IVF-RaBitQ `construct`, or a new SymphonyQG build, makes it writable again. +- 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 @@ -48,7 +48,7 @@ - Point IDs are `int64` at the Python boundary (#211): - `search` returns `int64` IDs, and slots without a neighbor hold `-1` instead of `2**32 - 1`; their distance is still `inf`. Code that compares IDs with `2**32 - 1`, `0xFFFFFFFF` or `np.iinfo(np.uint32).max` must change; `np.isfinite(distances)`, recommended since 0.8.2, works before and after. - `add` returns `int64` IDs. `remove` already took any integer IDs and still rejects `-1` and other out-of-range values without removing anything. - - IDs remain the row numbers the index assigns. The existing C++ index classes keep 32-bit `PID` values with `kPidMax` for a missing result; the new C++ `IvfIndex`, `HnswIndex` and `SymqgIndex` use 64-bit IDs, as Python does. + - 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. @@ -85,7 +85,24 @@ - A failed `add` leaves the index without a graph. `add` takes a worker count, with 0, the default, for every available CPU. - `search` takes a `GraphSearchOptions` struct. Without an `ef_search` it uses `max(k, 64)`, a smaller value is raised to `k`, and an explicit 0 throws; `symqg::QuantizedGraph` rejects an `ef_search` below `k`. - `seed()`, `ef_construction()` and `init()` have no value for a file of a release up to 0.8. -- `ivf::IVF`, `hnsw::HierarchicalNSW`, `symqg::QuantizedGraph` and `symqg::QGBuilder` are otherwise unchanged. +- `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. - `qgkmeans::QGKMeansParameters` uses the Python names (#233): `graph_degree` becomes `max_degree`, `ef_build` becomes `ef_construction`, and `quantization_bits` (0, 4 or 8) becomes `nbits` (32, 4 or 8, with 32 for raw float32). The fields keep their order and types. An `nbits` of 0 is rejected, so code that initialized the field positionally with 0 must pass 32. `QGAssigner` keeps its constructor, including `quantization_bits` with 0 for raw storage. - Messages follow the names: `QGKMeans nbits must be 4, 8, or 32`, `QGKMeans max_degree must be a positive multiple of 32`, `QGKMeans requires more centroids than max_degree` and `QGKMeans ef_construction and ef_search must be positive`. diff --git a/sample/cpp/hnsw_rabitq_indexing.cpp b/sample/cpp/hnsw_rabitq_indexing.cpp index f1e1d540..929aa6a9 100644 --- a/sample/cpp/hnsw_rabitq_indexing.cpp +++ b/sample/cpp/hnsw_rabitq_indexing.cpp @@ -7,13 +7,11 @@ #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; @@ -75,23 +73,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..797661c1 100644 --- a/sample/cpp/hnsw_rabitq_querying.cpp +++ b/sample/cpp/hnsw_rabitq_querying.cpp @@ -4,11 +4,10 @@ #include #include #include -#include #include #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" @@ -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; } diff --git a/sample/cpp/ivf_rabitq_indexing.cpp b/sample/cpp/ivf_rabitq_indexing.cpp index 2f04ebc6..e1cbdf8e 100644 --- a/sample/cpp/ivf_rabitq_indexing.cpp +++ b/sample/cpp/ivf_rabitq_indexing.cpp @@ -7,13 +7,12 @@ #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; @@ -69,15 +68,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..5d633546 100644 --- a/sample/cpp/ivf_rabitq_querying.cpp +++ b/sample/cpp/ivf_rabitq_querying.cpp @@ -7,22 +7,24 @@ #include #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); @@ -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/symqg_indexing.cpp b/sample/cpp/symqg_indexing.cpp index 872614bb..6cd2b09f 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) { @@ -29,9 +21,9 @@ int run(int argc, char** argv) { << "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" + << "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; } @@ -52,7 +44,10 @@ int run(int argc, char** argv) { } else if (metric_type == rabitqlib::METRIC_L2) { std::cout << "Metric Type: L2\n"; } - size_t quantization_bits = argc > 6 ? static_cast(atoi(argv[6])) : 0; + size_t nbits = argc > 6 ? static_cast(atoi(argv[6])) : 32; + if (nbits == 0) { // the 0.8 spelling of raw vectors + nbits = 32; + } data_type data; @@ -62,41 +57,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..92fefcdf 100644 --- a/sample/cpp/symqg_querying.cpp +++ b/sample/cpp/symqg_querying.cpp @@ -5,14 +5,13 @@ #include #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; } diff --git a/tests/integration/cpp_example_index_check.cpp b/tests/integration/cpp_example_index_check.cpp index 9a613046..22f96728 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" @@ -27,37 +27,34 @@ int main(int argc, char** argv) { 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. 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");