Skip to content

ENH Add EMeans, a mini-batch k-means with EMA center updates - #46

Closed
cakedev0 wants to merge 5 commits into
mainfrom
emeans
Closed

cakedev0 wants to merge 5 commits into
mainfrom
emeans

Conversation

@cakedev0

@cakedev0 cakedev0 commented Nov 11, 2026 •

Copy link
Copy Markdown
Owner

Reference Issues/PRs

e-means was published this month by Meta FAIR (arXiv:2611.09501), with a reference implementation in faiss/contrib/e_means. There is a feature request for it upstream (scikit-learn/scikit-learn#35383, still needs triage).

What does this implement/fix? Explain your changes.

This adds EMeans, a mini-batch k-means where each center is an EMA of the samples assigned to it. The batch size and the initial step size come from scaling laws fitted by the authors, so the only parameter to choose is n_epochs. It reaches the inertia of KMeans in a few epochs instead of tens of iterations (see benchmarks).

API: EMeans(n_clusters=8, *, init="random", n_epochs=5, random_state=None). It inherits from _BaseKMeans, so predict, transform and score work as for KMeans. Fitted attributes: cluster_centers_, labels_, inertia_, batch_size_.

To keep this first version small, EMeans doesn't support sparse input, sample_weight, verbose or a user-chosen batch_size. They can be added later without breaking anything.

The algorithm follows the faiss reference implementation, including its constants, which differ slightly from the paper (they're documented in _emeans.py):

  • each step assigns the batch, then updates N_j <- (1 - a) N_j + a n_j and c_j <- ((1 - a) N_j c_j + a s_j) / N_j', with a cosine schedule on a;
  • every 5 steps, clusters with an EMA weight below 10% of the mean are revived by splitting a donor drawn proportionally to its weight;
  • the final centers are the means of the last epoch's assignments.

The Cython step (_k_means_emeans.pyx) has two parallel phases:

  1. assignment, parallel over chunks of 256 batch rows: gather the rows, one GEMM, argmin (as in Lloyd);
  2. update, parallel over centers: a counting sort of the batch by label, then each center sums its rows and applies the EMA update.

So there are no per-thread (n_clusters, n_features) buffers, and the result doesn't depend on the number of threads (tested). All parallel regions of a fit use the same number of threads, min(n_threads, ceil(batch_size / 256)).

The squared norms of the samples are only computed for init="k-means++": the step doesn't need them.

Correctness: from the same initial centers and permutations, the centers match faiss's NumpyEmeans to float32 precision (max abs diff ~6e-6 on two configs, revivals included). On a third config with k=1000, 2 of the 1000 centers differ: they are near-identical twins from a split, whose points flip at float32 precision. A unit test checks the Cython step against a NumPy implementation (float32 and float64).

Choices I'd like opinions on:

  • labels_ and inertia_ come from an extra assignment pass on the final centers, so that fit(X).labels_ == predict(X) as in KMeans. It costs about one more epoch. faiss returns the last epoch's labels for free instead.
  • No n_init, max_iter, tol or partial_fit. The paper only uses random init and a fixed budget.

No changelog entry yet, I'll add it with the upstream PR number.

AI usage disclosure

I used AI assistance for:

  • Code generation, tests, docs and benchmarks: written by Claude Code from a one-line request, including the cross-check against faiss. Not reviewed line by line yet.

Benchmarks

EMeans measured at 8242706, KMeans and faiss at a80b4cf (neither changed since). On intel-xeon, one socket (Xeon 6787P), 43 threads (OMP_NUM_THREADS=43 OPENBLAS_NUM_THREADS=43), threadpoolctl 3.8.0, float32 blobs with 2 * k true centers. Time of fit, and inertia relative to EMeans(n_epochs=5) in parentheses.

TLDR: EMeans is 6-17x faster than KMeans for the same or lower inertia, and 1.3-5x faster than faiss's NumPy implementation of e-means.

n, d, k EMeans EMeans 2 epochs KMeans faiss NumpyEmeans
200k, 64, 256 0.08 s 0.06 s (0.995) 0.52 s (1.011) 0.39 s
1M, 16, 1000 0.64 s 0.37 s (1.002) 10.6 s (1.000) 0.84 s
1M, 128, 1024 0.70 s 0.35 s (1.001) 5.24 s (1.018) 3.34 s
500k, 3, 100 0.18 s 0.12 s (1.001) 2.29 s (1.000) 0.34 s

KMeans uses init="random", n_init=1 and ran 35 to 237 iterations (its code is the same as on main). faiss is 1.15.1 with the contrib/e_means sources of faiss main, with the same batch sizes. Its time doesn't include a final labels pass.

faiss runs in a separate process: it loads an OpenMP-threaded OpenBLAS, and then sequential_blas_under_openmp doesn't limit any BLAS, so scipy's OpenBLAS runs 43 threads inside each OpenMP thread. This makes EMeans and KMeans ~10x slower in the same process. With threadpoolctl < 3.8, the same happens even without faiss (fixed by joblib/threadpoolctl#283).

Benchmark script
import time

import numpy as np

from sklearn.cluster import EMeans, KMeans
from sklearn.datasets import make_blobs

for n, d, k in [(200_000, 64, 256), (1_000_000, 16, 1000), (1_000_000, 128, 1024), (500_000, 3, 100)]:
    X, _ = make_blobs(n_samples=n, n_features=d, centers=2 * k, cluster_std=4, random_state=0)
    X = X.astype(np.float32)
    models = {
        "EMeans(n_epochs=5)": EMeans(n_clusters=k, random_state=0),
        "EMeans(n_epochs=2)": EMeans(n_clusters=k, n_epochs=2, random_state=0),
        "KMeans": KMeans(n_clusters=k, init="random", n_init=1, random_state=0),
    }
    ref = None
    for name, est in models.items():
        tic = time.perf_counter()
        est.fit(X)
        t = time.perf_counter() - tic
        ref = ref or est.inertia_
        print(f"n={n} d={d} k={k} {name}: {t:.2f} s, inertia ratio {est.inertia_ / ref:.4f}")

🤖 Generated with Claude Code

@cakedev0

Copy link
Copy Markdown
Owner Author

Fixed costs of EMeans.fit at small budgets

From kmeans-benchmarks, where EMeans (this PR at a80b4cf) runs next to faiss's NumpyEmeans with its accumulation step compiled (same algorithm and constants, but no final labels pass and no up-front row norms).

fit has two costs that don't depend on n_epochs:

  • row_norms(X, squared=True) before the first batch: for dense input it is np.einsum("ij,ij->i", X, X), single-threaded (~18 GB/s on GloVe), a full pass over X;
  • the final labels pass (_labels_inertia_threadpool_limit) for labels_ and inertia_.

At 1 or 2 epochs they are a quarter to 40% of the fit time:

dataset (n x d), k fit, 1 epoch labels pass row norms share of fit at 1 / 2 / 5 epochs
GloVe (1.18M x 200), 256 0.29 s 0.04 s 0.05 s 33% / 26% / 16%
GloVe (1.18M x 200), 1024 0.48 s 0.12 s 0.05 s 36% / 29% / 16%
SIFT (1M x 128), 256 0.20 s 0.03 s 0.03 s 30% / 24% / 16%
SIFT (1M x 128), 1024 0.30 s 0.08 s 0.03 s 35% / 29% / 15%
CLIP (1M x 512), 256 0.43 s 0.08 s 0.10 s 41% / 33% / 23%
CLIP (1M x 512), 1024 0.78 s 0.19 s 0.13 s 41% / 34% / 20%

intel-xeon, one socket (Xeon 6787P), 43 threads, threadpoolctl 3.8.0, float32, default batch_size="auto", median of 3 seeds.

Without them, EMeans at 1 epoch would be faster than the faiss-based version on GloVe and SIFT (0.20 s vs 0.26 s and 0.14 s vs 0.18 s at k=256), and close on CLIP (0.26 s vs 0.21 s). With them, it is behind at small budgets on all three.

Two possible changes:

  1. Compute the squared norms of each batch's rows inside the step (the rows are being gathered anyway, in parallel, and in cache), instead of a separate single-threaded pass over X. Or at least parallelize it.
  2. The labels pass is the open question from the description: faiss returns the last epoch's labels for free. Keeping fit(X).labels_ == predict(X) costs 15 to 25% of a 1-epoch fit here.

🤖 Generated with Claude Code

The full single-threaded row_norms pass over X before the fit is now only
done for k-means++ init.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cakedev0

Copy link
Copy Markdown
Owner Author

Compute the squared norms of each batch's rows inside the step

Done in 1b32e04: each chunk computes the norms of its gathered rows, and the full row_norms pass only runs for init="k-means++". Same centers as before, and 1.11-1.24x faster fits on blobs with the shapes of GloVe, SIFT and CLIP:

n x d, k 1 epoch 2 epochs
1.18M x 200, 256 0.306 -> 0.249 s 0.381 -> 0.327 s
1.18M x 200, 1024 0.454 -> 0.397 s 0.582 -> 0.522 s
1M x 128, 256 0.202 -> 0.168 s 0.257 -> 0.231 s
1M x 128, 1024 0.310 -> 0.273 s 0.397 -> 0.352 s
1M x 512, 256 0.458 -> 0.370 s 0.568 -> 0.473 s
1M x 512, 1024 0.754 -> 0.658 s 0.942 -> 0.843 s

intel-xeon, one socket, 43 threads, threadpoolctl 3.8.0, float32, median of 4 interleaved runs in one process.

The labels pass is the open question from the description

I kept it for now, so that fit(X).labels_ == predict(X) as in KMeans.

🤖 Generated with Claude Code

Keep the first version minimal: they can be added back without breaking
anything.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread sklearn/cluster/_emeans.py Resolved
Comment thread sklearn/cluster/_emeans.py Resolved
Comment thread sklearn/cluster/_emeans.py Outdated
`n_epochs > 1`, the fractional pass comes before the last epoch, which
is always a full pass.

batch_size : int or 'auto', default='auto'

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

I'm not even sure this one is needed for a first support: we could just have the batch_size as in the paper, without giving the choice to the user.

Does changing the batch size helps in some cases?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

It does help on some datasets. On YearPredictionMSD (standardized, k=256), 2x the auto batch is faster and gets a lower inertia for 1, 2 and 5 epochs, and the auto batch is never on the Pareto front:

n_epochs auto 2x auto 4x auto
1 0.086 s, 4.44% 0.072 s, 4.37% 0.063 s, 3.33%
2 0.118 s, 2.66% 0.098 s, 2.19% 0.092 s, 2.17%
5 0.200 s, 1.72% 0.173 s, 1.48% 0.168 s, 1.65%
10 0.322 s, 1.57% 0.298 s, 1.58%

Fit time and inertia relative to the best known one (54.0966), median of 3 seeds. intel-xeon, one socket, 43 threads, float32. With 4 threads the time barely depends on the batch size, so the larger batches win there too.

On the blobs of the benchmark in the description it's a trade-off instead: 2x the auto batch is 2-25% faster, but its inertia is up to 0.6% higher (in 7 of the 8 cases).

So tuning it can gain up to ~1 point of inertia or ~15% of fit time, but finding the right value needs a sweep per dataset. faiss exposes it (batch_size=None), and adding batch_size="auto" back later doesn't break anything.

I'd remove it for the first release, as you suggest, and batch_size_ with it (it would only be informative). WDYT?

🤖 Generated with Claude Code

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

I removed the parameter in 386b30c and kept batch_size_, as you suggested.

For the record, the road network cases go the other way from YearPredictionMSD: a quarter of the auto batch does better than the auto batch at any number of epochs.

k 1/4x auto batch auto batch
256 2 epochs: 0.96 s, 0.18% 5 epochs: 1.34 s, 1.21%
10 epochs: 2.28 s, 1.04%
1024 2 epochs: 1.59 s, 1.03%
3 epochs: 2.24 s, 0.31%
5 epochs: 1.83 s, 1.15%
10 epochs: 3.30 s, 0.75%

Fit time and inertia relative to the best fit of the sweep, median of 3 seeds. intel-xeon, one socket, 43 threads, float32. Above ~1 s, the auto batch is almost never on the Pareto front. Only for 1-epoch fits do larger batches give faster fits, at a higher inertia, as on blobs. The inertia is noisy from one config to the next, so only the trend is reliable.

So the scaling law is off in both directions depending on the dataset: YearPredictionMSD wants 2-4x larger batches, road network 4-8x smaller ones. On road network, a smaller batch is ~2x faster for the same inertia. That's a good reason to add batch_size back in a follow-up, once we know how to explain to users when to change it.

🤖 Generated with Claude Code

cakedev0 and others added 2 commits November 12, 2026 09:22
Without early stopping, they follow from n_epochs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The batch size is always given by the scaling law. batch_size_ stays.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
cakedev0 added a commit to probabl-ai/scikit-learn-benchmarks that referenced this pull request Nov 12, 2026
cakedev0/scikit-learn#46 removed the parameter: the batch size always comes
from the scaling law.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
cakedev0 added a commit to probabl-ai/scikit-learn-benchmarks that referenced this pull request Nov 12, 2026
…arn@8242706

They passed batch_size, which cakedev0/scikit-learn#46 has since removed; the
reruns on 386b30c replace them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cakedev0

Copy link
Copy Markdown
Owner Author

@cakedev0 cakedev0 closed this Nov 13, 2026
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.

1 participant