Skip to content

PERF New parallelism API with lower overhead - #34914

Closed
itamarst wants to merge 26 commits into
scikit-learn:mainfrom
itamarst:isolation-forest-faster-parallelism
Closed

itamarst wants to merge 26 commits into
scikit-learn:mainfrom
itamarst:isolation-forest-faster-parallelism

Conversation

@itamarst

@itamarst itamarst commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

joblib.Parallel has significant performance overhead. sklearn.utils.parallel.Parallel has even more. That means parallelism becomes pointless in some cases, because the overhead of using these APIs drowns out the benefits of parallelism.

This PR introduces a new parallelism API with lower overhead, and switches the IsolationForest prediction algorithm to use it instead of Parallel() as a demonstration of the benefits.

Background

#28622 introduced parallelism for IsolationForest prediction. However, it did not enable parallelism by default, because for smaller samples the overhead made the parallel version slower.

Speed-up of IsolationForest enabled by this PR

With this PR, the speed of predicting large number of samples is essentially the same (so I omitted this from the plots below because it obscures the improvements on small numbers of samples). However, because of lower overhead:

  • Parallelism is now almost always faster than parallelism. Even in the worst case, previously it was much faster in the 100 samples case, now it's only slightly worse given how much faster all of this is for 100 samples.
  • For smaller number of samples, the lower overhead speeds up results.

Here's a plot of before and after using this API, generated with bench_plot_isolation_forest_predict.py (with the 50,000 sample case disabled; for that value there's no benefit in the new API):

out

Question for reviewers

Since parallelism is now useful in almost all cases, and less harmful when it's not, it is worth turning it on by default?

AI: None

Future work

@itamarst itamarst changed the title New parallelism API with lower overhead PERF New parallelism API with lower overhead Sep 9, 2026
@itamarst
itamarst marked this pull request as ready for review September 9, 2026 18:53
@itamarst

itamarst commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

@cakedev0 Relevant to your interests?

@cakedev0

Copy link
Copy Markdown
Member

Happy to follow! Thanks for the cc 👍

Not sure I can have an opinion on introducing a new parallelism API without more context about joblib & free-threaded. But I can talk with Loic & Olivier today to try getting a better view of the context.

@jeremiedbb

Copy link
Copy Markdown
Member

joblib.Parallel has significant performance overhead.

My first reaction before considering an alternative to joblib is: is it possible to reduce joblib's overhead ?

@cakedev0

Copy link
Copy Markdown
Member

@jeremiedbb, in #34747 (comment) Itamar wrote (a while ago):

I considered reducing joblib overhead in joblib itself, but it's very complex, with a lot of backwards compatibility requirements; this is much simpler and much less constrained by the need to support every edge case. And scikit-learn only uses a subset of joblib's functionality, which also makes it easier.

Unsure if it still stands

@jeremiedbb

Copy link
Copy Markdown
Member

I considered reducing joblib overhead in joblib itself, but it's very complex, with a lot of backwards compatibility requirements; this is much simpler and much less constrained by the need to support every edge case. And scikit-learn only uses a subset of joblib's functionality, which also makes it easier.

but then the overhead stays for all other joblib users. If it's actually possible to reduce joblib's overhead I think it would be a lot more valuable to do that.

I understand the simplicity tradeoff though. And we could actually include this in the mean time to have sklearn benefit from the speed up right away rather than waiting to bump joblib min version. But I think that both should be started jointly.

@itamarst

Copy link
Copy Markdown
Contributor Author

Overhead numbers

Some approximate numbers for context. If you run 1000 noop functions on 8 cores, you're measuring pure overhead. Here's the runtime for different thread pools, run with Python 3.14 free-threaded:

Runner Total runtime in microseconds
sklearn 25,000
joblib 23,000
ThreadPoolExecutor 7,500
spinningjenny 900

If you do the "delayed() for task" idiom that scikit-learn uses, instead of "delayed() once" that this benchmark does, the overhead is even higher...

Optimizing joblib

I did indeed look into making joblib faster. My first idea was a fast path bypass, where it just switched to a faster mechanism in restricted cases. It proved harder than I expected.

I'm sure it's technically possible if I put more time into it, but joblib is complicated. It has batch dispatching of tasks, and different return_as types, and timeouts, and pluggable backends, and an API approach that I honestly think was a mistake.

Most of this wasn't a problem until now. With process-based workers, you don't want to use lots of tasks anyway, so high overhead gets amortized over a small number of long-running chunks of work and so is less of an issue.

So my takeways were:

  • joblib's current speed is OK in many cases, especially as used in scikit-learn.
  • Achieving the full level of speed you can get from ThreadPoolExecutor would be tricky because there's so much there in joblib.
  • Some of joblib's functionality will become irrelevant in a plausible future world where threading is the default (timeouts and pre-dispatching, for example).
  • Given all the above, my thought was the long-term outcome might be Parallel() becoming unnecessary; if you don't need pluggable backends, and don't use processes so don't need timeouts or batching, does it really add much?

Of course, since joblib is currently widely used, making it faster is a good thing. So if a prerequisite for this PR is spending some time on making joblib faster too, I can do that. But it may be tricky to make it as fast as something that bypasses all that complexity, given the way that Python abstractions end up adding performance costs.

@lorentzenchr

lorentzenchr commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

There is prior art in using concurrent.futures.ThreadPoolExecutor in #28064 (and follow-up #29386).

@itamarst

Copy link
Copy Markdown
Contributor Author

Thanks for the links! So ThreadPoolExectur was added, and then removed because it was no faster and broke some things.

My benchmarks suggest that ThreadPoolExecutor is faster, contra what was in those PRs, so that's the motivation for switching the implementation.

The motivation for using an abstraction layer here instead of ThreadPoolExecutor directly is to address some of the issues that came up in the linked PRs that motivated switching back to joblib:

  • There are various nice things you need to layer top on a thread pool. E.g. _parallel_thread_map() allows for n_jobs = 1 to be sequential, and so ought to make pyodide work (or possible to work). It also allows for things like the sklearn config, warnings configuration, and eventually over-saturation protection without having to redo that logic repeatedly.
  • I would like to eventually switch to https://github.com/Quansight/spinningjenny/ instead of ThreadPoolExecutor since that will reduce the overhead by an additional 80%, and having a single pluggable abstraction should help with that.

@ogrisel ogrisel added this to Labs Sep 14, 2026
@ogrisel ogrisel moved this to PR waiting for reviews in Labs Sep 14, 2026
@itamarst

Copy link
Copy Markdown
Contributor Author

Another example where this can make a real difference is #4769. Some benchmarks I shared there:

joblib.Parallel:

done in 3.502s, with n_jobs = 1.
done in 2.870s, with n_jobs = 4.
done in 3.484s, with n_jobs = 8.

ThreadPoolExecutor:

done in 3.477s, with n_jobs = 1.
done in 2.274s, with n_jobs = 4.
done in 1.308s, with n_jobs = 8.

ThreadPoolExecutor, reusing the pool instead of creating a new one each time (not implemented in this PR; if/when this gets merged, I will likely do this as part of a PR for #4769).

done in 3.457s, with n_jobs = 1.
done in 1.117s, with n_jobs = 4.
done in 0.751s, with n_jobs = 8.

Comment thread sklearn/ensemble/_iforest.py Resolved
Comment thread sklearn/utils/parallel.py Resolved
Comment thread sklearn/utils/parallel.py Resolved
Comment thread sklearn/utils/parallel.py Resolved
Comment thread sklearn/utils/parallel.py Resolved
Comment thread sklearn/utils/parallel.py Resolved
Comment thread sklearn/utils/tests/test_parallel.py Resolved
Comment thread sklearn/utils/tests/test_parallel.py Resolved
Comment thread sklearn/utils/tests/test_parallel.py Resolved
Comment thread sklearn/utils/tests/test_parallel.py Resolved
@lorentzenchr

Copy link
Copy Markdown
Member

I think it is sound and safe to use the standard library of Python. And this PR shows nice improvements for some use cases.

@lorentzenchr

Copy link
Copy Markdown
Member

"let's be adventurous"

I don’t think relying on the Python Standard Library is advanturous. If any, it is sound and safe.

Comment thread sklearn/utils/parallel.py Resolved
@lorentzenchr

Copy link
Copy Markdown
Member

@scikit-learn/core-devs Are there any concerns left? If not, I intend to merge in about a week.

@itamarst

itamarst commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

I would like to first:

  1. Rerun benchmarks; adding the joblib backend initialization might change things somewhat.
  2. Explain some future changes I will need to do to match in-progress joblib features.

I will do both next week when I return from travels.

@cakedev0

Copy link
Copy Markdown
Member

@lorentzenchr let's wait for more people to have a look before merging. I'd prefer to have a good consensus and confidence on this one before merging. So one it's merged we can quickly start using it in many places.

@betatim

betatim commented Oct 14, 2026

Copy link
Copy Markdown
Member

I'd like us to try and move towards making things simpler and more consistent for users. For example, right now you have n_jobs to control "using more than one core". However, if you use it you might get oversubscription because libraries used to do the work already use multiple threads. I don't know if we have a recommendation/simple recipe somewhere already that would explain how to figure out what to set n_jobs to so that it does "the right thing" (make your code run faster and use more of your hardware). All I know off the top of my head is that "naively setting it to a bigger number is as likely to make things slower as it is to make it faster".

If you add free threading to the mix it seems like things will not get simpler for users.

I don't know if adding "yet another way" to do things in parallel is a step towards improving the situation for users or not. In particular because at least some of the motivation for this PR reads as (simplified): I disagree with how complex joblib is and if we do less we can make things go faster. I don't think we want to grow more ways of "make your code run faster and use more of your hardware". Today it is already hard for users to understand and do the right thing. There is also maintenance cost to having several ways of doing things.

I've not spent enough time on this topic to figure out: what are the reasons for the current amount of user facing complexity? What can we do about reducing it? What of that work is work in scikit-learn? Basically, some kind of holistic view of making life better for users, letting them use more of their hardware and get speed ups because of it. Right now it feels like we started from "how can we make scikit-learn faster?" which in my opinion is not the first question to ask/answer.

The approach in this PR might be the way to go, but let's discuss it and illustrate why it is (from the point of view of making life better for (average) users). What are the trade offs and compromises?

@itamarst

itamarst commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor Author

As of the next release of joblib, oversaturation problems are (mostly) going to be solved, hopefully. Probably will be some follow up work, but the core problem will be solved.

First, threadpoolctl will be used to control number of nested BLAS and OpenMP thread pools in joblib when using the threaded backend; in released versions it's just Loky.

Second, n_jobs = -1 will switch from meaning "all cores available to this process" to "all cores available to this thread", with Python thread pools slicing available cores for worker threads. In practical terms, if you have nested Python thread pools using joblib, and they all use n_jobs=-1, it should do the right thing and prevent oversaturation. If your machine has 10 cores, and a parent thread pool uses 5 cores, worker threads will get 2 cores each if they do n_jobs = -1 or use BLAS/OpenMP.

(This is the extra work I mentioned that needs to be done in this PR to match joblib once new joblib is out; essentially an extra 2-3 lines that will integrate the infrastructure I've built in joblib for this.)

Insofar as oversaturation was a motivation to not use threads, or oversaturation was a motivation not to enable parallelism by default, those problems will be (mostly) solved.

Relevant PRs:

And there was also some work on the threadpoolctl side.

@lesteve

lesteve commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

I am assuming there will still be some performance issues left in joblib.Parallel(backend='threading') even when all the ongoing work mentioned in #34914 (comment) ends up in a joblib release? I may be wrong about this though.

Assuming there are still performance issues with joblib.Parallel(backend='threading') after all the ongoing work is in a joblib release, my personal reading on the broad consensus based on discussions in our Monday weekly meetings 1.

  1. this PR is certainly useful to identify that joblib.Parallel(backend='threading') is sub-optimal and have some kind of ceiling for performance
  2. we should try to understand where the joblib.Parallel(backend='threading') performance issues come from.
  3. we should try to fix them in joblib as much as possible

Of course, if it turns out after trying some time that 2. and 3. are too complicated and not worth the effort, there is a world where we can revisit this.

Footnotes

  1. we could certainly improve how we make these discussions more easily accessible for people who are not at the Monday weekly meetings 😓 ↩

@cakedev0

Copy link
Copy Markdown
Member

Of course, if it turns out after trying some time that 2. and 3. are too complicated and not worth the effort, there is a world where we can revisit this.

I think it's already a bit the conclusion @itamarst reached, see: joblib/joblib#1830 (comment) (and preceding comments)

@itamarst

Copy link
Copy Markdown
Contributor Author

I am assuming there will still be some performance issues left in joblib.Parallel(backend='threading') even when all the ongoing work mentioned in #34914 (comment) ends up in a joblib release?

Yes. The work on oversaturation in joblib is orthogonal to this PR, which is about the overhead from joblib.Parallel and all its abstractions and features.

@itamarst

Copy link
Copy Markdown
Contributor Author

Given the skepticism I'm hearing, I'm going to put this on hold and see how far I can get speeding up joblib.Parallel in the threaded case.

@itamarst
itamarst marked this pull request as draft October 15, 2026 13:59
@lorentzenchr

Copy link
Copy Markdown
Member

Let‘s summarize:
Threads are the future of (single worker) parallelism in Python.
There are 2 main problems for thread-parallelism:

  1. oversubscription
  2. overhead of the mechanism (pool/executor) to handle threads / get a thread

1. Oversubscription

This one is mostly solved with a new joblib release (in the future). In scikit-learn, we rely on joblib for detecting "number of threads to use".
This PR does not change that.

2. Overhead to deal with threads

This is what this PR is about. It matters for users when many small jobs are send to threads. For instance, HGBT (just for illustration, not applicable for this PR) calls roughly some_constant * max_iter * n_features * n_splits threads.
This PR simply uses ThreadPoolExecutor (TPE) from the Python Standard Library (PSL) instead of joblib Parallel. Note that TPE is newer than joblib. It is therefore no suprise that it is faster. As part of the PSL, it is future proof.
This is a pure internal change, the user does not even has to know. Things should just work nicer out of the box.

Way forward

I interpret the questions not as skepticism but as interest in this topic. It is correct that an overview with coclusions and a plan of work was missing (what issues are for). I hope it is clearer now (for me it is clearer, not 100% but better than before).

@adam2392

Copy link
Copy Markdown
Member

Thanks for the summary @lorentzenchr !

@itamarst

Copy link
Copy Markdown
Contributor Author

I think it's useful to have joblib be faster, so certainly can do both that and this PR at the same time. (The joblib PR will I think demonstrate why I want to to bypass joblib when possible, huge number of features and backwards compatibility edge cases most of which are irrelevant to scikit-learn.)

But also: since this PR is a different API, in cases where you want configurability of backend (i.e. supporting both threading and Loky) you'd have to have two different code paths. Which is not great. So doing both is useful in that:

  1. If you're only using threading, you can use a nicer, simpler new API.
  2. If you want configurability of backend, joblib threaded backend will be faster than it used to be without having to have two code paths. It won't be as fast as the new API in this PR, though, just because there's just all this extra backwards compat needed in joblib.

@lesteve lesteve removed the Waiting for Second Reviewer First reviewer is done, need a second one! label Oct 16, 2026
@cakedev0

Copy link
Copy Markdown
Member

Thanks @lorentzenchr and @itamarst for your summaries, it's very helpful!

I think the idea of having both joblib and this API makes a lot of sense!

IIUC, jolib has three main features:

  1. making process based parallelism more usable (dispatch, memmap, ...). Process based parallelism exists to work around the GIL, it will become irrelevant if/when CPython free-threaded becomes the norm.
  2. configurability (esp. dispatching to distributed backends like dask)
  3. handling over-subscription concerns for inner parallelism

Those features are geared towards outer-parallelism and they are great for that, but they cost overhead. For now, if you want to do some simple inner-parallelism in scikit-learn, you are forced to either:

  • pay this overhead
  • implement it with a prange in Cython nogil (but you loose access to the very optimized np.sort for instance)
  • (or you workload is BLAS dominated and you have inner parallelism by default)

Having the option for some simple & low-overhead Python threads inner-parallelism would be very useful. I think there are plenty of places where we don't do inner parallelism because we lack such a tool.

Conclusion: I'm strongly in favor of introducing a new API that is not joblib. But it's a big thing so we should take our time and try to get it right.


Some requirements/notes for getting this new API right:

  • If this API is used under joblib outer-parallelism, it needs to avoid over subscription. Implementation of this PR does that thanks to calling joblib.effective_n_jobs(n_jobs) under with joblib.parallel_config(require="sharedmem"): (but is it enough?)
  • This API should never be used for a task that might have inner parallelism (other Python threads, BLAS, OpenMP, joblib), so it doesn't have to prevent over-subscription like joblib does.
  • All calls to Parallel(require="sharedmem") or Parallel(backend="threading") should be ok to replace by this API, as long as they respect the point above. I think? If it's not the case, it would be interesting to know what additional requirements this API has to respect for that be be true. Maybe supporting verbose progress messages, but I'd say this is an acceptable behavior change.

Some candidates where I'd like to use this new API:

  • finding the binning thresholds in HGB (currently Parallel(backend="threading") and the over-head makes it counter-productive for small datasets.
  • column-based pre-processing, like encoders for instance.
  • Itamar showed text pre-processing would also benefit from it

@ogrisel

ogrisel commented Oct 16, 2026

Copy link
Copy Markdown
Member

Thanks for the summaries.

For the short term, I think I would rather put the effort on improving the joblib threading backend as much as we can before deciding to introduce an alternative Python threading API.

@lorentzenchr

lorentzenchr commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

For the short term, I think I would rather put the effort on improving the joblib threading backend as much as we can before deciding to introduce an alternative Python threading API.

As you are not the first one with such an opinion, may I ask for the reasons? (addressed to everybody who shares this opinion)

@ogrisel

ogrisel commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

As you are not the first one with such an opinion, may I ask for the reasons? (addressed to everybody who shares this opinion)

I would rather keep the parallelization story in scikit-learn not too complex. Currently we already have the following mechanisms:

  • (a) joblib without backend restrictions (currently defaults to process-based parallelism with loky);
  • (b) joblib with shared memory constaints (in trees, defaults to thread-based parallelism);
  • (c) OpenMP in Cython code via prange;
  • (d) BLAS related parallelism (managed by OpenMP or something else depending on the BLAS implementation).

If we had an extra option (mostly as a potential alternative to (b) and sometimes (a)), this will make it a bit harder to make decisions when reviewing PRs as of which backend is the best for a particular piece of code and it will make it even more complex to explain to users how scikit-learn parallelism works and how public API options and environment variables impact the expected scalability behavior of their workloads, especially when parallel operations are nested together.

Also, if we can reduce the overhead of the threading backend of joblib, this could benefit other projects rather than just scikit-learn.

@cakedev0

cakedev0 commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

(b) joblib with shared memory constaints (in trees, defaults to thread-based parallelism);

I would propose to replace this by a threads-only API simpler and faster than joblib.Parallel. It could be:

  1. improvements and threads-only short-cuts in joblib.Parallel: unsure it's enough and personally, I'm not a fan of having a single user-facing tool hacked to serve two fairly different purposes, I prefer librairies to expose more APIs and re-use code internally if/when it makes sense.
  2. a new API in joblib, something like joblib.ThreadsParallel
  3. a new API in scikit-learn like what this PR proposes, but I don't think it's the best option as this parallelism layer has to interact with joblib, so we might as well put it in joblib.

@ogrisel

ogrisel commented Oct 26, 2026

Copy link
Copy Markdown
Member

Note that some overhead of the joblib threading backend is being optimizes away by @itamarst the joblib/joblib#1899

@ogrisel ogrisel removed this from Labs Nov 2, 2026
@itamarst itamarst closed this Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

module:ensemble module:utils Parallelism and scalability All things related to efficient handling of cores via thread-based or process-based parallelism. Performance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants