Sub topic 12
How XGBoost finds splits: exact and histogram methods
Every tree XGBoost grows is a series of split decisions. Building a tree is mostly a search for the best split. This chapter covers how that search works, the strategies XGBoost offers, and how to choose between them.
It assumes you know the XGBoost objective (gradients g, hessians h, the regularization terms lambda and gamma), basic tree structure, and the scikit-learn API from earlier chapters.
The quantity being maximized
For one candidate split, let G_L and H_L be the sums of gradients and hessians of the rows going left. Let G_R and H_R be the same sums for the rows going right. With G = G_L + G_R and H = H_L + H_R, the gain is:
gain = 0.5 * [ G_L^2/(H_L+lambda) + G_R^2/(H_R+lambda) - G^2/(H+lambda) ] - gamma
A split is kept only if the gain is positive. This is why gamma (also called min_split_loss) acts as a pruning threshold. The score depends only on four sums per candidate. So the whole search reduces to computing G_L and H_L for many thresholds efficiently. The split-finding methods differ in how they choose the candidate thresholds and how they compute those sums.
Exact greedy search
The exact method, tree_method="exact", works like this for each node and each feature:
- Sort the node's rows by the feature value.
- Scan left to right, keeping running sums of
gandh. These running sums areG_LandH_L. - At each boundary between two distinct values, compute the gain from the running sums and the node totals.
- Keep the best (feature, threshold) pair across all features.
The following NumPy function does this for one feature. It uses squared error, where g = prediction - y and h = 1.
import numpy as np
def best_split(x, g, h, lam=1.0, gamma=0.0):
order = np.argsort(x)
xs, gs, hs = x[order], g[order], h[order]
G, H = gs.sum(), hs.sum()
GL = np.cumsum(gs)[:-1]
HL = np.cumsum(hs)[:-1]
GR, HR = G - GL, H - HL
gain = 0.5 * (GL**2 / (HL + lam) + GR**2 / (HR + lam)
- G**2 / (H + lam)) - gamma
gain = np.where(xs[:-1] < xs[1:], gain, -np.inf) # only between distinct values
if not np.isfinite(gain).any():
return None
i = int(np.argmax(gain))
return (xs[i] + xs[i + 1]) / 2, float(gain[i])
rng = np.random.default_rng(0)
x = rng.uniform(0, 1, 500)
y = np.where(x > 0.6, 2.0, 0.0) + rng.normal(0, 0.1, 500)
pred = np.full_like(y, y.mean())
threshold, gain = best_split(x, pred - y, np.ones_like(y))
print(round(threshold, 3), round(gain, 1)) # threshold close to 0.6The first scan finds a threshold near 0.6, the true step. Exact search is the reference behavior: it considers every distinct threshold, so it can find the best split on the data. The cost is the sort and scan on every feature at every node. XGBoost avoids repeated sorting by pre-sorting columns once, but memory use and run time still grow quickly with rows. Exact mode runs on CPU only and does not support distributed training.
Approximate and histogram methods
On large data you rarely need every threshold. Two methods propose a limited set of candidates instead.
approxbuilds candidate thresholds with a weighted quantile sketch, where each row is weighted by its hessian. It re-proposes candidates for every tree.histgroups each feature into at mostmax_binbins (default 256) once, before training. Every later step works on small integer bin indices rather than raw floats.
With hist, each node builds a histogram per feature. A histogram holds the sum of g and h for each bin. Split search then scans at most max_bin bins instead of all rows. The prefix sums over bins give G_L and H_L, and the same gain formula applies.
The subtraction trick in the last steps saves roughly half the histogram work. The parent's histogram already equals the sum of its children's histograms. So XGBoost scans only the rows of the smaller child and gets the other child by subtraction.
Comparing the methods
| Method | Candidate thresholds | Typical use | Notes |
|---|---|---|---|
| `exact` | Every distinct value | Small data, reference results | CPU only, slow and memory-heavy on large data |
| `approx` | Hessian-weighted quantiles, re-proposed per tree | Rarely preferred now | Supports distributed training |
| `hist` | At most `max_bin` bins, computed once | Default choice, large data, GPU | Fast. Thresholds are limited to bin edges |
Using the methods in practice
The method is one constructor argument. This script compares run times on a moderately large problem:
import time
from sklearn.datasets import make_classification
from xgboost import XGBClassifier
X, y = make_classification(n_samples=100_000, n_features=50,
n_informative=20, random_state=0)
for method, extra in [("exact", {}), ("hist", {}), ("hist", {"max_bin": 32})]:
model = XGBClassifier(n_estimators=100, max_depth=6,
tree_method=method, **extra)
start = time.perf_counter()
model.fit(X, y)
label = method + (f" max_bin={extra['max_bin']}" if extra else "")
print(f"{label:<18}{time.perf_counter() - start:6.1f}s")Timings depend on your hardware, but hist is typically several times faster than exact at this size, and the gap widens as rows grow. On GPU, use tree_method="hist" with device="cuda" (XGBoost 2.0 and later).
Choosing max_bin and understanding the trade-off
max_bin controls the resolution of thresholds.
- Features with fewer unique values than
max_binget one bin per value, so they lose nothing. - Continuous features lose precision because a threshold can only fall on a bin edge. A coarse grid can miss the sharpest cut, but the error is usually small and often acts as mild regularization.
- Raising
max_bin(for example to 512) costs more memory and time. It helps when a feature has fine-grained structure, such as an exact cutoff in a continuous variable. - Lowering it (64 or 32) speeds up training and reduces GPU memory.
Quantile bins are chosen by rank, not by value range. Skewed features still get roughly equal numbers of rows per bin, which is why no manual scaling is needed.
Edge cases
- Missing values. At each split XGBoost tries sending rows with missing values left, then right, and keeps the direction with higher gain. That direction becomes the default for missing values at that node. Missing values get their own handling and do not occupy a normal bin.
- Categorical features. With
enable_categorical=True, categories are partitioned into two groups, rather than split by a numeric threshold. This works withhistandapproxbut notexact. - Ties and constant features. A feature with one distinct value yields no valid split and is skipped. In
best_splitabove, the checkxs[:-1] < xs[1:]prevents a threshold between equal values. - Sampling interacts with search.
colsample_bytree,colsample_bylevelandcolsample_bynodeshrink the feature set searched.subsampleshrinks the rows in the histograms. Both reduce the work. min_child_weight. A candidate split is rejected if either side hasHbelow this value. It applies to every method.
Decision guide
- Start with
tree_method="hist"and the defaultmax_bin=256. - If training is slow or memory is tight, lower
max_binor switch to GPU. - If a feature has a sharp, precise cutoff you suspect is being blurred, raise
max_binand check the validation metric. - Use
exactonly for small datasets where you want to rule out binning as a cause of a discrepancy.
Exercise
In the histogram method, a parent node has histogram bin sums G = [4, -2, 6] and the smaller child (rows going left) has G = [1, -2, 3] in the same bins. What are the bin sums for the larger child, and why does this save time?
Show answer
The larger child gets the parent minus the smaller child: [4-1, -2-(-2), 6-3] = [3, 0, 3]. It saves time because XGBoost builds a histogram by scanning rows, and only the smaller child's rows are scanned. Subtraction over a few hundred bins is far cheaper than scanning the larger child's rows.
Exercise
You switch from exact to hist with max_bin=16 and your validation AUC drops slightly. Name two ways to address this, and say which one costs more training time.
Show answer
Raise max_bin (for example to 256 or 512), which gives finer thresholds. Alternatively, switch back to exact if the dataset is small. The exact method costs more training time on large data. Raising max_bin increases histogram size and scan cost only modestly.