Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RSofieReader.hxx
Go to the documentation of this file.
1/**********************************************************************************
2 * Project: ROOT - a Root-integrated toolkit for multivariate data analysis *
3 * Package: TMVA * *
4 * *
5 * Description: *
6 * *
7 * Authors: *
8 * Lorenzo Moneta *
9 * *
10 * Copyright (c) 2022: *
11 * CERN, Switzerland *
12 * *
13 **********************************************************************************/
14
15
16#ifndef TMVA_RSOFIEREADER
17#define TMVA_RSOFIEREADER
18
19
20#include <string>
21#include <vector>
22#include <memory> // std::unique_ptr
23#include <sstream> // std::stringstream
24#include <iostream>
25#include "TROOT.h"
26#include "TSystem.h"
27#include "TError.h"
28#include "TInterpreter.h"
29#include "TUUID.h"
30#include "TMVA/RTensor.hxx"
31#include "Math/Util.h"
32
33namespace TMVA {
34namespace Experimental {
35
36
37
38
39/// TMVA::RSofieReader class for reading external Machine Learning models
40/// in ONNX files, Keras .h5 or .keras files or PyTorch .pt files
41/// and performing the inference using SOFIE
42/// It is reccomended to use ONNX if possible since there is a larger support for
43/// model operators.
44
46
47
48public:
49 /// Dummy constructor which needs model loading afterwards
51 /// Create TMVA model from ONNX file
52 /// print level can be 0 (minimal) 1 with info , 2 with all ONNX parsing info
53 RSofieReader(const std::string &path, std::vector<std::vector<size_t>> inputShapes = {}, int verbose = 0)
54 {
55 Load(path, inputShapes, verbose);
56 }
57
58 void Load(const std::string &path, std::vector<std::vector<size_t>> inputShapes = {}, int verbose = 0)
59 {
60
61 enum EModelType {kONNX, kKeras, kPt, kROOT, kNotDef}; // type of model
63
64 size_t pos2 = std::string::npos;
65 if ( (pos2 = path.find(".onnx")) != std::string::npos) {
66 if (verbose) std::cout << "input model type is ONNX" << std::endl;
67 type = kONNX;
68 } else if ( (pos2 = path.find(".h5")) != std::string::npos || (pos2 = path.find(".keras")) != std::string::npos) {
69 if (verbose) std::cout << "input model type is Keras" << std::endl;
70 type = kKeras;
71 } else if ( (pos2 = path.find(".pt")) != std::string::npos) {
72 if (verbose) std::cout << "input model type is PyTorch" << std::endl;
73 type = kPt;
74 } else if ( (pos2 = path.find(".root")) != std::string::npos) {
75 if (verbose) std::cout << "input model type is ROOT" << std::endl;
76 type = kROOT;
77 }
78
79 if (type == kNotDef) {
80 throw std::runtime_error("Input file is not an ONNX or Keras or PyTorch file");
81 }
82 auto pos1 = path.rfind("/");
83 if (pos1 == std::string::npos)
84 pos1 = 0;
85 else
86 pos1 += 1;
87 std::string modelName = path.substr(pos1,pos2-pos1);
88 std::string fileType = path.substr(pos2+1, path.length()-pos2-1);
89 if (verbose) std::cout << "Parsing SOFIE model " << modelName << " of type " << fileType << std::endl;
90
91 // create code for parsing model and generate C++ code for inference
92 // make it in a separate scope to avoid polluting global interpreter space
93 std::string parserCode;
94 if (type == kONNX) {
95 // check first if we can load the SOFIE parser library
96 if (gSystem->Load("libROOTTMVASofieParser") < 0) {
97 throw std::runtime_error("RSofieReader: cannot use SOFIE with ONNX since libROOTTMVASofieParser is missing");
98 }
99 gInterpreter->Declare("#include \"TMVA/RModelParser_ONNX.hxx\"");
100 parserCode += "{\nTMVA::Experimental::SOFIE::RModelParser_ONNX parser ; \n";
101 if (verbose == 2)
102 parserCode += "TMVA::Experimental::SOFIE::RModel model = parser.Parse(\"" + path + "\",true); \n";
103 else
104 parserCode += "TMVA::Experimental::SOFIE::RModel model = parser.Parse(\"" + path + "\"); \n";
105 }
106 else if (type == kKeras) {
107 // use Keras direct parser
108 if (gSystem->Load("libROOTTMVASofiePyParsers") < 0) {
109 throw std::runtime_error("RSofieReader: cannot use SOFIE with Keras since libROOTTMVASofiePyParsers is missing");
110 }
111 // assume batch size is first entry in first input !
112 std::string batch_size = "-1";
113 if (!inputShapes.empty() && ! inputShapes[0].empty())
114 batch_size = std::to_string(inputShapes[0][0]);
115 parserCode += "{\nTMVA::Experimental::SOFIE::RModel model = TMVA::Experimental::SOFIE::PyKeras::Parse(\"" + path +
116 "\"," + batch_size + "); \n";
117 }
118 else if (type == kPt) {
119 // use PyTorch direct parser
120 if (gSystem->Load("libROOTTMVASofiePyParsers") < 0) {
121 throw std::runtime_error("RSofieReader: cannot use SOFIE with PyTorch since libROOTTMVASofiePyParsers is missing");
122 }
123 if (inputShapes.size() == 0) {
124 throw std::runtime_error("RSofieReader: cannot use SOFIE with PyTorch since the input tensor shape is missing and is needed by the PyTorch parser");
125 }
126 std::string inputShapesStr = "{";
127 for (unsigned int i = 0; i < inputShapes.size(); i++) {
128 inputShapesStr += "{ ";
129 for (unsigned int j = 0; j < inputShapes[i].size(); j++) {
131 if (j < inputShapes[i].size()-1) inputShapesStr += ", ";
132 }
133 inputShapesStr += "}";
134 if (i < inputShapes.size()-1) inputShapesStr += ", ";
135 }
136 inputShapesStr += "}";
137 parserCode += "{\nTMVA::Experimental::SOFIE::RModel model = TMVA::Experimental::SOFIE::PyTorch::Parse(\"" + path + "\", "
138 + inputShapesStr + "); \n";
139 }
140 else if (type == kROOT) {
141 // use parser from ROOT
142 parserCode += "{\nauto fileRead = TFile::Open(\"" + path + "\",\"READ\");\n";
143 parserCode += "TMVA::Experimental::SOFIE::RModel * modelPtr;\n";
144 parserCode += "auto keyList = fileRead->GetListOfKeys(); TString name;\n";
145 parserCode += "for (const auto&& k : *keyList) { \n";
146 parserCode += " TString cname = ((TKey*)k)->GetClassName(); if (cname==\"TMVA::Experimental::SOFIE::RModel\") name = k->GetName(); }\n";
147 parserCode += "fileRead->GetObject(name,modelPtr); fileRead->Close(); delete fileRead;\n";
148 parserCode += "TMVA::Experimental::SOFIE::RModel & model = *modelPtr;\n";
149 }
150
151 // add custom operators if needed
152 if (fCustomOperators.size() > 0) {
153
154 for (auto & op : fCustomOperators) {
155 parserCode += "{ auto p = new TMVA::Experimental::SOFIE::ROperator_Custom<float>(\""
156 + op.fOpName + "\"," + op.fInputNames + "," + op.fOutputNames + "," + op.fOutputShapes + ",\"" + op.fFileName + "\");\n";
157 parserCode += "std::unique_ptr<TMVA::Experimental::SOFIE::ROperator> op(p);\n";
158 parserCode += "model.AddOperator(std::move(op));\n}\n";
159 }
160 }
161
162 int batchSize = 1;
163 if (inputShapes.size() > 0 && inputShapes[0].size() > 0) {
164 batchSize = inputShapes[0][0];
165 if (batchSize < 1) batchSize = 1;
166 }
167 if (verbose) std::cout << "generating the code with batch size = " << batchSize << " ...\n";
168
169 parserCode += "model.Generate(TMVA::Experimental::SOFIE::Options::kDefault,"
170 + ROOT::Math::Util::ToString(batchSize) + ", 0, " + std::to_string(verbose) + "); \n";
171
172 if (verbose) {
173 parserCode += "model.PrintRequiredInputTensors();\n";
174 parserCode += "model.PrintIntermediateTensors();\n";
175 parserCode += "model.PrintOutputTensors();\n";
176 }
177
178 // add custom operators if needed
179#if 0
180 if (fCustomOperators.size() > 0) {
181 if (verbose) {
182 parserCode += "model.PrintRequiredInputTensors();\n";
183 parserCode += "model.PrintIntermediateTensors();\n";
184 parserCode += "model.PrintOutputTensors();\n";
185 }
186 for (auto & op : fCustomOperators) {
187 parserCode += "{ auto p = new TMVA::Experimental::SOFIE::ROperator_Custom<float>(\""
188 + op.fOpName + "\"," + op.fInputNames + "," + op.fOutputNames + "," + op.fOutputShapes + ",\"" + op.fFileName + "\");\n";
189 parserCode += "std::unique_ptr<TMVA::Experimental::SOFIE::ROperator> op(p);\n";
190 parserCode += "model.AddOperator(std::move(op));\n}\n";
191 }
192 parserCode += "model.Generate(TMVA::Experimental::SOFIE::Options::kDefault,"
193 + ROOT::Math::Util::ToString(batchSize) + "); \n";
194 }
195#endif
196 if (verbose > 1)
197 parserCode += "model.PrintGenerated(); \n";
198 parserCode += "model.OutputGenerated();\n";
199
200 parserCode += "int nInputs = model.GetInputTensorNames().size();\n";
201
202 // need information on number of inputs (assume output is 1)
203
204 //end of parsing code, close the scope and return 1 to indicate a success
205 parserCode += "return nInputs;\n}\n";
206
207 if (verbose) std::cout << "//ParserCode being executed:\n" << parserCode << std::endl;
208
209 auto iret = gROOT->ProcessLine(parserCode.c_str());
210 if (iret <= 0) {
211 std::string msg = "RSofieReader: error processing the parser code: \n" + parserCode;
212 throw std::runtime_error(msg);
213 }
214 fNInputs = iret;
215 if (fNInputs > 3) {
216 throw std::runtime_error("RSofieReader does not yet support model with > 3 inputs");
217 }
218
219 // compile now the generated code and create Session class
220 std::string modelHeader = modelName + ".hxx";
221 if (verbose) std::cout << "compile generated code from file " <<modelHeader << std::endl;
222 if (gSystem->AccessPathName(modelHeader.c_str())) {
223 std::string msg = "RSofieReader: input header file " + modelHeader + " is not existing";
224 throw std::runtime_error(msg);
225 }
226 if (verbose) std::cout << "Creating Inference function for model " << modelName << std::endl;
227 std::string declCode;
228 declCode += "#pragma cling optimize(2)\n";
229 declCode += "#include \"" + modelHeader + "\"\n";
230 // create global session instance: use UUID to have an unique name
231 std::string sessionClassName = "TMVA_SOFIE_" + modelName + "::Session";
232 TUUID uuid;
233 std::string uidName = uuid.AsString();
234 uidName.erase(std::remove_if(uidName.begin(), uidName.end(),
235 []( char const& c ) -> bool { return !std::isalnum(c); } ), uidName.end());
236
237 std::string sessionName = "session_" + uidName;
238 declCode += sessionClassName + " " + sessionName + ";";
239
240 if (verbose) std::cout << "//global session declaration\n" << declCode << std::endl;
241
242 bool ret = gInterpreter->Declare(declCode.c_str());
243 if (!ret) {
244 std::string msg = "RSofieReader: error compiling inference code and creating session class\n" + declCode;
245 throw std::runtime_error(msg);
246 }
247
248 fSessionPtr = (void *) gInterpreter->Calc(sessionName.c_str());
249
250 // define a function to be called for inference
251 std::stringstream ifuncCode;
252 std::string funcName = "SofieInference_" + uidName;
253 ifuncCode << "std::vector<float> " + funcName + "( void * ptr";
254 for (int i = 0; i < fNInputs; i++)
255 ifuncCode << ", float * data" << i;
256 ifuncCode << ") {\n";
257 ifuncCode << " " << sessionClassName << " * s = " << "(" << sessionClassName << "*) (ptr);\n";
258 ifuncCode << " return s->infer(";
259 for (int i = 0; i < fNInputs; i++) {
260 if (i>0) ifuncCode << ",";
261 ifuncCode << "data" << i;
262 }
263 ifuncCode << ");\n";
264 ifuncCode << "}\n";
265
266 if (verbose) std::cout << "//Inference function code using global session instance\n"
267 << ifuncCode.str() << std::endl;
268
269 ret = gInterpreter->Declare(ifuncCode.str().c_str());
270 if (!ret) {
271 std::string msg = "RSofieReader: error compiling inference function\n" + ifuncCode.str();
272 throw std::runtime_error(msg);
273 }
274 fFuncPtr = (void *) gInterpreter->Calc(funcName.c_str());
275 //fFuncPtr = reinterpret_cast<std::vector<float> (*)(void *, const float *)>(fptr);
276 fInitialized = true;
277 }
278
279 // Add custom operator
280 void AddCustomOperator(const std::string &opName, const std::string &inputNames, const std::string & outputNames,
281 const std::string & outputShapes, const std::string & fileName) {
282 if (fInitialized) std::cout << "WARNING: Model is already loaded and initialised. It must be done after adding the custom operators" << std::endl;
284 }
285
286 // implementations for different outputs
287 std::vector<float> DoCompute(const std::vector<float> & x1) {
288 if (fNInputs != 1) {
289 std::string msg = "Wrong number of inputs - model requires " + std::to_string(fNInputs);
290 throw std::runtime_error(msg);
291 }
292 auto fptr = reinterpret_cast<std::vector<float> (*)(void *, const float *)>(fFuncPtr);
293 return fptr(fSessionPtr, x1.data());
294 }
295 std::vector<float> DoCompute(const std::vector<float> & x1, const std::vector<float> & x2) {
296 if (fNInputs != 2) {
297 std::string msg = "Wrong number of inputs - model requires " + std::to_string(fNInputs);
298 throw std::runtime_error(msg);
299 }
300 auto fptr = reinterpret_cast<std::vector<float> (*)(void *, const float *, const float *)>(fFuncPtr);
301 return fptr(fSessionPtr, x1.data(),x2.data());
302 }
303 std::vector<float> DoCompute(const std::vector<float> & x1, const std::vector<float> & x2, const std::vector<float> & x3) {
304 if (fNInputs != 3) {
305 std::string msg = "Wrong number of inputs - model requires " + std::to_string(fNInputs);
306 throw std::runtime_error(msg);
307 }
308 auto fptr = reinterpret_cast<std::vector<float> (*)(void *, const float *, const float *, const float *)>(fFuncPtr);
309 return fptr(fSessionPtr, x1.data(),x2.data(),x3.data());
310 }
311
312 /// Compute model prediction on vector
313 template<typename... T>
314 std::vector<float> Compute(T... x)
315 {
316 if(!fInitialized) {
317 return std::vector<float>();
318 }
319
320 // Take lock to protect model evaluation
322
323 // Evaluate TMVA model (need to add support for multiple outputs)
324 return DoCompute(x...);
325
326 }
327 std::vector<float> Compute(const std::vector<float> &x) {
328 if(!fInitialized) {
329 return std::vector<float>();
330 }
331
332 // Take lock to protect model evaluation
334
335 // Evaluate TMVA model (need to add support for multiple outputs)
336 return DoCompute(x);
337 }
338 /// Compute model prediction on input RTensor
339 /// The shape of the input tensor should be {nevents, nfeatures}
340 /// and the return shape will be {nevents, noutputs}
341 /// support for now only a single input
343 {
344 if(!fInitialized) {
345 return RTensor<float>({0});
346 }
347 const auto nrows = x.GetShape()[0];
348 const auto rowsize = x.GetStrides()[0];
349 auto fptr = reinterpret_cast<std::vector<float> (*)(void *, const float *)>(fFuncPtr);
350 auto result = fptr(fSessionPtr, x.GetData());
351
352 RTensor<float> y({nrows, result.size()}, MemoryLayout::ColumnMajor);
353 std::copy(result.begin(),result.end(), y.GetData());
354 //const bool layout = x.GetMemoryLayout() == MemoryLayout::ColumnMajor ? false : true;
355 // assume column major layout
356 for (size_t i = 1; i < nrows; i++) {
357 result = fptr(fSessionPtr, x.GetData() + i*rowsize);
358 std::copy(result.begin(),result.end(), y.GetData() + i*result.size());
359 }
360 return y;
361 }
362
363private:
364
365 bool fInitialized = false;
366 int fNInputs = 0;
367 void * fSessionPtr = nullptr;
368 void * fFuncPtr = nullptr;
369
370 // data to insert custom operators
372 std::string fFileName; // code implementing the custom operator
373 std::string fOpName; // operator name
374 std::string fInputNames; // input tensor names (convert as string as {"n1", "n2"})
375 std::string fOutputNames; // output tensor names converted as trind
376 std::string fOutputShapes; // output shapes
377 };
378 std::vector<CustomOperatorData> fCustomOperators;
379
380};
381
382} // namespace Experimental
383} // namespace TMVA
384
385#endif // TMVA_RREADER
#define c(i)
Definition RSha256.hxx:101
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char x2
Option_t Option_t TPoint TPoint const char x1
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
#define gInterpreter
#define gROOT
Definition TROOT.h:414
R__EXTERN TSystem * gSystem
Definition TSystem.h:572
#define R__WRITE_LOCKGUARD(mutex)
const_iterator begin() const
const_iterator end() const
TMVA::RSofieReader class for reading external Machine Learning models in ONNX files,...
RSofieReader(const std::string &path, std::vector< std::vector< size_t > > inputShapes={}, int verbose=0)
Create TMVA model from ONNX file print level can be 0 (minimal) 1 with info , 2 with all ONNX parsing...
RTensor< float > Compute(RTensor< float > &x)
Compute model prediction on input RTensor The shape of the input tensor should be {nevents,...
std::vector< float > Compute(const std::vector< float > &x)
std::vector< float > Compute(T... x)
Compute model prediction on vector.
void Load(const std::string &path, std::vector< std::vector< size_t > > inputShapes={}, int verbose=0)
std::vector< float > DoCompute(const std::vector< float > &x1, const std::vector< float > &x2, const std::vector< float > &x3)
std::vector< CustomOperatorData > fCustomOperators
std::vector< float > DoCompute(const std::vector< float > &x1)
void AddCustomOperator(const std::string &opName, const std::string &inputNames, const std::string &outputNames, const std::string &outputShapes, const std::string &fileName)
std::vector< float > DoCompute(const std::vector< float > &x1, const std::vector< float > &x2)
RSofieReader()
Dummy constructor which needs model loading afterwards.
virtual int Load(const char *module, const char *entry="", Bool_t system=kFALSE)
Load a shared library.
Definition TSystem.cxx:1868
virtual Bool_t AccessPathName(const char *path, EAccessMode mode=kFileExists)
Returns FALSE if one can access a file using the specified access mode.
Definition TSystem.cxx:1307
This class defines a UUID (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDent...
Definition TUUID.h:42
const char * AsString() const
Return UUID as string. Copy string immediately since it will be reused.
Definition TUUID.cxx:570
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
std::string ToString(const T &val)
Utility function for conversion to strings.
Definition Util.h:64
R__EXTERN TVirtualRWMutex * gCoreMutex
create variable transformations