diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index b2526230..e42a1423 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -99,6 +99,7 @@ jobs: tests/python/test_ivf.py::test_save_load_roundtrip tests/python/test_hnsw.py::test_save_load_roundtrip tests/python/test_symqg.py::test_save_load_roundtrip + tests/python/test_qgemeans.py::test_train_populates_outputs_per_iteration tests/python/test_qgkmeans.py::test_train_populates_faiss_style_outputs tests/python/test_rabitqkmeans.py::test_flat_parameters_and_outputs - name: Install FAISS comparison dependency @@ -148,5 +149,6 @@ jobs: tests/python/test_ivf.py::test_save_load_roundtrip tests/python/test_hnsw.py::test_save_load_roundtrip tests/python/test_symqg.py::test_save_load_roundtrip + tests/python/test_qgemeans.py::test_train_populates_outputs_per_iteration tests/python/test_qgkmeans.py::test_train_populates_faiss_style_outputs tests/python/test_rabitqkmeans.py::test_flat_parameters_and_outputs diff --git a/docs/development.md b/docs/development.md index cc608249..352d0970 100644 --- a/docs/development.md +++ b/docs/development.md @@ -49,7 +49,7 @@ factors estimate L2 distance or inner product. | `include/rabitqlib/index/ivf_index.hpp` | `IvfIndex`, the supported C++ IVF API: the Python workflow over `ivf::IVF` | | `include/rabitqlib/index/hnsw_index.hpp` | `HnswIndex`, the supported C++ HNSW API: the Python workflow over `hnsw::HierarchicalNSW` | | `include/rabitqlib/index/symqg_index.hpp` | `SymqgIndex`, the supported C++ SymphonyQG API: the Python workflow over `symqg::QuantizedGraph` and `QGBuilder` | -| `include/rabitqlib/clustering/` | RaBitQKMeans flat assignment, QGKMeans graph assignment, and shared Lloyd training | +| `include/rabitqlib/clustering/` | RaBitQKMeans flat assignment, QGKMeans graph assignment, shared Lloyd training, and mini-batch e-means (`detail/emeans.hpp`: `EMeans` over a pluggable assignment, as `LloydKMeans` in `detail/kmeans.hpp`, which also holds the input checks both share; QGKMeans and QGEMeans share the centroid-graph assigner and graph cache in `detail/qg_assigner.hpp`) | | `include/rabitqlib/index/{ivf,hnsw,symqg}/` | Unsupported inner index classes behind the supported ones: construction, in-memory record layouts, search, save and load; no compatibility promise | | `include/rabitqlib/{core,fastscan,index}/detail/` | Module-owned implementation headers; no public stability promise | | `src/core/` | Compiled stable core v1 API and provisional API implementations (blob container, checksums and validation in `blob.*`, `crc32.hpp`, `validation.hpp`), and the frozen `faster_config` scale table | @@ -1125,6 +1125,11 @@ backends. Indexed float32 rows accumulate into float64 sums through the matrix backends, preserving per-cluster point order without additional workspace. +**QGEMeans mini-batch updates** + +Scalar float32 per-cluster sums in mini-batch member order, as the Faiss e-means reference; +objectives are summed per cluster, then in cluster order, so they do not depend on scheduling. + **HNSW-RaBitQ search and IVF-RaBitQ centroid routing** Cached HNSW search selection; centroid routing uses the common raw-distance dispatcher. @@ -1141,7 +1146,7 @@ caller-owned. **Example KMeans training** -Explicit RaBitQKMeans flat or QGKMeans graph assignment; FAISS is an optional comparison +Explicit RaBitQKMeans flat, QGKMeans graph or QGEMeans mini-batch assignment; FAISS is an optional comparison dependency only. #### Portable builds and test coverage diff --git a/docs/docs/clustering.md b/docs/docs/clustering.md index ec3bbfe3..49626c8d 100644 --- a/docs/docs/clustering.md +++ b/docs/docs/clustering.md @@ -1,9 +1,10 @@ # Clustering -RaBitQ Library provides two implementations of Lloyd's k-means. Both compute -centroid means from the original float32 data, accumulate in float64, and require -no external clustering package. Choose the class explicitly; neither switches -algorithms based on the cluster count. +RaBitQ Library provides two implementations of Lloyd's k-means and one of +mini-batch [e-means](#qgemeans). The Lloyd classes compute centroid means from +the original float32 data and accumulate in float64. None requires an external +clustering package. Choose the class explicitly; none switches algorithms based +on the cluster count. For installation, see [Quick start](quick_start.md#install). @@ -21,18 +22,20 @@ per centroid; the classes below default to training on every vector. | --- | --- | --- | --- | | [RaBitQKMeans](#rabitqkmeans) | Flat RaBitQ scan | Small cluster counts | `n >= k >= 1` | | [QGKMeans](#qgkmeans) | SymphonyQG centroid graph | Larger cluster counts | `n >= k > max_degree` (default 32) | +| [QGEMeans](#qgemeans) | SymphonyQG centroid graph, per mini-batch | Larger cluster counts, fewer passes over the data | `n >= k > max_degree` (default 32) | ## Python -Both classes have the same training and result interface. Here `x` is a float32 +All three classes have the same training and result interface. Here `x` is a float32 array of shape `(n, d)` and `queries` one of shape `(m, d)`: ```python -from rabitqlib import QGKMeans, RaBitQKMeans +from rabitqlib import QGEMeans, QGKMeans, RaBitQKMeans kmeans = RaBitQKMeans(d, 16, niter=25, num_threads=8) # For larger cluster counts, use instead: # kmeans = QGKMeans(d, 4096, niter=25, num_threads=8) +# kmeans = QGEMeans(d, 4096, niter=8, num_threads=8) last_iteration_obj = kmeans.train(x) centroids = kmeans.centroids # shape (k, d) @@ -53,6 +56,7 @@ Link that target; a core-only installation does not include clustering headers. ```cpp #include +#include #include rabitqlib::rabitqkmeans::RaBitQKMeansParameters parameters; @@ -60,7 +64,8 @@ parameters.niter = 25; parameters.num_threads = 8; rabitqlib::rabitqkmeans::RaBitQKMeans kmeans(dimension, 16, parameters); -// For graph assignment, use qgkmeans::QGKMeansParameters and qgkmeans::QGKMeans. +// For graph assignment, use qgkmeans::QGKMeansParameters and qgkmeans::QGKMeans, +// or qgemeans::QGEMeansParameters and qgemeans::QGEMeans. kmeans.train(num_points, data); // row-major float32 input const auto& centroids = kmeans.centroids; @@ -75,22 +80,27 @@ kmeans.assign(num_queries, queries, query_assignments.data(), query_distances.da ``` Complete examples: [RaBitQKMeans](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/sample/cpp/rabitqkmeans.cpp) -(`bin/rabitqkmeans`) and [QGKMeans](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/sample/cpp/qgkmeans.cpp) -(`bin/qgkmeans`). Run either without arguments for a synthetic demo, or save +(`bin/rabitqkmeans`), [QGKMeans](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/sample/cpp/qgkmeans.cpp) +(`bin/qgkmeans`) and [QGEMeans](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/sample/cpp/qgemeans.cpp) +(`bin/qgemeans`). Run any of them without arguments for a synthetic demo, or save clusters for the C++ indexing examples: ```bash ./bin/qgkmeans data.fvecs 4096 centroids.fvecs labels.ivecs +./bin/qgemeans data.fvecs 4096 centroids.fvecs labels.ivecs ./bin/rabitqkmeans data.fvecs 16 centroids.fvecs labels.ivecs ``` File mode uses exact final assignment and the default training parameters. -Append `ip` for spherical clustering of normalized input; the default is `l2`. +For the Lloyd examples, append `ip` for spherical clustering of normalized +input; the default is `l2`. `sample/run_cpp.sh` runs the C++ clustering and indexing workflow without Python. ## Parameters and input -Set Python keyword arguments or fields of the corresponding C++ parameter type: +Set Python keyword arguments or fields of the corresponding C++ parameter type. +QGEMeans takes `num_threads`, `seed`, `verbose` and `final_assignment` from this +table; its other parameters are listed [with the method](#qgemeans). | Parameter | Default | Meaning | | --- | --- | --- | @@ -186,6 +196,51 @@ The seed also controls fallback neighbors; PiPNN uses fixed internal seeds. without the clustering loop. To assign vectors with trained QGKMeans centroids, use [`assign`](#assign-new-vectors). +### QGEMeans + +QGEMeans runs mini-batch e-means (Algorithm 1 of +[arXiv:2611.09501](https://arxiv.org/abs/2611.09501), with the constants of the +Faiss reference implementation in `faiss/contrib/e_means`) and assigns each +mini-batch through a SymphonyQG graph over the current centroids. It starts +from `k` distinct random training vectors chosen by `seed`. Each iteration visits +the vectors in a seeded random order, in mini-batches. Before every mini-batch +the raw-vector centroid graph is rebuilt and searched for each vector's nearest +and second-nearest centroids, without search hints. Each centroid then moves +toward its mini-batch mean, weighted by its batch count against an +exponentially decaying mass. Every fifth mini-batch, cost-based revival (the +Faiss default) moves centroids that cost little to remove: those whose removal +cost, a decaying average of each vector's extra squared distance to its second +centroid, is at most zero or below 0.3 times the median. The cheapest move +first, each splitting the remaining centroid with the longest principal axis, +tracked by Oja's rule, as long as the split's expected gain exceeds the removal +cost. The step size follows the e-means step law and a cosine schedule that +decays to a tenth of its initial value. After the last iteration, each centroid +assigned in that iteration becomes the mean of its last-iteration vectors; a centroid +split in the last iteration uses only the vectors it received after the split. +This last iteration matches Faiss with `closing_handover=False`, which is not +Faiss's default; the closing handover is not implemented. + +| Parameter | Default | Meaning | +| --- | --- | --- | +| `niter` | `8` | Positive number of iterations, each one pass (an e-means epoch) over the training vectors. | +| `batch_size` | `0` | Vectors per mini-batch, capped at `n`; `0` selects the e-means batch-size law, rounded to a power of two and capped at the power of two nearest `n / 2`. | +| `max_degree` | `32` | A positive multiple of 32, strictly smaller than `k`. | +| `ef_construction`, `ef_search` | `240`, `16` | Positive graph construction and search window sizes; `ef_search` is at least 2, since each search returns the two nearest centroids. | +| `graph_build_iterations` | `1` | As for QGKMeans. | + +C++ and Python use the same names. The centroid graph always stores raw +float32 centroids, and QGEMeans has no `spherical`, sampling or early-stop +setting. Mini-batch sums accumulate in +float32, as in the Faiss reference. + +`obj` and `iteration_stats` have one entry per iteration: `obj` sums the mini-batch +assignment distances of that iteration, each measured before that mini-batch's +update; `shift` is the squared centroid displacement over the iteration; and +`nsplit` counts revived centroids. Python `train()` returns the last iteration's +`obj`. `train()` then assigns all vectors to the final centroids with +`final_assignment`: `'approximate'` searches a graph rebuilt over them, and +`'exact'` uses the exhaustive assignment described below. + ## Results and final assignment Python result properties are `None` until a successful fit; a failed fit @@ -198,13 +253,14 @@ their sum (WCSS); spherical mode sums `1 - inner_product`. `obj` and `train()` returns the last such objective. `final_assignment='approximate'` (default) uses the selected class's assignment -algorithm. Labels need not identify the exact nearest centroids, but reported +algorithm. QGEMeans `obj` and `iteration_stats` are per iteration, as described +[with the method](#qgemeans). Labels need not identify the exact nearest centroids, but reported distances and WCSS remain exact for those labels. Without sampling, quantized QGKMeans final assignment retains a point's last-iteration label when it is closer. After sampling, most points have no such label, so every point uses the same graph search. Approximate training objectives need not decrease monotonically. -To require exact nearest-centroid **final** assignments with either class: +To require exact nearest-centroid **final** assignments with any class: ```python from rabitqlib import RaBitQKMeans @@ -218,8 +274,9 @@ reads back as one of them. 0.9 removed the `FinalAssignmentMode` enum from the P package. In C++, set `parameters.final_assignment` to -`rabitqlib::rabitqkmeans::FinalAssignmentMode::Exact` or -`rabitqlib::qgkmeans::FinalAssignmentMode::Exact`; both names refer to the same +`rabitqlib::rabitqkmeans::FinalAssignmentMode::Exact`, +`rabitqlib::qgkmeans::FinalAssignmentMode::Exact` or +`rabitqlib::qgemeans::FinalAssignmentMode::Exact`; all three name the same enum, whose values are `Approximate` and `Exact` (0.9 removed the alias `SymphonyQG`). Training still uses the selected approximate assignment algorithm. @@ -247,7 +304,7 @@ C++ callers that change `centroids` or graph parameters cause one rebuild on the next call. Each call still validates the `k * d` centroid coordinates. For the training vectors, `assign` reproduces `assignments` and `distances` -with exact final assignment, for RaBitQKMeans, and whenever training +with exact final assignment, for RaBitQKMeans and QGEMeans, and whenever training sampled the input, because the sampled final pass is the same assignment. Unsampled approximate QGKMeans training also uses previous labels as graph search hints, so its final labels can differ. diff --git a/docs/docs/index.md b/docs/docs/index.md index 5546b06c..116c4d09 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -90,7 +90,7 @@ For input shapes, distance conventions, memory estimates, and threading, see - **Bring your own storage:** use the [stable C++ core API](rabitq/core_api.md) to encode vectors and estimate distances in caller-owned buffers. Add [FastScan](cpp_integration.md#fastscan-integration) for batch scoring. -- **Train clusters:** use [RaBitQKMeans or QGKMeans](clustering.md) to prepare +- **Train clusters:** use [RaBitQKMeans, QGKMeans or QGEMeans](clustering.md) to prepare centroids and assignments for IVF-RaBitQ or HNSW-RaBitQ. ## Compare measured performance diff --git a/docs/docs/quick_start.md b/docs/docs/quick_start.md index a7235284..4272995d 100644 --- a/docs/docs/quick_start.md +++ b/docs/docs/quick_start.md @@ -133,6 +133,6 @@ See [file compatibility](index/usage.md#index-file-compatibility) before downgra - [IVF-RaBitQ](index/ivf.md): raw-vector reranking, precision, centroid routing and updates. - [HNSW-RaBitQ](index/hnsw.md) and [SymphonyQG](index/qg.md): graph-index workflows and parameters. - [Index usage contracts](index/usage.md): counts, threading, input lifetimes and file paths. -- [Clustering](clustering.md): choose flat RaBitQKMeans or graph-based QGKMeans. +- [Clustering](clustering.md): choose flat RaBitQKMeans, graph-based QGKMeans or mini-batch QGEMeans. - [C++ integration](cpp_integration.md): builds, installation and component selection. - [Stable core API](rabitq/core_api.md): integrate quantization into your own storage. diff --git a/include/rabitqlib/clustering/detail/emeans.hpp b/include/rabitqlib/clustering/detail/emeans.hpp new file mode 100644 index 00000000..8d7f16a9 --- /dev/null +++ b/include/rabitqlib/clustering/detail/emeans.hpp @@ -0,0 +1,782 @@ +#pragma once + +// The mini-batch e-means algorithm QGEMeans trains with, independent of how each +// mini-batch is assigned: Algorithm 1 of arXiv 2611.09501, with the constants of +// the FAISS reference implementation (faiss/contrib/e_means at b14b3d693, MIT +// license): the throughput batch-size law (d > 16), the step law, a cosine +// schedule and cost-based revival. EMeans runs it over a pluggable assignment, as +// LloydKMeans does for Lloyd's algorithm. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rabitqlib/clustering/detail/kmeans.hpp" +#include "rabitqlib/core/rotator.hpp" +#include "rabitqlib/index/types.hpp" +#include "rabitqlib/utils/input_checks.hpp" +#include "rabitqlib/utils/tools.hpp" + +namespace rabitqlib::qgemeans::detail { + +constexpr double kAlphaMinFactor = 0.1; +constexpr size_t kReviveEvery = 5; +constexpr float kInitialMass = 1.0F / 65536.0F; +// Cost-based revival: a centroid may move when its removal cost R, the EMA of +// d2 - d1 over its vectors, is at most zero or below kRemovalThreshold times the +// median, and only if its donor's split gain kSplitGain * |U| exceeds R. +constexpr double kRemovalThreshold = 0.3; +constexpr double kBatchC = 0.035134; +constexpr double kBatchK = 0.134749; +constexpr double kBatchN = 0.876473; +constexpr double kBatchT = 0.813344; +constexpr double kAlphaC = 0.8244; +constexpr double kAlphaK = -0.4617; +constexpr double kAlphaB = 0.9003; +constexpr double kAlphaN = -0.4498; +constexpr double kAlphaT = -0.1057; +constexpr double kPi = 3.14159265358979323846; +constexpr double kSplitGain = 2.0 / kPi; + +// Nearest power of two to value, 1 below 1. +[[nodiscard]] inline size_t round_power_of_two(double value) { + if (value <= 1) { + return 1; + } + const size_t low = size_t{1} << static_cast(std::floor(std::log2(value))); + const auto high = static_cast(2 * low); + return value / static_cast(low) < high / value ? low : 2 * low; +} + +struct Recipe { + size_t batch_size; + double alpha0; + size_t steps_per_iteration; + size_t total_steps; +}; + +// Requires n >= 1 and niter >= 1. +[[nodiscard]] inline Recipe resolve_recipe( + size_t n, size_t k, size_t niter, size_t batch_size +) { + const auto nd = static_cast(n); + const auto kd = static_cast(k); + const auto td = static_cast(niter); + if (batch_size == 0) { + const double law = + kBatchC * std::pow(kd, kBatchK) * std::pow(nd, kBatchN) * std::pow(td, kBatchT); + // Rounding is monotone, so capping first gives the same power of two and + // keeps an extreme law within the shift range of round_power_of_two. + batch_size = round_power_of_two(std::min(law, nd / 2)); + } + batch_size = std::max(1, std::min(batch_size, n)); + double alpha0 = kAlphaC * std::pow(kd, kAlphaK) * + std::pow(static_cast(batch_size), kAlphaB) * + std::pow(nd, kAlphaN) * std::pow(td, kAlphaT); + alpha0 = std::min(std::max(alpha0, 1e-4), 1.0); + const size_t steps = (n + batch_size - 1) / batch_size; + return {batch_size, alpha0, steps, steps * niter}; +} + +[[nodiscard]] inline double scheduled_alpha( + double alpha0, size_t step, size_t total_steps +) { + const double fraction = static_cast(std::min(step, total_steps)) / + static_cast(std::max(1, total_steps)); + const double cosine = 0.5 * (1.0 + std::cos(kPi * fraction)); + return alpha0 * (kAlphaMinFactor + ((1.0 - kAlphaMinFactor) * cosine)); +} + +// A pass seed equal to the initialization seed moves by the golden-ratio +// constant, so a pass never replays the initialization draw. +[[nodiscard]] inline uint32_t iteration_seed(uint64_t seed, uint64_t iteration) { + auto value = static_cast((seed * 1000003ULL + iteration) % (1ULL << 32)); + if (value == static_cast(seed)) { + value += 0x9E3779B9U; + } + return value; +} + +// Uniform double in (0, 1) from 53 random bits, so the axis draws do not depend on +// the standard library. The initial rows and pass orders use std distributions, +// so results are reproducible for one toolchain only. +[[nodiscard]] inline double open_uniform(std::mt19937_64& rng) { + constexpr double kScale = 1.0 / 9007199254740992.0; // 2^-53 + return (static_cast(rng() >> 11) + 0.5) * kScale; +} + +// Training state of one fit. removal holds k rows [U / axis_scale | R]: the Oja +// long-axis sums U and the removal cost R, the EMA of d2 - d1 over each +// centroid's vectors. The batch_* inputs are filled by the caller's assignment of +// each mini-batch; the vectors after split_rng are scratch reused across +// mini-batches. +struct EMeansState { + size_t d = 0; + size_t k = 0; + std::vector centroids; + std::vector mass; + std::vector pass_counts; + std::vector pass_sums; + std::vector removal; + std::vector axes; + double axis_scale = 1.0; + std::vector batch_sums; + std::vector batch_counts; + std::vector batch_removal; + std::vector batch_assignments; + std::vector batch_distances; + std::vector batch_second_distances; + std::vector offsets; + std::vector members; + std::vector cluster_objectives; + std::mt19937_64 split_rng; + std::vector cursor; + std::vector costs; + std::vector axis_norms; + std::vector candidates; + std::vector donors; + std::vector sorted_costs; +}; + +// Initial centroids are k distinct random rows; every centroid starts with the +// reference's small initial mass. +inline void initialize( + EMeansState& state, + size_t d, + size_t k, + size_t n, + const float* x, + size_t batch, + uint32_t seed +) { + state.d = d; + state.k = k; + state.centroids.resize(k * d); + { + std::mt19937_64 rng(seed); + std::vector rows(n); + std::iota(rows.begin(), rows.end(), size_t{0}); + for (size_t cluster = 0; cluster < k; ++cluster) { + std::uniform_int_distribution pick(cluster, n - 1); + std::swap(rows[cluster], rows[pick(rng)]); + std::copy_n(x + rows[cluster] * d, d, state.centroids.data() + cluster * d); + } + } + state.mass.assign(k, kInitialMass); + state.split_rng.seed(seed); + state.pass_counts.assign(k, 0.0); + state.removal.assign(k * (d + 1), 0.0F); + state.axis_scale = 1.0; + // Random unit initial axes: k rows of d standard normals (Box-Muller), each + // normalized in double. Same distribution as the reference, not the same values. + state.axes.resize(k * d); + std::vector axis(d); + for (size_t cluster = 0; cluster < k; ++cluster) { + double norm2 = 0.0; + for (size_t dim = 0; dim < d; ++dim) { + const double radius = std::sqrt(-2.0 * std::log(open_uniform(state.split_rng))); + const double angle = 2.0 * kPi * open_uniform(state.split_rng); + axis[dim] = radius * std::cos(angle); + norm2 += axis[dim] * axis[dim]; + } + const double norm = std::sqrt(norm2); + for (size_t dim = 0; dim < d; ++dim) { + state.axes[cluster * d + dim] = static_cast(axis[dim] / norm); + } + } + state.batch_sums.resize(k * d); + state.batch_counts.resize(k); + state.batch_removal.assign(k * (d + 1), 0.0F); + state.batch_assignments.resize(batch); + state.batch_distances.resize(batch); + state.batch_second_distances.resize(batch); + state.offsets.resize(k + 1); + state.members.resize(batch); + state.cluster_objectives.resize(k); + state.cursor.resize(k); + state.costs.resize(k); + state.axis_norms.resize(k); + state.candidates.reserve(k); + state.donors.reserve(k); + state.sorted_costs.resize(k); +} + +// Starts a pass: resets the pass counts, and in the last pass the pass sums that +// close the means. +inline void start_iteration(EMeansState& state, bool last) { + std::fill(state.pass_counts.begin(), state.pass_counts.end(), 0.0); + if (last) { + state.pass_sums.assign(state.k * state.d, 0.0F); + } +} + +// Per-centroid sums and counts of one batch, in float32 as the reference, over +// members in batch order, and the removal statistics of cost-based revival: for +// a vector with residual y to its centroid and p = , p * y is added to +// U and d2 - d1 to R (zero when not finite). Returns the batch's assignment +// objective. +inline double accumulate( + EMeansState& state, + const float* x, + const size_t* rows, + size_t count, + uint32_t num_workers +) { + const size_t d = state.d; + const size_t k = state.k; + auto& offsets = state.offsets; + std::fill(offsets.begin(), offsets.end(), size_t{0}); + for (size_t i = 0; i < count; ++i) { + ++offsets[state.batch_assignments[i] + 1]; + } + std::partial_sum(offsets.begin(), offsets.end(), offsets.begin()); + auto& cursor = state.cursor; + std::copy(offsets.begin(), offsets.end() - 1, cursor.begin()); + for (size_t i = 0; i < count; ++i) { + state.members[cursor[state.batch_assignments[i]]++] = i; + } + static_cast(num_workers); +#pragma omp parallel num_threads(num_workers) + { + std::vector residual(d); +#pragma omp for schedule(dynamic, 16) + for (std::ptrdiff_t index = 0; index < static_cast(k); ++index) { + const auto cluster = static_cast(index); + float* sums = state.batch_sums.data() + cluster * d; + float* removal = state.batch_removal.data() + cluster * (d + 1); + const float* centroid = state.centroids.data() + cluster * d; + const float* axis = state.axes.data() + cluster * d; + std::fill_n(sums, d, 0.0F); + std::fill_n(removal, d + 1, 0.0F); + double cluster_objective = 0.0; + for (size_t m = offsets[cluster]; m < offsets[cluster + 1]; ++m) { + const size_t i = state.members[m]; + const float* row = x + rows[i] * d; + float projection = 0.0F; + for (size_t dim = 0; dim < d; ++dim) { + sums[dim] += row[dim]; + residual[dim] = row[dim] - centroid[dim]; + projection += residual[dim] * axis[dim]; + } + for (size_t dim = 0; dim < d; ++dim) { + removal[dim] += projection * residual[dim]; + } + const float margin = + state.batch_second_distances[i] - state.batch_distances[i]; + removal[d] += std::isfinite(margin) ? margin : 0.0F; + cluster_objective += state.batch_distances[i]; + } + state.cluster_objectives[cluster] = cluster_objective; + state.batch_counts[cluster] = + static_cast(offsets[cluster + 1] - offsets[cluster]); + } + } + // Summed in cluster order, so the objective does not depend on scheduling. + return std::accumulate( + state.cluster_objectives.begin(), state.cluster_objectives.end(), 0.0 + ); +} + +// Algorithm 1, line 8: mass' = (1 - alpha) mass + alpha count, and each +// centroid moves toward its batch mean by alpha count / mass'. The removal +// statistics take the same step: R' = (1 - alpha) R + alpha R_batch, and U +// decays through the shared axis_scale while each assigned centroid adds its +// batch term and renews its unit axis U / |U| (Oja's rule). +inline void apply_statistics( + EMeansState& state, double alpha_value, bool last, uint32_t num_workers +) { + const size_t d = state.d; + const size_t k = state.k; + const auto alpha = static_cast(alpha_value); + const auto decay = static_cast(1.0 - alpha_value); + const bool replace_mass = alpha_value == 1.0; + double scale = state.axis_scale * (1.0 - alpha_value); + if (!(scale > 0x1p-32)) { + const auto factor = static_cast(scale); + for (size_t cluster = 0; cluster < k; ++cluster) { + float* u = state.removal.data() + cluster * (d + 1); + for (size_t dim = 0; dim < d; ++dim) { + u[dim] *= factor; + } + } + scale = 1.0; + } + state.axis_scale = scale; + const auto axis_weight = static_cast(alpha_value / scale); + const float bound = max_coordinate_magnitude(d); + static_cast(num_workers); +#pragma omp parallel for num_threads(num_workers) schedule(static) + for (std::ptrdiff_t index = 0; index < static_cast(k); ++index) { + const auto cluster = static_cast(index); + const float count = state.batch_counts[cluster]; + state.pass_counts[cluster] += count; + const float* sums = state.batch_sums.data() + cluster * d; + if (last) { + float* pass = state.pass_sums.data() + cluster * d; + for (size_t dim = 0; dim < d; ++dim) { + pass[dim] += sums[dim]; + } + } + if (!replace_mass) { + state.mass[cluster] *= decay; + } + float* removal = state.removal.data() + cluster * (d + 1); + const float* batch_removal = state.batch_removal.data() + cluster * (d + 1); + removal[d] = (decay * removal[d]) + (alpha * batch_removal[d]); + if (count <= 0) { + continue; + } + double norm2 = 0.0; + for (size_t dim = 0; dim < d; ++dim) { + removal[dim] += axis_weight * batch_removal[dim]; + norm2 += static_cast(removal[dim]) * removal[dim]; + } + const double norm = std::sqrt(norm2); + if (norm > 0) { + float* axis = state.axes.data() + cluster * d; + for (size_t dim = 0; dim < d; ++dim) { + axis[dim] = static_cast(removal[dim] / norm); + } + } + const float retained = replace_mass ? 0.0F : state.mass[cluster]; + const float mass = retained + (alpha * count); + const float weight = alpha * count / mass; + float* centroid = state.centroids.data() + cluster * d; + for (size_t dim = 0; dim < d; ++dim) { + const float mean = sums[dim] / count; + const float moved = + weight == 1.0F ? mean : centroid[dim] + (weight * (mean - centroid[dim])); + // float32 means of points on the bound can round past it. + centroid[dim] = std::clamp(moved, -bound, bound); + } + state.mass[cluster] = mass; + } +} + +// Cost-based revival (Faiss's default): centroids whose removal cost R is at +// most zero or below kRemovalThreshold times the median move, cheapest first, +// to split the donors with the longest axes |U|, longest first. Pairs move in +// that order until the first whose donor's split gain kSplitGain * |U| does not +// exceed the candidate's R; a candidate with R <= 0 always moves. A split puts +// the donor and the candidate at c -/+ s u along the donor's unit axis u, with +// s = sqrt(2 |U| / (pi N)): the half-means of a Gaussian along u. They share the +// donor's halved mass and removal statistics. In the last iteration, both lose their +// pass sums and counts, so each closes from the vectors it receives after the +// split (Faiss's rule without closing handover). +[[nodiscard]] inline size_t revive(EMeansState& state, bool last) { + const size_t d = state.d; + const size_t k = state.k; + auto& costs = state.costs; + auto& axis_norms = state.axis_norms; + for (size_t cluster = 0; cluster < k; ++cluster) { + const float* removal = state.removal.data() + cluster * (d + 1); + costs[cluster] = removal[d]; + double norm2 = 0.0; + for (size_t dim = 0; dim < d; ++dim) { + norm2 += static_cast(removal[dim]) * removal[dim]; + } + axis_norms[cluster] = state.axis_scale * std::sqrt(norm2); + } + auto& sorted = state.sorted_costs; + std::copy(costs.begin(), costs.end(), sorted.begin()); + const size_t middle = k / 2; + std::nth_element( + sorted.begin(), sorted.begin() + static_cast(middle), sorted.end() + ); + double median = sorted[middle]; + if (k % 2 == 0) { + median = (median + + *std::max_element( + sorted.begin(), sorted.begin() + static_cast(middle) + )) / + 2.0; + } + const double threshold = kRemovalThreshold * median; + + auto& candidates = state.candidates; + auto& donors = state.donors; + candidates.clear(); + donors.clear(); + for (size_t cluster = 0; cluster < k; ++cluster) { + if (costs[cluster] <= 0 || costs[cluster] < threshold) { + candidates.push_back(cluster); + } else if (state.mass[cluster] > 0) { + donors.push_back(cluster); + } + } + if (candidates.empty()) { + return 0; + } + std::stable_sort(candidates.begin(), candidates.end(), [&](size_t a, size_t b) { + return costs[a] < costs[b]; + }); + // Donors rank by their float32 axis length, as in the reference. + std::stable_sort(donors.begin(), donors.end(), [&](size_t a, size_t b) { + return static_cast(axis_norms[a]) > static_cast(axis_norms[b]); + }); + size_t nsplit = 0; + const size_t pairs = std::min(candidates.size(), donors.size()); + while (nsplit < pairs) { + const double cost = costs[candidates[nsplit]]; + const double gain = kSplitGain * static_cast(axis_norms[donors[nsplit]]); + if (!(cost <= 0 || gain > cost)) { + break; + } + ++nsplit; + } + + // Donors and candidates are disjoint, so each split reads its donor's + // state from before this check. Split coordinates stay within the bound + // train() and assign() accept, so a trained model always assigns. + const auto bound = static_cast(max_coordinate_magnitude(d)); + for (size_t split = 0; split < nsplit; ++split) { + const size_t source = donors[split]; + const size_t target = candidates[split]; + const double norm = axis_norms[source]; + const auto mass = static_cast(state.mass[source]); + const bool valid = + norm > 0 && mass > 0 && std::isfinite(norm) && std::isfinite(mass); + const double spread = valid ? std::sqrt(2.0 * (norm / mass) / kPi) : 0.0; + float* donor = state.centroids.data() + source * d; + float* child = state.centroids.data() + target * d; + const float* axis = state.axes.data() + source * d; + bool collapsed = true; + for (size_t dim = 0; dim < d; ++dim) { + const auto value = static_cast(donor[dim]); + const double offset = spread * static_cast(axis[dim]); + donor[dim] = static_cast(std::clamp(value - offset, -bound, bound)); + child[dim] = static_cast(std::clamp(value + offset, -bound, bound)); + collapsed = collapsed && donor[dim] == child[dim]; + } + if (collapsed) { + // Coincident copies; separate the child along one coordinate, toward + // zero so it stays within the bound. + child[0] = std::nextafter( + child[0], + child[0] > 0 ? -std::numeric_limits::infinity() + : std::numeric_limits::infinity() + ); + } + const float half = state.mass[source] / 2.0F; + state.mass[source] = half; + state.mass[target] = half; + float* source_removal = state.removal.data() + source * (d + 1); + float* target_removal = state.removal.data() + target * (d + 1); + for (size_t dim = 0; dim <= d; ++dim) { + source_removal[dim] /= 2.0F; + target_removal[dim] = source_removal[dim]; + } + std::copy_n(axis, d, state.axes.data() + target * d); + if (last) { + for (const size_t cluster : {source, target}) { + state.pass_counts[cluster] = 0.0; + std::fill_n(state.pass_sums.data() + cluster * d, d, 0.0F); + } + } + } + return nsplit; +} + +// Closing means: centroids assigned during the last iteration become the mean of +// their last-iteration members; the others keep their positions. +inline void close_means(EMeansState& state, uint32_t num_workers) { + const size_t d = state.d; + const size_t k = state.k; + const float bound = max_coordinate_magnitude(d); + static_cast(num_workers); +#pragma omp parallel for num_threads(num_workers) schedule(static) + for (std::ptrdiff_t index = 0; index < static_cast(k); ++index) { + const auto cluster = static_cast(index); + if (state.pass_counts[cluster] > 0) { + const auto count = static_cast(state.pass_counts[cluster]); + for (size_t dim = 0; dim < d; ++dim) { + // As in apply_statistics, keep rounded means within the bound. + state.centroids[cluster * d + dim] = + std::clamp(state.pass_sums[cluster * d + dim] / count, -bound, bound); + } + } + } +} + +/** + * Mini-batch e-means over a pluggable assignment, the counterpart of LloydKMeans. + * Parameters provides niter, batch_size, verbose, seed, final_assignment and + * num_threads. Assignment provides: + * + * static constexpr const char* kName; // prefixes messages and output + * static void validate_parameters(size_t d, size_t k, const Parameters&); + * Assignment(size_t d, size_t k, const float* x, size_t n, uint32_t num_workers, + * const Parameters&); // one training call; may borrow x + * void prepare(const float* centroids); // before each mini-batch and the final + * // pass; may borrow centroids until the + * // next prepare + * void assign_batch(const size_t* rows, size_t count, PID* assignments, + * float* distances, float* second_distances); + * void end_pass(); // after each pass over all n training rows + * struct ModelState; // kept by the model for assign() + * void store_model_state(ModelState&) const; + * static bool has_model_state(const ModelState&, size_t d); + * static void assign_with_state(size_t d, size_t k, const float* centroids, + * const float* x, size_t n, uint32_t num_workers, + * const Parameters&, const ModelState&, + * PID* assignments, float* distances); + * + * assign_batch labels rows[i] (row i when rows is null) of the training x with the + * nearest prepared centroid it finds, which a graph search may miss and whose ties + * it breaks in no fixed order, and returns exact squared L2 distances to that + * centroid and, when second_distances is non-null, to the second one found; + * infinity when the assignment finds only one centroid. Revival reads + * second - first as each vector's removal cost. + */ +template +class EMeans : public Parameters { + public: + using Parameters::batch_size; + using Parameters::final_assignment; + using Parameters::niter; + using Parameters::num_threads; + using Parameters::seed; + using Parameters::verbose; + + EMeans(size_t d, size_t k, const Parameters& cp) : Parameters(cp), d(d), k(k) { + validate_parameters(); + } + + void train(size_t n, const float* x) { fit(n, x, true); } + + /** + * Trains the same centroids as train() but skips its final assignment of all n + * vectors. Leaves assignments and distances empty and final_obj zero; + * centroids, iteration_stats and assign() match a train() call. + */ + void train_centroids(size_t n, const float* x) { fit(n, x, false); } + + /** + * Assigns n row-major vectors to the current centroids with final_assignment. + * Each vector's result is independent of the others in the call. Requires a + * successful train() or train_centroids(); the outputs hold n elements each + * and must not overlap x or centroids. + */ + void assign( + size_t n, const float* x, PID* point_assignments, float* point_distances + ) const { + validate_parameters(); + const uint32_t num_workers = resolved_num_workers(); + clustering::detail::assign_trained( + Assignment::kName, + Assignment::has_model_state(model_state_, d), + d, + k, + centroids, + n, + x, + point_assignments, + point_distances, + num_workers, + [&] { assign_points(n, x, num_workers, point_assignments, point_distances); } + ); + } + + size_t d; + size_t k; + std::vector centroids; + std::vector assignments; + std::vector distances; + // One entry per iteration: obj sums the mini-batch assignment distances of that + // iteration, shift is the squared centroid displacement over it, and nsplit counts + // revived centroids. + std::vector iteration_stats; + // Objective of the final returned assignments against the final centroids. + double final_obj = 0.0; + + private: + void fit(size_t n, const float* x, bool assign_all) { + validate_parameters(); + if (x == nullptr) { + throw std::invalid_argument( + std::string(Assignment::kName) + " x must not be null" + ); + } + if (n < k) { + throw std::invalid_argument( + std::string(Assignment::kName) + " requires n >= k" + ); + } + const uint32_t num_workers = resolved_num_workers(); + clustering::detail::validate_points(Assignment::kName, n, d, x, num_workers, "x"); + + const Recipe recipe = resolve_recipe(n, k, niter, batch_size); + if (verbose) { + std::cout << Assignment::kName << " mini-batches of " << recipe.batch_size + << " training points\n"; + } + Assignment graph(d, k, x, n, num_workers, *this); + EMeansState state; + initialize(state, d, k, n, x, recipe.batch_size, seed); + + std::vector stats; + stats.reserve(niter); + std::vector order(n); + std::vector iteration_start(state.centroids.size()); + size_t step = 0; + for (size_t iteration = 0; iteration < niter; ++iteration) { + const bool last = iteration + 1 == niter; + std::copy( + state.centroids.begin(), state.centroids.end(), iteration_start.begin() + ); + start_iteration(state, last); + std::iota(order.begin(), order.end(), size_t{0}); + std::mt19937_64 rng(iteration_seed(seed, iteration)); + std::shuffle(order.begin(), order.end(), rng); + double objective = 0.0; + size_t nsplit = 0; + for (size_t begin = 0; begin < n; begin += recipe.batch_size) { + const size_t rows = std::min(recipe.batch_size, n - begin); + const size_t* batch = order.data() + begin; + graph.prepare(state.centroids.data()); + graph.assign_batch( + batch, + rows, + state.batch_assignments.data(), + state.batch_distances.data(), + state.batch_second_distances.data() + ); + objective += accumulate(state, x, batch, rows, num_workers); + apply_statistics( + state, + scheduled_alpha(recipe.alpha0, step, recipe.total_steps), + last, + num_workers + ); + if ((step + 1) % kReviveEvery == 0) { + nsplit += revive(state, last); + } + ++step; + } + graph.end_pass(); + if (last) { + close_means(state, num_workers); + } + double shift = 0.0; + for (size_t cluster = 0; cluster < k; ++cluster) { + shift += clustering::detail::euclidean_sqr_f64( + state.centroids.data() + cluster * d, + iteration_start.data() + cluster * d, + d + ); + } + stats.push_back({iteration + 1, objective, shift, nsplit}); + if (verbose) { + std::cout << Assignment::kName << " iteration " << iteration + 1 << "/" + << niter << " | objective=" << objective << " | shift=" << shift + << " | splits=" << nsplit << '\n'; + } + } + + std::vector final_assignments; + std::vector final_distances; + double objective = 0.0; + if (assign_all) { + final_assignments.resize(n); + final_distances.resize(n); + // The approximate pass reuses the training assignment and its state. + clustering::detail::assign_with_mode( + final_assignment, + x, + state.centroids.data(), + n, + d, + k, + false, + num_workers, + final_assignments.data(), + final_distances.data(), + [&] { + graph.prepare(state.centroids.data()); + graph.assign_batch( + nullptr, + n, + final_assignments.data(), + final_distances.data(), + nullptr + ); + } + ); + objective = + std::accumulate(final_distances.begin(), final_distances.end(), 0.0); + } + + // Commit: the previous results stay intact if anything above throws. + centroids.swap(state.centroids); + assignments.swap(final_assignments); + distances.swap(final_distances); + iteration_stats.swap(stats); + final_obj = objective; + graph.store_model_state(model_state_); + } + + // Assigns validated points to the current centroids without training state, so + // each point's result is independent of the batch. Requires n > 0 and outputs + // that do not overlap x or centroids. + void assign_points( + size_t n, + const float* x, + uint32_t num_workers, + PID* point_assignments, + float* point_distances + ) const { + clustering::detail::assign_with_mode( + final_assignment, + x, + centroids.data(), + n, + d, + k, + false, + num_workers, + point_assignments, + point_distances, + [&] { + Assignment::assign_with_state( + d, + k, + centroids.data(), + x, + n, + num_workers, + *this, + model_state_, + point_assignments, + point_distances + ); + } + ); + } + + void validate_parameters() const { + clustering::detail::validate_common_parameters( + Assignment::kName, d, k, niter, "niter", num_threads, final_assignment + ); + Assignment::validate_parameters(d, k, *this); + } + + [[nodiscard]] uint32_t resolved_num_workers() const { + return static_cast(resolve_num_threads(num_threads)); + } + + // Kept for assign(); empty until the first successful fit. + typename Assignment::ModelState model_state_; +}; + +} // namespace rabitqlib::qgemeans::detail diff --git a/include/rabitqlib/clustering/detail/kmeans.hpp b/include/rabitqlib/clustering/detail/kmeans.hpp index 9257ef39..e8917d05 100644 --- a/include/rabitqlib/clustering/detail/kmeans.hpp +++ b/include/rabitqlib/clustering/detail/kmeans.hpp @@ -241,6 +241,147 @@ inline void exact_assign( return indices; } +// Checks n row-major vectors of d coordinates: n * d must fit in ptrdiff_t, and +// every coordinate must be finite and within the clustering bound. component and +// name prefix the error messages. Requires a non-null x and d > 0. +inline void validate_points( + const char* component, + size_t n, + size_t d, + const float* x, + uint32_t num_workers, + const char* name +) { + if (n > static_cast(std::numeric_limits::max()) / d) { + throw std::invalid_argument( + std::string(component) + " input dimensions overflow ptrdiff_t" + ); + } + // 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; + static_cast(num_workers); +#pragma omp parallel for num_threads(num_workers) reduction(&& : finite, in_range) \ + schedule(static) + for (std::ptrdiff_t index = 0; index < static_cast(n * d); ++index) { + const size_t i = static_cast(index); + finite = finite && std::isfinite(x[i]); + in_range = in_range && std::abs(x[i]) <= max_coordinate; + } + if (!finite) { + throw std::invalid_argument( + std::string(component) + " " + name + " must contain only finite values" + ); + } + if (!in_range) { + throw std::invalid_argument( + std::string(component) + " " + name + + " exceeds the safe float32 coordinate range" + ); + } +} + +// Checks the settings every clustering class shares. iterations is niter, +// named by iterations_name in the error message. +inline void validate_common_parameters( + const char* component, + size_t d, + size_t k, + size_t iterations, + const char* iterations_name, + uint32_t num_threads, + FinalAssignmentMode final_assignment +) { + if (d == 0 || k == 0 || iterations == 0) { + throw std::invalid_argument( + std::string(component) + " d, k, and " + iterations_name + " must be positive" + ); + } + if (d < 64 || d > rotator_impl::FhtKacRotator::kMaxDim) { + throw std::invalid_argument( + std::string(component) + + " currently requires dimensions in the range [64, 65536]" + ); + } + if (num_threads > static_cast(std::numeric_limits::max())) { + throw std::invalid_argument( + std::string(component) + " num_threads must fit in an OpenMP int" + ); + } + if (final_assignment != FinalAssignmentMode::Approximate && + final_assignment != FinalAssignmentMode::Exact) { + throw std::invalid_argument( + std::string(component) + " final_assignment mode is invalid" + ); + } +} + +// The shared public assign(): checks that a model is trained, with k * d valid +// centroids, and validates the inputs, then calls assign_points() when n > 0. +template +void assign_trained( + const char* component, + bool trained, + size_t d, + size_t k, + const std::vector& centroids, + size_t n, + const float* x, + const PID* point_assignments, + const float* point_distances, + uint32_t num_workers, + AssignPoints&& assign_points +) { + if (!trained || centroids.size() != k * d) { + throw std::runtime_error(std::string(component) + " has not been trained"); + } + validate_points(component, k, d, centroids.data(), num_workers, "centroids"); + if (n == 0) { + return; + } + if (x == nullptr || point_assignments == nullptr || point_distances == nullptr) { + throw std::invalid_argument( + std::string(component) + " assign input and output pointers must not be null" + ); + } + validate_points(component, n, d, x, num_workers, "x"); + std::forward(assign_points)(); +} + +// Final assignment of n validated points: exhaustive for Exact, approximate() +// otherwise. Requires n > 0 and outputs that do not overlap x or centroids. +template +void assign_with_mode( + FinalAssignmentMode final_assignment, + const float* x, + const float* centroids, + size_t n, + size_t d, + size_t k, + bool spherical, + uint32_t num_workers, + PID* point_assignments, + float* point_distances, + Approximate&& approximate +) { + if (final_assignment == FinalAssignmentMode::Exact) { + exact_assign( + x, + centroids, + n, + d, + k, + spherical, + num_workers, + point_assignments, + point_distances + ); + } else { + std::forward(approximate)(); + } +} + // Copy the fields LloydKMeans reads, which every k-means parameter type shares, // leaving the method-specific ones of `to` unchanged. Keep this list and the // using-declarations below the same. @@ -300,7 +441,7 @@ class LloydKMeans : public Parameters { ); } const uint32_t num_workers = resolved_num_workers(); - validate_points(n, x, num_workers, "x"); + validate_points(Assignment::kName, n, d, x, num_workers, "x"); if (verbose && min_points_per_centroid > 0 && n / k < min_points_per_centroid) { std::cerr << "WARNING " << Assignment::kName << " clustering " << n << " points to " << k << " centroids: please provide at least " @@ -453,25 +594,20 @@ class LloydKMeans : public Parameters { size_t n, const float* x, PID* point_assignments, float* point_distances ) const { validate_parameters(); - if (centroids.size() != k * d || - !Assignment::has_model_state(assignment_state_, d)) { - throw std::runtime_error( - std::string(Assignment::kName) + " has not been trained" - ); - } const uint32_t num_workers = resolved_num_workers(); - validate_points(k, centroids.data(), num_workers, "centroids"); - if (n == 0) { - return; - } - if (x == nullptr || point_assignments == nullptr || point_distances == nullptr) { - throw std::invalid_argument( - std::string(Assignment::kName) + - " assign input and output pointers must not be null" - ); - } - validate_points(n, x, num_workers, "x"); - assign_points(n, x, num_workers, point_assignments, point_distances); + assign_trained( + Assignment::kName, + Assignment::has_model_state(assignment_state_, d), + d, + k, + centroids, + n, + x, + point_assignments, + point_distances, + num_workers, + [&] { assign_points(n, x, num_workers, point_assignments, point_distances); } + ); } size_t d; @@ -494,28 +630,9 @@ class LloydKMeans : public Parameters { }; void validate_parameters() const { - if (d == 0 || k == 0 || niter == 0) { - throw std::invalid_argument( - std::string(Assignment::kName) + " d, k, and niter must be positive" - ); - } - if (d < 64 || d > rotator_impl::FhtKacRotator::kMaxDim) { - throw std::invalid_argument( - std::string(Assignment::kName) + - " currently requires dimensions in the range [64, 65536]" - ); - } - if (num_threads > static_cast(std::numeric_limits::max())) { - throw std::invalid_argument( - std::string(Assignment::kName) + " num_threads must fit in an OpenMP int" - ); - } - if (final_assignment != FinalAssignmentMode::Approximate && - final_assignment != FinalAssignmentMode::Exact) { - throw std::invalid_argument( - std::string(Assignment::kName) + " final_assignment mode is invalid" - ); - } + validate_common_parameters( + Assignment::kName, d, k, niter, "niter", num_threads, final_assignment + ); Assignment::validate_parameters(k, *this); if (!std::isfinite(early_stop_threshold) || early_stop_threshold < 0.0 || early_stop_threshold > 1.0) { @@ -526,41 +643,6 @@ class LloydKMeans : public Parameters { } } - // Requires a non-null x. name identifies the rows in error messages. - void validate_points( - size_t n, const float* x, uint32_t num_workers, const char* name - ) const { - if (n > static_cast(std::numeric_limits::max()) / d) { - throw std::invalid_argument( - std::string(Assignment::kName) + " input dimensions overflow ptrdiff_t" - ); - } - // 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) \ - schedule(static) - for (std::ptrdiff_t index = 0; index < static_cast(n * d); - ++index) { - const size_t i = static_cast(index); - finite = finite && std::isfinite(x[i]); - in_range = in_range && std::abs(x[i]) <= max_coordinate; - } - if (!finite) { - throw std::invalid_argument( - std::string(Assignment::kName) + " " + name + - " must contain only finite values" - ); - } - if (!in_range) { - throw std::invalid_argument( - std::string(Assignment::kName) + " " + name + - " exceeds the safe float32 coordinate range" - ); - } - } - // Assigns validated points to the current centroids. Uses the state saved by // train() but neither Lloyd assignments nor graph search hints, so each // point's result is independent of the batch. Requires n > 0 and outputs @@ -572,32 +654,32 @@ class LloydKMeans : public Parameters { PID* point_assignments, float* point_distances ) const { - if (final_assignment == FinalAssignmentMode::Exact) { - detail::exact_assign( - x, - centroids.data(), - n, - d, - k, - spherical, - num_workers, - point_assignments, - point_distances - ); - } else { - Assignment::assign_with_state( - d, - k, - centroids.data(), - x, - n, - num_workers, - *this, - assignment_state_, - point_assignments, - point_distances - ); - } + assign_with_mode( + final_assignment, + x, + centroids.data(), + n, + d, + k, + spherical, + num_workers, + point_assignments, + point_distances, + [&] { + Assignment::assign_with_state( + d, + k, + centroids.data(), + x, + n, + num_workers, + *this, + assignment_state_, + point_assignments, + point_distances + ); + } + ); } void initialize_centroids(const float* x, size_t n) { diff --git a/include/rabitqlib/clustering/detail/qg_assigner.hpp b/include/rabitqlib/clustering/detail/qg_assigner.hpp new file mode 100644 index 00000000..0334828a --- /dev/null +++ b/include/rabitqlib/clustering/detail/qg_assigner.hpp @@ -0,0 +1,533 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rabitqlib/core/metric.hpp" +#include "rabitqlib/core/rotator.hpp" +#include "rabitqlib/fastscan/pack_codes.hpp" +#include "rabitqlib/fastscan/query.hpp" +#include "rabitqlib/index/detail/parallel_exception.hpp" +#include "rabitqlib/index/detail/visited_set.hpp" +#include "rabitqlib/index/symqg/detail/search_scratch.hpp" +#include "rabitqlib/index/symqg/qg.hpp" +#include "rabitqlib/index/symqg/qg_builder.hpp" +#include "rabitqlib/index/types.hpp" +#include "rabitqlib/utils/space.hpp" +#include "rabitqlib/utils/tools.hpp" + +// The SymphonyQG centroid-graph assigner shared by QGKMeans and QGEMeans. +namespace rabitqlib::clustering::detail { + +// Padded dimensions from which assignment caches each query's sum of coordinates. +constexpr size_t kMinQuerySumDim = 512; + +// Most centroids one search returns: the nearest, and the second for QGEMeans' +// removal costs. +constexpr uint32_t kMaxQGResults = 2; + +// Settings that determine a centroid graph and its search results. +struct QGGraphSettings { + uint32_t max_degree; + uint32_t ef_construction; + uint32_t ef_search; + uint32_t graph_build_iterations; + uint32_t num_threads = 0; + uint32_t seed = 42; + MetricType metric_type = METRIC_L2; + // QG's own storage argument, which is 0 for raw float32. + uint32_t quantization_bits = 0; + // Centroids each search returns, 1 or 2. + uint32_t results = 1; + + [[nodiscard]] bool operator==(const QGGraphSettings& other) const { + return max_degree == other.max_degree && ef_construction == other.ef_construction && + ef_search == other.ef_search && + graph_build_iterations == other.graph_build_iterations && + num_threads == other.num_threads && seed == other.seed && + metric_type == other.metric_type && + quantization_bits == other.quantization_bits && results == other.results; + } +}; + +// Checks the centroid-graph settings; component prefixes the error messages. +inline void validate_graph_parameters( + const char* component, size_t d, size_t k, const QGGraphSettings& settings +) { + if (d < 64 || d > rotator_impl::FhtKacRotator::kMaxDim) { + throw std::invalid_argument( + std::string(component) + + " currently requires dimensions in the range [64, 65536]" + ); + } + if (settings.max_degree == 0 || settings.max_degree % fastscan::kBatchSize != 0) { + throw std::invalid_argument( + std::string(component) + " max_degree must be a positive multiple of 32" + ); + } + if (k <= settings.max_degree) { + throw std::invalid_argument( + std::string(component) + " requires more centroids than max_degree" + ); + } + if (settings.ef_construction == 0 || settings.ef_search == 0) { + throw std::invalid_argument( + std::string(component) + " ef_construction and ef_search must be positive" + ); + } + // A search pool smaller than its result count is rejected by the graph. + if (settings.ef_search < settings.results) { + throw std::invalid_argument( + std::string(component) + " ef_search must be at least " + + std::to_string(settings.results) + ); + } + if (settings.graph_build_iterations == 0) { + throw std::invalid_argument( + std::string(component) + " graph_build_iterations must be positive" + ); + } +} + +// Per-point query sums for repeated searches of the same input vectors. Either +// owns storage for one training call or borrows caller storage. State is +// read-only while workers run. +class QuerySumCache { + enum class State { Disabled, Pending, Ready }; + State state_ = State::Disabled; + std::vector storage_; + float* values_ = nullptr; + + public: + // Owns storage, allocated by prepare(), when reused and padded_dim is large enough. + QuerySumCache(size_t padded_dim, bool reused) { + if (reused && padded_dim >= kMinQuerySumDim) { + state_ = State::Pending; + } + } + + QuerySumCache(float* values, bool ready) : values_(values) { + if (values != nullptr) { + state_ = ready ? State::Ready : State::Pending; + } + } + + QuerySumCache(const QuerySumCache&) = delete; + QuerySumCache& operator=(const QuerySumCache&) = delete; + + // Allocates owned storage for n points. Training keeps n and the + // input/rotation fixed throughout this lifetime. + void prepare(size_t n) { + if (state_ == State::Pending && values_ == nullptr) { + storage_.resize(n); + values_ = storage_.data(); + } + } + + [[nodiscard]] const float* cached(size_t i) const { + return state_ == State::Ready ? values_ + i : nullptr; + } + + void store(size_t i, float value) const { + if (state_ == State::Pending) { + values_[i] = value; + } + } + + // Commit only after every worker and the caller's state update succeed. + void complete() { + if (state_ == State::Pending) { + state_ = State::Ready; + } + } +}; + +/** + * Builds a SymphonyQG over a fixed number of centroids and finds each vector's + * nearest centroid, and optionally the second nearest. The graph allocation and + * per-thread search scratch are reused between calls; assign_with_cache() uses + * the previous assignment as the next call's search hint. + */ +class QGAssigner { + public: + // component prefixes the error messages. + QGAssigner(size_t d, size_t k, const QGGraphSettings& settings, const char* component) + : dim_(d), num_clusters_(k), settings_(settings) { + if (settings.num_threads > static_cast(std::numeric_limits::max())) { + throw std::invalid_argument("QGAssigner num_threads must fit in an OpenMP int"); + } + validate_graph_parameters(component, d, k, settings); + // Cosine belongs to the indexes, which normalize vectors; the assigner's exact + // distances are raw L2 or inner product. + validate_metric_type(settings.metric_type); + // Quantized searches rerank only the nearest centroid. + assert(settings.results == 1 || settings.quantization_bits == 0); + assert(settings.results >= 1 && settings.results <= kMaxQGResults); + num_workers_ = static_cast(resolve_num_threads(settings.num_threads)); + + graph_ = std::make_unique>( + num_clusters_, + dim_, + settings.max_degree, + settings.metric_type, + RotatorType::FhtKacRotator, + settings.quantization_bits, + settings.seed + ); + graph_->set_ef(settings.ef_search); + scratch_ = make_scratch(); + } + + [[nodiscard]] size_t padded_dim() const { return graph_->padded_dim(); } + + void clear_hints() { previous_assignments_.clear(); } + + void rebuild_centroid_graph(const float* centroids) { + if (builder_) { + builder_->reset(centroids); + } else { + // Centroid graphs have much less work than the training-vector batch. + // Amortize their short phases without reducing assignment parallelism. + constexpr size_t kMinVerticesPerBuildThread = 128; + const size_t build_threads = std::min( + num_workers_, + std::max(1, num_clusters_ / kMinVerticesPerBuildThread) + ); + builder_ = std::make_unique( + *graph_, + settings_.ef_construction, + centroids, + build_threads, + symqg::QGInitialization::PiPNN, + settings_.seed, + true + ); + } + if (settings_.graph_build_iterations == 1) { + builder_->build(); + } else { + builder_->build(settings_.graph_build_iterations); + } + } + + // Rebuilds the graph over centroids and assigns all n points, hinted by the + // previous call's assignments when it had the same n. + void assign_with_cache( + const float* centroids, + const float* x, + size_t n, + PID* assignments, + float* distances, + QuerySumCache& query_sums + ) { + if (centroids == nullptr || x == nullptr || assignments == nullptr || + distances == nullptr) { + throw std::invalid_argument( + "QGAssigner input and output pointers must not be null" + ); + } + + if (n > static_cast(std::numeric_limits::max()) / dim_) { + throw std::invalid_argument("QGAssigner input dimensions overflow ptrdiff_t"); + } + + rebuild_centroid_graph(centroids); + + // Stable grouping changes only the order of independent full searches. + std::vector query_order; + if (previous_assignments_.size() == n && + n <= std::numeric_limits::max()) { + query_order.resize(n); + std::vector offsets(num_clusters_ + 1, 0); + for (PID cluster_id : previous_assignments_) { + ++offsets[cluster_id + 1]; + } + std::partial_sum(offsets.begin(), offsets.end(), offsets.begin()); + for (size_t point = 0; point < n; ++point) { + query_order[offsets[previous_assignments_[point]]++] = + static_cast(point); + } + } + search_points( + centroids, + x, + n, + query_order.empty() ? nullptr : query_order.data(), + nullptr, + previous_assignments_.size() == n ? previous_assignments_.data() : nullptr, + assignments, + distances, + nullptr, + query_sums, + scratch_ + ); + + previous_assignments_.assign(assignments, assignments + n); + query_sums.complete(); + } + + // Requires a graph built from centroids. Uses no hints or query-sum cache + // and allocates its own scratch, so concurrent calls only read the graph. + void search_built_graph( + const float* centroids, const float* x, size_t n, PID* assignments, float* distances + ) const { + const auto scratch = make_scratch(); + const QuerySumCache query_sums(nullptr, false); + search_points( + centroids, + x, + n, + nullptr, + nullptr, + nullptr, + assignments, + distances, + nullptr, + query_sums, + scratch + ); + } + + // Searches rows[i] (row i when rows is null) of x for output i with this + // assigner's scratch; see search_points. + void search_rows( + const float* centroids, + const float* x, + size_t n, + const size_t* rows, + PID* assignments, + float* distances, + float* second_distances, + const QuerySumCache& query_sums + ) { + search_points( + centroids, + x, + n, + nullptr, + rows, + nullptr, + assignments, + distances, + second_distances, + query_sums, + scratch_ + ); + } + + private: + /** + * Searches each point independently for its nearest centroid and distance. + * Output i reads input row rows[i] (row i when rows is null), which also + * indexes the query-sum cache. A non-null query_order lists the outputs in + * scheduling order; non-null hints hold one centroid ID per output. With + * 2 results and non-null second_distances, also returns the distance to the + * second nearest (infinity if the search reaches one centroid). centroids + * may be null for a raw graph; quantized distances are recomputed from it. + */ + void search_points( + const float* centroids, + const float* x, + size_t n, + const uint32_t* query_order, + const size_t* rows, + const PID* hints, + PID* assignments, + float* distances, + float* second_distances, + const QuerySumCache& query_sums, + const std::vector>& scratch + ) const { + assert(centroids != nullptr || !graph_->is_quantized()); + assert(second_distances == nullptr || settings_.results == 2); + const auto distance_func = graph_->metric_type() == METRIC_IP + ? dot_product_dis + : euclidean_sqr; + const uint32_t ef_search = settings_.ef_search; + index_detail::ParallelException failure; +#pragma omp parallel for num_threads(num_workers_) schedule(dynamic, 64) + for (std::ptrdiff_t index = 0; index < static_cast(n); ++index) { + const size_t i = query_order == nullptr + ? static_cast(index) + : query_order[static_cast(index)]; + const int thread_id = omp_get_thread_num(); + if (failure.failed()) { + continue; + } + try { + auto& worker_scratch = *scratch[static_cast(thread_id)]; + // Keep visited storage with the worker, as in QuantizedGraph::search. + thread_local VisitedSet visited; + thread_local size_t visited_size = 0; + thread_local size_t visited_capacity = 0; + const size_t capacity = std::min( + static_cast(ef_search) * ef_search, num_clusters_ / 10 + ); + if (visited_size != num_clusters_ || visited_capacity != capacity) { + visited.initialize(num_clusters_, capacity); + visited_size = num_clusters_; + visited_capacity = capacity; + } + const size_t row = rows == nullptr ? i : rows[i]; + const PID hint = hints == nullptr ? kPidMax : hints[i]; + std::array ids{}; + std::array found{}; + symqg::detail::search_with_workspace( + *graph_, + x + row * dim_, + settings_.results, + ids.data(), + found.data(), + worker_scratch.view(visited), + hint, + query_sums.cached(row) + ); + query_sums.store(row, worker_scratch.batch_query.g_k1xsumq()); + assignments[i] = ids[0]; + distances[i] = found[0]; + if (second_distances != nullptr) { + second_distances[i] = found[1]; + } + if (graph_->is_quantized()) { + // Keep objectives and returned distances relative to the original + // centroids; graph search scores are quantized estimates. + distances[i] = distance_func( + x + row * dim_, centroids + assignments[i] * dim_, dim_ + ); + } + } catch (...) { failure.capture(); } + } + + failure.rethrow(); + } + + [[nodiscard]] std::vector> + make_scratch() const { + std::vector> scratch; + scratch.reserve(num_workers_); + for (uint32_t thread = 0; thread < num_workers_; ++thread) { + scratch.emplace_back( + std::make_unique( + graph_->padded_dim(), + settings_.max_degree, + settings_.ef_search, + settings_.results + ) + ); + } + return scratch; + } + + size_t dim_; + size_t num_clusters_; + QGGraphSettings settings_; + uint32_t num_workers_ = 0; + std::unique_ptr> graph_; + std::unique_ptr builder_; + std::vector> scratch_; + std::vector previous_assignments_; +}; + +// Graph over a model's centroids for stateless assignment, rebuilt when the +// centroids or graph settings differ from those it was built from. Copies share +// the immutable graph; each object has its own lock. +class CentroidGraphCache { + struct Entry { + std::vector centroids; + QGGraphSettings settings; + QGAssigner assigner; + + Entry( + size_t d, + size_t k, + const float* source, + const QGGraphSettings& graph, + const char* component + ) + : centroids(source, source + k * d) + , settings(graph) + , assigner(d, k, graph, component) { + // The builder borrows this copy, which lives as long as the graph. + assigner.rebuild_centroid_graph(centroids.data()); + } + + [[nodiscard]] bool matches( + size_t d, size_t k, const float* source, const QGGraphSettings& graph + ) const { + return centroids.size() == k * d && + std::equal(centroids.begin(), centroids.end(), source) && + settings == graph; + } + }; + + mutable std::mutex mutex_; + mutable std::shared_ptr entry_; + + [[nodiscard]] std::shared_ptr snapshot() const { + const std::lock_guard lock(mutex_); + return entry_; + } + + public: + CentroidGraphCache() = default; + + CentroidGraphCache(const CentroidGraphCache& other) : entry_(other.snapshot()) {} + + CentroidGraphCache& operator=(const CentroidGraphCache& other) { + if (this != &other) { + auto entry = other.snapshot(); + const std::lock_guard lock(mutex_); + entry_ = std::move(entry); + } + return *this; + } + + ~CentroidGraphCache() = default; + + void clear() { + const std::lock_guard lock(mutex_); + entry_.reset(); + } + + // Requires k * d validated centroid coordinates and validated settings; + // component prefixes the error messages. + void assign( + size_t d, + size_t k, + const float* centroids, + const QGGraphSettings& settings, + const char* component, + const float* x, + size_t n, + PID* assignments, + float* distances + ) const { + std::shared_ptr entry; + { + const std::lock_guard lock(mutex_); + if (!entry_ || !entry_->matches(d, k, centroids, settings)) { + entry_ = + std::make_shared(d, k, centroids, settings, component); + } + entry = entry_; + } + entry->assigner.search_built_graph( + entry->centroids.data(), x, n, assignments, distances + ); + } +}; + +} // namespace rabitqlib::clustering::detail diff --git a/include/rabitqlib/clustering/qgemeans.hpp b/include/rabitqlib/clustering/qgemeans.hpp new file mode 100644 index 00000000..ef114bdb --- /dev/null +++ b/include/rabitqlib/clustering/qgemeans.hpp @@ -0,0 +1,165 @@ +#pragma once + +#include +#include + +#include "rabitqlib/clustering/detail/emeans.hpp" +#include "rabitqlib/clustering/detail/kmeans.hpp" // IWYU pragma: export +#include "rabitqlib/clustering/detail/qg_assigner.hpp" +#include "rabitqlib/core/metric.hpp" +#include "rabitqlib/index/types.hpp" + +namespace rabitqlib::qgemeans { + +using clustering::FinalAssignmentMode; + +struct QGEMeansParameters { + // Number of clustering iterations, each one pass over the training vectors. + size_t niter = 8; + // Vectors per mini-batch; 0 selects the batch-size law. + size_t batch_size = 0; + bool verbose = false; + uint32_t seed = 42; + FinalAssignmentMode final_assignment = FinalAssignmentMode::Approximate; + + // SymphonyQG assignment parameters, as in QGKMeansParameters. + uint32_t max_degree = 32; + uint32_t ef_construction = 240; + uint32_t ef_search = 16; + // Graph-building passes after PiPNN initialization; the last refines the graph. + uint32_t graph_build_iterations = 1; + uint32_t num_threads = 0; +}; + +namespace detail { + +constexpr const char* kName = "QGEMeans"; + +// Centroids each search returns: the nearest centroid labels the vector, and the +// second gives the removal cost of cost-based revival. +constexpr uint32_t kSearchResults = 2; + +[[nodiscard]] inline clustering::detail::QGGraphSettings graph_settings( + const QGEMeansParameters& cp +) { + return { + cp.max_degree, + cp.ef_construction, + cp.ef_search, + cp.graph_build_iterations, + cp.num_threads, + cp.seed, + METRIC_L2, + 0, + kSearchResults}; +} + +// SymphonyQG assignment for EMeans: a raw-vector graph over the current centroids, +// rebuilt by every prepare() and searched for each row's two nearest centroids, +// without hints. The query-sum cache is filled during the first pass, which visits +// every row once, and reused afterwards. assign() searches a cached graph over +// the final centroids. +class QGEAssignment { + const float* data_; + const float* centroids_ = nullptr; + clustering::detail::QGAssigner assigner_; + clustering::detail::QuerySumCache query_sums_; + + public: + static constexpr const char* kName = detail::kName; + + static void validate_parameters(size_t d, size_t k, const QGEMeansParameters& cp) { + clustering::detail::validate_graph_parameters(kName, d, k, graph_settings(cp)); + } + + QGEAssignment( + size_t d, size_t k, const float* x, size_t n, uint32_t, const QGEMeansParameters& cp + ) + : data_(x) + , assigner_(d, k, graph_settings(cp), kName) + // Later passes and the final approximate assignment reread every row. + , query_sums_( + assigner_.padded_dim(), + cp.niter > 1 || cp.final_assignment != FinalAssignmentMode::Exact + ) { + query_sums_.prepare(n); + } + + void prepare(const float* centroids) { + centroids_ = centroids; + assigner_.rebuild_centroid_graph(centroids); + } + + void assign_batch( + const size_t* rows, + size_t count, + PID* assignments, + float* distances, + float* second_distances + ) { + assigner_.search_rows( + centroids_, + data_, + count, + rows, + assignments, + distances, + second_distances, + query_sums_ + ); + } + + // Every row has been searched once, so its query sum is cached. + void end_pass() { query_sums_.complete(); } + + struct ModelState { + bool trained = false; + clustering::detail::CentroidGraphCache graph; + }; + + void store_model_state(ModelState& state) const { + state.graph.clear(); + state.trained = true; + } + + [[nodiscard]] static bool has_model_state(const ModelState& state, size_t) { + return state.trained; + } + + // Requires validated inputs and centroids. Reuses the cached centroid graph. + static void assign_with_state( + size_t d, + size_t k, + const float* centroids, + const float* x, + size_t n, + uint32_t, + const QGEMeansParameters& cp, + const ModelState& state, + PID* assignments, + float* distances + ) { + state.graph.assign( + d, k, centroids, graph_settings(cp), kName, x, n, assignments, distances + ); + } +}; + +} // namespace detail + +/** + * Mini-batch e-means with SymphonyQG graph assignment. Each mini-batch is assigned + * through a raw-vector graph over the current centroids, rebuilt before every + * batch; centroids follow the e-means mass-weighted update and cost-based revival + * of cheap centroids. train() then assigns every vector to the final centroids. + */ +class QGEMeans : public detail::EMeans { + using Base = detail::EMeans; + + public: + QGEMeans(size_t d, size_t k) : QGEMeans(d, k, QGEMeansParameters{}) {} + + QGEMeans(size_t d, size_t k, const QGEMeansParameters& cp) : Base(d, k, cp) {} +}; + +} // namespace rabitqlib::qgemeans diff --git a/include/rabitqlib/clustering/qgkmeans.hpp b/include/rabitqlib/clustering/qgkmeans.hpp index 96f112c2..4582c3e8 100644 --- a/include/rabitqlib/clustering/qgkmeans.hpp +++ b/include/rabitqlib/clustering/qgkmeans.hpp @@ -2,41 +2,21 @@ #include -#include #include #include -#include -#include -#include -#include #include #include #include "rabitqlib/clustering/detail/kmeans.hpp" // IWYU pragma: export +#include "rabitqlib/clustering/detail/qg_assigner.hpp" #include "rabitqlib/core/metric.hpp" -#include "rabitqlib/core/rotator.hpp" -#include "rabitqlib/fastscan/pack_codes.hpp" -#include "rabitqlib/fastscan/query.hpp" -#include "rabitqlib/index/detail/parallel_exception.hpp" -#include "rabitqlib/index/detail/visited_set.hpp" -#include "rabitqlib/index/symqg/detail/search_scratch.hpp" -#include "rabitqlib/index/symqg/qg.hpp" -#include "rabitqlib/index/symqg/qg_builder.hpp" #include "rabitqlib/index/types.hpp" #include "rabitqlib/utils/space.hpp" -#include "rabitqlib/utils/tools.hpp" namespace rabitqlib::qgkmeans { using clustering::FinalAssignmentMode; -namespace detail { - -class CentroidGraphCache; -class QGAssignment; - -} // namespace detail - struct QGKMeansParameters { // Number of clustering iterations. size_t niter = 25; @@ -66,64 +46,25 @@ struct QGKMeansParameters { namespace detail { -// QG's own storage argument, which is 0 for raw float32. -inline uint32_t qg_quantization_bits(const QGKMeansParameters& cp) { - return cp.nbits == 32 ? 0 : cp.nbits; +[[nodiscard]] inline clustering::detail::QGGraphSettings graph_settings( + const QGKMeansParameters& cp +) { + return { + cp.max_degree, + cp.ef_construction, + cp.ef_search, + cp.graph_build_iterations, + cp.num_threads, + cp.seed, + cp.spherical ? METRIC_IP : METRIC_L2, + // QG's own storage argument, which is 0 for raw float32. + cp.nbits == 32 ? 0 : cp.nbits}; } -// One training call owns the storage; the public assign adapter can instead -// borrow caller storage for one batch. State is read-only while workers run. -class QuerySumCache { - enum class State { Disabled, Pending, Ready }; - State state_ = State::Disabled; - std::vector storage_; - float* values_ = nullptr; - - public: - QuerySumCache(size_t padded_dim, const QGKMeansParameters& parameters) { - constexpr size_t kMinCachedDim = 512; - if (padded_dim >= kMinCachedDim && - (parameters.niter > 1 || - parameters.final_assignment != FinalAssignmentMode::Exact)) { - state_ = State::Pending; - } - } - - QuerySumCache(float* values, bool ready) : values_(values) { - if (values != nullptr) { - state_ = ready ? State::Ready : State::Pending; - } - } - - QuerySumCache(const QuerySumCache&) = delete; - QuerySumCache& operator=(const QuerySumCache&) = delete; - - // Called after centroid initialization releases its point permutation. - // Training keeps n and the input/rotation fixed throughout this lifetime. - void prepare(size_t n) { - if (state_ == State::Pending && values_ == nullptr) { - storage_.resize(n); - values_ = storage_.data(); - } - } - - [[nodiscard]] const float* cached(size_t i) const { - return state_ == State::Ready ? values_ + i : nullptr; - } - - void store(size_t i, float value) const { - if (state_ == State::Pending) { - values_[i] = value; - } - } - - // Commit only after every worker and the assignment's state update succeed. - void complete() { - if (state_ == State::Pending) { - state_ = State::Ready; - } - } -}; +// Whether training searches the same vectors more than once. +[[nodiscard]] inline bool reuses_query_sums(const QGKMeansParameters& cp) { + return cp.niter > 1 || cp.final_assignment != FinalAssignmentMode::Exact; +} } // namespace detail @@ -133,9 +74,6 @@ class QuerySumCache { * calls, and the previous assignment is used as the next call's search hint. */ class QGAssigner { - friend class detail::CentroidGraphCache; - friend class detail::QGAssignment; - public: QGAssigner( size_t d, @@ -149,39 +87,19 @@ class QGAssigner { MetricType metric_type = METRIC_L2, uint32_t quantization_bits = 0 ) - : dim_(d) - , num_clusters_(k) - , max_degree_(max_degree) - , ef_construction_(ef_construction) - , ef_search_(ef_search) - , graph_build_iterations_(graph_build_iterations) - , seed_(seed) { - validate_configuration(num_threads); - // Cosine belongs to the indexes, which normalize vectors; the assigner's exact - // distances are raw L2 or inner product. - validate_metric_type(metric_type); - num_workers_ = static_cast(resolve_num_threads(num_threads)); - - graph_ = std::make_unique>( - num_clusters_, - dim_, - max_degree_, - metric_type, - RotatorType::FhtKacRotator, - quantization_bits, - seed_ - ); - graph_->set_ef(ef_search_); - - scratch_.reserve(num_workers_); - for (uint32_t thread = 0; thread < num_workers_; ++thread) { - scratch_.emplace_back( - std::make_unique( - graph_->padded_dim(), max_degree_, ef_search_, 1 - ) - ); - } - } + : assigner_( + d, + k, + {max_degree, + ef_construction, + ef_search, + graph_build_iterations, + num_threads, + seed, + metric_type, + quantization_bits}, + "QGKMeans" + ) {} // Optional n-element cache: fill it on the first call, then reuse it only // for the same input vectors and this assigner. A null pointer disables it. @@ -194,316 +112,18 @@ class QGAssigner { float* query_sums = nullptr, bool sums_ready = false ) { - detail::QuerySumCache cache(query_sums, sums_ready); - assign_with_cache(centroids, x, n, assignments, distances, cache); + clustering::detail::QuerySumCache cache(query_sums, sums_ready); + assigner_.assign_with_cache(centroids, x, n, assignments, distances, cache); } - void clear_hints() { previous_assignments_.clear(); } + void clear_hints() { assigner_.clear_hints(); } private: - void rebuild_centroid_graph(const float* centroids) { - if (builder_) { - builder_->reset(centroids); - } else { - // Centroid graphs have much less work than the training-vector batch. - // Amortize their short phases without reducing assignment parallelism. - constexpr size_t kMinVerticesPerBuildThread = 128; - const size_t build_threads = std::min( - num_workers_, - std::max(1, num_clusters_ / kMinVerticesPerBuildThread) - ); - builder_ = std::make_unique( - *graph_, - ef_construction_, - centroids, - build_threads, - symqg::QGInitialization::PiPNN, - seed_, - true - ); - } - if (graph_build_iterations_ == 1) { - builder_->build(); - } else { - builder_->build(graph_build_iterations_); - } - } - - void assign_with_cache( - const float* centroids, - const float* x, - size_t n, - PID* assignments, - float* distances, - detail::QuerySumCache& query_sums - ) { - if (centroids == nullptr || x == nullptr || assignments == nullptr || - distances == nullptr) { - throw std::invalid_argument( - "QGAssigner input and output pointers must not be null" - ); - } - - if (n > static_cast(std::numeric_limits::max()) / dim_) { - throw std::invalid_argument("QGAssigner input dimensions overflow ptrdiff_t"); - } - - rebuild_centroid_graph(centroids); - - // Stable grouping changes only the order of independent full searches. - std::vector query_order; - if (previous_assignments_.size() == n && - n <= std::numeric_limits::max()) { - query_order.resize(n); - std::vector offsets(num_clusters_ + 1, 0); - for (PID cluster_id : previous_assignments_) { - ++offsets[cluster_id + 1]; - } - std::partial_sum(offsets.begin(), offsets.end(), offsets.begin()); - for (size_t point = 0; point < n; ++point) { - query_order[offsets[previous_assignments_[point]]++] = - static_cast(point); - } - } - search_points( - centroids, - x, - n, - assignments, - distances, - query_order, - previous_assignments_.size() == n ? previous_assignments_.data() : nullptr, - query_sums, - scratch_ - ); - - previous_assignments_.assign(assignments, assignments + n); - query_sums.complete(); - } - - // Requires a graph built from centroids. Uses no hints or query-sum cache - // and allocates its own scratch, so concurrent calls only read the graph. - void search_built_graph( - const float* centroids, const float* x, size_t n, PID* assignments, float* distances - ) const { - std::vector> scratch; - scratch.reserve(num_workers_); - for (uint32_t thread = 0; thread < num_workers_; ++thread) { - scratch.emplace_back( - std::make_unique( - graph_->padded_dim(), max_degree_, ef_search_, 1 - ) - ); - } - const detail::QuerySumCache query_sums(nullptr, false); - search_points( - centroids, x, n, assignments, distances, {}, nullptr, query_sums, scratch - ); - } - - // Searches each point independently. A non-empty query_order only changes - // scheduling; hints, if given, hold one centroid ID per point. - void search_points( - const float* centroids, - const float* x, - size_t n, - PID* assignments, - float* distances, - const std::vector& query_order, - const PID* hints, - const detail::QuerySumCache& query_sums, - const std::vector>& scratch - ) const { - const auto distance_func = graph_->metric_type() == METRIC_IP - ? dot_product_dis - : euclidean_sqr; - index_detail::ParallelException failure; -#pragma omp parallel for num_threads(num_workers_) schedule(dynamic, 64) - for (std::ptrdiff_t index = 0; index < static_cast(n); ++index) { - const size_t i = query_order.empty() ? static_cast(index) - : query_order[static_cast(index)]; - const int thread_id = omp_get_thread_num(); - if (failure.failed()) { - continue; - } - try { - auto& worker_scratch = *scratch[static_cast(thread_id)]; - // Keep visited storage with the worker, as in QuantizedGraph::search. - thread_local VisitedSet visited; - thread_local size_t visited_size = 0; - thread_local size_t visited_capacity = 0; - const size_t capacity = std::min( - static_cast(ef_search_) * ef_search_, num_clusters_ / 10 - ); - if (visited_size != num_clusters_ || visited_capacity != capacity) { - visited.initialize(num_clusters_, capacity); - visited_size = num_clusters_; - visited_capacity = capacity; - } - const PID hint = hints == nullptr ? kPidMax : hints[i]; - symqg::detail::search_with_workspace( - *graph_, - x + i * dim_, - 1, - assignments + i, - distances + i, - worker_scratch.view(visited), - hint, - query_sums.cached(i) - ); - query_sums.store(i, worker_scratch.batch_query.g_k1xsumq()); - if (graph_->is_quantized()) { - // Keep objectives and returned distances relative to the original - // centroids; graph search scores are quantized estimates. - distances[i] = distance_func( - x + i * dim_, centroids + assignments[i] * dim_, dim_ - ); - } - } catch (...) { failure.capture(); } - } - - failure.rethrow(); - } - - void validate_configuration(uint32_t num_threads) const { - if (num_threads > static_cast(std::numeric_limits::max())) { - throw std::invalid_argument("QGAssigner num_threads must fit in an OpenMP int"); - } - if (dim_ < 64 || dim_ > rotator_impl::FhtKacRotator::kMaxDim) { - throw std::invalid_argument( - "QGKMeans currently requires dimensions in the range [64, 65536]" - ); - } - if (max_degree_ == 0 || max_degree_ % fastscan::kBatchSize != 0) { - throw std::invalid_argument( - "QGKMeans max_degree must be a positive multiple of 32" - ); - } - if (num_clusters_ <= max_degree_) { - throw std::invalid_argument("QGKMeans requires more centroids than max_degree"); - } - if (ef_construction_ == 0 || ef_search_ == 0) { - throw std::invalid_argument( - "QGKMeans ef_construction and ef_search must be positive" - ); - } - if (graph_build_iterations_ == 0) { - throw std::invalid_argument("QGKMeans graph_build_iterations must be positive"); - } - } - - size_t dim_; - size_t num_clusters_; - uint32_t max_degree_; - uint32_t ef_construction_; - uint32_t ef_search_; - uint32_t graph_build_iterations_; - uint32_t num_workers_ = 0; - uint32_t seed_; - std::unique_ptr> graph_; - std::unique_ptr builder_; - std::vector> scratch_; - std::vector previous_assignments_; + clustering::detail::QGAssigner assigner_; }; namespace detail { -// Graph over a model's centroids for stateless assignment, rebuilt when the -// centroids or graph settings differ from those it was built from. Copies share -// the immutable graph; each object has its own lock. -class CentroidGraphCache { - struct Entry { - std::vector centroids; - QGKMeansParameters parameters; - QGAssigner assigner; - - Entry(size_t d, size_t k, const float* source, const QGKMeansParameters& cp) - : centroids(source, source + k * d) - , parameters(cp) - , assigner( - d, - k, - cp.max_degree, - cp.ef_construction, - cp.ef_search, - cp.graph_build_iterations, - cp.num_threads, - cp.seed, - cp.spherical ? METRIC_IP : METRIC_L2, - qg_quantization_bits(cp) - ) { - // The builder borrows this copy, which lives as long as the graph. - assigner.rebuild_centroid_graph(centroids.data()); - } - - [[nodiscard]] bool matches( - size_t d, size_t k, const float* source, const QGKMeansParameters& cp - ) const { - const auto& p = parameters; - return centroids.size() == k * d && - std::equal(centroids.begin(), centroids.end(), source) && - p.spherical == cp.spherical && p.seed == cp.seed && - p.max_degree == cp.max_degree && - p.ef_construction == cp.ef_construction && p.ef_search == cp.ef_search && - p.graph_build_iterations == cp.graph_build_iterations && - p.num_threads == cp.num_threads && p.nbits == cp.nbits; - } - }; - - mutable std::mutex mutex_; - mutable std::shared_ptr entry_; - - [[nodiscard]] std::shared_ptr snapshot() const { - const std::lock_guard lock(mutex_); - return entry_; - } - - public: - CentroidGraphCache() = default; - - CentroidGraphCache(const CentroidGraphCache& other) : entry_(other.snapshot()) {} - - CentroidGraphCache& operator=(const CentroidGraphCache& other) { - if (this != &other) { - auto entry = other.snapshot(); - const std::lock_guard lock(mutex_); - entry_ = std::move(entry); - } - return *this; - } - - ~CentroidGraphCache() = default; - - void clear() { - const std::lock_guard lock(mutex_); - entry_.reset(); - } - - // Requires k * d validated centroid coordinates. - void assign( - size_t d, - size_t k, - const float* centroids, - const QGKMeansParameters& cp, - const float* x, - size_t n, - PID* assignments, - float* distances - ) const { - std::shared_ptr entry; - { - const std::lock_guard lock(mutex_); - if (!entry_ || !entry_->matches(d, k, centroids, cp)) { - entry_ = std::make_shared(d, k, centroids, cp); - } - entry = entry_; - } - entry->assigner.search_built_graph( - entry->centroids.data(), x, n, assignments, distances - ); - } -}; - // Retain graph-specific state for one synchronous training call. class QGAssignment { size_t dim_; @@ -512,8 +132,8 @@ class QGAssignment { uint32_t num_workers_; MetricType metric_type_; bool quantized_; - QGAssigner assigner_; - QuerySumCache query_sums_; + clustering::detail::QGAssigner assigner_; + clustering::detail::QuerySumCache query_sums_; public: static constexpr const char* kName = "QGKMeans"; @@ -538,19 +158,8 @@ class QGAssignment { , num_workers_(num_workers) , metric_type_(cp.spherical ? METRIC_IP : METRIC_L2) , quantized_(cp.nbits != 32) - , assigner_( - d, - k, - cp.max_degree, - cp.ef_construction, - cp.ef_search, - cp.graph_build_iterations, - cp.num_threads, - cp.seed, - metric_type_, - qg_quantization_bits(cp) - ) - , query_sums_(assigner_.graph_->padded_dim(), cp) {} + , assigner_(d, k, graph_settings(cp), kName) + , query_sums_(assigner_.padded_dim(), reuses_query_sums(cp)) {} void assign( const float* centroids, PID* assignments, float* distances, bool final = false @@ -591,7 +200,7 @@ class QGAssignment { // Kept by the model after training for stateless assignment. struct ModelState { bool trained = false; - CentroidGraphCache graph; + clustering::detail::CentroidGraphCache graph; }; void store_model_state(ModelState& state) const { @@ -616,7 +225,9 @@ class QGAssignment { PID* assignments, float* distances ) { - state.graph.assign(d, k, centroids, cp, x, n, assignments, distances); + state.graph.assign( + d, k, centroids, graph_settings(cp), kName, x, n, assignments, distances + ); } }; diff --git a/python_bindings/__init__.py b/python_bindings/__init__.py index 5364678c..738de3be 100644 --- a/python_bindings/__init__.py +++ b/python_bindings/__init__.py @@ -9,9 +9,11 @@ HnswIndex, IvfIndex, KMeansIterationStats, + QGEMeansParameters, QGKMeansParameters, RaBitQKMeansParameters, SymqgIndex, + _QGEMeans, _QGKMeans, _RaBitQKMeans, ) @@ -21,7 +23,7 @@ class _KMeans: - """Shared result handling for the two clustering methods.""" + """Shared result handling for the clustering methods.""" def __init__(self, d, k, **kwargs): self.d = int(d) @@ -203,6 +205,137 @@ class QGKMeans(_KMeans): _implementation_type = _QGKMeans +class QGEMeans(_KMeans): + """Cluster vectors with mini-batch e-means and SymphonyQG graph assignment. + + Parameters + ---------- + d : int + Original vector dimension, from 64 through 65536. + k : int + Number of centroids; greater than max_degree and no more than the + number of training vectors. + niter : int, optional + Number of clustering iterations, each one pass over the training + vectors. Default is 8. + batch_size : int, optional + Vectors per mini-batch, capped at the number of training vectors; 0 + selects the e-means batch-size law. Default is 0. + verbose : bool, optional + Print training progress when True. Default is False. + seed : int, optional + Random seed. Default is 42. + num_threads : int, optional + Worker count; 0 selects the available CPU count, + capped by OMP_NUM_THREADS. Default is 0. + final_assignment : {'approximate', 'exact'}, optional + 'approximate' assigns through a centroid graph over the final + centroids; 'exact' uses exhaustive assignment against them. Default is + 'approximate'. + max_degree : int, optional + Centroid graph degree; a positive multiple of 32. Default is 32. + ef_construction : int, optional + Positive centroid-graph construction search breadth. Default is 240. + ef_search : int, optional + Centroid-graph assignment search breadth, at least 2. Default is 16. + graph_build_iterations : int, optional + Positive number of graph-building passes after initialization. Default + is 1. + + Notes + ----- + Each iteration visits the vectors in a seeded random order, in mini-batches. + Before every mini-batch a SymphonyQG graph is rebuilt over the current + centroids and searched for each vector's nearest centroid; centroids then + take the e-means mass-weighted step, and centroids that cost little to remove + periodically split the centroids with the longest axes. The step size follows the + e-means law and a cosine schedule, and the last iteration's means become the + final centroids. train then assigns all vectors to them. + + Training results are None until the first successful train call. Set cp + fields before training to customize subsequent runs. A failed train + preserves previous results. + + Examples + -------- + >>> import numpy as np + >>> from rabitqlib import QGEMeans + >>> x = np.random.default_rng(42).normal(size=(256, 64)).astype(np.float32) + >>> model = QGEMeans(64, 40, niter=2, ef_construction=40, num_threads=1) + >>> objective = model.train(x) + >>> model.centroids.shape + (40, 64) + """ + + _parameters_type = QGEMeansParameters + _implementation_type = _QGEMeans + + def train(self, x): + """Train centroids and retain the final assignments. + + Parameters + ---------- + x : array_like of float, shape (n, d) + Vectors in the original, unpadded coordinates, with n >= k. + Converted to contiguous float32; a copy may be made. + + Returns + ------- + objective : float + Sum of the mini-batch assignment distances in the last iteration, each + measured before that batch's update. This can differ from + final_obj, which uses the returned assignments and final centroids. + + Notes + ----- + A failed fit preserves the last successful results. Returned arrays are + copies. + """ + return super().train(x) + + def assign(self, x): + """Assign vectors to the trained centroids. + + Parameters + ---------- + x : array_like of float, shape (m, d) + Vectors in the original, unpadded coordinates, with finite + coordinates in the range accepted by train; m may be 0. Converted to + contiguous float32; a copy may be made. + + Returns + ------- + assignments : ndarray of uint32, shape (m,) + Centroid IDs. + distances : ndarray of float32, shape (m,) + Distances to the assigned centroids, as in the distances property. + + Raises + ------ + RuntimeError + If no train call has succeeded. + + Notes + ----- + Uses final_assignment and the other parameters of the last successful + train call, so each vector's result is independent of the other vectors + in x. Approximate assignment builds a centroid graph on first use and + reuses it in later calls. For the training vectors, the result + reproduces assignments and distances in both modes. + """ + return super().assign(x) + + @property + def obj(self): + """Per-iteration sums of mini-batch assignment distances, float64 array of shape (niter,), or None before training.""" + return super().obj + + @property + def iteration_stats(self): + """Per-iteration statistics, or None before training: obj sums the mini-batch assignment distances, shift is the squared centroid displacement over the iteration and nsplit counts revived centroids.""" + return super().iteration_stats + + class RaBitQKMeans(_KMeans): """Cluster vectors using flat RaBitQ assignment. @@ -270,6 +403,8 @@ class RaBitQKMeans(_KMeans): "HnswIndex", "IvfIndex", "KMeansIterationStats", + "QGEMeans", + "QGEMeansParameters", "QGKMeans", "QGKMeansParameters", "RaBitQKMeans", diff --git a/python_bindings/__init__.pyi b/python_bindings/__init__.pyi index 4675a026..060ee604 100644 --- a/python_bindings/__init__.pyi +++ b/python_bindings/__init__.pyi @@ -17,6 +17,8 @@ __all__ = [ "HnswIndex", "IvfIndex", "KMeansIterationStats", + "QGEMeans", + "QGEMeansParameters", "QGKMeans", "QGKMeansParameters", "RaBitQKMeans", @@ -988,6 +990,290 @@ class SymqgIndex: An index ready for search; add raises because it already has a graph. """ +class QGEMeans: + """Cluster vectors with mini-batch e-means and SymphonyQG graph assignment. + + Parameters + ---------- + d : int + Original vector dimension, from 64 through 65536. + k : int + Number of centroids; greater than max_degree and no more than the + number of training vectors. + niter : int, optional + Number of clustering iterations, each one pass over the training + vectors. Default is 8. + batch_size : int, optional + Vectors per mini-batch, capped at the number of training vectors; 0 + selects the e-means batch-size law. Default is 0. + verbose : bool, optional + Print training progress when True. Default is False. + seed : int, optional + Random seed. Default is 42. + num_threads : int, optional + Worker count; 0 selects the available CPU count, + capped by OMP_NUM_THREADS. Default is 0. + final_assignment : {'approximate', 'exact'}, optional + 'approximate' assigns through a centroid graph over the final + centroids; 'exact' uses exhaustive assignment against them. Default is + 'approximate'. + max_degree : int, optional + Centroid graph degree; a positive multiple of 32. Default is 32. + ef_construction : int, optional + Positive centroid-graph construction search breadth. Default is 240. + ef_search : int, optional + Centroid-graph assignment search breadth, at least 2. Default is 16. + graph_build_iterations : int, optional + Positive number of graph-building passes after initialization. Default + is 1. + + Notes + ----- + Each iteration visits the vectors in a seeded random order, in mini-batches. + Before every mini-batch a SymphonyQG graph is rebuilt over the current + centroids and searched for each vector's nearest centroid; centroids then + take the e-means mass-weighted step, and centroids that cost little to remove + periodically split the centroids with the longest axes. The step size follows the + e-means law and a cosine schedule, and the last iteration's means become the + final centroids. train then assigns all vectors to them. + + Training results are None until the first successful train call. Set cp + fields before training to customize subsequent runs. A failed train + preserves previous results. + + Examples + -------- + >>> import numpy as np + >>> from rabitqlib import QGEMeans + >>> x = np.random.default_rng(42).normal(size=(256, 64)).astype(np.float32) + >>> model = QGEMeans(64, 40, niter=2, ef_construction=40, num_threads=1) + >>> objective = model.train(x) + >>> model.centroids.shape + (40, 64) + """ + + d: int + k: int + cp: QGEMeansParameters + + def __init__( + self, + d: SupportsIndex, + k: SupportsIndex, + *, + niter: SupportsIndex = 8, + batch_size: SupportsIndex = 0, + verbose: bool | np.bool_ = False, + seed: SupportsIndex = 42, + num_threads: SupportsIndex = 0, + final_assignment: _FinalAssignment = "approximate", + max_degree: SupportsIndex = 32, + ef_construction: SupportsIndex = 240, + ef_search: SupportsIndex = 16, + graph_build_iterations: SupportsIndex = 1, + ) -> None: + """Cluster vectors with mini-batch e-means and SymphonyQG graph assignment. + + Parameters + ---------- + d : int + Original vector dimension, from 64 through 65536. + k : int + Number of centroids; greater than max_degree and no more than the + number of training vectors. + niter : int, optional + Number of clustering iterations, each one pass over the training + vectors. Default is 8. + batch_size : int, optional + Vectors per mini-batch, capped at the number of training vectors; 0 + selects the e-means batch-size law. Default is 0. + verbose : bool, optional + Print training progress when True. Default is False. + seed : int, optional + Random seed. Default is 42. + num_threads : int, optional + Worker count; 0 selects the available CPU count, + capped by OMP_NUM_THREADS. Default is 0. + final_assignment : {'approximate', 'exact'}, optional + 'approximate' assigns through a centroid graph over the final + centroids; 'exact' uses exhaustive assignment against them. Default is + 'approximate'. + max_degree : int, optional + Centroid graph degree; a positive multiple of 32. Default is 32. + ef_construction : int, optional + Positive centroid-graph construction search breadth. Default is 240. + ef_search : int, optional + Centroid-graph assignment search breadth, at least 2. Default is 16. + graph_build_iterations : int, optional + Positive number of graph-building passes after initialization. Default + is 1. + + Notes + ----- + Each iteration visits the vectors in a seeded random order, in mini-batches. + Before every mini-batch a SymphonyQG graph is rebuilt over the current + centroids and searched for each vector's nearest centroid; centroids then + take the e-means mass-weighted step, and centroids that cost little to remove + periodically split the centroids with the longest axes. The step size follows the + e-means law and a cosine schedule, and the last iteration's means become the + final centroids. train then assigns all vectors to them. + + Training results are None until the first successful train call. Set cp + fields before training to customize subsequent runs. A failed train + preserves previous results. + + Examples + -------- + >>> import numpy as np + >>> from rabitqlib import QGEMeans + >>> x = np.random.default_rng(42).normal(size=(256, 64)).astype(np.float32) + >>> model = QGEMeans(64, 40, niter=2, ef_construction=40, num_threads=1) + >>> objective = model.train(x) + >>> model.centroids.shape + (40, 64) + """ + + def train(self, x: npt.ArrayLike) -> float: + """Train centroids and retain the final assignments. + + Parameters + ---------- + x : array_like of float, shape (n, d) + Vectors in the original, unpadded coordinates, with n >= k. + Converted to contiguous float32; a copy may be made. + + Returns + ------- + objective : float + Sum of the mini-batch assignment distances in the last iteration, each + measured before that batch's update. This can differ from + final_obj, which uses the returned assignments and final centroids. + + Notes + ----- + A failed fit preserves the last successful results. Returned arrays are + copies. + """ + + def assign( + self, x: npt.ArrayLike + ) -> tuple[npt.NDArray[np.uint32], npt.NDArray[np.float32]]: + """Assign vectors to the trained centroids. + + Parameters + ---------- + x : array_like of float, shape (m, d) + Vectors in the original, unpadded coordinates, with finite + coordinates in the range accepted by train; m may be 0. Converted to + contiguous float32; a copy may be made. + + Returns + ------- + assignments : ndarray of uint32, shape (m,) + Centroid IDs. + distances : ndarray of float32, shape (m,) + Distances to the assigned centroids, as in the distances property. + + Raises + ------ + RuntimeError + If no train call has succeeded. + + Notes + ----- + Uses final_assignment and the other parameters of the last successful + train call, so each vector's result is independent of the other vectors + in x. Approximate assignment builds a centroid graph on first use and + reuses it in later calls. For the training vectors, the result + reproduces assignments and distances in both modes. + """ + + @property + def centroids(self) -> npt.NDArray[np.float32] | None: + """Final centroids, float32 array of shape (k, d), or None before training.""" + + @property + def assignments(self) -> npt.NDArray[np.uint32] | None: + """Final centroid IDs, uint32 array of shape (n,), or None before training.""" + + @property + def distances(self) -> npt.NDArray[np.float32] | None: + """Final assignment distances for all n vectors, float32 array of shape (n,), or None before training.""" + + @property + def obj(self) -> npt.NDArray[np.float64] | None: + """Per-iteration sums of mini-batch assignment distances, float64 array of shape (niter,), or None before training.""" + + @property + def final_obj(self) -> float | None: + """Objective for the final assignments of all n vectors, or None before training.""" + + @property + def iteration_stats(self) -> list[KMeansIterationStats] | None: + """Per-iteration statistics, or None before training: obj sums the mini-batch assignment distances, shift is the squared centroid displacement over the iteration and nsplit counts revived centroids.""" + +class QGEMeansParameters: + """Mutable training settings for QGEMeans. + + Notes + ----- + Create with no arguments; set attributes directly or use keyword arguments + on QGEMeans. + """ + + @property + def niter(self) -> int: + """Positive number of passes over the training vectors. Default is 8.""" + @niter.setter + def niter(self, value: SupportsIndex) -> None: ... + @property + def batch_size(self) -> int: + """Vectors per mini-batch, capped at the number of training vectors; 0 selects the e-means batch-size law. Default is 0.""" + @batch_size.setter + def batch_size(self, value: SupportsIndex) -> None: ... + @property + def verbose(self) -> bool: + """Print training progress when True. Default is False.""" + @verbose.setter + def verbose(self, value: bool | np.bool_) -> None: ... + @property + def seed(self) -> int: + """Random seed. Default is 42.""" + @seed.setter + def seed(self, value: SupportsIndex) -> None: ... + @property + def num_threads(self) -> int: + """Worker count; 0 selects the available CPU count, capped by OMP_NUM_THREADS. Default is 0.""" + @num_threads.setter + def num_threads(self, value: SupportsIndex) -> None: ... + @property + def final_assignment(self) -> _FinalAssignment: + """'approximate' assigns through a centroid graph over the final centroids; 'exact' uses exhaustive assignment against them. Default is 'approximate'.""" + @final_assignment.setter + def final_assignment(self, value: _FinalAssignment) -> None: ... + @property + def max_degree(self) -> int: + """Centroid graph degree; a positive multiple of 32. Default is 32.""" + @max_degree.setter + def max_degree(self, value: SupportsIndex) -> None: ... + @property + def ef_construction(self) -> int: + """Positive centroid-graph construction search breadth. Default is 240.""" + @ef_construction.setter + def ef_construction(self, value: SupportsIndex) -> None: ... + @property + def ef_search(self) -> int: + """Centroid-graph assignment search breadth, at least 2. Default is 16.""" + @ef_search.setter + def ef_search(self, value: SupportsIndex) -> None: ... + @property + def graph_build_iterations(self) -> int: + """Positive number of graph-building passes after initialization. Default is 1.""" + @graph_build_iterations.setter + def graph_build_iterations(self, value: SupportsIndex) -> None: ... + def __init__(self) -> None: + """Create parameters with their documented defaults.""" + class QGKMeans: """Cluster vectors using SymphonyQG graph assignment. diff --git a/python_bindings/kmeans_bindings.cpp b/python_bindings/kmeans_bindings.cpp index 7e7960b6..abae37aa 100644 --- a/python_bindings/kmeans_bindings.cpp +++ b/python_bindings/kmeans_bindings.cpp @@ -12,6 +12,7 @@ #include #include "bindings_common.hpp" +#include "rabitqlib/clustering/qgemeans.hpp" #include "rabitqlib/clustering/qgkmeans.hpp" #include "rabitqlib/clustering/rabitqkmeans.hpp" #include "rabitqlib/index/types.hpp" @@ -197,6 +198,8 @@ void bind_clustering(py::module_& m, const char* native_name, const char* public void register_kmeans(py::module_& m) { using namespace rabitqlib::python_bindings; using rabitqlib::clustering::KMeansIterationStats; + using rabitqlib::qgemeans::QGEMeans; + using rabitqlib::qgemeans::QGEMeansParameters; using rabitqlib::qgkmeans::QGKMeans; using rabitqlib::qgkmeans::QGKMeansParameters; using rabitqlib::rabitqkmeans::RaBitQKMeans; @@ -248,6 +251,90 @@ on RaBitQKMeans.)doc" ); bind_training_parameters(flat_parameters); + py::class_( + m, "QGEMeansParameters", R"doc(Mutable training settings for QGEMeans. + +Notes +----- +Create with no arguments; set attributes directly or use keyword arguments +on QGEMeans.)doc" + ) + .def(py::init<>(), "Create parameters with their documented defaults.") + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) + .def_readwrite( + "niter", + &QGEMeansParameters::niter, + R"doc(Positive number of passes over the training vectors. Default is 8.)doc" + ) + .def_readwrite( + "batch_size", + &QGEMeansParameters::batch_size, + R"doc(Vectors per mini-batch, capped at the number of training vectors; 0 selects the e-means batch-size law. Default is 0.)doc" + ) + .def_readwrite( + "verbose", + &QGEMeansParameters::verbose, + R"doc(Print training progress when True. Default is False.)doc" + ) + .def_readwrite( + "seed", &QGEMeansParameters::seed, R"doc(Random seed. Default is 42.)doc" + ) + .def_readwrite( + "num_threads", + &QGEMeansParameters::num_threads, + R"doc(Worker count; 0 selects the available CPU count, capped by OMP_NUM_THREADS. Default is 0.)doc" + ) + .def_property( + "final_assignment", + [](const QGEMeansParameters& parameters) { + return std::string( + parameters.final_assignment == + rabitqlib::clustering::FinalAssignmentMode::Exact + ? "exact" + : "approximate" + ); + }, + [](QGEMeansParameters& parameters, const std::string& value) { + if (value == "approximate") { + parameters.final_assignment = + rabitqlib::clustering::FinalAssignmentMode::Approximate; + } else if (value == "exact") { + parameters.final_assignment = + rabitqlib::clustering::FinalAssignmentMode::Exact; + } else { + throw std::invalid_argument( + "final_assignment must be 'approximate' or 'exact'" + ); + } + }, + R"doc('approximate' assigns through a centroid graph over the final centroids; 'exact' uses exhaustive assignment against them. Default is 'approximate'.)doc" + ) + .def_readwrite( + "max_degree", + &QGEMeansParameters::max_degree, + R"doc(Centroid graph degree; a positive multiple of 32. Default is 32.)doc" + ) + .def_readwrite( + "ef_construction", + &QGEMeansParameters::ef_construction, + R"doc(Positive centroid-graph construction search breadth. Default is 240.)doc" + ) + .def_readwrite( + "ef_search", + &QGEMeansParameters::ef_search, + R"doc(Centroid-graph assignment search breadth, at least 2. Default is 16.)doc" + ) + .def_readwrite( + "graph_build_iterations", + &QGEMeansParameters::graph_build_iterations, + R"doc(Positive number of graph-building passes after initialization. Default is 1.)doc" + ); + py::class_( m, "KMeansIterationStats", @@ -281,6 +368,7 @@ on RaBitQKMeans.)doc" ); bind_clustering(m, "_QGKMeans", "QGKMeans"); + bind_clustering(m, "_QGEMeans", "QGEMeans"); bind_clustering( m, "_RaBitQKMeans", "RaBitQKMeans" ); diff --git a/sample/cpp/CMakeLists.txt b/sample/cpp/CMakeLists.txt index 416d16dd..b3f1a64f 100644 --- a/sample/cpp/CMakeLists.txt +++ b/sample/cpp/CMakeLists.txt @@ -21,6 +21,7 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/bin) add_executable(symqg_indexing symqg_indexing.cpp) add_executable(symqg_querying symqg_querying.cpp) add_executable(qgkmeans qgkmeans.cpp) +add_executable(qgemeans qgemeans.cpp) add_executable(rabitqkmeans rabitqkmeans.cpp) add_executable(ivf_rabitq_indexing ivf_rabitq_indexing.cpp) @@ -33,6 +34,7 @@ foreach(RABITQ_SAMPLE_TARGET symqg_indexing symqg_querying qgkmeans + qgemeans rabitqkmeans ivf_rabitq_indexing ivf_rabitq_querying diff --git a/sample/cpp/kmeans_example.hpp b/sample/cpp/kmeans_example.hpp index a80ee269..63aeafbc 100644 --- a/sample/cpp/kmeans_example.hpp +++ b/sample/cpp/kmeans_example.hpp @@ -8,6 +8,8 @@ #include #include #include +#include +#include #include "rabitqlib/core/detail/eigen.hpp" #include "rabitqlib/utils/io.hpp" @@ -31,13 +33,22 @@ void write_vecs(const char* path, const T* data, size_t rows, size_t cols) { output.close(); } +// True for parameter types with a spherical field, which take an l2|ip argument. +template +struct HasSpherical : std::false_type {}; +template +struct HasSpherical< + Parameters, + std::void_t().spherical)>> : std::true_type {}; + template int cluster_file(int argc, char** argv) { - if (argc != 5 && argc != 6) { - std::cerr - << "Usage: " << argv[0] - << " [l2|ip]\n" - << "Without arguments, run a synthetic clustering demo.\n"; + constexpr bool kMetric = HasSpherical::value; + if (argc != 5 && !(kMetric && argc == 6)) { + std::cerr << "Usage: " << argv[0] + << " " + << (kMetric ? " [l2|ip]" : "") << '\n' + << "Without arguments, run a synthetic clustering demo.\n"; return 1; } const std::string count(argv[2]); @@ -58,7 +69,9 @@ int cluster_file(int argc, char** argv) { rabitqlib::RowMajorArray data; rabitqlib::load_vecs(argv[1], data); Parameters parameters; - parameters.spherical = metric == "ip"; + if constexpr (kMetric) { + parameters.spherical = metric == "ip"; + } parameters.final_assignment = decltype(parameters.final_assignment)::Exact; parameters.verbose = true; KMeans clustering(data.cols(), num_clusters, parameters); diff --git a/sample/cpp/qgemeans.cpp b/sample/cpp/qgemeans.cpp new file mode 100644 index 00000000..daaa9d67 --- /dev/null +++ b/sample/cpp/qgemeans.cpp @@ -0,0 +1,57 @@ +#include "rabitqlib/clustering/qgemeans.hpp" + +#include +#include +#include +#include +#include + +#include "kmeans_example.hpp" + +namespace { + +int run_demo() { + constexpr size_t kNumClusters = 33; + constexpr size_t kPointsPerCluster = 40; + constexpr size_t kDimension = 64; + constexpr size_t kNumPoints = kNumClusters * kPointsPerCluster; + + std::mt19937 rng(42); + std::normal_distribution noise(0.0F, 0.05F); + std::vector data(kNumPoints * kDimension); + for (size_t point = 0; point < kNumPoints; ++point) { + const float center = static_cast(point / kPointsPerCluster); + for (size_t dim = 0; dim < kDimension; ++dim) { + data[point * kDimension + dim] = center + noise(rng); + } + } + + rabitqlib::qgemeans::QGEMeansParameters parameters; + parameters.niter = 8; + parameters.ef_construction = 64; + parameters.ef_search = 32; + parameters.verbose = true; + + rabitqlib::qgemeans::QGEMeans clustering(kDimension, kNumClusters, parameters); + clustering.train(kNumPoints, data.data()); + + std::cout << "Completed " << clustering.iteration_stats.size() + << " iterations; final objective=" << clustering.final_obj << '\n'; + return 0; +} + +} // namespace + +int main(int argc, char** argv) { + try { + if (argc == 1) { + return run_demo(); + } + return kmeans_example::cluster_file< + rabitqlib::qgemeans::QGEMeans, + rabitqlib::qgemeans::QGEMeansParameters>(argc, argv); + } catch (const std::exception& error) { + std::cerr << "Error: " << error.what() << '\n'; + return 1; + } +} diff --git a/tests/README.md b/tests/README.md index 02602530..3ded4624 100644 --- a/tests/README.md +++ b/tests/README.md @@ -178,7 +178,7 @@ Locally, build both the examples and this checker first; missing executables oth ## Installed CMake package test After building the library, verify that another project can consume its installed -headers and library. The consumer trains QGKMeans and RaBitQKMeans and checks +headers and library. The consumer trains QGKMeans, QGEMeans and RaBitQKMeans and checks final assignments, distances, and objective against a scalar L2 reference. Use an absolute path for ``: diff --git a/tests/consumer/main.cpp b/tests/consumer/main.cpp index 8758be51..db6e77a7 100644 --- a/tests/consumer/main.cpp +++ b/tests/consumer/main.cpp @@ -6,6 +6,7 @@ #include #include "rabitqlib/clustering/detail/kmeans.hpp" +#include "rabitqlib/clustering/qgemeans.hpp" #include "rabitqlib/clustering/qgkmeans.hpp" #include "rabitqlib/clustering/rabitqkmeans.hpp" #include "rabitqlib/core/metric.hpp" @@ -91,6 +92,18 @@ int main() { return 1; } + rabitqlib::qgemeans::QGEMeansParameters emeans_parameters; + emeans_parameters.niter = 2; + emeans_parameters.num_threads = 2; + emeans_parameters.ef_construction = 33; + emeans_parameters.ef_search = 33; + emeans_parameters.final_assignment = rabitqlib::clustering::FinalAssignmentMode::Exact; + rabitqlib::qgemeans::QGEMeans emeans(kDimension, 33, emeans_parameters); + if (!check_clustering(emeans, data)) { + std::cerr << "Installed QGEMeans returned invalid clustering results\n"; + return 1; + } + rabitqlib::rabitqkmeans::RaBitQKMeansParameters flat_parameters; flat_parameters.niter = 2; flat_parameters.num_threads = 2; diff --git a/tests/core_consumer/check_symbols.cmake b/tests/core_consumer/check_symbols.cmake index 8ce25310..108f84fa 100644 --- a/tests/core_consumer/check_symbols.cmake +++ b/tests/core_consumer/check_symbols.cmake @@ -8,7 +8,7 @@ foreach(binary IN ITEMS "${CORE}" "${CONSUMER}") message(FATAL_ERROR "OpenMP runtime symbol in disabled build: ${binary}") endif() # Check definitions AND unresolved references in the archive, plus the linked consumer. - if(symbols MATCHES "rabitqlib::(ivf|hnsw|symqg|qgkmeans|rabitqkmeans)::|hnswlib::") + if(symbols MATCHES "rabitqlib::(ivf|hnsw|symqg|qgemeans|qgkmeans|rabitqkmeans)::|hnswlib::") message(FATAL_ERROR "ANN symbols in ${binary}") endif() if(binary STREQUAL CORE OR COMPONENT STREQUAL "core") diff --git a/tests/python/test_editor_support.py b/tests/python/test_editor_support.py index c00f751e..51f0c8db 100644 --- a/tests/python/test_editor_support.py +++ b/tests/python/test_editor_support.py @@ -75,7 +75,10 @@ def test_editor_docs_match_runtime_help(): continue # Python wrappers inherit __init__(d, k, **kwargs); class help documents # the supported keyword parameters and the stub expands them for IDEs. - if name in ("QGKMeans", "RaBitQKMeans") and node.name == "__init__": + if ( + name in ("QGEMeans", "QGKMeans", "RaBitQKMeans") + and node.name == "__init__" + ): continue actual = getattr(runtime, node.name).__doc__ assert normalized(documentation) in normalized(actual), (name, node.name) @@ -131,7 +134,7 @@ def test_native_signature_names_and_defaults(name): assert actual == expected, (name, node.name) -@pytest.mark.parametrize("name", ["QGKMeans", "RaBitQKMeans"]) +@pytest.mark.parametrize("name", ["QGEMeans", "QGKMeans", "RaBitQKMeans"]) def test_clustering_keyword_defaults(name): cls = declarations()[name] init = next( @@ -191,12 +194,15 @@ def test_documented_search_result_types(kind): assert distances.dtype == np.float32 -@pytest.mark.parametrize("name", ["QGKMeans", "RaBitQKMeans"]) -def test_documented_training_result_types(name): +@pytest.mark.parametrize( + ("name", "iterations"), + [("QGEMeans", "niter"), ("QGKMeans", "niter"), ("RaBitQKMeans", "niter")], +) +def test_documented_training_result_types(name, iterations): import numpy as np data = np.random.default_rng(42).normal(size=(80, 64)).astype(np.float32) - model = getattr(rabitqlib, name)(64, 40, niter=2, num_threads=1) + model = getattr(rabitqlib, name)(64, 40, num_threads=1, **{iterations: 2}) assert isinstance(model.train(data), float) assert model.centroids.shape == (40, 64) assert model.centroids.dtype == np.float32 diff --git a/tests/python/test_qgemeans.py b/tests/python/test_qgemeans.py new file mode 100644 index 00000000..cdc994b3 --- /dev/null +++ b/tests/python/test_qgemeans.py @@ -0,0 +1,200 @@ +"""Tests for the QGEMeans Python API.""" + +import numpy as np +import pytest +from conftest import DIM +from rabitqlib import QGEMeans, QGEMeansParameters + +K = 33 + + +def qgemeans(**kwargs): + parameters = { + "niter": 3, + "num_threads": 1, + "ef_construction": K, + "ef_search": K, + } + parameters.update(kwargs) + return QGEMeans(DIM, K, **parameters) + + +def nearest(x, centroids): + distances = ((x[:, None, :].astype(np.float64) - centroids[None]) ** 2).sum(-1) + return distances.argmin(1), distances.min(1) + + +def test_parameters_use_index_names_and_defaults(): + cp = QGEMeansParameters() + assert cp.niter == 8 + assert cp.batch_size == 0 + assert not cp.verbose + assert cp.seed == 42 + assert cp.num_threads == 0 + assert cp.final_assignment == "approximate" + assert cp.max_degree == 32 + assert cp.ef_construction == 240 + assert cp.ef_search == 16 + assert cp.graph_build_iterations == 1 + for old in ("graph_degree", "ef_build", "epochs", "quantization_bits", "nbits"): + assert not hasattr(cp, old) + + +def test_constructor_sets_keyword_parameters(): + model = qgemeans(batch_size=64, seed=7, verbose=True, final_assignment="exact") + assert (model.d, model.k) == (DIM, K) + assert model.cp.batch_size == 64 + assert model.cp.seed == 7 + assert model.cp.verbose + assert model.cp.final_assignment == "exact" + assert model.centroids is None + assert model.obj is None + assert model.iteration_stats is None + + +@pytest.mark.parametrize("name", ["epochs", "graph_degree", "ef_build", "nbits"]) +def test_constructor_rejects_parameters_of_other_methods(name): + with pytest.raises( + AttributeError, + match=f"QGEMeans\\(\\) got an unexpected keyword argument '{name}'", + ): + QGEMeans(DIM, K, **{name: 1}) + + +def test_final_assignment_rejects_unknown_strings(): + with pytest.raises( + ValueError, match="final_assignment must be 'approximate' or 'exact'" + ): + qgemeans(final_assignment="symphonyqg") + + +def test_train_populates_outputs_per_iteration(base_data): + model = qgemeans() + objective = model.train(base_data) + + assert model.centroids.shape == (K, DIM) + assert model.centroids.dtype == np.float32 + assert model.assignments.shape == (base_data.shape[0],) + assert model.assignments.dtype == np.uint32 + assert model.distances.shape == (base_data.shape[0],) + assert model.obj.shape == (model.cp.niter,) + stats = model.iteration_stats + assert [s.iteration for s in stats] == [1, 2, 3] + assert objective == model.obj[-1] == stats[-1].obj + assert all(s.shift >= 0 for s in stats) + # Cost-based revival moves centroids that cost little to remove. + assert sum(s.nsplit for s in stats) > 0 + assert model.final_obj == pytest.approx( + float(model.distances.sum(dtype=np.float64)) + ) + + +def test_distances_are_exact_for_returned_assignments(base_data): + model = qgemeans() + model.train(base_data) + selected = model.centroids[model.assignments] + expected = ((base_data.astype(np.float64) - selected) ** 2).sum(1) + np.testing.assert_allclose(model.distances, expected, rtol=1e-4, atol=1e-4) + + +def test_exact_final_assignment_returns_the_nearest_centroid(base_data): + model = qgemeans(final_assignment="exact") + model.train(base_data) + ids, distances = nearest(base_data, model.centroids) + np.testing.assert_array_equal(model.assignments, ids) + np.testing.assert_allclose(model.distances, distances, rtol=1e-4, atol=1e-4) + + +def test_final_assignment_does_not_change_trained_centroids(base_data): + approximate = qgemeans() + approximate.train(base_data) + exact = qgemeans(final_assignment="exact") + exact.train(base_data) + np.testing.assert_array_equal(approximate.centroids, exact.centroids) + np.testing.assert_array_equal(approximate.obj, exact.obj) + + +@pytest.mark.parametrize("mode", ["approximate", "exact"]) +def test_assign_reproduces_training_assignments(base_data, mode): + model = qgemeans(final_assignment=mode) + model.train(base_data) + ids, distances = model.assign(base_data) + np.testing.assert_array_equal(ids, model.assignments) + np.testing.assert_array_equal(distances, model.distances) + empty_ids, empty_distances = model.assign(np.empty((0, DIM), dtype=np.float32)) + assert empty_ids.shape == empty_distances.shape == (0,) + + +def test_assign_before_training_raises(base_data): + with pytest.raises(RuntimeError, match="QGEMeans has not been trained"): + qgemeans().assign(base_data) + + +def test_training_is_deterministic_across_thread_counts(base_data): + single = qgemeans(num_threads=1) + single.train(base_data) + multi = qgemeans(num_threads=4) + multi.train(base_data) + np.testing.assert_array_equal(single.centroids, multi.centroids) + np.testing.assert_array_equal(single.assignments, multi.assignments) + np.testing.assert_array_equal(single.obj, multi.obj) + + +def test_parameters_can_be_changed_through_cp(base_data): + model = qgemeans() + model.cp.niter = 1 + model.cp.batch_size = 50 + model.train(base_data) + assert model.obj.shape == (1,) + + +@pytest.mark.parametrize( + ("parameters", "message"), + [ + ({"niter": 0}, "QGEMeans d, k, and niter must be positive"), + ({"max_degree": 48}, "QGEMeans max_degree must be a positive multiple of 32"), + ( + {"ef_construction": 0}, + "QGEMeans ef_construction and ef_search must be positive", + ), + ({"ef_search": 1}, "QGEMeans ef_search must be at least 2"), + ( + {"graph_build_iterations": 0}, + "QGEMeans graph_build_iterations must be positive", + ), + ], +) +def test_invalid_parameters_raise_with_python_names(base_data, parameters, message): + model = qgemeans(**parameters) + with pytest.raises(ValueError, match=f"^{message}$"): + model.train(base_data) + + +def test_rejects_too_few_clusters_and_dimensions(base_data): + with pytest.raises( + ValueError, match="QGEMeans requires more centroids than max_degree" + ): + QGEMeans(DIM, 32).train(base_data) + with pytest.raises( + ValueError, + match=r"QGEMeans currently requires dimensions in the range \[64, 65536\]", + ): + QGEMeans(32, K).train(base_data[:, :32]) + with pytest.raises(ValueError, match="QGEMeans requires n >= k"): + qgemeans().train(base_data[: K - 1]) + + +def test_failed_refit_keeps_previous_results(base_data): + model = qgemeans() + model.train(base_data) + centroids = model.centroids.copy() + bad = base_data.copy() + bad[3, 5] = np.nan + with pytest.raises(ValueError, match="QGEMeans x must contain only finite values"): + model.train(bad) + np.testing.assert_array_equal(model.centroids, centroids) + + +def test_train_rejects_wrong_dimension(base_data): + with pytest.raises(ValueError, match="x dimension does not match d"): + qgemeans().train(base_data[:, :-1]) diff --git a/tests/python/typing/public_api.py b/tests/python/typing/public_api.py index 80a29039..d17fb31d 100644 --- a/tests/python/typing/public_api.py +++ b/tests/python/typing/public_api.py @@ -11,6 +11,8 @@ HnswIndex, IvfIndex, KMeansIterationStats, + QGEMeans, + QGEMeansParameters, QGKMeans, QGKMeansParameters, RaBitQKMeans, @@ -70,7 +72,9 @@ def check(x: npt.NDArray[np.float32], labels: npt.NDArray[np.uint32]) -> None: assert_type(flat.cp.final_assignment, Literal["approximate", "exact"]) assert_type(qg.cp, QGKMeansParameters) assert_type(flat.cp, RaBitQKMeansParameters) - for model in (qg, flat): + emeans = QGEMeans(64, 40, niter=2, batch_size=32, final_assignment="exact") + assert_type(emeans.cp, QGEMeansParameters) + for model in (qg, flat, emeans): assert_type(model.train(x), float) assert_type(model.centroids, npt.NDArray[np.float32] | None) assert_type(model.assignments, npt.NDArray[np.uint32] | None) @@ -93,6 +97,9 @@ def check(x: npt.NDArray[np.float32], labels: npt.NDArray[np.uint32]) -> None: hnsw.train(x, 1) # type: ignore[call-arg] qg.cp.final_assignment = "Exact" # type: ignore[assignment] QGKMeans(64, 40, ef_build=1, bogus=1) # type: ignore[call-arg] + QGEMeans(64, 40, epochs=2) # type: ignore[call-arg] + emeans.cp.niter = "two" # type: ignore[assignment] + emeans.cp.final_assignment = "Exact" # type: ignore[assignment] def reject_removed_forms( @@ -224,6 +231,27 @@ def check_numpy_scalars() -> None: qg.cp.ef_search = np.int64(16) qg.cp.graph_build_iterations = np.int64(1) qg.cp.nbits = np.int64(4) + emeans = QGEMeans( + np.int64(64), + np.int64(40), + niter=np.int64(1), + batch_size=np.int64(16), + seed=np.uint32(42), + verbose=np.bool_(False), + num_threads=np.int64(1), + max_degree=np.int64(32), + ef_construction=np.int64(40), + ef_search=np.int64(16), + graph_build_iterations=np.int64(1), + ) + emeans.cp.niter = np.int64(1) + emeans.cp.batch_size = np.int64(16) + emeans.cp.final_assignment = "exact" + assert_type(emeans.train(x), float) + assert_type(emeans.cp.niter, int) + assert type(emeans.cp.niter) is int + assignments, distances = emeans.assign(x[:3]) + assert assignments.shape == distances.shape == (3,) for mode in ("approximate", "exact"): qg.cp.final_assignment = mode assert qg.cp.final_assignment == mode diff --git a/tests/unit/rabitqlib/clustering/qgemeans_test.cpp b/tests/unit/rabitqlib/clustering/qgemeans_test.cpp new file mode 100644 index 00000000..0b7ee818 --- /dev/null +++ b/tests/unit/rabitqlib/clustering/qgemeans_test.cpp @@ -0,0 +1,772 @@ +#include "rabitqlib/clustering/qgemeans.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rabitqlib/index/types.hpp" +#include "rabitqlib/utils/input_checks.hpp" + +namespace rabitqlib::qgemeans { + +namespace { + +constexpr size_t kDim = 64; +constexpr size_t kClusters = 40; +constexpr size_t kPointsPerCluster = 30; +constexpr size_t kCount = kClusters * kPointsPerCluster; + +// Well-separated Gaussian clusters around random centers. +std::vector clustered_data( + size_t clusters = kClusters, + size_t per_cluster = kPointsPerCluster, + uint32_t seed = 7, + size_t dimension = kDim +) { + std::mt19937 rng(seed); + std::normal_distribution center(0.0F, 4.0F); + std::normal_distribution noise(0.0F, 0.1F); + std::vector centers(clusters * dimension); + for (auto& value : centers) { + value = center(rng); + } + std::vector data(clusters * per_cluster * dimension); + for (size_t point = 0; point < clusters * per_cluster; ++point) { + const size_t cluster = point % clusters; + for (size_t dim = 0; dim < dimension; ++dim) { + data[point * dimension + dim] = centers[cluster * dimension + dim] + noise(rng); + } + } + return data; +} + +// Revival state of a 40-centroid model in which every centroid has removal cost +// 10 and no axis, except: centroid 3 costs 0, centroid 5 costs 1 (both below 0.3 +// times the median of 10), donor 7 has |U| = 100 along coordinate 0 and mass 4, +// and donor 9 has |U| = 1, whose gain (2 / pi) does not pay for centroid 5. +detail::EMeansState revival_state(const std::vector& data) { + detail::EMeansState state; + detail::initialize(state, kDim, kClusters, kCount, data.data(), 16, 42); + const size_t row = kDim + 1; + for (size_t cluster = 0; cluster < kClusters; ++cluster) { + std::fill_n(state.removal.data() + cluster * row, kDim, 0.0F); + state.removal[cluster * row + kDim] = 10.0F; + } + state.removal[3 * row + kDim] = 0.0F; + state.removal[5 * row + kDim] = 1.0F; + state.removal[7 * row] = 100.0F; + state.removal[9 * row + 1] = 1.0F; + std::fill_n(state.axes.data() + 7 * kDim, kDim, 0.0F); + state.axes[7 * kDim] = 1.0F; + state.mass[7] = 4.0F; + return state; +} + +QGEMeansParameters small_parameters(uint32_t threads = 2) { + QGEMeansParameters parameters; + parameters.niter = 4; + parameters.ef_construction = 40; + parameters.ef_search = 16; + parameters.num_threads = threads; + return parameters; +} + +double squared_distance(const float* a, const float* b) { + double sum = 0.0; + for (size_t dim = 0; dim < kDim; ++dim) { + const double difference = static_cast(a[dim]) - b[dim]; + sum += difference * difference; + } + return sum; +} + +template +void expect_invalid_argument(Function&& function, const std::string& message) { + try { + function(); + FAIL() << "expected std::invalid_argument: " << message; + } catch (const std::invalid_argument& error) { + EXPECT_EQ(std::string(error.what()), message); + } +} + +TEST(QGEMeansTest, UsesDocumentedDefaults) { + const QGEMeansParameters parameters; + EXPECT_EQ(parameters.niter, 8U); + EXPECT_EQ(parameters.batch_size, 0U); + EXPECT_FALSE(parameters.verbose); + EXPECT_EQ(parameters.seed, 42U); + EXPECT_EQ(parameters.final_assignment, FinalAssignmentMode::Approximate); + EXPECT_EQ(parameters.max_degree, 32U); + EXPECT_EQ(parameters.ef_construction, 240U); + EXPECT_EQ(parameters.ef_search, 16U); + EXPECT_EQ(parameters.graph_build_iterations, 1U); + EXPECT_EQ(parameters.num_threads, 0U); +} + +TEST(QGEMeansRecipeTest, FollowsBatchSizeAndStepLaws) { + // GIST1M with k = 4096 over 8 iterations: the law's batch of 2^17 vectors. + const auto gist = detail::resolve_recipe(1000000, 4096, 8, 0); + EXPECT_EQ(gist.batch_size, 131072U); + EXPECT_EQ(gist.steps_per_iteration, 8U); + EXPECT_EQ(gist.total_steps, 64U); + const double expected_alpha = 0.8244 * std::pow(4096.0, -0.4617) * + std::pow(131072.0, 0.9003) * std::pow(1e6, -0.4498) * + std::pow(8.0, -0.1057); + EXPECT_DOUBLE_EQ(gist.alpha0, std::min(std::max(expected_alpha, 1e-4), 1.0)); + + // An explicit batch is kept, and capped at n. + EXPECT_EQ(detail::resolve_recipe(1000, 40, 2, 64).batch_size, 64U); + const auto capped = detail::resolve_recipe(1000, 40, 2, 5000); + EXPECT_EQ(capped.batch_size, 1000U); + EXPECT_EQ(capped.steps_per_iteration, 1U); + EXPECT_EQ(capped.total_steps, 2U); + + // The law never exceeds half the vectors, rounded to a power of two, and the + // step size stays in [1e-4, 1]. + for (size_t n : {33U, 100U, 1000U, 100000U}) { + const auto recipe = detail::resolve_recipe(n, 33, 8, 0); + EXPECT_GE(recipe.batch_size, 1U); + EXPECT_LE(recipe.batch_size, n); + EXPECT_EQ(recipe.batch_size & (recipe.batch_size - 1), 0U); + EXPECT_GE(recipe.alpha0, 1e-4); + EXPECT_LE(recipe.alpha0, 1.0); + EXPECT_EQ( + recipe.steps_per_iteration, (n + recipe.batch_size - 1) / recipe.batch_size + ); + } +} + +TEST(QGEMeansRecipeTest, CapsAnExtremeBatchLawAtHalfTheVectors) { + // A law beyond 2^64 vectors must not overflow the power-of-two rounding. + const auto recipe = detail::resolve_recipe(1000, 40, size_t{1} << 62, 0); + EXPECT_EQ(recipe.batch_size, 512U); +} + +TEST(QGEMeansRecipeTest, RoundsToTheNearestPowerOfTwo) { + EXPECT_EQ(detail::round_power_of_two(0.5), 1U); + EXPECT_EQ(detail::round_power_of_two(1.0), 1U); + EXPECT_EQ(detail::round_power_of_two(2.8), 2U); + EXPECT_EQ(detail::round_power_of_two(2.9), 4U); + EXPECT_EQ(detail::round_power_of_two(1024.0), 1024U); + EXPECT_EQ(detail::round_power_of_two(1500.0), 2048U); +} + +TEST(QGEMeansRecipeTest, CosineScheduleDecaysToATenthOfTheInitialStep) { + EXPECT_DOUBLE_EQ(detail::scheduled_alpha(0.5, 0, 10), 0.5); + EXPECT_DOUBLE_EQ(detail::scheduled_alpha(0.5, 10, 10), 0.05); + EXPECT_DOUBLE_EQ(detail::scheduled_alpha(0.5, 5, 10), 0.5 * (0.1 + (0.9 * 0.5))); + // Steps past the end stay at the floor. + EXPECT_DOUBLE_EQ(detail::scheduled_alpha(0.5, 20, 10), 0.05); +} + +TEST(QGEMeansTest, RejectsInvalidParametersWithDescriptiveMessages) { + const auto with = [](auto change) { + QGEMeansParameters parameters = small_parameters(); + change(parameters); + return parameters; + }; + expect_invalid_argument( + [&] { QGEMeans(kDim, kClusters, with([](auto& p) { p.niter = 0; })); }, + "QGEMeans d, k, and niter must be positive" + ); + expect_invalid_argument( + [&] { QGEMeans(kDim, 0, small_parameters()); }, + "QGEMeans d, k, and niter must be positive" + ); + expect_invalid_argument( + [&] { QGEMeans(63, kClusters, small_parameters()); }, + "QGEMeans currently requires dimensions in the range [64, 65536]" + ); + expect_invalid_argument( + [&] { QGEMeans(65537, kClusters, small_parameters()); }, + "QGEMeans currently requires dimensions in the range [64, 65536]" + ); + expect_invalid_argument( + [&] { + QGEMeans(kDim, kClusters, with([](auto& p) { + p.num_threads = + static_cast(std::numeric_limits::max()) + 1U; + })); + }, + "QGEMeans num_threads must fit in an OpenMP int" + ); + expect_invalid_argument( + [&] { + QGEMeans(kDim, kClusters, with([](auto& p) { + p.final_assignment = static_cast(7); + })); + }, + "QGEMeans final_assignment mode is invalid" + ); + for (uint32_t degree : {0U, 48U}) { + expect_invalid_argument( + [&] { + QGEMeans(kDim, kClusters, with([degree](auto& p) { + p.max_degree = degree; + })); + }, + "QGEMeans max_degree must be a positive multiple of 32" + ); + } + expect_invalid_argument( + [&] { QGEMeans(kDim, 32, small_parameters()); }, + "QGEMeans requires more centroids than max_degree" + ); + expect_invalid_argument( + [&] { QGEMeans(kDim, kClusters, with([](auto& p) { p.ef_construction = 0; })); }, + "QGEMeans ef_construction and ef_search must be positive" + ); + expect_invalid_argument( + [&] { QGEMeans(kDim, kClusters, with([](auto& p) { p.ef_search = 0; })); }, + "QGEMeans ef_construction and ef_search must be positive" + ); + // Each search returns two centroids, so its pool needs at least two. + expect_invalid_argument( + [&] { QGEMeans(kDim, kClusters, with([](auto& p) { p.ef_search = 1; })); }, + "QGEMeans ef_search must be at least 2" + ); + expect_invalid_argument( + [&] { + QGEMeans(kDim, kClusters, with([](auto& p) { p.graph_build_iterations = 0; })); + }, + "QGEMeans graph_build_iterations must be positive" + ); + + // Parameters changed after construction are checked again by train. + QGEMeans model(kDim, kClusters, small_parameters()); + model.niter = 0; + const auto data = clustered_data(); + expect_invalid_argument( + [&] { model.train(kCount, data.data()); }, + "QGEMeans d, k, and niter must be positive" + ); +} + +TEST(QGEMeansTest, RejectsInvalidInputAndKeepsPreviousResults) { + auto data = clustered_data(); + QGEMeans model(kDim, kClusters, small_parameters()); + expect_invalid_argument( + [&] { model.train(kCount, nullptr); }, "QGEMeans x must not be null" + ); + expect_invalid_argument( + [&] { model.train(kClusters - 1, data.data()); }, "QGEMeans requires n >= k" + ); + + model.train(kCount, data.data()); + const auto centroids = model.centroids; + const auto assignments = model.assignments; + const double objective = model.final_obj; + + auto bad = data; + bad[5] = std::numeric_limits::quiet_NaN(); + expect_invalid_argument( + [&] { model.train(kCount, bad.data()); }, + "QGEMeans x must contain only finite values" + ); + bad[5] = 1e30F; + expect_invalid_argument( + [&] { model.train(kCount, bad.data()); }, + "QGEMeans x exceeds the safe float32 coordinate range" + ); + EXPECT_EQ(model.centroids, centroids); + EXPECT_EQ(model.assignments, assignments); + EXPECT_EQ(model.final_obj, objective); +} + +TEST(QGEMeansTest, AssignRequiresTrainingAndValidPointers) { + const auto data = clustered_data(); + QGEMeans model(kDim, kClusters, small_parameters()); + std::vector ids(kCount); + std::vector distances(kCount); + try { + model.assign(kCount, data.data(), ids.data(), distances.data()); + FAIL() << "expected std::runtime_error"; + } catch (const std::runtime_error& error) { + EXPECT_EQ(std::string(error.what()), "QGEMeans has not been trained"); + } + + model.train(kCount, data.data()); + EXPECT_NO_THROW(model.assign(0, nullptr, nullptr, nullptr)); + expect_invalid_argument( + [&] { model.assign(kCount, data.data(), nullptr, distances.data()); }, + "QGEMeans assign input and output pointers must not be null" + ); + auto bad = data; + bad[0] = std::numeric_limits::infinity(); + expect_invalid_argument( + [&] { model.assign(kCount, bad.data(), ids.data(), distances.data()); }, + "QGEMeans x must contain only finite values" + ); +} + +TEST(QGEMeansTest, RecordsOneStatisticPerIteration) { + const auto data = clustered_data(); + QGEMeans model(kDim, kClusters, small_parameters()); + model.train(kCount, data.data()); + ASSERT_EQ(model.iteration_stats.size(), model.niter); + for (size_t iteration = 0; iteration < model.niter; ++iteration) { + const auto& stats = model.iteration_stats[iteration]; + EXPECT_EQ(stats.iteration, iteration + 1); + EXPECT_GT(stats.obj, 0.0); + EXPECT_GE(stats.shift, 0.0); + } + ASSERT_EQ(model.centroids.size(), kClusters * kDim); + ASSERT_EQ(model.assignments.size(), kCount); + ASSERT_EQ(model.distances.size(), kCount); +} + +TEST(QGEMeansTest, ReturnsExactDistancesForItsAssignments) { + const auto data = clustered_data(); + QGEMeans model(kDim, kClusters, small_parameters()); + model.train(kCount, data.data()); + double objective = 0.0; + for (size_t point = 0; point < kCount; ++point) { + const PID cluster = model.assignments[point]; + ASSERT_LT(cluster, kClusters); + const double expected = squared_distance( + data.data() + point * kDim, model.centroids.data() + cluster * kDim + ); + EXPECT_NEAR(model.distances[point], expected, 1e-4 * (1.0 + expected)); + objective += model.distances[point]; + } + EXPECT_NEAR(model.final_obj, objective, 1e-6 * objective); +} + +TEST(QGEMeansTest, ExactFinalAssignmentReturnsTheNearestCentroid) { + const auto data = clustered_data(); + QGEMeansParameters parameters = small_parameters(); + parameters.final_assignment = FinalAssignmentMode::Exact; + QGEMeans model(kDim, kClusters, parameters); + model.train(kCount, data.data()); + for (size_t point = 0; point < kCount; ++point) { + const float* vector = data.data() + point * kDim; + double best = std::numeric_limits::infinity(); + PID best_cluster = 0; + for (size_t cluster = 0; cluster < kClusters; ++cluster) { + const double distance = + squared_distance(vector, model.centroids.data() + cluster * kDim); + if (distance < best) { + best = distance; + best_cluster = static_cast(cluster); + } + } + EXPECT_EQ(model.assignments[point], best_cluster) << "point " << point; + } +} + +TEST(QGEMeansTest, ApproximateAssignmentAgreesWithExactOnSeparatedClusters) { + const auto data = clustered_data(); + QGEMeansParameters parameters = small_parameters(); + QGEMeans approximate(kDim, kClusters, parameters); + approximate.train(kCount, data.data()); + parameters.final_assignment = FinalAssignmentMode::Exact; + QGEMeans exact(kDim, kClusters, parameters); + exact.train(kCount, data.data()); + // The final assignment does not change the trained centroids. + EXPECT_EQ(approximate.centroids, exact.centroids); + EXPECT_EQ(approximate.iteration_stats.size(), exact.iteration_stats.size()); + size_t agree = 0; + for (size_t point = 0; point < kCount; ++point) { + agree += approximate.assignments[point] == exact.assignments[point] ? 1 : 0; + } + EXPECT_GE(agree, kCount * 99 / 100); + EXPECT_GE(approximate.final_obj, exact.final_obj * (1.0 - 1e-6)); +} + +TEST(QGEMeansTest, IsDeterministicAcrossRunsAndThreadCounts) { + const auto data = clustered_data(); + QGEMeans single(kDim, kClusters, small_parameters(1)); + single.train(kCount, data.data()); + for (uint32_t threads : {1U, 4U}) { + QGEMeans model(kDim, kClusters, small_parameters(threads)); + model.train(kCount, data.data()); + EXPECT_EQ(model.centroids, single.centroids) << threads << " threads"; + EXPECT_EQ(model.assignments, single.assignments) << threads << " threads"; + EXPECT_EQ(model.distances, single.distances) << threads << " threads"; + ASSERT_EQ(model.iteration_stats.size(), single.iteration_stats.size()); + for (size_t iteration = 0; iteration < model.iteration_stats.size(); ++iteration) { + EXPECT_EQ( + model.iteration_stats[iteration].obj, single.iteration_stats[iteration].obj + ); + EXPECT_EQ( + model.iteration_stats[iteration].shift, + single.iteration_stats[iteration].shift + ); + EXPECT_EQ( + model.iteration_stats[iteration].nsplit, + single.iteration_stats[iteration].nsplit + ); + } + } + // A different seed trains different centroids. + QGEMeansParameters reseeded = small_parameters(1); + reseeded.seed = 43; + QGEMeans other(kDim, kClusters, reseeded); + other.train(kCount, data.data()); + EXPECT_NE(other.centroids, single.centroids); +} + +TEST(QGEMeansTest, CachedQuerySumsFollowTheSearchedRows) { + // Padded dimensions of 512 or more enable the query-sum cache. + constexpr size_t kWideDim = 512; + constexpr size_t kWideClusters = 64; + constexpr size_t kRows = 256; + std::mt19937 rng(5); + std::normal_distribution normal(0.0F, 1.0F); + std::vector data(kRows * kWideDim); + for (auto& value : data) { + value = normal(rng); + } + const float* centroids = data.data(); + std::vector first_pass(kRows); + std::vector second_pass(kRows); + for (size_t row = 0; row < kRows; ++row) { + first_pass[row] = (row * 37) % kRows; + second_pass[row] = (row * 101 + 3) % kRows; + } + + QGEMeansParameters cached_parameters; + cached_parameters.num_threads = 1; + detail::QGEAssignment cached( + kWideDim, kWideClusters, data.data(), kRows, 1, cached_parameters + ); + std::vector ids(kRows); + std::vector distances(kRows); + std::vector seconds(kRows); + cached.prepare(centroids); + cached.assign_batch( + first_pass.data(), kRows, ids.data(), distances.data(), seconds.data() + ); + cached.end_pass(); + cached.prepare(centroids); + cached.assign_batch( + second_pass.data(), kRows, ids.data(), distances.data(), seconds.data() + ); + + // One pass with an exact final assignment never rereads a row, so no cache. + QGEMeansParameters uncached_parameters = cached_parameters; + uncached_parameters.niter = 1; + uncached_parameters.final_assignment = FinalAssignmentMode::Exact; + detail::QGEAssignment uncached( + kWideDim, kWideClusters, data.data(), kRows, 1, uncached_parameters + ); + std::vector expected_ids(kRows); + std::vector expected_distances(kRows); + std::vector expected_seconds(kRows); + uncached.prepare(centroids); + uncached.assign_batch( + second_pass.data(), + kRows, + expected_ids.data(), + expected_distances.data(), + expected_seconds.data() + ); + EXPECT_EQ(ids, expected_ids); + EXPECT_EQ(distances, expected_distances); + EXPECT_EQ(seconds, expected_seconds); +} + +TEST(QGEMeansTest, TrainCentroidsMatchesTrainWithoutFinalAssignment) { + const auto data = clustered_data(); + QGEMeans full(kDim, kClusters, small_parameters()); + full.train(kCount, data.data()); + QGEMeans centroids_only(kDim, kClusters, small_parameters()); + centroids_only.train_centroids(kCount, data.data()); + EXPECT_EQ(centroids_only.centroids, full.centroids); + EXPECT_TRUE(centroids_only.assignments.empty()); + EXPECT_TRUE(centroids_only.distances.empty()); + EXPECT_EQ(centroids_only.final_obj, 0.0); + + std::vector ids(kCount); + std::vector distances(kCount); + centroids_only.assign(kCount, data.data(), ids.data(), distances.data()); + EXPECT_EQ(ids, full.assignments); + EXPECT_EQ(distances, full.distances); +} + +TEST(QGEMeansTest, AssignReproducesTrainingAssignmentsInBothModes) { + const auto data = clustered_data(); + for (auto mode : {FinalAssignmentMode::Approximate, FinalAssignmentMode::Exact}) { + QGEMeansParameters parameters = small_parameters(); + parameters.final_assignment = mode; + QGEMeans model(kDim, kClusters, parameters); + model.train(kCount, data.data()); + std::vector ids(kCount); + std::vector distances(kCount); + model.assign(kCount, data.data(), ids.data(), distances.data()); + EXPECT_EQ(ids, model.assignments); + EXPECT_EQ(distances, model.distances); + // Repeated calls reuse the cached centroid graph and agree. + std::vector again(kCount); + model.assign(kCount, data.data(), again.data(), distances.data()); + EXPECT_EQ(again, ids); + // Each point's result is independent of the others in the call. + PID single = 0; + float single_distance = 0; + model.assign(1, data.data() + 17 * kDim, &single, &single_distance); + EXPECT_EQ(single, ids[17]); + } +} + +TEST(QGEMeansTest, ExplicitBatchSizesFromThreeVectorsPerBatch) { + const auto data = clustered_data(kClusters, 3); + const size_t count = kClusters * 3; + // Not 1 or 2: steps on one or two vectors can move centroids onto the same + // point, and the SymphonyQG builder's pruning cosine then divides by zero, which + // the sanitizer build reports. + for (size_t batch : {3U, 7U, 1000000U}) { + QGEMeansParameters parameters = small_parameters(); + parameters.niter = 2; + parameters.batch_size = batch; + QGEMeans model(kDim, kClusters, parameters); + model.train(count, data.data()); + EXPECT_EQ(model.iteration_stats.size(), 2U); + EXPECT_EQ(model.assignments.size(), count); + for (float value : model.centroids) { + ASSERT_TRUE(std::isfinite(value)); + } + } +} + +TEST(QGEMeansTest, TrainsWithAsManyCentroidsAsVectors) { + const auto data = clustered_data(kClusters, 1); + QGEMeans model(kDim, kClusters, small_parameters()); + model.train(kClusters, data.data()); + EXPECT_EQ(model.assignments.size(), kClusters); + for (float value : model.centroids) { + ASSERT_TRUE(std::isfinite(value)); + } +} + +TEST(QGEMeansTest, ConstantDataKeepsFiniteCentroidsAndZeroObjective) { + // Every centroid starts at the same point; revival splits zero donors. + const std::vector data(kCount * kDim, 0.0F); + QGEMeans model(kDim, kClusters, small_parameters()); + model.train(kCount, data.data()); + for (float value : model.centroids) { + ASSERT_TRUE(std::isfinite(value)); + } + EXPECT_NEAR(model.final_obj, 0.0, 1e-20); +} + +TEST(QGEMeansTest, RetrainsOnItsOwnCentroidsLikeAnIndependentCopy) { + const auto data = clustered_data(); + QGEMeans model(kDim, kClusters, small_parameters()); + model.train(kCount, data.data()); + const std::vector copy = model.centroids; + + QGEMeans reference(kDim, kClusters, small_parameters()); + reference.train(kClusters, copy.data()); + // Training reads model.centroids while it trains new ones. + model.train(kClusters, model.centroids.data()); + EXPECT_EQ(model.centroids, reference.centroids); + EXPECT_EQ(model.assignments, reference.assignments); +} + +TEST(QGEMeansTest, ReducesTheObjectiveOnSeparatedClusters) { + const auto data = clustered_data(); + QGEMeansParameters parameters = small_parameters(); + parameters.niter = 8; + QGEMeans model(kDim, kClusters, parameters); + model.train(kCount, data.data()); + EXPECT_LT(model.iteration_stats.back().obj, model.iteration_stats.front().obj); + // Random initial centroids give a much larger objective than the trained ones. + double initial = 0.0; + for (size_t point = 0; point < kCount; ++point) { + initial += squared_distance(data.data() + point * kDim, data.data()); + } + EXPECT_LT(model.final_obj, initial / 10.0); +} + +TEST(QGEMeansRevivalTest, MovesTheCheapestCentroidsToSplitTheLongestAxes) { + const auto data = clustered_data(); + auto state = revival_state(data); + const auto before = state.centroids; + const auto mass_five = state.mass[5]; + + // Centroid 3 always moves; the pair (5, 9) does not pay and stops the list. + EXPECT_EQ(detail::revive(state, false), 1U); + const double spread = std::sqrt(2.0 * (100.0 / 4.0) / 3.14159265358979323846); + EXPECT_FLOAT_EQ( + state.centroids[7 * kDim], static_cast(before[7 * kDim] - spread) + ); + EXPECT_FLOAT_EQ( + state.centroids[3 * kDim], static_cast(before[7 * kDim] + spread) + ); + for (size_t dim = 1; dim < kDim; ++dim) { + EXPECT_EQ(state.centroids[7 * kDim + dim], before[7 * kDim + dim]); + EXPECT_EQ(state.centroids[3 * kDim + dim], before[7 * kDim + dim]); + } + EXPECT_EQ(state.mass[7], 2.0F); + EXPECT_EQ(state.mass[3], 2.0F); + EXPECT_EQ(state.mass[5], mass_five); + // The child takes half of the donor's statistics and its axis. + const size_t row = kDim + 1; + EXPECT_EQ(state.removal[7 * row], 50.0F); + EXPECT_EQ(state.removal[3 * row], 50.0F); + EXPECT_EQ(state.removal[3 * row + kDim], 5.0F); + EXPECT_EQ(state.axes[3 * kDim], 1.0F); + for (size_t cluster = 0; cluster < kClusters; ++cluster) { + if (cluster != 3 && cluster != 7) { + EXPECT_TRUE( + std::equal( + before.begin() + static_cast(cluster * kDim), + before.begin() + static_cast((cluster + 1) * kDim), + state.centroids.begin() + static_cast(cluster * kDim) + ) + ) << cluster; + } + } +} + +TEST(QGEMeansRevivalTest, MovesNothingWithoutCheapCentroids) { + const auto data = clustered_data(); + auto state = revival_state(data); + state.removal[3 * (kDim + 1) + kDim] = 10.0F; + state.removal[5 * (kDim + 1) + kDim] = 10.0F; + const auto before = state.centroids; + EXPECT_EQ(detail::revive(state, false), 0U); + EXPECT_EQ(state.centroids, before); +} + +TEST(QGEMeansRevivalTest, LastIterationSplitsCloseFromLaterVectorsOnly) { + const auto data = clustered_data(); + for (const bool last : {false, true}) { + auto state = revival_state(data); + // Every centroid received two vectors summing to one per coordinate. + state.pass_counts.assign(kClusters, 2.0); + state.pass_sums.assign(kClusters * kDim, 1.0F); + ASSERT_EQ(detail::revive(state, last), 1U); + const auto split = state.centroids; + for (size_t cluster = 0; cluster < kClusters; ++cluster) { + const bool cleared = last && (cluster == 3 || cluster == 7); + EXPECT_EQ(state.pass_counts[cluster], cleared ? 0.0 : 2.0) << cluster; + EXPECT_EQ(state.pass_sums[cluster * kDim], cleared ? 0.0F : 1.0F) << cluster; + } + detail::close_means(state, 1); + // Without later vectors the split pair keeps its split positions instead + // of returning to the donor's earlier mean; the others close at 0.5. + for (const size_t cluster : {size_t{3}, size_t{7}}) { + EXPECT_EQ(state.centroids[cluster * kDim], last ? split[cluster * kDim] : 0.5F) + << cluster; + } + EXPECT_EQ(state.centroids[0], 0.5F); + } +} + +TEST(QGEMeansRevivalTest, SplitsStayWithinTheCoordinateBound) { + const auto data = clustered_data(); + auto state = revival_state(data); + const float bound = max_coordinate_magnitude(kDim); + state.centroids[7 * kDim] = bound; + state.centroids[7 * kDim + 1] = -bound; + // A long axis across both coordinates, spread far beyond the bound. + state.axes[7 * kDim] = std::sqrt(0.5F); + state.axes[7 * kDim + 1] = -std::sqrt(0.5F); + state.removal[7 * (kDim + 1)] = 1e30F; + ASSERT_EQ(detail::revive(state, false), 1U); + for (const size_t cluster : {size_t{3}, size_t{7}}) { + for (size_t dim = 0; dim < kDim; ++dim) { + EXPECT_LE(std::abs(state.centroids[cluster * kDim + dim]), bound) + << cluster << " " << dim; + } + } + EXPECT_EQ(state.centroids[3 * kDim], bound); + EXPECT_EQ(state.centroids[3 * kDim + 1], -bound); +} + +TEST(QGEMeansRevivalTest, CollapsedSplitsAtTheBoundStayWithinIt) { + const auto data = clustered_data(); + auto state = revival_state(data); + const float bound = max_coordinate_magnitude(kDim); + // No donor has an axis, so centroid 3 (cost 0) splits the first donor, 0, + // with zero spread: the copies coincide at the bound and must separate inward. + std::fill_n(state.removal.data() + 7 * (kDim + 1), kDim, 0.0F); + std::fill_n(state.removal.data() + 9 * (kDim + 1), kDim, 0.0F); + state.centroids[0] = bound; + ASSERT_EQ(detail::revive(state, false), 1U); + EXPECT_EQ(state.centroids[0], bound); + EXPECT_LT(state.centroids[3 * kDim], bound); + EXPECT_EQ(state.centroids[3 * kDim], std::nextafter(bound, 0.0F)); +} + +TEST(QGEMeansRevivalTest, UpdatedAndClosedMeansStayWithinTheBound) { + // At d = 960 the float32 sum of ten coordinates on the bound, accumulated as + // in accumulate(), divides back to a value just above the bound. + constexpr size_t kWide = 960; + constexpr size_t kMembers = 10; + const float bound = max_coordinate_magnitude(kWide); + float sum = 0.0F; + for (size_t member = 0; member < kMembers; ++member) { + sum += bound; + } + ASSERT_GT(sum / static_cast(kMembers), bound); + + const std::vector rows(2 * kWide, 0.0F); + detail::EMeansState state; + detail::initialize(state, kWide, 2, 2, rows.data(), 2, 42); + state.batch_counts = {static_cast(kMembers), 0.0F}; + state.batch_sums.assign(2 * kWide, 0.0F); + state.batch_sums[0] = sum; + state.pass_sums.assign(2 * kWide, 0.0F); + detail::start_iteration(state, true); + detail::apply_statistics(state, 1.0, true, 1); + EXPECT_EQ(state.centroids[0], bound); + detail::close_means(state, 1); + EXPECT_EQ(state.centroids[0], bound); +} + +TEST(QGEMeansTest, RevivesCentroidsWhileTraining) { + const auto data = clustered_data(); + QGEMeansParameters parameters = small_parameters(); + parameters.niter = 8; + QGEMeans model(kDim, kClusters, parameters); + model.train(kCount, data.data()); + size_t revived = 0; + for (const auto& stats : model.iteration_stats) { + revived += stats.nsplit; + } + EXPECT_GT(revived, 0U); +} + +TEST(QGEMeansTest, IsDeterministicAcrossGraphBuildThreadCounts) { + // From k = 256 the centroid graph builds with up to k / 128 threads. + constexpr size_t kManyClusters = 256; + constexpr size_t kPerCluster = 8; + const auto data = clustered_data(kManyClusters, kPerCluster); + QGEMeans single(kDim, kManyClusters, small_parameters(1)); + single.train(kManyClusters * kPerCluster, data.data()); + QGEMeans parallel(kDim, kManyClusters, small_parameters(4)); + parallel.train(kManyClusters * kPerCluster, data.data()); + EXPECT_EQ(parallel.centroids, single.centroids); + EXPECT_EQ(parallel.assignments, single.assignments); + EXPECT_EQ(parallel.distances, single.distances); +} + +TEST(QGEMeansTest, AssignReproducesTrainingAssignmentsWithCachedQuerySums) { + // From 512 padded dimensions training reuses cached query sums; assign() does not. + constexpr size_t kWide = 512; + const auto data = clustered_data(kClusters, kPointsPerCluster, 7, kWide); + for (auto mode : {FinalAssignmentMode::Approximate, FinalAssignmentMode::Exact}) { + QGEMeansParameters parameters = small_parameters(); + parameters.final_assignment = mode; + QGEMeans model(kWide, kClusters, parameters); + model.train(kCount, data.data()); + std::vector ids(kCount); + std::vector distances(kCount); + model.assign(kCount, data.data(), ids.data(), distances.data()); + EXPECT_EQ(ids, model.assignments); + EXPECT_EQ(distances, model.distances); + } +} + +} // namespace +} // namespace rabitqlib::qgemeans diff --git a/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp b/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp index d1336ddd..19b300eb 100644 --- a/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp +++ b/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp @@ -46,7 +46,9 @@ TEST(QGKMeansQuerySumTest, CachePolicyAndSuccessfulFillControlValidity) { QGKMeansParameters parameters; parameters.niter = configuration.iterations; parameters.final_assignment = configuration.final_assignment; - detail::QuerySumCache cache(configuration.dim, parameters); + clustering::detail::QuerySumCache cache( + configuration.dim, detail::reuses_query_sums(parameters) + ); EXPECT_EQ(cache.cached(0), nullptr); if (!configuration.enabled) { // Disabled preparation must not attempt an allocation, even at this size. @@ -73,7 +75,7 @@ TEST(QGKMeansQuerySumTest, CachePolicyAndSuccessfulFillControlValidity) { EXPECT_EQ(cache.cached(0), data); EXPECT_FLOAT_EQ(data[0], 2.0F); } - detail::QuerySumCache disabled(nullptr, true); + clustering::detail::QuerySumCache disabled(nullptr, true); disabled.complete(); EXPECT_EQ(disabled.cached(0), nullptr); }