From f1e940a463ef8fbd47f08c3bcd2ce4732a745724 Mon Sep 17 00:00:00 2001 From: gouyt13clear Date: Thu, 3 Dec 2026 12:24:19 +0800 Subject: [PATCH 1/3] feat(rotator)!: add FHT/block rotation and make it the default FHT/Kac transforms a power-of-two window alternately at the start and end of the padded vector and pairs i with i + n/2 in its Kac steps. When the window t is below 3n/4, some inputs keep a path that misses every transform and leave as two fixed spikes of magnitude 1/4, which makes RaBitQ estimates noisier than under a random rotation when data concentrates on those coordinates. FHT/block splits padded_dim into its power-of-two blocks, transforms every block in each of three rounds, and mixes the blocks with a fixed stride gather between rounds, so every coordinate is transformed in every round. It is specified in docs/formats.md, stored as rotator blob method 3, and bit-identical across the generic, AVX2, AVX-512 and NEON backends. New rotators and indexes use FHT/block. Saved FHT/Kac and matrix rotators keep loading and keep their rotation when re-saved; 0.9 cannot read files written with FHT/block. Creating an FHT/Kac rotator now rejects padded_dim above twice its window, which left coordinates untransformed; saved rotators with such padding still load. --- docs/development.md | 10 +- docs/docs/index/hnsw.md | 2 +- docs/docs/index/qg.md | 2 +- docs/docs/index/usage.md | 2 +- docs/docs/rabitq/core_api.md | 14 +- docs/docs/rabitq/estimator.md | 2 +- docs/docs/rabitq/quant_python.md | 4 +- docs/docs/rabitq/rotator.md | 66 +++- docs/formats.md | 22 +- .../clustering/detail/qg_assigner.hpp | 2 +- include/rabitqlib/clustering/rabitqkmeans.hpp | 4 +- .../core/detail/simd/rotator_dispatch.hpp | 50 +++ include/rabitqlib/core/rotator.hpp | 118 ++++++- include/rabitqlib/core/types.hpp | 2 +- include/rabitqlib/index/hnsw/hnsw.hpp | 2 + include/rabitqlib/index/ivf/ivf.hpp | 6 +- include/rabitqlib/index/symqg/qg.hpp | 6 +- python_bindings/quant.pyi | 6 +- python_bindings/quant_bindings.cpp | 88 +++-- python_bindings/rabitq_bindings.cpp | 1 + sample/cpp/core/main.cpp | 2 +- sample/cpp/fastscan/main.cpp | 2 +- src/core/blob.cpp | 39 ++- src/index/hnsw.cpp | 16 +- src/index/ivf_index.cpp | 4 +- src/index/qg.cpp | 7 +- src/index/symqg_index.cpp | 4 +- src/simd/dispatch.cpp | 27 ++ src/simd/fht_block_kernels.hpp | 76 +++++ src/simd/fht_block_scratch.hpp | 11 + src/simd/fht_kernels.hpp | 39 ++- src/simd/portable_generic.cpp | 37 +++ src/simd/rotator_avx2.cpp | 43 +++ src/simd/rotator_avx512.cpp | 39 +++ src/simd/rotator_kernels.hpp | 26 ++ src/simd/rotator_neon.cpp | 20 ++ tests/allocation/core_api_no_alloc.cpp | 16 +- tests/consumer/main.cpp | 8 +- tests/core_consumer/core_static_init.cpp | 21 +- tests/python/fixtures/quant/README.md | 4 +- ...ator_fht_block_dim100_padded128_seed42.bin | Bin 0 -> 112 bytes .../quant/rotator_fht_block_dim420_seed42.bin | Bin 0 -> 232 bytes tests/python/format2_file.py | 15 +- tests/python/test_historical_persistence.py | 23 ++ tests/python/test_ivf_initializers.py | 11 +- tests/python/test_large_dimensions.py | 2 +- tests/python/test_quant_rotator.py | 66 +++- tests/python/test_symqg.py | 4 +- tests/python/test_symqg_api.py | 4 +- tests/python/typing/public_api.py | 5 +- .../rabitqlib/clustering/qgkmeans_test.cpp | 4 +- .../clustering/rabitqkmeans_test.cpp | 4 +- .../index/historical_persistence_test.cpp | 46 +++ tests/unit/rabitqlib/index/ivf_test.cpp | 20 +- tests/unit/rabitqlib/index/qg_test.cpp | 5 +- .../unit/rabitqlib/index/symqg_index_test.cpp | 8 +- tests/unit/rabitqlib/utils/blob_test.cpp | 24 +- tests/unit/rabitqlib/utils/rotator_test.cpp | 302 +++++++++++++++++- 58 files changed, 1247 insertions(+), 146 deletions(-) create mode 100644 src/simd/fht_block_kernels.hpp create mode 100644 src/simd/fht_block_scratch.hpp create mode 100644 tests/python/fixtures/quant/rotator_fht_block_dim100_padded128_seed42.bin create mode 100644 tests/python/fixtures/quant/rotator_fht_block_dim420_seed42.bin diff --git a/docs/development.md b/docs/development.md index 352d0970..c100f039 100644 --- a/docs/development.md +++ b/docs/development.md @@ -897,7 +897,7 @@ Do not provide global fake `omp_*` functions. Test both configurations, includin ### Rotation and padded dimensions -Indexes quantize and search in the rotated, padded domain. FHT/Kac, RaBitQKMeans, QGKMeans, +Indexes quantize and search in the rotated, padded domain. FHT rotation, RaBitQKMeans, QGKMeans, SymphonyQG, IVF (all bit widths), and HNSW pad to multiples of 32. Packed extra-bit and sign codes retain the historical full 64-coordinate blocks and compact final 32-coordinate tails. Binary query planes round their scratch storage up to @@ -996,7 +996,7 @@ Select a cached function pointer through the private shared resolver in `src/simd/dispatch_resolver.hpp`. Core, FastScan and HNSW-RaBitQ have separate dispatch translation units. The x86 order is AVX-512, AVX2/FMA, then the portable generic implementation. ARM64 selects NEON for raw float distances, FastScan, packed-code dot products (1–8 extra -bits), masked sums, binary warmup, HNSW-RaBitQ search, and FHT/Kac rotation including +bits), masked sums, binary warmup, HNSW-RaBitQ search, and FHT/block and FHT/Kac rotation including sign flipping, query-bit transposition, uint8/uint16 scalar quantization, and FastScan LUT construction. Extra-code packing retains a portable scalar implementation. Cache selection in thread-safe function-local statics, including tables; public calls must @@ -1110,10 +1110,12 @@ generic on ARM. Complete estimator runs in the selected backend; non-float template paths remain generic. -**FHT/Kac rotation** +**FHT/block and FHT/Kac rotation** Complete rotation and scaling run in selected ISA translation units; shared AVX intrinsics -preserve the FFHT butterfly order. +preserve the FFHT butterfly order. FHT/block's cross-block gathers use thread-local scratch +that generic code allocates (`src/simd/fht_block_scratch.hpp`), and every backend runs the +same round sequence (`src/simd/fht_block_kernels.hpp`), so results are bit-identical. **Float matrix rotation and PiPNN construction** diff --git a/docs/docs/index/hnsw.md b/docs/docs/index/hnsw.md index 5f5fe86c..35ff450d 100644 --- a/docs/docs/index/hnsw.md +++ b/docs/docs/index/hnsw.md @@ -80,7 +80,7 @@ For build setup, see [C++ integration](../cpp_integration.md). In C++, the construction settings are fields of `HnswOptions`, and `ef_search` and `num_threads` fields of `GraphSearchOptions`. -`seed` controls graph levels and the FHT/Kac rotation (using its low 32 bits). +`seed` controls graph levels and the FHT/block rotation (using its low 32 bits). With identical inputs and parameters, single-threaded construction is reproducible within the same build environment. A seed is drawn unless one is given, and `train` and `add` default to every available CPU, so **default builds are not diff --git a/docs/docs/index/qg.md b/docs/docs/index/qg.md index 3c054ea5..ddc45df1 100644 --- a/docs/docs/index/qg.md +++ b/docs/docs/index/qg.md @@ -116,7 +116,7 @@ The input may be released after `add` returns. ### Random seeds -The seed controls the FHT/Kac rotation, which is the same on every platform, and +The seed controls the FHT/block rotation, which is the same on every platform, and random initialization and fallback edges. PiPNN uses fixed internal seeds. ## Querying diff --git a/docs/docs/index/usage.md b/docs/docs/index/usage.md index 4ced57f8..09b1d14b 100644 --- a/docs/docs/index/usage.md +++ b/docs/docs/index/usage.md @@ -7,7 +7,7 @@ SymphonyQG. Start with the [Python quick start](../quick_start.md) for a complet `IvfIndex`, `HnswIndex`, and `SymqgIndex` accept data and query arrays with shape `(count, dim)`, converted to contiguous float32; the C++ classes of the same names -take row-major float32 buffers. Their FHT/Kac rotation requires +take row-major float32 buffers. Their FHT/block rotation requires `64 <= dim <= 65536`. Supply the original dimension; the indexes pad internally to a multiple of 32. Queries and centroids must have the same original dimension as the indexed data. diff --git a/docs/docs/rabitq/core_api.md b/docs/docs/rabitq/core_api.md index 192d5ac9..bad2f6da 100644 --- a/docs/docs/rabitq/core_api.md +++ b/docs/docs/rabitq/core_api.md @@ -16,7 +16,7 @@ These entry points execute serially. Core/FastScan can be built without OpenMP u The call sequence is `requirements` → `encode` → `prepare_query` → `compute`. This complete example generates 128-dimensional data and a query with a fixed -seed, applies the same seeded [FHT/Kac rotation](rotator.md) to both, and uses +seed, applies the same seeded [FHT/block rotation](rotator.md) to both, and uses unpacked four-bit codes with a zero centroid. It compares the estimated squared L2 distance with the true distance computed from the original vectors. Rotation is explicit caller-side preprocessing; the v1 API does not perform it. @@ -44,7 +44,7 @@ int main() { } std::unique_ptr> rotator(rabitqlib::choose_rotator( - kDim, rabitqlib::RotatorType::FhtKacRotator, 0, 42 + kDim, rabitqlib::RotatorType::FhtBlockRotator, 0, 42 )); std::vector rotated_input(rotator->size()), rotated_query(rotator->size()); rotator->rotate(input.data(), rotated_input.data()); @@ -233,7 +233,10 @@ that allocates on every operation. Allocate application storage and initialize any rotation/configuration objects before entering the hot path. Allocation failures during setup and allocation by exception machinery for invalid calls are outside this guarantee. Other numerical APIs have their own allocation behavior; for example, -`MatrixRotator` uses temporary storage. Callers may supply their own rotation pipeline. +`MatrixRotator` uses temporary storage, and `FhtBlockRotator`, the default, allocates +per-thread scratch on a thread's first `rotate` call (and again for a larger padded +dimension), so call it once on each thread before the hot path. `FhtKacRotator` allocates +nothing after construction. Callers may supply their own rotation pipeline. Concurrent encodes/conversions use separate workspaces and writable outputs. Read-only codes, factors, parameters and prepared query state can be shared; callers synchronize @@ -268,8 +271,9 @@ ctest --no-tests=error --test-dir build-stable-example --output-on-failure The frozen v1 consumer (`tests/fixtures/core_api_v1/consumer.cpp`) is compiled against source-tree and installed packages in CI. The internal workspace resource -uses only caller memory with no upstream allocator. A separate test checks the -FHT rotator's first `rotate` call after construction for allocations. +uses only caller memory with no upstream allocator. A separate test checks that +the FHT/Kac rotator's first `rotate` call after construction makes no allocations, and that +the FHT/block rotator makes none after one warm-up call. The unit suite covers bits 1–9, both metrics, dimensions around packing boundaries, non-padded logical codes, zero residuals, buffer guards, code/factor parity, legacy packed diff --git a/docs/docs/rabitq/estimator.md b/docs/docs/rabitq/estimator.md index f7f06596..adbe8b3f 100644 --- a/docs/docs/rabitq/estimator.md +++ b/docs/docs/rabitq/estimator.md @@ -62,7 +62,7 @@ The expressions below describe the data-code error with an unquantized query under the random-rotation model. They do not include floating-point roundoff or additional query/LUT quantization error. The one-bit probabilistic bound is derived in [RaBitQ, Section 3.2](https://arxiv.org/pdf/2405.12497). -The default [FHT/Kac rotation](rotator.md) efficiently approximates the random +The default [FHT/block rotation](rotator.md) efficiently approximates the random orthogonal rotation, following the Fast JLT implementation approach in SymphonyQG. For one-bit estimation, query/LUT quantization error is typically negligible relative to the data-code error. For higher-bit batch estimation, diff --git a/docs/docs/rabitq/quant_python.md b/docs/docs/rabitq/quant_python.md index 0716cc8c..36f03a6d 100644 --- a/docs/docs/rabitq/quant_python.md +++ b/docs/docs/rabitq/quant_python.md @@ -29,7 +29,7 @@ q = rot.rotate(query[None])[0] c = x.mean(axis=0) # a centroid in the working space ``` -A seeded `"fht_kac"` rotation (the default, for 64 dimensions and up) is identical on every platform. A `"matrix"` rotation drawn from a seed is reproducible only with the same standard library and build, so persist rotators with `to_bytes()` and load them with `Rotator.from_bytes(data)`. Rotators also pickle. +A seeded FHT rotation, `"fht_block"` (the default) or the earlier `"fht_kac"`, both for 64 dimensions and up, is identical on every platform. A `"matrix"` rotation drawn from a seed is reproducible only with the same standard library and build, so persist rotators with `to_bytes()` and load them with `Rotator.from_bytes(data)`. Rotators also pickle. ## Encoding @@ -129,4 +129,4 @@ The layouts are specified in [`docs/formats.md`](https://github.com/VectorDB-NTU `Rotator.to_bytes()` writes a self-describing blob with a magic, a kind, a version and a CRC-32. A change to any layout is a new version, never an edit of an existing one, and golden files in the test suite freeze each version. While the module is provisional, a release may stop reading an old version; reading it then raises `FormatError`. A promise that every released version stays readable comes with stabilisation. -Byte layouts, rotator blobs and seeded FHT/Kac rotations are identical everywhere. Rotated values, codes, factors and distances are identical with the same wheel and CPU features, and otherwise agree within float32 rounding, because kernels are chosen at runtime by CPU. +Byte layouts, rotator blobs and seeded FHT rotations are identical everywhere. Rotated values, codes, factors and distances are identical with the same wheel and CPU features, and otherwise agree within float32 rounding, because kernels are chosen at runtime by CPU. diff --git a/docs/docs/rabitq/rotator.md b/docs/docs/rabitq/rotator.md index 2c134c1d..3a8bb631 100644 --- a/docs/docs/rabitq/rotator.md +++ b/docs/docs/rabitq/rotator.md @@ -1,30 +1,34 @@ # Random rotation Random rotation is the preprocessing step used by RaBitQ's distance estimators. Apply the same sampled transformation to data, centroids and queries. -RaBitQ Library provides FHT/Kac rotation (the default) and a dense random -orthogonal transformation. +RaBitQ Library provides FHT/block rotation (the default since 0.10), the earlier +FHT/Kac rotation, and a dense random orthogonal transformation. -The default FHT/Kac transform is an efficient structured approximation to a +The FHT rotations are efficient structured approximations to a random orthogonal rotation. [SymphonyQG, Section 3.1.4](https://dl.acm.org/doi/abs/10.1145/3709730) describes using a Fast Hadamard-based Fast Johnson–Lindenstrauss Transform to reduce rotation work from $O(D^2)$ to $O(D\log D)$. This library combines -Hadamard transforms, random sign flips and the Givens steps described below. -The transform preserves norms; its sampling distribution approximates the +Hadamard transforms and random sign flips with the mixing steps described below. +The transforms preserve norms; their sampling distribution approximates the uniform random rotation used in the RaBitQ analysis. -The default FHT/Kac rotator supports `float` and accepts input dimensions from 64 through 65,536 inclusive. It pads to a multiple of 32 and uses AVX or NEON kernels +The FHT rotators support `float` and accept input dimensions from 64 through 65,536 inclusive. They pad to a multiple of 32 and use AVX or NEON kernels for power-of-two blocks through `2^16`. Allocate the output using `rotator->size()`, which can exceed the input dimension. RaBitQKMeans, QGKMeans, SymphonyQG, IVF-RaBitQ, and HNSW-RaBitQ also use multiples of 32 for all their supported bit widths. -Index loading preserves the padded domain used when the index was built. +Index loading preserves the rotation and padded domain used when the index was +built: indexes saved before 0.10 keep their FHT/Kac rotation. Reducing the padded dimension changes the sampled rotation and quantization even with the same seed. Newly built indexes can therefore have different recall and latency; smaller padding does not guarantee faster search or unchanged accuracy. -When restoring a standalone rotator saved with earlier 64-dimension padding, -pass that original padded dimension to `choose_rotator` before loading its state. -The saved sign bytes do not contain dimension metadata. +When restoring standalone rotator state saved without a blob, pass its original +type and padded dimension to `choose_rotator` before loading it: state saved before +0.10 is FHT/Kac, and earlier releases padded to multiples of 64. The saved sign bytes +do not contain this metadata. FHT/Kac state with `padded_dim` above `2 * trunc_dim` +(see below) cannot be restored this way, because `choose_rotator` refuses to create such +a rotator; restore it from a blob, which index files and `Rotator.to_bytes()` store. The rotation interfaces are in `rabitqlib/core/rotator.hpp`. @@ -38,7 +42,7 @@ The rotation interfaces are in `rabitqlib/core/rotator.hpp`. int main() { const size_t dim = 769; // deliberately not a multiple of 32 std::unique_ptr> rotator( - rabitqlib::choose_rotator(dim, rabitqlib::RotatorType::FhtKacRotator) + rabitqlib::choose_rotator(dim, rabitqlib::RotatorType::FhtBlockRotator) ); std::vector x(dim, 1.0F); std::vector x_prime(rotator->size()); // 800 elements @@ -56,20 +60,43 @@ padded dimension explicitly if subsequent packed-code operations require a multi of 32. Stored space and per-vector work are proportional to `dim * padded_dim` (quadratic when both dimensions are equal). Constructing the random matrix also performs QR factorization. The `seed` argument -of `choose_rotator` seeds both rotators. FHT/Kac signs come from a fixed mapping of +of `choose_rotator` seeds every rotator. FHT signs come from a fixed mapping of `std::mt19937` output, so a seed gives the same rotation on every platform and standard library. A seeded MatrixRotator is reproducible only with the same standard library and build, because `std::normal_distribution` and QR rounding differ between them. Save and restore the actual rotator state rather than relying on a seed to recreate a matrix rotation. -## FFHT + Kac’s walk +## Kernels On x86-64, transforms use the shared AVX intrinsics in `src/simd/fht_kernels.hpp` within the AVX2 or AVX-512 backend selected at runtime. GCC, Clang, and MSVC use the same implementation without inline assembly or MASM. ARM64 uses NEON kernels in `src/simd/rotator_neon.cpp`; a portable scalar implementation is also available. The backends preserve the FFHT butterfly order, -normalization, four sign-flip passes, and saved rotation state. +normalization, sign-flip passes, and saved rotation state, so a rotation is +bit-identical on every backend. [The format specification](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/docs/formats.md#fht-rotations) +gives both FHT constructions exactly. + +## FHT/block (default) +This rotation samples 3 sequences of random signs. It splits the padded +dimension into its power-of-two blocks, largest first: 768 into 512 and 256, +and 960 into 512, 256, 128 and 64. Each of three rounds: + +1. Flips the coordinates with the round's sequence of random signs. +2. Applies a normalized FFHT to every block. +3. Except after the last round, permutes the coordinates by a fixed stride + coprime to the padded dimension, which spreads every block over all blocks. + +Every coordinate passes through a transform in every round, whatever the padded +dimension. When the padded dimension is a power of two, there is one block. +The permutation needs a second buffer of `padded_dim` floats: each thread allocates +it on its first rotation (and again for a larger padded dimension) and keeps it. + +| Space Consumption | Time Complexity | +| ----------------- | --------------- | +| $3D$ binary values ($3D$ bits) | $O(D\log D)$ | + +## FFHT + Kac’s walk (FHT/Kac) This method is a combination of the well-known Fast Johnson-Lindenstrauss Transformation algorithms based on [Fast Hadamard Transform](https://www.cs.princeton.edu/~chazelle/pubs/FJLT-sicomp09.pdf) and ideas in [Kac’s Walk](https://projecteuclid.org/journals/annals-of-applied-probability/volume-27/issue-1/Kacs-walk-on-n-sphere-mixes-in-nlog-n-steps/10.1214/16-AAP1214.full). It first samples 4 sequences of random signs (i.e., Rademacher random variables). @@ -88,6 +115,17 @@ Otherwise, each round performs the following steps: | ----------------- | --------------- | | $4D$ binary values ($4D$ bits) | $O(D\log D)$ | +When `trunc_dim` is below three quarters of `padded_dim` (for example at 768, 960 +or 1536 dimensions), the two windows and the fixed pairing leave a band of input +coordinates that each keep one path through the Kac steps that misses every +transform: each such input ends with two fixed spikes of magnitude 1/4, at its own +position and `padded_dim / 2` below it. On typical dense embeddings this does not measurably change +RaBitQ's estimates, but data whose variance concentrates on a few such coordinates +gets noisier estimates than under a random rotation. FHT/block has no such band. +A new FHT/Kac rotator requires `padded_dim` at most `2 * trunc_dim`, since larger +padding leaves coordinates untransformed; rotators saved with larger padding still load +from their blob. + This implementation is based on the [FFHT library](https://github.com/FALCONN-LIB/FFHT) developed by Alexandr Andoni, Piotr Indyk, Thijs Laarhoven, Ilya Razenshteyn and Ludwig Schmidt. ## Random orthogonal transformation diff --git a/docs/formats.md b/docs/formats.md index 2f6fd282..30bd823d 100644 --- a/docs/formats.md +++ b/docs/formats.md @@ -2,7 +2,7 @@ This is the specification of the byte formats `rabitqlib.quant` reads and writes. Index files ([format 2](#index-format-2)) use their own container and nest blobs in its sections. While `rabitqlib.quant` is provisional, a release may stop reading an old format version; reading it then raises `rabitqlib.FormatError` (also `quant.FormatError`) instead of returning wrong results. A promise that every released version stays readable comes with stabilisation. -Every format has a version. A change to any layout is a new version, never an edit of an existing one. The golden files in `tests/python/fixtures/quant/` freeze each version and are never regenerated. +Every format has a version. A change to any layout is a new version, never an edit of an existing one. A version may gain a value of a field that its readers reject when unknown, such as the rotator `method`: an older reader then refuses the blob instead of misreading it. The golden files in `tests/python/fixtures/quant/` freeze each version and are never regenerated. All multi-byte fields are little-endian. @@ -75,9 +75,9 @@ Readers check, in order: the length covers the common header, the magic, the kin | Offset | Size | Type | Field | Rule | | --- | --- | --- | --- | --- | -| 40 | 4 | u32 | `method` | 1 = FHT/Kac, 2 = matrix | +| 40 | 4 | u32 | `method` | 1 = FHT/Kac, 2 = matrix, 3 = FHT/block (written since 0.10; earlier readers reject it as an unknown method) | | 44 | 4 | u32 | `scalar` | 1 = float32. 2 = float64 is reserved and rejected in version 1 | -| 48 | 4 | u32 | `dim` | 1–65536 for matrix; 64–65536 for FHT/Kac | +| 48 | 4 | u32 | `dim` | 1–65536 for matrix; 64–65536 for FHT/Kac and FHT/block | | 52 | 4 | u32 | `padded_dim` | A multiple of 32 in `[dim, 65536]` | | 56 | 4 | u32 | `seed` | Informational. Valid only when flag bit 0 (`seed_known`) is set; zero otherwise | | 60 | 4 | — | reserved | Writers write zero; readers reject anything else | @@ -90,8 +90,20 @@ The body is what `Rotator::save()` writes, and `body_bytes` must equal it | --- | --- | --- | | FHT/Kac | The sign-flip bytes | `padded_dim / 2` | | Matrix | The rotation matrix as row-major float32 | `4 * dim * padded_dim` | +| FHT/block | The sign-flip bytes | `3 * padded_dim / 8` | -The body defines the rotation; `seed` only records where it came from. A seeded FHT/Kac rotation is identical on every platform, while a matrix drawn from a seed is reproducible only with the same standard library and build, which is why the matrix itself is stored. +The body defines the rotation; `seed` only records where it came from. A seeded FHT rotation is identical on every platform, while a matrix drawn from a seed is reproducible only with the same standard library and build, which is why the matrix itself is stored. + +#### FHT rotations + +Both FHT methods map a vector of `dim` float32 values, zero-padded to `n = padded_dim`, through rounds of sign flips and Walsh-Hadamard transforms. Every operation below is a float32 operation, performed in the order given, so the result is identical on every platform. + +- **Sign flip of round r.** Bit `i` of round `r` is bit `i % 8` of body byte `r * n / 8 + i / 8`; a set bit negates coordinate `i`. A seeded rotator fills the body with the most significant byte of each successive output of `std::mt19937(seed)`. +- **Transform of `m` consecutive coordinates**, `m` a power of two: butterflies `(a, b) -> (a + b, a - b)`, with `a` the lower coordinate, on all pairs 1 apart, then 2 apart, and so on up to `m / 2` apart (within aligned groups of twice the distance); then every coordinate is multiplied by `1 / sqrt(m)`, computed as a float32 square root and division. + +**FHT/Kac (method 1).** Let `t` be the largest power of two at most `dim`. If `t = n`, there are four rounds, each a sign flip followed by the transform of all `n` coordinates. Otherwise round `r = 0, 1, 2, 3` is a sign flip, the transform of coordinates `[0, t)` for even `r` and `[n - t, n)` for odd `r`, and a Kac step that replaces `(x[i], x[i + n/2])` by `(x[i] + x[i + n/2], x[i] - x[i + n/2])` for `i < n/2`; finally every coordinate is multiplied by 0.25. When `t < 3n/4`, each input `i` in `[t, min(dim, 3n/2 - t))` keeps one path through the Kac steps that misses every transform window: it leaves as two fixed spikes of magnitude 1/4, at outputs `i` and `i - n/2`, which FHT/block avoids. Since 0.10, a new FHT/Kac rotator requires `n <= 2t`, because larger padding leaves coordinates untransformed; readers still accept stored rotators with larger padding. + +**FHT/block (method 3).** The blocks of `n` are its binary digits: `n = 2^k1 + 2^k2 + ...` with `k1 > k2 > ...`, and block `j` covers the next `2^kj` coordinates, starting at coordinate 0. Since `n` is a multiple of 32, every block has at least 32 coordinates. The stride `s` is `floor(618034 * n / 1000000)` with its lowest bit set, increased by 2 until it is coprime to `n`. There are three rounds: round `r = 0, 1, 2` is a sign flip followed by the transform of every block, and after rounds 0 and 1, `x` is replaced by `y` with `y[i] = x[(i * s) mod n]`. Every coordinate passes through a transform in every round, for any `n`. @@ -315,7 +327,7 @@ Besides the rules above, an IVF-RaBitQ reader requires: ### HNSW-RaBitQ files -An HNSW-RaBitQ reader requires `num_points` from 1 to 2^31, `code_bits` from 1 to 9, `raw_type` none, `id_bits = 32`, `dim` at least 64, and an FHT/Kac rotator. In `hnsw_params`: `max_elements` from `num_points` to 2^31; `num_clusters` from 1 to 2^31; `M` from 2 to 10,000, with `upper_max_degree = M` and `base_max_degree = 2 * M`; `ef_construction` at least `M`; a finite positive `level_multiplier`; `max_level` at least 0; `entry_point` below `num_points`; and the reserved field zero. Every level in `hnsw_levels` is at most `max_level`, and the entry point's level equals it. Every record's cluster ID (without the removal mark) is below `num_clusters`, its labels are distinct, its base-layer neighbor count is at most `base_max_degree` and each upper-layer count at most `M`, and every neighbor ID is below `num_points` with at least the level of the list that holds it. +An HNSW-RaBitQ reader requires `num_points` from 1 to 2^31, `code_bits` from 1 to 9, `raw_type` none, `id_bits = 32`, `dim` at least 64, and an FHT/Kac or FHT/block rotator. In `hnsw_params`: `max_elements` from `num_points` to 2^31; `num_clusters` from 1 to 2^31; `M` from 2 to 10,000, with `upper_max_degree = M` and `base_max_degree = 2 * M`; `ef_construction` at least `M`; a finite positive `level_multiplier`; `max_level` at least 0; `entry_point` below `num_points`; and the reserved field zero. Every level in `hnsw_levels` is at most `max_level`, and the entry point's level equals it. Every record's cluster ID (without the removal mark) is below `num_clusters`, its labels are distinct, its base-layer neighbor count is at most `base_max_degree` and each upper-layer count at most `M`, and every neighbor ID is below `num_points` with at least the level of the list that holds it. ### SymphonyQG files diff --git a/include/rabitqlib/clustering/detail/qg_assigner.hpp b/include/rabitqlib/clustering/detail/qg_assigner.hpp index 0334828a..b3d888aa 100644 --- a/include/rabitqlib/clustering/detail/qg_assigner.hpp +++ b/include/rabitqlib/clustering/detail/qg_assigner.hpp @@ -183,7 +183,7 @@ class QGAssigner { dim_, settings.max_degree, settings.metric_type, - RotatorType::FhtKacRotator, + RotatorType::FhtBlockRotator, settings.quantization_bits, settings.seed ); diff --git a/include/rabitqlib/clustering/rabitqkmeans.hpp b/include/rabitqlib/clustering/rabitqkmeans.hpp index a8d37e65..75985562 100644 --- a/include/rabitqlib/clustering/rabitqkmeans.hpp +++ b/include/rabitqlib/clustering/rabitqkmeans.hpp @@ -58,7 +58,7 @@ class RaBitQAssignment { uint32_t num_workers_; MetricType metric_type_; size_t padded_dim_; - rotator_impl::FhtKacRotator rotator_; + rotator_impl::FhtBlockRotator rotator_; std::vector center_; std::vector batch_data_; std::vector> centroid_queries_; @@ -92,7 +92,7 @@ class RaBitQAssignment { , num_batches_(1 + (n - 1) / fastscan::kBatchSize) , num_workers_(static_cast(std::min(num_workers, num_batches_))) , metric_type_(cp.spherical ? METRIC_IP : METRIC_L2) - , padded_dim_(rotator_impl::padding_requirement(d, RotatorType::FhtKacRotator)) + , padded_dim_(rotator_impl::padding_requirement(d, RotatorType::FhtBlockRotator)) , rotator_(d, padded_dim_, cp.seed) , center_(d) , batch_data_(num_batches_ * QGBatchDataMap::data_bytes(padded_dim_), 0) diff --git a/include/rabitqlib/core/detail/simd/rotator_dispatch.hpp b/include/rabitqlib/core/detail/simd/rotator_dispatch.hpp index c835b906..cd983a5f 100644 --- a/include/rabitqlib/core/detail/simd/rotator_dispatch.hpp +++ b/include/rabitqlib/core/detail/simd/rotator_dispatch.hpp @@ -19,6 +19,56 @@ void fht_rotate( const uint8_t* flip ); +// Rotates with the FHT/block construction; scratch storage is thread-local. +void fht_block_rotate( + const float* data, + float* rotated_data, + size_t dim, + size_t padded_dim, + size_t stride, + const uint8_t* flip +); + +// FHT/block rotation (RotatorType::FhtBlockRotator). `scratch` holds padded_dim floats and +// must not overlap `rotated_data`; `stride` is the cross-block permutation stride for +// padded_dim. +void fht_block_rotate_generic( + const float* data, + float* rotated_data, + size_t dim, + size_t padded_dim, + size_t stride, + const uint8_t* flip, + float* scratch +); +void fht_block_rotate_avx2( + const float* data, + float* rotated_data, + size_t dim, + size_t padded_dim, + size_t stride, + const uint8_t* flip, + float* scratch +); +void fht_block_rotate_avx512( + const float* data, + float* rotated_data, + size_t dim, + size_t padded_dim, + size_t stride, + const uint8_t* flip, + float* scratch +); +void fht_block_rotate_neon( + const float* data, + float* rotated_data, + size_t dim, + size_t padded_dim, + size_t stride, + const uint8_t* flip, + float* scratch +); + void flip_sign_generic(const uint8_t* flip, float* data, size_t dim); void kacs_walk_generic(float* data, size_t len); void fht_rotate_generic( diff --git a/include/rabitqlib/core/rotator.hpp b/include/rabitqlib/core/rotator.hpp index fc277b05..03cd05aa 100644 --- a/include/rabitqlib/core/rotator.hpp +++ b/include/rabitqlib/core/rotator.hpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -50,7 +51,7 @@ inline size_t padding_requirement(size_t dim, RotatorType type) { if (type == RotatorType::MatrixRotator) { return dim; } - if (type == RotatorType::FhtKacRotator) { + if (type == RotatorType::FhtKacRotator || type == RotatorType::FhtBlockRotator) { if (dim > std::numeric_limits::max() - 31) { throw std::invalid_argument("Rotator dimension is too large to pad"); } @@ -187,6 +188,14 @@ class FhtKacRotator : public Rotator { size_t dim, size_t padded_dim, uint32_t seed = std::random_device{}() ) : FhtKacRotator(dim, padded_dim, AllocateOnly{}) { + // Beyond twice the transform window, some coordinates are never transformed. + // Loading (AllocateOnly) still accepts such saved rotations. + if (padded_dim > 2 * trunc_dim_) { + throw std::invalid_argument( + "FhtKacRotator padded_dim must be at most twice the largest power of two " + "not above dim" + ); + } // Frozen, portable mapping: the top byte of each mt19937 output. Its output // sequence is fixed by the standard, unlike std::uniform_int_distribution; // GCC 11+ libstdc++'s uniform_int_distribution(0, 255) yields these same @@ -256,10 +265,104 @@ class FhtKacRotator : public Rotator { ); } }; +// FHT/block rotation (method 3 in docs/formats.md). Each of kRounds rounds flips signs and +// applies a normalized Walsh-Hadamard transform to every power-of-two block of padded_dim, +// largest first; a fixed stride permutation mixes the blocks between rounds. Unlike the +// FHT/Kac windows, every coordinate is transformed in every round for any padded_dim. +class FhtBlockRotator : public Rotator { + private: + std::vector flip_; + size_t stride_ = 0; + + static constexpr size_t kByteLen = 8; + + public: + static constexpr size_t kMaxDim = 65536; + static constexpr size_t kRounds = 3; + + explicit FhtBlockRotator( + size_t dim, size_t padded_dim, uint32_t seed = std::random_device{}() + ) + : FhtBlockRotator(dim, padded_dim, AllocateOnly{}) { + // The FHT/Kac mapping: the top byte of each mt19937 output. + std::mt19937 gen(seed); + for (auto& i : flip_) { + i = static_cast(gen() >> 24); + } + } + + FhtBlockRotator(size_t dim, size_t padded_dim, AllocateOnly) + : Rotator(dim, padded_dim) { + if (dim < 64 || padded_dim < dim || padded_dim % 32 != 0 || padded_dim > kMaxDim) { + throw std::invalid_argument("Unsupported dimension for FhtBlockRotator"); + } + flip_.resize(kRounds * (padded_dim / kByteLen)); + stride_ = permutation_stride(padded_dim); + } + ~FhtBlockRotator() override = default; + + // The first odd number from floor(0.618034 * padded_dim) up that is coprime to + // padded_dim. + static size_t permutation_stride(size_t padded_dim) { + size_t stride = + static_cast(static_cast(padded_dim) * 618034 / 1000000) | 1U; + while (std::gcd(stride, padded_dim) != 1) { + stride += 2; + } + return stride; + } + + void load(std::ifstream& input) override { + input.read( + reinterpret_cast(flip_.data()), + static_cast(FhtBlockRotator::dump_bytes()) + ); + } + + void save(std::ofstream& output) const override { + output.write( + reinterpret_cast(flip_.data()), + static_cast(FhtBlockRotator::dump_bytes()) + ); + } + + void load(const char* data) override { + std::memcpy(flip_.data(), data, FhtBlockRotator::dump_bytes()); + } + + void save(char* data) const override { + std::memcpy(data, flip_.data(), FhtBlockRotator::dump_bytes()); + } + + [[nodiscard]] size_t dump_bytes() const override { + return sizeof(uint8_t) * flip_.size(); + } + + FhtBlockRotator(const FhtBlockRotator&) = default; + + FhtBlockRotator& operator=(const FhtBlockRotator& other) { + // Preserve the old dimensions if copying the sign storage fails. + flip_ = other.flip_; + dim_ = other.dim_; + padded_dim_ = other.padded_dim_; + stride_ = other.stride_; + return *this; + } + + void rotate(const float* data, float* rotated_data) const override { + simd::fht_block_rotate( + data, rotated_data, dim_, padded_dim_, stride_, flip_.data() + ); + } +}; + inline std::unique_ptr> make_rotator_for_loading( size_t dim, RotatorType type, size_t padded_dim ) { padded_dim = checked_padded_dimension(dim, type, padded_dim); + if (type == RotatorType::FhtBlockRotator) { + return std::make_unique(dim, padded_dim, AllocateOnly{}); + } if (type == RotatorType::FhtKacRotator) { return std::make_unique(dim, padded_dim, AllocateOnly{}); } @@ -268,18 +371,27 @@ inline std::unique_ptr> make_rotator_for_loading( } // namespace rotator_impl // Return an owning pointer; wrap it in RAII and use size() for the output dimension. -// FHT/Kac supports float; its seed gives the same rotation on every platform. +// FHT/block (the default) and FHT/Kac support float; their seeds give the same rotation on +// every platform. // Matrix rotation supports float/double; its seed reproduces the matrix only with // the same standard library and build, so persist matrix rotators with save(). template Rotator* choose_rotator( size_t dim, - RotatorType type = RotatorType::FhtKacRotator, + RotatorType type = RotatorType::FhtBlockRotator, size_t padded_dim = 0, uint32_t seed = std::random_device{}() ) { padded_dim = rotator_impl::checked_padded_dimension(dim, type, padded_dim); + if (type == RotatorType::FhtBlockRotator) { + if constexpr (std::is_same_v) { + return ::new rotator_impl::FhtBlockRotator(dim, padded_dim, seed); + } else { + throw std::invalid_argument("FhtBlockRotator only supports float"); + } + } + if (type == RotatorType::FhtKacRotator) { if constexpr (std::is_same_v) { return ::new rotator_impl::FhtKacRotator(dim, padded_dim, seed); diff --git a/include/rabitqlib/core/types.hpp b/include/rabitqlib/core/types.hpp index 041c60db..d03351ec 100644 --- a/include/rabitqlib/core/types.hpp +++ b/include/rabitqlib/core/types.hpp @@ -4,7 +4,7 @@ namespace rabitqlib { enum ScalarQuantizerType : uint8_t { RECONSTRUCTION, UNBIASED_ESTIMATION, PLAIN }; -enum class RotatorType : uint8_t { MatrixRotator, FhtKacRotator }; +enum class RotatorType : uint8_t { MatrixRotator, FhtKacRotator, FhtBlockRotator }; namespace quant { struct RabitqConfig { diff --git a/include/rabitqlib/index/hnsw/hnsw.hpp b/include/rabitqlib/index/hnsw/hnsw.hpp index b5c6debb..7a3a349c 100644 --- a/include/rabitqlib/index/hnsw/hnsw.hpp +++ b/include/rabitqlib/index/hnsw/hnsw.hpp @@ -309,6 +309,8 @@ class HierarchicalNSW { float (*ip_func_)(const float*, const uint8_t*, size_t){nullptr}; std::unique_ptr> rotator_; + // FHT/block for new indexes; FHT/Kac for files written before 0.10. + RotatorType rotator_type_ = RotatorType::FhtBlockRotator; quant::RabitqConfig query_config_; diff --git a/include/rabitqlib/index/ivf/ivf.hpp b/include/rabitqlib/index/ivf/ivf.hpp index 0e9a62eb..e71240a1 100644 --- a/include/rabitqlib/index/ivf/ivf.hpp +++ b/include/rabitqlib/index/ivf/ivf.hpp @@ -96,7 +96,7 @@ class IVF { bool read_only_ = false; std::optional seed_; // the construction seed, when known size_t ex_bits_ = 0; // total bits = ex_bits_ + 1; 0 with raw reranking - RotatorType rotator_type_ = RotatorType::FhtKacRotator; + RotatorType rotator_type_ = RotatorType::FhtBlockRotator; std::unique_ptr> rotator_; std::vector clusters_; MetricType metric_type_ = METRIC_L2; // METRIC_IP for the cosine metric @@ -246,7 +246,7 @@ class IVF { size_t num_clusters, size_t total_bits, MetricType metric_type = METRIC_L2, - RotatorType rotator_type = RotatorType::FhtKacRotator, + RotatorType rotator_type = RotatorType::FhtBlockRotator, InitializerType initializer_type = InitializerType::Auto ); @@ -274,7 +274,7 @@ class IVF { size_t total_bits, MetricType metric_type, uint32_t seed, - RotatorType rotator_type = RotatorType::FhtKacRotator, + RotatorType rotator_type = RotatorType::FhtBlockRotator, InitializerType initializer_type = InitializerType::Auto ); diff --git a/include/rabitqlib/index/symqg/qg.hpp b/include/rabitqlib/index/symqg/qg.hpp index b414fba2..37aa7bfd 100644 --- a/include/rabitqlib/index/symqg/qg.hpp +++ b/include/rabitqlib/index/symqg/qg.hpp @@ -93,7 +93,7 @@ class QuantizedGraph { PID entry_point_id_ = 0; MetricType metric_type_ = METRIC_L2; // METRIC_IP for the cosine metric bool cosine_ = false; // normalize data and queries; metric_type_ is METRIC_IP - RotatorType rotator_type_ = RotatorType::FhtKacRotator; + RotatorType rotator_type_ = RotatorType::FhtBlockRotator; size_t quantization_bits_ = 0; // 0: raw vectors, 4/8: packed RaBitQ vectors std::vector centroid_; // rotated global centroid for qg-quant float (*quantized_ip_func_)(const float*, const uint8_t*, size_t) = nullptr; @@ -260,7 +260,7 @@ class QuantizedGraph { size_t dim, size_t max_degree, MetricType metric_type = METRIC_L2, - RotatorType rotator_type = RotatorType::FhtKacRotator, + RotatorType rotator_type = RotatorType::FhtBlockRotator, size_t quantization_bits = 0, uint32_t seed = std::random_device{}() ); @@ -394,7 +394,7 @@ QuantizedGraph( size_t, size_t, MetricType = METRIC_L2, - RotatorType = RotatorType::FhtKacRotator, + RotatorType = RotatorType::FhtBlockRotator, size_t = 0, uint32_t = std::random_device{}() ) -> QuantizedGraph; diff --git a/python_bindings/quant.pyi b/python_bindings/quant.pyi index 44e88e8e..d750a7ed 100644 --- a/python_bindings/quant.pyi +++ b/python_bindings/quant.pyi @@ -45,7 +45,7 @@ class Rotator: self, dim: int, *, - method: Literal["fht_kac", "fht", "matrix"] = "fht_kac", + method: Literal["fht_block", "fht_kac", "fht", "matrix"] = "fht_block", padded_dim: int | None = None, seed: int | None = None, ) -> None: ... @@ -56,8 +56,8 @@ class Rotator: def padded_dim(self) -> int: """Working dimension of rotated vectors.""" @property - def method(self) -> Literal["fht_kac", "matrix"]: - """Canonical method name, 'fht_kac' or 'matrix'.""" + def method(self) -> Literal["fht_block", "fht_kac", "matrix"]: + """Canonical method name: 'fht_block', 'fht_kac' or 'matrix'.""" @property def seed(self) -> int | None: """The seed the rotation was drawn from, or None if unknown.""" diff --git a/python_bindings/quant_bindings.cpp b/python_bindings/quant_bindings.cpp index 8f91198d..1d514e36 100644 --- a/python_bindings/quant_bindings.cpp +++ b/python_bindings/quant_bindings.cpp @@ -1504,6 +1504,7 @@ constexpr size_t kRotatorHeaderBytes = 64; constexpr uint32_t kSeedKnown = 1; constexpr uint32_t kMethodFhtKac = 1; constexpr uint32_t kMethodMatrix = 2; +constexpr uint32_t kMethodFhtBlock = 3; constexpr uint32_t kScalarFloat32 = 1; constexpr uint32_t kScalarFloat64 = 2; @@ -1588,29 +1589,61 @@ class ByteView { // --- Rotator -------------------------------------------------------------------- RotatorType rotator_method(const std::string& method) { + if (method == "fht_block") { + return RotatorType::FhtBlockRotator; + } if (method == "fht_kac" || method == "fht") { return RotatorType::FhtKacRotator; } if (method == "matrix") { return RotatorType::MatrixRotator; } - throw std::invalid_argument("method must be 'fht_kac' (alias 'fht') or 'matrix'"); + throw std::invalid_argument( + "method must be 'fht_block', 'fht_kac' (alias 'fht') or 'matrix'" + ); } const char* method_name(RotatorType type) { - return type == RotatorType::FhtKacRotator ? "fht_kac" : "matrix"; + switch (type) { + case RotatorType::FhtBlockRotator: + return "fht_block"; + case RotatorType::FhtKacRotator: + return "fht_kac"; + case RotatorType::MatrixRotator: + break; + } + return "matrix"; +} + +uint32_t method_id(RotatorType type) { + switch (type) { + case RotatorType::FhtBlockRotator: + return kMethodFhtBlock; + case RotatorType::FhtKacRotator: + return kMethodFhtKac; + case RotatorType::MatrixRotator: + break; + } + return kMethodMatrix; } size_t rotator_body_bytes(RotatorType type, size_t dim, size_t padded_dim) { - return type == RotatorType::FhtKacRotator ? padded_dim / 2 - : sizeof(float) * dim * padded_dim; + switch (type) { + case RotatorType::FhtBlockRotator: + return rotator_impl::FhtBlockRotator::kRounds * (padded_dim / 8); + case RotatorType::FhtKacRotator: + return padded_dim / 2; + case RotatorType::MatrixRotator: + break; + } + return sizeof(float) * dim * padded_dim; } // Python's quant.Rotator: immutable, so copies and threads may share it. class QuantRotator { private: std::shared_ptr> rotator_; - RotatorType type_ = RotatorType::FhtKacRotator; + RotatorType type_ = RotatorType::FhtBlockRotator; size_t dim_ = 0; size_t padded_dim_ = 0; std::optional seed_; @@ -1624,9 +1657,10 @@ class QuantRotator { std::to_string(dim) ); } - if (type == RotatorType::FhtKacRotator && dim < 64) { + if (type != RotatorType::MatrixRotator && dim < 64) { throw std::invalid_argument( - "dim must be at least 64 for method 'fht_kac'; got " + std::to_string(dim) + std::string("dim must be at least 64 for method '") + method_name(type) + + "'; got " + std::to_string(dim) ); } if (padded_dim % 32 != 0 || padded_dim < dim || padded_dim > kMaxRotatorDim) { @@ -1657,6 +1691,15 @@ class QuantRotator { padded_dim_ = padded.is_none() ? (dim == 0 ? 0 : padded_dim(dim)) : checked_padded_dim_argument(padded); check_dimensions(type_, dim_, padded_dim_); + // Saved rotators with larger padding still load: see from_bytes. + const size_t window = size_t{1} << floor_log2(dim_); + if (type_ == RotatorType::FhtKacRotator && padded_dim_ > 2 * window) { + throw std::invalid_argument( + "padded_dim must be at most " + std::to_string(2 * window) + + " for method 'fht_kac' and dim " + std::to_string(dim_) + "; got " + + std::to_string(padded_dim_) + ); + } seed_ = seed.is_none() ? std::random_device{}() : static_cast(checked_seed( seed, std::numeric_limits::max() @@ -1713,9 +1756,7 @@ class QuantRotator { put_u32(&blob[16], static_cast(kRotatorHeaderBytes)); put_u32(&blob[20], seed_.has_value() ? kSeedKnown : 0); put_u64(&blob[24], body); - put_u32( - &blob[40], type_ == RotatorType::FhtKacRotator ? kMethodFhtKac : kMethodMatrix - ); + put_u32(&blob[40], method_id(type_)); put_u32(&blob[44], kScalarFloat32); put_u32(&blob[48], static_cast(dim_)); put_u32(&blob[52], static_cast(padded_dim_)); @@ -1768,7 +1809,8 @@ class QuantRotator { throw FormatError("data has non-zero reserved fields"); } const uint32_t method = get_u32(blob + 40); - if (method != kMethodFhtKac && method != kMethodMatrix) { + if (method != kMethodFhtKac && method != kMethodMatrix && + method != kMethodFhtBlock) { throw FormatError( "data has an unknown rotator method " + std::to_string(method) ); @@ -1781,8 +1823,9 @@ class QuantRotator { throw FormatError("data has an unknown scalar type " + std::to_string(scalar)); } QuantRotator result; - result.type_ = method == kMethodFhtKac ? RotatorType::FhtKacRotator - : RotatorType::MatrixRotator; + result.type_ = method == kMethodFhtKac ? RotatorType::FhtKacRotator + : method == kMethodFhtBlock ? RotatorType::FhtBlockRotator + : RotatorType::MatrixRotator; result.dim_ = get_u32(blob + 48); result.padded_dim_ = get_u32(blob + 52); try { @@ -2037,15 +2080,18 @@ codes : numpy.ndarray of uint8, shape (n, d))doc" Parameters ---------- dim : int - Original vector dimension: 64 to 65536 for 'fht_kac', 1 to 65536 for - 'matrix'. -method : {'fht_kac', 'fht', 'matrix'}, optional - FHT/Kac rotation (default; 'fht' is an alias) or a dense random matrix. + Original vector dimension: 64 to 65536 for 'fht_block' and 'fht_kac', + 1 to 65536 for 'matrix'. +method : {'fht_block', 'fht_kac', 'fht', 'matrix'}, optional + FHT/block rotation (default), the earlier FHT/Kac rotation ('fht' is an + alias), or a dense random matrix. FHT/Kac mixes some coordinates poorly + when padded_dim is not a power of two. padded_dim : int, optional Working dimension, a multiple of 32 in [dim, 65536]. Default is - padded_dim(dim). + padded_dim(dim). For 'fht_kac', at most twice the largest power of two + not above dim. seed : int, optional - Seed in [0, 2**32 - 1]; None (the default) draws one. A seeded FHT/Kac + Seed in [0, 2**32 - 1]; None (the default) draws one. A seeded FHT rotation is identical on every platform; a matrix rotation only with the same standard library and build, so persist rotators with to_bytes. @@ -2068,7 +2114,7 @@ Examples py::init(), py::arg("dim"), py::kw_only(), - py::arg("method") = "fht_kac", + py::arg("method") = "fht_block", py::arg("padded_dim") = py::none(), py::arg("seed") = py::none(), kRotatorDoc @@ -2084,7 +2130,7 @@ Examples .def_property_readonly( "method", &QuantRotator::method, - R"doc(Canonical method name, 'fht_kac' or 'matrix'.)doc" + R"doc(Canonical method name: 'fht_block', 'fht_kac' or 'matrix'.)doc" ) .def_property_readonly( "seed", diff --git a/python_bindings/rabitq_bindings.cpp b/python_bindings/rabitq_bindings.cpp index 55d2f187..e02d7bdf 100644 --- a/python_bindings/rabitq_bindings.cpp +++ b/python_bindings/rabitq_bindings.cpp @@ -80,6 +80,7 @@ PYBIND11_MODULE(_rabitqlib, m) { ) .value("FhtKacRotator", rabitqlib::RotatorType::FhtKacRotator) .value("MatrixRotator", rabitqlib::RotatorType::MatrixRotator) + .value("FhtBlockRotator", rabitqlib::RotatorType::FhtBlockRotator) .export_values(); // Register each index's bindings into the same module diff --git a/sample/cpp/core/main.cpp b/sample/cpp/core/main.cpp index 404b5558..6b0f9839 100644 --- a/sample/cpp/core/main.cpp +++ b/sample/cpp/core/main.cpp @@ -27,7 +27,7 @@ int main() { // Data, centroid and query must use the same rotation and padded domain. std::unique_ptr> rotator( rabitqlib::choose_rotator( - kDim, rabitqlib::RotatorType::FhtKacRotator, 0, 42 + kDim, rabitqlib::RotatorType::FhtBlockRotator, 0, 42 ) ); const size_t padded_dim = rotator->size(); diff --git a/sample/cpp/fastscan/main.cpp b/sample/cpp/fastscan/main.cpp index 37f28bda..7bf3a00a 100644 --- a/sample/cpp/fastscan/main.cpp +++ b/sample/cpp/fastscan/main.cpp @@ -23,7 +23,7 @@ int main() { constexpr size_t kDim = 65, kCount = 49, kExBits = 3; std::unique_ptr> rotator( rabitqlib::choose_rotator( - kDim, rabitqlib::RotatorType::FhtKacRotator, 0, 42 + kDim, rabitqlib::RotatorType::FhtBlockRotator, 0, 42 ) ); const size_t padded_dim = rotator->size(); diff --git a/src/core/blob.cpp b/src/core/blob.cpp index 3d8132aa..10a3b924 100644 --- a/src/core/blob.cpp +++ b/src/core/blob.cpp @@ -18,6 +18,7 @@ constexpr uint32_t kRotatorVersion = 1; constexpr uint32_t kSeedKnown = 1; constexpr uint32_t kMethodFhtKac = 1; constexpr uint32_t kMethodMatrix = 2; +constexpr uint32_t kMethodFhtBlock = 3; constexpr uint32_t kScalarFloat32 = 1; constexpr uint32_t kScalarFloat64 = 2; constexpr size_t kMaxRotatorDim = rotator_impl::FhtKacRotator::kMaxDim; @@ -80,9 +81,11 @@ void check_dimensions(RotatorType type, size_t dim, size_t padded_dim) { std::to_string(dim) ); } - if (type == RotatorType::FhtKacRotator && dim < 64) { + if (type != RotatorType::MatrixRotator && dim < 64) { throw std::invalid_argument( - "dim must be at least 64 for method 'fht_kac'; got " + std::to_string(dim) + std::string("dim must be at least 64 for method '") + + (type == RotatorType::FhtKacRotator ? "fht_kac" : "fht_block") + "'; got " + + std::to_string(dim) ); } if (padded_dim % 32 != 0 || padded_dim < dim || padded_dim > kMaxRotatorDim) { @@ -94,8 +97,27 @@ void check_dimensions(RotatorType type, size_t dim, size_t padded_dim) { } size_t body_bytes(RotatorType type, size_t dim, size_t padded_dim) { - return type == RotatorType::FhtKacRotator ? padded_dim / 2 - : sizeof(float) * dim * padded_dim; + switch (type) { + case RotatorType::FhtKacRotator: + return padded_dim / 2; + case RotatorType::FhtBlockRotator: + return rotator_impl::FhtBlockRotator::kRounds * (padded_dim / 8); + case RotatorType::MatrixRotator: + break; + } + return sizeof(float) * dim * padded_dim; +} + +uint32_t method_id(RotatorType type) { + switch (type) { + case RotatorType::FhtKacRotator: + return kMethodFhtKac; + case RotatorType::FhtBlockRotator: + return kMethodFhtBlock; + case RotatorType::MatrixRotator: + break; + } + return kMethodMatrix; } } // namespace @@ -134,7 +156,7 @@ void encode_rotator_blob( put_u32(out + 16, static_cast(kRotatorBlobHeaderBytes)); put_u32(out + 20, seed.has_value() ? kSeedKnown : 0); put_u64(out + 24, body); - put_u32(out + 40, type == RotatorType::FhtKacRotator ? kMethodFhtKac : kMethodMatrix); + put_u32(out + 40, method_id(type)); put_u32(out + 44, kScalarFloat32); put_u32(out + 48, static_cast(dim)); put_u32(out + 52, static_cast(padded_dim)); @@ -185,7 +207,7 @@ DecodedRotator decode_rotator_blob(const uint8_t* data, size_t size) { throw std::invalid_argument("data has non-zero reserved fields"); } const uint32_t method = get_u32(data + 40); - if (method != kMethodFhtKac && method != kMethodMatrix) { + if (method != kMethodFhtKac && method != kMethodMatrix && method != kMethodFhtBlock) { throw std::invalid_argument( "data has an unknown rotator method " + std::to_string(method) ); @@ -203,8 +225,9 @@ DecodedRotator decode_rotator_blob(const uint8_t* data, size_t size) { } DecodedRotator result; - result.type = - method == kMethodFhtKac ? RotatorType::FhtKacRotator : RotatorType::MatrixRotator; + result.type = method == kMethodFhtKac ? RotatorType::FhtKacRotator + : method == kMethodFhtBlock ? RotatorType::FhtBlockRotator + : RotatorType::MatrixRotator; result.dim = get_u32(data + 48); result.padded_dim = get_u32(data + 52); try { diff --git a/src/index/hnsw.cpp b/src/index/hnsw.cpp index bceedd5e..c67f5da6 100644 --- a/src/index/hnsw.cpp +++ b/src/index/hnsw.cpp @@ -107,11 +107,12 @@ HierarchicalNSW::HierarchicalNSW( rotator_.reset( choose_rotator( dim, - RotatorType::FhtKacRotator, + RotatorType::FhtBlockRotator, round_up_to_multiple(dim_, 32), static_cast(random_seed) ) ); + rotator_type_ = RotatorType::FhtBlockRotator; padded_dim_ = rotator_->size(); assert(padded_dim_ % 32 == 0); assert(padded_dim_ >= dim_); @@ -193,11 +194,11 @@ void HierarchicalNSW::write_file(const char* filename) const { // The rotation was drawn from the low 32 bits of the seed. std::vector rotator( - rabitqlib::detail::rotator_blob_bytes(RotatorType::FhtKacRotator, dim_, padded_dim_) + rabitqlib::detail::rotator_blob_bytes(rotator_type_, dim_, padded_dim_) ); rabitqlib::detail::encode_rotator_blob( *rotator_, - RotatorType::FhtKacRotator, + rotator_type_, dim_, seed_.has_value() ? std::optional(static_cast(*seed_)) : std::nullopt, @@ -333,6 +334,7 @@ void HierarchicalNSW::load(const char* filename) { swap(visited_set_pool_, loaded.visited_set_pool_); swap(ip_func_, loaded.ip_func_); swap(rotator_, loaded.rotator_); + swap(rotator_type_, loaded.rotator_type_); swap(query_config_, loaded.query_config_); swap(raw_dist_func_, loaded.raw_dist_func_); swap(seed_, loaded.seed_); @@ -412,9 +414,8 @@ void HierarchicalNSW::read_legacy(std::ifstream& input) { // Validate pointer-table capacity before allocating it. (void)checked_product(max_elements_, sizeof(LinkStorage)); const size_t link_headers_bytes = checked_product(element_count, sizeof(uint32_t)); - rotator_ = rotator_impl::make_rotator_for_loading( - dim_, RotatorType::FhtKacRotator, padded_dim_ - ); + rotator_type_ = RotatorType::FhtKacRotator; + rotator_ = rotator_impl::make_rotator_for_loading(dim_, rotator_type_, padded_dim_); const size_t rotator_bytes = rotator_->dump_bytes(); const auto payload_start = input.tellg(); @@ -582,10 +583,11 @@ void HierarchicalNSW::read_format2(std::istream& input) { std::string("HNSW index file has an invalid rotator (") + error.what() + ")" ); } - if (rotator.type != RotatorType::FhtKacRotator || rotator.dim != dim_ || + if (rotator.type == RotatorType::MatrixRotator || rotator.dim != dim_ || rotator.padded_dim != padded_dim_) { throw f2::FormatError("HNSW index file rotator does not match its dimensions"); } + rotator_type_ = rotator.type; rotator_ = std::move(rotator.rotator); const size_t centroids_bytes = sizeof(float) * num_clusters_ * padded_dim_; diff --git a/src/index/ivf_index.cpp b/src/index/ivf_index.cpp index d6431c56..415a4371 100644 --- a/src/index/ivf_index.cpp +++ b/src/index/ivf_index.cpp @@ -36,7 +36,7 @@ IvfIndex::IvfIndex(size_t dim, size_t num_clusters, const IvfOptions& options) { options.nbits, options.metric, seed, - RotatorType::FhtKacRotator, + RotatorType::FhtBlockRotator, options.routing ); cp_ = std::make_unique( @@ -119,7 +119,7 @@ Id IvfIndex::add(const float* data, size_t num_points, const AddOptions& options index_->nbits(), index_->metric_type(), index_->seed().value(), - RotatorType::FhtKacRotator, + index_->rotator_type(), index_->initializer_type() ); staged->train(num_points, data, training_parameters(options.num_threads)); diff --git a/src/index/qg.cpp b/src/index/qg.cpp index f0794b77..51bbfdc4 100644 --- a/src/index/qg.cpp +++ b/src/index/qg.cpp @@ -169,7 +169,8 @@ void QuantizedGraph::validate_configuration() const { throw std::invalid_argument("QuantizedGraph dimension must be positive"); } if (rotator_type_ != RotatorType::MatrixRotator && - rotator_type_ != RotatorType::FhtKacRotator) { + rotator_type_ != RotatorType::FhtKacRotator && + rotator_type_ != RotatorType::FhtBlockRotator) { throw std::invalid_argument("QuantizedGraph rotator type is invalid"); } if (max_degree_ == 0 || max_degree_ % fastscan::kBatchSize != 0) { @@ -579,6 +580,10 @@ void QuantizedGraph::load(const char* filename) { } catch (const std::invalid_argument& error) { throw FormatError(error.what()); // stored settings that do not fit } + // These layouts predate FHT/block rotation. + if (loaded.rotator_type_ == RotatorType::FhtBlockRotator) { + throw FormatError("QuantizedGraph rotator type is invalid"); + } if (stored_padded_dim < loaded.dim_ || stored_padded_dim % 32 != 0) { throw FormatError("QuantizedGraph file has an invalid padded dimension"); } diff --git a/src/index/symqg_index.cpp b/src/index/symqg_index.cpp index dd85260d..4c0cfc4d 100644 --- a/src/index/symqg_index.cpp +++ b/src/index/symqg_index.cpp @@ -38,7 +38,7 @@ SymqgIndex::SymqgIndex(size_t dim, const SymqgOptions& options) validate_metric_type(index_detail::stored_metric(options.metric)); // Checked now; the graph is created only on add. if (dim < 64 || dim > rotator_impl::FhtKacRotator::kMaxDim) { - throw std::invalid_argument("Unsupported dimension for FhtKacRotator"); + throw std::invalid_argument("Unsupported dimension for FhtBlockRotator"); } if (options.max_degree == 0 || options.max_degree % fastscan::kBatchSize != 0) { throw std::invalid_argument("max_degree must be a positive multiple of 32"); @@ -107,7 +107,7 @@ Id SymqgIndex::add(const float* data, size_t num_points, size_t num_threads) { dim_, max_degree_, metric_, - RotatorType::FhtKacRotator, + RotatorType::FhtBlockRotator, graph_bits(nbits_), seed ); diff --git a/src/simd/dispatch.cpp b/src/simd/dispatch.cpp index 26394873..f615f12c 100644 --- a/src/simd/dispatch.cpp +++ b/src/simd/dispatch.cpp @@ -4,6 +4,7 @@ #include #include "dispatch_resolver.hpp" +#include "fht_block_scratch.hpp" #include "rabitqlib/core/detail/simd/matrix_dispatch.hpp" #include "rabitqlib/core/detail/simd/pack_excode_dispatch.hpp" #include "rabitqlib/core/detail/simd/quantization_dispatch.hpp" @@ -170,6 +171,32 @@ void fht_rotate( kFhtRotateFn(data, rotated_data, dim, padded_dim, trunc_dim, scale_factor, flip); } +void fht_block_rotate( + const float* data, + float* rotated_data, + size_t dim, + size_t padded_dim, + size_t stride, + const uint8_t* flip +) { + static const auto kFhtBlockRotateFn = RABITQ_RESOLVE_NEON( + fht_block_rotate_neon, + fht_block_rotate_avx512, + fht_block_rotate_avx2, + fht_block_rotate_generic + ); + + kFhtBlockRotateFn( + data, + rotated_data, + dim, + padded_dim, + stride, + flip, + detail::fht_block_scratch(padded_dim) + ); +} + void flip_sign(const uint8_t* flip, float* data, size_t dim) { static const auto kFlipSignFn = RABITQ_RESOLVE_NEON( flip_sign_neon, flip_sign_avx512, flip_sign_avx2, flip_sign_generic diff --git a/src/simd/fht_block_kernels.hpp b/src/simd/fht_block_kernels.hpp new file mode 100644 index 00000000..403c5049 --- /dev/null +++ b/src/simd/fht_block_kernels.hpp @@ -0,0 +1,76 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace rabitqlib::simd { +namespace { + +constexpr size_t kFhtBlockRounds = 3; + +// out[i] = in[(i * stride) mod n] with the sign of out[i] flipped where bit i of `flip` is +// set (the next round's sign flip), for n a multiple of 32 and stride < n. Eight +// independent index chains, one per bit of a flip byte: a single chain of dependent +// additions would bound the loop. +inline void stride_gather( + const float* in, float* out, size_t n, size_t stride, const uint8_t* flip +) { + constexpr size_t kChains = 8; + const size_t step = (kChains * stride) % n; + size_t index[kChains]; + for (size_t chain = 0; chain < kChains; ++chain) { + index[chain] = (chain * stride) % n; + } + for (size_t i = 0; i < n; i += kChains) { + const uint32_t byte = flip[i / kChains]; + for (size_t chain = 0; chain < kChains; ++chain) { + uint32_t bits; + std::memcpy(&bits, in + index[chain], sizeof(bits)); + bits ^= ((byte >> chain) & 1U) << 31; + std::memcpy(out + i + chain, &bits, sizeof(bits)); + index[chain] += step; + index[chain] -= index[chain] >= n ? n : 0; + } + } +} + +template +void fht_block_rotate_impl( + const float* data, + float* rotated_data, + size_t dim, + size_t padded_dim, + size_t stride, + const uint8_t* flip, + float* scratch +) { + std::memmove(rotated_data, data, sizeof(float) * dim); + std::fill(rotated_data + dim, rotated_data + padded_dim, 0.0F); + float* current = rotated_data; + float* next = scratch; + FlipSign(flip, current, padded_dim); + for (size_t round = 0; round < kFhtBlockRounds; ++round) { + size_t offset = 0; + for (size_t block = size_t{1} << 16; block >= 32; block /= 2) { + if ((padded_dim & block) != 0) { + Fht(current + offset, block, 1.0F / std::sqrt(static_cast(block))); + offset += block; + } + } + if (round + 1 < kFhtBlockRounds) { + Gather( + current, next, padded_dim, stride, flip + ((round + 1) * (padded_dim / 8)) + ); + std::swap(current, next); + } + } + // An even number of gathers leaves the result in rotated_data. + static_assert(kFhtBlockRounds % 2 == 1); +} + +} // namespace +} // namespace rabitqlib::simd diff --git a/src/simd/fht_block_scratch.hpp b/src/simd/fht_block_scratch.hpp new file mode 100644 index 00000000..df960f07 --- /dev/null +++ b/src/simd/fht_block_scratch.hpp @@ -0,0 +1,11 @@ +#pragma once + +#include + +namespace rabitqlib::simd::detail { + +// Returns padded_dim floats of thread-local storage for the FHT/block gathers. Defined in +// portable_generic.cpp so that thread-local initialization stays in generic code. +float* fht_block_scratch(size_t padded_dim); + +} // namespace rabitqlib::simd::detail diff --git a/src/simd/fht_kernels.hpp b/src/simd/fht_kernels.hpp index 20ca0d0b..d3426334 100644 --- a/src/simd/fht_kernels.hpp +++ b/src/simd/fht_kernels.hpp @@ -110,12 +110,47 @@ inline void fht_eight_registers(float* data, size_t stride, float factor = 1.0F) _mm256_storeu_ps(data + 7 * stride, h); } +// The 32-point transform used by FHT/block rotation: three in-register stages, +// then the stride-8 and stride-16 butterflies across four registers. +template +inline void fht_four_registers(float* data, float factor) { + __m256 a = fht_lane_stage<0>(_mm256_loadu_ps(data)); + __m256 b = fht_lane_stage<0>(_mm256_loadu_ps(data + 8)); + __m256 c = fht_lane_stage<0>(_mm256_loadu_ps(data + 16)); + __m256 d = fht_lane_stage<0>(_mm256_loadu_ps(data + 24)); + a = fht_lane_stage<1>(a); + b = fht_lane_stage<1>(b); + c = fht_lane_stage<1>(c); + d = fht_lane_stage<1>(d); + a = fht_lane_stage<2>(a); + b = fht_lane_stage<2>(b); + c = fht_lane_stage<2>(c); + d = fht_lane_stage<2>(d); + fht_butterfly(a, b); + fht_butterfly(c, d); + fht_butterfly(a, c); + fht_butterfly(b, d); + if constexpr (Normalize) { + const __m256 multiplier = _mm256_set1_ps(factor); + a = _mm256_mul_ps(a, multiplier); + b = _mm256_mul_ps(b, multiplier); + c = _mm256_mul_ps(c, multiplier); + d = _mm256_mul_ps(d, multiplier); + } + _mm256_storeu_ps(data, a); + _mm256_storeu_ps(data + 8, b); + _mm256_storeu_ps(data + 16, c); + _mm256_storeu_ps(data + 24, d); +} + // Only the outermost merge applies the rotation scale, after every butterfly. template void fht_impl(float* data, float factor = 1.0F) { - static_assert(LogDim >= 6 && LogDim <= 16); + static_assert(LogDim >= 5 && LogDim <= 16); constexpr size_t kDim = size_t{1} << LogDim; - if constexpr (LogDim == 6) { + if constexpr (LogDim == 5) { + fht_four_registers(data, factor); + } else if constexpr (LogDim == 6) { fht_eight_registers(data, 8, factor); } else if constexpr (LogDim < 9) { fht_impl(data); diff --git a/src/simd/portable_generic.cpp b/src/simd/portable_generic.cpp index 00a5edc0..fd87ff4d 100644 --- a/src/simd/portable_generic.cpp +++ b/src/simd/portable_generic.cpp @@ -4,7 +4,10 @@ #include #include #include +#include +#include "fht_block_kernels.hpp" +#include "fht_block_scratch.hpp" #include "rabitqlib/core/detail/simd/pack_excode_dispatch.hpp" #include "rabitqlib/core/detail/simd/rotator_dispatch.hpp" #include "rabitqlib/core/detail/simd/space_dispatch.hpp" @@ -370,4 +373,38 @@ void fht_rotate_generic( } } } + +namespace { +void fht_normalized_generic(float* data, size_t len, float factor) { + fht(data, len); + for (size_t i = 0; i < len; ++i) { + data[i] *= factor; + } +} +} // namespace + +void fht_block_rotate_generic( + const float* data, + float* rotated_data, + size_t dim, + size_t padded_dim, + size_t stride, + const uint8_t* flip, + float* scratch +) { + fht_block_rotate_impl( + data, rotated_data, dim, padded_dim, stride, flip, scratch + ); +} + +namespace detail { +float* fht_block_scratch(size_t padded_dim) { + // Rotation does not re-enter itself; keep the largest buffer on each thread. + thread_local std::vector scratch; + if (scratch.size() < padded_dim) { + scratch.resize(padded_dim); + } + return scratch.data(); +} +} // namespace detail } // namespace rabitqlib::simd diff --git a/src/simd/rotator_avx2.cpp b/src/simd/rotator_avx2.cpp index ef934222..bb37b591 100644 --- a/src/simd/rotator_avx2.cpp +++ b/src/simd/rotator_avx2.cpp @@ -67,4 +67,47 @@ void fht_rotate_avx2( ); } +namespace { +// stride_gather with hardware gathers; indices stay below 2 * n, so signed compares work. +void stride_gather_avx2( + const float* in, float* out, size_t n, size_t stride, const uint8_t* flip +) { + alignas(32) int32_t first[8]; + for (size_t lane = 0; lane < 8; ++lane) { + first[lane] = static_cast((lane * stride) % n); + } + __m256i index = _mm256_load_si256(reinterpret_cast(first)); + const __m256i limit = _mm256_set1_epi32(static_cast(n)); + const __m256i last = _mm256_set1_epi32(static_cast(n - 1)); + const __m256i step = _mm256_set1_epi32(static_cast((8 * stride) % n)); + const __m256i bit_select = + _mm256_setr_epi32(0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80); + const __m256i sign = _mm256_set1_epi32(std::numeric_limits::min()); + for (size_t i = 0; i < n; i += 8) { + const __m256i bits = _mm256_and_si256(_mm256_set1_epi32(flip[i / 8]), bit_select); + const __m256i flips = _mm256_and_si256(_mm256_cmpeq_epi32(bits, bit_select), sign); + const __m256 values = _mm256_i32gather_ps(in, index, 4); + _mm256_storeu_ps(out + i, _mm256_xor_ps(values, _mm256_castsi256_ps(flips))); + index = _mm256_add_epi32(index, step); + index = _mm256_sub_epi32( + index, _mm256_and_si256(_mm256_cmpgt_epi32(index, last), limit) + ); + } +} +} // namespace + +void fht_block_rotate_avx2( + const float* data, + float* rotated_data, + size_t dim, + size_t padded_dim, + size_t stride, + const uint8_t* flip, + float* scratch +) { + fht_block_rotate_impl( + data, rotated_data, dim, padded_dim, stride, flip, scratch + ); +} + } // namespace rabitqlib::simd diff --git a/src/simd/rotator_avx512.cpp b/src/simd/rotator_avx512.cpp index b0d11d00..1e4a77c7 100644 --- a/src/simd/rotator_avx512.cpp +++ b/src/simd/rotator_avx512.cpp @@ -31,6 +31,31 @@ void kacs_walk_flip(const uint8_t* flip, float* data, size_t len) { } } +// stride_gather with hardware gathers. +void stride_gather_avx512( + const float* in, float* out, size_t n, size_t stride, const uint8_t* flip +) { + alignas(64) uint32_t first[16]; + for (size_t lane = 0; lane < 16; ++lane) { + first[lane] = static_cast((lane * stride) % n); + } + __m512i index = _mm512_load_si512(first); + const __m512i limit = _mm512_set1_epi32(static_cast(n)); + const __m512i step = _mm512_set1_epi32(static_cast((16 * stride) % n)); + const __m512 sign = + _mm512_castsi512_ps(_mm512_set1_epi32(std::numeric_limits::min())); + for (size_t i = 0; i < n; i += 16) { + uint16_t bits; + std::memcpy(&bits, flip + (i / 8), sizeof(bits)); + const __m512 values = _mm512_i32gather_ps(index, in, 4); + _mm512_storeu_ps(out + i, _mm512_mask_xor_ps(values, bits, values, sign)); + index = _mm512_add_epi32(index, step); + index = _mm512_mask_sub_epi32( + index, _mm512_cmpge_epu32_mask(index, limit), index, limit + ); + } +} + } // namespace void flip_sign_avx512(const uint8_t* flip, float* data, size_t dim) { @@ -123,4 +148,18 @@ void fht_rotate_avx512( ); } +void fht_block_rotate_avx512( + const float* data, + float* rotated_data, + size_t dim, + size_t padded_dim, + size_t stride, + const uint8_t* flip, + float* scratch +) { + fht_block_rotate_impl( + data, rotated_data, dim, padded_dim, stride, flip, scratch + ); +} + } // namespace rabitqlib::simd diff --git a/src/simd/rotator_kernels.hpp b/src/simd/rotator_kernels.hpp index 743c6edc..8eff58a0 100644 --- a/src/simd/rotator_kernels.hpp +++ b/src/simd/rotator_kernels.hpp @@ -5,6 +5,7 @@ #include #include +#include "fht_block_kernels.hpp" #include "fht_kernels.hpp" namespace rabitqlib::simd { @@ -36,6 +37,31 @@ inline void kacs_walk_rescale(float* data, size_t dim, float factor) { } #endif } +// Normalized transform of one FHT/block block of 32 to 65536 floats. +inline void fht_normalized(float* data, size_t len, float factor) { +#define RABITQ_FHT_BLOCK_CASE(log_dim) \ + case size_t{1} << (log_dim): \ + fht_impl(data, factor); \ + return; + switch (len) { + RABITQ_FHT_BLOCK_CASE(5) + RABITQ_FHT_BLOCK_CASE(6) + RABITQ_FHT_BLOCK_CASE(7) + RABITQ_FHT_BLOCK_CASE(8) + RABITQ_FHT_BLOCK_CASE(9) + RABITQ_FHT_BLOCK_CASE(10) + RABITQ_FHT_BLOCK_CASE(11) + RABITQ_FHT_BLOCK_CASE(12) + RABITQ_FHT_BLOCK_CASE(13) + RABITQ_FHT_BLOCK_CASE(14) + RABITQ_FHT_BLOCK_CASE(15) + RABITQ_FHT_BLOCK_CASE(16) + default: + throw std::invalid_argument("Unsupported block size for FhtBlockRotator"); + } +#undef RABITQ_FHT_BLOCK_CASE +} + // Both backends and all compilers use the same AVX butterfly ordering. template void fht_rotate_impl( diff --git a/src/simd/rotator_neon.cpp b/src/simd/rotator_neon.cpp index 44c087ea..842ac268 100644 --- a/src/simd/rotator_neon.cpp +++ b/src/simd/rotator_neon.cpp @@ -6,6 +6,7 @@ #include #include +#include "fht_block_kernels.hpp" #include "rabitqlib/core/detail/simd/rotator_dispatch.hpp" namespace rabitqlib::simd { @@ -77,6 +78,11 @@ void rescale(float* data, size_t dim, float factor) { vst1q_f32(data + i, vmulq_f32(vld1q_f32(data + i), scale)); } } + +void fht_normalized(float* data, size_t len, float factor) { + fht(data, len); + rescale(data, len, factor); +} } // namespace void flip_sign_neon(const uint8_t* flip, float* data, size_t dim) { @@ -149,4 +155,18 @@ void fht_rotate_neon( rescale(rotated_data, padded_dim, 0.25F); } } + +void fht_block_rotate_neon( + const float* data, + float* rotated_data, + size_t dim, + size_t padded_dim, + size_t stride, + const uint8_t* flip, + float* scratch +) { + fht_block_rotate_impl( + data, rotated_data, dim, padded_dim, stride, flip, scratch + ); +} } // namespace rabitqlib::simd diff --git a/tests/allocation/core_api_no_alloc.cpp b/tests/allocation/core_api_no_alloc.cpp index c861933c..30429b8e 100644 --- a/tests/allocation/core_api_no_alloc.cpp +++ b/tests/allocation/core_api_no_alloc.cpp @@ -230,8 +230,8 @@ int main() { f ); } - // Rotation remains optional. The existing default FHT path is allocation-free - // after constructing its state, including its first rotate call. + // Rotation remains optional. FHT/Kac is allocation-free after constructing its + // state, including its first rotate call. std::unique_ptr> rotation( rabitqlib::choose_rotator( 65, rabitqlib::RotatorType::FhtKacRotator, 0, 42 @@ -241,6 +241,18 @@ int main() { Watch guard; rotation->rotate(data.data(), rotated.data()); } + // FHT/block, the default, sizes per-thread gather scratch on a thread's first + // rotate at a given padded dimension; after that warm-up call it allocates nothing. + std::unique_ptr> block( + rabitqlib::choose_rotator( + 65, rabitqlib::RotatorType::FhtBlockRotator, 0, 42 + ) + ); + block->rotate(data.data(), rotated.data()); + { + Watch guard; + block->rotate(data.data(), rotated.data()); + } } catch (const std::exception& error) { std::fprintf(stderr, "Unexpected error: %s\n", error.what()); return 3; diff --git a/tests/consumer/main.cpp b/tests/consumer/main.cpp index db6e77a7..c169d513 100644 --- a/tests/consumer/main.cpp +++ b/tests/consumer/main.cpp @@ -114,10 +114,12 @@ int main() { return 1; } - // Exercise the compiled IVF and SymphonyQG implementations with both - // rotators, including Eigen-backed ownership across the library boundary. + // Exercise the compiled IVF and SymphonyQG implementations with every + // rotator, including Eigen-backed ownership across the library boundary. for (const auto rotator : - {rabitqlib::RotatorType::FhtKacRotator, rabitqlib::RotatorType::MatrixRotator}) { + {rabitqlib::RotatorType::FhtBlockRotator, + rabitqlib::RotatorType::FhtKacRotator, + rabitqlib::RotatorType::MatrixRotator}) { rabitqlib::ivf::IVF index( kPoints, kDimension, diff --git a/tests/core_consumer/core_static_init.cpp b/tests/core_consumer/core_static_init.cpp index c70b435d..ad133ec1 100644 --- a/tests/core_consumer/core_static_init.cpp +++ b/tests/core_consumer/core_static_init.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include "rabitqlib/core/api.hpp" @@ -60,7 +61,25 @@ const bool kBeforeMain = [] { } } } - return true; + // FHT/block (its dispatch and thread-local scratch) before main, against the FNV-1a + // hash an independent NumPy model gives for this exactly representable input. + std::array exact{}, block_rotated{}; + for (size_t i = 0; i < exact.size(); ++i) { + exact[i] = static_cast(static_cast((i * 37) % 101) - 50) / 16.0F; + } + block_rotated.fill(12345.0F); + rabitqlib::rotator_impl::FhtBlockRotator block(64, 64, 42); + block.rotate(exact.data(), block_rotated.data()); + uint64_t hash = 14695981039346656037ULL; + for (const float value : block_rotated) { + uint32_t bits = 0; + std::memcpy(&bits, &value, sizeof(bits)); + for (size_t byte = 0; byte < sizeof(bits); ++byte) { + hash ^= (bits >> (8 * byte)) & 0xFFU; + hash *= 1099511628211ULL; + } + } + return hash == 0x488ec0290379df2bULL; }(); } // namespace diff --git a/tests/python/fixtures/quant/README.md b/tests/python/fixtures/quant/README.md index 4df4470b..05fdf359 100644 --- a/tests/python/fixtures/quant/README.md +++ b/tests/python/fixtures/quant/README.md @@ -1,6 +1,8 @@ These files freeze the `rabitqlib.quant` byte formats described in [docs/formats.md](../../../../docs/formats.md). They were written once by the code that introduced each format and are never regenerated: a test failure against them means a format changed, which needs a new format version rather than new fixtures. -`rotator_fht_kac_dim64_seed0.bin` and `rotator_fht_kac_dim100_padded128_seed42.bin` are rotator blobs (kind 1, version 1) from `quant.Rotator(64, seed=0).to_bytes()` and `quant.Rotator(100, padded_dim=128, seed=42).to_bytes()`. The first body equals the frozen FHT/Kac sign flips for `(64, 64, seed 0)` in `tests/unit/rabitqlib/utils/rotator_test.cpp` (FNV-1a hash `0x7fcf0925975a6086`). +`rotator_fht_kac_dim64_seed0.bin` and `rotator_fht_kac_dim100_padded128_seed42.bin` are rotator blobs (kind 1, version 1) from `quant.Rotator(64, seed=0).to_bytes()` and `quant.Rotator(100, padded_dim=128, seed=42).to_bytes()`, written when `"fht_kac"` was the default method. The first body equals the frozen FHT/Kac sign flips for `(64, 64, seed 0)` in `tests/unit/rabitqlib/utils/rotator_test.cpp` (FNV-1a hash `0x7fcf0925975a6086`). + +`rotator_fht_block_dim100_padded128_seed42.bin` and `rotator_fht_block_dim420_seed42.bin` are rotator blobs (kind 1, version 1, method 3) from `quant.Rotator(100, padded_dim=128, seed=42).to_bytes()` and `quant.Rotator(420, seed=42).to_bytes()` in 0.10, whose default method is `"fht_block"`. The second has three blocks (256, 128 and 64 coordinates). Before they were frozen, an independent NumPy implementation of [docs/formats.md](../../../../docs/formats.md#fht-rotations) checked every header field, the checksum, the sign bytes (the `std::mt19937` mapping) and the rotation of a fixed input bit for bit. `packed_codes_nbits{1..8}_n3_d96.bin` are `quant.pack_codes(codes, nbits=nbits).tobytes()` (packed-codes version 1) for three rows of 96 coordinates, which covers one full 64-coordinate block and a 32-coordinate tail, with diff --git a/tests/python/fixtures/quant/rotator_fht_block_dim100_padded128_seed42.bin b/tests/python/fixtures/quant/rotator_fht_block_dim100_padded128_seed42.bin new file mode 100644 index 0000000000000000000000000000000000000000..43beb8681dfaf990c9b9ff105e1e2e32de28c9e8 GIT binary patch literal 112 zcmWG?bP9Cx@pocmU|;}Y2Pka-q(Q*ozOyZeW(H!AdQqJXWu^Icdt=UO!{40R)N~asU7T literal 0 HcmV?d00001 diff --git a/tests/python/fixtures/quant/rotator_fht_block_dim420_seed42.bin b/tests/python/fixtures/quant/rotator_fht_block_dim420_seed42.bin new file mode 100644 index 0000000000000000000000000000000000000000..4c6eb150869b1949081d4f6e80e841f7cd1e0d57 GIT binary patch literal 232 zcmWG?bP9Cx@pocmU|;}Y2PnM)NQ1z_pQ&CTni+^e@=Jik0U*`_2?9a<>Cbw*kI$T; zUZgI`S9&*erpnf3tb9LqT>W6ip!ZL2p6{GC#ynQ9wmE6a++IIptxLpD&NEJI{yn{% z`_Alj+QkCQpFVz{a4yN0Mbdh`ZNWPEIdxY#bY7%5>8(8IpVMmEJyD int: return struct.unpack_from(" int: + """The rotator blob's method: 1 FHT/Kac, 2 matrix, 3 FHT/block.""" + return struct.unpack_from(" None: """Recompute section and header checksums after a same-size edit in place.""" table, count = struct.unpack_from(" tuple[bytes, bytes | None]: """Convert an IVF-RaBitQ format-2 file to the layout releases up to 0.8 wrote. Returns the RABQIDX1 version 2 index and, for HNSW routing, its ``.hnsw`` - sidecar. Tests use it to build earlier layouts that no fixture covers. + sidecar. Tests use it to build earlier layouts that no fixture covers. Those + layouts predate FHT/block rotation (rotator method 3): such a file gets an + FHT/Kac rotation of the same dimensions instead, so its codes no longer match + its rotation and its search results differ from the source file's. """ assert data[:8] == MAGIC present = sections(data) @@ -69,7 +77,10 @@ def to_rabqidx1(data: bytes) -> tuple[bytes, bytes | None]: num_points = struct.unpack_from(" None: - rotator = quant.Rotator(64, method="fht_kac", seed=0) + rotator = quant.Rotator(64, method="fht_block", seed=0) + quant.Rotator(64, method="fht_kac") assert_type(rotator.padded_dim, int) assert_type(rotator.seed, int | None) - assert_type(rotator.method, Literal["fht_kac", "matrix"]) + assert_type(rotator.method, Literal["fht_block", "fht_kac", "matrix"]) residuals = rotator.rotate(x, num_threads=1) assert_type(residuals, npt.NDArray[np.float32]) assert_type(quant.Rotator.from_bytes(rotator.to_bytes()), quant.Rotator) diff --git a/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp b/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp index 19b300eb..a4a4d3be 100644 --- a/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp +++ b/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp @@ -176,7 +176,7 @@ TEST(QGAssignerTest, QuantizedSearchReturnsExactDistancesToOriginalCentroids) { ); symqg::QuantizedGraph graph( - kClusters, kDim, 32, metric, RotatorType::FhtKacRotator, bits, 42 + kClusters, kDim, 32, metric, RotatorType::FhtBlockRotator, bits, 42 ); symqg::QGBuilder builder(graph, 33, centroids.data(), 1, 42); builder.build(2); @@ -225,7 +225,7 @@ TEST(QGAssignerTest, GroupedQueriesPreserveIndependentSearchHintsAcrossRebuilds) kDim, kClusters, 32, 64, kEf, 1, threads, 42, metric, bits ); symqg::QuantizedGraph graph( - kClusters, kDim, 32, metric, RotatorType::FhtKacRotator, bits, 42 + kClusters, kDim, 32, metric, RotatorType::FhtBlockRotator, bits, 42 ); symqg::QGBuilder builder( graph, diff --git a/tests/unit/rabitqlib/clustering/rabitqkmeans_test.cpp b/tests/unit/rabitqlib/clustering/rabitqkmeans_test.cpp index d7d25c22..78dbb3f1 100644 --- a/tests/unit/rabitqlib/clustering/rabitqkmeans_test.cpp +++ b/tests/unit/rabitqlib/clustering/rabitqkmeans_test.cpp @@ -50,8 +50,8 @@ std::vector scalar_rabitq_assignments( const size_t clusters = centroids.size() / dim; const size_t points = data.size() / dim; const size_t padded = - rotator_impl::padding_requirement(dim, RotatorType::FhtKacRotator); - rotator_impl::FhtKacRotator rotator(dim, padded, seed); + rotator_impl::padding_requirement(dim, RotatorType::FhtBlockRotator); + rotator_impl::FhtBlockRotator rotator(dim, padded, seed); std::vector center(dim), rotated_center(padded), rotated(points * padded); for (size_t j = 0; j < dim; ++j) { double sum = 0; diff --git a/tests/unit/rabitqlib/index/historical_persistence_test.cpp b/tests/unit/rabitqlib/index/historical_persistence_test.cpp index 470497c4..3f23b867 100644 --- a/tests/unit/rabitqlib/index/historical_persistence_test.cpp +++ b/tests/unit/rabitqlib/index/historical_persistence_test.cpp @@ -412,6 +412,52 @@ TEST(HistoricalPersistenceTest, MalformedEarlierHeadersRaiseFormatError) { fs::remove(path); } +// The earlier layouts store the rotator type as a byte and predate FHT/block rotation, +// so its value (2) is rejected rather than read with an FHT/Kac-sized rotator. +TEST(HistoricalPersistenceTest, EarlierLayoutsRejectFhtBlockRotatorType) { + namespace fs = std::filesystem; + const fs::path path = + fs::temp_directory_path() / rabitq_test::process_unique("historical_rotator"); + struct Case { + const char* fixture; + size_t offset; // the rotator type byte + const char* message; + }; + const Case cases[] = { + {"ivf4_flat_l2", 60, "Invalid IVF rotator type"}, + {"qg4_l2", 48, "QuantizedGraph rotator type is invalid"}, + {"qg0_ip", 36, "QuantizedGraph rotator type is invalid"}, + }; + for (const auto& c : cases) { + SCOPED_TRACE(c.fixture); + fs::copy_file( + fs::path(RABITQ_TEST_FIXTURE_ROOT) / "v0.8.3" / + (std::string(c.fixture) + ".index"), + path, + fs::copy_options::overwrite_existing + ); + { + std::fstream file(path, std::ios::binary | std::ios::in | std::ios::out); + file.seekg(static_cast(c.offset)); + ASSERT_EQ(file.get(), static_cast(RotatorType::FhtKacRotator)); + file.seekp(static_cast(c.offset)); + file.put(static_cast(RotatorType::FhtBlockRotator)); + } + const std::string file = path.string(); + try { + if (c.fixture[0] == 'i') { + ivf::IVF index; + index.load(file.c_str()); + } else { + symqg::QuantizedGraph index; + index.load(file.c_str()); + } + ADD_FAILURE() << "accepted"; + } catch (const FormatError& error) { EXPECT_STREQ(error.what(), c.message); } + } + fs::remove(path); +} + // Truncated files of the earlier layouts raise FormatError like format-2 files. TEST(HistoricalPersistenceTest, TruncatedEarlierFilesRaiseFormatError) { namespace fs = std::filesystem; diff --git a/tests/unit/rabitqlib/index/ivf_test.cpp b/tests/unit/rabitqlib/index/ivf_test.cpp index 8919d95a..3a33cea8 100644 --- a/tests/unit/rabitqlib/index/ivf_test.cpp +++ b/tests/unit/rabitqlib/index/ivf_test.cpp @@ -244,7 +244,10 @@ TEST(IvfSearchTest, RawRerankingUsesOriginalCoordinates) { data[i] = static_cast(i % 71) / 71.0F; } for (auto metric : {METRIC_L2, METRIC_IP}) { - for (auto rotator : {RotatorType::FhtKacRotator, RotatorType::MatrixRotator}) { + for (auto rotator : + {RotatorType::FhtBlockRotator, + RotatorType::FhtKacRotator, + RotatorType::MatrixRotator}) { IVF index(kCount, kDim, 1, 32, metric, rotator); EXPECT_EQ(index.nbits(), 32); index.construct(data.data(), centroid.data(), clusters.data(), false, 1); @@ -443,7 +446,10 @@ TEST(IvfPersistenceTest, ReloadsRawAndQuantizedStorage) { const rabitq_test::TempFile path_file("rabitq_ivf_storage.index"); const std::string& path = path_file.path(); IVF loaded; - for (auto rotator : {RotatorType::FhtKacRotator, RotatorType::MatrixRotator}) { + for (auto rotator : + {RotatorType::FhtBlockRotator, + RotatorType::FhtKacRotator, + RotatorType::MatrixRotator}) { for (size_t bits : {32UL, 1UL, 2UL, 3UL, 4UL, 5UL, 6UL, 7UL, 8UL, 9UL}) { IVF index(kCount, kDim, 1, bits, METRIC_L2, rotator); index.construct(data.data(), centroid.data(), clusters.data(), false, 1); @@ -1177,7 +1183,10 @@ TEST(IvfConstructionTest, RebuildMatchesIncrementalEncodingWithSkewedClustersAnd const rabitq_test::TempFile path_file("rabitq_ivf_rebuild.index"); const std::string& path = path_file.path(); for (auto metric : {METRIC_L2, METRIC_IP}) { - for (auto rotation : {RotatorType::FhtKacRotator, RotatorType::MatrixRotator}) { + for (auto rotation : + {RotatorType::FhtBlockRotator, + RotatorType::FhtKacRotator, + RotatorType::MatrixRotator}) { for (size_t bits : {1UL, 2UL, 3UL, 4UL, 5UL, 6UL, 7UL, 8UL, 9UL, 32UL}) { SCOPED_TRACE( ::testing::Message() << "bits=" << bits << " metric=" << metric @@ -1816,7 +1825,10 @@ TEST(IvfTrainTest, SetCentroidsAndAddMatchConstructByteForByte) { IvfTestAccess::rotator(constructed) .reset( choose_rotator( - kDynDim, RotatorType::FhtKacRotator, constructed.padded_dim(), kSeed + kDynDim, + RotatorType::FhtBlockRotator, + constructed.padded_dim(), + kSeed ) ); IvfTestAccess::seed(constructed) = kSeed; diff --git a/tests/unit/rabitqlib/index/qg_test.cpp b/tests/unit/rabitqlib/index/qg_test.cpp index 53819733..5a88c257 100644 --- a/tests/unit/rabitqlib/index/qg_test.cpp +++ b/tests/unit/rabitqlib/index/qg_test.cpp @@ -1792,7 +1792,10 @@ TEST(QgPersistenceTest, PreservesNewAndLegacyPaddedDomains) { const rabitq_test::TempFile path_file("rabitq_qg_padding.index"); const std::string& path = path_file.path(); for (auto metric : {METRIC_L2, METRIC_IP}) { - for (auto rotator : {RotatorType::FhtKacRotator, RotatorType::MatrixRotator}) { + for (auto rotator : + {RotatorType::FhtBlockRotator, + RotatorType::FhtKacRotator, + RotatorType::MatrixRotator}) { for (size_t bits : {0U, 4U, 8U}) { for (bool legacy : {false, true}) { SCOPED_TRACE(::testing::Message() << bits << '/' << legacy); diff --git a/tests/unit/rabitqlib/index/symqg_index_test.cpp b/tests/unit/rabitqlib/index/symqg_index_test.cpp index e3a8626d..e44223ef 100644 --- a/tests/unit/rabitqlib/index/symqg_index_test.cpp +++ b/tests/unit/rabitqlib/index/symqg_index_test.cpp @@ -142,8 +142,8 @@ TEST(SymqgIndexTest, ConstructorRejectsInvalidSettings) { expect_error([&] { SymqgIndex(dim, settings); }, message); }; const auto keep = [](SymqgOptions&) {}; - invalid(63, keep, "Unsupported dimension for FhtKacRotator"); - invalid(65537, keep, "Unsupported dimension for FhtKacRotator"); + invalid(63, keep, "Unsupported dimension for FhtBlockRotator"); + invalid(65537, keep, "Unsupported dimension for FhtBlockRotator"); for (size_t bad : {size_t{0}, size_t{48}}) { invalid( kDim, @@ -177,7 +177,7 @@ TEST(SymqgIndexTest, ConstructorRejectsInvalidSettings) { several.nbits = 16; several.ef_construction = 0; expect_error( - [&] { SymqgIndex(10, several); }, "Unsupported dimension for FhtKacRotator" + [&] { SymqgIndex(10, several); }, "Unsupported dimension for FhtBlockRotator" ); expect_error( [&] { SymqgIndex(kDim, several); }, "max_degree must be a positive multiple of 32" @@ -228,7 +228,7 @@ TEST(SymqgIndexTest, AddBuildsTheGraphWithTheConstructorSettings) { kDim, settings.max_degree, settings.metric, - RotatorType::FhtKacRotator, + RotatorType::FhtBlockRotator, settings.nbits == 32 ? 0 : settings.nbits, *settings.seed ); diff --git a/tests/unit/rabitqlib/utils/blob_test.cpp b/tests/unit/rabitqlib/utils/blob_test.cpp index b7d61100..9a3cdc44 100644 --- a/tests/unit/rabitqlib/utils/blob_test.cpp +++ b/tests/unit/rabitqlib/utils/blob_test.cpp @@ -87,18 +87,30 @@ TEST(CoreBlobTest, Crc32MatchesZlib) { TEST(CoreBlobTest, ReadsAndRewritesTheQuantGoldenRotators) { const struct { const char* name; + RotatorType type; size_t dim; size_t padded_dim; uint32_t seed; } cases[] = { - {"rotator_fht_kac_dim64_seed0.bin", 64, 64, 0}, - {"rotator_fht_kac_dim100_padded128_seed42.bin", 100, 128, 42}, + {"rotator_fht_kac_dim64_seed0.bin", RotatorType::FhtKacRotator, 64, 64, 0}, + {"rotator_fht_kac_dim100_padded128_seed42.bin", + RotatorType::FhtKacRotator, + 100, + 128, + 42}, + {"rotator_fht_block_dim100_padded128_seed42.bin", + RotatorType::FhtBlockRotator, + 100, + 128, + 42}, + {"rotator_fht_block_dim420_seed42.bin", RotatorType::FhtBlockRotator, 420, 448, 42}, }; for (const auto& c : cases) { + SCOPED_TRACE(c.name); const std::vector golden = read_fixture(c.name); const detail::DecodedRotator decoded = detail::decode_rotator_blob(golden.data(), golden.size()); - EXPECT_EQ(decoded.type, RotatorType::FhtKacRotator); + EXPECT_EQ(decoded.type, c.type); EXPECT_EQ(decoded.dim, c.dim); EXPECT_EQ(decoded.padded_dim, c.padded_dim); ASSERT_TRUE(decoded.seed.has_value()); @@ -108,9 +120,7 @@ TEST(CoreBlobTest, ReadsAndRewritesTheQuantGoldenRotators) { ); const std::unique_ptr> fresh( - rabitqlib::choose_rotator( - c.dim, RotatorType::FhtKacRotator, c.padded_dim, c.seed - ) + rabitqlib::choose_rotator(c.dim, c.type, c.padded_dim, c.seed) ); EXPECT_EQ(rotate(*decoded.rotator, c.dim), rotate(*fresh, c.dim)); } @@ -185,7 +195,7 @@ TEST(CoreBlobTest, RejectsInvalidBlobsWithTheQuantMessages) { expect_rejected(blob, "data checksum mismatch (corrupt blob)"); expect_rejected(edited(20, 2), "data has unknown flags"); expect_rejected(edited(60, 1), "data has non-zero reserved fields"); - expect_rejected(edited(40, 3), "data has an unknown rotator method 3"); + expect_rejected(edited(40, 4), "data has an unknown rotator method 4"); expect_rejected( edited(44, 2), "data stores a float64 rotator, which version 1 cannot load" ); diff --git a/tests/unit/rabitqlib/utils/rotator_test.cpp b/tests/unit/rabitqlib/utils/rotator_test.cpp index 1814c93e..c5916186 100644 --- a/tests/unit/rabitqlib/utils/rotator_test.cpp +++ b/tests/unit/rabitqlib/utils/rotator_test.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -24,12 +25,13 @@ class RotatorTest : public ::testing::Test { size_t dim = 128; }; -// Test that FhtKacRotator is chosen by default +// Test that FhtBlockRotator is chosen by default TEST_F(RotatorTest, DefaultRotatorType) { std::unique_ptr> rotator(choose_rotator(dim)); ASSERT_NE(rotator, nullptr); + EXPECT_NE(dynamic_cast(rotator.get()), nullptr); - // FhtKacRotator pads to multiple of 32 + // FhtBlockRotator pads to multiple of 32 size_t padded_dim = rotator->size(); EXPECT_EQ(padded_dim % 32, 0); EXPECT_GE(padded_dim, dim); @@ -768,3 +770,299 @@ TEST(MatrixRotatorFactoryTest, DoublePreservesNormAndRejectsFloatOnlyRotation) { EXPECT_STREQ(error.what(), "FhtKacRotator only supports float"); } } + +namespace { + +uint64_t fnv1a(const void* data, size_t size) { + uint64_t hash = 14695981039346656037ULL; + for (size_t i = 0; i < size; ++i) { + hash ^= static_cast(data)[i]; + hash *= 1099511628211ULL; + } + return hash; +} + +// FHT/block rotation written from docs/formats.md (rotator method 3), independently of +// the library kernels. Butterflies, scaling and gathers follow the specified order, so +// every backend must match it bit for bit. +std::vector fht_block_reference( + const float* input, size_t dim, size_t padded, const uint8_t* flip +) { + size_t stride = (padded * 618034 / 1000000) | 1U; + while (std::gcd(stride, padded) != 1) { + stride += 2; + } + std::vector x(padded, 0.0F), next(padded); + std::copy(input, input + dim, x.begin()); + for (size_t round = 0; round < 3; ++round) { + for (size_t i = 0; i < padded; ++i) { + if ((flip[(round * padded / 8) + (i / 8)] >> (i % 8)) & 1U) { + x[i] = -x[i]; + } + } + size_t offset = 0; + for (size_t block = 65536; block >= 32; block /= 2) { + if ((padded & block) == 0) { + continue; + } + for (size_t width = 1; width < block; width *= 2) { + for (size_t start = 0; start < block; start += 2 * width) { + for (size_t i = 0; i < width; ++i) { + float& a = x[offset + start + i]; + float& b = x[offset + start + i + width]; + const float sum = a + b, difference = a - b; + a = sum; + b = difference; + } + } + } + const float factor = 1.0F / std::sqrt(static_cast(block)); + for (size_t i = 0; i < block; ++i) { + x[offset + i] *= factor; + } + offset += block; + } + if (round < 2) { + for (size_t i = 0; i < padded; ++i) { + next[i] = x[(i * stride) % padded]; + } + x.swap(next); + } + } + return x; +} + +std::vector fht_block_backends() { + std::vector backends{ + simd::fht_block_rotate_generic}; +#if defined(__x86_64__) || defined(_M_X64) + if (cpu::has_avx2()) { + backends.push_back(simd::fht_block_rotate_avx2); + } + if (cpu::has_avx512_core()) { + backends.push_back(simd::fht_block_rotate_avx512); + } +#endif +#if defined(__aarch64__) || defined(_M_ARM64) + if (cpu::has_neon()) { + backends.push_back(simd::fht_block_rotate_neon); + } +#endif + return backends; +} + +} // namespace + +// Hashes computed with an independent NumPy implementation of docs/formats.md: the seed-42 +// sign bytes and the rotation of an exactly representable input. +TEST(FhtBlockRotatorTest, MatchesFrozenReferenceRotations) { + struct Golden { + size_t dim; + size_t padded_dim; + uint64_t signs_fnv1a; + uint64_t output_fnv1a; + }; + const std::array goldens{{ + {64, 64, 0x8ba4eb7f7055982aULL, 0x488ec0290379df2bULL}, + {70, 96, 0x584aff693e8ee659ULL, 0x10d3c24a22c179afULL}, + {100, 128, 0xd9e9cf1fc973e865ULL, 0xdeda25ddb5b683b2ULL}, + {420, 448, 0x2c24fb3011267d87ULL, 0xbe470390b9940196ULL}, + {768, 768, 0xf7d277f7e5c21ce6ULL, 0x607b52d7846081a8ULL}, + {1000, 1024, 0x31d5343b7828f931ULL, 0xb086297bc1b7caf3ULL}, + {3000, 3008, 0x58a2a35911979959ULL, 0x66b0fd1c57026f78ULL}, + }}; + for (const Golden& golden : goldens) { + SCOPED_TRACE(golden.dim); + rotator_impl::FhtBlockRotator rotator(golden.dim, golden.padded_dim, 42); + const std::vector state = rotator_state(rotator); + ASSERT_EQ(state.size(), 3 * golden.padded_dim / 8); + EXPECT_EQ(fnv1a(state.data(), state.size()), golden.signs_fnv1a); + std::vector input(golden.dim), output(golden.padded_dim); + for (size_t i = 0; i < golden.dim; ++i) { + input[i] = static_cast(static_cast((i * 37) % 101) - 50) / 16.0F; + } + rotator.rotate(input.data(), output.data()); + EXPECT_EQ(fnv1a(output.data(), sizeof(float) * output.size()), golden.output_fnv1a); + } +} + +TEST(FhtBlockDispatchTest, BackendsMatchScalarReferenceBitwise) { + const auto backends = fht_block_backends(); + for (size_t dim : + {64U, 65U, 95U, 96U, 100U, 127U, 128U, 129U, 420U, 768U, + 960U, 1000U, 1024U, 1056U, 2049U, 3000U, 4095U, 16385U, 65504U, 65536U}) { + SCOPED_TRACE(dim); + for (size_t multiple : {32U, 64U}) { + const size_t padded = (dim + multiple - 1) / multiple * multiple; + if (padded > 65536) { + continue; + } + SCOPED_TRACE(padded); + const size_t stride = rotator_impl::FhtBlockRotator::permutation_stride(padded); + std::vector flip(3 * padded / 8); + for (size_t i = 0; i < flip.size(); ++i) { + flip[i] = static_cast(i * 73 + 13); + } + // Offset by one float so that no buffer is 32-byte aligned. + std::vector data(dim + 1); + for (size_t i = 0; i < dim; ++i) { + data[i + 1] = std::sin(static_cast(i) * 0.13F); + } + const std::vector expected = + fht_block_reference(data.data() + 1, dim, padded, flip.data()); + std::vector scratch(padded + 1); + for (auto backend : backends) { + std::vector actual(padded + 2, 12345); + backend( + data.data() + 1, + actual.data() + 1, + dim, + padded, + stride, + flip.data(), + scratch.data() + 1 + ); + EXPECT_TRUE( + std::equal(expected.begin(), expected.end(), actual.begin() + 1) + ); + EXPECT_EQ(actual.front(), 12345); + EXPECT_EQ(actual.back(), 12345); + // In place: the input occupies the start of the output. + std::vector in_place(padded + 2, 12345); + std::copy(data.begin() + 1, data.end(), in_place.begin() + 1); + backend( + in_place.data() + 1, + in_place.data() + 1, + dim, + padded, + stride, + flip.data(), + scratch.data() + 1 + ); + EXPECT_TRUE( + std::equal(expected.begin(), expected.end(), in_place.begin() + 1) + ); + EXPECT_EQ(in_place.back(), 12345); + } + std::vector dispatched(padded); + simd::fht_block_rotate( + data.data() + 1, dispatched.data(), dim, padded, stride, flip.data() + ); + EXPECT_EQ(dispatched, expected); + } + } +} + +TEST(FhtBlockRotatorTest, IsOrthonormal) { + for (size_t padded : {64U, 96U, 448U, 960U, 1024U}) { + SCOPED_TRACE(padded); + rotator_impl::FhtBlockRotator rotator(padded, padded, 5); + // Row i of rows is the image of basis vector i. + std::vector rows(padded * padded); + std::vector basis(padded, 0.0F), image(padded); + for (size_t i = 0; i < padded; ++i) { + basis[i] = 1.0F; + rotator.rotate(basis.data(), image.data()); + basis[i] = 0.0F; + std::copy(image.begin(), image.end(), rows.begin() + (i * padded)); + } + double max_error = 0; + for (size_t i = 0; i < padded; ++i) { + for (size_t j = i; j < padded; ++j) { + double dot = 0; + for (size_t k = 0; k < padded; ++k) { + dot += rows[(i * padded) + k] * rows[(j * padded) + k]; + } + max_error = std::max(max_error, std::abs(dot - (i == j ? 1.0 : 0.0))); + } + } + EXPECT_LT(max_error, 1e-5); + } +} + +// Every basis vector spreads like under a random rotation (largest padded * R_ij^2 about +// 26 to 31 for a Haar rotation at these sizes). FHT/Kac leaves spikes of 59 to 147 here, +// and transforms that skip mixing the blocks keep each input inside its own block. +TEST(FhtBlockRotatorTest, SpreadsEveryCoordinateOverAllBlocks) { + for (size_t padded : {448U, 768U, 960U, 1536U}) { + SCOPED_TRACE(padded); + for (uint32_t seed : {1U, 2U}) { + rotator_impl::FhtBlockRotator rotator(padded, padded, seed); + const size_t first_block = size_t{1} << floor_log2(padded); + std::vector basis(padded, 0.0F), image(padded); + double max_entry = 0, max_share_error = 0; + for (size_t i = 0; i < padded; ++i) { + basis[i] = 1.0F; + rotator.rotate(basis.data(), image.data()); + basis[i] = 0.0F; + double first_share = 0; + for (size_t j = 0; j < padded; ++j) { + const double energy = static_cast(image[j]) * image[j]; + max_entry = std::max(max_entry, energy * static_cast(padded)); + if (j < first_block) { + first_share += energy; + } + } + max_share_error = std::max( + max_share_error, + std::abs(first_share - (static_cast(first_block) / padded)) + ); + } + EXPECT_LT(max_entry, 50.0); + EXPECT_LT(max_share_error, 0.15); + } + } +} + +TEST(FhtBlockRotatorTest, SavedRotationRoundTripsAndRejectsBadDimensions) { + rotator_impl::FhtBlockRotator rotator(420, 448, 9); + std::unique_ptr> loaded = + rotator_impl::make_rotator_for_loading(420, RotatorType::FhtBlockRotator, 448); + ASSERT_EQ(loaded->dump_bytes(), 3 * 448 / 8); + loaded->load(rotator_state(rotator).data()); + std::vector input(420), expected(448), actual(448); + for (size_t i = 0; i < input.size(); ++i) { + input[i] = std::cos(static_cast(i)); + } + rotator.rotate(input.data(), expected.data()); + loaded->rotate(input.data(), actual.data()); + EXPECT_EQ(actual, expected); + + rotator_impl::FhtBlockRotator copy(64, 64, 1); + copy = rotator; + EXPECT_EQ(copy.size(), 448U); + copy.rotate(input.data(), actual.data()); + EXPECT_EQ(actual, expected); + + for (const auto& [dim, padded] : std::vector>{ + {63, 64}, {64, 48}, {65, 80}, {100, 96}, {65536, 65568}}) { + SCOPED_TRACE(dim); + EXPECT_THROW((rotator_impl::FhtBlockRotator(dim, padded)), std::invalid_argument); + } + try { + std::unique_ptr> rejected( + choose_rotator(128, RotatorType::FhtBlockRotator) + ); + FAIL() << "double FHT/block must be rejected"; + } catch (const std::invalid_argument& error) { + EXPECT_STREQ(error.what(), "FhtBlockRotator only supports float"); + } +} + +// Padding past twice the FHT/Kac window leaves coordinates untransformed. New rotators +// reject it; saved ones still load. +TEST(FhtRotatorTest, RejectsPaddingPastTwiceTheWindowButLoadsIt) { + EXPECT_NO_THROW((rotator_impl::FhtKacRotator(768, 1024, 1))); + EXPECT_NO_THROW((rotator_impl::FhtKacRotator(65, 128, 1))); + EXPECT_THROW((rotator_impl::FhtKacRotator(768, 1056, 1)), std::invalid_argument); + EXPECT_THROW((rotator_impl::FhtKacRotator(64, 160, 1)), std::invalid_argument); + EXPECT_THROW( + (std::unique_ptr>( + choose_rotator(768, RotatorType::FhtKacRotator, 2048, 1) + )), + std::invalid_argument + ); + std::unique_ptr> loaded = + rotator_impl::make_rotator_for_loading(768, RotatorType::FhtKacRotator, 2048); + EXPECT_EQ(loaded->size(), 2048U); +} From 145869afdd28ce6fbcf839a378fb57df2f19d5d2 Mon Sep 17 00:00:00 2001 From: gouyt13clear Date: Thu, 3 Dec 2026 12:40:43 +0800 Subject: [PATCH 2/3] test(rotator): load saved FHT/Kac signs through the loading constructor FhtNeonTest restores saved signs with extra padding, which can exceed twice the transform window. New FHT/Kac rotators now refuse that padding, so the seeded constructor threw on NEON hosts; the loading constructor accepts it, as loading saved rotators must. --- tests/unit/rabitqlib/utils/rotator_test.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/unit/rabitqlib/utils/rotator_test.cpp b/tests/unit/rabitqlib/utils/rotator_test.cpp index c5916186..a019ce8f 100644 --- a/tests/unit/rabitqlib/utils/rotator_test.cpp +++ b/tests/unit/rabitqlib/utils/rotator_test.cpp @@ -518,7 +518,9 @@ TEST(FhtNeonTest, MatchesSavedScalarRotationInPlaceAndWithExtraPadding) { 1.0F / std::sqrt(static_cast(trunc)), flip.data() ); - rotator_impl::FhtKacRotator rotator(dim, padded); + // Restore saved signs through the loading constructor, which also accepts + // padding past twice the transform window that new rotators refuse. + rotator_impl::FhtKacRotator rotator(dim, padded, rotator_impl::AllocateOnly{}); rotator.load(reinterpret_cast(flip.data())); for (size_t offset : {0U, 1U}) { std::vector actual(padded + 2, 12345); From b459a54daf86215bdbb79b42b541bd20da270b8a Mon Sep 17 00:00:00 2001 From: gouyt13clear Date: Thu, 3 Dec 2026 13:23:00 +0800 Subject: [PATCH 3/3] docs(rotator): correct restore advice, versioning rules and FHT/Kac condition - rotator.md: raw FHT/Kac state padded past twice the window has no public C++ restore path; name the internal loading constructor. - formats.md and development.md: list a nested blob value that its readers reject when unknown, such as a new rotator method, among the additive changes of format 2, as the blob rules already allow; quant_python.md states the same exception. - quant.Rotator docstring: FHT/Kac mixes poorly when the largest power of two not above dim is below three quarters of padded_dim, which also happens for some power-of-two paddings. - Test comments: scratch grows only above the largest padded dimension a thread has used; the QuantizedGraph legacy-padding case also covers FHT/block. --- docs/development.md | 3 ++- docs/docs/rabitq/quant_python.md | 2 +- docs/docs/rabitq/rotator.md | 4 +++- docs/formats.md | 2 +- python_bindings/quant_bindings.cpp | 3 ++- tests/allocation/core_api_no_alloc.cpp | 5 +++-- tests/unit/rabitqlib/index/qg_test.cpp | 3 ++- 7 files changed, 14 insertions(+), 8 deletions(-) diff --git a/docs/development.md b/docs/development.md index c100f039..f951eb3e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -589,7 +589,8 @@ shared validators while loading; only a file that cannot be opened throws a plai Do not silently reinterpret an old file. Every index writes index format 2 ([`docs/formats.md`](formats.md#index-format-2), container in `src/index/format2.*`). Change it only by its [compatibility rules](formats.md#compatibility-rules): an additive change appends -header fields, adds sections or adds feature bits, and keeps `version = 2`, because every 0.9 +header fields, adds sections, adds feature bits, or gives a nested blob's field a value that +its readers reject when unknown (such as a new rotator `method`), and keeps `version = 2`, because every 0.9 reader rejects any other `version`; a change an older reader cannot detect needs `version = 3`. Each released format change adds a frozen fixture, plus synthetic "future" fixtures for the rules (`tests/unit/rabitqlib/index/format2_test.cpp`). Use fixed-width fields diff --git a/docs/docs/rabitq/quant_python.md b/docs/docs/rabitq/quant_python.md index 36f03a6d..1de7644b 100644 --- a/docs/docs/rabitq/quant_python.md +++ b/docs/docs/rabitq/quant_python.md @@ -127,6 +127,6 @@ The layouts are specified in [`docs/formats.md`](https://github.com/VectorDB-NTU | `quant.FACTORS_VERSION` | `FACTORS_DTYPE`, `ESTIMATE_DTYPE` and `QUERY_TERMS_DTYPE` | | `quant.FASTSCAN_BLOCKS_VERSION` | `pack_fastscan_blocks` output | -`Rotator.to_bytes()` writes a self-describing blob with a magic, a kind, a version and a CRC-32. A change to any layout is a new version, never an edit of an existing one, and golden files in the test suite freeze each version. While the module is provisional, a release may stop reading an old version; reading it then raises `FormatError`. A promise that every released version stays readable comes with stabilisation. +`Rotator.to_bytes()` writes a self-describing blob with a magic, a kind, a version and a CRC-32. A change to any layout is a new version, never an edit of an existing one, and golden files in the test suite freeze each version. A version may gain a value of a field that its readers reject when unknown, such as a new rotator method: an older release then refuses the blob instead of misreading it. While the module is provisional, a release may stop reading an old version; reading it then raises `FormatError`. A promise that every released version stays readable comes with stabilisation. Byte layouts, rotator blobs and seeded FHT rotations are identical everywhere. Rotated values, codes, factors and distances are identical with the same wheel and CPU features, and otherwise agree within float32 rounding, because kernels are chosen at runtime by CPU. diff --git a/docs/docs/rabitq/rotator.md b/docs/docs/rabitq/rotator.md index 3a8bb631..69fcf932 100644 --- a/docs/docs/rabitq/rotator.md +++ b/docs/docs/rabitq/rotator.md @@ -28,7 +28,9 @@ type and padded dimension to `choose_rotator` before loading it: state saved bef 0.10 is FHT/Kac, and earlier releases padded to multiples of 64. The saved sign bytes do not contain this metadata. FHT/Kac state with `padded_dim` above `2 * trunc_dim` (see below) cannot be restored this way, because `choose_rotator` refuses to create such -a rotator; restore it from a blob, which index files and `Rotator.to_bytes()` store. +a rotator, and no public C++ function restores it: only the internal +`rotator_impl::FhtKacRotator(dim, padded_dim, rotator_impl::AllocateOnly{})` followed by +`load` does. Index files and `rabitqlib.quant` store blobs, which load whatever the padding. The rotation interfaces are in `rabitqlib/core/rotator.hpp`. diff --git a/docs/formats.md b/docs/formats.md index 30bd823d..b7264fab 100644 --- a/docs/formats.md +++ b/docs/formats.md @@ -382,5 +382,5 @@ Readers dispatch on the leading bytes: `"RABQINDX"`, then each index's legacy ma - A new release reads every earlier released index file. - An older release reads a newer format-2 file or rejects it with an error naming the problem; it never misreads it. Older releases reject `version` values other than 2, unknown `index_kind`, `metric` or `id_bits` values, unknown required sections and unknown `incompat` bits. -- An additive change appends header fields (raising `header_bytes`), adds sections, or adds feature bits, chosen by the table in [Feature flags](#feature-flags). A change that an older reader cannot detect from these is not allowed; it needs `version = 3`. +- An additive change appends header fields (raising `header_bytes`), adds sections, or adds feature bits, chosen by the table in [Feature flags](#feature-flags), or gives a field of a nested blob a value that the blob's readers reject when unknown, such as a new rotator `method`. A change that an older reader cannot detect from these is not allowed; it needs `version = 3`. - Every released change adds a frozen fixture. Synthetic "future" fixtures check the rules above: an unknown optional section loads; an unknown required section, an `incompat` bit or a larger `version` is rejected with its message; a `ro_compat` bit loads read-only; a longer header loads. diff --git a/python_bindings/quant_bindings.cpp b/python_bindings/quant_bindings.cpp index 1d514e36..cd60b72c 100644 --- a/python_bindings/quant_bindings.cpp +++ b/python_bindings/quant_bindings.cpp @@ -2085,7 +2085,8 @@ dim : int method : {'fht_block', 'fht_kac', 'fht', 'matrix'}, optional FHT/block rotation (default), the earlier FHT/Kac rotation ('fht' is an alias), or a dense random matrix. FHT/Kac mixes some coordinates poorly - when padded_dim is not a power of two. + when the largest power of two not above dim is below three quarters of + padded_dim. padded_dim : int, optional Working dimension, a multiple of 32 in [dim, 65536]. Default is padded_dim(dim). For 'fht_kac', at most twice the largest power of two diff --git a/tests/allocation/core_api_no_alloc.cpp b/tests/allocation/core_api_no_alloc.cpp index 30429b8e..4af13fb6 100644 --- a/tests/allocation/core_api_no_alloc.cpp +++ b/tests/allocation/core_api_no_alloc.cpp @@ -241,8 +241,9 @@ int main() { Watch guard; rotation->rotate(data.data(), rotated.data()); } - // FHT/block, the default, sizes per-thread gather scratch on a thread's first - // rotate at a given padded dimension; after that warm-up call it allocates nothing. + // FHT/block, the default, grows per-thread gather scratch when a thread first + // rotates at a padded dimension above any it has used; after that warm-up call + // it allocates nothing. std::unique_ptr> block( rabitqlib::choose_rotator( 65, rabitqlib::RotatorType::FhtBlockRotator, 0, 42 diff --git a/tests/unit/rabitqlib/index/qg_test.cpp b/tests/unit/rabitqlib/index/qg_test.cpp index 5a88c257..bd62bf9b 100644 --- a/tests/unit/rabitqlib/index/qg_test.cpp +++ b/tests/unit/rabitqlib/index/qg_test.cpp @@ -1805,7 +1805,8 @@ TEST(QgPersistenceTest, PreservesNewAndLegacyPaddedDomains) { EXPECT_EQ(source.padded_dim(), 96U); if (legacy) { // The raw and version-1 quantized file layouts are unchanged. - // Recreate their original 64-padded rotation, codes, and rows. + // Recreate their original 64-padded rotation, codes, and rows; + // FHT/block, which they predate, checks the same padding. QGConstructionTestAccess::use_legacy_padding(source); } QGBuilder builder(source, kDegree, data.data(), 1);