Skip to content

PRF: Over-subscription in pairwise_distances with backend="threading" + BLAS-pthreads #34736

Open

Description

@cakedev0

🚨 This is a complex issue that already has experts working on it. Please don't start work on this without first coordinating with them.

sklearn.metrics.pairwise_distances accepts a n_jobs parameters and uses joblib.Parallel(backend="threading", n_jobs=n_jobs) under-the-hood. But this parallelization happens on top on openBLAS parallelism, and can lead to what looks like over-subscription.

(but maybe it's not over-subscription, and something else, like cost of repeated small parallelized blas calls, etc. I haven't investigated)

Results from a small benchmark script shows that limiting blas to 1 thread helps scaling as n_jobs grows (and usually achieves best performance compared to n_jobs=1 with blas parallelism enabled):

--- n_samples=2000  n_features=200 ---
  n_jobs=  1 | pin-blas=0:      33ms
  n_jobs=  1 | pin-blas=1:      52ms
  n_jobs=  4 | pin-blas=0:      66ms
  n_jobs=  4 | pin-blas=1:      53ms
  n_jobs=  8 | pin-blas=0:      76ms
  n_jobs=  8 | pin-blas=1:      35ms
  n_jobs= 14 | pin-blas=0:     102ms
  n_jobs= 14 | pin-blas=1:      25ms

--- n_samples=4000  n_features=200 ---
  n_jobs=  1 | pin-blas=0:     150ms
  n_jobs=  1 | pin-blas=1:     226ms
  n_jobs=  4 | pin-blas=0:     107ms
  n_jobs=  4 | pin-blas=1:     102ms
  n_jobs=  8 | pin-blas=0:     141ms
  n_jobs=  8 | pin-blas=1:      75ms
  n_jobs= 14 | pin-blas=0:     163ms
  n_jobs= 14 | pin-blas=1:      70ms

--- n_samples=8000  n_features=200 ---
  n_jobs=  1 | pin-blas=0:     547ms
  n_jobs=  1 | pin-blas=1:     864ms
  n_jobs=  4 | pin-blas=0:     375ms
  n_jobs=  4 | pin-blas=1:     296ms
  n_jobs=  8 | pin-blas=0:     356ms
  n_jobs=  8 | pin-blas=1:     217ms
  n_jobs= 14 | pin-blas=0:     362ms
  n_jobs= 14 | pin-blas=1:     204ms

Results with 10 or 1000 features are similar, but for n_samples=2000, the n_jobs=1 pin-blas=0 variant wins.

The script:

Details
import argparse
from itertools import product
import time
from statistics import median

import numpy as np
import threadpoolctl

from sklearn.metrics import pairwise_distances


def bench_once(X, n_jobs, pin_blas):
    if pin_blas:
        with threadpoolctl.threadpool_limits(1, user_api="blas"):
            return pairwise_distances(X, X, n_jobs=n_jobs)
    return pairwise_distances(X, X, n_jobs=n_jobs)


def bench(X, n_jobs, pin_blas, reps):
    bench_once(X, n_jobs, pin_blas)  # warmup / compilation
    times = []
    for _ in range(reps):
        t0 = time.perf_counter()
        bench_once(X, n_jobs, pin_blas)
        times.append(time.perf_counter() - t0)
    return median(times)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--n-samples", type=str, default="2000,4000,8000")
    parser.add_argument("--n-features", type=str, default="200")
    parser.add_argument("--n-jobs", type=str, default="1,4,8,14")
    parser.add_argument("--reps", type=int, default=30)
    args = parser.parse_args()

    n_samples_list = [int(v) for v in args.n_samples.split(",")]
    n_features_list = [int(v) for v in args.n_features.split(",")]
    n_jobs_list = [int(v) for v in args.n_jobs.split(",")]

    rng = np.random.RandomState(4872)

    for n_samples, n_features in product(n_samples_list, n_features_list):
        X = rng.rand(n_samples, n_features)
        print(f"\n--- n_samples={n_samples}  n_features={n_features} ---")

        for n_jobs in n_jobs_list:
            for pin_blas in [False, True]:
                t = bench(X, n_jobs, pin_blas, args.reps)
                print(f"  n_jobs={n_jobs:>3} | pin-blas={pin_blas:>1}: {t * 1000:7.0f}ms")


if __name__ == "__main__":
    main()

Note: the default metric is euclidean, but I think I observed similar behavior with cosine too. l1 doesn't call blas so it doesn't have the same issue.

CC @itamarst I was told it might be of interest for you 😉

sklearn.show_versions()

System:
    python: 3.12.3 (main, Jun 19 2026, 12:46:00) [GCC 13.3.0]
executable: /home/arthur/scikit-learn/sklearn-env/bin/python
   machine: Linux-6.17.0-1030-oem-x86_64-with-glibc2.39

Python dependencies:
      sklearn: 1.10.dev0
          pip: None
   setuptools: None
        numpy: 2.5.1
        scipy: 1.18.0
       Cython: 3.2.8
       pandas: 3.0.5
   matplotlib: 3.11.1
       joblib: 1.5.3
threadpoolctl: 3.6.0
     narwhals: 2.24.0

Built with OpenMP: True

threadpoolctl info:
       user_api: blas
   internal_api: openblas
    num_threads: 14
         prefix: libscipy_openblas
       filepath: /home/arthur/scikit-learn/sklearn-env/lib/python3.12/site-packages/numpy.libs/libscipy_openblas64_-017048f4.so
        version: 0.3.33.112.0
threading_layer: pthreads
   architecture: Haswell

       user_api: blas
   internal_api: openblas
    num_threads: 14
         prefix: libscipy_openblas
       filepath: /home/arthur/scikit-learn/sklearn-env/lib/python3.12/site-packages/scipy.libs/libscipy_openblas-5f890258.so
        version: 0.3.31.dev
threading_layer: pthreads
   architecture: Haswell

       user_api: openmp
   internal_api: openmp
    num_threads: 14
         prefix: libgomp
       filepath: /usr/lib/x86_64-linux-gnu/libgomp.so.1.0.0
        version: None

Activity

  1. added
    Needs Triage
    on Aug 12, 2026
  2. itamarst commented on Aug 12, 2026

    @itamarst
    Contributor

    I have a systemic solution planned: basically information about top-level threads would percolate down to how many BLAS threads are started.

    There's a series of threadpoolctl PRs, starting with joblib/threadpoolctl#213 which will eventually result in threadpoolctl API for this use case, of Python thread pools rather than process pools.

    Once those are all in, next step is to use the new resulting API and have joblib limit BLAS/OpenMP number of threads for threading backend, and not just loky backend as is the case now.

  3. itamarst commented on Aug 12, 2026

    @itamarst
    Contributor

    I also have open PR to prevent oversaturation of nested Python workers (processes / threads): joblib/joblib#1825

  4. cakedev0 commented on Aug 17, 2026

    @cakedev0
    MemberAuthor

    @itamarst I'll let you close this issue once you think it's properly resolved, or if it feels too much like a duplicate of another already existing issue.

  5. added
    Parallelism and scalability
    and removed
    Needs Triage
    on Aug 18, 2026
  6. itamarst commented on Sep 24, 2026

    @itamarst
    Contributor

    I tried this with my joblib-does-blas-limits-in-python-threads-too branch. This is with OpenBLAS pthreads backend.

    main joblib:

    --- n_samples=2000  n_features=200 ---
      n_jobs= 12 | pin-blas=0:      81ms
      n_jobs= 12 | pin-blas=1:      37ms
    
    --- n_samples=4000  n_features=200 ---
      n_jobs= 12 | pin-blas=0:     164ms
      n_jobs= 12 | pin-blas=1:     106ms
    
    --- n_samples=8000  n_features=200 ---
      n_jobs= 12 | pin-blas=0:     394ms
      n_jobs= 12 | pin-blas=1:     390ms
    

    With my branch:

    --- n_samples=2000  n_features=200 ---
      n_jobs= 12 | pin-blas=0:      28ms
      n_jobs= 12 | pin-blas=1:      38ms
    
    --- n_samples=4000  n_features=200 ---
      n_jobs= 12 | pin-blas=0:     108ms
      n_jobs= 12 | pin-blas=1:     106ms
    
    --- n_samples=8000  n_features=200 ---
      n_jobs= 12 | pin-blas=0:     389ms
      n_jobs= 12 | pin-blas=1:     391ms
    

    So it does seem like this will be fixed once all the joblib PRs get merged and a new joblib is released.

  7. stepan-srsen commented on Oct 19, 2026

    @stepan-srsen
    Contributor

    Why not directly use with threadpool_limits(limits=1): from the threadpoolctl library in the fuction to avoid over-subscription with threading and not to rely on the new joblib version?

  8. itamarst commented on Oct 19, 2026

    @itamarst
    Contributor

    The idea is that joblib already has all the necessary info so it can just fix this automatically, everywhere. One could of course also fix it manually one location a time, but scikit-learn likely has multiple places where oversaturation happens so fixing it systemically is nicer.

  9. stepan-srsen commented on Oct 19, 2026

    @stepan-srsen
    Contributor

    I agree in principle, but the question is when the new joblib version becomes scikit-learn's mandatory requirement. In my eyes, this issue is severe enough to be fixed on the scikit-learn side in the meantime.

  10. cakedev0 commented on Oct 20, 2026

    @cakedev0
    MemberAuthor

    If we fix it in scikit-learn, only people who will install the 1.10 will benefit from it, and I think those people will also automatically install the latest joblib (because of how package managers work), unless they have a joblib<x in their other requirements, which I think is unlikely.

  11. stepan-srsen commented on Oct 20, 2026

    @stepan-srsen
    Contributor

    @cakedev0 What you say is true only for clean environments without other dependencies from other packages. However, it seems that I am in the minority here, so I will already let it go 😄

  12. cakedev0 commented on Oct 20, 2026

    @cakedev0
    MemberAuthor

    In case you have an example easy to share: I'm very interested about real complex environments with joblib<x constraints due to other packages than scikit-learn.

  13. added a commit that references this issue on Nov 3, 2026
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

    Parallelism and scalability

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions