Skip to content

ENH HGBT use stack allocated buffers in histogram - #35441

Merged
ogrisel merged 5 commits into
scikit-learn:mainfrom
lorentzenchr:hgbt_stack_allocated_buffers_histogram
Nov 19, 2026
Merged

ogrisel merged 5 commits into
scikit-learn:mainfrom
lorentzenchr:hgbt_stack_allocated_buffers_histogram

Conversation

@lorentzenchr

Copy link
Copy Markdown
Member

Reference Issues/PRs

None.

What does this implement/fix? Explain your changes.

Histogram building is the bottleneck of HistGradientBoosting* fit. The update
out[bin[i]] += grad[i] is a read-modify-write: if 2 consecutive samples fall into
the same bin, the 2nd update has to wait for the 1st one (store-to-load forwarding).
This is frequent for features with few or unevenly populated bins (binary,
one-hot, zero-inflated).

This PR writes samples at odd positions of the unrolled loop to a temporary
stack-allocated histogram (256 bins, ~5 kB) and adds it to the output at the end.
Consecutive samples then never write to the same memory location.

  • Fit is up to ~20% faster on data with many low-cardinality features (covtype) and
    unchanged on continuous features, see benchmark in the first comment.
  • The 4 _build_histogram* functions get an additional n_bins argument.
  • Results are the same up to floating point summation order.
  • The module comment claiming that the loop unrolling enables auto-vectorization is
    corrected.
  • test_unrolled_equivalent_to_naive is parametrized over n_samples and n_bins.

AI usage disclosure

I used AI assistance for:

  • Code generation (reduction from 3 temporary histograms to 1, code comments)
  • Test/benchmark generation
  • Research and understanding

The first commit, I wrote my self, the others from AI were reviewd by me.

Any other comments?

Using 3 temporary histograms (one per unrolled position) gave no additional gain in
fit time over 1.

@lorentzenchr

Copy link
Copy Markdown
Member Author

Benchmark

Fit time in seconds, OMP_NUM_THREADS=4, Intel Core i7-8559U (4 cores), macOS, clang.
Best of 4 fits (2 alternating runs of main and this PR, 2 fits each).

data max_leaf_nodes main (s) PR (s) PR / main
covtype 581k x 54, binary clf 31 1.58 1.26 0.80
covtype 581k x 54, regression 31 1.27 0.99 0.77
synthetic mixed 1M x 28, binary clf 31 2.05 1.87 0.91
synthetic gauss 1M x 28, binary clf 31 1.99 2.03 1.02
california 20k x 8, regression 31 0.25 0.26 1.03
covtype 581k x 54, binary clf 255 2.93 2.52 0.86
covtype 581k x 54, regression 255 2.51 2.11 0.84
synthetic mixed 1M x 28, binary clf 255 4.73 4.51 0.95
synthetic gauss 1M x 28, binary clf 255 4.65 4.69 1.01
california 20k x 8, regression 255 1.31 1.32 1.01
  • covtype: 44 of 54 features are binary.
  • synthetic mixed: 1/4 rare binary (5% ones), 1/4 zero-inflated (70% zeros), 1/2 Gaussian features.
  • Regression uses constant hessians (_no_hessian code path), binary classification does not.
Benchmark script
"""Fit time of HGBT. Run once on main and once on the PR branch, e.g.
OMP_NUM_THREADS=4 python bench_pr.py
"""
from time import perf_counter

import numpy as np

from sklearn.datasets import fetch_california_housing, fetch_covtype
from sklearn.ensemble import (
    HistGradientBoostingClassifier,
    HistGradientBoostingRegressor,
)


def make_synthetic(n_samples, n_features, kind, seed=0):
    rng = np.random.default_rng(seed)
    X = rng.standard_normal((n_samples, n_features)).astype(np.float32)
    if kind == "mixed":
        q = n_features // 4
        # 1/4 rare binary features, 1/4 zero-inflated features, 1/2 Gaussian
        X[:, :q] = rng.random((n_samples, q)) < 0.05
        mask = rng.random((n_samples, q)) < 0.7
        X[:, q : 2 * q] = np.where(mask, 0, X[:, q : 2 * q])
    w = rng.standard_normal(n_features)
    noise = rng.standard_normal(n_samples)
    y = (X @ w + 2 * np.sin(3 * X[:, -1]) + noise > 0).astype(int)
    return X, y


def bench(name, Estimator, X, y, max_iter, max_leaf_nodes, n_repeat=2):
    best = np.inf
    for _ in range(n_repeat):
        est = Estimator(
            max_iter=max_iter,
            max_leaf_nodes=max_leaf_nodes,
            early_stopping=False,
            random_state=0,
        )
        tic = perf_counter()
        est.fit(X, y)
        best = min(best, perf_counter() - tic)
    print(f"{name} | {max_leaf_nodes} | {best:.3f}", flush=True)


clf, reg = HistGradientBoostingClassifier, HistGradientBoostingRegressor
X_cov, y_cov = fetch_covtype(return_X_y=True)  # 44 of 54 features are binary
X_cal, y_cal = fetch_california_housing(return_X_y=True)
X_mix, y_mix = make_synthetic(1_000_000, 28, "mixed")
X_gau, y_gau = make_synthetic(1_000_000, 28, "gauss")

print("data | max_leaf_nodes | fit time (s)")
for max_leaf_nodes in (31, 255):
    bench("covtype 581k x 54, binary clf", clf, X_cov, y_cov == 2, 20, max_leaf_nodes)
    bench("covtype 581k x 54, regression", reg, X_cov, y_cov, 20, max_leaf_nodes)
    bench("synthetic mixed 1M x 28, binary clf", clf, X_mix, y_mix, 20, max_leaf_nodes)
    bench("synthetic gauss 1M x 28, binary clf", clf, X_gau, y_gau, 20, max_leaf_nodes)
    bench("california 20k x 8, regression", reg, X_cal, y_cal, 100, max_leaf_nodes)

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

Interesting PR. The comments are great, I learned a few things in reviewing the diff.

@ogrisel
ogrisel merged commit d6a5828 into scikit-learn:main Nov 19, 2026
36 checks passed
@ogrisel

ogrisel commented Nov 19, 2026

Copy link
Copy Markdown
Member

I merged because this does not impact the public API and benchmarking results show no downsides to this change but @cakedev0 @adam2392 and others might be interested in this diff.

@lorentzenchr

Copy link
Copy Markdown
Member Author

Interesting PR. The comments are great, I learned a few things in reviewing the diff.

Glad to hear that.

@cakedev0

cakedev0 commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

I benchmarked it: neutral to slightly positive on most datasets, 1.5x faster on "kdd churn 2009" (2s faster), 1.1x faster on susy (4s faster), and 5% slower on "ames housing" (small dataset, 20ms slower => we don't care) 👍

Nice 😄

And fun trick indeed!

(ps: I benchmarked it single threaded, pinned on one cores, those kind of improvements tend to be invisible with many threads. But the single threaded performance is very important as it's what user get when doing hyper-parameter tuning with n_jobs=-1).

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

whoa neat simple trick! is this generalizable beyond just this issue in HGBT? e.g. we do a lot of such accumulations elsewhere (not gradients, but e.g. sample criterions in decision trees).

@lorentzenchr

Copy link
Copy Markdown
Member Author

is this generalizable beyond just this issue in HGBT?

I don’t think so, at least I don’t think it is worth it. Here it kind of was worth the effort because computing the histograms is usually the largest bottleneck for HGBT. I tried a lot in the last years to improve it.

@cakedev0

Copy link
Copy Markdown
Member

I tried a lot in the last years to improve it.

Out of curiosity: What's your motivation? Is it because you use it and it would be convenient if it was faster? Is it because it's an important model? Or because it's fun? 😁 (or something else... ^^)

@lorentzenchr

Copy link
Copy Markdown
Member Author

What's your motivation?

For fun, for my own education, I learned a lot. For instance, LightGBM does not compute sample counts, it only approximates it via the hessian. This saves ~10-20% of time in histograms. This means we, scikit-learn, provide a better/more correct feature for „min samples per feaf“ (and so on). Who knows it? (Almost nobody) It is advertised nowhere!

Another motivation: HGBT is our top tier supervised model. But it is hardly ever mentioned in publications and posts outside scikit-learn. I think LightGBM has 3 main advantages:

  • always works, ie. no 256 bin limitation
  • faster fit
  • native model persitence

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