Compares implementations of ReduceSum#

This example compares the numpy.sum from numpy, 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 OnnxReduceSumApi11
from cpyquickhelper.numbers import measure_time
from tqdm import tqdm
from mlprodict.testing.experimental_c_impl.experimental_c import (
    code_optimisation, custom_reducesum_rk_float)
print(code_optimisation())

Out:

AVX-omp=8

ReduceSum implementations#

try:
    from tensorflow.math import reduce_sum as tf_reduce_sum
    from tensorflow import convert_to_tensor
except ImportError:
    tf_reduce_sum = None
try:
    from torch import sum as torch_sum, from_numpy
except ImportError:
    torch_sum = None


def build_ort_reducesum(axes, op_version=14):  # opset=13, 14, ...
    node = OnnxReduceSumApi11('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=5, number=5, name="ReduceSum", shape_fct=None,
                 custom_impl=False):
    if shape_fct is None:
        def shape_fct(dim):
            return (3, dim, 1, 128, 64)
    ort_fct = build_ort_reducesum(axes)
    res = []
    for dim in tqdm([8, 16, 32, 64, 100, 128, 200,
                     256, 400, 512, 1024]):
        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
        ctx = dict(
            xs=xs, ys=ys,
            fct=lambda x, y: numpy.sum(x, *y),
            loop_fct=loop_fct)
        obs = measure_time(
            "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
        ctx['fct'] = ort_fct
        obs = measure_time(
            "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 custom_impl:
            if axes != (0, ):
                raise RuntimeError(
                    "Unexpected axes=%r." % axes)
            ctx['fct'] = lambda x, y: custom_reducesum_rk_float(x)
            ctx['xs'] = [x.reshape((x.shape[0], -1)).copy() for x in xs]
            obs = measure_time(
                "loop_fct(fct, xs, ys)",
                div_by_number=True, context=ctx, repeat=repeat, number=number)
            obs['dim'] = dim
            obs['fct'] = 'custom'
            obs.update(info)
            res.append(obs)

        if tf_reduce_sum is not None:
            # tensorflow
            ctx['fct'] = tf_reduce_sum
            ctx['xs'] = [convert_to_tensor(x) for x in xs]
            ctx['ys'] = ys
            obs = measure_time(
                "loop_fct(fct, xs, 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_sum is not None:
            def torch_sum1(x, y):
                return torch_sum(x, y[0])

            def torch_sum2(x, y):
                return torch_sum(torch_sum(x, y[1]), y[0])

            # torch
            ctx['fct'] = torch_sum1 if len(axes) == 1 else torch_sum2
            ctx['xs'] = [from_numpy(x) for x in xs]
            ctx['ys'] = ys  # [from_numpy(y) for y in ys]
            obs = measure_time(
                "loop_fct(fct, xs, 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")
ReduceSum benchmark '(8, 24, 48, N)' - (3,) lower better, ReduceSum Speedup, baseline=numpy '(8, 24, 48, N)' - (3,) higher better

Out:

  0%|          | 0/11 [00:00<?, ?it/s]
  9%|9         | 1/11 [00:00<00:02,  3.97it/s]
 18%|#8        | 2/11 [00:00<00:02,  3.59it/s]
 27%|##7       | 3/11 [00:00<00:02,  3.03it/s]
 36%|###6      | 4/11 [00:01<00:02,  2.35it/s]
 45%|####5     | 5/11 [00:02<00:03,  1.82it/s]
 55%|#####4    | 6/11 [00:03<00:03,  1.49it/s]
 64%|######3   | 7/11 [00:04<00:03,  1.15it/s]
 73%|#######2  | 8/11 [00:06<00:03,  1.09s/it]
 82%|########1 | 9/11 [00:08<00:02,  1.45s/it]
 91%|######### | 10/11 [00:09<00:01,  1.37s/it]
100%|##########| 11/11 [00:11<00:00,  1.64s/it]
100%|##########| 11/11 [00:11<00:00,  1.07s/it]
N 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.004017 0.004717 0.006313 0.007819 0.010080 0.011968 0.018191 0.021608 0.031477 0.015996 0.031347
ort 0.001001 0.001190 0.001656 0.003253 0.004900 0.005798 0.006819 0.008279 0.012213 0.006114 0.011078
torch 0.004220 0.004334 0.004650 0.005827 0.006462 0.006984 0.008075 0.009050 0.010826 0.006778 0.010686


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),
                           custom_impl=True)
dfs.append(df)
df.pivot("fct", "N", "average")
ReduceSum benchmark '(8, 24, 48, N)' - (0,) lower better, ReduceSum Speedup, baseline=numpy '(8, 24, 48, N)' - (0,) higher better

Out:

  0%|          | 0/11 [00:00<?, ?it/s]
  9%|9         | 1/11 [00:00<00:01,  5.42it/s]
 18%|#8        | 2/11 [00:00<00:02,  4.29it/s]
 27%|##7       | 3/11 [00:00<00:02,  3.01it/s]
 36%|###6      | 4/11 [00:01<00:03,  1.90it/s]
 45%|####5     | 5/11 [00:02<00:04,  1.34it/s]
 55%|#####4    | 6/11 [00:04<00:05,  1.00s/it]
 64%|######3   | 7/11 [00:06<00:05,  1.39s/it]
 73%|#######2  | 8/11 [00:09<00:05,  1.82s/it]
 82%|########1 | 9/11 [00:13<00:05,  2.57s/it]
 91%|######### | 10/11 [00:15<00:02,  2.47s/it]
100%|##########| 11/11 [00:20<00:00,  3.02s/it]
100%|##########| 11/11 [00:20<00:00,  1.82s/it]
N 8 16 32 64 100 128 200 256 400 512 1024
fct
custom 0.002857 0.003424 0.004703 0.007529 0.009415 0.011319 0.014544 0.016900 0.025799 0.013378 0.024586
numpy 0.001150 0.002225 0.003762 0.007543 0.011502 0.017179 0.027220 0.035777 0.055139 0.029739 0.056471
ort 0.001210 0.001869 0.004155 0.007459 0.009450 0.012472 0.017932 0.022182 0.032790 0.017903 0.033341
torch 0.001235 0.001384 0.002148 0.004100 0.005583 0.006686 0.008911 0.010504 0.017281 0.009986 0.017325


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")
ReduceSum benchmark '(8, 24, 48, N)' - (1, 2) lower better, ReduceSum Speedup, baseline=numpy '(8, 24, 48, N)' - (1, 2) higher better

Out:

  0%|          | 0/11 [00:00<?, ?it/s]
  9%|9         | 1/11 [00:00<00:02,  3.37it/s]
 18%|#8        | 2/11 [00:00<00:02,  3.35it/s]
 27%|##7       | 3/11 [00:01<00:03,  2.66it/s]
 36%|###6      | 4/11 [00:01<00:03,  1.77it/s]
 45%|####5     | 5/11 [00:03<00:04,  1.22it/s]
 55%|#####4    | 6/11 [00:04<00:05,  1.08s/it]
 64%|######3   | 7/11 [00:07<00:06,  1.52s/it]
 73%|#######2  | 8/11 [00:10<00:05,  2.00s/it]
 82%|########1 | 9/11 [00:14<00:05,  2.84s/it]
 91%|######### | 10/11 [00:17<00:02,  2.73s/it]
100%|##########| 11/11 [00:22<00:00,  3.45s/it]
100%|##########| 11/11 [00:22<00:00,  2.05s/it]
N 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.002682 0.005019 0.009245 0.018366 0.028725 0.035055 0.055290 0.069669 0.107723 0.056499 0.116935
ort 0.005702 0.002263 0.003036 0.004993 0.006310 0.007787 0.012333 0.015306 0.023876 0.012397 0.026562
torch 0.002654 0.003041 0.003427 0.004787 0.006416 0.009137 0.011167 0.013123 0.020324 0.011972 0.023643


(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")
ReduceSum benchmark '(8, 1152, N)' - (1,) lower better, ReduceSum Speedup, baseline=numpy '(8, 1152, N)' - (1,) higher better

Out:

  0%|          | 0/11 [00:00<?, ?it/s]
  9%|9         | 1/11 [00:00<00:03,  3.03it/s]
 18%|#8        | 2/11 [00:00<00:02,  3.41it/s]
 27%|##7       | 3/11 [00:01<00:02,  2.89it/s]
 36%|###6      | 4/11 [00:01<00:03,  2.18it/s]
 45%|####5     | 5/11 [00:02<00:03,  1.69it/s]
 55%|#####4    | 6/11 [00:03<00:03,  1.33it/s]
 64%|######3   | 7/11 [00:05<00:04,  1.01s/it]
 73%|#######2  | 8/11 [00:07<00:03,  1.32s/it]
 82%|########1 | 9/11 [00:09<00:03,  1.83s/it]
 91%|######### | 10/11 [00:11<00:01,  1.75s/it]
100%|##########| 11/11 [00:14<00:00,  2.14s/it]
100%|##########| 11/11 [00:14<00:00,  1.33s/it]
N 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.004361 0.004892 0.006691 0.010179 0.011643 0.013199 0.017833 0.021311 0.031840 0.015497 0.030075
ort 0.005699 0.001433 0.003012 0.004970 0.006303 0.007812 0.012377 0.015125 0.023803 0.012209 0.026015
torch 0.002279 0.002746 0.003593 0.004178 0.005990 0.009938 0.013582 0.019878 0.025684 0.016535 0.028612


(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")
ReduceSum benchmark '(2, 8, 12, 24, 2, N)' - (2, 3) lower better, ReduceSum Speedup, baseline=numpy '(2, 8, 12, 24, 2, N)' - (2, 3) higher better

Out:

  0%|          | 0/11 [00:00<?, ?it/s]
  9%|9         | 1/11 [00:00<00:01,  5.39it/s]
 18%|#8        | 2/11 [00:00<00:02,  4.24it/s]
 27%|##7       | 3/11 [00:00<00:02,  2.93it/s]
 36%|###6      | 4/11 [00:01<00:03,  1.80it/s]
 45%|####5     | 5/11 [00:03<00:05,  1.20it/s]
 55%|#####4    | 6/11 [00:04<00:05,  1.11s/it]
 64%|######3   | 7/11 [00:07<00:06,  1.59s/it]
 73%|#######2  | 8/11 [00:10<00:06,  2.10s/it]
 82%|########1 | 9/11 [00:15<00:05,  2.97s/it]
 91%|######### | 10/11 [00:18<00:02,  2.85s/it]
100%|##########| 11/11 [00:23<00:00,  3.65s/it]
100%|##########| 11/11 [00:23<00:00,  2.13s/it]
N 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.002724 0.005085 0.009573 0.018787 0.029635 0.037324 0.057883 0.073643 0.114009 0.058468 0.123800
ort 0.000934 0.001389 0.002355 0.004338 0.006633 0.007964 0.012628 0.016438 0.022204 0.013432 0.033393
torch 0.002925 0.002749 0.003680 0.006269 0.007811 0.009201 0.013699 0.014890 0.023174 0.013318 0.023602


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")
ReduceSum benchmark '(8, 24, 48, N)' - (0, 2) lower better, ReduceSum Speedup, baseline=numpy '(8, 24, 48, N)' - (0, 2) higher better

Out:

  0%|          | 0/11 [00:00<?, ?it/s]
  9%|9         | 1/11 [00:00<00:01,  5.50it/s]
 18%|#8        | 2/11 [00:00<00:02,  3.85it/s]
 27%|##7       | 3/11 [00:00<00:02,  2.73it/s]
 36%|###6      | 4/11 [00:01<00:04,  1.65it/s]
 45%|####5     | 5/11 [00:03<00:05,  1.09it/s]
 55%|#####4    | 6/11 [00:05<00:06,  1.25s/it]
 64%|######3   | 7/11 [00:08<00:07,  1.79s/it]
 73%|#######2  | 8/11 [00:11<00:07,  2.42s/it]
 82%|########1 | 9/11 [00:17<00:06,  3.45s/it]
 91%|######### | 10/11 [00:21<00:03,  3.52s/it]
100%|##########| 11/11 [00:32<00:00,  5.81s/it]
100%|##########| 11/11 [00:32<00:00,  2.95s/it]
N 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.002822 0.005162 0.009915 0.021942 0.034445 0.043298 0.067013 0.085577 0.133380 0.067766 0.134407
ort 0.001065 0.002717 0.003296 0.006323 0.008578 0.012360 0.019240 0.028752 0.037910 0.050482 0.246583
torch 0.002536 0.003081 0.003377 0.004888 0.006317 0.008641 0.011185 0.013548 0.021128 0.010967 0.022395


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 = "reducesum"
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 reducesum

Total running time of the script: ( 2 minutes 15.471 seconds)

Gallery generated by Sphinx-Gallery