Repository navigation
Conversation
BenchmarkFit time in seconds,
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) |
Co-Authored-By: Claude Fable 5.2 <[email protected]>
ogrisel
left a comment
There was a problem hiding this comment.
Interesting PR. The comments are great, I learned a few things in reviewing the diff.
Glad to hear that. |
|
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 |
adam2392
left a comment
There was a problem hiding this comment.
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).
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. |
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... ^^) |
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:
|
Reference Issues/PRs
None.
What does this implement/fix? Explain your changes.
Histogram building is the bottleneck of
HistGradientBoosting*fit. The updateout[bin[i]] += grad[i]is a read-modify-write: if 2 consecutive samples fall intothe 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.
unchanged on continuous features, see benchmark in the first comment.
_build_histogram*functions get an additionaln_binsargument.corrected.
test_unrolled_equivalent_to_naiveis parametrized overn_samplesandn_bins.AI usage disclosure
I used AI assistance for:
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.