Skip to content

PRF Speed up k-means++ initialization - #23

Closed
cakedev0 wants to merge 9 commits into
mainfrom
kmeans/fast_kmeans_plusplus
Closed

cakedev0 wants to merge 9 commits into
mainfrom
kmeans/fast_kmeans_plusplus

Conversation

@cakedev0

@cakedev0 cakedev0 commented Oct 8, 2026 •

Copy link
Copy Markdown
Owner

Reference Issues/PRs

I found this while looking at why scikit-learn-intelex is much faster than scikit-learn on KMeans in scikit-learn-benchmarks: on an Intel Xeon 6787P (2 x 86 cores), the k-means++ init takes 75-97% of the time of KMeans.fit.

Related to scikit-learn#17334.

What does this implement/fix? Explain your changes.

Current implementation is slow for two reasons:

  • for float32 data, _euclidean_distances goes 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.
  • for low-dimensional data, the single-threaded numpy passes dominate (~10 ms per step for 350k x 3 samples, while the gemm takes 0.2 ms).

This PR evaluates the candidates of a step in a single OpenMP kernel (_kmeans_plusplus_trials_dense). It introduces two units of work:

  • the blocks: each thread process exactly one block
  • the chunks: it's the parallel reduction unit, and it also allows a trick in the candidates sampling which avoids np.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_origin fails 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:

  • For a given random_state, the selected centers are not the same as on main, because the cumulative sums used for sampling are different.
  • kmeans_plusplus now 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).
  • I do one BLAS call per thread rather than one per chunk of samples because many small concurrent BLAS calls scale badly with OpenBLAS (see also PRF Use bigger chunks of samples in dense Lloyd with many threads #24 for Lloyd).

AI usage disclosure

I used AI assistance for:

  • Code & Algorithm generation, A/B testing several approaches/variants: I've dug deeply into this final version but not in all the things the AI tested.
  • Test generation
  • Research and understanding (profiling)

The main things I trust:

  • existing tests
  • my benchmarks
  • from the code / the algorithm, it's easy to believe this is a good improvement

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.

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]>
- 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
Comment thread sklearn/cluster/_k_means_common.pyx Resolved
Comment thread sklearn/cluster/_k_means_common.pyx Resolved
Comment thread sklearn/cluster/_k_means_common.pyx Resolved
Comment thread sklearn/cluster/_k_means_common.pyx Resolved
- 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]>
@cakedev0

Copy link
Copy Markdown
Owner Author

Note for later, the sparse kernel (_kmeans_plusplus_trials_sparse) adds to trials_chunk_pot[j, chunk_idx] in memory for each (sample, trial) pair, while the dense kernel sums in a local pot. The loop is over samples, then trials, so a single scalar doesn't work: it would need a small per-thread buffer of n_trials sums.

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]>
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.

Numerical precision of euclidean_distances with float32

1 participant