Benchmark ONNX conversion#

Example Train and deploy a scikit-learn pipeline converts a simple model. This example takes a similar example but on random data and compares the processing time required by each option to compute predictions.

Training a pipeline#

import numpy
from pandas import DataFrame
from tqdm import tqdm
from sklearn import config_context
from sklearn.datasets import make_regression
from sklearn.ensemble import (
    GradientBoostingRegressor, RandomForestRegressor,
    VotingRegressor)
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from mlprodict.onnxrt import OnnxInference
from onnxruntime import InferenceSession
from skl2onnx import to_onnx
from skl2onnx.tutorial import measure_time


N = 11000
X, y = make_regression(N, n_features=10)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, train_size=0.01)
print("Train shape", X_train.shape)
print("Test shape", X_test.shape)

reg1 = GradientBoostingRegressor(random_state=1)
reg2 = RandomForestRegressor(random_state=1)
reg3 = LinearRegression()
ereg = VotingRegressor([('gb', reg1), ('rf', reg2), ('lr', reg3)])
ereg.fit(X_train, y_train)

Out:

Train shape (110, 10)
Test shape (10890, 10)

VotingRegressor(estimators=[('gb', GradientBoostingRegressor(random_state=1)),
                            ('rf', RandomForestRegressor(random_state=1)),
                            ('lr', LinearRegression())])

Measure the processing time#

We use function skl2onnx.tutorial.measure_time(). The page about assume_finite may be useful if you need to optimize the prediction. We measure the processing time per observation whether or not an observation belongs to a batch or is a single one.

sizes = [(1, 50), (10, 50), (1000, 10), (10000, 5)]

with config_context(assume_finite=True):
    obs = []
    for batch_size, repeat in tqdm(sizes):
        context = {"ereg": ereg, 'X': X_test[:batch_size]}
        mt = measure_time(
            "ereg.predict(X)", context, div_by_number=True,
            number=10, repeat=repeat)
        mt['size'] = context['X'].shape[0]
        mt['mean_obs'] = mt['average'] / mt['size']
        obs.append(mt)

df_skl = DataFrame(obs)
df_skl

Out:

  0%|                                                                                             | 0/4 [00:00<?, ?it/s]
 25%|#####################2                                                               | 1/4 [00:02<00:06,  2.22s/it]
 50%|##########################################5                                          | 2/4 [00:04<00:04,  2.23s/it]
 75%|###############################################################7                     | 3/4 [00:06<00:02,  2.04s/it]
100%|#####################################################################################| 4/4 [00:11<00:00,  3.20s/it]
100%|#####################################################################################| 4/4 [00:11<00:00,  2.81s/it]
average deviation min_exec max_exec repeat number size mean_obs
0 0.004433 0.000531 0.004249 0.007082 50 10 1 0.004433
1 0.004482 0.000598 0.004302 0.008658 50 10 10 0.000448
2 0.018039 0.001172 0.017042 0.021282 10 10 1000 0.000018
3 0.099685 0.004037 0.094844 0.106786 5 10 10000 0.000010


Graphe.

df_skl.set_index('size')[['mean_obs']].plot(
    title="scikit-learn", logx=True, logy=True)
scikit-learn

ONNX runtime#

The same is done with the two ONNX runtime available.

onx = to_onnx(ereg, X_train[:1].astype(numpy.float32),
              target_opset=14)
sess = InferenceSession(onx.SerializeToString())
oinf = OnnxInference(onx, runtime="python_compiled")

obs = []
for batch_size, repeat in tqdm(sizes):

    # scikit-learn
    context = {"ereg": ereg, 'X': X_test[:batch_size].astype(numpy.float32)}
    mt = measure_time(
        "ereg.predict(X)", context, div_by_number=True,
        number=10, repeat=repeat)
    mt['size'] = context['X'].shape[0]
    mt['skl'] = mt['average'] / mt['size']

    # onnxruntime
    context = {"sess": sess, 'X': X_test[:batch_size].astype(numpy.float32)}
    mt2 = measure_time(
        "sess.run(None, {'X': X})[0]", context, div_by_number=True,
        number=10, repeat=repeat)
    mt['ort'] = mt2['average'] / mt['size']

    # mlprodict
    context = {"oinf": oinf, 'X': X_test[:batch_size].astype(numpy.float32)}
    mt2 = measure_time(
        "oinf.run({'X': X})['variable']", context, div_by_number=True,
        number=10, repeat=repeat)
    mt['pyrt'] = mt2['average'] / mt['size']

    # end
    obs.append(mt)


df = DataFrame(obs)
df

Out:

  0%|                                                                                             | 0/4 [00:00<?, ?it/s]
 25%|#####################2                                                               | 1/4 [00:02<00:06,  2.32s/it]
 50%|##########################################5                                          | 2/4 [00:04<00:04,  2.37s/it]
 75%|###############################################################7                     | 3/4 [00:06<00:02,  2.29s/it]
100%|#####################################################################################| 4/4 [00:13<00:00,  4.10s/it]
100%|#####################################################################################| 4/4 [00:13<00:00,  3.45s/it]
average deviation min_exec max_exec repeat number size skl ort pyrt
0 0.004501 0.000592 0.004245 0.007055 50 10 1 0.004501 4.902980e-05 0.000081
1 0.004546 0.000397 0.004371 0.006559 50 10 10 0.000455 1.138424e-05 0.000014
2 0.017997 0.000922 0.017088 0.019845 10 10 1000 0.000018 1.212071e-06 0.000003
3 0.104850 0.003925 0.097119 0.107921 5 10 10000 0.000010 9.453676e-07 0.000002


Graph.

df.set_index('size')[['skl', 'ort', 'pyrt']].plot(
    title="Average prediction time per runtime",
    logx=True, logy=True)
Average prediction time per runtime

ONNX runtimes are much faster than scikit-learn to predict one observation. scikit-learn is optimized for training, for batch prediction. That explains why scikit-learn and ONNX runtimes seem to converge for big batches. They use similar implementation, parallelization and languages (C++, openmp).

Total running time of the script: ( 0 minutes 32.657 seconds)

Gallery generated by Sphinx-Gallery