Skip to content

PERF Faster GradientHistogramBooster by improving the binning algorithm's binary search - #34194

Merged
ogrisel merged 17 commits into
scikit-learn:mainfrom
itamarst:faster-binning
Jun 24, 2026
Merged

ogrisel merged 17 commits into
scikit-learn:mainfrom
itamarst:faster-binning

Conversation

@itamarst

@itamarst itamarst commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Binning is a significant percentage of time spent by GradientHistogramBooster. The new implementation in this PR is inspired by Paul Khuong's version, plus one idea taken from the original article.

GradientHistogramBooster benchmarks seem to be 5-25% faster, depending on benchmark, machine, and number of OpenMP threads.

Why is it faster? Looking at perf stat for the higgs boson benchmark, it reduces branch mispredictions quite a bit. Given histograms are still a minority of the code runtime, I have to imagine the misprediction reduction is that much more significant if I were to look just at the modified part of the code.

Benchmarks

Benchmarks are on Linux x86-64, i7-12700K, compiled with gcc.

Running on my Mac M1, the performance difference is less significant than benchmarks below (clang is smarter? CPU differences?), but it's still faster on the branch than on main. So numbers may vary but it's still seems like a speed benefit on Mac ARM machines as well.

On main:

$ OMP_NUM_THREADS=1 DISPLAY= /usr/bin/time python benchmarks/bench_hist_gradient_boosting_higgsboson.py 
Training set with 8800000 records with 28 features.
Fitting a sklearn model...
Binning 1.971 GB of training data: 12.909 s
Fitting gradient boosted rounds:
Fit 10 trees in 28.376 s, (310 total leaves)
Time spent computing histograms: 11.203s
Time spent finding best splits:  0.019s
Time spent applying splits:      1.987s
Time spent predicting:           0.651s
fitted in 28.386s
predicted in 2.351s, ROC AUC: 0.7953, ACC: 0.7184
32.98user 1.48system 0:34.48elapsed 99%CPU (0avgtext+0avgdata 7766556maxresident)k
0inputs+0outputs (0major+327127minor)pagefaults 0swaps

On new branch:

$ OMP_NUM_THREADS=1 DISPLAY= /usr/bin/time python benchmarks/bench_hist_gradient_boosting_higgsboson.py 
Training set with 8800000 records with 28 features.
Fitting a sklearn model...
Binning 1.971 GB of training data: 4.304 s
Fitting gradient boosted rounds:
Fit 10 trees in 19.346 s, (310 total leaves)
Time spent computing histograms: 11.032s
Time spent finding best splits:  0.019s
Time spent applying splits:      1.941s
Time spent predicting:           0.652s
fitted in 19.356s
predicted in 2.390s, ROC AUC: 0.7953, ACC: 0.7184
24.18user 1.27system 0:25.48elapsed 99%CPU (0avgtext+0avgdata 7766404maxresident)k
0inputs+0outputs (0major+262910minor)pagefaults 0swaps

Higgs Boson benchmark uses 255 bins most of the time, 2-3 bins a tiny bit.

benchmarks/bench_hist_gradient_boosting_categorical_only.py --n-samples 1_000_000 shows small speed-ups, or no speed-ups, with 128 and 255 bins, all threads or 1 thread.

benchmarks/bench_hist_gradient_boosting_threading.py goes from 91CPU seconds / 34.6 seconds elapsed on main to 71 CPU seconds / 26 elapsed on this branch (255 bins).

Reference Issues/PRs

Can open one if it's helpful.

What does this implement/fix? Explain your changes.

Should have identical behavior, just run faster.

AI usage disclosure

No "AI".

Any other comments?

Tried the graphing in #34128; more threads is still a problem.

@itamarst itamarst closed this Jun 3, 2026
@itamarst itamarst reopened this Jun 4, 2026
@itamarst
itamarst marked this pull request as ready for review June 4, 2026 14:30
@ogrisel
ogrisel requested review from Copilot and ogrisel June 4, 2026 16:48
@ogrisel

ogrisel commented Jun 4, 2026

Copy link
Copy Markdown
Member

Sorry I clicked the copilot review request by mistake (I wanted to self request a review on this instead)...

@ogrisel

ogrisel commented Jun 4, 2026

Copy link
Copy Markdown
Member

For the record, I'll tried to find the time to runs some benchmarks on my Apple M4 laptops to see if I can reproduce similar improvements on a different OS/CPU/compiler setup.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR optimizes the binning step used by HistGradientBoosting* by replacing the per-value branching binary search with a more branch-misprediction-resistant (largely branchless) binary search strategy, aiming to reduce runtime spent in _map_to_bins.

Changes:

  • Refactor _map_col_to_bins to use a new nogil inline _binary_search implementation.
  • Add a small log2ceil lookup table (0–255) to bound the binary search loop count.
  • Tighten some memoryview typings to favor contiguous access patterns ([::1]).

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@itamarst

itamarst commented Jun 4, 2026

Copy link
Copy Markdown
Contributor Author

For the record, I'll tried to find the time to runs some benchmarks on my Apple M4 laptops to see if I can reproduce similar improvements on a different OS/CPU/compiler setup.

Thanks! As mentioned it helps somewhat on some of the benchmarks on M1, most noticeably on the ..._threading.py one in single-threaded mode, and doesn't seem worse anywhere that I tried.

@itamarst

Copy link
Copy Markdown
Contributor Author

Got access to a Mac M4. Seems faster here too for these two benchmarks, and no difference on others I tried.

Peak memory seems a bit higher in the asv test, with no speedup there.

benchmarks/bench_hist_gradient_boosting_higgsboson.py with OMP_NUM_THREADS=1

branch real user sys
main 17.56 real 17.15 user 0.40 sys
PR 15.50 real 14.43 user 0.37 sys

benchmarks/bench_hist_gradient_boosting_threading.py with OMP_NUM_THREADS=1

branch real user sys
main 44.54 real 43.54 user 0.35 sys
PR 33.45 real 33.15 user 0.35 sys

@ogrisel ogrisel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM once the following comment is addressed given the benchmark results.

@cakedev0 would love your feedback on this PR.

@itamarst

Copy link
Copy Markdown
Contributor Author

Thank you, will do next week.

@cakedev0

Copy link
Copy Markdown
Member

Hi @itamarst, this is a really cool optimization! And a really nice showcase of branchless code benefits! Thank you!

On this benchmark https://github.com/cakedev0/numerical-python-bench/blob/main/bench_hgbt_sweep.py that records the time taken by each part, I get a 5x speed-up for the bin transform part. It's less when increasing the number of threads (2x for 12 threads on my machine) but still nice. I guess this optimized version of the function becomes memory bound quickly.

@cakedev0

Copy link
Copy Markdown
Member

I benchmark with F-order vs C-order for X, and it's interesting:

  • for 1 thread, the difference is small (C-order is ~30% slower)
  • for 12 threads, C-order is almost twice slower (which means F-order scales better).

This is visible for big enough datasets (n_samples * 64B > size of L3 cache I think).

Note that the gain from having X in F-order is not big enough to compensate for the cost of doing np.asfortranarray(X), at least on my machine. So I don't think we can optimize further than what is done there. And honestly, what is done there is quite fast 😄

@github-actions github-actions Bot added the CI:Linter failure The linter CI is failing on this PR label Jun 22, 2026
@github-actions github-actions Bot removed the CI:Linter failure The linter CI is failing on this PR label Jun 22, 2026
@itamarst

Copy link
Copy Markdown
Contributor Author

I merged forward to address the cython-lint issues.

@cakedev0 cakedev0 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM 👍

@ogrisel

ogrisel commented Jun 22, 2026 •

Copy link
Copy Markdown
Member

@itamarst could you please add a changelog entry for this PR? I think this qualifies as an "efficiency" improvement.

@ogrisel

ogrisel commented Jun 22, 2026

Copy link
Copy Markdown
Member

Let's also wait for the merge of #34343 and check that this test still pass with this PR updated to run it.

@itamarst

Copy link
Copy Markdown
Contributor Author

Added news file (which is hopefully accurate—is binning also used in fitting?) and merged forward, should include #34343 now.

@itamarst

Copy link
Copy Markdown
Contributor Author

Or maybe I misunderstood and it's only used in fitting...

@cakedev0

Copy link
Copy Markdown
Member

Yes it's only used during fit (for preprocessing, and for "in-fit predictions" for early stopping)

@cakedev0

Copy link
Copy Markdown
Member

For normal/public predict, we use "predict_raw".

... But I wouldn't be surprised binning first and then predicting on binned values to be faster (X.dtype becomes uint8 instead of float64 and logic gets simpler).

@itamarst

Copy link
Copy Markdown
Contributor Author

Ok, fixed the changelog. If you have time @cakedev0 would be interesting to see if this does indeed speed up predictions, I won't this week.

@cakedev0

Copy link
Copy Markdown
Member

I did that a bit this morning, but it's quite hard to make a conclusion, there are so many impacting factors.

It's really easy to draw a conclusion, then change a few things in the benchmarks set-up and draw opposite conclusions...

I'll try to make a good benchmark for that, which means:

  • various real world datasets (statistical tree structure matters for memory cache hits)
  • small to huge number of features
  • a few leaves to hundreds of leaves per tree
  • a few dozens of trees to thousands of trees

But that'll be for a bit later.

@cakedev0 cakedev0 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think we can merge this one, thanks again @itamarst!

@cakedev0 cakedev0 moved this to In progress in Labs Jun 24, 2026
@cakedev0 cakedev0 added this to Labs Jun 24, 2026
@ogrisel
ogrisel merged commit 52c2525 into scikit-learn:main Jun 24, 2026
33 checks passed
@github-project-automation github-project-automation Bot moved this from In progress to Done in Labs Jun 24, 2026
@ogrisel

ogrisel commented Jun 24, 2026

Copy link
Copy Markdown
Member

Merged. Thanks, @itamarst, for the contrib and benchmarking efforts and @cakedev0 for the review and extra benchmarking checks.

prady0t pushed a commit to prady0t/scikit-learn that referenced this pull request Sep 2, 2026
@jeremiedbb jeremiedbb mentioned this pull request Sep 8, 2026
14 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants