Compares implementations of ReduceSumSquare#

This example compares the numpy for the operator ReduceSumSquare 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 OnnxReduceSumSquare
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

ReduceSumSquare 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_reducesumsquare(axes, op_version=14):  # opset=13, 14, ...
    node = OnnxReduceSumSquare('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="ReduceSumSquare", shape_fct=None):
    if shape_fct is None:
        def shape_fct(dim):
            return (3, dim, 1, 128, 64)
    ort_fct = build_ort_reducesumsquare(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 ** 2, *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 tf_reduce_sum is not None:
            # tensorflow
            ctx['fct'] = lambda x, y: tf_reduce_sum(x ** 2, y)
            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 ** 2, y[0])

            def torch_sum2(x, y):
                return torch_sum(torch_sum(x ** 2, 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. KRK means kept axis - reduced axis - kept 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")
ReduceSumSquare benchmark '(8, 24, 48, N)' - (3,) lower better, ReduceSumSquare 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:03,  2.58it/s]
 18%|#8        | 2/11 [00:00<00:02,  3.56it/s]
 27%|##7       | 3/11 [00:00<00:02,  3.52it/s]
 36%|###6      | 4/11 [00:01<00:02,  2.80it/s]
 45%|####5     | 5/11 [00:02<00:02,  2.11it/s]
 55%|#####4    | 6/11 [00:02<00:02,  1.67it/s]
 64%|######3   | 7/11 [00:04<00:03,  1.24it/s]
 73%|#######2  | 8/11 [00:05<00:03,  1.04s/it]
 82%|########1 | 9/11 [00:07<00:02,  1.45s/it]
 91%|######### | 10/11 [00:09<00:01,  1.37s/it]
100%|##########| 11/11 [00:11<00:00,  1.67s/it]
100%|##########| 11/11 [00:11<00:00,  1.05s/it]
N 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.005039 0.007544 0.010781 0.016270 0.023052 0.029326 0.043970 0.053477 0.082011 0.042265 0.085115
ort 0.001158 0.001410 0.002024 0.003753 0.005551 0.006542 0.008945 0.010728 0.015530 0.009890 0.014459
torch 0.030434 0.007597 0.008424 0.011973 0.016479 0.018865 0.026258 0.032203 0.045966 0.023291 0.043827


Reduction on a particular case RK#

Consecutive axis not reduced and consecutive reduced axis are merged. KRK means kept axis - 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")
ReduceSumSquare benchmark '(8, 24, 48, N)' - (0,) lower better, ReduceSumSquare 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,  8.11it/s]
 18%|#8        | 2/11 [00:00<00:01,  5.96it/s]
 27%|##7       | 3/11 [00:00<00:01,  4.31it/s]
 36%|###6      | 4/11 [00:01<00:02,  2.83it/s]
 45%|####5     | 5/11 [00:01<00:03,  1.97it/s]
 55%|#####4    | 6/11 [00:02<00:03,  1.47it/s]
 64%|######3   | 7/11 [00:04<00:03,  1.06it/s]
 73%|#######2  | 8/11 [00:06<00:03,  1.25s/it]
 82%|########1 | 9/11 [00:09<00:03,  1.77s/it]
 91%|######### | 10/11 [00:10<00:01,  1.68s/it]
100%|##########| 11/11 [00:13<00:00,  2.08s/it]
100%|##########| 11/11 [00:13<00:00,  1.25s/it]
N 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.002095 0.005034 0.008826 0.015516 0.024286 0.034828 0.053976 0.067252 0.113119 0.054765 0.109921
ort 0.001281 0.003121 0.005606 0.009272 0.010502 0.015868 0.019743 0.025668 0.038100 0.019958 0.037820
torch 0.006854 0.007683 0.008700 0.014383 0.020494 0.021473 0.029371 0.038986 0.051743 0.026728 0.057812


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")
ReduceSumSquare benchmark '(8, 24, 48, N)' - (1, 2) lower better, ReduceSumSquare 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:01,  7.37it/s]
 18%|#8        | 2/11 [00:00<00:01,  5.62it/s]
 27%|##7       | 3/11 [00:00<00:01,  4.08it/s]
 36%|###6      | 4/11 [00:01<00:02,  2.60it/s]
 45%|####5     | 5/11 [00:02<00:03,  1.74it/s]
 55%|#####4    | 6/11 [00:03<00:04,  1.24it/s]
 64%|######3   | 7/11 [00:05<00:04,  1.13s/it]
 73%|#######2  | 8/11 [00:08<00:05,  1.85s/it]
 82%|########1 | 9/11 [00:12<00:04,  2.37s/it]
 91%|######### | 10/11 [00:15<00:02,  2.53s/it]
100%|##########| 11/11 [00:20<00:00,  3.55s/it]
100%|##########| 11/11 [00:20<00:00,  1.90s/it]
N 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.003908 0.008066 0.014403 0.027137 0.042178 0.051649 0.082268 0.100304 0.162253 0.084078 0.169598
ort 0.001185 0.001834 0.003434 0.006673 0.009871 0.021609 0.020811 0.143334 0.043178 0.127075 0.269953
torch 0.006395 0.006806 0.006944 0.011344 0.016207 0.023673 0.030464 0.039394 0.056322 0.030454 0.054946


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

