diff --git a/docs/docs/clustering.md b/docs/docs/clustering.md index 49626c8d..732ca774 100644 --- a/docs/docs/clustering.md +++ b/docs/docs/clustering.md @@ -204,10 +204,11 @@ 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 +(by default; see `max_rebuild_gap`) 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 +exponentially decaying mass. Every fifth mini-batch (by default; see +`max_rebuild_gap`), 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 @@ -227,6 +228,19 @@ Faiss's default; the closing handover is not implemented. | `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. | +| `max_rebuild_gap` | `1` | Largest number of mini-batches between centroid-graph rebuilds; `1` rebuilds before every mini-batch. See below. | + +With `max_rebuild_gap` above 1, the graph is still rebuilt before every +mini-batch during the first quarter of the run; after that the gap between +rebuilds grows linearly to `max_rebuild_gap` mini-batches at the end. Before the +other mini-batches the graph keeps its edges, and its vertices and neighbor codes +move to the current centroids, which costs a fraction of a rebuild. Kept edges +cannot follow revival, which moves centroids far, so a due revival waits until +the mini-batch before the next rebuild, or the last mini-batch, and several due +revivals may run as one. +Late in the run consecutive graphs share most of their edges, so this mainly +saves rebuild time; results differ from `max_rebuild_gap = 1` at the same seed. The final +assignment always uses a freshly built graph. C++ and Python use the same names. The centroid graph always stores raw float32 centroids, and QGEMeans has no `spherical`, sampling or early-stop @@ -236,7 +250,8 @@ 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 +`nsplit` counts revived centroids; with `max_rebuild_gap` above 1, a waiting revival +is counted in the iteration that runs it, which may follow the one where it fell due. 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. diff --git a/include/rabitqlib/clustering/detail/emeans.hpp b/include/rabitqlib/clustering/detail/emeans.hpp index 8d7f16a9..dbaa8042 100644 --- a/include/rabitqlib/clustering/detail/emeans.hpp +++ b/include/rabitqlib/clustering/detail/emeans.hpp @@ -32,6 +32,9 @@ namespace rabitqlib::qgemeans::detail { constexpr double kAlphaMinFactor = 0.1; constexpr size_t kReviveEvery = 5; +// Fraction of the mini-batches that rebuild the centroid graph every time before +// rebuilds are spaced out. +constexpr double kRebuildWarmup = 0.25; 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 @@ -89,6 +92,58 @@ struct Recipe { return {batch_size, alpha0, steps, steps * niter}; } +// Mini-batches between centroid-graph rebuilds at step: 1 for the first +// kRebuildWarmup of the run, then growing linearly to max_gap at the end. +[[nodiscard]] inline size_t rebuild_gap(size_t step, size_t total_steps, size_t max_gap) { + if (max_gap <= 1) { + return 1; + } + const double progress = + static_cast(step) / static_cast(std::max(1, total_steps)); + if (progress < kRebuildWarmup) { + return 1; + } + const double grown = (progress - kRebuildWarmup) / (1.0 - kRebuildWarmup); + return 1 + static_cast((grown * static_cast(max_gap - 1)) + 0.5); +} + +// Chooses, before each step, between rebuilding and refreshing the assignment +// graph, and runs revival every kReviveEvery steps. A refresh keeps the graph's +// edges, which cannot follow the long moves of revival, so a due revival waits +// until the step before the next rebuild, or the last step, after which the final +// assignment builds a fresh graph. With max_gap 1 every step rebuilds and revival +// is never delayed. +class GraphSchedule { + public: + GraphSchedule(size_t total_steps, size_t max_gap) + : total_steps_(total_steps), max_gap_(max_gap) {} + + [[nodiscard]] bool rebuild_due(size_t step) const { + return step == 0 || + step - last_rebuild_ >= rebuild_gap(step, total_steps_, max_gap_); + } + + void rebuilt(size_t step) { last_rebuild_ = step; } + + // Called after step's update; true when revival should run now. + [[nodiscard]] bool revive_after(size_t step) { + if ((step + 1) % kReviveEvery == 0) { + revival_pending_ = true; + } + if (revival_pending_ && (step + 1 == total_steps_ || rebuild_due(step + 1))) { + revival_pending_ = false; + return true; + } + return false; + } + + private: + size_t total_steps_; + size_t max_gap_; + size_t last_rebuild_ = 0; + bool revival_pending_ = false; +}; + [[nodiscard]] inline double scheduled_alpha( double alpha0, size_t step, size_t total_steps ) { @@ -511,16 +566,18 @@ inline void close_means(EMeansState& state, uint32_t num_workers) { /** * 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: + * Parameters provides niter, batch_size, verbose, seed, final_assignment, + * num_threads and max_rebuild_gap. 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 + * void prepare(const float* centroids); // before a mini-batch and the final * // pass; may borrow centroids until the - * // next prepare + * // next prepare or refresh + * void refresh(const float* centroids); // before a mini-batch that reuses the + * // last prepare's structure; same borrow * 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 @@ -544,6 +601,7 @@ class EMeans : public Parameters { public: using Parameters::batch_size; using Parameters::final_assignment; + using Parameters::max_rebuild_gap; using Parameters::niter; using Parameters::num_threads; using Parameters::seed; @@ -630,6 +688,7 @@ class EMeans : public Parameters { std::vector order(n); std::vector iteration_start(state.centroids.size()); size_t step = 0; + GraphSchedule schedule(recipe.total_steps, max_rebuild_gap); for (size_t iteration = 0; iteration < niter; ++iteration) { const bool last = iteration + 1 == niter; std::copy( @@ -644,7 +703,12 @@ class EMeans : public Parameters { 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()); + if (schedule.rebuild_due(step)) { + graph.prepare(state.centroids.data()); + schedule.rebuilt(step); + } else { + graph.refresh(state.centroids.data()); + } graph.assign_batch( batch, rows, @@ -659,7 +723,7 @@ class EMeans : public Parameters { last, num_workers ); - if ((step + 1) % kReviveEvery == 0) { + if (schedule.revive_after(step)) { nsplit += revive(state, last); } ++step; @@ -768,6 +832,11 @@ class EMeans : public Parameters { clustering::detail::validate_common_parameters( Assignment::kName, d, k, niter, "niter", num_threads, final_assignment ); + if (max_rebuild_gap == 0) { + throw std::invalid_argument( + std::string(Assignment::kName) + " max_rebuild_gap must be positive" + ); + } Assignment::validate_parameters(d, k, *this); } diff --git a/include/rabitqlib/clustering/detail/qg_assigner.hpp b/include/rabitqlib/clustering/detail/qg_assigner.hpp index 0334828a..4abcfa7a 100644 --- a/include/rabitqlib/clustering/detail/qg_assigner.hpp +++ b/include/rabitqlib/clustering/detail/qg_assigner.hpp @@ -223,6 +223,14 @@ class QGAssigner { } } + // Moves the built graph's vertices to centroids, keeping its edges. + void refresh_centroid_graph(const float* centroids) { + if (!builder_) { + throw std::logic_error("QGAssigner refresh requires a built centroid graph"); + } + builder_->refresh(centroids); + } + // 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( diff --git a/include/rabitqlib/clustering/qgemeans.hpp b/include/rabitqlib/clustering/qgemeans.hpp index ef114bdb..4bae2420 100644 --- a/include/rabitqlib/clustering/qgemeans.hpp +++ b/include/rabitqlib/clustering/qgemeans.hpp @@ -29,6 +29,12 @@ struct QGEMeansParameters { // Graph-building passes after PiPNN initialization; the last refines the graph. uint32_t graph_build_iterations = 1; uint32_t num_threads = 0; + // Largest number of mini-batches between centroid-graph rebuilds; 1 rebuilds + // before every mini-batch. Larger values rebuild before every mini-batch for the + // first quarter of the run, then let the gap grow linearly to this value; between + // rebuilds the graph keeps its edges and moves its vertices to the centroids, and + // a due revival waits for the mini-batch before the next rebuild (or the last one). + uint32_t max_rebuild_gap = 1; }; namespace detail { @@ -55,7 +61,8 @@ constexpr uint32_t kSearchResults = 2; } // 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, +// rebuilt by every prepare(), moved to them with its edges kept by every refresh(), +// 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. @@ -90,6 +97,11 @@ class QGEAssignment { assigner_.rebuild_centroid_graph(centroids); } + void refresh(const float* centroids) { + centroids_ = centroids; + assigner_.refresh_centroid_graph(centroids); + } + void assign_batch( const size_t* rows, size_t count, @@ -150,8 +162,10 @@ class QGEAssignment { /** * 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. + * batch or, with max_rebuild_gap above 1, rebuilt less often late in the run and + * otherwise moved to the current centroids; 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; diff --git a/include/rabitqlib/index/symqg/qg.hpp b/include/rabitqlib/index/symqg/qg.hpp index b414fba2..d4489d6c 100644 --- a/include/rabitqlib/index/symqg/qg.hpp +++ b/include/rabitqlib/index/symqg/qg.hpp @@ -117,6 +117,9 @@ class QuantizedGraph { size_t record_bytes_ = 0; // length of entire row size_t default_ef_search_ = 0; bool ready_ = false; + // Identifies the QGBuilder build that wrote the current rows; 0 after load. Not + // persisted. + uint64_t build_token_ = 0; uint32_t seed_ = 42; bool seed_known_ = false; // false for files that do not record the seed // Construction settings a builder records; unknown (0 and no value) otherwise. diff --git a/include/rabitqlib/index/symqg/qg_builder.hpp b/include/rabitqlib/index/symqg/qg_builder.hpp index 70e5f4b3..1c84fd2b 100644 --- a/include/rabitqlib/index/symqg/qg_builder.hpp +++ b/include/rabitqlib/index/symqg/qg_builder.hpp @@ -62,7 +62,8 @@ class QGBuilder { static constexpr size_t kLockStripes = 4096; std::vector new_neighbors_; // new neighbors for current iteration std::vector degrees_; - uint32_t seed_; // base seed for graph initialization + uint64_t build_token_ = 0; // matches qg_.build_token_ while qg_ holds our build + uint32_t seed_; // base seed for graph initialization std::optional cache_; std::vector reverse_buffer_; struct BuildWorker { @@ -142,6 +143,16 @@ class QGBuilder { */ void reset(const float* data); + /** Move every vertex of a built raw-vector graph to data, keeping its edges. + * Re-encodes each row's neighbor codes against the new positions and picks + * the entry point again as build does; costs far + * less than reset() plus build() when the vectors moved little; refine() or + * build() may follow and rescore the kept edges at the new positions. A + * failure leaves the graph unready with partly updated state; only reset() + * followed by build() makes it ready again. + */ + void refresh(const float* data); + // One complete search/prune/reverse-edge/degree-completion iteration. Call // before serving a seeded graph: search() requires full final rows. void refine(); diff --git a/python_bindings/__init__.py b/python_bindings/__init__.py index 738de3be..2636fe74 100644 --- a/python_bindings/__init__.py +++ b/python_bindings/__init__.py @@ -241,12 +241,20 @@ class QGEMeans(_KMeans): graph_build_iterations : int, optional Positive number of graph-building passes after initialization. Default is 1. + max_rebuild_gap : int, optional + Largest number of mini-batches between centroid-graph rebuilds, at + least 1; 1 rebuilds before every mini-batch. 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 + centroids and searched for each vector's nearest centroid. With + max_rebuild_gap above 1, rebuilds after the first quarter of the run are + spaced up to that many mini-batches apart; in between, the graph keeps its + edges and moves its vertices to the current centroids, and a due revival + waits for the mini-batch before the next rebuild, or the last one; + several may run as one. 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 @@ -332,7 +340,7 @@ def obj(self): @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.""" + """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; with max_rebuild_gap above 1 a waiting revival is counted in the iteration that runs it.""" return super().iteration_stats diff --git a/python_bindings/__init__.pyi b/python_bindings/__init__.pyi index 060ee604..d36ea00c 100644 --- a/python_bindings/__init__.pyi +++ b/python_bindings/__init__.pyi @@ -1026,12 +1026,20 @@ class QGEMeans: graph_build_iterations : int, optional Positive number of graph-building passes after initialization. Default is 1. + max_rebuild_gap : int, optional + Largest number of mini-batches between centroid-graph rebuilds, at + least 1; 1 rebuilds before every mini-batch. 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 + centroids and searched for each vector's nearest centroid. With + max_rebuild_gap above 1, rebuilds after the first quarter of the run are + spaced up to that many mini-batches apart; in between, the graph keeps its + edges and moves its vertices to the current centroids, and a due revival + waits for the mini-batch before the next rebuild, or the last one; + several may run as one. 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 @@ -1071,6 +1079,7 @@ class QGEMeans: ef_construction: SupportsIndex = 240, ef_search: SupportsIndex = 16, graph_build_iterations: SupportsIndex = 1, + max_rebuild_gap: SupportsIndex = 1, ) -> None: """Cluster vectors with mini-batch e-means and SymphonyQG graph assignment. @@ -1107,12 +1116,20 @@ class QGEMeans: graph_build_iterations : int, optional Positive number of graph-building passes after initialization. Default is 1. + max_rebuild_gap : int, optional + Largest number of mini-batches between centroid-graph rebuilds, at + least 1; 1 rebuilds before every mini-batch. 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 + centroids and searched for each vector's nearest centroid. With + max_rebuild_gap above 1, rebuilds after the first quarter of the run are + spaced up to that many mini-batches apart; in between, the graph keeps its + edges and moves its vertices to the current centroids, and a due revival + waits for the mini-batch before the next rebuild, or the last one; + several may run as one. 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 @@ -1210,7 +1227,7 @@ class QGEMeans: @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.""" + """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; with max_rebuild_gap above 1 a waiting revival is counted in the iteration that runs it.""" class QGEMeansParameters: """Mutable training settings for QGEMeans. @@ -1271,6 +1288,11 @@ class QGEMeansParameters: """Positive number of graph-building passes after initialization. Default is 1.""" @graph_build_iterations.setter def graph_build_iterations(self, value: SupportsIndex) -> None: ... + @property + def max_rebuild_gap(self) -> int: + """Largest number of mini-batches between centroid-graph rebuilds, at least 1; 1 rebuilds before every mini-batch. Default is 1.""" + @max_rebuild_gap.setter + def max_rebuild_gap(self, value: SupportsIndex) -> None: ... def __init__(self) -> None: """Create parameters with their documented defaults.""" diff --git a/python_bindings/kmeans_bindings.cpp b/python_bindings/kmeans_bindings.cpp index abae37aa..027c3c00 100644 --- a/python_bindings/kmeans_bindings.cpp +++ b/python_bindings/kmeans_bindings.cpp @@ -333,6 +333,11 @@ on QGEMeans.)doc" "graph_build_iterations", &QGEMeansParameters::graph_build_iterations, R"doc(Positive number of graph-building passes after initialization. Default is 1.)doc" + ) + .def_readwrite( + "max_rebuild_gap", + &QGEMeansParameters::max_rebuild_gap, + R"doc(Largest number of mini-batches between centroid-graph rebuilds, at least 1; 1 rebuilds before every mini-batch. Default is 1.)doc" ); py::class_( diff --git a/src/index/qg_builder.cpp b/src/index/qg_builder.cpp index 4204ebee..9e2ae34d 100644 --- a/src/index/qg_builder.cpp +++ b/src/index/qg_builder.cpp @@ -32,6 +32,10 @@ namespace rabitqlib::symqg { +namespace { +std::atomic last_build_token{0}; +} // namespace + QGBuilder::BuildQuery::BuildQuery( const QuantizedGraph& graph, const BuildCache* cache ) @@ -129,6 +133,80 @@ void QGBuilder::reset(const float* data) { } } +void QGBuilder::refresh(const float* data) { + if (data == nullptr) { + throw std::invalid_argument("QuantizedGraph build data must not be null"); + } + // degrees_ and the cache describe only rows this builder wrote; a load or another + // builder's build replaces them. + if (!qg_.ready_ || build_token_ == 0 || qg_.build_token_ != build_token_) { + throw std::logic_error( + "QuantizedGraph refresh requires a graph built by this builder" + ); + } + if (qg_.is_quantized()) { + throw std::logic_error("QuantizedGraph refresh requires a raw-vector graph"); + } + check_coordinates(data, num_points_ * dim_, dim_, "QuantizedGraph build data"); + std::vector normalized; + if (qg_.cosine_) { + normalized = index_detail::normalized_rows(data, num_points_, dim_, num_workers_); + data = normalized.data(); + } + qg_.ready_ = false; + // Pending scores were measured at the old positions; a later pass rescores the + // kept edges from the rows instead. + for (CandidateList& pending : new_neighbors_) { + pending.clear(); + } + qg_.copy_vectors(data, num_workers_); + // As in initialize_storage: start searches from the vertex nearest the mean. + const std::vector centroid = + compute_centroid(data, num_points_, dim_, num_workers_); + qg_.set_ep( + exact_nn(data, centroid.data(), num_points_, dim_, num_workers_, qg_.raw_dist_func_) + ); + const size_t padded_dim = qg_.padded_dim_; + index_detail::ParallelException failure; + if (cache_) { +#pragma omp parallel for num_threads(num_workers_) schedule(static) + for (std::ptrdiff_t index = 0; index < static_cast(num_points_); + ++index) { + if (failure.failed()) { + continue; + } + try { + const auto internal_id = static_cast(index); + qg_.rotator_->rotate( + qg_.get_vector(internal_id), + cache_->rotated_vectors.data() + internal_id * padded_dim + ); + } catch (...) { failure.capture(); } + } + failure.rethrow(); + } +#pragma omp parallel for num_threads(num_workers_) schedule(static) + for (std::ptrdiff_t index = 0; index < static_cast(num_points_); + ++index) { + if (failure.failed()) { + continue; + } + try { + const auto internal_id = static_cast(index); + auto& worker = workers_[static_cast(omp_get_thread_num())]; + const auto neighbors = + static_cast&>(qg_).get_neighbors(internal_id); + worker.neighbor_ids.resize(degrees_[internal_id]); + for (size_t j = 0; j < worker.neighbor_ids.size(); ++j) { + worker.neighbor_ids[j] = neighbors[j]; + } + write_row(internal_id, worker); + } catch (...) { failure.capture(); } + } + failure.rethrow(); + qg_.ready_ = true; +} + void QGBuilder::initialize_seed( const float* data, const std::vector& offsets, const std::vector& neighbors ) { @@ -232,6 +310,8 @@ void QGBuilder::run_passes(size_t num_iter) { run_pass(/*final_pass=*/false); } run_pass(/*final_pass=*/true); + build_token_ = ++last_build_token; + qg_.build_token_ = build_token_; qg_.ready_ = true; } @@ -301,6 +381,8 @@ void QGBuilder::initialize_storage(const float* data) { std::vector centroid = compute_centroid(data, num_points_, dim_, num_workers_); qg_.ready_ = false; + build_token_ = 0; + qg_.build_token_ = 0; qg_.set_quantization_centroid(centroid.data()); qg_.copy_vectors(data, num_workers_); diff --git a/tests/python/test_qgemeans.py b/tests/python/test_qgemeans.py index cdc994b3..dac8ad03 100644 --- a/tests/python/test_qgemeans.py +++ b/tests/python/test_qgemeans.py @@ -36,6 +36,7 @@ def test_parameters_use_index_names_and_defaults(): assert cp.ef_construction == 240 assert cp.ef_search == 16 assert cp.graph_build_iterations == 1 + assert cp.max_rebuild_gap == 1 for old in ("graph_degree", "ef_build", "epochs", "quantization_bits", "nbits"): assert not hasattr(cp, old) @@ -140,6 +141,27 @@ def test_training_is_deterministic_across_thread_counts(base_data): np.testing.assert_array_equal(single.obj, multi.obj) +def test_spaced_rebuilds_train_deterministically(base_data): + every = qgemeans(batch_size=32) + every.train(base_data) + spaced = qgemeans(batch_size=32, max_rebuild_gap=np.int64(4)) + assert spaced.cp.max_rebuild_gap == 4 + spaced.train(base_data) + assert spaced.final_obj < every.final_obj * 1.05 + again = qgemeans(batch_size=32, num_threads=3) + again.cp.max_rebuild_gap = 4 + again.train(base_data) + np.testing.assert_array_equal(again.centroids, spaced.centroids) + np.testing.assert_array_equal(again.assignments, spaced.assignments) + + +def test_max_rebuild_gap_rejects_negative_values(): + with pytest.raises( + TypeError, match="QGEMeans\\(\\) could not convert parameter 'max_rebuild_gap'" + ): + qgemeans(max_rebuild_gap=-1) + + def test_parameters_can_be_changed_through_cp(base_data): model = qgemeans() model.cp.niter = 1 @@ -162,6 +184,7 @@ def test_parameters_can_be_changed_through_cp(base_data): {"graph_build_iterations": 0}, "QGEMeans graph_build_iterations must be positive", ), + ({"max_rebuild_gap": 0}, "QGEMeans max_rebuild_gap must be positive"), ], ) def test_invalid_parameters_raise_with_python_names(base_data, parameters, message): diff --git a/tests/python/typing/public_api.py b/tests/python/typing/public_api.py index d17fb31d..d4f671ab 100644 --- a/tests/python/typing/public_api.py +++ b/tests/python/typing/public_api.py @@ -243,8 +243,10 @@ def check_numpy_scalars() -> None: ef_construction=np.int64(40), ef_search=np.int64(16), graph_build_iterations=np.int64(1), + max_rebuild_gap=np.int64(4), ) emeans.cp.niter = np.int64(1) + emeans.cp.max_rebuild_gap = np.int64(1) emeans.cp.batch_size = np.int64(16) emeans.cp.final_assignment = "exact" assert_type(emeans.train(x), float) diff --git a/tests/unit/rabitqlib/clustering/qgemeans_test.cpp b/tests/unit/rabitqlib/clustering/qgemeans_test.cpp index 0b7ee818..49c5ba23 100644 --- a/tests/unit/rabitqlib/clustering/qgemeans_test.cpp +++ b/tests/unit/rabitqlib/clustering/qgemeans_test.cpp @@ -2,10 +2,12 @@ #include +#include #include #include #include #include +#include #include #include #include @@ -109,6 +111,7 @@ TEST(QGEMeansTest, UsesDocumentedDefaults) { EXPECT_EQ(parameters.ef_search, 16U); EXPECT_EQ(parameters.graph_build_iterations, 1U); EXPECT_EQ(parameters.num_threads, 0U); + EXPECT_EQ(parameters.max_rebuild_gap, 1U); } TEST(QGEMeansRecipeTest, FollowsBatchSizeAndStepLaws) { @@ -167,6 +170,79 @@ TEST(QGEMeansRecipeTest, CosineScheduleDecaysToATenthOfTheInitialStep) { EXPECT_DOUBLE_EQ(detail::scheduled_alpha(0.5, 20, 10), 0.05); } +TEST(QGEMeansRecipeTest, RebuildGapGrowsLinearlyAfterTheFirstQuarter) { + for (size_t step = 0; step <= 100; ++step) { + EXPECT_EQ(detail::rebuild_gap(step, 100, 1), 1U) << step; + } + for (size_t step = 0; step <= 25; ++step) { + EXPECT_EQ(detail::rebuild_gap(step, 100, 8), 1U) << step; + } + // (0.62 - 0.25) / 0.75 of the way from 1 to 8 rounds to 4. + EXPECT_EQ(detail::rebuild_gap(62, 100, 8), 4U); + EXPECT_EQ(detail::rebuild_gap(100, 100, 8), 8U); + EXPECT_EQ(detail::rebuild_gap(100, 100, 16), 16U); + size_t previous = 1; + for (size_t step = 0; step <= 100; ++step) { + const size_t gap = detail::rebuild_gap(step, 100, 16); + EXPECT_GE(gap, previous) << step; + EXPECT_LE(gap, 16U) << step; + previous = gap; + } + EXPECT_EQ(detail::rebuild_gap(0, 0, 8), 1U); +} + +TEST(QGEMeansRecipeTest, RevivalWaitsForTheNextRebuild) { + constexpr size_t kSteps = 100; + for (size_t max_gap : {1U, 8U, 16U}) { + SCOPED_TRACE(max_gap); + detail::GraphSchedule schedule(kSteps, max_gap); + std::vector rebuilds; + std::vector revivals; + for (size_t step = 0; step < kSteps; ++step) { + rebuilds.push_back(schedule.rebuild_due(step)); + if (rebuilds.back()) { + schedule.rebuilt(step); + } + if (schedule.revive_after(step)) { + revivals.push_back(step); + } + } + // The final assignment builds a fresh graph, so a waiting revival runs on the + // last step. + rebuilds.push_back(true); + size_t next = 0; // index of the next revival to match + for (size_t due = detail::kReviveEvery - 1; due < kSteps; + due += detail::kReviveEvery) { + // The first step from due whose successor rebuilds runs the revival. + size_t expected = due; + while (!rebuilds[expected + 1]) { + ++expected; + } + if (next > 0 && revivals[next - 1] >= expected) { + continue; // merged into an earlier waiting revival + } + ASSERT_LT(next, revivals.size()) << due; + EXPECT_EQ(revivals[next], expected) << due; + ++next; + } + EXPECT_EQ(next, revivals.size()); + // The revival due on the last step is never dropped. + ASSERT_FALSE(revivals.empty()); + EXPECT_EQ(revivals.back(), kSteps - 1); + if (max_gap == 1) { + EXPECT_TRUE(std::all_of(rebuilds.begin(), rebuilds.end() - 1, [](bool b) { + return b; + })); + ASSERT_EQ(revivals.size(), kSteps / detail::kReviveEvery); + for (size_t i = 0; i < revivals.size(); ++i) { + EXPECT_EQ(revivals[i], (i + 1) * detail::kReviveEvery - 1); + } + } else { + EXPECT_LT(revivals.size(), kSteps / detail::kReviveEvery); + } + } +} + TEST(QGEMeansTest, RejectsInvalidParametersWithDescriptiveMessages) { const auto with = [](auto change) { QGEMeansParameters parameters = small_parameters(); @@ -239,6 +315,10 @@ TEST(QGEMeansTest, RejectsInvalidParametersWithDescriptiveMessages) { }, "QGEMeans graph_build_iterations must be positive" ); + expect_invalid_argument( + [&] { QGEMeans(kDim, kClusters, with([](auto& p) { p.max_rebuild_gap = 0; })); }, + "QGEMeans max_rebuild_gap must be positive" + ); // Parameters changed after construction are checked again by train. QGEMeans model(kDim, kClusters, small_parameters()); @@ -737,6 +817,67 @@ TEST(QGEMeansTest, RevivesCentroidsWhileTraining) { EXPECT_GT(revived, 0U); } +TEST(QGEMeansTest, SpacedRebuildsAreDeterministicAndKeepTheObjective) { + // Overlapping clusters and small batches give many steps whose graph searches + // depend on the graph, so refreshing instead of rebuilding changes results. + constexpr size_t kManyClusters = 128; + constexpr size_t kPerCluster = 16; + constexpr size_t kPoints = kManyClusters * kPerCluster; + std::mt19937 rng(11); + std::normal_distribution normal; + std::vector data(kPoints * kDim); + std::generate(data.begin(), data.end(), [&] { return normal(rng); }); + const auto train = [&](uint32_t gap, uint32_t threads) { + QGEMeansParameters parameters = small_parameters(threads); + parameters.batch_size = 64; + parameters.max_rebuild_gap = gap; + auto model = std::make_unique(kDim, kManyClusters, parameters); + model->train(kPoints, data.data()); + return model; + }; + const auto every = train(1, 1); + const auto spaced = train(8, 1); + EXPECT_NE(spaced->centroids, every->centroids); + EXPECT_LT(spaced->final_obj, every->final_obj * 1.02); + for (size_t point = 0; point < kPoints; ++point) { + EXPECT_LT(spaced->assignments[point], kManyClusters); + } + const auto parallel = train(8, 4); + EXPECT_EQ(parallel->centroids, spaced->centroids); + EXPECT_EQ(parallel->assignments, spaced->assignments); + EXPECT_EQ(parallel->distances, spaced->distances); +} + +TEST(QGEMeansAssignmentTest, RefreshSearchesTheMovedCentroids) { + const auto data = clustered_data(); + std::vector centroids(data.begin(), data.begin() + kClusters * kDim); + const QGEMeansParameters parameters = small_parameters(); + detail::QGEAssignment assignment( + kDim, kClusters, data.data(), kCount, parameters.num_threads, parameters + ); + assignment.prepare(centroids.data()); + std::mt19937 rng(5); + std::normal_distribution shift(0.0F, 0.5F); + for (float& value : centroids) { + value += shift(rng); + } + assignment.refresh(centroids.data()); + std::vector assignments(kCount); + std::vector distances(kCount); + std::vector second_distances(kCount); + assignment.assign_batch( + nullptr, kCount, assignments.data(), distances.data(), second_distances.data() + ); + for (size_t point = 0; point < kCount; ++point) { + ASSERT_LT(assignments[point], kClusters); + const double expected = squared_distance( + data.data() + point * kDim, centroids.data() + assignments[point] * kDim + ); + EXPECT_NEAR(distances[point], expected, 1e-3 * (1.0 + expected)) << point; + EXPECT_LE(distances[point], second_distances[point]) << point; + } +} + TEST(QGEMeansTest, IsDeterministicAcrossGraphBuildThreadCounts) { // From k = 256 the centroid graph builds with up to k / 128 threads. constexpr size_t kManyClusters = 256; diff --git a/tests/unit/rabitqlib/index/qg_test.cpp b/tests/unit/rabitqlib/index/qg_test.cpp index 53819733..24587b6c 100644 --- a/tests/unit/rabitqlib/index/qg_test.cpp +++ b/tests/unit/rabitqlib/index/qg_test.cpp @@ -89,6 +89,20 @@ struct QGConstructionTestAccess { graph.padded_dim_ = round_up_to_multiple(graph.dim_, 64); graph.initialize(); } + // Pending neighbor scores that differ from the distance at the current positions. + static size_t stale_scores(QGBuilder& builder) { + size_t stale = 0; + for (PID id = 0; id < builder.num_points_; ++id) { + for (const auto& neighbor : builder.new_neighbors_[id]) { + const float current = build_distance(builder, id, neighbor.id); + if (std::abs(neighbor.distance - current) > + 1e-4F * std::max(1.0F, std::abs(current))) { + ++stale; + } + } + } + return stale; + } static float build_distance(QGBuilder& builder, PID source_id, PID target_id) { QGBuilder::BuildQuery query(builder.qg_, builder.build_cache()); query.reset(source_id); @@ -183,6 +197,16 @@ struct QGConstructionTestAccess { } return result; } + static std::vector neighbor_ids(const QuantizedGraph& graph) { + std::vector result; + for (PID id = 0; id < graph.max_elements_; ++id) { + const auto row = graph.get_neighbors(id); + for (size_t slot = 0; slot < graph.max_degree_; ++slot) { + result.push_back(row[slot]); + } + } + return result; + } static void fill_storage(QuantizedGraph& graph, float value) { std::fill(graph.data_.begin(), graph.data_.end(), value); } @@ -843,6 +867,161 @@ TEST(QgConstructionTest, CachedResetMatchesFreshConstruction) { } } +TEST(QgConstructionTest, RefreshMovesVerticesAndKeepsEdges) { + constexpr size_t kCount = 41; + constexpr size_t kEfBuild = 40; + for (bool cache : {false, true}) { + for (size_t dim : {65U, 1025U}) { + for (auto metric : {METRIC_L2, METRIC_IP}) { + for (size_t threads : {1U, 3U}) { + SCOPED_TRACE( + ::testing::Message() + << cache << "/" << dim << "/" << metric << "/" << threads + ); + std::mt19937 rng(123); + std::normal_distribution normal; + std::vector original(kCount * dim); + std::generate(original.begin(), original.end(), [&] { + return normal(rng); + }); + // Each vertex takes the next one's position, plus noise, so the + // vertex nearest the mean, the entry point, changes. + std::vector moved(original.size()); + for (size_t id = 0; id < kCount; ++id) { + const size_t source = (id + 1) % kCount; + for (size_t j = 0; j < dim; ++j) { + moved[id * dim + j] = + original[source * dim + j] + 0.2F * normal(rng); + } + } + QuantizedGraph graph( + kCount, dim, 32, metric, RotatorType::FhtKacRotator, 0, 42 + ); + QGBuilder builder( + graph, + kEfBuild, + original.data(), + threads, + QGInitialization::PiPNN, + 42, + cache + ); + builder.build(); + const auto built_rows = QGConstructionTestAccess::rows(graph); + const auto edges = QGConstructionTestAccess::neighbor_ids(graph); + + // Re-encoding the built vectors reproduces the built rows. + builder.refresh(original.data()); + EXPECT_EQ(QGConstructionTestAccess::rows(graph), built_rows); + + const PID built_entry = graph.entry_point(); + builder.refresh(moved.data()); + EXPECT_EQ(QGConstructionTestAccess::neighbor_ids(graph), edges); + // The entry point is the one a build over the moved vectors picks. + QuantizedGraph fresh( + kCount, dim, 32, metric, RotatorType::FhtKacRotator, 0, 42 + ); + QGBuilder fresh_builder( + fresh, kEfBuild, moved.data(), 1, QGInitialization::PiPNN, 42 + ); + EXPECT_NE(graph.entry_point(), built_entry); + EXPECT_EQ(graph.entry_point(), fresh.entry_point()); + const auto stored = QGConstructionTestAccess::codes(graph); + ASSERT_EQ(stored.size(), moved.size() * sizeof(float)); + EXPECT_EQ(std::memcmp(stored.data(), moved.data(), stored.size()), 0); + EXPECT_NE(QGConstructionTestAccess::rows(graph), built_rows); + EXPECT_EQ(graph.num_points(), kCount); + + builder.refresh(original.data()); + EXPECT_EQ(QGConstructionTestAccess::rows(graph), built_rows); + EXPECT_EQ(graph.entry_point(), built_entry); + } + } + } + } +} + +TEST(QgConstructionTest, RefineAfterRefreshScoresTheMovedVertices) { + constexpr size_t kCount = 41; + constexpr size_t kDim = 65; + for (bool cache : {false, true}) { + SCOPED_TRACE(cache); + std::mt19937 rng(7); + std::normal_distribution normal; + std::vector original(kCount * kDim); + std::generate(original.begin(), original.end(), [&] { return normal(rng); }); + std::vector moved(original.size()); + for (size_t id = 0; id < kCount; ++id) { + for (size_t j = 0; j < kDim; ++j) { + moved[id * kDim + j] = original[((id + 1) % kCount) * kDim + j]; + } + } + QuantizedGraph graph( + kCount, kDim, 32, METRIC_L2, RotatorType::FhtKacRotator, 0, 42 + ); + QGBuilder builder( + graph, 40, original.data(), 1, QGInitialization::PiPNN, 42, cache + ); + builder.build(); + builder.refresh(moved.data()); + EXPECT_EQ(QGConstructionTestAccess::stale_scores(builder), 0U); + builder.refine(); + EXPECT_EQ(QGConstructionTestAccess::stale_scores(builder), 0U); + } +} + +TEST(QgConstructionTest, RefreshRejectsUnbuiltQuantizedAndInvalidInput) { + constexpr size_t kCount = 41; + constexpr size_t kDim = 65; + std::mt19937 rng(7); + std::normal_distribution normal; + std::vector data(kCount * kDim); + std::generate(data.begin(), data.end(), [&] { return normal(rng); }); + + QuantizedGraph graph( + kCount, kDim, 32, METRIC_L2, RotatorType::FhtKacRotator, 0, 42 + ); + QGBuilder builder(graph, 40, data.data(), 1, QGInitialization::PiPNN, 42); + EXPECT_THROW(builder.refresh(data.data()), std::logic_error); + builder.build(); + const auto built_rows = QGConstructionTestAccess::rows(graph); + + EXPECT_THROW(builder.refresh(nullptr), std::invalid_argument); + std::vector invalid = data; + invalid[3] = std::numeric_limits::quiet_NaN(); + EXPECT_THROW(builder.refresh(invalid.data()), std::invalid_argument); + // Rejected input leaves the built graph unchanged and searchable. + EXPECT_EQ(QGConstructionTestAccess::rows(graph), built_rows); + EXPECT_EQ(graph.num_points(), kCount); + + QuantizedGraph quantized( + kCount, kDim, 32, METRIC_L2, RotatorType::FhtKacRotator, 4, 42 + ); + QGBuilder quantized_builder(quantized, 40, data.data(), 1, QGInitialization::PiPNN, 42); + quantized_builder.build(); + EXPECT_THROW(quantized_builder.refresh(data.data()), std::logic_error); + + // Rows the builder did not write: another builder's build, or a loaded file. + QGBuilder other(graph, 40, data.data(), 1, QGInitialization::Random, 42); + other.build(); + EXPECT_THROW(builder.refresh(data.data()), std::logic_error); + EXPECT_NO_THROW(other.refresh(data.data())); + const rabitq_test::TempFile file("rabitq_qg_refresh.index"); + graph.save(file.path().c_str()); + graph.load(file.path().c_str()); + EXPECT_THROW(other.refresh(data.data()), std::logic_error); + try { + other.refresh(data.data()); + } catch (const std::logic_error& error) { + EXPECT_STREQ( + error.what(), "QuantizedGraph refresh requires a graph built by this builder" + ); + } + builder.reset(data.data()); + builder.build(); + EXPECT_NO_THROW(builder.refresh(data.data())); +} + TEST(QgCompatibilityTest, SupportsExplicitAndDeducedFloatTypes) { using Graph = rabitqlib::symqg::QuantizedGraph; static_assert(std::is_same_v>);