Sub topic 18
Scaling up: larger data and GPU training
This chapter assumes you can train an XGBClassifier or a native Booster, and that you know the tree_method options from the split-finding chapter. It covers what changes when the data gets large, how to move training to a GPU, and the failure modes you are likely to hit.
Where training time goes
Training cost grows with three things: the number of rows, the number of features, and the number of boosting rounds times tree size. In each round XGBoost computes gradients and hessians for every row. It then builds one tree by evaluating candidate splits for every feature at every node.
Split evaluation dominates. The exact method sorts or scans every distinct feature value. The histogram method (tree_method="hist") first bins each feature into at most max_bin buckets. It then accumulates gradient and hessian sums per bucket, so a split search scans buckets, not rows.
In current XGBoost releases hist is the default tree method. If you set tree_method="exact" on a large dataset, switching back to hist is usually the first speedup available.
Tuning the histogram method
Three settings control the cost of hist:
| Setting | Effect | Trade-off |
|---|---|---|
| `max_bin` (default 256) | Number of buckets per feature | Fewer bins train faster and use less memory but give coarser split thresholds |
| `max_depth` | Tree depth | Deeper trees cost more per round and overfit more easily |
| `subsample`, `colsample_bytree` | Rows and columns sampled per tree | Lower values cut cost per round and also regularize |
Lowering max_bin to 64 or 128 rarely hurts accuracy on noisy tabular data, and it is worth testing. Raising it above 256 helps only when a feature has many distinct, informative values.
Reducing memory with QuantileDMatrix
A regular DMatrix keeps the raw feature values. For hist training, XGBoost only needs the binned values. QuantileDMatrix builds the bins directly from your input and skips storing a full second copy, which lowers peak memory.
Validation data must use the same bin boundaries as the training data. Pass the training matrix as ref.
import time
import numpy as np
import xgboost as xgb
from sklearn.datasets import make_classification
X, y = make_classification(
n_samples=200_000, n_features=50, n_informative=20, random_state=0
)
X = X.astype(np.float32) # float32 halves memory compared with float64
split = 160_000
dtrain = xgb.QuantileDMatrix(X[:split], label=y[:split], max_bin=256)
dval = xgb.QuantileDMatrix(X[split:], label=y[split:], ref=dtrain)
for device in ["cpu", "cuda"]:
params = {
"objective": "binary:logistic",
"eval_metric": "logloss",
"tree_method": "hist",
"device": device,
"eta": 0.1,
"max_depth": 6,
"max_bin": 256,
}
start = time.perf_counter()
try:
booster = xgb.train(
params,
dtrain,
num_boost_round=200,
evals=[(dval, "val")],
early_stopping_rounds=20,
verbose_eval=False,
)
except xgb.core.XGBoostError as err:
print(f"{device}: unavailable ({str(err).splitlines()[0]})")
continue
elapsed = time.perf_counter() - start
print(f"{device}: {elapsed:.1f}s, best iteration {booster.best_iteration}")On a machine without a CUDA GPU, the cuda run raises an XGBoostError. The script catches it and prints a message, so the comparison still finishes for the CPU run.
Training on a GPU
Since XGBoost 2.0, you select the GPU with the device parameter. Older tutorials use tree_method="gpu_hist" or gpu_id. Those settings are deprecated, and you should not copy them into new code.
from xgboost import XGBClassifier
model = XGBClassifier(
n_estimators=500,
learning_rate=0.1,
max_depth=6,
tree_method="hist",
device="cuda", # "cuda:1" selects the second GPU
)The GPU builds histograms in parallel across thousands of threads. The speedup is largest when you have many rows (hundreds of thousands or more), many features, and deep trees. For small datasets, the cost of copying data to the GPU and launching kernels can make it slower than the CPU.
What stays the same
The algorithm is the same: the same objective, the same regularization, and the same split gain formula. The same parameters apply, including eta, lambda, gamma, and min_child_weight. Early stopping, xgb.cv, importance, and model saving all work as before. Results can differ slightly between CPU and GPU because floating-point sums are accumulated in a different order, so do not expect bit-identical models.
What differs
- GPU memory is the limit. A dataset that fits in system RAM may not fit in a GPU with 16 GB.
- Prediction also runs on the device. If you train with
device="cuda"and predict on a CPU array, XGBoost may warn about a device mismatch and move the data. Usebooster.inplace_predict(X)with a matching array type to avoid extra copies. - Not every objective and metric has a GPU implementation in every version. If a metric silently falls back to the CPU, per-round evaluation can become the bottleneck.
Data that does not fit in memory
When even binned data is too large, you have three options.
- Reduce the data. Use
float32, drop unused columns, and train on a row sample. Check whether more rows still improve validation scores. Often they stop helping long before you run out of memory. - External memory. XGBoost can read data in batches from disk through a custom data iterator. Training is slower because of disk reads, but memory use stays bounded. This is available for both CPU and GPU training in recent versions, and its details change between releases, so read the documentation for your installed version.
- Distributed training. XGBoost has Dask and Spark integrations that split rows across workers. Each worker builds local histograms and the workers combine them. Use this when a single machine cannot hold the data or finish in acceptable time.
Common errors and gotchas
- Using
gpu_histfrom old examples. In XGBoost 2.x this is deprecated. Usetree_method="hist"withdevice="cuda". - Benchmarking on tiny data. A GPU speedup claim means nothing on 5,000 rows. Time a realistic dataset, and exclude one-off startup cost by timing a warm second run.
- Out-of-memory errors on the GPU. Lower
max_depth, lowermax_bin, useQuantileDMatrix, or train on fewer rows. Memory use grows with the number of features and bins. - Forgetting
reffor validation matrices. A validationQuantileDMatrixbuilt withoutref=dtrainuses its own bins, which can give inconsistent evaluation. - Tuning only for speed. A faster setup with
max_bin=16can lose accuracy. Always compare validation scores, not only time.
Summary of settings
| Goal | Setting |
|---|---|
| Fast default on CPU | `tree_method="hist"` |
| Use an NVIDIA GPU | `device="cuda"` |
| Lower memory | `QuantileDMatrix`, `float32`, smaller `max_bin` |
| Consistent validation bins | `ref=dtrain` on the validation matrix |
| Data larger than memory | External memory or Dask/Spark |
Exercise
You trained with device="cuda" and tree_method="hist", but on a 10,000-row dataset the GPU run is slower than the CPU run. Give one reason and one change that you would test.
Show answer
With so few rows, the fixed costs of copying data to the GPU and launching kernels outweigh the parallel speedup, so the CPU can win. Test the CPU (device="cpu") for this dataset, or benchmark again on a larger dataset or with more features and deeper trees, where the GPU's parallel histogram building pays off.
Exercise
Why must a validation QuantileDMatrix be created with ref=dtrain, and what could go wrong if it is not?
Show answer
The ref argument makes the validation matrix reuse the training matrix's bin boundaries. Without it, the validation data is binned with its own quantiles, so the same feature value can land in a different bin than during training. Evaluation and early stopping then use inconsistent data, and the validation scores can be misleading.