Skip to content

Fitting different instances of LinearSVR is not thread-safe #31883

Open

Description

@ogrisel

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

  1. added theissue type on Aug 6, 2025
  2. ogrisel commented on Aug 7, 2025

    @ogrisel
    MemberAuthor

    test_logisticregression_liblinear_sample_weight might be impacted by the same problem when run concurrently with pytest-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.

  3. ogrisel commented on Aug 7, 2025

    @ogrisel
    MemberAuthor

    Similar problem in test_liblinear_dual_random_state.

  4. PaulOberg1 commented on Aug 11, 2025

    @PaulOberg1
  5. changed the title [-]Fitting different instances of `LinearSVC` is not thread-safe[/-] [+]Fitting different instances of `LinearSVR` is not thread-safe[/+] on Aug 27, 2025
  6. ayushmanpani commented on Jan 21, 2026

    @ayushmanpani

    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.

  7. removed theissue type on Apr 8, 2026
  8. Higgs32584 commented on Oct 9, 2026

    @Higgs32584
    Contributor

    mt_rand in sklearn/svm/src/newrand/newrand.h was 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_rand as thread_local. Nothing else needs to change in the C/C++ or Cython code. This is sufficient because set_seed() is always called from the same thread that then runs the solver:

    • liblinear: train_wrap calls set_parameter (which seeds) and then train in the same call.
    • libsvm: svm_train and svm_cross_validation seed at their start.
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