From 3184948ac5ec36273cf34bb3d343217f0c6cbb50 Mon Sep 17 00:00:00 2001 From: gouyt13clear Date: Sat, 21 Nov 2026 00:25:05 +0800 Subject: [PATCH] fix(index): scale given centroids of cosine indexes to unit length Cosine indexes scale data and queries to unit length, but set_centroids and construct used the given centroids as they were. The codes are residuals against the centroids, so centroids far from the unit sphere, such as the means of unscaled data, ruined the estimates: with centroids of norm about 100, recall@10 fell to 0.001 at 5 bits. ivf::IVF and hnsw::HierarchicalNSW now scale centroids given to set_centroids or construct, after checking their coordinates, as they scale data. train keeps the centroids k-means computes from the scaled data, so trained indexes are unchanged. IvfIndex, HnswIndex and the Python classes get the fix through set_centroids. Closes #259. --- docs/docs/index/usage.md | 13 ++-- docs/docs/releases/unreleased.md | 2 +- docs/formats.md | 4 +- include/rabitqlib/index/hnsw/hnsw.hpp | 10 ++- include/rabitqlib/index/hnsw_index.hpp | 1 + include/rabitqlib/index/ivf/ivf.hpp | 12 +++- include/rabitqlib/index/ivf_index.hpp | 1 + python_bindings/__init__.pyi | 6 +- python_bindings/hnsw_bindings.cpp | 3 +- python_bindings/ivf_bindings.cpp | 3 +- src/index/hnsw.cpp | 17 ++++- src/index/ivf.cpp | 15 +++- tests/python/test_cosine.py | 7 +- tests/unit/rabitqlib/index/hnsw_test.cpp | 45 +++++++++--- tests/unit/rabitqlib/index/ivf_test.cpp | 90 ++++++++++++++++++++++++ 15 files changed, 199 insertions(+), 30 deletions(-) diff --git a/docs/docs/index/usage.md b/docs/docs/index/usage.md index 1e55838b..18cfee91 100644 --- a/docs/docs/index/usage.md +++ b/docs/docs/index/usage.md @@ -33,11 +33,14 @@ the index classes do not expose a rotator choice. With `metric="cosine"` (C++ `METRIC_COSINE`), every index scales data and queries to unit length, stores the inner-product codes of the scaled vectors, and returns `1 - cos` as the distance, the inner-product distance `1 - dot` of unit vectors. -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` are used as given; `train`, and the first -`add` that trains, compute them from the scaled vectors with spherical k-means. +Centroids passed to `set_centroids` are scaled the same way, because the codes are +residuals against them: centroids far from the unit sphere, such as the means of +unscaled data, would ruin the estimates. `train`, and the first `add` that trains, +compute centroids from the scaled vectors with spherical k-means and use them as +computed. Results equal those of a `metric="ip"` index built from the same vectors, +and given the same centroids, after this scaling. A zero vector stays zero, as in +hnswlib and Faiss: its true distance to every vector is 1, which quantized storage +estimates like any other distance. The index checks the original coordinates first, as above. Because it then trains on scaled copies, invalid training data is reported as `IVF training data ...` or diff --git a/docs/docs/releases/unreleased.md b/docs/docs/releases/unreleased.md index aec283cb..6d289541 100644 --- a/docs/docs/releases/unreleased.md +++ b/docs/docs/releases/unreleased.md @@ -44,7 +44,7 @@ ## Python changes -- New `metric="cosine"` for `IvfIndex`, `HnswIndex` and `SymqgIndex` (#212). The index scales data and queries to unit length and returns `1 - cos`; results equal those of a `metric="ip"` index built from the scaled vectors. A zero vector stays zero, so its true distance to every vector is 1. The saved file records the metric, so a loaded index keeps scaling. `index.metric` can now return `"cosine"`, and an invalid metric raises `metric must be 'l2', 'ip' or 'cosine'`. See [the cosine metric](../index/usage.md#the-cosine-metric). +- New `metric="cosine"` for `IvfIndex`, `HnswIndex` and `SymqgIndex` (#212). The index scales data, queries and centroids passed to `set_centroids` to unit length and returns `1 - cos`; results equal those of a `metric="ip"` index built from the scaled vectors and given the scaled centroids (#259). A zero vector stays zero, so its true distance to every vector is 1. The saved file records the metric, so a loaded index keeps scaling. `index.metric` can now return `"cosine"`, and an invalid metric raises `metric must be 'l2', 'ip' or 'cosine'`. See [the cosine metric](../index/usage.md#the-cosine-metric). - Point IDs are `int64` at the Python boundary (#211): - `search` returns `int64` IDs, and slots without a neighbor hold `-1` instead of `2**32 - 1`; their distance is still `inf`. Code that compares IDs with `2**32 - 1`, `0xFFFFFFFF` or `np.iinfo(np.uint32).max` must change; `np.isfinite(distances)`, recommended since 0.8.2, works before and after. - `add` returns `int64` IDs. `remove` already took any integer IDs and still rejects `-1` and other out-of-range values without removing anything. diff --git a/docs/formats.md b/docs/formats.md index 1a401f6d..09fbc9d0 100644 --- a/docs/formats.md +++ b/docs/formats.md @@ -192,9 +192,9 @@ No bit is defined in version 2. Bits are assigned when a feature needs one. Exam ### Metrics -L2 and inner product are as in [Distance conventions](development.md#distance-conventions). Cosine stores the codes and factors of inner product over L2-normalized vectors. The index normalizes data on `train`, `add` and construction, and queries on `search`, and reports `1 - cos` as the distance. It is a stored metric, not a flag of the caller, so a reloaded index keeps normalizing. +L2 and inner product are as in [Distance conventions](development.md#distance-conventions). Cosine stores the codes and factors of inner product over L2-normalized vectors. The index normalizes data on `train`, `add` and construction, centroids given to `set_centroids` or construction, and queries on `search`, and reports `1 - cos` as the distance. It is a stored metric, not a flag of the caller, so a reloaded index keeps normalizing. -Normalization computes `scale = 1 / sqrt(s)` in double precision, where `s` is the sum of the squared coordinates added in coordinate order in double precision; each coordinate is multiplied by `scale` in double precision and rounded once to float32. The product of two float32 values is exact in double precision, so the sum does not depend on whether a compiler fuses multiply and add. A zero vector stays zero, so its true distance to every vector is 1. Every vector section (codes, raw float32 vectors and the IVF rerank vectors) holds the normalized vectors, so a cosine file equals the inner-product file of the normalized vectors except for `metric`. Centroids are stored as the index was given or trained them. +Normalization computes `scale = 1 / sqrt(s)` in double precision, where `s` is the sum of the squared coordinates added in coordinate order in double precision; each coordinate is multiplied by `scale` in double precision and rounded once to float32. The product of two float32 values is exact in double precision, so the sum does not depend on whether a compiler fuses multiply and add. A zero vector stays zero, so its true distance to every vector is 1. Every vector section (codes, raw float32 vectors and the IVF rerank vectors) holds the normalized vectors, so a cosine file equals the inner-product file of the normalized vectors except for `metric`. Centroids are stored as trained, or normalized as above when they were given. ### Point IDs diff --git a/include/rabitqlib/index/hnsw/hnsw.hpp b/include/rabitqlib/index/hnsw/hnsw.hpp index 6861ef33..b5c6debb 100644 --- a/include/rabitqlib/index/hnsw/hnsw.hpp +++ b/include/rabitqlib/index/hnsw/hnsw.hpp @@ -112,7 +112,8 @@ class HierarchicalNSW { * these centroids; the first add into the empty graph links like construct. * * @param num_clusters Number of centroids, from 1 through 2^31 - * @param centroids Centroid vectors (num_clusters * dim) in the original coordinates + * @param centroids Centroid vectors (num_clusters * dim) in the original coordinates; + * a cosine index scales them to unit length, as it does data */ void set_centroids(size_t num_clusters, const float* centroids); @@ -135,6 +136,7 @@ class HierarchicalNSW { ); // Centroids and data use the original dimension; cluster_ids has num_points entries. + // A cosine index scales the data and the centroids to unit length. // Input buffers must remain valid until this synchronous call returns or throws; // the index retains no pointers to them afterward. // fast_quantization selects fixed-scale extra-bit quantization instead of exact scale @@ -228,6 +230,10 @@ class HierarchicalNSW { // Borrows construct() input only while its workers run; cleared on success or failure. const float* construction_data_{nullptr}; + // set_centroids with given = true scales the centroids of a cosine index to unit + // length, as data and queries are; train passes centroids trained on scaled data. + void set_centroids_impl(size_t num_clusters, const float* centroids, bool given); + friend struct HnswTestAccess; friend struct detail::HnswSearchAccess; @@ -248,7 +254,7 @@ class HierarchicalNSW { size_t base_layer_max_degree_{0}; size_t ef_construction_{0}; MetricType metric_type_{METRIC_L2}; // METRIC_IP for the cosine metric - bool cosine_{false}; // normalize data and queries; metric_type_ is METRIC_IP + bool cosine_{false}; // normalize data, queries, given centroids; metric_type_ is IP double level_multiplier_{0.0}; // max_level_ == -1 and entry_point_id_ == kPidMax mark an empty graph. diff --git a/include/rabitqlib/index/hnsw_index.hpp b/include/rabitqlib/index/hnsw_index.hpp index 83c5255b..e8cf5103 100644 --- a/include/rabitqlib/index/hnsw_index.hpp +++ b/include/rabitqlib/index/hnsw_index.hpp @@ -100,6 +100,7 @@ class HnswIndex { * @brief Use the given centroids instead of training. * * Allowed while the index stores no points. The index is unchanged if this throws. + * A cosine index scales the centroids to unit length, as it does data. * * @param centroids num_clusters() * dim values */ diff --git a/include/rabitqlib/index/ivf/ivf.hpp b/include/rabitqlib/index/ivf/ivf.hpp index 9985edc0..f1f16f91 100644 --- a/include/rabitqlib/index/ivf/ivf.hpp +++ b/include/rabitqlib/index/ivf/ivf.hpp @@ -100,7 +100,7 @@ class IVF { std::unique_ptr> rotator_; std::vector clusters_; MetricType metric_type_ = METRIC_L2; // METRIC_IP for the cosine metric - bool cosine_ = false; // normalize data and queries; metric_type_ is METRIC_IP + bool cosine_ = false; // normalize data, queries, given centroids; metric_type_ is IP float (*ip_func_)(const float*, const uint8_t*, size_t) = nullptr; static constexpr uint64_t kRawFormatMagic = 0x3157415251464252ULL; @@ -163,6 +163,10 @@ class IVF { [[nodiscard]] std::unique_ptr make_initializer() const; + // set_centroids with given = true scales the centroids of a cosine index to unit + // length, as data and queries are; train passes centroids trained on scaled data. + void set_centroids_impl(const float* centroids, size_t num_threads, bool given); + // Reset the index and allocate a new initializer and per-cluster storage void allocate_storage(const std::vector& cluster_sizes); @@ -299,7 +303,8 @@ class IVF { * * Builds the centroid initializer and empty clusters, so the index can add points. * An index created with a point count is built by construct instead, so this - * throws std::logic_error for it. The index is unchanged if this throws. + * throws std::logic_error for it. The index is unchanged if this throws. A cosine + * index scales the centroids to unit length, as it does data. * * @param centroids Centroid vectors (num_clusters() * dim) * @param num_threads Threads used to build the centroid initializer @@ -311,7 +316,8 @@ class IVF { /** * @brief Quantize every point into its cluster and build the centroid initializer. * - * Replaces any existing contents of the index. + * Replaces any existing contents of the index. A cosine index scales the data and + * the centroids to unit length. * * @param data Data points (max_elements() * dim) * @param centroids Centroid vectors (num_clusters() * dim) diff --git a/include/rabitqlib/index/ivf_index.hpp b/include/rabitqlib/index/ivf_index.hpp index 840a0374..0a132d9f 100644 --- a/include/rabitqlib/index/ivf_index.hpp +++ b/include/rabitqlib/index/ivf_index.hpp @@ -105,6 +105,7 @@ class IvfIndex { * @brief Use the given centroids instead of training. * * Allowed while the index stores no points. The index is unchanged if this throws. + * A cosine index scales the centroids to unit length, as it does data. * * @param centroids num_clusters() * dim values * @param num_threads Worker count for building the centroid routing diff --git a/python_bindings/__init__.pyi b/python_bindings/__init__.pyi index 36b34e53..4675a026 100644 --- a/python_bindings/__init__.pyi +++ b/python_bindings/__init__.pyi @@ -209,7 +209,8 @@ class IvfIndex: ---------- centroids : array_like of float, shape (num_clusters, dim) Centroids in the original, unpadded coordinates. Converted to - contiguous float32; a copy may be made. + contiguous float32; a copy may be made. A cosine index scales them + to unit length, as it does data. num_threads : int, optional Keyword-only. Worker count for rotating the centroids and building the centroid routing. None (default) and 0 select the available CPU count, @@ -568,7 +569,8 @@ class HnswIndex: ---------- centroids : array_like of float, shape (num_clusters, dim) Centroids in the original, unpadded coordinates. Converted to - contiguous float32; a copy may be made. + contiguous float32; a copy may be made. A cosine index scales them + to unit length, as it does data. Notes ----- diff --git a/python_bindings/hnsw_bindings.cpp b/python_bindings/hnsw_bindings.cpp index 543b1a89..397303fb 100644 --- a/python_bindings/hnsw_bindings.cpp +++ b/python_bindings/hnsw_bindings.cpp @@ -415,7 +415,8 @@ Parameters ---------- centroids : array_like of float, shape (num_clusters, dim) Centroids in the original, unpadded coordinates. Converted to - contiguous float32; a copy may be made. + contiguous float32; a copy may be made. A cosine index scales them + to unit length, as it does data. Notes ----- diff --git a/python_bindings/ivf_bindings.cpp b/python_bindings/ivf_bindings.cpp index 2f099f42..d3b1c731 100644 --- a/python_bindings/ivf_bindings.cpp +++ b/python_bindings/ivf_bindings.cpp @@ -421,7 +421,8 @@ Parameters ---------- centroids : array_like of float, shape (num_clusters, dim) Centroids in the original, unpadded coordinates. Converted to - contiguous float32; a copy may be made. + contiguous float32; a copy may be made. A cosine index scales them + to unit length, as it does data. num_threads : int, optional Keyword-only. Worker count for rotating the centroids and building the centroid routing. None (default) and 0 select the available CPU count, diff --git a/src/index/hnsw.cpp b/src/index/hnsw.cpp index e59d7439..bceedd5e 100644 --- a/src/index/hnsw.cpp +++ b/src/index/hnsw.cpp @@ -753,9 +753,13 @@ void HierarchicalNSW::construct( check_coordinates(data, num_points * dim_, dim_, "HNSW construction data"); check_coordinates(centroids, num_clusters * dim_, dim_, "HNSW construction centroids"); std::vector normalized; + std::vector scaled_centroids; if (cosine_) { normalized = index_detail::normalized_rows(data, num_points, dim_, num_threads); data = normalized.data(); + scaled_centroids = + index_detail::normalized_rows(centroids, num_clusters, dim_, num_threads); + centroids = scaled_centroids.data(); } try { @@ -815,6 +819,12 @@ void HierarchicalNSW::link_exact( } void HierarchicalNSW::set_centroids(size_t num_clusters, const float* centroids) { + set_centroids_impl(num_clusters, centroids, /*given=*/true); +} + +void HierarchicalNSW::set_centroids_impl( + size_t num_clusters, const float* centroids, bool given +) { if (level0_record_bytes_ == 0) { throw std::logic_error("HNSW index must be initialized before setting centroids"); } @@ -831,6 +841,11 @@ void HierarchicalNSW::set_centroids(size_t num_clusters, const float* centroids) throw std::invalid_argument("HNSW centroids exceed addressable storage"); } check_coordinates(centroids, num_clusters * dim_, dim_, "HNSW centroids"); + std::vector scaled; + if (cosine_ && given) { + scaled = index_detail::normalized_rows(centroids, num_clusters, dim_, 1); + centroids = scaled.data(); + } // construct rotates centroids the same way, so both paths quantize identically. AlignedStorage rotated( @@ -881,7 +896,7 @@ void HierarchicalNSW::train( } rabitqkmeans::RaBitQKMeans kmeans(dim_, num_clusters, cp); kmeans.train_centroids(num_points, data); - set_centroids(num_clusters, kmeans.centroids.data()); + set_centroids_impl(num_clusters, kmeans.centroids.data(), /*given=*/false); } template diff --git a/src/index/ivf.cpp b/src/index/ivf.cpp index b44ae798..4b0f1a35 100644 --- a/src/index/ivf.cpp +++ b/src/index/ivf.cpp @@ -277,6 +277,10 @@ std::unique_ptr IVF::make_initializer() const { } void IVF::set_centroids(const float* centroids, size_t num_threads) { + set_centroids_impl(centroids, num_threads, /*given=*/true); +} + +void IVF::set_centroids_impl(const float* centroids, size_t num_threads, bool given) { if (rotator_ == nullptr) { throw std::logic_error("IVF must be configured before setting centroids"); } @@ -290,6 +294,11 @@ void IVF::set_centroids(const float* centroids, size_t num_threads) { throw std::invalid_argument("IVF centroids must not be null"); } check_coordinates(centroids, num_clusters_ * dim_, dim_, "IVF centroids"); + std::vector scaled; + if (cosine_ && given) { + scaled = index_detail::normalized_rows(centroids, num_clusters_, dim_, num_threads); + centroids = scaled.data(); + } // construct rotates centroids the same way, so both paths route identically. std::vector rotated_centroids(num_clusters_ * padded_dim_); @@ -369,7 +378,7 @@ void IVF::train( kmeans.train_centroids(num_points, data); centroids = std::move(kmeans.centroids); } - set_centroids(centroids.data(), cp.num_threads); + set_centroids_impl(centroids.data(), cp.num_threads, /*given=*/false); } void IVF::construct( @@ -400,9 +409,13 @@ void IVF::construct( check_coordinates(data, max_elements_ * dim_, dim_, "IVF construction data"); check_coordinates(centroids, num_clusters_ * dim_, dim_, "IVF construction centroids"); std::vector normalized; + std::vector scaled_centroids; if (cosine_) { normalized = index_detail::normalized_rows(data, max_elements_, dim_, num_threads); data = normalized.data(); + scaled_centroids = + index_detail::normalized_rows(centroids, num_clusters_, dim_, num_threads); + centroids = scaled_centroids.data(); } allocate_storage(cluster_sizes); diff --git a/tests/python/test_cosine.py b/tests/python/test_cosine.py index c731e313..3f818ae3 100644 --- a/tests/python/test_cosine.py +++ b/tests/python/test_cosine.py @@ -104,10 +104,11 @@ def test_cosine_trained_or_given_centroids_match_inner_product(kind, setup, vect cosine.train(data[:200], num_threads=1) ip.train(normalized(data[:200]), num_threads=1) else: - # Centroids are used as given. - centroids = normalized(data[:4]) + # Given centroids are scaled to unit length, as the data is, so centroids far + # from the unit sphere match their scaled copies. + centroids = data[:4] * np.float32(50) cosine.set_centroids(centroids) - ip.set_centroids(centroids) + ip.set_centroids(normalized(centroids)) cosine.add(data, num_threads=1) ip.add(normalized(data), num_threads=1) ids, distances = cosine.search(queries, 10) diff --git a/tests/unit/rabitqlib/index/hnsw_test.cpp b/tests/unit/rabitqlib/index/hnsw_test.cpp index b0f61b13..d91e91bd 100644 --- a/tests/unit/rabitqlib/index/hnsw_test.cpp +++ b/tests/unit/rabitqlib/index/hnsw_test.cpp @@ -1203,17 +1203,46 @@ TEST(HnswCosineTest, MatchesInnerProductOverNormalizedVectors) { ); } - // construct normalizes its data too; the centroids are used as given. - std::vector cosine_ids(kCount, 0); - std::vector ip_ids(kCount, 0); - const std::vector centroids(unit_points.begin(), unit_points.begin() + kDim); + // construct and set_centroids scale given centroids to unit length, as the data is, + // so centroids far from the unit sphere match their scaled copies. + std::vector centroids(points.begin(), points.begin() + (kClusters * kDim)); + for (auto& value : centroids) { + value *= 100.0F; // like cluster means of unscaled data + } + const auto unit_centroids = rabitq_test::normalized_rows(centroids, kDim); + std::vector cosine_ids(kCount); + for (size_t i = 0; i < kCount; ++i) { + cosine_ids[i] = static_cast(i % kClusters); + } + std::vector ip_ids = cosine_ids; HierarchicalNSW cosine(kCount, kDim, 5, 8, 50, 7, METRIC_COSINE); - cosine.construct(1, centroids.data(), kCount, points.data(), cosine_ids.data(), 1); + cosine.construct( + kClusters, centroids.data(), kCount, points.data(), cosine_ids.data(), 1 + ); HierarchicalNSW ip(kCount, kDim, 5, 8, 50, 7, METRIC_IP); - ip.construct(1, centroids.data(), kCount, unit_points.data(), ip_ids.data(), 1); + ip.construct( + kClusters, unit_centroids.data(), kCount, unit_points.data(), ip_ids.data(), 1 + ); + const auto expected = ip.search(unit_queries.data(), kQueries, 10, 64, 1); + EXPECT_EQ(cosine.search(queries.data(), kQueries, 10, 64, 1), expected); + + HierarchicalNSW given(kCount, kDim, 5, 8, 50, 7, METRIC_COSINE); + given.set_centroids(kClusters, centroids.data()); + given.add(points.data(), kCount, cosine_ids.data(), false, 1); + HierarchicalNSW given_ip(kCount, kDim, 5, 8, 50, 7, METRIC_IP); + given_ip.set_centroids(kClusters, unit_centroids.data()); + given_ip.add(unit_points.data(), kCount, ip_ids.data(), false, 1); + given.save(cosine_file.path().c_str()); + given_ip.save(ip_file.path().c_str()); + rabitq_test::expect_same_sections_except_metric( + cosine_file.path(), + ip_file.path(), + rabitq_test::format2::IndexKind::Hnsw, + rabitq_test::kHnswSections + ); EXPECT_EQ( - cosine.search(queries.data(), kQueries, 10, 64, 1), - ip.search(unit_queries.data(), kQueries, 10, 64, 1) + given.search(queries.data(), kQueries, 10, 64, 1), + given_ip.search(unit_queries.data(), kQueries, 10, 64, 1) ); } diff --git a/tests/unit/rabitqlib/index/ivf_test.cpp b/tests/unit/rabitqlib/index/ivf_test.cpp index d286c04c..8919d95a 100644 --- a/tests/unit/rabitqlib/index/ivf_test.cpp +++ b/tests/unit/rabitqlib/index/ivf_test.cpp @@ -2171,6 +2171,96 @@ TEST(IvfCosineTest, ZeroVectorsHaveDistanceOne) { EXPECT_EQ(from_point.distances[zero_rank - from_point.ids.begin()], 1.0F); } +// Given centroids are scaled to unit length, as data and queries are: a cosine index given +// centroids far from the unit sphere matches an inner-product index given the scaled +// centroids, and construct estimates distances as accurately. +TEST(IvfCosineTest, ScalesGivenCentroidsToUnitLength) { + constexpr size_t kCount = 300; + constexpr size_t kQueries = 4; + const auto points = rabitq_test::rescaled_rows(random_rows(kCount, 36), kDynDim); + const auto queries = rabitq_test::rescaled_rows(random_rows(kQueries, 37), kDynDim); + auto centroids = random_rows(kDynNumClusters, 38); + for (auto& value : centroids) { + value *= 100.0F; // like cluster means of unscaled data + } + const auto unit_points = rabitq_test::normalized_rows(points, kDynDim); + const auto unit_queries = rabitq_test::normalized_rows(queries, kDynDim); + const auto unit_centroids = rabitq_test::normalized_rows(centroids, kDynDim); + std::vector assigned(kCount); + for (size_t i = 0; i < kCount; ++i) { + assigned[i] = static_cast(i % kDynNumClusters); + } + const rabitq_test::TempFile cosine_file("rabitq_ivf_given_cosine.index"); + const rabitq_test::TempFile ip_file("rabitq_ivf_given_ip.index"); + for (const size_t total_bits : {size_t{1}, size_t{5}}) { + for (const auto initializer : {InitializerType::Flat, InitializerType::HNSW}) { + SCOPED_TRACE( + std::to_string(total_bits) + " bits, initializer " + + std::to_string(static_cast(initializer)) + ); + IVF cosine( + kDynDim, + kDynNumClusters, + total_bits, + METRIC_COSINE, + 7, + RotatorType::FhtKacRotator, + initializer + ); + cosine.set_centroids(centroids.data(), 1); + cosine.add(points.data(), kCount, assigned.data(), false, 1); + IVF ip( + kDynDim, + kDynNumClusters, + total_bits, + METRIC_IP, + 7, + RotatorType::FhtKacRotator, + initializer + ); + ip.set_centroids(unit_centroids.data(), 1); + ip.add(unit_points.data(), kCount, assigned.data(), false, 1); + // The files differ only in the metric field, centroids included. + cosine.save(cosine_file.path().c_str()); + ip.save(ip_file.path().c_str()); + rabitq_test::expect_same_sections_except_metric( + cosine_file.path(), + ip_file.path(), + rabitq_test::format2::IndexKind::Ivf, + rabitq_test::kIvfSections + ); + for (size_t q = 0; q < kQueries; ++q) { + const auto expected = + search_everything(ip, unit_queries.data() + (q * kDynDim)); + const auto actual = + search_everything(cosine, queries.data() + (q * kDynDim)); + EXPECT_EQ(actual.ids, expected.ids); + EXPECT_EQ(actual.distances, expected.distances); + } + } + } + + // construct draws its rotation, so compare its estimates with exact distances. + IVF built(kCount, kDynDim, kDynNumClusters, 5, METRIC_COSINE); + built.construct(points.data(), centroids.data(), assigned.data(), false, 1); + double worst = 0; + for (size_t q = 0; q < kQueries; ++q) { + const auto hits = search_everything(built, queries.data() + (q * kDynDim)); + for (size_t r = 0; r < hits.ids.size(); ++r) { + const float* point = unit_points.data() + (size_t{hits.ids[r]} * kDynDim); + const float* query = unit_queries.data() + (q * kDynDim); + double dot = 0; + for (size_t i = 0; i < kDynDim; ++i) { + dot += static_cast(point[i]) * query[i]; + } + worst = std::max(worst, std::abs(hits.distances[r] - (1.0 - dot))); + } + } + // Scaled centroids keep the worst error below 0.06 over many rotations; unscaled + // centroids give errors near 19. + EXPECT_LT(worst, 0.5); +} + uint32_t get_size(const std::string& bytes, size_t offset) { uint32_t value = 0; std::memcpy(&value, bytes.data() + offset, sizeof(value));