Skip to content

PRF Reduce Lloyd's thread buffers after the parallel region - #35193

Open
cakedev0 wants to merge 11 commits into
scikit-learn:mainfrom
cakedev0:kmeans/lloyd_no_blocking_sync
Open

cakedev0 wants to merge 11 commits into
scikit-learn:mainfrom
cakedev0:kmeans/lloyd_no_blocking_sync

Conversation

@cakedev0

@cakedev0 cakedev0 commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

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), Lloyd iterations stop scaling at ~16 threads.

What does this implement/fix? Explain your changes.

Current implementation has three costs per Lloyd iteration that grow with the number of threads:

  • at the end of the parallel region, every thread adds its buffers (n_clusters * n_features values) to the result under an omp_set_lock. The pairwise distances reductions already use a similar pattern with the parallel_on_Y strategy.
  • the chunks are passed as memoryview slices (X[start:end], ...). Slicing can raise, so Cython wraps the whole with nogil, parallel(): block in PyGILState_Ensure() / PyGILState_Release(): all the threads take the GIL one after the other at the start and at the end of each iteration.
  • every thread callocs its buffers at each iteration. Above glibc's mmap threshold (32 MiB, e.g. sparse data with many features), they are new mappings each time, and their page faults dominate the iteration. For dense data, this is usually negligible.

This PR:

  • Avoids the lock by summing the thread buffers after the parallel region, without lock.
  • Avoids the memoryview slicing by passing the chunks as start / end indices instead of slices, in Lloyd and in other places.
  • Allocates the thread buffers once per fit, in _kmeans_single_lloyd (_alloc_thread_buffers: one row per thread, aligned and padded to cache lines), and passes them to each Lloyd iteration. The reduction zeroes the buffers for the next iteration, but only the cache lines that hold a non-zero value: the pages that a thread never writes to stay unmapped, as after a calloc.

The pairwise distances reductions already use this pattern with the parallel_on_Y strategy (_argkmin.pyx.tp: heaps allocated in each thread, indexed by omp_get_thread_num(), merged after the parallel region in a prange over samples without locks).

Some notes:

  • The reduction order is now fixed (by thread index), so for a given number of threads the result doesn't depend on the order in which the threads got the lock anymore.
  • The buffers of the centers aren't allocated anymore when the centers are not updated (predict).
  • Sparse with 1 thread, GCC 13 builds can be up to ~12% slower than main (Core Ultra X7 358H, 20newsgroups and RCV1): the inner loop over the non-zeros reloads the pointer to the centers from the stack at each iteration (register pressure). With GCC 16 (Xeon 6787P) and clang (M2), it's on par with main or faster. Computing the dot products with 2 centers per loop over the non-zeros removes this, but it brings nothing with threads, so I left it out.

AI usage disclosure

I used AI assistance for:

  • Code 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, and the new test against a NumPy implementation
  • my benchmarks
  • from the code, it's easy to believe this removes serial costs

Benchmarks

See probabl-ai/scikit-learn-benchmarks#154: 34 KMeans cases (sift, nytimes, fashion_mnist, road_network and CIFAR-10, plus 20newsgroups and RCV1 as CSR matrices), in float32 and float64, with init="random" and up to 100 Lloyd iterations, 5 runs per case. Dashboards: intel-xeon, intel-laptop.

cakedev0 and others added 8 commits October 10, 2026 12:51
The thread local buffers are now added to the result after the parallel
region instead of under a lock inside it, and the chunks are passed as
indices instead of memoryview slices (which made Cython acquire the GIL
in every thread at the start and end of the parallel region). Both are
serial costs that grow with the number of threads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ainst NumPy

- Move _reduce_thread_buffers to _k_means_common so that Elkan can use it,
  zero the result in it, sum the buffers with flat loops, and call it
  without the GIL.
- Raise MemoryError if the arrays of buffer pointers can't be allocated.
- Get the thread index with omp_get_thread_num from _openmp_helpers.
- Check one Lloyd iteration against a NumPy implementation, so that the
  test also fails when the reduction is wrong for both dense and sparse.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The sum of the n_threads buffers of n_clusters * n_features values is done
by blocks in a prange, with the same team size as the Lloyd region. The
buffers of the centers are not allocated when update_centers is False.

The test limits BLAS to 1 thread as in KMeans.fit, and uses more samples
and clusters so that it still covers several chunks per thread with bigger
chunks, and several blocks in the reduction.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Slicing the sparse rows made Cython take the GIL in every thread of the
parallel region. _euclidean_sparse_dense now takes start/end indices, which
also removes it from Elkan's init_bounds_sparse.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test now covers float32 and the predict path (no buffers).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The thread buffers are allocated once per fit instead of at each iteration.
Buffers larger than glibc's mmap threshold (32 MiB) were new mappings at each
iteration, and their page faults dominated sparse Lloyd with many threads.

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

Copy link
Copy Markdown

This PR exceeds the recommended size of 500 lines changed. Consider splitting it into smaller PRs to ease the review process. Please make sure you read our Contributing guide and in particular our Pull Request guidelines

…cking_sync

# Conflicts:
#	sklearn/cluster/_k_means_common.pyx
#	sklearn/cluster/tests/test_k_means.py
cakedev0 added a commit to cakedev0/my-scikit-learn-backlog that referenced this pull request Nov 3, 2026
done: HGB: get [sklearn#35216](scikit-learn/scikit-learn#35216) merged (binning crash on all-missing features, fixes [sklearn#35164](scikit-learn/scikit-learn#35164)), merged before I removed it
done: Trees: get [sklearn#34554](scikit-learn/scikit-learn#34554) merged (recursion PDP on categorical features)
drop: Threads: answer lesteve on [sklearn#35105](scikit-learn/scikit-learn#35105) (RFC deprecate `pre_dispatch`)
drop: Maintenance: follow up on [sklearn#35209](scikit-learn/scikit-learn#35209) (newton-cg test failing on the macOS x86_64 wheels)
drop: Benchmarks: review [benchmarks#142](probabl-ai/scikit-learn-benchmarks#142) (cuML benchmark config)
drop: Threads: review [sklearn#34729](scikit-learn/scikit-learn#34729) (inference methods don't modify the estimator)
drop: Linear: [sklearn#34793](scikit-learn/scikit-learn#34793) (Ridge centering trick for cholesky), benchmarks in [benchmarks#115](probabl-ai/scikit-learn-benchmarks#115) and [benchmarks#31](probabl-ai/scikit-learn-benchmarks#31)
drop: Upstream: sklearnex reports [sklearnex#3402](uxlfoundation/scikit-learn-intelex#3402), [sklearnex#3377](uxlfoundation/scikit-learn-intelex#3377), [sklearnex#3220](uxlfoundation/scikit-learn-intelex#3220)
drop: Upstream: [data-apis/array-api#976](data-apis/array-api#976) (why `stable=True` is the default for `xp.sort`)
drop: Upstream: dpnp reports [IntelPython/dpnp#3149](IntelPython/dpnp#3149) and [IntelPython/dpnp#3148](IntelPython/dpnp#3148)
drop: Threads: [sklearn#34736](scikit-learn/scikit-learn#34736) (oversubscription in `pairwise_distances`), out of the reported findings item
drop: KMeans: benchmarks [benchmarks#154](probabl-ai/scikit-learn-benchmarks#154), [benchmarks#160](probabl-ai/scikit-learn-benchmarks#160), [OpenBLAS#6105](OpenMathLib/OpenBLAS#6105) and [sklearn#17334](scikit-learn/scikit-learn#17334), out of the [sklearn#35193](scikit-learn/scikit-learn#35193) item
todo: move [joblib#1899](joblib/joblib#1899), [sklearn#35261](scikit-learn/scikit-learn#35261) and [sklearn#35053](scikit-learn/scikit-learn#35053) from Reviews to Now, [sklearn#35181](scikit-learn/scikit-learn#35181) to the top of Waiting (by hand in 03835dd)

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

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant