blob: a62383b563d9006fb0645cd2fabdb64e80895491 [file] [log] [blame]
telsoa01c577f2c2018-08-31 09:22:23 +01001//
2// Copyright © 2017 Arm Ltd. All rights reserved.
David Beckecb56cd2018-09-05 12:52:57 +01003// SPDX-License-Identifier: MIT
telsoa01c577f2c2018-08-31 09:22:23 +01004//
5#include "OnnxParser.hpp"
6
7#include <armnn/ArmNN.hpp>
8#include <armnn/Utils.hpp>
9#include <VerificationHelpers.hpp>
10
Aron Virginas-Tard4f0fea2019-04-09 14:08:06 +010011#include <boost/format.hpp>
12#include <boost/numeric/conversion/cast.hpp>
13
telsoa01c577f2c2018-08-31 09:22:23 +010014#include <google/protobuf/text_format.h>
15#include <google/protobuf/io/zero_copy_stream_impl.h>
16
telsoa01c577f2c2018-08-31 09:22:23 +010017#include <numeric>
18
19using namespace armnn;
20
21namespace armnnOnnxParser
22{
23namespace
24{
25void CheckValidDataType(std::initializer_list<onnx::TensorProto::DataType> validInputTypes,
26 const onnx::TensorProto::DataType actualValue,
27 const char* validExpr,
28 std::string nodeName,
29 std::string tensorName,
30 const armnn::CheckLocation& location)
31{
32 bool isValid = std::any_of(validInputTypes.begin(),
33 validInputTypes.end(),
34 [&actualValue](onnx::TensorProto::DataType x) { return x == actualValue; } );
35 if (!isValid)
36 {
37 throw ParseException(
38 boost::str(
39 boost::format("Datatype %1% is not valid for tensor '%2%' of node '%3%', not in {%4%}. %5%") %
40 onnx::TensorProto::DataType_Name(actualValue) %
41 tensorName %
42 nodeName %
43 validExpr %
44 location.AsString()));
45 }
46}
47
48#define CHECK_VALID_DATATYPE(NODE, TENSOR, ACTUAL, ...) \
49CheckValidDataType({__VA_ARGS__}, ACTUAL, #__VA_ARGS__, NODE, TENSOR, CHECK_LOCATION())
50
51using StrTypeListPair = std::pair<const char*, std::initializer_list<onnx::TensorProto::DataType>>;
52#define STR_LIST(...) StrTypeListPair(#__VA_ARGS__, {__VA_ARGS__})
53
54template <typename Callable>
55void ReadMandatoryNodeAttributeImpl(const onnx::NodeProto& node,
56 const std::string& attribName,
57 onnx::AttributeProto::AttributeType expectedType,
58 Callable callable)
59{
60 auto attribs = node.attribute();
61 int attriNum = 0;
62 while (attriNum < node.attribute_size())
63 {
64 if (attribs.Get(attriNum).name() == attribName)
65 {
66 if (attribs.Get(attriNum).type() == expectedType)
67 {
68 callable(attribs.Get(attriNum));
69 }
70 else
71 {
72 throw ParseException(boost::str(boost::format(
73 "Attribute %1% of node %2% expected to have %3% as onnx::AttributeProto::AttributeType, "
74 "but found %4% instead %5%")
75 % attribName
76 % node.name()
77 % onnx::AttributeProto::AttributeType_Name(expectedType)
78 % onnx::AttributeProto::AttributeType_Name(attribs.Get(attriNum).type())
79 % CHECK_LOCATION().AsString()));
80 }
81 break;
82 }
83 ++attriNum;
84 }
85 if (attriNum == node.attribute_size())
86 {
87 throw ParseException(boost::str(boost::format("Could not find required attribute %1% in node %2% %3%")
88 % attribName % node.name() % CHECK_LOCATION().AsString()));
89 }
90}
91
92template <typename Callable>
93void ReadOptionalNodeAttributeImpl(const onnx::NodeProto& node,
94 const std::string& attribName,
95 onnx::AttributeProto::AttributeType expectedType,
96 Callable callable)
97{
98 auto attribs = node.attribute();
99 for (int attriNum = 0; attriNum < node.attribute_size(); ++attriNum)
100 {
101 if (attribs.Get(attriNum).name() == attribName)
102 {
103 if (attribs.Get(attriNum).type() == expectedType)
104 {
105 callable(attribs.Get(attriNum));
106 }
107 else
108 {
109 throw ParseException(boost::str(boost::format(
110 "Attribute %1% of node %2% expected to have %3% as onnx::AttributeProto::AttributeType, "
111 "but found %4% instead %5%")
112 % attribName
113 % node.name()
114 % onnx::AttributeProto::AttributeType_Name(expectedType)
115 % onnx::AttributeProto::AttributeType_Name(attribs.Get(attriNum).type())
116 % CHECK_LOCATION().AsString()));
117 }
118 }
119 }
120}
121
122std::vector<uint32_t> ReadMandatoryNodeUint32ListAttribute(const onnx::NodeProto& node,
123 const std::string& name)
124{
125 std::vector<uint32_t> attriList;
126 ReadMandatoryNodeAttributeImpl(node, name, onnx::AttributeProto::INTS,
127 [&attriList](const onnx::AttributeProto& attrValue)
128 {
129 for (int attriNum = 0; attriNum < attrValue.ints_size(); ++attriNum)
130 {
131 attriList.push_back(CHECKED_NON_NEGATIVE(CHECKED_INT32(attrValue.ints().Get(attriNum))));
132 }
133 });
134 return attriList;
135}
136
137uint32_t ReadOptionalNodeUint32Attribute(const onnx::NodeProto& node,
138 const std::string& name,
139 const uint32_t defaultVal = 0u)
140{
141 uint32_t attribValue = defaultVal;
142 ReadOptionalNodeAttributeImpl(node, name, onnx::AttributeProto::INT,
143 [&attribValue](const onnx::AttributeProto& attrValue)
144 {
145 attribValue = CHECKED_NON_NEGATIVE(CHECKED_INT32((attrValue.i())));
146 });
147 return attribValue;
148}
149
150std::vector<uint32_t> ReadOptionalNodeUint32ListAttribute(const onnx::NodeProto& node,
151 const std::string& name)
152{
153 std::vector<uint32_t> attriList;
154 ReadOptionalNodeAttributeImpl(node, name, onnx::AttributeProto::INTS,
155 [&attriList](const onnx::AttributeProto& attrValue)
156 {
157 for (int attriNum = 0; attriNum < attrValue.ints_size(); ++attriNum)
158 {
159 attriList.push_back(CHECKED_NON_NEGATIVE(CHECKED_INT32(attrValue.ints().Get(attriNum))));
160 }
161 });
162
163 return attriList;
164}
165
166float ReadOptionalNodeFloatAttribute(const onnx::NodeProto& node,
167 const std::string& name,
168 const float defaultValue = 0.0f)
169{
170 float attribValue = defaultValue;
171 ReadOptionalNodeAttributeImpl(node, name, onnx::AttributeProto::FLOAT,
172 [&attribValue](const onnx::AttributeProto& attrValue)
173 {
174 attribValue = attrValue.f();
175 });
176 return attribValue;
177}
178
179std::string ReadOptionalNodeStringAttribute(const onnx::NodeProto& node, const std::string& name)
180{
181 std::string attribValue = "";
182 ReadOptionalNodeAttributeImpl(node, name, onnx::AttributeProto::STRING,
183 [&attribValue](const onnx::AttributeProto& attrValue)
184 {
185 attribValue = attrValue.s();
186 });
187 return attribValue;
188}
189
190armnn::TensorInfo ToTensorInfo(const onnx::ValueInfoProto& info)
191{
192 const onnx::TensorShapeProto onnxShape = info.type().tensor_type().shape();
193 std::vector<unsigned int> shapeDims;
194 for (int i = 0; i < onnxShape.dim_size(); ++i)
195 {
196 shapeDims.push_back(CHECKED_NON_NEGATIVE(CHECKED_INT32(onnxShape.dim(i).dim_value())));
197 }
198 DataType type;
199 switch(info.type().tensor_type().elem_type())
200 {
201 case onnx::TensorProto::FLOAT:
202 {
203 type = DataType::Float32;
204 break;
205 }
206 case onnx::TensorProto::INT32:
207 case onnx::TensorProto::INT64:
208 {
209 type = DataType::Signed32;
210 break;
211 }
212 default:
213 {
214 throw ParseException(
215 boost::str(
216 boost::format("'%1%' is not a currently supported datatype for tensor %2%."
217 " Supported dataTypes are FLOAT, INT32 and INT64. %3%") %
Matteo Martincighe355dc22018-12-10 13:45:27 +0000218 onnx::TensorProto::DataType_Name(
219 static_cast<onnx::TensorProto::DataType>(info.type().tensor_type().elem_type())) %
telsoa01c577f2c2018-08-31 09:22:23 +0100220 info.name() %
221 CHECK_LOCATION().AsString() ));
222 }
223
224 }
225 return TensorInfo(TensorShape(static_cast<unsigned int>(shapeDims.size()), shapeDims.data()), type);
226}
227
228std::string TensorInfoAsString(const TensorInfo& info,
229 const std::string& name,
230 const onnx::TensorProto::DataType& type)
231{
232 const TensorShape shape = info.GetShape();
233 std::stringstream ss;
234 ss << "tensor '" << name << "' contains "
235 << onnx::TensorProto::DataType_Name(type)
236 << " and has shape [";
237
238 for (uint32_t i = 0; i < shape.GetNumDimensions() - 1; ++i)
239 {
240 ss << shape[i] << ", ";
241 }
242 ss << shape[shape.GetNumDimensions() - 1] << "]";
243 return ss.str();
244}
245
246void CalcPadding(uint32_t inputSize, uint32_t filterSize, uint32_t stride, uint32_t* paddingFront,
247 uint32_t* paddingBack, bool isUpper)
248{
249 uint32_t outputSize = (inputSize + stride - 1) / stride;
250 uint32_t temp = (outputSize - 1) * stride + filterSize;
251 *paddingFront = (temp - inputSize) / 2;
252 *paddingBack = *paddingFront;
253 if((temp - inputSize) % 2 == 1)
254 {
255 if (isUpper)
256 {
257 *paddingBack += 1;
258 }
259 else
260 {
261 *paddingFront += 1;
262 }
263 }
264}
265
266TensorInfo ComputeReshapeInfo(const onnx::TensorProto& targetShapeTensor,
267 const TensorShape& inShape,
268 const std::string& outName)
269{
270 std::vector<int> targetDims;
271 for(int i = 0; i < targetShapeTensor.int64_data_size(); ++i)
272 {
273 int val = CHECKED_INT32(targetShapeTensor.int64_data(i));
274 if(val == 0)
275 {
276 targetDims.push_back(static_cast<int>(inShape[static_cast<uint>(i)]));
277 }
278 else
279 {
280 targetDims.push_back(val);
281 }
282 }
283
284 std::vector<unsigned int> outDims(targetDims.begin(), targetDims.end());
285 const auto stretchDim = std::find(targetDims.begin(), targetDims.end(), -1);
286 if (stretchDim != targetDims.end())
287 {
288 if (std::find(std::next(stretchDim), targetDims.end(), -1) != targetDims.end())
289 {
290 std::stringstream ss;
291 ss << "[ ";
292 for(uint i = 0; i < targetDims.size() - 1; ++i)
293 {
294 ss << targetDims[i] << ", ";
295 }
296 ss << targetDims[targetDims.size() - 1] << " ]";
297
298 throw ParseException(boost::str(
299 boost::format("Error during creation of reshaped tensor '%1%'. At most one component of shape can be "
300 " -1 and here, shape is %2% %3%")
301 % outName
302 % ss.str()
303 % CHECK_LOCATION().AsString()));
304 }
305
306 auto targetNumElements = boost::numeric_cast<unsigned int>(std::accumulate(targetDims.begin(), targetDims.end(),
307 -1, std::multiplies<int32_t>()));
308 auto stretchIndex = static_cast<size_t>(std::distance(targetDims.begin(), stretchDim));
309 outDims[stretchIndex] = inShape.GetNumElements() / targetNumElements;
310 }
311 TensorShape outShape = TensorShape{static_cast<unsigned int>(outDims.size()), outDims.data()};
312 return TensorInfo(outShape, DataType::Float32);
313}
314
315} //namespace
316
317const std::map<std::string, OnnxParser::OperationParsingFunction> OnnxParser::m_ParserFunctions = {
318 { "BatchNormalization", &OnnxParser::ParseBatchNormalization},
319 { "GlobalAveragePool", &OnnxParser::ParseGlobalAveragePool},
320 { "AveragePool", &OnnxParser::ParseAveragePool },
321 { "Constant", &OnnxParser::ParseConstant },
322 { "MaxPool", &OnnxParser::ParseMaxPool },
323 { "Reshape", &OnnxParser::ParseReshape },
324 { "Relu", &OnnxParser::ParseRelu },
325 { "Conv", &OnnxParser::ParseConv },
326 { "Add", &OnnxParser::ParseAdd },
327};
328
329template<typename TypePair, typename Location>
330void OnnxParser::ValidateInputs(const onnx::NodeProto& node,
331 TypePair validInputs,
332 const Location& location)
333{
334 for(auto input : node.input())
335 {
336 CheckValidDataType(validInputs.second,
337 m_TensorsInfo[input].m_dtype,
338 validInputs.first,
339 node.name(),
340 input,
341 location);
342 }
343}
344
345#define VALID_INPUTS(NODE, VALID_INPUTS) \
346 OnnxParser::ValidateInputs(NODE, \
347 VALID_INPUTS, \
348 CHECK_LOCATION())
349
350std::vector<TensorInfo> OnnxParser::ComputeOutputInfo(std::vector<std::string> outNames,
351 const IConnectableLayer* layer,
352 std::vector<TensorShape> inputShapes)
353{
354 BOOST_ASSERT(! outNames.empty());
355 bool needCompute = std::any_of(outNames.begin(),
356 outNames.end(),
357 [this](std::string name)
358 {
359 return (m_TensorsInfo.count(name) == 0 || m_TensorsInfo[name].m_info == nullptr);
360 });
361 std::vector<TensorInfo> outInfo;
362 //if the output info(s) are not here, we need to compute them
363 std::vector<TensorShape> inferredShapes;
364 if(needCompute)
365 {
366 inferredShapes = layer->InferOutputShapes(inputShapes);
367 BOOST_ASSERT(inferredShapes.size() == outNames.size());
368 }
369 for (uint i = 0; i < outNames.size(); ++i)
370 {
371 if(needCompute)
372 {
373 m_TensorsInfo[outNames[i]] = OnnxTensor();
374 m_TensorsInfo[outNames[i]].m_info = std::make_unique<TensorInfo>(
375 TensorInfo(inferredShapes[i], DataType::Float32));
376 }
377 outInfo.push_back(*m_TensorsInfo[outNames[i]].m_info);
378 }
379 return outInfo;
380}
381
382IOnnxParser* IOnnxParser::CreateRaw()
383{
384 return new OnnxParser();
385}
386
387IOnnxParserPtr IOnnxParser::Create()
388{
389 return IOnnxParserPtr(CreateRaw(), &IOnnxParser::Destroy);
390}
391
392void IOnnxParser::Destroy(IOnnxParser* parser)
393{
394 delete parser;
395}
396
397OnnxParser::OnnxParser()
398 : m_Network(nullptr, nullptr)
399{
400}
401
402void OnnxParser::ResetParser()
403{
404 m_Network = armnn::INetworkPtr(nullptr, nullptr);
405 m_Graph = nullptr;
406}
407
408void OnnxParser::Cleanup()
409{
410 m_TensorConnections.clear();
411 m_TensorsInfo.clear();
412 m_OutputsMap.clear();
413 m_OutputsFusedAndUsed.clear();
414}
415
416std::pair<ConstTensor, std::unique_ptr<float[]>> OnnxParser::CreateConstTensor(const std::string name)
417{
418 const TensorInfo tensorInfo = *m_TensorsInfo[name].m_info;
419 onnx::TensorProto onnxTensor = *m_TensorsInfo[name].m_tensor;
420
421 auto srcData = onnxTensor.float_data().data();
Pablo Tello3dcc1c62019-04-24 14:20:21 +0100422 std::unique_ptr<float[]> tensorData(new float[tensorInfo.GetNumElements()]);
423 const size_t tensorSizeInBytes = tensorInfo.GetNumBytes();
424 // Copy the value list entries into the destination
425 if (!onnxTensor.has_raw_data())
telsoa01c577f2c2018-08-31 09:22:23 +0100426 {
Pablo Tello3dcc1c62019-04-24 14:20:21 +0100427 if(tensorInfo.GetNumElements() != static_cast<uint>(onnxTensor.float_data_size()))
428 {
429 throw ParseException(boost::str(
430 boost::format("The number of data provided (%1%) does not match the tensor '%2%' number of elements"
telsoa01c577f2c2018-08-31 09:22:23 +0100431 " (%3%) %4%")
432 % onnxTensor.float_data_size()
433 % name
434 % tensorInfo.GetNumElements()
435 % CHECK_LOCATION().AsString()));
Pablo Tello3dcc1c62019-04-24 14:20:21 +0100436 }
437 ::memcpy(tensorData.get(), srcData, tensorSizeInBytes);
telsoa01c577f2c2018-08-31 09:22:23 +0100438 }
Pablo Tello3dcc1c62019-04-24 14:20:21 +0100439 else
440 {
441 ::memcpy(tensorData.get(), onnxTensor.raw_data().c_str(), tensorSizeInBytes);
442 }
telsoa01c577f2c2018-08-31 09:22:23 +0100443
444 // Const tensors requires at least a list of values
445 if (tensorInfo.GetNumElements() == 0)
446 {
447 throw ParseException(boost::str(
448 boost::format("No tensor data found for Const tensor '%1%' %2%")
449 % name
450 % CHECK_LOCATION().AsString()));
451 }
452 return std::make_pair(ConstTensor(tensorInfo, tensorData.get()), std::move(tensorData));
453}
454
455ModelPtr OnnxParser::LoadModelFromTextFile(const char* graphFile)
456{
457 FILE* fd = fopen(graphFile, "r");
458
459 if (fd == nullptr)
460 {
461 throw FileNotFoundException(boost::str(
462 boost::format("Invalid (null) filename %1%") % CHECK_LOCATION().AsString()));
463 }
464
465 // Parse the file into a message
466 ModelPtr modelProto = std::make_unique<onnx::ModelProto>();
467 using google::protobuf::io::FileInputStream;
468 std::unique_ptr<FileInputStream> input = std::make_unique<FileInputStream>(fileno(fd));
469 bool success = google::protobuf::TextFormat::Parse(input.get(), modelProto.get());
470 fclose(fd);
471
472 if (!success)
473 {
474 std::stringstream error;
475 error << "Failed to parse graph file";
476 throw ParseException(boost::str(
477 boost::format("%1% %2%") % error.str() % CHECK_LOCATION().AsString()));
478 }
479 return modelProto;
480}
481
482INetworkPtr OnnxParser::CreateNetworkFromTextFile(const char* graphFile)
483{
484 ResetParser();
485 ModelPtr modelProto = LoadModelFromTextFile(graphFile);
486 return CreateNetworkFromModel(*modelProto);
487}
488
489
490ModelPtr OnnxParser::LoadModelFromBinaryFile(const char* graphFile)
491{
492 FILE* fd = fopen(graphFile, "rb");
493
494 if (fd == nullptr)
495 {
496 throw FileNotFoundException(boost::str(
497 boost::format("Invalid (null) filename %1%") % CHECK_LOCATION().AsString()));
498 }
499
500 // Parse the file into a message
501 ModelPtr modelProto = std::make_unique<onnx::ModelProto>();
502
503 google::protobuf::io::FileInputStream inStream(fileno(fd));
504 google::protobuf::io::CodedInputStream codedStream(&inStream);
505 codedStream.SetTotalBytesLimit(INT_MAX, INT_MAX);
506 bool success = modelProto.get()->ParseFromCodedStream(&codedStream);
507 fclose(fd);
508
509 if (!success)
510 {
511 std::stringstream error;
512 error << "Failed to parse graph file";
513 throw ParseException(boost::str(
514 boost::format("%1% %2%") % error.str() % CHECK_LOCATION().AsString()));
515 }
516 return modelProto;
517
518}
519
520INetworkPtr OnnxParser::CreateNetworkFromBinaryFile(const char* graphFile)
521{
522 ResetParser();
523 ModelPtr modelProto = LoadModelFromBinaryFile(graphFile);
524 return CreateNetworkFromModel(*modelProto);
525}
526
527ModelPtr OnnxParser::LoadModelFromString(const std::string& protoText)
528{
529 if (protoText == "")
530 {
531 throw InvalidArgumentException(boost::str(
532 boost::format("Invalid (empty) string for model parameter %1%") % CHECK_LOCATION().AsString()));
533 }
534 // Parse the string into a message
535 ModelPtr modelProto = std::make_unique<onnx::ModelProto>();
536 bool success = google::protobuf::TextFormat::ParseFromString(protoText, modelProto.get());
537 if (!success)
538 {
539 std::stringstream error;
540 error << "Failed to parse graph file";
541 throw ParseException(boost::str(
542 boost::format("%1% %2%") % error.str() % CHECK_LOCATION().AsString()));
543 }
544 return modelProto;
545}
546
547INetworkPtr OnnxParser::CreateNetworkFromString(const std::string& protoText)
548{
549 ResetParser();
550 ModelPtr modelProto = LoadModelFromString(protoText);
551 return CreateNetworkFromModel(*modelProto);
552}
553
554INetworkPtr OnnxParser::CreateNetworkFromModel(onnx::ModelProto& model)
555{
556 m_Network = INetwork::Create();
557 try
558 {
559 m_Graph = std::make_unique<onnx::GraphProto>(*model.mutable_graph());
560 LoadGraph();
561 }
562 catch (const ParseException& e)
563 {
564 Cleanup();
565 throw e;
566 }
567 Cleanup();
568 return std::move(m_Network);
569}
570
571void OnnxParser::LoadGraph()
572{
573 BOOST_ASSERT(m_Graph.get() != nullptr);
574
575 //Fill m_TensorsInfo with the shapes and value of every tensor
576 SetupInfo(m_Graph->mutable_output());
577 SetupInfo(m_Graph->mutable_input());
578 SetupInfo(m_Graph->mutable_value_info());
579
580 for (auto tensor : m_Graph->initializer())
581 {
582 m_TensorsInfo[tensor.name()].m_tensor = std::make_unique<const onnx::TensorProto>(tensor);
583 }
584
585 SetupInputLayers();
586 SetupOutputLayers();
587
588 //Detect FullyConnected layers with bias and update the FusedAndUsed map acccordingly
589 DetectFullyConnected();
590
591 //Parsing the graph
592 for(size_t nodeIndex = 0; nodeIndex < static_cast<size_t>(m_Graph->node_size()); nodeIndex++)
593 {
594 auto node = m_Graph->node(static_cast<int>(nodeIndex));
595 const std::string& operation = node.op_type();
596
597 // check which layers we handled already (add and matmul fused as FC)
598 if(operation == "MatMul" )
599 {
600 if(m_OutputsFusedAndUsed[nodeIndex].inputForNodes != m_OutputsFusedAndUsed[nodeIndex].fusedWithNodes.size())
601 {
602 //Node which can not be fused as a FullyConnected layer (used in layers as a simple matmul output)
603 AddFullyConnected(node);
604 }
605 }
606 else if (!(m_OutputsFusedAndUsed[nodeIndex].fusedWithNodes.empty()) && operation == "Add")
607 {
608 int matmulIndex = static_cast<int> (m_OutputsFusedAndUsed[nodeIndex].fusedWithNodes[0]);
609 AddFullyConnected(m_Graph->node(matmulIndex), &node);
610 }
611 else if (m_OutputsFusedAndUsed[nodeIndex].fusedWithNodes.empty()) //node is not part of a fused layer
612 {
613 auto it = m_ParserFunctions.find(operation);
614 if (it != m_ParserFunctions.end())
615 {
616 auto func = it->second;
617 (this->*func)(node);
618 }
619 else
620 {
621 throw ParseException(boost::str(
622 boost::format("Unsupported operation %1% for node '%2%' %3%")
623 % operation
624 % node.name()
625 % CHECK_LOCATION().AsString()));
626 }
627 }
628 }
629
630 //Making the connections between outputs and inputs of each layers
631 for (const auto& tensorCon : m_TensorConnections)
632 {
633 if (tensorCon.second.outputSlot != nullptr)
634 {
635 for (size_t inputSlotIdx = 0; inputSlotIdx < tensorCon.second.inputSlots.size(); ++inputSlotIdx)
636 {
637 tensorCon.second.outputSlot->Connect(*(tensorCon.second.inputSlots[inputSlotIdx]));
638 }
639 }
640 }
641}
642
643void OnnxParser::SetupInfo(const google::protobuf::RepeatedPtrField<onnx::ValueInfoProto >* list)
644{
645 for (auto tensor : *list)
646 {
647 m_TensorsInfo[tensor.name()] = OnnxTensor();
648 m_TensorsInfo[tensor.name()].m_info = std::make_unique<TensorInfo>(ToTensorInfo(tensor));
Matteo Martincighe355dc22018-12-10 13:45:27 +0000649 m_TensorsInfo[tensor.name()].m_dtype =
650 static_cast<onnx::TensorProto::DataType>(tensor.type().tensor_type().elem_type());
telsoa01c577f2c2018-08-31 09:22:23 +0100651 }
652}
653
654void OnnxParser::DetectFullyConnected()
655{
656 m_OutputsFusedAndUsed = std::vector<UsageSummary> (static_cast<size_t>(m_Graph->node_size()), UsageSummary());
657 auto matmulAndConstant = [&](const std::string& constInput,
658 const std::string& matmulInput,
659 int& nodeIndex)
660 {
661 auto matmulIt = m_OutputsMap.find(matmulInput);
662 if(matmulIt != m_OutputsMap.end() && matmulIt->second.first->op_type() == "MatMul"
663 && m_TensorsInfo[constInput].isConstant())
664 {
665 nodeIndex = matmulIt->second.second;
666 return true;
667 }
668 return false;
669 };
670
671 for(int nodeIndex = 0; nodeIndex < m_Graph->node_size(); nodeIndex++)
672 {
673 const onnx::NodeProto* node = &m_Graph->node(nodeIndex);
674 for (const std::string& output : node->output())
675 {
676 m_OutputsMap[output] = std::make_pair(node, nodeIndex);
677 }
678
679 for (const std::string& input : node->input()) //count how many time a node is used as input
680 {
681 auto matmulIt = m_OutputsMap.find(input);
682 if(matmulIt != m_OutputsMap.end()){
683 ++m_OutputsFusedAndUsed[static_cast<size_t>(matmulIt->second.second)].inputForNodes; //node used
684 }
685 }
686
687 if (node->op_type() == "Add")
688 {
689 int matmulIndex = 0;
690 if (matmulAndConstant(node->input(0), node->input(1), matmulIndex) ||
691 matmulAndConstant(node->input(1), node->input(0), matmulIndex))
692 {
693 //matmul and add were fused
694 m_OutputsFusedAndUsed[static_cast<size_t>(matmulIndex)].fusedWithNodes
695 .push_back(static_cast<size_t>(nodeIndex));
696
697 m_OutputsFusedAndUsed[static_cast<size_t>(nodeIndex)].fusedWithNodes
698 .push_back(static_cast<size_t>(matmulIndex));
699 }
700 }
701 }
702
703 for (auto output: m_Graph->output()) { //Add usages as output of the graph in count of usages
704 auto matmulIt = m_OutputsMap.find(output.name());
705 if(matmulIt != m_OutputsMap.end()){
706 ++m_OutputsFusedAndUsed[static_cast<size_t>(matmulIt->second.second)].inputForNodes;
707 }
708 }
709}
710
711template<typename Location>
712void OnnxParser::GetInputAndParam(const onnx::NodeProto& node,
713 std::string* inputName,
714 std::string* constName,
715 const Location& location)
716{
717 int cstIndex;
718 if (m_TensorsInfo[node.input(0)].isConstant())
719 {
720 cstIndex = 0;
721 }
722 else if (m_TensorsInfo[node.input(1)].isConstant())
723 {
724 cstIndex = 1;
725 }
726 else
727 {
728 throw ParseException(boost::str(
729 boost::format("One of the input tensors ('%1%' or '%2%') should be constant in node '%3%' %4%")
730 % node.input(0)
731 % node.input(1)
732 % node.name()
733 % location.AsString()));
734 }
735 if(constName)
736 {
737 *constName = node.input(cstIndex);
738 }
739 if(inputName)
740 {
741 *inputName = node.input(!cstIndex);
742 }
743}
744
745template<typename Location>
746void OnnxParser::To1DTensor(const std::string& name, const Location& location)
747{
748 TensorShape shape = m_TensorsInfo[name].m_info->GetShape();
749 std::vector<uint32_t> newShape;
750 for(uint i = 0; i < shape.GetNumDimensions() - 1; ++i)
751 {
752 if(shape[i] != 1)
753 {
754 throw ParseException(boost::str(
755 boost::format("Only tensors with shape [1, ..., 1, X] can be converted to 1D and %1% %2%")
756 % TensorInfoAsString(*m_TensorsInfo[name].m_info, name, m_TensorsInfo[name].m_dtype)
757 % location.AsString()));
758 }
759 }
760 newShape.push_back(shape[shape.GetNumDimensions() - 1]);
761
762 m_TensorsInfo[name].m_info->SetShape(TensorShape(static_cast<unsigned int>(newShape.size()), newShape.data()));
763}
764
765void OnnxParser::AddFullyConnected(const onnx::NodeProto& matmulNode, const onnx::NodeProto* addNode)
766{
767
768 // find matmul inputs
769 std::string weightName;
770 std::string inputName;
771 CHECK_VALID_SIZE(static_cast<size_t>(matmulNode.input_size()), 2);
772 CHECK_VALID_SIZE(static_cast<size_t>(matmulNode.output_size()), 1);
773 VALID_INPUTS(matmulNode, STR_LIST(onnx::TensorProto::FLOAT));
774
775 GetInputAndParam(matmulNode, &inputName, &weightName, CHECK_LOCATION());
776
777 FullyConnectedDescriptor desc;
778 desc.m_BiasEnabled = addNode != nullptr;
779
780 IConnectableLayer* layer = nullptr;
781 if(desc.m_BiasEnabled)
782 {
783 // find bias const
784 std::string biasName;
785 CHECK_VALID_SIZE(static_cast<size_t>(addNode->input_size()), 2);
786 CHECK_VALID_SIZE(static_cast<size_t>(addNode->output_size()), 1);
787 VALID_INPUTS(*addNode, STR_LIST(onnx::TensorProto::FLOAT));
788
789 GetInputAndParam(*addNode, nullptr, &biasName, CHECK_LOCATION());
790
791 //Output shape is [1, weights[1]] and 1d vec in ONNX can be [1,X] so we convert biases to "armnn" 1D
792 To1DTensor(biasName, CHECK_LOCATION());
793 TensorInfo weightInfo = *m_TensorsInfo[weightName].m_info;
794 TensorInfo biasInfo = *m_TensorsInfo[biasName].m_info;
795
796 if (weightInfo.GetShape()[1] != biasInfo.GetShape()[0])
797 {
798 throw ParseException(boost::str(
799 boost::format("Shape of weights '%1%' and bias of following Add node '%2%' do not match : %3%"
800 " and %4% ( /!\\ bias should be a 1D tensor) %5%")
801 % weightName
802 % addNode->name()
803 % TensorInfoAsString(*m_TensorsInfo[weightName].m_info,
804 weightName,
805 m_TensorsInfo[weightName].m_dtype)
806 % TensorInfoAsString(*m_TensorsInfo[biasName].m_info, biasName,
807 m_TensorsInfo[biasName].m_dtype )
808 % CHECK_LOCATION().AsString()));
809 }
810 layer = m_Network->AddFullyConnectedLayer(desc,
811 CreateConstTensor(weightName).first,
812 CreateConstTensor(biasName).first,
813 matmulNode.name().c_str());
814 BOOST_ASSERT(layer != nullptr);
815
816 auto outputInfo = ComputeOutputInfo({addNode->output(0)}, layer,
817 {m_TensorsInfo[inputName].m_info->GetShape(),
818 m_TensorsInfo[weightName].m_info->GetShape()});
819
820 layer->GetOutputSlot(0).SetTensorInfo(outputInfo[0]);
821
822 RegisterInputSlots(layer, {inputName});
823 RegisterOutputSlots(layer, {addNode->output(0)});
824 }
825 else
826 {
827 layer = m_Network->AddFullyConnectedLayer(desc, CreateConstTensor(weightName).first, matmulNode.name().c_str());
828 BOOST_ASSERT(layer != nullptr);
829
830 auto outputInfo = ComputeOutputInfo({matmulNode.output(0)}, layer,
831 {m_TensorsInfo[inputName].m_info->GetShape(),
832 m_TensorsInfo[weightName].m_info->GetShape()});
833 layer->GetOutputSlot(0).SetTensorInfo(outputInfo[0]);
834
835 RegisterInputSlots(layer, {inputName});
836 RegisterOutputSlots(layer, {matmulNode.output(0)});
837 }
838}
839
840void OnnxParser::CreateConstantLayer(const std::string& tensorName, const std::string& layerName)
841{
842 auto armnnTensor = CreateConstTensor(tensorName);
843
844 IConnectableLayer* layer = m_Network->AddConstantLayer(armnnTensor.first, layerName.c_str());
845 layer->GetOutputSlot(0).SetTensorInfo(armnnTensor.first.GetInfo());
846 RegisterOutputSlots(layer, {tensorName});
847}
848
849void OnnxParser::ParseConstant(const onnx::NodeProto& node)
850{
851 CHECK_VALID_SIZE(static_cast<size_t>(node.attribute_size()), 1);
852
853 if (!node.attribute(0).has_t())
854 {
855 throw ParseException(boost::str(
856 boost::format("Value not found for Constant node '%1%' %2%")
857 % node.name()
858 % CHECK_LOCATION().AsString()));
859 }
860 const onnx::TensorProto& onnxTensor = node.attribute(0).t();
861
862 //ONNX can have Float16 and double constant nodes but ArmNN only supports float32
Matteo Martincighe355dc22018-12-10 13:45:27 +0000863 CHECK_VALID_DATATYPE(node.name(), onnxTensor.name(),
864 static_cast<onnx::TensorProto::DataType>(onnxTensor.data_type()), onnx::TensorProto::FLOAT);
telsoa01c577f2c2018-08-31 09:22:23 +0100865
866 //Register this as a m_ConstParam so we know we can use it as a constant param in future layers.
867 m_TensorsInfo[node.output(0)].m_tensor = std::make_unique<const onnx::TensorProto>(onnxTensor);
868
869 CreateConstantLayer(node.output(0), node.name());
870
871}
872
873void OnnxParser::ParseMaxPool(const onnx::NodeProto& node)
874{
875 Pooling2dDescriptor desc;
876 desc.m_PoolType = PoolingAlgorithm::Max;
877 desc.m_PaddingMethod = PaddingMethod::Exclude;
878 AddPoolingLayer(node, desc);
879}
880
881void OnnxParser::ParseGlobalAveragePool(const onnx::NodeProto& node)
882{
883 Pooling2dDescriptor desc = Pooling2dDescriptor();
884 desc.m_PoolType = PoolingAlgorithm::Average;
885
886 //kernel size is the same as input
887 TensorShape inputShape = m_TensorsInfo[node.input(0)].m_info->GetShape();
888 desc.m_PoolWidth = inputShape[3];
889 desc.m_PoolHeight = inputShape[2];
890
891 IConnectableLayer* layer = m_Network->AddPooling2dLayer(desc, node.name().c_str());
892 BOOST_ASSERT(layer != nullptr);
893
894 auto outputInfo = ComputeOutputInfo({node.output(0)}, layer, {inputShape});
895 layer->GetOutputSlot(0).SetTensorInfo(outputInfo[0]);
896
897 // register the input connection slots for the layer, connections are made after all layers have been created
898 // only the tensors for the inputs are relevant, exclude the const tensors
899 RegisterInputSlots(layer, {node.input(0)});
900
901 // register the output connection slots for the layer, connections are made after all layers have been created
902 RegisterOutputSlots(layer, {node.output(0)});
903}
904
905void OnnxParser::ParseAveragePool(const onnx::NodeProto& node)
906{
907 Pooling2dDescriptor desc;
908 desc.m_PoolType = PoolingAlgorithm::Average;
909
910 uint32_t count_include_pad = 0;
911 count_include_pad = ReadOptionalNodeUint32Attribute(node, "count_include_pad");
912 if(count_include_pad) {
913 desc.m_PaddingMethod = PaddingMethod::IgnoreValue;
914 }
915 AddPoolingLayer(node, desc);
916}
917
918void OnnxParser::AddPoolingLayer(const onnx::NodeProto& node, Pooling2dDescriptor& desc)
919{
920
921 CHECK_VALID_SIZE(static_cast<size_t>(node.input_size()), 1);
922 CHECK_VALID_SIZE(static_cast<size_t>(node.output_size()), 1);
923
924 VALID_INPUTS(node, STR_LIST(onnx::TensorProto::FLOAT));
925
926 std::vector<uint32_t> kernel_shape = ReadMandatoryNodeUint32ListAttribute(node, "kernel_shape"); //size of pool win
927 std::vector<uint32_t> strides = ReadOptionalNodeUint32ListAttribute(node, "strides");
928 std::vector<uint32_t> pads = ReadOptionalNodeUint32ListAttribute(node, "pads");
929
930 desc.m_OutputShapeRounding = OutputShapeRounding::Floor;
931 desc.m_PoolWidth = kernel_shape[1];
932 desc.m_PoolHeight = kernel_shape[0];
933
934 if(strides.empty())
935 {
936 desc.m_StrideX = 1;
937 desc.m_StrideY = 1;
938 }
939 else
940 {
941 desc.m_StrideX = strides[1];
942 desc.m_StrideY = strides[0];
943 }
944
945 //Check new padding version first
946 if(pads.empty())
947 {
948 //Check deprecated version
949 std::string paddingString = ReadOptionalNodeStringAttribute(node, "auto_pad");
950 if(paddingString != "VALID" && paddingString != "" && paddingString != "NOTSET")
951 {
952 bool isUpper;
953 if( paddingString == "SAME_LOWER")
954 {
955 isUpper = false;
956 }
957 else if (paddingString == "SAME_UPPER")
958 {
959 isUpper = true;
960 }
961 else
962 {
963 throw ParseException(boost::str(
964 boost::format("Invalid auto_pad attribute for node %1%. "
965 "Only SAME_UPPER, SAME_LOWER or VALID supported and found %2% %3%")
966 % node.name()
967 % paddingString
968 % CHECK_LOCATION().AsString()));
969 }
970 auto inputInfo = *m_TensorsInfo[node.input(0)].m_info;
971 uint32_t inputHeight = inputInfo.GetShape()[2];
972 uint32_t inputWidth = inputInfo.GetShape()[3];
973 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, &desc.m_PadTop, &desc.m_PadBottom, isUpper);
974 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, &desc.m_PadLeft, &desc.m_PadRight, isUpper);
975 }
976 }
977 else
978 {
979 desc.m_PadTop = pads[0];
980 desc.m_PadLeft = pads[1];
981 desc.m_PadBottom = pads[2];
982 desc.m_PadRight = pads[3];
983 }
984
985 IConnectableLayer* layer = m_Network->AddPooling2dLayer(desc, node.name().c_str());
986 BOOST_ASSERT(layer != nullptr);
987
988 auto outputInfo = ComputeOutputInfo({node.output(0)}, layer, {m_TensorsInfo[node.input(0)].m_info->GetShape()});
989 layer->GetOutputSlot(0).SetTensorInfo(outputInfo[0]);
990
991 // register the input connection slots for the layer, connections are made after all layers have been created
992 // only the tensors for the inputs are relevant, exclude the const tensors
993 RegisterInputSlots(layer, {node.input(0)});
994
995 // register the output connection slots for the layer, connections are made after all layers have been created
996 RegisterOutputSlots(layer, {node.output(0)});
997}
998
999void OnnxParser::CreateReshapeLayer(const std::string& inputName,
1000 const std::string& outputName,
1001 const std::string& layerName)
1002{
1003 const TensorInfo outputTensorInfo = *m_TensorsInfo[outputName].m_info;
1004 ReshapeDescriptor reshapeDesc;
1005 reshapeDesc.m_TargetShape = outputTensorInfo.GetShape();
1006
1007 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
1008 BOOST_ASSERT(layer != nullptr);
1009 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1010
1011 // register the input connection slots for the layer, connections are made after all layers have been created
1012 // only the tensors for the inputs are relevant, exclude the const tensors
1013 RegisterInputSlots(layer, {inputName});
1014
1015 // register the output connection slots for the layer, connections are made after all layers have been created
1016 RegisterOutputSlots(layer, {outputName});
1017}
1018
1019void OnnxParser::ParseReshape(const onnx::NodeProto& node)
1020{
1021 CHECK_VALID_SIZE(static_cast<size_t>(node.input_size()), 2);
1022 CHECK_VALID_SIZE(static_cast<size_t>(node.output_size()), 1);
1023
1024 CHECK_VALID_DATATYPE(node.name(), node.input(0),
1025 m_TensorsInfo[node.input(0)].m_dtype,
1026 onnx::TensorProto::FLOAT); //input
1027 CHECK_VALID_DATATYPE(node.name(), node.input(1),
1028 m_TensorsInfo[node.input(1)].m_dtype,
1029 onnx::TensorProto::INT64); //shape
1030
1031 if(!m_TensorsInfo[node.input(1)].isConstant())
1032 {
1033 throw ParseException(boost::str(
1034 boost::format("Shape '%1%' should be constant in Reshape layer '%2%' %3%")
1035 % node.input(1)
1036 % node.name()
1037 % CHECK_LOCATION().AsString()));
1038 }
1039
1040 if(m_TensorsInfo[node.input(0)].isConstant())
1041 {
1042 //make a new cst tensor -> move the data to the output tensor (the shape is already good in the output tensor)
1043 if(m_TensorsInfo.count(node.output(0)) == 0)
1044 {
1045 m_TensorsInfo[node.output(0)] = OnnxTensor();
1046 }
1047 m_TensorsInfo[node.output(0)].m_tensor =
1048 std::make_unique<onnx::TensorProto>(*m_TensorsInfo[node.input(0)].m_tensor);
1049 }
1050 else
1051 {
1052 TensorShape inputShape = m_TensorsInfo[node.input(0)].m_info->GetShape();
1053
1054 if(m_TensorsInfo.count(node.output(0)) == 0 || m_TensorsInfo[node.output(0)].m_info == nullptr)
1055 {
1056 auto outInfo = ComputeReshapeInfo(*m_TensorsInfo[node.input(1)].m_tensor, inputShape, node.output(0));
1057 m_TensorsInfo[node.output(0)].m_info = std::make_unique<TensorInfo>(outInfo);
1058 }
1059
1060 CreateReshapeLayer(node.input(0), node.output(0), node.name());
1061 }
1062}
1063
1064void OnnxParser::ParseRelu(const onnx::NodeProto& node)
1065{
1066 CHECK_VALID_SIZE(static_cast<size_t>(node.input_size()), 1);
1067 CHECK_VALID_SIZE(static_cast<size_t>(node.output_size()), 1);
1068
1069 VALID_INPUTS(node, STR_LIST(onnx::TensorProto::FLOAT));
1070
1071 ActivationDescriptor desc;
1072 desc.m_Function = ActivationFunction::ReLu;
1073
1074 IConnectableLayer* const layer = m_Network->AddActivationLayer(desc, node.name().c_str());
1075 BOOST_ASSERT(layer != nullptr);
1076
1077 auto outputInfo = ComputeOutputInfo({ node.output(0)}, layer, {m_TensorsInfo[node.input(0)].m_info->GetShape()});
1078 layer->GetOutputSlot(0).SetTensorInfo(outputInfo[0]);
1079
1080 // register the input connection slots for the layer, connections are made after all layers have been created
1081 // only the tensors for the inputs are relevant, exclude the const tensors
1082 RegisterInputSlots(layer, {node.input(0)});
1083
1084 // register the output connection slots for the layer, connections are made after all layers have been created
1085 RegisterOutputSlots(layer, {node.output(0)});
1086}
1087
1088
1089void OnnxParser::AddConvLayerWithDepthwiseConv(const onnx::NodeProto& node, const Convolution2dDescriptor& convDesc)
1090{
1091 BOOST_ASSERT(node.op_type() == "Conv");
1092
1093 DepthwiseConvolution2dDescriptor desc;
1094 desc.m_PadLeft = convDesc.m_PadLeft;
1095 desc.m_PadRight = convDesc.m_PadRight;
1096 desc.m_PadTop = convDesc.m_PadTop;
1097 desc.m_PadBottom = convDesc.m_PadBottom;
1098 desc.m_StrideX = convDesc.m_StrideX;
1099 desc.m_StrideY = convDesc.m_StrideY;
1100 desc.m_BiasEnabled = convDesc.m_BiasEnabled;
1101
1102 armnn::IConnectableLayer* layer;
1103 auto weightTensor = CreateConstTensor(node.input(1));
1104 TensorShape& weightShape = weightTensor.first.GetShape();
1105 weightShape[1] = weightShape[0];
1106 weightShape[0] = 1;
1107 m_TensorsInfo[node.input(1)].m_info->SetShape(weightShape);
1108
1109 if (node.input_size() == 3)
1110 {
1111 if(!m_TensorsInfo[node.input(2)].isConstant())
1112 {
1113 throw ParseException(boost::str(
1114 boost::format("Bias '%1%' should be constant in Conv layer '%2%' %3%")
1115 % node.input(2)
1116 % node.name()
1117 % CHECK_LOCATION().AsString()));
1118 }
1119 desc.m_BiasEnabled = true;
1120 auto biasTensor = CreateConstTensor(node.input(2));
1121 layer = m_Network->AddDepthwiseConvolution2dLayer(desc,
1122 weightTensor.first,
1123 biasTensor.first,
1124 node.name().c_str());
1125 }
1126 else
1127 {
1128 layer = m_Network->AddDepthwiseConvolution2dLayer(desc,
1129 weightTensor.first,
1130 node.name().c_str());
1131 }
1132 BOOST_ASSERT(layer != nullptr);
1133
1134 auto outputInfo = ComputeOutputInfo({ node.output(0) }, layer,
1135 { m_TensorsInfo[node.input(0)].m_info->GetShape(),
1136 m_TensorsInfo[node.input(1)].m_info->GetShape() });
1137
1138 layer->GetOutputSlot(0).SetTensorInfo(outputInfo[0]);
1139
1140 // register the input connection slots for the layer, connections are made after all layers have been created
1141 // only the tensors for the inputs are relevant, exclude the const tensors
1142 RegisterInputSlots(layer, {node.input(0)});
1143
1144 // register the output connection slots for the layer, connections are made after all layers have been created
1145 RegisterOutputSlots(layer, {node.output(0)});
1146}
1147
1148void OnnxParser::ParseConv(const onnx::NodeProto& node)
1149{
1150 CHECK_VALID_SIZE(static_cast<size_t>(node.input_size()), 2, 3); //input, weight, (bias)
1151 CHECK_VALID_SIZE(static_cast<size_t>(node.output_size()), 1);
1152
1153 VALID_INPUTS(node, STR_LIST(onnx::TensorProto::FLOAT));
1154
1155 if(m_TensorsInfo[node.input(0)].m_info->GetNumDimensions() != 4)
1156 {
1157 throw ParseException(boost::str(
1158 boost::format("ArmNN only supports 2D convolution and Conv layer '%1%' input %2% %3%")
1159 % node.name()
1160 % TensorInfoAsString(*m_TensorsInfo[node.input(0)].m_info, node.input(0),
1161 m_TensorsInfo[node.input(0)].m_dtype)
1162 % CHECK_LOCATION().AsString()));
1163 }
1164
1165 if(!m_TensorsInfo[node.input(1)].isConstant())
1166 {
1167 throw ParseException(boost::str(
1168 boost::format("Weights '%1%' should be constant in Conv layer '%2%' %3%")
1169 % node.input(1)
1170 % node.name()
1171 % CHECK_LOCATION().AsString()));
1172 }
1173
1174 auto inputInfo = *m_TensorsInfo[node.input(0)].m_info;
1175
1176 std::vector<uint32_t> dilations = ReadOptionalNodeUint32ListAttribute(node, "dilations");
1177 if (!dilations.empty())
1178 {
1179 std::stringstream ss;
1180 ss << "[ ";
1181 for (auto dilation : dilations)
1182 {
1183 ss << dilation << ", ";
1184 if (dilation != 1u)
1185 {
1186 ss << "... ]";
1187 throw ParseException(boost::str(
1188 boost::format("ArmNN only supports Convolution layers with dilations [1,1], and node '%1%' "
1189 "has dilatation %2% %3%")
1190 % node.name()
1191 % ss.str()
1192 % CHECK_LOCATION().AsString()));
1193 }
1194 }
1195 }
1196
1197 Convolution2dDescriptor desc;
1198 desc.m_BiasEnabled = false;
1199
1200 std::vector<uint32_t> strides = ReadOptionalNodeUint32ListAttribute(node, "strides");
1201 if(strides.empty())
1202 {
1203 desc.m_StrideX = 1;
1204 desc.m_StrideY = 1;
1205 }
1206 else
1207 {
1208 desc.m_StrideX = strides[1];
1209 desc.m_StrideY = strides[0];
1210 }
1211
1212 std::vector<uint32_t> pads = ReadOptionalNodeUint32ListAttribute(node, "pads");
1213 //Check new padding version first
1214 if(pads.empty())
1215 {
1216 //Check deprecated version
1217 std::string paddingString = ReadOptionalNodeStringAttribute(node, "auto_pad");
1218 if(paddingString != "VALID" && paddingString != "" && paddingString != "NOTSET")
1219 {
1220 bool isUpper;
1221 if( paddingString == "SAME_LOWER")
1222 {
1223 isUpper = false;
1224 }
1225 else if (paddingString == "SAME_UPPER")
1226 {
1227 isUpper = true;
1228 }
1229 else
1230 {
1231 throw ParseException(boost::str(
1232 boost::format("Invalid auto_pad attribute for node %1%. "
1233 "Only SAME_UPPER, SAME_LOWER or VALID supported and found %2% %3%")
1234 % node.name()
1235 % paddingString
1236 % CHECK_LOCATION().AsString()));
1237 }
1238 uint32_t inputHeight = inputInfo.GetShape()[2];
1239 uint32_t inputWidth = inputInfo.GetShape()[3];
1240
1241 uint32_t weightHeight;
1242 uint32_t weightWidth;
1243 std::vector<uint32_t> kernel_shape = ReadOptionalNodeUint32ListAttribute(node, "kernel_shape");
1244 if (kernel_shape.empty())
1245 {
1246 const TensorInfo weightTensorInfo = *m_TensorsInfo[node.input(1)].m_info;
1247 weightHeight = weightTensorInfo.GetShape()[2];
1248 weightWidth = weightTensorInfo.GetShape()[3];
1249 }
1250 else
1251 {
1252 weightHeight = kernel_shape[0];
1253 weightWidth = kernel_shape[1];
1254 }
1255 CalcPadding(inputHeight, weightHeight, desc.m_StrideY, &desc.m_PadTop, &desc.m_PadBottom, isUpper);
1256 CalcPadding(inputWidth, weightWidth, desc.m_StrideX, &desc.m_PadLeft, &desc.m_PadRight, isUpper);
1257 }
1258 }
1259 else
1260 {
1261 desc.m_PadTop = pads[0];
1262 desc.m_PadLeft = pads[1];
1263 desc.m_PadBottom = pads[2];
1264 desc.m_PadRight = pads[3];
1265 }
1266
1267 uint32_t group = ReadOptionalNodeUint32Attribute(node, "group", 1);
1268 if(group > 1)
1269 {
1270 if (group > inputInfo.GetShape()[1])
1271 {
1272 throw ParseException(
1273 boost::str(
1274 boost::format(
1275 "Error parsing Convolution node: %1%. "
1276 "The 'group'=%2% parameter cannot be larger than the "
1277 "channel of the input shape=%3% (in NCHW format). %4%") %
1278 node.name() %
1279 group %
1280 inputInfo.GetShape()[1] %
1281 CHECK_LOCATION().AsString()));
1282 }
1283 else if (group == inputInfo.GetShape()[1])
1284 {
1285 // we use a depthwise convolution here, because the number of groups equals to the
1286 // input channels
1287 AddConvLayerWithDepthwiseConv(node, desc);
1288 return;
1289 }
1290 else
1291 {
1292 // TODO: split the input by channels into channels/groups separate convolutions
1293 // and merger the results afterwards
1294 throw ParseException(boost::str(
1295 boost::format("Error parsing Convolution node: %1%. "
1296 "The 'group'=%2% parameter should be 1 or be equal to the "
1297 "channel of the input shape=%3% (in NCHW format). %4%") %
1298 node.name() %
1299 group %
1300 inputInfo.GetShape()[1] %
1301 CHECK_LOCATION().AsString()));
1302 }
1303 }
1304
1305 armnn::IConnectableLayer* layer;
1306 auto weightTensor = CreateConstTensor(node.input(1));
1307
1308 if (node.input_size() == 3)
1309 {
1310 if(!m_TensorsInfo[node.input(2)].isConstant())
1311 {
1312 throw ParseException(boost::str(
1313 boost::format("Bias '%1%' should be constant in Conv layer '%2%' %3%")
1314 % node.input(2)
1315 % node.name()
1316 % CHECK_LOCATION().AsString()));
1317 }
1318 desc.m_BiasEnabled = true;
1319 auto biasTensor = CreateConstTensor(node.input(2));
1320 layer = m_Network->AddConvolution2dLayer(desc,
1321 weightTensor.first,
1322 biasTensor.first,
1323 node.name().c_str());
1324 }
1325 else
1326 {
1327 layer = m_Network->AddConvolution2dLayer(desc,
1328 weightTensor.first,
1329 node.name().c_str());
1330 }
1331 BOOST_ASSERT(layer != nullptr);
1332
1333 auto outputInfo = ComputeOutputInfo({ node.output(0) }, layer,
1334 { m_TensorsInfo[node.input(0)].m_info->GetShape(),
1335 m_TensorsInfo[node.input(1)].m_info->GetShape() });
1336 layer->GetOutputSlot(0).SetTensorInfo(outputInfo[0]);
1337
1338 // register the input connection slots for the layer, connections are made after all layers have been created
1339 // only the tensors for the inputs are relevant, exclude the const tensors
1340 RegisterInputSlots(layer, {node.input(0)});
1341
1342 // register the output connection slots for the layer, connections are made after all layers have been created
1343 RegisterOutputSlots(layer, {node.output(0)});
1344}
1345
1346void OnnxParser::PrependForBroadcast(const std::string& outputName,
1347 const std::string& input0,
1348 const std::string& input1)
1349{
1350 //input0 should be reshaped to have same number of dim as input1
1351 TensorInfo outputTensorInfo = TensorInfo(*m_TensorsInfo[input0].m_info);
1352
1353 TensorShape input0Shape = m_TensorsInfo[input0].m_info->GetShape();
1354 TensorShape input1Shape = m_TensorsInfo[input1].m_info->GetShape();
1355
1356 uint32_t diff = input1Shape.GetNumDimensions() - input0Shape.GetNumDimensions();
1357 std::vector<uint32_t> newShape;
1358 while(diff > 0)
1359 {
1360 newShape.push_back(1);
1361 diff--;
1362 }
1363 for (uint dim = 0; dim < input0Shape.GetNumDimensions(); ++dim)
1364 {
1365 newShape.push_back(input0Shape[dim]);
1366 }
1367 outputTensorInfo.SetShape(TensorShape(static_cast<unsigned int>(newShape.size()), newShape.data()));
1368
1369 //add the new tensor to m_TensorsInfo
1370 m_TensorsInfo[outputName] = OnnxTensor();
1371 m_TensorsInfo[outputName].m_info = std::make_unique<TensorInfo>(outputTensorInfo);
1372
1373 //add reshape layer if the parent was not constant...
1374 if( ! m_TensorsInfo[input0].isConstant())
1375 {
1376 CreateReshapeLayer(input0, outputName, boost::str(boost::format("Add:reshapeOf%1%") % input0));
1377 }
1378 else //make it constant and it will be create in Add
1379 {
1380 m_TensorsInfo[outputName].m_tensor = std::make_unique<onnx::TensorProto>(*m_TensorsInfo[input0].m_tensor);
1381
1382 }
1383}
1384
1385std::pair<std::string, std::string> OnnxParser::AddPrepareBroadcast(const std::string& input0,
1386 const std::string& input1)
1387{
1388 std::pair<std::string, std::string> inputs = std::make_pair(input0, input1);
1389
1390 TensorShape input0Shape = m_TensorsInfo[input0].m_info->GetShape();
1391 TensorShape input1Shape = m_TensorsInfo[input1].m_info->GetShape();
1392
1393 if(input1Shape.GetNumDimensions() < input0Shape.GetNumDimensions())
1394 {
1395 auto outputName = boost::str(boost::format("reshape_output_%1%") % input1);
1396 PrependForBroadcast(outputName, input1, input0);
1397 inputs.second = outputName;
1398 }
1399 else if(input0Shape.GetNumDimensions() < input1Shape.GetNumDimensions())
1400 {
1401 auto outputName = boost::str(boost::format("reshape_output_%1%") % input0);
1402 PrependForBroadcast(outputName, input0, input1);
1403 inputs.first = outputName;
1404 }
1405 return inputs;
1406}
1407
1408void OnnxParser::ParseAdd(const onnx::NodeProto& node)
1409{
1410 CHECK_VALID_SIZE(static_cast<size_t>(node.input_size()), 2);
1411 CHECK_VALID_SIZE(static_cast<size_t>(node.output_size()), 1);
1412
1413 VALID_INPUTS(node, STR_LIST(onnx::TensorProto::FLOAT));
1414
1415 // TODO: unify broadcast validation code across layers
1416 // tracked by: IVGCVSW-1576
1417
1418 // Checking broadcast compatibility : only scalar or 1D tensors
1419 auto inputs = AddPrepareBroadcast(node.input(0), node.input(1));
1420 auto input0 = *m_TensorsInfo[inputs.first].m_info;
1421 auto input1 = *m_TensorsInfo[inputs.second].m_info;
1422 BOOST_ASSERT(input0.GetNumDimensions() == input1.GetNumDimensions());
1423
1424 unsigned int numDims = input0.GetNumDimensions();
1425 for (unsigned int i = 0; i < numDims; i++)
1426 {
1427 unsigned int dim0 = input0.GetShape()[i];
1428 unsigned int dim1 = input1.GetShape()[i];
1429 if (dim0 != dim1 && dim0 != 1 && dim1 != 1)
1430 {
1431 throw ParseException(boost::str(
1432 boost::format("Broadcast is only supported for scalar or 1D tensors in Add node '%1%'. "
1433 "Input dimensions should either match or one should be of size 1 and here, "
1434 "%2% and %3% %4%")
1435 % node.name()
1436 % TensorInfoAsString(*m_TensorsInfo[inputs.first].m_info, inputs.first,
1437 m_TensorsInfo[inputs.first].m_dtype)
1438 % TensorInfoAsString(*m_TensorsInfo[inputs.second].m_info, inputs.second,
1439 m_TensorsInfo[inputs.second].m_dtype)
1440 % CHECK_LOCATION().AsString()));
1441 }
1442 }
1443
1444
1445 IConnectableLayer* layer = m_Network->AddAdditionLayer(node.name().c_str());
1446 BOOST_ASSERT(layer != nullptr);
1447
1448 auto outputInfo = ComputeOutputInfo({ node.output(0) }, layer,
1449 { m_TensorsInfo[inputs.first].m_info->GetShape(),
1450 m_TensorsInfo[inputs.second].m_info->GetShape() });
1451 layer->GetOutputSlot(0).SetTensorInfo(outputInfo[0]);
1452
1453 // register the input connection -> for constant inputs, we need to make a newDim constant layer
1454 if(m_TensorsInfo[inputs.first].isConstant()) {
1455
1456 CreateConstantLayer(inputs.first, boost::str(boost::format("Add:constant_of_%1%") % node.input(0)));
1457 }
1458 if(m_TensorsInfo[inputs.second].isConstant()) {
1459
1460 CreateConstantLayer(inputs.second, boost::str(boost::format("Add:constant_of_%1%") % node.input(1)));
1461 }
1462 RegisterInputSlots(layer, {inputs.first, inputs.second});
1463
1464 // register the output connection
1465 RegisterOutputSlots(layer, {node.output(0)});
1466}
1467
1468void OnnxParser::ParseBatchNormalization(const onnx::NodeProto& node)
1469{
1470 //IGNORE momentum parameter and spatial parameters
1471
1472 CHECK_VALID_SIZE(static_cast<size_t>(node.input_size()), 5);
1473 CHECK_VALID_SIZE(static_cast<size_t>(node.output_size()), 1);
1474
1475 VALID_INPUTS(node, STR_LIST(onnx::TensorProto::FLOAT));
1476 for(int ind = 1; ind < node.input_size(); ++ind)
1477 {
1478 auto tensor = node.input(ind);
1479 if(! m_TensorsInfo[tensor].isConstant())
1480 {
1481 throw ParseException(boost::str(
1482 boost::format("Input tensor '%1%' should be constant in BatchNormalization node '%2%' %3%")
1483 % tensor
1484 % node.name()
1485 % CHECK_LOCATION().AsString()));
1486 }
1487 }
1488
1489 float epsilon = ReadOptionalNodeFloatAttribute(node, "epsilon", 1e-5f);
1490 BatchNormalizationDescriptor desc;
1491 desc.m_Eps = epsilon;
1492
1493 auto scaleTensor = CreateConstTensor(node.input(1));
1494 auto biasTensor = CreateConstTensor(node.input(2));
1495 auto meanTensor = CreateConstTensor(node.input(3));
1496 auto varTensor = CreateConstTensor(node.input(4));
1497
1498 IConnectableLayer* layer = m_Network->AddBatchNormalizationLayer(desc,
1499 meanTensor.first,
1500 varTensor.first,
1501 biasTensor.first,
1502 scaleTensor.first,
1503 node.name().c_str());
1504 BOOST_ASSERT(layer != nullptr);
1505
1506 auto outputInfo = ComputeOutputInfo({node.output(0)}, layer, {m_TensorsInfo[node.input(0)].m_info->GetShape()});
1507 layer->GetOutputSlot(0).SetTensorInfo(outputInfo[0]);
1508
1509 RegisterInputSlots(layer, {node.input(0)}); //don't register constant inputs
1510
1511 // register the output connection
1512 RegisterOutputSlots(layer, {node.output(0)});
1513}
1514
1515void OnnxParser::SetupInputLayers()
1516{
1517 //Find user input and add their layers
1518 for(int inputIndex = 0; inputIndex < m_Graph->input_size(); ++inputIndex)
1519 {
1520 auto input = m_Graph->input(inputIndex);
1521 if (! m_TensorsInfo[input.name()].isConstant())
1522 {
1523 IConnectableLayer* layer =
1524 m_Network->AddInputLayer(static_cast<armnn::LayerBindingId>(inputIndex), input.name().c_str());
1525 auto tensorInfo = ToTensorInfo(input);
1526 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
1527
1528 RegisterOutputSlots(layer,{ input.name() });
1529 }
1530 }
1531}
1532
1533void OnnxParser::SetupOutputLayers()
1534{
1535 if(m_Graph->output_size() == 0)
1536 {
1537 throw ParseException(boost::str(boost::format("The given model does not have any outputs %1%")
1538 % CHECK_LOCATION().AsString()));
1539 }
1540
1541 for(int outputIndex = 0; outputIndex < m_Graph->output_size(); ++outputIndex)
1542 {
1543 IConnectableLayer* layer =
1544 m_Network->AddOutputLayer(static_cast<armnn::LayerBindingId>(outputIndex),
1545 m_Graph->output(outputIndex).name().c_str());
1546
1547 RegisterInputSlots(layer, { m_Graph->output(outputIndex).name() });
1548 }
1549}
1550
1551void OnnxParser::RegisterInputSlots(IConnectableLayer* layer, const std::vector<std::string>& tensorIds)
1552{
1553 BOOST_ASSERT(layer != nullptr);
1554 if (tensorIds.size() != layer->GetNumInputSlots())
1555 {
1556 throw ParseException(
1557 boost::str(boost::format("The number of tensor inputs (%1%) does not match the number expected (%2%) %3%") %
1558 tensorIds.size() %
1559 layer->GetNumInputSlots() %
1560 CHECK_LOCATION().AsString()));
1561 }
1562 for (unsigned int slotIndex = 0; slotIndex < layer->GetNumInputSlots(); ++slotIndex)
1563 {
1564 std::string tensorId = tensorIds[slotIndex];
1565 armnn::IInputSlot* slot = &(layer->GetInputSlot(slotIndex));
1566
1567 auto it = m_TensorConnections.find(tensorId);
1568
1569 if (it == m_TensorConnections.end())
1570 {
1571 //First time seing this tensor, we need to map it
1572 m_TensorConnections[tensorId] = TensorSlots();
1573 }
1574 m_TensorConnections[tensorId].inputSlots.push_back(slot);
1575 }
1576}
1577
1578void OnnxParser::RegisterOutputSlots(IConnectableLayer* layer, const std::vector<std::string>& tensorIds)
1579{
1580 BOOST_ASSERT(layer != nullptr);
1581 if (tensorIds.size() != layer->GetNumOutputSlots())
1582 {
1583 throw ParseException(
1584 boost::str(boost::format("The number of tensor outputs (%1%) does not match the number expected (%2%) %3% ")
1585 % tensorIds.size()
1586 % layer->GetNumOutputSlots()
1587 % CHECK_LOCATION().AsString()));
1588 }
1589
1590 for (unsigned int slotIndex = 0; slotIndex < layer->GetNumOutputSlots(); ++slotIndex)
1591 {
1592 std::string tensorId = tensorIds[slotIndex];
1593 armnn::IOutputSlot* slot = &(layer->GetOutputSlot(slotIndex));
1594
1595 auto it = m_TensorConnections.find(tensorId);
1596
1597 if (it == m_TensorConnections.end())
1598 {
1599 //First time seing this tensor, we need to map it
1600 m_TensorConnections[tensorId] = TensorSlots();
1601 }
1602
1603 TensorSlots & tensorSlots = m_TensorConnections[tensorId];
1604
1605 // assuming there is only one producer for that tensor
1606 if (tensorSlots.outputSlot != nullptr)
1607 {
1608 throw ParseException(boost::str(
1609 boost::format("Another layer has already registered itself as the producer of "
1610 "tensor:%2% %3%") %
1611 tensorId %
1612 CHECK_LOCATION().AsString()));
1613 }
1614 tensorSlots.outputSlot = slot;
1615 }
1616}
1617
1618BindingPointInfo OnnxParser::GetNetworkInputBindingInfo(const std::string& name) const
1619{
1620 for(int i = 0; i < m_Graph->input_size(); ++i)
1621 {
1622 auto input = m_Graph->input(i);
1623 if(input.name() == name)
1624 {
1625 return std::make_pair(static_cast<armnn::LayerBindingId>(i), ToTensorInfo(input));
1626 }
1627 }
1628 throw InvalidArgumentException(boost::str(boost::format("The input layer '%1%' does not exist %2%")
1629 % name % CHECK_LOCATION().AsString()));
1630}
1631
1632BindingPointInfo OnnxParser::GetNetworkOutputBindingInfo(const std::string& name) const
1633{
1634 for(int i = 0; i < m_Graph->output_size(); ++i)
1635 {
1636 auto output = m_Graph->output(i);
1637 if(output.name() == name)
1638 {
1639 return std::make_pair(static_cast<armnn::LayerBindingId>(i), ToTensorInfo(output));
1640 }
1641 }
1642 throw InvalidArgumentException(boost::str(boost::format("The output layer '%1%' does not exist %2%")
1643 % name % CHECK_LOCATION().AsString()));
1644}
1645
1646std::vector<std::string> OnnxParser::GetInputs(ModelPtr& model)
1647{
1648 if(model == nullptr) {
1649 throw InvalidArgumentException(boost::str(
1650 boost::format("The given model cannot be null %1%")
1651 % CHECK_LOCATION().AsString()));
1652 }
1653
1654 std::vector<std::string> inputNames;
1655 std::map<std::string, bool> isConstant;
1656 for(auto tensor : model->graph().initializer())
1657 {
1658 isConstant[tensor.name()] = true;
1659 }
1660 for(auto input : model->graph().input())
1661 {
1662 auto it = isConstant.find(input.name());
1663 if(it == isConstant.end())
1664 {
1665 inputNames.push_back(input.name());
1666 }
1667 }
1668 return inputNames;
1669}
1670
1671std::vector<std::string> OnnxParser::GetOutputs(ModelPtr& model)
1672{
1673 if(model == nullptr) {
1674 throw InvalidArgumentException(boost::str(
1675 boost::format("The given model cannot be null %1%")
1676 % CHECK_LOCATION().AsString()));
1677 }
1678
1679 std::vector<std::string> outputNames;
1680 for(auto output : model->graph().output())
1681 {
1682 outputNames.push_back(output.name());
1683 }
1684 return outputNames;
1685}
1686
1687} // namespace armnnOnnxParser