Compares implementations of ReduceMean#

This example compares the numpy for the operator ReduceMean to onnxruntime implementation. If available, tensorflow and pytorch are included as well.

Available optimisation#

The code shows which parallelisation optimisation could be used, AVX or SSE and the number of available processors.

import numpy
import pandas
import matplotlib.pyplot as plt
from onnxruntime import InferenceSession
from skl2onnx.common.data_types import FloatTensorType
from skl2onnx.algebra.onnx_ops import OnnxReduceMean
from cpyquickhelper.numbers import measure_time
from tqdm import tqdm
from mlprodict.testing.experimental_c_impl.experimental_c import code_optimisation
print(code_optimisation())

Out:

AVX-omp=8

ReduceMean implementations#

try:
    from tensorflow.math import reduce_mean as tf_reduce_mean
    from tensorflow import convert_to_tensor
except ImportError:
    tf_reduce_mean = None
try:
    from torch import mean as torch_mean, from_numpy
except ImportError:
    torch_mean = None


def build_ort_reducemean(axes, op_version=14):  # opset=13, 14, ...
    node = OnnxReduceMean('x', axes=axes, op_version=op_version,
                          output_names=['z'])
    onx = node.to_onnx(inputs=[('x', FloatTensorType())],
                       target_opset=op_version)
    sess = InferenceSession(onx.SerializeToString())
    return lambda x, y: sess.run(None, {'x': x})


def loop_fct(fct, xs, ys):
    for x, y in zip(xs, ys):
        fct(x, y)


def benchmark_op(axes, repeat=2, number=5, name="ReduceMean",
                 shape_fct=None, max_dim=None):
    if shape_fct is None:
        def shape_fct(dim):
            return (3, dim, 1, 128, 64)
    ort_fct = build_ort_reducemean(axes)
    res = []
    for dim in tqdm([4, 8, 16, 32, 64, 100, 128, 200,
                     256, 400, 512, 1024]):
        if max_dim is not None and dim > max_dim:
            continue
        shape = shape_fct(dim)
        n_arrays = 10 if dim < 512 else 4
        xs = [numpy.random.rand(*shape).astype(numpy.float32)
              for _ in range(n_arrays)]
        ys = [numpy.array(axes, dtype=numpy.int64)
              for _ in range(n_arrays)]
        info = dict(axes=axes, shape=shape)

        # numpy
        fct = lambda x, y: numpy.mean(x, axis=tuple(y))
        ctx = dict(
            xs=xs, ys=ys,
            loop_fct=loop_fct)
        obs = measure_time(
            lambda: loop_fct(fct, xs, ys),
            div_by_number=True, context=ctx, repeat=repeat, number=number)
        obs['dim'] = dim
        obs['fct'] = 'numpy'
        obs.update(info)
        res.append(obs)

        # onnxruntime
        fct = ort_fct
        obs = measure_time(
            lambda: loop_fct(fct, xs, ys),
            div_by_number=True, context=ctx, repeat=repeat, number=number)
        obs['dim'] = dim
        obs['fct'] = 'ort'
        obs.update(info)
        res.append(obs)

        if tf_reduce_mean is not None:
            # tensorflow
            fct = tf_reduce_mean
            ctx['xs'] = [convert_to_tensor(x) for x in xs]
            ctx['ys'] = ys
            obs = measure_time(
                lambda: loop_fct(fct, ctx['xs'], ctx['ys']),
                div_by_number=True, context=ctx, repeat=repeat, number=number)
            obs['dim'] = dim
            obs['fct'] = 'tf'
            obs.update(info)
            res.append(obs)

        if torch_mean is not None:
            def torch_mean1(x, y):
                return torch_mean(x, y[0])

            def torch_mean2(x, y):
                return torch_mean(torch_mean(x, y[1]), y[0])

            # torch
            fct = torch_mean1 if len(axes) == 1 else torch_mean2
            ctx['xs'] = [from_numpy(x) for x in xs]
            ctx['ys'] = ys  # [from_numpy(y) for y in ys]
            obs = measure_time(
                lambda: loop_fct(fct, ctx['xs'], ctx['ys']),
                div_by_number=True, context=ctx, repeat=repeat, number=number)
            obs['dim'] = dim
            obs['fct'] = 'torch'
            obs.update(info)
            res.append(obs)

    # Dataframes
    shape_name = str(shape).replace(str(dim), "N")
    df = pandas.DataFrame(res)
    df.columns = [_.replace('dim', 'N') for _ in df.columns]
    piv = df.pivot('N', 'fct', 'average')

    rs = piv.copy()
    for c in ['ort', 'torch', 'tf', 'tf_copy']:
        if c in rs.columns:
            rs[c] = rs['numpy'] / rs[c]
    rs['numpy'] = 1.

    # Graphs.
    fig, ax = plt.subplots(1, 2, figsize=(12, 4))
    piv.plot(logx=True, logy=True, ax=ax[0],
             title="%s benchmark\n%r - %r"
                   " lower better" % (name, shape_name, axes))
    ax[0].legend(prop={"size": 9})
    rs.plot(logx=True, logy=True, ax=ax[1],
            title="%s Speedup, baseline=numpy\n%r - %r"
                  " higher better" % (name, shape_name, axes))
    ax[1].plot([min(rs.index), max(rs.index)], [0.5, 0.5], 'g--')
    ax[1].plot([min(rs.index), max(rs.index)], [2., 2.], 'g--')
    ax[1].legend(prop={"size": 9})
    return df, rs, ax


