Skip to content

PERF Speed up Parallel() threading backend - #1899

Open
itamarst wants to merge 47 commits into
joblib:mainfrom
itamarst:1830-speed-up-parallel-take-2
Open

itamarst wants to merge 47 commits into
joblib:mainfrom
itamarst:1830-speed-up-parallel-take-2

Conversation

@itamarst

@itamarst itamarst commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1830

Backwards compatibility results in overhead that would be unnecessary if simply switching to using a ThreadPoolExecutor/ThreadPool directly, but it's definitely a meaningful improvement. And follow-ups could probably do even better (caching the thread pool can be very helpful).

Question for reviewers: Adding a different code path for some configurations undermines the test coverage somewhat. Which of these solutions would you prefer?

  • Dropping support for timeouts for the threading backend, which seems reasonable to me.
  • Adding more test coverage by parametrizing a bunch of the tests on timeouts.

Benchmarks

MiniBatchDictionaryLearning in scikit-learn (scikit-learn/scikit-learn#4769) on free-threaded Python

Benchmark code:

Details
from time import time
from sklearn.datasets import make_sparse_coded_signal
from sklearn.decomposition import MiniBatchDictionaryLearning
X, dictionary, code = make_sparse_coded_signal(
    n_samples=1000, n_components=15, n_features=20, n_nonzero_coefs=10,
    random_state=42)
import joblib
joblib.parallel_backend("threading")

n_jobs = [1, 4, 8]

for nj in n_jobs:
    dict_learner = MiniBatchDictionaryLearning(
        n_components=15, transform_algorithm='lasso_lars', random_state=42,
        n_jobs=nj
    )
    t0 = time()
    X_transformed = dict_learner.fit_transform(X)
    print("done in %0.3fs, with n_jobs = %d." % ((time() - t0), nj))

joblib main branch

done in 3.464s, with n_jobs = 1.
done in 1.944s, with n_jobs = 4.
done in 2.519s, with n_jobs = 8.

This PR

done in 3.465s, with n_jobs = 1.
done in 1.139s, with n_jobs = 4.
done in 0.731s, with n_jobs = 8.

New benchmarks/bench_simple_parallel.py in PR

Details

main branch

noop(): 4 workers,    10 tasks,    24446 µs
noop(): 4 workers,    10 tasks,    11772 µs
noop(): 4 workers,   100 tasks,    11805 µs
noop(): 4 workers,   100 tasks,    11697 µs
noop(): 4 workers,  1000 tasks,    24321 µs
noop(): 4 workers,  1000 tasks,    13382 µs
noop(): 4 workers, 10000 tasks,   151763 µs
noop(): 4 workers, 10000 tasks,   133140 µs
noop(): 1 workers,    10 tasks,      102 µs
noop(): 1 workers,    10 tasks,       51 µs
noop(): 1 workers,   100 tasks,      164 µs
noop(): 1 workers,   100 tasks,      160 µs
noop(): 1 workers,  1000 tasks,     1372 µs
noop(): 1 workers,  1000 tasks,     1356 µs
noop(): 1 workers, 10000 tasks,    13593 µs
noop(): 1 workers, 10000 tasks,    13380 µs
work_10us(): 4 workers,    10 tasks,    12152 µs
work_10us(): 4 workers,    10 tasks,    11343 µs
work_10us(): 4 workers,   100 tasks,    12419 µs
work_10us(): 4 workers,   100 tasks,    14004 µs
work_10us(): 4 workers,  1000 tasks,    40689 µs
work_10us(): 4 workers,  1000 tasks,    14670 µs
work_10us(): 4 workers, 10000 tasks,   147495 µs
work_10us(): 4 workers, 10000 tasks,   154504 µs
work_10us(): 1 workers,    10 tasks,      251 µs
work_10us(): 1 workers,    10 tasks,      191 µs
work_10us(): 1 workers,   100 tasks,     1366 µs
work_10us(): 1 workers,   100 tasks,     1417 µs
work_10us(): 1 workers,  1000 tasks,    12871 µs
work_10us(): 1 workers,  1000 tasks,    12521 µs
work_10us(): 1 workers, 10000 tasks,   116224 µs
work_10us(): 1 workers, 10000 tasks,   115266 µs

PR

== Threaded/sequential backend ==
noop(): 4 workers,    10 tasks,    18447 µs
noop(): 4 workers,    10 tasks,      902 µs
noop(): 4 workers,   100 tasks,     1369 µs
noop(): 4 workers,   100 tasks,     1308 µs
noop(): 4 workers,  1000 tasks,     7891 µs
noop(): 4 workers,  1000 tasks,     7932 µs
noop(): 4 workers, 10000 tasks,    72085 µs
noop(): 4 workers, 10000 tasks,    74265 µs
noop(): 1 workers,    10 tasks,      105 µs
noop(): 1 workers,    10 tasks,       53 µs
noop(): 1 workers,   100 tasks,      154 µs
noop(): 1 workers,   100 tasks,      184 µs
noop(): 1 workers,  1000 tasks,     1382 µs
noop(): 1 workers,  1000 tasks,     1368 µs
noop(): 1 workers, 10000 tasks,    13356 µs
work_10us(): 4 workers,    10 tasks,     1098 µs
work_10us(): 4 workers,    10 tasks,      686 µs
work_10us(): 4 workers,   100 tasks,     1152 µs
work_10us(): 4 workers,   100 tasks,     1130 µs
work_10us(): 4 workers,  1000 tasks,     7393 µs
work_10us(): 4 workers,  1000 tasks,     7522 µs
work_10us(): 4 workers, 10000 tasks,    69243 µs
work_10us(): 4 workers, 10000 tasks,    68896 µs
work_10us(): 1 workers,    10 tasks,      215 µs
work_10us(): 1 workers,    10 tasks,      147 µs
work_10us(): 1 workers,   100 tasks,     1191 µs
work_10us(): 1 workers,   100 tasks,     1184 µs
work_10us(): 1 workers,  1000 tasks,    11576 µs
work_10us(): 1 workers,  1000 tasks,    11594 µs
work_10us(): 1 workers, 10000 tasks,   115442 µs
work_10us(): 1 workers, 10000 tasks,   115432 µs

@codecov

codecov Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.74%. Comparing base (6a12020) to head (0a202e3).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1899      +/-   ##
==========================================
+ Coverage   93.67%   93.74%   +0.06%     
==========================================
  Files          46       46              
  Lines        8869     8932      +63     
==========================================
+ Hits         8308     8373      +65     
+ Misses        561      559       -2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@itamarst itamarst changed the title PERF Speed up Parallel() for threading PERF Speed up Parallel() threading backend Oct 19, 2026
@itamarst

itamarst commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Test failure is known error, #1890

@cakedev0 cakedev0 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on this, AI found a couple of fairly important bugs, but they don't look too hard to fix.

About your coverage question: I think the bugs AI found show which kind of tests this threading-only path needs: errors and early exit, verbose, nested calls, BaseException, ...

Comment thread joblib/_parallel_backends.py Resolved
Comment thread joblib/parallel.py Resolved
Comment thread joblib/parallel.py Resolved
Comment thread joblib/parallel.py Resolved
Comment thread joblib/parallel.py Resolved
Comment thread conftest.py Resolved
@cakedev0

cakedev0 commented Nov 5, 2026

Copy link
Copy Markdown

One more issue with the fast path: because it ignores pre_dispatch, users could have unexpected an memory blow-up:

import time
import numpy as np
from joblib import Parallel, delayed

def load(i):
    return np.full(2_000_000, i, dtype=np.float64)  # 16 MB, e.g. a chunk read from disk

def process(x):
    time.sleep(0.05)
    return float(x[0])

Parallel(n_jobs=4, backend="threading")(delayed(process)(load(i)) for i in range(1000))

Peak extra RSS: ~12GB on this branch, 144 MB on main.

Streaming chunks into threads that release the GIL is a typical use of the threading backend, and the docstring presents pre_dispatch as the way to bound memory in this situation. So I don't think a changelog entry is enough.

I discussed this with @ogrisel IRL, and one idea is to take the fast path only when pre_dispatch="all". That value already means "consume the whole iterable up front" on main: the same snippet with pre_dispatch="all" also peaks at 12GB on main. So nobody gets a new surprise. scikit-learn can opt in at its threaded call sites, which mostly pass small inputs or inputs that are already present in memory. Everyone else keeps the current path.

I also had my agent trying to honour pre_dispatch in the fast path: it was slow and complex.

One related point that the restriction doesn't solve: inside with Parallel(...) as p:, the fast path doesn't terminate the pool on errors. With 1000 tasks and pre_dispatch="all", 996 tasks still run after the first one raises (19 on main), and the next p(...) call waits 0.5 s behind them. Breaking out of a return_as="generator" loop early has the same effect (1000 tasks run vs 24 on main). This needs its own fix, e.g. calling self._backend.abort_everything(ensure_ready=True) in the except branch when the backend is managed, like _abort() does on main.

@itamarst

itamarst commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

I really should've thought of that, sorry.

I don't want to limit to pre_dispatch="all" because that makes the speed up opt-in, the ideal is most users and callers get it automatically.

ThreadPoolExecutor.map() has a buffersize option that can be used to limit how many results are stored in memory without iteration over those results, so I can switch to that and set it to the evaled pre_dispatch. This will mean unordered results will use the slow path, but seems like a reasonable tradeoff to me, since scikit-learn doesn't use unordered results.

I think that will solve both cases.

@ogrisel

ogrisel commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

It's worth giving it a try.

@itamarst

itamarst commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

OK, updated with ThreadPoolExecutor and updated benchmarks. This time it's faster?! Maybe the buffersize makes a difference.

Memory usage is a bit higher than main branch for the example above, but same order of magnitude so this should fix the memory usage problem.

@itamarst

itamarst commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

(GitHub is being slow about noticing pushed commits.)

@itamarst

itamarst commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

Ugh, buffersize isn't in older Python. I'm gonna just fall back to slow path in those versions of Python, anyone who cares about speed really ought to be using newer Pythons anyway.

@itamarst

itamarst commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

Ok, should be ready for review again; looks like the failure is in Loky?

B0yko commented Nov 6, 2026 •

Copy link
Copy Markdown

The new buffersize path needs to translate the pre_dispatch="all" sentinel. _parse_pre_dispatch("all", n_jobs) returns 0, and _get_threaded_output passes that directly to pool.map(buffersize=...). Python 3.14's Executor.map rejects 0 with ValueError: buffersize must be None or > 0, before submitting any tasks. Thus an ordered threading call with n_jobs=2, pre_dispatch="all", and no timeout fails instead of running its tasks on the new fast path.

Could the call use buffersize=None when _pre_dispatch_amount == 0, retaining the existing 0 sentinel for Joblib's bookkeeping? None is the executor's eager-submission setting. A Python 3.14 regression using Parallel(n_jobs=2, backend="threading", pre_dispatch="all")(delayed(abs)(i) for i in [-1, -2]) would cover this separately from the earlier bounded-memory concern.

Review of head 6ba5473. I executed the exact extracted PR parser and CPython v3.14.0 Executor.map function on Python 3.12.14, confirming 0 reaches that validation and raises the stated error. I did not execute the complete PR on Python 3.14 or run its test suite.

@lesteve

lesteve commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

@B0yko if there is a human behind the bot, can you share a few details about your motivation and what you are trying to do? It seems like you are "AI-reviewing" PRs in a variety of unrelated repos, and I personally don't think this is very useful!

See scikit-learn's automated contribution policy for more details.

@itamarst

itamarst commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

It's a real bug, but also yeah I'd just block people who have no direct interest in the repo.

@itamarst

itamarst commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

I wonder if expanded testing is catching existing bugs that weren't previously being caught? In any case I will look at errors in more detail next week.

@itamarst

itamarst commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Got as far as figuring out that these are real bugs, seemingly caused by switch to ThreadPoolExecutor. Since Loky is also an executor modeling on that ought to help, but we'll see.

@itamarst

itamarst commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Maybe easiest thing to do is have ThreadingBackend stick to ThreadPool and then... FastThreadingBackend or something that never gets instantiated by a user but gets instantiated behind the scenes and that uses ThreadPoolExecutor. And that also reduces risk that I introduced more obscure race conditions than the ones showing up in CI.

@itamarst
itamarst requested a review from ogrisel November 10, 2026 16:28
@itamarst

Copy link
Copy Markdown
Contributor Author

Should be ready for review again. New scheme is less risky, as slow path is the same as it was before.

@itamarst

Copy link
Copy Markdown
Contributor Author

Realized there is one difference in behavior between slow and fast path: on free-threaded Python, the ThreadPoolExecutor will copy contextvars context, whereas the current (slow path) version will not.

@itamarst

Copy link
Copy Markdown
Contributor Author

I would suggest finishing this up in a follow-up, separate release than #1871, so the oversaturation work can get out the door faster.

This branch has not been deployed

No deployments
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.

joblib.Parallel with threading backend is a lot slower than concurrent.futures.ThreadPoolExecutor

5 participants