Repository navigation
Description
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.moduleslookups of function-level imports and thelru_cachebehindinspect.getattr_static, both from narwhals' dataframe checks incheck_array; - the
warningsmodule lock, taken by the per-task warning filters handling ofsklearn.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_mapof 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=Falseno longer callscheck_arrayper tree). sklearn.utils.parallelno longer resets the warning filters in each task (now in its own issue and PR: BUG: thread-basedParallelcan 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 "delayedshould be used withParallel" 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 likeinspect.getattr_static;importstatements inside functions;isinstancechecks against an ABC, true or false, includingscipy.sparse.issparse(isinstance(x, SparseABC)): the ABC's caches are sets shared by all threads, and each lookup takes the set's lock. So everyissparse(ndarray)call from every thread goes through onePyMutex;- input validation (
check_arrayand 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:
-
LOAD_GLOBALspecialization contention: Lock contention inside _Py_Specialize_LoadGlobal under free threading python/cpython#152075 (fixed on CPythonmain, backported to 3.14 in [3.14] gh-152075: Avoid lock contention in _Py_Specialize_LoadGlobal under free threading (gh-153720) python/cpython#158904, 3.15 backport in [3.15] gh-152075: Avoid lock contention in _Py_Specialize_LoadGlobal under free threading (gh-153720) python/cpython#158905) -
PyMutexfair handoff makes contention collapse: Free-threading scalability issue: contended PyMutex collapses with a few tens of threads (fair handoff) python/cpython#158901 - joblib's threading backend overhead: joblib.Parallel with threading backend is a lot slower than concurrent.futures.ThreadPoolExecutor joblib/joblib#1830
- narwhals' dataframe checks contend (mostly
inspect.getattr_static): not reported yet, depends on Free-threading scalability issue: contended PyMutex collapses with a few tens of threads (fair handoff) python/cpython#158901 -
issparsecontends on the ABC cache ofSparseABC: not reported yet. Seen with gdb ontest_partial_dependence_non_null_weight_idxwith--parallel-threads 14(all but one thread waiting inissparsefromTree.apply), once thewarningslock contention was removed. A fast path inissparsefor exact types (scipy) or lock-free ABC cache lookups (CPython) would avoid it -
multiprocessing.pool.ThreadPool.terminate()doesn't join its threads: already reported in multiprocessing.dummy.Pool not joining threads on shutdown python/cpython#107616, no performance impact seen
scikit-learn:
- Forests (PERF Lower overhead thread pool and fewer contended locks in forest fit cakedev0/scikit-learn#19):
- lazy thread pool: should be less needed once Lock contention inside _Py_Specialize_LoadGlobal under free threading python/cpython#152075 is in. With
PYTHON_TLBC=0as a stand-in for that fix, joblib was still 1.5x to 4x slower on 344 threads with fast-to-build trees (0.1 to 1 s each). The gap shrinks for slow-to-build trees (~1.1x for year_prediction_msd). - no per-tree validation (works around the narwhals contention, and saves a
check_arrayper tree)
- lazy thread pool: should be less needed once Lock contention inside _Py_Specialize_LoadGlobal under free threading python/cpython#152075 is in. With
- Warning filters race/lock in
sklearn.utils.parallel(bug onmain): BUG: thread-basedParallelcan corrupt the process-wide warning filters #35089, fixed by FIX Don't reset the warning filters in each task of thread-based Parallel #35090 - Audit the other thread-parallel code paths on a many-core machine (list above)
- Write down what to watch for, for contributors (see Explicit documentation / contract for free-threading #34596)
Activity
cakedev0 commentedon Oct 6, 2026
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
cakedev0 commentedon Oct 26, 2026
Quick update: CPython 3.14.9 (released on Oct 21) includes the
LOAD_GLOBALspecialization 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:main, GIL 3.14.7main, GIL 3.14.9main, free-threaded 3.14.7tmain, free-threaded 3.14.9tmainis gone: 12 to 14 s -> ~4 s.mainfree-threaded is still ~1.6x slower than with the GIL, and PERF Lower overhead thread pool and fewer contended locks in forest fit cakedev0/scikit-learn#19 is still ~5.5x faster thanmainon 3.14.9t.3.14.10 (Oct 25) also has the fix. I used 3.14.9 because conda-forge doesn't have 3.14.10 yet.