Note
Go to the end to download the full example code.
201: Evaluate DORT Training¶
It compares DORT to eager mode and onnxrt backend.
To run the script:
python _doc/examples/plot_torch_aot --help
Some helpers¶
import warnings
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 torch._dynamo
import contextlib
import itertools
import os
import gc
import platform
# import pickle
import pprint
import multiprocessing
import time
import cProfile
import pstats
import io
import logging
from pstats import SortKey
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.plotting.memory import memory_peak_plot
from experimental_experiment.ext_test_case import measure_time, get_figure
from experimental_experiment.args import get_parsed_args
from experimental_experiment.memory_peak import start_spying_on
from experimental_experiment.torch_models.training_helper import make_aot_ort
from tqdm import tqdm
has_cuda = has_cuda and torch.cuda.is_available()
logging.disable(logging.ERROR)
def system_info():
obs = {}
obs["processor"] = platform.processor()
obs["cores"] = multiprocessing.cpu_count()
try:
obs["cuda"] = 1 if torch.cuda.is_available() 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
script_args = get_parsed_args(
"plot_torch_aot",
description=__doc__,
scenarios={
"small": "small model to test",
"middle": "55Mb model",
"large": "1Gb model",
},
warmup=5,
repeat=5,
repeat1=(1, "repeat for the first iteration"),
maxtime=(
2,
"maximum time to run a model to measure the computation time, "
"it is 0.1 when scenario is small",
),
expose="scenarios,repeat,repeat1,warmup",
)
if script_args.scenario in (None, "small"):
script_args.maxtime = 0.1
print(f"scenario={script_args.scenario or 'small'}")
print(f"warmup={script_args.warmup}")
print(f"repeat={script_args.repeat}")
print(f"repeat1={script_args.repeat1}")
print(f"maxtime={script_args.maxtime}")
scenario=small
warmup=5
repeat=5
repeat1=1
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, 32, 5)
# self.conv2 = nn.Conv2d(128, 16, 5)
self.fc1 = nn.Linear(30752, 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(144, 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, 32, 5)
# self.conv2 = nn.Conv2d(128, 16, 5)
self.fc1 = nn.Linear(30752, 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)
# 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)), (4, 4))
# 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))
# end of the loop
x = F.relu(self.fc2(x))
y = self.fc3(x)
return y
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)
y = torch.rand((1, 10)).to(torch.float32)
model = MyModelClass(scenario=scenario)
assert model(input_tensor) is not None
return model, (input_tensor, y)
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_tensors = create_model_and_input()
model_size = torch_model_size(model)
print(f"model size={model_size / 2 ** 20} Mb")
model size=0.5401992797851562 Mb
Backends¶
def run(model, tensor_x, tensor_y):
tensor_x = tensor_x.detach()
tensor_y = tensor_y.detach()
for param in model.parameters():
param.grad = None
try:
output = model(tensor_x)
except Exception as e:
raise AssertionError(f"issue with {type(tensor_x)}") from e
loss = F.mse_loss(output, tensor_y)
# return loss
def _backward_():
loss.backward()
_backward_()
return loss, (param.grad for param in model.parameters())
def get_torch_eager(model, *args):
def my_compiler(gm, example_inputs):
return gm.forward
with contextlib.redirect_stdout(io.StringIO()):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
optimized_mod = torch.compile(model, fullgraph=True, backend=my_compiler)
assert run(optimized_mod, *args)
return optimized_mod
def get_torch_default(model, *args):
with contextlib.redirect_stdout(io.StringIO()):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
optimized_mod = torch.compile(model, fullgraph=True, mode="reduce-overhead")
assert run(optimized_mod, *args)
return optimized_mod
def get_torch_dort(model, *args):
with contextlib.redirect_stdout(io.StringIO()):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
local_aot_ort, _ = make_aot_ort(dynamic=True, rewrite=True)
optimized_mod = torch.compile(model, backend=local_aot_ort, fullgraph=True)
run(optimized_mod, *args)
assert run(optimized_mod, *args)
return optimized_mod
Let’s check they are working.
export_functions = [
get_torch_eager,
get_torch_default,
get_torch_dort,
]
exporters = {f.__name__.replace("get_", ""): f for f in export_functions}
supported_exporters = {}
for k, v in exporters.items():
print(f"run function {k}")
filename = f"plot_torch_aot_{k}.onnx"
torch._dynamo.reset()
model, input_tensors = create_model_and_input()
try:
run(model, *input_tensors)
except Exception as e:
print(f"skipped due to {str(e)[:1000]}") # noqa: F821
continue
supported_exporters[k] = v
del model
gc.collect()
time.sleep(1)
run function torch_eager
run function torch_default
run function torch_dort
Compile and 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 in supported_exporters:
print(f"run compile for memory {k} on cpu")
filename = f"plot_torch_aot_{k}.onnx"
if has_cuda:
torch.cuda.set_device(0)
torch._dynamo.reset()
# CPU
model, input_tensors = create_model_and_input()
stat = start_spying_on(cuda=1 if has_cuda else 0)
run(model, *input_tensors)
obs = flatten(stat.stop())
print("done.")
obs.update(dict(export=k, p="cpu"))
data.append(obs)
del model
gc.collect()
time.sleep(1)
if not has_cuda:
continue
torch._dynamo.reset()
# CUDA
model, input_tensors = create_model_and_input()
model = model.cuda()
input_tensors = [i.cuda() for i in input_tensors]
print(f"run compile for memory {k} on cuda")
stat = start_spying_on(cuda=1 if has_cuda else 0)
run(model, *input_tensors)
obs = flatten(stat.stop())
print("done.")
obs.update(dict(export=k, p="cuda"))
data.append(obs)
del model
gc.collect()
time.sleep(1)
run compile for memory torch_eager on cpu
done.
run compile for memory torch_eager on cuda
done.
run compile for memory torch_default on cpu
done.
run compile for memory torch_default on cuda
done.
run compile for memory torch_dort on cpu
done.
run compile for memory torch_dort on cuda
done.
The result.
df1 = pandas.DataFrame(data)
df1.to_csv("plot_torch_aot_1_memory.csv", index=False)
df1.to_excel("plot_torch_aot_1_memory.xlsx", index=False)
print(df1)
for p in ["cpu", "cuda"]:
if not has_cuda and p == "cuda":
continue
ax = memory_peak_plot(
df1[df1["p"] == p],
key=("export",),
bars=[model_size * i / 2**20 for i in range(1, 5)],
suptitle=f"Memory Consumption of the Compilation on {p}\n"
f"model size={model_size / 2**20:1.0f} Mb",
)
get_figure(ax).savefig(f"plot_torch_aot_1_memory_{p}.png")
peak mean n begin end gpu0_peak gpu0_mean gpu0_n gpu0_begin gpu0_end export p
0 6214.968750 6213.976562 4 6214.968750 6212.984375 1527.617188 1527.617188 4 1527.617188 1527.617188 torch_eager cpu
1 6215.484375 6214.239844 5 6212.988281 6215.484375 1555.617188 1548.417187 5 1527.617188 1555.617188 torch_eager cuda
2 6215.488281 6215.478516 4 6215.480469 6215.480469 1555.617188 1555.617188 4 1555.617188 1555.617188 torch_default cpu
3 6215.937500 6215.708984 2 6215.480469 6215.937500 1555.617188 1555.617188 2 1555.617188 1555.617188 torch_default cuda
4 6217.917969 6217.253906 6 6217.917969 6217.917969 1555.617188 1555.617188 6 1555.617188 1555.617188 torch_dort cpu
5 6215.937500 6215.937500 2 6215.937500 6215.937500 1555.617188 1555.617188 2 1555.617188 1555.617188 torch_dort cuda
dort first iteration speed¶
data = []
for k in supported_exporters:
print(f"run dort cpu {k}: {script_args.repeat1}")
times = []
for _ in range(int(script_args.repeat1)):
model, input_tensors = create_model_and_input()
torch._dynamo.reset()
begin = time.perf_counter()
run(model, *input_tensors)
duration = time.perf_counter() - begin
times.append(duration)
del model
gc.collect()
time.sleep(1)
print(f"done: {times[-1]}")
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),
p="cpu",
)
)
if not has_cuda:
continue
print(f"run dort cuda {k}: {script_args.repeat1}")
times = []
for i in range(int(script_args.repeat1)):
model, input_tensors = create_model_and_input()
model = model.cuda()
input_tensors = [i.cuda() for i in input_tensors]
torch._dynamo.reset()
begin = time.perf_counter()
run(model, *input_tensors)
duration = time.perf_counter() - begin
times.append(duration)
del model
gc.collect()
time.sleep(1)
print(f"done: {times[-1]}")
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),
p="cuda",
)
)
run dort cpu torch_eager: 1
done: 0.013733271000091918
run dort cuda torch_eager: 1
done: 0.003229819005355239
run dort cpu torch_default: 1
done: 0.006443742000556085
run dort cuda torch_default: 1
done: 0.0037006040001870133
run dort cpu torch_dort: 1
done: 0.009630859000026248
run dort cuda torch_dort: 1
done: 0.0032553259952692315
The result.
df1 = pandas.DataFrame(data)
df1.to_csv("plot_torch_aot_1_time.csv", index=False)
df1.to_excel("plot_torch_aot_1_time.xlsx", index=False)
print(df1)
fig, ax = plt.subplots(1, 1)
dfi = df1[["export", "p", "time", "std"]].set_index(["export", "p"])
dfi["time"].plot.bar(ax=ax, title="Compilation time", yerr=dfi["std"], rot=30)
fig.tight_layout()
fig.savefig("plot_torch_aot_1_time.png")
export time min max first last std p
0 torch_eager 0.013733 0.013733 0.013733 0.013733 0.013733 0.0 cpu
1 torch_eager 0.003230 0.003230 0.003230 0.003230 0.003230 0.0 cuda
2 torch_default 0.006444 0.006444 0.006444 0.006444 0.006444 0.0 cpu
3 torch_default 0.003701 0.003701 0.003701 0.003701 0.003701 0.0 cuda
4 torch_dort 0.009631 0.009631 0.009631 0.009631 0.009631 0.0 cpu
5 torch_dort 0.003255 0.003255 0.003255 0.003255 0.003255 0.0 cuda
Compilation 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, with_args=True, verbose=False, suffix="export"):
if verbose:
print(f"profile {name}: {export_function}")
if with_args:
model, input_tensors = create_model_and_input()
export_function(model, input_tensors)
pr = cProfile.Profile()
pr.enable()
for _ in range(int(script_args.repeat1)):
export_function(model, input_tensors)
pr.disable()
else:
pr = cProfile.Profile()
pr.enable()
for _ in range(int(script_args.repeat1)):
export_function()
pr.disable()
s = io.StringIO()
sortby = SortKey.CUMULATIVE
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
# with open(f"plot_torch_aot_profile_{name}_{suffix}.pickle", "wb") as f:
# pickle.dump(ps, f)
raw = s.getvalue()
text = "\n".join(raw.split("\n")[:200])
if verbose:
print(text)
with open(f"plot_torch_aot_profile_{name}_{suffix}.txt", "w") as f:
f.write(raw)
root, nodes = profile2graph(ps, clean_text=clean_text)
text = root.to_text()
with open(f"plot_torch_aot_profile_{name}_{suffix}_h.txt", "w") as f:
f.write(text)
if verbose:
print("done.")
model, input_tensors = create_model_and_input()
def function_to_profile(model=model, input_tensors=input_tensors):
return get_torch_dort(model, *input_tensors)
profile_function("dort", function_to_profile, verbose=True, suffix="1")
profile dort: <function function_to_profile at 0x7f62dc3d9b20>
1646076 function calls (1606424 primitive calls) in 1.458 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
13/8 0.000 0.000 0.566 0.071 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/symbolic_convert.py:878(call_function)
16/5 0.000 0.000 0.557 0.111 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/lazy.py:166(realize_and_forward)
1 0.000 0.000 0.438 0.438 /home/xadupre/github/experimental-experiment/experimental_experiment/torch_models/training_helper.py:7(make_aot_ort)
1 0.000 0.000 0.438 0.438 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/onnxruntime.py:763(__init__)
1 0.000 0.000 0.390 0.390 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/_exporter_legacy.py:297(__init__)
1 0.000 0.000 0.263 0.263 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/_exporter_legacy.py:90(__init__)
1 0.001 0.001 0.263 0.263 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/_exporter_legacy.py:114(_initiate_registry_from_torchlib)
1 0.005 0.005 0.260 0.260 /home/xadupre/github/onnxscript/onnxscript/_framework_apis/torch_2_5.py:99(get_torchlib_ops)
184 0.001 0.000 0.253 0.001 /home/xadupre/github/onnxscript/onnxscript/values.py:640(function_ir)
128 0.053 0.000 0.241 0.002 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_subclasses/functional_tensor.py:352(__torch_dispatch__)
593/496 0.001 0.000 0.139 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_ops.py:721(__call__)
1 0.001 0.001 0.127 0.127 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/fx/decomposition_table.py:73(create_onnx_friendly_decomposition_table)
82 0.000 0.000 0.115 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/interpreter.py:290(call_function)
184 0.001 0.000 0.099 0.001 /home/xadupre/github/onnxscript/onnxscript/_internal/ast_utils.py:16(get_src_and_ast)
591/586 0.006 0.000 0.098 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1788(dispatch)
297/276 0.002 0.000 0.097 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:1329(__torch_dispatch__)
2 0.019 0.009 0.096 0.048 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/fx/decomposition_table.py:14(_create_onnx_supports_op_overload_table)
212 0.002 0.000 0.090 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1348(_cached_dispatch_impl)
420/380 0.002 0.000 0.088 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:1231(__torch_function__)
69/54 0.003 0.000 0.081 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:762(proxy_call)
103/35 0.001 0.000 0.079 0.002 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/symbolic_convert.py:935(step)
184 0.000 0.000 0.079 0.000 /home/xadupre/github/onnxscript/onnxscript/converter.py:1463(translate_function_signature)
184 0.005 0.000 0.078 0.000 /home/xadupre/github/onnxscript/onnxscript/converter.py:1378(_translate_function_signature_common)
187730/182143 0.036 0.000 0.077 0.000 {built-in method builtins.isinstance}
13 0.000 0.000 0.074 0.006 {built-in method torch._to_functional_tensor}
1 0.000 0.000 0.073 0.073 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/export/decomp_utils.py:125(items)
1 0.000 0.000 0.073 0.073 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/export/decomp_utils.py:142(_materialize_if_needed)
1 0.000 0.000 0.073 0.073 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/export/decomp_utils.py:129(materialize)
1 0.000 0.000 0.073 0.073 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_export/utils.py:1088(_collect_all_valid_cia_ops)
23 0.001 0.000 0.072 0.003 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_export/utils.py:1071(_collect_all_valid_cia_ops_for_namespace)
12/6 0.000 0.000 0.072 0.012 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/symbolic_convert.py:653(wrapper)
184 0.005 0.000 0.071 0.000 /usr/lib/python3.12/inspect.py:1606(getclosurevars)
12/6 0.000 0.000 0.071 0.012 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/symbolic_convert.py:2341(CALL)
12/6 0.000 0.000 0.070 0.012 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/symbolic_convert.py:2300(_call)
185 0.000 0.000 0.070 0.000 /usr/lib/python3.12/inspect.py:1279(getsource)
185 0.006 0.000 0.069 0.000 /usr/lib/python3.12/inspect.py:1258(getsourcelines)
23 0.025 0.001 0.065 0.003 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_export/utils.py:1006(_materialize_cpp_cia_ops)
8459 0.025 0.000 0.064 0.000 /usr/lib/python3.12/dis.py:434(_get_instructions_bytes)
1 0.000 0.000 0.063 0.063 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_functorch/partitioners.py:1702(min_cut_rematerialization_partition)
14 0.000 0.000 0.057 0.004 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:2594(from_tensor)
314 0.005 0.000 0.057 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/utils/_pytree.py:1152(tree_map_only)
28 0.000 0.000 0.056 0.002 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/symbolic_convert.py:1799(LOAD_ATTR)
4 0.000 0.000 0.054 0.014 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/nn_module.py:851(call_function)
184 0.015 0.000 0.054 0.000 /usr/lib/python3.12/inspect.py:1239(getblock)
27/14 0.001 0.000 0.054 0.004 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:331(from_real_tensor)
2 0.000 0.000 0.053 0.027 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/onnxruntime.py:1099(compile)
28 0.000 0.000 0.053 0.002 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/symbolic_convert.py:1792(_load_attr)
2 0.000 0.000 0.053 0.026 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/passes/infra/partitioner.py:384(partition_and_fuse)
5/4 0.000 0.000 0.053 0.013 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/functions.py:293(call_function)
5/4 0.000 0.000 0.053 0.013 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/functions.py:112(call_function)
5/4 0.000 0.000 0.049 0.012 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/symbolic_convert.py:900(inline_user_function_return)
5/4 0.000 0.000 0.049 0.012 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/symbolic_convert.py:3071(inline_call)
2 0.000 0.000 0.049 0.025 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/passes/infra/partitioner.py:297(fuse_partitions)
2 0.000 0.000 0.049 0.025 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/passes/utils/fuser_utils.py:250(fuse_by_partitions)
5/4 0.000 0.000 0.049 0.012 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/symbolic_convert.py:3108(inline_call_)
30179/29739 0.010 0.000 0.048 0.000 {built-in method builtins.next}
12 0.000 0.000 0.048 0.004 /home/xadupre/github/onnxscript/onnxscript/rewriter/__init__.py:28(rewrite)
7569/1816 0.010 0.000 0.048 0.000 /home/xadupre/github/onnxscript/onnxscript/type_annotation.py:131(is_value_type)
8 0.000 0.000 0.046 0.006 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/fx/_pass.py:240(run)
590 0.003 0.000 0.045 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:1111(create_node)
16630 0.006 0.000 0.045 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/_exporter_legacy.py:199(is_registered_op)
4 0.000 0.000 0.045 0.011 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/fx/passes/type_promotion.py:1696(_run)
12 0.000 0.000 0.043 0.004 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:1569(python_code)
198 0.001 0.000 0.043 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1722(_output_from_cache_entry)
1 0.000 0.000 0.042 0.042 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/backends/common.py:52(_wrapped_bw_compiler)
202 0.004 0.000 0.042 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1656(_get_output_tensor_from_cache_entry)
16689 0.009 0.000 0.040 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/_exporter_legacy.py:177(get_op_functions)
86 0.000 0.000 0.039 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/fx/passes/type_promotion.py:1601(run_node)
397 0.001 0.000 0.039 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:1500(node_copy)
5895/50 0.003 0.000 0.038 0.001 /home/xadupre/github/onnxscript/onnxscript/ir/serde.py:94(wrapper)
12/9 0.000 0.000 0.037 0.004 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/nn/functional.py:1693(relu)
1569 0.037 0.000 0.037 0.000 {built-in method builtins.compile}
9 0.000 0.000 0.036 0.004 {built-in method torch.relu}
12 0.000 0.000 0.035 0.003 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:1646(_python_code)
6246 0.009 0.000 0.035 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/node.py:869(__setattr__)
12 0.003 0.000 0.035 0.003 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:408(_gen_python_code)
4 0.000 0.000 0.035 0.009 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/overrides.py:1669(handle_torch_function)
26790 0.018 0.000 0.034 0.000 /usr/lib/python3.12/tokenize.py:569(_generate_tokens_from_c_tokenizer)
212 0.001 0.000 0.033 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1391(_cache_key)
31/29 0.000 0.000 0.032 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/builtin.py:987(call_function)
8 0.000 0.000 0.032 0.004 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/graph_module.py:792(recompile)
75 0.000 0.000 0.032 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/base.py:445(build)
141 0.000 0.000 0.031 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/lazy.py:61(realize)
6/2 0.000 0.000 0.031 0.016 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/fx/fx_onnx_interpreter.py:393(run_node)
3/2 0.000 0.000 0.031 0.016 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/fx/fx_onnx_interpreter.py:556(placeholder)
3/2 0.000 0.000 0.031 0.016 /home/xadupre/github/onnxscript/onnxscript/function_libs/torch_lib/graph_building/_graph_building_torch.py:613(add_input)
1308/1164 0.001 0.000 0.031 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/base.py:184(__instancecheck__)
29 0.000 0.000 0.031 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/builtin.py:850(builtin_dispatch)
133/104 0.001 0.000 0.031 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/nn/modules/module.py:1932(__setattr__)
28 0.000 0.000 0.031 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/builtin.py:770(call_self_handler)
1022 0.001 0.000 0.031 0.000 /home/xadupre/github/onnxscript/onnxscript/type_annotation.py:172(is_valid_type)
28 0.000 0.000 0.031 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/builtin.py:1632(call_getattr)
75 0.000 0.000 0.031 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/builder.py:369(__call__)
4 0.000 0.000 0.030 0.008 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/passes/utils/fuser_utils.py:95(fuse_as_graphmodule)
13 0.000 0.000 0.030 0.002 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/graph_module.py:548(graph)
2929/2710 0.002 0.000 0.030 0.000 /usr/lib/python3.12/contextlib.py:132(__enter__)
804/219 0.004 0.000 0.030 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1467(_prep_args_for_hash)
67/2 0.000 0.000 0.030 0.015 /home/xadupre/github/onnxscript/onnxscript/function_libs/torch_lib/graph_building/_graph_building_torch.py:270(_wrap_torch_value_to_tensor)
4/2 0.115 0.029 0.030 0.015 /home/xadupre/github/onnxscript/onnxscript/function_libs/torch_lib/graph_building/_graph_building_torch.py:199(dtype)
4/2 0.115 0.029 0.030 0.015 /home/xadupre/github/onnxscript/onnxscript/function_libs/torch_lib/graph_building/_graph_building_torch.py:170(shape)
51/35 0.000 0.000 0.030 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/nn_module.py:1015(var_getattr)
99282 0.028 0.000 0.030 0.000 {built-in method builtins.getattr}
31 0.000 0.000 0.030 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_subclasses/meta_utils.py:1794(__call__)
40 0.001 0.000 0.029 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/builder.py:528(_wrap)
12/9 0.001 0.000 0.029 0.003 {built-in method torch._C._nn.linear}
11595/5368 0.015 0.000 0.029 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/node.py:899(map_aggregate)
35/19 0.000 0.000 0.029 0.002 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/user_defined.py:1019(var_getattr)
31 0.001 0.000 0.028 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_subclasses/meta_utils.py:836(meta_tensor)
167 0.002 0.000 0.028 0.000 /home/xadupre/github/onnxscript/onnxscript/optimizer/_legacy/constant_folding.py:165(process_node)
36 0.000 0.000 0.028 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/lazy.py:20(realize)
10 0.000 0.000 0.027 0.003 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/graph_module.py:437(__init__)
4 0.001 0.000 0.027 0.007 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_functorch/partitioners.py:157(_extract_graph_with_inputs_outputs)
4 0.000 0.000 0.027 0.007 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_functorch/aot_autograd.py:500(convert)
18 0.000 0.000 0.025 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/utils.py:2072(wrap_fake_exception)
614 0.003 0.000 0.025 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/node.py:380(prepend)
3735 0.003 0.000 0.024 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/node.py:890(map_arg)
112 0.001 0.000 0.024 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/proxy.py:209(create_proxy)
20 0.000 0.000 0.024 0.001 /home/xadupre/github/onnxscript/onnxscript/ir/serde.py:461(deserialize_model)
184 0.000 0.000 0.023 0.000 /usr/lib/python3.12/ast.py:34(parse)
31 0.001 0.000 0.023 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/autograd/grad_mode.py:273(__exit__)
632 0.001 0.000 0.023 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/utils/_pytree.py:874(tree_flatten)
42011 0.014 0.000 0.023 0.000 {method 'get' of 'dict' objects}
9 0.000 0.000 0.023 0.003 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/builder.py:1533(wrap_tensor)
1 0.000 0.000 0.022 0.022 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_functorch/partitioners.py:289(_extract_fwd_bwd_modules)
61 0.000 0.000 0.022 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:594(track_tensor_tree)
20 0.001 0.000 0.021 0.001 /home/xadupre/github/onnxscript/onnxscript/ir/serde.py:551(_deserialize_graph)
76/61 0.000 0.000 0.021 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:616(wrap_with_proxy)
12 0.000 0.000 0.021 0.002 /home/xadupre/github/onnxscript/onnxscript/rewriter/pattern.py:1500(apply_to_model)
1973/632 0.006 0.000 0.021 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/utils/_pytree.py:882(helper)
12 0.001 0.000 0.020 0.002 /home/xadupre/github/onnxscript/onnxscript/rewriter/pattern.py:1467(_apply_to_graph_or_function)
9 0.000 0.000 0.020 0.002 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/torch.py:876(call_function)
9993 0.009 0.000 0.020 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/fx/registration.py:55(from_qualified_name)
358/272 0.010 0.000 0.020 0.000 {built-in method torch._ops.prim.}
7569 0.005 0.000 0.020 0.000 /home/xadupre/github/onnxscript/onnxscript/type_annotation.py:123(_is_tensor_type)
20 0.000 0.000 0.019 0.001 /home/xadupre/github/onnxscript/onnxscript/optimizer/_remove_unused_function.py:64(remove_unused_functions)
389 0.003 0.000 0.019 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:634(emit_node)
794 0.000 0.000 0.018 0.000 /home/xadupre/github/onnxscript/onnxscript/type_annotation.py:168(is_attr_type)
2553 0.001 0.000 0.018 0.000 /home/xadupre/github/onnxscript/onnxscript/rewriter/pattern.py:1309(try_rewrite)
114 0.001 0.000 0.016 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/proxy.py:143(create_node)
24 0.000 0.000 0.016 0.001 /home/xadupre/github/onnxscript/onnxscript/optimizer/_legacy/_simple_function_folding.py:30(visit_model)
4 0.000 0.000 0.016 0.004 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/graph_module.py:908(print_readable)
4 0.000 0.000 0.016 0.004 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/graph_module.py:297(_print_readable)
26607 0.009 0.000 0.016 0.000 /usr/lib/python3.12/collections/__init__.py:447(_make)
9 0.000 0.000 0.016 0.002 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/builder.py:2833(wrap_to_fake_tensor_and_record)
4 0.000 0.000 0.015 0.004 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/passes/utils/common.py:27(lift_subgraph_as_module)
448 0.001 0.000 0.015 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/utils/_pytree.py:1101(wrapped)
1377 0.002 0.000 0.015 0.000 /home/xadupre/github/onnxscript/onnxscript/converter.py:451(_eval_constant_expr)
20 0.000 0.000 0.015 0.001 /home/xadupre/github/onnxscript/onnxscript/ir/serde.py:988(serialize_model)
20 0.000 0.000 0.015 0.001 /home/xadupre/github/onnxscript/onnxscript/ir/serde.py:992(serialize_model_into)
120/13 0.001 0.000 0.015 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/interpreter.py:212(run_node)
2929/2710 0.002 0.000 0.015 0.000 /usr/lib/python3.12/contextlib.py:141(__exit__)
9 0.000 0.000 0.015 0.002 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/builder.py:2870(<lambda>)
20 0.001 0.000 0.015 0.001 /home/xadupre/github/onnxscript/onnxscript/ir/serde.py:1153(serialize_graph_into)
65543 0.015 0.000 0.015 0.000 {method 'split' of 'str' objects}
16689 0.006 0.000 0.015 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/fx/registration.py:45(from_name_parts)
18 0.000 0.000 0.015 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/builder.py:2151(wrap_fx_proxy)
17035 0.012 0.000 0.015 0.000 /usr/lib/python3.12/dis.py:623(_unpack_opargs)
18 0.000 0.000 0.015 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/builder.py:2224(wrap_fx_proxy_cls)
6903 0.011 0.000 0.014 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:914(__contains__)
4 0.000 0.000 0.014 0.004 /home/xadupre/github/onnxscript/onnxscript/rewriter/onnxruntime/__init__.py:28(rewrite)
566 0.001 0.000 0.014 0.000 /home/xadupre/github/onnxscript/onnxscript/_legacy_ir/visitor.py:557(process_node)
317 0.005 0.000 0.014 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:678(__new__)
8045 0.004 0.000 0.014 0.000 /home/xadupre/github/onnxscript/onnxscript/type_annotation.py:70(_remove_annotation)
4/3 0.000 0.000 0.014 0.005 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_jit_internal.py:614(fn)
4/3 0.000 0.000 0.014 0.005 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/nn/functional.py:807(_max_pool2d)
2074 0.001 0.000 0.014 0.000 /home/xadupre/github/onnxscript/onnxscript/rewriter/pattern.py:1194(match)
1 0.000 0.000 0.014 0.014 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_functorch/partitioners.py:545(reordering_to_mimic_autograd_engine)
331 0.003 0.000 0.014 0.000 /home/xadupre/github/onnxscript/onnxscript/ir/serde.py:883(_deserialize_node)
261 0.004 0.000 0.014 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:954(_flatten_into)
2 0.000 0.000 0.014 0.007 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/metrics_context.py:37(__exit__)
2 0.000 0.000 0.014 0.007 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/utils.py:1010(record_compilation_metrics)
3 0.000 0.000 0.014 0.005 {built-in method torch.max_pool2d}
887/42 0.002 0.000 0.013 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/utils/_stats.py:15(wrapper)
813/669 0.004 0.000 0.013 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/recording.py:238(wrapper)
31 0.002 0.000 0.013 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/autograd/grad_mode.py:269(__enter__)
2 0.001 0.000 0.013 0.006 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/utils.py:969(_scrubbed_inductor_config_for_logging)
9 0.000 0.000 0.013 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/variables/builder.py:2308(_wrap_fx_proxy)
587/42 0.001 0.000 0.013 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1263(__torch_dispatch__)
16 0.000 0.000 0.013 0.001 /home/xadupre/github/onnxscript/onnxscript/optimizer/_legacy/_simple_function_folding.py:204(inline_simple_functions)
74 0.001 0.000 0.012 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/experimental/proxy_tensor.py:487(set_meta)
59 0.000 0.000 0.012 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/fx/onnxfunction_dispatcher.py:96(dispatch)
191 0.004 0.000 0.012 0.000 /usr/lib/python3.12/dis.py:647(findlabels)
6279 0.012 0.000 0.012 0.000 {built-in method builtins.setattr}
261 0.003 0.000 0.012 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:974(extract_tensor_metadata)
111484/111371 0.011 0.000 0.011 0.000 {built-in method builtins.len}
14 0.000 0.000 0.011 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py:1974(_dispatch_impl)
216/2 0.003 0.000 0.011 0.006 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/onnx/_internal/diagnostics/infra/decorator.py:66(wrapper)
836 0.002 0.000 0.011 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/node.py:576(__update_args_kwargs)
4/3 0.000 0.000 0.011 0.004 {built-in method torch.conv2d}
604 0.003 0.000 0.011 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/node.py:243(__init__)
9 0.000 0.000 0.011 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_dynamo/utils.py:2468(get_fake_value)
15 0.003 0.000 0.011 0.001 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:1706(lint)
48/40 0.001 0.000 0.011 0.000 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_logging/_internal.py:1156(trace_structured)
7 0.000 0.000 0.011 0.002 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/fx/graph.py:1815(eliminate_dead_code)
1 0.000 0.000 0.011 0.011 /home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_functorch/partitioners.py:1465(choose_saved_values_set)
done.
Benchmark exported models with ORT¶
def benchmark(shape):
data = []
data_mem_first_run = []
data_mem_run = []
confs = list(
itertools.product(
export_functions,
["CPU", "CUDA"],
)
)
loop = tqdm(confs)
print(f"number of experiments: {len(loop)}")
for export_fct, p in loop:
name = export_fct.__name__.replace("get_torch_", "")
obs = {} # system_info()
obs["name"] = name
obs["compute"] = p
obs["export"] = name
model, input_tensors = create_model_and_input()
if p == "CUDA":
if not has_cuda:
continue
model = model.cuda()
input_tensors = [i.cuda() for i in input_tensors]
try:
exported_model = export_fct(model, *input_tensors)
except Exception as e:
obs["error"] = str(e)
data.append(obs)
continue
def call_model(
export_fct=export_fct,
exported_model=exported_model,
input_tensors=input_tensors,
):
res = run(exported_model, *input_tensors)
return res
stat = start_spying_on(cuda=1 if has_cuda else 0)
try:
call_model()
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(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):
call_model()
memobs = flatten(stat.stop())
memobs.update(obs)
data_mem_run.append(memobs)
obs.update(
measure_time(
call_model,
max_time=script_args.maxtime,
repeat=script_args.repeat,
number=1,
)
)
profile_function(name, call_model, with_args=False, suffix=f"run_{p}")
loop.set_description(f"{obs['average']} {name} {p}")
data.append(obs)
del model
del exported_model
gc.collect()
time.sleep(1)
df = pandas.DataFrame(data)
df.to_csv("plot_torch_aot_ort_time.csv", index=False)
df.to_excel("plot_torch_aot_ort_time.xlsx", index=False)
dfmemr = pandas.DataFrame(data_mem_run)
dfmemr.to_csv("plot_torch_aot_ort_run_mem.csv", index=False)
dfmemr.to_excel("plot_torch_aot_ort_run_mem.xlsx", index=False)
dfmemfr = pandas.DataFrame(data_mem_first_run)
dfmemfr.to_csv("plot_torch_aot_ort_first_run_mem.csv", index=False)
dfmemfr.to_excel("plot_torch_aot_ort_first_run_mem.xlsx", index=False)
return df, dfmemfr, dfmemr
df, dfmemfr, dfmemr = benchmark(list(input_tensors[0].shape))
print(df)
0%| | 0/6 [00:00<?, ?it/s]number of experiments: 6
0.00794258526681612 eager CPU: 0%| | 0/6 [00:00<?, ?it/s]
0.00794258526681612 eager CPU: 17%|█▋ | 1/6 [00:02<00:10, 2.09s/it]
0.0016601794712438151 eager CUDA: 17%|█▋ | 1/6 [00:02<00:10, 2.09s/it]
0.0016601794712438151 eager CUDA: 33%|███▎ | 2/6 [00:03<00:07, 1.95s/it]
0.003066049212065991 default CPU: 33%|███▎ | 2/6 [00:10<00:07, 1.95s/it]
0.003066049212065991 default CPU: 50%|█████ | 3/6 [00:11<00:13, 4.48s/it]
0.0009188867391734992 default CUDA: 50%|█████ | 3/6 [00:14<00:13, 4.48s/it]
0.0009188867391734992 default CUDA: 67%|██████▋ | 4/6 [00:15<00:08, 4.49s/it]/home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/utils.py:130: UserWarning: Your compiler for AOTAutograd is returning a function that doesn't take boxed arguments. Please wrap it with functorch.compile.make_boxed_func or handle the boxed arguments yourself. See https://github.com/pytorch/pytorch/pull/83137#issuecomment-1211320670 for rationale.
warnings.warn(
0.007436426933660793 dort CPU: 67%|██████▋ | 4/6 [00:17<00:08, 4.49s/it]
0.007436426933660793 dort CPU: 83%|████████▎ | 5/6 [00:18<00:03, 3.87s/it]/home/xadupre/vv/this312/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/utils.py:130: UserWarning: Your compiler for AOTAutograd is returning a function that doesn't take boxed arguments. Please wrap it with functorch.compile.make_boxed_func or handle the boxed arguments yourself. See https://github.com/pytorch/pytorch/pull/83137#issuecomment-1211320670 for rationale.
warnings.warn(
0.0022984157872765246 dort CUDA: 83%|████████▎ | 5/6 [00:19<00:03, 3.87s/it]
0.0022984157872765246 dort CUDA: 100%|██████████| 6/6 [00:21<00:00, 3.44s/it]
0.0022984157872765246 dort CUDA: 100%|██████████| 6/6 [00:21<00:00, 3.55s/it]
name compute export average deviation min_exec max_exec repeat number ttime context_size warmup_time
0 eager CPU eager 0.007943 0.000809 0.005892 0.008800 1 15.0 0.119139 64 0.004668
1 eager CUDA eager 0.001660 0.000099 0.001617 0.002248 1 87.0 0.144436 64 0.002504
2 default CPU default 0.003066 0.000195 0.002558 0.003893 1 33.0 0.101180 64 0.016288
3 default CUDA default 0.000919 0.000089 0.000791 0.001173 1 115.0 0.105672 64 0.002153
4 dort CPU dort 0.007436 0.000757 0.005811 0.008106 1 15.0 0.111546 64 0.002948
5 dort CUDA dort 0.002298 0.000105 0.002260 0.002949 1 47.0 0.108026 64 0.004351
Other view
def view_time(df, title, suffix="time"):
piv = pandas.pivot_table(df, index="export", columns=["compute"], values="average")
print(piv)
piv.to_csv(f"plot_torch_aot_{suffix}_compute.csv")
piv.to_excel(f"plot_torch_aot_{suffix}_compute.xlsx")
piv_cpu = pandas.pivot_table(
df[df.compute == "CPU"],
index="export",
columns=["compute"],
values="average",
)
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
fig.suptitle(title)
piv_cpu.plot.barh(ax=ax[0], title="CPU", logx=True)
if has_cuda:
piv_gpu = pandas.pivot_table(
df[df.compute == "CUDA"],
index="export",
columns=["compute"],
values="average",
)
piv_gpu.plot.barh(ax=ax[1], title="CUDA", logx=True)
fig.tight_layout()
fig.savefig(f"plot_torch_aot_{suffix}.png")
return ax
view_time(df, "Compares processing time on backends")
compute CPU CUDA
export
default 0.003066 0.000919
dort 0.007436 0.002298
eager 0.007943 0.001660
array([<Axes: title={'center': 'CPU'}, ylabel='export'>,
<Axes: title={'center': 'CUDA'}, ylabel='export'>], dtype=object)
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",),
suptitle=f"Memory Consumption of backend, 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_aot_first_run_mem_{compute}.png")
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",),
suptitle=f"Memory Consumption of backens, 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_aot_run_mem_{compute}.png")
Total running time of the script: (0 minutes 48.478 seconds)
Related examples
201: Evaluate DORT
201: Evaluate different ways to export a torch model to ONNX
201: Evaluate different ways to export a torch model to ONNX
101: Profile an existing model with onnxruntime
101: Profile an existing model with onnxruntime