Out:

  0%|          | 0/11 [00:00<?, ?it/s]
  9%|9         | 1/11 [00:00<00:01,  6.62it/s]
 18%|#8        | 2/11 [00:00<00:01,  5.52it/s]
 27%|##7       | 3/11 [00:00<00:01,  4.32it/s]
 36%|###6      | 4/11 [00:01<00:02,  2.90it/s]
 45%|####5     | 5/11 [00:01<00:02,  2.05it/s]
 55%|#####4    | 6/11 [00:02<00:03,  1.50it/s]
 64%|######3   | 7/11 [00:04<00:03,  1.10it/s]
 73%|#######2  | 8/11 [00:07<00:04,  1.55s/it]
 82%|########1 | 9/11 [00:09<00:03,  1.91s/it]
 91%|######### | 10/11 [00:12<00:02,  2.08s/it]
100%|##########| 11/11 [00:17<00:00,  3.01s/it]
100%|##########| 11/11 [00:17<00:00,  1.59s/it]
N 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.005328 0.007770 0.011353 0.018970 0.024692 0.029259 0.044366 0.053067 0.083334 0.042227 0.083621
ort 0.001162 0.001828 0.003427 0.006562 0.009877 0.019692 0.019291 0.142519 0.042824 0.127031 0.278754
torch 0.006072 0.006528 0.006656 0.011673 0.016527 0.022903 0.031379 0.038558 0.055006 0.029315 0.056945


(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")
ReduceSumSquare benchmark '(2, 8, 12, 24, 2, N)' - (2, 3) lower better, ReduceSumSquare 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,  7.58it/s]
 18%|#8        | 2/11 [00:00<00:01,  5.08it/s]
 27%|##7       | 3/11 [00:00<00:02,  3.82it/s]
 36%|###6      | 4/11 [00:01<00:02,  2.42it/s]
 45%|####5     | 5/11 [00:02<00:03,  1.68it/s]
 55%|#####4    | 6/11 [00:03<00:04,  1.25it/s]
 64%|######3   | 7/11 [00:05<00:04,  1.12s/it]
 73%|#######2  | 8/11 [00:07<00:04,  1.56s/it]
 82%|########1 | 9/11 [00:11<00:04,  2.18s/it]
 91%|######### | 10/11 [00:14<00:02,  2.37s/it]
100%|##########| 11/11 [00:20<00:00,  3.46s/it]
100%|##########| 11/11 [00:20<00:00,  1.82s/it]
N 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.003811 0.008153 0.014858 0.027725 0.042570 0.053850 0.082993 0.107502 0.160132 0.082016 0.180325
ort 0.001013 0.004293 0.003276 0.008257 0.007887 0.012892 0.015782 0.043227 0.047557 0.119762 0.263311
torch 0.006295 0.007722 0.008047 0.013701 0.018401 0.024667 0.033008 0.043283 0.057036 0.031303 0.057644


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")
Traceback (most recent call last):
  File "somewhere/workspace/mlprodict/mlprodict_UT_39_std/_doc/examples/plot_op_reducesumsquare.py", line 234, in <module>
    df, piv, ax = benchmark_op(
  File "somewhere/workspace/mlprodict/mlprodict_UT_39_std/_doc/examples/plot_op_reducesumsquare.py", line 81, in benchmark_op
    obs = measure_time(
  File "somewhere/workspace/mlprodict/mlprodict_UT_39_std/_venv/lib/python3.9/site-packages/cpyquickhelper/numbers/speed_measure.py", line 86, in measure_time
    res = numpy.array(tim.repeat(repeat=repeat, number=number))
  File "/usr/local/lib/python3.9/timeit.py", line 205, in repeat
    t = self.timeit(number)
  File "/usr/local/lib/python3.9/timeit.py", line 177, in timeit
    timing = self.inner(it, self.timer)
  File "<timeit-src>", line 6, in inner
  File "somewhere/workspace/mlprodict/mlprodict_UT_39_std/_doc/examples/plot_op_reducesumsquare.py", line 57, in loop_fct
    fct(x, y)
  File "somewhere/workspace/mlprodict/mlprodict_UT_39_std/_doc/examples/plot_op_reducesumsquare.py", line 79, in <lambda>
    fct=lambda x, y: numpy.sum(x ** 2, *y),
  File "<__array_function__ internals>", line 180, in sum
  File "somewhere/workspace/mlprodict/mlprodict_UT_39_std/_venv/lib/python3.9/site-packages/numpy/core/fromnumeric.py", line 2296, in sum
    return _wrapreduction(a, np.add, 'sum', axis, dtype, out, keepdims=keepdims,
  File "somewhere/workspace/mlprodict/mlprodict_UT_39_std/_venv/lib/python3.9/site-packages/numpy/core/fromnumeric.py", line 86, in _wrapreduction
    return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
TypeError: output must be an array

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")

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 = "reducesumsquare"
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()

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

Gallery generated by Sphinx-Gallery