From c7087503c3e9543d40a1876a30677e3bb5c07b1d Mon Sep 17 00:00:00 2001 From: lerman25 Date: Sun, 8 Nov 2026 14:11:26 +0200 Subject: [PATCH] [MOD-17920] Keep cosine distances finite for zero vectors --- src/VecSim/spaces/normalize/normalize_naive.h | 12 ++ src/VecSim/vec_sim.h | 2 + tests/unit/test_common.cpp | 121 ++++++++++++++++++ 3 files changed, 135 insertions(+) diff --git a/src/VecSim/spaces/normalize/normalize_naive.h b/src/VecSim/spaces/normalize/normalize_naive.h index c193e70ab..a49bcdcc6 100644 --- a/src/VecSim/spaces/normalize/normalize_naive.h +++ b/src/VecSim/spaces/normalize/normalize_naive.h @@ -29,6 +29,9 @@ static inline void normalizeVector_imp(void *vec, const size_t dim) { for (size_t i = 0; i < dim; i++) { sum += (double)input_vector[i] * (double)input_vector[i]; } + if (sum == 0) { + return; + } double norm = sqrt(sum); for (size_t i = 0; i < dim; i++) { @@ -51,6 +54,9 @@ static inline void bfloat16_normalizeVector(void *vec, const size_t dim) { sum += (double)val * (double)val; } + if (sum == 0) { + return; + } double norm = sqrt(sum); for (size_t i = 0; i < dim; i++) { @@ -71,6 +77,9 @@ static inline void float16_normalizeVector(void *vec, const size_t dim) { sum += val * val; } + if (sum == 0) { + return; + } float norm = sqrt(sum); for (size_t i = 0; i < dim; i++) { @@ -83,6 +92,9 @@ static inline void integer_normalizeVector(void *vec, const size_t dim) { DataType *input_vector = static_cast(vec); float norm = IntegralType_ComputeNorm(input_vector, dim); + if (norm == 0) { + norm = 1.0f; + } // The norm follows a one-byte element payload and may be unaligned for odd dimensions. std::memcpy(input_vector + dim, &norm, sizeof(norm)); diff --git a/src/VecSim/vec_sim.h b/src/VecSim/vec_sim.h index b51442d04..7c547e4fc 100644 --- a/src/VecSim/vec_sim.h +++ b/src/VecSim/vec_sim.h @@ -140,6 +140,8 @@ double VecSimIndex_GetDistanceFrom_Unsafe(VecSimIndex *index, size_t label, cons /** * @brief normalize the vector blob in place. + * Zero vectors remain zero, with an integer norm payload of 1 instead of 0, so cosine + * distance involving a zero vector is 1 rather than NaN. * @param blob binary representation of a vector. Blob size should match the specified type and * dimension. * @param dim vector dimension. diff --git a/tests/unit/test_common.cpp b/tests/unit/test_common.cpp index 2db8c9963..c3a11d24e 100644 --- a/tests/unit/test_common.cpp +++ b/tests/unit/test_common.cpp @@ -40,6 +40,9 @@ #include #include #include +#include +#include +#include using bfloat16 = vecsim_types::bfloat16; using float16 = vecsim_types::float16; @@ -51,6 +54,124 @@ class CommonIndexTest : public ::testing::Test {}; TYPED_TEST_SUITE(CommonIndexTest, DataTypeSet); +template +class ZeroCosineTest : public ::testing::Test { +protected: + using data_t = typename index_type_t::data_t; + static constexpr size_t dim = 33; + std::array zero{}, aligned{}, orthogonal{}; + VecSimWriteMode original_mode; + + void SetUp() override { + original_mode = VecSimIndexInterface::asyncWriteMode; + VecSim_SetWriteMode(VecSim_WriteAsync); + if constexpr (std::is_same_v) { + aligned[0] = orthogonal[1] = vecsim_types::float_to_bf16(1.0f); + } else if constexpr (std::is_same_v) { + aligned[0] = orthogonal[1] = vecsim_types::FP32_to_FP16(1.0f); + } else { + aligned[0] = orthogonal[1] = 1; + } + } + + void TearDown() override { VecSimIndexInterface::asyncWriteMode = original_mode; } + + void populate(VecSimIndex *index, bool multi) { + VecSimIndex_AddVector(index, zero.data(), 0); + VecSimIndex_AddVector(index, aligned.data(), 1); + VecSimIndex_AddVector(index, zero.data(), 2); + VecSimIndex_AddVector(index, orthogonal.data(), 3); + if (multi) { + VecSimIndex_AddVector(index, zero.data(), 0); + } + } + + void checkResults(VecSimIndex *index) { + for (bool zero_query : {false, true}) { + const auto &query = zero_query ? zero : aligned; + const std::array ids = + zero_query ? std::array{0, 1, 2, 3} : std::array{1, 0, 2, 3}; + for (size_t k : {2, 4}) { + SCOPED_TRACE(testing::Message() << "zero_query=" << zero_query << ", k=" << k); + std::unique_ptr reply( + VecSimIndex_TopKQuery(index, query.data(), k, nullptr, BY_SCORE), + VecSimQueryReply_Free); + ASSERT_EQ(reply->code, VecSim_QueryReply_OK); + ASSERT_EQ(reply->results.size(), k); + for (size_t i = 0; i < k; ++i) { + EXPECT_EQ(reply->results[i].id, ids[i]); + EXPECT_TRUE(std::isfinite(reply->results[i].score)); + EXPECT_DOUBLE_EQ(reply->results[i].score, !zero_query && i == 0 ? 0.0 : 1.0); + } + } + } + } +}; + +using ZeroCosineTypes = testing::Types< + IndexType, IndexType, + IndexType, IndexType, + IndexType, IndexType>; +TYPED_TEST_SUITE(ZeroCosineTest, ZeroCosineTypes); + +TYPED_TEST(ZeroCosineTest, NormalizeZero) { + std::array normalized{}; + VecSim_Normalize(normalized.data(), TestFixture::dim, TypeParam::get_index_type()); + for (size_t i = 0; i < TestFixture::dim; ++i) { + EXPECT_EQ(normalized[i], TEST_DATA_T{}); + } + if constexpr (std::is_integral_v) { + float norm; + std::memcpy(&norm, normalized.data() + TestFixture::dim, sizeof(norm)); + EXPECT_FLOAT_EQ(norm, 1.0f); + } +} + +TYPED_TEST(ZeroCosineTest, FlatAndHNSW) { + for (bool multi : {false, true}) { + for (auto algo : {VecSimAlgo_BF, VecSimAlgo_HNSWLIB}) { + SCOPED_TRACE(testing::Message() << "multi=" << multi << ", algo=" << algo); + BFParams bf = {.dim = TestFixture::dim, .metric = VecSimMetric_Cosine}; + HNSWParams hnsw = {.dim = TestFixture::dim, .metric = VecSimMetric_Cosine}; + std::unique_ptr index( + algo == VecSimAlgo_BF + ? test_utils::CreateNewIndex(bf, TypeParam::get_index_type(), multi) + : test_utils::CreateNewIndex(hnsw, TypeParam::get_index_type(), multi), + VecSimIndex_Free); + ASSERT_NE(index, nullptr); + this->populate(index.get(), multi); + this->checkResults(index.get()); + } + } +} + +TYPED_TEST(ZeroCosineTest, TieredMigration) { + for (bool multi : {false, true}) { + SCOPED_TRACE(testing::Message() << "multi=" << multi); + HNSWParams params = {.type = TypeParam::get_index_type(), + .dim = TestFixture::dim, + .metric = VecSimMetric_Cosine, + .multi = multi}; + tieredIndexMock pool; + auto *index = test_utils::CreateNewTieredVecSimIndex(params, pool); + ASSERT_NE(index, nullptr); + this->populate(index, multi); + const size_t count = multi ? 5 : 4; + for (size_t migrated = 0; migrated <= count; ++migrated) { + SCOPED_TRACE(testing::Message() << "migrated=" << migrated); + auto info = index->debugInfo().tieredInfo; + ASSERT_EQ(info.backendCommonInfo.indexSize, migrated); + ASSERT_EQ(info.frontendCommonInfo.indexSize, count - migrated); + this->checkResults(index); + if (migrated < count) { + ASSERT_FALSE(pool.jobQ.empty()); + pool.thread_iteration(); + } + } + ASSERT_TRUE(pool.jobQ.empty()); + } +} + TYPED_TEST(CommonIndexTest, ResolveQueryRuntimeParams) { size_t dim = 4;