201: Evaluate different ways to export a torch model to ONNX

The example evaluates the performance of onnxruntime of a simple torch model after it was converted into ONNX through different processes:

  • TorchScript-based ONNX Exporter, let’s call it script

  • TorchDynamo-based ONNX Exporter, let’s call it dynamo

  • if available, the previous model but optimized, dynopt

  • a custom exporter cus_p0, this exporter supports a very limited set of models, as dynamo, it relies on torch.fx but the design is closer to what tensorflow-onnx does.

  • the same exporter but unused nodes were removed and constants were folded, cus_p2

To run the script:

python _doc/examples/plot_torch_export --help

The script takes around 12 minutes with a larger models.

Some helpers

from experimental_experiment.args import get_parsed_args


script_args = get_parsed_args(
    "plot_torch_export",
    description=__doc__,
    scenarios={
        "small": "small model to test",
        "middle": "55Mb model",
        "large": "1Gb model",
    },
    warmup=5,
    repeat=5,
    maxtime=(
        2,
        "maximum time to run a model to measure the computation time, "
        "it is 0.1 when scenario is small",
    ),
    expose="scenarios,repeat,warmup",
)


import contextlib
import itertools
import os
import platform
import pprint
import multiprocessing
import time
import cProfile
import pstats
import io
import warnings
import logging
from pstats import SortKey

try:
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        import onnxruntime

        has_cuda = "CUDAExecutionProvider" in onnxruntime.get_available_providers()
except ImportError:
    print("onnxruntime not available.")
    import sys

    sys.exit(0)

import numpy as np
import matplotlib.pyplot as plt
import pandas
import onnx
from onnx_array_api.profiling import profile2graph
import torch
from torch import nn
import torch.nn.functional as F
import experimental_experiment
from experimental_experiment.torch_interpreter import to_onnx
from experimental_experiment.xbuilder import OptimizationOptions
from experimental_experiment.plotting.memory import memory_peak_plot
from experimental_experiment.ext_test_case import measure_time, get_figure
from experimental_experiment.memory_peak import start_spying_on
from experimental_experiment.ext_test_case import unit_test_going
from experimental_experiment.helpers import pretty_onnx
from tqdm import tqdm

has_cuda = has_cuda and torch.cuda.device_count() > 0
logging.disable(logging.ERROR)


def system_info():
    obs = {}
    obs["processor"] = platform.processor()
    obs["cores"] = multiprocessing.cpu_count()
    try:
        obs["cuda"] = 1 if torch.cuda.device_count() > 0 else 0
        obs["cuda_count"] = torch.cuda.device_count()
        obs["cuda_name"] = torch.cuda.get_device_name()
        obs["cuda_capa"] = torch.cuda.get_device_capability()
    except (RuntimeError, AssertionError):
        # no cuda
        pass
    return obs


pprint.pprint(system_info())
{'cores': 20,
 'cuda': 1,
 'cuda_capa': (8, 9),
 'cuda_count': 1,
 'cuda_name': 'NVIDIA GeForce RTX 4060 Laptop GPU',
 'processor': 'x86_64'}

Scripts arguments

if script_args.scenario in (None, "small"):
    script_args.maxtime = 0.1

if unit_test_going():
    script_args.warmup = 1
    script_args.repeat = 1
    script_args.maxtime = 0.1
    script_args.scenario = "small"

print(f"scenario={script_args.scenario or 'small'}")
print(f"warmup={script_args.warmup}")
print(f"repeat={script_args.repeat}")
print(f"maxtime={script_args.maxtime}")
scenario=small
warmup=5
repeat=5
maxtime=0.1

The model

A simple model to convert.

class MyModelClass(nn.Module):
    def __init__(self, scenario=script_args.scenario):
        super().__init__()
        if scenario == "middle":
            self.large = False
            self.conv1 = nn.Conv2d(1, 128, 5)
            self.conv2 = nn.Conv2d(128, 16, 5)
            self.fc1 = nn.Linear(13456, 1024)
            self.fcs = []
            self.fc2 = nn.Linear(1024, 128)
            self.fc3 = nn.Linear(128, 10)
        elif scenario in (None, "small"):
            self.large = False
            self.conv1 = nn.Conv2d(1, 16, 5)
            self.conv2 = nn.Conv2d(16, 16, 5)
            self.fc1 = nn.Linear(16, 512)
            self.fcs = []
            self.fc2 = nn.Linear(512, 128)
            self.fc3 = nn.Linear(128, 10)
        elif scenario in (None, "large"):
            self.large = True
            self.conv1 = nn.Conv2d(1, 128, 5)
            self.conv2 = nn.Conv2d(128, 16, 5)
            self.fc1 = nn.Linear(13456, 4096)
            # torch script does not support loops.
            self.fca = nn.Linear(4096, 4096)
            self.fcb = nn.Linear(4096, 4096)
            self.fcc = nn.Linear(4096, 4096)
            self.fcd = nn.Linear(4096, 4096)
            self.fce = nn.Linear(4096, 4096)
            self.fcf = nn.Linear(4096, 4096)
            self.fcg = nn.Linear(4096, 4096)
            self.fch = nn.Linear(4096, 4096)
            self.fci = nn.Linear(4096, 4096)
            self.fck = nn.Linear(4096, 4096)
            self.fcl = nn.Linear(4096, 4096)
            self.fcm = nn.Linear(4096, 4096)
            self.fcn = nn.Linear(4096, 4096)
            # end of the unfolded loop.
            self.fc2 = nn.Linear(4096, 128)
            self.fc3 = nn.Linear(128, 10)
        else:
            raise ValueError(f"Unsupported scenario={scenario!r}.")

    def forward(self, x):
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        x = torch.flatten(x, 1)
        x = F.relu(self.fc1(x))
        if self.large:
            # loop
            x = F.relu(self.fca(x))
            x = F.relu(self.fcb(x))
            x = F.relu(self.fcc(x))
            x = F.relu(self.fcd(x))
            x = F.relu(self.fce(x))
            x = F.relu(self.fcf(x))
            x = F.relu(self.fcg(x))
            x = F.relu(self.fch(x))
            x = F.relu(self.fci(x))
            x = F.relu(self.fck(x))
            x = F.relu(self.fcl(x))
            x = F.relu(self.fcm(x))
            x = F.relu(self.fcn(x))
            # end of the loop
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x


def create_model_and_input(scenario=script_args.scenario):
    if scenario == "middle":
        shape = [1, 1, 128, 128]
    elif scenario in (None, "small"):
        shape = [1, 1, 16, 16]
    elif scenario == "large":
        shape = [1, 1, 128, 128]
    else:
        raise ValueError(f"Unsupported scenario={scenario!r}.")
    input_tensor = torch.rand(*shape).to(torch.float32)
    model = MyModelClass(scenario=scenario)
    assert model(input_tensor) is not None
    return model, input_tensor


def torch_model_size(model):
    size_model = 0
    for param in model.parameters():
        size = param.numel() * torch.finfo(param.data.dtype).bits / 8
        size_model += size
    return size_model


model, input_tensor = create_model_and_input()
model_size = torch_model_size(model)
print(f"model size={model_size / 2 ** 20} Mb")
model size=0.31467437744140625 Mb

The exporters

def export_script(filename, model, *args):
    with contextlib.redirect_stdout(io.StringIO()):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            torch.onnx.export(model, *args, filename, input_names=["input"], dynamo=False)


def export_dynamo(filename, model, *args):
    with contextlib.redirect_stdout(io.StringIO()):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            export_output = torch.onnx.export(model, args, dynamo=True)
            export_output.save(filename)


def export_dynopt(filename, model, *args):
    with contextlib.redirect_stdout(io.StringIO()):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            export_output = torch.onnx.export(model, args, dynamo=True)
            model_onnx = export_output.model_proto

            from experimental_experiment.convert.convert_helper import (
                optimize_model_proto_oxs,
            )

            optimized_model = optimize_model_proto_oxs(model_onnx)

            with open(filename, "wb") as f:
                f.write(optimized_model.SerializeToString())


def export_cus_p0(filename, model, *args):
    onx = to_onnx(model, tuple(args), input_names=["input"])
    with open(filename, "wb") as f:
        f.write(onx.SerializeToString())


def export_cus_p2(filename, model, *args):
    onx = to_onnx(
        model,
        tuple(args),
        input_names=["input"],
        options=OptimizationOptions(
            remove_unused=True,
            constant_folding=True,
        ),
    )
    with open(filename, "wb") as f:
        f.write(onx.SerializeToString())

Let’s check they are working.

export_functions = [
    export_script,
    export_dynamo,
    export_dynopt,
    export_cus_p0,
    export_cus_p2,
]

exporters = {f.__name__.replace("export_", ""): f for f in export_functions}

supported_exporters = {}
for k, v in exporters.items():
    print(f"run exporter {k}")
    filename = f"plot_torch_export_{k}.onnx"
    try:
        v(filename, model, input_tensor)
    except Exception as e:
        print(f"skipped due to {str(e)[:1000]}")
        continue
    supported_exporters[k] = v
    print(f"done. size={os.stat(filename).st_size / 2 ** 20:1.0f} Mb")
run exporter script
done. size=0 Mb
run exporter dynamo
done. size=0 Mb
run exporter dynopt
done. size=0 Mb
run exporter cus_p0
done. size=0 Mb
run exporter cus_p2
done. size=0 Mb

Exporter memory

def flatten(ps):
    obs = ps["cpu"].to_dict(unit=2**20)
    if "gpus" in ps:
        for i, g in enumerate(ps["gpus"]):
            for k, v in g.to_dict(unit=2**20).items():
                obs[f"gpu{i}_{k}"] = v
    return obs


data = []

for k, v in supported_exporters.items():
    print(f"run exporter for memory {k}")
    filename = f"plot_torch_export_{k}.onnx"
    if has_cuda:
        torch.cuda.set_device(0)
    stat = start_spying_on(cuda=1 if has_cuda else 0)
    v(filename, model, input_tensor)
    obs = flatten(stat.stop())
    print("done.")
    onx = onnx.load(filename)
    obs.update(dict(nodes=len(onx.graph.node), export=k))
    data.append(obs)

stat = start_spying_on(cuda=1 if has_cuda else 0)
exported_mod = torch.export.export(model, (input_tensor,))
obs = flatten(stat.stop())
obs.update(dict(export="torch.fx"))
data.append(obs)
run exporter for memory script
done.
run exporter for memory dynamo
done.
run exporter for memory dynopt
done.
run exporter for memory cus_p0
done.
run exporter for memory cus_p2
done.

The result.

df1 = pandas.DataFrame(data)
df1.to_csv("plot_torch_export_memory.csv", index=False)
df1.to_excel("plot_torch_export_memory.xlsx", index=False)
print(df1)

ax = memory_peak_plot(
    data,
    bars=[model_size * i / 2**20 for i in range(1, 5)],
    suptitle=f"Memory Consumption of the Export\nmodel size={model_size / 2**20:1.0f} Mb",
)
get_figure(ax).savefig("plot_torch_export_memory.png")
Memory Consumption of the Export model size=0 Mb, Memory peak (Mb), Memory peak - memory begin (Mb), Memory average - memory begin (Mb), GPU Memory peak (Mb), GPU Memory peak - memory begin (Mb), GPU Memory average - memory begin (Mb)
          peak         mean    n        begin          end   gpu0_peak   gpu0_mean  gpu0_n  gpu0_begin    gpu0_end  nodes    export
0  1188.781250  1187.734375   10  1187.531250  1188.781250  318.617188  318.617188      10  318.617188  318.617188   12.0    script
1  1189.250000  1188.811531  129  1188.781250  1189.250000  318.617188  318.617188     129  318.617188  318.617188   12.0    dynamo
2  1189.250000  1189.189991   69  1189.250000  1185.109375  318.617188  318.617188      69  318.617188  318.617188   12.0    dynopt
3  1185.109375  1185.109375   11  1185.109375  1185.109375  318.617188  318.617188      11  318.617188  318.617188   12.0    cus_p0
4  1185.265625  1185.209821   14  1185.109375  1185.265625  318.617188  318.617188      14  318.617188  318.617188   12.0    cus_p2
5  1185.265625  1185.265625    9  1185.265625  1185.265625  318.617188  318.617188       9  318.617188  318.617188    NaN  torch.fx

Exporter speed

data = []

for k, v in supported_exporters.items():
    print(f"run exporter {k}")
    filename = f"plot_torch_export_{k}.onnx"
    times = []
    for _ in range(script_args.repeat):
        begin = time.perf_counter()
        v(filename, model, input_tensor)
        duration = time.perf_counter() - begin
        times.append(duration)
    onx = onnx.load(filename)
    print("done.")
    data.append(
        dict(
            export=k,
            time=np.mean(times),
            min=min(times),
            max=max(times),
            first=times[0],
            last=times[-1],
            std=np.std(times),
            nodes=len(onx.graph.node),
        )
    )
run exporter script
done.
run exporter dynamo
done.
run exporter dynopt
done.
run exporter cus_p0
done.
run exporter cus_p2
done.

The last export to measure time torch spends in export the model before any other export can begin the translation except the first one.

times = []
for _ in range(script_args.repeat):
    begin = time.perf_counter()
    exported_mod = torch.export.export(model, (input_tensor,))
    duration = time.perf_counter() - begin
    times.append(duration)
