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 torch
import ROOT
import numpy as np
import inspect
)
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 [[-6.01221144e-01 1.19053714e-01 -2.45943832e+00 2.12796196e-01
3.59251350e-01 1.69989944e+00 -1.45543015e+00 -2.42614836e-01
2.40988610e-03 -5.08478820e-01 3.93389344e+00 1.12916040e+00
-4.54266518e-01 -6.74715400e-01 5.57646573e-01 1.61057740e-01
4.01047081e-01 -2.17865658e+00 -4.93074208e-01 4.91779983e-01
6.03726096e-02 1.46321520e-01 -8.50548074e-02 3.65753442e-01
-1.35761845e+00 7.16157615e-01 2.67857730e-01 1.38448700e-01
1.31619394e+00 3.28651786e-01 2.88355619e-01 1.74426639e+00]]
-> output using SOFIE = [0.41176823 0.5882318 ]
Missing ONNXRuntime: skipping comparison test
- Author
- Lorenzo Moneta
Definition in file TMVA_SOFIE_ONNX.py.