Skip to content

pairwise_distances_argmin_min / ArgKMin64 is not thread-safe #31884

Closed

Description

@ogrisel

Describe the bug

Problem found while test investigating failures found in #30041. I crafted a minimal reproducer below. It might be caused by a race condition (corruption) of shared intermediate buffers used in OpenMP threads.

Some remarks:

  • the problem happens with either strategy ("parallel_on_X" vs "parallel_on_Y");
  • running the reproducer with OMP_NUM_THREADS=1 hides the problem;
  • running the reproducer with a lower than default value for OMP_NUM_THREADS makes the problem less likely to happen;
  • using threadpoolctl.threadpool_limits(limits=1, user_api="openmp") does not hide the problem for some reason...

Steps/Code to Reproduce

from sklearn.metrics._pairwise_distances_reduction._argkmin import ArgKmin64
import numpy as np
from joblib import delayed, Parallel
from threadpoolctl import threadpool_info
from pprint import pprint

pprint(threadpool_info())
rng = np.random.RandomState(0)
X = rng.randn(97, 149)
Y = rng.randn(111, 149)


# Note: strategy does not matter.
shared_kwargs = dict(
    k=1, metric="euclidean", strategy="parallel_on_X", return_distance=True
)
reference_results = ArgKmin64.compute(X, Y, **shared_kwargs)

for n_iter in range(10):
    print(".", end="")
    for results in Parallel(n_jobs=4, backend="threading")(
        delayed(ArgKmin64.compute)(X, Y, **shared_kwargs) for _ in range(100)
    ):
        if shared_kwargs["return_distance"]:
            result_distances, result_indices = results
            np.testing.assert_allclose(result_distances, reference_results[0])
            np.testing.assert_array_equal(result_indices, reference_results[1])
        else:
            np.testing.assert_array_equal(results, reference_results)

Expected Results

No error.

Actual Results

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Cell In[20], line 27
     25 if shared_kwargs["return_distance"]:
     26     result_distances, result_indices = results
---> 27     np.testing.assert_allclose(result_distances, reference_results[0])
     28     np.testing.assert_array_equal(result_indices, reference_results[1])
     29 else:

    [... skipping hidden 1 frame]

File ~/miniforge3/envs/dev/lib/python3.13/site-packages/numpy/testing/_private/utils.py:926, in assert_array_compare(comparison, x, y, err_msg, verbose, header, precision, equal_nan, equal_inf, strict, names)
    921         err_msg += '\n' + '\n'.join(remarks)
    922         msg = build_err_msg([ox, oy], err_msg,
    923                             verbose=verbose, header=header,
    924                             names=names,
    925                             precision=precision)
--> 926         raise AssertionError(msg)
    927 except ValueError:
    928     import traceback

AssertionError: 
Not equal to tolerance rtol=1e-07, atol=0

