From 3789633b0b8e0cd1f923b3407a27de3805588cd7 Mon Sep 17 00:00:00 2001 From: gouyt13clear Date: Thu, 19 Nov 2026 15:39:20 +0800 Subject: [PATCH] fix(clustering): check k-means coordinates against the index bound k-means validate_points compared coordinates with the exact double bound sqrt(sqrt(FLT_MAX) / (64 d)), while check_coordinates in the indexes uses max_coordinate_magnitude(d), the same value rounded to float. Where the rounding goes up (for example d = 64, 100, 256, 960, 1024), a coordinate equal to the float bound passed add and search but failed training, so the first add of an IvfIndex or HnswIndex rejected data a trained index accepted. Use max_coordinate_magnitude(d) in validate_points. --- docs/docs/releases/unreleased.md | 1 + .../rabitqlib/clustering/detail/kmeans.hpp | 11 ++--- tests/python/test_input_boundaries.py | 38 +++++++++++++++ .../clustering/kmeans_sampling_test.cpp | 46 +++++++++++++++++++ 4 files changed, 89 insertions(+), 7 deletions(-) diff --git a/docs/docs/releases/unreleased.md b/docs/docs/releases/unreleased.md index 90d121fb..bcf9f75b 100644 --- a/docs/docs/releases/unreleased.md +++ b/docs/docs/releases/unreleased.md @@ -51,6 +51,7 @@ - IDs remain the row numbers the index assigns. The C++ `IvfIndex`, `HnswIndex` and `SymqgIndex` use 64-bit `rabitqlib::Id` values with `kNoId` (-1) for a missing result, as Python does. The indexes still hold 32-bit row numbers inside, so they keep their limit of 2^31 points; the unsupported `ivf::IVF`, `hnsw::HierarchicalNSW` and `symqg::QuantizedGraph` keep `PID` and `kPidMax`. - An `IvfIndex`, `HnswIndex` or `SymqgIndex` call with both an invalid argument and the wrong state may now report the argument first, for example `ValueError` for `nprobe=0` on an untrained index, which raised `RuntimeError`, or for data of the wrong dimension passed to `SymqgIndex.add` after the graph is built. `HnswIndex()` with an invalid `metric` or `seed` and an out-of-range `num_clusters` now reports the metric or seed. `SymqgIndex()` with an invalid `init` and an invalid `dim`, `nbits` or `max_degree` now reports the `init`, and with an invalid `seed` and an invalid `dim`, `nbits`, `max_degree` or `ef_construction` the seed. +- k-means training accepts every coordinate that `add` and `search` accept. For many dimensions, including 64, 100, 256, 960 and 1024, `train` and `assign` of `QGKMeans` and `RaBitQKMeans`, and `train` and the first `add`, which trains, of `IvfIndex` and `HnswIndex` rejected a coordinate whose magnitude equals the float32 coordinate bound with `exceeds the safe float32 coordinate range`, although a trained index accepted it. The C++ `rabitqkmeans::RaBitQKMeans` and `qgkmeans::QGKMeans` change the same way. - Loading a format-2 file keeps the `seed` of every index, and `ef_construction` and `init` of SymphonyQG. They were `None` after `load`, and still are for files from releases up to 0.8. - With a recorded seed, `cp.seed` after `load` follows it as for a new index; for an HNSW-RaBitQ file whose seed exceeds 32 bits, which only C++ can write, it is the low 32 bits. It was the k-means default. diff --git a/include/rabitqlib/clustering/detail/kmeans.hpp b/include/rabitqlib/clustering/detail/kmeans.hpp index d243bdcf..9257ef39 100644 --- a/include/rabitqlib/clustering/detail/kmeans.hpp +++ b/include/rabitqlib/clustering/detail/kmeans.hpp @@ -25,6 +25,7 @@ #include "rabitqlib/index/detail/parallel_exception.hpp" #include "rabitqlib/index/types.hpp" #include "rabitqlib/utils/cpu_features.hpp" +#include "rabitqlib/utils/input_checks.hpp" #include "rabitqlib/utils/space.hpp" #include "rabitqlib/utils/tools.hpp" @@ -534,12 +535,8 @@ class LloydKMeans : public Parameters { std::string(Assignment::kName) + " input dimensions overflow ptrdiff_t" ); } - // Leave headroom for products of squared distances in graph pruning, - // as well as quantized reconstruction and rotated residuals. - const double max_coordinate = std::sqrt( - std::sqrt(static_cast(std::numeric_limits::max())) / - (64.0 * static_cast(d)) - ); + // The index bound, so training accepts every point the indexes accept. + const float max_coordinate = max_coordinate_magnitude(d); bool in_range = true; bool finite = true; #pragma omp parallel for num_threads(num_workers) reduction(&& : finite, in_range) \ @@ -548,7 +545,7 @@ class LloydKMeans : public Parameters { ++index) { const size_t i = static_cast(index); finite = finite && std::isfinite(x[i]); - in_range = in_range && std::abs(static_cast(x[i])) <= max_coordinate; + in_range = in_range && std::abs(x[i]) <= max_coordinate; } if (!finite) { throw std::invalid_argument( diff --git a/tests/python/test_input_boundaries.py b/tests/python/test_input_boundaries.py index 15650c94..def77dcc 100644 --- a/tests/python/test_input_boundaries.py +++ b/tests/python/test_input_boundaries.py @@ -344,3 +344,41 @@ def test_build_rejects_bad_coordinates_without_building(index_kind, value): with pytest.raises(ValueError): index.add(bad_data, cluster_ids=ids, num_threads=1) assert len(index) == 0 + + +@pytest.mark.parametrize("model", ["ivf", "hnsw", "qgkmeans", "rabitqkmeans"]) +def test_training_accepts_coordinates_at_the_index_bound(model): + # At dim 64 the float32 bound rounds above the exact real bound. + exact = np.sqrt(np.sqrt(np.float64(np.finfo(np.float32).max)) / (64.0 * 64)) + bound = np.float32(exact) + assert np.float64(bound) > exact + data = np.random.default_rng(5).normal(size=(400, 64)).astype(np.float32) + data[5, 3] = bound + data[6, 4] = -bound + + def fresh(): + if model == "ivf": + return IvfIndex(64, 4, nbits=4) + if model == "hnsw": + return HnswIndex(64, nbits=4, num_clusters=4) + return (QGKMeans if model == "qgkmeans" else RaBitQKMeans)(64, 40, niter=2) + + trained = fresh() + if model in ("ivf", "hnsw"): + trained.add(data, num_threads=1) # the first add trains + assert len(trained) == 400 + else: + trained.train(data) + trained.assign(data[5:7]) + + data[5, 3] = np.nextafter(bound, np.float32(np.inf)) + message = "KMeans x exceeds the safe float32 coordinate range$" + # Index train reaches the k-means check first; HNSW add checks before training. + with pytest.raises(ValueError, match=message): + if model in ("ivf", "hnsw"): + fresh().train(data, num_threads=1) + else: + fresh().train(data) + if model not in ("ivf", "hnsw"): + with pytest.raises(ValueError, match=message): + trained.assign(data[5:7]) diff --git a/tests/unit/rabitqlib/clustering/kmeans_sampling_test.cpp b/tests/unit/rabitqlib/clustering/kmeans_sampling_test.cpp index c40c31f0..62dcc2c3 100644 --- a/tests/unit/rabitqlib/clustering/kmeans_sampling_test.cpp +++ b/tests/unit/rabitqlib/clustering/kmeans_sampling_test.cpp @@ -17,6 +17,7 @@ #include "rabitqlib/clustering/qgkmeans.hpp" #include "rabitqlib/clustering/rabitqkmeans.hpp" #include "rabitqlib/index/types.hpp" +#include "rabitqlib/utils/input_checks.hpp" namespace rabitqlib { namespace { @@ -234,6 +235,43 @@ void check_assign_requires_training_and_valid_input(const std::string& name) { ); } +// Training and assignment accept exactly the coordinates the indexes accept. +// At kDim the float32 bound rounds above the exact real bound, so a value equal +// to it is the one an exact double comparison would wrongly reject. +template +void check_coordinate_bound_matches_index_check(const std::string& name) { + constexpr size_t kClusterCount = kClusters; + const float bound = max_coordinate_magnitude(kDim); + ASSERT_GT( + static_cast(bound), + std::sqrt( + std::sqrt(static_cast(std::numeric_limits::max())) / + (64.0 * static_cast(kDim)) + ) + ); + const size_t num_points = 2 * kClusterCount; + auto points = clustered_points(num_points, 67); + points[1] = bound; + points[kDim + 2] = -bound; + Clustering clustering(kDim, kClusterCount, test_parameters()); + ASSERT_NO_THROW(clustering.train(num_points, points.data())); + PID assignment = kPidMax; + float distance = 0; + EXPECT_NO_THROW(clustering.assign(1, points.data(), &assignment, &distance)); + EXPECT_LT(assignment, kClusterCount); + + const std::string message = name + " x exceeds the safe float32 coordinate range"; + points[1] = std::nextafter(bound, std::numeric_limits::infinity()); + try { + clustering.assign(1, points.data(), &assignment, &distance); + FAIL() << "Assigned a coordinate above the bound"; + } catch (const std::invalid_argument& error) { EXPECT_EQ(error.what(), message); } + try { + clustering.train(num_points, points.data()); + FAIL() << "Trained on a coordinate above the bound"; + } catch (const std::invalid_argument& error) { EXPECT_EQ(error.what(), message); } +} + // With sampling, train's final pass is assign() itself, including QGKMeans' // cached graph. Without it, Exact assignment and RaBitQKMeans' scan around the // stored training center also reproduce train(); graph training uses hints. @@ -602,6 +640,14 @@ TEST(KMeansAssignTest, QGRequiresTrainingAndValidInput) { check_assign_requires_training_and_valid_input("QGKMeans"); } +TEST(KMeansAssignTest, RaBitQCoordinateBoundMatchesIndexCheck) { + check_coordinate_bound_matches_index_check("RaBitQKMeans"); +} + +TEST(KMeansAssignTest, QGCoordinateBoundMatchesIndexCheck) { + check_coordinate_bound_matches_index_check("QGKMeans"); +} + TEST(KMeansAssignTest, RaBitQMatchesFinalTrainingAssignment) { check_assign_matches_final_training_assignment(); }