From 38664c7db20acd8e745129a3034600b15f494d49 Mon Sep 17 00:00:00 2001 From: gouyt13clear Date: Thu, 19 Nov 2026 21:05:39 +0800 Subject: [PATCH] fix(clustering): reject the cosine metric in QGAssigner 0.9 added METRIC_COSINE for the ANN indexes, which normalize vectors; the quantizers, FastScan and clustering are documented to reject it. QGAssigner passed its metric unchecked to QuantizedGraph, which accepts cosine, so it assigned by cosine but reported exact distances on a 2(1 - cos) scale instead of rejecting the metric. Its constructor now calls validate_metric_type after the configuration checks. QGKMeans passes only L2 or inner product and is unaffected. --- include/rabitqlib/clustering/qgkmeans.hpp | 3 +++ tests/unit/rabitqlib/clustering/qgkmeans_test.cpp | 12 ++++++++++++ 2 files changed, 15 insertions(+) diff --git a/include/rabitqlib/clustering/qgkmeans.hpp b/include/rabitqlib/clustering/qgkmeans.hpp index 51916b18..96f112c2 100644 --- a/include/rabitqlib/clustering/qgkmeans.hpp +++ b/include/rabitqlib/clustering/qgkmeans.hpp @@ -157,6 +157,9 @@ class QGAssigner { , graph_build_iterations_(graph_build_iterations) , seed_(seed) { validate_configuration(num_threads); + // Cosine belongs to the indexes, which normalize vectors; the assigner's exact + // distances are raw L2 or inner product. + validate_metric_type(metric_type); num_workers_ = static_cast(resolve_num_threads(num_threads)); graph_ = std::make_unique>( diff --git a/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp b/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp index 9ce6f1c4..d1336ddd 100644 --- a/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp +++ b/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp @@ -1236,6 +1236,18 @@ TEST(QGAssignerTest, RejectsTooFewClustersForGraphDegree) { EXPECT_THROW(QGAssigner(64, 32, 32, 64, 16, 1, 1), std::invalid_argument); } +// Like the quantizers and FastScan, clustering takes only L2 and inner product. +TEST(QGAssignerTest, RejectsTheCosineMetric) { + try { + const QGAssigner assigner(64, 33, 32, 64, 16, 1, 1, 42, METRIC_COSINE); + ADD_FAILURE() << "accepted METRIC_COSINE"; + } catch (const std::invalid_argument& error) { + EXPECT_STREQ(error.what(), "Metric type must be METRIC_L2 or METRIC_IP"); + } + EXPECT_NO_THROW(QGAssigner(64, 33, 32, 64, 16, 1, 1, 42, METRIC_L2)); + EXPECT_NO_THROW(QGAssigner(64, 33, 32, 64, 16, 1, 1, 42, METRIC_IP)); +} + TEST(QGKMeansTest, RejectsTooFewClustersForGraphDegreeInBothFinalModes) { constexpr size_t kDim = 64, kPoints = 65; const std::vector data(kPoints * kDim, 0.0F);