Repository navigation
Description
Warning
This issue is not yet ready for a PR. If you are interested in contributing to scikit-learn, please have a look at our contributing guidelines, and in particular the sections for new contributors and the "Needs triage" label.
pre_dispatch is exposed by GridSearchCV, RandomizedSearchCV, cross_validate, cross_val_score, cross_val_predict, learning_curve, validation_curve, LearningCurveDisplay.from_estimator and ValidationCurveDisplay.from_estimator. I couldn't find a case where setting it helps with today's joblib, and I think we should deprecate it.
Why it was added
It was added to GridSearchCV in 2011 to bound memory usage. At that time, joblib pickled X into every task sent to the pool, so dispatching all the (candidate, split) tasks at once meant one copy of X per task. That's no longer the case:
- joblib memmaps large arrays (including the ones inside DataFrames and sparse matrices);
- loky only pickles a task when it enters a call queue of
n_workers + 1items. Queued tasks stay in the parent and only reference the data.
Our default ("2*n_jobs") is also joblib's default, so dropping the parameter changes nothing for users who don't set it. The same parameter was already removed from CalibratedClassifierCV (#18030), and @ogrisel questioned its usefulness on memory in #23108.
The docstring is also wrong in several ways:
- It says
Nonedispatches everything, but parameter validation rejectsNone("all"works). - It says an int gives "the exact number of total jobs that are spawned", but joblib counts batches, and with
batch_size="auto"a batch can hold many tasks. - It recommends dispatching everything for "lightweight and fast-running jobs". I couldn't measure any gain from that, and it's the only setting that hurts in the benchmarks below.
Benchmarks
I tried cases where one could expect the knob to matter: large dense arrays with the loky and threading backends, data that joblib can't memmap (a polars DataFrame, a list of strings for a text pipeline), and an estimator with a large constructor parameter. GridSearchCV with n_jobs=8, Intel Core Ultra 5 225H (14 cores), Python 3.13, joblib 1.6.0, one run each. Each cell is fit time / parent peak RSS increase / peak PSS increase summed over the parent and the workers:
| case | "n_jobs" |
"2*n_jobs" (default) |
"all" |
|---|---|---|---|
Ridge, 200k x 100 float64 array, loky |
11.5s / 29MB / 3.1GB | 10.8s / 29MB / 3.1GB | 10.6s / 29MB / 3.2GB |
| same, threading backend | 15.1s / 2.35GB / 2.35GB | 14.7s / 2.35GB / 2.35GB | 14.9s / 2.35GB / 2.35GB |
Ridge, same data as a polars DataFrame |
113s / 700MB / 2.7GB | 130s / 700MB / 2.5GB | 115s / 700MB / 2.6GB |
TfidfVectorizer + LogisticRegression, 300k documents as a list of str |
107s / 81MB / 2.1GB | 104s / 81MB / 2.2GB | 104s / 82MB / 2.2GB |
TfidfVectorizer(vocabulary=<1M terms>) + LogisticRegression |
201s / 640MB / 5.9GB | 178s / 901MB / 6.0GB | 199s / 3.2GB / 8.4GB |
The size of the data doesn't change anything, memmappable or not. The last case is the only one where the setting matters. clone deep-copies constructor parameters that aren't estimators, and "all" keeps one copy per task alive in the parent (~27 MB each here). The default already bounds that.
With many fast tasks (2000 candidates x 5 folds of ~1 ms on iris), "all" isn't faster either: 4.6 s vs 4.4 s for the default. Those timings exclude the callback context overhead reported in #35104, which makes "all" much worse (290 s).
Benchmark script
"""Does GridSearchCV's ``pre_dispatch`` still bound memory (or help speed)?
Each (case, pre_dispatch) pair runs in a fresh Python process so that loky
workers are not reused across runs. A sampler thread polls the memory of the
whole process tree (parent + loky workers) during ``fit``:
- parent_rss: peak RSS increase of the parent process (where not-yet-dispatched
tasks and their arguments live);
- tree_pss: peak PSS increase summed over the tree (PSS splits shared pages,
e.g. memmaps, between processes so they are not counted once per worker).
Usage: python benchmarks/bench_pre_dispatch.py [case ...]
"""
import json
import subprocess
import sys
import threading
import time
N_JOBS = 8
PRE_DISPATCHES = ["n_jobs", "2*n_jobs", "all"]
def make_case(name):
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression, Ridge
from sklearn.pipeline import make_pipeline
from sklearn.tree import DecisionTreeClassifier
rng = np.random.default_rng(0)
def text_data(n_docs, n_words=40, vocab_size=50_000):
words = np.array([f"w{i}" for i in range(vocab_size)])
tokens = words[rng.zipf(1.3, size=(n_docs, n_words)) % vocab_size]
X = [" ".join(row) for row in tokens]
y = rng.integers(0, 2, n_docs)
return X, y
if name in ("numpy", "numpy_threading", "polars"):
# 200k x 100 float64 = 160 MB, 40 candidates x 5 folds = 200 tasks
X = rng.standard_normal((200_000, 100))
y = X @ rng.standard_normal(100) + rng.standard_normal(200_000)
if name == "polars":
import polars as pl
X = pl.DataFrame(X, schema=[f"f{i}" for i in range(X.shape[1])])
grid = {"alpha": np.logspace(-3, 3, 40)}
return Ridge(), grid, X, y
if name == "text":
# list of str: not memmappable, pickled for every task sent to a worker
X, y = text_data(300_000)
grid = {"logisticregression__C": np.logspace(-3, 3, 20)}
est = make_pipeline(TfidfVectorizer(), LogisticRegression(max_iter=50))
return est, grid, X, y
if name == "big_param":
# Fixed 1M-term vocabulary passed as a constructor parameter: clone
# deep-copies it for every task.
X, y = text_data(20_000)
vocab = {f"w{i}": i for i in range(50_000)}
vocab.update({f"term_{i}": 50_000 + i for i in range(950_000)})
grid = {"logisticregression__C": np.logspace(-3, 3, 20)}
est = make_pipeline(
TfidfVectorizer(vocabulary=vocab), LogisticRegression(max_iter=50)
)
return est, grid, X, y
if name == "tiny_tasks":
# 2000 candidates x 5 folds of ~1 ms fits: the case the docstring says
# pre_dispatch="all" is for
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
grid = {"max_depth": range(1, 21), "random_state": range(100)}
return DecisionTreeClassifier(), grid, X, y
raise ValueError(name)
def tree_memory(proc):
"""Return (parent RSS, sum of PSS over the process tree), in bytes."""
import psutil
rss = proc.memory_info().rss
pss = 0
for p in [proc, *proc.children(recursive=True)]:
try:
pss += p.memory_full_info().pss
except psutil.Error:
pass
return rss, pss
def run_one(case, pre_dispatch):
import psutil
from joblib import parallel_config
from sklearn.model_selection import GridSearchCV
est, grid, X, y = make_case(case)
backend = "threading" if case == "numpy_threading" else "loky"
proc = psutil.Process()
base_rss, base_pss = tree_memory(proc)
peak = [0, 0]
stop = threading.Event()
def sample():
while not stop.is_set():
rss, pss = tree_memory(proc)
peak[0] = max(peak[0], rss - base_rss)
peak[1] = max(peak[1], pss - base_pss)
time.sleep(0.02)
sampler = threading.Thread(target=sample)
sampler.start()
tic = time.perf_counter()
with parallel_config(backend=backend):
GridSearchCV(
est, grid, cv=5, n_jobs=N_JOBS, pre_dispatch=pre_dispatch, refit=False
).fit(X, y)
elapsed = time.perf_counter() - tic
stop.set()
sampler.join()
return {
"case": case,
"pre_dispatch": pre_dispatch,
"time_s": round(elapsed, 2),
"parent_rss_mb": round(peak[0] / 1e6),
"tree_pss_mb": round(peak[1] / 1e6),
}
def main():
if len(sys.argv) == 4 and sys.argv[1] == "--worker":
print(json.dumps(run_one(sys.argv[2], sys.argv[3])))
return
cases = sys.argv[1:] or [
"numpy",
"numpy_threading",
"polars",
"text",
"big_param",
"tiny_tasks",
]
print(f"{'case':<16} {'pre_dispatch':<10} {'time':>7} {'parent':>8} {'tree':>8}")
for case in cases:
for pre_dispatch in PRE_DISPATCHES:
out = subprocess.run(
[sys.executable, __file__, "--worker", case, pre_dispatch],
capture_output=True,
text=True,
)
if out.returncode:
print(case, pre_dispatch, "FAILED\n", out.stderr[-2000:])
continue
r = json.loads(out.stdout.strip().splitlines()[-1])
print(
f"{case:<16} {pre_dispatch:<10} {r['time_s']:>6}s "
f"{r['parent_rss_mb']:>6}MB {r['tree_pss_mb']:>6}MB",
flush=True,
)
if __name__ == "__main__":
main()Proposal
Deprecate pre_dispatch in all the functions and classes above in 1.10 and remove it in 1.12. joblib's default applies afterwards.
The alternative is to keep it and fix the docstring. I'd prefer not to: it's API surface on 9 public entry points for a knob with no measured benefit. If a real need shows up later, I think the right place for it is joblib.parallel_config, as @thomasjpfan suggested in #23108 (it doesn't accept pre_dispatch today).
Is there a workload where setting pre_dispatch helps that I missed?
Activity
thomasjpfan commentedon Oct 8, 2026
I'm +1 on removing
pre_dispatch.My extra hot take is to have
n_jobsaccept ajoblib.Parallel, which only works ifn_jobsis only be use forjoblibbased parallelism. This may not be the case with PRs like this: #34914lorentzenchr commentedon Oct 8, 2026
+1 on the deprecation too
lorentzenchr commentedon Oct 8, 2026
@thomasjpfan Given threads are the future parallelism (for scikit-learn), what would you propose to do with all the
n_jobsparameters?cakedev0 commentedon Oct 9, 2026
Thanks for the +1s, I'll open a PR, I dont' really expect someone to be against this deprecation so 2 +1s seems enough to poen the PR.
Why is this needed? Isn't
joblib.parallel_contextsufficient?n_jobs can still be the parameter to control the Python-level parallelism IMO, whether it is threads or processes. n_jobs in forests is already about the number of threads for instance.
lesteve commentedon Oct 9, 2026
With my "if it's not broken, don't fix it" hat on, I would do something like this:
Paralleldoc and not give it that much importance whenn_jobsis probably the important parameter for memory usagejoblib.parallel_configsupportpre_dispatch1pre_dispatchsaying that you can usejoblib.parallel_configif you have a use case for it in the deprecation message.One case I found in our issue tracker where being able to change
pre_dispatchseems useful: #29579 (comment) and the linked SO answer's comment.If I was trying to find some use cases by using my 🔮 based on the reports 2:
n_jobs. Maybe you could try on an Intel many-cores server to come up of a possible use case? Maybe in this case you have highn_jobsand you want a lowerpre_dispatch.Footnotes
this comes as a surprise to me that
joblib.parallel_configdoesn't supportpre_dispatch. Without looking in details it doesn't seem too hard to add the functionality? ↩yes it's quite frustrating as a maintainer to try to guess from sparse information like this but at the same time, I think there is potentially some small signal in it 😉. ↩
cakedev0 commentedon Oct 9, 2026
I had my agents go over those reports, try reproducing them and evaluate the impact of
pre_dispatchand here is the TLDR:So I prefer to avoid extra steps and deprecate directly.
cakedev0 commentedon Oct 9, 2026
I know you don't like breaking people's code, but here, see it this way: People using
pre_dispatchare very likely using it for bad reason, and possibly suffering from it. So throwing them a deprecation warning is helping them, not breaking their code 😜lesteve commentedon Oct 9, 2026
Which one is the fourth one,
HalvingGridSearchCVwithpre_dispatch?Yeah, another one I am not a big fan of is "as maintainers we know better that the users what they need" 😜. There are user reports that
pre_dispatch=1.5*n_jobshelped forGridSearchCV, maybe they could have done it another way (hard to tell), but it allowed them to run their code at the time 1 ...All in all, I don't want to block the deprecation if that's the general consensus. I would have been a lot more comfortable with the deprecation, if there was a way to tell the users in the deprecation message "if you really need this, use joblib.parallel_config".
Footnotes
and yes maybe the world has changed since and it no longer applies, I don't know ... ↩
cakedev0 commentedon Oct 9, 2026
I'm not against adding it in
joblib.parallel_configfirst! Indeed, that would make a much nicer deprecation message.cakedev0 commentedon Oct 9, 2026
It's one that Claude decided to add on its own 😅 It's the high
n_jobswith aTfidfVectorizer(vocabulary=<1M terms>).Claude says:
With a large constructor parameter that isn't an estimator (here
TfidfVectorizer(vocabulary=<1M terms>)),clonedeep-copies it for each task, and the parent keeps one copy per pending task. Withn_jobs=128on a 2x Xeon 6787P server (344 logical CPUs), the parent peaks at 15.1 GB with the default and at 7.9 GB withpre_dispatch="n_jobs".n_jobs=16does better on memory (2.1 GB in the parent and 10.7 GB in total, vs 37 GB) and is ~30% slower (480 s vs 369 s).The HPC report itself (
HalvingGridSearchCVon large data with highn_jobs) isn't somethingpre_dispatchcan fix. Each worker holds its own copy of the training split, so memory grows withn_jobs. With a 160 MB array andn_jobs=128, all values ofpre_dispatch≥n_jobsgive the same time (~4 s) and memory (30 to 37 GB, which looks like sampling noise).pre_dispatch=16lowers memory to 19.4 GB, butn_jobs=16beats that on both time and memory (8.8 s and 5.7 GB vs 15.2 s and 19.4 GB).thomasjpfan commentedon Oct 11, 2026
joblib.parallel_contextis sufficient. The only small benefit ofn_jobs=Parallel(...)is that it's a local config and scoped to just that estimator. (I am not advocating forn_jobs=Parallel(..).)lesteve commentedon Oct 12, 2026
IIRC I don't think that's always true. The pattern we have tried to use in the past 1 is to have a worker function that takes the full dataset
X+ indices:So
Xcan be memmapped and reused on the workers without copies and the worker functions indexes intoX.FYI, I have started joblib/joblib#1879 to estimate how hard it would be to support
pre_dispatchinjoblib.parallel_config. For now, no surprises but it's vibe-coded and I haven't had a closer look yet 😅.Footnotes
easy to forget though. Also maybe this pattern is not always appropriate, not sure ... ↩
cakedev0 commentedon Oct 12, 2026
Hum... we already use this pattern (
_fit_and_scorecalls_safe_splitin the worker), and the numbers above were measured with it. ButX_train = X[train_indices]is still allocated by each worker, and it's usually roughly the same size asX.For a CV search, I guess we could split first, memmap the
X_trainof each fold and share it across candidates (each candidate uses the same splits). I don't think we do that. It would have the biggest impact for estimators that don't copyX_trainthemselves, which many do for now (copy_X=True, dtype or order conversion invalidate_data). But that's something I'd like to optimize (avoiding copying X when possible).lesteve commentedon Oct 12, 2026
My naive expectation was that with memory mapping
Xwould be reused and shared between workers (so no new memory allocated when doingX[train_indices]). I am not going to claim that I deeply understand this kind of OS topics though, so there is a chance my naive expectation is dead wrong 😅.cakedev0 commentedon Oct 12, 2026
This allocates a new contiguous array, so no chance that it doesn't allocate a new array (for each worker).
Edit, my Agent tells me: "contiguous" isn't really the reason. A view has to be a fixed-stride layout over the original buffer. An arbitrary set of rows can't be written that way, so NumPy has to gather the rows into a new buffer.
lorentzenchr commentedon Oct 12, 2026
https://numpy.org/doc/stable/user/basics.indexing.html#advanced-indexing
Advanced indexing triggers a copy. My understanding is also that
Xis not copied.(sometimes less AI is more reliable)
cakedev0 commentedon Oct 12, 2026
That's exactly the behavior I had in mind and AI confirmed it & detailed/rephrased it.
lesteve commentedon Oct 17, 2026
Ah right, fancy indexing does a copy, makes sense of course ...
sync: 2026-11-03