Skip to content

Prevent CPU over-subscription when using thread pools, similar to what process pools do #34070

Closed

Description

@itamarst

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:

  1. Documentation for algorithms with limited parallelism, suggesting that it's better to use processes in order to utilize all cores.
  2. Custom settings per parallelism mechanism: set OpenMP to max(cpu_count() // effective_n_jobs, 1) and BLAS to cpu_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 threadpoolctl uses.

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

  1. added
    free-threading
    Needs Decision
    and removed
    Needs Triage
    on May 24, 2026
  2. github-actions commented on May 24, 2026

    @github-actions

    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.

  3. ogrisel commented on May 26, 2026

    @ogrisel
    Member

    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_limits context manager and evaluate it on some typical workfload (e.g. a cross_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).

    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."

    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:

    $ mamba install "libblas=*=*_openblas" "openblas=*=openmp_*"
    

    as opposed to using the pthread threading layer of OpenBLAS:

    $ mamba install "libblas=*=*_openblas" "openblas=*=pthreads_*"
    

    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.

  4. added
    Parallelism and scalability
    on May 26, 2026
  5. david-cortes-intel commented on May 27, 2026

    @david-cortes-intel
    Contributor

    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.

  6. removed
    Needs Decision
    on May 27, 2026
  7. ogrisel commented on May 27, 2026

    @ogrisel
    Member

    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.

  8. itamarst commented on May 28, 2026

    @itamarst
    ContributorAuthor

    typical workfload (e.g. a cross_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).

    @ogrisel Are there any existing benchmarks (or lacking that, examples in the docs) that match the scenarios you think are worth testing?

  9. itamarst commented on May 29, 2026

    @itamarst
    ContributorAuthor

    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 have n_jobs=-1, and tried comparing process pool and thread pools.

    (See itamarst/thread-oversaturation-experiments branch: you can set SKLEARN_THREADING environment variable to enable thread pools.)

    The result:

    • Using a thread pool was 10× to 40× slower than process pool.
    • Disabling the nested thread pools (from OpenBLAS) made the thread pool version faster than the process pool.

    OpenBLAS with OpenMP backend (from Conda-Forge)

    Here's the process pool version:

    41.31user 2.01system 0:05.96elapsed 726%CPU (0avgtext+0avgdata 333604maxresident)k
    

    It's much much slower with threads:

    1621.33user 1216.53system 4:12.78elapsed 1122%CPU (0avgtext+0avgdata 391964maxresident)k
    

    But if I disable OpenMP it's nice and fast again (faster than processes, even):

    17.42user 0.29system 0:03.29elapsed 537%CPU (0avgtext+0avgdata 374864maxresident)k
    

    OpenBLAS with pthreads (PyPI)

    Same results, just naive thread pool isn't quite as bad.

    Process pool:

    51.01user 2.11system 0:06.75elapsed 786%CPU (0avgtext+0avgdata 346760maxresident)k
    

    Thread pool version:

    607.88user 0.59system 0:55.55elapsed 1095%CPU (0avgtext+0avgdata 383572maxresident)k
    

    Thread pool, disabling OpenMP and OpenBLAS thread pools:

    18.24user 0.42system 0:03.67elapsed 508%CPU (0avgtext+0avgdata 368032maxresident)k
    
  10. ogrisel commented on Jun 1, 2026

    @ogrisel
    Member

    @ogrisel Are there any existing benchmarks (or lacking that, examples in the docs) that match the scenarios you think are worth testing?

    examples/model_selection/plot_grid_search_refit_callable.py
    

    is in indeed a good start but let more on a few scripts that I will put in a gist to cover different cases.

  11. ogrisel commented on Jun 1, 2026

    @ogrisel
    Member

    In the meantime, feel free to open a draft PR with mitigation strategy you propose.

  12. moved this to In progress in Labson Jun 1, 2026
  13. itamarst commented on Jun 1, 2026

    @itamarst
    ContributorAuthor

    At first glance it looks Parallel users have no way of checking the backend, at least via public APIs. So options include:

    • Adding the oversaturation mitigation functionality to joblib, certainly the best long-term solution since this will affect other libraries.
    • Adding public API to joblib.Parallel to get the backend name.
    • Using private joblib API 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.

  14. itamarst commented on Jun 1, 2026

    @itamarst
    ContributorAuthor

    OK opened #34171 with a sketch of what oversaturation prevention would require.

  15. ogrisel commented on Jun 24, 2026

    @ogrisel
    Member

    @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.

  16. itamarst commented on Jun 24, 2026

    @itamarst
    ContributorAuthor

    Thank you!

  17. ogrisel commented on Jun 30, 2026

    @ogrisel
    Member

    @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).

  18. moved this from PR in progress to Issue in progress in Labson Sep 21, 2026
  19. itamarst commented on Sep 29, 2026

    @itamarst
    ContributorAuthor

    This work got moved to joblib.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    New FeatureParallelism and scalabilityfree-threading

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions