Repository navigation
Conversation
Evaluate the candidates of each k-means++ step in a single OpenMP kernel (one BLAS call per thread, then the min with the closest distances and the potential per chunk of samples), instead of `_euclidean_distances` followed by several single-threaded numpy passes. The per-chunk potentials are used to sample the next candidates without a cumulative sum over all the samples. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each k-means++ step is a parallel region: for small datasets, starting and synchronizing many threads costs more than the work itself. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
cakedev0
added a commit
that referenced
this pull request
Oct 12, 2026
- Recompute small distances in the sparse kernel too, as in the dense one: a sample identical to a chosen center could be chosen again in float32 far from the origin. - Don't slice memoryviews per (sample, candidate) in the sparse kernel, it made it much slower than main with many threads. - Accept read-only sparse input, reject sparse input with 64-bit indices in kmeans_plusplus as in the estimators. - Use a lower recompute threshold in float64, recomputing is costly on data far from the origin. - Only sample candidates with a positive potential when rounding errors overshoot the potential of a chunk. Co-Authored-By: Claude Opus 5.5 <[email protected]>
cakedev0
added a commit
that referenced
this pull request
Oct 13, 2026
# Conflicts: # sklearn/cluster/_k_means_common.pyx
cakedev0
commented
Oct 13, 2026
- Pick the best candidate with np.argmin instead of a Cython function. - Sum the duplicate entries of sparse X in KMeans, MiniBatchKMeans and kmeans_plusplus: row_norms and the Cython kernels assume there are none. The sparse kernel can then copy the values of a sample instead of adding them. - Explain why the direct recomputation of small distances is accurate. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Owner
Author
|
Note for later, the sparse kernel ( Probably minor, not measured yet. |
It fixes a bug that is already on main, out of scope for this PR. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Oct 13, 2026
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Reference Issues/PRs
I found this while looking at why scikit-learn-intelex is much faster than scikit-learn on
KMeansin scikit-learn-benchmarks: on an Intel Xeon 6787P (2 x 86 cores), the k-means++ init takes 75-97% of the time ofKMeans.fit.Related to scikit-learn#17334.
What does this implement/fix? Explain your changes.
Current implementation is slow for two reasons:
_euclidean_distancesgoes through the upcast path: many float64 BLAS calls on small chunks. On sift (1M x 128) with 64 threads, it takes 365 ms vs 2.7 ms for the raw gemm, and it gets slower with more threads.This PR evaluates the candidates of a step in a single OpenMP kernel (
_kmeans_plusplus_trials_dense). It introduces two units of work:blocks: each thread process exactly one blockchunks: it's the parallel reduction unit, and it also allows a trick in the candidates sampling which avoidsnp.searchsorted(np.cumsum(w * d), r)which is single-threaded and can dominate when the rest is parallelized.Each thread does one BLAS call for its block of samples, then adds the squared norms, takes the min with the current closest distances and sums the weighted distances per chunk of 256 samples. The next candidates are sampled from these per-chunk sums (first a chunk, then a sample in that chunk), so there is no cumulative sum over all the samples anymore.
Distances smaller than 1% of
||x||² + ||c||²(1e-8 in float64) are recomputed directly, to avoid catastrophic cancellation in float32 (this is what the upcast was protecting against: it was added in scikit-learn#13554 to fix scikit-learn#9354). In particular, a sample identical to a chosen center gets a zero distance and can't be sampled again:test_kmeans_plusplus_far_from_originfails without this.Sparse input uses the same sampling and the same recomputation of small distances, with a kernel that computes
||c||² + sum((x_k - c_k)² - c_k²)over the non-zeros of x, so dense and sparse inputs still give the same centers.Some notes:
random_state, the selected centers are not the same as on main, because the cumulative sums used for sampling are different.kmeans_plusplusnow converts X to a C-contiguous float array, so integer input gives float centers (see the docstring example). It also rejects sparse input with 64-bit indices, like the estimators already do (the kernels use 32-bit indices).AI usage disclosure
I used AI assistance for:
The main things I trust:
Benchmarks
See the init columns in probabl-ai/scikit-learn-benchmarks#144
Init speed-up ranges from ~1x to 100x depending on the cases. Typical speed-up is 3x-15x I'd say.