Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -897,7 +898,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
Expand Down Expand Up @@ -996,7 +997,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
Expand Down Expand Up @@ -1110,10 +1111,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**

Expand Down
2 changes: 1 addition & 1 deletion docs/docs/index/hnsw.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/index/qg.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/index/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
14 changes: 9 additions & 5 deletions docs/docs/rabitq/core_api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -44,7 +44,7 @@ int main() {
}

std::unique_ptr<rabitqlib::Rotator<float>> rotator(rabitqlib::choose_rotator<float>(
kDim, rabitqlib::RotatorType::FhtKacRotator, 0, 42
kDim, rabitqlib::RotatorType::FhtBlockRotator, 0, 42
));
std::vector<float> rotated_input(rotator->size()), rotated_query(rotator->size());
rotator->rotate(input.data(), rotated_input.data());
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/rabitq/estimator.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
6 changes: 3 additions & 3 deletions docs/docs/rabitq/quant_python.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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/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.
68 changes: 54 additions & 14 deletions docs/docs/rabitq/rotator.md
Original file line number Diff line number Diff line change
@@ -1,30 +1,36 @@
# 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, 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`.

Expand All @@ -38,7 +44,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<rabitqlib::Rotator<float>> rotator(
rabitqlib::choose_rotator<float>(dim, rabitqlib::RotatorType::FhtKacRotator)
rabitqlib::choose_rotator<float>(dim, rabitqlib::RotatorType::FhtBlockRotator)
);
std::vector<float> x(dim, 1.0F);
std::vector<float> x_prime(rotator->size()); // 800 elements
Expand All @@ -56,20 +62,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).
Expand All @@ -88,6 +117,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
Expand Down
Loading
Loading