Skip to content

PRF Mitigation heuristics for HGB scalability - #34935

Merged
lesteve merged 84 commits into
scikit-learn:mainfrom
cakedev0:hgb/active_wait
Nov 30, 2026
Merged

lesteve merged 84 commits into
scikit-learn:mainfrom
cakedev0:hgb/active_wait

Conversation

@cakedev0

@cakedev0 cakedev0 commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

Finally, I have something that has a uniformly positive impact on the 8 scenarios I'm testing:

  • Big machine with default OMP settings
  • Big machine with OMP_PROC_BIND=close (avoids penalizing runs that use fewer threads than what's available on the machine)
  • Laptop with active wait disabled (the default behavior of conda-forge packages)
  • Laptop with active wait enabled

(× libgomp & libomp for each of those)

And it can be very/hugely beneficial in some scenarios (2-10x speed-ups):

  • small to medium datasets on a big machine
  • small to medium-big datasets on laptops with active wait disabled

Reference Issues/PRs

Fixes #30662

Implements item 4 (partially), item 5 and item 6 of #34764 (comment)

I'd also say it closes #14306, though that issue does have some ideas that aren't implemented here, in particular parallelizing over blocks of samples × features when building histograms. Benchmarks show HGB does keep scaling up to 16-32 threads for many medium/big datasets, as long as active wait is enabled, which I'd personally consider good enough for now.

What does this implement/fix? Explain your changes.

  • Detect whether the OpenMP runtime uses active wait, i.e. whether idle threads spin instead of sleeping while waiting for work (_openmp_uses_active_wait in sklearn/utils/_openmp_helpers.pyx). This is done by parsing the environment dump the runtime prints under OMP_DISPLAY_ENV=VERBOSE, in a short-lived subprocess. Active wait makes rejoining a parallel region much cheaper, so all the heuristics below branch on it.
  • Cap the number of threads used to grow each tree, based on the number of features and samples (BaseHistGradientBoosting._get_heuristic_optimal_n_threads), instead of always using every available thread.
  • Same idea for binning: _BinMapper's n_threads parameter is renamed to max_n_threads since it's now only an upper bound, the actual thread count used being derived from the amount of data to bin.
  • In Splitter.split_indices, fall back to a single-threaded partitioning pass when there isn't enough work per thread to justify the chunking/offset bookkeeping of the multi-threaded version.
  • In Splitter.find_node_split, when active wait is disabled, skip parallelizing over features when there are too few of them relative to n_threads.

AI usage disclosure

Mostly not, except for the active wait detection: Claude helped find a way to make the subprocess-based _openmp_uses_active_wait fast enough not to matter (result cached after the first call, subprocess kept minimal to avoid a full import sklearn).

Benchmarks

  • Breakdown of the speed-up vs main:

https://pr-81.sklbench-dashboard-preview.pages.dev/

  • Comparative Pareto analysis vs alternative libraries:

https://pr-141.sklbench-dashboard-preview.pages.dev/gbdt_pareto

I still have to run some tests on windows.

cakedev0 and others added 30 commits August 13, 2026 09:50
Non regression test for the OverflowError fixed in 68e1aae: find_best_split
only populated n_subsampled_features entries of the split_infos buffer, but
scanned all n_allowed_features when picking the best split, reading
uninitialized memory whenever max_features < 1.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@lorentzenchr lorentzenchr 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.

Some initial review (need a bigger screen to do it properly).

Comment thread doc/developers/global_configuration.rst Resolved
Comment thread sklearn/utils/_openmp_helpers.pyx Resolved
Comment thread sklearn/utils/_openmp_helpers.pyx Outdated
Comment on lines +22 to +39
# Patterns matched against the block an OpenMP runtime prints on stderr when
# OMP_DISPLAY_ENV is set: they identify a *resolved* spin-count setting (as
# opposed to what was requested through environment variables, which the
# runtime may ignore, normalize, or default differently) that means idle
# threads do not spin. Note that ``OMP_WAIT_POLICY`` is not a reliable
# signal by itself: e.g. libgomp can report it as ``PASSIVE`` while
# ``GOMP_SPINCOUNT`` was explicitly set to a large value, which still makes
# threads spin in practice. Values may be prefixed by a device scope (e.g.
# "[host] ") and wrapped in quotes, hence the loose whitespace/quoting.
_PASSIVE_WAIT_PATTERNS = tuple(
re.compile(pattern)
for pattern in (
# GNU libgomp: spinning at most once is effectively passive.
r"GOMP_SPINCOUNT\s*=\s*'?[01]'?\D",
# Intel's and LLVM's OpenMP runtimes.
r"KMP_BLOCKTIME\s*=\s*'?0'?\D",
)
)

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.

Maybe it is late, I don't get it. What is _PASSIVE_WAIT_PATTERNS for?

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.

My understanding is that this is to parse the output of the subprocess that figures out whether active wait is on or not see _openmp_uses_active_wait function below.

Comment thread sklearn/utils/_openmp_helpers.pyx Resolved
Comment thread sklearn/utils/_openmp_helpers.pyx Outdated
Comment on lines +48 to +49
smaller workloads. This is controlled by ``GOMP_SPINCOUNT`` (GNU's ``libgomp``) and
``KMP_BLOCKTIME`` (Intel's and LLVM's OpenMP runtimes).

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.

One is a count and the other a time. This is calling for trouble. Isn't it?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Well, there is nothing we can do about it 😅

Comment thread sklearn/utils/_openmp_helpers.pyx Resolved
@cakedev0

Copy link
Copy Markdown
Member Author

@lorentzenchr I had claude rewrote the comments & docstrings based on your questions, @lesteve answers and my answers. Then I edited it a bit, and now I think it's easier to understand, and more consistent in terms of vocabulary.

cakedev0 and others added 4 commits November 17, 2026 10:43
…t one

TreeGrower is private and only HGB's fit passes the heuristic thread
count, so requiring both arguments only added churn to the tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread sklearn/utils/_openmp_helpers.pyx Resolved
Comment thread sklearn/utils/_openmp_helpers.pyx Resolved
Comment on lines +63 to +65
If ``SKLEARN_OMP_WAIT_POLICY`` is set to ``"active"`` or ``"passive"``
(case-insensitive), its value is used without any detection. It does not change
the wait policy of the OpenMP runtime itself.

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.

Suggested change
If ``SKLEARN_OMP_WAIT_POLICY`` is set to ``"active"`` or ``"passive"``
(case-insensitive), its value is used without any detection. It does not change
the wait policy of the OpenMP runtime itself.
If ``SKLEARN_OMP_WAIT_POLICY`` is set (by a user) to ``"active"`` or ``"passive"``
(case-insensitive), this value is used without any further automatic detection. Note, however, that it does not change
the wait policy of the OpenMP runtime itself.

If setting SKLEARN_OMP_WAIT_POLICY manually does not change the OpenMP runtime policy, what good does it do to set it manually?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

(good suggestion 👍 )

In case you know your OpenMP policy but the detection doesn't get it right (It's very niche, but I think Olivier wanted that, initially I had a private env var IIRC).

@ogrisel ogrisel Nov 18, 2026 •

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.

The point is to provide easier control to debug this part of the code, improve testability and makes it possible to avoid redoing redundant runtime checks in each joblib/loky subprocess worker (e.g. when tuning the HGB parameters a gridsearch with n_jobs > 1).

If you prefer, we can set it back to an undocumented private env variable named _SKLEARN_OMP_WAIT_POLICY instead.

# its settings) as soon as it is loaded, but libomp only on the first OpenMP
# call.
#
# TODO: move this detection to threadpoolctl. For libomp, it could read the

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.

Yeah, I like that.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Me too 😄

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

(but it might be painful as for libgomp we need to import a compiled extension using OpenMP, and for now threadpoolctl is pure Python...)

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.

We could make the threadpoolctl argument accept a module name argument or dynlib filename argument that would be in charge of triggering the openmp runtime load in the subprocess. This way threadpoolctl can stay pure python and only the caller (that actually exercises openmp enabled native extensions) can deal with this.

@ogrisel ogrisel Nov 18, 2026 •

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.

However I would would not block this PR for this. I think we can do this refactoring later, after this PR's merge.

Note: making the _SKLEARN_OMP_WAIT_POLICY env var private as discussed in #34935 (comment) would actually make this refactoring easier to do (without any backward compat concerns) I think.

@lesteve lesteve 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.

Partial review ....

# sample-wise parallel regions start to dominate which could be the
# case on datasets with small number of features but very large
# numbers of data points.
n_threads_for_samples = min(0.1 * math.pow(n_samples, 1 / 3), max_n_threads)

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.

Out of curiosity, any intuition on this formula? Was your agent somehow guided in the kind of heuristics it was trying?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

How I chose this y= f(x) transformation:

I had a few empirical (x, y) pairs and I wanted to find a formula to interpolate from those, while keeping it simple. But basically, you have to have a very large n_samples (and low n_features) for this to have an impact, because empirically, it's very rarely beneficial to grow the number of threads above n_features.

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.

There seems to be a resurgence of the cube root of n_samples these days 🤣

Comment thread sklearn/utils/_openmp_helpers.pyx Resolved
Comment thread sklearn/utils/_openmp_helpers.pyx Resolved
@lesteve

lesteve commented Nov 20, 2026

Copy link
Copy Markdown
Member

Tiny merge conflicts to fix.

@ogrisel

ogrisel commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

For information, I tried to rerun the original script of #30662 on my Apple M4 with the current PR and the most catastrophic slowdowns are fixed by this PR (without having to enable active wait): the worst slowdown is now 4x (instead of 15x) for the smallest problem size and as many threads as cores.

For instance, here the first plot of that issue (executed on main branch at the time):

image

now becomes (when run on this branch):

image

The shape=(100, 10) case is still quite bad but this an extremely small dataset. I don't think anybody would care. More interesting cases such as shape=(10000, 10) that were also very bad are mostly fixed by that PR. Note that the y axis has a log scale. So the improvement is quite significant.

Note that this machine has only 4 performance cores (out of 10), so I think those curves are ok.

I also tried with KMP_BLOCKTIME=200 and in this case the worst slowdowns are further reduced and the best speed-ups improved a bit as well. The first plot becomes:

image

@ogrisel

ogrisel commented Nov 20, 2026

Copy link
Copy Markdown
Member

We could try to better handle non-performance cores in a follow-up PR but I think this PR is already a great improvement in its current state.

# Used by _openmp_uses_active_wait to parse the settings that the OpenMP runtime
# prints on stderr when OMP_DISPLAY_ENV=VERBOSE. Each pattern matches a value
# meaning that idle threads sleep right away instead of spinning, e.g.
# "[host] KMP_BLOCKTIME='0ms'" (libomp) or "GOMP_SPINCOUNT = '1'" (libgomp).

@lesteve lesteve Nov 23, 2026 •

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.

It would be nice to mention that GOMP_SPINCOUNT=1 is a bit of a special case that happens often enough on modern laptops because gcc>=14 sets GOMP_SPINCOUNT=1 for hybrid CPUs. Without such a comment, I find it hard to understand why we special case GOMP_SPINCOUNT=1.

I couldn't find a public gcc discussion about it, only the gcc commit or the same gcc commit in the GitHub mirror. There is also ggml-org/llama.cpp#31516.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good point 👍

I also mentioned libomp: it sets KMP_BLOCKTIME=0 on hybrid CPUs since LLVM 14 (no rationale given either).
This is the linux scheduler thing I started investigated, I think people (GCC and LLVM) adapted to it but nobody did the digging.

@lesteve

lesteve commented Nov 30, 2026

Copy link
Copy Markdown
Member

I gave it another look, this looks in good shape, let's merge this one!

@lesteve
lesteve merged commit a3a827b into scikit-learn:main Nov 30, 2026
39 checks passed
@github-project-automation github-project-automation Bot moved this from PR waiting for reviews to Done in Labs Nov 30, 2026
@cakedev0

Copy link
Copy Markdown
Member Author

🕺 🎉 🚀

Thank you everyone for the reviews!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

6 participants