Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RModelParser_ONNX.cxx
Go to the documentation of this file.
1#include "Byteswap.h"
3// The operator base class is a private header: RModelParser_ONNX.hxx only
4// forward-declares it, but this translation unit manages ROperator instances
5// through std::unique_ptr and needs the complete type.
6#include "TMVA/ROperator.hxx"
7#include "onnx.hxx"
8
9#include <algorithm>
10#include <stdexcept>
11#include <string>
12#include <cstring>
13#include <memory>
14#include <cassert>
15#include <iostream>
16#include <unordered_map>
17#include <functional>
18#include "TMVA/SOFIE_common.hxx"
19
20namespace TMVA {
21namespace Experimental {
22namespace SOFIE {
23
24// Declaration of operators
25// Unary operators
26void RegisterBasicUnaryParsers(RModelParser_ONNX &parser);
27// Binary operators
28void RegisterBasicBinaryParsers(RModelParser_ONNX &parser);
29// Nary operators
30void RegisterBasicNaryParsers(RModelParser_ONNX &parser);
31//Comparision Operators
32void RegisterComparisionParsers(RModelParser_ONNX &parser);
33//Is Operators
34void RegisterBasicIsParsers(RModelParser_ONNX &parser);
36// Reduce operators
37void RegisterReduceParsers(RModelParser_ONNX &parser);
38// Others
90// Declaration of fused operators
96
97// Definition of RModelParser_ONNX::OperatorsMap
99 // Registered operators
100 std::unordered_map<std::string, ParserFuncSignature> fOperatorsMap;
101};
102
103// helper function to get initialized tensor data
104template<typename T>
106};
107// trait function to extract data from TensorProto
108template<>
109struct ExtractDataFromTP<float> {
110 static void Copy(onnx::TensorProto * tensor, void * data, int length) {
111 if (tensor->float_data_size() != length)
112 throw std::runtime_error("TMVA::SOFIE - Failed to read float initialized tensor - actual size is " + std::to_string(tensor->float_data_size()));
113 const auto &src = tensor->float_data();
114 std::copy(src.begin(), src.end(), static_cast<float *>(data));
115 }
116};
117template<>
119 static void Copy(onnx::TensorProto * tensor, void * data, int length) {
120 if (tensor->double_data_size() != length)
121 throw std::runtime_error("TMVA::SOFIE - Failed to read double initialized tensor - actual size is " + std::to_string(tensor->double_data_size()));
122 const auto &src = tensor->double_data();
123 std::copy(src.begin(), src.end(), static_cast<double *>(data));
124 }
125};
126template<>
127struct ExtractDataFromTP<int32_t> {
128 static void Copy(onnx::TensorProto * tensor, void * data, int length) {
129 if (tensor->int32_data_size() != length)
130 throw std::runtime_error("TMVA::SOFIE - Failed to read int32 initialized tensor - actual size is " + std::to_string(tensor->int32_data_size()));
131 const auto &src = tensor->int32_data();
132 std::copy(src.begin(), src.end(), static_cast<int32_t *>(data));
133 }
134};
135template<>
136struct ExtractDataFromTP<int64_t> {
137 static void Copy(onnx::TensorProto * tensor, void * data, int length) {
138 if (tensor->int64_data_size() != length)
139 throw std::runtime_error("TMVA::SOFIE - Failed to read int64 initialized tensor - actual size is " + std::to_string(tensor->int64_data_size()));
140 const auto &src = tensor->int64_data();
141 std::copy(src.begin(), src.end(), static_cast<int64_t *>(data));
142 }
143};
144
145#ifndef R__BYTESWAP
146namespace {
147
148// Copy nbytes from source to dest, byte-swapping each N-byte element. The
149// temporary avoids misaligned loads from the protobuf string buffer and makes
150// in-place swapping (dest == source) valid.
151template <std::size_t N>
152void CopyBswap(void *dest, const void *source, std::size_t nbytes)
153{
154 using value_type = typename RByteSwap<N>::value_type;
155 auto dst = static_cast<unsigned char *>(dest);
156 auto src = static_cast<const unsigned char *>(source);
157 for (std::size_t k = 0; k < nbytes; k += N) {
158 value_type v;
159 std::memcpy(&v, src + k, N);
161 std::memcpy(dst + k, &v, N);
162 }
163}
164
165// Copy a buffer of little-endian tensor elements to host (big-endian) byte order
166void CopyLEToHost(void *dest, const void *source, std::size_t nbytes, ETensorType tensor_type)
167{
168 switch (GetTypeSize(tensor_type)) {
169 case 1:
170 if (dest != source)
171 std::memcpy(dest, source, nbytes);
172 break;
173 case 2: CopyBswap<2>(dest, source, nbytes); break;
174 case 4: CopyBswap<4>(dest, source, nbytes); break;
175 case 8: CopyBswap<8>(dest, source, nbytes); break;
176 default:
177 throw std::runtime_error("Data type " + ConvertTypeToString(tensor_type) + " in tensor is not supported!\n");
178 }
179}
180
181} // anonymous namespace
182#endif
183
184std::shared_ptr<void> RModelParser_ONNX::GetInitializedTensorData(onnx::TensorProto *tensorproto, size_t tensor_size, ETensorType tensor_type)
185{
186
187 std::shared_ptr<void> data(malloc(tensor_size), free);
188
189 // check if initialized tensors are stored internally
190 if (tensorproto->data_location() != onnx::TensorProto::EXTERNAL) {
191 if (tensorproto->raw_data().size() > 0) {
192 if (tensorproto->raw_data().size() != tensor_size)
193 throw std::runtime_error("TMVA::SOFIE - Failed to read raw data of initialized tensor - actual raw size is " +
194 std::to_string(tensorproto->raw_data().size()));
195
196#ifdef R__BYTESWAP
197 // R__BYTESWAP is defined for little-endian architectures (most common ones)
198 std::memcpy(data.get(), tensorproto->raw_data().c_str(), tensor_size);
199#else
200 // big-endian architectures - need to swap bytes
201 CopyLEToHost(data.get(), tensorproto->raw_data().c_str(), tensor_size, tensor_type);
202#endif
203 } else {
204 // case tensor data are stored as specific types and not in raw_data
205 switch (tensor_type) {
206 case ETensorType::FLOAT: {
207 ExtractDataFromTP<float>::Copy(tensorproto, data.get(), tensor_size/ 4);
208 break;
209 }
210 case ETensorType::DOUBLE: {
211 ExtractDataFromTP<double>::Copy(tensorproto, data.get(), tensor_size/ 8);
212 break;
213 }
214 case ETensorType::INT32: {
215 ExtractDataFromTP<int32_t>::Copy(tensorproto, data.get(), tensor_size/ 4);
216 break;
217 }
218 case ETensorType::INT64: {
219 ExtractDataFromTP<int64_t>::Copy(tensorproto, data.get(), tensor_size/ 8);
220 break;
221 }
222 case ETensorType::BOOL: {
223 throw std::runtime_error("TMVA::SOFIE - ExtractData from TP in BOOL not supported");
224 break;
225 }
226 case ETensorType::UINT8: {
227 throw std::runtime_error("TMVA::SOFIE - ExtractData from TP in UINT8 not supported");
228 break;
229 }
230 default:
231 throw std::runtime_error("Data type " + ConvertTypeToString(tensor_type) + " in weight tensor is not supported!\n");
232 }
233 }
234
235 } else {
236 // case of external data
237
238 // read now tensor from file
239 std::string location;
240 size_t offset = 0, buffer_size = 0;
241
242 for (const auto &kv : tensorproto->external_data()) {
243 if (kv.key() == "location") location = kv.value();
244 else if (kv.key() == "offset") offset = std::stoull(kv.value());
245 else if (kv.key() == "length") buffer_size = std::stoull(kv.value());
246 }
247
248 // an explicitly set data file (SetExternalDataFile) takes precedence;
249 // otherwise use the location stored in the model, which is a path
250 // relative to the model directory, and as a last resort the
251 // conventional <model file>.data
252 std::string dataFileName = fDataFileName;
253 if (dataFileName.empty())
254 dataFileName = location.empty() ? fDefaultDataFileName : fModelDirectory + location;
255 if (dataFileName.empty())
256 throw std::runtime_error("TMVA::SOFIE ONNX : tensor " + tensorproto->name() +
257 " has external data but no data file location is available");
258
259 if (fVerbose)
260 std::cout << "Initialized data are stored externally in file " << dataFileName
261 << " at location " << location << " offset " << offset << " and with length " << buffer_size << std::endl;
262
263 if (buffer_size != tensor_size)
264 throw std::runtime_error("TMVA::SOFIE ONNX : invalid stored data size vs tensor size");
265
266 // open the data file if needed (a previous tensor may have opened a different one)
267 if (fDataFile.is_open() && fOpenedDataFileName != dataFileName)
268 fDataFile.close();
269 if (!fDataFile.is_open()) {
270 fDataFile.open(dataFileName, std::ios::binary);
271 if (!fDataFile.is_open())
272 throw std::runtime_error("TMVA::SOFIE ONNX: error reading external weight ONNX data file " + dataFileName);
273 fOpenedDataFileName = dataFileName;
274 }
275
276 fDataFile.seekg(offset);
277 fDataFile.read(reinterpret_cast<char *>(data.get()), buffer_size);
278#ifndef R__BYTESWAP
279 // external data is stored little-endian like raw_data - swap in place
280 CopyLEToHost(data.get(), data.get(), buffer_size, tensor_type);
281#endif
282 }
283
284 return data;
285}
286
287
288// Constructor of the parser
289RModelParser_ONNX::RModelParser_ONNX() noexcept : fOperatorsMapImpl(std::make_unique<OperatorsMapImpl>()) {
290 // Register operators
291 // Unary operators
293 // Binary operators
295 // Nary operators
297 //Comparision Operators
299 // Is If operators
302 // Reduce operators
304 // Others
305 RegisterOperator("BatchNormalization", ParseBatchNormalization);
306 RegisterOperator("Constant", ParseConstant);
307 RegisterOperator("ConstantOfShape", ParseConstant);
309 RegisterOperator("Concat", ParseConcat);
311 RegisterOperator("ConvTranspose", ParseConvTranspose);
314 RegisterOperator("Identity", ParseIdentity);
315 RegisterOperator("LeakyRelu", ParseLeakyRelu);
316 RegisterOperator("ThresholdedRelu", ParseThresholdedRelu);
318 RegisterOperator("AveragePool", ParsePool);
319 RegisterOperator("GlobalAveragePool", ParsePool);
320 RegisterOperator("MaxPool", ParsePool);
322 RegisterOperator("Reshape", ParseReshape);
323 RegisterOperator("Flatten", ParseReshape);
324 RegisterOperator("Squeeze", ParseReshape);
325 RegisterOperator("Unsqueeze", ParseReshape);
330 RegisterOperator("Sigmoid", ParseSigmoid);
333 RegisterOperator("Softmax", ParseSoftmax);
334 RegisterOperator("LogSoftmax", ParseSoftmax);
336 RegisterOperator("Transpose", ParseTranspose);
337 RegisterOperator("MatMul", ParseMatMul);
338 RegisterOperator("LayerNormalization", ParseLayerNormalization);
339 RegisterOperator("Expand", ParseExpand);
340 RegisterOperator("Gather", ParseGather);
341 RegisterOperator("GatherND", ParseGatherND);
344 RegisterOperator("HardSigmoid", ParseHardSigmoid);
345 RegisterOperator("HardSwish", ParseHardSwish);
346 RegisterOperator("EyeLike", ParseEyeLike);
352 RegisterOperator("InstanceNormalization", ParseInstanceNormalization);
355 RegisterOperator("Einsum", ParseEinsum);
356 RegisterOperator("RandomNormal", ParseRandom);
357 RegisterOperator("RandomNormalLike", ParseRandom);
358 RegisterOperator("RandomUniform", ParseRandom);
359 RegisterOperator("RandomUniformLike", ParseRandom);
360 RegisterOperator("ScatterElements", ParseScatterElements);
361 RegisterOperator("ScatterND", ParseScatterND);
362 RegisterOperator("NonZero", ParseNonZero);
364 RegisterOperator("ArgMax", ParseArgMax);
366}
367
368// Destructor of the parser
370
372{
373 fOperatorsMapImpl->fOperatorsMap[name] = func;
374}
375
377{
378 return fOperatorsMapImpl->fOperatorsMap.find(name) != fOperatorsMapImpl->fOperatorsMap.end();
379}
380
382{
383 std::vector<std::string> ops;
384 ops.reserve(fOperatorsMapImpl->fOperatorsMap.size());
385 for (auto &it : fOperatorsMapImpl->fOperatorsMap) {
386 ops.emplace_back(it.first);
387 }
388 // return sorted list in alphabetical order
389 std::sort(ops.begin(), ops.end());
390 return ops;
391}
392
397
399{
401}
402
407
408namespace {
409
410/// Is the Add following a Conv / ConvTranspose really that convolution's bias?
411///
412/// Only if the convolution has no bias yet and the added tensor is a rank-1 initializer, one
413/// value per output channel. Anything else - a residual connection, an operand computed at
414/// run time - is a genuine addition.
415bool IsConvBiasAdd(const onnx::GraphProto &graph, const onnx::NodeProto &convnode, const onnx::NodeProto &addnode)
416{
417 if (convnode.input_size() > 2 || addnode.input_size() != 2)
418 return false;
419 const std::string &added = (addnode.input(0) == convnode.output(0)) ? addnode.input(1) : addnode.input(0);
420 for (int i = 0; i < graph.initializer_size(); i++) {
421 if (graph.initializer(i).name() == added)
422 return graph.initializer(i).dims_size() == 1;
423 }
424 return false;
425}
426
427} // namespace
428
429// Parse an operator
430std::unique_ptr<ROperator>
431RModelParser_ONNX::ParseOperator(const size_t i, const onnx::GraphProto &graphproto, const std::vector<size_t> &nodes, const std::vector<int> & children)
432{
433 if (i >= nodes.size())
434 throw std::runtime_error("TMVA::SOFIE - Error in parsing ordered operators " + std::to_string(i) + " is >= " + std::to_string(nodes.size()));
435 int idx = nodes[i];
436 const auto &nodeproto = graphproto.node(idx);
437 const std::string op_type = nodeproto.op_type();
438 if (fVerbose)
439 std::cout << "Parsing operator " << op_type << std::endl;
440
441 // perform the fusion of operators
442 if (fFusedOperators.count(idx) == 1) {
443 int idx1 = fFusedOperators[idx].second;
444 if (fVerbose) {
445 std::cout << "\tFusing operators " << graphproto.node(idx1).name()
446 << " with " << graphproto.node(idx1).name() << std::endl;
447 }
448 if (fFusedOperators[idx].first == EFusedOp::kMatMulAdd) {
449 return ParseFuseMatMulAdd(*this, graphproto.node(idx1), graphproto.node(idx));
450 } else if (fFusedOperators[idx].first == EFusedOp::kConvAdd) {
451 return ParseFuseConvAdd(*this, graphproto.node(idx1), graphproto.node(idx));
452 } else if (fFusedOperators[idx].first == EFusedOp::kConvTransAdd) {
453 return ParseFuseConvTransposeAdd(*this, graphproto.node(idx1), graphproto.node(idx));
454 } else if (fFusedOperators[idx].first == EFusedOp::kGemmRelu) {
455 return ParseFuseGemmRelu(*this, graphproto.node(idx1), graphproto.node(idx));
456 } else if (fFusedOperators[idx].first == EFusedOp::kBatchnormRelu) {
457 return ParseFuseBatchnormRelu(*this, graphproto.node(idx1), graphproto.node(idx));
458 }
459 }
460
461 // try to fuse with following operator in case it is not last one and having only a single child
462 if (children.size() == 1) {
463 int idx2 = children.front();
464 if (op_type == "MatMul") {
465 // Fuse MatMul and Add
466 if (idx2 < graphproto.node_size() && graphproto.node(idx2).op_type() == "Add") {
468 return nullptr;
469 }
470 } else if (nodeproto.op_type() == "Conv" || nodeproto.op_type() == "ConvTranspose") {
471 // Fuse Conv or ConvTranspose without bias and Add, when the Add really is the bias
472 if (idx2 < graphproto.node_size() && graphproto.node(idx2).op_type() == "Add" &&
473 IsConvBiasAdd(graphproto, nodeproto, graphproto.node(idx2))) {
474 if (nodeproto.op_type() == "Conv") {
475 fFusedOperators[idx2] = { EFusedOp::kConvAdd, idx};
476 return nullptr;
477 } else {
479 return nullptr;
480 }
481 }
482 } else if (nodeproto.op_type() == "Gemm") {
483 // Fuse Gemm with activation operators
484 if (idx2 < graphproto.node_size() && graphproto.node(idx2).op_type() == "Relu") {
486 return nullptr;
487 }
488 } else if (nodeproto.op_type() == "BatchNormalization") {
489 if (idx2 < graphproto.node_size() && graphproto.node(idx2).op_type() == "Relu") {
491 return nullptr;
492 }
493 }
494 }
495
496 auto it = fOperatorsMapImpl->fOperatorsMap.find(op_type);
497 if (it == fOperatorsMapImpl->fOperatorsMap.end()) {
498 std::cout << "operator " << op_type << " is not supported" << std::endl;
499 throw std::runtime_error("TMVA::SOFIE Operator type " + op_type + " is not yet supported");
500 }
501 if (fVerbose) {
502 std::cout << "\tCreating operator " << op_type << std::endl;
503 }
504 return it->second(*this, nodeproto);
505}
506
507// Parse a model
508RModel RModelParser_ONNX::Parse(std::string const &filename, bool verbose)
509{
510 fVerbose = verbose;
511
512 fTensorTypeMap.clear();
513
514 auto model = LoadModel(filename);
515 if (!model)
516 throw std::runtime_error("TMVA::SOFIE - Failed to load onnx file " + filename);
517
518 const onnx::GraphProto &graph = model->graph(); // not a memory leak. model freed automatically at the end.
519
520
521 std::time_t ttime = std::time(0);
522 std::tm *gmt_time = std::gmtime(&ttime);
523 std::string parsetime(std::asctime(gmt_time));
524
525 // get name of model (filename without directory name)
526 char sep = '/';
527#ifdef _WIN32
528 sep = '\\';
529#endif
530 size_t isep = filename.rfind(sep, filename.length());
531 std::string filename_nodir = filename;
532 if (isep != std::string::npos) {
533 filename_nodir = (filename.substr(isep + 1, filename.length() - isep));
534 }
535
536 fModelDirectory = (isep != std::string::npos) ? filename.substr(0, isep + 1) : "";
537 fDefaultDataFileName = filename + ".data";
538
539 RModel rmodel(filename_nodir, parsetime);
540 ParseONNXGraph(rmodel, graph, filename_nodir);
542 return rmodel;
543}
544
545RModel RModelParser_ONNX::Parse(std::istream &input, std::string const &name, bool verbose)
546{
547 fVerbose = verbose;
548
549 fTensorTypeMap.clear();
550
551 auto model = LoadModel(input);
552 if (!model)
553 throw std::runtime_error("TMVA::SOFIE - Failed to parse ONNX model from input stream");
554
555 const onnx::GraphProto &graph = model->graph(); // not a memory leak. model freed automatically at the end.
556
557 std::time_t ttime = std::time(0);
558 std::tm *gmt_time = std::gmtime(&ttime);
559 std::string parsetime(std::asctime(gmt_time));
560
561 RModel rmodel(name, parsetime);
562 ParseONNXGraph(rmodel, graph, name);
564 return rmodel;
565}
566
567// Reset the state used to read external weight data, so that the next Parse
568// call does not pick up the data file of a previously parsed model. The
569// file name set with SetExternalDataFile is valid for a single Parse call.
571{
572 fDataFileName.clear();
573 fModelDirectory.clear();
574 fDefaultDataFileName.clear();
575 fOpenedDataFileName.clear();
576 if (fDataFile.is_open())
577 fDataFile.close();
578}
579
580std::unique_ptr<onnx::ModelProto> RModelParser_ONNX::LoadModel(const std::string &filename) {
581 std::fstream input(filename, std::ios::in | std::ios::binary);
582 if (!input) {
583 std::cerr << "TMVA::SOFIE - Failed to open onnx file " << filename << std::endl;
584 return {};
585 }
586
587 return LoadModel(input);
588}
589
590std::unique_ptr<onnx::ModelProto> RModelParser_ONNX::LoadModel(std::istream &input)
591{
592 auto model = std::make_unique<onnx::ModelProto>();
593
594 if (!model->ParseFromIstream(&input)) {
595 std::cerr << "TMVA::SOFIE - Failed to parse ONNX model from input stream" << std::endl;
596 return {};
597 }
598
599 // ONNX version is ir_version() - model_version() returns 0
600 if (fVerbose) {
601 std::cout << "ONNX Version " << model->ir_version() << std::endl;
602 }
603 return model;
604}
605
606void RModelParser_ONNX::CheckGraph(const onnx::GraphProto & graph, int & level, std::map<std::string, int> & missingOperators) {
607 if (fVerbose)
608 std::cout << "\n" << graph.name() << " Graph operator list\n";
609 for (int i = 0; i < graph.node_size(); i++) {
610 const auto & node = graph.node(i);
611 const std::string opType = node.op_type();
612 if (fVerbose) {
613 std::cout << "\tOperator " << i << " : " << opType << " (" << node.name() << "), " << graph.node(i).input_size()
614 << " inputs : {";
615 for (int j = 0; j < graph.node(i).input_size(); j++) {
616 std::cout << graph.node(i).input(j);
617 if (j < graph.node(i).input_size() - 1)
618 std::cout << ", ";
619 }
620 std::cout << " }" << std::endl;
621 }
622 // check if operator exists
623 if (!IsRegisteredOperator(opType))
624 missingOperators[opType] = level;
625 // see if sub-graph exists as node attributes
626 for (int j = 0; j < node.attribute_size(); j++) {
627 const auto & attribute = node.attribute(j);
628 if (attribute.has_g()) {
629 const auto & subGraph = attribute.g();
630 level += 1;
631 CheckGraph(subGraph, level, missingOperators);
632 }
633 }
634 }
635}
636
637bool RModelParser_ONNX::CheckModel(std::string filename, bool verbose) {
638
639 fVerbose = verbose;
640 auto model = LoadModel(filename);
641 if (!model) return false;
642
643 const onnx::GraphProto &graph = model->graph();
644 // Initial operator order
645 if (fVerbose)
646 std::cout << "\nModel operator list " << model->producer_name() << "\n";
647
648 std::map<std::string, int> missingOperators;
649 int level = 1;
650 CheckGraph(graph, level, missingOperators);
651
652 if (!missingOperators.empty()) {
653 std::cout << "List of missing operators for model loaded from file " << filename << std::endl;
654 for (auto & op : missingOperators) {
655 std::cout << op.first << " " << op.second << std::endl;
656 }
657 return false;
658 }
659 std::cout << "All operators in the loaded model are supported!\n";
660 return true;
661}
662
663void RModelParser_ONNX::ParseONNXGraph(RModel & rmodel, const onnx::GraphProto & graph, std::string graphName)
664{
665 bool verbose = fVerbose;
666
667 if (graphName.empty())
668 graphName = graph.name();
669
670 if (verbose)
671 std::cout << "\nParsing Graph - " << graphName << std::endl;
672
673 // fFusedOperators is keyed by node index, so it is only valid for the graph
674 // being parsed: neither a second model parsed with the same parser nor a
675 // subgraph (e.g. of the If operator) may inherit it.
676 struct FusedOperatorsGuard {
677 std::map<int, std::pair<EFusedOp, int>> &fMap;
678 std::map<int, std::pair<EFusedOp, int>> fSaved;
679 FusedOperatorsGuard(std::map<int, std::pair<EFusedOp, int>> &map) : fMap(map) { fSaved.swap(fMap); }
680 ~FusedOperatorsGuard() { fMap.swap(fSaved); }
681 } fusedOperatorsGuard{fFusedOperators};
682
683 std::unordered_set<std::string> initializer_names;
684 for (int i = 0; i < graph.initializer_size(); i++) {
685 initializer_names.insert(graph.initializer(i).name());
686 }
687
688 if (verbose)
689 std::cout << "Parsing model inputs...." << std::endl;
690 /// Loop on model inputs
691 for (int i = 0; i < graph.input_size(); i++) {
692 RegisterTensorType(graph.input(i).name(),
693 static_cast<ETensorType>(graph.input(i).type().tensor_type().elem_type()));
694
695 if (verbose)
696 std::cout << "\tgraph input " << i << " name " << graph.input(i).name() << " type "
697 << graph.input(i).type().tensor_type().elem_type() << std::endl;
698
699 if (initializer_names.find(graph.input(i).name()) != initializer_names.end())
700 continue;
701
702 // input data node is not a weight node (has no initializer)
703 const onnx::ValueInfoProto &valueinfoproto = graph.input(i);
704 std::string input_name = valueinfoproto.name();
705
706 ETensorType type = static_cast<ETensorType>(valueinfoproto.type().tensor_type().elem_type());
707
708 std::vector<Dim> fShape;
709 bool existParam = false;
710 if (!valueinfoproto.type().tensor_type().has_shape())
711 throw std::runtime_error("TMVA::SOFIE data node with no shape restrictions is not supported yet");
712 for (int j = 0; j < valueinfoproto.type().tensor_type().shape().dim_size(); j++) {
713 Dim dim;
714 if (valueinfoproto.type().tensor_type().shape().dim(j).value_case() ==
716 int dim_value = valueinfoproto.type().tensor_type().shape().dim(j).dim_value();
717 dim.dim = dim_value;
718 // case input dim is -1 - set a parametric shape
719 if (dim_value < 0) {
720 dim.isParam = true;
721 existParam = true;
722 dim.param = UTILITY::Clean_name(input_name) + "_size";
723 }
724 } else if (valueinfoproto.type().tensor_type().shape().dim(j).value_case() ==
726 dim.isParam = true;
727 existParam = true;
728 dim.param = valueinfoproto.type().tensor_type().shape().dim(j).dim_param();
729 } else {
730 throw std::runtime_error("TMVA::SOFIE ONNX file error: Valueinfoproto " + input_name +
731 " has neither dim_value nor dim_param! \n");
732 }
733 fShape.push_back(dim);
734 }
735 if (valueinfoproto.type().tensor_type().shape().dim_size() == 0) {
736 Dim dim;
737 dim.dim = 1;
738 fShape.push_back(dim);
739 } // in case this TensorShapeProto has no dimension message: ONNX IR defines this to be a scalar
740
741 if (!existParam) {
742 std::vector<size_t> fShape_sizet;
743 for (auto &j : fShape) {
744 fShape_sizet.push_back(j.dim);
745 }
746
747 rmodel.AddInputTensorInfo(input_name, type, fShape_sizet);
748 } else {
749 rmodel.AddInputTensorInfo(input_name, type, fShape);
750 }
751 rmodel.AddInputTensorName(input_name); // store also names in given order
752 }
753
754 std::map<std::string, int> allInitializedTensors;
755
756 if (verbose)
757 std::cout << "\nParsing graph initializer list and fill model initialized tensors" << std::endl;
758
759 for (int i = 0; i < graph.initializer_size(); i++) {
760 onnx::TensorProto *tensorproto = const_cast<onnx::TensorProto *>(&graph.initializer(i));
761 std::vector<std::size_t> shape;
762 std::size_t tensor_length = 1;
763 for (int j = 0; j < tensorproto->dims_size(); j++) {
764 shape.push_back(tensorproto->dims(j));
765 tensor_length *= tensorproto->dims(j);
766 }
767 // in case of scalars keep an empty shape but with length =1
768
769 std::string tensor_name = graph.initializer(i).name();
770
771 if (verbose)
772 std::cout << "\t initializer " << i << " name " << tensor_name << " type " << graph.initializer(i).data_type()
773 << " and length " << tensor_length << std::endl;
774
775
776 // register also the initialized tensors
777 auto tensor_type = static_cast<ETensorType>(graph.initializer(i).data_type());
778 RegisterTensorType(tensor_name, tensor_type);
779
780 std::shared_ptr<void> data = GetInitializedTensorData(tensorproto, tensor_length * GetTypeSize(tensor_type), tensor_type);
781 rmodel.AddInitializedTensor(tensor_name, tensor_type, shape, data);
782 allInitializedTensors[tensor_name] = i;
783
784 if (verbose) {
785 std::cout << "add initialized tensor " << tensor_name << "with shape " << ConvertShapeToString(shape) << "and ";
786 if (tensor_type == ETensorType::FLOAT) {
787 std::cout << " float data: ";
788 for (int j = 0; j < std::min(int(tensor_length),3); j++) std::cout << static_cast<float*>(data.get())[j] << " ";
789 }
790 else if (tensor_type == ETensorType::INT64) {
791 std::cout << " int64 data: ";
792 for (int j = 0; j < std::min(int(tensor_length),3); j++) std::cout << static_cast<int64_t*>(data.get())[j] << " ";
793 }
794 else if (tensor_type == ETensorType::UINT8) {
795 std::cout << " uint8 data: ";
796 for (int j = 0; j < std::min(int(tensor_length),3); j++) std::cout << static_cast<uint8_t*>(data.get())[j] << " ";
797 }
798 else if (tensor_type == ETensorType::BOOL) {
799 std::cout << " Boolean data: ";
800 for (int j = 0; j < std::min(int(tensor_length),3); j++) std::cout << static_cast<bool*>(data.get())[j] << " ";
801 }
802 std::cout << std::endl;
803 }
804 } // end initializer list
805
806 // Initial operator order
807 if (verbose) {
808 std::cout << "\nGraph operator list (ONNX order)\n";
809 for (int i = 0; i < graph.node_size(); i++) {
810 std::cout << "\tOperator " << i << " : " << graph.node(i).op_type() << " , " << graph.node(i).input_size()
811 << " inputs : {";
812 for (int j = 0; j < graph.node(i).input_size(); j++) {
813 std::cout << graph.node(i).input(j);
814 if (j < graph.node(i).input_size() - 1)
815 std::cout << ", ";
816 }
817 std::cout << " }" << std::endl;
818 }
819 }
820
821 // make order of nodes:
822 if (verbose)
823 std::cout << "\n***********************\nRe-Order graph operator list\n*************************\n";
824 std::vector<size_t> nodesOrder;
825 nodesOrder.reserve(graph.node_size());
826 std::vector<bool> foundNodes(graph.node_size());
827
828 // loop at graph inputs
829 std::map<std::string, int> allInputs;
830 for (int i = 0; i < graph.input_size(); i++) {
831 allInputs[graph.input(i).name()] = -1;
832 }
833 do {
834 auto psize = nodesOrder.size();
835 for (int i = 0; i < graph.node_size(); i++) {
836 if (foundNodes[i])
837 continue;
838 // check if all input exists add to list
839 bool existInputs = true;
840 int input_size = graph.node(i).input_size();
841 // special case for Reshape where shape is input and not a weight tensor
842 if (fVerbose)
843 std::cout << "Checking input of Node " << i << " : " << graph.node(i).name() << std::endl;
844 for (int j = 0; j < input_size; j++) {
845 std::string name = graph.node(i).input(j);
846 // skip empty names
847 if (!name.empty()) {
848 existInputs &= (allInputs.find(name) != allInputs.end() ||
849 allInitializedTensors.find(name) != allInitializedTensors.end());
850 if (fVerbose) {
851 std::cout << "\t\t input " << name << " "
852 << bool(allInputs.find(name) != allInputs.end()) << " " <<
853 bool(allInitializedTensors.find(name) != allInitializedTensors.end()) << " " <<
854 existInputs << std::endl;
855 }
856 }
857 }
858 if (!existInputs) {
859 if (fVerbose) {
860 std::cout << "skip node " << graph.node(i).op_type() << " " << graph.node(i).name() << " inputs are not existing ";
861 for (int j = 0; j < input_size; j++) {
862 std::cout << graph.node(i).input(j) << " ";
863 }
864 std::cout << std::endl;
865 }
866 continue;
867 }
868
869 // adding node to the currectly ordered list
870 if (verbose)
871 std::cout << "===> New node " << graph.node(i).op_type() << " " << graph.node(i).name() << " order " << i << std::endl;
872
873 nodesOrder.push_back(i);
874 foundNodes[i] = true;
875 // register the outputs
876 for (int j = 0; j < graph.node(i).output_size(); j++) {
877 if (fVerbose) std::cout << "\toutput : " << graph.node(i).output(j) << std::endl;
878 allInputs[graph.node(i).output(j)] = i;
879 }
880 }
881 // no increment in nodes - something wrong
882 if (nodesOrder.size() == psize) {
883 if (!nodesOrder.empty()) {
884 int ilast = nodesOrder.back();
885 std::cout << "cannot find a new node after " << graph.node(ilast).op_type() << " " << graph.node(ilast).name() << std::endl;
886 }
887 throw std::runtime_error("TMVA::SOFIE - cannot find a new node ");
888 }
889 } while ((int)nodesOrder.size() < graph.node_size());
890
891
892 // find list of children for each operator (used for fusing oiperators)
893 std::vector<std::vector<int>> nodesChildren(graph.node_size());
894
895 for (int k = 0; k < graph.node_size(); k++) {
896 int i = nodesOrder[k];
897 // compute the number of output for the operators
898 if (graph.node(i).output_size() > 0) nodesChildren[i].reserve(graph.node(i).output_size());
899 for (const auto& output_name : graph.node(i).output()) {
900 // loop on all nodes
901 for (int l = k; l < graph.node_size(); l++) {
902 int j = nodesOrder[l];
903 for (const auto& input_name : graph.node(j).input()) {
904 if (input_name == output_name)
905 nodesChildren[i].push_back(j);
906 }
907 }
908 }
909 }
910
911 // print lit of order operators with list of inputs and list of children nodes
912 if (verbose) {
913 std::cout << "\nGraph operator list (re-ordered)\n";
914 for (int k = 0; k < graph.node_size(); k++) {
915 int i = nodesOrder[k];
916 std::cout << "\tOperator " << i << " : " << graph.node(i).op_type() << " , " << graph.node(i).name() << " input tensors : {";
917 for (int j = 0; j < graph.node(i).input_size(); j++) {
918 std::cout << graph.node(i).input(j);
919 if (j < graph.node(i).input_size() - 1)
920 std::cout << ", ";
921 }
922 std::cout << " } ";
923 std::cout << " children : {";
924 for ( const auto & ichild : nodesChildren[i]) {
925 std::cout << " [ " << ichild << " " << graph.node(ichild).op_type() << " , " << graph.node(ichild).name() << "]";
926 }
927 std::cout << "}" << std::endl;
928 }
929 }
930
931 // fill model with operators
932 if (verbose) {
933 std::cout << "Fill RModel with operators...\n";
934 }
935
936 // we have to record order of node execution separately to
937 // account for fused operators
938 size_t node_order_exec = 0;
939 for (int i = 0; i < graph.node_size(); i++) {
940 std::string op_type = graph.node(nodesOrder[i]).op_type();
941
942 if (verbose) {
943 std::cout << "\t" << i << " " << nodesOrder[i] << " parsing operator " << op_type << std::endl;
944 }
945
946 std::unique_ptr<ROperator> op = ParseOperator(i, graph, nodesOrder, nodesChildren[nodesOrder[i]]);
947 if (!op) {
948 if (verbose) {
949 std::cout << "\t\tskipping operator since it is fused with previous one" << std::endl;
950 }
951 // for skipping the fused nodes like Add after MatMul
952 continue;
953 }
954 rmodel.AddOperator(std::move(op), node_order_exec++);
955 }
956
957 std::vector<std::string> outputnames;
958 if (verbose)
959 std::cout << "\nParsing Graph output list\n";
960 for (int i = 0; i < graph.output_size(); i++) {
961 if (verbose)
962 std::cout << "\toutput " << i << " name " << graph.output(i).name() << std::endl;
963 outputnames.push_back(graph.output(i).name());
964 }
965 rmodel.AddOutputTensorNameList(outputnames);
966
967 return;
968}
969
970} // namespace SOFIE
971} // namespace Experimental
972} // namespace TMVA
dims_t fShape
double * dst
#define N
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void input
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t dest
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 filename
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 offset
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 length
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t src
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
char name[80]
Definition TGX11.cxx:142
void RegisterOperator(const std::string &name, ParserFuncSignature func)
std::unique_ptr< ROperator > ParseOperator(const size_t, const onnx::GraphProto &, const std::vector< size_t > &, const std::vector< int > &)
bool IsRegisteredOperator(const std::string &name)
void CheckGraph(const onnx::GraphProto &g, int &level, std::map< std::string, int > &missingOperators)
void ParseONNXGraph(RModel &model, const onnx::GraphProto &g, std::string name="")
std::unordered_map< std::string, ETensorType > fTensorTypeMap
RModel Parse(std::string const &filename, bool verbose=false)
std::shared_ptr< void > GetInitializedTensorData(onnx::TensorProto *tensorproto, size_t tensor_length, ETensorType type)
std::map< int, std::pair< EFusedOp, int > > fFusedOperators
void RegisterTensorType(const std::string &, ETensorType)
ETensorType GetTensorType(const std::string &name)
std::vector< std::string > GetRegisteredOperators()
std::unique_ptr< onnx::ModelProto > LoadModel(const std::string &filename)
std::unique_ptr< OperatorsMapImpl > fOperatorsMapImpl
bool CheckModel(std::string filename, bool verbose=false)
void AddInputTensorInfo(std::string input_name, ETensorType type, std::vector< Dim > shape)
Definition RModel.cxx:213
void AddOutputTensorNameList(std::vector< std::string > output_tensor_names)
Definition RModel.cxx:437
void AddInitializedTensor(std::string tensor_name, ETensorType type, std::vector< std::size_t > shape, std::shared_ptr< void > data)
Definition RModel.cxx:269
void AddInputTensorName(std::string name)
Definition RModel.cxx:232
void AddOperator(std::unique_ptr< ROperator > op, int order_execution=-1)
Definition RModel.cxx:236
const ValueInfoProto & input(int i) const
Definition onnx.hxx:549
const ValueInfoProto & output(int i) const
Definition onnx.hxx:551
const std::string & name() const
Definition onnx.hxx:545
const NodeProto & node(int i) const
Definition onnx.hxx:547
const TensorProto & initializer(int i) const
Definition onnx.hxx:553
const std::string & op_type() const
Definition onnx.hxx:506
const std::string & input(int i) const
Definition onnx.hxx:509
const std::string & output(int i) const
Definition onnx.hxx:512
const std::string & name() const
Definition onnx.hxx:507
const std::string & raw_data() const
Definition onnx.hxx:398
const std::vector< int64_t > & int64_data() const
Definition onnx.hxx:409
const std::vector< StringStringEntryProto > & external_data() const
Definition onnx.hxx:400
const std::vector< double > & double_data() const
Definition onnx.hxx:407
const std::string & name() const
Definition onnx.hxx:394
const std::vector< float > & float_data() const
Definition onnx.hxx:406
const std::vector< int32_t > & int32_data() const
Definition onnx.hxx:408
const TensorShapeProto_Dimension & dim(int i) const
Definition onnx.hxx:250
const TensorShapeProto & shape() const
Definition onnx.hxx:275
const TypeProto_Tensor & tensor_type() const
Definition onnx.hxx:302
std::string Clean_name(std::string input_tensor_name)
ParserFuncSignature ParseArgMax
ParserFuncSignature ParseBatchNormalization
std::function< std::unique_ptr< ROperator >(RModelParser_ONNX &, const onnx::NodeProto &, const onnx::NodeProto &)> ParserFuseFuncSignature
ParserFuncSignature ParseReshape
ParserFuseFuncSignature ParseFuseConvTransposeAdd
ParserFuseFuncSignature ParseFuseMatMulAdd
ParserFuncSignature ParseGather
ParserFuncSignature ParseWhere
Definition ParseWhere.cxx:9
ParserFuncSignature ParseLeakyRelu
std::function< std::unique_ptr< ROperator >(RModelParser_ONNX &, const onnx::NodeProto &)> ParserFuncSignature
ParserFuncSignature ParseEinsum
ParserFuncSignature ParsePool
Definition ParsePool.cxx:9
ParserFuncSignature ParseLayerNormalization
ParserFuncSignature ParseConcat
ParserFuncSignature ParseTopK
Definition ParseTopK.cxx:9
void RegisterReduceParsers(RModelParser_ONNX &parser)
ParserFuncSignature ParseIdentity
ParserFuncSignature ParseConvTranspose
ParserFuncSignature ParseNot
Definition ParseNot.cxx:9
ParserFuncSignature ParseSlice
Definition ParseSlice.cxx:9
ParserFuncSignature ParseRandom
ParserFuncSignature ParseTranspose
ParserFuncSignature ParseShape
ParserFuncSignature ParseClip
Definition ParseClip.cxx:25
constexpr size_t GetTypeSize(ETensorType type)
ParserFuncSignature ParseScatterND
void RegisterBasicBinaryParsers(RModelParser_ONNX &parser)
ParserFuncSignature ParseGRU
Definition ParseGRU.cxx:9
ParserFuncSignature ParseMatMul
ParserFuncSignature ParseErf
Definition ParseErf.cxx:9
ParserFuncSignature ParseNonZero
ParserFuncSignature ParseIf
Definition ParseIf.cxx:9
ParserFuncSignature ParseRange
Definition ParseRange.cxx:9
ParserFuncSignature ParseExpand
ParserFuncSignature ParseRNN
Definition ParseRNN.cxx:9
ParserFuncSignature ParseHardSigmoid
ParserFuncSignature ParseLSTM
Definition ParseLSTM.cxx:9
ParserFuncSignature ParseCast
Definition ParseCast.cxx:9
ParserFuncSignature ParseSwish
Definition ParseSwish.cxx:9
ParserFuncSignature ParseSigmoid
ParserFuseFuncSignature ParseFuseConvAdd
ParserFuncSignature ParsePRelu
Definition ParsePRelu.cxx:9
ParserFuseFuncSignature ParseFuseBatchnormRelu
ParserFuncSignature ParseSoftmax
void RegisterComparisionParsers(RModelParser_ONNX &parser)
std::string ConvertTypeToString(ETensorType type)
ParserFuncSignature ParseGelu
Definition ParseGelu.cxx:9
ParserFuncSignature ParseSplit
Definition ParseSplit.cxx:9
ParserFuncSignature ParseConstant
ParserFuncSignature ParseSelu
Definition ParseSelu.cxx:9
ParserFuncSignature ParseHardSwish
ParserFuncSignature ParseGatherND
ParserFuncSignature ParseEyeLike
ParserFuncSignature ParsePad
Definition ParsePad.cxx:9
ParserFuncSignature ParseElu
Definition ParseElu.cxx:9
void RegisterBasicIsParsers(RModelParser_ONNX &parser)
std::string ConvertShapeToString(const std::vector< size_t > &shape)
ParserFuncSignature ParseRelu
Definition ParseRelu.cxx:9
ParserFuncSignature ParseConv
Definition ParseConv.cxx:9
ParserFuncSignature ParseInstanceNormalization
ParserFuncSignature ParseScatterElements
ParserFuncSignature ParseGemm
Definition ParseGemm.cxx:9
ParserFuncSignature ParseTile
Definition ParseTile.cxx:9
ParserFuseFuncSignature ParseFuseGemmRelu
void RegisterBasicUnaryParsers(RModelParser_ONNX &parser)
ParserFuncSignature ParseThresholdedRelu
void RegisterBasicNaryParsers(RModelParser_ONNX &parser)
ParserFuncSignature ParseTanh
Definition ParseTanh.cxx:9
create variable transformations
Helper templated class for swapping bytes; specializations for N={2,4,8} are provided below.
Definition Byteswap.h:124
static void Copy(onnx::TensorProto *tensor, void *data, int length)
static void Copy(onnx::TensorProto *tensor, void *data, int length)
static void Copy(onnx::TensorProto *tensor, void *data, int length)
static void Copy(onnx::TensorProto *tensor, void *data, int length)
std::unordered_map< std::string, ParserFuncSignature > fOperatorsMap
TLine l
Definition textangle.C:4