Skip to content

RFC Deprecate the pre_dispatch parameter #35105

Open

Description

@cakedev0

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 + 1 items. 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 None dispatches everything, but parameter validation rejects None ("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

  1. added
    Needs Triage
    Parallelism and scalability
    and removed
    Needs Triage
    on Oct 8, 2026
  2. thomasjpfan commented on Oct 8, 2026

    @thomasjpfan
    Member

    I'm +1 on removing pre_dispatch.

    My extra hot take is to have n_jobs accept a joblib.Parallel, which only works if n_jobs is only be use for joblib based parallelism. This may not be the case with PRs like this: #34914

  3. lorentzenchr commented on Oct 8, 2026

    @lorentzenchr
    Member

    +1 on the deprecation too

  4. lorentzenchr commented on Oct 8, 2026

    @lorentzenchr
    Member

    @thomasjpfan Given threads are the future parallelism (for scikit-learn), what would you propose to do with all the n_jobs parameters?

  5. cakedev0 commented on Oct 9, 2026

    @cakedev0
    MemberAuthor

    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.

    have n_jobs accept a joblib.Parallel

    Why is this needed? Isn't joblib.parallel_context sufficient?

    Given threads are the future parallelism (for scikit-learn), what would you propose to do with all the n_jobs parameters?

    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.

  6. lesteve commented on Oct 9, 2026

    @lesteve
    Member

    With my "if it's not broken, don't fix it" hat on, I would do something like this:

    • tweak the docstring to point to Parallel doc and not give it that much importance when n_jobs is probably the important parameter for memory usage
    • make joblib.parallel_config support pre_dispatch 1
    • deprecate pre_dispatch saying that you can use joblib.parallel_config if 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_dispatch seems 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:

    Footnotes

    1. this comes as a surprise to me that joblib.parallel_config doesn't support pre_dispatch. Without looking in details it doesn't seem too hard to add the functionality? ↩

    2. 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 😉. ↩

  7. cakedev0 commented on Oct 9, 2026

    @cakedev0
    MemberAuthor

    I had my agents go over those reports, try reproducing them and evaluate the impact of pre_dispatch and here is the TLDR:

    Short version: three of Loïc's four use cases don't hold up. The fourth is real but niche, and lowering n_jobs handles it better.

    So I prefer to avoid extra steps and deprecate directly.

  8. cakedev0 commented on Oct 9, 2026

    @cakedev0
    MemberAuthor

    I know you don't like breaking people's code, but here, see it this way: People using pre_dispatch are 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 😜

  9. lesteve commented on Oct 9, 2026

    @lesteve
    Member

    Short version: three of Loïc's four use cases don't hold up. The fourth is real but niche, and lowering n_jobs handles it better.

    Which one is the fourth one, HalvingGridSearchCV with pre_dispatch?

    I know you don't like breaking people's code, but here, see it this way: People using pre_dispatch are 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 😜

    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_jobs helped for GridSearchCV, 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

    1. and yes maybe the world has changed since and it no longer applies, I don't know ... ↩

  10. cakedev0 commented on Oct 9, 2026

    @cakedev0
    MemberAuthor

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

    I'm not against adding it in joblib.parallel_config first! Indeed, that would make a much nicer deprecation message.

  11. cakedev0 commented on Oct 9, 2026

    @cakedev0
    MemberAuthor

    Which one is the fourth one, HalvingGridSearchCV with pre_dispatch?

    It's one that Claude decided to add on its own 😅 It's the high n_jobs with a TfidfVectorizer(vocabulary=<1M terms>).

    Claude says:

    With a large constructor parameter that isn't an estimator (here TfidfVectorizer(vocabulary=<1M terms>)), clone deep-copies it for each task, and the parent keeps one copy per pending task. With n_jobs=128 on a 2x Xeon 6787P server (344 logical CPUs), the parent peaks at 15.1 GB with the default and at 7.9 GB with pre_dispatch="n_jobs". n_jobs=16 does 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 (HalvingGridSearchCV on large data with high n_jobs) isn't something pre_dispatch can fix. Each worker holds its own copy of the training split, so memory grows with n_jobs. With a 160 MB array and n_jobs=128, all values of pre_dispatch ≥ n_jobs give the same time (~4 s) and memory (30 to 37 GB, which looks like sampling noise). pre_dispatch=16 lowers memory to 19.4 GB, but n_jobs=16 beats that on both time and memory (8.8 s and 5.7 GB vs 15.2 s and 19.4 GB).

  12. thomasjpfan commented on Oct 11, 2026

    @thomasjpfan
    Member

    have n_jobs accept a joblib.Parallel Why is this needed? Isn't joblib.parallel_context sufficient?

    joblib.parallel_context is sufficient. The only small benefit of n_jobs=Parallel(...) is that it's a local config and scoped to just that estimator. (I am not advocating for n_jobs=Parallel(..).)

  13. lesteve commented on Oct 12, 2026

    @lesteve
    Member

    Each worker holds its own copy of the training split, so memory grows with n_jobs.

    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:

    def worker_func(X, y, train_indices):
        # do the indexing in the worker function
        X_train = X[train_indices]
        y_train = y[train_indices]

    So X can be memmapped and reused on the workers without copies and the worker functions indexes into X.

    FYI, I have started joblib/joblib#1879 to estimate how hard it would be to support pre_dispatch in joblib.parallel_config. For now, no surprises but it's vibe-coded and I haven't had a closer look yet 😅.

    Footnotes

    1. easy to forget though. Also maybe this pattern is not always appropriate, not sure ... ↩

  14. cakedev0 commented on Oct 12, 2026

    @cakedev0
    MemberAuthor

    So X can be memmapped and reused on the workers without copies and the worker functions indexes into X.

    Hum... we already use this pattern (_fit_and_score calls _safe_split in the worker), and the numbers above were measured with it. But X_train = X[train_indices] is still allocated by each worker, and it's usually roughly the same size as X.

    For a CV search, I guess we could split first, memmap the X_train of 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 copy X_train themselves, which many do for now (copy_X=True, dtype or order conversion in validate_data). But that's something I'd like to optimize (avoiding copying X when possible).

  15. lesteve commented on Oct 12, 2026

    @lesteve
    Member

    But X_train = X[train_indices] is still allocated by each worker

    My naive expectation was that with memory mapping X would be reused and shared between workers (so no new memory allocated when doing X[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 😅.

  16. cakedev0 commented on Oct 12, 2026

    @cakedev0
    MemberAuthor

    no new memory allocated when doing X[train_indices]

    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.

  17. lorentzenchr commented on Oct 12, 2026

    @lorentzenchr
    Member

    But X_train = X[train_indices] is still allocated by each worker

    https://numpy.org/doc/stable/user/basics.indexing.html#advanced-indexing
    Advanced indexing triggers a copy. My understanding is also that X is not copied.
    (sometimes less AI is more reliable)

  18. cakedev0 commented on Oct 12, 2026

    @cakedev0
    MemberAuthor

    That's exactly the behavior I had in mind and AI confirmed it & detailed/rephrased it.

  19. lesteve commented on Oct 17, 2026

    @lesteve
    Member

    Ah right, fancy indexing does a copy, makes sense of course ...

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

    APIParallelism and scalabilityRFC

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions