Skip to content

feat(rotator)!: add FHT/block rotation and make it the default - #268

Merged
gouyt13 merged 3 commits into
mainfrom
feat/fht-block-rotator
Dec 3, 2026
Merged

gouyt13 merged 3 commits into
mainfrom
feat/fht-block-rotator

Conversation

@gouyt13

@gouyt13 gouyt13 commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

Adds FHT/block, a structured rotation that transforms every coordinate in every round, and makes it the default for new rotators and indexes. Saved indexes and rotators keep loading with their own rotation, so this changes only what new code writes.

Draft until marked ready by the maintainer; a final audit of the changes made after the first independent review found no high or medium issues, and its documentation fixes are in the last commit. CI passes on x86-64, Linux ARM64, Apple silicon and Windows, and the full suite also passed on an Apple M5 Pro (see "Validation").

Why

When the padded dimension n is not a power of two, FHT/Kac transforms a power-of-two window t alternately at the start and the end of the vector, and pairs i with i + n/2 in its Kac steps. When t < 3n/4, each input in [t, min(dim, 3n/2 - t)) keeps one path through the Kac steps that misses every window. The input then ends as two fixed spikes of magnitude 1/4, at outputs i and i - n/2; only their signs are random. This affects 1/6 of the inputs at 768, 1536 and 3072 dimensions, and 38–49% at 420, 960 and 1000. More rounds shrink the spikes but do not remove them. Random permutations and re-paired Kac steps were tried and do not help either.

Effect on RaBitQ estimates (rabitqlib.quant, L2, N = 4000, 100 queries, 3 rotator seeds; columns are 4-bit error std relative to a Haar rotation, with the share of estimates outside the library's error bound in brackets):

Input FHT/Kac FHT/block Haar (matrix)
One shared band coordinate with 30× the std (900× the variance): 768 / 960 / 1536 / 3072 2.79 / 3.44 / 4.26 / 4.94 [22–41%] 0.99–1.00 [4–5%] 1 [4–5%]
Sparse residuals (one large coordinate): 768 / 960 / 1000 / 1536 1.25 / 1.63 / 1.73 / 1.39 1.00 1
Isotropic and PCA-ordered inputs 1.00–1.04 1.00 1

On real dense embeddings, the outcome was:

  • No measurable difference: msong 420, contriever 768, gist 960, dbpedia-openai3 1536 and mxbai 1024 (see below).
  • Their largest in-band variance is at most about 5× the mean. The effect needs a single band coordinate with roughly 50× or more, shared by data and queries.

So this is a robustness fix rather than a recall fix for today's workloads.

Two smaller defects of the FHT/Kac path:

  • t is derived from dim, not padded_dim: 310 dimensions whose padding is a power of two (for example 993–1023) take the windowed path.
  • An explicit padded_dim > 2t leaves coordinates untransformed. For example, at 768/4096, 256 inputs map to ±e_j. Default padding never reaches this.

FHT/block

Specified exactly in docs/formats.md, "FHT rotations". Every backend implements that specification bit for bit.

  • n is split into its power-of-two blocks, largest first; all blocks have at least 32 coordinates.
  • There are three rounds. Each round is a sign flip followed by a normalized FWHT of every block.
  • Between rounds, a fixed stride gather y[i] = x[(i * s) mod n] mixes the blocks. s is floor(0.618034 n), made odd, then increased by 2 until it is coprime to n.
  • Sign bits use the FHT/Kac seed mapping; the body is 3n/8 bytes.

Validation of the construction against an independent NumPy model:

  • Structure. For every n from 64 to 4096 in steps of 32, plus sampled rows up to 65536, the basis-image entries have kurtosis 2.98–3.02 (Haar: 3), and the minimum L1 mass is at Haar level.
  • RaBitQ. Matrix-level estimates match the Haar baseline for every input class above.
  • Backends. The x86 backends (generic, AVX2, AVX-512 and the dispatched class) match a reference written from the specification bit for bit for all 2047 padded sizes from 64 to 65536, in place and out of place. NEON matches the in-test scalar reference bit for bit (20 dimensions × two paddings, unaligned and in place) and the frozen NumPy hashes, on Linux ARM64 CI, Apple silicon CI and an Apple M5 Pro.

Changes

  • include/rabitqlib/core/rotator.hpp:
    • Adds RotatorType::FhtBlockRotator (appended, value 2) and rotator_impl::FhtBlockRotator.
    • choose_rotator defaults to it.
    • FhtKacRotator creation rejects padded_dim > 2t; loading saved rotators still accepts it.
  • src/simd/:
    • The round sequence is shared by all backends (fht_block_kernels.hpp).
    • AVX2 and AVX-512 use hardware gathers that also apply the next round's sign flip.
    • Generic and NEON use an eight-chain scalar gather.
    • AVX gains a 32-point FWHT.
    • Thread-local scratch is allocated in generic code (fht_block_scratch.hpp).
  • Blob method 3 is added in both codecs (src/core/blob.cpp and python_bindings/quant_bindings.cpp).
  • New indexes use FHT/block: IVF, HNSW, SymphonyQG, RaBitQKMeans and QG assigner internals.
    • HNSW now records its rotator type. Its legacy reader keeps FHT/Kac, and its format-2 reader takes the type from the blob.
    • The IVF and SymphonyQG legacy layouts reject type byte 2.
  • Python: quant.Rotator(method="fht_block") is the default; "fht_kac", its "fht" alias and "matrix" remain. The native module's RotatorType enum gains FhtBlockRotator (it is not re-exported from rabitqlib, as before). The stubs are updated.
  • Docs: the FHT/Kac construction is now specified too. Rotator, core API, quant and index pages are updated.
  • Tests:
    • frozen NumPy hashes and bitwise backend comparisons, orthonormality, and a spreading test that FHT/Kac fails;
    • persistence round trips and new frozen quant fixtures;
    • resaving v0.9.0 fixtures keeps method 1/2;
    • legacy type-2 rejection, pre-main use, and allocation behaviour.

Compatibility

  • New releases read every earlier file. Resaving a loaded index or rotator keeps its FHT/Kac or matrix rotation.
  • 0.9 cannot read files that new code writes with FHT/block: indexes, quant blobs and pickles. It rejects them with unknown rotator method 3.
  • The same seed now gives a different rotation. Built indexes and RaBitQKMeans/QGKMeans results therefore differ from 0.9.
  • Silent misuse to call out in the release notes. Code that saved raw rotator state without its type and restores it through the default type now builds FHT/block and reads part of the old state without error. For example: choose_rotator<float>(dim) followed by load(), or quant.Rotator(dim, seed=s) used to recreate an old rotation. Such code must pass RotatorType::FhtKacRotator / method="fht_kac", or store blobs, which carry the type. zvec is unaffected: it stores the type and always passes it.
  • Smaller changes:
    • HierarchicalNSW gains a member, so downstream code must be rebuilt.
    • Two error messages changed: the SymphonyQG dimension message, and the quant dim message, which now names 'fht_block'.
    • The default rotator allocates per-thread scratch on a thread's first rotate, and again at a larger padded dimension.

I suggest the release:breaking label when this merges.

Performance

Measurement setup:

  • Xeon Gold 6418H (Sapphire Rapids, GDS not affected), GCC 14.3, Release build, RABITQ_ENABLE_NATIVE_OPTIMIZATION=OFF.
  • Single thread pinned to one core, 4096 vectors per run, median of 9 repetitions per run, median of 3 runs.
  • Shared host with load 18–44 during the runs, so differences below about 5% are noise.

Rotation alone:

dim (padded) AVX-512 (dispatch) FHT/Kac → FHT/block AVX2 generic
128 (128) 220 → 281 ns (1.28×) 167 → 214 ns (1.28×) 1330 → 994 ns (0.75×)
420 (448) 442 → 667 ns (1.51×) 498 → 576 ns (1.16×) 3474 → 3381 ns (0.97×)
768 726 → 1050 ns (1.45×) 960 → 1129 ns (1.18×) 6755 → 5681 ns (0.84×)
960 794 → 1324 ns (1.67×) 1146 → 1408 ns (1.23×) 7493 → 7226 ns (0.96×)
1024 1309 → 1334 ns (1.02×) 1494 → 1545 ns (1.03×) 11600 → 7819 ns (0.67×)
1536 1665 → 2120 ns (1.27×) 2149 → 2467 ns (1.15×) 14154 → 12404 ns (0.88×)
3072 4021 → 4826 ns (1.20×) 4803 → 5665 ns (1.18×) 57928 → 25055 ns (0.43×)

NEON on an Apple M5 Pro (AppleClang 21, portable build, single thread, 4096 vectors, median of 9 repetitions, last of 3 stable runs), FHT/Kac → FHT/block through the dispatched rotators:

dim (padded) NEON portable scalar
128 (128) 189 → 188 ns (0.99×) 445 → 338 ns (0.76×)
420 (448) 575 → 624 ns (1.09×) 1309 → 1205 ns (0.92×)
512 802 → 773 ns (0.96×) 1987 → 1385 ns (0.70×)
768 1106 → 1135 ns (1.03×) 2499 → 2086 ns (0.83×)
960 1221 → 1400 ns (1.15×) 2873 → 2631 ns (0.92×)
1024 1628 → 1582 ns (0.97×) 4263 → 2842 ns (0.67×)
1536 2287 → 2409 ns (1.05×) 5421 → 4269 ns (0.79×)
3072 4840 → 5142 ns (1.06×) 11037 → 9076 ns (0.82×)
4096 7227 → 6824 ns (0.94×) 19084 → 12848 ns (0.67×)

A per-stage breakdown on x86 puts the remaining non-power-of-two cost on two things:

  • transforming every block in every round, where FHT/Kac transforms only t of n coordinates — this is the price of the fix;
  • the two gathers, compared with FHT/Kac's four sequential Kac steps.

IVF-RaBitQ end to end. Each dataset uses the first 200k vectors and 1000 queries; for dbpedia the queries are held-out rows. Ground truth is exact (float64). There are 1024 shared RaBitQKMeans centroids with Flat routing. Insertion uses 32 threads; search is single-threaded. Recall@10 at nprobe 64 is the mean of 3 rotator seeds:

Dataset 1 bit: FHT/Kac / FHT/block 4 bits: FHT/Kac / FHT/block
msong 420 0.7624 / 0.7618 0.9581 / 0.9577
contriever 768 0.7634 / 0.7602 0.9443 / 0.9453
gist 960 0.7048 / 0.7017 0.9186 / 0.9190
mxbai 1024 0.8365 / 0.8374 0.9615 / 0.9605
dbpedia-openai3 1536 0.8247 / 0.8250 0.9340 / 0.9338
  • At every nprobe from 16 to 128, mean recall differs by at most 0.0041, and the per-seed ranges overlap except for mxbai at 4 bits.
  • The mxbai 4-bit gap was rechecked with 10 seeds per rotator: −0.0008 at nprobe 32 and 64 (z ≈ −1.4; 95% CI −0.0019 to +0.0003).
  • QPS differed by ±10–15% in both directions, which is host noise.
  • Rotation adds 0.2–0.55 µs per query against 50–215 µs per query in the fastest settings, so I expect under 1% end to end. This is inferred from the two measurements, not resolved by the QPS runs.
  • These IVF runs used the gather kernels before flip fusion; results are bit-identical.

Validation

  • CI: all jobs pass on x86-64 Linux, Linux ARM64, macOS arm64 and Windows (VS 2026), including the C++ suites, consumers with OpenMP on and off, Clang validation and the wheels.
  • Apple M5 Pro (AppleClang 21, portable build): ctest 666 passed, 14 skipped (AVX backends, Linux-only or failing-device tests); the same suite under ASan/UBSan without reports; pytest 1218 passed, 42 skipped (platform or optional dependencies) with the extension built from this branch.
  • x86-64 host: ctest: 668 passed. The same suite under ASan/UBSan: 668 passed, no reports.
  • pytest: 1258 passed, 2 skipped, against the package rebuilt from this branch.
  • mypy/Pyright editor checks: 32 passed.
  • Full check-tidy.sh with clang-tidy 23.
  • check-isa-symbols.sh (49 translation units).
  • check-format.sh and check-python.sh.
  • mkdocs build --strict.
  • Installed-package consumer, and tests/core_consumer/run.cmake with OpenMP ON and OFF.
  • New assertions were mutation-checked: dropping the cross-block gather, changing the round count, removing the FHT/Kac padding check, removing the warm-up and removing the legacy type-2 rejection each make a test fail.
  • An independent review of the full diff found no high-severity defects. Its follow-ups are included, except gather throughput on other CPUs (below).

Not tested

  • Gather throughput on GDS-mitigated Intel (Skylake-SP to Ice Lake-SP) and AMD Zen 2/3. The scalar gather is a drop-in fallback if hardware gathers turn out slower there. Rotation is a small share of index build and search either way.
  • HNSW and SymphonyQG end-to-end benchmarks.

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.
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.
…ondition

- 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.
@gouyt13
gouyt13 marked this pull request as ready for review December 3, 2026 06:08
@gouyt13 gouyt13 added the release:breaking Breaking change; listed first in release notes (set by hand) label Dec 3, 2026
@gouyt13
gouyt13 merged commit 6c070d8 into main Dec 3, 2026
48 checks passed
@gouyt13
gouyt13 deleted the feat/fht-block-rotator branch December 3, 2026 06:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release:breaking Breaking change; listed first in release notes (set by hand)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant