Skip to content

Evaluate multi-threading LogisticRegression #32162

Open

Description

@jeremiedbb

When #32073 is merged, n_jobs will have no effect in LogisticRegression so should be deprecated.

It's also a good time to consider enabling multi-threading to compute the logistic regression path here

# TODO: Refactor this to avoid joblib parallelism entirely when doing binary
# and multinomial multiclass classification and use joblib only for the
# one-vs-rest multiclass case.
if (
solver in ["lbfgs", "newton-cg", "newton-cholesky"]
and len(classes_) == 1
and effective_n_jobs(self.n_jobs) == 1
):
# In the future, we would like n_threads = _openmp_effective_n_threads()
# For the time being, we just do
n_threads = 1
else:
n_threads = 1
fold_coefs_ = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, prefer=prefer)(
path_func(

So far it was disabled because parallelism was happening at a higher level using joblib. Now we should benchmark the impact of enabling multi-threading to see if it's positive for all the solvers and a wide range of problems.
Like for other estimators using OpenMP-based multi-threading, the number of thread should not be controlled by n_jobs but instead use all available core (n_threads = _openmp_effective_n_threads()).

Activity

  1. added
    Needs Benchmarks
    on Sep 11, 2025
  2. KoolDrip commented on Sep 19, 2025

    @KoolDrip

    I’d like to take this up. Plan is to handle the n_jobs deprecation and then benchmark the impact of enabling multi-threading across different solvers and datasets. I’ll also look into using _openmp_effective_n_threads() consistently, as done in other estimators.

  3. FrancoisPgm commented on Nov 17, 2025

    @FrancoisPgm
    Member

    Here are some results of a benchmark comparing n_threads=1 (denoted as n_thread False in the legends) to n_trheads=_openmp_effective_n_threads() (denoted as n_thread True in the legends) for fitting a logistic regression using the code from #32073. I ran the benchmark locally on my machine, limiting the number of available CPUs using either threadpool_limits in the script or a OMP_NUM_THREADS environment variable.
    I only tested the lbfgs, newton-cg and newton-cholesky solvers as the other ones don't take n_threads as an argument.

    Selection of plots lbfgs 100 samples 100 features 32 classes newton-cg 100 samples 100 features 32 classes newton-cholesky 100 samples 100 features 8 classes lbfgs 1e4 samples 100 features 32 classes newton-cg 1e4 samples 100 features 32 classes newton-cholesky 1e4 samples 100 features 8 classes lbfgs 1e6 samples 100 features 32 classes newton-cg 1e6 samples 100 features 32 classes newton-cholesky 1e6 samples 100 features 8 classes
    All lbfgs plots Image Image Image Image Image Image Image Image Image Image Image Image Image Image Image Image Image Image
    All newton-cg plots Image Image Image Image Image Image Image Image Image Image Image Image Image Image Image Image Image Image
    All newton-cholesky plots Image Image Image Image Image Image Image Image Image Image Image Image

    The conclusion I draw from the plots are :

    • for a small sample size (100) the overhead of using more CPUs increases the run time proportionally to the number of CPUs, for all solvers
    • for a medium sample size (1e4) there is a moderate speedup for lbfgs when using more CPUs, with the fastest results with 4 CPUs and then we see some overhead slowdown for higher CPU counts. For newton-cg and newton-cholesky there seem to be no significant difference.
    • for a large sample size (1e6) there is a significant speedup for both lbfgs and newton-cg with increasing CPU counts, and a saturation around 8 CPUs. For newton-cholesky, there are noticeable speedups only for the smallest values for number of featuers and classes, otherwise there is no clear difference.

    Additionally, it seems that when there are speedups, they diminish with increasing number of features (10 or 100) and increase with increasing number of classes (2, 8 or 32).

    Here is the script I used for the benchmark
    import os
    import time
    import itertools
    import argparse
    import warnings
    import numpy as np
    import pandas as pd
    from pathlib import Path
    from sklearn.datasets import make_classification
    from sklearn.linear_model import LogisticRegression
    from sklearn.exceptions import ConvergenceWarning
    
    from threadpoolctl import threadpool_limits
    from rich.progress import (
        Progress,
        SpinnerColumn,
        BarColumn,
        MofNCompleteColumn,
        TextColumn,
        TimeElapsedColumn,
        TimeRemainingColumn,
    )
    
    warnings.filterwarnings("ignore", category=ConvergenceWarning)
    warnings.filterwarnings("ignore", category=FutureWarning)
    
    
    def main(cpu_limit_type, isolated, n_threads):
        results = []
    
        n_cpu_list = range(1, 11)
        n_samples_list = (100, 10000, int(1e6))
        n_features_list = (10, 100)
        n_classes_list = (2, 8, 32)
        solver_list = (
            "lbfgs",
            "newton-cg",
            "newton-cholesky",
        )
    
        param_lists = [n_cpu_list] if cpu_limit_type == "threadpool_limits" else []
        param_lists += [
            n_samples_list,
            n_features_list,
            n_classes_list,
            solver_list,
        ]
    
        with Progress(
            SpinnerColumn(),
            TextColumn("[progress.description]{task.description}"),
            BarColumn(),
            MofNCompleteColumn(),
            TimeElapsedColumn(),
            TimeRemainingColumn(),
            transient=False,
        ) as progress:
            task = progress.add_task(
                "Benchmarking", total=np.prod([len(l) for l in param_lists])
            )
    
            for params in itertools.product(*param_lists):
                if cpu_limit_type == "threadpool_limits":
                    n_cpu, n_samples, n_features, n_classes, solver = params
                else:
                    n_samples, n_features, n_classes, solver = params
                    n_cpu = os.environ["OMP_NUM_THREADS"]
    
                progress.update(
                    task,
                    description=f"[magenta]CPU:[/] {n_cpu}"
                    f" [yellow]Samples:[/] {n_samples} [red]Feat:[/] {n_features}"
                    f" [green]Classes:[/] {n_classes} [cyan]Solver:[/] {solver}",
                )
    
                if n_classes == 32 and solver == "newton-cholesky":
                    # takes too long so gets skipped
                    progress.update(task, advance=1)
                    continue
    
                n_informative = int(0.6 * n_features)
                n_redundant = int(0.2 * n_features)
    
                X, y = make_classification(
                    n_samples=n_samples,
                    n_features=n_features,
                    n_informative=n_informative,
                    n_redundant=n_redundant,
                    n_classes=n_classes,
                    random_state=0,
                )
                clf = LogisticRegression(solver=solver, random_state=0)
    
                start = time.perf_counter()
                if cpu_limit_type == "threadpool_limits":
                    with threadpool_limits(limits=n_cpu):
                        clf.fit(X, y)
                else:
                    clf.fit(X, y)
                duration = time.perf_counter() - start
                reached_max_iter = int(clf.n_iter_[0]) < clf.max_iter
    
                results.append(
                    {
                        "n_cpu": n_cpu,
                        "n_samples": n_samples,
                        "n_features": n_features,
                        "n_classes": n_classes,
                        "n_informative": n_informative,
                        "n_redundant": n_redundant,
                        "solver": solver,
                        "duration": duration,
                        "cpu_limit_type": cpu_limit_type,
                        "isolated": isolated,
                        "n_threads": n_threads,
                        "reached_max_iter": reached_max_iter,
                    }
                )
                progress.update(task, advance=1)
    
        df = pd.DataFrame.from_records(results)
        df.to_csv(
            "logistic_regression_bench_results.csv",
            mode="a",
            index=False,
            header=not Path("logistic_regression_bench_results.csv").exists(),
        )
    
    
    if __name__ == "__main__":
        parser = argparse.ArgumentParser(description="Benchmark the Logistic Regression.")
        parser.add_argument(
            "--isolated",
            action="store_true",
            help="Indicate that this script is the only thing running on the machine.",
        )
        parser.add_argument(
            "--cpu_limit_type",
            choices=("threadpool_limits", "OMP_NUM_THREADS"),
            help="How the CPU limitation is handled.",
        )
        parser.add_argument(
            "--n_threads",
            action="store_true",
            help="Indicate that the version of the logistic regression used is using n_threads > 1.",
        )
        args = parser.parse_args()
        main(args.cpu_limit_type, args.isolated, args.n_threads)

    To summarize : the parallelization seems to improve the performance at higher sample sizes, especially for lbfgs and to a lesser degree also for newton-cg. There are slowdowns at low sample sizes due to overhead. The speedups seem greater for lower number of features and higher number of classes.

  4. lesteve commented on Nov 18, 2025

    @lesteve
    Member

    FYI I created #32739 to do the simple part of deprecating n_jobs in LogisticRegression for the 1.8 relase. We can keep this issue about evalutating multi-threading which is longer term.

  5. changed the title [-]Deprecate n_jobs in LogisticRegression and evaluate multi-threading[/-] [+]Evaluate multi-threading `LogisticRegression`[/+] on Nov 19, 2025
  6. FrancoisPgm commented on Nov 19, 2025

    @FrancoisPgm
    Member

    Here are the same plots as in my previous comment, but this time in term of speed-up (i.e. median time with n_threads=1 divided by the median time with n_threads=_openmp_effective_n_threads()).

    lbfgs plots

    Image
    Image
    Image
    Image
    Image
    Image
    Image
    Image
    Image
    Image
    Image
    Image

    Image
    Image
    Image
    Image
    Image
    Image

    Image
    Image
    Image
    Image
    Image
    Image

    newton-cg plots

    Image
    Image
    Image
    Image
    Image
    Image
    Image
    Image
    Image
    Image
    Image
    Image

    Image
    Image
    Image
    Image
    Image
    Image

    Image
    Image
    Image
    Image
    Image
    Image

    newton-cholesky plots

    Image
    Image
    Image
    Image
    Image
    Image
    Image

    Image
    Image
    Image
    Image

    Image
    Image
    Image
    Image

    EDIT : added plots for 1e5 samples

  7. moved this to Todo in Labson Dec 11, 2025
  8. removed their assignment
    on Dec 11, 2025
  9. sudoMakeMeCool commented on Jan 28, 2026

    @sudoMakeMeCool
    Contributor

    System specifications:

    • OS: Windows 11
    • CPU: Intel Evo i7-1260P
    • RAM: 16 GB (DDR5)
    • Sklearn version: 1.7.2

    The experiment:

    I ran the script given by @FrancoisPgm to test three solvers - lbfgs, newton-cg, and newton-cholesky. I found that for lower sample sizes (100 and 10k), the lines in the graph are almost parallel to the X-axis, meaning multithreading provided negligible performance boost. For the 1M sample size, the duration became unstable, possibly due to a hardware bottleneck.

    Observations:

    • For the 1M sample size, performance is unpredictable for all three solvers. The duration seems to drop around n_cpu = 5 or 6, but zig-zags afterwards, likely due to memory bandwidth saturation.
    • The benchmark skipped results for newton-cholesky with class=32 (for both feature 10 and 100), hence the empty plots.

    Interpretation:

    The zig-zag pattern for higher sample sizes indicates that blindly increasing threads can introduce instability. Interestingly, lbfgs appears to be the most consistent solver across different tasks.

    Graphs plotted:

    lbfgs Image Image Image Image Image Image
    Newton-cg Image Image Image Image Image Image
    Newton-cholesky Image Image Image Image Image Image

    No data recorded for class = 32

  10. Vivek-ML001 commented on May 14, 2026

    @Vivek-ML001

    Benchmark results — Windows (Intel Core i7, 16GB DDR5)

    System specs:

    • OS: Windows 11 (10.0.19045)
    • CPU: Intel Evo i7-1260P
    • RAM: 16 GB DDR5
    • scikit-learn version: 1.6.1

    I ran the benchmark script from @FrancoisPgm comparing n_threads=1 vs n_threads=4 (via OMP_NUM_THREADS) for the lbfgs, newton-cg, and newton-cholesky solvers across sample sizes of 100, 10k, and 1M, with 10 and 100 features.

    Observations:

    • For small sample sizes (100 and 10k), 4 threads provides negligible improvement. The threading overhead cancels out any gains for all three solvers.
    • For large samples (1M) with 10 features, there are modest speedups:
      • lbfgs: 1.24s → 1.12s (~1.1x speedup)
      • newton-cholesky: 1.36s → 1.17s (~1.16x speedup)
      • newton-cg: 2.67s → 2.18s (~1.22x speedup)
    • For large samples (1M) with 100 features, 4 threads is slightly slower than 1 thread for all solvers, likely due to memory bandwidth saturation on this hardware.

    Summary:

    The results on this Windows/Intel machine are more modest than the Linux results reported by @FrancoisPgm. Speedups at 1M samples are present but small (~1.1–1.2x), and disappear or reverse at higher feature counts. This is consistent with the memory bandwidth saturation pattern observed by @CipherCat7134.

    This suggests the benefit of enabling multi-threading may be hardware/OS dependent, and a threshold-based heuristic (e.g. only enable for large n_samples and small n_features) could be worth considering.

    Graphs plotted:

    1. Duration by solver
    Image
    1. Speedup heatmap
    Image
    1. Large sample detail
    Image
  11. moved this from Todo to In progress in Labson May 17, 2026
  12. ogrisel commented on May 20, 2026

    @ogrisel
    Member

    Could you please expand the benchmark to cover large n_classes cases (e.g. n_classes >= n_features) and varying n_samples?

  13. cakedev0 commented on Sep 7, 2026

    @cakedev0
    Member

    Enabling multi-threading here would likely be very detrimental in some not-so-rare set-ups, as alternating between OpenMP parallel regions and OpenBLAS parallel regions can be very bad. See #17334.

  14. cakedev0 commented on Sep 29, 2026

    @cakedev0
    Member

    FYI, LogisticRegression with lbfgs solver currently suffers for a bad interactions between numpy's openBLAS and scipy's (older) openBLAS on PyPI: scipy/scipy#26193 (comment)

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

    APINeeds Benchmarks

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions