Repository navigation
Description
Describe the workflow you want to enable
Process pools in sklearn will limit the number of threads used by OpenMP and BLAS. Thread pools will not set any limits.
Consider the following program, which lists how many threads are set for OpenMP/OpenBLAS/etc:
import joblib, sys
from sklearn.utils.parallel import Parallel, delayed
import threadpoolctl
def print_thread_pool_sizes():
for info in threadpoolctl.threadpool_info():
print(info["user_api"], info["internal_api"], f"threads: {info['num_threads']}")
with joblib.parallel_config(backend=sys.argv[1]):
Parallel(n_jobs=-1)([delayed(print_thread_pool_sizes)()])When run under the default backend, the loky process pool, I get:
$ python nested-parallelism.py loky
blas openblas threads: 1
blas openblas threads: 1
openmp openmp threads: 1
When run under the threading joblib backend, I get:
$ python nested-parallelism.py threading
blas openblas threads: 20
blas openblas threads: 20
openmp openmp threads: 20
This can lead to significant CPU oversubscription, depending on the semantics of the library:
- When using OpenBLAS, you will get a total of 40 (20 + 20) threads, since the limit is for a single thread pool shared by the whole process.
- When using OpenMP, you will get 400 (20 * 20) threads, since the limit is per operation starting a thread pool.
The result is code that runs slower, wasting CPU cycles, and not actually achieving any more work.
Describe your proposed solution
There are a number of scenarios:
Scenario 1: All cores: If the number of threads in a thread pool is the same as the number of (available) CPU cores, setting the OpenMP/BLAS limit to 1 will work correctly: no oversubscription, no cores sitting idle.
Scenario 2: All cores but 1 or 2: If the requested number of threads/processes is negative number -N in joblib, this is defined as "number of available cores + 1- N". I.e. this semantically suggests the users wants to saturate the cores, but leave a few cores for other tasks. Typically N will be small, e.g. 2 to leave one core free but use all others. In this case again setting the OpenMP/BLAS limit to 1 is the right thing to do.
Scenario 3: A hard-coded small number of cores, less than available cores: The remaining case is most likely when the number of cores is limited due to the way the algorithm works. For process pools joblib will already automatically set the number of threads in OpenMP/BLAS to max(cpu_count() // effective_n_jobs, 1). So for example if you have 10 cores and only starting a pool of size 5, OpenMP/BLAS will each be set to allow 2 threads. In a process pool, this works fine.
For a top-level thread pool, this heuristic works fine for OpenMP but not OpenBLAS, since the meaning of "2" is different: for OpenMP it means "2 threads for every operation started in the 5 threads, for a total of 2 * 5 == 10 threads", for OpenBLAS it means "2 threads for the whole process, for a total of 5 + 2 threads."
So this suggests two options; one could choose one, the other, or both:
- Documentation for algorithms with limited parallelism, suggesting that it's better to use processes in order to utilize all cores.
- Custom settings per parallelism mechanism: set OpenMP to
max(cpu_count() // effective_n_jobs, 1)and BLAS tocpu_count(). This could still lead to oversaturation in certain edge cases, but perhaps it's not as bad.
As a follow-up it looks like MKL at least can due OpenMP-style configuration, with a different API than the one
threadpoolctluses.
Describe alternatives you've considered, if relevant
This could be implemented in joblib, rather than in sklearn, but that's a more generic context; there are additional threaded libraries that it might grow support for over time, whereas sklearn has more restricted set. Still, this arguably also be done as the default joblib policy for thread pools.
Additional context
joblib.cpu_count() is aware of CPU resource constraints when running inside Linux containers, so its notion of "all available cores" is usually quite accurate.
I am happy to implement this.
I have also tested this on actual code, and OPENBLAS_NUM_THREADS=1 on an all-cores thread pool makes the resulting calculation run faster and reduce involuntary context switches. This is not a perfect experiment since OpenBLAS in threaded mode is often slower than single-threaded OpenBLAS for small tasks, so a better experiment would be with some code that uses OpenMP, if someone can suggest one.
Activity
github-actions commentedon May 24, 2026
Thanks for the work you've done so far. The goal of this comment is to set expectations.
Deciding on new features or substantial changes is a lengthy process. It frequently happens that no maintainer is available to take on this task right now.
Please do not create a Pull Request before a decision has been made regarding the proposed work. Making this decision can often take a significant amount of time and effort.
ogrisel commentedon May 26, 2026
Thanks for opening this issue.
For reference, joblib already implements a builtin protection against oversubscription when nesting thread-based parallelism under process-based parallelism by setting environment variables:
https://github.com/joblib/joblib/blob/5d1653a529af271083d2622ed760351e8348492f/joblib/_parallel_backends.py#L221-L248
I agree, that we should try to extend this protection when nesting any kind of thread-based parallelism under joblib-managed Python threads. We can prototype this with the help of the
threadpoolctl.threadpool_limitscontext manager and evaluate it on some typical workfload (e.g. across_validate(model, X, y, k=5)where models either use OpenBLAS (e.g. Ridge), OpenMP (e.g. HistGradientBoostingRegressor) or both (e.g. a pipeline with KMeans used as a transformer followed by Ridge for instance).I wasn't aware of this. I wonder what could be a good policy for the number of the threads for OpenBLAS when using the pthreads threading layer.
Note, that on some distributions such as conda-forge, it's possible to tell OpenBLAS to use the OpenMP threading layer:
as opposed to using the pthread threading layer of OpenBLAS:
We also need to conduct similar experiments for the Windows OpenMP implementation, macOS with the LLVM implementation + OpenBLAS, macOS with the newaccelerate implementation of BLAS and Linux and MKL with the TBB and OpenMP threading layers... and make sure that our oversubscription protection logic works well for all those runtime environments.
david-cortes-intel commentedon May 27, 2026
For MKL with TBB threading layer (note that the default is OpenMP), I think it would also be interpreted as number of threads per caller, not for the whole process, but setting them only through an environment variable would have no effect if launched on a thread from a process that already imported MKL.
CCing @mkrainiuk for further comment.
ogrisel commentedon May 27, 2026
We should keep in mind that thread scalability can also be negatively impacted by related problems such as:
We should keep those in mind in case we observe lower-than-expected scalability results when implementing and evaluating the proposed oversubscription mitigation strategy on actual scikit-learn pipelines.
itamarst commentedon May 28, 2026
@ogrisel Are there any existing benchmarks (or lacking that, examples in the docs) that match the scenarios you think are worth testing?
itamarst commentedon May 29, 2026
I would like to suggest that while testing various configurations is important and useful, lacking basic limits on nesting makes threading completely unusable in some configurations. So I would like to proceed with something basic, even if not ideal.
To demonstrate what I mean: consider
examples/model_selection/plot_grid_search_refit_callable.py. I updated it to haven_jobs=-1, and tried comparing process pool and thread pools.(See itamarst/thread-oversaturation-experiments branch: you can set
SKLEARN_THREADINGenvironment variable to enable thread pools.)The result:
OpenBLAS with OpenMP backend (from Conda-Forge)
Here's the process pool version:
It's much much slower with threads:
But if I disable OpenMP it's nice and fast again (faster than processes, even):
OpenBLAS with pthreads (PyPI)
Same results, just naive thread pool isn't quite as bad.
Process pool:
Thread pool version:
Thread pool, disabling OpenMP and OpenBLAS thread pools:
ogrisel commentedon Jun 1, 2026
is in indeed a good start but let more on a few scripts that I will put in a gist to cover different cases.
ogrisel commentedon Jun 1, 2026
In the meantime, feel free to open a draft PR with mitigation strategy you propose.
itamarst commentedon Jun 1, 2026
At first glance it looks
Parallelusers have no way of checking the backend, at least via public APIs. So options include:joblib, certainly the best long-term solution since this will affect other libraries.joblib.Parallelto get the backend name.joblibAPI in sklearn.Since this is a draft PR, I will go with the last strategy of using a private API, but final PR should do something else.
itamarst commentedon Jun 1, 2026
OK opened #34171 with a sketch of what oversaturation prevention would require.
ogrisel commentedon Jun 24, 2026
@itamarst here is another benchmark script that could be useful to study the interplay of nested threads/processes on "real world" pipelines that compose many scikit-learn components together:
https://gist.github.com/ogrisel/1b24301bfc90d61ab2138bb7fbf7f623
On macOS (libomp):
Using OpenBLAS with the OpenMP threading layer (from conda-forge) does not seem to suffer from oversubscription. Same for newaccelerate on macOS.
OpenBLAS with pthreads does get a slowdown when run under the joblib threading backend while it does get a (small) speed-up when running under the loky backend.
On Linux (libgomp):
I get a slowdown with joblib threading but a speedup with loky for both openblas with openmp and with pthreads.
I also get thread oversubscription (slowdown) when using MKL with joblib threading. MKL with loky yieds a very good speed-up and the best performance measured so far.
EDIT: I consolidated some platform specific results above.
itamarst commentedon Jun 24, 2026
Thank you!
ogrisel commentedon Jun 30, 2026
@itamarst I moved the gist to a dedicated repo to make it easier to consolidate measurements from several machines with raw json result files stored in a subfolder + a script to summarize the main results in a markdown table:
https://github.com/ogrisel/example_pipelines/blob/main/RESULTS_SUMMARY.md
On macOS, OpenBLAS with the pthreads layer is quite problematic. Fortunately, when you pip install numpy you get accelarate based wheels which are fine.
OpenBLAS with the openmp threading layer is much better (both on macOS and Linux). But one can still get oversubcription problems when using the joblib threading layer for the outer loop.
Accelerate does not seem to suffer from oversubscription when nested under a joblib threading loop, but it's not as efficient as single-threaded OpenBLAS under loky for the outer loop.
Interestingly, free-threading is helpful (a bit) even when using loky for the outer loop. I suspect that there is some GIL contention in the joblib dispatching/resulting collection threads.
Feel free to clone and tweak this repo to your needs.
I plan to expand later with more user-level scenarios (e.g. Cython/OpenMP heavy workloads using HistGradientBoostingRegressor, and also some KMeans workloads that successively alternate between BLAS operations and Cython/OpenMP operations).
itamarst commentedon Sep 29, 2026
This work got moved to joblib.