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
1 change: 1 addition & 0 deletions docs/docs/releases/unreleased.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
- IDs remain the row numbers the index assigns. The C++ `IvfIndex`, `HnswIndex` and `SymqgIndex` use 64-bit `rabitqlib::Id` values with `kNoId` (-1) for a missing result, as Python does. The indexes still hold 32-bit row numbers inside, so they keep their limit of 2^31 points; the unsupported `ivf::IVF`, `hnsw::HierarchicalNSW` and `symqg::QuantizedGraph` keep `PID` and `kPidMax`.

- An `IvfIndex`, `HnswIndex` or `SymqgIndex` call with both an invalid argument and the wrong state may now report the argument first, for example `ValueError` for `nprobe=0` on an untrained index, which raised `RuntimeError`, or for data of the wrong dimension passed to `SymqgIndex.add` after the graph is built. `HnswIndex()` with an invalid `metric` or `seed` and an out-of-range `num_clusters` now reports the metric or seed. `SymqgIndex()` with an invalid `init` and an invalid `dim`, `nbits` or `max_degree` now reports the `init`, and with an invalid `seed` and an invalid `dim`, `nbits`, `max_degree` or `ef_construction` the seed.
- k-means training accepts every coordinate that `add` and `search` accept. For many dimensions, including 64, 100, 256, 960 and 1024, `train` and `assign` of `QGKMeans` and `RaBitQKMeans`, and `train` and the first `add`, which trains, of `IvfIndex` and `HnswIndex` rejected a coordinate whose magnitude equals the float32 coordinate bound with `exceeds the safe float32 coordinate range`, although a trained index accepted it. The C++ `rabitqkmeans::RaBitQKMeans` and `qgkmeans::QGKMeans` change the same way.

- Loading a format-2 file keeps the `seed` of every index, and `ef_construction` and `init` of SymphonyQG. They were `None` after `load`, and still are for files from releases up to 0.8.
- With a recorded seed, `cp.seed` after `load` follows it as for a new index; for an HNSW-RaBitQ file whose seed exceeds 32 bits, which only C++ can write, it is the low 32 bits. It was the k-means default.
Expand Down
11 changes: 4 additions & 7 deletions include/rabitqlib/clustering/detail/kmeans.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#include "rabitqlib/index/detail/parallel_exception.hpp"
#include "rabitqlib/index/types.hpp"
#include "rabitqlib/utils/cpu_features.hpp"
#include "rabitqlib/utils/input_checks.hpp"
#include "rabitqlib/utils/space.hpp"
#include "rabitqlib/utils/tools.hpp"

Expand Down Expand Up @@ -534,12 +535,8 @@ class LloydKMeans : public Parameters {
std::string(Assignment::kName) + " input dimensions overflow ptrdiff_t"
);
}
// Leave headroom for products of squared distances in graph pruning,
// as well as quantized reconstruction and rotated residuals.
const double max_coordinate = std::sqrt(
std::sqrt(static_cast<double>(std::numeric_limits<float>::max())) /
(64.0 * static_cast<double>(d))
);
// The index bound, so training accepts every point the indexes accept.
const float max_coordinate = max_coordinate_magnitude(d);
bool in_range = true;
bool finite = true;
#pragma omp parallel for num_threads(num_workers) reduction(&& : finite, in_range) \
Expand All @@ -548,7 +545,7 @@ class LloydKMeans : public Parameters {
++index) {
const size_t i = static_cast<size_t>(index);
finite = finite && std::isfinite(x[i]);
in_range = in_range && std::abs(static_cast<double>(x[i])) <= max_coordinate;
in_range = in_range && std::abs(x[i]) <= max_coordinate;
}
if (!finite) {
throw std::invalid_argument(
Expand Down
38 changes: 38 additions & 0 deletions tests/python/test_input_boundaries.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,3 +344,41 @@ def test_build_rejects_bad_coordinates_without_building(index_kind, value):
with pytest.raises(ValueError):
index.add(bad_data, cluster_ids=ids, num_threads=1)
assert len(index) == 0


@pytest.mark.parametrize("model", ["ivf", "hnsw", "qgkmeans", "rabitqkmeans"])
def test_training_accepts_coordinates_at_the_index_bound(model):
# At dim 64 the float32 bound rounds above the exact real bound.
exact = np.sqrt(np.sqrt(np.float64(np.finfo(np.float32).max)) / (64.0 * 64))
bound = np.float32(exact)
assert np.float64(bound) > exact
data = np.random.default_rng(5).normal(size=(400, 64)).astype(np.float32)
data[5, 3] = bound
data[6, 4] = -bound

def fresh():
if model == "ivf":
return IvfIndex(64, 4, nbits=4)
if model == "hnsw":
return HnswIndex(64, nbits=4, num_clusters=4)
return (QGKMeans if model == "qgkmeans" else RaBitQKMeans)(64, 40, niter=2)

trained = fresh()
if model in ("ivf", "hnsw"):
trained.add(data, num_threads=1) # the first add trains
assert len(trained) == 400
else:
trained.train(data)
trained.assign(data[5:7])

data[5, 3] = np.nextafter(bound, np.float32(np.inf))
message = "KMeans x exceeds the safe float32 coordinate range$"
# Index train reaches the k-means check first; HNSW add checks before training.
with pytest.raises(ValueError, match=message):
if model in ("ivf", "hnsw"):
fresh().train(data, num_threads=1)
else:
fresh().train(data)
if model not in ("ivf", "hnsw"):
with pytest.raises(ValueError, match=message):
trained.assign(data[5:7])
46 changes: 46 additions & 0 deletions tests/unit/rabitqlib/clustering/kmeans_sampling_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#include "rabitqlib/clustering/qgkmeans.hpp"
#include "rabitqlib/clustering/rabitqkmeans.hpp"
#include "rabitqlib/index/types.hpp"
#include "rabitqlib/utils/input_checks.hpp"

namespace rabitqlib {
namespace {
Expand Down Expand Up @@ -234,6 +235,43 @@ void check_assign_requires_training_and_valid_input(const std::string& name) {
);
}

// Training and assignment accept exactly the coordinates the indexes accept.
// At kDim the float32 bound rounds above the exact real bound, so a value equal
// to it is the one an exact double comparison would wrongly reject.
template <typename Clustering>
void check_coordinate_bound_matches_index_check(const std::string& name) {
constexpr size_t kClusterCount = kClusters<Clustering>;
const float bound = max_coordinate_magnitude(kDim);
ASSERT_GT(
static_cast<double>(bound),
std::sqrt(
std::sqrt(static_cast<double>(std::numeric_limits<float>::max())) /
(64.0 * static_cast<double>(kDim))
)
);
const size_t num_points = 2 * kClusterCount;
auto points = clustered_points(num_points, 67);
points[1] = bound;
points[kDim + 2] = -bound;
Clustering clustering(kDim, kClusterCount, test_parameters<Clustering>());
ASSERT_NO_THROW(clustering.train(num_points, points.data()));
PID assignment = kPidMax;
float distance = 0;
EXPECT_NO_THROW(clustering.assign(1, points.data(), &assignment, &distance));
EXPECT_LT(assignment, kClusterCount);

const std::string message = name + " x exceeds the safe float32 coordinate range";
points[1] = std::nextafter(bound, std::numeric_limits<float>::infinity());
try {
clustering.assign(1, points.data(), &assignment, &distance);
FAIL() << "Assigned a coordinate above the bound";
} catch (const std::invalid_argument& error) { EXPECT_EQ(error.what(), message); }
try {
clustering.train(num_points, points.data());
FAIL() << "Trained on a coordinate above the bound";
} catch (const std::invalid_argument& error) { EXPECT_EQ(error.what(), message); }
}

// With sampling, train's final pass is assign() itself, including QGKMeans'
// cached graph. Without it, Exact assignment and RaBitQKMeans' scan around the
// stored training center also reproduce train(); graph training uses hints.
Expand Down Expand Up @@ -602,6 +640,14 @@ TEST(KMeansAssignTest, QGRequiresTrainingAndValidInput) {
check_assign_requires_training_and_valid_input<qgkmeans::QGKMeans>("QGKMeans");
}

TEST(KMeansAssignTest, RaBitQCoordinateBoundMatchesIndexCheck) {
check_coordinate_bound_matches_index_check<rabitqkmeans::RaBitQKMeans>("RaBitQKMeans");
}

TEST(KMeansAssignTest, QGCoordinateBoundMatchesIndexCheck) {
check_coordinate_bound_matches_index_check<qgkmeans::QGKMeans>("QGKMeans");
}

TEST(KMeansAssignTest, RaBitQMatchesFinalTrainingAssignment) {
check_assign_matches_final_training_assignment<rabitqkmeans::RaBitQKMeans>();
}
Expand Down
Loading