Repository navigation
Conversation
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]>
… team 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 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 |
This was referenced Oct 26, 2026
Draft
…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
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), 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:
n_clusters * n_featuresvalues) to the result under anomp_set_lock. The pairwise distances reductions already use a similar pattern with theparallel_on_Ystrategy.X[start:end], ...). Slicing can raise, so Cython wraps the wholewith nogil, parallel():block inPyGILState_Ensure()/PyGILState_Release(): all the threads take the GIL one after the other at the start and at the end of each iteration.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:
start/endindices instead of slices, in Lloyd and in other places._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 acalloc.The pairwise distances reductions already use this pattern with the
parallel_on_Ystrategy (_argkmin.pyx.tp: heaps allocated in each thread, indexed byomp_get_thread_num(), merged after the parallel region in aprangeover samples without locks).Some notes:
AI usage disclosure
I used AI assistance for:
The main things I trust:
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.