Skip to main content

RepLeafGBM

CI Coverage PyPI License: MIT

Representation-enhanced Leaf Gradient Boosting Machine — gradient boosting that routes on raw features and predicts with small linear models over learned representations inside each leaf.

RepLeafGBM is not a neural network inside a tree, nor a tree over embeddings. It is a boosted ensemble of raw-feature routers with representation-conditioned local predictors.

Paper

📄 RepLeafGBM: Gradient Boosting with Raw-Feature Routing and Representation-Conditioned Leaves — Masaya Kawamata (PDF, LaTeX source).

A technical report covering the method, the frozen-encoder correctness argument, and an honest empirical study: a fair same-HPO-budget leaderboard on the Grinsztajn tabular suites (RepLeafGBM is competitive mid-pack), plus niche studies where the representation-conditioned leaf and scale-consistent robust multi-output objectives provide a defensible edge. All numbers are reproducible with the benchmark and experiment harness in this repository.

Preprint draft — not yet peer-reviewed or posted to an external repository.

Project status & development notes

  • GPU acceleration is an active work in progress. device="cuda" turns on the GPU path in one switch (GPU histograms, split scan, and device leaf fit, plus GPU pretraining for torch_* encoders; docs/cuda.md, ADR 0007) — it is a macro over split_backend="cuda", which remains available directly. Performance is still being optimized and is validated only on a limited set of GPUs (e.g. NVIDIA T4). For most CPU workloads the Rust backend (repleafgbm-native) is the faster, more mature path — treat GPU speed as evolving, not final.
  • Built with Claude Code. RepLeafGBM's implementation and architecture were developed with heavy use of Claude Code (both coding and architecture design).

How it works

GBDTs dominate tabular ML because axis-aligned splits on raw features handle discontinuities, interactions, and messy data extremely well. Tabular deep learning has shown that numerical feature embeddings (PLR, periodic) capture smooth nonlinear structure that constant-leaf trees approximate only with many splits. RepLeafGBM combines both with a deliberately asymmetric design:

  • Routing — every split is on a raw feature, exactly like a normal GBDT. Trees find the discontinuous boundaries and partition the space into local regions.
  • Leaf output — each leaf holds a small ridge-regularized linear model over a learned representation z_theta(x) instead of a constant. The embedding does the smooth interpolation within each region.
f_t(x) = b + w^T z_theta(x)            # one tree: route on x_raw, predict in the leaf
F_T(x) = F_0(x) + sum_t eta * f_t(x)   # boosted sum

Three properties fall out of this design:

  • Embeddings are never used for splitting → interpretable raw-feature routing, no split-histogram blow-up, no curse of dimensionality in the search.
  • The encoder is frozen during boosting (v0), preserving the stage-wise additive structure of gradient boosting.
  • Leaf models fall back to a constant when a leaf is too small, so the model degrades gracefully toward a classic GBDT.

See docs/math.md for the full formulation and leaf fitting.

Installation

pip install repleafgbm                 # core (numpy, pandas, scikit-learn)
pip install repleafgbm-native          # + optional Rust split/leaf kernels (auto-detected)
pip install "repleafgbm[external]"     # + LightGBM external_model / router_extraction
pip install "repleafgbm[bench]"        # + XGBoost / CatBoost for benchmarks
pip install "repleafgbm[torch]"        # + learned torch encoders

repleafgbm ships type information (PEP 561). repleafgbm-native is a separate package of prebuilt Linux/macOS/Windows wheels; once installed the Rust backend is selected automatically (split_backend="auto"), giving ~5.8x faster constant-leaf training while staying parity-tested against the NumPy reference.

Quickstart

import numpy as np
from repleafgbm import RepLeafRegressor
from repleafgbm.data import RepLeafDataset

rng = np.random.default_rng(0)
X = rng.normal(size=(500, 4))
y = np.where(X[:, 0] > 0, 3.0, -2.0) + 2.0 * X[:, 1] + rng.normal(0, 0.1, 500)

model = RepLeafRegressor(
    n_estimators=50,
    learning_rate=0.1,
    num_leaves=8,
    leaf_model="embedded_linear",   # or "constant", "raw_linear"
    encoder="plr",                  # or "identity", "periodic", "cross"
    max_leaf_emb_dim=16,
    random_state=42,
)
model.fit(X, y)
pred = model.predict(X)

model.save_model("repleaf_model")
loaded = RepLeafRegressor.load_model("repleaf_model")

pandas DataFrames with categorical columns are supported through the dataset API:

train_data = RepLeafDataset(df_train, y_train, categorical_features=["city"])
model.fit(train_data, eval_set=[RepLeafDataset(df_valid, y_valid,
                                               metadata=train_data.metadata)])

MatGBM: leaf-only features and fixed expert blocks

MatGBM is an experimental composition for one fitted GBM: raw columns route the trees while selected numerical columns are available only inside leaves. leaf_only_features excludes those columns from routing, feature sampling, and importance calculations.