dfs = []

Reduction on a particular case KR#

Consecutive axis not reduced and consecutive reduced axis are merged. KR means kept axis - reduced axis

(8, 24, 48, N), axis=(3, )#

axes = (3, )
df, piv, ax = benchmark_op(axes, shape_fct=lambda dim: (8, 24, 48, dim))
dfs.append(df)
df.pivot("fct", "N", "average")
ReduceMean benchmark '(8, 24, 48, N)' - (3,) lower better, ReduceMean Speedup, baseline=numpy '(8, 24, 48, N)' - (3,) higher better

Out:

  0%|          | 0/12 [00:00<?, ?it/s]
  8%|8         | 1/12 [00:00<00:01,  5.99it/s]
 17%|#6        | 2/12 [00:00<00:01,  6.32it/s]
 25%|##5       | 3/12 [00:00<00:01,  5.84it/s]
 33%|###3      | 4/12 [00:00<00:01,  4.76it/s]
 42%|####1     | 5/12 [00:01<00:01,  3.75it/s]
 50%|#####     | 6/12 [00:01<00:02,  2.95it/s]
 58%|#####8    | 7/12 [00:02<00:02,  2.39it/s]
 67%|######6   | 8/12 [00:03<00:02,  1.79it/s]
 75%|#######5  | 9/12 [00:04<00:02,  1.43it/s]
 83%|########3 | 10/12 [00:05<00:01,  1.05it/s]
 92%|#########1| 11/12 [00:06<00:00,  1.11it/s]
100%|##########| 12/12 [00:07<00:00,  1.08s/it]
100%|##########| 12/12 [00:07<00:00,  1.53it/s]
N 4 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.004226 0.004789 0.005701 0.007322 0.008807 0.011106 0.012951 0.019229 0.022946 0.032592 0.016678 0.031634
ort 0.001328 0.001430 0.001689 0.004081 0.003714 0.004785 0.005602 0.009323 0.008570 0.012567 0.006204 0.012913
torch 0.010029 0.006833 0.007292 0.007943 0.009264 0.009279 0.010520 0.011755 0.012522 0.015770 0.009201 0.013477


Reduction on a particular case RK#

Consecutive axis not reduced and consecutive reduced axis are merged. RK means reduced axis - kept axis

(8, 24, 48, N), axis=(0, )#

axes = (0, )
df, piv, ax = benchmark_op(axes, shape_fct=lambda dim: (8, 24, 48, dim))
dfs.append(df)
df.pivot("fct", "N", "average")
ReduceMean benchmark '(8, 24, 48, N)' - (0,) lower better, ReduceMean Speedup, baseline=numpy '(8, 24, 48, N)' - (0,) higher better

Out:

  0%|          | 0/12 [00:00<?, ?it/s]
 17%|#6        | 2/12 [00:00<00:01,  9.18it/s]
 25%|##5       | 3/12 [00:00<00:01,  7.29it/s]
 33%|###3      | 4/12 [00:00<00:01,  5.29it/s]
 42%|####1     | 5/12 [00:01<00:01,  3.60it/s]
 50%|#####     | 6/12 [00:01<00:02,  2.56it/s]
 58%|#####8    | 7/12 [00:02<00:02,  1.91it/s]
 67%|######6   | 8/12 [00:03<00:02,  1.37it/s]
 75%|#######5  | 9/12 [00:05<00:02,  1.03it/s]
 83%|########3 | 10/12 [00:07<00:02,  1.38s/it]
 92%|#########1| 11/12 [00:08<00:01,  1.32s/it]
100%|##########| 12/12 [00:11<00:00,  1.65s/it]
100%|##########| 12/12 [00:11<00:00,  1.08it/s]
N 4 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.001356 0.001912 0.003552 0.005911 0.010152 0.016221 0.023674 0.037088 0.048601 0.076980 0.038970 0.080135
ort 0.000898 0.001702 0.003176 0.005759 0.009244 0.010420 0.014715 0.020533 0.027531 0.039022 0.020665 0.040949
torch 0.006354 0.006386 0.006951 0.008238 0.010269 0.012117 0.013497 0.014105 0.016694 0.024481 0.014773 0.025434


Reduction on a particular case KRK#

Consecutive axis not reduced and consecutive reduced axis are merged. KRK means kept axis - reduced axis - kept axis,

(8, 24, 48, N), axis=(1, 2)#

axes = (1, 2)
df, piv, ax = benchmark_op(axes, shape_fct=lambda dim: (8, 24, 48, dim))
dfs.append(df)
df.pivot("fct", "N", "average")
ReduceMean benchmark '(8, 24, 48, N)' - (1, 2) lower better, ReduceMean Speedup, baseline=numpy '(8, 24, 48, N)' - (1, 2) higher better

Out:

  0%|          | 0/12 [00:00<?, ?it/s]
  8%|8         | 1/12 [00:00<00:01,  5.91it/s]
 17%|#6        | 2/12 [00:00<00:01,  5.34it/s]
 25%|##5       | 3/12 [00:00<00:01,  5.29it/s]
 33%|###3      | 4/12 [00:00<00:01,  4.53it/s]
 42%|####1     | 5/12 [00:01<00:01,  3.56it/s]
 50%|#####     | 6/12 [00:01<00:02,  2.69it/s]
 58%|#####8    | 7/12 [00:02<00:02,  2.18it/s]
 67%|######6   | 8/12 [00:03<00:02,  1.65it/s]
 75%|#######5  | 9/12 [00:04<00:02,  1.30it/s]
 83%|########3 | 10/12 [00:06<00:02,  1.07s/it]
 92%|#########1| 11/12 [00:07<00:01,  1.02s/it]
100%|##########| 12/12 [00:09<00:00,  1.43s/it]
100%|##########| 12/12 [00:09<00:00,  1.27it/s]
N 4 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.004353 0.004706 0.005492 0.007344 0.010684 0.012301 0.014283 0.018718 0.022181 0.032835 0.016006 0.030511
ort 0.005635 0.006842 0.002847 0.004689 0.004344 0.006313 0.007673 0.012185 0.014962 0.024523 0.012013 0.027540
torch 0.005806 0.006277 0.006738 0.007261 0.009004 0.013103 0.012832 0.016046 0.017665 0.029126 0.014671 0.086193


(8, 24 * 48, N), axis=1#

axes = (1, )
df, piv, ax = benchmark_op(axes, shape_fct=lambda dim: (8, 24 * 48, dim))
dfs.append(df)
df.pivot("fct", "N", "average")
ReduceMean benchmark '(8, 1152, N)' - (1,) lower better, ReduceMean Speedup, baseline=numpy '(8, 1152, N)' - (1,) higher better

Out:

  0%|          | 0/12 [00:00<?, ?it/s]
  8%|8         | 1/12 [00:00<00:08,  1.25it/s]
 17%|#6        | 2/12 [00:01<00:08,  1.23it/s]
 25%|##5       | 3/12 [00:02<00:06,  1.39it/s]
 33%|###3      | 4/12 [00:02<00:05,  1.41it/s]
 42%|####1     | 5/12 [00:03<00:05,  1.22it/s]
 50%|#####     | 6/12 [00:05<00:05,  1.08it/s]
 58%|#####8    | 7/12 [00:06<00:05,  1.04s/it]
 67%|######6   | 8/12 [00:07<00:04,  1.21s/it]
 75%|#######5  | 9/12 [00:09<00:04,  1.43s/it]
 83%|########3 | 10/12 [00:11<00:03,  1.53s/it]
 92%|#########1| 11/12 [00:12<00:01,  1.34s/it]
100%|##########| 12/12 [00:14<00:00,  1.50s/it]
100%|##########| 12/12 [00:14<00:00,  1.20s/it]
N 4 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.004333 0.004685 0.005465 0.007314 0.010530 0.012459 0.014183 0.018695 0.022364 0.032739 0.015788 0.030447
ort 0.005665 0.006015 0.001612 0.002779 0.004349 0.007488 0.007728 0.012411 0.017484 0.023786 0.011918 0.027406
torch 0.069007 0.069796 0.048881 0.051450 0.072699 0.068693 0.078839 0.080676 0.092793 0.028663 0.019054 0.035912


(2, 8, 12, 24, 2, N), axis=(2, 3)#

axes = (2, 3)
df, piv, ax = benchmark_op(axes, shape_fct=lambda dim: (2, 8, 12, 24, 2, dim))
dfs.append(df)
df.pivot("fct", "N", "average")
ReduceMean benchmark '(2, 8, 12, 24, 2, N)' - (2, 3) lower better, ReduceMean Speedup, baseline=numpy '(2, 8, 12, 24, 2, N)' - (2, 3) higher better

Out:

  0%|          | 0/12 [00:00<?, ?it/s]
  8%|8         | 1/12 [00:00<00:01,  7.51it/s]
 17%|#6        | 2/12 [00:00<00:01,  7.90it/s]
 25%|##5       | 3/12 [00:00<00:01,  7.14it/s]
 33%|###3      | 4/12 [00:00<00:01,  5.30it/s]
 42%|####1     | 5/12 [00:01<00:01,  3.87it/s]
 50%|#####     | 6/12 [00:01<00:02,  2.85it/s]
 58%|#####8    | 7/12 [00:02<00:02,  2.25it/s]
 67%|######6   | 8/12 [00:03<00:02,  1.66it/s]
 75%|#######5  | 9/12 [00:04<00:02,  1.29it/s]
 83%|########3 | 10/12 [00:06<00:02,  1.08s/it]
 92%|#########1| 11/12 [00:07<00:01,  1.03s/it]
100%|##########| 12/12 [00:08<00:00,  1.27s/it]
100%|##########| 12/12 [00:08<00:00,  1.36it/s]
N 4 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.002793 0.003023 0.003889 0.006751 0.008238 0.010626 0.012624 0.017779 0.021398 0.032589 0.016096 0.031002
ort 0.003129 0.001179 0.001514 0.004774 0.004388 0.006784 0.008157 0.012175 0.017058 0.022718 0.013337 0.032032
torch 0.006277 0.005834 0.006200 0.007168 0.010769 0.012756 0.014160 0.018522 0.019983 0.030155 0.017166 0.027379


Reduction on a particular case RKR#

(N, 64, 16, 16), axis=(0, 2, 3)#

axes = (0, 2, 3)
df, piv, ax = benchmark_op(
    axes, shape_fct=lambda dim: (dim, 64, 16, 16))
dfs.append(df)
df.pivot("fct", "N", "average")
ReduceMean benchmark '(N, 64, 16, 16)' - (0, 2, 3) lower better, ReduceMean Speedup, baseline=numpy '(N, 64, 16, 16)' - (0, 2, 3) higher better

Out:

  0%|          | 0/12 [00:00<?, ?it/s]
 17%|#6        | 2/12 [00:00<00:00, 10.12it/s]
 33%|###3      | 4/12 [00:00<00:01,  4.76it/s]
 42%|####1     | 5/12 [00:01<00:02,  3.15it/s]
 50%|#####     | 6/12 [00:02<00:02,  2.12it/s]
 58%|#####8    | 7/12 [00:03<00:03,  1.56it/s]
 67%|######6   | 8/12 [00:04<00:03,  1.10it/s]
 75%|#######5  | 9/12 [00:06<00:03,  1.21s/it]
 83%|########3 | 10/12 [00:09<00:03,  1.72s/it]
 92%|#########1| 11/12 [00:11<00:01,  1.66s/it]
100%|##########| 12/12 [00:14<00:00,  2.05s/it]
100%|##########| 12/12 [00:14<00:00,  1.17s/it]
N 4 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.001441 0.002246 0.004482 0.006761 0.011139 0.016394 0.020135 0.030418 0.038175 0.058464 0.029490 0.058416
ort 0.000775 0.001114 0.003634 0.003865 0.006766 0.011678 0.014416 0.020642 0.023710 0.036096 0.020115 0.037165
torch 0.001673 0.007172 0.007950 0.010915 0.013352 0.015272 0.018720 0.023026 0.026798 0.036081 0.021490 0.037824


Reduction on a particular case RKRK#

(8, 24, 48, N), axis=(0, 2)#

axes = (0, 2)
df, piv, ax = benchmark_op(axes, shape_fct=lambda dim: (8, 24, 48, dim))
dfs.append(df)
df.pivot("fct", "N", "average")
ReduceMean benchmark '(8, 24, 48, N)' - (0, 2) lower better, ReduceMean Speedup, baseline=numpy '(8, 24, 48, N)' - (0, 2) higher better

Out:

  0%|          | 0/12 [00:00<?, ?it/s]
  8%|8         | 1/12 [00:00<00:01,  7.94it/s]
 17%|#6        | 2/12 [00:00<00:01,  7.35it/s]
 25%|##5       | 3/12 [00:00<00:01,  7.38it/s]
 33%|###3      | 4/12 [00:00<00:01,  5.43it/s]
 42%|####1     | 5/12 [00:01<00:01,  3.65it/s]
 50%|#####     | 6/12 [00:01<00:02,  2.71it/s]
 58%|#####8    | 7/12 [00:02<00:02,  2.12it/s]
 67%|######6   | 8/12 [00:03<00:02,  1.55it/s]
 75%|#######5  | 9/12 [00:04<00:02,  1.20it/s]
 83%|########3 | 10/12 [00:06<00:02,  1.16s/it]
 92%|#########1| 11/12 [00:07<00:01,  1.18s/it]
100%|##########| 12/12 [00:11<00:00,  2.03s/it]
100%|##########| 12/12 [00:11<00:00,  1.03it/s]
N 4 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.005283 0.005188 0.006024 0.007840 0.011194 0.012495 0.014526 0.019392 0.022910 0.033628 0.016315 0.031266
ort 0.000738 0.001397 0.001802 0.003287 0.008787 0.008650 0.012315 0.020267 0.025726 0.038918 0.044400 0.247433
torch 0.005453 0.005596 0.001662 0.007122 0.008564 0.011242 0.012101 0.016723 0.017615 0.026641 0.014949 0.029049


Conclusion#

Some of the configurations should be investigated. l-reducesum-problem1. The reduction on tensorflow in one dimension seems to be lazy.

merged = pandas.concat(dfs)
name = "reducemean"
merged.to_csv("plot_%s.csv" % name, index=False)
merged.to_excel("plot_%s.xlsx" % name, index=False)
plt.savefig("plot_%s.png" % name)

plt.show()
plot op reducemean

Total running time of the script: ( 1 minutes 30.829 seconds)

Gallery generated by Sphinx-Gallery