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 [[-1.5626997e-01 -1.0246775e+00 2.2545328e+00 -1.8436207e+00
-7.8209174e-01 6.8553740e-01 1.0100849e+00 4.6164967e-02
5.9960908e-01 1.6526457e+00 -1.5629822e+00 -3.2810596e-01
1.2968576e-01 -1.7728367e+00 7.1812904e-01 4.8971954e-01
1.6294963e+00 -1.5744703e+00 -2.6187068e-01 -2.8629309e-01
-1.8896052e-01 3.8288784e-01 1.9680183e-02 -7.0164871e-01
-1.2696911e+00 -1.4824054e+00 6.4289284e-01 -7.5982800e-03
-4.4402620e-01 -9.9570513e-01 -2.8915584e-01 1.9825464e-04]]
-> output using SOFIE = [0.52278346 0.47721657]
Missing ONNXRuntime: skipping comparison test
- Author
- Lorenzo Moneta
Definition in file TMVA_SOFIE_ONNX.py.