diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index 85886b7af..8f82cd028 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -45,6 +45,8 @@ on: - bm-sq8-compare-fp16 - bm-sq8-train-fp32 - bm-sq8-train-fp16 + - bm-spaces-sq4-fp32 + - bm-spaces-sq4-sq4 - bm-svs-train-fp32 - bm-svs-train-fp16 - bm-basics-svs-fp32-single diff --git a/src/VecSim/spaces/IP/IP_AVX2_FMA_SQ4_FP32.h b/src/VecSim/spaces/IP/IP_AVX2_FMA_SQ4_FP32.h new file mode 100644 index 000000000..1799d672a --- /dev/null +++ b/src/VecSim/spaces/IP/IP_AVX2_FMA_SQ4_FP32.h @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once +#include "VecSim/spaces/space_includes.h" +#include "VecSim/spaces/AVX_utils.h" +#include "VecSim/spaces/IP/IP.h" +#include "VecSim/types/sq4.h" +#include "VecSim/utils/alignment.h" +#include +#include +#include + +namespace { + +/* + * Asymmetric SQ4 inner product with the same identity as SQ8: + * + * IP(x, y) ≈ Σ((min + delta * q_i) * y_i) = min * y_sum + delta * Σ(q_i * y_i) + * + * Storage packs coordinate i into byte i / 2, the low nibble for even i and the high nibble for + * odd i, followed by unaligned FP32 metadata. The query blob carries y_sum after its dim floats. + */ + +// Interleave the low and high nibbles of the packed bytes, so `first` holds the codes of the low +// eight bytes and `second` those of the high eight bytes, each in coordinate order. +static inline void SQ4_Unpack_AVX2_FMA(__m128i packed, __m128i &first, __m128i &second) { + const __m128i nibble = _mm_set1_epi8(15); + const __m128i low = _mm_and_si128(packed, nibble); + const __m128i high = _mm_and_si128(_mm_srli_epi16(packed, 4), nibble); + first = _mm_unpacklo_epi8(low, high); + second = _mm_unpackhi_epi8(low, high); +} + +// Sixteen byte codes in coordinate order to two float vectors. +static inline void SQ4_ToFloats_AVX2_FMA(__m128i codes, __m256 &first, __m256 &second) { + first = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(codes)); + second = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(_mm_unpackhi_epi64(codes, codes))); +} + +// Exactly `bytes` (1..8) packed bytes in the low half of a vector, the rest zero. +template +static inline __m128i SQ4_LoadBytes_AVX2_FMA(const uint8_t *data) { + static_assert(bytes >= 1 && bytes <= 8); + uint64_t bits = 0; + std::memcpy(&bits, data, bytes); + return _mm_cvtsi64_si128(static_cast(bits)); +} + +// Blend control selecting the top `lanes` (1..8) of eight float lanes. +template +constexpr int SQ4_TailLanes_AVX2_FMA = (0xFF << (8 - lanes)) & 0xFF; + +// The `lanes` (1..8) query floats that end at `end`, in the top lanes with zero below. The tail is +// read with a full 8-float load ending at `end`, which stays inside the query whenever dim >= 8 +// (the dispatcher's minimum); a smaller dim copies the floats instead. Masked AVX2 loads are not +// used because some processors may fault on their masked-out lanes. +template +static inline __m256 SQ4_TailQuery_AVX2_FMA(const float *end, size_t dimension) { + static_assert(lanes >= 1 && lanes <= 8); + if (dimension >= 8) { + return _mm256_blend_ps(_mm256_setzero_ps(), _mm256_loadu_ps(end - 8), + SQ4_TailLanes_AVX2_FMA); + } + float window[8] = {}; + std::memcpy(window + 8 - lanes, end - lanes, lanes * sizeof(float)); + return _mm256_loadu_ps(window); +} + +// The first `lanes` (1..8) byte codes of `codes` as floats in the top lanes, zero below, to line up +// with SQ4_TailQuery_AVX2_FMA. Later bytes, such as an odd dim's padding nibble, are shifted out. +template +static inline __m256 SQ4_TailCodes_AVX2_FMA(__m128i codes) { + static_assert(lanes >= 1 && lanes <= 8); + return _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(_mm_slli_si128(codes, 8 - lanes))); +} + +// Accumulate Σ(q_i * y_i) for 32 coordinates: one 16-byte load of packed codes. +static inline void SQ4_FP32_IPStep32_AVX2_FMA(const uint8_t *x, const float *y, __m256 &sum0, + __m256 &sum1, __m256 &sum2, __m256 &sum3) { + __m128i ordered0, ordered1; + SQ4_Unpack_AVX2_FMA(_mm_loadu_si128(reinterpret_cast(x)), ordered0, ordered1); + __m256 codes0, codes1, codes2, codes3; + SQ4_ToFloats_AVX2_FMA(ordered0, codes0, codes1); + SQ4_ToFloats_AVX2_FMA(ordered1, codes2, codes3); + sum0 = _mm256_fmadd_ps(codes0, _mm256_loadu_ps(y), sum0); + sum1 = _mm256_fmadd_ps(codes1, _mm256_loadu_ps(y + 8), sum1); + sum2 = _mm256_fmadd_ps(codes2, _mm256_loadu_ps(y + 16), sum2); + sum3 = _mm256_fmadd_ps(codes3, _mm256_loadu_ps(y + 24), sum3); +} + +template // 0..31 +float SQ4_FP32_InnerProductSIMD32_AVX2_FMA(const void *pVect1v, const void *pVect2v, + size_t dimension) { + using vecsim_types::sq4; + const auto *x = static_cast(pVect1v); + const auto *y = static_cast(pVect2v); + // Eight accumulators break the FMA dependency chain: two 32-coordinate steps per iteration. + __m256 sum0 = _mm256_setzero_ps(), sum1 = _mm256_setzero_ps(); + __m256 sum2 = _mm256_setzero_ps(), sum3 = _mm256_setzero_ps(); + __m256 sum4 = _mm256_setzero_ps(), sum5 = _mm256_setzero_ps(); + __m256 sum6 = _mm256_setzero_ps(), sum7 = _mm256_setzero_ps(); + const size_t complete = dimension - residual; + size_t i = 0; + for (; i + 64 <= complete; i += 64) { + SQ4_FP32_IPStep32_AVX2_FMA(x + i / 2, y + i, sum0, sum1, sum2, sum3); + SQ4_FP32_IPStep32_AVX2_FMA(x + i / 2 + 16, y + i + 32, sum4, sum5, sum6, sum7); + } + if (i < complete) { + SQ4_FP32_IPStep32_AVX2_FMA(x + i / 2, y + i, sum0, sum1, sum2, sum3); + } + sum0 = _mm256_add_ps(sum0, sum4); + sum1 = _mm256_add_ps(sum1, sum5); + sum2 = _mm256_add_ps(sum2, sum6); + sum3 = _mm256_add_ps(sum3, sum7); + i = complete; + if constexpr (residual >= 16) { + // One 8-byte load covers exactly 16 coordinates. + __m128i ordered, unused; + SQ4_Unpack_AVX2_FMA(_mm_loadl_epi64(reinterpret_cast(x + i / 2)), ordered, + unused); + __m256 codes0, codes1; + SQ4_ToFloats_AVX2_FMA(ordered, codes0, codes1); + sum0 = _mm256_fmadd_ps(codes0, _mm256_loadu_ps(y + i), sum0); + sum1 = _mm256_fmadd_ps(codes1, _mm256_loadu_ps(y + i + 8), sum1); + i += 16; + } + constexpr unsigned rest = residual % 16; + if constexpr (rest > 0) { + // Exactly the tail's code bytes. The last query window ends at the last coordinate (see + // SQ4_TailQuery_AVX2_FMA). + __m128i ordered, unused; + SQ4_Unpack_AVX2_FMA(SQ4_LoadBytes_AVX2_FMA<(rest + 1) / 2>(x + i / 2), ordered, unused); + const float *end = y + dimension; + if constexpr (rest > 8) { + const __m256 codes0 = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(ordered)); + sum2 = _mm256_fmadd_ps(codes0, _mm256_loadu_ps(y + i), sum2); + sum3 = _mm256_fmadd_ps( + SQ4_TailCodes_AVX2_FMA(_mm_unpackhi_epi64(ordered, ordered)), + SQ4_TailQuery_AVX2_FMA(end, dimension), sum3); + } else { + sum2 = _mm256_fmadd_ps(SQ4_TailCodes_AVX2_FMA(ordered), + SQ4_TailQuery_AVX2_FMA(end, dimension), sum2); + } + } + const float dot = my_mm256_reduce_add_ps_tree( + _mm256_add_ps(_mm256_add_ps(sum0, sum1), _mm256_add_ps(sum2, sum3))); + const auto *params = x + sq4::data_bytes_count(dimension); + const float min_val = load_unaligned(params + sq4::MIN_VAL * sizeof(float)); + const float delta = load_unaligned(params + sq4::DELTA * sizeof(float)); + return 1.0f - (min_val * y[dimension + sq4::SUM_QUERY] + delta * dot); +} + +} // namespace diff --git a/src/VecSim/spaces/IP/IP_AVX2_SQ4_SQ4.h b/src/VecSim/spaces/IP/IP_AVX2_SQ4_SQ4.h new file mode 100644 index 000000000..78cd09727 --- /dev/null +++ b/src/VecSim/spaces/IP/IP_AVX2_SQ4_SQ4.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once +#include "VecSim/spaces/space_includes.h" +#include "VecSim/types/sq4.h" +#include "VecSim/spaces/quantized_distance_helpers.h" +#include +#include + +namespace { + +/* + * The packed code dot is the sum of low-nibble products and high-nibble products. + * Both operands' codes are 0..15, so maddubs' signed operand is nonnegative and its + * saturating pair sum is at most 450. madd with ones widens groups of four products + * to int32 before accumulation. Each lane of each accumulator adds at most 900 per + * 64 coordinates. Even after combining low and high, 1800 * ceil(dim / 64) is below + * 537 million at SQ4_MAX_EXACT_SIMD_DIM, safely below INT32_MAX. The horizontal sum + * uses wrapping SIMD additions and unsigned extraction: the dispatch bound keeps + * the full sum, at most 225 * dim, within UINT32_MAX. + */ + +static inline void SQ4_SQ4_DotStep_AVX2(__m256i &sum_low, __m256i &sum_high, __m256i x, __m256i y) { + const __m256i nibble = _mm256_set1_epi8(15); + const __m256i ones = _mm256_set1_epi16(1); + const __m256i low = + _mm256_maddubs_epi16(_mm256_and_si256(x, nibble), _mm256_and_si256(y, nibble)); + const __m256i high = _mm256_maddubs_epi16(_mm256_and_si256(_mm256_srli_epi16(x, 4), nibble), + _mm256_and_si256(_mm256_srli_epi16(y, 4), nibble)); + sum_low = _mm256_add_epi32(sum_low, _mm256_madd_epi16(low, ones)); + sum_high = _mm256_add_epi32(sum_high, _mm256_madd_epi16(high, ones)); +} + +// Raw inner product, shared with the stored-sum L2 identity. +template // 0..63 +float SQ4_SQ4_InnerProductSIMD64_AVX2_IMP(const void *pVect1v, const void *pVect2v, + size_t dimension) { + const auto *x = static_cast(pVect1v); + const auto *y = static_cast(pVect2v); + __m256i sum_low = _mm256_setzero_si256(); + __m256i sum_high = _mm256_setzero_si256(); + const size_t complete = dimension - residual; + for (size_t i = 0; i < complete; i += 64) { + SQ4_SQ4_DotStep_AVX2(sum_low, sum_high, + _mm256_loadu_si256(reinterpret_cast(x + i / 2)), + _mm256_loadu_si256(reinterpret_cast(y + i / 2))); + } + if constexpr (residual > 0) { + // Copy only code bytes, without reading into the stored metadata. Clear the unused + // high nibble for an odd dimension, even if a foreign writer left it nonzero. + alignas(32) uint8_t xt[32] = {}; + alignas(32) uint8_t yt[32] = {}; + std::memcpy(xt, x + complete / 2, (residual + 1) / 2); + std::memcpy(yt, y + complete / 2, (residual + 1) / 2); + if constexpr (residual % 2 != 0) { + xt[residual / 2] &= 15; + } + SQ4_SQ4_DotStep_AVX2(sum_low, sum_high, + _mm256_load_si256(reinterpret_cast(xt)), + _mm256_load_si256(reinterpret_cast(yt))); + } + const __m256i sum = _mm256_add_epi32(sum_low, sum_high); + const __m128i s4 = _mm_add_epi32(_mm256_castsi256_si128(sum), _mm256_extracti128_si256(sum, 1)); + const __m128i s2 = _mm_add_epi32(s4, _mm_srli_si128(s4, 8)); + const __m128i s1 = _mm_add_epi32(s2, _mm_srli_si128(s2, 4)); + const auto code_dot = static_cast(_mm_cvtsi128_si32(s1)); + return spaces::quantized::Stored_InnerProduct_FromCodeDot( + x, y, dimension, static_cast(code_dot)); +} + +template // 0..63 +float SQ4_SQ4_InnerProductSIMD64_AVX2(const void *pVect1v, const void *pVect2v, size_t dimension) { + return 1.0f - SQ4_SQ4_InnerProductSIMD64_AVX2_IMP(pVect1v, pVect2v, dimension); +} + +} // namespace diff --git a/src/VecSim/spaces/IP/IP_AVX512F_BW_VL_VNNI_SQ4_FP32.h b/src/VecSim/spaces/IP/IP_AVX512F_BW_VL_VNNI_SQ4_FP32.h new file mode 100644 index 000000000..8c5e215d2 --- /dev/null +++ b/src/VecSim/spaces/IP/IP_AVX512F_BW_VL_VNNI_SQ4_FP32.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once +#include "VecSim/spaces/space_includes.h" +#include "VecSim/spaces/IP/IP.h" +#include "VecSim/types/sq4.h" +#include "VecSim/utils/alignment.h" +#include +#include + +namespace { + +/* + * Asymmetric SQ4 inner product with the same identity as SQ8: + * + * IP(x, y) ≈ Σ((min + delta * q_i) * y_i) = min * y_sum + delta * Σ(q_i * y_i) + * + * Storage packs coordinate i into byte i / 2, the low nibble for even i and the high nibble for + * odd i, followed by unaligned FP32 metadata. The query blob carries y_sum after its dim floats. + */ + +// Unpack 16 packed bytes (32 coordinates) into two float vectors in coordinate order. +static inline void SQ4_Unpack32_AVX512F_BW_VL_VNNI(__m128i packed, __m512 &first, __m512 &second) { + const __m128i nibble = _mm_set1_epi8(15); + const __m128i low = _mm_and_si128(packed, nibble); + const __m128i high = _mm_and_si128(_mm_srli_epi16(packed, 4), nibble); + first = _mm512_cvtepi32_ps(_mm512_cvtepu8_epi32(_mm_unpacklo_epi8(low, high))); + second = _mm512_cvtepi32_ps(_mm512_cvtepu8_epi32(_mm_unpackhi_epi8(low, high))); +} + +// Masks for a tail of `residual` (0..31) coordinates: the packed bytes that hold it, and the query +// lanes of each 16-coordinate half. +template +struct SQ4TailMasks_AVX512F_BW_VL_VNNI { + static constexpr __mmask16 bytes = (1u << ((residual + 1) / 2)) - 1; + static constexpr __mmask16 first = residual >= 16 ? 0xffff : (1u << residual) - 1; + static constexpr __mmask16 second = residual > 16 ? (1u << (residual - 16)) - 1 : 0; +}; + +template // 0..31 +float SQ4_FP32_InnerProductSIMD32_AVX512F_BW_VL_VNNI(const void *pVect1v, const void *pVect2v, + size_t dimension) { + using vecsim_types::sq4; + const auto *x = static_cast(pVect1v); + const auto *y = static_cast(pVect2v); + __m512 sum0 = _mm512_setzero_ps(); + __m512 sum1 = _mm512_setzero_ps(); + const size_t complete = dimension - residual; + for (size_t i = 0; i < complete; i += 32) { + __m512 codes0, codes1; + SQ4_Unpack32_AVX512F_BW_VL_VNNI( + _mm_loadu_si128(reinterpret_cast(x + i / 2)), codes0, codes1); + sum0 = _mm512_fmadd_ps(codes0, _mm512_loadu_ps(y + i), sum0); + sum1 = _mm512_fmadd_ps(codes1, _mm512_loadu_ps(y + i + 16), sum1); + } + if constexpr (residual > 0) { + // Masked loads of exactly the tail's code bytes and query floats, so nothing past the codes + // or the query's dim floats is read. Masked-out query lanes are zero, so the padding nibble + // of an odd dim adds nothing. + using masks = SQ4TailMasks_AVX512F_BW_VL_VNNI; + __m512 codes0, codes1; + SQ4_Unpack32_AVX512F_BW_VL_VNNI(_mm_maskz_loadu_epi8(masks::bytes, x + complete / 2), + codes0, codes1); + sum0 = _mm512_fmadd_ps(codes0, _mm512_maskz_loadu_ps(masks::first, y + complete), sum0); + if constexpr (masks::second != 0) { + sum1 = _mm512_fmadd_ps(codes1, _mm512_maskz_loadu_ps(masks::second, y + complete + 16), + sum1); + } + } + const float dot = _mm512_reduce_add_ps(_mm512_add_ps(sum0, sum1)); + const auto *params = x + sq4::data_bytes_count(dimension); + const float min_val = load_unaligned(params + sq4::MIN_VAL * sizeof(float)); + const float delta = load_unaligned(params + sq4::DELTA * sizeof(float)); + return 1.0f - (min_val * y[dimension + sq4::SUM_QUERY] + delta * dot); +} + +} // namespace diff --git a/src/VecSim/spaces/IP/IP_AVX512F_BW_VL_VNNI_SQ4_SQ4.h b/src/VecSim/spaces/IP/IP_AVX512F_BW_VL_VNNI_SQ4_SQ4.h new file mode 100644 index 000000000..72b4de0d6 --- /dev/null +++ b/src/VecSim/spaces/IP/IP_AVX512F_BW_VL_VNNI_SQ4_SQ4.h @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once +#include "VecSim/spaces/space_includes.h" +#include "VecSim/types/sq4.h" +#include "VecSim/spaces/quantized_distance_helpers.h" +#include + +namespace { + +/* + * Symmetric SQ4-SQ4 inner product with the same identity as SQ8-SQ8: + * + * IP(x, y) = min_x * sum_y + min_y * sum_x - dim * min_x * min_y + * + delta_x * delta_y * Σ(qx_i * qy_i) + * + * Only the integer code dot Σ(qx_i * qy_i) is vectorized. Both operands pack coordinate i into + * byte i / 2, the low nibble for even i and the high nibble for odd i, so the code dot is the sum + * of the low-nibble products plus the sum of the high-nibble products and no lane reordering is + * needed. Each half is unpacked to bytes and multiplied with vpdpbusd into signed int32 lanes. + * The packed codes are followed by unaligned FP32 metadata. + * + * Exactness: every vpdpbusd adds four products of at most 225 to each lane, and a lane takes part + * in at most dim / 128 + 2 steps per nibble half, so a lane of the summed accumulators holds at + * most 1800 * (dim / 128 + 2), about 268 million at spaces::SQ4_MAX_EXACT_SIMD_DIM, far below + * INT32_MAX. Explicit wrapping SIMD additions reduce the lanes to uint32; + * the whole total, at most 225 * dim, is what the dispatcher's uint32-based bound keeps exact. + */ + +// Byte masks for a tail of `residual` (0..63) coordinates: the packed bytes that hold it, and the +// bytes whose high nibble is in it. For an odd residual the last byte's high nibble is the padding. +template +struct SQ4SQ4TailMasks_AVX512F_BW_VL_VNNI { + static constexpr __mmask64 bytes = (uint64_t(1) << ((residual + 1) / 2)) - 1; + static constexpr __mmask64 high = (uint64_t(1) << (residual / 2)) - 1; +}; + +// Code products of up to 64 packed bytes (128 coordinates): low nibbles into sum_low, high nibbles +// into sum_high. Codes are 0..15, so vpdpbusd's unsigned-by-signed bytes multiply them exactly. +static inline void SQ4_SQ4_DotStep_AVX512F_BW_VL_VNNI(__m512i &sum_low, __m512i &sum_high, + __m512i x, __m512i y) { + const __m512i nibble = _mm512_set1_epi8(15); + sum_low = + _mm512_dpbusd_epi32(sum_low, _mm512_and_si512(x, nibble), _mm512_and_si512(y, nibble)); + sum_high = _mm512_dpbusd_epi32(sum_high, _mm512_and_si512(_mm512_srli_epi16(x, 4), nibble), + _mm512_and_si512(_mm512_srli_epi16(y, 4), nibble)); +} + +// Returns the raw inner product (not the distance); the L2 identity kernels share it. +template // 0..63 +float SQ4_SQ4_InnerProductSIMD64_AVX512F_BW_VL_VNNI_IMP(const void *pVect1v, const void *pVect2v, + size_t dimension) { + const auto *x = static_cast(pVect1v); + const auto *y = static_cast(pVect2v); + __m512i sum_low = _mm512_setzero_si512(); + __m512i sum_high = _mm512_setzero_si512(); + const size_t complete = dimension - residual; + size_t i = 0; + for (; i + 128 <= complete; i += 128) { + SQ4_SQ4_DotStep_AVX512F_BW_VL_VNNI(sum_low, sum_high, _mm512_loadu_si512(x + i / 2), + _mm512_loadu_si512(y + i / 2)); + } + if (i < complete) { + // One 64-coordinate chunk left: exactly its 32 bytes per operand. + constexpr __mmask64 half = 0xffffffffull; + SQ4_SQ4_DotStep_AVX512F_BW_VL_VNNI(sum_low, sum_high, + _mm512_maskz_loadu_epi8(half, x + i / 2), + _mm512_maskz_loadu_epi8(half, y + i / 2)); + } + if constexpr (residual > 0) { + // Masked loads of exactly the tail's code bytes, so nothing past the codes is read. An odd + // dim's padding nibble is cleared in x, so its product is zero. + using masks = SQ4SQ4TailMasks_AVX512F_BW_VL_VNNI; + __m512i xt = _mm512_maskz_loadu_epi8(masks::bytes, x + complete / 2); + if constexpr (residual % 2 != 0) { + xt = _mm512_mask_mov_epi8(xt, masks::bytes & ~masks::high, + _mm512_and_si512(xt, _mm512_set1_epi8(15))); + } + SQ4_SQ4_DotStep_AVX512F_BW_VL_VNNI(sum_low, sum_high, xt, + _mm512_maskz_loadu_epi8(masks::bytes, y + complete / 2)); + } + // Existing dispatch bounds the full sum by UINT32_MAX. Keep all additions in SIMD, + // then extract as unsigned before FP32 conversion. + const __m512i sum = _mm512_add_epi32(sum_low, sum_high); + const __m256i s8 = + _mm256_add_epi32(_mm512_castsi512_si256(sum), _mm512_extracti64x4_epi64(sum, 1)); + const __m128i s4 = _mm_add_epi32(_mm256_castsi256_si128(s8), _mm256_extracti128_si256(s8, 1)); + const __m128i s2 = _mm_add_epi32(s4, _mm_srli_si128(s4, 8)); + const __m128i s1 = _mm_add_epi32(s2, _mm_srli_si128(s2, 4)); + const auto code_dot = static_cast(_mm_cvtsi128_si32(s1)); + return spaces::quantized::Stored_InnerProduct_FromCodeDot( + x, y, dimension, static_cast(code_dot)); +} + +template // 0..63 +float SQ4_SQ4_InnerProductSIMD64_AVX512F_BW_VL_VNNI(const void *pVect1v, const void *pVect2v, + size_t dimension) { + return 1.0f - + SQ4_SQ4_InnerProductSIMD64_AVX512F_BW_VL_VNNI_IMP(pVect1v, pVect2v, dimension); +} + +} // namespace diff --git a/src/VecSim/spaces/IP/IP_NEON_DOTPROD_SQ4_SQ4.h b/src/VecSim/spaces/IP/IP_NEON_DOTPROD_SQ4_SQ4.h new file mode 100644 index 000000000..5bb70e063 --- /dev/null +++ b/src/VecSim/spaces/IP/IP_NEON_DOTPROD_SQ4_SQ4.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once +#include "VecSim/spaces/space_includes.h" +#include "VecSim/spaces/IP/IP_NEON_SQ4_SQ4.h" // SQ4TailNibbleMask +#include "VecSim/spaces/quantized_distance_helpers.h" +#include + +namespace { + +/* + * Symmetric SQ4-SQ4 inner product, as IP_NEON_SQ4_SQ4.h, with the code dot on vdot_u32: the low + * nibbles and the high nibbles of both operands are each unpacked to bytes and dotted, which needs + * no lane reordering because both operands share the packing. The uint32 lanes are exact up to + * spaces::SQ4_MAX_EXACT_SIMD_DIM, which the dispatcher enforces. + */ +// Returns the raw inner product (not the distance); the L2 identity kernels share it. +template // 0..31 +float SQ4_SQ4_InnerProductSIMD32_NEON_DOTPROD_IMP(const void *pVect1v, const void *pVect2v, + size_t dimension) { + const auto *x = static_cast(pVect1v); + const auto *y = static_cast(pVect2v); + const uint8x16_t nibble = vdupq_n_u8(15); + uint32x4_t sum0 = vdupq_n_u32(0); + uint32x4_t sum1 = vdupq_n_u32(0); + const size_t complete = dimension - residual; + size_t i = 0; + // One 16-byte load per operand covers 32 coordinates. + for (; i < complete; i += 32) { + const uint8x16_t xb = vld1q_u8(x + i / 2), yb = vld1q_u8(y + i / 2); + sum0 = vdotq_u32(sum0, vandq_u8(xb, nibble), vandq_u8(yb, nibble)); + sum1 = vdotq_u32(sum1, vshrq_n_u8(xb, 4), vshrq_n_u8(yb, 4)); + } + uint32x2_t tail = vdup_n_u32(0); + if constexpr (residual >= 16) { + const uint8x8_t xb = vld1_u8(x + i / 2), yb = vld1_u8(y + i / 2); + tail = vdot_u32(tail, vand_u8(xb, vget_low_u8(nibble)), vand_u8(yb, vget_low_u8(nibble))); + tail = vdot_u32(tail, vshr_n_u8(xb, 4), vshr_n_u8(yb, 4)); + i += 16; + } + if constexpr (residual % 16 > 0) { + // One 8-byte load per operand from an even coordinate. The bytes past the last code are the + // metadata that follows the codes in every stored blob (at least 12 bytes, so the load + // stays inside it); masking x drops them and an odd dim's unused high nibble. + constexpr unsigned rest = residual % 16; + const uint8x8_t xb = vld1_u8(x + i / 2), yb = vld1_u8(y + i / 2); + const uint8x8_t x_low = vand_u8(xb, vcreate_u8(SQ4TailNibbleMask(rest, false))); + const uint8x8_t x_high = + vand_u8(vshr_n_u8(xb, 4), vcreate_u8(SQ4TailNibbleMask(rest, true))); + tail = vdot_u32(tail, x_low, vand_u8(yb, vget_low_u8(nibble))); + tail = vdot_u32(tail, x_high, vshr_n_u8(yb, 4)); + } + const uint32_t code_dot = vaddvq_u32(vaddq_u32(sum0, sum1)) + vaddv_u32(tail); + return spaces::quantized::Stored_InnerProduct_FromCodeDot( + x, y, dimension, static_cast(code_dot)); +} + +template // 0..31 +float SQ4_SQ4_InnerProductSIMD32_NEON_DOTPROD(const void *pVect1v, const void *pVect2v, + size_t dimension) { + return 1.0f - + SQ4_SQ4_InnerProductSIMD32_NEON_DOTPROD_IMP(pVect1v, pVect2v, dimension); +} + +} // namespace diff --git a/src/VecSim/spaces/IP/IP_NEON_SQ4_FP32.h b/src/VecSim/spaces/IP/IP_NEON_SQ4_FP32.h new file mode 100644 index 000000000..ace6fae4b --- /dev/null +++ b/src/VecSim/spaces/IP/IP_NEON_SQ4_FP32.h @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once +#include "VecSim/spaces/space_includes.h" +#include "VecSim/spaces/IP/IP.h" +#include "VecSim/types/sq4.h" +#include "VecSim/utils/alignment.h" +#include +#include + +namespace { + +/* + * Asymmetric SQ4 inner product with the same identity as SQ8: + * + * IP(x, y) ≈ Σ((min + delta * q_i) * y_i) = min * y_sum + delta * Σ(q_i * y_i) + * + * Storage packs coordinate i into byte i / 2, the low nibble for even i and the high nibble for + * odd i, followed by unaligned FP32 metadata. The query blob carries y_sum after its dim floats. + */ + +// Byte-to-u32 widening indices for TBL: lane j of the result is byte `first + j` of the table, +// zero-extended (out-of-range indices yield zero). +static inline uint8x16_t SQ4_NEON_WidenIndex(uint8_t first) { + const uint8_t z = 0xff; + const uint8_t f = first; + const uint8_t idx[16] = { + f, z, z, z, uint8_t(f + 1), z, z, z, uint8_t(f + 2), z, z, z, uint8_t(f + 3), z, z, z}; + return vld1q_u8(idx); +} + +// Load exactly two packed bytes, yielding four coordinates in order without touching metadata. +static inline float32x4_t SQ4_NEON_Unpack4(const uint8_t *data) { + const uint8x8_t packed = vcreate_u8(load_unaligned(data)); + const uint8x8_t ordered = vzip_u8(vand_u8(packed, vdup_n_u8(15)), vshr_n_u8(packed, 4)).val[0]; + return vcvtq_f32_u32(vmovl_u16(vget_low_u16(vmovl_u8(ordered)))); +} + +template // 0..15 +float SQ4_FP32_InnerProductSIMD16_NEON(const void *pVect1v, const void *pVect2v, size_t dimension) { + using vecsim_types::sq4; + const auto *x = static_cast(pVect1v); + const auto *y = static_cast(pVect2v); + float32x4_t sum0 = vdupq_n_f32(0.0f); + float32x4_t sum1 = vdupq_n_f32(0.0f); + float32x4_t sum2 = vdupq_n_f32(0.0f); + float32x4_t sum3 = vdupq_n_f32(0.0f); + const size_t complete = dimension - residual; + size_t i = 0; + const uint8x16_t widen0 = SQ4_NEON_WidenIndex(0), widen1 = SQ4_NEON_WidenIndex(4); + const uint32x4_t low_mask = vdupq_n_u32(15); + for (; i < complete; i += 16) { + // One eight-byte load covers sixteen coordinates. TBL puts one packed byte in each u32 + // lane; its low nibble is an even coordinate and its high nibble the next odd one, and a + // structure load (LD2) splits the query into the same even and odd lanes. + const uint8x16_t packed = vcombine_u8(vld1_u8(x + i / 2), vdup_n_u8(0)); + const uint32x4_t bytes0 = vreinterpretq_u32_u8(vqtbl1q_u8(packed, widen0)); + const uint32x4_t bytes1 = vreinterpretq_u32_u8(vqtbl1q_u8(packed, widen1)); + const float32x4x2_t query0 = vld2q_f32(y + i), query1 = vld2q_f32(y + i + 8); + sum0 = vfmaq_f32(sum0, vcvtq_f32_u32(vandq_u32(bytes0, low_mask)), query0.val[0]); + sum1 = vfmaq_f32(sum1, vcvtq_f32_u32(vshrq_n_u32(bytes0, 4)), query0.val[1]); + sum2 = vfmaq_f32(sum2, vcvtq_f32_u32(vandq_u32(bytes1, low_mask)), query1.val[0]); + sum3 = vfmaq_f32(sum3, vcvtq_f32_u32(vshrq_n_u32(bytes1, 4)), query1.val[1]); + } + // Packed tail: groups of four read two whole bytes, the last 1..3 coordinates read nibbles, + // so no load passes the code bytes (an odd dim's unused high nibble is never read). + if constexpr (residual >= 4) { + sum0 = vfmaq_f32(sum0, SQ4_NEON_Unpack4(x + i / 2), vld1q_f32(y + i)); + i += 4; + } + if constexpr (residual >= 8) { + sum1 = vfmaq_f32(sum1, SQ4_NEON_Unpack4(x + i / 2), vld1q_f32(y + i)); + i += 4; + } + if constexpr (residual >= 12) { + sum2 = vfmaq_f32(sum2, SQ4_NEON_Unpack4(x + i / 2), vld1q_f32(y + i)); + i += 4; + } + if constexpr (residual % 4 > 0) { + float32x4_t codes = vdupq_n_f32(0.0f); + float32x4_t query = vdupq_n_f32(0.0f); + const float q0 = sq4::get_code(x, i); + codes = vld1q_lane_f32(&q0, codes, 0); + query = vld1q_lane_f32(y + i, query, 0); + if constexpr (residual % 4 >= 2) { + const float q1 = sq4::get_code(x, i + 1); + codes = vld1q_lane_f32(&q1, codes, 1); + query = vld1q_lane_f32(y + i + 1, query, 1); + } + if constexpr (residual % 4 >= 3) { + const float q2 = sq4::get_code(x, i + 2); + codes = vld1q_lane_f32(&q2, codes, 2); + query = vld1q_lane_f32(y + i + 2, query, 2); + } + sum3 = vfmaq_f32(sum3, codes, query); + } + const float dot = vaddvq_f32(vaddq_f32(vaddq_f32(sum0, sum1), vaddq_f32(sum2, sum3))); + const auto *params = x + sq4::data_bytes_count(dimension); + const float min_val = load_unaligned(params + sq4::MIN_VAL * sizeof(float)); + const float delta = load_unaligned(params + sq4::DELTA * sizeof(float)); + return 1.0f - (min_val * y[dimension + sq4::SUM_QUERY] + delta * dot); +} + +} // namespace diff --git a/src/VecSim/spaces/IP/IP_NEON_SQ4_SQ4.h b/src/VecSim/spaces/IP/IP_NEON_SQ4_SQ4.h new file mode 100644 index 000000000..21344e934 --- /dev/null +++ b/src/VecSim/spaces/IP/IP_NEON_SQ4_SQ4.h @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once +#include "VecSim/spaces/space_includes.h" +#include "VecSim/types/sq4.h" +#include "VecSim/spaces/quantized_distance_helpers.h" +#include + +namespace { + +/* + * Symmetric SQ4-SQ4 inner product with the same identity as SQ8-SQ8: + * + * IP(x, y) = min_x * sum_y + min_y * sum_x - dim * min_x * min_y + * + delta_x * delta_y * Σ(qx_i * qy_i) + * + * Only the integer code dot Σ(qx_i * qy_i) is vectorized. Both operands pack coordinate i into + * byte i / 2, the low nibble for even i and the high nibble for odd i, so the code dot is the sum + * of the low-nibble products plus the sum of the high-nibble products and no lane reordering is + * needed. The total is exact in uint32 up to spaces::SQ4_MAX_EXACT_SIMD_DIM, which the dispatcher + * enforces. The packed codes are followed by unaligned FP32 metadata. + */ + +// Byte-lane mask for a tail of `residual` (0..15) coordinates read as one 8-byte load from an even +// coordinate: byte j keeps its low nibble while coordinate 2j is in the tail (high == false) and +// its high nibble while coordinate 2j + 1 is (high == true). Each kept lane is 0x0f. +constexpr uint64_t SQ4TailNibbleMask(unsigned residual, bool high) { + const unsigned kept = high ? residual / 2 : (residual + 1) / 2; + uint64_t mask = 0; + for (unsigned j = 0; j < kept; ++j) { + mask |= uint64_t(0x0f) << (8 * j); + } + return mask; +} + +// The masked tails here and in L2_NEON_SQ4_SQ4.h / IP_NEON_DOTPROD_SQ4_SQ4.h read up to 7 bytes of +// the metadata after the codes, so it must stay at least 8 bytes for both metrics. +static_assert(vecsim_types::sq4::storage_metadata_count() * sizeof(float) >= 8); +static_assert(vecsim_types::sq4::storage_metadata_count() * sizeof(float) >= 8); + +// Code products of one 8-byte group (16 coordinates), added pairwise into four uint32 lanes. A +// byte's low and high nibble products are at most 225 each, so their sum fits a uint16 lane. +static inline uint32x4_t SQ4_SQ4_DotStep_NEON(uint32x4_t sum, uint8x8_t x_low, uint8x8_t x_high, + uint8x8_t y) { + const uint16x8_t low = vmull_u8(x_low, vand_u8(y, vdup_n_u8(15))); + return vpadalq_u16(sum, vmlal_u8(low, x_high, vshr_n_u8(y, 4))); +} + +// Returns the raw inner product (not the distance); the L2 identity kernels share it. +template // 0..15 +float SQ4_SQ4_InnerProductSIMD16_NEON_IMP(const void *pVect1v, const void *pVect2v, + size_t dimension) { + const auto *x = static_cast(pVect1v); + const auto *y = static_cast(pVect2v); + const uint8x8_t nibble = vdup_n_u8(15); + uint32x4_t sum0 = vdupq_n_u32(0); + uint32x4_t sum1 = vdupq_n_u32(0); + const size_t complete = dimension - residual; + size_t i = 0; + const uint8x16_t nibble16 = vdupq_n_u8(15); + for (; i + 32 <= complete; i += 32) { + // One 16-byte load per operand covers 32 coordinates; the nibble split runs on whole + // registers and the widening multiplies take the low and high halves. + const uint8x16_t xb = vld1q_u8(x + i / 2), yb = vld1q_u8(y + i / 2); + const uint8x16_t xl = vandq_u8(xb, nibble16), xh = vshrq_n_u8(xb, 4); + const uint8x16_t yl = vandq_u8(yb, nibble16), yh = vshrq_n_u8(yb, 4); + const uint16x8_t lo = + vmlal_u8(vmull_u8(vget_low_u8(xl), vget_low_u8(yl)), vget_low_u8(xh), vget_low_u8(yh)); + const uint16x8_t hi = vmlal_high_u8(vmull_high_u8(xl, yl), xh, yh); + sum0 = vpadalq_u16(sum0, lo); + sum1 = vpadalq_u16(sum1, hi); + } + if (i < complete) { + const uint8x8_t x0 = vld1_u8(x + i / 2); + sum0 = + SQ4_SQ4_DotStep_NEON(sum0, vand_u8(x0, nibble), vshr_n_u8(x0, 4), vld1_u8(y + i / 2)); + i += 16; + } + if constexpr (residual > 0) { + // One 8-byte load per operand from an even coordinate. The bytes past the last code are the + // metadata that follows the codes in every stored blob (at least 12 bytes, so the load + // stays inside it); masking x drops them and an odd dim's unused high nibble. + const uint8x8_t xt = vld1_u8(x + i / 2); + const uint8x8_t x_low = vand_u8(xt, vcreate_u8(SQ4TailNibbleMask(residual, false))); + const uint8x8_t x_high = + vand_u8(vshr_n_u8(xt, 4), vcreate_u8(SQ4TailNibbleMask(residual, true))); + sum1 = SQ4_SQ4_DotStep_NEON(sum1, x_low, x_high, vld1_u8(y + i / 2)); + } + const uint32_t code_dot = vaddvq_u32(vaddq_u32(sum0, sum1)); + return spaces::quantized::Stored_InnerProduct_FromCodeDot( + x, y, dimension, static_cast(code_dot)); +} + +template // 0..15 +float SQ4_SQ4_InnerProductSIMD16_NEON(const void *pVect1v, const void *pVect2v, size_t dimension) { + return 1.0f - SQ4_SQ4_InnerProductSIMD16_NEON_IMP(pVect1v, pVect2v, dimension); +} + +} // namespace diff --git a/src/VecSim/spaces/IP/IP_SVE_SQ4_FP32.h b/src/VecSim/spaces/IP/IP_SVE_SQ4_FP32.h new file mode 100644 index 000000000..3a5307000 --- /dev/null +++ b/src/VecSim/spaces/IP/IP_SVE_SQ4_FP32.h @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once +#include "VecSim/spaces/space_includes.h" +#include "VecSim/spaces/IP/IP.h" +#include "VecSim/types/sq4.h" +#include "VecSim/utils/alignment.h" +#include +#include + +// SVE.cpp and SVE2.cpp both compile this header, under different -march flags. The +// anonymous namespace keeps each tier's bodies to itself; without it they are weak +// symbols that both objects define and link order picks the -march. Only the Choose_* +// entry points stay external. Dependencies above must stay outside the namespace. +namespace { + +/* + * Asymmetric SQ4 inner product with the same identity as SQ8: + * + * IP(x, y) ≈ Σ((min + delta * q_i) * y_i) = min * y_sum + delta * Σ(q_i * y_i) + * + * Storage packs coordinate i into byte i / 2, the low nibble for even i and the high nibble for + * odd i, followed by unaligned FP32 metadata. The query blob carries y_sum after its dim floats. + */ + +// Coordinates per step: one u32 lane per packed byte, two coordinates per lane. +static inline size_t SQ4_FP32_SVE_CoordinatesPerStep() { return 2 * svcntw(); } + +// Helper: accumulate Σ(q_i * y_i) for the 2 * svcntw() coordinates held in svcntw() packed bytes +// (no dequantization). The low nibbles are the even coordinates and the high nibbles the odd ones; +// a de-interleaving load splits the query the same way, so no lane reordering is needed. +static inline void InnerProductStepSQ4_FP32(const uint8_t *x, const float *y, svfloat32_t &sum_even, + svfloat32_t &sum_odd) { + const svbool_t pg = svptrue_b32(); + const svuint32_t packed = svld1ub_u32(pg, x); + const svfloat32x2_t query = svld2_f32(pg, y); + sum_even = svmla_f32_x(pg, sum_even, svcvt_f32_u32_x(pg, svand_n_u32_x(pg, packed, 15)), + svget2_f32(query, 0)); + sum_odd = svmla_f32_x(pg, sum_odd, svcvt_f32_u32_x(pg, svlsr_n_u32_x(pg, packed, 4)), + svget2_f32(query, 1)); +} + +// Four accumulators and one final affine correction, as in SQ8. Full steps precede the tail, so +// every packed load starts at an even coordinate (a whole byte). +template +float SQ4_FP32_InnerProductSIMD_SVE(const void *pVect1v, const void *pVect2v, size_t dimension) { + using vecsim_types::sq4; + const auto *x = static_cast(pVect1v); + const auto *y = static_cast(pVect2v); + const size_t vl = svcntw(); // packed bytes per step + const svbool_t pg = svptrue_b32(); + svfloat32_t sum0 = svdup_f32(0.0f); + svfloat32_t sum1 = svdup_f32(0.0f); + svfloat32_t sum2 = svdup_f32(0.0f); + svfloat32_t sum3 = svdup_f32(0.0f); + size_t offset = 0; // in packed bytes; the step's first coordinate is 2 * offset + const size_t main_bytes = (dimension / (8 * vl)) * 4 * vl; + for (; offset < main_bytes; offset += 4 * vl) { + InnerProductStepSQ4_FP32(x + offset, y + 2 * offset, sum0, sum1); + InnerProductStepSQ4_FP32(x + offset + vl, y + 2 * (offset + vl), sum2, sum3); + InnerProductStepSQ4_FP32(x + offset + 2 * vl, y + 2 * (offset + 2 * vl), sum0, sum1); + InnerProductStepSQ4_FP32(x + offset + 3 * vl, y + 2 * (offset + 3 * vl), sum2, sum3); + } + if constexpr (additional_steps > 0) { + InnerProductStepSQ4_FP32(x + offset, y + 2 * offset, sum0, sum1); + offset += vl; + } + if constexpr (additional_steps > 1) { + InnerProductStepSQ4_FP32(x + offset, y + 2 * offset, sum2, sum3); + offset += vl; + } + if constexpr (additional_steps > 2) { + InnerProductStepSQ4_FP32(x + offset, y + 2 * offset, sum0, sum1); + offset += vl; + } + if constexpr (partial_chunk) { + // (remaining + 1) / 2 bytes hold the tail. Their even coordinates are all in it, their odd + // ones only for the first remaining / 2 bytes (an odd dim's last high nibble is padding). + // The structure load reads y in pairs, so an odd tail's last pair reads the first query + // metadata float, which odd_pg then drops. + const size_t remaining = dimension - 2 * offset; + const svbool_t even_pg = svwhilelt_b32(uint64_t(0), uint64_t((remaining + 1) / 2)); + const svbool_t odd_pg = svwhilelt_b32(uint64_t(0), uint64_t(remaining / 2)); + const svuint32_t packed = svld1ub_u32(even_pg, x + offset); + const svfloat32x2_t query = svld2_f32(even_pg, y + 2 * offset); + sum0 = svmla_f32_m(even_pg, sum0, svcvt_f32_u32_x(pg, svand_n_u32_x(pg, packed, 15)), + svget2_f32(query, 0)); + sum1 = svmla_f32_m(odd_pg, sum1, svcvt_f32_u32_x(pg, svlsr_n_u32_x(pg, packed, 4)), + svget2_f32(query, 1)); + } + svfloat32_t sum = svadd_f32_x(pg, sum0, sum1); + sum = svadd_f32_x(pg, sum, sum2); + sum = svadd_f32_x(pg, sum, sum3); + const float dot = svaddv_f32(pg, sum); + const auto *params = x + sq4::data_bytes_count(dimension); + const float min_val = load_unaligned(params + sq4::MIN_VAL * sizeof(float)); + const float delta = load_unaligned(params + sq4::DELTA * sizeof(float)); + return 1.0f - (min_val * y[dimension + sq4::SUM_QUERY] + delta * dot); +} + +} // namespace diff --git a/src/VecSim/spaces/IP/IP_SVE_SQ4_SQ4.h b/src/VecSim/spaces/IP/IP_SVE_SQ4_SQ4.h new file mode 100644 index 000000000..1ac93c0b3 --- /dev/null +++ b/src/VecSim/spaces/IP/IP_SVE_SQ4_SQ4.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once +#include "VecSim/spaces/space_includes.h" +#include "VecSim/types/sq4.h" +#include "VecSim/spaces/quantized_distance_helpers.h" +#include + +// SVE.cpp and SVE2.cpp both compile this header, under different -march flags. The +// anonymous namespace keeps each tier's bodies to itself; without it they are weak +// symbols that both objects define and link order picks the -march. Only the Choose_* +// entry points stay external. Dependencies above must stay outside the namespace. +namespace { + +/* + * Symmetric SQ4-SQ4 inner product with the same identity as SQ8-SQ8: + * + * IP(x, y) = min_x * sum_y + min_y * sum_x - dim * min_x * min_y + * + delta_x * delta_y * Σ(qx_i * qy_i) + * + * Only the integer code dot Σ(qx_i * qy_i) is vectorized, with svdot_u32 on the low nibbles and on + * the high nibbles unpacked to bytes. Both operands pack coordinate i into byte i / 2 (the low + * nibble for even i), so no lane reordering is needed. The uint32 lanes are exact up to + * spaces::SQ4_MAX_EXACT_SIMD_DIM, which the dispatcher enforces. + */ + +// Coordinates per SVE vector of packed bytes: the chunk CHOOSE_SVE_IMPLEMENTATION steps by. +static inline size_t SQ4_SQ4_SVE_CoordinatesPerVector() { return 2 * svcntb(); } + +// Code dot of one full vector of packed bytes. +static inline void InnerProductStepSQ4_SQ4_SVE(const uint8_t *x, const uint8_t *y, + svuint32_t &sum) { + const svbool_t pg = svptrue_b8(); + const svuint8_t xb = svld1_u8(pg, x), yb = svld1_u8(pg, y); + sum = svdot_u32(sum, svand_n_u8_x(pg, xb, 15), svand_n_u8_x(pg, yb, 15)); + sum = svdot_u32(sum, svlsr_n_u8_x(pg, xb, 4), svlsr_n_u8_x(pg, yb, 4)); +} + +// Returns the raw inner product (not the distance); the L2 identity kernels share it. +template +float SQ4_SQ4_InnerProductSIMD_SVE_IMP(const void *pVect1v, const void *pVect2v, size_t dimension) { + const auto *x = static_cast(pVect1v); + const auto *y = static_cast(pVect2v); + const size_t vl = svcntb(); + const size_t chunk = 2 * vl; + svuint32_t sum0 = svdup_u32(0); + svuint32_t sum1 = svdup_u32(0); + svuint32_t sum2 = svdup_u32(0); + svuint32_t sum3 = svdup_u32(0); + size_t offset = 0; // in coordinates; always even before the tail, so x + offset / 2 is a byte + // Bounds compared rather than divided, as in the SQ8 kernels: chunk is a runtime value. + for (; offset + 4 * chunk <= dimension; offset += 4 * chunk) { + InnerProductStepSQ4_SQ4_SVE(x + offset / 2, y + offset / 2, sum0); + InnerProductStepSQ4_SQ4_SVE(x + offset / 2 + vl, y + offset / 2 + vl, sum1); + InnerProductStepSQ4_SQ4_SVE(x + offset / 2 + 2 * vl, y + offset / 2 + 2 * vl, sum2); + InnerProductStepSQ4_SQ4_SVE(x + offset / 2 + 3 * vl, y + offset / 2 + 3 * vl, sum3); + } + if constexpr (additional_steps > 0) { + InnerProductStepSQ4_SQ4_SVE(x + offset / 2, y + offset / 2, sum0); + offset += chunk; + } + if constexpr (additional_steps > 1) { + InnerProductStepSQ4_SQ4_SVE(x + offset / 2, y + offset / 2, sum1); + offset += chunk; + } + if constexpr (additional_steps > 2) { + InnerProductStepSQ4_SQ4_SVE(x + offset / 2, y + offset / 2, sum2); + offset += chunk; + } + if constexpr (partial_chunk) { + const size_t remaining = dimension - offset; + // The bytes holding any remaining coordinate, and those whose high nibble is one too: an + // odd dim's last byte carries an unused high nibble. Loads zero the inactive lanes. + const svbool_t pg = svptrue_b8(); + const svbool_t bytes_pg = svwhilelt_b8(uint64_t(0), uint64_t((remaining + 1) / 2)); + const svbool_t high_pg = svwhilelt_b8(uint64_t(0), uint64_t(remaining / 2)); + const svuint8_t xb = svld1_u8(bytes_pg, x + offset / 2); + const svuint8_t yb = svld1_u8(bytes_pg, y + offset / 2); + sum3 = svdot_u32(sum3, svand_n_u8_x(pg, xb, 15), svand_n_u8_x(pg, yb, 15)); + sum3 = svdot_u32(sum3, svlsr_n_u8_z(high_pg, xb, 4), svlsr_n_u8_x(pg, yb, 4)); + } + const svbool_t pg32 = svptrue_b32(); + svuint32_t sum = svadd_u32_x(pg32, sum0, sum1); + sum = svadd_u32_x(pg32, sum, sum2); + sum = svadd_u32_x(pg32, sum, sum3); + const float code_dot = static_cast(svaddv_u32(pg32, sum)); + + return spaces::quantized::Stored_InnerProduct_FromCodeDot(x, y, dimension, + code_dot); +} + +template +float SQ4_SQ4_InnerProductSIMD_SVE(const void *pVect1v, const void *pVect2v, size_t dimension) { + return 1.0f - SQ4_SQ4_InnerProductSIMD_SVE_IMP( + pVect1v, pVect2v, dimension); +} + +} // namespace diff --git a/src/VecSim/spaces/IP_space.cpp b/src/VecSim/spaces/IP_space.cpp index 224e28bb6..ba5a5f0a8 100644 --- a/src/VecSim/spaces/IP_space.cpp +++ b/src/VecSim/spaces/IP_space.cpp @@ -39,22 +39,101 @@ using bfloat16 = vecsim_types::bfloat16; using float16 = vecsim_types::float16; namespace spaces { -// SQ4-FP32: packed storage and unaligned metadata, so no alignment requirement. +// SQ4-FP32: packed storage and unaligned metadata, so no alignment requirement on any tier. dist_func_t IP_SQ4_FP32_GetDistFunc(size_t dim, unsigned char *alignment, const void *arch_opt) { if (alignment) { *alignment = 0; } - return SQ4_FP32_InnerProduct; + dist_func_t ret_dist_func = SQ4_FP32_InnerProduct; + [[maybe_unused]] auto features = getCpuOptimizationFeatures(arch_opt); +#ifdef CPU_FEATURES_ARCH_AARCH64 + // The kernels handle any dim: tails read only the codes and the query's floats plus metadata. +#ifdef OPT_SVE2 + if (features.sve2) { + return Choose_SQ4_FP32_IP_implementation_SVE2(dim); + } +#endif +#ifdef OPT_SVE + if (features.sve) { + return Choose_SQ4_FP32_IP_implementation_SVE(dim); + } +#endif +#ifdef OPT_NEON + if (features.asimd) { + return Choose_SQ4_FP32_IP_implementation_NEON(dim); + } +#endif +#endif +#ifdef CPU_FEATURES_ARCH_X86_64 + // As SQ8: below eight coordinates scalar is at least as fast. + if (dim < 8) { + return ret_dist_func; + } +#ifdef OPT_AVX512_F_BW_VL_VNNI + if (features.avx512f && features.avx512bw && features.avx512vl && features.avx512vnni) { + return Choose_SQ4_FP32_IP_implementation_AVX512F_BW_VL_VNNI(dim); + } +#endif +#ifdef OPT_AVX2_FMA + if (features.avx2 && features.fma3) { + return Choose_SQ4_FP32_IP_implementation_AVX2_FMA(dim); + } +#endif +#endif + return ret_dist_func; } -// SQ4-SQ4: packed storage and unaligned metadata, so no alignment requirement. +// SQ4-SQ4: packed storage and unaligned metadata, so no alignment requirement on any tier. dist_func_t IP_SQ4_SQ4_GetDistFunc(size_t dim, unsigned char *alignment, const void *arch_opt) { if (alignment) { *alignment = 0; } - return SQ4_SQ4_InnerProduct; + dist_func_t ret_dist_func = SQ4_SQ4_InnerProduct; + // Above this dimension the SIMD kernels' uint32 code dot could wrap, so hand back the scalar + // kernel. Decided here, once per index. See spaces.h for how the bound is derived. + if (dim > spaces::SQ4_MAX_EXACT_SIMD_DIM) { + return ret_dist_func; + } + [[maybe_unused]] auto features = getCpuOptimizationFeatures(arch_opt); +#ifdef CPU_FEATURES_ARCH_AARCH64 +#ifdef OPT_SVE2 + if (features.sve2) { + return Choose_SQ4_SQ4_IP_implementation_SVE2(dim); + } +#endif +#ifdef OPT_SVE + if (features.sve) { + return Choose_SQ4_SQ4_IP_implementation_SVE(dim); + } +#endif +#ifdef OPT_NEON_DOTPROD + if (features.asimddp && dim >= 16) { + return Choose_SQ4_SQ4_IP_implementation_NEON_DOTPROD(dim); + } +#endif +#ifdef OPT_NEON + if (features.asimd && dim >= 16) { + return Choose_SQ4_SQ4_IP_implementation_NEON(dim); + } +#endif +#endif +#ifdef CPU_FEATURES_ARCH_X86_64 +#ifdef OPT_AVX512_F_BW_VL_VNNI + // The kernel handles any dim, but below one 64-coordinate chunk scalar is at least as fast. + if (features.avx512f && features.avx512bw && features.avx512vl && features.avx512vnni && + dim >= 64) { + return Choose_SQ4_SQ4_IP_implementation_AVX512F_BW_VL_VNNI(dim); + } +#endif +#ifdef OPT_AVX2 + if (features.avx2 && dim >= 64) { + return Choose_SQ4_SQ4_IP_implementation_AVX2(dim); + } +#endif +#endif + return ret_dist_func; } // SQ8-FP32: asymmetric distance between SQ8 storage and FP32 query diff --git a/src/VecSim/spaces/L2/L2_AVX2_FMA_SQ4_FP32.h b/src/VecSim/spaces/L2/L2_AVX2_FMA_SQ4_FP32.h new file mode 100644 index 000000000..6c08305e7 --- /dev/null +++ b/src/VecSim/spaces/L2/L2_AVX2_FMA_SQ4_FP32.h @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once +#include "VecSim/spaces/space_includes.h" +#include "VecSim/spaces/AVX_utils.h" +// SQ4_Unpack_AVX2_FMA, SQ4_ToFloats_AVX2_FMA, SQ4_LoadBytes_AVX2_FMA, SQ4_TailLanes_AVX2_FMA, +// SQ4_TailQuery_AVX2_FMA, SQ4_TailCodes_AVX2_FMA +#include "VecSim/spaces/IP/IP_AVX2_FMA_SQ4_FP32.h" +#include "VecSim/types/sq4.h" +#include "VecSim/utils/alignment.h" +#include + +namespace { + +/* + * Asymmetric SQ4-FP32 L2 squared distance via direct residual accumulation, as SQ8: + * + * ||x - y||² = Σ(delta * q_i + (min - y_i))² + * + * Keeping min - y first (one fused multiply-add per coordinate) rounds at the scale of the + * residual, not of min, when the data has a large common offset. Storage packs coordinate i into + * byte i / 2, the low nibble for even i and the high nibble for odd i, followed by unaligned FP32 + * metadata. + */ + +// Accumulate Σ(diff_i²) for eight coordinates. +static inline __m256 SQ4_FP32_L2Step_AVX2_FMA(__m256 sum, __m256 codes, __m256 query, + __m256 min_val_vec, __m256 delta_vec) { + const __m256 diff = _mm256_fmadd_ps(delta_vec, codes, _mm256_sub_ps(min_val_vec, query)); + return _mm256_fmadd_ps(diff, diff, sum); +} + +// As SQ4_FP32_L2Step_AVX2_FMA for a tail of `lanes` (1..8) coordinates held in the top lanes (see +// SQ4_TailQuery_AVX2_FMA); the other lanes' diff is zeroed. +template +static inline __m256 SQ4_FP32_L2TailStep_AVX2_FMA(__m256 sum, __m256 codes, __m256 query, + __m256 min_val_vec, __m256 delta_vec) { + const __m256 diff = _mm256_blend_ps( + _mm256_setzero_ps(), _mm256_fmadd_ps(delta_vec, codes, _mm256_sub_ps(min_val_vec, query)), + SQ4_TailLanes_AVX2_FMA); + return _mm256_fmadd_ps(diff, diff, sum); +} + +template // 0..31 +float SQ4_FP32_L2SqrSIMD32_AVX2_FMA(const void *pVect1v, const void *pVect2v, size_t dimension) { + using vecsim_types::sq4; + const auto *x = static_cast(pVect1v); + const auto *y = static_cast(pVect2v); + const auto *params = x + sq4::data_bytes_count(dimension); + const __m256 min_val_vec = + _mm256_set1_ps(load_unaligned(params + sq4::MIN_VAL * sizeof(float))); + const __m256 delta_vec = + _mm256_set1_ps(load_unaligned(params + sq4::DELTA * sizeof(float))); + // Four accumulators break the FMA dependency chain. + __m256 sum0 = _mm256_setzero_ps(); + __m256 sum1 = _mm256_setzero_ps(); + __m256 sum2 = _mm256_setzero_ps(); + __m256 sum3 = _mm256_setzero_ps(); + const size_t complete = dimension - residual; + for (size_t i = 0; i < complete; i += 32) { + // One 16-byte load covers exactly 32 coordinates. + __m128i ordered0, ordered1; + SQ4_Unpack_AVX2_FMA(_mm_loadu_si128(reinterpret_cast(x + i / 2)), ordered0, + ordered1); + __m256 codes0, codes1, codes2, codes3; + SQ4_ToFloats_AVX2_FMA(ordered0, codes0, codes1); + SQ4_ToFloats_AVX2_FMA(ordered1, codes2, codes3); + sum0 = + SQ4_FP32_L2Step_AVX2_FMA(sum0, codes0, _mm256_loadu_ps(y + i), min_val_vec, delta_vec); + sum1 = SQ4_FP32_L2Step_AVX2_FMA(sum1, codes1, _mm256_loadu_ps(y + i + 8), min_val_vec, + delta_vec); + sum2 = SQ4_FP32_L2Step_AVX2_FMA(sum2, codes2, _mm256_loadu_ps(y + i + 16), min_val_vec, + delta_vec); + sum3 = SQ4_FP32_L2Step_AVX2_FMA(sum3, codes3, _mm256_loadu_ps(y + i + 24), min_val_vec, + delta_vec); + } + size_t i = complete; + if constexpr (residual >= 16) { + // One 8-byte load covers exactly 16 coordinates. + __m128i ordered, unused; + SQ4_Unpack_AVX2_FMA(_mm_loadl_epi64(reinterpret_cast(x + i / 2)), ordered, + unused); + __m256 codes0, codes1; + SQ4_ToFloats_AVX2_FMA(ordered, codes0, codes1); + sum0 = + SQ4_FP32_L2Step_AVX2_FMA(sum0, codes0, _mm256_loadu_ps(y + i), min_val_vec, delta_vec); + sum1 = SQ4_FP32_L2Step_AVX2_FMA(sum1, codes1, _mm256_loadu_ps(y + i + 8), min_val_vec, + delta_vec); + i += 16; + } + constexpr unsigned rest = residual % 16; + if constexpr (rest > 0) { + // Exactly the tail's code bytes. The last query window ends at the last coordinate (see + // SQ4_TailQuery_AVX2_FMA). + __m128i ordered, unused; + SQ4_Unpack_AVX2_FMA(SQ4_LoadBytes_AVX2_FMA<(rest + 1) / 2>(x + i / 2), ordered, unused); + const float *end = y + dimension; + if constexpr (rest > 8) { + const __m256 codes0 = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(ordered)); + sum2 = SQ4_FP32_L2Step_AVX2_FMA(sum2, codes0, _mm256_loadu_ps(y + i), min_val_vec, + delta_vec); + sum3 = SQ4_FP32_L2TailStep_AVX2_FMA( + sum3, SQ4_TailCodes_AVX2_FMA(_mm_unpackhi_epi64(ordered, ordered)), + SQ4_TailQuery_AVX2_FMA(end, dimension), min_val_vec, delta_vec); + } else { + sum2 = SQ4_FP32_L2TailStep_AVX2_FMA(sum2, SQ4_TailCodes_AVX2_FMA(ordered), + SQ4_TailQuery_AVX2_FMA(end, dimension), + min_val_vec, delta_vec); + } + } + return my_mm256_reduce_add_ps_tree( + _mm256_add_ps(_mm256_add_ps(sum0, sum1), _mm256_add_ps(sum2, sum3))); +} + +} // namespace diff --git a/src/VecSim/spaces/L2/L2_AVX2_SQ4_SQ4.h b/src/VecSim/spaces/L2/L2_AVX2_SQ4_SQ4.h new file mode 100644 index 000000000..2b1d27e68 --- /dev/null +++ b/src/VecSim/spaces/L2/L2_AVX2_SQ4_SQ4.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once +#include "VecSim/spaces/space_includes.h" +// SQ4_SQ4_InnerProductSIMD64_AVX2_IMP +#include "VecSim/spaces/IP/IP_AVX2_SQ4_SQ4.h" +#include "VecSim/types/sq4.h" +#include "VecSim/utils/alignment.h" +#include + +namespace { + +/* + * Symmetric SQ4-SQ4 L2 squared distance by the stored-sum identity, the same one SQ8-SQ8 uses: + * + * ||x - y||^2 = ||x||^2 + ||y||^2 - 2 * IP(x, y) + * + * where ||x||^2 and ||y||^2 are the stored SUM_SQUARES metadata and IP(x, y) comes from the + * integer code dot of the inner product kernel. Exact-dim bound and dispatch as the inner product + * kernel. + */ +template // 0..63 +float SQ4_SQ4_L2SqrSIMD64_AVX2(const void *pVect1v, const void *pVect2v, size_t dimension) { + using vecsim_types::sq4; + const float ip = SQ4_SQ4_InnerProductSIMD64_AVX2_IMP(pVect1v, pVect2v, dimension); + const auto *x = static_cast(pVect1v); + const auto *y = static_cast(pVect2v); + const size_t data_bytes = sq4::data_bytes_count(dimension); + const float sum_sq_x = load_unaligned(x + data_bytes + sq4::SUM_SQUARES * sizeof(float)); + const float sum_sq_y = load_unaligned(y + data_bytes + sq4::SUM_SQUARES * sizeof(float)); + return sum_sq_x + sum_sq_y - 2.0f * ip; +} + +} // namespace diff --git a/src/VecSim/spaces/L2/L2_AVX512F_BW_VL_VNNI_SQ4_FP32.h b/src/VecSim/spaces/L2/L2_AVX512F_BW_VL_VNNI_SQ4_FP32.h new file mode 100644 index 000000000..9928060df --- /dev/null +++ b/src/VecSim/spaces/L2/L2_AVX512F_BW_VL_VNNI_SQ4_FP32.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once +#include "VecSim/spaces/space_includes.h" +// SQ4_Unpack32_AVX512F_BW_VL_VNNI, SQ4TailMasks_AVX512F_BW_VL_VNNI +#include "VecSim/spaces/IP/IP_AVX512F_BW_VL_VNNI_SQ4_FP32.h" +#include "VecSim/types/sq4.h" +#include "VecSim/utils/alignment.h" +#include + +namespace { + +/* + * Asymmetric SQ4-FP32 L2 squared distance via direct residual accumulation, as SQ8: + * + * ||x - y||² = Σ(delta * q_i + (min - y_i))² + * + * Keeping min - y first (one fused multiply-add per coordinate) rounds at the scale of the + * residual, not of min, when the data has a large common offset. Storage packs coordinate i into + * byte i / 2, the low nibble for even i and the high nibble for odd i, followed by unaligned FP32 + * metadata. + */ + +static inline __m512 SQ4_FP32_L2Diff_AVX512F_BW_VL_VNNI(__m512 codes, __m512 query, + __m512 min_val_vec, __m512 delta_vec) { + return _mm512_fmadd_ps(delta_vec, codes, _mm512_sub_ps(min_val_vec, query)); +} + +template // 0..31 +float SQ4_FP32_L2SqrSIMD32_AVX512F_BW_VL_VNNI(const void *pVect1v, const void *pVect2v, + size_t dimension) { + using vecsim_types::sq4; + const auto *x = static_cast(pVect1v); + const auto *y = static_cast(pVect2v); + const auto *params = x + sq4::data_bytes_count(dimension); + const __m512 min_val_vec = + _mm512_set1_ps(load_unaligned(params + sq4::MIN_VAL * sizeof(float))); + const __m512 delta_vec = + _mm512_set1_ps(load_unaligned(params + sq4::DELTA * sizeof(float))); + __m512 sum0 = _mm512_setzero_ps(); + __m512 sum1 = _mm512_setzero_ps(); + const size_t complete = dimension - residual; + for (size_t i = 0; i < complete; i += 32) { + __m512 codes0, codes1; + SQ4_Unpack32_AVX512F_BW_VL_VNNI( + _mm_loadu_si128(reinterpret_cast(x + i / 2)), codes0, codes1); + const __m512 diff0 = SQ4_FP32_L2Diff_AVX512F_BW_VL_VNNI(codes0, _mm512_loadu_ps(y + i), + min_val_vec, delta_vec); + const __m512 diff1 = SQ4_FP32_L2Diff_AVX512F_BW_VL_VNNI(codes1, _mm512_loadu_ps(y + i + 16), + min_val_vec, delta_vec); + sum0 = _mm512_fmadd_ps(diff0, diff0, sum0); + sum1 = _mm512_fmadd_ps(diff1, diff1, sum1); + } + if constexpr (residual > 0) { + // Masked loads of exactly the tail's code bytes and query floats, so nothing past the codes + // or the query's dim floats is read. Masked-out lanes keep the running sum, which also + // drops the padding nibble of an odd dim. + using masks = SQ4TailMasks_AVX512F_BW_VL_VNNI; + __m512 codes0, codes1; + SQ4_Unpack32_AVX512F_BW_VL_VNNI(_mm_maskz_loadu_epi8(masks::bytes, x + complete / 2), + codes0, codes1); + const __m512 diff0 = SQ4_FP32_L2Diff_AVX512F_BW_VL_VNNI( + codes0, _mm512_maskz_loadu_ps(masks::first, y + complete), min_val_vec, delta_vec); + sum0 = _mm512_mask3_fmadd_ps(diff0, diff0, sum0, masks::first); + if constexpr (masks::second != 0) { + const __m512 diff1 = SQ4_FP32_L2Diff_AVX512F_BW_VL_VNNI( + codes1, _mm512_maskz_loadu_ps(masks::second, y + complete + 16), min_val_vec, + delta_vec); + sum1 = _mm512_mask3_fmadd_ps(diff1, diff1, sum1, masks::second); + } + } + return _mm512_reduce_add_ps(_mm512_add_ps(sum0, sum1)); +} + +} // namespace diff --git a/src/VecSim/spaces/L2/L2_AVX512F_BW_VL_VNNI_SQ4_SQ4.h b/src/VecSim/spaces/L2/L2_AVX512F_BW_VL_VNNI_SQ4_SQ4.h new file mode 100644 index 000000000..4216fe15b --- /dev/null +++ b/src/VecSim/spaces/L2/L2_AVX512F_BW_VL_VNNI_SQ4_SQ4.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once +#include "VecSim/spaces/space_includes.h" +// SQ4_SQ4_InnerProductSIMD64_AVX512F_BW_VL_VNNI_IMP +#include "VecSim/spaces/IP/IP_AVX512F_BW_VL_VNNI_SQ4_SQ4.h" +#include "VecSim/types/sq4.h" +#include "VecSim/utils/alignment.h" +#include + +namespace { + +/* + * Symmetric SQ4-SQ4 L2 squared distance by the stored-sum identity, the same one SQ8-SQ8 uses: + * + * ||x - y||^2 = ||x||^2 + ||y||^2 - 2 * IP(x, y) + * + * where ||x||^2 and ||y||^2 are the stored SUM_SQUARES metadata and IP(x, y) comes from the + * integer code dot of the inner product kernel. Exact-dim bound and dispatch as the inner product + * kernel. + */ +template // 0..63 +float SQ4_SQ4_L2SqrSIMD64_AVX512F_BW_VL_VNNI(const void *pVect1v, const void *pVect2v, + size_t dimension) { + using vecsim_types::sq4; + const float ip = + SQ4_SQ4_InnerProductSIMD64_AVX512F_BW_VL_VNNI_IMP(pVect1v, pVect2v, dimension); + const auto *x = static_cast(pVect1v); + const auto *y = static_cast(pVect2v); + const size_t data_bytes = sq4::data_bytes_count(dimension); + const float sum_sq_x = load_unaligned(x + data_bytes + sq4::SUM_SQUARES * sizeof(float)); + const float sum_sq_y = load_unaligned(y + data_bytes + sq4::SUM_SQUARES * sizeof(float)); + return sum_sq_x + sum_sq_y - 2.0f * ip; +} + +} // namespace diff --git a/src/VecSim/spaces/L2/L2_NEON_DOTPROD_SQ4_SQ4.h b/src/VecSim/spaces/L2/L2_NEON_DOTPROD_SQ4_SQ4.h new file mode 100644 index 000000000..c76837552 --- /dev/null +++ b/src/VecSim/spaces/L2/L2_NEON_DOTPROD_SQ4_SQ4.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once +#include "VecSim/spaces/space_includes.h" +#include "VecSim/spaces/IP/IP_NEON_DOTPROD_SQ4_SQ4.h" // SQ4_SQ4_InnerProductSIMD32_NEON_DOTPROD_IMP +#include "VecSim/types/sq4.h" +#include "VecSim/utils/alignment.h" + +namespace { + +/* + * Symmetric SQ4-SQ4 L2 squared distance by the stored-sum identity, the same one SQ8-SQ8 uses: + * + * ||x - y||^2 = ||x||^2 + ||y||^2 - 2 * IP(x, y) + * + * where ||x||^2 and ||y||^2 are the stored SUM_SQUARES metadata and IP(x, y) comes from the + * integer code dot of the inner product kernel. Exact-dim bound and dispatch as the inner product + * kernel. + */ +template // 0..31 +float SQ4_SQ4_L2SqrSIMD32_NEON_DOTPROD(const void *pVect1v, const void *pVect2v, size_t dimension) { + using vecsim_types::sq4; + const float ip = + SQ4_SQ4_InnerProductSIMD32_NEON_DOTPROD_IMP(pVect1v, pVect2v, dimension); + const auto *x = static_cast(pVect1v); + const auto *y = static_cast(pVect2v); + const size_t data_bytes = sq4::data_bytes_count(dimension); + const float sum_sq_x = load_unaligned(x + data_bytes + sq4::SUM_SQUARES * sizeof(float)); + const float sum_sq_y = load_unaligned(y + data_bytes + sq4::SUM_SQUARES * sizeof(float)); + return sum_sq_x + sum_sq_y - 2.0f * ip; +} + +} // namespace diff --git a/src/VecSim/spaces/L2/L2_NEON_SQ4_FP32.h b/src/VecSim/spaces/L2/L2_NEON_SQ4_FP32.h new file mode 100644 index 000000000..7980e3bcf --- /dev/null +++ b/src/VecSim/spaces/L2/L2_NEON_SQ4_FP32.h @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once +#include "VecSim/spaces/space_includes.h" +#include "VecSim/spaces/IP/IP_NEON_SQ4_FP32.h" // SQ4_NEON_Unpack4, SQ4_NEON_WidenIndex +#include "VecSim/types/sq4.h" +#include "VecSim/utils/alignment.h" +#include + +namespace { + +/* + * Asymmetric SQ4-FP32 L2 squared distance via direct residual accumulation, as SQ8: + * + * ||x - y||² = Σ(delta * q_i + (min - y_i))² + * + * Keeping min - y first (one fused multiply-add per coordinate) rounds at the scale of the + * residual, not of min, when the data has a large common offset. Storage packs coordinate i into + * byte i / 2, the low nibble for even i and the high nibble for odd i, followed by unaligned FP32 + * metadata. + */ + +// Accumulate Σ(diff_i²) for four coordinates. +static inline float32x4_t L2StepSQ4_FP32_NEON(float32x4_t sum, float32x4_t codes, float32x4_t query, + float32x4_t min_val_vec, float32x4_t delta_vec) { + const float32x4_t diff = vfmaq_f32(vsubq_f32(min_val_vec, query), delta_vec, codes); + return vfmaq_f32(sum, diff, diff); +} + +template // 0..15 +float SQ4_FP32_L2SqrSIMD16_NEON(const void *pVect1v, const void *pVect2v, size_t dimension) { + using vecsim_types::sq4; + const auto *x = static_cast(pVect1v); + const auto *y = static_cast(pVect2v); + const auto *params = x + sq4::data_bytes_count(dimension); + const float min_val = load_unaligned(params + sq4::MIN_VAL * sizeof(float)); + const float delta = load_unaligned(params + sq4::DELTA * sizeof(float)); + const float32x4_t min_val_vec = vdupq_n_f32(min_val); + const float32x4_t delta_vec = vdupq_n_f32(delta); + float32x4_t sum0 = vdupq_n_f32(0.0f); + float32x4_t sum1 = vdupq_n_f32(0.0f); + float32x4_t sum2 = vdupq_n_f32(0.0f); + float32x4_t sum3 = vdupq_n_f32(0.0f); + const size_t complete = dimension - residual; + size_t i = 0; + const uint8x16_t widen0 = SQ4_NEON_WidenIndex(0), widen1 = SQ4_NEON_WidenIndex(4); + const uint32x4_t low_mask = vdupq_n_u32(15); + const uint8x16_t widen2 = SQ4_NEON_WidenIndex(8), widen3 = SQ4_NEON_WidenIndex(12); + // One 16-byte load covers 32 coordinates; a remaining 16-coordinate chunk takes one 8-byte + // load below. + for (; i + 32 <= complete; i += 32) { + const uint8x16_t packed = vld1q_u8(x + i / 2); + const uint32x4_t bytes0 = vreinterpretq_u32_u8(vqtbl1q_u8(packed, widen0)); + const uint32x4_t bytes1 = vreinterpretq_u32_u8(vqtbl1q_u8(packed, widen1)); + const uint32x4_t bytes2 = vreinterpretq_u32_u8(vqtbl1q_u8(packed, widen2)); + const uint32x4_t bytes3 = vreinterpretq_u32_u8(vqtbl1q_u8(packed, widen3)); + const float32x4x2_t query0 = vld2q_f32(y + i), query1 = vld2q_f32(y + i + 8); + const float32x4x2_t query2 = vld2q_f32(y + i + 16), query3 = vld2q_f32(y + i + 24); + sum0 = L2StepSQ4_FP32_NEON(sum0, vcvtq_f32_u32(vandq_u32(bytes0, low_mask)), query0.val[0], + min_val_vec, delta_vec); + sum1 = L2StepSQ4_FP32_NEON(sum1, vcvtq_f32_u32(vshrq_n_u32(bytes0, 4)), query0.val[1], + min_val_vec, delta_vec); + sum2 = L2StepSQ4_FP32_NEON(sum2, vcvtq_f32_u32(vandq_u32(bytes1, low_mask)), query1.val[0], + min_val_vec, delta_vec); + sum3 = L2StepSQ4_FP32_NEON(sum3, vcvtq_f32_u32(vshrq_n_u32(bytes1, 4)), query1.val[1], + min_val_vec, delta_vec); + sum0 = L2StepSQ4_FP32_NEON(sum0, vcvtq_f32_u32(vandq_u32(bytes2, low_mask)), query2.val[0], + min_val_vec, delta_vec); + sum1 = L2StepSQ4_FP32_NEON(sum1, vcvtq_f32_u32(vshrq_n_u32(bytes2, 4)), query2.val[1], + min_val_vec, delta_vec); + sum2 = L2StepSQ4_FP32_NEON(sum2, vcvtq_f32_u32(vandq_u32(bytes3, low_mask)), query3.val[0], + min_val_vec, delta_vec); + sum3 = L2StepSQ4_FP32_NEON(sum3, vcvtq_f32_u32(vshrq_n_u32(bytes3, 4)), query3.val[1], + min_val_vec, delta_vec); + } + if (i < complete) { + // As the IP kernel: TBL puts one packed byte in each u32 lane (an even coordinate in its + // low nibble, the next odd one in its high nibble) and LD2 splits the query the same way. + const uint8x16_t packed = vcombine_u8(vld1_u8(x + i / 2), vdup_n_u8(0)); + const uint32x4_t bytes0 = vreinterpretq_u32_u8(vqtbl1q_u8(packed, widen0)); + const uint32x4_t bytes1 = vreinterpretq_u32_u8(vqtbl1q_u8(packed, widen1)); + const float32x4x2_t query0 = vld2q_f32(y + i), query1 = vld2q_f32(y + i + 8); + sum0 = L2StepSQ4_FP32_NEON(sum0, vcvtq_f32_u32(vandq_u32(bytes0, low_mask)), query0.val[0], + min_val_vec, delta_vec); + sum1 = L2StepSQ4_FP32_NEON(sum1, vcvtq_f32_u32(vshrq_n_u32(bytes0, 4)), query0.val[1], + min_val_vec, delta_vec); + sum2 = L2StepSQ4_FP32_NEON(sum2, vcvtq_f32_u32(vandq_u32(bytes1, low_mask)), query1.val[0], + min_val_vec, delta_vec); + sum3 = L2StepSQ4_FP32_NEON(sum3, vcvtq_f32_u32(vshrq_n_u32(bytes1, 4)), query1.val[1], + min_val_vec, delta_vec); + i += 16; + } + // Packed tail: groups of four read two whole bytes, the last 1..3 coordinates read nibbles, + // so no load passes the code bytes (an odd dim's unused high nibble is never read). + if constexpr (residual >= 4) { + sum0 = L2StepSQ4_FP32_NEON(sum0, SQ4_NEON_Unpack4(x + i / 2), vld1q_f32(y + i), min_val_vec, + delta_vec); + i += 4; + } + if constexpr (residual >= 8) { + sum1 = L2StepSQ4_FP32_NEON(sum1, SQ4_NEON_Unpack4(x + i / 2), vld1q_f32(y + i), min_val_vec, + delta_vec); + i += 4; + } + if constexpr (residual >= 12) { + sum2 = L2StepSQ4_FP32_NEON(sum2, SQ4_NEON_Unpack4(x + i / 2), vld1q_f32(y + i), min_val_vec, + delta_vec); + i += 4; + } + if constexpr (residual % 4 > 0) { + // Padding lanes get q = 0 and y = min, so their diff is exactly 0. + float32x4_t codes = vdupq_n_f32(0.0f); + float32x4_t query = min_val_vec; + const float q0 = sq4::get_code(x, i); + codes = vld1q_lane_f32(&q0, codes, 0); + query = vld1q_lane_f32(y + i, query, 0); + if constexpr (residual % 4 >= 2) { + const float q1 = sq4::get_code(x, i + 1); + codes = vld1q_lane_f32(&q1, codes, 1); + query = vld1q_lane_f32(y + i + 1, query, 1); + } + if constexpr (residual % 4 >= 3) { + const float q2 = sq4::get_code(x, i + 2); + codes = vld1q_lane_f32(&q2, codes, 2); + query = vld1q_lane_f32(y + i + 2, query, 2); + } + sum3 = L2StepSQ4_FP32_NEON(sum3, codes, query, min_val_vec, delta_vec); + } + return vaddvq_f32(vaddq_f32(vaddq_f32(sum0, sum1), vaddq_f32(sum2, sum3))); +} + +} // namespace diff --git a/src/VecSim/spaces/L2/L2_NEON_SQ4_SQ4.h b/src/VecSim/spaces/L2/L2_NEON_SQ4_SQ4.h new file mode 100644 index 000000000..72c541fda --- /dev/null +++ b/src/VecSim/spaces/L2/L2_NEON_SQ4_SQ4.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once +#include "VecSim/spaces/space_includes.h" +// SQ4_SQ4_InnerProductSIMD16_NEON_IMP +#include "VecSim/spaces/IP/IP_NEON_SQ4_SQ4.h" +#include "VecSim/types/sq4.h" +#include "VecSim/utils/alignment.h" +#include + +namespace { + +/* + * Symmetric SQ4-SQ4 L2 squared distance by the stored-sum identity, the same one SQ8-SQ8 uses: + * + * ||x - y||^2 = ||x||^2 + ||y||^2 - 2 * IP(x, y) + * + * where ||x||^2 and ||y||^2 are the stored SUM_SQUARES metadata and IP(x, y) comes from the + * integer code dot of the inner product kernel. Exact-dim bound and dispatch as the inner product + * kernel. + */ +template // 0..15 +float SQ4_SQ4_L2SqrSIMD16_NEON(const void *pVect1v, const void *pVect2v, size_t dimension) { + using vecsim_types::sq4; + const float ip = SQ4_SQ4_InnerProductSIMD16_NEON_IMP(pVect1v, pVect2v, dimension); + const auto *x = static_cast(pVect1v); + const auto *y = static_cast(pVect2v); + const size_t data_bytes = sq4::data_bytes_count(dimension); + const float sum_sq_x = load_unaligned(x + data_bytes + sq4::SUM_SQUARES * sizeof(float)); + const float sum_sq_y = load_unaligned(y + data_bytes + sq4::SUM_SQUARES * sizeof(float)); + return sum_sq_x + sum_sq_y - 2.0f * ip; +} + +} // namespace diff --git a/src/VecSim/spaces/L2/L2_SVE_SQ4_FP32.h b/src/VecSim/spaces/L2/L2_SVE_SQ4_FP32.h new file mode 100644 index 000000000..b20a26892 --- /dev/null +++ b/src/VecSim/spaces/L2/L2_SVE_SQ4_FP32.h @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once +#include "VecSim/spaces/space_includes.h" +#include "VecSim/spaces/IP/IP_SVE_SQ4_FP32.h" // SQ4_FP32_SVE_CoordinatesPerStep +#include "VecSim/types/sq4.h" +#include "VecSim/utils/alignment.h" +#include + +// SVE.cpp and SVE2.cpp both compile this header, under different -march flags. The +// anonymous namespace keeps each tier's bodies to itself; without it they are weak +// symbols that both objects define and link order picks the -march. Only the Choose_* +// entry points stay external. Dependencies above must stay outside the namespace. +namespace { + +/* + * Asymmetric SQ4-FP32 L2 squared distance via direct residual accumulation, as SQ8: + * + * ||x - y||² = Σ(delta * q_i + (min - y_i))² + * + * Keeping min - y first (one fused multiply-add per coordinate) rounds at the scale of the + * residual, not of min, when the data has a large common offset. Storage packs coordinate i into + * byte i / 2, the low nibble for even i and the high nibble for odd i, followed by unaligned FP32 + * metadata. + */ + +// Helper: accumulate Σ(diff_i²) for the 2 * svcntw() coordinates held in svcntw() packed bytes. +// The low nibbles are the even coordinates and the high nibbles the odd ones; a de-interleaving +// load splits the query the same way, so no lane reordering is needed. +static inline void L2StepSQ4_FP32_SVE(const uint8_t *x, const float *y, svfloat32_t &sum_even, + svfloat32_t &sum_odd, svfloat32_t min_val_vec, + svfloat32_t delta_vec) { + const svbool_t pg = svptrue_b32(); + const svuint32_t packed = svld1ub_u32(pg, x); + const svfloat32x2_t query = svld2_f32(pg, y); + const svfloat32_t diff_even = + svmla_f32_x(pg, svsub_f32_x(pg, min_val_vec, svget2_f32(query, 0)), delta_vec, + svcvt_f32_u32_x(pg, svand_n_u32_x(pg, packed, 15))); + const svfloat32_t diff_odd = + svmla_f32_x(pg, svsub_f32_x(pg, min_val_vec, svget2_f32(query, 1)), delta_vec, + svcvt_f32_u32_x(pg, svlsr_n_u32_x(pg, packed, 4))); + sum_even = svmla_f32_x(pg, sum_even, diff_even, diff_even); + sum_odd = svmla_f32_x(pg, sum_odd, diff_odd, diff_odd); +} + +// Four accumulators, full steps first and a predicated tail last, as SQ8. Every full step is an +// even number of coordinates, so every packed load starts at a whole byte. +template +float SQ4_FP32_L2SqrSIMD_SVE(const void *pVect1v, const void *pVect2v, size_t dimension) { + using vecsim_types::sq4; + const auto *x = static_cast(pVect1v); + const auto *y = static_cast(pVect2v); + const size_t vl = svcntw(); // packed bytes per step + const svbool_t pg = svptrue_b32(); + const auto *params = x + sq4::data_bytes_count(dimension); + const float min_val = load_unaligned(params + sq4::MIN_VAL * sizeof(float)); + const float delta = load_unaligned(params + sq4::DELTA * sizeof(float)); + const svfloat32_t min_val_vec = svdup_f32(min_val); + const svfloat32_t delta_vec = svdup_f32(delta); + svfloat32_t sum0 = svdup_f32(0.0f); + svfloat32_t sum1 = svdup_f32(0.0f); + svfloat32_t sum2 = svdup_f32(0.0f); + svfloat32_t sum3 = svdup_f32(0.0f); + size_t offset = 0; // in packed bytes; the step's first coordinate is 2 * offset + const size_t main_bytes = (dimension / (8 * vl)) * 4 * vl; + for (; offset < main_bytes; offset += 4 * vl) { + L2StepSQ4_FP32_SVE(x + offset, y + 2 * offset, sum0, sum1, min_val_vec, delta_vec); + L2StepSQ4_FP32_SVE(x + offset + vl, y + 2 * (offset + vl), sum2, sum3, min_val_vec, + delta_vec); + L2StepSQ4_FP32_SVE(x + offset + 2 * vl, y + 2 * (offset + 2 * vl), sum0, sum1, min_val_vec, + delta_vec); + L2StepSQ4_FP32_SVE(x + offset + 3 * vl, y + 2 * (offset + 3 * vl), sum2, sum3, min_val_vec, + delta_vec); + } + if constexpr (additional_steps > 0) { + L2StepSQ4_FP32_SVE(x + offset, y + 2 * offset, sum0, sum1, min_val_vec, delta_vec); + offset += vl; + } + if constexpr (additional_steps > 1) { + L2StepSQ4_FP32_SVE(x + offset, y + 2 * offset, sum2, sum3, min_val_vec, delta_vec); + offset += vl; + } + if constexpr (additional_steps > 2) { + L2StepSQ4_FP32_SVE(x + offset, y + 2 * offset, sum0, sum1, min_val_vec, delta_vec); + offset += vl; + } + if constexpr (partial_chunk) { + // As the IP tail: an odd tail's last query pair reads the first metadata float, which + // odd_pg drops. + const size_t remaining = dimension - 2 * offset; + const svbool_t even_pg = svwhilelt_b32(uint64_t(0), uint64_t((remaining + 1) / 2)); + const svbool_t odd_pg = svwhilelt_b32(uint64_t(0), uint64_t(remaining / 2)); + const svuint32_t packed = svld1ub_u32(even_pg, x + offset); + const svfloat32x2_t query = svld2_f32(even_pg, y + 2 * offset); + const svfloat32_t diff_even = + svmla_f32_x(pg, svsub_f32_x(pg, min_val_vec, svget2_f32(query, 0)), delta_vec, + svcvt_f32_u32_x(pg, svand_n_u32_x(pg, packed, 15))); + const svfloat32_t diff_odd = + svmla_f32_x(pg, svsub_f32_x(pg, min_val_vec, svget2_f32(query, 1)), delta_vec, + svcvt_f32_u32_x(pg, svlsr_n_u32_x(pg, packed, 4))); + // Merging (_m): lanes outside the tail keep the running sums. + sum3 = svmla_f32_m(even_pg, sum3, diff_even, diff_even); + sum2 = svmla_f32_m(odd_pg, sum2, diff_odd, diff_odd); + } + svfloat32_t sum = svadd_f32_x(pg, sum0, sum1); + sum = svadd_f32_x(pg, sum, sum2); + sum = svadd_f32_x(pg, sum, sum3); + return svaddv_f32(pg, sum); +} + +} // namespace diff --git a/src/VecSim/spaces/L2/L2_SVE_SQ4_SQ4.h b/src/VecSim/spaces/L2/L2_SVE_SQ4_SQ4.h new file mode 100644 index 000000000..1087b70d6 --- /dev/null +++ b/src/VecSim/spaces/L2/L2_SVE_SQ4_SQ4.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once +#include "VecSim/spaces/space_includes.h" +#include "VecSim/spaces/IP/IP_SVE_SQ4_SQ4.h" // SQ4_SQ4_InnerProductSIMD_SVE_IMP +#include "VecSim/types/sq4.h" +#include "VecSim/utils/alignment.h" +#include + +// SVE.cpp and SVE2.cpp both compile this header, under different -march flags. The +// anonymous namespace keeps each tier's bodies to itself; without it they are weak +// symbols that both objects define and link order picks the -march. Only the Choose_* +// entry points stay external. Dependencies above must stay outside the namespace. +namespace { + +/* + * Symmetric SQ4-SQ4 L2 squared distance by the stored-sum identity, the same one SQ8-SQ8 uses: + * + * ||x - y||^2 = ||x||^2 + ||y||^2 - 2 * IP(x, y) + * + * where ||x||^2 and ||y||^2 are the stored SUM_SQUARES metadata and IP(x, y) comes from the + * integer code dot of the inner product kernel. Exact-dim bound and dispatch as the inner product + * kernel. + */ +template +float SQ4_SQ4_L2SqrSIMD_SVE(const void *pVect1v, const void *pVect2v, size_t dimension) { + using vecsim_types::sq4; + const float ip = SQ4_SQ4_InnerProductSIMD_SVE_IMP( + pVect1v, pVect2v, dimension); + const auto *x = static_cast(pVect1v); + const auto *y = static_cast(pVect2v); + const size_t data_bytes = sq4::data_bytes_count(dimension); + const float sum_sq_x = load_unaligned(x + data_bytes + sq4::SUM_SQUARES * sizeof(float)); + const float sum_sq_y = load_unaligned(y + data_bytes + sq4::SUM_SQUARES * sizeof(float)); + return sum_sq_x + sum_sq_y - 2.0f * ip; +} + +} // namespace diff --git a/src/VecSim/spaces/L2_space.cpp b/src/VecSim/spaces/L2_space.cpp index 63e2c2d60..4b2e5b12b 100644 --- a/src/VecSim/spaces/L2_space.cpp +++ b/src/VecSim/spaces/L2_space.cpp @@ -39,22 +39,101 @@ using float16 = vecsim_types::float16; namespace spaces { -// SQ4-FP32: packed storage and unaligned metadata, so no alignment requirement. +// SQ4-FP32: packed storage and unaligned metadata, so no alignment requirement on any tier. dist_func_t L2_SQ4_FP32_GetDistFunc(size_t dim, unsigned char *alignment, const void *arch_opt) { if (alignment) { *alignment = 0; } - return SQ4_FP32_L2Sqr; + dist_func_t ret_dist_func = SQ4_FP32_L2Sqr; + [[maybe_unused]] auto features = getCpuOptimizationFeatures(arch_opt); +#ifdef CPU_FEATURES_ARCH_AARCH64 + // The kernels handle any dim: tails read only the codes and the query's floats plus metadata. +#ifdef OPT_SVE2 + if (features.sve2) { + return Choose_SQ4_FP32_L2_implementation_SVE2(dim); + } +#endif +#ifdef OPT_SVE + if (features.sve) { + return Choose_SQ4_FP32_L2_implementation_SVE(dim); + } +#endif +#ifdef OPT_NEON + if (features.asimd) { + return Choose_SQ4_FP32_L2_implementation_NEON(dim); + } +#endif +#endif +#ifdef CPU_FEATURES_ARCH_X86_64 + // As SQ8: below eight coordinates scalar is at least as fast. + if (dim < 8) { + return ret_dist_func; + } +#ifdef OPT_AVX512_F_BW_VL_VNNI + if (features.avx512f && features.avx512bw && features.avx512vl && features.avx512vnni) { + return Choose_SQ4_FP32_L2_implementation_AVX512F_BW_VL_VNNI(dim); + } +#endif +#ifdef OPT_AVX2_FMA + if (features.avx2 && features.fma3) { + return Choose_SQ4_FP32_L2_implementation_AVX2_FMA(dim); + } +#endif +#endif + return ret_dist_func; } -// SQ4-SQ4: packed storage and unaligned metadata, so no alignment requirement. +// SQ4-SQ4 by the stored-sum identity, like SQ8-SQ8. The kernels share the inner product's integer +// code dot, so the tiers, dispatch minimums and exact-dim bound are those of +// IP_SQ4_SQ4_GetDistFunc. No alignment requirement on any tier. dist_func_t L2_SQ4_SQ4_GetDistFunc(size_t dim, unsigned char *alignment, const void *arch_opt) { if (alignment) { *alignment = 0; } - return SQ4_SQ4_L2Sqr; + dist_func_t ret_dist_func = SQ4_SQ4_L2Sqr; + // Above this dimension the SIMD kernels' uint32 code dot could wrap. See spaces.h. + if (dim > spaces::SQ4_MAX_EXACT_SIMD_DIM) { + return ret_dist_func; + } + [[maybe_unused]] auto features = getCpuOptimizationFeatures(arch_opt); +#ifdef CPU_FEATURES_ARCH_AARCH64 +#ifdef OPT_SVE2 + if (features.sve2) { + return Choose_SQ4_SQ4_L2_implementation_SVE2(dim); + } +#endif +#ifdef OPT_SVE + if (features.sve) { + return Choose_SQ4_SQ4_L2_implementation_SVE(dim); + } +#endif +#ifdef OPT_NEON_DOTPROD + if (features.asimddp && dim >= 16) { + return Choose_SQ4_SQ4_L2_implementation_NEON_DOTPROD(dim); + } +#endif +#ifdef OPT_NEON + if (features.asimd && dim >= 16) { + return Choose_SQ4_SQ4_L2_implementation_NEON(dim); + } +#endif +#endif +#ifdef CPU_FEATURES_ARCH_X86_64 +#ifdef OPT_AVX512_F_BW_VL_VNNI + if (features.avx512f && features.avx512bw && features.avx512vl && features.avx512vnni && + dim >= 64) { + return Choose_SQ4_SQ4_L2_implementation_AVX512F_BW_VL_VNNI(dim); + } +#endif +#ifdef OPT_AVX2 + if (features.avx2 && dim >= 64) { + return Choose_SQ4_SQ4_L2_implementation_AVX2(dim); + } +#endif +#endif + return ret_dist_func; } // SQ8-FP32: asymmetric L2 distance between SQ8 storage and FP32 query diff --git a/src/VecSim/spaces/functions/AVX2.cpp b/src/VecSim/spaces/functions/AVX2.cpp index 1a9c41b6f..9101b7a5e 100644 --- a/src/VecSim/spaces/functions/AVX2.cpp +++ b/src/VecSim/spaces/functions/AVX2.cpp @@ -13,6 +13,9 @@ #include "VecSim/spaces/IP/IP_AVX2_SQ8_FP32.h" #include "VecSim/spaces/L2/L2_AVX2_SQ8_FP32.h" +#include "VecSim/spaces/IP/IP_AVX2_SQ4_SQ4.h" +#include "VecSim/spaces/L2/L2_AVX2_SQ4_SQ4.h" + namespace spaces { #include "implementation_chooser.h" @@ -47,6 +50,18 @@ dist_func_t Choose_SQ8_FP32_L2_implementation_AVX2(size_t dim) { return ret_dist_func; } +dist_func_t Choose_SQ4_SQ4_IP_implementation_AVX2(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_IMPLEMENTATION(ret_dist_func, dim, 64, SQ4_SQ4_InnerProductSIMD64_AVX2); + return ret_dist_func; +} + +dist_func_t Choose_SQ4_SQ4_L2_implementation_AVX2(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_IMPLEMENTATION(ret_dist_func, dim, 64, SQ4_SQ4_L2SqrSIMD64_AVX2); + return ret_dist_func; +} + #include "implementation_chooser_cleanup.h" } // namespace spaces diff --git a/src/VecSim/spaces/functions/AVX2.h b/src/VecSim/spaces/functions/AVX2.h index 081c42a4e..b0ee5b224 100644 --- a/src/VecSim/spaces/functions/AVX2.h +++ b/src/VecSim/spaces/functions/AVX2.h @@ -19,4 +19,7 @@ dist_func_t Choose_SQ8_FP32_L2_implementation_AVX2(size_t dim); dist_func_t Choose_BF16_IP_implementation_AVX2(size_t dim); dist_func_t Choose_BF16_L2_implementation_AVX2(size_t dim); +dist_func_t Choose_SQ4_SQ4_IP_implementation_AVX2(size_t dim); +dist_func_t Choose_SQ4_SQ4_L2_implementation_AVX2(size_t dim); + } // namespace spaces diff --git a/src/VecSim/spaces/functions/AVX2_FMA.cpp b/src/VecSim/spaces/functions/AVX2_FMA.cpp index 0eaacd070..d8ea8869a 100644 --- a/src/VecSim/spaces/functions/AVX2_FMA.cpp +++ b/src/VecSim/spaces/functions/AVX2_FMA.cpp @@ -9,6 +9,8 @@ #include "AVX2_FMA.h" #include "VecSim/spaces/L2/L2_AVX2_FMA_SQ8_FP32.h" #include "VecSim/spaces/IP/IP_AVX2_FMA_SQ8_FP32.h" +#include "VecSim/spaces/IP/IP_AVX2_FMA_SQ4_FP32.h" +#include "VecSim/spaces/L2/L2_AVX2_FMA_SQ4_FP32.h" namespace spaces { @@ -31,6 +33,18 @@ dist_func_t Choose_SQ8_FP32_L2_implementation_AVX2_FMA(size_t dim) { return ret_dist_func; } +dist_func_t Choose_SQ4_FP32_IP_implementation_AVX2_FMA(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_IMPLEMENTATION(ret_dist_func, dim, 32, SQ4_FP32_InnerProductSIMD32_AVX2_FMA); + return ret_dist_func; +} + +dist_func_t Choose_SQ4_FP32_L2_implementation_AVX2_FMA(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_IMPLEMENTATION(ret_dist_func, dim, 32, SQ4_FP32_L2SqrSIMD32_AVX2_FMA); + return ret_dist_func; +} + #include "implementation_chooser_cleanup.h" } // namespace spaces diff --git a/src/VecSim/spaces/functions/AVX2_FMA.h b/src/VecSim/spaces/functions/AVX2_FMA.h index b20b1a588..eb97b6114 100644 --- a/src/VecSim/spaces/functions/AVX2_FMA.h +++ b/src/VecSim/spaces/functions/AVX2_FMA.h @@ -16,4 +16,8 @@ dist_func_t Choose_SQ8_FP32_IP_implementation_AVX2_FMA(size_t dim); dist_func_t Choose_SQ8_FP32_Cosine_implementation_AVX2_FMA(size_t dim); dist_func_t Choose_SQ8_FP32_L2_implementation_AVX2_FMA(size_t dim); +// SQ4 storage with an FP32 query +dist_func_t Choose_SQ4_FP32_IP_implementation_AVX2_FMA(size_t dim); +dist_func_t Choose_SQ4_FP32_L2_implementation_AVX2_FMA(size_t dim); + } // namespace spaces diff --git a/src/VecSim/spaces/functions/AVX512F_BW_VL_VNNI.cpp b/src/VecSim/spaces/functions/AVX512F_BW_VL_VNNI.cpp index 97da55546..75c5e423e 100644 --- a/src/VecSim/spaces/functions/AVX512F_BW_VL_VNNI.cpp +++ b/src/VecSim/spaces/functions/AVX512F_BW_VL_VNNI.cpp @@ -20,6 +20,12 @@ #include "VecSim/spaces/IP/IP_AVX512F_BW_VL_VNNI_SQ8_SQ8.h" #include "VecSim/spaces/L2/L2_AVX512F_BW_VL_VNNI_SQ8_SQ8.h" +#include "VecSim/spaces/IP/IP_AVX512F_BW_VL_VNNI_SQ4_FP32.h" +#include "VecSim/spaces/L2/L2_AVX512F_BW_VL_VNNI_SQ4_FP32.h" + +#include "VecSim/spaces/IP/IP_AVX512F_BW_VL_VNNI_SQ4_SQ4.h" +#include "VecSim/spaces/L2/L2_AVX512F_BW_VL_VNNI_SQ4_SQ4.h" + namespace spaces { #include "implementation_chooser.h" @@ -75,6 +81,27 @@ dist_func_t Choose_SQ8_FP32_L2_implementation_AVX512F_BW_VL_VNNI(size_t d CHOOSE_IMPLEMENTATION(ret_dist_func, dim, 32, SQ8_FP32_L2SqrSIMD16_AVX512F_BW_VL_VNNI); return ret_dist_func; } + +dist_func_t Choose_SQ4_FP32_IP_implementation_AVX512F_BW_VL_VNNI(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_IMPLEMENTATION(ret_dist_func, dim, 32, SQ4_FP32_InnerProductSIMD32_AVX512F_BW_VL_VNNI); + return ret_dist_func; +} +dist_func_t Choose_SQ4_FP32_L2_implementation_AVX512F_BW_VL_VNNI(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_IMPLEMENTATION(ret_dist_func, dim, 32, SQ4_FP32_L2SqrSIMD32_AVX512F_BW_VL_VNNI); + return ret_dist_func; +} +dist_func_t Choose_SQ4_SQ4_IP_implementation_AVX512F_BW_VL_VNNI(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_IMPLEMENTATION(ret_dist_func, dim, 64, SQ4_SQ4_InnerProductSIMD64_AVX512F_BW_VL_VNNI); + return ret_dist_func; +} +dist_func_t Choose_SQ4_SQ4_L2_implementation_AVX512F_BW_VL_VNNI(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_IMPLEMENTATION(ret_dist_func, dim, 64, SQ4_SQ4_L2SqrSIMD64_AVX512F_BW_VL_VNNI); + return ret_dist_func; +} // SQ8-to-SQ8 distance functions (both vectors are uint8 quantized with precomputed sum) dist_func_t Choose_SQ8_SQ8_IP_implementation_AVX512F_BW_VL_VNNI(size_t dim) { dist_func_t ret_dist_func; diff --git a/src/VecSim/spaces/functions/AVX512F_BW_VL_VNNI.h b/src/VecSim/spaces/functions/AVX512F_BW_VL_VNNI.h index fe1583491..f0022cee3 100644 --- a/src/VecSim/spaces/functions/AVX512F_BW_VL_VNNI.h +++ b/src/VecSim/spaces/functions/AVX512F_BW_VL_VNNI.h @@ -24,6 +24,15 @@ dist_func_t Choose_SQ8_FP32_IP_implementation_AVX512F_BW_VL_VNNI(size_t d dist_func_t Choose_SQ8_FP32_Cosine_implementation_AVX512F_BW_VL_VNNI(size_t dim); dist_func_t Choose_SQ8_FP32_L2_implementation_AVX512F_BW_VL_VNNI(size_t dim); +// SQ4 storage with an FP32 query +dist_func_t Choose_SQ4_FP32_IP_implementation_AVX512F_BW_VL_VNNI(size_t dim); +dist_func_t Choose_SQ4_FP32_L2_implementation_AVX512F_BW_VL_VNNI(size_t dim); + +// SQ4-to-SQ4 distance functions (both vectors are SQ4 stored blobs) +dist_func_t Choose_SQ4_SQ4_IP_implementation_AVX512F_BW_VL_VNNI(size_t dim); +// L2 by the stored-sum identity (see L2_SQ4_SQ4_GetDistFunc) +dist_func_t Choose_SQ4_SQ4_L2_implementation_AVX512F_BW_VL_VNNI(size_t dim); + // SQ8-to-SQ8 distance functions (both vectors are uint8 quantized with precomputed sum) dist_func_t Choose_SQ8_SQ8_IP_implementation_AVX512F_BW_VL_VNNI(size_t dim); dist_func_t Choose_SQ8_SQ8_Cosine_implementation_AVX512F_BW_VL_VNNI(size_t dim); diff --git a/src/VecSim/spaces/functions/NEON.cpp b/src/VecSim/spaces/functions/NEON.cpp index 0c9a286e3..616c7c5d6 100644 --- a/src/VecSim/spaces/functions/NEON.cpp +++ b/src/VecSim/spaces/functions/NEON.cpp @@ -19,6 +19,10 @@ #include "VecSim/spaces/IP/IP_NEON_SQ8_FP32.h" #include "VecSim/spaces/IP/IP_NEON_SQ8_SQ8.h" #include "VecSim/spaces/L2/L2_NEON_SQ8_SQ8.h" +#include "VecSim/spaces/IP/IP_NEON_SQ4_FP32.h" +#include "VecSim/spaces/L2/L2_NEON_SQ4_FP32.h" +#include "VecSim/spaces/IP/IP_NEON_SQ4_SQ4.h" +#include "VecSim/spaces/L2/L2_NEON_SQ4_SQ4.h" namespace spaces { @@ -101,6 +105,30 @@ dist_func_t Choose_SQ8_FP32_Cosine_implementation_NEON(size_t dim) { return ret_dist_func; } +dist_func_t Choose_SQ4_FP32_IP_implementation_NEON(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_IMPLEMENTATION(ret_dist_func, dim, 16, SQ4_FP32_InnerProductSIMD16_NEON); + return ret_dist_func; +} + +dist_func_t Choose_SQ4_FP32_L2_implementation_NEON(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_IMPLEMENTATION(ret_dist_func, dim, 16, SQ4_FP32_L2SqrSIMD16_NEON); + return ret_dist_func; +} + +dist_func_t Choose_SQ4_SQ4_IP_implementation_NEON(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_IMPLEMENTATION(ret_dist_func, dim, 16, SQ4_SQ4_InnerProductSIMD16_NEON); + return ret_dist_func; +} + +dist_func_t Choose_SQ4_SQ4_L2_implementation_NEON(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_IMPLEMENTATION(ret_dist_func, dim, 16, SQ4_SQ4_L2SqrSIMD16_NEON); + return ret_dist_func; +} + // SQ8-to-SQ8 distance functions (both vectors are uint8 quantized with precomputed sum) // Uses 64-element chunking to leverage efficient UINT8_InnerProductImp dist_func_t Choose_SQ8_SQ8_IP_implementation_NEON(size_t dim) { diff --git a/src/VecSim/spaces/functions/NEON.h b/src/VecSim/spaces/functions/NEON.h index 08060b402..62d151715 100644 --- a/src/VecSim/spaces/functions/NEON.h +++ b/src/VecSim/spaces/functions/NEON.h @@ -30,6 +30,15 @@ dist_func_t Choose_SQ8_FP32_L2_implementation_NEON(size_t dim); dist_func_t Choose_SQ8_FP32_IP_implementation_NEON(size_t dim); dist_func_t Choose_SQ8_FP32_Cosine_implementation_NEON(size_t dim); +// SQ4 storage with an FP32 query +dist_func_t Choose_SQ4_FP32_IP_implementation_NEON(size_t dim); +dist_func_t Choose_SQ4_FP32_L2_implementation_NEON(size_t dim); + +// SQ4-to-SQ4 distance functions (both vectors are SQ4 quantized with precomputed sum) +dist_func_t Choose_SQ4_SQ4_IP_implementation_NEON(size_t dim); +// L2 by the stored-sum identity (see L2_SQ4_SQ4_GetDistFunc) +dist_func_t Choose_SQ4_SQ4_L2_implementation_NEON(size_t dim); + // SQ8-to-SQ8 distance functions (both vectors are uint8 quantized with precomputed sum) dist_func_t Choose_SQ8_SQ8_IP_implementation_NEON(size_t dim); dist_func_t Choose_SQ8_SQ8_Cosine_implementation_NEON(size_t dim); diff --git a/src/VecSim/spaces/functions/NEON_DOTPROD.cpp b/src/VecSim/spaces/functions/NEON_DOTPROD.cpp index 12f762093..9c7f52a9c 100644 --- a/src/VecSim/spaces/functions/NEON_DOTPROD.cpp +++ b/src/VecSim/spaces/functions/NEON_DOTPROD.cpp @@ -10,9 +10,11 @@ #include "VecSim/spaces/IP/IP_NEON_DOTPROD_INT8.h" #include "VecSim/spaces/IP/IP_NEON_DOTPROD_UINT8.h" #include "VecSim/spaces/IP/IP_NEON_DOTPROD_SQ8_SQ8.h" +#include "VecSim/spaces/IP/IP_NEON_DOTPROD_SQ4_SQ4.h" #include "VecSim/spaces/L2/L2_NEON_DOTPROD_INT8.h" #include "VecSim/spaces/L2/L2_NEON_DOTPROD_UINT8.h" #include "VecSim/spaces/L2/L2_NEON_DOTPROD_SQ8_SQ8.h" +#include "VecSim/spaces/L2/L2_NEON_DOTPROD_SQ4_SQ4.h" namespace spaces { @@ -73,6 +75,18 @@ dist_func_t Choose_SQ8_SQ8_L2_implementation_NEON_DOTPROD(size_t dim) { return ret_dist_func; } +dist_func_t Choose_SQ4_SQ4_IP_implementation_NEON_DOTPROD(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_IMPLEMENTATION(ret_dist_func, dim, 32, SQ4_SQ4_InnerProductSIMD32_NEON_DOTPROD); + return ret_dist_func; +} + +dist_func_t Choose_SQ4_SQ4_L2_implementation_NEON_DOTPROD(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_IMPLEMENTATION(ret_dist_func, dim, 32, SQ4_SQ4_L2SqrSIMD32_NEON_DOTPROD); + return ret_dist_func; +} + #include "implementation_chooser_cleanup.h" } // namespace spaces diff --git a/src/VecSim/spaces/functions/NEON_DOTPROD.h b/src/VecSim/spaces/functions/NEON_DOTPROD.h index 0fda479bc..62bcebba7 100644 --- a/src/VecSim/spaces/functions/NEON_DOTPROD.h +++ b/src/VecSim/spaces/functions/NEON_DOTPROD.h @@ -26,4 +26,8 @@ dist_func_t Choose_SQ8_SQ8_IP_implementation_NEON_DOTPROD(size_t dim); dist_func_t Choose_SQ8_SQ8_Cosine_implementation_NEON_DOTPROD(size_t dim); dist_func_t Choose_SQ8_SQ8_L2_implementation_NEON_DOTPROD(size_t dim); +// SQ4-to-SQ4 inner product, and L2 by the stored-sum identity (see L2_SQ4_SQ4_GetDistFunc) +dist_func_t Choose_SQ4_SQ4_IP_implementation_NEON_DOTPROD(size_t dim); +dist_func_t Choose_SQ4_SQ4_L2_implementation_NEON_DOTPROD(size_t dim); + } // namespace spaces diff --git a/src/VecSim/spaces/functions/SVE.cpp b/src/VecSim/spaces/functions/SVE.cpp index bd197c84c..a1adc9aea 100644 --- a/src/VecSim/spaces/functions/SVE.cpp +++ b/src/VecSim/spaces/functions/SVE.cpp @@ -31,6 +31,11 @@ #include "VecSim/spaces/IP/IP_SVE_SQ8_SQ8.h" #include "VecSim/spaces/L2/L2_SVE_SQ8_SQ8.h" +#include "VecSim/spaces/IP/IP_SVE_SQ4_FP32.h" +#include "VecSim/spaces/L2/L2_SVE_SQ4_FP32.h" +#include "VecSim/spaces/IP/IP_SVE_SQ4_SQ4.h" +#include "VecSim/spaces/L2/L2_SVE_SQ4_SQ4.h" + namespace spaces { #include "implementation_chooser.h" @@ -122,6 +127,34 @@ dist_func_t Choose_SQ8_FP32_L2_implementation_SVE(size_t dim) { return ret_dist_func; } +dist_func_t Choose_SQ4_FP32_IP_implementation_SVE(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_SVE_IMPLEMENTATION(ret_dist_func, SQ4_FP32_InnerProductSIMD_SVE, dim, + SQ4_FP32_SVE_CoordinatesPerStep); + return ret_dist_func; +} + +dist_func_t Choose_SQ4_FP32_L2_implementation_SVE(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_SVE_IMPLEMENTATION(ret_dist_func, SQ4_FP32_L2SqrSIMD_SVE, dim, + SQ4_FP32_SVE_CoordinatesPerStep); + return ret_dist_func; +} + +dist_func_t Choose_SQ4_SQ4_IP_implementation_SVE(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_SVE_IMPLEMENTATION(ret_dist_func, SQ4_SQ4_InnerProductSIMD_SVE, dim, + SQ4_SQ4_SVE_CoordinatesPerVector); + return ret_dist_func; +} + +dist_func_t Choose_SQ4_SQ4_L2_implementation_SVE(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_SVE_IMPLEMENTATION(ret_dist_func, SQ4_SQ4_L2SqrSIMD_SVE, dim, + SQ4_SQ4_SVE_CoordinatesPerVector); + return ret_dist_func; +} + dist_func_t Choose_SQ8_FP16_IP_implementation_SVE(size_t dim) { dist_func_t ret_dist_func; CHOOSE_SVE_IMPLEMENTATION(ret_dist_func, SQ8_FP16_InnerProductSIMD_SVE, dim, svcntw); diff --git a/src/VecSim/spaces/functions/SVE.h b/src/VecSim/spaces/functions/SVE.h index 43b3b22cd..1c5c37eae 100644 --- a/src/VecSim/spaces/functions/SVE.h +++ b/src/VecSim/spaces/functions/SVE.h @@ -33,6 +33,15 @@ dist_func_t Choose_SQ8_FP32_IP_implementation_SVE(size_t dim); dist_func_t Choose_SQ8_FP32_Cosine_implementation_SVE(size_t dim); dist_func_t Choose_SQ8_FP32_L2_implementation_SVE(size_t dim); +// SQ4 storage with an FP32 query +dist_func_t Choose_SQ4_FP32_IP_implementation_SVE(size_t dim); +dist_func_t Choose_SQ4_FP32_L2_implementation_SVE(size_t dim); + +// SQ4-to-SQ4 distance functions (both vectors are SQ4 quantized with precomputed sum) +dist_func_t Choose_SQ4_SQ4_IP_implementation_SVE(size_t dim); +// L2 by the stored-sum identity (see L2_SQ4_SQ4_GetDistFunc) +dist_func_t Choose_SQ4_SQ4_L2_implementation_SVE(size_t dim); + dist_func_t Choose_SQ8_FP16_IP_implementation_SVE(size_t dim); dist_func_t Choose_SQ8_FP16_Cosine_implementation_SVE(size_t dim); dist_func_t Choose_SQ8_FP16_L2_implementation_SVE(size_t dim); diff --git a/src/VecSim/spaces/functions/SVE2.cpp b/src/VecSim/spaces/functions/SVE2.cpp index 9eea81523..a13d40c81 100644 --- a/src/VecSim/spaces/functions/SVE2.cpp +++ b/src/VecSim/spaces/functions/SVE2.cpp @@ -26,6 +26,10 @@ #include "VecSim/spaces/L2/L2_SVE2_SQ8_FP16.h" // SVE2 fast path: FMLALB/FMLALT widening #include "VecSim/spaces/IP/IP_SVE_SQ8_SQ8.h" // SVE2 implementation is identical to SVE #include "VecSim/spaces/L2/L2_SVE_SQ8_SQ8.h" // SVE2 implementation is identical to SVE +#include "VecSim/spaces/IP/IP_SVE_SQ4_FP32.h" // SVE2 implementation is identical to SVE +#include "VecSim/spaces/L2/L2_SVE_SQ4_FP32.h" // SVE2 implementation is identical to SVE +#include "VecSim/spaces/IP/IP_SVE_SQ4_SQ4.h" // SVE2 implementation is identical to SVE +#include "VecSim/spaces/L2/L2_SVE_SQ4_SQ4.h" // SVE2 implementation is identical to SVE namespace spaces { @@ -118,6 +122,34 @@ dist_func_t Choose_SQ8_FP32_L2_implementation_SVE2(size_t dim) { return ret_dist_func; } +dist_func_t Choose_SQ4_FP32_IP_implementation_SVE2(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_SVE_IMPLEMENTATION(ret_dist_func, SQ4_FP32_InnerProductSIMD_SVE, dim, + SQ4_FP32_SVE_CoordinatesPerStep); + return ret_dist_func; +} + +dist_func_t Choose_SQ4_FP32_L2_implementation_SVE2(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_SVE_IMPLEMENTATION(ret_dist_func, SQ4_FP32_L2SqrSIMD_SVE, dim, + SQ4_FP32_SVE_CoordinatesPerStep); + return ret_dist_func; +} + +dist_func_t Choose_SQ4_SQ4_IP_implementation_SVE2(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_SVE_IMPLEMENTATION(ret_dist_func, SQ4_SQ4_InnerProductSIMD_SVE, dim, + SQ4_SQ4_SVE_CoordinatesPerVector); + return ret_dist_func; +} + +dist_func_t Choose_SQ4_SQ4_L2_implementation_SVE2(size_t dim) { + dist_func_t ret_dist_func; + CHOOSE_SVE_IMPLEMENTATION(ret_dist_func, SQ4_SQ4_L2SqrSIMD_SVE, dim, + SQ4_SQ4_SVE_CoordinatesPerVector); + return ret_dist_func; +} + dist_func_t Choose_SQ8_FP16_IP_implementation_SVE2(size_t dim) { dist_func_t ret_dist_func; CHOOSE_SVE_IMPLEMENTATION(ret_dist_func, SQ8_FP16_InnerProductSIMD_SVE2, dim, svcnth); diff --git a/src/VecSim/spaces/functions/SVE2.h b/src/VecSim/spaces/functions/SVE2.h index 2c1bfbac3..d5e81e70e 100644 --- a/src/VecSim/spaces/functions/SVE2.h +++ b/src/VecSim/spaces/functions/SVE2.h @@ -33,6 +33,15 @@ dist_func_t Choose_SQ8_FP32_IP_implementation_SVE2(size_t dim); dist_func_t Choose_SQ8_FP32_Cosine_implementation_SVE2(size_t dim); dist_func_t Choose_SQ8_FP32_L2_implementation_SVE2(size_t dim); +// SQ4 storage with an FP32 query +dist_func_t Choose_SQ4_FP32_IP_implementation_SVE2(size_t dim); +dist_func_t Choose_SQ4_FP32_L2_implementation_SVE2(size_t dim); + +// SQ4-to-SQ4 distance functions (both vectors are SQ4 quantized with precomputed sum) +dist_func_t Choose_SQ4_SQ4_IP_implementation_SVE2(size_t dim); +// L2 by the stored-sum identity (see L2_SQ4_SQ4_GetDistFunc) +dist_func_t Choose_SQ4_SQ4_L2_implementation_SVE2(size_t dim); + dist_func_t Choose_SQ8_FP16_IP_implementation_SVE2(size_t dim); dist_func_t Choose_SQ8_FP16_Cosine_implementation_SVE2(size_t dim); dist_func_t Choose_SQ8_FP16_L2_implementation_SVE2(size_t dim); diff --git a/src/VecSim/spaces/quantized_distance_helpers.h b/src/VecSim/spaces/quantized_distance_helpers.h new file mode 100644 index 000000000..dddaf0ceb --- /dev/null +++ b/src/VecSim/spaces/quantized_distance_helpers.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#pragma once + +#include +#include +#include "VecSim/utils/alignment.h" + +namespace spaces { +namespace quantized { + +// Complete the symmetric stored-stored inner product from the integer code dot and stored sums. +// This ISA-neutral helper is shared by scalar and SIMD kernels. Internal linkage keeps each +// translation unit's body under its own ISA flags instead of merging target-specific definitions. +// The expression's operation order is part of the numerical contract: do not reassociate it or +// compile with -ffast-math / -Ofast. +template +static inline float Stored_InnerProduct_FromCodeDot(const uint8_t *a, const uint8_t *b, size_t dim, + float code_dot) { + // Metadata follows byte payloads and is not necessarily float-aligned. + const auto *params1 = a + StorageType::data_bytes_count(dim); + const float min_val1 = load_unaligned(params1 + StorageType::MIN_VAL * sizeof(float)); + const float delta1 = load_unaligned(params1 + StorageType::DELTA * sizeof(float)); + const float sum1 = load_unaligned(params1 + StorageType::SUM * sizeof(float)); + const auto *params2 = b + StorageType::data_bytes_count(dim); + const float min_val2 = load_unaligned(params2 + StorageType::MIN_VAL * sizeof(float)); + const float delta2 = load_unaligned(params2 + StorageType::DELTA * sizeof(float)); + const float sum2 = load_unaligned(params2 + StorageType::SUM * sizeof(float)); + + return min_val1 * sum2 + min_val2 * sum1 - static_cast(dim) * min_val1 * min_val2 + + delta1 * delta2 * code_dot; +} + +} // namespace quantized +} // namespace spaces diff --git a/src/VecSim/spaces/quantized_kernels.h b/src/VecSim/spaces/quantized_kernels.h index 26246f40c..245a8fa47 100644 --- a/src/VecSim/spaces/quantized_kernels.h +++ b/src/VecSim/spaces/quantized_kernels.h @@ -11,6 +11,7 @@ #include #include #include "VecSim/utils/alignment.h" +#include "VecSim/spaces/quantized_distance_helpers.h" // SIMD translation units (functions/*.cpp) must not include this header; they call the exported // scalar functions (e.g. SQ8_FP32_L2Sqr) instead. @@ -101,22 +102,7 @@ static inline float Stored_InnerProduct_Impl(const void *a, const void *b, size_ // Compute inner product of quantized values: sum(q1[i]*q2[i]) const float product = StorageType::code_dot(pVect1, pVect2, dim); - // Metadata follows byte payloads and is not necessarily float-aligned. - const auto *params1 = pVect1 + StorageType::data_bytes_count(dim); - const float min_val1 = load_unaligned(params1 + StorageType::MIN_VAL * sizeof(float)); - const float delta1 = load_unaligned(params1 + StorageType::DELTA * sizeof(float)); - const float sum1 = load_unaligned(params1 + StorageType::SUM * sizeof(float)); - - // Get quantization parameters from pVect2 - const auto *params2 = pVect2 + StorageType::data_bytes_count(dim); - const float min_val2 = load_unaligned(params2 + StorageType::MIN_VAL * sizeof(float)); - const float delta2 = load_unaligned(params2 + StorageType::DELTA * sizeof(float)); - const float sum2 = load_unaligned(params2 + StorageType::SUM * sizeof(float)); - - // Apply the algebraic formula using precomputed sums: - // IP = min1*sum2 + min2*sum1 + delta1*delta2*sum(q1[i]*q2[i]) - dim*min1*min2 - return min_val1 * sum2 + min_val2 * sum1 - static_cast(dim) * min_val1 * min_val2 + - delta1 * delta2 * product; + return Stored_InnerProduct_FromCodeDot(pVect1, pVect2, dim, product); } /* diff --git a/src/VecSim/spaces/spaces.h b/src/VecSim/spaces/spaces.h index f6de7823e..2ab04116c 100644 --- a/src/VecSim/spaces/spaces.h +++ b/src/VecSim/spaces/spaces.h @@ -65,6 +65,17 @@ static constexpr size_t UINT8_MAX_EXACT_SIMD_DIM = std::numeric_limits::max() / (std::numeric_limits::max() * std::numeric_limits::max()); +// The SQ4-SQ4 inner product kernels accumulate the integer code dot sum(q1 * q2), each product at +// most 15 * 15 = 225, in unsigned 32-bit lanes (vpadalq_u16 / vdotq_u32 / svdot_u32), and NEON +// reduces those lanes with vaddvq_u32, whose result is also a uint32. The narrowest accumulator is +// therefore a uint32 holding the whole total, so the kernels are exact while 225 * dim fits +// UINT32_MAX: 225 * 19,088,743 is 4,294,967,175, and one dimension more wraps. Above it the chooser +// hands back the scalar kernel, which cannot wrap. The x86 AVX512F_BW_VL_VNNI kernel accumulates +// with vpdpbusd into signed int32 lanes, but each lane holds only a small share of the total (at +// most about 268 million at this bound). The lanes are reduced with 32-bit SIMD additions to a +// uint32 total, so the same whole-total bound keeps that reduction exact. +static constexpr size_t SQ4_MAX_EXACT_SIMD_DIM = std::numeric_limits::max() / (15 * 15); + // Native-fp16 accumulation is a throughput optimization and may overflow for sufficiently large // values at any dimension. These limits are conservative dispatch guardrails, not an input-range // contract or a general overflow guarantee. They retain the native path at ordinary embedding diff --git a/tests/benchmark/CMakeLists.txt b/tests/benchmark/CMakeLists.txt index 2cf536d91..75e3bb50d 100644 --- a/tests/benchmark/CMakeLists.txt +++ b/tests/benchmark/CMakeLists.txt @@ -39,7 +39,7 @@ endif() # Spaces benchmarks # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -set(DATA_TYPE fp32 fp64 bf16 fp16 int8 uint8 sq8_fp32 sq8_fp16 sq8_sq8) +set(DATA_TYPE fp32 fp64 bf16 fp16 int8 uint8 sq8_fp32 sq8_fp16 sq8_sq8 sq4_fp32 sq4_sq4) foreach(data_type IN LISTS DATA_TYPE) add_executable(bm_spaces_${data_type} spaces_benchmarks/bm_spaces_${data_type}.cpp) target_link_libraries(bm_spaces_${data_type} VectorSimilarity benchmark::benchmark) diff --git a/tests/benchmark/benchmarks.sh b/tests/benchmark/benchmarks.sh index e6ba13f85..2298a9e84 100755 --- a/tests/benchmark/benchmarks.sh +++ b/tests/benchmark/benchmarks.sh @@ -25,6 +25,8 @@ if [ -z "$BM_TYPE" ] || [ "$BM_TYPE" = "benchmarks-all" ]; then echo spaces_sq8_fp32 echo spaces_sq8_fp16 echo spaces_sq8_sq8 + echo spaces_sq4_fp32 + echo spaces_sq4_sq4 elif [ "$BM_TYPE" = "benchmarks-default" ]; then echo basics_single_fp32 @@ -38,6 +40,8 @@ elif [ "$BM_TYPE" = "benchmarks-default" ]; then echo spaces_sq8_fp32 echo spaces_sq8_fp16 echo spaces_sq8_sq8 + echo spaces_sq4_fp32 + echo spaces_sq4_sq4 # Basic benchmarks @@ -145,6 +149,8 @@ elif [ "$BM_TYPE" = "bm-spaces" ] ; then echo spaces_sq8_fp32 echo spaces_sq8_fp16 echo spaces_sq8_sq8 + echo spaces_sq4_fp32 + echo spaces_sq4_sq4 elif [ "$BM_TYPE" = "bm-spaces-fp32" ] ; then echo spaces_fp32 @@ -164,4 +170,8 @@ elif [ "$BM_TYPE" = "bm-spaces-sq8-fp16" ] ; then echo spaces_sq8_fp16 elif [ "$BM_TYPE" = "bm-spaces-sq8-sq8" ] ; then echo spaces_sq8_sq8 +elif [ "$BM_TYPE" = "bm-spaces-sq4-fp32" ] ; then + echo spaces_sq4_fp32 +elif [ "$BM_TYPE" = "bm-spaces-sq4-sq4" ] ; then + echo spaces_sq4_sq4 fi diff --git a/tests/benchmark/spaces_benchmarks/bm_spaces_sq4_fp32.cpp b/tests/benchmark/spaces_benchmarks/bm_spaces_sq4_fp32.cpp new file mode 100644 index 000000000..57c6af22c --- /dev/null +++ b/tests/benchmark/spaces_benchmarks/bm_spaces_sq4_fp32.cpp @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#include "bm_spaces.h" +#include +#include "VecSim/spaces/computer/preprocessors.h" +#include "VecSim/types/sq4.h" + +using sq4 = vecsim_types::sq4; + +/** + * SQ4-FP32 benchmarks: packed 4-bit storage against an FP32 query. Both blobs come from the + * production preprocessor. The L2 layouts carry every field the IP kernels read, so one pair + * serves both metrics. + */ +class BM_VecSimSpaces_SQ4_FP32 : public benchmark::Fixture { +protected: + std::shared_ptr allocator; + size_t dim; + void *v1 = nullptr; + void *v2 = nullptr; + +public: + BM_VecSimSpaces_SQ4_FP32() = default; + ~BM_VecSimSpaces_SQ4_FP32() = default; + + void SetUp(const ::benchmark::State &state) { + allocator = VecSimAllocator::newVecsimAllocator(); + dim = state.range(0); + std::mt19937 rng(47); + std::uniform_real_distribution uniform(-1.0f, 1.0f); + std::vector stored(dim), query(dim); + for (size_t i = 0; i < dim; ++i) { + stored[i] = uniform(rng); + query[i] = uniform(rng); + } + QuantPreprocessor pp(allocator, dim); + size_t stored_size = dim * sizeof(float), query_size = dim * sizeof(float); + pp.preprocessForStorage(stored.data(), v1, stored_size, 0); + pp.preprocessQuery(query.data(), v2, query_size, 0); + } + void TearDown(const ::benchmark::State &state) { + allocator->free_allocation(v1); + allocator->free_allocation(v2); + v1 = v2 = nullptr; + allocator.reset(); + } +}; + +#ifdef CPU_FEATURES_ARCH_AARCH64 +cpu_features::Aarch64Features opt = cpu_features::GetAarch64Info().features; + +// NEON implementation for ARMv8-a +#ifdef OPT_NEON +bool neon_supported = opt.asimd; // ARMv8-a always supports NEON +INITIALIZE_BENCHMARKS_SET_L2_IP(BM_VecSimSpaces_SQ4_FP32, SQ4_FP32, NEON, 16, neon_supported); +#endif +// SVE implementation +#ifdef OPT_SVE +bool sve_supported = opt.sve; // Check for SVE support +INITIALIZE_BENCHMARKS_SET_L2_IP(BM_VecSimSpaces_SQ4_FP32, SQ4_FP32, SVE, 16, sve_supported); +#endif +// SVE2 implementation +#ifdef OPT_SVE2 +bool sve2_supported = opt.sve2; // Check for SVE2 support +INITIALIZE_BENCHMARKS_SET_L2_IP(BM_VecSimSpaces_SQ4_FP32, SQ4_FP32, SVE2, 16, sve2_supported); +#endif +#endif // AARCH64 + +#ifdef CPU_FEATURES_ARCH_X86_64 +cpu_features::X86Features opt = cpu_features::GetX86Info().features; + +// AVX512_F_BW_VL_VNNI functions +#ifdef OPT_AVX512_F_BW_VL_VNNI +bool avx512_f_bw_vl_vnni_supported = opt.avx512f && opt.avx512bw && opt.avx512vl && opt.avx512vnni; +INITIALIZE_BENCHMARKS_SET_L2_IP(BM_VecSimSpaces_SQ4_FP32, SQ4_FP32, AVX512F_BW_VL_VNNI, 32, + avx512_f_bw_vl_vnni_supported); +#endif // AVX512_F_BW_VL_VNNI + +#ifdef OPT_AVX2_FMA +bool avx2_fma3_supported = opt.avx2 && opt.fma3; +INITIALIZE_BENCHMARKS_SET_L2_IP(BM_VecSimSpaces_SQ4_FP32, SQ4_FP32, AVX2_FMA, 32, + avx2_fma3_supported); +#endif // AVX2_FMA +#endif // x86_64 + +// Naive algorithms + +INITIALIZE_NAIVE_BM(BM_VecSimSpaces_SQ4_FP32, SQ4_FP32, InnerProduct, 16); +INITIALIZE_NAIVE_BM(BM_VecSimSpaces_SQ4_FP32, SQ4_FP32, L2Sqr, 16); + +BENCHMARK_MAIN(); diff --git a/tests/benchmark/spaces_benchmarks/bm_spaces_sq4_sq4.cpp b/tests/benchmark/spaces_benchmarks/bm_spaces_sq4_sq4.cpp new file mode 100644 index 000000000..11c2f8785 --- /dev/null +++ b/tests/benchmark/spaces_benchmarks/bm_spaces_sq4_sq4.cpp @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2006-Present, Redis Ltd. + * All rights reserved. + * + * Licensed under your choice of the Redis Source Available License 2.0 + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the + * GNU Affero General Public License v3 (AGPLv3). + */ +#include "bm_spaces.h" +#include +#include "VecSim/spaces/computer/preprocessors.h" +#include "VecSim/types/sq4.h" + +using sq4 = vecsim_types::sq4; + +/** + * SQ4-to-SQ4 benchmarks: both vectors are packed 4-bit storage blobs from the production + * preprocessor. The L2 layout carries every field the IP kernels read, so one pair serves both + * metrics. + */ +class BM_VecSimSpaces_SQ4_SQ4 : public benchmark::Fixture { +protected: + std::shared_ptr allocator; + size_t dim; + void *v1 = nullptr; + void *v2 = nullptr; + +public: + BM_VecSimSpaces_SQ4_SQ4() = default; + ~BM_VecSimSpaces_SQ4_SQ4() = default; + + void SetUp(const ::benchmark::State &state) { + allocator = VecSimAllocator::newVecsimAllocator(); + dim = state.range(0); + std::mt19937 rng(47); + std::uniform_real_distribution uniform(-1.0f, 1.0f); + std::vector first(dim), second(dim); + for (size_t i = 0; i < dim; ++i) { + first[i] = uniform(rng); + second[i] = uniform(rng); + } + QuantPreprocessor pp(allocator, dim); + size_t first_size = dim * sizeof(float), second_size = dim * sizeof(float); + pp.preprocessForStorage(first.data(), v1, first_size, 0); + pp.preprocessForStorage(second.data(), v2, second_size, 0); + } + void TearDown(const ::benchmark::State &state) { + allocator->free_allocation(v1); + allocator->free_allocation(v2); + v1 = v2 = nullptr; + allocator.reset(); + } +}; + +#ifdef CPU_FEATURES_ARCH_AARCH64 +cpu_features::Aarch64Features opt = cpu_features::GetAarch64Info().features; + +// NEON SQ4-to-SQ4 functions +#ifdef OPT_NEON +bool neon_supported = opt.asimd; +INITIALIZE_BENCHMARKS_SET_L2_IP(BM_VecSimSpaces_SQ4_SQ4, SQ4_SQ4, NEON, 16, neon_supported); +#endif // NEON +// NEON DOTPROD SQ4-to-SQ4 functions +#ifdef OPT_NEON_DOTPROD +bool neon_dotprod_supported = opt.asimddp; +INITIALIZE_BENCHMARKS_SET_L2_IP(BM_VecSimSpaces_SQ4_SQ4, SQ4_SQ4, NEON_DOTPROD, 32, + neon_dotprod_supported); +#endif // NEON_DOTPROD +// SVE SQ4-to-SQ4 functions +#ifdef OPT_SVE +bool sve_supported = opt.sve; +INITIALIZE_BENCHMARKS_SET_L2_IP(BM_VecSimSpaces_SQ4_SQ4, SQ4_SQ4, SVE, 16, sve_supported); +#endif // SVE +// SVE2 SQ4-to-SQ4 functions +#ifdef OPT_SVE2 +bool sve2_supported = opt.sve2; +INITIALIZE_BENCHMARKS_SET_L2_IP(BM_VecSimSpaces_SQ4_SQ4, SQ4_SQ4, SVE2, 16, sve2_supported); +#endif // SVE2 +#endif // AARCH64 + +#ifdef CPU_FEATURES_ARCH_X86_64 +cpu_features::X86Features opt = cpu_features::GetX86Info().features; + +// AVX512_F_BW_VL_VNNI SQ4-to-SQ4 functions +#ifdef OPT_AVX512_F_BW_VL_VNNI +bool avx512_f_bw_vl_vnni_supported = opt.avx512f && opt.avx512bw && opt.avx512vl && opt.avx512vnni; +INITIALIZE_BENCHMARKS_SET_L2_IP(BM_VecSimSpaces_SQ4_SQ4, SQ4_SQ4, AVX512F_BW_VL_VNNI, 64, + avx512_f_bw_vl_vnni_supported); +#endif // AVX512_F_BW_VL_VNNI +#endif // x86_64 + +// Naive SQ4-to-SQ4 algorithms +INITIALIZE_NAIVE_BM(BM_VecSimSpaces_SQ4_SQ4, SQ4_SQ4, InnerProduct, 16); +INITIALIZE_NAIVE_BM(BM_VecSimSpaces_SQ4_SQ4, SQ4_SQ4, L2Sqr, 16); + +BENCHMARK_MAIN(); diff --git a/tests/unit/test_sq4_distances.cpp b/tests/unit/test_sq4_distances.cpp index 345ffde8e..5a222d4ef 100644 --- a/tests/unit/test_sq4_distances.cpp +++ b/tests/unit/test_sq4_distances.cpp @@ -14,16 +14,29 @@ #include "VecSim/spaces/L2_space.h" #include "VecSim/types/sq4.h" #include "VecSim/types/sq8.h" +#include "VecSim/spaces/functions/NEON.h" +#include "VecSim/spaces/functions/NEON_DOTPROD.h" +#include "VecSim/spaces/functions/SVE.h" +#include "VecSim/spaces/functions/SVE2.h" +#include "VecSim/spaces/functions/AVX2.h" +#include "VecSim/spaces/functions/AVX2_FMA.h" +#include "VecSim/spaces/functions/AVX512F_BW_VL_VNNI.h" #include #include #include #include +#include #include #include #include #include +#ifdef __linux__ +#include +#include +#endif + namespace { using vecsim_types::sq4; using vecsim_types::sq8; @@ -309,20 +322,820 @@ TEST(SQ4Distances, FP32IPEqualsReconstruction) { 1e-5 * std::max(1.0f, std::abs(ref))); } +namespace { +// The dispatcher hands out SQ4-FP32 SIMD kernels from this dim up: any dim on AArch64, eight +// coordinates on x86 (as SQ8, for the AVX2 tail's full 8-float query load). +#ifdef CPU_FEATURES_ARCH_X86_64 +constexpr size_t SQ4_FP32_SIMD_MIN_DIM = 8; +#else +constexpr size_t SQ4_FP32_SIMD_MIN_DIM = 0; +#endif +} // namespace + TEST(SQ4Distances, DispatchIsScalarWithZeroAlignment) { for (size_t dim : {7u, 8u, 15u, 16u, 63u, 64u, 768u}) { SCOPED_TRACE(dim); + // SQ4-FP32 has SIMD kernels from SQ4_FP32_SIMD_MIN_DIM (see the SQ4SIMD tests), below + // that scalar. for (auto metric : {VecSimMetric_IP, VecSimMetric_L2}) { SCOPED_TRACE(metric); - const bool ip = metric == VecSimMetric_IP; unsigned char alignment = 255; - EXPECT_EQ((spaces::GetDistFunc(metric, dim, &alignment)), - ip ? SQ4_FP32_InnerProduct : SQ4_FP32_L2Sqr); + const auto fp32 = spaces::GetDistFunc(metric, dim, &alignment); + if (dim < SQ4_FP32_SIMD_MIN_DIM) { + EXPECT_EQ(fp32, metric == VecSimMetric_IP ? SQ4_FP32_InnerProduct : SQ4_FP32_L2Sqr); + } + EXPECT_EQ(alignment, 0); + alignment = 255; + const auto direct = metric == VecSimMetric_IP + ? spaces::IP_SQ4_FP32_GetDistFunc(dim, &alignment) + : spaces::L2_SQ4_FP32_GetDistFunc(dim, &alignment); + EXPECT_EQ(direct, fp32); EXPECT_EQ(alignment, 0); + } + // SQ4-SQ4 has SIMD kernels on AArch64 and on x86 with AVX2 or VNNI from dim 64 (both + // metrics: L2 is the stored-sum identity over the IP code dot), see the SQ4SIMD tests. + // Elsewhere scalar. + for (auto metric : {VecSimMetric_IP, VecSimMetric_L2}) { + SCOPED_TRACE(metric); + unsigned char alignment = 255; + const auto stored = spaces::GetDistFunc(metric, dim, &alignment); + EXPECT_EQ(alignment, 0); + const auto scalar = metric == VecSimMetric_IP ? SQ4_SQ4_InnerProduct : SQ4_SQ4_L2Sqr; +#if defined(CPU_FEATURES_ARCH_X86_64) + if (dim < 64) { + EXPECT_EQ(stored, scalar); + } + // Clearing all CPU features must return scalar even on SIMD-capable hosts. + decltype(spaces::getCpuOptimizationFeatures()) no_simd{}; + EXPECT_EQ(metric == VecSimMetric_IP + ? spaces::IP_SQ4_SQ4_GetDistFunc(dim, nullptr, &no_simd) + : spaces::L2_SQ4_SQ4_GetDistFunc(dim, nullptr, &no_simd), + scalar); +#elif !defined(CPU_FEATURES_ARCH_AARCH64) + EXPECT_EQ(stored, scalar); +#endif alignment = 255; - EXPECT_EQ((spaces::GetDistFunc(metric, dim, &alignment)), - ip ? SQ4_SQ4_InnerProduct : SQ4_SQ4_L2Sqr); + const auto direct = metric == VecSimMetric_IP + ? spaces::IP_SQ4_SQ4_GetDistFunc(dim, &alignment) + : spaces::L2_SQ4_SQ4_GetDistFunc(dim, &alignment); + EXPECT_EQ(direct, stored); + EXPECT_EQ(alignment, 0); + } + } +} + +// SIMD SQ4-FP32 tiers. Each tier is reached through the dispatcher by clearing the feature flags +// of the tiers above it, and its choosers are also called directly. +namespace { +using Features = decltype(spaces::getCpuOptimizationFeatures()); +using Chooser = spaces::dist_func_t (*)(size_t); + +struct SimdTier { + const char *name; + Features features; + Chooser chooseIP; + Chooser chooseL2; + + Chooser choose(VecSimMetric metric) const { + return metric == VecSimMetric_IP ? chooseIP : chooseL2; + } +}; + +std::vector sq4FP32Tiers() { + std::vector tiers; + [[maybe_unused]] Features features = spaces::getCpuOptimizationFeatures(); +#ifdef CPU_FEATURES_ARCH_AARCH64 +#ifdef OPT_SVE2 + if (features.sve2) { + tiers.push_back({"SVE2", features, spaces::Choose_SQ4_FP32_IP_implementation_SVE2, + spaces::Choose_SQ4_FP32_L2_implementation_SVE2}); + } +#endif + features.sve2 = 0; +#ifdef OPT_SVE + if (features.sve) { + tiers.push_back({"SVE", features, spaces::Choose_SQ4_FP32_IP_implementation_SVE, + spaces::Choose_SQ4_FP32_L2_implementation_SVE}); + } +#endif + features.sve = 0; +#ifdef OPT_NEON + if (features.asimd) { + tiers.push_back({"NEON", features, spaces::Choose_SQ4_FP32_IP_implementation_NEON, + spaces::Choose_SQ4_FP32_L2_implementation_NEON}); + } +#endif +#endif +#ifdef CPU_FEATURES_ARCH_X86_64 +#ifdef OPT_AVX512_F_BW_VL_VNNI + if (features.avx512f && features.avx512bw && features.avx512vl && features.avx512vnni) { + tiers.push_back({"AVX512F_BW_VL_VNNI", features, + spaces::Choose_SQ4_FP32_IP_implementation_AVX512F_BW_VL_VNNI, + spaces::Choose_SQ4_FP32_L2_implementation_AVX512F_BW_VL_VNNI}); + } +#endif + features.avx512f = 0; +#ifdef OPT_AVX2_FMA + if (features.avx2 && features.fma3) { + tiers.push_back({"AVX2_FMA", features, spaces::Choose_SQ4_FP32_IP_implementation_AVX2_FMA, + spaces::Choose_SQ4_FP32_L2_implementation_AVX2_FMA}); + } +#endif +#endif + return tiers; +} + +spaces::dist_func_t scalarFP32(VecSimMetric metric) { + return metric == VecSimMetric_IP ? SQ4_FP32_InnerProduct : SQ4_FP32_L2Sqr; +} + +spaces::dist_func_t dispatchFP32(VecSimMetric metric, size_t dim, unsigned char *alignment, + const Features *features) { + return metric == VecSimMetric_IP ? spaces::IP_SQ4_FP32_GetDistFunc(dim, alignment, features) + : spaces::L2_SQ4_FP32_GetDistFunc(dim, alignment, features); +} + +size_t storageBytes(VecSimMetric metric, size_t dim) { + return metric == VecSimMetric_IP ? sq4::storage_bytes_count(dim) + : sq4::storage_bytes_count(dim); +} + +size_t queryBytes(VecSimMetric metric, size_t dim) { + const size_t metadata = metric == VecSimMetric_IP + ? sq4::query_metadata_count() + : sq4::query_metadata_count(); + return (dim + metadata) * sizeof(float); +} + +// Exact-size storage blob of `metric` at `offset` bytes into its buffer. For odd dims the unused +// high nibble is set, so a kernel that lets it into the distance fails. +struct OffsetVector { + std::vector bytes; + size_t offset; + + OffsetVector(VecSimMetric metric, const std::vector &codes, float minimum, float delta, + size_t offset) + : bytes(offset + storageBytes(metric, codes.size()), 0xff), offset(offset) { + const size_t dim = codes.size(); + float metadata[4] = {minimum, delta, 0.0f, 0.0f}; + for (size_t i = 0; i < dim; ++i) { + sq4::set_code(data(), i, codes[i]); + const float xi = minimum + delta * codes[i]; + metadata[sq4::SUM] += xi; + metadata[sq4::SUM_SQUARES] += xi * xi; + } + if (dim % 2) { + data()[sq4::data_bytes_count(dim) - 1] |= 0xf0; + } + std::memcpy(data() + sq4::data_bytes_count(dim), metadata, + size() - sq4::data_bytes_count(dim)); + } + + uint8_t *data() { return bytes.data() + offset; } + size_t size() const { return bytes.size() - offset; } +}; + +// SIMD-versus-scalar bound: 1e-5 of the magnitude of the summed terms. The result itself can +// cancel to near zero, so a bound relative to it would be too tight for IP. +// IP: |min| * sum|y_i| + |delta| * sum(code_i * |y_i|) +// L2: sum((|delta * code_i| + |min - y_i|)^2) +double fp32Tolerance(VecSimMetric metric, const uint8_t *x, const float *y, size_t dim) { + const double min_val = storedMeta(x, dim, sq4::MIN_VAL); + const double delta = storedMeta(x, dim, sq4::DELTA); + double magnitude = 0.0; + for (size_t i = 0; i < dim; ++i) { + const double code = sq4::get_code(x, i); + if (metric == VecSimMetric_IP) { + magnitude += + std::abs(min_val) * std::abs(y[i]) + std::abs(delta) * code * std::abs(y[i]); + } else { + const double term = std::abs(delta * code) + std::abs(min_val - y[i]); + magnitude += term * term; + } + } + return 1e-5 * std::max(1.0, magnitude); +} + +#ifdef __linux__ +// Places an exact-size object immediately before a PROT_NONE page: any read past it faults. +class GuardedBuffer { + void *mapping = MAP_FAILED; + size_t mapping_size = 0; + uint8_t *object = nullptr; + +public: + explicit GuardedBuffer(size_t bytes) { + const long page_size = sysconf(_SC_PAGESIZE); + if (page_size <= 0) { + return; + } + const size_t page = size_t(page_size); + const size_t accessible = std::max(size_t(1), (bytes + page - 1) / page) * page; + mapping_size = accessible + page; + mapping = + mmap(nullptr, mapping_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (mapping == MAP_FAILED) { + return; + } + auto *boundary = static_cast(mapping) + accessible; + if (mprotect(boundary, page, PROT_NONE) == 0) { + object = boundary - bytes; + } + } + ~GuardedBuffer() { + if (mapping != MAP_FAILED) { + munmap(mapping, mapping_size); + } + } + GuardedBuffer(const GuardedBuffer &) = delete; + GuardedBuffer &operator=(const GuardedBuffer &) = delete; + uint8_t *data() { return object; } +}; +#endif + +// Per tier: dims 1..130 and 767..769, blob offsets 0..7, query offsets 0 and 4 bytes. Checks the +// dispatched function and alignment, then the chooser kernel (also below the dispatch minimum) +// against scalar. +void fp32MatchesScalar(VecSimMetric metric) { + const auto tiers = sq4FP32Tiers(); + if (tiers.empty()) { + GTEST_SKIP() << "no SIMD SQ4-FP32 tier on this machine"; + } + std::vector dims; + for (size_t dim = 1; dim <= 130; ++dim) { + dims.push_back(dim); + } + dims.insert(dims.end(), {767u, 768u, 769u}); + std::mt19937 rng(0x5134); + std::uniform_int_distribution code_dist(0, 15); + std::uniform_real_distribution val_dist(-1.0f, 1.0f); + for (const auto &tier : tiers) { + SCOPED_TRACE(tier.name); + for (size_t dim : dims) { + SCOPED_TRACE(dim); + unsigned char alignment = 255; + const auto dispatched = dispatchFP32(metric, dim, &alignment, &tier.features); + const auto chosen = tier.choose(metric); + const auto kernel = chosen(dim); + EXPECT_EQ(dispatched, dim >= SQ4_FP32_SIMD_MIN_DIM ? kernel : scalarFP32(metric)); + EXPECT_EQ(alignment, 0); + std::vector codes(dim); + std::vector values(dim); + for (size_t i = 0; i < dim; ++i) { + codes[i] = code_dist(rng); + values[i] = val_dist(rng); + } + const auto query = makeQuery(values); + const float min_val = val_dist(rng), delta = (1.0f + val_dist(rng)) / 15; + for (size_t query_offset : {0u, 1u}) { + SCOPED_TRACE(query_offset * sizeof(float)); + std::vector query_buffer(query_offset + query.size()); + std::copy(query.begin(), query.end(), query_buffer.begin() + query_offset); + const float *y = query_buffer.data() + query_offset; + for (size_t offset = 0; offset < 8; ++offset) { + SCOPED_TRACE(offset); + OffsetVector x(metric, codes, min_val, delta, offset); + const float scalar = scalarFP32(metric)(x.data(), y, dim); + const float simd = kernel(x.data(), y, dim); + EXPECT_LE(std::abs(double(simd) - scalar), + fp32Tolerance(metric, x.data(), y, dim)); + } + } + } + } +} + +// Negative control for fp32MatchesScalar's bound: a kernel that reads the nibbles in swapped order +// or the metadata one float late must miss it by more than 100 times. The query is the stored +// vector plus small noise, so swapping the nibbles changes the distance systematically rather than +// by chance. +void fp32ToleranceRejectsCorruption(VecSimMetric metric) { + const auto tiers = sq4FP32Tiers(); + if (tiers.empty()) { + GTEST_SKIP() << "no SIMD SQ4-FP32 tier on this machine"; + } + std::mt19937 rng(0x5135); + std::uniform_int_distribution code_dist(0, 15); + std::uniform_real_distribution val_dist(-1.0f, 1.0f); + for (const auto &tier : tiers) { + SCOPED_TRACE(tier.name); + for (size_t dim : {16u, 45u, 768u}) { + SCOPED_TRACE(dim); + // A minimum away from zero keeps the stored sum (the late-read delta) away from zero. + const float min_val = 0.75f + 0.25f * val_dist(rng); + const float delta = (1.5f + 0.5f * val_dist(rng)) / 15; + std::vector codes(dim); + std::vector values(dim); + for (size_t i = 0; i < dim; ++i) { + codes[i] = code_dist(rng); + values[i] = min_val + delta * codes[i] + 0.05f * val_dist(rng); + } + const auto query = makeQuery(values); + OffsetVector x(metric, codes, min_val, delta, 0); + const auto kernel = tier.choose(metric)(dim); + const double tolerance = fp32Tolerance(metric, x.data(), query.data(), dim); + const float scalar = scalarFP32(metric)(x.data(), query.data(), dim); + EXPECT_LE(std::abs(double(kernel(x.data(), query.data(), dim)) - scalar), tolerance); + + OffsetVector swapped = x; + for (size_t b = 0; b < sq4::data_bytes_count(dim); ++b) { + const uint8_t byte = swapped.data()[b]; + swapped.data()[b] = uint8_t(byte >> 4) | uint8_t(byte << 4); + } + EXPECT_GT(std::abs(double(kernel(swapped.data(), query.data(), dim)) - scalar), + 100 * tolerance); + + OffsetVector shifted = x; + uint8_t *metadata = shifted.data() + sq4::data_bytes_count(dim); + const size_t metadata_bytes = shifted.size() - sq4::data_bytes_count(dim); + std::memmove(metadata, metadata + sizeof(float), metadata_bytes - sizeof(float)); + EXPECT_GT(std::abs(double(kernel(shifted.data(), query.data(), dim)) - scalar), + 100 * tolerance); + } + } +} +} // namespace + +TEST(SQ4SIMD, FP32IPMatchesScalar) { fp32MatchesScalar(VecSimMetric_IP); } +TEST(SQ4SIMD, FP32L2MatchesScalar) { fp32MatchesScalar(VecSimMetric_L2); } + +TEST(SQ4SIMD, FP32IPToleranceRejectsCorruption) { fp32ToleranceRejectsCorruption(VecSimMetric_IP); } +TEST(SQ4SIMD, FP32L2ToleranceRejectsCorruption) { fp32ToleranceRejectsCorruption(VecSimMetric_L2); } + +// FP32L2PreservesResidualsAtLargeCommonOffset for every tier: with a common offset of 1e4 (float +// spacing 2^-10 there) and residuals up to 1e-2, forming min + delta * q before subtracting y +// would round away a large part of each residual, so the kernels must keep min - y first. +TEST(SQ4SIMD, FP32L2LargeCommonOffset) { + const auto tiers = sq4FP32Tiers(); + if (tiers.empty()) { + GTEST_SKIP() << "no SIMD SQ4-FP32 tier on this machine"; + } + const float min_val = 1e4f, delta = 1e-2f / 15, spacing = 1.0f / 1024; + for (size_t dim : {16u, 17u, 31u, 32u, 45u, 64u, 129u, 768u, 769u}) { + SCOPED_TRACE(dim); + std::vector codes(dim); + std::vector values(dim); + double expected = 0.0; + float reconstructed_first = 0.0f; + for (size_t i = 0; i < dim; ++i) { + codes[i] = (i * 7) % 16; + // min - y is 0, 1 or 2 float spacings, exact by Sterbenz. + values[i] = min_val - float(i % 3) * spacing; + const double residual = double(delta) * codes[i] + (double(min_val) - values[i]); + expected += residual * residual; + const float diff = (min_val + delta * codes[i]) - values[i]; + reconstructed_first += diff * diff; + } + const double tolerance = 1e-4 * expected; + // The bound below discriminates: reconstructing first misses it. + ASSERT_GT(std::abs(reconstructed_first - expected), tolerance); + const auto query = makeQuery(values); + OffsetVector x(VecSimMetric_L2, codes, min_val, delta, 1); + EXPECT_NEAR(SQ4_FP32_L2Sqr(x.data(), query.data(), dim), expected, tolerance); + for (const auto &tier : tiers) { + SCOPED_TRACE(tier.name); + EXPECT_NEAR(tier.chooseL2(dim)(x.data(), query.data(), dim), expected, tolerance); + EXPECT_NEAR(spaces::L2_SQ4_FP32_GetDistFunc(dim, nullptr, &tier.features)( + x.data(), query.data(), dim), + expected, tolerance); + } + } +} + +#ifdef __linux__ +// Storage blobs and query blobs of both metrics end exactly at a PROT_NONE page, so a kernel that +// reads past the packed codes plus metadata, or past the query's floats plus metadata, faults. +TEST(SQ4SIMD, ExactBuffersBeforeGuard) { + const auto tiers = sq4FP32Tiers(); + if (tiers.empty()) { + GTEST_SKIP() << "no SIMD SQ4-FP32 tier on this machine"; + } + std::vector dims; + for (size_t dim = 0; dim < 32; ++dim) { + dims.push_back(dim); + } + dims.insert(dims.end(), {127u, 128u, 129u, 767u, 768u, 769u, 1536u, 65536u}); + for (auto metric : {VecSimMetric_IP, VecSimMetric_L2}) { + SCOPED_TRACE(metric); + for (size_t dim : dims) { + SCOPED_TRACE(dim); + std::vector codes(dim); + std::vector values(dim); + for (size_t i = 0; i < dim; ++i) { + codes[i] = (i * 7) % 16; + values[i] = 0.75f + 0.0625f * ((i * 7) % 16); + } + OffsetVector x(metric, codes, -1.25f, 0.125f, 0); + const auto query = makeQuery(values); + const size_t query_bytes = queryBytes(metric, dim); + GuardedBuffer guarded_x(x.size()), guarded_query(query_bytes); + ASSERT_NE(guarded_x.data(), nullptr); + ASSERT_NE(guarded_query.data(), nullptr); + std::memcpy(guarded_x.data(), x.data(), x.size()); + std::memcpy(guarded_query.data(), query.data(), query_bytes); + const auto *y = reinterpret_cast(guarded_query.data()); + // Double-precision oracle over the reconstructed coordinates. + double dot = 0.0, norm_x = 0.0, norm_y = 0.0, l2 = 0.0; + for (size_t i = 0; i < dim; ++i) { + const double xi = -1.25 + 0.125 * codes[i]; + dot += xi * values[i]; + norm_x += xi * xi; + norm_y += double(values[i]) * values[i]; + l2 += (xi - values[i]) * (xi - values[i]); + } + // IP keeps the prototype's bound; L2 uses the equivalence bound. + const double expected = metric == VecSimMetric_IP ? 1.0 - dot : l2; + const double tolerance = metric == VecSimMetric_IP + ? 32 * std::numeric_limits::epsilon() * + (1.0 + std::sqrt(norm_x * norm_y)) + : fp32Tolerance(metric, guarded_x.data(), y, dim); + for (const auto &tier : tiers) { + SCOPED_TRACE(tier.name); + EXPECT_NEAR(tier.choose(metric)(dim)(guarded_x.data(), y, dim), expected, + tolerance); + } + } + } +} +#endif + +// SIMD SQ4-SQ4 tiers, reached through the dispatcher by clearing the feature flags of the tiers +// above each, and through their choosers directly. The L2 kernels are the stored-sum identity over +// the integer code dot, so L2 has the same tiers and dispatch minimum as IP, including the NEON dot +// product tier. On x86 AVX512F_BW_VL_VNNI takes precedence over AVX2; AVX2 needs no FMA. +namespace { +// Stored-to-stored forms: IP, and the L2 identity ||x||^2 + ||y||^2 - 2 * IP(x, y) over the stored +// metadata. +enum class SQ4Form { IP, L2 }; + +VecSimMetric metricOf(SQ4Form form) { + return form == SQ4Form::IP ? VecSimMetric_IP : VecSimMetric_L2; +} + +struct SQ4Tier { + const char *name; + Features features; + Chooser chooseIP; + Chooser chooseL2; + // The dispatcher hands out this tier's kernels (both metrics) from this dim up. + size_t min_dim; + + Chooser choose(SQ4Form form) const { return form == SQ4Form::IP ? chooseIP : chooseL2; } + size_t minDim() const { return min_dim; } +}; + +std::vector sq4SQ4Tiers() { + std::vector tiers; + [[maybe_unused]] Features features = spaces::getCpuOptimizationFeatures(); +#ifdef CPU_FEATURES_ARCH_AARCH64 +#ifdef OPT_SVE2 + if (features.sve2) { + tiers.push_back({"SVE2", features, spaces::Choose_SQ4_SQ4_IP_implementation_SVE2, + spaces::Choose_SQ4_SQ4_L2_implementation_SVE2, 0}); + } +#endif + features.sve2 = 0; +#ifdef OPT_SVE + if (features.sve) { + tiers.push_back({"SVE", features, spaces::Choose_SQ4_SQ4_IP_implementation_SVE, + spaces::Choose_SQ4_SQ4_L2_implementation_SVE, 0}); + } +#endif + features.sve = 0; +#ifdef OPT_NEON_DOTPROD + if (features.asimddp) { + tiers.push_back({"NEON_DOTPROD", features, + spaces::Choose_SQ4_SQ4_IP_implementation_NEON_DOTPROD, + spaces::Choose_SQ4_SQ4_L2_implementation_NEON_DOTPROD, 16}); + } +#endif + features.asimddp = 0; +#ifdef OPT_NEON + if (features.asimd) { + tiers.push_back({"NEON", features, spaces::Choose_SQ4_SQ4_IP_implementation_NEON, + spaces::Choose_SQ4_SQ4_L2_implementation_NEON, 16}); + } +#endif +#endif +#ifdef CPU_FEATURES_ARCH_X86_64 +#ifdef OPT_AVX512_F_BW_VL_VNNI + if (features.avx512f && features.avx512bw && features.avx512vl && features.avx512vnni) { + tiers.push_back({"AVX512F_BW_VL_VNNI", features, + spaces::Choose_SQ4_SQ4_IP_implementation_AVX512F_BW_VL_VNNI, + spaces::Choose_SQ4_SQ4_L2_implementation_AVX512F_BW_VL_VNNI, 64}); + } +#endif +#ifdef OPT_AVX2 + if (features.avx2) { + // Force the AVX2-only gate, with FMA and every AVX512 flag cleared. + Features avx2_only{}; + avx2_only.avx2 = 1; + tiers.push_back({"AVX2", avx2_only, spaces::Choose_SQ4_SQ4_IP_implementation_AVX2, + spaces::Choose_SQ4_SQ4_L2_implementation_AVX2, 64}); + } +#endif +#endif + return tiers; +} + +spaces::dist_func_t scalarSQ4(SQ4Form form) { + return form == SQ4Form::IP ? SQ4_SQ4_InnerProduct : SQ4_SQ4_L2Sqr; +} + +spaces::dist_func_t dispatchSQ4(SQ4Form form, size_t dim, unsigned char *alignment, + const Features *features) { + switch (form) { + case SQ4Form::IP: + return spaces::IP_SQ4_SQ4_GetDistFunc(dim, alignment, features); + case SQ4Form::L2: + return spaces::L2_SQ4_SQ4_GetDistFunc(dim, alignment, features); + } + return nullptr; +} + +// Magnitude of the summed terms of the stored-to-stored IP identity: +// |min_x| * sum|y_i| + |min_y| * sum|x_i| + dim * |min_x * min_y| + |dx * dy| * sum(qx * qy) +double sq4IPMagnitude(const uint8_t *x, const uint8_t *y, size_t dim) { + const double min_x = storedMeta(x, dim, sq4::MIN_VAL), dx = storedMeta(x, dim, sq4::DELTA); + const double min_y = storedMeta(y, dim, sq4::MIN_VAL), dy = storedMeta(y, dim, sq4::DELTA); + double abs_x = 0.0, abs_y = 0.0, code_dot = 0.0; + for (size_t i = 0; i < dim; ++i) { + const double qx = sq4::get_code(x, i), qy = sq4::get_code(y, i); + abs_x += std::abs(min_x + dx * qx); + abs_y += std::abs(min_y + dy * qy); + code_dot += qx * qy; + } + return std::abs(min_x) * abs_y + std::abs(min_y) * abs_x + + double(dim) * std::abs(min_x * min_y) + std::abs(dx * dy) * code_dot; +} + +// SIMD-versus-scalar bound for two stored vectors: 1e-5 of the magnitude of the summed terms. +// IP: sq4IPMagnitude +// L2: |sum_sq_x| + |sum_sq_y| + 2 * sq4IPMagnitude +double sq4Tolerance(SQ4Form form, const uint8_t *x, const uint8_t *y, size_t dim) { + double magnitude = sq4IPMagnitude(x, y, dim); + if (form == SQ4Form::L2) { + magnitude = std::abs(storedMeta(x, dim, sq4::SUM_SQUARES)) + + std::abs(storedMeta(y, dim, sq4::SUM_SQUARES)) + 2 * magnitude; + } + return 1e-5 * std::max(1.0, magnitude); +} + +// Double-precision stored-to-stored reference: the IP and L2 identities over the stored metadata +// (what the scalar kernels compute). +double sq4Reference(SQ4Form form, const uint8_t *x, const uint8_t *y, size_t dim) { + if (form == SQ4Form::IP) { + return 1.0 - identityIP(x, y, dim); + } + return storedMeta(x, dim, sq4::SUM_SQUARES) + storedMeta(y, dim, sq4::SUM_SQUARES) - + 2 * identityIP(x, y, dim); +} + +// Per tier: dims 1..130 and 767..769, offsets 0..7 for each operand. Checks the dispatched function +// and alignment, then the chooser kernel (also below the dispatch minimum) against scalar. +void sq4MatchesScalar(SQ4Form form) { + const VecSimMetric metric = metricOf(form); + const auto tiers = sq4SQ4Tiers(); + if (tiers.empty()) { + GTEST_SKIP() << "no SIMD SQ4-SQ4 tier on this machine"; + } + std::vector dims; + for (size_t dim = 1; dim <= 130; ++dim) { + dims.push_back(dim); + } + dims.insert(dims.end(), {767u, 768u, 769u}); + std::mt19937 rng(0x5144); + std::uniform_int_distribution code_dist(0, 15); + std::uniform_real_distribution val_dist(-1.0f, 1.0f); + for (const auto &tier : tiers) { + SCOPED_TRACE(tier.name); + for (size_t dim : dims) { + SCOPED_TRACE(dim); + unsigned char alignment = 255; + const auto dispatched = dispatchSQ4(form, dim, &alignment, &tier.features); + const auto kernel = tier.choose(form)(dim); + EXPECT_EQ(dispatched, dim >= tier.minDim() ? kernel : scalarSQ4(form)); EXPECT_EQ(alignment, 0); + std::vector x_codes(dim), y_codes(dim); + for (size_t i = 0; i < dim; ++i) { + x_codes[i] = code_dist(rng); + y_codes[i] = code_dist(rng); + } + const float min_x = val_dist(rng), dx = (1.0f + val_dist(rng)) / 15; + const float min_y = val_dist(rng), dy = (1.0f + val_dist(rng)) / 15; + std::vector ys; + for (size_t offset = 0; offset < 8; ++offset) { + ys.emplace_back(metric, y_codes, min_y, dy, offset); + } + for (size_t x_offset = 0; x_offset < 8; ++x_offset) { + SCOPED_TRACE(x_offset); + OffsetVector x(metric, x_codes, min_x, dx, x_offset); + for (auto &y : ys) { + SCOPED_TRACE(y.offset); + const float scalar = scalarSQ4(form)(x.data(), y.data(), dim); + const float simd = kernel(x.data(), y.data(), dim); + EXPECT_LE(std::abs(double(simd) - scalar), + sq4Tolerance(form, x.data(), y.data(), dim)); + } + } + } + } +} + +// Negative control for sq4MatchesScalar's bound: a kernel that reads the nibbles in swapped order +// or the metadata one float late must miss it by more than 100 times. y is x's codes moved by at +// most one level, so both corruptions change the distance systematically rather than by chance. +void sq4ToleranceRejectsCorruption(SQ4Form form) { + const VecSimMetric metric = metricOf(form); + const auto tiers = sq4SQ4Tiers(); + if (tiers.empty()) { + GTEST_SKIP() << "no SIMD SQ4-SQ4 tier on this machine"; + } + std::mt19937 rng(0x5145); + std::uniform_int_distribution code_dist(0, 15); + std::uniform_int_distribution step_dist(-1, 1); + std::uniform_real_distribution val_dist(-1.0f, 1.0f); + for (const auto &tier : tiers) { + SCOPED_TRACE(tier.name); + for (size_t dim : {16u, 45u, 768u}) { + SCOPED_TRACE(dim); + std::vector x_codes(dim), y_codes(dim); + for (size_t i = 0; i < dim; ++i) { + x_codes[i] = code_dist(rng); + y_codes[i] = std::clamp(x_codes[i] + step_dist(rng), 0, 15); + } + // Positive minimums keep the stored sum (the late-read delta) away from zero. + const float min_x = 0.1f + 0.05f * val_dist(rng), + dx = (1.5f + 0.5f * val_dist(rng)) / 15; + const float min_y = 0.1f + 0.05f * val_dist(rng), + dy = dx * (1.0f + 0.1f * val_dist(rng)); + OffsetVector x(metric, x_codes, min_x, dx, 0); + OffsetVector y(metric, y_codes, min_y, dy, 0); + const auto kernel = tier.choose(form)(dim); + const double tolerance = sq4Tolerance(form, x.data(), y.data(), dim); + const float scalar = scalarSQ4(form)(x.data(), y.data(), dim); + EXPECT_LE(std::abs(double(kernel(x.data(), y.data(), dim)) - scalar), tolerance); + + OffsetVector swapped = x; + for (size_t b = 0; b < sq4::data_bytes_count(dim); ++b) { + const uint8_t byte = swapped.data()[b]; + swapped.data()[b] = uint8_t(byte >> 4) | uint8_t(byte << 4); + } + EXPECT_GT(std::abs(double(kernel(swapped.data(), y.data(), dim)) - scalar), + 100 * tolerance); + + OffsetVector shifted = x; + uint8_t *metadata = shifted.data() + sq4::data_bytes_count(dim); + const size_t metadata_bytes = shifted.size() - sq4::data_bytes_count(dim); + std::memmove(metadata, metadata + sizeof(float), metadata_bytes - sizeof(float)); + EXPECT_GT(std::abs(double(kernel(shifted.data(), y.data(), dim)) - scalar), + 100 * tolerance); + } + } +} +} // namespace + +TEST(SQ4SIMD, SQ4IPMatchesScalar) { sq4MatchesScalar(SQ4Form::IP); } +TEST(SQ4SIMD, SQ4L2MatchesScalar) { sq4MatchesScalar(SQ4Form::L2); } + +TEST(SQ4SIMD, SQ4IPToleranceRejectsCorruption) { sq4ToleranceRejectsCorruption(SQ4Form::IP); } +TEST(SQ4SIMD, SQ4L2ToleranceRejectsCorruption) { sq4ToleranceRejectsCorruption(SQ4Form::L2); } + +// The integer code dot is exact while 225 * dim fits a uint32. Above SQ4_MAX_EXACT_SIMD_DIM the +// dispatcher hands back the scalar kernel on every tier; at it, the SIMD kernels are still handed +// out and are exact for all-15 codes, whose total is the largest a uint32 holds. +// On x86 that total also exceeds INT32_MAX, so it checks that the signed int32 SIMD lanes are +// reduced without signed wrap. +TEST(SQ4_SQ4, DispatchFallsBackAboveExactDim) { + constexpr size_t cap = spaces::SQ4_MAX_EXACT_SIMD_DIM; + constexpr uint64_t max_term = 15 * 15; + constexpr uint64_t uint32_max = std::numeric_limits::max(); + ASSERT_LE(max_term * cap, uint32_max); + ASSERT_GT(max_term * (cap + 1), uint32_max); + + unsigned char alignment = 255; + EXPECT_EQ(spaces::IP_SQ4_SQ4_GetDistFunc(cap + 1, &alignment), SQ4_SQ4_InnerProduct); + EXPECT_EQ(alignment, 0); + EXPECT_EQ((spaces::GetDistFunc(VecSimMetric_IP, cap + 1, nullptr)), + SQ4_SQ4_InnerProduct); + alignment = 255; + EXPECT_EQ(spaces::L2_SQ4_SQ4_GetDistFunc(cap + 1, &alignment), SQ4_SQ4_L2Sqr); + EXPECT_EQ(alignment, 0); + + const auto tiers = sq4SQ4Tiers(); + if (tiers.empty()) { + return; + } + // All codes 15 with min 0, delta 1 and sum 0: the distance is 1 - float(225 * cap). + std::vector blob(sq4::storage_bytes_count(cap), 0); + std::memset(blob.data(), 0xff, sq4::data_bytes_count(cap)); + blob[sq4::data_bytes_count(cap) - 1] = cap % 2 ? 0x0f : 0xff; + const float metadata[3] = {0.0f, 1.0f, 0.0f}; + std::memcpy(blob.data() + sq4::data_bytes_count(cap), metadata, sizeof(metadata)); + const float expected = 1.0f - static_cast(uint32_t(max_term * cap)); + for (const auto &tier : tiers) { + SCOPED_TRACE(tier.name); + alignment = 255; + EXPECT_EQ(spaces::IP_SQ4_SQ4_GetDistFunc(cap + 1, &alignment, &tier.features), + SQ4_SQ4_InnerProduct); + EXPECT_EQ(alignment, 0); + const auto kernel = tier.chooseIP(cap); + EXPECT_EQ(spaces::IP_SQ4_SQ4_GetDistFunc(cap, nullptr, &tier.features), kernel); + EXPECT_EQ(kernel(blob.data(), blob.data(), cap), expected); + } + + // L2 is the identity over the same code dot: with sum_squares 0 as well, it is -2 * float(225 * + // cap). + blob.resize(sq4::storage_bytes_count(cap), 0); + const float expected_l2 = -2.0f * static_cast(uint32_t(max_term * cap)); + for (const auto &tier : tiers) { + SCOPED_TRACE(tier.name); + alignment = 255; + EXPECT_EQ(spaces::L2_SQ4_SQ4_GetDistFunc(cap + 1, &alignment, &tier.features), + SQ4_SQ4_L2Sqr); + EXPECT_EQ(alignment, 0); + const auto kernel = tier.chooseL2(cap); + EXPECT_EQ(spaces::L2_SQ4_SQ4_GetDistFunc(cap, nullptr, &tier.features), kernel); + EXPECT_EQ(kernel(blob.data(), blob.data(), cap), expected_l2); + } +} + +#ifdef __linux__ +// Both stored operands end exactly at a PROT_NONE page, for both metrics and every tier, with the +// odd-dim padding nibble set: a kernel that reads past the packed codes plus metadata faults, and +// one that lets the padding nibble in misses the double reference. +TEST(SQ4SIMD, SQ4ExactBuffersBeforeGuard) { + const auto tiers = sq4SQ4Tiers(); + if (tiers.empty()) { + GTEST_SKIP() << "no SIMD SQ4-SQ4 tier on this machine"; + } + std::vector dims; + for (size_t dim = 0; dim < 128; ++dim) { + dims.push_back(dim); + } + dims.insert(dims.end(), {127u, 128u, 129u, 767u, 768u, 769u, 1536u, 65536u}); + for (auto form : {SQ4Form::IP, SQ4Form::L2}) { + SCOPED_TRACE(int(form)); + const VecSimMetric metric = metricOf(form); + for (size_t dim : dims) { + SCOPED_TRACE(dim); + std::vector x_codes(dim), y_codes(dim); + for (size_t i = 0; i < dim; ++i) { + x_codes[i] = (i * 7) % 16; + y_codes[i] = (i * 5 + 3) % 16; + } + OffsetVector x(metric, x_codes, -1.25f, 0.125f, 0); + OffsetVector y(metric, y_codes, 0.5f, 0.0625f, 0); + GuardedBuffer guarded_x(x.size()), guarded_y(y.size()); + ASSERT_NE(guarded_x.data(), nullptr); + ASSERT_NE(guarded_y.data(), nullptr); + std::memcpy(guarded_x.data(), x.data(), x.size()); + std::memcpy(guarded_y.data(), y.data(), y.size()); + const uint8_t *gx = guarded_x.data(), *gy = guarded_y.data(); + const double expected = sq4Reference(form, gx, gy, dim); + const double tolerance = sq4Tolerance(form, gx, gy, dim); + for (const auto &tier : tiers) { + SCOPED_TRACE(tier.name); + const auto kernel = tier.choose(form)(dim); + EXPECT_NEAR(kernel(gx, gy, dim), expected, tolerance); + EXPECT_NEAR(kernel(gy, gx, dim), expected, tolerance); + } + } + } +} +#endif + +#if defined(CPU_FEATURES_ARCH_X86_64) && defined(OPT_AVX2) +TEST(SQ4SIMD, AVX2NibbleProductsAreExact) { + if (!spaces::getCpuOptimizationFeatures().avx2) { + GTEST_SKIP() << "AVX2 unavailable"; + } + for (size_t dim = 64; dim < 192; ++dim) { + SCOPED_TRACE(dim); + // All-15 pairs exercise maddubs' largest sum; alternating and asymmetric codes + // distinguish low and high nibbles and expose leakage from the 16-bit shift. + for (unsigned pattern = 0; pattern < 3; ++pattern) { + SCOPED_TRACE(pattern); + std::vector xc(dim), yc(dim); + uint64_t dot = 0; + for (size_t i = 0; i < dim; ++i) { + xc[i] = pattern == 0 ? 15 : (i % 2 ? 15 : 0); + yc[i] = pattern < 2 ? 15 : (i % 2 ? 1 : 14); + dot += uint64_t(xc[i]) * yc[i]; + } + PackedVector x(xc, 0.0f, 1.0f), y(yc, 0.0f, 1.0f); + if (dim % 2) { + x.data()[dim / 2] |= 0xf0; + y.data()[dim / 2] |= 0xf0; + } + const float expected_ip = 1.0f - static_cast(dot); + const float expected_l2 = + referenceDistance(VecSimMetric_L2, x.reconstructed, y.reconstructed); + EXPECT_EQ(spaces::Choose_SQ4_SQ4_IP_implementation_AVX2(dim)(x.data(), y.data(), dim), + expected_ip); + EXPECT_EQ(spaces::Choose_SQ4_SQ4_L2_implementation_AVX2(dim)(x.data(), y.data(), dim), + expected_l2); } } } +#endif