Repository navigation
Conversation
Use _parallel_thread_map instead of joblib's Parallel to fit the trees of forests, unless the user set a joblib backend with parallel_config. With many threads, joblib's per-task overhead dominates, especially on free-threaded Python: on a 344-thread machine, free-threaded 3.14 with a plain thread pool fits forests 1.2-3x faster than GIL 3.14 with joblib. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ThreadPoolExecutor starts its threads lazily, one per submitted task. With the GIL, each start then waits for the GIL held by the threads already running tasks: on a 344-thread machine, forests took up to 1.5x longer to fit than with joblib, which starts its workers first. Not without the GIL: idle threads all woken at once by the submitted tasks get crowded onto a few CPUs (up to 30 trees on one CPU), while lazily started threads each land on an idle CPU. Co-Authored-By: Claude Opus 5.5 <[email protected]>
With check_input=False, trees skip check_classification_targets and convert sample weights directly instead of calling check_array, and _check_categorical_features skips narwhals for NumPy arrays. With many threads on free-threaded Python, these per-tree checks were contended locks: function-level imports in narwhals (sys.modules), the lru_cache of inspect.getattr_static, and the warnings module lock. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…llel catch_warnings and resetwarnings swap the process-wide warning filters, which isn't thread-safe: with many threads, tasks could leave the filters stale or reset, losing the user's filters and raising spurious warnings. Threads of the caller's process (or inheriting its context, with context-aware warnings) already have the caller's filters, so they are now kept as is. This also removes a contended lock on free-threaded Python. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Oct 6, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Reference Issues/PRs
Built on top of scikit-learn#34914 (
_parallel_thread_map, by @itamarst), at3212e320bf. Benchmarks: probabl-ai/scikit-learn-benchmarks#137. Related: scikit-learn#20666 (threads awaiting the GIL in forests), scikit-learn#32631 (spuriousdelayedwarnings on free-threaded Python).What does this implement/fix? Explain your changes.
Technical improvements of the parallelism of forest fitting, no change to the tree algorithm:
_parallel_thread_mapinstead of joblib'sParallel. If the user set a joblib backend (parallel_config(backend=...)), joblib is still used: there is no public joblib API to know whether a backend is set, so_joblib_backend_is_setreads joblib's active config (joblib.parallel._backend, available in joblib >= 1.4, our minimum).ThreadPoolExecutorstarts its threads lazily, one per submitted task, so each new thread waits for the GIL held by the threads already fitting trees._parallel_thread_mapnow starts all its workers first, only when the GIL is enabled. Without the GIL, starting them first makes things much worse (see below).check_input=False(as forests call trees), trees no longer callcheck_classification_targetsandcheck_array(sample weights are converted directly, their length is still checked), and_check_categorical_featuresskips narwhals for NumPy arrays. These per-tree checks were contended locks with many threads on free-threaded Python (see below).Paralleltasks running in the caller's process (or inheriting its context, with context-aware warnings) no longer reset and re-add the warning filters. On Python without context-aware warnings,catch_warningsswaps the process-wide filters, which isn't thread-safe: with many threads, the user's own filters could be lost, and spurious "delayedshould be used withParallel" warnings raised. Per-task overhead: ~50 -> 28 us (8 threads).Behavior changes:
verboseno longer prints joblib's progress lines in forest fit (theverbose > 1"building tree" messages remain);fit(..., check_input=False)on trees skips the target and sample weight validation, as the parameter's docstring says.AI usage disclosure
I used AI assistance for:
Benchmarks
probabl-ai/scikit-learn-benchmarks#137,
mainfit time / this branch fit time, 31 forest cases (synthetic and real datasets,n_jobs=-1or 154):The 3 GIL "slower" cases are within noise (0.93-0.95x); the free-threaded one is
ExtraTreesRegressoron the 1M x 1 synthetic data.The first run (
05e2875d7b, thread map only) had 15 GIL slowdowns (down to 0.50x): the lazy thread start-up, fixed by87da72c560.Does it need the thread map? This branch, thread map vs joblib fallback (
parallel_config(backend="threading"), so with the fixed warning filters handling and no per-tree validation too), intel-gnr, fit time (s), 3 runs, one fresh process per fit.PYTHON_TLBC=0(thread-local bytecode off) stands for the CPython fix of the specialization convoy (see below):RandomForestClassifier, 688 trees, 344 threadsPYTHON_TLBC=0ExtraTreesClassifier, 616 trees, 154 threadsPYTHON_TLBC=0RandomForestClassifier, 616 trees, 154 threadsPYTHON_TLBC=0With the GIL, both are on par. Free-threaded, the thread map is 2-10x faster, and still 1.5-4x faster without the specialization convoy.
Any other comments?
Why free-threaded Python gains so much (intel-gnr, 344 threads, 100k x 20): joblib's workers, like a thread pool whose workers are started first, all start their trees at the same time. They then hit the same locks at the same time, get them one by one, and stay in lockstep for the next ones: lock convoys. With lazily started threads, the starts are staggered and they rarely collide. Native stacks (gdb) during slow fits showed most of the threads parked on:
_Py_Specialize_LoadGlobal: with thread-local bytecode, each thread specializes its own copy of every function it runs, and eachLOAD_GLOBALspecialization locks the module globals and the builtins dict. Fixed on CPython main (Lock contention inside _Py_Specialize_LoadGlobal under free threading python/cpython#152075), not backported to 3.14 / 3.15. WithPYTHON_TLBC=0, a thread pool with all its workers started first: 17-23 s -> ~5 s; the lazy thread pool: 2.1 s either way.check_array:sys.moduleslookups of its function-level imports, and thelru_cachebehindinspect.getattr_static. Removed from the per-tree path here; worth reporting to narwhals.warningsmodule lock, taken by the per-task warning filter handling ofsklearn.utils.parallel(joblib path only). Fixed here.Not thread placement (pinning each thread to its own CPU didn't help), not the GC, not NUMA balancing: all tried, no effect.
🤖 Generated with Claude Code