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)
return {
}
input_names=["input"],
output_names=["output"],
external_data=False,
dynamo=True
)
print("calling torch.onnx.export with parameters",kwargs)
try:
print("model exported to ONNX as",modelFile)
return modelFile
except TypeError:
print("Skip tutorial execution")
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
raiseError(
'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.2665609 -0.5483359 -0.7554795 0.8489792 1.2839893 0.27063927
-1.490416 -1.1734604 -0.5355978 -0.05200399 0.4630398 2.0338717
-0.9871244 0.9388966 1.232024 1.6938746 0.2705685 0.05303876
-0.7797969 0.15409304 0.44651073 3.350963 -0.3746963 0.2332477
0.2092952 -0.6054465 0.0741356 -0.8616909 2.283162 0.9177138
-0.42378515 0.7737654 ]]
-> output using SOFIE = [0.4873852 0.5126147]
Missing ONNXRuntime: skipping comparison test
- Author
- Lorenzo Moneta
Definition in file TMVA_SOFIE_ONNX.py.