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
3 changes: 3 additions & 0 deletions docs/docs/rabitq/rotator.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ This implementation is based on the [FFHT library](https://github.com/FALCONN-LI

## Random orthogonal transformation
This method samples a Gaussian matrix and orthogonalizes it with QR decomposition.
Each column of the orthogonal factor takes the sign of the matching diagonal entry
of the triangular factor, which makes the transform Haar distributed, that is,
uniform over orthogonal matrices ([Mezzadri, 2007](https://arxiv.org/abs/math-ph/0609050), Section 5).
It then multiplies each vector by the stored transform. The table describes stored
space and per-vector rotation work when input and output dimensions are both $D$;
QR construction is separate setup work.
Expand Down
3 changes: 3 additions & 0 deletions docs/docs/releases/unreleased.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
- A missing sidecar of an earlier file still raises `Cannot open HNSW centroid sidecar`.
- A failed HNSW-RaBitQ write raises `HNSW index file cannot be written` instead of `HNSW failed to write index file`.
- `pickle.dumps(obj, protocol=0)` or `protocol=1` on a `rabitqlib` object no longer aborts the Python process. `quant.Rotator` and `quant.Query` now pickle with every protocol; the index, k-means, parameter and iteration-statistics classes raise `TypeError: cannot pickle ...`, as they already did with protocol 2 and higher, which include the default. Protocols 0 and 1 cannot reduce pybind11 objects ([pybind11#3745](https://github.com/pybind/pybind11/issues/3745)), so they now use the protocol-2 reduction.
- `quant.Rotator(method="matrix")` now draws a Haar-distributed rotation, uniform over orthogonal matrices. It used the orthogonal factor of a Householder QR factorization as returned, whose determinant is fixed and whose first entry is always negative; each column now takes the sign of the matching diagonal entry of the triangular factor. RaBitQ's codes and estimator do not change when the same rotated coordinate changes sign in every vector and query, and the old rotation was Haar distributed up to such sign changes, so accuracy is not expected to change. A given `seed` now produces a different matrix; rotators saved with `to_bytes()` and saved indexes keep theirs.

## C++ changes

Expand Down Expand Up @@ -127,4 +128,6 @@ Four differences are not renames: `HnswIndex::add` uses every CPU unless `num_th

- `rabitqlib::ceil_log2` in `rabitqlib/utils/tools.hpp` shifts a `size_t`, so an input of 2^32 or more is no longer undefined on 64-bit Windows, where `unsigned long` has 32 bits (#247). The library does not call it.

- `MatrixRotator`, which `choose_rotator` returns for `RotatorType::MatrixRotator` and `IVF` and `QuantizedGraph` use when given it, draws a Haar-distributed rotation, as described for `quant.Rotator` above. A given seed now produces a different matrix; saved rotators and indexes keep theirs.

- The installed CMake package satisfies `find_package(rabitqlib X.Y[.Z])` only when the major and minor versions match: `find_package(rabitqlib 0.8)` no longer finds 0.9, which `SameMajorVersion` compatibility allowed, and a version range must stay within one minor release, such as `0.9...<0.10`. Before 1.0 a minor release may break the API.
10 changes: 10 additions & 0 deletions include/rabitqlib/core/rotator.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,16 @@ class MatrixRotator : public Rotator<T> {
qr.householderQ()
.transpose(); // The inverse of an orthogonal matrix is its transpose.

// Householder Q alone is not Haar distributed (its determinant is fixed). Giving
// column i of Q, row i of q_inv, the sign of R(i, i) makes it Haar (Mezzadri,
// Notices AMS 2007, Section 5); only the copied rows matter.
const auto r_diag = qr.matrixQR().diagonal();
for (Eigen::Index i = 0; i < static_cast<Eigen::Index>(dim); ++i) {
if (r_diag(i) < T(0)) {
q_inv.row(i) *= T(-1);
}
}

// the random matrix only need the first dim rows, since we just pad zeros for
// the vector to be rotated to padded dimension
std::memcpy(&rand_mat_(0, 0), &q_inv(0, 0), sizeof(T) * dim * padded_dim);
Expand Down
13 changes: 13 additions & 0 deletions tests/python/test_quant_rotator.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,19 @@ def test_seeds_threads_and_out():
assert first.rotate(np.empty((0, 64), np.float32)).shape == (0, 64)


def test_matrix_rotation_takes_both_signs():
# An unadjusted Householder Q has a fixed determinant and a negative first entry;
# a Haar-distributed matrix takes either sign of both across seeds.
first_negative, det_negative = set(), set()
for seed in range(64):
rotator = quant.Rotator(32, method="matrix", seed=seed)
q_t = rotator.rotate(np.eye(32, dtype=np.float32)).astype(np.float64)
first_negative.add(bool(q_t[0, 0] < 0))
det_negative.add(bool(np.linalg.det(q_t) < 0))
assert first_negative == {False, True}
assert det_negative == {False, True}


def test_golden_blobs():
for name, rotator in (
("rotator_fht_kac_dim64_seed0.bin", quant.Rotator(64, seed=0)),
Expand Down
29 changes: 29 additions & 0 deletions tests/unit/rabitqlib/utils/rotator_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -712,6 +712,35 @@ TEST(MatrixRotatorFactoryTest, SeedReproducesTheMatrix) {
EXPECT_EQ(rotator_state(direct), first);
}

// An unadjusted Householder Q has a fixed determinant and a negative first entry. A
// Haar-distributed matrix takes either sign of both, so over 64 seeds each sign must
// occur; a correct rotator fails this only with probability about 2^-62.
TEST(MatrixRotatorFactoryTest, SeededMatricesTakeBothSignsAsHaarRequires) {
constexpr size_t kDim = 3;
constexpr uint32_t kSeeds = 64;
uint32_t negative_first = 0;
uint32_t negative_det = 0;
for (uint32_t seed = 0; seed < kSeeds; ++seed) {
const rotator_impl::MatrixRotator<float> rotator(kDim, kDim, seed);
std::array<float, kDim * kDim> m{};
ASSERT_EQ(rotator.dump_bytes(), sizeof(m));
rotator.save(reinterpret_cast<char*>(m.data()));
const double det = (static_cast<double>(m[0]) * m[4] * m[8]) +
(static_cast<double>(m[1]) * m[5] * m[6]) +
(static_cast<double>(m[2]) * m[3] * m[7]) -
(static_cast<double>(m[2]) * m[4] * m[6]) -
(static_cast<double>(m[1]) * m[3] * m[8]) -
(static_cast<double>(m[0]) * m[5] * m[7]);
ASSERT_NEAR(std::abs(det), 1.0, 1e-5) << "seed " << seed;
negative_first += m[0] < 0 ? 1U : 0U;
negative_det += det < 0 ? 1U : 0U;
}
EXPECT_GT(negative_first, 0U);
EXPECT_LT(negative_first, kSeeds);
EXPECT_GT(negative_det, 0U);
EXPECT_LT(negative_det, kSeeds);
}

TEST(MatrixRotatorFactoryTest, DoublePreservesNormAndRejectsFloatOnlyRotation) {
const size_t dim = 64;
std::unique_ptr<Rotator<double>> rotator(
Expand Down
Loading