Skip to content

ENH software prefetching of bins in HGBT histogram building - #35526

Open
lorentzenchr wants to merge 3 commits into
scikit-learn:mainfrom
lorentzenchr:hgbt_prefetch_bins
Open

lorentzenchr wants to merge 3 commits into
scikit-learn:mainfrom
lorentzenchr:hgbt_prefetch_bins

Conversation

@lorentzenchr

Copy link
Copy Markdown
Member

Reference Issues/PRs

Follow-up of #35441.

TLDR This PR makes HGBT faster by software prefetching (as does LightGBM).

What does this implement/fix? Explain your changes.

The samples of a small node are scattered over the whole column of X_binned.
Reading their bins is a gather with a cache miss for almost every sample, which
hardware prefetchers do not detect. On Higgs (8.8M x 28, 31 leaves), nodes with less
than 1/16 of the samples take about half of the histogram time.

This PR prefetches the bins 128 samples ahead in _build_histogram and
_build_histogram_no_hessian. It is only done if all of the following hold:

  • X_binned has at least 2**17 rows (smaller columns fit into the CPU caches),
  • the node has at most 1/16 of all samples (larger nodes read the column nearly
    sequentially),
  • the node has at least 1024 samples.

LightGBM does the same in its column-wise histograms (distance 64, without
conditions), see
dense_bin.hpp.

Results are bit-wise identical to main.

Benchmarks

Intel Core i7-8559U (4 cores), macOS, clang, 4 threads, best of 2 alternating runs of
main and this PR.

Histogram computation alone, 2M x 28, time per node in ms:

node size / n_samples main PR
1/1 (root) 14.8 14.9
1/2 9.92 9.93
1/4 5.13 5.22
1/8 2.72 2.70
1/16 1.69 1.64
1/64 1.43 1.17
1/256 0.97 0.51
1/1024 0.18 0.08

Fit time in seconds:

data max_leaf_nodes main PR
covtype 581k x 54, binary clf 31 1.18 1.12
synthetic 1M x 28, binary clf 31 1.80 1.73
california 20k x 8, regression 31 0.26 0.25
covtype 581k x 54, binary clf 255 2.46 2.29
synthetic 1M x 28, binary clf 255 4.57 3.74
california 20k x 8, regression 255 1.32 1.38

python benchmarks/bench_hist_gradient_boosting_higgsboson.py --n-trees 100 --no-predict:
fit 51.8 s -> 43.7 s, time spent computing histograms 35.0 s -> 28.5 s.

Benchmark script: histogram computation alone
"""Time the histogram computation of HGBT alone, for nodes of different sizes.

Run on main and on the PR branch and compare, e.g.
    python bench_histogram.py --n-samples 2000000 --n-features 28
"""

import argparse
from time import perf_counter

import numpy as np

from sklearn.ensemble._hist_gradient_boosting.common import G_H_DTYPE, X_BINNED_DTYPE
from sklearn.ensemble._hist_gradient_boosting.histogram import HistogramBuilder
from sklearn.utils._openmp_helpers import _openmp_effective_n_threads

parser = argparse.ArgumentParser()
parser.add_argument("--n-samples", type=int, default=2_000_000)
parser.add_argument("--n-features", type=int, default=28)
parser.add_argument("--n-threads", type=int, default=None)
args = parser.parse_args()

n_samples, n_features = args.n_samples, args.n_features
n_threads = _openmp_effective_n_threads(args.n_threads)
rng = np.random.default_rng(0)
X_binned = np.asfortranarray(
    rng.integers(0, 255, size=(n_samples, n_features), dtype=X_BINNED_DTYPE)
)
gradients = rng.standard_normal(n_samples).astype(G_H_DTYPE)
hessians = rng.random(n_samples).astype(G_H_DTYPE)
builder = HistogramBuilder(X_binned, 256, gradients, hessians, False, n_threads)

print(f"{n_samples} x {n_features}, {n_threads} threads")
print("| node size / n_samples | n_node_samples | time per node (ms) |")
print("|---|---|---|")
for denominator in (1, 2, 4, 8, 16, 64, 256, 1024):
    n_node_samples = n_samples // denominator
    if denominator == 1:
        sample_indices = np.arange(n_samples, dtype=np.uint32)  # root
    else:
        # A node is a sorted subset of all samples.
        sample_indices = np.sort(
            rng.choice(n_samples, size=n_node_samples, replace=False)
        ).astype(np.uint32)
    n_calls = min(denominator, 32)
    best = np.inf
    for _ in range(5):
        tic = perf_counter()
        for _ in range(n_calls):
            builder.compute_histograms_brute(sample_indices)
        best = min(best, (perf_counter() - tic) / n_calls)
    print(f"| 1/{denominator} | {n_node_samples} | {1e3 * best:.2f} |", flush=True)
Benchmark script: fit time
"""Fit time of HGBT on a few datasets. Run on main and on the PR branch."""

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, seed=0):
    rng = np.random.default_rng(seed)
    X = rng.standard_normal((n_samples, n_features)).astype(np.float32)
    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=3):
    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:.2f} |", flush=True)


clf, reg = HistGradientBoostingClassifier, HistGradientBoostingRegressor
X_cov, y_cov = fetch_covtype(return_X_y=True)
X_cal, y_cal = fetch_california_housing(return_X_y=True)
X_syn, y_syn = make_synthetic(1_000_000, 28)

print("| data | max_leaf_nodes | fit time (s) |")
print("|---|---|---|")
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("synthetic 1M x 28, binary clf", clf, X_syn, y_syn, 20, max_leaf_nodes)
    bench("california 20k x 8, regression", reg, X_cal, y_cal, 100, max_leaf_nodes)

AI usage disclosure

I used AI assistance for:

  • Code generation
  • Test/benchmark generation
  • Research and understanding

I, Christian, reviewed the code changes and specifically instructed Claude to improve HGBT by prefetching.

Any other comments?

  • The 3 thresholds and the distance were tuned on a single Intel machine. Timings on
    other hardware, in particular Apple Silicon and AMD, are very welcome.
  • 1, 2 or 4 prefetches per loop iteration: 4 was fastest.

lorentzenchr and others added 2 commits November 25, 2026 20:46
The samples of a small node are scattered over the whole column of
X_binned, so reading their bins is a gather with a cache miss for almost
every sample. For large X_binned, prefetch the bins 128 samples ahead.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Nodes with 1/8 or 1/4 of all samples were about 13% slower with prefetching.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

This branch has not been deployed

No deployments
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.

1 participant