Pass named frozen spaces through leaf_experts; each block specifies an encoder, optional columns, and optional encoder_params. With leaf_model="embedded_linear", each leaf with enough rows fits one ridge model over the fixed, concatenated blocks (smaller leaves stay constant). The per-leaf block selection leaf_model="select" of 1.13.0 was removed in 1.14.0 because fixed blocks beat it (ADR 0012).

examples/matgbm_leaf_experts.py runs a small regression and binary example with a fold-safe target_encoding block and a teacher-score block, comparing constant leaves with one and two fixed blocks on holdouts. These APIs and the experimental target_encoding encoder may change before stabilization; see the MatGBM guide for scope and limitations.

API overview

The public API is scikit-learn compatible (fit / predict / predict_proba, get_params / set_params).

Main classes

Class Use
RepLeafRegressor Regression (squared error, plus huber / quantile / poisson); multi-output via vector leaves.
RepLeafClassifier Binary (logistic) and multiclass (softmax) — chosen automatically from the labels. Has predict_proba.
RepLeafDataset pandas / categorical inputs, eval sets, and embedding caching.

Key parameters (constructor; same for both estimators)

Parameter Default Meaning
n_estimators 100 Boosting rounds (trees).
learning_rate 0.1 Shrinkage per round.
num_leaves 31 Max leaves per tree (leaf-wise growth).
min_samples_leaf 20 Minimum rows per leaf.
leaf_model "embedded_linear" Leaf predictor (see below).
encoder "identity" Representation z_theta(x) (see below); this unchanged default is ignored when leaf_experts supplies the bundle.
leaf_only_features None Numerical columns hidden from tree splits and exposed only to leaf encoders.
leaf_experts None Named encoder/column blocks; mutually exclusive with a non-default encoder or top-level encoder_params.
max_leaf_emb_dim 64 Resolved embedding width when reduction is enabled.
leaf_reduction "random_projection" Wide-embedding policy: compatibility projection, learned "target_correlation", or "none".
subsample / subsample_freq 1.0 / 0 Row fraction and refresh interval (0 disables).
colsample_bytree 1.0 Raw split-feature fraction sampled per tree.
l2_leaf 1.0 Ridge penalty for leaf models.
early_stopping_rounds None Stop when an eval_set metric plateaus.
random_state 42 Seed; same seed ⇒ same model.

leaf_model

Value Leaf predicts
"constant" A constant (classic GBDT leaf).
"embedded_linear" Ridge linear model over z_theta(x) (default).
"raw_linear" Ridge linear model over the raw features.
"adaptive" Per-leaf weighted-LOO gate: keeps the embedded_linear leaf only where it beats a constant, else falls back.

encoder

Value Representation
"identity" Standardized raw features. Evidence-backed default on real tabular data.
"plr" Piecewise-linear + linear term.
"periodic" Frozen sinusoidal (PBLD-style) features.
"cross" Residual-correlated pairwise products (interactions).
"target_encoding" Fold-safe scalar-target means over exact, rounded, and quantile-bin numerical keys; direct and leaf_experts training values are OOF.
"torch_periodic" / "torch_plr" / "torch_periodic_plr" / "torch_mlp" Learned encoders ([torch] extra; supervised-pretrained on the initial residual then frozen — torch is needed only at fit time, not at predict).

The experimental space encoders of 1.13.0 ("pca", "quantile", "spline", "rff", "row_stats", "prototype") were removed in 1.14.0 because none beat constant leaves in the S6E10 wave-4 screen (ADR 0013).

API stability follows Semantic Versioning from 1.0.0; exactly what is covered vs. experimental is in docs/adr/0003-api-stability.md.

Features

Area Support
Backends NumPy reference (histogram split search, leaf-wise growth) + optional Rust kernels (repleafgbm-native, ~5.8x faster, parity-tested).
Tasks Regression, binary & multiclass classification, multi-output regression (vector leaves).
Objectives Squared error, huber, quantile, poisson, logistic, softmax (parameterized instances like Quantile(alpha=0.9) too).
Leaf models constant, embedded_linear, raw_linear, adaptive.
Encoders identity, plr, periodic, cross, fold-safe target_encoding, learned torch_*.
Training Early stopping, eval metrics (rmse, mae, logloss, multi_logloss, auc, accuracy, or a custom callable via make_metric), feature importances, sample weights, class_weight, label_smoothing.
Data RepLeafDataset with pandas/categorical, leaf-only numerical columns, and embedding caching.
Persistence Directory-based save_model / load_model with schema validation and a human-readable summary().
External LightGBM / XGBoost / CatBoost as base models, OOF + stacking utilities, and RouterExtraction{Regressor,Classifier} ([external] extra).

Full implemented-vs-planned status (and what is intentionally not done yet — encoder updates during boosting, GPU / distributed training) is in docs/roadmap.md.

Benchmarks

Fair-budget Grinsztajn leaderboard (10 seeds). Every model family is tuned by Optuna TPE under an identical budget (50 trials per dataset, 70/15/15 split, 10 seeds) on the four Grinsztajn suites; all models see the same ordinal-encoded matrix. RepLeafGBM's mean rank among the five tuned families (lower is better):

Grinsztajn suite (datasets) RepLeafGBM mean rank (of 5) Friedman p
Numerical regression (19) 3.00 (3rd) 2.2e-3
Numerical classification (16) 3.81 (4th) 4.3e-4
Categorical regression (17) 3.00 (3rd) 0.025
Categorical classification (7) 3.71 0.438 (flat)

Honest summary: mid-pack overall — a clean third on both regression suites (ahead of XGBoost and HistGB), fourth–fifth on classification (consistent with the documented binary-Hessian limitation), never the leader, and never significantly and practically worse than the best baseline. Full reports: experiments/results/leaderboard-grinsztajn_*-10seed.md; consolidated verdict: experiments/results/2026-07-04-grinsztajn-10seed-consolidated-verdict.md.

The two snapshots below are older development-tracking benchmarks (unequal tuning; kept for breadth); they are not performance claims.

Real data — OpenML mean rank across 9 standard datasets, 3 seeds, a 60/20/20 split with early stopping. Rank is among all 11 models in the suite (lower is better); primary metric is RMSE (regression) / logloss (classification):

Model Regression (4) Classification (5)
LightGBM 2.50 5.00
CatBoost 3.00 3.40
XGBoost 4.25 6.40
RepLeaf (adaptive) 4.50 4.20
RepLeaf (constant) 4.50 7.60
RepLeaf (adaptive_insample) 5.00 5.40
RepLeaf (embedded_linear) 5.25 4.80
RepLeaf (embedded + plr) 8.50 6.80
HistGradientBoosting 8.50 9.80
RepLeaf (embedded + torch_mlp) 9.75 5.60
RepLeaf (embedded + torch_periodic_plr) 10.25 7.00

The tuned external GBMs lead on real tabular data. Among the RepLeaf arms the adaptive leaf — a per-leaf weighted-LOO gate between a constant and an embedded-linear leaf — is the most robust (2nd overall on classification, behind only CatBoost; never worse than constant). Its leverage-free ablation adaptive_insample ranks below it, and higher-dimensional representations (plr, learned torch_*) do not help here: on real data a constant or adaptively-gated leaf is the honest choice.

Synthetic signal — regression RMSE (mean of 3 seeds, n=10k, 20 features). The leaf embeddings pay off on smoother structure: an embedded-linear leaf over standardized raw features (identity) edges out a constant leaf and LightGBM (CatBoost still leads):

Model RMSE
CatBoost 0.395
RepLeaf (embedded_linear, identity) 0.407
HistGradientBoosting 0.411
RepLeaf (constant) 0.412
LightGBM 0.413

The higher-dimensional plr / torch_* encoders are random-projected at the default max_leaf_emb_dim=64 on this 20-feature signal and don't gain over identity (raise the cap to fit them directly). Separately, refitting LightGBM's own routes with representation-conditioned leaves (router_extraction) improves it by 2–12% RMSE.

Reproduce with python benchmarks/openml_suite.py --learned-encoders and python benchmarks/benchmark_synthetic_regression.py; full real-data numbers in experiments/results/openml_benchmark.md.

Development

git clone https://github.com/Matapanino/repleafgbm.git && cd repleafgbm
pip install -e ".[dev]"
bash scripts/check.sh               # lint + tests + all examples
python -m pytest tests/ -q          # PYTHONPATH=src if not installed
python examples/regression_basic.py

See CONTRIBUTING.md for the contribution workflow.

Documentation

License

MIT

Metadata

Release files for repleafgbm 1.14.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for repleafgbm 1.14.0
File Size Uploaded Provenance Actions
repleafgbm-1.14.0.tar.gz 252.9 kB With provenance Details for repleafgbm-1.14.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for repleafgbm 1.14.0
File Interpreter ABI Platform Actions
repleafgbm-1.14.0-py3-none-any.whl Python 3 none any Details for repleafgbm-1.14.0-py3-none-any.whl

Total release size: 427.5 kB

Release files / repleafgbm-1.14.0.tar.gz

Download URL repleafgbm-1.14.0.tar.gz
Size 252.9 kB
Tags Source
SHA-256 checksum
How to use checksums
141889d148e6a1128fcd14dd79ec7761dc4749131630085891b096f13603f291
BLAKE2b-256 checksum
How to use checksums
84b6d3dbe9793b033c18d1f8ea1a7af34619b3b243d0dfcb79702aee5f46b097
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.

Transparency log

Release files / repleafgbm-1.14.0-py3-none-any.whl

Download URL repleafgbm-1.14.0-py3-none-any.whl
Size 174.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
167039e290435a85d1cb2a74ef7306cbe5f116da8444a0ad713e25b09685a8de
BLAKE2b-256 checksum
How to use checksums
59497265400be74669eae22ff24ef2760b57a9655034165c312b0e05745737d5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.

Transparency log

Security for repleafgbm 1.14.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for repleafgbm-1.14.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page