This macro provides a simple example for:
- creating a model with Pytorch and export to ONNX
- parsing the ONNX file with SOFIE and generate C++ code
- compiling the model using ROOT Cling
- run the code and optionally compare with ONNXRuntime
import inspect
import numpy as np
import ROOT
import torch
y_pred = model(x)
modelFile = modelName + ".onnx"
model(dummy_x)
input_names=["input"],
output_names=["output"],
external_data=False,
dynamo=True,
)
print("calling torch.onnx.export with parameters", kwargs)
print("model exported to ONNX as", modelFile)
return modelFile
if verbose:
print("0weight", data)
print("2weight", data)
if verbose:
print("Generated model header file ", modelCode)
return modelCode
modelName = "LinearModel"
sofie =
getattr(ROOT,
"TMVA_SOFIE_" + modelName)
print("\n************************************************************")
print("Running inference with SOFIE ")
print("\ninput to model is ", x)
print("-> output using SOFIE = ", y_sofie)
try:
import onnxruntime as ort
print("Running inference with ONNXRuntime ")
y_ort = outputs[0]
print("-> output using ORT =", y_ort)
testFailed = abs(y_sofie - y_ort) > 0.01
raise RuntimeError(
"Result is different between SOFIE and ONNXRT")
else:
print("OK")
except ImportError:
print("Missing ONNXRuntime: skipping comparison test")
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
calling torch.onnx.export with parameters {'input_names': ['input'], 'output_names': ['output'], 'external_data': False, 'dynamo': True}
[torch.onnx] Obtain model graph for `Sequential([...]` with `torch.export.export(..., strict=False)`...
[torch.onnx] Obtain model graph for `Sequential([...]` with `torch.export.export(..., strict=False)`... ✅
[torch.onnx] Run decompositions...
[torch.onnx] Run decompositions... ✅
[torch.onnx] Translate the graph into ONNX...
[torch.onnx] Translate the graph into ONNX... ✅
[torch.onnx] Optimize the ONNX graph...
[torch.onnx] Optimize the ONNX graph... ✅
model exported to ONNX as LinearModel.onnx
Generated model header file LinearModel.hxx
************************************************************
Running inference with SOFIE
input to model is [[-1.6602433 1.2427353 3.5806966 -1.651341 1.231087 1.6040536
0.7551528 0.8745446 0.15802068 -1.1301984 -1.3030363 -1.9053272
1.465862 -0.6698467 -0.14333288 -2.253695 0.8838225 -1.5403255
-0.43727115 0.502984 -1.038776 -0.57028157 -0.4334797 0.77547747
-1.5230148 1.2906015 -0.94456315 0.43685406 -0.0357208 -0.9652042
1.0397481 0.7497735 ]]
-> output using SOFIE = [0.48080128 0.5191987 ]
Missing ONNXRuntime: skipping comparison test
- Author
- Lorenzo Moneta
Definition in file TMVA_SOFIE_ONNX.py.