From 805371268da67863754f989ef0c8835432c624a6 Mon Sep 17 00:00:00 2001 From: trvon Date: Tue, 24 Nov 2026 10:20:54 -0700 Subject: [PATCH 1/3] perf(simd,quantization): close x86 runtime dispatch gaps and fuse RaBitQ popcount - Wire SQLITE_VEC_X86_RUNTIME_DISPATCH (x86::l2_squared_avx2) in distances::l2_squared_distance() - Store inv_scales on LVQ8Store/LVQ4Store, add AVX2/runtime-dispatch kernels, and compare squared distances in quantized beam search (no per-hop sqrt) - Replace 256-entry LUT popcount in RaBitQ with uint64 std::popcount + fused 4-plane kernel and precomputed uint16_t code_popcount - Fix signed int16 overflow in l2_distance_int8_neon using widening vsubl_s8 + vmlal_s16 - Install simd/x86_dispatch.hpp in meson.build --- include/sqlite-vec-cpp/distances/l2.hpp | 5 + .../sqlite-vec-cpp/index/hnsw_quantized.hpp | 37 +-- .../sqlite-vec-cpp/quantization/rabitq.hpp | 187 +++++++++++---- include/sqlite-vec-cpp/quantization/store.hpp | 225 ++++++++++++++++-- include/sqlite-vec-cpp/simd/neon.hpp | 26 +- include/sqlite-vec-cpp/simd/x86_dispatch.hpp | 88 +++++++ meson.build | 1 + 7 files changed, 472 insertions(+), 97 deletions(-) diff --git a/include/sqlite-vec-cpp/distances/l2.hpp b/include/sqlite-vec-cpp/distances/l2.hpp index fef405c..6a62861 100644 --- a/include/sqlite-vec-cpp/distances/l2.hpp +++ b/include/sqlite-vec-cpp/distances/l2.hpp @@ -71,6 +71,11 @@ float l2_squared_distance(std::span a, std::span b) { if (a.size() > 16) { return simd::l2_squared_distance_float_neon(a, b); } +#endif +#ifdef SQLITE_VEC_X86_RUNTIME_DISPATCH + if (a.size() >= 8 && x86::cpu_has_avx2_fma()) { + return x86::l2_squared_avx2(a.data(), b.data(), a.size()); + } #endif return l2_squared_distance_float(a, b); } else if constexpr (std::is_same_v) { diff --git a/include/sqlite-vec-cpp/index/hnsw_quantized.hpp b/include/sqlite-vec-cpp/index/hnsw_quantized.hpp index 0daa6f9..2249730 100644 --- a/include/sqlite-vec-cpp/index/hnsw_quantized.hpp +++ b/include/sqlite-vec-cpp/index/hnsw_quantized.hpp @@ -99,29 +99,31 @@ template class HNSWQuantize /// Delegates to HNSWIndex::search_quantized_rerank which uses the internal /// beam search loop with visited pool, prefetching, and lock-free neighbors. std::vector> search(std::span query, size_t k, - size_t ef_search = 50) const { - return search_with_filter(query, k, ef_search, nullptr); + size_t ef_search = 50, + SearchStats* stats = nullptr) const { + return search_with_filter(query, k, ef_search, nullptr, stats); } /// Two-stage search with pre-filtering std::vector> search_with_filter(std::span query, size_t k, size_t ef_search, - const FilterFn& filter) const { + const FilterFn& filter, + SearchStats* stats = nullptr) const { // If no quantization built or index was mutated since build, fall back to base index if (config_.quantization == QuantizationType::None || !has_quantization() || is_stale()) { - return filter ? base_index_.search_with_filter(query, k, ef_search, filter) - : base_index_.search(query, k, ef_search); + return filter ? base_index_.search_with_filter(query, k, ef_search, filter, stats) + : base_index_.search(query, k, ef_search, stats); } switch (config_.quantization) { case QuantizationType::LVQ8: - return search_with_store(lvq8_store_, query, k, ef_search, filter); + return search_with_store(lvq8_store_, query, k, ef_search, filter, stats); case QuantizationType::LVQ4: - return search_with_store(lvq4_store_, query, k, ef_search, filter); + return search_with_store(lvq4_store_, query, k, ef_search, filter, stats); case QuantizationType::RaBitQ: - return search_rabitq(query, k, ef_search, filter); + return search_rabitq(query, k, ef_search, filter, stats); default: - return base_index_.search(query, k, ef_search); + return base_index_.search(query, k, ef_search, stats); } } @@ -212,34 +214,35 @@ template class HNSWQuantize quantization::RaBitQStore rabitq_store_; /// Search using an LVQ store (LVQ-8 or LVQ-4) - /// The store provides l2_distance(query, dense_id) and prefetch(dense_id) + /// Uses squared distances during beam search (monotonic with L2, avoids per-hop sqrt). template std::vector> search_with_store(const StoreT& store, std::span query, size_t k, size_t ef_search, - const FilterFn& filter) const { + const FilterFn& filter, SearchStats* stats = nullptr) const { auto approx_dist = [&store](std::span q, size_t dense_id) -> float { - return store.l2_distance(q, dense_id); + return store.l2_distance_squared(q, dense_id); }; auto prefetch_fn = [&store](size_t dense_id) { store.prefetch(dense_id); }; return base_index_.search_quantized_rerank(query, k, ef_search, config_.rerank_factor, - approx_dist, prefetch_fn, filter); + approx_dist, prefetch_fn, filter, stats); } - /// Search using RaBitQ (needs precomputed query state) + /// Search using RaBitQ (needs precomputed query state; uses squared distance in beam search) std::vector> search_rabitq(std::span query, size_t k, size_t ef_search, - const FilterFn& filter) const { + const FilterFn& filter, + SearchStats* stats = nullptr) const { auto query_state = rabitq_store_.prepare_query(query); auto approx_dist = [this, &query_state](std::span /*q*/, size_t dense_id) -> float { - return rabitq_store_.l2_distance(query_state, dense_id); + return rabitq_store_.l2_distance_squared(query_state, dense_id); }; auto prefetch_fn = [this](size_t dense_id) { rabitq_store_.prefetch(dense_id); }; return base_index_.search_quantized_rerank(query, k, ef_search, config_.rerank_factor, - approx_dist, prefetch_fn, filter); + approx_dist, prefetch_fn, filter, stats); } }; diff --git a/include/sqlite-vec-cpp/quantization/rabitq.hpp b/include/sqlite-vec-cpp/quantization/rabitq.hpp index aee31b0..b33e4f1 100644 --- a/include/sqlite-vec-cpp/quantization/rabitq.hpp +++ b/include/sqlite-vec-cpp/quantization/rabitq.hpp @@ -33,9 +33,11 @@ /// FP32 rerank for final top-K #include +#include #include #include #include +#include #include #include #include @@ -52,41 +54,89 @@ inline constexpr float kRaBitQEpsilon = 1e-12f; namespace detail { -inline constexpr uint8_t kPopcountTable[256] = { - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, - 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, - 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, - 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, - 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, - 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, - 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, - 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, - 5, 6, 6, 7, 6, 7, 7, 8}; - -inline uint32_t popcount_scalar(const uint8_t* a, size_t num_bytes) { +inline uint32_t popcount_u64(const uint8_t* a, size_t num_bytes) noexcept { uint32_t count = 0; - for (size_t i = 0; i < num_bytes; ++i) { - count += kPopcountTable[a[i]]; + size_t i = 0; + for (; i + sizeof(uint64_t) <= num_bytes; i += sizeof(uint64_t)) { + uint64_t word = 0; + std::memcpy(&word, a + i, sizeof(word)); + count += static_cast(std::popcount(word)); + } + for (; i < num_bytes; ++i) { + count += static_cast(std::popcount(static_cast(a[i]))); } return count; } -inline uint32_t and_popcount_scalar(const uint8_t* a, const uint8_t* b, size_t num_bytes) { +inline uint32_t and_popcount_u64(const uint8_t* a, const uint8_t* b, size_t num_bytes) noexcept { uint32_t count = 0; - for (size_t i = 0; i < num_bytes; ++i) { - count += kPopcountTable[a[i] & b[i]]; + size_t i = 0; + for (; i + sizeof(uint64_t) <= num_bytes; i += sizeof(uint64_t)) { + uint64_t wa = 0; + uint64_t wb = 0; + std::memcpy(&wa, a + i, sizeof(wa)); + std::memcpy(&wb, b + i, sizeof(wb)); + count += static_cast(std::popcount(wa & wb)); + } + for (; i < num_bytes; ++i) { + count += static_cast(std::popcount(static_cast(a[i] & b[i]))); } return count; } -inline uint32_t xor_popcount_scalar(const uint8_t* a, const uint8_t* b, size_t num_bytes) { +inline uint32_t xor_popcount_u64(const uint8_t* a, const uint8_t* b, size_t num_bytes) noexcept { uint32_t count = 0; - for (size_t i = 0; i < num_bytes; ++i) { - count += kPopcountTable[a[i] ^ b[i]]; + size_t i = 0; + for (; i + sizeof(uint64_t) <= num_bytes; i += sizeof(uint64_t)) { + uint64_t wa = 0; + uint64_t wb = 0; + std::memcpy(&wa, a + i, sizeof(wa)); + std::memcpy(&wb, b + i, sizeof(wb)); + count += static_cast(std::popcount(wa ^ wb)); + } + for (; i < num_bytes; ++i) { + count += static_cast(std::popcount(static_cast(a[i] ^ b[i]))); } return count; } +/// Fused single-pass weighted 4-plane AND-popcount: +/// sum_{j=0..3} (1 << j) * popcount(code & plane[j]) +/// Loads each code word once instead of scanning `code` 4 separate times. +inline uint64_t and_popcount_4planes_u64(const uint8_t* code, const uint8_t* p0, const uint8_t* p1, + const uint8_t* p2, const uint8_t* p3, + size_t num_bytes) noexcept { + uint64_t s0 = 0; + uint64_t s1 = 0; + uint64_t s2 = 0; + uint64_t s3 = 0; + size_t i = 0; + for (; i + sizeof(uint64_t) <= num_bytes; i += sizeof(uint64_t)) { + uint64_t c = 0; + uint64_t q0 = 0; + uint64_t q1 = 0; + uint64_t q2 = 0; + uint64_t q3 = 0; + std::memcpy(&c, code + i, sizeof(c)); + std::memcpy(&q0, p0 + i, sizeof(q0)); + std::memcpy(&q1, p1 + i, sizeof(q1)); + std::memcpy(&q2, p2 + i, sizeof(q2)); + std::memcpy(&q3, p3 + i, sizeof(q3)); + s0 += static_cast(std::popcount(c & q0)); + s1 += static_cast(std::popcount(c & q1)); + s2 += static_cast(std::popcount(c & q2)); + s3 += static_cast(std::popcount(c & q3)); + } + for (; i < num_bytes; ++i) { + const unsigned int c = code[i]; + s0 += static_cast(std::popcount(c & static_cast(p0[i]))); + s1 += static_cast(std::popcount(c & static_cast(p1[i]))); + s2 += static_cast(std::popcount(c & static_cast(p2[i]))); + s3 += static_cast(std::popcount(c & static_cast(p3[i]))); + } + return s0 + (s1 << 1) + (s2 << 2) + (s3 << 3); +} + #ifdef SQLITE_VEC_ENABLE_NEON inline uint32_t reduce_u8x16(uint8x16_t acc) { uint16x8_t sum16 = vpaddlq_u8(acc); @@ -111,9 +161,8 @@ inline uint32_t popcount_neon(const uint8_t* a, size_t num_bytes) { } } total += reduce_u8x16(acc); - while (i < num_bytes) { - total += kPopcountTable[a[i]]; - ++i; + if (i < num_bytes) { + total += popcount_u64(a + i, num_bytes - i); } return total; } @@ -134,9 +183,8 @@ inline uint32_t and_popcount_neon(const uint8_t* a, const uint8_t* b, size_t num } } total += reduce_u8x16(acc); - while (i < num_bytes) { - total += kPopcountTable[a[i] & b[i]]; - ++i; + if (i < num_bytes) { + total += and_popcount_u64(a + i, b + i, num_bytes - i); } return total; } @@ -157,39 +205,96 @@ inline uint32_t xor_popcount_neon(const uint8_t* a, const uint8_t* b, size_t num } } total += reduce_u8x16(acc); - while (i < num_bytes) { - total += kPopcountTable[a[i] ^ b[i]]; - ++i; + if (i < num_bytes) { + total += xor_popcount_u64(a + i, b + i, num_bytes - i); + } + return total; +} + +inline uint64_t and_popcount_4planes_neon(const uint8_t* code, const uint8_t* p0, const uint8_t* p1, + const uint8_t* p2, const uint8_t* p3, + size_t num_bytes) noexcept { + uint64_t s0 = 0; + uint64_t s1 = 0; + uint64_t s2 = 0; + uint64_t s3 = 0; + size_t i = 0; + const size_t end16 = (num_bytes / 16) * 16; + uint8x16_t acc0 = vdupq_n_u8(0); + uint8x16_t acc1 = vdupq_n_u8(0); + uint8x16_t acc2 = vdupq_n_u8(0); + uint8x16_t acc3 = vdupq_n_u8(0); + size_t iters = 0; + while (i < end16) { + const uint8x16_t c = vld1q_u8(code + i); + acc0 = vaddq_u8(acc0, vcntq_u8(vandq_u8(c, vld1q_u8(p0 + i)))); + acc1 = vaddq_u8(acc1, vcntq_u8(vandq_u8(c, vld1q_u8(p1 + i)))); + acc2 = vaddq_u8(acc2, vcntq_u8(vandq_u8(c, vld1q_u8(p2 + i)))); + acc3 = vaddq_u8(acc3, vcntq_u8(vandq_u8(c, vld1q_u8(p3 + i)))); + i += 16; + if (++iters == 31) { + s0 += reduce_u8x16(acc0); + s1 += reduce_u8x16(acc1); + s2 += reduce_u8x16(acc2); + s3 += reduce_u8x16(acc3); + acc0 = vdupq_n_u8(0); + acc1 = vdupq_n_u8(0); + acc2 = vdupq_n_u8(0); + acc3 = vdupq_n_u8(0); + iters = 0; + } + } + s0 += reduce_u8x16(acc0); + s1 += reduce_u8x16(acc1); + s2 += reduce_u8x16(acc2); + s3 += reduce_u8x16(acc3); + uint64_t total = s0 + (s1 << 1) + (s2 << 2) + (s3 << 3); + if (i < num_bytes) { + total += and_popcount_4planes_u64(code + i, p0 + i, p1 + i, p2 + i, p3 + i, num_bytes - i); } return total; } #endif -inline uint32_t popcount_bytes(const uint8_t* a, size_t num_bytes) { +inline uint32_t popcount_bytes(const uint8_t* a, size_t num_bytes) noexcept { #ifdef SQLITE_VEC_ENABLE_NEON if (num_bytes >= 16) { return popcount_neon(a, num_bytes); } #endif - return popcount_scalar(a, num_bytes); + return popcount_u64(a, num_bytes); } -inline uint32_t and_popcount_bytes(const uint8_t* a, const uint8_t* b, size_t num_bytes) { +inline uint32_t and_popcount_bytes(const uint8_t* a, const uint8_t* b, size_t num_bytes) noexcept { #ifdef SQLITE_VEC_ENABLE_NEON if (num_bytes >= 16) { return and_popcount_neon(a, b, num_bytes); } #endif - return and_popcount_scalar(a, b, num_bytes); + return and_popcount_u64(a, b, num_bytes); } -inline uint32_t xor_popcount_bytes(const uint8_t* a, const uint8_t* b, size_t num_bytes) { +inline uint32_t xor_popcount_bytes(const uint8_t* a, const uint8_t* b, size_t num_bytes) noexcept { #ifdef SQLITE_VEC_ENABLE_NEON if (num_bytes >= 16) { return xor_popcount_neon(a, b, num_bytes); } #endif - return xor_popcount_scalar(a, b, num_bytes); + return xor_popcount_u64(a, b, num_bytes); +} + +inline uint64_t and_popcount_4planes(const uint8_t* code, const uint8_t* planes, + size_t plane_bytes) noexcept { + const uint8_t* p0 = planes; + const uint8_t* p1 = planes + plane_bytes; + const uint8_t* p2 = planes + 2 * plane_bytes; + const uint8_t* p3 = planes + 3 * plane_bytes; +#ifdef SQLITE_VEC_ENABLE_NEON + if (plane_bytes >= 16) { + return and_popcount_4planes_neon(code, p0, p1, p2, p3, plane_bytes); + } +#endif + return and_popcount_4planes_u64(code, p0, p1, p2, p3, plane_bytes); } } // namespace detail @@ -273,6 +378,7 @@ struct RaBitQCode { float norm = 0.0f; ///< L2 norm of the original vector float dist_to_centroid = 0.0f; ///< ||v - c||, used in the distance identity float ip_quant = 1.0f; ///< , the per-vector correction factor + uint16_t code_popcount = 0; ///< Precomputed popcount(bits) /// Number of packed bytes [[nodiscard]] size_t byte_size() const { return bits.size(); } @@ -348,12 +454,15 @@ class RaBitQ { rotation_.apply(std::span(residual), std::span(rotated)); float abs_sum = 0.0f; + uint32_t pc = 0; for (size_t i = 0; i < padded; ++i) { abs_sum += std::abs(rotated[i]); if (rotated[i] >= 0.0f) { code.bits[i / 8] |= (1u << (i % 8)); + ++pc; } } + code.code_popcount = static_cast(std::min(pc, 65535u)); code.ip_quant = std::max(abs_sum * rotation_.inv_sqrt_padded(), kRaBitQEpsilon); return code; @@ -455,12 +564,8 @@ class RaBitQ { const size_t nb = query.plane_bytes; const uint8_t* bits = code.bits.data(); - const uint32_t pc = detail::popcount_bytes(bits, nb); - uint64_t su = 0; - for (size_t j = 0; j < 4; ++j) { - su += static_cast(1u << j) * - detail::and_popcount_bytes(bits, query.planes.data() + j * nb, nb); - } + const uint32_t pc = code.code_popcount; + const uint64_t su = detail::and_popcount_4planes(bits, query.planes.data(), nb); const float sum_selected = query.vl * static_cast(pc) + query.delta * static_cast(su); diff --git a/include/sqlite-vec-cpp/quantization/store.hpp b/include/sqlite-vec-cpp/quantization/store.hpp index d392f06..9da2936 100644 --- a/include/sqlite-vec-cpp/quantization/store.hpp +++ b/include/sqlite-vec-cpp/quantization/store.hpp @@ -19,9 +19,14 @@ #include #include "../index/quantization_snapshot.hpp" +#include "../simd/x86_dispatch.hpp" #include "lvq.hpp" #include "rabitq.hpp" +#ifdef SQLITE_VEC_ENABLE_AVX2 +#include +#endif + namespace sqlite_vec_cpp::quantization { /// Flat storage for LVQ-8 codes indexed by dense_id @@ -30,6 +35,8 @@ struct LVQ8Store { std::vector codes; /// Per-vector scale factors: scales[dense_id] std::vector scales; + /// Precomputed 1.0f / scales[dense_id] (0.0f when scale == 0.0f) + std::vector inv_scales; /// Per-vector offsets: offsets[dense_id] std::vector offsets; /// Dimensionality @@ -50,6 +57,7 @@ struct LVQ8Store { count = max_dense_id + 1; codes.resize(count * dim, 0); scales.resize(count, 0.0f); + inv_scales.resize(count, 0.0f); offsets.resize(count, 0.0f); for (const auto& e : snap.entries) { @@ -57,12 +65,13 @@ struct LVQ8Store { size_t offset = e.dense_id * dim; std::copy(code.codes.begin(), code.codes.end(), codes.begin() + offset); scales[e.dense_id] = code.scale; + inv_scales[e.dense_id] = code.scale > 0.0f ? (1.0f / code.scale) : 0.0f; offsets[e.dense_id] = code.offset; } } - /// Estimate L2 distance between float query and quantized vector at dense_id - [[nodiscard]] float l2_distance(std::span query, size_t dense_id) const { + /// Estimate squared L2 distance between float query and quantized vector at dense_id + [[nodiscard]] float l2_distance_squared(std::span query, size_t dense_id) const { assert(dense_id < count); assert(query.size() == dim); @@ -76,12 +85,18 @@ struct LVQ8Store { float diff = query[i] - offset; sum += diff * diff; } - return std::sqrt(sum); + return sum; } - const float inv_scale = 1.0f / scale; + const float inv_scale = + (dense_id < inv_scales.size()) ? inv_scales[dense_id] : (1.0f / scale); float sum_sq = l2_sq_impl(query.data(), code_ptr, dim, inv_scale, offset); - return std::sqrt(sum_sq * scale * scale); + return sum_sq * scale * scale; + } + + /// Estimate L2 distance between float query and quantized vector at dense_id + [[nodiscard]] float l2_distance(std::span query, size_t dense_id) const { + return std::sqrt(l2_distance_squared(query, dense_id)); } /// Prefetch the quantized code for a given dense_id into L1 cache @@ -96,20 +111,95 @@ struct LVQ8Store { /// Memory usage in bytes [[nodiscard]] size_t memory_bytes() const { - return codes.size() + scales.size() * sizeof(float) + offsets.size() * sizeof(float); + return codes.size() + scales.size() * sizeof(float) + inv_scales.size() * sizeof(float) + + offsets.size() * sizeof(float); } private: static float l2_sq_impl(const float* query, const uint8_t* codes, size_t dim, float inv_scale, float offset) { +#ifdef SQLITE_VEC_ENABLE_AVX2 + if (dim >= 8) { + return l2_sq_avx2(query, codes, dim, inv_scale, offset); + } +#endif #ifdef SQLITE_VEC_ENABLE_NEON if (dim >= 16) { return l2_sq_neon(query, codes, dim, inv_scale, offset); } +#endif +#ifdef SQLITE_VEC_X86_RUNTIME_DISPATCH + if (dim >= 8 && distances::x86::cpu_has_avx2_fma()) { + return distances::x86::lvq8_l2_sq_avx2(query, codes, dim, inv_scale, offset); + } #endif return l2_sq_scalar(query, codes, dim, inv_scale, offset); } +#ifdef SQLITE_VEC_ENABLE_AVX2 + static float hsum256(__m256 v) noexcept { + __m128 lo = _mm256_castps256_ps128(v); + const __m128 hi = _mm256_extractf128_ps(v, 1); + lo = _mm_add_ps(lo, hi); + __m128 shuf = _mm_movehdup_ps(lo); + __m128 sums = _mm_add_ps(lo, shuf); + shuf = _mm_movehl_ps(shuf, sums); + sums = _mm_add_ss(sums, shuf); + return _mm_cvtss_f32(sums); + } + + static float l2_sq_avx2(const float* query, const uint8_t* codes, size_t dim, float inv_scale, + float offset) { + const __m256 voffset = _mm256_set1_ps(offset); + const __m256 vinv_scale = _mm256_set1_ps(inv_scale); + __m256 sum0 = _mm256_setzero_ps(); + __m256 sum1 = _mm256_setzero_ps(); + + size_t i = 0; + for (; i + 16 <= dim; i += 16) { + const __m128i bytes0 = _mm_loadl_epi64(reinterpret_cast(codes + i)); + const __m128i bytes1 = _mm_loadl_epi64(reinterpret_cast(codes + i + 8)); + const __m256 c0 = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(bytes0)); + const __m256 c1 = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(bytes1)); + + const __m256 q0 = _mm256_mul_ps(_mm256_sub_ps(_mm256_loadu_ps(query + i), voffset), + vinv_scale); + const __m256 q1 = _mm256_mul_ps(_mm256_sub_ps(_mm256_loadu_ps(query + i + 8), voffset), + vinv_scale); + + const __m256 d0 = _mm256_sub_ps(q0, c0); + const __m256 d1 = _mm256_sub_ps(q1, c1); +#ifdef SQLITE_VEC_ENABLE_FMA + sum0 = _mm256_fmadd_ps(d0, d0, sum0); + sum1 = _mm256_fmadd_ps(d1, d1, sum1); +#else + sum0 = _mm256_add_ps(sum0, _mm256_mul_ps(d0, d0)); + sum1 = _mm256_add_ps(sum1, _mm256_mul_ps(d1, d1)); +#endif + } + for (; i + 8 <= dim; i += 8) { + const __m128i bytes0 = _mm_loadl_epi64(reinterpret_cast(codes + i)); + const __m256 c0 = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(bytes0)); + const __m256 q0 = _mm256_mul_ps(_mm256_sub_ps(_mm256_loadu_ps(query + i), voffset), + vinv_scale); + const __m256 d0 = _mm256_sub_ps(q0, c0); +#ifdef SQLITE_VEC_ENABLE_FMA + sum0 = _mm256_fmadd_ps(d0, d0, sum0); +#else + sum0 = _mm256_add_ps(sum0, _mm256_mul_ps(d0, d0)); +#endif + } + + float sum = hsum256(_mm256_add_ps(sum0, sum1)); + for (; i < dim; ++i) { + const float q_normalized = (query[i] - offset) * inv_scale; + const float diff = q_normalized - static_cast(codes[i]); + sum += diff * diff; + } + return sum; + } +#endif + static float l2_sq_scalar(const float* query, const uint8_t* codes, size_t dim, float inv_scale, float offset) { float sum = 0.0f; @@ -185,6 +275,8 @@ struct LVQ4Store { std::vector codes; /// Per-vector scale factors std::vector scales; + /// Precomputed 1.0f / scales[dense_id] (0.0f when scale == 0.0f) + std::vector inv_scales; /// Per-vector offsets std::vector offsets; /// Dimensionality @@ -208,6 +300,7 @@ struct LVQ4Store { count = max_dense_id + 1; codes.resize(count * bytes_per_vec, 0); scales.resize(count, 0.0f); + inv_scales.resize(count, 0.0f); offsets.resize(count, 0.0f); for (const auto& e : snap.entries) { @@ -215,12 +308,13 @@ struct LVQ4Store { size_t offset = e.dense_id * bytes_per_vec; std::copy(code.codes.begin(), code.codes.end(), codes.begin() + offset); scales[e.dense_id] = code.scale; + inv_scales[e.dense_id] = code.scale > 0.0f ? (1.0f / code.scale) : 0.0f; offsets[e.dense_id] = code.offset; } } - /// Estimate L2 distance between float query and quantized vector at dense_id - [[nodiscard]] float l2_distance(std::span query, size_t dense_id) const { + /// Estimate squared L2 distance between float query and quantized vector at dense_id + [[nodiscard]] float l2_distance_squared(std::span query, size_t dense_id) const { assert(dense_id < count); assert(query.size() == dim); @@ -234,12 +328,18 @@ struct LVQ4Store { float diff = query[i] - offset; sum += diff * diff; } - return std::sqrt(sum); + return sum; } - const float inv_scale = 1.0f / scale; + const float inv_scale = + (dense_id < inv_scales.size()) ? inv_scales[dense_id] : (1.0f / scale); float sum_sq = l2_sq_impl(query.data(), code_ptr, dim, inv_scale, offset); - return std::sqrt(sum_sq * scale * scale); + return sum_sq * scale * scale; + } + + /// Estimate L2 distance between float query and quantized vector at dense_id + [[nodiscard]] float l2_distance(std::span query, size_t dense_id) const { + return std::sqrt(l2_distance_squared(query, dense_id)); } /// Prefetch the quantized code for a given dense_id into L1 cache @@ -254,20 +354,89 @@ struct LVQ4Store { /// Memory usage in bytes [[nodiscard]] size_t memory_bytes() const { - return codes.size() + scales.size() * sizeof(float) + offsets.size() * sizeof(float); + return codes.size() + scales.size() * sizeof(float) + inv_scales.size() * sizeof(float) + + offsets.size() * sizeof(float); } private: static float l2_sq_impl(const float* query, const uint8_t* codes, size_t dim, float inv_scale, float offset) { +#ifdef SQLITE_VEC_ENABLE_AVX2 + if (dim >= 16) { + return l2_sq_avx2(query, codes, dim, inv_scale, offset); + } +#endif #ifdef SQLITE_VEC_ENABLE_NEON if (dim >= 32) { return l2_sq_neon(query, codes, dim, inv_scale, offset); } +#endif +#ifdef SQLITE_VEC_X86_RUNTIME_DISPATCH + if (dim >= 16 && distances::x86::cpu_has_avx2_fma()) { + return distances::x86::lvq4_l2_sq_avx2(query, codes, dim, inv_scale, offset); + } #endif return l2_sq_scalar(query, codes, dim, inv_scale, offset); } +#ifdef SQLITE_VEC_ENABLE_AVX2 + static float hsum256(__m256 v) noexcept { + __m128 lo = _mm256_castps256_ps128(v); + const __m128 hi = _mm256_extractf128_ps(v, 1); + lo = _mm_add_ps(lo, hi); + __m128 shuf = _mm_movehdup_ps(lo); + __m128 sums = _mm_add_ps(lo, shuf); + shuf = _mm_movehl_ps(shuf, sums); + sums = _mm_add_ss(sums, shuf); + return _mm_cvtss_f32(sums); + } + + static float l2_sq_avx2(const float* query, const uint8_t* codes, size_t dim, float inv_scale, + float offset) { + const __m256 voffset = _mm256_set1_ps(offset); + const __m256 vinv_scale = _mm256_set1_ps(inv_scale); + const __m128i mask_0f = _mm_set1_epi8(0x0F); + __m256 sum0 = _mm256_setzero_ps(); + __m256 sum1 = _mm256_setzero_ps(); + + size_t i = 0; + for (; i + 16 <= dim; i += 16) { + const __m128i packed = _mm_loadl_epi64(reinterpret_cast(codes + i / 2)); + const __m128i lo = _mm_and_si128(packed, mask_0f); + const __m128i hi = _mm_and_si128(_mm_srli_epi16(packed, 4), mask_0f); + const __m128i unpacked = _mm_unpacklo_epi8(lo, hi); + + const __m256 c0 = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(unpacked)); + const __m256 c1 = + _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(_mm_srli_si128(unpacked, 8))); + + const __m256 q0 = _mm256_mul_ps(_mm256_sub_ps(_mm256_loadu_ps(query + i), voffset), + vinv_scale); + const __m256 q1 = _mm256_mul_ps(_mm256_sub_ps(_mm256_loadu_ps(query + i + 8), voffset), + vinv_scale); + + const __m256 d0 = _mm256_sub_ps(q0, c0); + const __m256 d1 = _mm256_sub_ps(q1, c1); +#ifdef SQLITE_VEC_ENABLE_FMA + sum0 = _mm256_fmadd_ps(d0, d0, sum0); + sum1 = _mm256_fmadd_ps(d1, d1, sum1); +#else + sum0 = _mm256_add_ps(sum0, _mm256_mul_ps(d0, d0)); + sum1 = _mm256_add_ps(sum1, _mm256_mul_ps(d1, d1)); +#endif + } + + float sum = hsum256(_mm256_add_ps(sum0, sum1)); + for (; i < dim; ++i) { + const uint8_t c = (i % 2 == 0) ? (codes[i / 2] & 0x0F) : ((codes[i / 2] >> 4) & 0x0F); + const float q_normalized = (query[i] - offset) * inv_scale; + const float diff = q_normalized - static_cast(c); + sum += diff * diff; + } + return sum; + } +#endif + static float l2_sq_scalar(const float* query, const uint8_t* codes, size_t dim, float inv_scale, float offset) { float sum = 0.0f; @@ -382,6 +551,8 @@ struct RaBitQStore { std::vector dist_to_centroid; /// Per-vector correction factor std::vector ip_quant; + /// Precomputed popcount of each packed binary code + std::vector code_popcount; /// Dataset centroid std::vector centroid; /// Bytes per vector (padded_dim / 8) @@ -418,6 +589,7 @@ struct RaBitQStore { bits.assign(count * bytes_per_vec, 0); dist_to_centroid.assign(count, 0.0f); ip_quant.assign(count, 1.0f); + code_popcount.assign(count, 0); std::vector residual(dim); std::vector rotated(padded); @@ -442,12 +614,15 @@ struct RaBitQStore { uint8_t* code_ptr = bits.data() + e.dense_id * bytes_per_vec; float abs_sum = 0.0f; + uint32_t pc = 0; for (size_t i = 0; i < padded; ++i) { abs_sum += std::abs(rotated[i]); if (rotated[i] >= 0.0f) { code_ptr[i / 8] |= static_cast(1u << (i % 8)); + ++pc; } } + code_popcount[e.dense_id] = static_cast(std::min(pc, 65535u)); ip_quant[e.dense_id] = std::max(abs_sum * rotation_->inv_sqrt_padded(), kRaBitQEpsilon); } @@ -518,25 +693,23 @@ struct RaBitQStore { return state; } - /// Estimate L2 distance using precomputed query state - [[nodiscard]] float l2_distance(const QueryState& qs, size_t dense_id) const { + /// Estimate squared L2 distance using precomputed query state + [[nodiscard]] float l2_distance_squared(const QueryState& qs, size_t dense_id) const { assert(dense_id < count); const float qd = qs.dist_to_centroid; const float cd = dist_to_centroid[dense_id]; if (qd <= 0.0f || cd <= 0.0f) { - return std::sqrt(std::max(0.0f, qd * qd + cd * cd)); + return std::max(0.0f, qd * qd + cd * cd); } const uint8_t* code_ptr = bits.data() + dense_id * bytes_per_vec; const size_t nb = qs.plane_bytes; - const uint32_t pc = detail::popcount_bytes(code_ptr, nb); - uint64_t su = 0; - for (size_t j = 0; j < 4; ++j) { - su += static_cast(1u << j) * - detail::and_popcount_bytes(code_ptr, qs.planes.data() + j * nb, nb); - } + const uint32_t pc = (dense_id < code_popcount.size()) + ? static_cast(code_popcount[dense_id]) + : detail::popcount_bytes(code_ptr, nb); + const uint64_t su = detail::and_popcount_4planes(code_ptr, qs.planes.data(), nb); const float sum_selected = qs.vl * static_cast(pc) + qs.delta * static_cast(su); @@ -545,7 +718,12 @@ struct RaBitQStore { const float est = std::clamp(ip_xq / ip_quant[dense_id], -1.0f, 1.0f); const float dist_sq = qd * qd + cd * cd - 2.0f * qd * cd * est; - return std::sqrt(std::max(0.0f, dist_sq)); + return std::max(0.0f, dist_sq); + } + + /// Estimate L2 distance using precomputed query state + [[nodiscard]] float l2_distance(const QueryState& qs, size_t dense_id) const { + return std::sqrt(l2_distance_squared(qs, dense_id)); } /// Prefetch bits for a given dense_id @@ -561,7 +739,8 @@ struct RaBitQStore { /// Memory usage in bytes [[nodiscard]] size_t memory_bytes() const { return bits.size() + dist_to_centroid.size() * sizeof(float) + - ip_quant.size() * sizeof(float) + centroid.size() * sizeof(float) + + ip_quant.size() * sizeof(float) + code_popcount.size() * sizeof(uint16_t) + + centroid.size() * sizeof(float) + (rotation_ ? rotation_->memory_bytes() : 0); } diff --git a/include/sqlite-vec-cpp/simd/neon.hpp b/include/sqlite-vec-cpp/simd/neon.hpp index d3f0da4..4c6923f 100644 --- a/include/sqlite-vec-cpp/simd/neon.hpp +++ b/include/sqlite-vec-cpp/simd/neon.hpp @@ -72,34 +72,28 @@ inline float l2_distance_float_neon(std::span a, std::span 7 inline float l2_distance_int8_neon(std::span a, std::span b) { const std::size_t size = a.size(); - std::int32_t sum_scalar = 0; + int32x4_t acc = vdupq_n_s32(0); std::size_t i = 0; - // Process 8 int8s at a time + // Process 8 int8s at a time using widening subtract (s8 -> s16) and widening + // multiply-accumulate (s16 * s16 -> s32) since |diff| <= 255 and diff^2 <= 65025 + // overflows signed int16. while (i + 7 < size) { int8x8_t v1 = vld1_s8(&a[i]); int8x8_t v2 = vld1_s8(&b[i]); - // Widen to int16 to avoid overflow - int16x8_t v1_wide = vmovl_s8(v1); - int16x8_t v2_wide = vmovl_s8(v2); - - int16x8_t diff = vsubq_s16(v1_wide, v2_wide); - int16x8_t squared_diff = vmulq_s16(diff, diff); - - // Pairwise add to int32 - int32x4_t sum = vpaddlq_s16(squared_diff); - - // Extract lanes and add to scalar sum - sum_scalar += vgetq_lane_s32(sum, 0) + vgetq_lane_s32(sum, 1) + vgetq_lane_s32(sum, 2) + - vgetq_lane_s32(sum, 3); + int16x8_t diff = vsubl_s8(v1, v2); + acc = vmlal_s16(acc, vget_low_s16(diff), vget_low_s16(diff)); + acc = vmlal_s16(acc, vget_high_s16(diff), vget_high_s16(diff)); i += 8; } + std::int64_t sum_scalar = static_cast(vaddvq_s32(acc)); + // Handle remaining elements while (i < size) { - std::int16_t diff = static_cast(a[i]) - static_cast(b[i]); + std::int32_t diff = static_cast(a[i]) - static_cast(b[i]); sum_scalar += diff * diff; ++i; } diff --git a/include/sqlite-vec-cpp/simd/x86_dispatch.hpp b/include/sqlite-vec-cpp/simd/x86_dispatch.hpp index 79d3d46..2e980b8 100644 --- a/include/sqlite-vec-cpp/simd/x86_dispatch.hpp +++ b/include/sqlite-vec-cpp/simd/x86_dispatch.hpp @@ -14,6 +14,7 @@ #define SQLITE_VEC_X86_RUNTIME_DISPATCH 1 #include +#include #include #define SQLITE_VEC_TARGET_AVX2_FMA __attribute__((target("avx2,fma"))) @@ -130,6 +131,93 @@ SQLITE_VEC_TARGET_AVX2_FMA inline void cosine_terms_avx2(const float* a, const f } } +// LVQ-8 squared L2 distance in quantized space: sum_i ((query[i] - offset) * inv_scale - codes[i])^2 +SQLITE_VEC_TARGET_AVX2_FMA inline float lvq8_l2_sq_avx2(const float* query, + const std::uint8_t* codes, std::size_t dim, + float inv_scale, float offset) noexcept { + const __m256 voffset = _mm256_set1_ps(offset); + const __m256 vinv_scale = _mm256_set1_ps(inv_scale); + __m256 sum0 = _mm256_setzero_ps(); + __m256 sum1 = _mm256_setzero_ps(); + + std::size_t i = 0; + for (; i + 16 <= dim; i += 16) { + const __m128i bytes0 = _mm_loadl_epi64(reinterpret_cast(codes + i)); + const __m128i bytes1 = _mm_loadl_epi64(reinterpret_cast(codes + i + 8)); + const __m256 c0 = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(bytes0)); + const __m256 c1 = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(bytes1)); + + const __m256 q0 = _mm256_mul_ps(_mm256_sub_ps(_mm256_loadu_ps(query + i), voffset), + vinv_scale); + const __m256 q1 = _mm256_mul_ps(_mm256_sub_ps(_mm256_loadu_ps(query + i + 8), voffset), + vinv_scale); + + const __m256 d0 = _mm256_sub_ps(q0, c0); + const __m256 d1 = _mm256_sub_ps(q1, c1); + sum0 = _mm256_fmadd_ps(d0, d0, sum0); + sum1 = _mm256_fmadd_ps(d1, d1, sum1); + } + for (; i + 8 <= dim; i += 8) { + const __m128i bytes0 = _mm_loadl_epi64(reinterpret_cast(codes + i)); + const __m256 c0 = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(bytes0)); + const __m256 q0 = _mm256_mul_ps(_mm256_sub_ps(_mm256_loadu_ps(query + i), voffset), + vinv_scale); + const __m256 d0 = _mm256_sub_ps(q0, c0); + sum0 = _mm256_fmadd_ps(d0, d0, sum0); + } + + float sum = hsum256(_mm256_add_ps(sum0, sum1)); + for (; i < dim; ++i) { + const float q_normalized = (query[i] - offset) * inv_scale; + const float diff = q_normalized - static_cast(codes[i]); + sum += diff * diff; + } + return sum; +} + +// LVQ-4 squared L2 distance in quantized space (2 nibbles packed per byte) +SQLITE_VEC_TARGET_AVX2_FMA inline float lvq4_l2_sq_avx2(const float* query, + const std::uint8_t* codes, std::size_t dim, + float inv_scale, float offset) noexcept { + const __m256 voffset = _mm256_set1_ps(offset); + const __m256 vinv_scale = _mm256_set1_ps(inv_scale); + const __m128i mask_0f = _mm_set1_epi8(0x0F); + __m256 sum0 = _mm256_setzero_ps(); + __m256 sum1 = _mm256_setzero_ps(); + + std::size_t i = 0; + for (; i + 16 <= dim; i += 16) { + const __m128i packed = _mm_loadl_epi64(reinterpret_cast(codes + i / 2)); + const __m128i lo = _mm_and_si128(packed, mask_0f); + const __m128i hi = _mm_and_si128(_mm_srli_epi16(packed, 4), mask_0f); + const __m128i unpacked = _mm_unpacklo_epi8(lo, hi); + + const __m256 c0 = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(unpacked)); + const __m256 c1 = + _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(_mm_srli_si128(unpacked, 8))); + + const __m256 q0 = _mm256_mul_ps(_mm256_sub_ps(_mm256_loadu_ps(query + i), voffset), + vinv_scale); + const __m256 q1 = _mm256_mul_ps(_mm256_sub_ps(_mm256_loadu_ps(query + i + 8), voffset), + vinv_scale); + + const __m256 d0 = _mm256_sub_ps(q0, c0); + const __m256 d1 = _mm256_sub_ps(q1, c1); + sum0 = _mm256_fmadd_ps(d0, d0, sum0); + sum1 = _mm256_fmadd_ps(d1, d1, sum1); + } + + float sum = hsum256(_mm256_add_ps(sum0, sum1)); + for (; i < dim; ++i) { + const std::uint8_t c = + (i % 2 == 0) ? (codes[i / 2] & 0x0F) : ((codes[i / 2] >> 4) & 0x0F); + const float q_normalized = (query[i] - offset) * inv_scale; + const float diff = q_normalized - static_cast(c); + sum += diff * diff; + } + return sum; +} + } // namespace sqlite_vec_cpp::distances::x86 #endif diff --git a/meson.build b/meson.build index 0779839..af34287 100644 --- a/meson.build +++ b/meson.build @@ -319,6 +319,7 @@ install_headers( [ 'include/sqlite-vec-cpp/simd/avx.hpp', 'include/sqlite-vec-cpp/simd/neon.hpp', + 'include/sqlite-vec-cpp/simd/x86_dispatch.hpp', ], subdir: 'sqlite-vec-cpp/simd', ) From 19419e782fc17a389af29851542aadd99fe5468e Mon Sep 17 00:00:00 2001 From: trvon Date: Tue, 24 Nov 2026 10:20:54 -0700 Subject: [PATCH 2/3] perf(vec0): incremental ANN maintenance and cached prepared statements - Maintain ann_index incrementally on INSERT/UPDATE/DELETE when ann_ready is true (compact only on needs_compaction() or node ID reuse, with invalidation fallback on error) - Cache prepared statements on Vec0Table for xUpdate and xColumn fallback, resetting/clearing bindings per call and finalizing on xDisconnect/xDestroy --- include/sqlite-vec-cpp/sqlite/vec0_module.hpp | 230 ++++++++++++++---- 1 file changed, 182 insertions(+), 48 deletions(-) diff --git a/include/sqlite-vec-cpp/sqlite/vec0_module.hpp b/include/sqlite-vec-cpp/sqlite/vec0_module.hpp index aaf9c14..9fdb0fb 100644 --- a/include/sqlite-vec-cpp/sqlite/vec0_module.hpp +++ b/include/sqlite-vec-cpp/sqlite/vec0_module.hpp @@ -119,7 +119,44 @@ struct Vec0Table { bool ann_ready = false; mutable std::mutex ann_mutex; + // Cached prepared statements for xUpdate and xColumn (lazy-prepared, finalized on disconnect/destroy) + sqlite3_stmt* stmt_select_embedding = nullptr; + sqlite3_stmt* stmt_delete = nullptr; + sqlite3_stmt* stmt_insert_with_rowid = nullptr; + sqlite3_stmt* stmt_insert_auto_rowid = nullptr; + sqlite3_stmt* stmt_update = nullptr; + Vec0Table() = default; + + ~Vec0Table() { finalize_cached_stmts(); } + + void finalize_cached_stmts() { + auto fin = [](sqlite3_stmt*& s) { + if (s) { + sqlite3_finalize(s); + s = nullptr; + } + }; + fin(stmt_select_embedding); + fin(stmt_delete); + fin(stmt_insert_with_rowid); + fin(stmt_insert_auto_rowid); + fin(stmt_update); + } + + int prepare_cached_stmt(sqlite3_stmt*& slot, const std::string& sql) { + if (!slot) { + int rc = sqlite3_prepare_v2(db, sql.c_str(), -1, &slot, nullptr); + if (rc != SQLITE_OK) { + slot = nullptr; + return rc; + } + } else { + sqlite3_reset(slot); + sqlite3_clear_bindings(slot); + } + return SQLITE_OK; + } }; struct Vec0Cursor { @@ -196,6 +233,78 @@ inline void vec0_invalidate_ann_index(Vec0Table* table) { table->ann_ready = false; } +inline void vec0_ann_on_delete(Vec0Table* table, int64_t old_rowid) { + std::lock_guard lock(table->ann_mutex); + if (!table->ann_ready || !table->ann_index) { + return; + } + try { + table->ann_index->remove(static_cast(old_rowid)); + if (table->ann_index->needs_compaction()) { + table->ann_index = std::make_shared(table->ann_index->compact()); + } + } catch (...) { + table->ann_index.reset(); + table->ann_ready = false; + } +} + +inline void vec0_ann_on_insert(Vec0Table* table, int64_t new_rowid, const void* blob, int bytes) { + std::lock_guard lock(table->ann_mutex); + if (!table->ann_ready || !table->ann_index) { + return; + } + if (!blob || bytes <= 0 || + static_cast(bytes) != table->dimensions * sizeof(float)) { + return; + } + try { + std::vector vec(table->dimensions); + std::memcpy(vec.data(), blob, static_cast(bytes)); + const size_t id = static_cast(new_rowid); + // If this rowid still exists in nodes_ (e.g., previously soft-deleted and now reused), + // compact first so insert() registers the new vector cleanly instead of no-oping. + if (table->ann_index->get_node(id) != nullptr) { + table->ann_index->remove(id); + table->ann_index = std::make_shared(table->ann_index->compact()); + } + table->ann_index->insert(id, std::span(vec)); + } catch (...) { + table->ann_index.reset(); + table->ann_ready = false; + } +} + +inline void vec0_ann_on_update(Vec0Table* table, int64_t old_rowid, int64_t new_rowid, + const void* blob, int bytes) { + std::lock_guard lock(table->ann_mutex); + if (!table->ann_ready || !table->ann_index) { + return; + } + try { + const size_t old_id = static_cast(old_rowid); + const size_t new_id = static_cast(new_rowid); + table->ann_index->remove(old_id); + + if (blob && bytes > 0 && static_cast(bytes) == table->dimensions * sizeof(float)) { + std::vector vec(table->dimensions); + std::memcpy(vec.data(), blob, static_cast(bytes)); + if (table->ann_index->get_node(new_id) != nullptr) { + table->ann_index->remove(new_id); + table->ann_index = std::make_shared(table->ann_index->compact()); + } + table->ann_index->insert(new_id, std::span(vec)); + } + + if (table->ann_index->needs_compaction()) { + table->ann_index = std::make_shared(table->ann_index->compact()); + } + } catch (...) { + table->ann_index.reset(); + table->ann_ready = false; + } +} + inline Result> vec0_ensure_ann_index(Vec0Table* table) { std::lock_guard lock(table->ann_mutex); if (table->ann_ready && table->ann_index) { @@ -662,6 +771,7 @@ inline int vec0Connect(sqlite3* db, void* pAux, int argc, const char* const* arg inline int vec0Disconnect(sqlite3_vtab* pVTab) { auto* table = reinterpret_cast(pVTab); vec0_registry_remove(table->db, table->schema_name, table->table_name); + table->finalize_cached_stmts(); delete table; return SQLITE_OK; } @@ -670,6 +780,8 @@ inline int vec0Disconnect(sqlite3_vtab* pVTab) { inline int vec0Destroy(sqlite3_vtab* pVTab) { auto* table = reinterpret_cast(pVTab); vec0_registry_remove(table->db, table->schema_name, table->table_name); + // Finalize cached statements before dropping shadow tables + table->finalize_cached_stmts(); // Drop shadow tables std::ostringstream drop_meta; @@ -1082,17 +1194,15 @@ inline int vec0Column(sqlite3_vtab_cursor* pCursor, sqlite3_context* ctx, int co } } - sqlite3_stmt* stmt = nullptr; std::string sql = "SELECT \"" + cursor->table->embedding_column + "\" FROM " + vec0_vectors_table_name(*cursor->table) + " WHERE rowid=?"; - int rc = sqlite3_prepare_v2(cursor->table->db, sql.c_str(), -1, &stmt, nullptr); - if (rc != SQLITE_OK || !stmt) { + int rc = + cursor->table->prepare_cached_stmt(cursor->table->stmt_select_embedding, sql); + if (rc != SQLITE_OK || !cursor->table->stmt_select_embedding) { sqlite3_result_null(ctx); - if (stmt) { - sqlite3_finalize(stmt); - } return SQLITE_OK; } + sqlite3_stmt* stmt = cursor->table->stmt_select_embedding; sqlite3_bind_int64(stmt, 1, cursor->current_rowid); rc = sqlite3_step(stmt); if (rc == SQLITE_ROW) { @@ -1106,7 +1216,8 @@ inline int vec0Column(sqlite3_vtab_cursor* pCursor, sqlite3_context* ctx, int co } else { sqlite3_result_null(ctx); } - sqlite3_finalize(stmt); + sqlite3_reset(stmt); + sqlite3_clear_bindings(stmt); return SQLITE_OK; } @@ -1158,20 +1269,27 @@ inline int vec0Update(sqlite3_vtab* pVTab, int argc, sqlite3_value** argv, sqlit // DELETE: argc==1, argv[0]=old_rowid if (argc == 1) { - sqlite3_stmt* stmt = nullptr; - std::ostringstream sql; - sql << "DELETE FROM \"" << table->schema_name << "\".\"" << table->table_name - << "_vectors\" WHERE rowid=?"; - int rc = sqlite3_prepare_v2(table->db, sql.str().c_str(), -1, &stmt, nullptr); - if (rc != SQLITE_OK) { - return rc; + const int64_t old_rowid = sqlite3_value_int64(argv[0]); + if (!table->stmt_delete) { + std::ostringstream sql; + sql << "DELETE FROM \"" << table->schema_name << "\".\"" << table->table_name + << "_vectors\" WHERE rowid=?"; + int prep_rc = table->prepare_cached_stmt(table->stmt_delete, sql.str()); + if (prep_rc != SQLITE_OK) { + return prep_rc; + } + } else { + sqlite3_reset(table->stmt_delete); + sqlite3_clear_bindings(table->stmt_delete); } - sqlite3_bind_int64(stmt, 1, sqlite3_value_int64(argv[0])); - rc = sqlite3_step(stmt); - sqlite3_finalize(stmt); + sqlite3_stmt* stmt = table->stmt_delete; + sqlite3_bind_int64(stmt, 1, old_rowid); + int rc = sqlite3_step(stmt); + sqlite3_reset(stmt); + sqlite3_clear_bindings(stmt); if (rc == SQLITE_DONE) { - vec0_invalidate_ann_index(table); + vec0_ann_on_delete(table, old_rowid); return SQLITE_OK; } return rc; @@ -1235,23 +1353,31 @@ inline int vec0Update(sqlite3_vtab* pVTab, int argc, sqlite3_value** argv, sqlit } if (is_insert) { - std::ostringstream sql; - if (has_declared_rowid || has_new_rowid) { - sql << "INSERT INTO \"" << table->schema_name << "\".\"" << table->table_name - << "_vectors\" (rowid, \"" << table->embedding_column << "\") VALUES (?, ?)"; + const bool explicit_rowid = (has_declared_rowid || has_new_rowid); + sqlite3_stmt*& slot = + explicit_rowid ? table->stmt_insert_with_rowid : table->stmt_insert_auto_rowid; + if (!slot) { + std::ostringstream sql; + if (explicit_rowid) { + sql << "INSERT INTO \"" << table->schema_name << "\".\"" << table->table_name + << "_vectors\" (rowid, \"" << table->embedding_column + << "\") VALUES (?, ?)"; + } else { + sql << "INSERT INTO \"" << table->schema_name << "\".\"" << table->table_name + << "_vectors\" (\"" << table->embedding_column << "\") VALUES (?)"; + } + int prep_rc = table->prepare_cached_stmt(slot, sql.str()); + if (prep_rc != SQLITE_OK) { + return prep_rc; + } } else { - sql << "INSERT INTO \"" << table->schema_name << "\".\"" << table->table_name - << "_vectors\" (\"" << table->embedding_column << "\") VALUES (?)"; - } - - sqlite3_stmt* stmt; - int rc = sqlite3_prepare_v2(table->db, sql.str().c_str(), -1, &stmt, nullptr); - if (rc != SQLITE_OK) { - return rc; + sqlite3_reset(slot); + sqlite3_clear_bindings(slot); } + sqlite3_stmt* stmt = slot; int bind_idx = 1; - if (has_declared_rowid || has_new_rowid) { + if (explicit_rowid) { sqlite3_bind_int64(stmt, bind_idx++, new_rowid); } @@ -1261,30 +1387,37 @@ inline int vec0Update(sqlite3_vtab* pVTab, int argc, sqlite3_value** argv, sqlit sqlite3_bind_null(stmt, bind_idx); } - rc = sqlite3_step(stmt); + int rc = sqlite3_step(stmt); + int64_t inserted_rowid = new_rowid; if (rc == SQLITE_DONE) { - *pRowid = (has_declared_rowid || has_new_rowid) - ? new_rowid - : sqlite3_last_insert_rowid(table->db); + inserted_rowid = + explicit_rowid ? new_rowid : sqlite3_last_insert_rowid(table->db); + *pRowid = inserted_rowid; rc = SQLITE_OK; } - sqlite3_finalize(stmt); + sqlite3_reset(stmt); + sqlite3_clear_bindings(stmt); if (rc == SQLITE_OK) { - vec0_invalidate_ann_index(table); + vec0_ann_on_insert(table, inserted_rowid, blob, bytes); } return rc; } else { - std::ostringstream sql; - sql << "UPDATE \"" << table->schema_name << "\".\"" << table->table_name - << "_vectors\" SET rowid=?, \"" << table->embedding_column << "\"=? WHERE rowid=?"; - - sqlite3_stmt* stmt; - int rc = sqlite3_prepare_v2(table->db, sql.str().c_str(), -1, &stmt, nullptr); - if (rc != SQLITE_OK) { - return rc; + if (!table->stmt_update) { + std::ostringstream sql; + sql << "UPDATE \"" << table->schema_name << "\".\"" << table->table_name + << "_vectors\" SET rowid=?, \"" << table->embedding_column + << "\"=? WHERE rowid=?"; + int prep_rc = table->prepare_cached_stmt(table->stmt_update, sql.str()); + if (prep_rc != SQLITE_OK) { + return prep_rc; + } + } else { + sqlite3_reset(table->stmt_update); + sqlite3_clear_bindings(table->stmt_update); } + sqlite3_stmt* stmt = table->stmt_update; sqlite3_bind_int64(stmt, 1, new_rowid); if (blob && bytes > 0) { @@ -1295,15 +1428,16 @@ inline int vec0Update(sqlite3_vtab* pVTab, int argc, sqlite3_value** argv, sqlit sqlite3_bind_int64(stmt, 3, old_rowid); - rc = sqlite3_step(stmt); + int rc = sqlite3_step(stmt); if (rc == SQLITE_DONE) { *pRowid = new_rowid; rc = SQLITE_OK; } - sqlite3_finalize(stmt); + sqlite3_reset(stmt); + sqlite3_clear_bindings(stmt); if (rc == SQLITE_OK) { - vec0_invalidate_ann_index(table); + vec0_ann_on_update(table, old_rowid, new_rowid, blob, bytes); } return rc; } From 5dbc97472f279d5bd8710002162630d39563bd8d Mon Sep 17 00:00:00 2001 From: trvon Date: Tue, 24 Nov 2026 10:20:54 -0700 Subject: [PATCH 3/3] feat(hnsw,tests): add optional SearchStats telemetry and invariant/parity test suite - Add optional SearchStats* out-parameter (hops, distance_evals, rerank_evals, filter_rejections) to HNSW and quantized search methods with zero overhead when nullptr - Add tests/test_invariants.cpp covering L2/Hamming symmetry & triangle inequality, unaligned float/int8 spans, odd dimensions (1..769), SIMD-vs-scalar parity for L2/LVQ8/LVQ4/RaBitQ, SearchStats telemetry, and incremental vec0 insert/update/delete recall parity --- include/sqlite-vec-cpp/index/hnsw.hpp | 134 ++++-- tests/meson.build | 13 + tests/test_invariants.cpp | 575 ++++++++++++++++++++++++++ 3 files changed, 688 insertions(+), 34 deletions(-) create mode 100644 tests/test_invariants.cpp diff --git a/include/sqlite-vec-cpp/index/hnsw.hpp b/include/sqlite-vec-cpp/index/hnsw.hpp index 4fdcb48..40dc214 100644 --- a/include/sqlite-vec-cpp/index/hnsw.hpp +++ b/include/sqlite-vec-cpp/index/hnsw.hpp @@ -49,6 +49,14 @@ namespace sqlite_vec_cpp::index { // Forward declaration for friend access template class HNSWQuantizedSearch; +/// Optional search telemetry counters (zero overhead when nullptr is passed). +struct SearchStats { + size_t hops = 0; ///< Nodes expanded during graph traversal + size_t distance_evals = 0; ///< Distance evaluations during graph traversal + size_t rerank_evals = 0; ///< Exact distance evaluations during reranking + size_t filter_rejections = 0; ///< Candidates rejected by filter or soft-delete +}; + /// Hierarchical Navigable Small World (HNSW) index for approximate nearest neighbor search /// Provides 100-1000x speedup over brute-force for large corpora (>100K vectors) /// @@ -506,10 +514,12 @@ template class HNSWIndex { /// @param ef_search Exploration factor (higher = better recall, slower) /// @return Vector of (id, distance) pairs, sorted by distance using FilterFn = std::function; + using SearchStats = sqlite_vec_cpp::index::SearchStats; std::vector> search(std::span query, size_t k, - size_t ef_search = 50) const { - return search_with_filter(query, k, ef_search, nullptr); + size_t ef_search = 50, + SearchStats* stats = nullptr) const { + return search_with_filter(query, k, ef_search, nullptr, stats); } /// Search with pre-filtering @@ -517,11 +527,13 @@ template class HNSWIndex { /// @param k Number of neighbors to return /// @param ef_search Exploration factor (higher = better recall, slower) /// @param filter Optional filter function: returns true if node should be included + /// @param stats Optional search telemetry output (zero overhead when nullptr) /// @return Vector of (id, distance) pairs, sorted by distance std::vector> search_with_filter(std::span query, size_t k, size_t ef_search, - const FilterFn& filter) const { - return search_with_filter_impl(query, k, ef_search, filter); + const FilterFn& filter, + SearchStats* stats = nullptr) const { + return search_with_filter_impl(query, k, ef_search, filter, {}, stats); } /// Search optimized for read-mostly workloads. @@ -529,48 +541,51 @@ template class HNSWIndex { /// neighbor vector copies. Do not use concurrently with unlocked bulk-build or /// single-threaded insert APIs that mutate graph edges without taking nodes_mutex_. std::vector> search_read_mostly(std::span query, size_t k, - size_t ef_search = 50) const { - return search_read_mostly_with_filter(query, k, ef_search, nullptr); + size_t ef_search = 50, + SearchStats* stats = nullptr) const { + return search_read_mostly_with_filter(query, k, ef_search, nullptr, stats); } std::vector> search_phss_rerank(std::span query, size_t k, size_t ef_search, - const PhssRerankConfig& cfg) const { - return search_phss_rerank_with_filter(query, k, ef_search, cfg, nullptr); + const PhssRerankConfig& cfg, + SearchStats* stats = nullptr) const { + return search_phss_rerank_with_filter(query, k, ef_search, cfg, nullptr, {}, stats); } /// Read-mostly search with pre-filtering. std::vector> search_read_mostly_with_filter(std::span query, size_t k, size_t ef_search, - const FilterFn& filter) const { - return search_with_filter_impl(query, k, ef_search, filter); + const FilterFn& filter, SearchStats* stats = nullptr) const { + return search_with_filter_impl(query, k, ef_search, filter, {}, stats); } /// Read-mostly filtered search seeded from route-specific entry points. Entry points /// participate in the same bounded beam; they do not increase ef_search. std::vector> search_read_mostly_with_filter_from_entries( std::span query, size_t k, size_t ef_search, const FilterFn& filter, - std::span entry_points) const { - return search_with_filter_impl(query, k, ef_search, filter, entry_points); + std::span entry_points, SearchStats* stats = nullptr) const { + return search_with_filter_impl(query, k, ef_search, filter, entry_points, stats); } std::vector> search_phss_rerank_with_filter(std::span query, size_t k, size_t ef_search, const PhssRerankConfig& cfg, const FilterFn& filter, - std::span entry_points = {}) const { + std::span entry_points = {}, + SearchStats* stats = nullptr) const { if (!cfg.enabled) { return entry_points.empty() - ? search_read_mostly_with_filter(query, k, ef_search, filter) + ? search_read_mostly_with_filter(query, k, ef_search, filter, stats) : search_read_mostly_with_filter_from_entries(query, k, ef_search, filter, - entry_points); + entry_points, stats); } const size_t candidate_k = std::max(k, cfg.candidates); - auto approx_candidates = entry_points.empty() - ? search_read_mostly_with_filter(query, candidate_k, ef_search, - filter) - : search_read_mostly_with_filter_from_entries( - query, candidate_k, ef_search, filter, entry_points); + auto approx_candidates = + entry_points.empty() + ? search_read_mostly_with_filter(query, candidate_k, ef_search, filter, stats) + : search_read_mostly_with_filter_from_entries(query, candidate_k, ef_search, filter, + entry_points, stats); if (approx_candidates.size() <= k) { return approx_candidates; } @@ -622,6 +637,9 @@ template class HNSWIndex { const auto* nj = candidate_nodes[j]; if (ni && nj) { const float d = distance_nodes(*ni, *nj); + if (stats) { + ++stats->rerank_evals; + } sim = 1.0f / (1.0f + std::max(0.0f, d)); } sims_tri[tri_index(i, j)] = sim; @@ -1459,11 +1477,13 @@ template class HNSWIndex { } template - std::vector> search_with_filter_impl(std::span query, - size_t k, size_t ef_search, - const FilterFn& filter, - std::span - preferred_entries = {}) const { + std::vector> search_with_filter_impl( + std::span query, size_t k, size_t ef_search, const FilterFn& filter, + std::span preferred_entries = {}, SearchStats* stats = nullptr) const { + if (stats) { + *stats = {}; + } + std::vector norm_query; std::span effective_query = query; if (config_.normalize_vectors) { @@ -1489,12 +1509,12 @@ template class HNSWIndex { } else { for (size_t lc = entry_point_layer_.load(std::memory_order_acquire); lc > 0; --lc) { current = greedy_search_layer_shared(effective_query, current, lc, - filter_ptr); + filter_ptr, stats); } } - auto candidates = beam_search_layer_shared(effective_query, current, ef_search, - 0, filter_ptr, additional_entries); + auto candidates = beam_search_layer_shared( + effective_query, current, ef_search, 0, filter_ptr, additional_entries, stats); if (candidates.size() > k) { candidates.resize(k); @@ -1988,7 +2008,8 @@ template class HNSWIndex { template size_t greedy_search_layer_shared(std::span query, size_t entry_point, - size_t layer, const FilterFn* filter) const { + size_t layer, const FilterFn* filter, + SearchStats* stats = nullptr) const { // Small negative threshold to handle floating-point error in distance calculation const float kDistanceEpsilon = config_.clamp_negative_distances ? -1e-5f : std::numeric_limits::lowest(); @@ -1998,6 +2019,9 @@ template class HNSWIndex { if (!initial_node) return current; float current_dist = comparable_distance_query_node(query, *initial_node); + if (stats) { + ++stats->distance_evals; + } const bool check_deleted = !deleted_ids_.empty(); auto passes_filter = [&](size_t id) { @@ -2015,6 +2039,9 @@ template class HNSWIndex { const auto* current_node = try_get_node(current); if (!current_node) break; + if (stats) { + ++stats->hops; + } const auto& neighbors = search_neighbors(*current_node, layer); @@ -2035,6 +2062,9 @@ template class HNSWIndex { if (!neighbor_node) continue; float neighbor_dist = comparable_distance_query_node(query, *neighbor_node); + if (stats) { + ++stats->distance_evals; + } if (!(neighbor_dist >= kDistanceEpsilon && neighbor_dist < current_dist)) continue; current = neighbor; @@ -2073,7 +2103,8 @@ template class HNSWIndex { std::vector> beam_search_layer_shared(std::span query, size_t entry_point, size_t ef, size_t layer, const FilterFn* filter, - std::span additional_entry_points = {}) const { + std::span additional_entry_points = {}, + SearchStats* stats = nullptr) const { auto cmp = [](const auto& a, const auto& b) { return a.first < b.first; }; std::vector> top_storage; top_storage.reserve(ef + 1); @@ -2116,6 +2147,9 @@ template class HNSWIndex { return; } const float distance = comparable_distance_query_node(query, *node); + if (stats) { + ++stats->distance_evals; + } if (distance < kDistanceEpsilon) { return; } @@ -2132,6 +2166,8 @@ template class HNSWIndex { if (top_candidates.size() > ef) { top_candidates.pop(); } + } else if (stats) { + ++stats->filter_rejections; } }; add_entry_point(entry_point); @@ -2154,6 +2190,9 @@ template class HNSWIndex { exploration_bound.size() >= ef) { break; } + if (stats) { + ++stats->hops; + } // Get neighbors and filter out already-visited ones const auto& neighbors = search_neighbors(*current_node, layer); @@ -2204,6 +2243,9 @@ template class HNSWIndex { } float neighbor_dist = comparable_distance_query_node(query, *neighbor_node); + if (stats) { + ++stats->distance_evals; + } if (neighbor_dist < kDistanceEpsilon) continue; @@ -2231,6 +2273,8 @@ template class HNSWIndex { top_candidates.pop(); } } + } else if (stats) { + ++stats->filter_rejections; } } } @@ -2282,7 +2326,12 @@ template class HNSWIndex { std::vector> search_quantized_rerank(std::span query, size_t k, size_t ef_search, size_t rerank_factor, ApproxDistFn&& approx_dist, - PrefetchFn&& prefetch_fn, const FilterFn& filter = nullptr) const { + PrefetchFn&& prefetch_fn, const FilterFn& filter = nullptr, + SearchStats* stats = nullptr) const { + if (stats) { + *stats = {}; + } + std::vector norm_query; std::span effective_query = query; if (config_.normalize_vectors) { @@ -2304,12 +2353,13 @@ template class HNSWIndex { // Stage 1: Greedy descent through upper layers (cheap, use FP32) size_t current = entry_point_id_.load(std::memory_order_acquire); for (size_t lc = entry_point_layer_.load(std::memory_order_acquire); lc > 0; --lc) { - current = greedy_search_layer_shared(effective_query, current, lc, filter_ptr); + current = greedy_search_layer_shared(effective_query, current, lc, filter_ptr, + stats); } // Stage 2: Beam search at layer 0 using quantized distances auto approx_candidates = beam_search_layer_quantized( - effective_query, current, expanded_ef, 0, filter_ptr, approx_dist, prefetch_fn); + effective_query, current, expanded_ef, 0, filter_ptr, approx_dist, prefetch_fn, stats); // Stage 3: Rerank with exact FP32 distances std::vector> reranked; @@ -2320,6 +2370,9 @@ template class HNSWIndex { if (!node) continue; float exact_dist = distance_query_node(effective_query, *node); + if (stats) { + ++stats->rerank_evals; + } reranked.emplace_back(id, exact_dist); } @@ -2344,7 +2397,7 @@ template class HNSWIndex { std::vector> beam_search_layer_quantized(std::span query, size_t entry_point, size_t ef, size_t layer, const FilterFn* filter, ApproxDistFn&& approx_dist, - PrefetchFn&& prefetch_fn) const { + PrefetchFn&& prefetch_fn, SearchStats* stats = nullptr) const { auto cmp = [](const auto& a, const auto& b) { return a.first < b.first; }; std::priority_queue, std::vector>, decltype(cmp)> @@ -2369,6 +2422,9 @@ template class HNSWIndex { return {}; float entry_dist = approx_dist(query, entry_dense); + if (stats) { + ++stats->distance_evals; + } candidates.emplace(entry_dist, entry_point); visited.visit(entry_dense); @@ -2385,6 +2441,8 @@ template class HNSWIndex { exploration_bound.emplace(score, entry_point); if (passes_filter(entry_point)) { top_candidates.emplace(score, entry_point); + } else if (stats) { + ++stats->filter_rejections; } } @@ -2400,6 +2458,9 @@ template class HNSWIndex { exploration_bound.size() >= ef) { break; } + if (stats) { + ++stats->hops; + } // Read-mostly: direct reference, no mutex, no copy const auto& neighbors = current_node->neighbors_unlocked(layer); @@ -2447,6 +2508,9 @@ template class HNSWIndex { } float neighbor_dist = approx_dist(query, neighbor_dense); + if (stats) { + ++stats->distance_evals; + } if (neighbor_dist < kDistanceEpsilon) continue; @@ -2473,6 +2537,8 @@ template class HNSWIndex { top_candidates.pop(); } } + } else if (stats) { + ++stats->filter_rejections; } } } diff --git a/tests/meson.build b/tests/meson.build index 5b38952..b7dcc07 100644 --- a/tests/meson.build +++ b/tests/meson.build @@ -127,3 +127,16 @@ test_overflow = executable( cpp_args: test_cpp_args + ['-DSQLITE_VEC_CPP_ENABLED'], ) test('vec0 Overflow & Validation', test_overflow, timeout: 120) + +test_invariants = executable( + 'test_invariants', + 'test_invariants.cpp', + include_directories: inc_dirs, + sources: [ + 'test_invariants.cpp', + '../src/sqlite_vec_c_api.cpp', + ], + dependencies: [sqlite3_dep], + cpp_args: test_cpp_args + ['-DSQLITE_VEC_CPP_ENABLED'], +) +test('Invariants, SIMD Parity, SearchStats & Incremental vec0', test_invariants, timeout: 120) diff --git a/tests/test_invariants.cpp b/tests/test_invariants.cpp new file mode 100644 index 0000000..b56a750 --- /dev/null +++ b/tests/test_invariants.cpp @@ -0,0 +1,575 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +// Invariant, SIMD-vs-scalar parity, SearchStats telemetry, and incremental vec0 tests + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#define INV_CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::cerr << "CHECK FAILED at " << __FILE__ << ":" << __LINE__ << ": " #cond \ + << std::endl; \ + std::abort(); \ + } \ + } while (0) + +using namespace sqlite_vec_cpp::distances; +using namespace sqlite_vec_cpp::index; +using namespace sqlite_vec_cpp::quantization; +using namespace sqlite_vec_cpp::sqlite; +namespace qdetail = sqlite_vec_cpp::quantization::detail; + +namespace { + +constexpr size_t kOddDims[] = {1, 7, 15, 17, 31, 33, 385, 769}; + +bool rel_approx_equal(float a, float b, float rel_tol = 1e-4f, float abs_tol = 1e-4f) { + const float diff = std::abs(a - b); + return diff <= abs_tol + rel_tol * std::max(std::abs(a), std::abs(b)); +} + +std::vector make_random_f32(size_t dim, std::mt19937& rng, float lo = -5.0f, + float hi = 5.0f) { + std::uniform_real_distribution dist(lo, hi); + std::vector v(dim); + for (auto& x : v) { + x = dist(rng); + } + return v; +} + +std::vector make_random_i8(size_t dim, std::mt19937& rng) { + std::uniform_int_distribution dist(-128, 127); + std::vector v(dim); + for (auto& x : v) { + x = static_cast(dist(rng)); + } + return v; +} + +std::vector make_random_bytes(size_t n, std::mt19937& rng) { + std::uniform_int_distribution dist(0, 255); + std::vector v(n); + for (auto& x : v) { + x = static_cast(dist(rng)); + } + return v; +} + +// 1. Triangle inequality & symmetry for L2 and Hamming +void test_metric_invariants() { + std::cout << "Testing L2 and Hamming metric invariants (symmetry + triangle inequality)..." + << std::endl; + std::mt19937 rng(2026); + + for (size_t dim : kOddDims) { + auto a = make_random_f32(dim, rng); + auto b = make_random_f32(dim, rng); + auto c = make_random_f32(dim, rng); + + const float d_aa = l2_distance(std::span(a), std::span(a)); + const float d_ab = l2_distance(std::span(a), std::span(b)); + const float d_ba = l2_distance(std::span(b), std::span(a)); + const float d_bc = l2_distance(std::span(b), std::span(c)); + const float d_ac = l2_distance(std::span(a), std::span(c)); + + INV_CHECK(d_aa == 0.0f); + INV_CHECK(d_ab >= 0.0f); + INV_CHECK(rel_approx_equal(d_ab, d_ba, 1e-5f, 1e-5f)); + INV_CHECK(d_ac <= d_ab + d_bc + 1e-3f); + + // int8 L2 + auto ia = make_random_i8(dim, rng); + auto ib = make_random_i8(dim, rng); + auto ic = make_random_i8(dim, rng); + const float id_aa = l2_distance(std::span(ia), std::span(ia)); + const float id_ab = l2_distance(std::span(ia), std::span(ib)); + const float id_ba = l2_distance(std::span(ib), std::span(ia)); + const float id_bc = l2_distance(std::span(ib), std::span(ic)); + const float id_ac = l2_distance(std::span(ia), std::span(ic)); + INV_CHECK(id_aa == 0.0f); + INV_CHECK(id_ab >= 0.0f); + INV_CHECK(rel_approx_equal(id_ab, id_ba, 1e-5f, 1e-5f)); + INV_CHECK(id_ac <= id_ab + id_bc + 1e-2f); + } + + // Hamming across both 64-bit-aligned and odd bit lengths + for (size_t bits : {size_t{7}, size_t{15}, size_t{33}, size_t{64}, size_t{128}, size_t{256}, + size_t{385}, size_t{512}}) { + const size_t bytes = (bits + 7) / 8; + auto a = make_random_bytes(bytes, rng); + auto b = make_random_bytes(bytes, rng); + auto c = make_random_bytes(bytes, rng); + + HammingMetric metric(bits); + const float d_aa = metric(std::span(a), std::span(a)); + const float d_ab = metric(std::span(a), std::span(b)); + const float d_ba = metric(std::span(b), std::span(a)); + const float d_bc = metric(std::span(b), std::span(c)); + const float d_ac = metric(std::span(a), std::span(c)); + + INV_CHECK(d_aa == 0.0f); + INV_CHECK(d_ab >= 0.0f); + INV_CHECK(d_ab == d_ba); + INV_CHECK(d_ac <= d_ab + d_bc); + } + + std::cout << " PASS: metric invariants" << std::endl; +} + +// 2. Unaligned float* and int8_t* spans + odd dimensions SIMD-vs-scalar parity +void test_unaligned_and_simd_scalar_parity() { + std::cout << "Testing unaligned spans and SIMD-vs-scalar L2 parity across odd dims..." + << std::endl; + std::mt19937 rng(777); + + for (size_t dim : kOddDims) { + // Allocate with extra padding so we can test non-16/32-byte aligned float offsets + std::vector a_buf = make_random_f32(dim + 7, rng); + std::vector b_buf = make_random_f32(dim + 7, rng); + + for (size_t offset : {size_t{0}, size_t{1}, size_t{2}, size_t{3}}) { + std::span a(a_buf.data() + offset, dim); + std::span b(b_buf.data() + ((offset + 1) % 4), dim); + + const float sq_simd = l2_squared_distance(a, b); + const float sq_scalar = l2_squared_distance_float(a, b); + INV_CHECK(rel_approx_equal(sq_simd, sq_scalar, 1e-4f, 1e-4f)); + + const float d_simd = l2_distance(a, b); + const float d_scalar = l2_distance_float(a, b); + INV_CHECK(rel_approx_equal(d_simd, d_scalar, 1e-4f, 1e-4f)); + INV_CHECK(rel_approx_equal(d_simd * d_simd, sq_simd, 1e-3f, 1e-3f)); + } + + // Unaligned int8_t spans at odd byte offsets + std::vector ia_buf = make_random_i8(dim + 15, rng); + std::vector ib_buf = make_random_i8(dim + 15, rng); + for (size_t offset : {size_t{0}, size_t{1}, size_t{3}, size_t{5}, size_t{7}}) { + std::span ia(ia_buf.data() + offset, dim); + std::span ib(ib_buf.data() + ((offset + 2) % 7), dim); + + const float sq_dispatch = l2_squared_distance(ia, ib); + const float sq_scalar = l2_squared_distance_int(ia, ib); + INV_CHECK(rel_approx_equal(sq_dispatch, sq_scalar, 1e-5f, 1e-5f)); + + const float d_dispatch = l2_distance(ia, ib); + const float d_scalar = l2_distance_int(ia, ib); + INV_CHECK(rel_approx_equal(d_dispatch, d_scalar, 1e-5f, 1e-5f)); + } + } + + std::cout << " PASS: unaligned spans & SIMD-vs-scalar L2 parity" << std::endl; +} + +// 3. Quantized store parity across odd dimensions (LVQ8, LVQ4, RaBitQ) + fused 4-plane popcount +void test_quantized_stores_odd_dims_parity() { + std::cout << "Testing LVQ8Store, LVQ4Store, RaBitQStore parity across odd dims..." << std::endl; + std::mt19937 rng(999); + + for (size_t dim : kOddDims) { + constexpr size_t kN = 16; + QuantizationSnapshot snap; + snap.dim = dim; + snap.generation = 1; + snap.entries.reserve(kN); + std::vector> corpus; + std::vector> corpus_spans; + corpus.reserve(kN); + corpus_spans.reserve(kN); + + for (size_t i = 0; i < kN; ++i) { + corpus.push_back(make_random_f32(dim, rng, -2.0f, 2.0f)); + corpus_spans.emplace_back(corpus.back()); + snap.entries.push_back({i, corpus.back()}); + } + + // Unaligned query slice + std::vector q_buf = make_random_f32(dim + 5, rng, -2.0f, 2.0f); + std::span query(q_buf.data() + 1, dim); + + // LVQ8Store + LVQ8Store lvq8; + lvq8.build(snap); + INV_CHECK(lvq8.inv_scales.size() == kN); + for (size_t i = 0; i < kN; ++i) { + auto ref_code = LVQ8::encode(std::span(corpus[i])); + const float ref_dist = LVQ8::l2_distance(query, ref_code); + const float store_dist = lvq8.l2_distance(query, i); + const float store_sq = lvq8.l2_distance_squared(query, i); + INV_CHECK(rel_approx_equal(store_dist, ref_dist, 1e-4f, 1e-4f)); + INV_CHECK(rel_approx_equal(std::sqrt(store_sq), store_dist, 1e-5f, 1e-5f)); + } + + // LVQ4Store + LVQ4Store lvq4; + lvq4.build(snap); + INV_CHECK(lvq4.inv_scales.size() == kN); + for (size_t i = 0; i < kN; ++i) { + auto ref_code = LVQ4::encode(std::span(corpus[i])); + const float ref_dist = LVQ4::l2_distance(query, ref_code, dim); + const float store_dist = lvq4.l2_distance(query, i); + const float store_sq = lvq4.l2_distance_squared(query, i); + INV_CHECK(rel_approx_equal(store_dist, ref_dist, 1e-4f, 1e-4f)); + INV_CHECK(rel_approx_equal(std::sqrt(store_sq), store_dist, 1e-5f, 1e-5f)); + } + + // RaBitQStore vs RaBitQ standalone + popcount & 4-plane kernel parity + RaBitQStore rabitq_store; + rabitq_store.build(snap); + INV_CHECK(rabitq_store.code_popcount.size() == kN); + + auto centroid = RaBitQ::compute_centroid(corpus_spans); + RaBitQ rabitq_ref(centroid, kRaBitQDefaultSeed); + auto ref_qs = rabitq_ref.prepare_query(query); + auto store_qs = rabitq_store.prepare_query(query); + + for (size_t i = 0; i < kN; ++i) { + auto ref_code = rabitq_ref.encode(corpus_spans[i]); + const uint8_t* code_ptr = rabitq_store.bits.data() + i * rabitq_store.bytes_per_vec; + const size_t nb = rabitq_store.bytes_per_vec; + + // Precomputed popcount matches full popcount + INV_CHECK(rabitq_store.code_popcount[i] == qdetail::popcount_bytes(code_ptr, nb)); + INV_CHECK(ref_code.code_popcount == qdetail::popcount_bytes(ref_code.bits.data(), nb)); + + // Fused 4-plane popcount matches naive 4-pass AND-popcount + uint64_t naive_su = 0; + for (size_t j = 0; j < 4; ++j) { + naive_su += static_cast(1u << j) * + qdetail::and_popcount_bytes(code_ptr, store_qs.planes.data() + j * nb, + nb); + } + const uint64_t fused_su = + qdetail::and_popcount_4planes(code_ptr, store_qs.planes.data(), nb); + INV_CHECK(fused_su == naive_su); + + const float ref_dist = rabitq_ref.estimate_l2_distance(ref_qs, ref_code); + const float store_dist = rabitq_store.l2_distance(store_qs, i); + const float store_sq = rabitq_store.l2_distance_squared(store_qs, i); + INV_CHECK(rel_approx_equal(store_dist, ref_dist, 1e-4f, 1e-4f)); + INV_CHECK(rel_approx_equal(std::sqrt(store_sq), store_dist, 1e-5f, 1e-5f)); + } + } + + std::cout << " PASS: quantized stores odd-dims & popcount parity" << std::endl; +} + +// 4. HNSW SearchStats telemetry tests +void test_hnsw_search_stats() { + std::cout << "Testing HNSW SearchStats telemetry..." << std::endl; + std::mt19937 rng(12345); + constexpr size_t kDim = 32; + constexpr size_t kN = 200; + + HNSWIndex>::Config cfg; + cfg.M = 12; + cfg.M_max = 12; + cfg.M_max_0 = 24; + cfg.ef_construction = 64; + cfg.random_seed = 42; + HNSWIndex> index(cfg); + + std::vector> corpus; + corpus.reserve(kN); + for (size_t i = 0; i < kN; ++i) { + corpus.push_back(make_random_f32(kDim, rng, -1.0f, 1.0f)); + index.insert_single_threaded(i, std::span(corpus.back())); + } + + auto query = make_random_f32(kDim, rng, -1.0f, 1.0f); + + // Unfiltered search with and without stats must match identically + auto res_no_stats = index.search(query, 10, 32); + SearchStats stats{}; + auto res_with_stats = index.search(query, 10, 32, &stats); + INV_CHECK(res_no_stats == res_with_stats); + INV_CHECK(stats.hops > 0); + INV_CHECK(stats.distance_evals >= stats.hops); + INV_CHECK(stats.rerank_evals == 0); + INV_CHECK(stats.filter_rejections == 0); + + // Filtered search should record filter_rejections + SearchStats filtered_stats{}; + auto res_filtered = index.search_with_filter( + query, 10, 32, [](size_t id) { return (id % 2) == 0; }, &filtered_stats); + INV_CHECK(!res_filtered.empty()); + for (const auto& [id, d] : res_filtered) { + INV_CHECK((id % 2) == 0); + } + INV_CHECK(filtered_stats.hops > 0); + INV_CHECK(filtered_stats.distance_evals > 0); + INV_CHECK(filtered_stats.filter_rejections > 0); + + // Quantized two-stage search should record rerank_evals + for (auto qtype : {QuantizationType::LVQ8, QuantizationType::LVQ4, QuantizationType::RaBitQ}) { + HNSWQuantizedSearch>::Config qcfg; + qcfg.quantization = qtype; + qcfg.rerank_factor = 2; + HNSWQuantizedSearch> qsearch(index, qcfg); + qsearch.build_quantization(); + + SearchStats qstats{}; + auto qres_no_stats = qsearch.search(query, 10, 24); + auto qres_stats = qsearch.search(query, 10, 24, &qstats); + INV_CHECK(qres_no_stats == qres_stats); + INV_CHECK(qstats.hops > 0); + INV_CHECK(qstats.distance_evals > 0); + INV_CHECK(qstats.rerank_evals >= qres_stats.size()); + } + + // PHSS rerank should record rerank_evals + HNSWIndex>::PhssRerankConfig phss_cfg; + phss_cfg.enabled = true; + phss_cfg.candidates = 20; + SearchStats phss_stats{}; + auto phss_res = index.search_phss_rerank(query, 5, 32, phss_cfg, &phss_stats); + INV_CHECK(phss_res.size() == 5); + INV_CHECK(phss_stats.hops > 0); + INV_CHECK(phss_stats.distance_evals > 0); + INV_CHECK(phss_stats.rerank_evals > 0); + + std::cout << " PASS: HNSW SearchStats telemetry" << std::endl; +} + +// 5. Incremental vec0 insert/update/delete recall parity & cached statements +void test_vec0_incremental_maintenance() { + std::cout << "Testing incremental vec0 ANN insert/update/delete recall parity..." << std::endl; + + sqlite3* db = nullptr; + INV_CHECK(sqlite3_open(":memory:", &db) == SQLITE_OK); + auto reg = register_vec0_module(db); + INV_CHECK(reg.has_value()); + + constexpr size_t kDim = 16; + char* err = nullptr; + int rc = sqlite3_exec(db, "CREATE VIRTUAL TABLE vecs USING vec0(embedding float[16])", nullptr, + nullptr, &err); + INV_CHECK(rc == SQLITE_OK); + + auto bind_and_insert = [&](int64_t rowid, const std::vector& v) { + sqlite3_stmt* stmt = nullptr; + int s_rc = sqlite3_prepare_v2(db, "INSERT INTO vecs(rowid, embedding) VALUES (?, ?)", -1, + &stmt, nullptr); + INV_CHECK(s_rc == SQLITE_OK); + sqlite3_bind_int64(stmt, 1, rowid); + sqlite3_bind_blob(stmt, 2, v.data(), static_cast(v.size() * sizeof(float)), + SQLITE_TRANSIENT); + s_rc = sqlite3_step(stmt); + INV_CHECK(s_rc == SQLITE_DONE); + sqlite3_finalize(stmt); + }; + + auto update_row = [&](int64_t rowid, const std::vector& v) { + sqlite3_stmt* stmt = nullptr; + int s_rc = sqlite3_prepare_v2(db, "UPDATE vecs SET embedding = ? WHERE rowid = ?", -1, + &stmt, nullptr); + INV_CHECK(s_rc == SQLITE_OK); + sqlite3_bind_blob(stmt, 1, v.data(), static_cast(v.size() * sizeof(float)), + SQLITE_TRANSIENT); + sqlite3_bind_int64(stmt, 2, rowid); + s_rc = sqlite3_step(stmt); + INV_CHECK(s_rc == SQLITE_DONE); + sqlite3_finalize(stmt); + }; + + auto delete_row = [&](int64_t rowid) { + sqlite3_stmt* stmt = nullptr; + int s_rc = sqlite3_prepare_v2(db, "DELETE FROM vecs WHERE rowid = ?", -1, &stmt, nullptr); + INV_CHECK(s_rc == SQLITE_OK); + sqlite3_bind_int64(stmt, 1, rowid); + s_rc = sqlite3_step(stmt); + INV_CHECK(s_rc == SQLITE_DONE); + sqlite3_finalize(stmt); + }; + + auto query_ann = [&](const std::vector& q, int k, int ef = 64) { + sqlite3_stmt* stmt = nullptr; + int s_rc = sqlite3_prepare_v2( + db, + "SELECT rowid, distance FROM vecs WHERE embedding MATCH ? AND k = ? AND ef_search = ?", + -1, &stmt, nullptr); + INV_CHECK(s_rc == SQLITE_OK); + sqlite3_bind_blob(stmt, 1, q.data(), static_cast(q.size() * sizeof(float)), + SQLITE_TRANSIENT); + sqlite3_bind_int(stmt, 2, k); + sqlite3_bind_int(stmt, 3, ef); + std::vector> out; + while ((s_rc = sqlite3_step(stmt)) == SQLITE_ROW) { + out.emplace_back(sqlite3_column_int64(stmt, 0), + static_cast(sqlite3_column_double(stmt, 1))); + } + INV_CHECK(s_rc == SQLITE_DONE); + sqlite3_finalize(stmt); + return out; + }; + + std::mt19937 rng(31415); + std::unordered_map> truth; + + // Phase 1: Initial population (60 vectors) + warm ANN index + for (int64_t id = 1; id <= 60; ++id) { + auto v = make_random_f32(kDim, rng, -1.0f, 1.0f); + bind_and_insert(id, v); + truth[id] = std::move(v); + } + + auto q0 = make_random_f32(kDim, rng, -1.0f, 1.0f); + auto init_res = query_ann(q0, 5); + INV_CHECK(init_res.size() == 5); + + // Grab the built ann_index pointer to verify incremental inserts do NOT invalidate it + Vec0AnnIndex* initial_ptr = nullptr; + vec0_with_table(db, "main", "vecs", [&](Vec0Table* t) { + INV_CHECK(t != nullptr); + INV_CHECK(t->ann_ready); + INV_CHECK(t->ann_index != nullptr); + initial_ptr = t->ann_index.get(); + }); + + // Phase 2: Incremental INSERTs (40 more vectors) — ann_index must stay ready and same instance + for (int64_t id = 61; id <= 100; ++id) { + auto v = make_random_f32(kDim, rng, -1.0f, 1.0f); + bind_and_insert(id, v); + truth[id] = std::move(v); + } + + vec0_with_table(db, "main", "vecs", [&](Vec0Table* t) { + INV_CHECK(t != nullptr); + INV_CHECK(t->ann_ready); + INV_CHECK(t->ann_index.get() == initial_ptr); + INV_CHECK(t->ann_index->active_size() == 100); + }); + + // Verify a newly inserted vector is found as exact top-1 match + auto res_new = query_ann(truth[95], 1); + INV_CHECK(res_new.size() == 1); + INV_CHECK(res_new[0].first == 95); + INV_CHECK(res_new[0].second < 1e-4f); + + // Phase 3: Incremental UPDATE (in-place same rowid) + std::vector updated_vec(kDim, 9.5f); + update_row(10, updated_vec); + truth[10] = updated_vec; + + vec0_with_table(db, "main", "vecs", [&](Vec0Table* t) { + INV_CHECK(t != nullptr); + INV_CHECK(t->ann_ready); + INV_CHECK(t->ann_index != nullptr); + INV_CHECK(t->ann_index->active_size() == 100); + }); + + auto res_upd = query_ann(updated_vec, 1); + INV_CHECK(res_upd.size() == 1); + INV_CHECK(res_upd[0].first == 10); + INV_CHECK(res_upd[0].second < 1e-4f); + + // Phase 4: Incremental DELETEs (30% of rows -> triggers compaction cleanly) + std::unordered_set deleted; + for (int64_t id = 1; id <= 30; ++id) { + if (id == 10) + continue; + delete_row(id); + truth.erase(id); + deleted.insert(id); + } + + vec0_with_table(db, "main", "vecs", [&](Vec0Table* t) { + INV_CHECK(t != nullptr); + INV_CHECK(t->ann_ready); + INV_CHECK(t->ann_index != nullptr); + INV_CHECK(t->ann_index->active_size() == truth.size()); + }); + + // Phase 5: Re-insert a previously deleted rowid with a distinct vector + std::vector reinserted_vec(kDim, -8.25f); + bind_and_insert(5, reinserted_vec); + truth[5] = reinserted_vec; + deleted.erase(5); + + auto res_reins = query_ann(reinserted_vec, 1); + INV_CHECK(res_reins.size() == 1); + INV_CHECK(res_reins[0].first == 5); + INV_CHECK(res_reins[0].second < 1e-4f); + + // Phase 6: Recall parity vs brute-force truth over 20 random queries + double total_recall = 0.0; + constexpr int kQueries = 20; + constexpr int kTopK = 10; + for (int qi = 0; qi < kQueries; ++qi) { + auto q = make_random_f32(kDim, rng, -1.0f, 1.0f); + auto ann_res = query_ann(q, kTopK, 64); + INV_CHECK(ann_res.size() == static_cast(kTopK)); + + // Ensure no deleted rowid ever leaks into ANN results + for (const auto& [rid, dist] : ann_res) { + INV_CHECK(!deleted.contains(rid)); + INV_CHECK(truth.contains(rid)); + } + + // Brute-force top-K over live truth + std::vector> exact; + exact.reserve(truth.size()); + for (const auto& [rid, vec] : truth) { + exact.emplace_back(rid, l2_distance(std::span(q), + std::span(vec))); + } + std::sort(exact.begin(), exact.end(), + [](const auto& lhs, const auto& rhs) { return lhs.second < rhs.second; }); + exact.resize(kTopK); + + std::unordered_set exact_ids; + for (const auto& [rid, _] : exact) { + exact_ids.insert(rid); + } + int hits = 0; + for (const auto& [rid, _] : ann_res) { + if (exact_ids.contains(rid)) { + ++hits; + } + } + total_recall += static_cast(hits) / static_cast(kTopK); + } + + const double mean_recall = total_recall / static_cast(kQueries); + std::cout << " vec0 incremental mean recall@" << kTopK << ": " << mean_recall << std::endl; + INV_CHECK(mean_recall >= 0.90); + + // Cleanly drop table to exercise finalize_cached_stmts() before shadow table drop + rc = sqlite3_exec(db, "DROP TABLE vecs", nullptr, nullptr, &err); + INV_CHECK(rc == SQLITE_OK); + sqlite3_close(db); + + std::cout << " PASS: incremental vec0 ANN maintenance & recall parity" << std::endl; +} + +} // namespace + +int main() { + test_metric_invariants(); + test_unaligned_and_simd_scalar_parity(); + test_quantized_stores_odd_dims_parity(); + test_hnsw_search_stats(); + test_vec0_incremental_maintenance(); + std::cout << "All invariant tests passed!" << std::endl; + return 0; +}