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.367764 0.50571823 0.656371 -0.1435604 2.6970513 0.6069507
-0.08378253 -0.08815525 -0.9546562 0.36806196 1.5668218 -0.8092264
1.2457751 0.5912777 -1.4591385 0.6704636 0.9441589 -0.66921526
-0.53377193 -0.37346548 0.4413543 1.0838823 0.26820326 -0.02907695
-0.44410625 0.94629586 0.7192299 -0.26345798 0.47244576 -1.5309932
-1.0469879 -0.23127167]]
-> output using SOFIE = [0.4874975 0.51250255]
Missing ONNXRuntime: skipping comparison test
- Author
- Lorenzo Moneta
Definition in file TMVA_SOFIE_ONNX.py.