Compares implementations of Tranpose#

This example compares the numpy.transpose 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. Both numpy and torch have lazy implementations, the function switches dimensions and strides but does not move any data. That’s why function contiguous was called in both cases.

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 OnnxTranspose
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

Transpose implementations#

Function einsum is used from tensorflow and pytorch instead of transpose. The equation reflects the required transposition.

try:
    from tensorflow import transpose as tf_transpose, convert_to_tensor
except ImportError:
    tf_transpose = None
try:
    from torch import einsum as torch_einsum, from_numpy
except ImportError:
    torch_einsum = None


def build_ort_transpose(perm, op_version=12):
    node = OnnxTranspose('x', perm=perm, 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 perm2eq(perm):
    first = "".join(chr(97 + i) for i in range(len(perm)))
    second = "".join(first[p] for p in perm)
    return "%s->%s" % (first, second)


def benchmark_op(perm, repeat=5, number=5, name="Transpose", shape_fct=None):
    if shape_fct is None:
        def shape_fct(dim): return (3, dim, 1, 512)
    ort_fct = build_ort_transpose(perm)
    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 = [perm for _ in range(n_arrays)]
        equation = perm2eq(perm)
        info = dict(perm=perm, shape=shape)

        # numpy
        ctx = dict(
            xs=xs, ys=ys,
            fct=lambda x, y: numpy.ascontiguousarray(numpy.transpose(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 tf_transpose is not None:
            # tensorflow
            ctx['fct'] = tf_transpose
            ctx['xs'] = [convert_to_tensor(x) for x in xs]
            ctx['ys'] = [convert_to_tensor(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'] = 'tf'
            obs.update(info)
            res.append(obs)

            # tensorflow with copy
            ctx['fct'] = lambda x, y: tf_transpose(
                convert_to_tensor(x)).numpy()
            ctx['xs'] = 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_copy'
            obs.update(info)
            res.append(obs)

        if torch_einsum is not None:
            # torch
            ctx['fct'] = lambda x, y: torch_einsum(equation, x).contiguous()
            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 - %s"
                   " lower better" % (name, shape_name, perm, equation))
    ax[0].legend(prop={"size": 9})
    rs.plot(logx=True, logy=True, ax=ax[1],
            title="%s Speedup, baseline=numpy\n%r - %r - %s"
                  " higher better" % (name, shape_name, perm, equation))
    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 = []

First permutation: (1, 0, 2, 3)#

perm = (1, 0, 2, 3)
df, piv, ax = benchmark_op(perm)
dfs.append(df)
df.pivot("fct", "N", "average")
Transpose benchmark '(3, N, 1, 512)' - (1, 0, 2, 3) - abcd->bacd lower better, Transpose Speedup, baseline=numpy '(3, N, 1, 512)' - (1, 0, 2, 3) - abcd->bacd higher better

Out:

  0%|          | 0/11 [00:00<?, ?it/s]
  9%|9         | 1/11 [00:00<00:01,  5.24it/s]
 27%|##7       | 3/11 [00:00<00:00,  9.18it/s]
 36%|###6      | 4/11 [00:00<00:00,  7.10it/s]
 45%|####5     | 5/11 [00:00<00:01,  5.13it/s]
 55%|#####4    | 6/11 [00:01<00:01,  3.91it/s]
 64%|######3   | 7/11 [00:01<00:01,  2.97it/s]
 73%|#######2  | 8/11 [00:02<00:01,  2.28it/s]
 82%|########1 | 9/11 [00:03<00:01,  1.60it/s]
 91%|######### | 10/11 [00:04<00:00,  1.67it/s]
100%|##########| 11/11 [00:05<00:00,  1.36it/s]
100%|##########| 11/11 [00:05<00:00,  2.18it/s]
N 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.00027 0.000429 0.000770 0.001642 0.003009 0.003907 0.005685 0.007157 0.011003 0.005803 0.010565
ort 0.00064 0.000862 0.001456 0.003788 0.006044 0.007743 0.009604 0.012218 0.018900 0.009347 0.018057
torch 0.00649 0.000793 0.001131 0.001496 0.001431 0.001584 0.002050 0.003299 0.005848 0.003125 0.006874


Second permutation: (0, 1, 3, 2)#

perm = (1, 0, 3, 2)
df, piv, ax = benchmark_op(perm)
dfs.append(df)
df.pivot("fct", "N", "average")
Transpose benchmark '(3, N, 1, 512)' - (1, 0, 3, 2) - abcd->badc lower better, Transpose Speedup, baseline=numpy '(3, N, 1, 512)' - (1, 0, 3, 2) - abcd->badc higher better

Out:

  0%|          | 0/11 [00:00<?, ?it/s]
 18%|#8        | 2/11 [00:00<00:00, 12.87it/s]
 36%|###6      | 4/11 [00:00<00:01,  5.72it/s]
 45%|####5     | 5/11 [00:01<00:01,  3.66it/s]
 55%|#####4    | 6/11 [00:01<00:01,  2.68it/s]
 64%|######3   | 7/11 [00:02<00:02,  1.89it/s]
 73%|#######2  | 8/11 [00:03<00:02,  1.40it/s]
 82%|########1 | 9/11 [00:05<00:02,  1.02s/it]
 91%|######### | 10/11 [00:06<00:00,  1.02it/s]
100%|##########| 11/11 [00:08<00:00,  1.21s/it]
100%|##########| 11/11 [00:08<00:00,  1.34it/s]
N 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.000280 0.000421 0.000703 0.001625 0.003177 0.003978 0.005981 0.007329 0.010384 0.004978 0.010477
ort 0.001343 0.002131 0.004063 0.008736 0.013988 0.016747 0.024632 0.031493 0.047509 0.024311 0.047325
torch 0.000678 0.000778 0.001081 0.001501 0.001457 0.001605 0.002092 0.003260 0.005869 0.003162 0.005978


Third permutation: (0, 2, 1, 3)#

This transposition is equivalent to a reshape because it only moves the empty axis. The comparison is entirely fair as the cost for onnxruntime includes a copy from numpy to onnxruntime, a reshape = another copy, than a copy back to numpy. Tensorflow and pytorch seems to have a lazy implementation in this case.

perm = (0, 2, 1, 3)
df, piv, ax = benchmark_op(perm)
dfs.append(df)
df.pivot("fct", "N", "average")
Transpose benchmark '(3, N, 1, 512)' - (0, 2, 1, 3) - abcd->acbd lower better, Transpose Speedup, baseline=numpy '(3, N, 1, 512)' - (0, 2, 1, 3) - abcd->acbd higher better

Out:

  0%|          | 0/11 [00:00<?, ?it/s]
 27%|##7       | 3/11 [00:00<00:00, 24.27it/s]
 55%|#####4    | 6/11 [00:00<00:00,  8.00it/s]
 73%|#######2  | 8/11 [00:01<00:00,  5.11it/s]
 82%|########1 | 9/11 [00:01<00:00,  3.84it/s]
 91%|######### | 10/11 [00:02<00:00,  3.85it/s]
100%|##########| 11/11 [00:02<00:00,  3.13it/s]
100%|##########| 11/11 [00:02<00:00,  4.24it/s]
N 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.000083 0.000081 0.000081 0.000082 0.000083 0.000083 0.000083 0.000081 0.000082 0.000035 0.000035
ort 0.000574 0.000714 0.001176 0.003368 0.006054 0.006429 0.007963 0.009706 0.013854 0.006878 0.013711
torch 0.000364 0.000362 0.000363 0.000364 0.000364 0.000363 0.000362 0.000365 0.000364 0.000148 0.000149


Fourth permutation: (3, 1, 2, 0)#

perm = (3, 1, 2, 0)
df, piv, ax = benchmark_op(perm)
dfs.append(df)
df.pivot("fct", "N", "average")
Transpose benchmark '(3, N, 1, 512)' - (3, 1, 2, 0) - abcd->dbca lower better, Transpose Speedup, baseline=numpy '(3, N, 1, 512)' - (3, 1, 2, 0) - abcd->dbca higher better

Out:

  0%|          | 0/11 [00:00<?, ?it/s]
  9%|9         | 1/11 [00:00<00:01,  8.37it/s]
 18%|#8        | 2/11 [00:00<00:01,  6.09it/s]
 27%|##7       | 3/11 [00:00<00:01,  4.22it/s]
 36%|###6      | 4/11 [00:01<00:02,  2.59it/s]
 45%|####5     | 5/11 [00:02<00:03,  1.67it/s]
 55%|#####4    | 6/11 [00:03<00:04,  1.22it/s]
 64%|######3   | 7/11 [00:12<00:14,  3.63s/it]
 73%|#######2  | 8/11 [00:25<00:19,  6.58s/it]
 82%|########1 | 9/11 [00:45<00:21, 10.61s/it]
 91%|######### | 10/11 [00:56<00:10, 10.95s/it]
100%|##########| 11/11 [01:21<00:00, 15.05s/it]
100%|##########| 11/11 [01:21<00:00,  7.39s/it]
N 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.001109 0.002124 0.004405 0.008884 0.015478 0.020358 0.135317 0.196995 0.282359 0.203156 0.435409
ort 0.001546 0.002649 0.005018 0.010804 0.018357 0.022957 0.215470 0.279109 0.436952 0.225751 0.451309
torch 0.001893 0.002662 0.002881 0.003799 0.003675 0.004381 0.023016 0.035183 0.053236 0.036645 0.080167


Fifth permutation: (1, 2, 3, 0)#

perm = (1, 2, 3, 0)
df, piv, ax = benchmark_op(perm)
dfs.append(df)
df.pivot("fct", "N", "average")
Transpose benchmark '(3, N, 1, 512)' - (1, 2, 3, 0) - abcd->bcda lower better, Transpose Speedup, baseline=numpy '(3, N, 1, 512)' - (1, 2, 3, 0) - abcd->bcda higher better

Out:

  0%|          | 0/11 [00:00<?, ?it/s]
 18%|#8        | 2/11 [00:00<00:00, 10.09it/s]
 36%|###6      | 4/11 [00:00<00:01,  4.96it/s]
 45%|####5     | 5/11 [00:01<00:01,  3.37it/s]
 55%|#####4    | 6/11 [00:01<00:01,  2.55it/s]
 64%|######3   | 7/11 [00:02<00:02,  1.85it/s]
 73%|#######2  | 8/11 [00:03<00:02,  1.40it/s]
 82%|########1 | 9/11 [00:05<00:02,  1.01s/it]
 91%|######### | 10/11 [00:06<00:00,  1.03it/s]
100%|##########| 11/11 [00:08<00:00,  1.20s/it]
100%|##########| 11/11 [00:08<00:00,  1.34it/s]
N 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.000910 0.001650 0.003140 0.006303 0.010011 0.012588 0.019197 0.024207 0.037372 0.019124 0.037902
ort 0.000681 0.000919 0.001530 0.003930 0.006588 0.007264 0.010069 0.012248 0.018084 0.009386 0.018014
torch 0.001250 0.001936 0.002473 0.002754 0.002588 0.002754 0.003303 0.004518 0.006704 0.003662 0.006889


Six th permutation: (1, 2, 4, 3, 0)#

perm = (1, 2, 4, 3, 0)
df, piv, ax = benchmark_op(perm, shape_fct=lambda dim: (3, dim, 1, 8, 512))
dfs.append(df)
df.pivot("fct", "N", "average")
Transpose benchmark '(3, N, 1, 8, 512)' - (1, 2, 4, 3, 0) - abcde->bceda lower better, Transpose Speedup, baseline=numpy '(3, N, 1, 8, 512)' - (1, 2, 4, 3, 0) - abcde->bceda higher better

Out:

  0%|          | 0/11 [00:00<?, ?it/s]
  9%|9         | 1/11 [00:00<00:06,  1.61it/s]
 18%|#8        | 2/11 [00:01<00:08,  1.11it/s]
 27%|##7       | 3/11 [00:03<00:11,  1.43s/it]
 36%|###6      | 4/11 [00:07<00:17,  2.46s/it]
 45%|####5     | 5/11 [00:14<00:22,  3.81s/it]
 55%|#####4    | 6/11 [00:21<00:26,  5.21s/it]
 64%|######3   | 7/11 [00:34<00:30,  7.53s/it]
 73%|#######2  | 8/11 [00:50<00:30, 10.15s/it]
 82%|########1 | 9/11 [01:14<00:29, 14.60s/it]
 91%|######### | 10/11 [01:26<00:13, 13.97s/it]
100%|##########| 11/11 [01:51<00:00, 17.35s/it]
100%|##########| 11/11 [01:51<00:00, 10.18s/it]
N 8 16 32 64 100 128 200 256 400 512 1024
fct
numpy 0.008103 0.016207 0.031749 0.062693 0.097270 0.124421 0.193464 0.248998 0.385411 0.198125 0.395666
ort 0.010779 0.020898 0.039242 0.076335 0.118450 0.151030 0.235038 0.300770 0.466131 0.241745 0.479248
torch 0.004800 0.004852 0.007529 0.014137 0.020606 0.025875 0.039752 0.050138 0.075738 0.038504 0.076151


Conclusion#

All libraries have similar implementations. onnxruntime measures includes 2 mores copies, one to copy from numpy container to onnxruntime container, another one to copy back from onnxruntime container to numpy. Parallelisation should be investigated.

merged = pandas.concat(dfs)
name = "transpose"
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 transpose

Total running time of the script: ( 3 minutes 48.060 seconds)

Gallery generated by Sphinx-Gallery