diff --git a/README.md b/README.md index b890bbcc..53a84fb2 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ QPS–recall tradeoffs. | Index | Search approach | Storage and updates | | --- | --- | --- | | [IVF-RaBitQ](https://vectordb-ntu.github.io/RaBitQ-Library/index/ivf/) | Partitioned search with batch scoring. | 1–9-bit codes or raw-vector reranking; add/remove. | -| [HNSW-RaBitQ](https://vectordb-ntu.github.io/RaBitQ-Library/index/hnsw/) | Graph traversal over quantized vectors. | 1–9-bit codes plus graph edges; add/remove and resize. | +| [HNSW-RaBitQ](https://vectordb-ntu.github.io/RaBitQ-Library/index/hnsw/) | Graph traversal over quantized vectors. | 1–9-bit codes plus graph edges; add/remove and reserve. | | [SymphonyQG](https://vectordb-ntu.github.io/RaBitQ-Library/index/qg/) | Graph search with batched distance estimation. | Raw or 4/8-bit storage; updates require rebuilding. | [Native clustering methods](https://vectordb-ntu.github.io/RaBitQ-Library/clustering/) prepare centroids and @@ -93,8 +93,8 @@ distance, with smaller values first. Without `nprobe`, search probes Quantization remains approximate even when all clusters are probed. The [complete quick start](https://vectordb-ntu.github.io/RaBitQ-Library/quick_start/) explains result handling, measures recall while varying `nprobe`, and shows save/load. Code written for -0.7 still runs in 0.8 with deprecation warnings; see the -[migration guide](https://vectordb-ntu.github.io/RaBitQ-Library/python_migration/). +0.8 may need changes for 0.9; see the +[migration guide](https://vectordb-ntu.github.io/RaBitQ-Library/python_migration/#from-08-to-09). For other indexes, see the [HNSW-RaBitQ](https://vectordb-ntu.github.io/RaBitQ-Library/index/hnsw/#minimal-workflow) and [SymphonyQG](https://vectordb-ntu.github.io/RaBitQ-Library/index/qg/#minimal-workflow) examples. @@ -208,7 +208,7 @@ listed above. - [Documentation](https://vectordb-ntu.github.io/RaBitQ-Library/) and [algorithm overview](https://vectordb-ntu.github.io/RaBitQ-Library/rabitq/rabitq/). - [Papers and citations](https://vectordb-ntu.github.io/RaBitQ-Library/papers/) for the research behind the library. -- [Release notes](https://github.com/VectorDB-NTU/RaBitQ-Library/releases) and [0.7 migration guide](https://vectordb-ntu.github.io/RaBitQ-Library/modular_migration/). +- [Release notes](https://github.com/VectorDB-NTU/RaBitQ-Library/releases), the [Python migration guide](https://vectordb-ntu.github.io/RaBitQ-Library/python_migration/) and the [0.7 migration guide](https://vectordb-ntu.github.io/RaBitQ-Library/modular_migration/). - [GPU implementation](https://github.com/Stardust-SJF/cuvs_rabitq/tree/cuvs_ivf_rabitq) in cuVS. ## Contributing diff --git a/docs/docs/index.md b/docs/docs/index.md index 71a74a18..a7c80a0e 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -36,7 +36,7 @@ python -m pip install "rabitqlib>=0.8.5" ## Choose your index -All three indexes support L2 and inner-product search, with save/load support. +All three indexes support L2, inner-product and cosine search, with save/load support. Start with IVF-RaBitQ for the complete introductory example, then compare on your own data.
diff --git a/docs/docs/index/hnsw.md b/docs/docs/index/hnsw.md index 63a67406..2cf6f78e 100644 --- a/docs/docs/index/hnsw.md +++ b/docs/docs/index/hnsw.md @@ -30,7 +30,8 @@ The first `add` trains an untrained index on the added vectors, as for `num_clusters`, it trains one centroid per row, and `num_clusters` then reports the row count. An empty first `add` raises `RuntimeError`. `train` and `set_centroids` work as for [IVF-RaBitQ](ivf.md#training-centroids-in-python), -with `num_clusters` centroids (default 16) and always RaBitQKMeans; `index.cp` +with `num_clusters` centroids (default 16) and always RaBitQKMeans, but +`set_centroids` takes no `num_threads`; `index.cp` starts from the same defaults with the index `seed`. The first `add` into the empty index links vectors with their exact coordinates, like the 0.7 `build`; later adds link through the stored codes (see [Recall after `add`](#recall-after-add)), @@ -74,7 +75,7 @@ For build setup, see [C++ integration](../cpp_integration.md). | `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. | +| `k`, `ef_search` | Result count, from 1 to 2^31, and search window. `k` may exceed the stored point count; missing results are padded with ID `-1` (C++ `kNoId`) and `+inf`. An omitted `ef_search` (Python `None`) uses `max(k, 64)`, an explicit 0 raises `ValueError` (C++ `std::invalid_argument`), a smaller value is raised to at least `k`, and a value above the stored point count is clamped to it. It replaces `ef`, which 0.9 removed. | In C++, the construction settings are fields of `HnswOptions`, and `ef_search` and `num_threads` fields of `GraphSearchOptions`. @@ -182,9 +183,8 @@ See the shared [concurrency contract](usage.md#threading-and-file-paths). ## Updating an index 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). +the original data. `save` always writes index format 2; see +[persistence](#persistence). ```c++ Id HnswIndex::add(const float* data, size_t num_points, const AddOptions& options = {}); @@ -293,10 +293,11 @@ Callers that track how many points they removed can apply this directly. `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 capacity growth, and a file without removals is -unchanged. +it survives `save`, `load`, and capacity growth, and a file without removals +carries no marks. -A file that has removals cannot be read by earlier releases. Releases 0.3.7 +In the layout written before 0.9, a file that has removals cannot be read by +releases before 0.5.2. Releases 0.3.7 through 0.5.1 check every cluster ID on `load` and reject the file as invalid instead of returning removed points. Releases before 0.3.7 do not check cluster IDs, so do not open such a file with them. diff --git a/docs/docs/index/ivf.md b/docs/docs/index/ivf.md index 7f897282..a20d4b51 100644 --- a/docs/docs/index/ivf.md +++ b/docs/docs/index/ivf.md @@ -56,7 +56,7 @@ centroids and cluster IDs. | `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`). | +| `k`, `nprobe` | Result count, from 1 to 2^31, and positive cluster probe count. `k` may exceed the stored point count; missing results are padded with ID `-1` (C++ `kNoId`) and `+inf`. `nprobe` defaults to `num_clusters / 16`, rounded and at least 1, when omitted (Python `None`); an explicit 0 raises `ValueError` (C++ `std::invalid_argument`). | | `high_accuracy` | Defaults to automatic selection (Python `None`): HACC for 4–9 bits, standard FastScan otherwise. | In C++, `nbits`, `seed`, `metric` and `routing` are fields of `IvfOptions`, and @@ -158,7 +158,7 @@ auto routing = ivf.routing(); // resolved routing type error instead of probing every cluster. Use `flat` or `flat_rabitq` when a query should probe most clusters. -All choices support L2 and inner product. Flat RaBitQ uses the IVF-RaBitQ rotation and +All choices support every metric. Flat RaBitQ uses the IVF-RaBitQ rotation and padded domain, retains float32 centroids for refinement, and stores its mean and codes in the main index file. Its code precision is independent of the index's `nbits`. It trades additional code storage and an O(cluster count) query work @@ -324,7 +324,8 @@ Concurrent Python searches may use independent `nprobe`, `high_accuracy`, and ## Updating an index `IvfIndex` supports `add()` and `remove()` on a trained or loaded index without -the original dataset. Updates preserve the file format. +the original dataset. `save` always writes index format 2; see +[how removal is stored](#how-removal-is-stored). ```c++ Id IvfIndex::add(const float* data, size_t num_points, const AddOptions& options = {}); diff --git a/docs/docs/index/qg.md b/docs/docs/index/qg.md index 075e5ccb..5f74d6df 100644 --- a/docs/docs/index/qg.md +++ b/docs/docs/index/qg.md @@ -78,7 +78,7 @@ index, and `train` only checks its input. | `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. | +| `k`, `ef_search` | `k` is from 1 to 2^31 and may exceed the point count; slots the graph cannot fill are padded with ID `-1` (C++ `kNoId`) and distance `+inf`. An omitted `ef_search` (Python `None`) uses `max(k, 64)`, an explicit 0 raises `ValueError` (C++ `std::invalid_argument`), and smaller values are raised to `k`, as for HNSW-RaBitQ. It replaces `ef`, which 0.9 removed. | | `num_threads` | `add` defaults to every available logical CPU, capped by `OMP_NUM_THREADS`, and `search` to 1; Python `None` and C++ 0 for `add` select the available CPUs. | In C++, the construction settings are fields of `SymqgOptions`, and `ef_search` @@ -153,7 +153,7 @@ outputs and an unchanged index. Python `search(queries, k, ef_search=None, *, num_threads=None)` accepts a two-dimensional query array and returns `(ids, distances)` arrays of shape `(num_queries, k)`, including empty batches. It defaults to one worker; `num_threads=0` selects the -available logical CPU count, capped by the number of queries. +available logical CPU count, capped by `OMP_NUM_THREADS` and by the number of queries. Queries use the original dimension, including when the internal rotation pads it. Python searches also use per-call `ef_search` values. For access rules, see the diff --git a/docs/docs/modular_migration.md b/docs/docs/modular_migration.md index e83e43cd..d6cd5d7e 100644 --- a/docs/docs/modular_migration.md +++ b/docs/docs/modular_migration.md @@ -175,8 +175,8 @@ HNSW-RaBitQ adds `num_stored_points`, and SymphonyQG adds `max_elements` and ID bounds, append offsets, and minimum resize capacity. Use `num_points` for a live count, without subtracting a separate deletion counter. -The IVF-RaBitQ constructor keyword `max_elements` still specifies the required initial -build size; 0.8 deprecates it and 0.9 removes it (see the [migration guide](python_migration.md)). SymphonyQG's C++ `num_vertices()` still returns the configured graph +In 0.7, the IVF-RaBitQ constructor keyword `max_elements` still specified the required +initial build size; 0.8 deprecated it and 0.9 removed it (see the [migration guide](python_migration.md)). SymphonyQG's C++ `num_vertices()` still returns the configured graph size for builders. Existing index files need no conversion: loading recovers counts from their removal markers. diff --git a/docs/docs/rabitq/rabitq.md b/docs/docs/rabitq/rabitq.md index 47c5c355..012a0d8a 100644 --- a/docs/docs/rabitq/rabitq.md +++ b/docs/docs/rabitq/rabitq.md @@ -14,7 +14,8 @@ with a low-bit unsigned integer and store per-vector factors for distance estima 3. **Estimate.** Combine the codes, factors and rotated query to estimate squared L2 or inner-product distance (`1 - dot`). See [Estimation](estimator.md). -For cosine search, normalize data and queries before rotation and use inner product. +For cosine search, normalize data and queries before rotation and use inner product; +the indexes' [cosine metric](../index/usage.md#the-cosine-metric) does this for you. The probabilistic error intervals can guide [reranking](reranking.md), but do not make approximate search exact. Recall depends on the data and search settings. diff --git a/docs/docs/releases/unreleased.md b/docs/docs/releases/unreleased.md index bcf9f75b..88833cb6 100644 --- a/docs/docs/releases/unreleased.md +++ b/docs/docs/releases/unreleased.md @@ -103,7 +103,7 @@ Move to the new classes as follows: 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. +- The C++ examples in `sample/cpp` and the IVF `add` hot-path benchmark use the new classes. `symqg_indexing` takes `nbits` (32 for raw vectors, 4 or 8, default 32) and still reads 0 as raw vectors; it no longer prints stage times or the average degree. Its optional thread count 0 selects every available CPU. The default thread counts of `symqg_indexing` and `ivf_rabitq_indexing` are now capped by `OMP_NUM_THREADS`, which they ignored. `ivf_rabitq_indexing`, `hnsw_rabitq_indexing` and `symqg_indexing` accept `cosine` as the metric and reject unknown metric names; both used to build an L2 index silently. - `qgkmeans::QGKMeansParameters` uses the Python names (#233): `graph_degree` becomes `max_degree`, `ef_build` becomes `ef_construction`, and `quantization_bits` (0, 4 or 8) becomes `nbits` (32, 4 or 8, with 32 for raw float32). The fields keep their order and types. An `nbits` of 0 is rejected, so code that initialized the field positionally with 0 must pass 32. `QGAssigner` keeps its constructor, including `quantization_bits` with 0 for raw storage. - Messages follow the names: `QGKMeans nbits must be 4, 8, or 32`, `QGKMeans max_degree must be a positive multiple of 32`, `QGKMeans requires more centroids than max_degree` and `QGKMeans ef_construction and ef_search must be positive`. diff --git a/sample/cpp/hnsw_rabitq_indexing.cpp b/sample/cpp/hnsw_rabitq_indexing.cpp index 929aa6a9..10e56796 100644 --- a/sample/cpp/hnsw_rabitq_indexing.cpp +++ b/sample/cpp/hnsw_rabitq_indexing.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include "rabitqlib/core/detail/eigen.hpp" @@ -26,7 +27,7 @@ int run(int argc, char* argv[]) { << "arg5: ef for indexing \n" << "arg6: total number of bits for quantization\n" << "arg7: path for saving index\n" - << "arg8: metric type (\"l2\" or \"ip\"), l2 by default\n" + << "arg8: metric type (\"l2\", \"ip\" or \"cosine\"), l2 by default\n" << "arg9: if use faster quantization (\"true\" or \"false\"), false by " "default\n"; return 1; @@ -41,17 +42,18 @@ int run(int argc, char* argv[]) { char* index_file = argv[7]; rabitqlib::MetricType metric_type = rabitqlib::METRIC_L2; - if (argc > 8) { - std::string metric_str(argv[8]); - if (metric_str == "ip" || metric_str == "IP") { - metric_type = rabitqlib::METRIC_IP; - } - } - if (metric_type == rabitqlib::METRIC_IP) { - std::cout << "Metric Type: IP\n"; - } else if (metric_type == rabitqlib::METRIC_L2) { - std::cout << "Metric Type: L2\n"; + const char* metric_name = "L2"; + const std::string metric_str = argc > 8 ? argv[8] : "l2"; + if (metric_str == "ip" || metric_str == "IP") { + metric_type = rabitqlib::METRIC_IP; + metric_name = "IP"; + } else if (metric_str == "cosine" || metric_str == "COSINE") { + metric_type = rabitqlib::METRIC_COSINE; + metric_name = "Cosine"; + } else if (metric_str != "l2" && metric_str != "L2") { + throw std::invalid_argument("Metric type must be l2, ip or cosine"); } + std::cout << "Metric Type: " << metric_name << '\n'; bool faster_quant = false; if (argc > 9) { diff --git a/sample/cpp/ivf_rabitq_indexing.cpp b/sample/cpp/ivf_rabitq_indexing.cpp index e1cbdf8e..3d832032 100644 --- a/sample/cpp/ivf_rabitq_indexing.cpp +++ b/sample/cpp/ivf_rabitq_indexing.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include "rabitqlib/core/detail/eigen.hpp" @@ -24,24 +25,25 @@ int run(int argc, char** argv) { << "arg3: path for cluster ids file, format .ivecs\n" << "arg4: total number of bits for quantization\n" << "arg5: path for saving index\n" - << "arg6: metric type (\"l2\" or \"ip\"), l2 by default\n" + << "arg6: metric type (\"l2\", \"ip\" or \"cosine\"), l2 by default\n" << "arg7: if use faster quantization (\"true\" or \"false\"), false by " "default\n"; return 1; } rabitqlib::MetricType metric_type = rabitqlib::METRIC_L2; - if (argc > 6) { - std::string metric_str(argv[6]); - if (metric_str == "ip" || metric_str == "IP") { - metric_type = rabitqlib::METRIC_IP; - } - } - if (metric_type == rabitqlib::METRIC_IP) { - std::cout << "Metric Type: IP\n"; - } else if (metric_type == rabitqlib::METRIC_L2) { - std::cout << "Metric Type: L2\n"; + const char* metric_name = "L2"; + const std::string metric_str = argc > 6 ? argv[6] : "l2"; + if (metric_str == "ip" || metric_str == "IP") { + metric_type = rabitqlib::METRIC_IP; + metric_name = "IP"; + } else if (metric_str == "cosine" || metric_str == "COSINE") { + metric_type = rabitqlib::METRIC_COSINE; + metric_name = "Cosine"; + } else if (metric_str != "l2" && metric_str != "L2") { + throw std::invalid_argument("Metric type must be l2, ip or cosine"); } + std::cout << "Metric Type: " << metric_name << '\n'; bool faster_quant = false; if (argc > 7) { diff --git a/sample/cpp/symqg_indexing.cpp b/sample/cpp/symqg_indexing.cpp index 6cd2b09f..b15c313f 100644 --- a/sample/cpp/symqg_indexing.cpp +++ b/sample/cpp/symqg_indexing.cpp @@ -20,7 +20,7 @@ int run(int argc, char** argv) { << "arg2: degree bound for symqg, must be a multiple of 32\n" << "arg3: ef for indexing \n" << "arg4: path for saving index\n" - << "arg5: metric type (\"l2\" or \"ip\"), l2 by default\n" + << "arg5: metric type (\"l2\", \"ip\" or \"cosine\"), l2 by default\n" << "arg6: nbits (32 or 0 for raw vectors, 4 or 8), 32 by default\n" << "arg7: init (pipnn or random), pipnn by default\n" << "arg8: threads, 0 or omitted for all (OMP_NUM_THREADS caps it)\n"; @@ -33,17 +33,18 @@ int run(int argc, char** argv) { char* index_file = argv[4]; rabitqlib::MetricType metric_type = rabitqlib::METRIC_L2; - if (argc > 5) { - std::string metric_str(argv[5]); - if (metric_str == "ip" || metric_str == "IP") { - metric_type = rabitqlib::METRIC_IP; - } - } - if (metric_type == rabitqlib::METRIC_IP) { - std::cout << "Metric Type: IP\n"; - } else if (metric_type == rabitqlib::METRIC_L2) { - std::cout << "Metric Type: L2\n"; + const char* metric_name = "L2"; + const std::string metric_str = argc > 5 ? argv[5] : "l2"; + if (metric_str == "ip" || metric_str == "IP") { + metric_type = rabitqlib::METRIC_IP; + metric_name = "IP"; + } else if (metric_str == "cosine" || metric_str == "COSINE") { + metric_type = rabitqlib::METRIC_COSINE; + metric_name = "Cosine"; + } else if (metric_str != "l2" && metric_str != "L2") { + throw std::invalid_argument("Metric type must be l2, ip or cosine"); } + std::cout << "Metric Type: " << metric_name << '\n'; size_t nbits = argc > 6 ? static_cast(atoi(argv[6])) : 32; if (nbits == 0) { // the 0.8 spelling of raw vectors nbits = 32; diff --git a/tests/integration/cpp_example_index_check.cpp b/tests/integration/cpp_example_index_check.cpp index 22f96728..ffe03410 100644 --- a/tests/integration/cpp_example_index_check.cpp +++ b/tests/integration/cpp_example_index_check.cpp @@ -19,8 +19,10 @@ int main(int argc, char** argv) { throw std::invalid_argument("Expected kind, index, data, metric and bits"); } const std::string kind(argv[1]); - const auto metric = - std::string(argv[4]) == "ip" ? rabitqlib::METRIC_IP : rabitqlib::METRIC_L2; + const std::string metric_name(argv[4]); + const auto metric = metric_name == "ip" ? rabitqlib::METRIC_IP + : metric_name == "cosine" ? rabitqlib::METRIC_COSINE + : rabitqlib::METRIC_L2; const size_t bits = std::stoull(argv[5]); rabitqlib::RowMajorArray data; rabitqlib::load_vecs(argv[3], data); @@ -32,7 +34,7 @@ int main(int argc, char** argv) { index.nbits() != bits) { throw std::runtime_error("Example index metadata does not match input"); } - // Unit vectors make self the exact winner for the IP fixture as well. + // Unit vectors make self the exact winner for the IP and cosine fixtures too. for (size_t row : std::array{0, count / 2, count - 1}) { rabitqlib::Id id = rabitqlib::kNoId; float distance = 0; diff --git a/tests/python/test_cpp_clustering_examples.py b/tests/python/test_cpp_clustering_examples.py index bf9860b0..c797d2cb 100644 --- a/tests/python/test_cpp_clustering_examples.py +++ b/tests/python/test_cpp_clustering_examples.py @@ -33,8 +33,10 @@ def read_vecs(path, rows, cols, dtype): @pytest.mark.parametrize("method,k", [("qgkmeans", 33), ("rabitqkmeans", 16)]) -@pytest.mark.parametrize("metric", ["l2", "ip"]) -def test_cpp_clustering_file_outputs(tmp_path, method, k, metric): +@pytest.mark.parametrize("index_metric", ["l2", "ip", "cosine"]) +def test_cpp_clustering_file_outputs(tmp_path, method, k, index_metric): + # The clustering examples take l2 or ip; unit vectors cluster alike for cosine. + metric = "l2" if index_metric == "l2" else "ip" data = np.random.default_rng(42).standard_normal((512, 65)).astype(np.float32) if metric == "ip": data /= np.linalg.norm(data, axis=1, keepdims=True) @@ -75,7 +77,7 @@ def test_cpp_clustering_file_outputs(tmp_path, method, k, metric): labels_path, 3, index_path, - metric, + index_metric, ) else: result = run_cpp( @@ -87,7 +89,7 @@ def test_cpp_clustering_file_outputs(tmp_path, method, k, metric): 32, 5, index_path, - metric, + index_metric, ) assert result.returncode == 0, result.stdout + result.stderr result = run_cpp( @@ -95,12 +97,31 @@ def test_cpp_clustering_file_outputs(tmp_path, method, k, metric): "ivf" if method == "qgkmeans" else "hnsw", index_path, source, - metric, + index_metric, 3 if method == "qgkmeans" else 5, ) assert result.returncode == 0, result.stdout + result.stderr +@pytest.mark.parametrize( + "example,args", + [ + ("ivf_rabitq_indexing", ["data.fvecs", "c.fvecs", "ids.ivecs", 3, "index"]), + ( + "hnsw_rabitq_indexing", + ["data.fvecs", "c.fvecs", "ids.ivecs", 16, 32, 5, "index"], + ), + ("symqg_indexing", ["data.fvecs", 32, 64, "index"]), + ], +) +def test_cpp_indexing_examples_reject_unknown_metric(tmp_path, example, args): + args = [tmp_path / arg if isinstance(arg, str) else arg for arg in args] + result = run_cpp(example, *args, "dot") + assert result.returncode == 1 + assert "Metric type must be l2, ip or cosine" in result.stderr + assert not (tmp_path / "index").exists() + + @pytest.mark.parametrize("method", ["qgkmeans", "rabitqkmeans"]) def test_cpp_clustering_synthetic_demo(method): result = run_cpp(method)