Mismatched elements: 41 / 97 (42.3%)
Max absolute difference among violations: 0.88436841
Max relative difference among violations: 0.06194002
 ACTUAL: array([[14.721555],
       [15.009136],
       [14.586221],...
 DESIRED: array([[14.721555],
       [15.009136],
       [14.586221],...

The values of the difference among violations change from one run to the next, but are always much larger than what could be expected from rounding errors.

Versions

System:
    python: 3.13.3 | packaged by conda-forge | (main, Apr 14 2025, 20:44:30) [Clang 18.1.8 ]
executable: /Users/ogrisel/miniforge3/envs/dev/bin/python
   machine: macOS-15.5-arm64-arm-64bit-Mach-O

Python dependencies:
      sklearn: 1.8.dev0
          pip: 25.1.1
   setuptools: 75.8.2
        numpy: 2.3.2
        scipy: 1.16.0
       Cython: 3.1.1
       pandas: 2.2.3
   matplotlib: 3.10.3
       joblib: 1.5.1
threadpoolctl: 3.6.0

Built with OpenMP: True

threadpoolctl info:
       user_api: blas
   internal_api: openblas
    num_threads: 1
         prefix: libopenblas
       filepath: /Users/ogrisel/miniforge3/envs/dev/lib/libopenblas.0.dylib
        version: 0.3.30
threading_layer: openmp
   architecture: VORTEX

       user_api: openmp
   internal_api: openmp
    num_threads: 10
         prefix: libomp
       filepath: /Users/ogrisel/miniforge3/envs/dev/lib/libomp.dylib
        version: None

Activity

  1. added
    Needs Triage
    and removed
    Needs Triage
    on Aug 6, 2025
  2. ogrisel commented on Aug 6, 2025

    @ogrisel
    MemberAuthor
  3. ogrisel commented on Aug 6, 2025

    @ogrisel
    MemberAuthor

    Note: the purpose of #30041 is to prepare testing scikit-learn for correct results in a free-threading environment, but the bug reported here happens with the regular variant of CPython.

  4. jjerphan commented on Aug 6, 2025

    @jjerphan
    Member

    Hello Olivier,

    Do you know if this issue is specific to osx or even to osx-arm64?

  5. ogrisel commented on Aug 7, 2025

    @ogrisel
    MemberAuthor

    I don't think so but maybe. Cannot you reproduce with the provided snippet?

  6. ogrisel commented on Aug 7, 2025

    @ogrisel
    MemberAuthor

    It might depend on the choice of the openmp runtime, which is often tied to the choice of the OS, however that would need to be confirmed.

  7. jjerphan commented on Aug 7, 2025

    @jjerphan
    Member

    I can only reproduce this issue on linux64 when openmp is used as the threading layer of OpenBLAS.

    I cannot reproduce this error when pthread is used as the threading layer of OpenBLAS.

    Builds I used:

      - libopenblas   0.3.30  openmp_hd680484_1    conda-forge     Cached
      - libopenblas   0.3.30  pthreads_h94d23a6_1  conda-forge     Cached
    

    When libopenblas==*=pthreads_* is used:

    [{'architecture': 'Haswell',                                                                                                                                                                   
      'filepath': '/path/envs/sk/lib/libopenblasp-r0.3.30.so',                                                                                                          
      'internal_api': 'openblas',                                                                                                                                                                  
      'num_threads': 20,                                                                                                                                                                           
      'prefix': 'libopenblas',                                                                                                                                                                     
      'threading_layer': 'pthreads',                                                                                                                                                               
      'user_api': 'blas',                                                                                                                                                                          
      'version': '0.3.30'},                                                                                                                                                                        
     {'filepath': '/path/envs/sk/lib/libgomp.so.1.0.0',                                                                                                                 
      'internal_api': 'openmp',                                                                                                                                                                    
      'num_threads': 20,                                                                                                                                                                           
      'prefix': 'libgomp',                                                                                                                                                                         
      'user_api': 'openmp',                                                                                                                                                                        
      'version': None}]                                                                                                                                                                            
    ..........% 

    and when libopenblas==*=openmp_* is used:

    [{'architecture': 'Haswell',
      'filepath': '/path/envs/sk/lib/libopenblasp-r0.3.30.so',
      'internal_api': 'openblas',
      'num_threads': 20,
      'prefix': 'libopenblas',
      'threading_layer': 'openmp',
      'user_api': 'blas',
      'version': '0.3.30'},
     {'filepath': '/path/envs/sk/lib/libomp.so',
      'internal_api': 'openmp',
      'num_threads': 20,
      'prefix': 'libomp',
      'user_api': 'openmp',
      'version': None}]
    .Traceback (most recent call last):                                                                                                                                                            
      File "/tmp/a.py", line 26, in <module>                                                                                                                                                       
        np.testing.assert_allclose(result_distances, reference_results[0])                                                                                                                         
        ~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^                                                                                                                         
      File "/home/jjerphan/.local/miniforge3/envs/sk/lib/python3.13/site-packages/numpy/testing/_private/utils.py", line 1718, in assert_allclose                                                  
        assert_array_compare(compare, actual, desired, err_msg=str(err_msg),                                                                                                                       
        ~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^                                                                                                                       
                             verbose=verbose, header=header, equal_nan=equal_nan,                                                                                                                  
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^                                                                                                                  
                             strict=strict)                                                                                                                                                        
                             ^^^^^^^^^^^^^^                                                                                                                                                        
      File "/home/jjerphan/.local/miniforge3/envs/sk/lib/python3.13/site-packages/numpy/testing/_private/utils.py", line 926, in assert_array_compare                                              
        raise AssertionError(msg)                                                                                                                                                                  
    AssertionError:                                                                                                                                                                                
    Not equal to tolerance rtol=1e-07, atol=0                                                                                                                                                      
                                                                                                                                                                                                   
    Mismatched elements: 13 / 97 (13.4%)                                                                                                                                                           
    Max absolute difference among violations: 0.76800467                                                                                                                                           
    Max relative difference among violations: 0.05362079                                                                                                                                           
     ACTUAL: array([[14.721555],                                                                                                                                                                   
           [15.009136],
           [14.586221],...
     DESIRED: array([[14.721555],
           [15.009136],
           [14.586221],...

    On Linux, one can switch between threading layers for builds using:

    mamba install  "libopenblas==*=openmp_*"

    and:

    mamba install "libopenblas==*=pthreads_*"

    On conda-forge, OpenBLAS builds of with pthreads are not available for macOS.

    Conda environment with OpenBLAS built with OpenMP
    name: sk
    channels:
      - conda-forge
    dependencies:
      - _libgcc_mutex=0.1=conda_forge
      - _openmp_mutex=4.5=3_kmp_llvm
      - asttokens=3.0.0=pyhd8ed1ab_1
      - bzip2=1.0.8=h4bc722e_7
      - ca-certificates=2025.8.3=hbd8a1cb_0
      - decorator=5.2.1=pyhd8ed1ab_0
      - exceptiongroup=1.3.0=pyhd8ed1ab_0
      - executing=2.2.0=pyhd8ed1ab_0
      - ipython=9.4.0=pyhfa0c392_0
      - ipython_pygments_lexers=1.1.1=pyhd8ed1ab_0
      - jedi=0.19.2=pyhd8ed1ab_1
      - joblib=1.5.1=pyhd8ed1ab_0
      - ld_impl_linux-64=2.44=h1423503_1
      - libblas=3.9.0=33_h59b9bed_openblas
      - libcblas=3.9.0=33_he106b2a_openblas
      - libexpat=2.7.1=hecca717_0
      - libffi=3.4.6=h2dba641_1
      - libgcc=15.1.0=h767d61c_4
      - libgcc-ng=15.1.0=h69a702a_4
      - libgfortran=15.1.0=h69a702a_4
      - libgfortran5=15.1.0=hcea5267_4
      - libgomp=15.1.0=h767d61c_4
      - liblapack=3.9.0=33_h7ac8fdf_openblas
      - liblzma=5.8.1=hb9d3cd8_2
      - libmpdec=4.0.0=hb9d3cd8_0
      - libopenblas=0.3.30=openmp_hd680484_1
      - libsqlite=3.50.4=h0c1763c_0
      - libstdcxx=15.1.0=h8f9b012_4
      - libuuid=2.38.1=h0b41bf4_0
      - libzlib=1.3.1=hb9d3cd8_2
      - llvm-openmp=20.1.8=h4922eb0_1
      - matplotlib-inline=0.1.7=pyhd8ed1ab_1
      - ncurses=6.5=h2d0b736_3
      - numpy=2.3.2=py313hf6604e3_0
      - openssl=3.5.2=h26f9b46_0
      - parso=0.8.4=pyhd8ed1ab_1
      - pexpect=4.9.0=pyhd8ed1ab_1
      - pickleshare=0.7.5=pyhd8ed1ab_1004
      - pip=25.2=pyh145f28c_0
      - prompt-toolkit=3.0.51=pyha770c72_0
      - ptyprocess=0.7.0=pyhd8ed1ab_1
      - pure_eval=0.2.3=pyhd8ed1ab_1
      - pygments=2.19.2=pyhd8ed1ab_0
      - python=3.13.5=hec9711d_102_cp313
      - python_abi=3.13=8_cp313
      - readline=8.2=h8c095d6_2
      - scikit-learn=1.7.1=py313h06d4379_0
      - scipy=1.16.0=py313h86fcf2b_0
      - setuptools=80.9.0=pyhff2d567_0
      - stack_data=0.6.3=pyhd8ed1ab_1
      - threadpoolctl=3.6.0=pyhecae5ae_0
      - tk=8.6.13=noxft_hd72426e_102
      - traitlets=5.14.3=pyhd8ed1ab_1
      - typing_extensions=4.14.1=pyhe01879c_0
      - tzdata=2025b=h78e105d_0
      - wcwidth=0.2.13=pyhd8ed1ab_1
    
    Versions with OpenBLAS built with OpenMP
    System:
        python: 3.13.5 | packaged by conda-forge | (main, Jun 16 2025, 08:27:50) [GCC 13.3.0]
    executable: /path/envs/sk/bin/python3.13
       machine: Linux-6.13.5-100.fc40.x86_64-x86_64-with-glibc2.41
    
    Python dependencies:
          sklearn: 1.7.1
              pip: 25.2
       setuptools: 80.9.0
            numpy: 2.3.2
            scipy: 1.16.0
           Cython: None
           pandas: None
       matplotlib: None
           joblib: 1.5.1
    threadpoolctl: 3.6.0
    
    Built with OpenMP: True
    
    threadpoolctl info:
           user_api: blas
       internal_api: openblas
        num_threads: 20
             prefix: libopenblas
           filepath: /path/envs/sk/lib/libopenblasp-r0.3.30.so
            version: 0.3.30
    threading_layer: openmp
       architecture: Haswell
    
           user_api: openmp
       internal_api: openmp
        num_threads: 20
             prefix: libomp
           filepath: /path/envs/sk/lib/libomp.so
            version: None
    
  8. jjerphan commented on Aug 7, 2025

    @jjerphan
    Member

    Note that I cannot reproduce the problem with libopenblas==0.3.10=openmp_*, so this is likely a regression into libopenblas which can be found by bisection.

    Edit: libopenblas==0.3.10=openmp_* surprisingly uses Intel's tbb or MKL for its threading layer.

  9. jjerphan commented on Aug 7, 2025

    @jjerphan
    Member

    I cannot reproduce the problem with libopenblas==0.3.23=openmp_*_0 but I can with libopenblas==0.3.24=openmp_*_0 (on Linux, there is only one build published per version).

    Since the openmp runtime is not being changed when switching from one build to another, the issue might be due either to a regression in changes between 0.3.23 and 0.3.24 or to a change of build system on the feedstock between 0.3.23 and 0.3.24 which might have altered the builds.

  10. ogrisel commented on Aug 11, 2025

    @ogrisel
    MemberAuthor

    Unfortunately, I can reproduce the problem with on my mac with:

    libopenblas               0.3.23          openmp_hc731615_0    conda-forge
    
  11. ogrisel commented on Aug 11, 2025

    @ogrisel
    MemberAuthor

    There does not seem to be a pthreads build of openblas on macOS.

  12. ogrisel commented on Aug 11, 2025

    @ogrisel
    MemberAuthor

    I cannot reproduce the problem when I install the "libblas=*=*accelerate" version of BLAS. So this confirms a bad interaction between OpenBLAS with OpenMP and our Cython OpenMP code.

  13. jjerphan commented on Aug 12, 2025

    @jjerphan
    Member
  14. jjerphan commented on Aug 12, 2025

    @jjerphan
    Member

    There does not seem to be a pthreads build of openblas on macOS.

    conda-forge/openblas-feedstock#177 might interest you.

  15. jjerphan commented on Aug 18, 2025

    @jjerphan
    Member

    Could you try whether you have problem with the libopenblas==*=pthreads_* which have been or are being published for macOS thanks to the merge of conda-forge/openblas-feedstock#177?

  16. ogrisel commented on Aug 22, 2025

    @ogrisel
    MemberAuthor

    Could you also try the new accelerate support for macOS?

    No bug with "new_accelerate" either.

    Could you try whether you have problem with the libopenblas===pthreads_ which have been or are being published for macOS thanks to the merge of conda-forge/openblas-feedstock#177?

    Thanks, I tried and there is no problem either. So it's definitely a problem that is specific to the use of openblas built with openmp.

  17. added 2 commits that reference this issue on Sep 3, 2026
    52aba9d
    16cc7f9
  18. cakedev0 commented on Sep 4, 2026

    @cakedev0
    Member

    @ogrisel maybe ongoing work on threadpoolctl/joblib is going to fix this issue?

  19. ogrisel commented on Sep 4, 2026

    @ogrisel
    MemberAuthor

    I don't think so unfortunately. But it's worth checking if recent version of openblas still have the problem.

  20. itamarst commented on Sep 23, 2026

    @itamarst
    Contributor

    I tested with recently released OpenBLAS (0.3.34) + OpenMP, since OpenBLAS had some fixes for thread safety. Unfortunately the problem still exists.

  21. itamarst commented on Sep 23, 2026

    @itamarst
    Contributor

    #34878 has a compelling theory; certainly the PR fixes it.

    However, I don't think the PR is necessary any more: if the reason is switching number of threads half-way through the computation, due to global impact of setting number of threads, that is solved by latest threadpoolctl.

    And in fact switching to threadpoolctl 3.7, where it uses omp_set_num_threads() (which is thread local) instead of openblas_set_num_threads (affects all threads), fixes the problem too.

    So this seems fixable simply by setting the minimum threadpoolctl version to 3.7. (Also requires OpenBLAS 0.3.34 or later due to bug fixes in OpenBLAS.)

  22. cakedev0 commented on Sep 24, 2026

    @cakedev0
    Member

    switching to threadpoolctl 3.7 fixes the problem

    Great! 🎉

    I'm not sure when we'll bump the min version to 3.7 but given that a vanilla pip install scikit-learn / uv add / pixi/conda install now resolve to threadpoolctl 3.7, I think we can close this issue.

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions