Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions docs/docs/clustering.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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.
Expand Down
81 changes: 75 additions & 6 deletions include/rabitqlib/clustering/detail/emeans.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<double>(step) / static_cast<double>(std::max<size_t>(1, total_steps));
if (progress < kRebuildWarmup) {
return 1;
}
const double grown = (progress - kRebuildWarmup) / (1.0 - kRebuildWarmup);
return 1 + static_cast<size_t>((grown * static_cast<double>(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
) {
Expand Down Expand Up @@ -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
Expand All @@ -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;
Expand Down Expand Up @@ -630,6 +688,7 @@ class EMeans : public Parameters {
std::vector<size_t> order(n);
std::vector<float> 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(
Expand All @@ -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,
Expand All @@ -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;
Expand Down Expand Up @@ -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);
}

Expand Down
8 changes: 8 additions & 0 deletions include/rabitqlib/clustering/detail/qg_assigner.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
20 changes: 17 additions & 3 deletions include/rabitqlib/clustering/qgemeans.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<QGEMeansParameters, detail::QGEAssignment> {
using Base = detail::EMeans<QGEMeansParameters, detail::QGEAssignment>;
Expand Down
3 changes: 3 additions & 0 deletions include/rabitqlib/index/symqg/qg.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,9 @@ class QuantizedGraph<float> {
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.
Expand Down
13 changes: 12 additions & 1 deletion include/rabitqlib/index/symqg/qg_builder.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ class QGBuilder {
static constexpr size_t kLockStripes = 4096;
std::vector<CandidateList> new_neighbors_; // new neighbors for current iteration
std::vector<uint32_t> 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<BuildCache> cache_;
std::vector<CandidateList> reverse_buffer_;
struct BuildWorker {
Expand Down Expand Up @@ -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();
Expand Down
12 changes: 10 additions & 2 deletions python_bindings/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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


Expand Down
Loading
Loading