Skip to content

feat(k-means): Add e-means solver - #493

Open
ahuber21 wants to merge 2 commits into
dev/ahuber/pq-upstreamfrom
dev/ahuber/emeans
Open

ahuber21 wants to merge 2 commits into
dev/ahuber/pq-upstreamfrom
dev/ahuber/emeans

Conversation

@ahuber21

@ahuber21 ahuber21 commented Dec 1, 2026

Copy link
Copy Markdown
Member

Adds e-means (svs::kmeans::emeans_train, svs/core/kmeans_emeans.h): mini-batch k-means with EMA centroid updates,
a cosine-annealed step, dead-cluster revival and the batch-size/step scaling laws of Bessa et al., arXiv:2611.09501
(Algorithm 1). It reuses the assignment and init code that the previous PR moved into svs/core/kmeans_training.h.

Things a reviewer should know:

  • Stacked on the PQ PR. Base is the PQ branch; the diff here is two files. It needs kmeans_training.h, which the
    PQ PR introduces.
  • No caller yet. Nothing in the tree uses emeans_train; it is covered by unit tests only. PQ training still
    uses the existing k-means.
  • Choices where the paper is silent are commented in the header (tail batch is trained, power-of-two rounding in
    log2 space, delta = 2^-7). epochs defaults to 2, an SVS choice, not the paper's. The scaling laws were fitted on DEEP
    (L2, 256 <= k <= 65536) and are applied as published outside that range.

@ahuber21
ahuber21 changed the base branch from main to dev/ahuber/pq-upstream December 1, 2026 07:36
@ahuber21
ahuber21 added this pull request to stack #495 December 1, 2026 07:36
@ahuber21
ahuber21 removed this pull request from stack #495 December 1, 2026 08:27
@ahuber21
ahuber21 added this pull request to stack #497 December 1, 2026 08:28

@mihaic mihaic left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The attribution and citation look good to me.

ahuber21 and others added 2 commits December 2, 2026 02:25
svs::kmeans::emeans_train in svs/core/kmeans_emeans.h implements Algorithm 1
of Bessa et al., arXiv:2611.09501:
- EMA per-cluster counts and sums (centroid = S / N), with a 1-based batch
  counter as in Algorithm 1.
- A cosine-annealed step from alpha0 down to 0.1 * alpha0.
- Batch size and alpha0 from the paper's Table 2 scaling laws when unset,
  including the /8 batch law above n = 2M.
- Dead-cluster revival by splitting every 5 batches at tau = 0.1.
- A final pass that sets each centroid to the mean of its last-epoch points.

It reuses centroid_assignment, generate_norms and init_centroids from
kmeans_training.h. Assignment runs in chunks of at most assignment_chunk rows,
so the score buffer is assignment_chunk x k floats rather than B x k. The
state (k * d double sums, k counts) and all scratch are allocated once.
Revival costs O(k + dead * log k) per round.

Deviations and readings where the paper is silent are commented in the code:
- the tail batch is trained;
- power-of-two rounding is done in log2 space;
- the donor pool excludes this round's dead clusters;
- delta = 2^-7;
- epochs defaults to 2, an SVS choice.

The scaling laws were fitted on DEEP (L2, 256 <= k <= 65536). Outside that
range they are applied as published.

The returned objective is the MSE of the final centroids. Tests cover:
determinism; revival of a forced-dead cluster; the scaling laws against
hand-computed values; a tail batch; the k > n error and the other parameter
checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The e-means paper's authors publish a reference implementation in Faiss (contrib/e_means),
so kmeans_emeans.h may contain portions derived from it. Add the file to the Faiss entry in
THIRD-PARTY-PROGRAMS and point to it from the header; the paper citation stays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mihaic
mihaic requested a balanced review from Copilot December 3, 2026 19:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Copilot review overview

6 open issues
What changed in this PR

Adds an e-means (mini-batch k-means with EMA centroid updates + dead-cluster revival) training API and accompanying unit tests, leveraging existing assignment/init utilities from kmeans_training.h.

Changes:

  • Introduces svs::kmeans::emeans_train (two overloads) plus parameter resolution utilities in a new public header.
  • Adds Catch2 unit tests covering determinism, objective skipping, dead-cluster revival, scaling-law resolution, tail batches, and error cases.
  • Updates third-party attribution to include the new header as potentially derived from Faiss.
File Description
tests/​svs/​core/​kmeans_training.cpp Adds unit tests validating the new e-means training behavior and parameter resolution.
include/​svs/​core/​kmeans_emeans.h Implements the e-means training API, scaling-law parameter resolution, revival logic, and objective computation.
THIRD-PARTY-PROGRAMS Extends Faiss attribution to cover the new header.

Review effort: Lite

Comment on lines +458 to +468
resolve_emeans_parameters(size_t n, size_t k, const EMeansParameters& parameters) {
size_t batch_size = std::clamp(
parameters.batch_size.value_or(detail::resolve_batch_size(n, k, parameters.epochs)),
size_t{1},
n
);
double alpha0 = parameters.alpha0.value_or(
detail::resolve_alpha0(n, k, batch_size, parameters.epochs)
);
return ResolvedEMeansParameters{batch_size, alpha0};
}
Comment on lines +559 to +567
// Scratch buffers sized once and reused for every batch; chunk_matmul_results is
// capped at chunk_size rows, not batch_size (B from the scaling law can be huge).
auto centroids_fp32 = data::SimpleData<float>(k, dims);
auto gathered = data::SimpleData<float>(batch_size, dims);
auto chunk_matmul_results = data::SimpleData<float>(chunk_size, k);
std::vector<float> chunk_norm_scratch(chunk_size);
std::vector<size_t> chunk_assignments(chunk_size);
std::vector<float> centroids_norm(k);
std::vector<size_t> local_assignments(batch_size);
Comment on lines +110 to +119
inline size_t resolve_batch_size(size_t n, size_t k, size_t epochs) {
double b_c = n > EMEANS_BATCH_LARGE_N_THRESHOLD ? EMEANS_BATCH_COEFF_LARGE_N
: EMEANS_BATCH_COEFF_SMALL_N;
double raw = b_c * std::pow(static_cast<double>(k), EMEANS_BATCH_EXP_K) *
std::pow(static_cast<double>(n), EMEANS_BATCH_EXP_N) *
std::pow(static_cast<double>(epochs), EMEANS_BATCH_EXP_T);
double pow2 = std::pow(2.0, std::round(std::log2(std::max(raw, 1.0))));
size_t b = static_cast<size_t>(std::min(pow2, static_cast<double>(n)));
return std::clamp(b, size_t{1}, n);
}
Comment on lines +487 to +494
EMeansResult emeans_train(
const EMeansParameters& parameters,
Data& data,
data::SimpleData<float> initial_centroids,
std::mt19937& rng,
Pool& threadpool,
lib::Timer& timer
) {
Comment on lines +758 to +765
EMeansResult emeans_train(
const EMeansParameters& parameters,
Data& data,
size_t num_clusters,
std::mt19937& rng,
Pool& threadpool,
lib::Timer& timer
) {
Comment on lines +405 to +419
CATCH_SECTION("k > n throws") {
auto data = svs::data::SimpleData<float>(3, 2);
data.set_datum(0, std::vector<float>{0.0F, 0.0F});
data.set_datum(1, std::vector<float>{1.0F, 0.0F});
data.set_datum(2, std::vector<float>{0.0F, 1.0F});

auto parameters = small_emeans_parameters();
auto rng = std::mt19937(0xc0ffee);
auto threadpool = svs::threads::as_threadpool(2);
auto timer = svs::lib::Timer();

CATCH_REQUIRE_THROWS(
svs::kmeans::emeans_train(parameters, data, size_t{5}, rng, threadpool, timer)
);
}

@mihaic mihaic left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please have a look at the Copilot suggestions which look reasonable to me.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants