diff --git a/docs/docs/rabitq/rotator.md b/docs/docs/rabitq/rotator.md index ec684581..2c134c1d 100644 --- a/docs/docs/rabitq/rotator.md +++ b/docs/docs/rabitq/rotator.md @@ -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. diff --git a/docs/docs/releases/unreleased.md b/docs/docs/releases/unreleased.md index fee04db7..aec283cb 100644 --- a/docs/docs/releases/unreleased.md +++ b/docs/docs/releases/unreleased.md @@ -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 @@ -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. diff --git a/include/rabitqlib/core/rotator.hpp b/include/rabitqlib/core/rotator.hpp index 789ba4e0..fc277b05 100644 --- a/include/rabitqlib/core/rotator.hpp +++ b/include/rabitqlib/core/rotator.hpp @@ -101,6 +101,16 @@ class MatrixRotator : public Rotator { 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(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); diff --git a/tests/python/test_quant_rotator.py b/tests/python/test_quant_rotator.py index 82f4e700..52a45072 100644 --- a/tests/python/test_quant_rotator.py +++ b/tests/python/test_quant_rotator.py @@ -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)), diff --git a/tests/unit/rabitqlib/utils/rotator_test.cpp b/tests/unit/rabitqlib/utils/rotator_test.cpp index 0a773fc7..1814c93e 100644 --- a/tests/unit/rabitqlib/utils/rotator_test.cpp +++ b/tests/unit/rabitqlib/utils/rotator_test.cpp @@ -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 rotator(kDim, kDim, seed); + std::array m{}; + ASSERT_EQ(rotator.dump_bytes(), sizeof(m)); + rotator.save(reinterpret_cast(m.data())); + const double det = (static_cast(m[0]) * m[4] * m[8]) + + (static_cast(m[1]) * m[5] * m[6]) + + (static_cast(m[2]) * m[3] * m[7]) - + (static_cast(m[2]) * m[4] * m[6]) - + (static_cast(m[1]) * m[3] * m[8]) - + (static_cast(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(