Repository navigation
Open
Labels
Description
Describe the bug
Found while working on #30041.
See the reproducer below. Fitting LinearSVR probably relies on a shared global state in the C++ code and that introduces a race condition when fitting several models concurrently in different threads. As a result, the outcomes are randomly corrupted.
LinearSVC does not seem to have the problem (or at least not with its default solver).
Steps/Code to Reproduce
# %%
import numpy as np
from sklearn.svm import LinearSVR, LinearSVC
from sklearn.datasets import make_regression
import warnings
from sklearn.exceptions import ConvergenceWarning
from joblib import Parallel, delayed
warnings.filterwarnings("ignore", category=ConvergenceWarning)
X, y = make_regression(n_samples=100, n_features=20, noise=0.1, random_state=42)
C_range = np.logspace(-6, 6, 13)
model_class = LinearSVR
if model_class == LinearSVC:
y = np.sign(y) # Convert to binary classification for LinearSVC
sequential_results = [
model_class(C=C, random_state=0).fit(X, y).coef_.copy() for C in C_range
]
parallel_results = Parallel(n_jobs=4, backend="threading")(
delayed(lambda C: model_class(C=C, random_state=0).fit(X, y).coef_.copy())(C)
for C in C_range
)
np.testing.assert_array_equal(
sequential_results,
parallel_results,
err_msg="Parallel and sequential results differ.",
)Expected Results
Nothing.
Actual Results
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Cell In[22], line 32
23 sequential_results = [
24 model_class(C=C, random_state=0).fit(X, y).coef_.copy() for C in C_range
25 ]
28 parallel_results = Parallel(n_jobs=4, backend="threading")(
29 delayed(lambda C: model_class(C=C, random_state=0).fit(X, y).coef_.copy())(C)
30 for C in C_range
31 )
---> 32 np.testing.assert_array_equal(
33 sequential_results,
34 parallel_results,
35 err_msg="Parallel and sequential results differ.",
36 )
[... skipping hidden 2 frame]
File ~/miniforge3/envs/dev/lib/python3.13/site-packages/numpy/testing/_private/utils.py:921, in assert_array_compare(comparison, x, y, err_msg, verbose, header, precision, equal_nan, equal_inf, strict, names)
916 err_msg += '\n' + '\n'.join(remarks)
917 msg = build_err_msg([ox, oy], err_msg,
918 verbose=verbose, header=header,
919 names=names,
920 precision=precision)
--> 921 raise AssertionError(msg)
922 except ValueError:
923 import traceback
AssertionError:
Arrays are not equal
Parallel and sequential results differ.
Mismatched elements: 120 / 260 (46.2%)
Max absolute difference among violations: 0.08899258
Max relative difference among violations: 34.19844827
ACTUAL: array([[ 1.041988e-05, 3.557394e-05, 1.559387e-05, 7.395653e-06,
2.093259e-06, 1.044073e-05, 9.847355e-06, 3.642882e-05,
3.347666e-05, 2.792198e-05, -1.039337e-05, 7.220585e-06,...
DESIRED: array([[ 1.041988e-05, 3.557394e-05, 1.559387e-05, 7.395653e-06,
2.093259e-06, 1.044073e-05, 9.847355e-06, 3.642882e-05,
3.347666e-05, 2.792198e-05, -1.039337e-05, 7.220585e-06,...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.2.6
scipy: 1.15.2
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: 10
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 7, 2025
test_logisticregression_liblinear_sample_weightmight be impacted by the same problem when run concurrently withpytest-run-parallel: it's using the liblinear solver for logistic regression with different solver configurations and the state of the internal liblinear RNG might be shared.We should investigate if this is the same problem or not. And if not, open a dedicated issue with a minimal reproducer that does not require
pytest-run-parallel.ogrisel commentedon Aug 7, 2025
Similar problem in
test_liblinear_dual_random_state.PaulOberg1 commentedon Aug 11, 2025
[-]Fitting different instances of `LinearSVC` is not thread-safe[/-][+]Fitting different instances of `LinearSVR` is not thread-safe[/+]ayushmanpani commentedon Jan 21, 2026
Tested LogisticRegression(solver="liblinear", penalty="l1") using a minimal joblib-threading reproducer outside pytest-run-parallel (pip-installed sklearn, Windows).
Nondeterministic coefficients when fitting concurrently in threads, even with fixed random_state.
Example output:
MISMATCH at index 4 (max abs diff ≈ 1.14)This suggests the same shared liblinear global state issue affects LogisticRegression as well.
ENH Add regression test for LinearSVR thread-safety (scikit-learn#31883)
ENH Add regression test for LinearSVR thread-safety (scikit-learn#31883)
Higgs32584 commentedon Oct 9, 2026
mt_randinsklearn/svm/src/newrand/newrand.hwas a process-wide global. The liblinear solvers draw from it to shuffle the sample order while the GIL is released, so concurrent fits in different threads reseeded and consumed the same generator, giving timing-dependent coefficients.We can declare
mt_randasthread_local. Nothing else needs to change in the C/C++ or Cython code. This is sufficient becauseset_seed()is always called from the same thread that then runs the solver:train_wrapcallsset_parameter(which seeds) and thentrainin the same call.svm_trainandsvm_cross_validationseed at their start.