data.append(
    dict(
        export="torch.fx",
        time=np.mean(times),
        min=min(times),
        max=max(times),
        first=times[0],
        last=times[-1],
        std=np.std(times),
        nodes=len(onx.graph.node),
    )
)

The result.

df1 = pandas.DataFrame(data)
df1.to_csv("plot_torch_export_time.csv", index=False)
df1.to_excel("plot_torch_export_time.xlsx", index=False)
print(df1)

fig, ax = plt.subplots(1, 1)
dfi = df1[["export", "time", "std"]].set_index("export")
dfi["time"].plot.bar(ax=ax, title="Export time", yerr=dfi["std"], rot=30)
fig.tight_layout()
fig.savefig("plot_torch_export_time.png")
Export time
     export      time       min       max     first      last       std  nodes
0    script  0.046061  0.018735  0.088960  0.088960  0.022593  0.029897     12
1    dynamo  0.991838  0.643624  1.458949  0.643624  0.906326  0.289741     12
2    dynopt  0.650094  0.563247  0.932520  0.572486  0.563247  0.141809     12
3    cus_p0  0.068490  0.054924  0.084487  0.080351  0.084487  0.011723     12
4    cus_p2  0.070560  0.051485  0.087028  0.059000  0.087028  0.013290     12
5  torch.fx  0.041713  0.035368  0.056817  0.056817  0.039296  0.007746     12

Exporter Profiling

def clean_text(text):
    pathes = [
        os.path.abspath(os.path.normpath(os.path.join(os.path.dirname(torch.__file__), ".."))),
        os.path.abspath(os.path.normpath(os.path.join(os.path.dirname(onnx.__file__), ".."))),
        os.path.abspath(
            os.path.normpath(
                os.path.join(os.path.dirname(experimental_experiment.__file__), "..")
            )
        ),
    ]
    for p in pathes:
        text = text.replace(p, "")
    text = text.replace("experimental_experiment", "experimental_experiment".upper())
    return text


def profile_function(name, export_function, verbose=False):
    print(f"profile {name}: {export_function}")
    pr = cProfile.Profile()
    pr.enable()
    for _ in range(script_args.repeat):
        export_function("dummyc.onnx", model, input_tensor)
    pr.disable()
    s = io.StringIO()
    sortby = SortKey.CUMULATIVE
    ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
    ps.print_stats()

    raw = s.getvalue()
    text = "\n".join(raw.split("\n")[:200])
    if verbose:
        print(text)
    with open(f"plot_torch_export_profile_{name}.txt", "w") as f:
        f.write(raw)

    root, _nodes = profile2graph(ps, clean_text=clean_text)
    text = root.to_text()
    with open(f"plot_torch_export_profile_{name}_h.txt", "w") as f:
        f.write(text)
    print("done.")


profile_function("custom0", export_cus_p0, True)
profile_function("custom2", export_cus_p2)
profile custom0: <function export_cus_p0 at 0x7c7709d2a8e0>
         653764 function calls (642133 primitive calls) in 0.578 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    80/20    0.001    0.000    0.362    0.018 ~/vv/this312/lib/python3.12/site-packages/torch/nn/functional.py:1686(relu)
     35/5    0.000    0.000    0.222    0.044 ~/vv/this312/lib/python3.12/site-packages/torch/nn/modules/module.py:1779(_call_impl)
        5    0.000    0.000    0.220    0.044 ~/vv/this312/lib/python3.12/site-packages/torch/export/_trace.py:1898(forward)
        5    0.000    0.000    0.210    0.042 ~/github/experimental-experiment/_doc/examples/plot_torch_export_201.py:191(forward)
        5    0.001    0.000    0.175    0.035 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:5494(to_onnx)
     1425    0.004    0.000    0.150    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:1399(__torch_function__)
     1425    0.004    0.000    0.140    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:1428(__torch_function__)
     2300    0.005    0.000    0.135    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_export/non_strict_utils.py:1048(__torch_function__)
       60    0.001    0.000    0.124    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/_ops.py:952(handler)
        5    0.001    0.000    0.121    0.024 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:6185(optimize)
       60    0.006    0.000    0.121    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/_library/utils.py:271(handle_dispatch_mode)
    40/10    0.000    0.000    0.114    0.011 ~/vv/this312/lib/python3.12/site-packages/torch/_jit_internal.py:617(fn)
   300/60    0.000    0.000    0.113    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_stats.py:23(wrapper)
       60    0.001    0.000    0.113    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:1520(__torch_dispatch__)
       60    0.002    0.000    0.112    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:866(proxy_call)
        5    0.000    0.000    0.102    0.020 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:6569(optimize_with_patterns)
        5    0.007    0.001    0.101    0.020 ~/github/experimental-experiment/experimental_experiment/xoptim/graph_builder_optim.py:1145(optimize)
     20/5    0.000    0.000    0.082    0.016 {built-in method torch.flatten}
     1595    0.020    0.000    0.075    0.000 ~/github/experimental-experiment/experimental_experiment/xoptim/patterns_api.py:148(enumerate_matches)
  390/130    0.002    0.000    0.066    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/overrides.py:1677(handle_torch_function)
      115    0.000    0.000    0.065    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/proxy.py:263(create_proxy)
      120    0.001    0.000    0.062    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:2011(create_node)
      120    0.000    0.000    0.061    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:1171(create_node)
      120    0.002    0.000    0.059    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/proxy.py:152(create_node)
  340/175    0.000    0.000    0.050    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_ops.py:840(__call__)
       65    0.000    0.000    0.048    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:656(track_tensor_tree)
   120/65    0.000    0.000    0.048    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:678(wrap_with_proxy)
        5    0.000    0.000    0.046    0.009 ~/vv/this312/lib/python3.12/site-packages/torch/export/_trace.py:523(_produce_aten_artifact)
 1390/270    0.003    0.000    0.045    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_pytree.py:1191(unflatten)
        5    0.002    0.000    0.042    0.008 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:4738(_build_initializers)
      120    0.000    0.000    0.042    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_traceback.py:174(summary)
       30    0.000    0.000    0.041    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph_module.py:807(recompile)
      240    0.000    0.000    0.039    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1363(__torch_dispatch__)
      240    0.002    0.000    0.038    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:2067(dispatch)
       20    0.000    0.000    0.038    0.002 {built-in method torch.relu}
       50    0.002    0.000    0.038    0.001 ~/github/onnx-diagnostic/onnx_diagnostic/helpers/mini_onnx_builder.py:17(proto_from_array)
      115    0.001    0.000    0.036    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:547(set_meta)
        5    0.001    0.000    0.036    0.007 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:5199(process)
       95    0.001    0.000    0.036    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1448(_cached_dispatch_impl)
3190/3170    0.003    0.000    0.035    0.000 {built-in method builtins.next}
      120    0.001    0.000    0.035    0.000 ~/github/experimental-experiment/experimental_experiment/torch_interpreter/interpreter.py:173(run_node)
      185    0.000    0.000    0.034    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_pytree.py:1335(tree_map)
       15    0.000    0.000    0.033    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/nn/modules/linear.py:130(forward)
    60/15    0.001    0.000    0.033    0.002 {built-in method torch._C._nn.linear}
       30    0.000    0.000    0.031    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:1635(python_code)
       10    0.000    0.000    0.030    0.003 ~/vv/this312/lib/python3.12/site-packages/torch/nn/modules/conv.py:547(forward)
       10    0.000    0.000    0.029    0.003 ~/vv/this312/lib/python3.12/site-packages/torch/nn/modules/conv.py:530(_conv_forward)
    40/10    0.000    0.000    0.029    0.003 {built-in method torch.conv2d}
       50    0.029    0.001    0.029    0.001 {method 'clone' of 'torch._C.TensorBase' objects}
      120    0.006    0.000    0.027    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_traceback.py:252(_extract_symbolized_tb)
        5    0.000    0.000    0.026    0.005 ~/vv/this312/lib/python3.12/site-packages/torch/fx/_symbolic_trace.py:634(create_args_for_root)
       55    0.001    0.000    0.026    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/meta_utils.py:871(meta_tensor)
      440    0.000    0.000    0.025    0.000 {method 'extend' of 'list' objects}
       60    0.000    0.000    0.025    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/_symbolic_trace.py:700(<genexpr>)
       55    0.000    0.000    0.025    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/_symbolic_trace.py:697(proxy_placeholder)
       55    0.000    0.000    0.025    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/_symbolic_trace.py:902(_proxy_placeholder)
       60    0.001    0.000    0.025    0.000 ~/github/experimental-experiment/experimental_experiment/torch_interpreter/interpreter.py:1400(call_function)
       55    0.000    0.000    0.024    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/_symbolic_trace.py:906(replace_ph)
       30    0.000    0.000    0.024    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:1714(_python_code)
       30    0.003    0.000    0.024    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:431(_gen_python_code)
      205    0.004    0.000    0.023    0.000 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:3996(make_node)
       55    0.002    0.000    0.023    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/autograd/grad_mode.py:287(__exit__)
      720    0.001    0.000    0.023    0.000 ~/github/experimental-experiment/experimental_experiment/xoptim/patterns_api.py:994(match)
      185    0.001    0.000    0.022    0.000 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder_opset.py:117(make_node)
      720    0.001    0.000    0.022    0.000 ~/github/experimental-experiment/experimental_experiment/xoptim/patterns_api.py:379(_get_match_pattern)
      115    0.001    0.000    0.022    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/passes/shape_prop.py:40(_extract_tensor_metadata)
       10    0.000    0.000    0.021    0.002 ~/github/experimental-experiment/experimental_experiment/xoptim/patterns_api.py:329(_build_pattern)
1505/1495    0.001    0.000    0.020    0.000 /usr/lib/python3.12/contextlib.py:132(__enter__)
     8365    0.003    0.000    0.020    0.000 /usr/lib/python3.12/traceback.py:265(__init__)
    40/10    0.000    0.000    0.019    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/nn/functional.py:800(_max_pool2d)
       95    0.001    0.000    0.018    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1545(_cache_key)
       15    0.000    0.000    0.018    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_pytree.py:2024(tree_map_with_path)
       10    0.000    0.000    0.018    0.002 {built-in method torch.max_pool2d}
96950/95770    0.015    0.000    0.018    0.000 {built-in method builtins.isinstance}
     25/5    0.000    0.000    0.018    0.004 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:347(from_real_tensor)
        5    0.000    0.000    0.017    0.003 ~/vv/this312/lib/python3.12/site-packages/torch/_export/non_strict_utils.py:328(make_fake_inputs)
      375    0.001    0.000    0.017    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_pytree.py:1264(tree_flatten)
     8705    0.005    0.000    0.017    0.000 /usr/lib/python3.12/traceback.py:318(line)
1505/1495    0.001    0.000    0.017    0.000 /usr/lib/python3.12/contextlib.py:141(__exit__)
   440/95    0.003    0.000    0.017    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1662(_prep_args_for_hash)
 2030/375    0.004    0.000    0.017    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_pytree.py:1272(helper)
       95    0.000    0.000    0.016    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1996(_output_from_cache_entry)
       30    0.000    0.000    0.016    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_pytree.py:2056(<genexpr>)
       10    0.000    0.000    0.016    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph_module.py:450(__init__)
  175/145    0.001    0.000    0.016    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/nn/modules/module.py:1968(__setattr__)
      105    0.002    0.000    0.016    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1923(_get_output_tensor_from_cache_entry)
     25/5    0.001    0.000    0.015    0.003 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/meta_utils.py:1844(__call__)
      120    0.015    0.000    0.015    0.000 {built-in method torch._C._profiler.symbolize_tracebacks}
       10    0.000    0.000    0.014    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph_module.py:563(graph)
       10    0.000    0.000    0.014    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/_export/passes/replace_with_hop_pass_util.py:157(_replace_with_hop_pass_helper)
      115    0.000    0.000    0.014    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_prims_common/__init__.py:423(is_contiguous_for_memory_format_or_false)
      115    0.000    0.000    0.014    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_prims_common/__init__.py:390(is_contiguous_for_memory_format)
      720    0.002    0.000    0.013    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:645(emit_node)
       55    0.002    0.000    0.013    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/autograd/grad_mode.py:283(__enter__)
       15    0.001    0.000    0.013    0.001 ~/github/experimental-experiment/experimental_experiment/xoptim/patterns/__init__.py:132(get_default_patterns)
     5755    0.013    0.000    0.013    0.000 {built-in method builtins.setattr}
      115    0.000    0.000    0.013    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:447(extract_val)
     20/4    0.000    0.000    0.013    0.003 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:2976(from_tensor)
      115    0.001    0.000    0.013    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_prims_common/__init__.py:296(is_contiguous)
      115    0.000    0.000    0.013    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:421(snapshot_fake)
      115    0.002    0.000    0.012    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_impls.py:1303(fast_detach)
      275    0.004    0.000    0.012    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:708(__new__)
        5    0.000    0.000    0.011    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/_export/utils.py:707(apply_runtime_assertion_pass)
      135    0.000    0.000    0.011    0.000 /usr/lib/python3.12/inspect.py:3343(signature)
     1080    0.003    0.000    0.011    0.000 ~/github/experimental-experiment/experimental_experiment/xoptim/patterns_api.py:124(__init__)
      135    0.000    0.000    0.011    0.000 /usr/lib/python3.12/inspect.py:3081(from_callable)
     8365    0.005    0.000    0.011    0.000 /usr/lib/python3.12/linecache.py:26(getline)
  265/135    0.002    0.000    0.011    0.000 /usr/lib/python3.12/inspect.py:2501(_signature_from_callable)
      115    0.002    0.000    0.011    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:575(track_tensor)
     1350    0.001    0.000    0.010    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/meta_utils.py:194(is_sparse_any)
     2515    0.004    0.000    0.010    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/node.py:903(__setattr__)
        5    0.000    0.000    0.010    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/export/exported_program.py:1052(__init__)
       15    0.000    0.000    0.010    0.001 ~/github/experimental-experiment/experimental_experiment/xoptim/graph_builder_optim.py:58(__init__)
       55    0.002    0.000    0.009    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/meta_utils.py:277(describe_tensor)
      115    0.001    0.000    0.009    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_prims_common/__init__.py:251(check_contiguous_sizes_strides)
        5    0.000    0.000    0.009    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/_export/utils.py:969(placeholder_naming_pass)
       10    0.001    0.000    0.009    0.001 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:7008(constant_folding)
     3620    0.002    0.000    0.009    0.000 <frozen _collections_abc>:804(get)
       30    0.000    0.000    0.009    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph_module.py:97(_forward_from_src)
       30    0.000    0.000    0.009    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph_module.py:103(_method_from_src)
      145    0.002    0.000    0.009    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1029(_flatten_into)
       30    0.000    0.000    0.009    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph_module.py:92(_exec_with_source)
        5    0.000    0.000    0.008    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/fx/_lazy_graph_module.py:57(_make_graph_module)
       30    0.008    0.000    0.008    0.000 {built-in method builtins.compile}
    50/40    0.001    0.000    0.008    0.000 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:6749(compute_constant)
        5    0.000    0.000    0.008    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/export/_trace.py:483(_replace_unbacked_bindings)
        5    0.000    0.000    0.008    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/export/exported_program.py:1672(_create_graph_module_for_export)
  510/210    0.001    0.000    0.008    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/__init__.py:849(sym_max)
      240    0.001    0.000    0.008    0.000 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:8345(_make_node_set_type_shape)
        5    0.000    0.000    0.007    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/_export/passes/replace_set_grad_with_hop_pass.py:110(replace_set_grad_with_hop_pass)
        5    0.000    0.000    0.007    0.001 ~/github/experimental-experiment/experimental_experiment/torch_interpreter/_aten_functions.py:3457(aten_flatten_using_ints)
        5    0.000    0.000    0.007    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/_export/non_strict_utils.py:403(<lambda>)
 1050/115    0.004    0.000    0.007    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/symbolic_shapes.py:1089(_free_unbacked_symbols_with_path)
     3620    0.004    0.000    0.007    0.000 <frozen os>:709(__getitem__)
      120    0.001    0.000    0.007    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:1172(create_node)
      240    0.001    0.000    0.007    0.000 ~/github/experimental-experiment/experimental_experiment/xbuilder/shape_type_compute.py:1481(set_shape_type_op_any)
        5    0.000    0.000    0.007    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/_export/passes/replace_autocast_with_hop_pass.py:178(replace_autocast_with_hop_pass)
        5    0.000    0.000    0.007    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/_export/non_strict_utils.py:159(fakify)
      135    0.002    0.000    0.007    0.000 /usr/lib/python3.12/inspect.py:2397(_signature_from_function)
       60    0.001    0.000    0.007    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:1690(override_node_repr)
       50    0.003    0.000    0.006    0.000 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:6683(remove_unused)
        5    0.000    0.000    0.006    0.001 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:5453(_update_metadata_props)
        5    0.000    0.000    0.006    0.001 ~/github/experimental-experiment/experimental_experiment/xoptim/patterns/onnx_functions.py:137(match_pattern)
       10    0.000    0.000    0.006    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/_symbolic_trace.py:1106(patch_method)
      420    0.002    0.000    0.006    0.000 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:1779(set_shape)
       10    0.000    0.000    0.006    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/_symbolic_trace.py:1074(patch)
      145    0.002    0.000    0.006    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1051(extract_tensor_metadata)
       15    0.000    0.000    0.006    0.000 ~/github/experimental-experiment/experimental_experiment/xbuilder/optimization_options.py:60(__init__)
       30    0.000    0.000    0.006    0.000 ~/github/experimental-experiment/experimental_experiment/xoptim/graph_builder_optim.py:779(apply_match)
       10    0.001    0.000    0.006    0.001 {built-in method torch._ops.aten.}
       55    0.000    0.000    0.005    0.000 ~/github/experimental-experiment/experimental_experiment/torch_interpreter/interpreter.py:487(placeholder)
        5    0.000    0.000    0.005    0.001 ~/github/experimental-experiment/experimental_experiment/xoptim/__init__.py:101(get_pattern_list)
       10    0.000    0.000    0.005    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/_symbolic_trace.py:1159(_new_patcher)
       90    0.001    0.000    0.005    0.000 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:2684(add_initializer)
        5    0.000    0.000    0.005    0.001 ~/github/experimental-experiment/experimental_experiment/xoptim/__init__.py:14(get_pattern)
     1570    0.002    0.000    0.005    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/meta_utils.py:189(is_sparse_compressed)
      250    0.001    0.000    0.005    0.000 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:4269(_make_node_set_type_shape_constant)
        5    0.000    0.000    0.005    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/_symbolic_trace.py:1127(revert_all_patches)
       10    0.000    0.000    0.005    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/_symbolic_trace.py:1071(revert)
       15    0.000    0.000    0.005    0.000 ~/github/experimental-experiment/experimental_experiment/torch_interpreter/_aten_functions.py:5933(aten_linear)
     8365    0.003    0.000    0.005    0.000 /usr/lib/python3.12/linecache.py:36(getlines)
1625/1540    0.001    0.000    0.005    0.000 {built-in method builtins.all}
     3340    0.002    0.000    0.005    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_pytree.py:1008(_get_node_type)
36370/36320    0.005    0.000    0.005    0.000 {built-in method builtins.len}
    27610    0.005    0.000    0.005    0.000 {method 'append' of 'list' objects}
       55    0.001    0.000    0.005    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:384(mk_fake_tensor)
      750    0.001    0.000    0.005    0.000 <string>:2(__init__)
     1375    0.002    0.000    0.005    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:620(__set__)
     1350    0.002    0.000    0.005    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/meta_utils.py:175(is_sparse_coo)
       50    0.003    0.000    0.004    0.000 ~/github/experimental-experiment/experimental_experiment/xoptim/graph_builder_optim.py:133(_build)
     2425    0.001    0.000    0.004    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_pytree.py:1020(tree_is_leaf)
       20    0.001    0.000    0.004    0.000 ~/github/experimental-experiment/experimental_experiment/helpers.py:234(string_sig)
  385/235    0.001    0.000    0.004    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:1135(create_arg)
     2330    0.001    0.000    0.004    0.000 {built-in method builtins.repr}
      180    0.002    0.000    0.004    0.000 {method 'extend' of 'google._upb._message.RepeatedCompositeContainer' objects}
      250    0.001    0.000    0.004    0.000 ~/github/onnx/onnx/helper.py:127(make_node)
  365/295    0.001    0.000    0.004    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/recording.py:246(wrapper)
       60    0.000    0.000    0.004    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:362(_call_method_with_signature_check)
     1525    0.001    0.000    0.004    0.000 {built-in method builtins.sum}
 1590/920    0.003    0.000    0.004    0.000 {method 'stride' of 'torch._C.TensorBase' objects}
     2370    0.002    0.000    0.004    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:157(create_name)
      130    0.002    0.000    0.004    0.000 ~/github/onnx/onnx/helper.py:1291(np_dtype_to_tensor_dtype)
     1505    0.002    0.000    0.004    0.000 /usr/lib/python3.12/contextlib.py:299(helper)
       55    0.000    0.000    0.004    0.000 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:2550(make_initializer)
      360    0.001    0.000    0.004    0.000 ~/github/experimental-experiment/experimental_experiment/xoptim/patterns/onnx_reshape.py:862(match)
       25    0.002    0.000    0.004    0.000 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:7277(remove_identity_nodes)
      360    0.002    0.000    0.004    0.000 ~/github/experimental-experiment/experimental_experiment/xoptim/patterns/onnx_conv.py:15(match)
      120    0.001    0.000    0.004    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/node.py:374(prepend)
     1215    0.002    0.000    0.004    0.000 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:852(make_key)
    12195    0.003    0.000    0.004    0.000 {built-in method builtins.getattr}
       85    0.000    0.000    0.004    0.000 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:7166(_refresh_values_cache)
       65    0.000    0.000    0.004    0.000 ~/github/experimental-experiment/experimental_experiment/xbuilder/graph_builder.py:6082(_check)
      750    0.001    0.000    0.004    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_pytree.py:1068(__post_init__)
     2615    0.001    0.000    0.004    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/node.py:570(__repr__)
       75    0.001    0.000    0.004    0.000 ~/github/experimental-experiment/experimental_experiment/xoptim/graph_builder_optim.py:1092(_check_graph)
done.
profile custom2: <function export_cus_p2 at 0x7c7709d2a980>
done.

Same with dynamo-exporter.

profile_function("dynamo", export_dynamo, verbose=True)
if "dynopt" in supported_exporters:
    profile_function("dynopt", export_dynopt)
profile dynamo: <function export_dynamo at 0x7c7709955440>
         10932785 function calls (10546901 primitive calls) in 7.125 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        5    0.008    0.002    3.488    0.698 ~/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/exporter/_registration.py:156(from_torchlib)
        5    0.047    0.009    2.658    0.532 ~/github/onnxscript/onnxscript/_framework_apis/torch_2_5.py:82(get_torchlib_ops)
     2455    0.019    0.000    2.601    0.001 ~/github/onnxscript/onnxscript/values.py:630(function_ir)
     2455    0.011    0.000    1.052    0.000 ~/github/onnxscript/onnxscript/_internal/ast_utils.py:13(get_src_and_ast)
       10    0.100    0.010    1.005    0.101 ~/vv/this312/lib/python3.12/site-packages/torch/export/exported_program.py:191(_override_composite_implicit_decomp)
    64635    0.910    0.000    0.958    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_ops.py:131(inner)
       10    0.001    0.000    0.845    0.085 ~/vv/this312/lib/python3.12/site-packages/torch/_export/utils.py:1308(_collect_all_valid_cia_ops)
      250    0.008    0.000    0.844    0.003 ~/vv/this312/lib/python3.12/site-packages/torch/_export/utils.py:1291(_collect_all_valid_cia_ops_for_namespace)
     2455    0.004    0.000    0.786    0.000 ~/github/onnxscript/onnxscript/converter.py:1458(translate_function_signature)
     2930    0.018    0.000    0.785    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/exporter/_registration.py:61(__post_init__)
     2455    0.052    0.000    0.776    0.000 ~/github/onnxscript/onnxscript/converter.py:1373(_translate_function_signature_common)
      250    0.291    0.001    0.774    0.003 ~/vv/this312/lib/python3.12/site-packages/torch/_export/utils.py:1226(_materialize_cpp_cia_ops)
     2930    0.060    0.000    0.757    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/exporter/_schemas.py:432(from_function)
     2455    0.003    0.000    0.748    0.000 /usr/lib/python3.12/inspect.py:1279(getsource)
     2455    0.079    0.000    0.741    0.000 /usr/lib/python3.12/inspect.py:1258(getsourcelines)
     2455    0.055    0.000    0.705    0.000 /usr/lib/python3.12/inspect.py:1606(getclosurevars)
    110/6    0.002    0.000    0.680    0.113 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/meta_utils.py:1844(__call__)
     35/5    0.001    0.000    0.678    0.136 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:2976(from_tensor)
    100/5    0.002    0.000    0.678    0.136 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:347(from_real_tensor)
    79750    0.238    0.000    0.604    0.000 /usr/lib/python3.12/dis.py:434(_get_instructions_bytes)
247675/47970    0.060    0.000    0.568    0.000 {built-in method builtins.next}
 5215/364    0.005    0.000    0.556    0.002 /usr/lib/python3.12/contextlib.py:132(__enter__)
     2455    0.154    0.000    0.535    0.000 /usr/lib/python3.12/inspect.py:1239(getblock)
        5    0.005    0.001    0.493    0.099 ~/vv/this312/lib/python3.12/site-packages/torch/export/exported_program.py:275(_split_decomp_table_to_cia_and_python_decomp)
83165/17030    0.100    0.000    0.485    0.000 ~/github/onnxscript/onnxscript/type_annotation.py:146(is_value_type)
        5    0.006    0.001    0.464    0.093 ~/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/exporter/_decomp.py:37(create_onnx_friendly_decomposition_table)
    25500    0.438    0.000    0.438    0.000 {built-in method builtins.compile}
        5    0.000    0.000    0.422    0.084 ~/vv/this312/lib/python3.12/site-packages/torch/export/decomp_utils.py:137(items)
        5    0.000    0.000    0.422    0.084 ~/vv/this312/lib/python3.12/site-packages/torch/export/decomp_utils.py:154(_materialize_if_needed)
        5    0.001    0.000    0.422    0.084 ~/vv/this312/lib/python3.12/site-packages/torch/export/decomp_utils.py:141(materialize)
    80/20    0.001    0.000    0.364    0.018 ~/vv/this312/lib/python3.12/site-packages/torch/nn/functional.py:1686(relu)
      660    0.103    0.000    0.337    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/functional_tensor.py:356(__torch_dispatch__)
   266270    0.178    0.000    0.334    0.000 /usr/lib/python3.12/tokenize.py:563(_generate_tokens_from_c_tokenizer)
     3710    0.008    0.000    0.318    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:1399(__torch_function__)
     9870    0.006    0.000    0.315    0.000 ~/github/onnxscript/onnxscript/type_annotation.py:187(is_valid_type)
1636810/1628970    0.247    0.000    0.314    0.000 {built-in method builtins.isinstance}
     2930    0.036    0.000    0.263    0.000 /usr/lib/python3.12/typing.py:2219(get_type_hints)
   787525    0.245    0.000    0.249    0.000 {built-in method builtins.getattr}
27955/5390    0.082    0.000    0.248    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/exporter/_schemas.py:268(_get_allowed_types_from_type_annotation)
     2475    0.004    0.000    0.243    0.000 /usr/lib/python3.12/ast.py:34(parse)
    45/15    0.000    0.000    0.224    0.015 ~/vv/this312/lib/python3.12/site-packages/torch/nn/modules/module.py:1779(_call_impl)
        5    0.000    0.000    0.221    0.044 ~/vv/this312/lib/python3.12/site-packages/torch/export/_trace.py:1898(forward)
        5    0.000    0.000    0.212    0.042 ~/github/experimental-experiment/_doc/examples/plot_torch_export_201.py:191(forward)
     1805    0.013    0.000    0.211    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:2067(dispatch)
      625    0.003    0.000    0.211    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:1520(__torch_dispatch__)
    64635    0.034    0.000    0.204    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_ops.py:122(py_impl)
    83165    0.052    0.000    0.200    0.000 ~/github/onnxscript/onnxscript/type_annotation.py:138(_is_tensor_type)
      495    0.003    0.000    0.191    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1448(_cached_dispatch_impl)
      120    0.004    0.000    0.188    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:866(proxy_call)
     7160    0.003    0.000    0.179    0.000 ~/github/onnxscript/onnxscript/type_annotation.py:183(is_attr_type)
   132010    0.102    0.000    0.176    0.000 /usr/lib/python3.12/typing.py:1546(__getitem__)
       95    0.001    0.000    0.165    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph_module.py:807(recompile)
   135/10    0.001    0.000    0.161    0.016 ~/github/ir-py/src/onnx_ir/passes/_pass_infra.py:111(__call__)
    20/10    0.000    0.000    0.161    0.016 ~/github/ir-py/src/onnx_ir/passes/_pass_infra.py:232(call)
   263815    0.085    0.000    0.156    0.000 /usr/lib/python3.12/collections/__init__.py:447(_make)
        5    0.000    0.000    0.152    0.030 ~/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/exporter/_onnx_program.py:313(optimize)
        5    0.000    0.000    0.152    0.030 ~/github/onnxscript/onnxscript/_framework_apis/torch_2_8.py:27(optimize)
        5    0.000    0.000    0.151    0.030 ~/github/onnxscript/onnxscript/optimizer/_optimizer.py:16(optimize_ir)
     1425    0.004    0.000    0.147    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:1428(__torch_function__)
    12050    0.020    0.000    0.147    0.000 ~/github/onnxscript/onnxscript/converter.py:444(_eval_constant_expr)
     2300    0.005    0.000    0.142    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_export/non_strict_utils.py:1048(__torch_function__)
        5    0.000    0.000    0.142    0.028 ~/github/ir-py/src/onnx_ir/passes/_pass_infra.py:273(call)
   159500    0.118    0.000    0.140    0.000 /usr/lib/python3.12/dis.py:623(_unpack_opargs)
    86295    0.042    0.000    0.138    0.000 ~/github/onnxscript/onnxscript/type_annotation.py:85(_remove_annotation)
     3170    0.002    0.000    0.134    0.000 /usr/lib/python3.12/inspect.py:3343(signature)
     3170    0.003    0.000    0.131    0.000 /usr/lib/python3.12/inspect.py:3081(from_callable)
       60    0.001    0.000    0.131    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/_ops.py:952(handler)
       95    0.001    0.000    0.129    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:1635(python_code)
       65    0.007    0.000    0.129    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/_library/utils.py:271(handle_dispatch_mode)
3400/3170    0.019    0.000    0.128    0.000 /usr/lib/python3.12/inspect.py:2501(_signature_from_callable)
      250    0.127    0.001    0.127    0.001 {built-in method torch._C._dispatch_get_registrations_for_dispatch_key}
   128720    0.069    0.000    0.122    0.000 /usr/lib/python3.12/typing.py:2344(get_origin)
     2455    0.037    0.000    0.116    0.000 /usr/lib/python3.12/dis.py:647(findlabels)
     2455    0.019    0.000    0.115    0.000 /usr/lib/python3.12/inspect.py:1070(findsource)
       70    0.001    0.000    0.113    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/_higher_order_ops/utils.py:36(autograd_not_implemented_inner)
     1370    0.003    0.000    0.112    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_pytree.py:1551(tree_map_only)
    40/10    0.000    0.000    0.109    0.011 ~/vv/this312/lib/python3.12/site-packages/torch/_jit_internal.py:617(fn)
     6520    0.004    0.000    0.106    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_export/utils.py:1212(_is_preservable_cia_op)
24415/10880    0.022    0.000    0.104    0.000 /usr/lib/python3.12/typing.py:407(_eval_type)
       95    0.001    0.000    0.104    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:1714(_python_code)
       95    0.009    0.000    0.103    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:431(_gen_python_code)
58135/58085    0.025    0.000    0.103    0.000 {built-in method builtins.repr}
   468290    0.103    0.000    0.103    0.000 {method 'split' of 'str' objects}
      230    0.001    0.000    0.100    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/proxy.py:263(create_proxy)
        5    0.000    0.000    0.097    0.019 ~/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/exporter/_fx_passes.py:22(insert_type_promotion_nodes)
1072090/1071520    0.097    0.000    0.097    0.000 {built-in method builtins.len}
    10880    0.020    0.000    0.096    0.000 /usr/lib/python3.12/typing.py:916(_evaluate)
      240    0.001    0.000    0.095    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:2011(create_node)
      240    0.001    0.000    0.094    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:1171(create_node)
        5    0.000    0.000    0.094    0.019 ~/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/fx/_pass.py:225(run)
        5    0.000    0.000    0.093    0.019 ~/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/fx/passes/type_promotion.py:1648(_run)
    36035    0.016    0.000    0.093    0.000 ~/github/ir-py/src/onnx_ir/_core.py:1900(__hash__)
       10    0.000    0.000    0.092    0.009 ~/github/onnxscript/onnxscript/rewriter/__init__.py:76(call)
       10    0.000    0.000    0.092    0.009 ~/github/onnxscript/onnxscript/rewriter/_rewrite_rule.py:757(apply_to_model)
      120    0.001    0.000    0.092    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/fx/passes/type_promotion.py:1568(run_node)
        5    0.000    0.000    0.091    0.018 ~/vv/this312/lib/python3.12/site-packages/torch/export/exported_program.py:1386(module)
    10880    0.012    0.000    0.091    0.000 /usr/lib/python3.12/typing.py:892(__init__)
        5    0.001    0.000    0.091    0.018 ~/vv/this312/lib/python3.12/site-packages/torch/export/_unlift.py:725(_unlift_exported_program_lifted_states)
     6520    0.051    0.000    0.090    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_export/utils.py:1260(_check_valid_to_preserve)
      240    0.004    0.000    0.089    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/proxy.py:152(create_node)
     3170    0.032    0.000    0.088    0.000 /usr/lib/python3.12/inspect.py:2397(_signature_from_function)
       10    0.002    0.000    0.087    0.009 ~/github/onnxscript/onnxscript/rewriter/_rewrite_rule.py:631(_apply_to_graph_or_function)
     20/5    0.000    0.000    0.084    0.017 {built-in method torch.flatten}
     5740    0.004    0.000    0.084    0.000 ~/github/onnxscript/onnxscript/rewriter/_rewrite_rule.py:301(try_rewrite)
   423695    0.077    0.000    0.077    0.000 {built-in method __new__ of type object at 0xa20960}
      495    0.003    0.000    0.077    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1545(_cache_key)
     5740    0.005    0.000    0.076    0.000 ~/github/onnxscript/onnxscript/rewriter/_rewrite_rule.py:99(match)
  510/250    0.002    0.000    0.073    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/overrides.py:1677(handle_torch_function)
      130    0.000    0.000    0.073    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:656(track_tensor_tree)
 1875/495    0.014    0.000    0.071    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1662(_prep_args_for_hash)
  240/130    0.001    0.000    0.071    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:678(wrap_with_proxy)
      170    0.002    0.000    0.071    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/meta_utils.py:871(meta_tensor)
17155/540    0.028    0.000    0.069    0.000 /usr/lib/python3.12/copy.py:118(deepcopy)
      420    0.001    0.000    0.069    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1996(_output_from_cache_entry)
       10    0.000    0.000    0.068    0.007 ~/vv/this312/lib/python3.12/site-packages/torch/export/_trace.py:523(_produce_aten_artifact)
      440    0.007    0.000    0.067    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1923(_get_output_tensor_from_cache_entry)
     5600    0.006    0.000    0.067    0.000 ~/github/onnxscript/onnxscript/rewriter/_matcher.py:345(match)
     2295    0.007    0.000    0.066    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:645(emit_node)
      665    0.003    0.000    0.066    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/traceback.py:62(__init__)
      980    0.001    0.000    0.065    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/interpreter.py:231(_set_current_node)
    39645    0.028    0.000    0.061    0.000 ~/github/ir-py/src/onnx_ir/_core.py:1908(__repr__)
      980    0.002    0.000    0.061    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/traceback.py:286(set_current_meta)
 1905/535    0.002    0.000    0.060    0.000 /usr/lib/python3.12/copy.py:191(_deepcopy_list)
    22955    0.046    0.000    0.057    0.000 {built-in method builtins.eval}
      180    0.001    0.000    0.057    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_traceback.py:174(summary)
    85235    0.027    0.000    0.056    0.000 {built-in method builtins.issubclass}
     2065    0.003    0.000    0.056    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_pytree.py:1264(tree_flatten)
   227231    0.045    0.000    0.055    0.000 {built-in method builtins.hasattr}
 1560/730    0.006    0.000    0.055    0.000 /usr/lib/python3.12/copy.py:247(_reconstruct)
      230    0.001    0.000    0.054    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:547(set_meta)
      170    0.004    0.000    0.054    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/autograd/grad_mode.py:287(__exit__)
        5    0.001    0.000    0.054    0.011 ~/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/exporter/_core.py:1017(_exported_program_to_onnx_program)
7200/2065    0.012    0.000    0.053    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_pytree.py:1272(helper)
       30    0.001    0.000    0.053    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph_module.py:450(__init__)
  710/610    0.003    0.000    0.052    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/nn/modules/module.py:1968(__setattr__)
     5600    0.004    0.000    0.051    0.000 ~/github/onnxscript/onnxscript/rewriter/_matcher.py:286(_match_single_output_node)
   155165    0.033    0.000    0.051    0.000 /usr/lib/python3.12/inspect.py:302(isclass)
     2455    0.010    0.000    0.049    0.000 /usr/lib/python3.12/textwrap.py:419(dedent)
    91355    0.023    0.000    0.047    0.000 <frozen abc>:117(__instancecheck__)
       10    0.000    0.000    0.047    0.005 ~/vv/this312/lib/python3.12/site-packages/torch/fx/_symbolic_trace.py:634(create_args_for_root)
     1775    0.001    0.000    0.047    0.000 {method 'extend' of 'list' objects}
       30    0.000    0.000    0.047    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph_module.py:563(graph)
   263815    0.047    0.000    0.047    0.000 /usr/lib/python3.12/inspect.py:1196(tokeneater)
      120    0.000    0.000    0.045    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/_symbolic_trace.py:700(<genexpr>)
      110    0.000    0.000    0.045    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/_symbolic_trace.py:697(proxy_placeholder)
      110    0.000    0.000    0.045    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/_symbolic_trace.py:902(_proxy_placeholder)
 1390/560    0.006    0.000    0.045    0.000 /usr/lib/python3.12/copy.py:217(_deepcopy_dict)
        5    0.000    0.000    0.044    0.009 ~/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/exporter/_core.py:746(_translate_fx_graph)
       10    0.000    0.000    0.044    0.004 ~/github/onnxscript/onnxscript/optimizer/_constant_folding.py:1261(call)
       10    0.000    0.000    0.044    0.004 ~/github/onnxscript/onnxscript/optimizer/_constant_folding.py:1237(visit_graph)
5730/5600    0.008    0.000    0.044    0.000 ~/github/onnxscript/onnxscript/rewriter/_matcher.py:132(_match_node)
      110    0.000    0.000    0.044    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/_symbolic_trace.py:906(replace_ph)
      145    0.001    0.000    0.043    0.000 ~/github/onnxscript/onnxscript/optimizer/_constant_folding.py:1227(visit_node)
        5    0.000    0.000    0.043    0.009 ~/vv/this312/lib/python3.12/site-packages/torch/export/_unlift.py:377(_unlift)
       60    0.001    0.000    0.042    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/exporter/_core.py:494(_handle_call_function_node_with_lowering)
      145    0.002    0.000    0.041    0.000 ~/github/onnxscript/onnxscript/optimizer/_constant_folding.py:1058(process_node)
    98520    0.026    0.000    0.041    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_ops.py:850(__hash__)
     1580    0.001    0.000    0.041    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_pytree.py:1490(wrapped)
       20    0.000    0.000    0.041    0.002 {built-in method torch.relu}
     2455    0.009    0.000    0.041    0.000 /usr/lib/python3.12/inspect.py:951(getsourcefile)
       75    0.001    0.000    0.040    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:2286(_dispatch_impl)
   305125    0.040    0.000    0.040    0.000 /usr/lib/python3.12/dis.py:195(_deoptop)
   134740    0.039    0.000    0.039    0.000 /usr/lib/python3.12/typing.py:392(inner)
   163485    0.035    0.000    0.037    0.000 {method 'get' of 'dict' objects}
    75/15    0.000    0.000    0.037    0.002 {built-in method torch._to_functional_tensor}
       15    0.000    0.000    0.037    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/nn/modules/linear.py:130(forward)
    60/15    0.001    0.000    0.037    0.002 {built-in method torch._C._nn.linear}
      180    0.008    0.000    0.037    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_traceback.py:252(_extract_symbolized_tb)
     2455    0.014    0.000    0.036    0.000 /usr/lib/python3.12/dis.py:342(get_instructions)
3825/1300    0.003    0.000    0.036    0.000 ~/github/ir-py/src/onnx_ir/serde.py:96(wrapper)
      620    0.009    0.000    0.036    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1029(_flatten_into)
     8340    0.012    0.000    0.034    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/node.py:903(__setattr__)
      840    0.010    0.000    0.033    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:708(__new__)
    10910    0.020    0.000    0.032    0.000 /usr/lib/python3.12/typing.py:175(_type_check)
      145    0.003    0.000    0.032    0.000 ~/github/onnxscript/onnxscript/optimizer/_constant_folding.py:957(_do_inference)
       95    0.000    0.000    0.032    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph_module.py:97(_forward_from_src)
       95    0.000    0.000    0.032    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph_module.py:103(_method_from_src)
       95    0.000    0.000    0.032    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph_module.py:92(_exec_with_source)
      170    0.006    0.000    0.031    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/autograd/grad_mode.py:283(__enter__)
    70/60    0.000    0.000    0.031    0.001 ~/github/onnxscript/onnxscript/values.py:624(__call__)
      165    0.002    0.000    0.031    0.000 {method 'detach' of 'torch._C.TensorBase' objects}
       55    0.000    0.000    0.031    0.001 ~/vv/this312/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_capture.py:136(_detach_and_copy_item_memo)
161885/160125    0.028    0.000    0.030    0.000 {built-in method builtins.hash}
      230    0.003    0.000    0.030    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/passes/shape_prop.py:40(_extract_tensor_metadata)
    68730    0.015    0.000    0.030    0.000 <frozen abc>:121(__subclasscheck__)
     1155    0.002    0.000    0.030    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:568(_format_args)
    39645    0.012    0.000    0.029    0.000 ~/github/ir-py/src/onnx_ir/_enums.py:366(__repr__)
  2410/16    0.003    0.000    0.028    0.002 ~/vv/this312/lib/python3.12/site-packages/torch/utils/_stats.py:23(wrapper)
       80    0.001    0.000    0.028    0.000 ~/github/onnxscript/onnxscript/values.py:300(__call__)
6205/6170    0.006    0.000    0.028    0.000 {method 'join' of 'str' objects}
 1260/775    0.011    0.000    0.028    0.000 {built-in method torch._ops.prim.}
       80    0.000    0.000    0.027    0.000 ~/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/exporter/_building.py:597(eval)
    11935    0.004    0.000    0.027    0.000 /usr/lib/python3.12/traceback.py:265(__init__)
     8830    0.027    0.000    0.027    0.000 {method 'copy' of 'dict' objects}
    23960    0.026    0.000    0.027    0.000 {built-in method builtins.setattr}
done.
profile dynopt: <function export_dynopt at 0x7c7709d2a700>
done.

Benchmark exported models with ORT

def benchmark(shape):
    from onnxruntime import InferenceSession, SessionOptions, GraphOptimizationLevel

    providers = [["CPUExecutionProvider"]]
    if has_cuda:
        providers.append(["CUDAExecutionProvider", "CPUExecutionProvider"])

    data = []
    data1 = []
    data_mem_load = []
    data_mem_first_run = []
    data_mem_run = []
    confs = list(
        itertools.product(
            [_ for _ in os.listdir(".") if ".onnx" in _ and _.startswith("plot_torch")],
            providers,
            ["0", "1"],
        )
    )
    loop = tqdm(confs)
    print(f"number of experiments: {len(loop)}")
    for name, ps, aot in loop:
        root = os.path.split(name)[-1]
        _, ext = os.path.splitext(root)
        if ext != ".onnx":
            continue

        obs = {}  # system_info()
        obs["name"] = name
        obs["providers"] = ",".join(ps)
        p = "CUDA" if "CUDA" in obs["providers"] else "CPU"
        obs["compute"] = p
        obs["aot"] = 1 if aot == "0" else 0
        obs["export"] = name.replace("plot_torch_export_", "").replace(".onnx", "")

        if not has_cuda and p == "CUDA":
            continue

        onx = onnx.load(name)
        obs["n_nodes"] = len(onx.graph.node)
        obs["n_function"] = len(onx.functions or [])
        obs["n_sub"] = len([n for n in onx.graph.node if n.op_type == "Sub"])
        obs1 = obs.copy()
        short_obs = dict(
            name=obs["name"],
            aot=obs["aot"],
            providers=obs["providers"],
            export=obs["export"],
            compute=obs["compute"],
        )

        opts = SessionOptions()
        opts.add_session_config_entry("session.disable_aot_function_inlining", aot)
        opts.graph_optimization_level = GraphOptimizationLevel.ORT_ENABLE_ALL
        opts.optimized_model_filepath = (
            f"ort-{name.replace('.onnx', '')}-{p.lower()}-aot{1 if aot == '0' else 0}.onnx"
        )

        try:
            InferenceSession(name, opts, providers=ps)
        except Exception as e:
            loop.set_description(f"ERROR-load: {name} {e}")
            obs.update({"error": e, "step": "run"})
            data.append(obs)
            continue

        opts = SessionOptions()
        opts.add_session_config_entry("session.disable_aot_function_inlining", aot)
        opts.graph_optimization_level = GraphOptimizationLevel.ORT_ENABLE_ALL
        stat = start_spying_on(cuda=1 if has_cuda else 0)
        sess = InferenceSession(name, opts, providers=ps)
        memobs = flatten(stat.stop())
        memobs.update(short_obs)
        data_mem_load.append(memobs)

        input_name = sess.get_inputs()[0].name
        feeds = {input_name: np.random.rand(*shape).astype(np.float32)}

        stat = start_spying_on(cuda=1 if has_cuda else 0)
        try:
            sess.run(None, feeds)
        except Exception as e:
            loop.set_description(f"ERROR-run: {name} {e}")
            obs.update({"error": e, "step": "load"})
            data.append(obs)
            stat.stop()
            continue
        memobs = flatten(stat.stop())
        memobs.update(short_obs)
        data_mem_first_run.append(memobs)

        # memory consumption
        stat = start_spying_on(cuda=1 if has_cuda else 0)
        for _ in range(0, script_args.warmup):
            sess.run(None, feeds)
        memobs = flatten(stat.stop())
        memobs.update(short_obs)
        data_mem_run.append(memobs)

        obs.update(
            measure_time(
                lambda sess=sess, feeds=feeds: sess.run(None, feeds),
                max_time=script_args.maxtime,
                repeat=script_args.repeat,
                number=1,
            )
        )

        loop.set_description(f"{obs['average']} {name} {ps}")
        data.append(obs)

        # check first run
        obs1.update(
            measure_time(
                lambda name=name, opts=opts, ps=ps, feeds=feeds: InferenceSession(
                    name, opts, providers=ps
                ).run(None, feeds),
                max_time=script_args.maxtime,
                repeat=max(1, script_args.repeat // 2),
                number=1,
            )
        )
        data1.append(obs1)

    df = pandas.DataFrame(data)
    df.to_csv("plot_torch_export_ort_time.csv", index=False)
    df.to_excel("plot_torch_export_ort_time.xlsx", index=False)
    df1 = pandas.DataFrame(data1)
    df1.to_csv("plot_torch_export_ort_time1_init.csv", index=False)
    df1.to_excel("plot_torch_export_ort_time1_init.xlsx", index=False)
    dfmem = pandas.DataFrame(data_mem_load)
    dfmem.to_csv("plot_torch_export_ort_load_mem.csv", index=False)
    dfmem.to_excel("plot_torch_export_ort_load_mem.xlsx", index=False)
    dfmemr = pandas.DataFrame(data_mem_run)
    dfmemr.to_csv("plot_torch_export_ort_run_mem.csv", index=False)
    dfmemr.to_excel("plot_torch_export_ort_run_mem.xlsx", index=False)
    dfmemfr = pandas.DataFrame(data_mem_first_run)
    dfmemfr.to_csv("plot_torch_export_ort_first_run_mem.csv", index=False)
    dfmemfr.to_excel("plot_torch_export_ort_first_run_mem.xlsx", index=False)
    return df, df1, dfmem, dfmemfr, dfmemr


df, df_init, dfmem, dfmemfr, dfmemr = benchmark(list(input_tensor.shape))
print(df)
  0%|          | 0/20 [00:00<?, ?it/s]number of experiments: 20

5.109725881219859e-05 plot_torch_export_cus_p2.onnx ['CPUExecutionProvider']:   0%|          | 0/20 [00:00<?, ?it/s]
5.109725881219859e-05 plot_torch_export_cus_p2.onnx ['CPUExecutionProvider']:   5%|▌         | 1/20 [00:00<00:08,  2.11it/s]
4.933234798308634e-05 plot_torch_export_cus_p2.onnx ['CPUExecutionProvider']:   5%|▌         | 1/20 [00:00<00:08,  2.11it/s]
4.933234798308634e-05 plot_torch_export_cus_p2.onnx ['CPUExecutionProvider']:  10%|█         | 2/20 [00:01<00:09,  1.96it/s]
0.0007835569666834393 plot_torch_export_cus_p2.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  10%|█         | 2/20 [00:01<00:09,  1.96it/s]
0.0007835569666834393 plot_torch_export_cus_p2.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  15%|█▌        | 3/20 [00:01<00:12,  1.41it/s]
0.0006640205987979041 plot_torch_export_cus_p2.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  15%|█▌        | 3/20 [00:02<00:12,  1.41it/s]
0.0006640205987979041 plot_torch_export_cus_p2.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  20%|██        | 4/20 [00:02<00:11,  1.43it/s]
4.3511229098138176e-05 plot_torch_export_dynopt.onnx ['CPUExecutionProvider']:  20%|██        | 4/20 [00:03<00:11,  1.43it/s]
4.3511229098138176e-05 plot_torch_export_dynopt.onnx ['CPUExecutionProvider']:  25%|██▌       | 5/20 [00:03<00:10,  1.46it/s]
5.9839564298197004e-05 plot_torch_export_dynopt.onnx ['CPUExecutionProvider']:  25%|██▌       | 5/20 [00:03<00:10,  1.46it/s]
5.9839564298197004e-05 plot_torch_export_dynopt.onnx ['CPUExecutionProvider']:  30%|███       | 6/20 [00:03<00:08,  1.63it/s]
0.0007288811475369644 plot_torch_export_dynopt.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  30%|███       | 6/20 [00:04<00:08,  1.63it/s]
0.0007288811475369644 plot_torch_export_dynopt.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  35%|███▌      | 7/20 [00:04<00:07,  1.70it/s]
0.0006755608307568577 plot_torch_export_dynopt.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  35%|███▌      | 7/20 [00:04<00:07,  1.70it/s]
0.0006755608307568577 plot_torch_export_dynopt.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  40%|████      | 8/20 [00:04<00:07,  1.67it/s]
4.84626928052965e-05 plot_torch_export_dynamo.onnx ['CPUExecutionProvider']:  40%|████      | 8/20 [00:05<00:07,  1.67it/s]
4.84626928052965e-05 plot_torch_export_dynamo.onnx ['CPUExecutionProvider']:  45%|████▌     | 9/20 [00:05<00:06,  1.62it/s]
4.827752558244264e-05 plot_torch_export_dynamo.onnx ['CPUExecutionProvider']:  45%|████▌     | 9/20 [00:06<00:06,  1.62it/s]
4.827752558244264e-05 plot_torch_export_dynamo.onnx ['CPUExecutionProvider']:  50%|█████     | 10/20 [00:06<00:06,  1.64it/s]
0.0006871806507992987 plot_torch_export_dynamo.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  50%|█████     | 10/20 [00:06<00:06,  1.64it/s]
0.0006871806507992987 plot_torch_export_dynamo.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  55%|█████▌    | 11/20 [00:06<00:05,  1.66it/s]
0.0007014885672404021 plot_torch_export_dynamo.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  55%|█████▌    | 11/20 [00:07<00:05,  1.66it/s]
0.0007014885672404021 plot_torch_export_dynamo.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  60%|██████    | 12/20 [00:07<00:05,  1.53it/s]
6.274278874718603e-05 plot_torch_export_script.onnx ['CPUExecutionProvider']:  60%|██████    | 12/20 [00:08<00:05,  1.53it/s]
6.274278874718603e-05 plot_torch_export_script.onnx ['CPUExecutionProvider']:  65%|██████▌   | 13/20 [00:08<00:04,  1.54it/s]
4.781118918971687e-05 plot_torch_export_script.onnx ['CPUExecutionProvider']:  65%|██████▌   | 13/20 [00:08<00:04,  1.54it/s]
4.781118918971687e-05 plot_torch_export_script.onnx ['CPUExecutionProvider']:  70%|███████   | 14/20 [00:08<00:03,  1.54it/s]
0.0008197867154660522 plot_torch_export_script.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  70%|███████   | 14/20 [00:09<00:03,  1.54it/s]
0.0008197867154660522 plot_torch_export_script.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  75%|███████▌  | 15/20 [00:09<00:03,  1.59it/s]
0.0006590216666577733 plot_torch_export_script.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  75%|███████▌  | 15/20 [00:10<00:03,  1.59it/s]
0.0006590216666577733 plot_torch_export_script.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  80%|████████  | 16/20 [00:10<00:02,  1.52it/s]
4.8256499396165616e-05 plot_torch_export_cus_p0.onnx ['CPUExecutionProvider']:  80%|████████  | 16/20 [00:10<00:02,  1.52it/s]
4.8256499396165616e-05 plot_torch_export_cus_p0.onnx ['CPUExecutionProvider']:  85%|████████▌ | 17/20 [00:10<00:01,  1.54it/s]
5.895123869771928e-05 plot_torch_export_cus_p0.onnx ['CPUExecutionProvider']:  85%|████████▌ | 17/20 [00:11<00:01,  1.54it/s]
5.895123869771928e-05 plot_torch_export_cus_p0.onnx ['CPUExecutionProvider']:  90%|█████████ | 18/20 [00:11<00:01,  1.49it/s]
0.0006621896103188448 plot_torch_export_cus_p0.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  90%|█████████ | 18/20 [00:11<00:01,  1.49it/s]
0.0006621896103188448 plot_torch_export_cus_p0.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  95%|█████████▌| 19/20 [00:12<00:00,  1.58it/s]
0.0009045872342343304 plot_torch_export_cus_p0.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']:  95%|█████████▌| 19/20 [00:12<00:00,  1.58it/s]
0.0009045872342343304 plot_torch_export_cus_p0.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']: 100%|██████████| 20/20 [00:12<00:00,  1.46it/s]
0.0009045872342343304 plot_torch_export_cus_p0.onnx ['CUDAExecutionProvider', 'CPUExecutionProvider']: 100%|██████████| 20/20 [00:12<00:00,  1.56it/s]
                             name                                   providers compute  ...     ttime context_size  warmup_time
0   plot_torch_export_cus_p2.onnx                        CPUExecutionProvider     CPU  ...  0.105822           64     0.000254
1   plot_torch_export_cus_p2.onnx                        CPUExecutionProvider     CPU  ...  0.108876           64     0.000280
2   plot_torch_export_cus_p2.onnx  CUDAExecutionProvider,CPUExecutionProvider    CUDA  ...  0.117534           64     0.001387
3   plot_torch_export_cus_p2.onnx  CUDAExecutionProvider,CPUExecutionProvider    CUDA  ...  0.110891           64     0.001203
4   plot_torch_export_dynopt.onnx                        CPUExecutionProvider     CPU  ...  0.118133           64     0.000336
5   plot_torch_export_dynopt.onnx                        CPUExecutionProvider     CPU  ...  0.101907           64     0.000244
6   plot_torch_export_dynopt.onnx  CUDAExecutionProvider,CPUExecutionProvider    CUDA  ...  0.133385           64     0.001466
7   plot_torch_export_dynopt.onnx  CUDAExecutionProvider,CPUExecutionProvider    CUDA  ...  0.131734           64     0.001552
8   plot_torch_export_dynamo.onnx                        CPUExecutionProvider     CPU  ...  0.127311           64     0.000238
9   plot_torch_export_dynamo.onnx                        CPUExecutionProvider     CPU  ...  0.128322           64     0.000512
10  plot_torch_export_dynamo.onnx  CUDAExecutionProvider,CPUExecutionProvider    CUDA  ...  0.129877           64     0.001637
11  plot_torch_export_dynamo.onnx  CUDAExecutionProvider,CPUExecutionProvider    CUDA  ...  0.119955           64     0.001632
12  plot_torch_export_script.onnx                        CPUExecutionProvider     CPU  ...  0.118207           64     0.000397
13  plot_torch_export_script.onnx                        CPUExecutionProvider     CPU  ...  0.132676           64     0.000386
14  plot_torch_export_script.onnx  CUDAExecutionProvider,CPUExecutionProvider    CUDA  ...  0.100834           64     0.001657
15  plot_torch_export_script.onnx  CUDAExecutionProvider,CPUExecutionProvider    CUDA  ...  0.104784           64     0.001601
16  plot_torch_export_cus_p0.onnx                        CPUExecutionProvider     CPU  ...  0.120014           64     0.000253
17  plot_torch_export_cus_p0.onnx                        CPUExecutionProvider     CPU  ...  0.139538           64     0.000331
18  plot_torch_export_cus_p0.onnx  CUDAExecutionProvider,CPUExecutionProvider    CUDA  ...  0.141046           64     0.001667
19  plot_torch_export_cus_p0.onnx  CUDAExecutionProvider,CPUExecutionProvider    CUDA  ...  0.100409           64     0.003319

[20 rows x 17 columns]

Other view

def view_time(df, title, suffix="time"):
    piv = pandas.pivot_table(df, index="export", columns=["compute", "aot"], values="average")
    print(piv)
    piv.to_csv(f"plot_torch_export_ort_{suffix}_compute.csv")
    piv.to_excel(f"plot_torch_export_ort_{suffix}_compute.xlsx")

    piv_cpu = pandas.pivot_table(
        df[df.compute == "CPU"],
        index="export",
        columns=["compute", "aot"],
        values="average",
    )

    fig, ax = plt.subplots(1, 2, figsize=(12, 4))
    fig.suptitle(title)
    piv_cpu.plot.barh(ax=ax[0], title="CPU")

    if has_cuda:
        piv_gpu = pandas.pivot_table(
            df[df.compute == "CUDA"],
            index="export",
            columns=["compute", "aot"],
            values="average",
        )
        piv_gpu.plot.barh(ax=ax[1], title="CUDA")

    fig.tight_layout()
    fig.savefig(f"plot_torch_export_ort_{suffix}.png")
    return ax


view_time(df, "Compares onnxruntime time on exported models")
Compares onnxruntime time on exported models, CPU, CUDA
compute       CPU                CUDA
aot             0         1         0         1
export
cus_p0   0.000059  0.000048  0.000905  0.000662
cus_p2   0.000049  0.000051  0.000664  0.000784
dynamo   0.000048  0.000048  0.000701  0.000687
dynopt   0.000060  0.000044  0.000676  0.000729
script   0.000048  0.000063  0.000659  0.000820

array([<Axes: title={'center': 'CPU'}, ylabel='export'>,
       <Axes: title={'center': 'CUDA'}, ylabel='export'>], dtype=object)

New graph without the very long times.

piv_cpu = pandas.pivot_table(
    df[
        (df.compute == "CPU")
        & ((df.aot == 1) | ((df.export != "dynamo") & (df.export != "dynopt")))
    ],
    index="export",
    columns=["compute", "aot"],
    values="average",
)

fig, ax = plt.subplots(1, 2, figsize=(12, 4))
fig.suptitle("Compares onnxruntime time on exported models\nHide dynamo without AOT")
piv_cpu.plot.barh(ax=ax[0], title="CPU")

if has_cuda:
    piv_gpu = pandas.pivot_table(
        df[df.compute == "CUDA"],
        index="export",
        columns=["compute", "aot"],
        values="average",
    )
    piv_gpu.plot.barh(ax=ax[1], title="CUDA")

fig.tight_layout()
fig.savefig("plot_torch_export_ort_time_2.png")
Compares onnxruntime time on exported models Hide dynamo without AOT, CPU, CUDA

Let’s do the same with the loading time + the first run.

view_time(
    df_init,
    "Compares onnxruntime loading time and first run on exported models",
    suffix="time1_init",
)
Compares onnxruntime loading time and first run on exported models, CPU, CUDA
compute       CPU                CUDA
aot             0         1         0         1
export
cus_p0   0.004828  0.003874  0.016517  0.016679
cus_p2   0.003901  0.003057  0.012243  0.021173
dynamo   0.004340  0.003697  0.017251  0.015475
dynopt   0.004941  0.003910  0.014794  0.014722
script   0.004997  0.004826  0.015820  0.016208

array([<Axes: title={'center': 'CPU'}, ylabel='export'>,
       <Axes: title={'center': 'CUDA'}, ylabel='export'>], dtype=object)

Memory Loading Time (ORT)

for compute in ["CPU", "CUDA"]:
    if not has_cuda and compute == "CUDA":
        continue
    ax = memory_peak_plot(
        dfmem[dfmem.compute == compute],
        ("export", "aot"),
        suptitle=f"Memory Consumption of onnxruntime loading time\nrunning on {compute}",
        bars=[model_size * i / 2**20 for i in range(1, 3)],
        figsize=(18, 6),
    )
    get_figure(ax).savefig(f"plot_torch_export_ort_load_mem_{compute}.png")
  • Memory Consumption of onnxruntime loading time running on CPU, Memory peak (Mb), Memory peak - memory begin (Mb), Memory average - memory begin (Mb), GPU Memory peak (Mb), GPU Memory peak - memory begin (Mb), GPU Memory average - memory begin (Mb)
  • Memory Consumption of onnxruntime loading time running on CUDA, Memory peak (Mb), Memory peak - memory begin (Mb), Memory average - memory begin (Mb), GPU Memory peak (Mb), GPU Memory peak - memory begin (Mb), GPU Memory average - memory begin (Mb)

Memory First Running Time (ORT)

for compute in ["CPU", "CUDA"]:
    if not has_cuda and compute == "CUDA":
        continue
    ax = memory_peak_plot(
        dfmemfr[dfmemfr.compute == compute],
        ("export", "aot"),
        suptitle=f"Memory Consumption of onnxruntime first running time"
        f"\nrunning on {compute}",
        bars=[model_size * i / 2**20 for i in range(1, 3)],
        figsize=(18, 6),
    )
    get_figure(ax).savefig(f"plot_torch_export_ort_first_run_mem_{compute}.png")
  • Memory Consumption of onnxruntime first running time running on CPU, Memory peak (Mb), Memory peak - memory begin (Mb), Memory average - memory begin (Mb), GPU Memory peak (Mb), GPU Memory peak - memory begin (Mb), GPU Memory average - memory begin (Mb)
  • Memory Consumption of onnxruntime first running time running on CUDA, Memory peak (Mb), Memory peak - memory begin (Mb), Memory average - memory begin (Mb), GPU Memory peak (Mb), GPU Memory peak - memory begin (Mb), GPU Memory average - memory begin (Mb)

Memory Running Time (ORT)

for compute in ["CPU", "CUDA"]:
    if not has_cuda and compute == "CUDA":
        continue
    ax = memory_peak_plot(
        dfmemr[dfmemr.compute == compute],
        ("export", "aot"),
        suptitle=f"Memory Consumption of onnxruntime running time\nrunning on {compute}",
        bars=[model_size * i / 2**20 for i in range(1, 3)],
        figsize=(18, 6),
    )
    get_figure(ax).savefig(f"plot_torch_export_ort_run_mem_{compute}.png")
  • Memory Consumption of onnxruntime running time running on CPU, Memory peak (Mb), Memory peak - memory begin (Mb), Memory average - memory begin (Mb), GPU Memory peak (Mb), GPU Memory peak - memory begin (Mb), GPU Memory average - memory begin (Mb)
  • Memory Consumption of onnxruntime running time running on CUDA, Memory peak (Mb), Memory peak - memory begin (Mb), Memory average - memory begin (Mb), GPU Memory peak (Mb), GPU Memory peak - memory begin (Mb), GPU Memory average - memory begin (Mb)

Show the interesting models for CPU

script

model = "ort-plot_torch_export_cus_p2-cpu-aot0.onnx"
if os.path.exists(model):
    print(pretty_onnx(onnx.load(model)))
opset: domain='' version=18
opset: domain='ai.onnx.ml' version=5
opset: domain='ai.onnx.training' version=1
opset: domain='ai.onnx.preview.training' version=1
opset: domain='com.microsoft' version=1
opset: domain='com.microsoft.experimental' version=1
opset: domain='com.microsoft.nchwc' version=1
opset: domain='org.pytorch.aten' version=1
input: name='input' type=dtype('float32') shape=[1, 1, 16, 16]
init: name='_onx_concat_max_pool2d_1::Shape:1' type=int64 shape=(2,) -- array([ 1, -1])-- GraphBuilder.constant_folding.from/fold(init7_s1_-1,max_pool2d_1::Shape:1)##max_pool2d_1::Shape:1/##init7_s1_-1/Opset.make_node.1/Shape
init: name='GemmTransposePattern--p_fc1_weight::T10' type=float32 shape=(512, 16)
init: name='GemmTransposePattern--p_fc2_weight::T10' type=float32 shape=(128, 512)
init: name='GemmTransposePattern--p_fc3_weight::T10' type=float32 shape=(10, 128)
init: name='reorder' type=float32 shape=(16, 1, 5, 5)
init: name='conv1.bias' type=float32 shape=(16,)                      -- DynamoInterpret.placeholder.1/P(conv1.bias)
init: name='reorder_token_2' type=float32 shape=(16, 16, 5, 5)
init: name='conv2.bias' type=float32 shape=(16,)                      -- DynamoInterpret.placeholder.1/P(conv2.bias)
init: name='fc1.bias' type=float32 shape=(512,)
init: name='fc2.bias' type=float32 shape=(128,)
init: name='fc3.bias' type=float32 shape=(10,)                        -- DynamoInterpret.placeholder.1/P(fc3.bias)
Conv[com.microsoft.nchwc](input, reorder, conv1.bias, activation=b'Relu', dilations=[1,1], group=1, strides=[1,1], pads=[0,0,0,0], auto_pad=b'NOTSET') -> reorder_token_0
  MaxPool[com.microsoft.nchwc](reorder_token_0, auto_pad=b'NOTSET', storage_order=0, ceil_mode=0, dilations=[1,1], kernel_shape=[2,2], pads=[0,0,0,0], strides=[2,2]) -> reorder_token_1
    Conv[com.microsoft.nchwc](reorder_token_1, reorder_token_2, conv2.bias, activation=b'Relu', dilations=[1,1], group=1, strides=[1,1], pads=[0,0,0,0], auto_pad=b'NOTSET') -> reorder_token_3
      MaxPool[com.microsoft.nchwc](reorder_token_3, auto_pad=b'NOTSET', storage_order=0, ceil_mode=0, dilations=[1,1], kernel_shape=[2,2], pads=[0,0,0,0], strides=[2,2]) -> reorder_token_4
        ReorderOutput[com.microsoft.nchwc](reorder_token_4, channels_last=0, channels=16) -> max_pool2d_1
          Reshape(max_pool2d_1, _onx_concat_max_pool2d_1::Shape:1, allowzero=0) -> flatten
            FusedGemm[com.microsoft](flatten, GemmTransposePattern--p_fc1_weight::T10, fc1.bias, transA=0, alpha=1.00, activation=b'Relu', transB=1, beta=1.00) -> relu_2
              FusedGemm[com.microsoft](relu_2, GemmTransposePattern--p_fc2_weight::T10, fc2.bias, transA=0, alpha=1.00, activation=b'Relu', transB=1, beta=1.00) -> relu_3
                Gemm(relu_3, GemmTransposePattern--p_fc3_weight::T10, fc3.bias, transA=0, alpha=1.00, transB=1, beta=1.00) -> output_0
output: name='output_0' type=dtype('float32') shape=[1, 10]

cus_p2

model = "ort-plot_torch_export_cus_p2-cpu-aot0.onnx"
if os.path.exists(model):
    print(pretty_onnx(onnx.load(model)))
opset: domain='' version=18
opset: domain='ai.onnx.ml' version=5
opset: domain='ai.onnx.training' version=1
opset: domain='ai.onnx.preview.training' version=1
opset: domain='com.microsoft' version=1
opset: domain='com.microsoft.experimental' version=1
opset: domain='com.microsoft.nchwc' version=1
opset: domain='org.pytorch.aten' version=1
input: name='input' type=dtype('float32') shape=[1, 1, 16, 16]
init: name='_onx_concat_max_pool2d_1::Shape:1' type=int64 shape=(2,) -- array([ 1, -1])-- GraphBuilder.constant_folding.from/fold(init7_s1_-1,max_pool2d_1::Shape:1)##max_pool2d_1::Shape:1/##init7_s1_-1/Opset.make_node.1/Shape
init: name='GemmTransposePattern--p_fc1_weight::T10' type=float32 shape=(512, 16)
init: name='GemmTransposePattern--p_fc2_weight::T10' type=float32 shape=(128, 512)
init: name='GemmTransposePattern--p_fc3_weight::T10' type=float32 shape=(10, 128)
init: name='reorder' type=float32 shape=(16, 1, 5, 5)
init: name='conv1.bias' type=float32 shape=(16,)                      -- DynamoInterpret.placeholder.1/P(conv1.bias)
init: name='reorder_token_2' type=float32 shape=(16, 16, 5, 5)
init: name='conv2.bias' type=float32 shape=(16,)                      -- DynamoInterpret.placeholder.1/P(conv2.bias)
init: name='fc1.bias' type=float32 shape=(512,)
init: name='fc2.bias' type=float32 shape=(128,)
init: name='fc3.bias' type=float32 shape=(10,)                        -- DynamoInterpret.placeholder.1/P(fc3.bias)
Conv[com.microsoft.nchwc](input, reorder, conv1.bias, activation=b'Relu', dilations=[1,1], group=1, strides=[1,1], pads=[0,0,0,0], auto_pad=b'NOTSET') -> reorder_token_0
  MaxPool[com.microsoft.nchwc](reorder_token_0, auto_pad=b'NOTSET', storage_order=0, ceil_mode=0, dilations=[1,1], kernel_shape=[2,2], pads=[0,0,0,0], strides=[2,2]) -> reorder_token_1
    Conv[com.microsoft.nchwc](reorder_token_1, reorder_token_2, conv2.bias, activation=b'Relu', dilations=[1,1], group=1, strides=[1,1], pads=[0,0,0,0], auto_pad=b'NOTSET') -> reorder_token_3
      MaxPool[com.microsoft.nchwc](reorder_token_3, auto_pad=b'NOTSET', storage_order=0, ceil_mode=0, dilations=[1,1], kernel_shape=[2,2], pads=[0,0,0,0], strides=[2,2]) -> reorder_token_4
        ReorderOutput[com.microsoft.nchwc](reorder_token_4, channels_last=0, channels=16) -> max_pool2d_1
          Reshape(max_pool2d_1, _onx_concat_max_pool2d_1::Shape:1, allowzero=0) -> flatten
            FusedGemm[com.microsoft](flatten, GemmTransposePattern--p_fc1_weight::T10, fc1.bias, transA=0, alpha=1.00, activation=b'Relu', transB=1, beta=1.00) -> relu_2
              FusedGemm[com.microsoft](relu_2, GemmTransposePattern--p_fc2_weight::T10, fc2.bias, transA=0, alpha=1.00, activation=b'Relu', transB=1, beta=1.00) -> relu_3
                Gemm(relu_3, GemmTransposePattern--p_fc3_weight::T10, fc3.bias, transA=0, alpha=1.00, transB=1, beta=1.00) -> output_0
output: name='output_0' type=dtype('float32') shape=[1, 10]

dynopt

model = "ort-plot_torch_export_dynopt-cpu-aot1.onnx"
if os.path.exists(model):
    print(pretty_onnx(onnx.load(model)))
opset: domain='' version=20
opset: domain='ai.onnx.ml' version=5
opset: domain='ai.onnx.training' version=1
opset: domain='ai.onnx.preview.training' version=1
opset: domain='com.microsoft' version=1
opset: domain='com.microsoft.experimental' version=1
opset: domain='com.microsoft.nchwc' version=1
opset: domain='org.pytorch.aten' version=1
input: name='x' type=dtype('float32') shape=[1, 1, 16, 16]
init: name='reorder' type=float32 shape=(16, 1, 5, 5)
init: name='conv1.bias' type=float32 shape=(16,)
init: name='reorder_token_2' type=float32 shape=(16, 16, 5, 5)
init: name='conv2.bias' type=float32 shape=(16,)
init: name='fc1.weight' type=float32 shape=(512, 16)
init: name='fc1.bias' type=float32 shape=(512,)
init: name='fc2.weight' type=float32 shape=(128, 512)
init: name='fc2.bias' type=float32 shape=(128,)
init: name='fc3.weight' type=float32 shape=(10, 128)
init: name='fc3.bias' type=float32 shape=(10,)
init: name='val_5' type=int64 shape=(2,) -- array([ 1, 16])
Conv[com.microsoft.nchwc](x, reorder, conv1.bias, activation=b'Relu', group=1, strides=[1,1], pads=[0,0,0,0], auto_pad=b'NOTSET', dilations=[1,1]) -> reorder_token_0
  MaxPool[com.microsoft.nchwc](reorder_token_0, pads=[0,0,0,0], kernel_shape=[2,2], ceil_mode=0, auto_pad=b'NOTSET', dilations=[1,1], strides=[2,2], storage_order=0) -> reorder_token_1
    Conv[com.microsoft.nchwc](reorder_token_1, reorder_token_2, conv2.bias, activation=b'Relu', group=1, strides=[1,1], pads=[0,0,0,0], auto_pad=b'NOTSET', dilations=[1,1]) -> reorder_token_3
      MaxPool[com.microsoft.nchwc](reorder_token_3, pads=[0,0,0,0], kernel_shape=[2,2], ceil_mode=0, auto_pad=b'NOTSET', dilations=[1,1], strides=[2,2], storage_order=0) -> reorder_token_4
        ReorderOutput[com.microsoft.nchwc](reorder_token_4, channels_last=0, channels=16) -> max_pool2d_1
          Reshape(max_pool2d_1, val_5, allowzero=1) -> view
            FusedGemm[com.microsoft](view, fc1.weight, fc1.bias, transA=0, alpha=1.00, activation=b'Relu', transB=1, beta=1.00) -> relu_2
              FusedGemm[com.microsoft](relu_2, fc2.weight, fc2.bias, transA=0, alpha=1.00, activation=b'Relu', transB=1, beta=1.00) -> relu_3
                Gemm(relu_3, fc3.weight, fc3.bias, transA=0, alpha=1.00, transB=1, beta=1.00) -> linear_2
output: name='linear_2' type=dtype('float32') shape=[1, 10]

dynamo

model = "ort-plot_torch_export_dynamo-cpu-aot1.onnx"
if os.path.exists(model):
    print(pretty_onnx(onnx.load(model)))
opset: domain='' version=20
opset: domain='ai.onnx.ml' version=5
opset: domain='ai.onnx.training' version=1
opset: domain='ai.onnx.preview.training' version=1
opset: domain='com.microsoft' version=1
opset: domain='com.microsoft.experimental' version=1
opset: domain='com.microsoft.nchwc' version=1
opset: domain='org.pytorch.aten' version=1
input: name='x' type=dtype('float32') shape=[1, 1, 16, 16]
init: name='reorder' type=float32 shape=(16, 1, 5, 5)
init: name='conv1.bias' type=float32 shape=(16,)
init: name='reorder_token_2' type=float32 shape=(16, 16, 5, 5)
init: name='conv2.bias' type=float32 shape=(16,)
init: name='fc1.weight' type=float32 shape=(512, 16)
init: name='fc1.bias' type=float32 shape=(512,)
init: name='fc2.weight' type=float32 shape=(128, 512)
init: name='fc2.bias' type=float32 shape=(128,)
init: name='fc3.weight' type=float32 shape=(10, 128)
init: name='fc3.bias' type=float32 shape=(10,)
init: name='val_5' type=int64 shape=(2,) -- array([ 1, 16])
Conv[com.microsoft.nchwc](x, reorder, conv1.bias, activation=b'Relu', group=1, strides=[1,1], pads=[0,0,0,0], auto_pad=b'NOTSET', dilations=[1,1]) -> reorder_token_0
  MaxPool[com.microsoft.nchwc](reorder_token_0, pads=[0,0,0,0], kernel_shape=[2,2], ceil_mode=0, auto_pad=b'NOTSET', dilations=[1,1], strides=[2,2], storage_order=0) -> reorder_token_1
    Conv[com.microsoft.nchwc](reorder_token_1, reorder_token_2, conv2.bias, activation=b'Relu', group=1, strides=[1,1], pads=[0,0,0,0], auto_pad=b'NOTSET', dilations=[1,1]) -> reorder_token_3
      MaxPool[com.microsoft.nchwc](reorder_token_3, pads=[0,0,0,0], kernel_shape=[2,2], ceil_mode=0, auto_pad=b'NOTSET', dilations=[1,1], strides=[2,2], storage_order=0) -> reorder_token_4
        ReorderOutput[com.microsoft.nchwc](reorder_token_4, channels_last=0, channels=16) -> max_pool2d_1
          Reshape(max_pool2d_1, val_5, allowzero=1) -> view
            FusedGemm[com.microsoft](view, fc1.weight, fc1.bias, transA=0, alpha=1.00, activation=b'Relu', transB=1, beta=1.00) -> relu_2
              FusedGemm[com.microsoft](relu_2, fc2.weight, fc2.bias, transA=0, alpha=1.00, activation=b'Relu', transB=1, beta=1.00) -> relu_3
                Gemm(relu_3, fc3.weight, fc3.bias, transA=0, alpha=1.00, transB=1, beta=1.00) -> linear_2
output: name='linear_2' type=dtype('float32') shape=[1, 10]

Show the interesting models for CUDA

script

model = "ort-plot_torch_export_cus_p2-cuda-aot0.onnx"
if os.path.exists(model):
    print(pretty_onnx(onnx.load(model)))
opset: domain='' version=18
opset: domain='ai.onnx.ml' version=5
opset: domain='ai.onnx.training' version=1
opset: domain='ai.onnx.preview.training' version=1
opset: domain='com.microsoft' version=1
opset: domain='com.microsoft.experimental' version=1
opset: domain='com.microsoft.nchwc' version=1
opset: domain='org.pytorch.aten' version=1
input: name='input' type=dtype('float32') shape=[1, 1, 16, 16]
init: name='_onx_concat_max_pool2d_1::Shape:1' type=int64 shape=(2,) -- array([ 1, -1])-- GraphBuilder.constant_folding.from/fold(init7_s1_-1,max_pool2d_1::Shape:1)##max_pool2d_1::Shape:1/##init7_s1_-1/Opset.make_node.1/Shape
init: name='GemmTransposePattern--p_fc1_weight::T10' type=float32 shape=(512, 16)
init: name='GemmTransposePattern--p_fc2_weight::T10' type=float32 shape=(128, 512)
init: name='GemmTransposePattern--p_fc3_weight::T10' type=float32 shape=(10, 128)
init: name='conv1.weight' type=float32 shape=(16, 1, 5, 5)
init: name='conv1.bias' type=float32 shape=(16,)                      -- DynamoInterpret.placeholder.1/P(conv1.bias)
init: name='conv2.weight' type=float32 shape=(16, 16, 5, 5)
init: name='conv2.bias' type=float32 shape=(16,)                      -- DynamoInterpret.placeholder.1/P(conv2.bias)
init: name='fc1.bias' type=float32 shape=(512,)
init: name='fc2.bias' type=float32 shape=(128,)
init: name='fc3.bias' type=float32 shape=(10,)                        -- DynamoInterpret.placeholder.1/P(fc3.bias)
Conv(input, conv1.weight, conv1.bias, dilations=[1,1], group=1, pads=[0,0,0,0], strides=[1,1]) -> conv2d
  Relu(conv2d) -> relu
    MaxPool(relu, ceil_mode=0, dilations=[1,1], kernel_shape=[2,2], pads=[0,0,0,0], strides=[2,2]) -> max_pool2d
      Conv(max_pool2d, conv2.weight, conv2.bias, dilations=[1,1], group=1, pads=[0,0,0,0], strides=[1,1]) -> conv2d_1
        Relu(conv2d_1) -> relu_1
          MaxPool(relu_1, ceil_mode=0, dilations=[1,1], kernel_shape=[2,2], pads=[0,0,0,0], strides=[2,2]) -> max_pool2d_1
            Reshape(max_pool2d_1, _onx_concat_max_pool2d_1::Shape:1) -> flatten
              Gemm(flatten, GemmTransposePattern--p_fc1_weight::T10, fc1.bias, transB=1) -> linear
                Relu(linear) -> relu_2
                  Gemm(relu_2, GemmTransposePattern--p_fc2_weight::T10, fc2.bias, transB=1) -> linear_1
                    Relu(linear_1) -> relu_3
                      Gemm(relu_3, GemmTransposePattern--p_fc3_weight::T10, fc3.bias, transB=1) -> output_0
output: name='output_0' type=dtype('float32') shape=[1, 10]

cus_p2

model = "ort-plot_torch_export_cus_p2-cuda-aot0.onnx"
if os.path.exists(model):
    print(pretty_onnx(onnx.load(model)))
opset: domain='' version=18
opset: domain='ai.onnx.ml' version=5
opset: domain='ai.onnx.training' version=1
opset: domain='ai.onnx.preview.training' version=1
opset: domain='com.microsoft' version=1
opset: domain='com.microsoft.experimental' version=1
opset: domain='com.microsoft.nchwc' version=1
opset: domain='org.pytorch.aten' version=1
input: name='input' type=dtype('float32') shape=[1, 1, 16, 16]
init: name='_onx_concat_max_pool2d_1::Shape:1' type=int64 shape=(2,) -- array([ 1, -1])-- GraphBuilder.constant_folding.from/fold(init7_s1_-1,max_pool2d_1::Shape:1)##max_pool2d_1::Shape:1/##init7_s1_-1/Opset.make_node.1/Shape
init: name='GemmTransposePattern--p_fc1_weight::T10' type=float32 shape=(512, 16)
init: name='GemmTransposePattern--p_fc2_weight::T10' type=float32 shape=(128, 512)
init: name='GemmTransposePattern--p_fc3_weight::T10' type=float32 shape=(10, 128)
init: name='conv1.weight' type=float32 shape=(16, 1, 5, 5)
init: name='conv1.bias' type=float32 shape=(16,)                      -- DynamoInterpret.placeholder.1/P(conv1.bias)
init: name='conv2.weight' type=float32 shape=(16, 16, 5, 5)
init: name='conv2.bias' type=float32 shape=(16,)                      -- DynamoInterpret.placeholder.1/P(conv2.bias)
init: name='fc1.bias' type=float32 shape=(512,)
init: name='fc2.bias' type=float32 shape=(128,)
init: name='fc3.bias' type=float32 shape=(10,)                        -- DynamoInterpret.placeholder.1/P(fc3.bias)
Conv(input, conv1.weight, conv1.bias, dilations=[1,1], group=1, pads=[0,0,0,0], strides=[1,1]) -> conv2d
  Relu(conv2d) -> relu
    MaxPool(relu, ceil_mode=0, dilations=[1,1], kernel_shape=[2,2], pads=[0,0,0,0], strides=[2,2]) -> max_pool2d
      Conv(max_pool2d, conv2.weight, conv2.bias, dilations=[1,1], group=1, pads=[0,0,0,0], strides=[1,1]) -> conv2d_1
        Relu(conv2d_1) -> relu_1
          MaxPool(relu_1, ceil_mode=0, dilations=[1,1], kernel_shape=[2,2], pads=[0,0,0,0], strides=[2,2]) -> max_pool2d_1
            Reshape(max_pool2d_1, _onx_concat_max_pool2d_1::Shape:1) -> flatten
              Gemm(flatten, GemmTransposePattern--p_fc1_weight::T10, fc1.bias, transB=1) -> linear
                Relu(linear) -> relu_2
                  Gemm(relu_2, GemmTransposePattern--p_fc2_weight::T10, fc2.bias, transB=1) -> linear_1
                    Relu(linear_1) -> relu_3
                      Gemm(relu_3, GemmTransposePattern--p_fc3_weight::T10, fc3.bias, transB=1) -> output_0
output: name='output_0' type=dtype('float32') shape=[1, 10]

dynopt

model = "ort-plot_torch_export_dynopt-cuda-aot1.onnx"
if os.path.exists(model):
    print(pretty_onnx(onnx.load(model)))
opset: domain='' version=20
opset: domain='ai.onnx.ml' version=5
opset: domain='ai.onnx.training' version=1
opset: domain='ai.onnx.preview.training' version=1
opset: domain='com.microsoft' version=1
opset: domain='com.microsoft.experimental' version=1
opset: domain='com.microsoft.nchwc' version=1
opset: domain='org.pytorch.aten' version=1
input: name='x' type=dtype('float32') shape=[1, 1, 16, 16]
init: name='conv1.weight' type=float32 shape=(16, 1, 5, 5)
init: name='conv1.bias' type=float32 shape=(16,)
init: name='conv2.weight' type=float32 shape=(16, 16, 5, 5)
init: name='conv2.bias' type=float32 shape=(16,)
init: name='fc1.weight' type=float32 shape=(512, 16)
init: name='fc1.bias' type=float32 shape=(512,)
init: name='fc2.weight' type=float32 shape=(128, 512)
init: name='fc2.bias' type=float32 shape=(128,)
init: name='fc3.weight' type=float32 shape=(10, 128)
init: name='fc3.bias' type=float32 shape=(10,)
init: name='val_5' type=int64 shape=(2,) -- array([ 1, 16])
Conv(x, conv1.weight, conv1.bias, group=1, pads=[0,0,0,0], auto_pad=b'NOTSET', strides=[1,1], dilations=[1,1]) -> conv2d
  Relu(conv2d) -> relu
    MaxPool(relu, storage_order=0, dilations=[1,1], ceil_mode=0, pads=[0,0,0,0], auto_pad=b'NOTSET', strides=[2,2], kernel_shape=[2,2]) -> max_pool2d
      Conv(max_pool2d, conv2.weight, conv2.bias, group=1, pads=[0,0,0,0], auto_pad=b'NOTSET', strides=[1,1], dilations=[1,1]) -> conv2d_1
        Relu(conv2d_1) -> relu_1
          MaxPool(relu_1, storage_order=0, dilations=[1,1], ceil_mode=0, pads=[0,0,0,0], auto_pad=b'NOTSET', strides=[2,2], kernel_shape=[2,2]) -> max_pool2d_1
            Reshape(max_pool2d_1, val_5, allowzero=1) -> view
              Gemm(view, fc1.weight, fc1.bias, beta=1.00, transB=1, alpha=1.00, transA=0) -> linear
                Relu(linear) -> relu_2
                  Gemm(relu_2, fc2.weight, fc2.bias, beta=1.00, transB=1, alpha=1.00, transA=0) -> linear_1
                    Relu(linear_1) -> relu_3
                      Gemm(relu_3, fc3.weight, fc3.bias, beta=1.00, transB=1, alpha=1.00, transA=0) -> linear_2
output: name='linear_2' type=dtype('float32') shape=[1, 10]

dynamo

model = "ort-plot_torch_export_dynamo-cuda-aot1.onnx"
if os.path.exists(model):
    print(pretty_onnx(onnx.load(model)))
opset: domain='' version=20
opset: domain='ai.onnx.ml' version=5
opset: domain='ai.onnx.training' version=1
opset: domain='ai.onnx.preview.training' version=1
opset: domain='com.microsoft' version=1
opset: domain='com.microsoft.experimental' version=1
opset: domain='com.microsoft.nchwc' version=1
opset: domain='org.pytorch.aten' version=1
input: name='x' type=dtype('float32') shape=[1, 1, 16, 16]
init: name='conv1.weight' type=float32 shape=(16, 1, 5, 5)
init: name='conv1.bias' type=float32 shape=(16,)
init: name='conv2.weight' type=float32 shape=(16, 16, 5, 5)
init: name='conv2.bias' type=float32 shape=(16,)
init: name='fc1.weight' type=float32 shape=(512, 16)
init: name='fc1.bias' type=float32 shape=(512,)
init: name='fc2.weight' type=float32 shape=(128, 512)
init: name='fc2.bias' type=float32 shape=(128,)
init: name='fc3.weight' type=float32 shape=(10, 128)
init: name='fc3.bias' type=float32 shape=(10,)
init: name='val_5' type=int64 shape=(2,) -- array([ 1, 16])
Conv(x, conv1.weight, conv1.bias, group=1, pads=[0,0,0,0], auto_pad=b'NOTSET', strides=[1,1], dilations=[1,1]) -> conv2d
  Relu(conv2d) -> relu
    MaxPool(relu, storage_order=0, dilations=[1,1], ceil_mode=0, pads=[0,0,0,0], auto_pad=b'NOTSET', strides=[2,2], kernel_shape=[2,2]) -> max_pool2d
      Conv(max_pool2d, conv2.weight, conv2.bias, group=1, pads=[0,0,0,0], auto_pad=b'NOTSET', strides=[1,1], dilations=[1,1]) -> conv2d_1
        Relu(conv2d_1) -> relu_1
          MaxPool(relu_1, storage_order=0, dilations=[1,1], ceil_mode=0, pads=[0,0,0,0], auto_pad=b'NOTSET', strides=[2,2], kernel_shape=[2,2]) -> max_pool2d_1
            Reshape(max_pool2d_1, val_5, allowzero=1) -> view
              Gemm(view, fc1.weight, fc1.bias, beta=1.00, transB=1, alpha=1.00, transA=0) -> linear
                Relu(linear) -> relu_2
                  Gemm(relu_2, fc2.weight, fc2.bias, beta=1.00, transB=1, alpha=1.00, transA=0) -> linear_1
                    Relu(linear_1) -> relu_3
                      Gemm(relu_3, fc3.weight, fc3.bias, beta=1.00, transB=1, alpha=1.00, transA=0) -> linear_2
output: name='linear_2' type=dtype('float32') shape=[1, 10]

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

Related examples

101: Profile an existing model with onnxruntime

101: Profile an existing model with onnxruntime

201: Use torch to export a scikit-learn model into ONNX

201: Use torch to export a scikit-learn model into ONNX

101: Onnx Model Optimization based on Pattern Rewriting

101: Onnx Model Optimization based on Pattern Rewriting

101: Some dummy examples with torch.export.export

101: Some dummy examples with torch.export.export

101: A custom backend for torch

101: A custom backend for torch

Gallery generated by Sphinx-Gallery