Repository navigation
Closed
Labels
Description
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=1hides the problem; - running the reproducer with a lower than default value for
OMP_NUM_THREADSmakes 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
ogrisel commentedon Aug 6, 2025
cc @jjerphan.
ogrisel commentedon Aug 6, 2025
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.
jjerphan commentedon Aug 6, 2025
Hello Olivier,
Do you know if this issue is specific to
osxor even toosx-arm64?ogrisel commentedon Aug 7, 2025
I don't think so but maybe. Cannot you reproduce with the provided snippet?
ogrisel commentedon Aug 7, 2025
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.
jjerphan commentedon Aug 7, 2025
I can only reproduce this issue on
linux64whenopenmpis used as the threading layer of OpenBLAS.I cannot reproduce this error when
pthreadis used as the threading layer of OpenBLAS.Builds I used:
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
pthreadsare not available for macOS.Conda environment with OpenBLAS built with OpenMP
Versions with OpenBLAS built with OpenMP
jjerphan commentedon Aug 7, 2025
Note that I cannot reproduce the problem with
libopenblas==0.3.10=openmp_*, so this is likely a regression intolibopenblaswhich can be found by bisection.Edit:
libopenblas==0.3.10=openmp_*surprisingly uses Intel's tbb or MKL for its threading layer.jjerphan commentedon Aug 7, 2025
I cannot reproduce the problem with
libopenblas==0.3.23=openmp_*_0but I can withlibopenblas==0.3.24=openmp_*_0(on Linux, there is only one build published per version).Since the
openmpruntime 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.ogrisel commentedon Aug 11, 2025
Unfortunately, I can reproduce the problem with on my mac with:
ogrisel commentedon Aug 11, 2025
There does not seem to be a pthreads build of openblas on macOS.
ogrisel commentedon Aug 11, 2025
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.jjerphan commentedon Aug 12, 2025
Could you also try the new accelerate support for macOS?
jjerphan commentedon Aug 12, 2025
conda-forge/openblas-feedstock#177 might interest you.
jjerphan commentedon Aug 18, 2025
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?ogrisel commentedon Aug 22, 2025
No bug with "new_accelerate" either.
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.
FIX Reference-count BLAS thread limit in pairwise distance reductions
FIX Reference-count BLAS thread limit in pairwise distance reductions
cakedev0 commentedon Sep 4, 2026
@ogrisel maybe ongoing work on threadpoolctl/joblib is going to fix this issue?
ogrisel commentedon Sep 4, 2026
I don't think so unfortunately. But it's worth checking if recent version of openblas still have the problem.
itamarst commentedon Sep 23, 2026
I tested with recently released OpenBLAS (0.3.34) + OpenMP, since OpenBLAS had some fixes for thread safety. Unfortunately the problem still exists.
itamarst commentedon Sep 23, 2026
#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 ofopenblas_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.)
cakedev0 commentedon Sep 24, 2026
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.