Skip to content

PERF Lower overhead thread pool and fewer contended locks in forest fit - #19

Open
cakedev0 wants to merge 4 commits into
isolation-forest-faster-parallelismfrom
perf/forest-fit-thread-map
Open

cakedev0 wants to merge 4 commits into
isolation-forest-faster-parallelismfrom
perf/forest-fit-thread-map

Conversation

@cakedev0

@cakedev0 cakedev0 commented Oct 2, 2026 •

Copy link
Copy Markdown
Owner

Reference Issues/PRs

Built on top of scikit-learn#34914 (_parallel_thread_map, by @itamarst), at 3212e320bf. Benchmarks: probabl-ai/scikit-learn-benchmarks#137. Related: scikit-learn#20666 (threads awaiting the GIL in forests), scikit-learn#32631 (spurious delayed warnings 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:

  • Thread pool: forests fit their trees with _parallel_thread_map instead of joblib's Parallel. 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_set reads joblib's active config (joblib.parallel._backend, available in joblib >= 1.4, our minimum).
  • Thread start-up with the GIL: ThreadPoolExecutor starts its threads lazily, one per submitted task, so each new thread waits for the GIL held by the threads already fitting trees. _parallel_thread_map now starts all its workers first, only when the GIL is enabled. Without the GIL, starting them first makes things much worse (see below).
  • No per-tree validation: with check_input=False (as forests call trees), trees no longer call check_classification_targets and check_array (sample weights are converted directly, their length is still checked), and _check_categorical_features skips narwhals for NumPy arrays. These per-tree checks were contended locks with many threads on free-threaded Python (see below).
  • Warning filters (bug fix, also on main): Parallel tasks 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_warnings swaps the process-wide filters, which isn't thread-safe: with many threads, the user's own filters could be lost, and spurious "delayed should be used with Parallel" warnings raised. Per-task overhead: ~50 -> 28 us (8 threads).

Behavior changes: verbose no longer prints joblib's progress lines in forest fit (the verbose > 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:

  • Code generation (closely guided)
  • Test/benchmark generation
  • Documentation (changelogs)
  • Research and understanding (profiling, native stacks with gdb)

Benchmarks

probabl-ai/scikit-learn-benchmarks#137, main fit time / this branch fit time, 31 forest cases (synthetic and real datasets, n_jobs=-1 or 154):

machine Python slower (< 0.95x) faster (> 1.05x) min median max
intel-gnr (2 x 86 cores, 344 threads) 3.14t 1 30 0.82x 5.57x 22.60x
intel-gnr GIL 3 24 0.93x 1.20x 2.25x
intel-laptop (16 cores) 3.14t 2 9 0.90x 1.01x 1.39x
intel-laptop GIL 0 10 0.96x 1.02x 1.66x

The 3 GIL "slower" cases are within noise (0.93-0.95x); the free-threaded one is ExtraTreesRegressor on 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 by 87da72c560.

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):

case Python thread map joblib
100k x 20, RandomForestClassifier, 688 trees, 344 threads GIL 4.01-4.24 3.78-4.11
3.14t 2.28-2.35 4.79-9.60
3.14t, PYTHON_TLBC=0 2.34-2.37 3.48-3.72
kick-like (58k x 32, DataFrame), ExtraTreesClassifier, 616 trees, 154 threads GIL 1.16-1.26 1.20-1.25
3.14t 0.43 3.52-3.82
3.14t, PYTHON_TLBC=0 0.45 1.08-1.33
amazon-like (26k x 9, DataFrame), RandomForestClassifier, 616 trees, 154 threads GIL 1.41-2.45 1.54-1.74
3.14t 0.45-0.46 4.09-4.52
3.14t, PYTHON_TLBC=0 0.47 0.90-1.94

With 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 each LOAD_GLOBAL specialization 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. With PYTHON_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.
  • narwhals' dataframe checks, called per tree through check_array: sys.modules lookups of its function-level imports, and the lru_cache behind inspect.getattr_static. Removed from the per-tree path here; worth reporting to narwhals.
  • the warnings module lock, taken by the per-task warning filter handling of sklearn.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

cakedev0 and others added 4 commits October 2, 2026 15:51
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant