Benchmark Random Forests, Tree Ensemble#

The following script benchmarks different libraries implementing random forests and boosting trees. This benchmark can be replicated by installing the following packages:

python -m virtualenv env
cd env
pip install -i https://test.pypi.org/simple/ ort-nightly
pip install git+https://github.com/microsoft/onnxconverter-common.git@jenkins
pip install git+https://https://github.com/xadupre/sklearn-onnx.git@jenkins
pip install mlprodict matplotlib scikit-learn pandas threadpoolctl
pip install mlprodict lightgbm xgboost jinja2

Import#

import os
import pickle
from pprint import pprint
import numpy
import pandas
import matplotlib.pyplot as plt
from xgboost import XGBClassifier
from lightgbm import LGBMClassifier
from onnxruntime import InferenceSession
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
from skl2onnx import to_onnx
from mlprodict.onnx_conv import register_converters
from mlprodict.onnxrt.validate.validate_helper import measure_time
from mlprodict.onnxrt import OnnxInference

Registers new converters for sklearn-onnx.

register_converters()
[<class 'lightgbm.sklearn.LGBMClassifier'>, <class 'lightgbm.sklearn.LGBMRegressor'>, <class 'lightgbm.basic.Booster'>, <class 'mlprodict.onnx_conv.operator_converters.parse_lightgbm.WrappedLightGbmBooster'>, <class 'mlprodict.onnx_conv.operator_converters.parse_lightgbm.WrappedLightGbmBoosterClassifier'>, <class 'xgboost.sklearn.XGBClassifier'>, <class 'xgboost.sklearn.XGBRegressor'>, <class 'mlinsights.mlmodel.transfer_transformer.TransferTransformer'>, <class 'skl2onnx.sklapi.woe_transformer.WOETransformer'>, <class 'mlprodict.onnx_conv.scorers.register.CustomScorerTransform'>]

Problem#

max_depth = 7
n_classes = 20
n_estimators = 500
n_features = 100
REPEAT = 3
NUMBER = 1
train, test = 1000, 10000

print('dataset')
X_, y_ = make_classification(n_samples=train + test, n_features=n_features,
                             n_classes=n_classes, n_informative=n_features - 3)
X_ = X_.astype(numpy.float32)
y_ = y_.astype(numpy.int64)
X_train, X_test = X_[:train], X_[train:]
y_train, y_test = y_[:train], y_[train:]

compilation = []


def train_cache(model, X_train, y_train, max_depth, n_estimators, n_classes):
    name = "cache-{}-N{}-f{}-d{}-e{}-cl{}.pkl".format(
        model.__class__.__name__, X_train.shape[0], X_train.shape[1],
        max_depth, n_estimators, n_classes)
    if os.path.exists(name):
        with open(name, 'rb') as f:
            return pickle.load(f)
    else:
        model.fit(X_train, y_train)
        with open(name, 'wb') as f:
            pickle.dump(model, f)
        return model
dataset

RandomForestClassifier#

rf = RandomForestClassifier(n_estimators=n_estimators, max_depth=max_depth)
print('train')
rf = train_cache(rf, X_train, y_train, max_depth, n_estimators, n_classes)

res = measure_time(rf.predict_proba, X_test[:10],
                   repeat=REPEAT, number=NUMBER,
                   div_by_number=True, first_run=True)
res['model'], res['runtime'] = rf.__class__.__name__, 'INNER'
pprint(res)
train
{'average': 0.18407272407785058,
 'context_size': 64,
 'deviation': 0.0005815684805466398,
 'max_exec': 0.18489190912805498,
 'min_exec': 0.18359961197711527,
 'model': 'RandomForestClassifier',
 'number': 1,
 'repeat': 3,
 'runtime': 'INNER',
 'ttime': 0.5522181722335517}

ONNX#

def measure_onnx_runtime(model, xt, repeat=REPEAT, number=NUMBER,
                         verbose=True):
    if verbose:
        print(model.__class__.__name__)

    res = measure_time(model.predict_proba, xt,
                       repeat=repeat, number=number,
                       div_by_number=True, first_run=True)
    res['model'], res['runtime'] = model.__class__.__name__, 'INNER'
    res['N'] = X_test.shape[0]
    res["max_depth"] = max_depth
    res["n_estimators"] = n_estimators
    res["n_features"] = n_features
    if verbose:
        pprint(res)
    yield res

    onx = to_onnx(model, X_train[:1], options={id(model): {'zipmap': False}})

    oinf = OnnxInference(onx)
    res = measure_time(lambda x: oinf.run({'X': x}), xt,
                       repeat=repeat, number=number,
                       div_by_number=True, first_run=True)
    res['model'], res['runtime'] = model.__class__.__name__, 'NPY/C++'
    res['N'] = X_test.shape[0]
    res['size'] = len(onx.SerializeToString())
    res["max_depth"] = max_depth
    res["n_estimators"] = n_estimators
    res["n_features"] = n_features
    if verbose:
        pprint(res)
    yield res

    sess = InferenceSession(onx.SerializeToString())
    res = measure_time(lambda x: sess.run(None, {'X': x}), xt,
                       repeat=repeat, number=number,
                       div_by_number=True, first_run=True)
    res['model'], res['runtime'] = model.__class__.__name__, 'ORT'
    res['N'] = X_test.shape[0]
    res['size'] = len(onx.SerializeToString())
    res["max_depth"] = max_depth
    res["n_estimators"] = n_estimators
    res["n_features"] = n_features
    if verbose:
        pprint(res)
    yield res


compilation.extend(list(measure_onnx_runtime(rf, X_test)))
RandomForestClassifier
{'N': 10000,
 'average': 2.9968321276828647,
 'context_size': 64,
 'deviation': 0.0017181705505757625,
 'max_depth': 7,
 'max_exec': 2.999245815910399,
 'min_exec': 2.9953829059377313,
 'model': 'RandomForestClassifier',
 'n_estimators': 500,
 'n_features': 100,
 'number': 1,
 'repeat': 3,
 'runtime': 'INNER',
 'ttime': 8.990496383048594}
{'N': 10000,
 'average': 0.15890872742359838,
 'context_size': 64,
 'deviation': 0.0021684302086680597,
 'max_depth': 7,
 'max_exec': 0.16161397914402187,
 'min_exec': 0.15630536410026252,
 'model': 'RandomForestClassifier',
 'n_estimators': 500,
 'n_features': 100,
 'number': 1,
 'repeat': 3,
 'runtime': 'NPY/C++',
 'size': 7028998,
 'ttime': 0.4767261822707951}
{'N': 10000,
 'average': 0.27081055698605877,
 'context_size': 64,
 'deviation': 0.00015215165026495945,
 'max_depth': 7,
 'max_exec': 0.27102003805339336,
 'min_exec': 0.2706632318440825,
 'model': 'RandomForestClassifier',
 'n_estimators': 500,
 'n_features': 100,
 'number': 1,
 'repeat': 3,
 'runtime': 'ORT',
 'size': 7028998,
 'ttime': 0.8124316709581763}

HistGradientBoostingClassifier#

hist = HistGradientBoostingClassifier(
    max_iter=n_estimators, max_depth=max_depth)
print('train')
hist = train_cache(hist, X_train, y_train, max_depth, n_estimators, n_classes)

compilation.extend(list(measure_onnx_runtime(hist, X_test)))
train
HistGradientBoostingClassifier
{'N': 10000,
 'average': 3.7871574182839445,
 'context_size': 64,
 'deviation': 0.023261162347252236,
 'max_depth': 7,
 'max_exec': 3.8194894378539175,
 'min_exec': 3.765737562905997,
 'model': 'HistGradientBoostingClassifier',
 'n_estimators': 500,
 'n_features': 100,
 'number': 1,
 'repeat': 3,
 'runtime': 'INNER',
 'ttime': 11.361472254851833}
{'N': 10000,
 'average': 2.3727021160690733,
 'context_size': 64,
 'deviation': 0.021332488917486656,
 'max_depth': 7,
 'max_exec': 2.398467106046155,
 'min_exec': 2.346227837027982,
 'model': 'HistGradientBoostingClassifier',
 'n_estimators': 500,
 'n_features': 100,
 'number': 1,
 'repeat': 3,
 'runtime': 'NPY/C++',
 'size': 4283223,
 'ttime': 7.11810634820722}
{'N': 10000,
 'average': 3.611440731367717,
 'context_size': 64,
 'deviation': 0.0013234833996178673,
 'max_depth': 7,
 'max_exec': 3.6131825300399214,
 'min_exec': 3.609976523090154,
 'model': 'HistGradientBoostingClassifier',
 'n_estimators': 500,
 'n_features': 100,
 'number': 1,
 'repeat': 3,
 'runtime': 'ORT',
 'size': 4283223,
 'ttime': 10.834322194103152}

LightGBM#

lgb = LGBMClassifier(n_estimators=n_estimators,
                     max_depth=max_depth, pred_early_stop=False)
print('train')
lgb = train_cache(lgb, X_train, y_train, max_depth, n_estimators, n_classes)

compilation.extend(list(measure_onnx_runtime(lgb, X_test)))
train
LGBMClassifier
{'N': 10000,
 'average': 4.221905080989624,
 'context_size': 64,
 'deviation': 0.13572506375806903,
 'max_depth': 7,
 'max_exec': 4.394219246925786,
 'min_exec': 4.062516784993932,
 'model': 'LGBMClassifier',
 'n_estimators': 500,
 'n_features': 100,
 'number': 1,
 'repeat': 3,
 'runtime': 'INNER',
 'ttime': 12.665715242968872}
{'N': 10000,
 'average': 2.3883680240251124,
 'context_size': 64,
 'deviation': 0.005805167938165284,
 'max_depth': 7,
 'max_exec': 2.3954531480558217,
 'min_exec': 2.3812337040435523,
 'model': 'LGBMClassifier',
 'n_estimators': 500,
 'n_features': 100,
 'number': 1,
 'repeat': 3,
 'runtime': 'NPY/C++',
 'size': 4514863,
 'ttime': 7.165104072075337}
{'N': 10000,
 'average': 3.6462705583932498,
 'context_size': 64,
 'deviation': 0.0017201400604464664,
 'max_depth': 7,
 'max_exec': 3.648703203070909,
 'min_exec': 3.6450526108965278,
 'model': 'LGBMClassifier',
 'n_estimators': 500,
 'n_features': 100,
 'number': 1,
 'repeat': 3,
 'runtime': 'ORT',
 'size': 4514863,
 'ttime': 10.93881167517975}

XGBoost#

xgb = XGBClassifier(n_estimators=n_estimators, max_depth=max_depth)
print('train')
xgb = train_cache(xgb, X_train, y_train, max_depth, n_estimators, n_classes)

compilation.extend(list(measure_onnx_runtime(xgb, X_test)))
train
XGBClassifier
{'N': 10000,
 'average': 0.20234788799037537,
 'context_size': 64,
 'deviation': 0.0025782526717687258,
 'max_depth': 7,
 'max_exec': 0.2059927200898528,
 'min_exec': 0.20043898792937398,
 'model': 'XGBClassifier',
 'n_estimators': 500,
 'n_features': 100,
 'number': 1,
 'repeat': 3,
 'runtime': 'INNER',
 'ttime': 0.6070436639711261}
{'N': 10000,
 'average': 2.3416258946526796,
 'context_size': 64,
 'deviation': 0.024044155536168062,
 'max_depth': 7,
 'max_exec': 2.375424745026976,
 'min_exec': 2.321499953046441,
 'model': 'XGBClassifier',
 'n_estimators': 500,
 'n_features': 100,
 'number': 1,
 'repeat': 3,
 'runtime': 'NPY/C++',
 'size': 1527918,
 'ttime': 7.024877683958039}
{'N': 10000,
 'average': 3.622338138986379,
 'context_size': 64,
 'deviation': 0.0017603712816314317,
 'max_depth': 7,
 'max_exec': 3.6246443919371814,
 'min_exec': 3.6203730651177466,
 'model': 'XGBClassifier',
 'n_estimators': 500,
 'n_features': 100,
 'number': 1,
 'repeat': 3,
 'runtime': 'ORT',
 'size': 1527918,
 'ttime': 10.867014416959137}

Summary#

All data

name = 'plot_time_tree_ensemble'
df = pandas.DataFrame(compilation)
df.to_csv(f'{name}.csv', index=False)
df.to_excel(f'{name}.xlsx', index=False)
df
average deviation min_exec max_exec repeat number ttime context_size model runtime N max_depth n_estimators n_features size
0 2.996832 0.001718 2.995383 2.999246 3 1 8.990496 64 RandomForestClassifier INNER 10000 7 500 100 NaN
1 0.158909 0.002168 0.156305 0.161614 3 1 0.476726 64 RandomForestClassifier NPY/C++ 10000 7 500 100 7028998.0
2 0.270811 0.000152 0.270663 0.271020 3 1 0.812432 64 RandomForestClassifier ORT 10000 7 500 100 7028998.0
3 3.787157 0.023261 3.765738 3.819489 3 1 11.361472 64 HistGradientBoostingClassifier INNER 10000 7 500 100 NaN
4 2.372702 0.021332 2.346228 2.398467 3 1 7.118106 64 HistGradientBoostingClassifier NPY/C++ 10000 7 500 100 4283223.0
5 3.611441 0.001323 3.609977 3.613183 3 1 10.834322 64 HistGradientBoostingClassifier ORT 10000 7 500 100 4283223.0
6 4.221905 0.135725 4.062517 4.394219 3 1 12.665715 64 LGBMClassifier INNER 10000 7 500 100 NaN
7 2.388368 0.005805 2.381234 2.395453 3 1 7.165104 64 LGBMClassifier NPY/C++ 10000 7 500 100 4514863.0
8 3.646271 0.001720 3.645053 3.648703 3 1 10.938812 64 LGBMClassifier ORT 10000 7 500 100 4514863.0
9 0.202348 0.002578 0.200439 0.205993 3 1 0.607044 64 XGBClassifier INNER 10000 7 500 100 NaN
10 2.341626 0.024044 2.321500 2.375425 3 1 7.024878 64 XGBClassifier NPY/C++ 10000 7 500 100 1527918.0
11 3.622338 0.001760 3.620373 3.624644 3 1 10.867014 64 XGBClassifier ORT 10000 7 500 100 1527918.0


Time per model and runtime.

piv = df.pivot("model", "runtime", "average")
piv
somewhere/workspace/mlprodict/mlprodict_UT_39_std/_doc/examples/plot_time_tree_ensemble.py:201: FutureWarning: In a future version of pandas all arguments of DataFrame.pivot will be keyword-only.
  piv = df.pivot("model", "runtime", "average")
runtime INNER NPY/C++ ORT
model
HistGradientBoostingClassifier 3.787157 2.372702 3.611441
LGBMClassifier 4.221905 2.388368 3.646271
RandomForestClassifier 2.996832 0.158909 0.270811
XGBClassifier 0.202348 2.341626 3.622338


Graphs.

ax = piv.T.plot(kind="bar")
ax.set_title("Computation time ratio for %d observations and %d features\n"
             "lower is better for onnx runtimes" % X_test.shape)
plt.savefig(f'{name}.png')
Computation time ratio for 10000 observations and 100 features lower is better for onnx runtimes

Available optimisation on this machine:

from mlprodict.testing.experimental_c_impl.experimental_c import code_optimisation
print(code_optimisation())

plt.show()
AVX-omp=8

Total running time of the script: ( 4 minutes 13.908 seconds)

Gallery generated by Sphinx-Gallery