Skip to content

META: lock contention can make thread-parallel code collapse on many-core machines (free-threading) #35091

Open

Description

@cakedev0

On free-threaded Python, a lock that many threads take at the same time can make thread-parallel code collapse on a machine with hundreds of cores, while the same code looks fine on a laptop. I hit this with random forests. I'm opening this issue to share what I found, discuss how to avoid it in scikit-learn, and track the related work.

How I got here

As you might know, I'm benchmarking scikit-learn on several machines, one of them is a 2 x 86-core Xeon 6787P (344 hardware threads).

On this machine, random forests fitted with 344 threads (what you get with n_jobs=-1) were often slower on free-threaded 3.14 than with the GIL (median 0.45x over 31 representative benchmark cases). For instance, the reproducer below takes ~3s with the GIL and ~12s free-threaded.

With gdb, I first found most threads parked on CPython's LOAD_GLOBAL specialization lock (python/cpython#152075, fixed on CPython main).

Then I saw the same collapse on other locks, taken once per tree:

  • the sys.modules lookups of function-level imports and the lru_cache behind inspect.getattr_static, both from narwhals' dataframe checks in check_array;
  • the warnings module lock, taken by the per-task warning filters handling of sklearn.utils.parallel.

The slowdown always appeared suddenly past a few tens of threads. This comes from CPython's locks (python/cpython#158901): once a thread has waited more than 1 ms, each lock acquisition costs a thread wake-up, so the waits get longer and the lock never gets back to the fast path. On a 14 or 16-core laptop this threshold is barely reached, so nothing shows.

Reproducer

import time

from sklearn.datasets import make_classification
from sklearn.ensemble import ExtraTreesClassifier

X, y = make_classification(n_samples=100_000, n_features=20, random_state=0)
clf = ExtraTreesClassifier(n_estimators=688, n_jobs=-1, random_state=0)
tic = time.perf_counter()
clf.fit(X, y)
print(f"fit: {time.perf_counter() - tic:.2f} s")

Fit time on the 2 x 86-core Xeon 6787P, 3 runs, one fresh process per run:

GIL (3.14.7) free-threaded (3.14.7t)
main (6ad9bb9) 2.2 to 3.3 s 12.3 to 13.0 s
cakedev0#19 1.7 to 1.9 s 0.70 to 0.74 s

What fixed it for forests

cakedev0#19 makes the reproducer 17x faster free-threaded:

  • Trees are fitted with a thread pool that starts its threads lazily, one per task (ThreadPoolExecutor, through the _parallel_thread_map of PERF New parallelism API with lower overhead #34914). The threads start a bit apart, so they rarely take the same lock at the same time. joblib's threading backend starts all its workers before dispatching, so they run the same code in lockstep. With the GIL it's the opposite: starting the workers first is faster, so the thread pool does that only when the GIL is enabled.
  • Trees don't validate again the inputs already validated by the forest (check_input=False no longer calls check_array per tree).
  • sklearn.utils.parallel no longer resets the warning filters in each task (now in its own issue and PR: BUG: thread-based Parallel can corrupt the process-wide warning filters #35089, FIX Don't reset the warning filters in each task of thread-based Parallel #35090). This also fixes a race on GIL Python with threads: the user's warning filters could be silently lost, and spurious "delayed should be used with Parallel" warnings raised.

What to watch for

Code that runs in many threads at the same time should avoid process-wide locks in each task. The ones I found:

  • warnings.catch_warnings() and changes of the warning filters;
  • functools.lru_cache'd functions (cache hits included), including stdlib ones like inspect.getattr_static;
  • import statements inside functions;
  • isinstance checks against an ABC, true or false, including scipy.sparse.issparse (isinstance(x, SparseABC)): the ABC's caches are sets shared by all threads, and each lookup takes the set's lock. So every issparse(ndarray) call from every thread goes through one PyMutex;
  • input validation (check_array and its narwhals checks): validate once, before the parallel loop.

Benchmarks on 16 cores can hide a 10x to 100x collapse. Close to the threshold, timings are also bimodal (4.8 to 9.6 s for the same fit at 344 threads), so repeats are needed.

Note for benchmarks: measure warm fits too (several fits in one process), not only fresh processes. On free-threaded Python, the LOAD_GLOBAL specialization contention is paid by the first fit only: on main, the reproducer's first fit takes 10 to 12 s, the next ones ~4 s.

Thread-based parallelism in scikit-learn today: forests (fit, predict, apply, decision_path), IsolationForest, neighbors queries, pairwise_distances, SGD one-vs-all, coordinate descent paths, HGB binning, and LogisticRegression free-threaded.

Tracking

Upstream:

scikit-learn:

Related issues

Activity

  1. added
    Needs Triage
    on Oct 6, 2026
  2. added
    Meta-issue
    free-threading
    and removed
    Needs Triage
    on Oct 6, 2026
  3. cakedev0 commented on Oct 6, 2026

    @cakedev0
    MemberAuthor

    cc @itamarst

    And cc @ogrisel and @lesteve: this summaries my findings and will track advances for the subject I started sharing during yesterday's call

  4. cakedev0 commented on Oct 26, 2026

    @cakedev0
    MemberAuthor

    Quick update: CPython 3.14.9 (released on Oct 21) includes the LOAD_GLOBAL specialization fix (python/cpython#158904), so I re-ran the reproducer on the same machine (2 x 86-core Xeon 6787P, 344 threads). Same commits as above, 3.14.7 and 3.14.9 interleaved, 3 fresh processes per config, 4 fits per process:

    first fit next fits
    main, GIL 3.14.7 2.4 to 2.6 s 2.1 to 3.3 s
    main, GIL 3.14.9 2.0 to 2.6 s 1.9 to 3.4 s
    main, free-threaded 3.14.7t 12.0 to 14.1 s 3.8 to 4.5 s
    main, free-threaded 3.14.9t 3.8 to 4.0 s 2.4 to 4.1 s
    cakedev0#19, GIL 3.14.9 1.6 to 1.7 s 1.5 to 2.3 s
    cakedev0#19, free-threaded 3.14.9t 0.70 to 1.07 s 0.64 to 0.69 s

    3.14.10 (Oct 25) also has the fix. I used 3.14.9 because conda-forge doesn't have 3.14.10 yet.

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

    Meta-issuePerformancefree-threading

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions