Skip to content

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

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

cakedev0 wants to merge 9 commits into
mainfrom
kmeans/lloyd_no_blocking_sync

Conversation

@cakedev0

@cakedev0 cakedev0 commented Oct 9, 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), 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.

Speed-up of the Lloyd time (lloyd_time, main / this PR, medians of the 5 runs, as in the dashboards), over the 34 cases:

machine BLAS (threads) min median max
Xeon 6787P, one socket OpenBLAS (64) 1.32 3.90 28.8
MKL (86) 1.42 5.65 18.6
Core Ultra X7 358H laptop OpenBLAS (16) 0.92 1.00 4.28
MKL (16) 0.78 0.99 4.02

On the laptop, the gains are on 20newsgroups and RCV1 in float64, where the thread buffers are large. The other cases are within the run-to-run spread, which is 10-50% on this laptop. The 0.78 is RCV1 in float32: its median fit runs 59 iterations instead of 52 (the float32 sums are in a different order), and the time per iteration is the same.

@cakedev0
cakedev0 force-pushed the kmeans/lloyd_no_blocking_sync branch from 7ba635c to d615355 Compare October 10, 2026 10:21
@cakedev0 cakedev0 changed the title PRF Avoid blocking synchronization inside Lloyd's parallel loops PRF Reduce Lloyd's thread buffers after the parallel region Oct 10, 2026
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]>
Comment thread sklearn/cluster/_k_means_lloyd.pyx Resolved
cakedev0 and others added 4 commits October 12, 2026 16:55
…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]>
cakedev0 added a commit to probabl-ai/scikit-learn-benchmarks that referenced this pull request Oct 19, 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