Skip to content

KMeans(init='k-means++') performance issue with OpenBLAS #17334

Open

Description

@ogrisel

I open this issue to investigate a performance problem that might be related to #17230.

I adapted the reproducer of #17230 to display more info and make it work on a medium-size random dataset.

from sklearn import cluster
from time import time
from pprint import pprint
from threadpoolctl import threadpool_info
import numpy as np


pprint(threadpool_info())
rng = np.random.RandomState(0)
data = rng.randn(5000, 50)
t0_global = time()
for k in range(1, 15):
    t0 = time()
    # print(f"Running k-means with k={k}: ", end="", flush=True)
    cluster.KMeans(
        n_clusters=k,
        random_state=42,
        n_init=10,
        max_iter=2000,
        algorithm='lloyd',
        init='k-means++').fit(data)
    # print(f"{time() - t0:.3f} s")

print(f"Total duration: {time() - t0_global:.3f} s")

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.

I will include my runs in the first comment.

/cc @jeremiedbb

Activity

  1. ogrisel commented on May 25, 2020

    @ogrisel
    MemberAuthor
    • mkl env with OMP_NUM_THREADS unset:
    [{'filepath': '/home/ogrisel/miniconda3/envs/pylatest/lib/libgomp.so.1.0.0',
      'internal_api': 'openmp',
      'num_threads': 4,
      'prefix': 'libgomp',
      'user_api': 'openmp',
      'version': None},
     {'filepath': '/home/ogrisel/miniconda3/envs/sklearn-mkl/lib/libmkl_rt.so',
      'internal_api': 'mkl',
      'num_threads': 2,
      'prefix': 'libmkl_rt',
      'threading_layer': 'intel',
      'user_api': 'blas',
      'version': '2020.0.1'},
     {'filepath': '/home/ogrisel/miniconda3/envs/sklearn-mkl/lib/libiomp5.so',
      'internal_api': 'openmp',
      'num_threads': 4,
      'prefix': 'libiomp',
      'user_api': 'openmp',
      'version': None}]
    Total duration: 4.032 s
    
    • mkl env + OMP_NUM_THREADS=1
    [{'filepath': '/home/ogrisel/miniconda3/envs/pylatest/lib/libgomp.so.1.0.0',
      'internal_api': 'openmp',
      'num_threads': 1,
      'prefix': 'libgomp',
      'user_api': 'openmp',
      'version': None},
     {'filepath': '/home/ogrisel/miniconda3/envs/sklearn-mkl/lib/libmkl_rt.so',
      'internal_api': 'mkl',
      'num_threads': 1,
      'prefix': 'libmkl_rt',
      'threading_layer': 'intel',
      'user_api': 'blas',
      'version': '2020.0.1'},
     {'filepath': '/home/ogrisel/miniconda3/envs/sklearn-mkl/lib/libiomp5.so',
      'internal_api': 'openmp',
      'num_threads': 1,
      'prefix': 'libiomp',
      'user_api': 'openmp',
      'version': None}]
    Total duration: 5.951 s
    
    • openblas env with OMP_NUM_THREADS unset:
    [{'filepath': '/home/ogrisel/miniconda3/envs/pylatest/lib/libgomp.so.1.0.0',
      'internal_api': 'openmp',
      'num_threads': 4,
      'prefix': 'libgomp',
      'user_api': 'openmp',
      'version': None},
     {'filepath': '/home/ogrisel/miniconda3/envs/pylatest/lib/python3.8/site-packages/numpy/.libs/libopenblasp-r0-34a18dc3.3.7.so',
      'internal_api': 'openblas',
      'num_threads': 4,
      'prefix': 'libopenblas',
      'threading_layer': 'pthreads',
      'user_api': 'blas',
      'version': '0.3.7'}]
    Total duration: 23.408 s
    
    • openblas env with OMP_NUM_THREADS=1:
    [{'filepath': '/home/ogrisel/miniconda3/envs/pylatest/lib/libgomp.so.1.0.0',
      'internal_api': 'openmp',
      'num_threads': 1,
      'prefix': 'libgomp',
      'user_api': 'openmp',
      'version': None},
     {'filepath': '/home/ogrisel/miniconda3/envs/pylatest/lib/python3.8/site-packages/numpy/.libs/libopenblasp-r0-34a18dc3.3.7.so',
      'internal_api': 'openblas',
      'num_threads': 1,
      'prefix': 'libopenblas',
      'threading_layer': 'pthreads',
      'user_api': 'blas',
      'version': '0.3.7'}]
    Total duration: 7.295 s
    
    • openblas env with OMP_NUM_THREADS=2
    [{'filepath': '/home/ogrisel/miniconda3/envs/pylatest/lib/libgomp.so.1.0.0',
      'internal_api': 'openmp',
      'num_threads': 2,
      'prefix': 'libgomp',
      'user_api': 'openmp',
      'version': None},
     {'filepath': '/home/ogrisel/miniconda3/envs/pylatest/lib/python3.8/site-packages/numpy/.libs/libopenblasp-r0-34a18dc3.3.7.so',
      'internal_api': 'openblas',
      'num_threads': 2,
      'prefix': 'libopenblas',
      'threading_layer': 'pthreads',
      'user_api': 'blas',
      'version': '0.3.7'}]
    Total duration: 7.567 s
    
  2. ogrisel commented on May 25, 2020

    @ogrisel
    MemberAuthor

    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.

  3. jeremiedbb commented on May 25, 2020

    @jeremiedbb
    Member

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

  4. ogrisel commented on May 25, 2020

    @ogrisel
    MemberAuthor

    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.

  5. jeremiedbb commented on May 25, 2020

    @jeremiedbb
    Member

    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.

  6. jeremiedbb commented on May 25, 2020

    @jeremiedbb
    Member

    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 ?

  7. ogrisel commented on May 25, 2020

    @ogrisel
    MemberAuthor

    meaning that the openmp loop and the inner blas are properly controlled.

    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.

    Maybe you can turn this issue into a k-means++ issue ?

    Yes but it's still an issue for the KMeans estimator.

  8. jeremiedbb commented on May 25, 2020

    @jeremiedbb
    Member

    Yes but it's still an issue for the KMeans estimator.

    True :)

  9. changed the title [-]K-Means performance issue with OpenBLAS[/-] [+]KMeans performance issue with OpenBLAS[/+] on May 25, 2020
  10. changed the title [-]KMeans performance issue with OpenBLAS[/-] [+]KMeans(init='k-means++') performance issue with OpenBLAS[/+] on May 25, 2020
  11. 1 remaining item

  12. jeremiedbb commented on May 25, 2020

    @jeremiedbb
    Member

    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.

  13. ogrisel commented on May 29, 2020

    @ogrisel
    MemberAuthor

    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.

  14. ogrisel commented on May 26, 2026

    @ogrisel
    MemberAuthor

    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=*=*_openblas" "openblas=*=openmp_*"
    $ mamba list blas
    List of packages in environment: "/home/ogrisel/miniforge3/envs/dev"
    
      Name         Version  Build                Channel    
    ──────────────────────────────────────────────────────────
      libblas      3.11.0   7_h4a7cf45_openblas  conda-forge
      libcblas     3.11.0   7_h0358290_openblas  conda-forge
      libopenblas  0.3.33   openmp_hd680484_0    conda-forge
      openblas     0.3.33   openmp_hd77311e_0    conda-forge
    $ python kmeanspp_threads.py 
    [{'architecture': 'Haswell',
      'filepath': '/home/ogrisel/miniforge3/envs/dev/lib/libopenblasp-r0.3.33.so',
      'internal_api': 'openblas',
      'num_threads': 16,
      'prefix': 'libopenblas',
      'threading_layer': 'openmp',
      'user_api': 'blas',
      'version': '0.3.33'},
     {'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.407 s
    $ OMP_NUM_THREADS=1 python kmeanspp_threads.py 
    [{'architecture': 'Haswell',
      'filepath': '/home/ogrisel/miniforge3/envs/dev/lib/libopenblasp-r0.3.33.so',
      'internal_api': 'openblas',
      'num_threads': 1,
      'prefix': 'libopenblas',
      'threading_layer': 'openmp',
      'user_api': 'blas',
      'version': '0.3.33'},
     {'filepath': '/home/ogrisel/miniforge3/envs/dev/lib/libomp.so',
      'internal_api': 'openmp',
      'num_threads': 1,
      'prefix': 'libomp',
      'user_api': 'openmp',
      'version': None}]
    Total duration: 2.194 s
    $ OMP_NUM_THREADS=4 python kmeanspp_threads.py 
    [{'architecture': 'Haswell',
      'filepath': '/home/ogrisel/miniforge3/envs/dev/lib/libopenblasp-r0.3.33.so',
      'internal_api': 'openblas',
      'num_threads': 4,
      'prefix': 'libopenblas',
      'threading_layer': 'openmp',
      'user_api': 'blas',
      'version': '0.3.33'},
     {'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.309 s
    

    and with MKL:

    $ 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).

  15. added
    Parallelism and scalability
    on May 26, 2026
  16. ogrisel commented on May 27, 2026

    @ogrisel
    MemberAuthor

    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.

    $ mamba install "libblas=*=*_openblas" "openblas=*=pthreads_*"
    $ mamba list blas
    List of packages in environment: "/home/ogrisel/miniforge3/envs/dev"
    
      Name         Version  Build                Channel    
    ──────────────────────────────────────────────────────────
      libblas      3.11.0   7_h4a7cf45_openblas  conda-forge
      libcblas     3.11.0   7_h0358290_openblas  conda-forge
      libopenblas  0.3.33   pthreads_h94d23a6_0  conda-forge
      openblas     0.3.33   pthreads_h6ec200e_0  conda-forge
    $ python kmeanspp_threads.py 
    [{'architecture': 'Haswell',
      'filepath': '/home/ogrisel/miniforge3/envs/dev/lib/libopenblasp-r0.3.33.so',
      'internal_api': 'openblas',
      'num_threads': 16,
      'prefix': 'libopenblas',
      'threading_layer': 'pthreads',
      'user_api': 'blas',
      'version': '0.3.33'},
     {'filepath': '/home/ogrisel/miniforge3/envs/dev/lib/libomp.so',
      'internal_api': 'openmp',
      'num_threads': 16,
      'prefix': 'libomp',
      'user_api': 'openmp',
      'version': None}]
    Total duration: 3.442 s
    $ OMP_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 python kmeanspp_threads.py 
    [{'architecture': 'Haswell',
      'filepath': '/home/ogrisel/miniforge3/envs/dev/lib/libopenblasp-r0.3.33.so',
      'internal_api': 'openblas',
      'num_threads': 4,
      'prefix': 'libopenblas',
      'threading_layer': 'pthreads',
      'user_api': 'blas',
      'version': '0.3.33'},
     {'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.248 s
    

    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.

  17. ogrisel commented on May 27, 2026

    @ogrisel
    MemberAuthor

    Actually the original problem is still there when we install everything from pypi.org. Here is a reproducer:

    $ uv venv venvs/thread_debug
    $ source venvs/thread_debug/bin/activate
    $ uv pip install scikit-learn
    $ python kmeanspp_threads.py 
    [{'architecture': 'Haswell',
      'filepath': '/home/ogrisel/venvs/thread_debug/lib/python3.13/site-packages/numpy.libs/libscipy_openblas64_-32a4b2a6.so',
      'internal_api': 'openblas',
      'num_threads': 16,
      'prefix': 'libscipy_openblas',
      'threading_layer': 'pthreads',
      'user_api': 'blas',
      'version': '0.3.31.188.0'},
     {'architecture': 'Haswell',
      'filepath': '/home/ogrisel/venvs/thread_debug/lib/python3.13/site-packages/scipy.libs/libscipy_openblas-6cdc3b4a.so',
      'internal_api': 'openblas',
      'num_threads': 16,
      'prefix': 'libscipy_openblas',
      'threading_layer': 'pthreads',
      'user_api': 'blas',
      'version': '0.3.30'},
     {'filepath': '/home/ogrisel/venvs/thread_debug/lib/python3.13/site-packages/scikit_learn.libs/libgomp-e985bcbb.so.1.0.0',
      'internal_api': 'openmp',
      'num_threads': 16,
      'prefix': 'libgomp',
      'user_api': 'openmp',
      'version': None}]
    Total duration: 70.687 s
    

    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:

    $ OMP_WAIT_POLICY=passive OPENBLAS_THREAD_TIMEOUT=1 python kmeanspp_threads.py 
    [{'architecture': 'Haswell',
      'filepath': '/home/ogrisel/venvs/thread_debug/lib/python3.13/site-packages/numpy.libs/libscipy_openblas64_-32a4b2a6.so',
      'internal_api': 'openblas',
      'num_threads': 16,
      'prefix': 'libscipy_openblas',
      'threading_layer': 'pthreads',
      'user_api': 'blas',
      'version': '0.3.31.188.0'},
     {'architecture': 'Haswell',
      'filepath': '/home/ogrisel/venvs/thread_debug/lib/python3.13/site-packages/scipy.libs/libscipy_openblas-6cdc3b4a.so',
      'internal_api': 'openblas',
      'num_threads': 16,
      'prefix': 'libscipy_openblas',
      'threading_layer': 'pthreads',
      'user_api': 'blas',
      'version': '0.3.30'},
     {'filepath': '/home/ogrisel/venvs/thread_debug/lib/python3.13/site-packages/scikit_learn.libs/libgomp-e985bcbb.so.1.0.0',
      'internal_api': 'openmp',
      'num_threads': 16,
      'prefix': 'libgomp',
      'user_api': 'openmp',
      'version': None}]
    Total duration: 4.609 s
    

    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:

    $ OMP_NUM_THREADS=4 python kmeanspp_threads.py 
    [{'architecture': 'Haswell',
      'filepath': '/home/ogrisel/venvs/thread_debug/lib/python3.13/site-packages/numpy.libs/libscipy_openblas64_-32a4b2a6.so',
      'internal_api': 'openblas',
      'num_threads': 4,
      'prefix': 'libscipy_openblas',
      'threading_layer': 'pthreads',
      'user_api': 'blas',
      'version': '0.3.31.188.0'},
     {'architecture': 'Haswell',
      'filepath': '/home/ogrisel/venvs/thread_debug/lib/python3.13/site-packages/scipy.libs/libscipy_openblas-6cdc3b4a.so',
      'internal_api': 'openblas',
      'num_threads': 4,
      'prefix': 'libscipy_openblas',
      'threading_layer': 'pthreads',
      'user_api': 'blas',
      'version': '0.3.30'},
     {'filepath': '/home/ogrisel/venvs/thread_debug/lib/python3.13/site-packages/scikit_learn.libs/libgomp-e985bcbb.so.1.0.0',
      'internal_api': 'openmp',
      'num_threads': 4,
      'prefix': 'libgomp',
      'user_api': 'openmp',
      'version': None}]
    Total duration: 1.136 s
    

    Note that OpenBLAS limits itself to 4 threads despite not setting OPENBLAS_NUM_THREADS and despite using OpenBLAS with threading_layer="pthreads".

  18. ogrisel commented on May 27, 2026

    @ogrisel
    MemberAuthor

    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.

  19. ogrisel commented on May 27, 2026

    @ogrisel
    MemberAuthor

    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.

    $ OPENBLAS_NUM_THREADS=4 python kmeanspp_threads.py 
    [{'architecture': 'Haswell',
      'filepath': '/home/ogrisel/venvs/thread_debug/lib/python3.13/site-packages/numpy.libs/libscipy_openblas64_-32a4b2a6.so',
      'internal_api': 'openblas',
      'num_threads': 4,
      'prefix': 'libscipy_openblas',
      'threading_layer': 'pthreads',
      'user_api': 'blas',
      'version': '0.3.31.188.0'},
     {'architecture': 'Haswell',
      'filepath': '/home/ogrisel/venvs/thread_debug/lib/python3.13/site-packages/scipy.libs/libscipy_openblas-6cdc3b4a.so',
      'internal_api': 'openblas',
      'num_threads': 4,
      'prefix': 'libscipy_openblas',
      'threading_layer': 'pthreads',
      'user_api': 'blas',
      'version': '0.3.30'},
     {'filepath': '/home/ogrisel/venvs/thread_debug/lib/python3.13/site-packages/scikit_learn.libs/libgomp-e985bcbb.so.1.0.0',
      'internal_api': 'openmp',
      'num_threads': 16,
      'prefix': 'libgomp',
      'user_api': 'openmp',
      'version': None}]
    Total duration: 69.572 s
    

    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.

  20. cakedev0 commented on Jul 4, 2026

    @cakedev0
    Member

    [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).

  21. cakedev0 commented on Jul 8, 2026

    @cakedev0
    Member

    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.

    A possible way I foresee to close this issue:

  22. ogrisel commented on Jul 10, 2026

    @ogrisel
    MemberAuthor

    We could also advise users impacted by this to set GOMP_SPINCOUNT=1 explicitly.

  23. cakedev0 commented on Aug 13, 2026

    @cakedev0
    Member

    One interesting additional experiment:

    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.

    [{'architecture': 'Haswell',
      'filepath': '/home/arthur/scikit-learn-benchmarks/.pixi/envs/sklearn-cf-libomp-openblas/lib/libopenblasp-r0.3.34.so',
      'internal_api': 'openblas',
      'num_threads': 14,
      'prefix': 'libopenblas',
      'threading_layer': 'pthreads',
      'user_api': 'blas',
      'version': '0.3.34'},
     {'filepath': '/home/arthur/scikit-learn-benchmarks/.pixi/envs/sklearn-cf-libomp-openblas/lib/libomp.so',
      'internal_api': 'openmp',
      'num_threads': 14,
      'prefix': 'libomp',
      'user_api': 'openmp',
      'version': None}]
    
  24. cakedev0 commented on Oct 13, 2026

    @cakedev0
    Member

    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:

    Standalone C reproducer
    // gcc -O2 -fopenmp regions.c -o regions && GOMP_SPINCOUNT=300000 ./regions
    #include <omp.h>
    #include <pthread.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void) {
        int n_rep = 5000, n = 5000 * 50;
        double *x = malloc(n * sizeof(double));
        for (int i = 0; i < n; i++) x[i] = i * 1e-6;
        pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
        double total = 0, t0 = 0;
        for (int rep = 0; rep < 2 * n_rep; rep++) {
            if (rep == n_rep) t0 = omp_get_wtime();
            double acc = 0;
            #pragma omp parallel reduction(+:acc)
            {
                #pragma omp for schedule(static)
                for (int i = 0; i < n; i++) acc += x[i] * x[i];
                pthread_mutex_lock(&mutex);
                total += 1;
                pthread_mutex_unlock(&mutex);
            }
            total += acc;
        }
        printf("%.1f us/region\n", (omp_get_wtime() - t0) / n_rep * 1e6);
        return total < 0;
    }
    us per region GOMP_SPINCOUNT=300000 GOMP_SPINCOUNT=1
    Core Ultra 5 225H, 14 threads 3800-7600 75-130
    Core Ultra X7 358H, 16 threads 1900-5000 ~100
    Xeon 6787P pinned to 14 cores, 14 threads 33-44 83-85

    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:

    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.

  25. cakedev0 commented on Oct 21, 2026

    @cakedev0
    Member

    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:

    scikit-learn libgomp spinning scipy's OpenBLAS OpenBLAS develop
    1.9.1 PyPI wheel (bundled libgomp 8.5) yes (default) 65.3, 67.7 57.2, 60.5
    #35140 + #35193 (GCC 13 libgomp) yes (GOMP_SPINCOUNT=300000) 9.79, 9.87 0.85, 0.93
    #35140 + #35193 (GCC 13 libgomp) no (default on hybrid CPUs) 2.90, 2.96 2.73, 2.82

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


    What's left for this issue:

    I'd close this issue once #35140 and #35193 are merged.

  26. added a commit that references this issue on Nov 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugParallelism and scalabilityPerformancemodule:cluster

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions