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 decomposition...
[torch.onnx] Run decomposition... ✅
[torch.onnx] Translate the graph into ONNX...
[torch.onnx] Translate the graph into ONNX... ✅
model exported to ONNX as LinearModel.onnx
Generated model header file LinearModel.hxx
************************************************************
Running inference with SOFIE
input to model is [[-0.18047772 0.17348063 -0.07630027 -0.55267006 -0.5652245 -0.35257247
-1.0806302 1.1162996 -0.28454325 0.63076913 -1.3105878 -2.4822302
0.857104 -0.6696996 0.1289086 -0.90326995 -1.2128385 -0.21306907
-0.71965474 0.81060654 -0.4187087 -0.04138555 0.6495054 -1.1164687
-1.1618471 -1.110425 -0.04759007 -0.13346122 0.52079695 -0.11834884
-0.04220404 2.3678155 ]]
-> output using SOFIE = [0.47339082 0.5266092 ]
Missing ONNXRuntime: skipping comparison test
- Author
- Lorenzo Moneta
Definition in file TMVA_SOFIE_ONNX.py.