From 04a42eb8b73c5626174e33fd27e7ddd0e2661f43 Mon Sep 17 00:00:00 2001 From: Dor Forer Date: Sun, 15 Nov 2026 14:25:45 +0200 Subject: [PATCH] TQ2/TQ3: Replace the dense rotation with a block Hadamard rotation Use three rounds of [random sign flip, fast Walsh-Hadamard transform per power-of-two block, random permutation] instead of the dense random orthogonal matrix. The block is the largest power of two dividing the dimension, capped at 1024; dimensions whose block would be under 64 keep the dense rotation, generated from the same RNG stream as before. * Add TurboQuantRotation, which owns either the dense matrix or the signs and permutations, generated portably from the existing seed with 64-bit arithmetic only. The transform is a plain scalar loop. * The fitted state schema number is now the rotation kind: schema 1 (dense) is byte-for-byte the previous format; schema 2 stores the actual signs and permutations. Loading validates everything before replacing state. * Size the components memory estimate for the rotation actually allocated. * Add tests for the block rule, an independent reference, norm and inner product preservation, orthonormality, seed determinism, encode/query consistency, save/load round trips, legacy dense loads and corrupt input. Co-Authored-By: Claude Opus 5.5 --- src/VecSim/quantization/turboquant.h | 124 ++++-- .../quantization/turboquant_components.h | 7 +- src/VecSim/quantization/turboquant_rotation.h | 259 ++++++++++++ tests/unit/test_hnsw_turboquant.cpp | 392 ++++++++++++++++++ 4 files changed, 743 insertions(+), 39 deletions(-) create mode 100644 src/VecSim/quantization/turboquant_rotation.h diff --git a/src/VecSim/quantization/turboquant.h b/src/VecSim/quantization/turboquant.h index b6ae58075..916bef006 100644 --- a/src/VecSim/quantization/turboquant.h +++ b/src/VecSim/quantization/turboquant.h @@ -9,6 +9,7 @@ #pragma once #include "VecSim/quantization/turboquant_kernels.h" +#include "VecSim/quantization/turboquant_rotation.h" #include "VecSim/utils/vecsim_stl.h" #include #include @@ -26,12 +27,13 @@ namespace vecsim::quantization { -// Dense MSE TurboQuant estimator for 1 - inner product, with a projection-match scale and a -// mean-error correction. Stored vectors encode r = x - mean as +// MSE TurboQuant estimator for 1 - inner product, with a projection-match scale and a +// mean-error correction. The rotation R is block Hadamard, or dense when the dimension needs it +// (see TurboQuantRotation). Stored vectors encode r = x - mean as // [ceil(d*b/8) packed codes][scale][delta], where n = ||r||, u = R*r/n, c = the centroid decode, // scale = n/(u.c) and delta = scale*(c.R*mean) - r.mean. Queries hold [R*q: d floats][q.mean]. -// Only construction and loading validate and throw. Encoding allocates scratch, so it can -// throw std::bad_alloc; query preparation and scoring never throw. +// Only construction and loading validate and throw. Encoding and query preparation allocate +// scratch, so they can throw std::bad_alloc; scoring never throws. class TurboQuant { std::shared_ptr allocator_; size_t dim_; @@ -41,7 +43,7 @@ class TurboQuant { turboquant_detail::RowDot row_dot_ = nullptr; turboquant_detail::PackedPairDot stored_pair_dot_ = nullptr; size_t code_bytes_; - vecsim_stl::vector rotation_; + TurboQuantRotation rotation_; vecsim_stl::vector centroids_; vecsim_stl::vector bias_mean_; vecsim_stl::vector bias_rotated_mean_; @@ -67,6 +69,11 @@ class TurboQuant { void initializeRotation(uint64_t seed) { std::mt19937_64 rotation_rng(splitSeed(seed)); + if (TurboQuantRotation::kindFor(dim_) == TurboQuantRotationKind::BlockHadamard) { + rotation_.generateBlockHadamard(dim_, rotation_rng); + return; + } + auto &dense = rotation_.resetDense(dim_); std::normal_distribution gaussian; vecsim_stl::vector basis(dim_ * dim_, allocator_); // Row-wise Gaussian QR with positive diagonal convention gives Haar orthogonal Pi. @@ -98,7 +105,7 @@ class TurboQuant { } for (size_t col = 0; col < dim_; ++col) { current[col] /= norm; - rotation_[row * dim_ + col] = static_cast(current[col]); + dense[row * dim_ + col] = static_cast(current[col]); } } } @@ -158,17 +165,24 @@ class TurboQuant { } } - // Derived mean terms: ||mean||^2 and R*mean, both accumulated in double. - void computeMeanTerms(std::span mean, float *rotated, - float &norm_squared) const noexcept { + // Derived mean terms: ||mean||^2 in double, and R*mean (in double for a dense R, zero while + // R is unset). A block Hadamard R uses `scratch`, dim floats not aliasing `rotated`. + void computeMeanTerms(std::span mean, float *rotated, float &norm_squared, + float *scratch) const noexcept { double norm = 0; for (float value : mean) norm += double(value) * value; norm_squared = static_cast(norm); + if (rotation_.isBlockHadamard()) { + rotation_.apply(mean.data(), rotated, scratch); + return; + } + const auto dense = rotation_.dense(); + const size_t cols = dense.empty() ? 0 : dim_; for (size_t row = 0; row < dim_; ++row) { double dot = 0; - for (size_t col = 0; col < dim_; ++col) - dot += double(rotation_[row * dim_ + col]) * mean[col]; + for (size_t col = 0; col < cols; ++col) + dot += double(dense[row * dim_ + col]) * mean[col]; rotated[row] = static_cast(dot); } } @@ -223,29 +237,34 @@ class TurboQuant { uint64_t seed, std::span mean, bool initialize = true) : allocator_(std::move(allocator)), dim_(validatedDim(allocator_, dim, bits, mean)), bits_(bits), seed_(seed), code_bytes_((dim_ * bits_ + 7) / 8), - rotation_(dim_ * dim_, allocator_), centroids_(size_t{1} << bits_, allocator_), + rotation_(allocator_), centroids_(size_t{1} << bits_, allocator_), bias_mean_(dim_, allocator_), bias_rotated_mean_(dim_, allocator_) { - std::copy(mean.begin(), mean.end(), bias_mean_.begin()); if (initialize) { initializeRotation(seed); initializeCentroids(); } - computeMeanTerms(biasMean(), bias_rotated_mean_.data(), bias_mean_norm_squared_); + setMean(mean); selectKernels(); } // Writer-only: install a fitted mean before any vector is stored, with readers excluded. // Updates the buffers in place, so the codec address and cached dispatches remain valid. void setMean(std::span mean) noexcept { - assert(mean.size() == dim_); + assert(mean.size() == dim_ && mean.data() != bias_mean_.data()); + // bias_mean_ serves as the rotation scratch before it receives the new mean. + computeMeanTerms(mean, bias_rotated_mean_.data(), bias_mean_norm_squared_, + bias_mean_.data()); std::copy(mean.begin(), mean.end(), bias_mean_.begin()); - computeMeanTerms(biasMean(), bias_rotated_mean_.data(), bias_mean_norm_squared_); } #ifdef BUILD_TESTS - // Fitted state, schema 1. The full rotation is stored; the seed is metadata only. + // Fitted state. The schema is the rotation kind: schema 1 stores a dense rotation as + // [count][dim*dim floats], byte-for-byte the format written before block Hadamard existed; + // schema 2 stores the actual block Hadamard signs and permutations in the same position. + // Everything after the rotation is common to both. The seed is metadata only. void saveFitted(std::ostream &out) const { - const uint32_t header[] = {1, bits_, 1, 3, 1}; // schema, MSE, projection-match, mean-error + // schema (= rotation kind), MSE, projection-match, mean-error + const uint32_t header[] = {static_cast(rotation_.kind()), bits_, 1, 3, 1}; out.write(reinterpret_cast(header), sizeof(header)); out.write(reinterpret_cast(&seed_), sizeof(seed_)); auto write = [&](const auto &values) { @@ -253,7 +272,10 @@ class TurboQuant { out.write(reinterpret_cast(&count), sizeof(count)); out.write(reinterpret_cast(values.data()), count * sizeof(float)); }; - write(rotation_); + if (rotation_.isBlockHadamard()) + rotation_.saveBlockHadamard(out); + else + write(rotation_.dense()); write(centroids_); write(bias_mean_); write(bias_rotated_mean_); @@ -269,16 +291,23 @@ class TurboQuant { uint64_t seed = 0; in.read(reinterpret_cast(header), sizeof(header)); in.read(reinterpret_cast(&seed), sizeof(seed)); - if (!in || header[0] != 1 || header[1] != bits || header[2] != 1 || header[3] != 3 || - header[4] != 1) + const auto kind = static_cast(header[0]); + // Schema 1 (dense) loads at any dimension; schema 2 only where a new index builds it. + if (!in || + (kind != TurboQuantRotationKind::Dense && + !(kind == TurboQuantRotationKind::BlockHadamard && + TurboQuantRotation::kindFor(dim) == kind)) || + header[1] != bits || header[2] != 1 || header[3] != 3 || header[4] != 1) throw std::runtime_error("Unsupported TurboQuant fitted policy"); const auto position = in.tellg(); in.seekg(0, std::ios::end); const auto end = in.tellg(); in.seekg(position); - const uint64_t minimum = - 4 * sizeof(uint64_t) + sizeof(float) + - (uint64_t(dim) * dim + (uint64_t(1) << bits) + 2 * dim) * sizeof(float); + const uint64_t rotation_bytes = kind == TurboQuantRotationKind::Dense + ? sizeof(uint64_t) + uint64_t(dim) * dim * sizeof(float) + : TurboQuantRotation::minimumBlockHadamardBytes(dim); + const uint64_t minimum = rotation_bytes + 3 * sizeof(uint64_t) + sizeof(float) + + ((uint64_t(1) << bits) + 2 * dim) * sizeof(float); if (!in || position < 0 || end < position || uint64_t(end - position) < minimum) throw std::runtime_error("Truncated TurboQuant fitted state"); vecsim_stl::vector zero(dim, 0.0f, allocator); @@ -297,7 +326,10 @@ class TurboQuant { if (!std::isfinite(value)) throw std::runtime_error("Nonfinite TurboQuant fitted state"); }; - read(codec->rotation_); + if (kind == TurboQuantRotationKind::Dense) + read(codec->rotation_.resetDense(dim)); + else + codec->rotation_.loadBlockHadamard(in, dim); read(codec->centroids_); read(codec->bias_mean_); read(codec->bias_rotated_mean_); @@ -309,16 +341,17 @@ class TurboQuant { (i && codec->centroids_[i] <= codec->centroids_[i - 1])) throw std::runtime_error("Invalid TurboQuant fitted centroids"); // Validate the relationship between persisted derived terms and the exact stored mean. - vecsim_stl::vector rotated(dim, allocator); + vecsim_stl::vector rotated(dim, allocator), scratch(dim, allocator); float norm_squared = 0; - codec->computeMeanTerms(codec->biasMean(), rotated.data(), norm_squared); + codec->computeMeanTerms(codec->biasMean(), rotated.data(), norm_squared, scratch.data()); if (norm_squared != codec->bias_mean_norm_squared_ || !std::equal(rotated.begin(), rotated.end(), codec->bias_rotated_mean_.begin())) throw std::runtime_error("Inconsistent TurboQuant fitted mean terms"); - for (size_t row = 0; row < dim; ++row) { + const auto dense = codec->rotation_.dense(); + for (size_t row = 0; row < dim && !dense.empty(); ++row) { double squared = 0; for (size_t col = 0; col < dim; ++col) { - const double value = codec->rotation_[row * dim + col]; + const double value = dense[row * dim + col]; squared += value * value; } if (std::abs(squared - 1.0) > 1e-4) @@ -331,7 +364,9 @@ class TurboQuant { size_t dim() const { return dim_; } unsigned bits() const { return bits_; } uint64_t seed() const { return seed_; } - std::span rotation() const { return {rotation_.data(), rotation_.size()}; } + // The dense row-major dim x dim matrix; empty for a block Hadamard rotation. + std::span rotation() const { return rotation_.dense(); } + const TurboQuantRotation &rotationOperator() const { return rotation_; } std::span centroids() const { return {centroids_.data(), centroids_.size()}; } std::span biasMean() const { return {bias_mean_.data(), bias_mean_.size()}; } std::span biasRotatedMean() const { @@ -339,9 +374,10 @@ class TurboQuant { } size_t storageBytes() const { return code_bytes_ + 2 * sizeof(float); } size_t queryBytes() const { return (dim_ + 1) * sizeof(float); } - // Rotation, centroids, mean and rotated mean, each in its own allocation. + // Rotation, centroids, mean and rotated mean of a new codec, each in its own allocation(s). static size_t sharedDataBytes(size_t dim, unsigned bits) { - return (dim * dim + (size_t(1) << bits) + 2 * dim) * sizeof(float); + return TurboQuantRotation::sharedBytesFor(dim) + + ((size_t(1) << bits) + 2 * dim) * sizeof(float); } // Encodes x - mean. Reads all of `input` before writing `stored`, so they may alias. @@ -362,11 +398,20 @@ class TurboQuant { for (size_t i = 0; i < dim_; ++i) { unit[i] /= norm; } + const auto dense = rotation_.dense(); + if (rotation_.isBlockHadamard()) { + vecsim_stl::vector scratch(dim_, allocator_); + rotation_.apply(unit.data(), unit.data(), scratch.data()); // unit now holds R*unit + } double unit_code_dot = 0, code_mean_dot = 0; for (size_t row = 0; row < dim_; ++row) { float rotated = 0; - for (size_t col = 0; col < dim_; ++col) { - rotated += rotation_[row * dim_ + col] * unit[col]; + if (dense.empty()) { + rotated = unit[row]; + } else { + for (size_t col = 0; col < dim_; ++col) { + rotated += dense[row * dim_ + col] * unit[col]; + } } unsigned code = 0; while (code + 1 < centroids_.size() && @@ -386,13 +431,18 @@ class TurboQuant { // Writes [R*q][q.mean] into an FP32-aligned buffer that does not alias `input`. void prepareQuery(const float *input, void *query) const { auto *output = static_cast(query); - for (size_t row = 0; row < dim_; ++row) { + if (rotation_.isBlockHadamard()) { + vecsim_stl::vector scratch(dim_, allocator_); + rotation_.apply(input, output, scratch.data()); + } + const auto dense = rotation_.dense(); + for (size_t row = 0; row < dim_ && !dense.empty(); ++row) { float value = 0; if (row_dot_) { - value = row_dot_(rotation_.data() + row * dim_, input, dim_); + value = row_dot_(dense.data() + row * dim_, input, dim_); } else { for (size_t col = 0; col < dim_; ++col) { - value += rotation_[row * dim_ + col] * input[col]; + value += dense[row * dim_ + col] * input[col]; } } output[row] = value; diff --git a/src/VecSim/quantization/turboquant_components.h b/src/VecSim/quantization/turboquant_components.h index 0117ab19a..ddd6e77db 100644 --- a/src/VecSim/quantization/turboquant_components.h +++ b/src/VecSim/quantization/turboquant_components.h @@ -139,10 +139,13 @@ inline size_t EstimateTurboQuantComponentsMemory(size_t dim, unsigned bits) { } const size_t overhead = VecSimAllocator::getAllocationOverheadSize(); // Calculator, container and preprocessor objects; the shared codec block (object plus - // control block); and its four float buffers. + // control block); its three float buffers; and the rotation's buffers. Sized for the + // rotation a new codec builds at this dimension. A test-only reload of a legacy dense + // (schema 1) state at a block Hadamard dimension allocates the d x d matrix. return sizeof(TurboQuantCalculator) + sizeof(MultiPreprocessorsContainer) + sizeof(TurboQuantPreprocessor) + sizeof(TurboQuant) + - sizeof(VecsimSTLAllocator) + 4 * sizeof(void *) + 8 * overhead + + sizeof(VecsimSTLAllocator) + 4 * sizeof(void *) + + (7 + TurboQuantRotation::allocationsFor(dim)) * overhead + TurboQuant::sharedDataBytes(dim, bits); } diff --git a/src/VecSim/quantization/turboquant_rotation.h b/src/VecSim/quantization/turboquant_rotation.h new file mode 100644 index 000000000..91d503030 --- /dev/null +++ b/src/VecSim/quantization/turboquant_rotation.h @@ -0,0 +1,259 @@ +/* + * 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/utils/vecsim_stl.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef BUILD_TESTS +#include +#include +#endif + +namespace vecsim::quantization { + +// The value is also the TurboQuant fitted-state schema number that persists this kind. +enum class TurboQuantRotationKind : uint32_t { Unset = 0, Dense = 1, BlockHadamard = 2 }; + +// The orthogonal transform Pi applied to stored residuals, queries and the fitted mean. +// +// BlockHadamard (the default whenever the dimension allows it): three rounds of +// [round > 0: permute coordinates] -> multiply by random signs -> normalized FWHT on each +// power-of-two block, +// with block = the largest power of two dividing dim, capped at kMaxBlock. There is no +// permutation after the last round: it would only relabel output coordinates, and the scalar +// codebook is shared by all coordinates. State is 3 sign vectors and 2 permutations (about +// 15 KB at dim 768) instead of a dim x dim matrix (2.36 MB at dim 768). +// +// Dense: a Haar random orthogonal matrix, kept for dimensions whose block would be below +// kMinBlock (for example dim 100 has block 4) and for fitted state written before +// BlockHadamard existed. Its arithmetic stays in TurboQuant so those indexes score exactly as +// before. +class TurboQuantRotation { +public: + static constexpr unsigned kRounds = 3; + // Below this block size the per-block mixing is too local; use the dense rotation instead. + // Recall was validated only for dim 768 (three 256 blocks), see the TQ rotation study. + static constexpr size_t kMinBlock = 64; + static constexpr size_t kMaxBlock = 1024; + + // Block size BlockHadamard uses for dim, or 0 when dim needs the dense fallback. + static size_t hadamardBlock(size_t dim) { + if (dim == 0) return 0; + size_t block = dim & (~dim + 1); + if (block > kMaxBlock) block = kMaxBlock; + return block >= kMinBlock ? block : 0; + } + static TurboQuantRotationKind kindFor(size_t dim) { + return hadamardBlock(dim) ? TurboQuantRotationKind::BlockHadamard + : TurboQuantRotationKind::Dense; + } + static float signMagnitude(size_t block) { return 1.0f / std::sqrt(static_cast(block)); } + // Permanent payload bytes for a freshly built rotation of this dimension. + static size_t sharedBytesFor(size_t dim) { + return kindFor(dim) == TurboQuantRotationKind::Dense + ? dim * dim * sizeof(float) + : kRounds * dim * sizeof(float) + (kRounds - 1) * dim * sizeof(uint32_t); + } + // Permanent allocations for a freshly built rotation of this dimension. + static size_t allocationsFor(size_t dim) { + return kindFor(dim) == TurboQuantRotationKind::Dense ? 1 : 2; + } + + explicit TurboQuantRotation(const std::shared_ptr &allocator) + : allocator_(allocator), dense_(allocator), signs_(allocator), permutations_(allocator) {} + + TurboQuantRotationKind kind() const { return kind_; } + bool isBlockHadamard() const { return kind_ == TurboQuantRotationKind::BlockHadamard; } + size_t dim() const { return dim_; } + size_t block() const { return block_; } + std::span dense() const { return {dense_.data(), dense_.size()}; } + std::span scaledSigns() const { return {signs_.data(), signs_.size()}; } + std::span permutations() const { + return {permutations_.data(), permutations_.size()}; + } + size_t sharedBytes() const { + return dense_.size() * sizeof(float) + signs_.size() * sizeof(float) + + permutations_.size() * sizeof(uint32_t); + } + + // Dense storage for TurboQuant to fill (generation or load). Row-major dim x dim. + vecsim_stl::vector &resetDense(size_t dim) { + clear(); + kind_ = TurboQuantRotationKind::Dense; + dim_ = dim; + dense_.assign(dim * dim, 0.0f); + return dense_; + } + + // Draws signs then permutations from rng. Only mt19937_64 raw output is used (its sequence + // is fixed by the C++ standard), not std::shuffle or std distributions, whose results are + // implementation defined. The same seed therefore gives the same rotation everywhere. + void generateBlockHadamard(size_t dim, std::mt19937_64 &rng) { + const size_t block = hadamardBlock(dim); + assert(block); // Callers check kindFor(dim) first. + clear(); + kind_ = TurboQuantRotationKind::BlockHadamard; + dim_ = dim; + block_ = block; + signs_.resize(kRounds * dim); + permutations_.resize((kRounds - 1) * dim); + const float magnitude = signMagnitude(block); + for (unsigned round = 0; round < kRounds; ++round) { + float *signs = signs_.data() + round * dim; + for (size_t i = 0; i < dim; i += 64) { + const uint64_t bits = rng(); + for (size_t b = 0; b < 64 && i + b < dim; ++b) + signs[i + b] = ((bits >> b) & 1) ? -magnitude : magnitude; + } + } + for (unsigned round = 1; round < kRounds; ++round) { + uint32_t *permutation = permutations_.data() + (round - 1) * dim; + for (size_t i = 0; i < dim; ++i) permutation[i] = static_cast(i); + for (size_t i = dim - 1; i > 0; --i) + std::swap(permutation[i], permutation[boundedDraw(rng, i + 1)]); + } + } + + // out = Pi * in. out may alias in; scratch (dim floats) must not alias out, and may alias + // in, which is fully consumed before scratch is written. Requires isBlockHadamard(). + void apply(const float *in, float *out, float *scratch) const { + assert(isBlockHadamard() && out != scratch); + if (in != out) std::memcpy(out, in, dim_ * sizeof(float)); + transformBlocks(out, signs_.data()); + float *current = out, *next = scratch; + for (unsigned round = 1; round < kRounds; ++round) { + const uint32_t *permutation = permutations_.data() + (round - 1) * dim_; + for (size_t i = 0; i < dim_; ++i) next[i] = current[permutation[i]]; + transformBlocks(next, signs_.data() + round * dim_); + std::swap(current, next); + } + if (current != out) std::memcpy(out, current, dim_ * sizeof(float)); + } + +#ifdef BUILD_TESTS + // [block u64][rounds u64][sign count u64][signs f32...][permutation count u64][u32...] + static uint64_t minimumBlockHadamardBytes(size_t dim) { + return 4 * sizeof(uint64_t) + uint64_t(kRounds) * dim * sizeof(float) + + uint64_t(kRounds - 1) * dim * sizeof(uint32_t); + } + void saveBlockHadamard(std::ostream &out) const { + assert(isBlockHadamard()); + const uint64_t header[] = {block_, kRounds, signs_.size()}; + out.write(reinterpret_cast(header), sizeof(header)); + out.write(reinterpret_cast(signs_.data()), signs_.size() * sizeof(float)); + const uint64_t count = permutations_.size(); + out.write(reinterpret_cast(&count), sizeof(count)); + out.write(reinterpret_cast(permutations_.data()), + permutations_.size() * sizeof(uint32_t)); + } + // Restores the persisted signs and permutations (never regenerated from the seed) and + // rejects anything that is not exactly a rotation this class would build for dim. + void loadBlockHadamard(std::istream &in, size_t dim) { + const size_t block = hadamardBlock(dim); + uint64_t header[3]{}; + in.read(reinterpret_cast(header), sizeof(header)); + if (!in || !block || header[0] != block || header[1] != kRounds || + header[2] != uint64_t(kRounds) * dim) + throw std::runtime_error("Invalid TurboQuant block Hadamard rotation"); + // Read and validate into locals; this object changes only once everything is valid. + vecsim_stl::vector signs(kRounds * dim, allocator_); + vecsim_stl::vector permutations((kRounds - 1) * dim, allocator_); + in.read(reinterpret_cast(signs.data()), signs.size() * sizeof(float)); + uint64_t count = 0; + if (in) in.read(reinterpret_cast(&count), sizeof(count)); + if (!in) throw std::runtime_error("Truncated TurboQuant block Hadamard rotation"); + if (count != permutations.size()) + throw std::runtime_error("Invalid TurboQuant block Hadamard permutations"); + in.read(reinterpret_cast(permutations.data()), + permutations.size() * sizeof(uint32_t)); + if (!in) throw std::runtime_error("Truncated TurboQuant block Hadamard rotation"); + const float magnitude = signMagnitude(block); + for (float sign : signs) + if (sign != magnitude && sign != -magnitude) + throw std::runtime_error("Invalid TurboQuant block Hadamard sign"); + vecsim_stl::vector seen(dim, false, allocator_); + for (unsigned round = 1; round < kRounds; ++round) { + std::fill(seen.begin(), seen.end(), false); + for (size_t i = 0; i < dim; ++i) { + const uint32_t source = permutations[(round - 1) * dim + i]; + if (source >= dim || seen[source]) + throw std::runtime_error("Invalid TurboQuant block Hadamard permutation"); + seen[source] = true; + } + } + clear(); + kind_ = TurboQuantRotationKind::BlockHadamard; + dim_ = dim; + block_ = block; + signs_.swap(signs); + permutations_.swap(permutations); + } +#endif + +private: + std::shared_ptr allocator_; + TurboQuantRotationKind kind_ = TurboQuantRotationKind::Unset; + size_t dim_ = 0; + size_t block_ = 0; + vecsim_stl::vector dense_; + vecsim_stl::vector signs_; // kRounds x dim, each +-1/sqrt(block) + vecsim_stl::vector permutations_; // (kRounds - 1) x dim, next[i] = cur[p[i]] + + void clear() { + kind_ = TurboQuantRotationKind::Unset; + dim_ = block_ = 0; + dense_.clear(); dense_.shrink_to_fit(); + signs_.clear(); signs_.shrink_to_fit(); + permutations_.clear(); permutations_.shrink_to_fit(); + } + // Per block: x *= scaled signs, then the unnormalized Walsh-Hadamard butterflies (the + // 1/sqrt(block) normalization is folded into the signs). Only element-wise multiply, add and + // subtract in a fixed order, so the result is the same on every machine, which persisted + // fitted state relies on. The compiler vectorizes the wider strides. + void transformBlocks(float *x, const float *signs) const { + for (size_t i = 0; i < dim_; ++i) x[i] *= signs[i]; + for (size_t start = 0; start < dim_; start += block_) { + float *b = x + start; + for (size_t h = 1; h < block_; h *= 2) + for (size_t j = 0; j < block_; j += 2 * h) + for (size_t k = j; k < j + h; ++k) { + const float lo = b[k], hi = b[k + h]; + b[k] = lo + hi; + b[k + h] = lo - hi; + } + } + } + // Uniform in [0, bound) by Lemire's multiply-shift with rejection, on the top 32 bits of + // each draw so only 64-bit arithmetic is needed. Dimensions are below 2^32. + static size_t boundedDraw(std::mt19937_64 &rng, uint64_t bound64) { + assert(bound64 > 0 && bound64 <= std::numeric_limits::max()); + const auto bound = static_cast(bound64); + uint64_t product = (rng() >> 32) * bound; + auto low = static_cast(product); + if (low < bound) { + const uint32_t threshold = (0u - bound) % bound; + while (low < threshold) { + product = (rng() >> 32) * bound; + low = static_cast(product); + } + } + return static_cast(product >> 32); + } +}; + +} // namespace vecsim::quantization diff --git a/tests/unit/test_hnsw_turboquant.cpp b/tests/unit/test_hnsw_turboquant.cpp index 671949d51..fda93aac3 100644 --- a/tests/unit/test_hnsw_turboquant.cpp +++ b/tests/unit/test_hnsw_turboquant.cpp @@ -15,14 +15,19 @@ #include "VecSim/vec_sim.h" #include "mock_thread_pool.h" #include "unit_test_utils.h" +#include #include +#include #include #include #include #include #include #include +#include +#include #include +#include #include using namespace vecsim::quantization; @@ -55,6 +60,7 @@ float unalignedFloat(const void *data, size_t offset) { return value; } // An independent bit reader and decoded-score reference, including the full mean error. +// The references read the dense matrix, so they only apply where the rotation is dense. std::vector decoded(const TurboQuant &quantizer, const void *blob) { const auto *bytes = static_cast(blob); std::vector values(quantizer.dim()); @@ -509,4 +515,390 @@ TEST_P(TurboQuantTest, ExistingWriterVersionsRemainUnchanged) { } } +// Block Hadamard rotation. +namespace { +std::vector gaussianVector(size_t dim, uint32_t seed, float scale = 1.0f) { + std::mt19937 rng(seed); + std::normal_distribution normal(0.0f, scale); + std::vector values(dim); + for (float &value : values) + value = normal(rng); + return values; +} +std::vector applyRotation(const TurboQuantRotation &rotation, const std::vector &x) { + std::vector out(x.size()), scratch(x.size()); + rotation.apply(x.data(), out.data(), scratch.data()); + return out; +} +// Independent double-precision reference of the documented transform: explicit Sylvester +// Hadamard entries (-1)^popcount(i & j) / sqrt(block), no butterflies. +std::vector referenceRotation(const TurboQuantRotation &rotation, + const std::vector &x) { + const size_t dim = rotation.dim(), block = rotation.block(); + std::vector current(x.begin(), x.end()), next(dim); + for (unsigned round = 0; round < TurboQuantRotation::kRounds; ++round) { + if (round > 0) { + const auto *permutation = rotation.permutations().data() + (round - 1) * dim; + for (size_t i = 0; i < dim; ++i) + next[i] = current[permutation[i]]; + current.swap(next); + } + const auto *signs = rotation.scaledSigns().data() + round * dim; + for (size_t i = 0; i < dim; ++i) + current[i] *= signs[i] < 0 ? -1.0 : 1.0; + for (size_t start = 0; start < dim; start += block) { + for (size_t i = 0; i < block; ++i) { + double sum = 0; + for (size_t j = 0; j < block; ++j) + sum += (std::popcount(uint64_t(i & j)) % 2 ? -1.0 : 1.0) * current[start + j]; + next[start + i] = sum / std::sqrt(double(block)); + } + } + current.swap(next); + } + return current; +} +std::shared_ptr newCodec(const std::shared_ptr &allocator, + size_t dim, unsigned bits = 2, uint64_t seed = 42, + std::vector mean = {}) { + mean.resize(dim, 0.0f); + return std::allocate_shared(VecsimSTLAllocator(allocator), allocator, + dim, bits, seed, std::span(mean)); +} +std::string savedFitted(const TurboQuant &quantizer) { + std::stringstream out; + quantizer.saveFitted(out); + return out.str(); +} +std::shared_ptr loadFittedString(const std::string &bytes, size_t dim, unsigned bits) { + std::stringstream in(bytes); + return TurboQuant::loadFitted(in, VecSimAllocator::newVecsimAllocator(), dim, bits); +} +} // namespace + +TEST(TurboQuantRotation, BlockSizeRuleAndDenseFallback) { + const std::pair cases[] = {{768, 256}, {384, 128}, {1536, 512}, + {1024, 1024}, {2048, 1024}, {960, 64}, + {64, 64}, {96, 0}, {100, 0}, {9, 0}, {2, 0}}; + auto allocator = VecSimAllocator::newVecsimAllocator(); + for (auto [dim, block] : cases) { + EXPECT_EQ(TurboQuantRotation::hadamardBlock(dim), block) << dim; + auto codec = newCodec(allocator, dim); + const auto &rotation = codec->rotationOperator(); + EXPECT_EQ(rotation.kind(), block ? TurboQuantRotationKind::BlockHadamard + : TurboQuantRotationKind::Dense) + << dim; + EXPECT_EQ(rotation.block(), block) << dim; + EXPECT_EQ(codec->rotation().size(), block ? 0 : dim * dim) << dim; + EXPECT_EQ(rotation.sharedBytes(), TurboQuantRotation::sharedBytesFor(dim)) << dim; + } + // About 15 KB instead of the 2.36 MB dense matrix at dim 768. + EXPECT_EQ(TurboQuantRotation::sharedBytesFor(768), 3 * 768 * 4 + 2 * 768 * 4); +} + +TEST(TurboQuantRotation, MatchesReferenceAndPreservesNormsAndInnerProducts) { + auto allocator = VecSimAllocator::newVecsimAllocator(); + for (size_t dim : {64, 384, 768, 960, 1024, 1536}) { + const auto owner = newCodec(allocator, dim); + const auto &rotation = owner->rotationOperator(); + ASSERT_TRUE(rotation.isBlockHadamard()); + for (uint32_t trial = 0; trial < 4; ++trial) { + const auto x = gaussianVector(dim, 1000 * dim + 2 * trial); + const auto y = gaussianVector(dim, 1000 * dim + 2 * trial + 1); + const auto rx = applyRotation(rotation, x), ry = applyRotation(rotation, y); + double nx = 0, nrx = 0, xy = 0, rxy = 0; + for (size_t i = 0; i < dim; ++i) { + nx += double(x[i]) * x[i]; + nrx += double(rx[i]) * rx[i]; + xy += double(x[i]) * y[i]; + rxy += double(rx[i]) * ry[i]; + } + EXPECT_NEAR(std::sqrt(nrx), std::sqrt(nx), 1e-5 * std::sqrt(nx)) << dim; + EXPECT_NEAR(rxy, xy, 1e-5 * nx) << dim; // |x| ~ |y| + if (trial == 0 && dim <= 1024) { + const auto reference = referenceRotation(rotation, x); + double max_error = 0; + for (size_t i = 0; i < dim; ++i) + max_error = std::max(max_error, std::abs(reference[i] - rx[i])); + EXPECT_LT(max_error, 1e-5) << dim; + } + } + } +} + +TEST(TurboQuantRotation, IsOrthonormal) { + auto allocator = VecSimAllocator::newVecsimAllocator(); + for (size_t dim : {256, 384}) { + const auto owner = newCodec(allocator, dim); + std::vector> columns; + for (size_t i = 0; i < dim; ++i) { + std::vector basis(dim, 0.0f); + basis[i] = 1.0f; + columns.push_back(applyRotation(owner->rotationOperator(), basis)); + } + double max_error = 0; + for (size_t i = 0; i < dim; ++i) + for (size_t j = i; j < dim; ++j) { + double dot = 0; + for (size_t k = 0; k < dim; ++k) + dot += double(columns[i][k]) * columns[j][k]; + max_error = std::max(max_error, std::abs(dot - (i == j ? 1.0 : 0.0))); + } + EXPECT_LT(max_error, 1e-5) << dim; + } +} + +TEST(TurboQuantRotation, DeterministicPerSeedAndDistinctAcrossSeeds) { + auto allocator = VecSimAllocator::newVecsimAllocator(); + auto a = newCodec(allocator, 768, 2, 42), b = newCodec(allocator, 768, 3, 42); + auto c = newCodec(allocator, 768, 2, 43); + const auto &ra = a->rotationOperator(), &rb = b->rotationOperator(); + const auto &rc = c->rotationOperator(); + EXPECT_TRUE(std::ranges::equal(ra.scaledSigns(), rb.scaledSigns())); + EXPECT_TRUE(std::ranges::equal(ra.permutations(), rb.permutations())); + EXPECT_FALSE(std::ranges::equal(ra.scaledSigns(), rc.scaledSigns())); + EXPECT_FALSE(std::ranges::equal(ra.permutations(), rc.permutations())); + // Every round holds a valid sign vector and permutation. + const float magnitude = 1.0f / 16.0f; + for (float sign : ra.scaledSigns()) + EXPECT_TRUE(sign == magnitude || sign == -magnitude); + for (size_t round = 0; round + 1 < TurboQuantRotation::kRounds; ++round) { + std::vector sorted(ra.permutations().begin() + round * 768, + ra.permutations().begin() + (round + 1) * 768); + std::sort(sorted.begin(), sorted.end()); + for (uint32_t i = 0; i < 768; ++i) + EXPECT_EQ(sorted[i], i); + } +} + +TEST_P(TurboQuantTest, BlockHadamardEncodeAndQueryShareTheRotation) { + const unsigned bits = GetParam(); + constexpr size_t dim = 768; + auto allocator = VecSimAllocator::newVecsimAllocator(); + const auto mean = gaussianVector(dim, 11, 0.02f); + const VecSimTurboQuantParams config{.mean = mean.data(), .seed = 42}; + auto parts = CreateTurboQuantIndexComponents(allocator, dim, bits, &config); + std::unique_ptr pp(parts.preprocessors); + std::unique_ptr> calculator(parts.indexCalculator); + const TurboQuant &native = *GetTurboQuantCodec(calculator.get()); + const auto &rotation = native.rotationOperator(); + ASSERT_TRUE(rotation.isBlockHadamard()); + // The rotated mean is exactly R * mean. + EXPECT_TRUE(std::ranges::equal(native.biasRotatedMean(), applyRotation(rotation, mean))); + for (uint32_t trial = 0; trial < 3; ++trial) { + const auto x = gaussianVector(dim, 100 + trial, 0.04f); + const auto q = gaussianVector(dim, 200 + trial, 0.04f); + auto stored = pp->preprocessForStorage(x.data(), dim * sizeof(float)); + auto prepared = pp->preprocessQuery(q.data(), dim * sizeof(float)); + // Query preparation writes exactly R * q. + const auto rotated_query = applyRotation(rotation, q); + for (size_t i = 0; i < dim; ++i) + ASSERT_EQ(unalignedFloat(prepared.get(), i * sizeof(float)), rotated_query[i]) << i; + // Encoding quantizes exactly R * (x - mean) / ||x - mean||. + std::vector unit(dim); + float norm = 0; + for (size_t i = 0; i < dim; ++i) + norm = std::hypot(norm, x[i] - mean[i]); + for (size_t i = 0; i < dim; ++i) + unit[i] = (x[i] - mean[i]) / norm; + const auto rotated_unit = applyRotation(rotation, unit); + const auto values = decoded(native, stored.get()); + const float scale = unalignedFloat(stored.get(), (dim * bits + 7) / 8); + for (size_t i = 0; i < dim; ++i) { + unsigned code = 0; + for (size_t c = 1; c < native.centroids().size(); ++c) + if (rotated_unit[i] > (native.centroids()[c - 1] + native.centroids()[c]) * 0.5f) + code = c; + ASSERT_DOUBLE_EQ(values[i], double(scale) * native.centroids()[code]) << i; + } + // The score matches the decoded double reference built from the same rotation. + double reference = 1 + unalignedFloat(stored.get(), native.storageBytes() - sizeof(float)); + for (size_t i = 0; i < dim; ++i) + reference -= values[i] * rotated_query[i] + double(mean[i]) * q[i]; + EXPECT_NEAR(calculator->calcDistanceForQuery(stored.get(), prepared.get(), dim), + reference, 3e-6); + } +} + +TEST_P(TurboQuantTest, BlockHadamardIndexSaveLoadRoundTrip) { + const unsigned bits = GetParam(); + constexpr size_t dim = 768; + const auto mean = gaussianVector(dim, 21, 0.02f); + VecSimTurboQuantParams config{.mean = mean.data(), .seed = 7}; + auto params = CreateParams(parameters(bits, dim, &config)); + IndexOwner index(VecSimIndex_New(¶ms), VecSimIndex_Free); + ASSERT_NE(index, nullptr); + auto *hnsw = dynamic_cast *>(index.get()); + ASSERT_NE(hnsw, nullptr); + EXPECT_TRUE(codecOf(hnsw).rotationOperator().isBlockHadamard()); + EXPECT_GE(VecSimIndex_EstimateInitialSize(¶ms), index->getAllocationSize()); + constexpr size_t rows = 24; + for (size_t i = 0; i < rows; ++i) { + const auto row = gaussianVector(dim, 300 + i, 0.04f); + ASSERT_EQ(VecSimIndex_AddVector(index.get(), row.data(), i), 1); + } + const auto query = gaussianVector(dim, 999, 0.04f); + const auto filename = path(bits, "hadamard_roundtrip"); + hnsw->saveIndex(filename); + IndexOwner restored(HNSWFactory::NewIndex(filename), VecSimIndex_Free); + std::remove(filename.c_str()); + ASSERT_NE(restored, nullptr); + auto *loaded = dynamic_cast *>(restored.get()); + ASSERT_NE(loaded, nullptr); + const auto &a = codecOf(hnsw).rotationOperator(); + const auto &b = codecOf(loaded).rotationOperator(); + EXPECT_TRUE(b.isBlockHadamard()); + EXPECT_EQ(b.block(), a.block()); + EXPECT_TRUE(std::ranges::equal(a.scaledSigns(), b.scaledSigns())); + EXPECT_TRUE(std::ranges::equal(a.permutations(), b.permutations())); + EXPECT_TRUE( + std::ranges::equal(codecOf(hnsw).biasRotatedMean(), codecOf(loaded).biasRotatedMean())); + for (size_t i = 0; i < rows; ++i) { + EXPECT_EQ(std::memcmp(hnsw->getDataByInternalId(i), loaded->getDataByInternalId(i), + hnsw->getStoredDataSize()), + 0); + EXPECT_EQ(VecSimIndex_GetDistanceFrom_Unsafe(index.get(), i, query.data()), + VecSimIndex_GetDistanceFrom_Unsafe(restored.get(), i, query.data())); + } + // A vector added after reload encodes identically to one added to the original. + const auto extra = gaussianVector(dim, 4242, 0.04f); + ASSERT_EQ(VecSimIndex_AddVector(index.get(), extra.data(), 500), 1); + ASSERT_EQ(VecSimIndex_AddVector(restored.get(), extra.data(), 500), 1); + EXPECT_EQ(std::memcmp(hnsw->getDataByInternalId(rows), loaded->getDataByInternalId(rows), + hnsw->getStoredDataSize()), + 0); + EXPECT_TRUE(loaded->checkIntegrity().valid_state); +} + +TEST_P(TurboQuantTest, LegacyDenseSchemaStillLoadsAtHadamardDimensions) { + // A schema-1 (dense) fitted blob at dim 768, as written before block Hadamard existed. Its + // matrix is the materialized block Hadamard rotation, so the dense codec must reproduce the + // structured codec's prepared queries to float tolerance. + const unsigned bits = GetParam(); + constexpr size_t dim = 768; + auto allocator = VecSimAllocator::newVecsimAllocator(); + auto structured = newCodec(allocator, dim, bits, 42, gaussianVector(dim, 31, 0.02f)); + std::vector matrix(dim * dim); + for (size_t col = 0; col < dim; ++col) { + std::vector basis(dim, 0.0f); + basis[col] = 1.0f; + const auto column = applyRotation(structured->rotationOperator(), basis); + for (size_t row = 0; row < dim; ++row) + matrix[row * dim + col] = column[row]; + } + const auto mean = structured->biasMean(); + std::vector rotated_mean(dim); + double norm = 0; + for (size_t row = 0; row < dim; ++row) { + double dot = 0; + for (size_t col = 0; col < dim; ++col) + dot += double(matrix[row * dim + col]) * mean[col]; + rotated_mean[row] = float(dot); + norm += double(mean[row]) * mean[row]; + } + std::string blob; + auto append = [&](const void *data, size_t bytes) { + blob.append(static_cast(data), bytes); + }; + auto appendFloats = [&](std::span values) { + const uint64_t count = values.size(); + append(&count, sizeof(count)); + append(values.data(), values.size_bytes()); + }; + const uint32_t header[] = {1, bits, 1, 3, 1}; + const uint64_t seed = 42; + const float norm_squared = float(norm); + append(header, sizeof(header)); + append(&seed, sizeof(seed)); + appendFloats(matrix); + appendFloats(structured->centroids()); + appendFloats(mean); + appendFloats(rotated_mean); + append(&norm_squared, sizeof(norm_squared)); + + auto legacy = loadFittedString(blob, dim, bits); + EXPECT_EQ(legacy->rotationOperator().kind(), TurboQuantRotationKind::Dense); + EXPECT_EQ(legacy->rotation().size(), dim * dim); + // Re-saving a dense codec is byte-for-byte the schema-1 layout. + EXPECT_EQ(savedFitted(*legacy), blob); + auto dense_parts = CreateTurboQuantIndexComponents(allocator, legacy); + auto structured_parts = CreateTurboQuantIndexComponents(allocator, structured); + std::unique_ptr dense_pp(dense_parts.preprocessors); + std::unique_ptr structured_pp(structured_parts.preprocessors); + std::unique_ptr> dense_calc(dense_parts.indexCalculator); + std::unique_ptr> structured_calc( + structured_parts.indexCalculator); + const auto q = gaussianVector(dim, 77, 0.04f); + auto a = dense_pp->preprocessQuery(q.data(), dim * sizeof(float)); + auto b = structured_pp->preprocessQuery(q.data(), dim * sizeof(float)); + for (size_t i = 0; i < dim; ++i) + EXPECT_NEAR(unalignedFloat(a.get(), 4 * i), unalignedFloat(b.get(), 4 * i), 1e-6) << i; +} + +TEST_P(TurboQuantTest, RejectsCorruptBlockHadamardFittedState) { + const unsigned bits = GetParam(); + constexpr size_t dim = 768; + auto allocator = VecSimAllocator::newVecsimAllocator(); + auto structured = newCodec(allocator, dim, bits, 42, gaussianVector(dim, 41, 0.02f)); + const auto bytes = savedFitted(*structured); + ASSERT_NO_THROW(loadFittedString(bytes, dim, bits)); + // Layout: header (5 x u32), seed, block, rounds, sign count, signs, perm count, perms, ... + const size_t block_offset = 5 * sizeof(uint32_t) + sizeof(uint64_t); + const size_t signs_offset = block_offset + 3 * sizeof(uint64_t); + const size_t perms_offset = signs_offset + 3 * dim * sizeof(float) + sizeof(uint64_t); + auto expectReject = [&](const std::string &corrupt) { + EXPECT_THROW(loadFittedString(corrupt, dim, bits), std::runtime_error); + }; + for (size_t length : + {size_t(0), block_offset, signs_offset + 7, perms_offset + 5, bytes.size() - 1}) + expectReject(bytes.substr(0, length)); + auto patch = [&](size_t offset, const auto &value) { + auto corrupt = bytes; + std::memcpy(corrupt.data() + offset, &value, sizeof(value)); + return corrupt; + }; + expectReject(patch(block_offset, uint64_t(128))); // wrong block for dim 768 + expectReject(patch(block_offset + 8, uint64_t(2))); // wrong round count + expectReject(patch(signs_offset, 0.5f)); // not +-1/sqrt(256) + expectReject(patch(perms_offset, uint32_t(dim))); // out of range + uint32_t second; + std::memcpy(&second, bytes.data() + perms_offset + 4, sizeof(second)); + expectReject(patch(perms_offset, second)); // duplicate entry + expectReject(patch(0, uint32_t(3))); // unknown schema + // Wrong dimension for the payload, and schema 2 where only dense is valid. + EXPECT_THROW(loadFittedString(bytes, 384, bits), std::runtime_error); + auto small = newCodec(allocator, 96, bits, 42, gaussianVector(96, 43, 0.02f)); + ASSERT_EQ(small->rotationOperator().kind(), TurboQuantRotationKind::Dense); + auto small_bytes = savedFitted(*small); + const uint32_t hadamard_schema = 2; + std::memcpy(small_bytes.data(), &hadamard_schema, sizeof(hadamard_schema)); + EXPECT_THROW(loadFittedString(small_bytes, 96, bits), std::runtime_error); +} + +TEST(TurboQuantRotation, DirectLoadRejectsTruncationAndLeavesStateUntouched) { + // The codec-level size check hides these branches, so exercise the rotation loader directly. + auto allocator = VecSimAllocator::newVecsimAllocator(); + auto owner = newCodec(allocator, 768); + std::stringstream saved; + owner->rotationOperator().saveBlockHadamard(saved); + const std::string bytes = saved.str(); + TurboQuantRotation target(allocator); + { + std::stringstream full(bytes); + target.loadBlockHadamard(full, 768); + } + const std::vector signs(target.scaledSigns().begin(), target.scaledSigns().end()); + ASSERT_TRUE(std::ranges::equal(signs, owner->rotationOperator().scaledSigns())); + const auto x = gaussianVector(768, 5); + for (size_t length : {size_t(10), size_t(24), size_t(24 + 100), size_t(24 + 3 * 768 * 4 + 4), + bytes.size() - 1}) { + std::stringstream truncated(bytes.substr(0, length)); + EXPECT_THROW(target.loadBlockHadamard(truncated, 768), std::runtime_error) << length; + // A failed load keeps the previous, still usable rotation. + EXPECT_TRUE(target.isBlockHadamard()); + EXPECT_TRUE(std::ranges::equal(target.scaledSigns(), signs)); + EXPECT_EQ(applyRotation(target, x), applyRotation(owner->rotationOperator(), x)); + } +} + INSTANTIATE_TEST_SUITE_P(TQ2AndTQ3, TurboQuantTest, ::testing::Values(2U, 3U));