22def CreateAndTrainModel(modelName):
24 model = nn.Sequential(nn.Linear(32, 16), nn.ReLU(), nn.Linear(16, 8), nn.ReLU(), nn.Linear(8, 2), nn.Softmax(dim=1))
26 criterion = nn.MSELoss()
27 optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
31 x = torch.randn(2, 32)
34 loss = criterion(y_pred, y)
46 modelFile = modelName +
".onnx"
47 dummy_x = torch.randn(1, 32)
51 def filtered_kwargs(func, **candidate_kwargs):
52 sig = inspect.signature(func)
53 return {k: v
for k, v
in candidate_kwargs.items()
if k
in sig.parameters}
55 kwargs = filtered_kwargs(
57 input_names=[
"input"],
58 output_names=[
"output"],
62 print(
"calling torch.onnx.export with parameters", kwargs)
64 torch.onnx.export(model, dummy_x, modelFile, **kwargs)
66 print(
"model exported to ONNX as", modelFile)
70def ParseModel(modelFile, verbose=False):
72 parser = ROOT.TMVA.Experimental.SOFIE.RModelParser_ONNX()
73 model = parser.Parse(modelFile, verbose)
77 model.PrintInitializedTensors()
78 data = model.GetTensorData[
"float"](
"0weight")
79 print(
"0weight", data)
80 data = model.GetTensorData[
"float"](
"2weight")
81 print(
"2weight", data)
86 model.OutputGenerated()
88 model.PrintGenerated()
90 modelCode = modelFile.replace(
".onnx",
".hxx")
91 print(
"Generated model header file ", modelCode)
100modelName =
"LinearModel"
101modelFile = CreateAndTrainModel(modelName)
107modelCode = ParseModel(modelFile,
False)
113ROOT.gInterpreter.Declare(
'#include "' + modelCode +
'"')
120sofie = getattr(ROOT,
"TMVA_SOFIE_" + modelName)
121session = sofie.Session()
123x = np.random.normal(0, 1, (1, 32)).astype(np.float32)
124print(
"\n************************************************************")
125print(
"Running inference with SOFIE ")
126print(
"\ninput to model is ", x)
129y_sofie = np.asarray(y.data())
130print(
"-> output using SOFIE = ", y_sofie)
134 import onnxruntime
as ort
137 print(
"Running inference with ONNXRuntime ")
138 ort_session = ort.InferenceSession(modelFile)
141 outputs = ort_session.run(
None, {
"input": x})
143 print(
"-> output using ORT =", y_ort)
145 testFailed = abs(y_sofie - y_ort) > 0.01
146 if np.any(testFailed):
147 raise RuntimeError(
"Result is different between SOFIE and ONNXRT")
152 print(
"Missing ONNXRuntime: skipping comparison test")