/
OnnxParser.cpp
2590 lines (2234 loc) · 99.8 KB
/
OnnxParser.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright © 2017,2022-2023 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "OnnxParser.hpp"
#include "armnnOnnxParser/Version.hpp"
#include <armnn/Descriptors.hpp>
#include <armnn/utility/Assert.hpp>
#include <armnn/utility/NumericCast.hpp>
#include <ParserHelper.hpp>
#include <VerificationHelpers.hpp>
#include <fmt/format.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <iostream>
#include <numeric>
#include <armnnUtils/Permute.hpp>
using namespace armnn;
namespace armnnOnnxParser
{
IOnnxParser::IOnnxParser() : pOnnxParserImpl(new OnnxParserImpl()) {}
IOnnxParser::~IOnnxParser() = default;
IOnnxParser* IOnnxParser::CreateRaw()
{
return new IOnnxParser();
}
IOnnxParserPtr IOnnxParser::Create()
{
return IOnnxParserPtr(CreateRaw(), &IOnnxParser::Destroy);
}
void IOnnxParser::Destroy(IOnnxParser* parser)
{
delete parser;
}
armnn::INetworkPtr IOnnxParser::CreateNetworkFromBinaryFile(const char* graphFile)
{
return pOnnxParserImpl->CreateNetworkFromBinaryFile(graphFile);
}
armnn::INetworkPtr IOnnxParser::CreateNetworkFromBinary(const std::vector<uint8_t>& binaryContent)
{
return pOnnxParserImpl->CreateNetworkFromBinary(binaryContent);
}
armnn::INetworkPtr IOnnxParser::CreateNetworkFromBinary(const std::vector<uint8_t>& binaryContent,
const std::map<std::string, armnn::TensorShape>& inputShapes)
{
return pOnnxParserImpl->CreateNetworkFromBinary(binaryContent, inputShapes);
}
armnn::INetworkPtr IOnnxParser::CreateNetworkFromTextFile(const char* graphFile)
{
return pOnnxParserImpl->CreateNetworkFromTextFile(graphFile);
}
armnn::INetworkPtr IOnnxParser::CreateNetworkFromString(const std::string& protoText)
{
return pOnnxParserImpl->CreateNetworkFromString(protoText);
}
armnn::INetworkPtr IOnnxParser::CreateNetworkFromBinaryFile(
const char* graphFile,
const std::map<std::string, armnn::TensorShape>& inputShapes)
{
return pOnnxParserImpl->CreateNetworkFromBinaryFile(graphFile, inputShapes);
}
armnn::INetworkPtr IOnnxParser::CreateNetworkFromTextFile(const char* graphFile,
const std::map<std::string, armnn::TensorShape>& inputShapes)
{
return pOnnxParserImpl->CreateNetworkFromTextFile(graphFile, inputShapes);
}
armnn::INetworkPtr IOnnxParser::CreateNetworkFromString(const std::string& protoText,
const std::map<std::string, armnn::TensorShape>& inputShapes)
{
return pOnnxParserImpl->CreateNetworkFromString(protoText, inputShapes);
}
BindingPointInfo IOnnxParser::GetNetworkInputBindingInfo(const std::string& name) const
{
return pOnnxParserImpl->GetNetworkInputBindingInfo(name);
}
BindingPointInfo IOnnxParser::GetNetworkOutputBindingInfo(const std::string& name) const
{
return pOnnxParserImpl->GetNetworkOutputBindingInfo(name);
}
namespace
{
void CheckValidDataType(std::initializer_list<onnx::TensorProto::DataType> validInputTypes,
const onnx::TensorProto::DataType actualValue,
const char* validExpr,
std::string nodeName,
std::string tensorName,
const armnn::CheckLocation& location)
{
bool isValid = std::any_of(validInputTypes.begin(),
validInputTypes.end(),
[&actualValue](onnx::TensorProto::DataType x) { return x == actualValue; } );
if (!isValid)
{
throw ParseException(
fmt::format("Datatype {} is not valid for tensor '{}' of node '{}', not in {{{}}}. {}",
onnx::TensorProto::DataType_Name(actualValue),
tensorName,
nodeName,
validExpr,
location.AsString()));
}
}
#define CHECK_VALID_DATATYPE(NODE, TENSOR, ACTUAL, ...) \
CheckValidDataType({__VA_ARGS__}, ACTUAL, #__VA_ARGS__, NODE, TENSOR, CHECK_LOCATION())
using StrTypeListPair = std::pair<const char*, std::initializer_list<onnx::TensorProto::DataType>>;
#define STR_LIST(...) StrTypeListPair(#__VA_ARGS__, {__VA_ARGS__})
template <typename Callable>
void ReadMandatoryNodeAttributeImpl(const onnx::NodeProto& node,
const std::string& attribName,
onnx::AttributeProto::AttributeType expectedType,
Callable callable)
{
auto attribs = node.attribute();
int attriNum = 0;
while (attriNum < node.attribute_size())
{
if (attribs.Get(attriNum).name() == attribName)
{
if (attribs.Get(attriNum).type() == expectedType)
{
callable(attribs.Get(attriNum));
}
else
{
throw ParseException(fmt::format("Attribute {} of node {} expected to have {} as "
"onnx::AttributeProto::AttributeType, but found {} instead {}",
attribName,
node.name(),
onnx::AttributeProto::AttributeType_Name(expectedType),
onnx::AttributeProto::AttributeType_Name(attribs.Get(attriNum).type()),
CHECK_LOCATION().AsString()));
}
break;
}
++attriNum;
}
if (attriNum == node.attribute_size())
{
throw ParseException(fmt::format("Could not find required attribute {} in node {} {}",
attribName, node.name(), CHECK_LOCATION().AsString()));
}
}
template <typename Callable>
void ReadOptionalNodeAttributeImpl(const onnx::NodeProto& node,
const std::string& attribName,
onnx::AttributeProto::AttributeType expectedType,
Callable callable)
{
auto attribs = node.attribute();
for (int attriNum = 0; attriNum < node.attribute_size(); ++attriNum)
{
if (attribs.Get(attriNum).name() == attribName)
{
if (attribs.Get(attriNum).type() == expectedType)
{
callable(attribs.Get(attriNum));
}
else
{
throw ParseException(
fmt::format("Attribute {} of node {} expected to have {} as onnx::AttributeProto::AttributeType, "
"but found {} instead {}",
attribName,
node.name(),
onnx::AttributeProto::AttributeType_Name(expectedType),
onnx::AttributeProto::AttributeType_Name(attribs.Get(attriNum).type()),
CHECK_LOCATION().AsString()));
}
}
}
}
int ReadMandatoryNodeIntAttribute(const onnx::NodeProto& node,
const std::string& name)
{
int attribValue = 0;
ReadMandatoryNodeAttributeImpl(node, name, onnx::AttributeProto::INT,
[&attribValue](const onnx::AttributeProto& attrValue)
{
attribValue = CHECKED_INT32(attrValue.i());
});
return attribValue;
}
int64_t ReadOptionalNodeInt64Attribute(const onnx::NodeProto& node,
const std::string& name,
const int64_t defaultValue = 0)
{
int64_t attribValue = defaultValue;
ReadOptionalNodeAttributeImpl(node, name, onnx::AttributeProto::INT,
[&attribValue](const onnx::AttributeProto& attrValue)
{
attribValue = attrValue.i();
});
return attribValue;
}
std::vector<uint32_t> ReadMandatoryNodeUint32ListAttribute(const onnx::NodeProto& node,
const std::string& name)
{
std::vector<uint32_t> attriList;
ReadMandatoryNodeAttributeImpl(node, name, onnx::AttributeProto::INTS,
[&attriList](const onnx::AttributeProto& attrValue)
{
for (int attriNum = 0; attriNum < attrValue.ints_size(); ++attriNum)
{
attriList.push_back(CHECKED_NON_NEGATIVE(CHECKED_INT32(attrValue.ints().Get(attriNum))));
}
});
return attriList;
}
uint32_t ReadOptionalNodeUint32Attribute(const onnx::NodeProto& node,
const std::string& name,
const uint32_t defaultVal = 0u)
{
uint32_t attribValue = defaultVal;
ReadOptionalNodeAttributeImpl(node, name, onnx::AttributeProto::INT,
[&attribValue](const onnx::AttributeProto& attrValue)
{
attribValue = CHECKED_NON_NEGATIVE(CHECKED_INT32((attrValue.i())));
});
return attribValue;
}
std::vector<uint32_t> ReadOptionalNodeUint32ListAttribute(const onnx::NodeProto& node,
const std::string& name)
{
std::vector<uint32_t> attriList;
ReadOptionalNodeAttributeImpl(node, name, onnx::AttributeProto::INTS,
[&attriList](const onnx::AttributeProto& attrValue)
{
for (int attriNum = 0; attriNum < attrValue.ints_size(); ++attriNum)
{
attriList.push_back(CHECKED_NON_NEGATIVE(CHECKED_INT32(attrValue.ints().Get(attriNum))));
}
});
return attriList;
}
float ReadOptionalNodeFloatAttribute(const onnx::NodeProto& node,
const std::string& name,
const float defaultValue = 0.0f)
{
float attribValue = defaultValue;
ReadOptionalNodeAttributeImpl(node, name, onnx::AttributeProto::FLOAT,
[&attribValue](const onnx::AttributeProto& attrValue)
{
attribValue = attrValue.f();
});
return attribValue;
}
std::string ReadOptionalNodeStringAttribute(const onnx::NodeProto& node, const std::string& name)
{
std::string attribValue = "";
ReadOptionalNodeAttributeImpl(node, name, onnx::AttributeProto::STRING,
[&attribValue](const onnx::AttributeProto& attrValue)
{
attribValue = attrValue.s();
});
return attribValue;
}
armnn::TensorInfo ToTensorInfo(const std::string& name, std::vector<unsigned int>& shape, int data_type)
{
DataType type;
switch(data_type)
{
case onnx::TensorProto::FLOAT:
{
type = DataType::Float32;
break;
}
case onnx::TensorProto::INT32:
case onnx::TensorProto::INT64:
{
type = DataType::Signed32;
break;
}
default:
{
throw ParseException(
fmt::format("'{}' is not a currently supported datatype for tensor {}."
" Supported dataTypes are FLOAT, INT32 and INT64. {}",
onnx::TensorProto::DataType_Name(static_cast<onnx::TensorProto::DataType>(data_type)),
name,
CHECK_LOCATION().AsString() ));
}
}
// Scalar Tensor
if (shape.empty())
{
return TensorInfo(TensorShape(Dimensionality::Scalar), type);
}
// Dynamic Tensor
if(std::find(shape.begin(), shape.end(), 0) != shape.end())
{
return TensorInfo(TensorShape(Dimensionality::NotSpecified), type);
}
return TensorInfo(TensorShape(static_cast<unsigned int>(shape.size()), shape.data()), type);
}
armnn::TensorInfo ToTensorInfo(const onnx::ValueInfoProto& info)
{
const onnx::TensorShapeProto onnxShape = info.type().tensor_type().shape();
std::vector<unsigned int> shapeDims;
for (int i = 0; i < onnxShape.dim_size(); ++i)
{
shapeDims.push_back(CHECKED_NON_NEGATIVE(CHECKED_INT32(onnxShape.dim(i).dim_value())));
}
return ToTensorInfo(info.name(), shapeDims, info.type().tensor_type().elem_type());
}
armnn::TensorInfo ToTensorInfo(const onnx::TensorProto& tensor)
{
std::vector<unsigned int> shapeDims;
for (auto dim: tensor.dims())
{
shapeDims.push_back(CHECKED_NON_NEGATIVE(CHECKED_INT32(dim)));
}
return ToTensorInfo(tensor.name(), shapeDims, tensor.data_type());
}
std::string TensorInfoAsString(const TensorInfo& info,
const std::string& name,
const onnx::TensorProto::DataType& type)
{
const TensorShape shape = info.GetShape();
std::stringstream ss;
ss << "tensor '" << name << "' contains "
<< onnx::TensorProto::DataType_Name(type)
<< " and has shape [";
for (uint32_t i = 0; i < shape.GetNumDimensions() - 1; ++i)
{
ss << shape[i] << ", ";
}
ss << shape[shape.GetNumDimensions() - 1] << "]";
return ss.str();
}
void CalcPadding(uint32_t inputSize,
uint32_t filterSize,
uint32_t stride,
uint32_t dilation,
uint32_t* paddingFront,
uint32_t* paddingBack,
bool isUpper)
{
uint32_t outputSize = (inputSize + stride - 1) / stride;
uint32_t dilatedSize = filterSize + (dilation - 1) * (filterSize - 1);
uint32_t temp = (outputSize - 1) * stride + dilatedSize;
*paddingFront = (temp - inputSize) / 2;
*paddingBack = *paddingFront;
if((temp - inputSize) % 2 == 1)
{
if (isUpper)
{
*paddingBack += 1;
}
else
{
*paddingFront += 1;
}
}
}
TensorInfo ComputeReshapeInfo(const TensorShape& targetShapeTensor,
const TensorShape& inShape,
const std::string& outName,
DataType dataType = DataType::Float32)
{
std::vector<int> targetDims;
for(uint i = 0; i < targetShapeTensor.GetNumDimensions(); ++i)
{
int val = CHECKED_INT32(targetShapeTensor[i]);
if(val == 0)
{
targetDims.push_back(static_cast<int>(inShape[static_cast<uint>(i)]));
}
else
{
targetDims.push_back(val);
}
}
std::vector<unsigned int> outDims(targetDims.begin(), targetDims.end());
const auto stretchDim = std::find(targetDims.begin(), targetDims.end(), -1);
if (stretchDim != targetDims.end())
{
if (std::find(std::next(stretchDim), targetDims.end(), -1) != targetDims.end())
{
std::stringstream ss;
ss << "[ ";
for(uint i = 0; i < targetDims.size() - 1; ++i)
{
ss << targetDims[i] << ", ";
}
ss << targetDims[targetDims.size() - 1] << " ]";
throw ParseException(
fmt::format("Error during creation of reshaped tensor '{}'. At most one component of shape can be "
" -1 and here, shape is {} {}",
outName,
ss.str(),
CHECK_LOCATION().AsString()));
}
auto targetNumElements = armnn::numeric_cast<unsigned int>(std::accumulate(targetDims.begin(), targetDims.end(),
-1, std::multiplies<int32_t>()));
auto stretchIndex = static_cast<size_t>(std::distance(targetDims.begin(), stretchDim));
outDims[stretchIndex] = inShape.GetNumElements() / targetNumElements;
}
TensorShape outShape = TensorShape{static_cast<unsigned int>(outDims.size()), outDims.data()};
return TensorInfo(outShape, dataType);
}
} //namespace
const std::map<std::string, OnnxParserImpl::OperationParsingFunction> OnnxParserImpl::m_ParserFunctions = {
{ "BatchNormalization", &OnnxParserImpl::ParseBatchNormalization},
{ "GlobalAveragePool", &OnnxParserImpl::ParseGlobalAveragePool},
{ "AveragePool", &OnnxParserImpl::ParseAveragePool },
{ "Clip", &OnnxParserImpl::ParseClip },
{ "Constant", &OnnxParserImpl::ParseConstant },
{ "MaxPool", &OnnxParserImpl::ParseMaxPool },
{ "Reshape", &OnnxParserImpl::ParseReshape },
{ "Sigmoid", &OnnxParserImpl::ParseSigmoid },
{ "Tanh", &OnnxParserImpl::ParseTanh },
{ "Relu", &OnnxParserImpl::ParseRelu },
{ "LeakyRelu", &OnnxParserImpl::ParseLeakyRelu },
{ "Conv", &OnnxParserImpl::ParseConv },
{ "Add", &OnnxParserImpl::ParseAdd },
{ "Flatten", &OnnxParserImpl::ParseFlatten },
{ "Shape", &OnnxParserImpl::ParseShape },
{ "Gather", &OnnxParserImpl::ParseGather },
{ "Unsqueeze", &OnnxParserImpl::ParseUnsqueeze },
{ "Concat", &OnnxParserImpl::ParseConcat },
{ "Gemm", &OnnxParserImpl::ParseGemm }
};
template<typename TypePair, typename Location>
void OnnxParserImpl::ValidateInputs(const onnx::NodeProto& node,
TypePair validInputs,
const Location& location)
{
for(auto input : node.input())
{
CheckValidDataType(validInputs.second,
m_TensorsInfo[input].m_dtype,
validInputs.first,
node.name(),
input,
location);
}
}
#define VALID_INPUTS(NODE, VALID_INPUTS) \
OnnxParserImpl::ValidateInputs(NODE, \
VALID_INPUTS, \
CHECK_LOCATION())
std::vector<TensorInfo> OnnxParserImpl::ComputeOutputInfo(std::vector<std::string> outNames,
const IConnectableLayer* layer,
std::vector<TensorShape> inputShapes,
const onnx::TensorProto::DataType& dataType)
{
ARMNN_ASSERT(! outNames.empty());
bool needCompute = std::any_of(outNames.begin(),
outNames.end(),
[this](std::string name)
{
return (m_TensorsInfo.count(name) == 0 ||
m_TensorsInfo[name].m_info == nullptr ||
m_TensorsInfo[name].m_info->GetShape().GetDimensionality() ==
Dimensionality::NotSpecified);
});
std::vector<TensorInfo> outInfo;
//if the output info(s) are not here, we need to compute them
std::vector<TensorShape> inferredShapes;
DataType armnnType = DataType::Float32;
if(needCompute) {
inferredShapes = layer->InferOutputShapes(inputShapes);
ARMNN_ASSERT(inferredShapes.size() == outNames.size());
switch (dataType) {
case onnx::TensorProto::FLOAT: {
armnnType = DataType::Float32;
break;
}
case onnx::TensorProto::INT32:
case onnx::TensorProto::INT64: {
armnnType = DataType::Signed32;
break;
}
default: {
throw ParseException(
fmt::format("'{}' is not a currently supported datatype for {}."
" Supported dataTypes are FLOAT, INT32 and INT64. {}",
onnx::TensorProto::DataType_Name(static_cast<onnx::TensorProto::DataType>(dataType)),
layer->GetName(),
CHECK_LOCATION().AsString()));
}
}
}
for (uint i = 0; i < outNames.size(); ++i)
{
if(needCompute)
{
m_TensorsInfo[outNames[i]] = OnnxTensor();
m_TensorsInfo[outNames[i]].m_info = std::make_unique<TensorInfo>(
TensorInfo(inferredShapes[i], armnnType));
m_TensorsInfo[outNames[i]].m_dtype = dataType;
}
outInfo.push_back(*m_TensorsInfo[outNames[i]].m_info);
}
return outInfo;
}
OnnxParserImpl::OnnxParserImpl()
: m_Network(nullptr, nullptr)
{
}
void OnnxParserImpl::ResetParser()
{
m_Network = armnn::INetworkPtr(nullptr, nullptr);
m_Graph = nullptr;
m_InputInfos.clear();
m_OutputInfos.clear();
}
void OnnxParserImpl::Cleanup()
{
m_TensorConnections.clear();
m_TensorsInfo.clear();
m_OutputsMap.clear();
m_OutputsFusedAndUsed.clear();
m_InputShapes.clear();
}
template<typename T>
std::pair<armnn::ConstTensor, std::unique_ptr<T[]>>
CreateConstTensorImpl(const T* bufferPtr,
armnn::TensorInfo& tensorInfo,
const armnn::Optional<armnn::PermutationVector&> permutationVector)
{
ARMNN_ASSERT_MSG(bufferPtr != nullptr, fmt::format("Buffer for permutation is null").c_str());
std::unique_ptr<T[]> data(new T[tensorInfo.GetNumElements()]);
if (permutationVector.has_value() && permutationVector.value().GetSize() > 0)
{
tensorInfo = armnnUtils::Permuted(tensorInfo, permutationVector.value());
armnnUtils::Permute(tensorInfo.GetShape(), permutationVector.value(),
reinterpret_cast<const T*>(bufferPtr), data.get(), sizeof(T));
}
else
{
::memcpy(data.get(), bufferPtr, tensorInfo.GetNumBytes());
}
return std::make_pair(ConstTensor(tensorInfo, data.get()), std::move(data));
}
std::pair<ConstTensor, std::unique_ptr<float[]>>
OnnxParserImpl::CreateConstTensor(const std::string name,
armnn::Optional<armnn::PermutationVector&> permutationVector)
{
TensorInfo tensorInfo = *m_TensorsInfo[name].m_info;
onnx::TensorProto onnxTensor = *m_TensorsInfo[name].m_tensor;
//ONNX can have Float16 and double constant nodes but ArmNN only supports float32
CHECK_VALID_DATATYPE(name, onnxTensor.name(),
static_cast<onnx::TensorProto::DataType>(onnxTensor.data_type()), onnx::TensorProto::FLOAT);
// Makes sure IsConstant flag is set.
tensorInfo.SetConstant();
// Const tensors requires at least a list of values
if (tensorInfo.GetNumElements() == 0)
{
throw ParseException(fmt::format("No tensor data found for Const tensor '{}' {}",
name,
CHECK_LOCATION().AsString()));
}
auto srcData = onnxTensor.float_data().data();
// Copy the value list entries into the destination
if (!onnxTensor.has_raw_data())
{
if(tensorInfo.GetNumElements() != static_cast<uint>(onnxTensor.float_data_size()))
{
throw ParseException(
fmt::format("The number of data provided ({}) does not match the tensor '{}' number of "
"elements ({}) {}",
onnxTensor.float_data_size(),
name,
tensorInfo.GetNumElements(),
CHECK_LOCATION().AsString()));
}
return CreateConstTensorImpl<float>(srcData, tensorInfo, permutationVector);
}
else
{
return CreateConstTensorImpl<float>(reinterpret_cast<const float*>(onnxTensor.raw_data().c_str()),
tensorInfo,
permutationVector);
}
}
std::pair<ConstTensor, std::unique_ptr<int32_t[]>>
OnnxParserImpl::CreateInt64ConstTensor(const std::string name,
armnn::Optional<armnn::PermutationVector&> permutationVector)
{
TensorInfo tensorInfo = *m_TensorsInfo[name].m_info;
onnx::TensorProto onnxTensor = *m_TensorsInfo[name].m_tensor;
CHECK_VALID_DATATYPE(name, onnxTensor.name(),
static_cast<onnx::TensorProto::DataType>(onnxTensor.data_type()), onnx::TensorProto::INT64);
// Makes sure IsConstant flag is set.
tensorInfo.SetConstant();
uint numElements = tensorInfo.GetNumElements();
// Const tensors requires at least a list of values
if (numElements == 0)
{
throw ParseException(fmt::format("No tensor data found for Const tensor '{}' {}",
name,
CHECK_LOCATION().AsString()));
}
// Copy the value list entries into the destination
if (!onnxTensor.has_raw_data())
{
auto srcData = onnxTensor.int64_data().data();
if(numElements != static_cast<uint>(onnxTensor.int64_data_size()))
{
throw ParseException(
fmt::format("The number of data provided ({}) does not match the tensor '{}' number of "
"elements ({}) {}",
onnxTensor.int64_data_size(),
name,
tensorInfo.GetNumElements(),
CHECK_LOCATION().AsString()));
}
std::vector<int32_t> int32Data;
for(uint i = 0; i < numElements; i++)
{
int32_t int32Value = CHECKED_INT32(srcData[i]);
int32Data.push_back(int32Value);
}
return CreateConstTensorImpl<int32_t>(int32Data.data(), tensorInfo, permutationVector);
}
else
{
auto srcData = reinterpret_cast<const int64_t*>(onnxTensor.raw_data().c_str());
std::vector<int32_t> int32Data;
for(uint i = 0; i < numElements; i++)
{
int32_t int32Value = CHECKED_INT32(srcData[i]);
int32Data.push_back(int32Value);
}
return CreateConstTensorImpl<int32_t>(int32Data.data(), tensorInfo, permutationVector);
}
}
ModelPtr OnnxParserImpl::LoadModelFromTextFile(const char* graphFile)
{
FILE* fd = fopen(graphFile, "r");
if (fd == nullptr)
{
throw FileNotFoundException(fmt::format("Invalid (null) filename {}", CHECK_LOCATION().AsString()));
}
// Parse the file into a message
ModelPtr modelProto = std::make_unique<onnx::ModelProto>();
using google::protobuf::io::FileInputStream;
std::unique_ptr<FileInputStream> input = std::make_unique<FileInputStream>(fileno(fd));
bool success = google::protobuf::TextFormat::Parse(input.get(), modelProto.get());
fclose(fd);
if (!success)
{
std::stringstream error;
error << "Failed to parse graph file";
throw ParseException(fmt::format("{} {}", error.str(), CHECK_LOCATION().AsString()));
}
return modelProto;
}
INetworkPtr OnnxParserImpl::CreateNetworkFromTextFile(const char* graphFile)
{
ResetParser();
ModelPtr modelProto = LoadModelFromTextFile(graphFile);
return CreateNetworkFromModel(*modelProto);
}
INetworkPtr OnnxParserImpl::CreateNetworkFromTextFile(const char* graphFile,
const std::map<std::string, armnn::TensorShape>& inputShapes)
{
ResetParser();
m_InputShapes = inputShapes;
ModelPtr modelProto = LoadModelFromTextFile(graphFile);
return CreateNetworkFromModel(*modelProto);
}
INetworkPtr OnnxParserImpl::CreateNetworkFromBinary(const std::vector<uint8_t>& binaryContent)
{
ResetParser();
ModelPtr modelProto = LoadModelFromBinary(binaryContent);
return CreateNetworkFromModel(*modelProto);
}
INetworkPtr OnnxParserImpl::CreateNetworkFromBinary(const std::vector<uint8_t>& binaryContent,
const std::map<std::string, armnn::TensorShape>& inputShapes)
{
ResetParser();
m_InputShapes = inputShapes;
ModelPtr modelProto = LoadModelFromBinary(binaryContent);
return CreateNetworkFromModel(*modelProto);
}
ModelPtr OnnxParserImpl::LoadModelFromBinary(const std::vector<uint8_t>& binaryContent)
{
if (binaryContent.size() == 0)
{
throw ParseException(fmt::format("Missing binary content", CHECK_LOCATION().AsString()));
}
// Parse the file into a message
ModelPtr modelProto = std::make_unique<onnx::ModelProto>();
google::protobuf::io::CodedInputStream codedStream(binaryContent.data(), static_cast<int>(binaryContent.size()));
codedStream.SetTotalBytesLimit(INT_MAX);
bool success = modelProto.get()->ParseFromCodedStream(&codedStream);
if (!success)
{
std::stringstream error;
error << "Failed to parse graph";
throw ParseException(fmt::format("{} {}", error.str(), CHECK_LOCATION().AsString()));
}
return modelProto;
}
ModelPtr OnnxParserImpl::LoadModelFromBinaryFile(const char* graphFile)
{
FILE* fd = fopen(graphFile, "rb");
if (fd == nullptr)
{
throw FileNotFoundException(fmt::format("Invalid (null) filename {}", CHECK_LOCATION().AsString()));
}
// Parse the file into a message
ModelPtr modelProto = std::make_unique<onnx::ModelProto>();
google::protobuf::io::FileInputStream inStream(fileno(fd));
google::protobuf::io::CodedInputStream codedStream(&inStream);
codedStream.SetTotalBytesLimit(INT_MAX);
bool success = modelProto.get()->ParseFromCodedStream(&codedStream);
fclose(fd);
if (!success)
{
std::stringstream error;
error << "Failed to parse graph file";
throw ParseException(fmt::format("{} {}", error.str(), CHECK_LOCATION().AsString()));
}
return modelProto;
}
INetworkPtr OnnxParserImpl::CreateNetworkFromBinaryFile(const char* graphFile)
{
ResetParser();
ModelPtr modelProto = LoadModelFromBinaryFile(graphFile);
return CreateNetworkFromModel(*modelProto);
}
INetworkPtr OnnxParserImpl::CreateNetworkFromBinaryFile(const char* graphFile,
const std::map<std::string, armnn::TensorShape>& inputShapes)
{
ResetParser();
m_InputShapes = inputShapes;
ModelPtr modelProto = LoadModelFromBinaryFile(graphFile);
return CreateNetworkFromModel(*modelProto);
}
ModelPtr OnnxParserImpl::LoadModelFromString(const std::string& protoText)
{
if (protoText == "")
{
throw InvalidArgumentException(fmt::format("Invalid (empty) string for model parameter {}",
CHECK_LOCATION().AsString()));
}
// Parse the string into a message
ModelPtr modelProto = std::make_unique<onnx::ModelProto>();
bool success = google::protobuf::TextFormat::ParseFromString(protoText, modelProto.get());
if (!success)
{
std::stringstream error;
error << "Failed to parse graph file";
throw ParseException(fmt::format("{} {}", error.str(), CHECK_LOCATION().AsString()));
}
return modelProto;
}
INetworkPtr OnnxParserImpl::CreateNetworkFromString(const std::string& protoText)
{
ResetParser();
ModelPtr modelProto = LoadModelFromString(protoText);
return CreateNetworkFromModel(*modelProto);
}
INetworkPtr OnnxParserImpl::CreateNetworkFromString(const std::string& protoText,
const std::map<std::string, armnn::TensorShape>& inputShapes)
{
ResetParser();
m_InputShapes = inputShapes;
ModelPtr modelProto = LoadModelFromString(protoText);
return CreateNetworkFromModel(*modelProto);
}
INetworkPtr OnnxParserImpl::CreateNetworkFromModel(onnx::ModelProto& model)
{
m_Network = INetwork::Create();
try
{
m_Graph = std::make_unique<onnx::GraphProto>(*model.mutable_graph());
LoadGraph();
}
catch (const ParseException& e)
{
Cleanup();
throw e;
}
Cleanup();
return std::move(m_Network);
}
void OnnxParserImpl::LoadGraph()
{
ARMNN_ASSERT(m_Graph.get() != nullptr);
//Fill m_TensorsInfo with the shapes and value of every tensor
SetupInfo(m_Graph->mutable_output());
SetupInfo(m_Graph->mutable_input());
SetupInfo(m_Graph->mutable_value_info());
for (auto tensor : m_Graph->initializer())
{
m_TensorsInfo[tensor.name()].m_tensor = std::make_unique<const onnx::TensorProto>(tensor);
m_TensorsInfo[tensor.name()].m_info = std::make_unique<TensorInfo>(ToTensorInfo(tensor));
m_TensorsInfo[tensor.name()].m_dtype =
static_cast<onnx::TensorProto::DataType>(tensor.data_type());
}
SetupInputLayers();
SetupOutputLayers();
//Detect FullyConnected layers with bias and update the FusedAndUsed map acccordingly
DetectFullyConnected();
//Parsing the graph
for(size_t nodeIndex = 0; nodeIndex < static_cast<size_t>(m_Graph->node_size()); nodeIndex++)
{
auto node = m_Graph->node(static_cast<int>(nodeIndex));
const std::string& operation = node.op_type();
// check which layers we handled already (add and matmul fused as FC)
if (operation == "MatMul" )
{
if(m_OutputsFusedAndUsed[nodeIndex].inputForNodes != m_OutputsFusedAndUsed[nodeIndex].fusedWithNodes.size())
{
//Node which can not be fused as a FullyConnected layer (used in layers as a simple matmul output)
AddFullyConnected(node);
}
}
else if (!(m_OutputsFusedAndUsed[nodeIndex].fusedWithNodes.empty()) && operation == "Add")
{
int matmulIndex = static_cast<int> (m_OutputsFusedAndUsed[nodeIndex].fusedWithNodes[0]);
AddFullyConnected(m_Graph->node(matmulIndex), &node);
}
else if (m_OutputsFusedAndUsed[nodeIndex].fusedWithNodes.empty()) //node is not part of a fused layer
{
auto it = m_ParserFunctions.find(operation);
if (it != m_ParserFunctions.end())
{
auto func = it->second;
(this->*func)(node);
}
else
{
throw ParseException(fmt::format("Unsupported operation {} for node '{}' {}",
operation,
node.name(),
CHECK_LOCATION().AsString()));
}
}
}
//Making the connections between outputs and inputs of each layers
for (const auto& tensorCon : m_TensorConnections)
{
if (tensorCon.second.outputSlot != nullptr)
{
for (size_t inputSlotIdx = 0; inputSlotIdx < tensorCon.second.inputSlots.size(); ++inputSlotIdx)
{
tensorCon.second.outputSlot->Connect(*(tensorCon.second.inputSlots[inputSlotIdx]));
}
}
}
// Get output info.
for(int outputIndex = 0; outputIndex < m_Graph->output_size(); ++outputIndex)
{
auto output = m_Graph->output(outputIndex);
m_OutputInfos[output.name()] = *m_TensorsInfo[output.name()].m_info;
}
}
void OnnxParserImpl::SetupInfo(const google::protobuf::RepeatedPtrField<onnx::ValueInfoProto >* list)
{
for (auto tensor : *list)
{
m_TensorsInfo[tensor.name()] = OnnxTensor();
m_TensorsInfo[tensor.name()].m_info = std::make_unique<TensorInfo>(ToTensorInfo(tensor));
m_TensorsInfo[tensor.name()].m_dtype =
static_cast<onnx::TensorProto::DataType>(tensor.type().tensor_type().elem_type());
}
}
void OnnxParserImpl::DetectFullyConnected()
{
m_OutputsFusedAndUsed = std::vector<UsageSummary> (static_cast<size_t>(m_Graph->node_size()), UsageSummary());
auto matmulAndConstant = [&](const std::string& constInput,
const std::string& matmulInput,
int& nodeIndex)
{
auto matmulIt = m_OutputsMap.find(matmulInput);
if(matmulIt != m_OutputsMap.end() && matmulIt->second.first->op_type() == "MatMul"
&& m_TensorsInfo[constInput].isConstant())
{
nodeIndex = matmulIt->second.second;
return true;
}
return false;
};
for(int nodeIndex = 0; nodeIndex < m_Graph->node_size(); nodeIndex++)
{
const onnx::NodeProto* node = &m_Graph->node(nodeIndex);
for (const std::string& output : node->output())
{
m_OutputsMap[output] = std::make_pair(node, nodeIndex);
}
for (const std::string& input : node->input()) //count how many time a node is used as input
{
auto matmulIt = m_OutputsMap.find(input);
if(matmulIt != m_OutputsMap.end()){