You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
KMeans(init='k-means++') performance issue with OpenBLAS #17334
I tried to run this on Linux with scikit-learn master (therefore including the #16499 fix) with 2 different builds of scipy (with openblas from pypi and MKL from anaconda) and various values for OMP_NUM_THREADS (unset, OMP_NUM_THREADS=1, OMP_NUM_THREADS=2, OMP_NUM_THREADS=4) on a laptop with 2 physical cpu cores (4 logical cpus).
In both cases, I use the same scikit-learn binaries (built with GCC in editable mode). I just change the env.
The summary is:
with MKL there is no problem: large or unset values of OMP_NUM_THREADS are faster than OMP_NUM_THREADS=1;
with OpenBLAS without explicit setting of OMP_NUM_THREADS or setting a large value for it is significanlty slower forced sequential run with OMP_NUM_THREADS=1.
As @jeremiedbb said during the core dev meeting, it might be caused by openblas that tries to use 4 threads on 2 physical cores / 4 logical core which is not an optimal strategy.
This might be related to OpenMathLib/OpenBLAS#1881 although the above benchmarks would need to rerun to control the size of the outer OpenMP and inner OpenBLAS loops to understand exactly what's going on.
Not exactly. The BLAS is always limited to 1 thread. Setting OMP_NUM_THREADS will impact the openmp loop (over data chunks). On my laptop I observe like you that using logical cores is detrimental with OpenBLAS (also with MKL but way less). I don't understand why changing the BLAS makes a difference since it should be single threaded (I checked that it's effectively single threaded).
I agree. Maybe the CPU cache usage pattern of OpenBLAS is different. Or maybe the inner BLAS is not limited to 1 thread as it's supposed to be when we use OpenBLAS.
Hum I just tried your snipped while setting OPENBLAS_NUM_THREADS and there's a big difference when I don't set it and I set it to 1, which seems to indicate that openblas is actually not properly limited to 1.
Actually it's k-means++ init faults ! it scales poorly, especially using hyperthreads.
The timings are back to expected when you set the init to 'random', meaning that the openmp loop and the inner blas are properly controlled.
Maybe you can turn this issue into a k-means++ issue ?
I think so but it might be more specific. In k-means++ the matrix multiplication is (n_candidates, n_features) x (n_samples, n_features) and the number of candidates is a small number (~log(n_clusters)). It's possible that mkl is better at optimizing the matrix multiplication where 1 dimension is much smaller than the other one.
A supposedly scalable alternative to k-means++ is k-means|| (#4357). However proper benchmarking of the DAAL implementation would be needed to tell what would be the actual benefit of implementing this alternative in scikit-learn.
I tried again today on a laptop with 4 P-cores, 8 E-cores and 4 LP-cores and the results are the following (using OpenMP variant of OpenBLAS installed from conda-forge):
$ mamba install "libblas=*=*_mkl"
$ mamba list blas
List of packages in environment: "/home/ogrisel/miniforge3/envs/dev"
Name Version Build Channel
────────────────────────────────────────────────────────
libblas 3.11.0 7_h5875eb1_mkl conda-forge
libcblas 3.11.0 7_hfef963f_mkl conda-forge
libopenblas 0.3.33 openmp_hd680484_0 conda-forge
openblas 0.3.33 openmp_hd77311e_0 conda-forge
$ mamba list mkl
List of packages in environment: "/home/ogrisel/miniforge3/envs/dev"
Name Version Build Channel
───────────────────────────────────────────────────────
mkl 2026.0.0 h0e700b2_915 conda-forge
onemkl-license 2026.0.0 hf2ce2f3_915 conda-forge
$ python kmeanspp_threads.py
[{'filepath': '/home/ogrisel/miniforge3/envs/dev/lib/libmkl_rt.so.3',
'internal_api': 'mkl',
'num_threads': 16,
'prefix': 'libmkl_rt',
'threading_layer': 'intel',
'user_api': 'blas',
'version': '2026.0-Product'},
{'filepath': '/home/ogrisel/miniforge3/envs/dev/lib/libomp.so',
'internal_api': 'openmp',
'num_threads': 16,
'prefix': 'libomp',
'user_api': 'openmp',
'version': None}]
Total duration: 4.083 s
(dev) ogrisel@xps-ultra-x7:~$ OMP_NUM_THREADS=4 python kmeanspp_threads.py
[{'filepath': '/home/ogrisel/miniforge3/envs/dev/lib/libmkl_rt.so.3',
'internal_api': 'mkl',
'num_threads': 4,
'prefix': 'libmkl_rt',
'threading_layer': 'intel',
'user_api': 'blas',
'version': '2026.0-Product'},
{'filepath': '/home/ogrisel/miniforge3/envs/dev/lib/libomp.so',
'internal_api': 'openmp',
'num_threads': 4,
'prefix': 'libomp',
'user_api': 'openmp',
'version': None}]
Total duration: 1.113 s
So there is still a bit of a slowdown when using one thread per core for either BLAS implementation, but this is not as bad as in the past (probably because of the fix of OpenMathLib/OpenBLAS#1881)
Still, being able to automatically adjust to tune the of threads to the number of P-cores would probably be beneficial. (see: joblib/loky#630).
The "active wait overhead" problem does not seem to be as bad as observed in the past. However, if it happens to be a problem for specific runtimes / workload combinations, a possible remediation might be to pursue the work proposed in #28883.
However, just limiting the number of threads of OpenMP while keeping active wait also fixes the problem and also the oversubscription problem and allows us to recover optimal performance:
I don't understand why we get the 70s duration on the default venv built with uv from pypi.org packages but does not happen when installing seemingly the same packages with similar threading layer config using conda-forge instead.
I also tried setting OPENBLAS_NUM_THREADS=4 only and contrary to the case where packages come from conda forge, the OpenMP runtime stays at 16 threads and we observe the catastrophic performance degradation.
Also, when installing packages from pypi.org we get libgomp (the OpenMP runtime implementation from the GCC toolchain) while conda-forge ships libomp (the one from the LLVM toolchain). So the active wait problem seems to be libgomp specific and related to oversubscription at the OpenMP level.
[I investigated this with codex, and I find the source of the specific PyPi slowdown, it's pretty interesting]
I ran a controlled PyPI-vs-conda comparison where scikit-learn came either from the PyPI wheel or from conda-forge, while BLAS was the same OpenBLAS pthreads build. The main difference I found is the OpenMP runtime used by scikit-learn:
PyPI scikit-learn loads its bundled scikit_learn.libs/libgomp-e985bcbb.so.1.0.0, apparently GCC/libgomp 8.5.0, with GOMP_SPINCOUNT=300000 by default.
conda-forge scikit-learn loads the environment libgomp.so.1.0.0, apparently GCC/libgomp 15.2.0, with GOMP_SPINCOUNT=1 by default.
In both cases OMP_WAIT_POLICY was reported as PASSIVE.
This seems to explain a large part of the PyPI-only slowdown. In a small custom reproducer with a direct OpenMP kernel interleaved with direct BLAS dgemm calls, the one-CPU case was basically identical, but the multi-CPU case was much slower with the PyPI runtime. Overriding the spin count was decisive:
GOMP_SPINCOUNT=1 ... # makes the PyPI/libgomp-8 case behave like conda
GOMP_SPINCOUNT=300000 ... # makes the conda/libgomp-15 case slow in the mixed workload
So this does not look like only a BLAS thread-count issue or classic nested oversubscription. It looks more like an active-wait / spin-wait interaction between OpenBLAS pthread workers and the libgomp worker pool, amplified by repeated short BLAS/OpenMP phases as in k-means++.
There is a tradeoff: GOMP_SPINCOUNT=300000 is faster for many tiny back-to-back OpenMP-only regions, while GOMP_SPINCOUNT=1 is much better for mixed BLAS/OpenMP workloads. But for the k-means++ pattern discussed here, the lower spin count seems to be the better default/workaround.
A practical workaround to test is therefore:
GOMP_SPINCOUNT=1 python kmeanspp_threads.py
Conclusion: This suggests that the PyPI wheel's bundled libgomp default behavior / version could be part of the problem, independently of the OpenBLAS version itself.
Spoiler: I continued investigating in this direction, and the libgomp we bundle in the PyPI wheel is very old, it comes from GCC 8.5 which is from 2003. Edit: it's from 2021 (still a bit old, and it still kinda a bug as it should rather come from GCC 14).
I checked GOMP_SPINCOUNT on an AMD EPYC 9555P 64-Core Processor for the libgomp coming with conda (gcc 15.2), it's 300k, which is indeed supposed to be the default expect for hybrid CPUs (laptops), see #34437 (comment)) . So CPUs servers probably experience very bad performances for this example, for any build of scikit-learn with libgomp and openblas pthreads. I'll soon-ish have benchmarks for that, so we'll see.
With openBLAS-pthreads + LLVM openMP, KMP_BLOCKTIME doesn't affect wall time of this script, it remains fast (it does affect the CPU usage though). To me, this means LLVM openMP active wait implementation is "less dangerous" than the libgomp one.
I ran more experiments on 3 machines to understand this slowdown. TLDR: there are two different problems, and which one dominates depends on the CPU:
on a server CPU, it's what we described above: the multithreaded OpenBLAS calls of the k-means++ init next to libgomp's actively waiting threads.
on hybrid laptop CPUs, it's mostly something else: threads that block (lock, GIL, something inside OpenBLAS) inside a parallel region while the other threads actively wait. It happens even with OPENBLAS_NUM_THREADS=1.
Both go away if libgomp's spinning threads call sched_yield() from time to time, which is what LLVM's libomp does. So I think the fix belongs upstream rather than in scikit-learn.
Machines: Intel Xeon 6787P (2 x 86 cores, GCC 16 libgomp), Intel Core Ultra 5 225H (14 cores: 4P + 8E + 2LPE) and Intel Core Ultra X7 358H (16 cores: 4P + 8E + 4LPE), both with GCC 13 libgomp. All the dev builds use the OpenBLAS pthreads build from the numpy/scipy wheels. Timings are for the reproducer from the first message unless stated otherwise.
Server CPU: the OpenBLAS + OpenMP oversubscription explanation holds. Pinned to 14 cores of the Xeon (taskset -c 0-13) with 14 threads, the reproducer takes 19 s on main. With a k-means++ init that doesn't call multithreaded BLAS anymore (cakedev0#23), it takes 2.1 s. With 12 threads on the same 14 cores, main takes 2.0 s: as soon as there are spare cores, the problem disappears.
Hybrid laptops: blocking inside a parallel region + active wait. With the PyPI wheel on the Core Ultra 5 225H (14 threads), OPENBLAS_NUM_THREADS=1 only goes from 112 s to 77 s, while OMP_NUM_THREADS=8 gives 1.2 s. I could reproduce it without Python nor BLAS, with a parallel region in which each thread takes a pthread_mutex once:
The same region without the mutex takes ~17 us with active wait on the Core Ultra X7 358H, so active wait itself is fine there. I don't know the exact mechanism, but it looks like the threads all reach the lock at the same time, and each futex handoff then takes very long to get a woken thread running again.
Lloyd's parallel region has three such blocking points: the GIL (Cython wraps with nogil, parallel(): blocks in PyGILState_Ensure() / PyGILState_Release() in every thread when the body can raise, here because of memoryview slicing), the omp_set_lock reduction, and a mutex inside OpenBLAS's single-threaded gemm (see below). Replacing the gemm call by a plain loop (experiment only) on top of removing the first two fixes the reproducer: 24-26 s -> 1.2-1.3 s (Core Ultra X7 358H, 14 threads, GOMP_SPINCOUNT=300000, OPENBLAS_NUM_THREADS=1).
OpenBLAS takes a global mutex in each single-threaded call, MKL doesn't. With an LD_PRELOAD shim counting pthread_mutex_lock calls, 14 threads each calling a small single-threaded dgemm (256 x 50 x 8) inside a parallel region: OpenBLAS (the scipy-openblas wheels, and a 0.3.33 build) takes exactly 2 locks per call, ~35% of them contended. Built with USE_TLS=1 it takes 3 per call, still contended. MKL takes none, and the same region doesn't stall with MKL (38-181 us vs 2100-3200 us with OpenBLAS, Core Ultra 5 225H, GOMP_SPINCOUNT=300000). This is probably the buffer allocator of OpenMathLib/OpenBLAS#1782.
This lock probably also limits scaling when many threads call BLAS at once: on the Xeon, dense Lloyd (one gemm per chunk of 256 samples) stops scaling at ~16 threads with OpenBLAS pthreads. I think this is worth reporting to OpenBLAS.
Why libomp doesn't stall: it yields while spinning. Same test with LLVM's libomp and active wait (KMP_BLOCKTIME=200ms or infinite): as much lock contention as with libgomp, but ~85-125 sched_yield calls per region, and 78-87 us per region instead of 3200-3500 us. libgomp's spin loop (do_spin in libgomp/config/linux/wait.h) only runs pause and never yields.
Since GCC 14 (PR109812), libgomp doesn't spin by default on hybrid CPUs (spin count 1 when neither OMP_WAIT_POLICY nor GOMP_SPINCOUNT is set), so a recent libgomp doesn't stall there, but it does as soon as spinning is enabled (conda-forge's GCC 16 with GOMP_SPINCOUNT=300000: 4800-5200 us per region). Not spinning has a big cost though, which is why I don't think GOMP_SPINCOUNT=1 is a good general workaround: it makes HGB fits 2.7-8x slower on the laptops, and on the Xeon an HGB fit goes from 0.4 s to 18 s.
So I tried a small libgomp patch that calls sched_yield() every 100 iterations of the spin loop (prototype, GOMP_SPINCOUNT=300000, scikit-learn main):
libgomp
patched libgomp
libgomp, GOMP_SPINCOUNT=1
reproducer, Core Ultra 5 225H, 14 threads
65 s
2.5 s
2.1-2.2 s
HGB fit, Core Ultra 5 225H, 14 threads
354-367 ms
325-393 ms
897-937 ms
reproducer, Xeon pinned to 14 cores, 14 threads
19.1 s
2.45 s
12.0 s
HGB fit, Xeon pinned to 14 cores, 14 threads
377-399 ms
361-395 ms
18.4 s
It fixes both problems (on the Xeon, I think it's the OpenBLAS threads of the init that get the CPU back) and keeps the speed-up of active wait. Same on the Core Ultra X7 358H (16 threads): reproducer 51 s -> 2.2-2.7 s, HGB fit 192-250 ms vs 1.87 s with GOMP_SPINCOUNT=1. On the Xeon, from 14 to 172 threads on one socket, it is neutral to positive everywhere. I couldn't test on non-Intel CPUs.
A smaller spin count without yielding is not an alternative: on the Core Ultra 5 225H the stall only goes away at spin counts around 300, where an HGB fit is already 1.45x slower than with spinning + yield (527 vs 364 ms), and on the Xeon a spin count of 3000 makes HGB fits 5-30x slower. For reference, libomp yields after 512 spin iterations, then every 256.
Side note, KMeans PRs on my fork. I'm also working on KMeans performance for big workloads, which happens to help here but is not meant to fix this issue:
PRF Speed up k-means++ initialization #35140: k-means++ init in a single OpenMP kernel, without multithreaded BLAS calls (up to ~100x faster on large datasets with 64 threads on the Xeon).
With both (earlier versions of them), the reproducer took 1.2 s on the Xeon pinned to 14 cores (19 s on main). On the hybrid laptops it's still slow with active wait, because of the BLAS call in dense Lloyd.
The OpenBLAS lock I mentioned above (2 pthread_mutex_lock per single-threaded gemm call) is fixed upstream by OpenMathLib/OpenBLAS#6105, merged today 🎉 (and the PR also improved how fast threads find a buffer to work on, which is even more beneficial).
It should reach us with the next OpenBLAS release and the scipy-openblas wheels that follow. On its own, it doesn't fix this issue, but with #35140 and #35193 it does.
Reproducer from the first message, Core Ultra X7 358H (16 threads), OpenBLAS develop (791b02a1a) swapped in for scipy's bundled OpenBLAS with LD_PRELOAD, 2 interleaved runs, seconds:
With the wheel, the GIL and the omp_set_lock reduction in Lloyd's parallel region still stall the spinning threads, so removing the OpenBLAS lock only gains ~10%. Once the 3 blocking points are gone, the stall disappears and spinning makes the reproducer ~3x faster than not spinning (which is great as now it goes in the same direction as for HGB).
Activity
ogrisel commentedon May 25, 2020
OMP_NUM_THREADSunset:OMP_NUM_THREADS=1OMP_NUM_THREADSunset:OMP_NUM_THREADS=1:OMP_NUM_THREADS=2ogrisel commentedon May 25, 2020
As @jeremiedbb said during the core dev meeting, it might be caused by openblas that tries to use 4 threads on 2 physical cores / 4 logical core which is not an optimal strategy.
This might be related to OpenMathLib/OpenBLAS#1881 although the above benchmarks would need to rerun to control the size of the outer OpenMP and inner OpenBLAS loops to understand exactly what's going on.
jeremiedbb commentedon May 25, 2020
Not exactly. The BLAS is always limited to 1 thread. Setting OMP_NUM_THREADS will impact the openmp loop (over data chunks). On my laptop I observe like you that using logical cores is detrimental with OpenBLAS (also with MKL but way less). I don't understand why changing the BLAS makes a difference since it should be single threaded (I checked that it's effectively single threaded).
ogrisel commentedon May 25, 2020
I agree. Maybe the CPU cache usage pattern of OpenBLAS is different. Or maybe the inner BLAS is not limited to 1 thread as it's supposed to be when we use OpenBLAS.
jeremiedbb commentedon May 25, 2020
Hum I just tried your snipped while setting OPENBLAS_NUM_THREADS and there's a big difference when I don't set it and I set it to 1, which seems to indicate that openblas is actually not properly limited to 1.
jeremiedbb commentedon May 25, 2020
Actually it's k-means++ init faults ! it scales poorly, especially using hyperthreads.
The timings are back to expected when you set the init to 'random', meaning that the openmp loop and the inner blas are properly controlled.
Maybe you can turn this issue into a k-means++ issue ?
ogrisel commentedon May 25, 2020
That's very good news. I completely forgot about the init. I should have started by profiling before investigating the behavior of the main loop.
Yes but it's still an issue for the
KMeansestimator.jeremiedbb commentedon May 25, 2020
True :)
[-]K-Means performance issue with OpenBLAS[/-][+]KMeans performance issue with OpenBLAS[/+][-]KMeans performance issue with OpenBLAS[/-][+]KMeans(init='k-means++') performance issue with OpenBLAS[/+]1 remaining item
jeremiedbb commentedon May 25, 2020
I think so but it might be more specific. In k-means++ the matrix multiplication is
(n_candidates, n_features) x (n_samples, n_features)and the number of candidates is a small number (~log(n_clusters)). It's possible that mkl is better at optimizing the matrix multiplication where 1 dimension is much smaller than the other one.ogrisel commentedon May 29, 2020
A supposedly scalable alternative to k-means++ is k-means|| (#4357). However proper benchmarking of the DAAL implementation would be needed to tell what would be the actual benefit of implementing this alternative in scikit-learn.
ogrisel commentedon May 26, 2026
I tried again today on a laptop with 4 P-cores, 8 E-cores and 4 LP-cores and the results are the following (using OpenMP variant of OpenBLAS installed from conda-forge):
and with MKL:
So there is still a bit of a slowdown when using one thread per core for either BLAS implementation, but this is not as bad as in the past (probably because of the fix of OpenMathLib/OpenBLAS#1881)
Still, being able to automatically adjust to tune the of threads to the number of P-cores would probably be beneficial. (see: joblib/loky#630).
ogrisel commentedon May 27, 2026
Note that beyond oversubscription problems, it's likely that this code can still under perform when openblas is configured to run with pthreads instead of openmp. In this case the active wait policy of openmp and openblas threadpools can hag the available CPUs as documented in https://www.openmathlib.org/OpenBLAS/docs/faq/#using-openblas-with-openmp.
The "active wait overhead" problem does not seem to be as bad as observed in the past. However, if it happens to be a problem for specific runtimes / workload combinations, a possible remediation might be to pursue the work proposed in #28883.
ogrisel commentedon May 27, 2026
Actually the original problem is still there when we install everything from pypi.org. Here is a reproducer:
This is terrible performance degration. Disabling active wait in both thread-pools fixes most of the problem as documented in https://www.openmathlib.org/OpenBLAS/docs/faq/#using-openblas-with-openmp:
However, just limiting the number of threads of OpenMP while keeping active wait also fixes the problem and also the oversubscription problem and allows us to recover optimal performance:
Note that OpenBLAS limits itself to 4 threads despite not setting
OPENBLAS_NUM_THREADSand despite using OpenBLAS withthreading_layer="pthreads".ogrisel commentedon May 27, 2026
I don't understand why we get the 70s duration on the default venv built with uv from pypi.org packages but does not happen when installing seemingly the same packages with similar threading layer config using conda-forge instead.
ogrisel commentedon May 27, 2026
I also tried setting
OPENBLAS_NUM_THREADS=4only and contrary to the case where packages come from conda forge, the OpenMP runtime stays at 16 threads and we observe the catastrophic performance degradation.Also, when installing packages from pypi.org we get libgomp (the OpenMP runtime implementation from the GCC toolchain) while conda-forge ships libomp (the one from the LLVM toolchain). So the active wait problem seems to be libgomp specific and related to oversubscription at the OpenMP level.
cakedev0 commentedon Jul 4, 2026
[I investigated this with codex, and I find the source of the specific PyPi slowdown, it's pretty interesting]
I ran a controlled PyPI-vs-conda comparison where
scikit-learncame either from the PyPI wheel or from conda-forge, while BLAS was the same OpenBLAS pthreads build. The main difference I found is the OpenMP runtime used by scikit-learn:scikit-learnloads its bundledscikit_learn.libs/libgomp-e985bcbb.so.1.0.0, apparently GCC/libgomp 8.5.0, withGOMP_SPINCOUNT=300000by default.scikit-learnloads the environmentlibgomp.so.1.0.0, apparently GCC/libgomp 15.2.0, withGOMP_SPINCOUNT=1by default.OMP_WAIT_POLICYwas reported asPASSIVE.This seems to explain a large part of the PyPI-only slowdown. In a small custom reproducer with a direct OpenMP kernel interleaved with direct BLAS
dgemmcalls, the one-CPU case was basically identical, but the multi-CPU case was much slower with the PyPI runtime. Overriding the spin count was decisive:So this does not look like only a BLAS thread-count issue or classic nested oversubscription. It looks more like an active-wait / spin-wait interaction between OpenBLAS pthread workers and the
libgompworker pool, amplified by repeated short BLAS/OpenMP phases as in k-means++.There is a tradeoff:
GOMP_SPINCOUNT=300000is faster for many tiny back-to-back OpenMP-only regions, whileGOMP_SPINCOUNT=1is much better for mixed BLAS/OpenMP workloads. But for the k-means++ pattern discussed here, the lower spin count seems to be the better default/workaround.A practical workaround to test is therefore:
Conclusion: This suggests that the PyPI wheel's bundled
libgompdefault behavior / version could be part of the problem, independently of the OpenBLAS version itself.Spoiler: I continued investigating in this direction, and the
libgompwe bundle in the PyPI wheel isvery old, it comes from GCC 8.5which is from 2003. Edit: it's from 2021 (still a bit old, and it still kinda a bug as it should rather come from GCC 14).cakedev0 commentedon Jul 8, 2026
I checked
GOMP_SPINCOUNTon an AMD EPYC 9555P 64-Core Processor for the libgomp coming with conda (gcc 15.2), it's 300k, which is indeed supposed to be the default expect for hybrid CPUs (laptops), see #34437 (comment)) . So CPUs servers probably experience very bad performances for this example, for any build of scikit-learn with libgomp and openblas pthreads. I'll soon-ish have benchmarks for that, so we'll see.A possible way I foresee to close this issue:
libgompon Linux #34437 (for scikit-learn or for everyone), ANDogrisel commentedon Jul 10, 2026
We could also advise users impacted by this to set
GOMP_SPINCOUNT=1explicitly.cakedev0 commentedon Aug 13, 2026
One interesting additional experiment:
With openBLAS-pthreads + LLVM openMP,
KMP_BLOCKTIMEdoesn't affect wall time of this script, it remains fast (it does affect the CPU usage though). To me, this means LLVM openMP active wait implementation is "less dangerous" than the libgomp one.cakedev0 commentedon Oct 13, 2026
I ran more experiments on 3 machines to understand this slowdown. TLDR: there are two different problems, and which one dominates depends on the CPU:
OPENBLAS_NUM_THREADS=1.Both go away if libgomp's spinning threads call
sched_yield()from time to time, which is what LLVM's libomp does. So I think the fix belongs upstream rather than in scikit-learn.Machines: Intel Xeon 6787P (2 x 86 cores, GCC 16 libgomp), Intel Core Ultra 5 225H (14 cores: 4P + 8E + 2LPE) and Intel Core Ultra X7 358H (16 cores: 4P + 8E + 4LPE), both with GCC 13 libgomp. All the dev builds use the OpenBLAS pthreads build from the numpy/scipy wheels. Timings are for the reproducer from the first message unless stated otherwise.
Server CPU: the OpenBLAS + OpenMP oversubscription explanation holds. Pinned to 14 cores of the Xeon (
taskset -c 0-13) with 14 threads, the reproducer takes 19 s on main. With a k-means++ init that doesn't call multithreaded BLAS anymore (cakedev0#23), it takes 2.1 s. With 12 threads on the same 14 cores, main takes 2.0 s: as soon as there are spare cores, the problem disappears.Hybrid laptops: blocking inside a parallel region + active wait. With the PyPI wheel on the Core Ultra 5 225H (14 threads),
OPENBLAS_NUM_THREADS=1only goes from 112 s to 77 s, whileOMP_NUM_THREADS=8gives 1.2 s. I could reproduce it without Python nor BLAS, with a parallel region in which each thread takes apthread_mutexonce:Standalone C reproducer
GOMP_SPINCOUNT=300000GOMP_SPINCOUNT=1The same region without the mutex takes ~17 us with active wait on the Core Ultra X7 358H, so active wait itself is fine there. I don't know the exact mechanism, but it looks like the threads all reach the lock at the same time, and each futex handoff then takes very long to get a woken thread running again.
Lloyd's parallel region has three such blocking points: the GIL (Cython wraps
with nogil, parallel():blocks inPyGILState_Ensure()/PyGILState_Release()in every thread when the body can raise, here because of memoryview slicing), theomp_set_lockreduction, and a mutex inside OpenBLAS's single-threadedgemm(see below). Replacing thegemmcall by a plain loop (experiment only) on top of removing the first two fixes the reproducer: 24-26 s -> 1.2-1.3 s (Core Ultra X7 358H, 14 threads,GOMP_SPINCOUNT=300000,OPENBLAS_NUM_THREADS=1).OpenBLAS takes a global mutex in each single-threaded call, MKL doesn't. With an
LD_PRELOADshim countingpthread_mutex_lockcalls, 14 threads each calling a small single-threadeddgemm(256 x 50 x 8) inside a parallel region: OpenBLAS (the scipy-openblas wheels, and a 0.3.33 build) takes exactly 2 locks per call, ~35% of them contended. Built withUSE_TLS=1it takes 3 per call, still contended. MKL takes none, and the same region doesn't stall with MKL (38-181 us vs 2100-3200 us with OpenBLAS, Core Ultra 5 225H,GOMP_SPINCOUNT=300000). This is probably the buffer allocator of OpenMathLib/OpenBLAS#1782.This lock probably also limits scaling when many threads call BLAS at once: on the Xeon, dense Lloyd (one
gemmper chunk of 256 samples) stops scaling at ~16 threads with OpenBLAS pthreads. I think this is worth reporting to OpenBLAS.Why libomp doesn't stall: it yields while spinning. Same test with LLVM's libomp and active wait (
KMP_BLOCKTIME=200msorinfinite): as much lock contention as with libgomp, but ~85-125sched_yieldcalls per region, and 78-87 us per region instead of 3200-3500 us. libgomp's spin loop (do_spininlibgomp/config/linux/wait.h) only runspauseand never yields.Since GCC 14 (PR109812), libgomp doesn't spin by default on hybrid CPUs (spin count 1 when neither
OMP_WAIT_POLICYnorGOMP_SPINCOUNTis set), so a recent libgomp doesn't stall there, but it does as soon as spinning is enabled (conda-forge's GCC 16 withGOMP_SPINCOUNT=300000: 4800-5200 us per region). Not spinning has a big cost though, which is why I don't thinkGOMP_SPINCOUNT=1is a good general workaround: it makes HGB fits 2.7-8x slower on the laptops, and on the Xeon an HGB fit goes from 0.4 s to 18 s.So I tried a small libgomp patch that calls
sched_yield()every 100 iterations of the spin loop (prototype,GOMP_SPINCOUNT=300000, scikit-learn main):GOMP_SPINCOUNT=1It fixes both problems (on the Xeon, I think it's the OpenBLAS threads of the init that get the CPU back) and keeps the speed-up of active wait. Same on the Core Ultra X7 358H (16 threads): reproducer 51 s -> 2.2-2.7 s, HGB fit 192-250 ms vs 1.87 s with
GOMP_SPINCOUNT=1. On the Xeon, from 14 to 172 threads on one socket, it is neutral to positive everywhere. I couldn't test on non-Intel CPUs.A smaller spin count without yielding is not an alternative: on the Core Ultra 5 225H the stall only goes away at spin counts around 300, where an HGB fit is already 1.45x slower than with spinning + yield (527 vs 364 ms), and on the Xeon a spin count of 3000 makes HGB fits 5-30x slower. For reference, libomp yields after 512 spin iterations, then every 256.
Side note, KMeans PRs on my fork. I'm also working on
KMeansperformance for big workloads, which happens to help here but is not meant to fix this issue:With both (earlier versions of them), the reproducer took 1.2 s on the Xeon pinned to 14 cores (19 s on main). On the hybrid laptops it's still slow with active wait, because of the BLAS call in dense Lloyd.
cakedev0 commentedon Oct 21, 2026
The OpenBLAS lock I mentioned above (2
pthread_mutex_lockper single-threadedgemmcall) is fixed upstream by OpenMathLib/OpenBLAS#6105, merged today 🎉 (and the PR also improved how fast threads find a buffer to work on, which is even more beneficial).It should reach us with the next OpenBLAS release and the scipy-openblas wheels that follow. On its own, it doesn't fix this issue, but with #35140 and #35193 it does.
Reproducer from the first message, Core Ultra X7 358H (16 threads), OpenBLAS develop (791b02a1a) swapped in for scipy's bundled OpenBLAS with
LD_PRELOAD, 2 interleaved runs, seconds:GOMP_SPINCOUNT=300000)With the wheel, the GIL and the
omp_set_lockreduction in Lloyd's parallel region still stall the spinning threads, so removing the OpenBLAS lock only gains ~10%. Once the 3 blocking points are gone, the stall disappears and spinning makes the reproducer ~3x faster than not spinning (which is great as now it goes in the same direction as for HGB).What's left for this issue:
I'd close this issue once #35140 and #35193 are merged.
sync: 2026-11-03