blob: e5948d55f4de98195e4516ae34962c290f13091b [file] [log] [blame]
surmeh01bceff2f2018-03-29 16:29:27 +01001//
2// Copyright © 2017 Arm Ltd. All rights reserved.
David Beckecb56cd2018-09-05 12:52:57 +01003// SPDX-License-Identifier: MIT
surmeh01bceff2f2018-03-29 16:29:27 +01004//
Ferran Balaguer51dd62f2019-01-11 19:29:18 +00005
surmeh01bceff2f2018-03-29 16:29:27 +01006#include "TfParser.hpp"
7
surmeh01bceff2f2018-03-29 16:29:27 +01008#include <armnn/TypesUtils.hpp>
surmeh01bceff2f2018-03-29 16:29:27 +01009#include <armnn/Descriptors.hpp>
10
11#include <GraphTopologicalSort.hpp>
Sadik Armagan479045b2018-10-01 11:51:37 +010012#include <ParserHelper.hpp>
surmeh01bceff2f2018-03-29 16:29:27 +010013#include <Permute.hpp>
Matteo Martincigh46315822018-11-28 16:22:36 +000014#include <DataLayoutIndexed.hpp>
surmeh01bceff2f2018-03-29 16:29:27 +010015
16#include <google/protobuf/io/zero_copy_stream_impl.h>
17#include <google/protobuf/text_format.h>
18
19#include "tensorflow/core/framework/graph.pb.h"
surmeh01bceff2f2018-03-29 16:29:27 +010020
surmeh01bceff2f2018-03-29 16:29:27 +010021#include <boost/format.hpp>
22#include <boost/core/ignore_unused.hpp>
Aron Virginas-Tard4f0fea2019-04-09 14:08:06 +010023#include <boost/format.hpp>
24#include <boost/numeric/conversion/cast.hpp>
surmeh01bceff2f2018-03-29 16:29:27 +010025#include <boost/polymorphic_cast.hpp>
26
surmeh01bceff2f2018-03-29 16:29:27 +010027#include <numeric>
surmeh01bceff2f2018-03-29 16:29:27 +010028
Matteo Martincigh46315822018-11-28 16:22:36 +000029using namespace armnnUtils;
surmeh01bceff2f2018-03-29 16:29:27 +010030using namespace armnn;
31
32namespace armnnTfParser
33{
34namespace
35{
36
37const PermutationVector NHWCToArmNN = { 0, 2, 3, 1 };
38const PermutationVector ArmNNToNHWC = { 0, 3, 1, 2 };
39
surmeh01bceff2f2018-03-29 16:29:27 +010040
41template <typename Callable>
42void ReadMandatoryNodeAttributeImpl(const tensorflow::NodeDef& nodeDef,
43 const std::string& attribName,
44 tensorflow::AttrValue::ValueCase expectedValueCase,
45 Callable callable)
46{
47 auto iter = nodeDef.attr().find(attribName);
48 if (iter != nodeDef.attr().end())
49 {
50 const auto& attrValue = iter->second;
51 if (attrValue.value_case() == expectedValueCase)
52 {
53 callable(attrValue);
54 }
55 else
56 {
telsoa01c577f2c2018-08-31 09:22:23 +010057 throw ParseException(
58 boost::str(
59 boost::format(
60 "Attribute %1% of node %2% expected to have %3% as tensorflow::AttrValue::ValueCase, "
61 "but found %4% instead %5%")
62 % attribName
63 % nodeDef.name()
64 % static_cast<int>(expectedValueCase)
65 % static_cast<int>(attrValue.value_case())
66 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +010067 }
68 }
69 else
70 {
telsoa01c577f2c2018-08-31 09:22:23 +010071 throw ParseException(
72 boost::str(
73 boost::format(
74 "Could not find required attribute %1% in node %2% %3%")
75 % attribName
76 % nodeDef.name()
77 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +010078 }
79}
80
81template <typename Callable>
82void ReadOptionalNodeAttributeImpl(const tensorflow::NodeDef& nodeDef,
83 const std::string& attribName,
84 tensorflow::AttrValue::ValueCase expectedValueCase,
85 Callable callable)
86{
87 auto iter = nodeDef.attr().find(attribName);
88 if (iter != nodeDef.attr().end())
89 {
90 const auto& attrValue = iter->second;
91 if (attrValue.value_case() == expectedValueCase)
92 {
93 callable(attrValue);
94 }
95 else
96 {
telsoa01c577f2c2018-08-31 09:22:23 +010097 throw ParseException(
98 boost::str(
99 boost::format(
100 "Attribute %1% of node %2% expected to have %3% as tensorflow::AttrValue::ValueCase, "
101 "but found %4% instead %5%")
102 % attribName
103 % nodeDef.name()
104 % static_cast<int>(expectedValueCase)
105 % static_cast<int>(attrValue.value_case())
106 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100107 }
108 }
109}
110
111float ReadMandatoryNodeFloatAttribute(const tensorflow::NodeDef& nodeDef, const std::string& name)
112{
113 float attribValue = 0.0f;
114 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kF,
115 [&attribValue](const tensorflow::AttrValue& attrValue)
116 {
117 attribValue = attrValue.f();
118 });
119 return attribValue;
120}
121
Conor Kennedyc2130a02018-12-05 11:05:54 +0000122int32_t ReadMandatoryNodeInt32Attribute(const tensorflow::NodeDef& nodeDef, const std::string& name)
123{
124 int32_t attribValue = 0u;
125 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kI,
126 [&attribValue](const tensorflow::AttrValue& attrValue)
127 {
128 attribValue = static_cast<int32_t>(attrValue.i());
129 });
130 return attribValue;
131}
132
Ferran Balaguer51dd62f2019-01-11 19:29:18 +0000133bool ReadMandatoryNodeBoolAttribute(const tensorflow::NodeDef& nodeDef, const std::string& name)
134{
135 bool attribValue = false;
136 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kB,
137 [&attribValue](const tensorflow::AttrValue& attrValue)
138 {
139 attribValue = static_cast<bool>(attrValue.b());
140 });
141 return attribValue;
142}
143
surmeh01bceff2f2018-03-29 16:29:27 +0100144uint32_t ReadMandatoryNodeUint32Attribute(const tensorflow::NodeDef& nodeDef, const std::string& name)
145{
146 uint32_t attribValue = 0u;
147 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kI,
148 [&attribValue](const tensorflow::AttrValue& attrValue)
149 {
150 attribValue = static_cast<uint32_t>(attrValue.i());
151 });
152 return attribValue;
153}
154
155std::string ReadMandatoryNodeStringAttribute(const tensorflow::NodeDef& nodeDef, const std::string& name)
156{
157 std::string attribValue = "";
158 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kS,
159 [&attribValue](const tensorflow::AttrValue& attrValue)
160 {
161 attribValue = attrValue.s();
162 });
163 return attribValue;
164}
165
166std::vector<uint32_t> ReadMandatoryNodeUint32ListAttribute(const tensorflow::NodeDef& nodeDef,
167 const std::string& name)
168{
169 std::vector<uint32_t> attriList;
170 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kList,
171 [&attriList](const tensorflow::AttrValue& attrValue)
172 {
173 for (int attriNum = 0; attriNum < attrValue.list().i_size(); ++attriNum)
174 {
175 attriList.push_back(static_cast<uint32_t>(attrValue.list().i(attriNum)));
176 }
177 });
178
179 return attriList;
180}
181
182std::vector<uint32_t> ReadOptionalNodeUint32ListAttribute(const tensorflow::NodeDef& nodeDef,
183 const std::string& name)
184{
185 std::vector<uint32_t> attriList;
186 ReadOptionalNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kList,
187 [&attriList](const tensorflow::AttrValue& attrValue)
188 {
189 for (int attriNum = 0; attriNum < attrValue.list().i_size(); ++attriNum)
190 {
191 attriList.push_back(static_cast<uint32_t>(attrValue.list().i(attriNum)));
192 }
193 });
194
195 return attriList;
196}
197
198bool ReadOptionalNodeBoolAttribute(const tensorflow::NodeDef& nodeDef,
199 const std::string& name,
200 bool defaultValue = false)
201{
202 bool attribValue = defaultValue;
203 ReadOptionalNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kB,
204 [&attribValue](const tensorflow::AttrValue& attrValue)
205 {
206 attribValue = attrValue.b();
207 });
208 return attribValue;
209}
210
211tensorflow::DataType ReadMandatoryNodeTypeAttribute(const tensorflow::NodeDef& nodeDef, const std::string& name)
212{
213 tensorflow::DataType attribValue = tensorflow::DT_INVALID;
214 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kType,
215 [&attribValue](const tensorflow::AttrValue& attrValue)
216 {
217 attribValue = attrValue.type();
218 });
219 return attribValue;
220}
221
222TensorInfo PrepareReshape(const TensorInfo& input, const std::vector<int32_t>& targetDims)
223{
224 std::vector<unsigned int> outDims(targetDims.begin(), targetDims.end());
225 const auto stretchDim = std::find(targetDims.begin(), targetDims.end(), -1);
226
227 if (stretchDim != targetDims.end())
228 {
229 if (std::find(std::next(stretchDim), targetDims.end(), -1) != targetDims.end())
230 {
telsoa01c577f2c2018-08-31 09:22:23 +0100231 throw ParseException(
232 boost::str(
233 boost::format(
234 "At most one component of shape can be -1 %1%")
235 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100236 }
237
telsoa01c577f2c2018-08-31 09:22:23 +0100238 auto targetNumElements =
239 boost::numeric_cast<unsigned int>(
240 std::accumulate(targetDims.begin(), targetDims.end(), -1, std::multiplies<int32_t>()));
surmeh01bceff2f2018-03-29 16:29:27 +0100241 auto stretchIndex = static_cast<size_t>(std::distance(targetDims.begin(), stretchDim));
242 outDims[stretchIndex] = input.GetNumElements() / targetNumElements;
243 }
244
245 TensorInfo reshapeInfo = input;
246 reshapeInfo.SetShape(TensorShape{ static_cast<unsigned int>(outDims.size()), outDims.data() });
247
248 return reshapeInfo;
249}
250
telsoa01c577f2c2018-08-31 09:22:23 +0100251// We need the input0Slot to guide the reshape for input1Slot.
saoste01bbd40612018-08-28 15:41:51 +0100252IOutputSlot* AddBroadcastReshapeLayer(IOutputSlot* input0Slot, IOutputSlot* input1Slot, bool isNHWC,
253 INetwork& m_Network, const tensorflow::NodeDef& nodeDef)
surmeh01bceff2f2018-03-29 16:29:27 +0100254{
255 const TensorInfo& input1Info = input1Slot->GetTensorInfo();
256 const TensorInfo inputTensorInfo = input0Slot->GetTensorInfo();
257 const unsigned int matchDim = inputTensorInfo.GetNumDimensions() - (isNHWC ? 1 : 3);
258 std::array<unsigned int, MaxNumOfTensorDimensions> reshapedDimensions;
259 std::fill_n(reshapedDimensions.begin(), inputTensorInfo.GetNumDimensions(), 1);
260 reshapedDimensions[matchDim] = input1Info.GetShape()[0];
261
262 armnn::TensorInfo reshapedInfo = input1Info;
263 reshapedInfo.SetShape(TensorShape{ inputTensorInfo.GetNumDimensions(), reshapedDimensions.data() });
264
265 const std::string reshapeLayerName = "reshape_for-" + nodeDef.name();
266 ReshapeDescriptor reshapeDesc;
267 reshapeDesc.m_TargetShape = reshapedInfo.GetShape();
268 IConnectableLayer* const reshapeLayer = m_Network.AddReshapeLayer(reshapeDesc, reshapeLayerName.c_str());
269
270 input1Slot->Connect(reshapeLayer->GetInputSlot(0));
271 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedInfo);
272
273 input1Slot = &reshapeLayer->GetOutputSlot(0);
274
275 return input1Slot;
276}
277
278OutputId ParseOutputId(const std::string & name)
279{
280 unsigned int outputNum = 0;
281 size_t colonPos = name.find_last_of(":");
282 if (colonPos != std::string::npos)
283 {
284 int n = std::stoi(name.substr(colonPos+1));
285 if (n<0 || n>100)
286 {
telsoa01c577f2c2018-08-31 09:22:23 +0100287 throw ParseException(
288 boost::str(
289 boost::format(
290 "Output tensor id is out of range for %1% %2%")
291 % name
292 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100293 }
294 outputNum = static_cast<unsigned int>(n);
295 }
296 return OutputId(name.substr(0,colonPos),outputNum);
297}
298
telsoa01c577f2c2018-08-31 09:22:23 +0100299#define CHECK_DATA_FORMAT(NODE_DEF, FORMAT, NODE_TYPE) \
300 if( FORMAT != "NHWC" && FORMAT != "NCHW" ) \
301 { \
302 throw ParseException( \
303 boost::str( \
304 boost::format( \
305 "Unsupported data format %1% passed for %2% node %3%. " \
306 "Only NHWC and NCHW supported %4%") \
307 % FORMAT \
308 % NODE_TYPE \
309 % NODE_DEF.name() \
310 % CHECK_LOCATION().AsString())); \
311 }
312
313#define CHECK_PADDING_TYPE(NODE_DEF, PADDING) \
314 if(PADDING != "SAME" && PADDING != "VALID" ) \
315 { \
316 throw ParseException( \
317 boost::str( \
318 boost::format( \
319 "Only 'SAME' and 'VALID' padding supported. Got %1% for %2% %3%") \
320 % PADDING \
321 % NODE_DEF.name() \
322 % CHECK_LOCATION().AsString())); \
323 } \
324
surmeh01bceff2f2018-03-29 16:29:27 +0100325} // namespace
326
327const std::map<std::string, TfParser::OperationParsingFunction> TfParser::ms_OperationNameToParsingFunctions = {
328 { "Const", &TfParser::ParseConst },
329 { "Add", &TfParser::ParseAdd },
Ferran Balaguerfbdad032018-12-28 18:15:24 +0000330 { "AddN", &TfParser::ParseAddN },
surmeh01bceff2f2018-03-29 16:29:27 +0100331 { "BiasAdd", &TfParser::ParseBiasAdd },
332 { "Identity", &TfParser::ParseIdentity },
333 { "Conv2D", &TfParser::ParseConv2D },
334 { "DepthwiseConv2dNative", &TfParser::ParseDepthwiseConv2D },
Conor Kennedyc2130a02018-12-05 11:05:54 +0000335 { "ExpandDims", &TfParser::ParseExpandDims },
surmeh01bceff2f2018-03-29 16:29:27 +0100336 { "FusedBatchNorm", &TfParser::ParseFusedBatchNorm },
FrancisMurtagh94412af2019-01-24 10:53:39 +0000337 { "Gather", &TfParser::ParseGather},
jimfly01a06bf312018-12-18 16:24:51 +0000338 { "Greater", &TfParser::ParseGreater},
surmeh01bceff2f2018-03-29 16:29:27 +0100339 { "ConcatV2", &TfParser::ParseConcat },
340 { "LRN", &TfParser::ParseLrn },
341 { "MatMul", &TfParser::ParseMatMul },
Ferran Balaguer51dd62f2019-01-11 19:29:18 +0000342 { "Mean", &TfParser::ParseMean },
surmeh01bceff2f2018-03-29 16:29:27 +0100343 { "Mul", &TfParser::ParseMul },
344 { "Placeholder", &TfParser::ParsePlaceholder },
saoste01bbd40612018-08-28 15:41:51 +0100345 { "RealDiv", &TfParser::ParseRealDiv },
surmeh01bceff2f2018-03-29 16:29:27 +0100346 { "Relu", &TfParser::ParseRelu },
347 { "Relu6", &TfParser::ParseRelu6 },
348 { "Reshape", &TfParser::ParseReshape },
349 { "ResizeBilinear", &TfParser::ParseResizeBilinear },
Mohamed Nour Abouelseoud7a8892f2019-01-09 14:19:58 +0000350 { "Rsqrt", &TfParser::ParseRsqrt },
surmeh01bceff2f2018-03-29 16:29:27 +0100351 { "Shape", &TfParser::ParseShape },
352 { "Squeeze", &TfParser::ParseSqueeze },
353 { "Sigmoid", &TfParser::ParseSigmoid },
354 { "Softmax", &TfParser::ParseSoftmax },
355 { "Softplus", &TfParser::ParseSoftplus },
Sadik Armagan2ad6cb42018-12-27 11:23:44 +0000356 { "Split", &TfParser::ParseSplit },
surmeh01bceff2f2018-03-29 16:29:27 +0100357 { "Tanh", &TfParser::ParseTanh },
358 { "MaxPool", &TfParser::ParseMaxPool },
359 { "AvgPool", &TfParser::ParseAvgPool },
telsoa01c577f2c2018-08-31 09:22:23 +0100360 { "Maximum", &TfParser::ParseMaximum },
Nattapat Chaimanowong24df8222018-12-04 13:47:02 +0000361 { "Minimum", &TfParser::ParseMinimum },
jimfly0184c70e62018-12-19 13:14:46 +0000362 { "Equal", &TfParser::ParseEqual },
jimfly01f6ba7472018-12-04 10:09:52 +0000363 { "Pad", &TfParser::ParsePad },
narpra016f37f832018-12-21 18:30:00 +0000364 { "Sub", &TfParser::ParseSub }
365};
366
367const std::list<std::string> TfParser::m_ControlInputs = {
368 "Assert"
surmeh01bceff2f2018-03-29 16:29:27 +0100369};
370
371ITfParser* ITfParser::CreateRaw()
372{
373 return new TfParser();
374}
375
376ITfParserPtr ITfParser::Create()
377{
378 return ITfParserPtr(CreateRaw(), &ITfParser::Destroy);
379}
380
381void ITfParser::Destroy(ITfParser* parser)
382{
383 delete parser;
384}
385
386inline void CalculateSamePadding(uint32_t inputSize, uint32_t stride,
387 uint32_t filterSize, bool samePadding,
388 uint32_t* paddingFront, uint32_t* paddingBack) {
389 *paddingFront = 0;
390 *paddingBack = 0;
391
392 if (samePadding) {
393 uint32_t outputSize = (inputSize + stride - 1) / stride;
394 uint32_t temp = (outputSize - 1) * stride + filterSize;
395 if (temp > inputSize) {
396 *paddingFront = (temp - inputSize) / 2;
397 *paddingBack = (temp - inputSize) - *paddingFront;
398 }
399 }
400}
401
402void CalcPadding(uint32_t input, uint32_t kernel, uint32_t stride, uint32_t& outPadHead, uint32_t& outPadTail,
403 bool samePadding)
404{
405 CalculateSamePadding(input, stride, kernel, samePadding, &outPadHead, &outPadTail);
406}
407
408/// An Abstract base class which represents a single tensorflow operation (node)
409/// that has been (potentially partially) converted to Armnn.
410/// It may not yet have been fully converted into actual Armnn layers.
411class ParsedTfOperation
412{
413public:
414 ParsedTfOperation(TfParser* parser, const tensorflow::NodeDef& node)
415 : m_Parser(parser)
416 , m_Node(node)
417 {
418 }
419
420 virtual ~ParsedTfOperation() {};
421
422 const tensorflow::NodeDef& GetNode() const { return m_Node; }
423
424 /// Gets the ArmNN IOutputSlot corresponding to the given output index of the Tensorflow operation.
425 /// This may result in the creation of Armnn layers if this was deferred (e.g. see ParsedConstTfOperation).
426 virtual IOutputSlot& ResolveArmnnOutputSlot(unsigned int tfOutputIndex) = 0;
427
428 /// If this operation is an Identity then this will follow return the 'parent' operation (recursively).
429 virtual ParsedTfOperation* ResolveIdentityOperations()
430 {
431 return this;
432 }
433
434protected:
435 TfParser* m_Parser;
436 const tensorflow::NodeDef& m_Node;
437};
438
439/// An ParsedTfOperation where the Armnn equivalent is a single layer,
440/// with output slots that correspond directly to the Tf node outputs.
441class SingleLayerParsedTfOperation : public ParsedTfOperation
442{
443public:
444 SingleLayerParsedTfOperation(TfParser* parser, const tensorflow::NodeDef& node, IConnectableLayer* layer)
445 : ParsedTfOperation(parser, node)
446 , m_Layer(layer)
447 {
448 }
449
450 IOutputSlot& ResolveArmnnOutputSlot(unsigned int tfOutputIndex) override
451 {
452 BOOST_ASSERT(m_Layer);
telsoa01c577f2c2018-08-31 09:22:23 +0100453 // Assumes one-to-one mapping between Tf and armnn output slots.
surmeh01bceff2f2018-03-29 16:29:27 +0100454 unsigned int armnnOutputSlotIdx = tfOutputIndex;
455 if (armnnOutputSlotIdx >= m_Layer->GetNumOutputSlots())
456 {
457 throw ParseException(
telsoa01c577f2c2018-08-31 09:22:23 +0100458 boost::str(
459 boost::format(
460 "The requested output slot #%1% "
461 "for %2% does not exist %3%")
462 % armnnOutputSlotIdx
463 % m_Layer->GetName()
464 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100465 }
466 return m_Layer->GetOutputSlot(armnnOutputSlotIdx);
467 }
468
469protected:
470 IConnectableLayer* m_Layer;
471};
472
telsoa01c577f2c2018-08-31 09:22:23 +0100473/// A SingleLayerParsedTfOperation for deferred layer creation.
surmeh01bceff2f2018-03-29 16:29:27 +0100474class DeferredSingleLayerParsedTfOperation : public SingleLayerParsedTfOperation
475{
476public:
477 DeferredSingleLayerParsedTfOperation(TfParser* parser, const tensorflow::NodeDef& node)
478 : SingleLayerParsedTfOperation(parser, node, nullptr)
479 {
480 }
481
482 IOutputSlot& ResolveArmnnOutputSlot(unsigned int tfOutputIndex) override
483 {
484 if (!m_Layer)
485 {
486 CreateLayerDeferred();
487 }
488 return SingleLayerParsedTfOperation::ResolveArmnnOutputSlot(tfOutputIndex);
489 }
490
491private:
492 virtual void CreateLayerDeferred() = 0;
493};
494
495
496TfParser::TfParser()
497 : m_Network(nullptr, nullptr)
498{
499}
500
501
502const tensorflow::NodeDef* TfParser::ResolveIdentityNode(const tensorflow::NodeDef* nodeDef)
503{
504 if (nodeDef->op() != "Identity")
505 {
506 return nodeDef;
507 }
508
509 if (nodeDef->input_size() != 1)
510 {
telsoa01c577f2c2018-08-31 09:22:23 +0100511 throw ParseException(
512 boost::str(
513 boost::format(
514 "Identity node should have a single input! %1% has %2% inputs %3%")
515 % nodeDef->name()
516 % nodeDef->input_size()
517 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100518 }
519
520 auto it = m_NodesByName.find(nodeDef->input(0));
521 if (it != m_NodesByName.end())
522 {
523 const tensorflow::NodeDef* inputNode = it->second;
524 return ResolveIdentityNode(inputNode);
525 }
526 else
527 {
telsoa01c577f2c2018-08-31 09:22:23 +0100528 throw ParseException(
529 boost::str(
530 boost::format(
531 "Cannot find what the Identity node %1% is linked to! %2%")
532 % nodeDef->name()
533 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100534 }
535}
536
537std::vector<OutputOfConstNodeDef>
538TfParser::GetTfInputNodes(const tensorflow::NodeDef& nodeDef) const
539{
540 std::vector<OutputOfConstNodeDef> ret;
541
surmeh013537c2c2018-05-18 16:31:43 +0100542 if (nodeDef.op() == "Const")
543 {
544 // For some reason const node can have "Control Inputs". We ignore them for now.
545 return ret;
546 }
547
surmeh01bceff2f2018-03-29 16:29:27 +0100548 ret.reserve(boost::numeric_cast<size_t>(nodeDef.input_size()));
549 for (int j = 0; j < nodeDef.input_size(); ++j)
550 {
551 OutputId outputId = ParseOutputId(nodeDef.input(j));
surmeh013537c2c2018-05-18 16:31:43 +0100552
553 if (nodeDef.input(j)[0] == '^') // I couldn't find a better test for control inputs.
554 {
narpra016f37f832018-12-21 18:30:00 +0000555 // We currently allow Control Input from TensorFlow graph but we ignore them from ArmNN graph.
556 continue;
surmeh013537c2c2018-05-18 16:31:43 +0100557 }
558
surmeh01bceff2f2018-03-29 16:29:27 +0100559 auto inputIt = m_NodesByName.find(outputId.m_IndexedValue);
560 if (inputIt == m_NodesByName.end())
561 {
562 throw ParseException(
telsoa01c577f2c2018-08-31 09:22:23 +0100563 boost::str(
564 boost::format(
565 "Can't find node '%1%', which is listed as an input of '%2%' %3%")
566 % nodeDef.input(j)
567 % nodeDef.name()
568 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100569 }
570 ret.push_back(OutputOfConstNodeDef(inputIt->second,outputId.m_Index));
571 }
572
573 return ret;
574}
575
576std::vector<OutputOfParsedTfOperation>
577TfParser::GetInputParsedTfOperationsChecked(const tensorflow::NodeDef& nodeDef,
578 std::size_t expectedNumInputs)
579{
telsoa01c577f2c2018-08-31 09:22:23 +0100580 // Fetches the tensorflow nodes connected as inputs and validate the size.
surmeh01bceff2f2018-03-29 16:29:27 +0100581 std::vector<OutputOfConstNodeDef> nodes = GetTfInputNodes(nodeDef);
582 const std::size_t numInputs = nodes.size();
583 if (numInputs != expectedNumInputs)
584 {
telsoa01c577f2c2018-08-31 09:22:23 +0100585 throw ParseException(
586 boost::str(
587 boost::format(
588 "Unexpected number of inputs for node %1%. Expected %2%, found %3% %4%")
589 % nodeDef.name()
590 % expectedNumInputs
591 % numInputs
592 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100593 }
telsoa01c577f2c2018-08-31 09:22:23 +0100594 // Fetches the corresponding ParsedTfOperation operations
surmeh01bceff2f2018-03-29 16:29:27 +0100595 std::vector<OutputOfParsedTfOperation> result;
596 for (auto&& node : nodes)
597 {
598 auto it = m_ParsedTfOperations.find(node.m_IndexedValue->name());
599 if (it == m_ParsedTfOperations.end())
600 {
telsoa01c577f2c2018-08-31 09:22:23 +0100601 throw ParseException(
602 boost::str(
603 boost::format(
604 "Node with name '%1%' has not been parsed %2%")
605 % node.m_IndexedValue->name()
606 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100607 }
608 ParsedTfOperation* parsedOp = it->second.get();
609 // Transparently 'skip' any Identity operations. This simplifies the logic inside the ParseXXX() functions.
610 parsedOp = parsedOp->ResolveIdentityOperations();
611 result.push_back(OutputOfParsedTfOperation(parsedOp,node.m_Index));
612 }
613 return result;
614}
615
Ferran Balaguerfbdad032018-12-28 18:15:24 +0000616IConnectableLayer* TfParser::CreateAdditionLayer(
617 const tensorflow::NodeDef& nodeDef,
618 IOutputSlot* input0Slot,
619 IOutputSlot* input1Slot,
620 const std::string& layerName)
621{
622 const TensorInfo& input0Info = input0Slot->GetTensorInfo();
623 const TensorInfo& input1Info = input1Slot->GetTensorInfo();
624
625 const unsigned int input0Dim = input0Info.GetNumDimensions();
626 const unsigned int input1Dim = input1Info.GetNumDimensions();
627 if (input0Dim != input1Dim)
628 {
629 // broadcasting where input0 and input1 have different number of dimensions
630 // is only supported for 1D and 4D tensors pair
631 if (input0Dim == 1 && input1Dim == 4)
632 {
633 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot, true, *m_Network, nodeDef);
634 }
635 else if (input0Dim == 4 && input1Dim == 1)
636 {
637 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, true, *m_Network, nodeDef);
638 }
639 else
640 {
641 throw ParseException(
642 boost::str(
643 boost::format("Unsupported broadcast configuration for %1% operation %2% %3%")
644 % layerName
645 % nodeDef.name()
646 % CHECK_LOCATION().AsString()));
647 }
648 }
649 IConnectableLayer* const layer = m_Network->AddAdditionLayer(layerName.c_str());
650
651 input0Slot->Connect(layer->GetInputSlot(0));
652 input1Slot->Connect(layer->GetInputSlot(1));
653
654 // Ensure the output tensor has the correct dimensions even if a broadcast has been done
655 TensorInfo outputInfo = input0Slot->GetTensorInfo();
656 std::vector<unsigned int> outputShape;
657
658 const TensorShape& input0Shape = input0Slot->GetTensorInfo().GetShape();
659 const TensorShape& input1Shape = input1Slot->GetTensorInfo().GetShape();
660
661 for (unsigned int i = 0; i < input0Shape.GetNumDimensions(); i++)
662 {
663 outputShape.push_back(std::max(input0Shape[i], input1Shape[i]));
664 }
665
666 outputInfo.SetShape(TensorShape(input0Shape.GetNumDimensions(), outputShape.data()));
667 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
668
669 return layer;
670}
671
672IConnectableLayer* TfParser::CreateAdditionLayer(
673 const tensorflow::NodeDef& nodeDef,
674 IConnectableLayer* layerOne,
675 IConnectableLayer* layerTwo,
676 unsigned int numberOfAddition,
677 unsigned long numberOfLayersToConnect,
678 bool isOdd)
679{
680 IOutputSlot* input0Slot = &layerOne->GetOutputSlot(0);
681 IOutputSlot* input1Slot = &layerTwo->GetOutputSlot(0);
682 std::string layerName(nodeDef.name());
683 if (isOdd || numberOfLayersToConnect != 2)
684 {
685 // we are not connecting the final layer
686 layerName.append("_addN_").append(std::to_string(numberOfAddition));
687 }
688 return CreateAdditionLayer(nodeDef, input0Slot, input1Slot, layerName);
689}
690
691IConnectableLayer* TfParser::CreateAdditionLayer(
692 const tensorflow::NodeDef& nodeDef,
693 const OutputOfParsedTfOperation& opOne,
694 const OutputOfParsedTfOperation& opTwo,
695 unsigned int numberOfAddition)
696{
697 IOutputSlot* input0Slot = &opOne.m_IndexedValue->ResolveArmnnOutputSlot(opOne.m_Index);
698 IOutputSlot* input1Slot = &opTwo.m_IndexedValue->ResolveArmnnOutputSlot(opTwo.m_Index);
699 std::string layerName(nodeDef.name());
700 layerName.append("_addN_").append(std::to_string(numberOfAddition));
701 return CreateAdditionLayer(nodeDef, input0Slot, input1Slot, layerName);
702}
703
704IConnectableLayer* TfParser::CreateAdditionLayer(
705 const tensorflow::NodeDef& nodeDef,
706 const OutputOfParsedTfOperation& op,
707 IConnectableLayer* layer)
708{
709 IOutputSlot* input0Slot = &op.m_IndexedValue->ResolveArmnnOutputSlot(op.m_Index);
710 IOutputSlot* input1Slot = &layer->GetOutputSlot(0);
711 return CreateAdditionLayer(nodeDef, input0Slot, input1Slot, nodeDef.name());
712}
713
714ParsedTfOperationPtr TfParser::ParseAddN(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
715{
716 uint32_t numberOfInputs = ReadMandatoryNodeUint32Attribute(nodeDef, "N");
717 if (numberOfInputs < 2)
718 {
719 // should never happen
720 throw ParseException(
721 boost::str(
722 boost::format(
723 "AddN Node with name '%1%' has less than two (%2) inputs %3%")
724 % nodeDef.name()
725 % std::to_string(numberOfInputs)
726 % CHECK_LOCATION().AsString()));
727 }
728 else if (numberOfInputs == 2)
729 {
730 //this is the same as a simple Add operation
731 return AddAdditionLayer(nodeDef, false);
732 }
733 else
734 {
735 // build a binary tree of Add layers and return the final Add as the return from the function
736 // if we have an odd number of inputs then the final Add will consist of a layer connecting to an
737 // OutputOfParsedTfOperation, otherwise it will be two layers being added together
738 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, numberOfInputs);
739 unsigned int numberOfAdditions = 0;
740 std::vector<IConnectableLayer*> layers;
741 // NOTE: at this point we will have a minimum of three inputs
742 for (unsigned int i = 0; i < numberOfInputs; ++i)
743 {
744 // every time i is odd we have two inputs to process.
745 bool onSecondItem = i % 2;
746 if (onSecondItem)
747 {
748 ++numberOfAdditions;
749 IConnectableLayer* newLayer = CreateAdditionLayer(
750 nodeDef, inputs[ i - 1], inputs[i], numberOfAdditions);
751 layers.push_back(newLayer);
752 }
753 }
754
755 std::vector<IConnectableLayer*> layersToConnect(layers);
756 unsigned long numberOfLayersToConnect = layersToConnect.size();
757 bool isOdd = numberOfInputs % 2;
758
759 while (numberOfLayersToConnect > 1)
760 {
761 layers.clear();
762 for (unsigned long i = 0; i < numberOfLayersToConnect; ++i) {
763 bool onSecondItem = i % 2;
764 if (onSecondItem) {
765 ++numberOfAdditions;
766 IConnectableLayer* newLayer = CreateAdditionLayer(
767 nodeDef,
768 layersToConnect[i - 1],
769 layersToConnect[i],
770 numberOfAdditions,
771 numberOfLayersToConnect,
772 isOdd);
773 layers.push_back(newLayer);
774 }
775 }
776 //OK... need to go again... maybe
777 layersToConnect = layers;
778 numberOfLayersToConnect = layersToConnect.size();
779 }
780 IConnectableLayer* finalLayer = layersToConnect[0];
781 // if we had an odd number of inputs we need to connect the final layer to the
782 // last OutputOfParsedTfOperation in order to create the last Add layer we will
783 // be handing back.
784 if (isOdd)
785 {
786 // connect the final layer to the last op
787 finalLayer = CreateAdditionLayer(nodeDef, inputs[numberOfInputs - 1], finalLayer);
788 }
789 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, finalLayer);
790 }
791}
792
surmeh01bceff2f2018-03-29 16:29:27 +0100793ParsedTfOperationPtr TfParser::ParseAdd(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
794{
795 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
796
telsoa01c577f2c2018-08-31 09:22:23 +0100797 // If one of the inputs is a MatMul and the other is a const, then we handle both nodes
798 // together as FullyConnected.
surmeh01bceff2f2018-03-29 16:29:27 +0100799 if (inputs[0].m_IndexedValue->GetNode().op() == "MatMul" &&
800 HasParsedConstTensor<float>(inputs[1].m_IndexedValue->GetNode().name()))
801 {
802 IConnectableLayer* layer =
803 AddFullyConnectedLayer(inputs[0].m_IndexedValue->GetNode(),
804 &nodeDef,nodeDef.name().c_str());
805 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
806 }
807 else if (HasParsedConstTensor<float>(inputs[0].m_IndexedValue->GetNode().name()) &&
808 inputs[1].m_IndexedValue->GetNode().op() == "MatMul")
809 {
810 IConnectableLayer* layer =
811 AddFullyConnectedLayer(inputs[1].m_IndexedValue->GetNode(),
812 &nodeDef,nodeDef.name().c_str());
813 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
814 }
815 else
816 {
telsoa01c577f2c2018-08-31 09:22:23 +0100817 // Otherwise it's just a regular addition.
surmeh01bceff2f2018-03-29 16:29:27 +0100818 return AddAdditionLayer(nodeDef);
819 }
820}
821
822ParsedTfOperationPtr TfParser::ParseBiasAdd(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
823{
824 return AddAdditionLayer(nodeDef, true);
825}
826
827/// An ParsedTfOperation which forwards to another (used for Identity nodes).
828class ParsedIdentityTfOperation : public ParsedTfOperation
829{
830public:
831 ParsedIdentityTfOperation(TfParser* parser, const tensorflow::NodeDef& node, ParsedTfOperation* representative)
832 : ParsedTfOperation(parser, node)
833 , m_Representative(representative)
834 {
835 }
836
837 virtual IOutputSlot& ResolveArmnnOutputSlot(unsigned int tfOutputIndex) override
838 {
839 BOOST_ASSERT(m_Representative);
840 return m_Representative->ResolveArmnnOutputSlot(tfOutputIndex);
841 }
842
843 virtual ParsedTfOperation* ResolveIdentityOperations() override
844 {
845 return m_Representative->ResolveIdentityOperations();
846 }
847
848private:
849 ParsedTfOperation* m_Representative;
850};
851
852ParsedTfOperationPtr TfParser::ParseIdentity(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
853{
854 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
855 // Any requests for the output slots of this node should be forwarded to the node connected as input.
856 return std::make_unique<ParsedIdentityTfOperation>(this, nodeDef, inputs[0].m_IndexedValue);
857}
858
859/// An ParsedTfOperation for a Const node.
860/// Creation of the armnn ConstLayer is deferred until it is actually needed, because Const nodes are mostly used
861/// for weight inputs to MatMul/Conv2D nodes and in these cases armnn doesn't need a ConstLayer.
862template <typename T>
863class ParsedConstTfOperation : public DeferredSingleLayerParsedTfOperation
864{
865public:
866 ParsedConstTfOperation(TfParser* parser, const tensorflow::NodeDef& node,
867 const T* tensorData, const TensorInfo& tensorInfo)
868 : DeferredSingleLayerParsedTfOperation(parser, node),
869 m_Storage(tensorData, tensorData + tensorInfo.GetNumElements()),
870 m_TensorInfo(tensorInfo)
871 {
Nattapat Chaimanowong649dd952019-01-22 16:10:44 +0000872 BOOST_ASSERT(GetDataTypeSize(tensorInfo.GetDataType()) == sizeof(T));
surmeh01bceff2f2018-03-29 16:29:27 +0100873 }
874
875 void CreateLayerDeferred() override
876 {
877 BOOST_ASSERT(m_Layer == nullptr);
878 m_Layer = m_Parser->m_Network->AddConstantLayer(ConstTensor(m_TensorInfo, m_Storage), m_Node.name().c_str());
879 m_Layer->GetOutputSlot(0).SetTensorInfo(m_TensorInfo);
880 }
881
Matteo Martincigh482ca852018-12-12 09:20:55 +0000882 ConstTensor GetConstTensor(std::vector<T>& outputTensorData) const
surmeh01bceff2f2018-03-29 16:29:27 +0100883 {
surmeh01bceff2f2018-03-29 16:29:27 +0100884 outputTensorData.resize(m_TensorInfo.GetNumElements());
885
Matteo Martincigh482ca852018-12-12 09:20:55 +0000886 memcpy(outputTensorData.data(), m_Storage.data(), m_TensorInfo.GetNumBytes());
887
telsoa01c577f2c2018-08-31 09:22:23 +0100888 // Updates the result to point to the user provided storage.
Matteo Martincigh482ca852018-12-12 09:20:55 +0000889 ConstTensor constTensor(m_TensorInfo, outputTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +0100890 return constTensor;
891 }
892
Matteo Martincigh46315822018-11-28 16:22:36 +0000893 const T* GetStorage() const
894 {
895 return m_Storage.data();
896 }
897
898 const TensorInfo& GetTensorInfo() const
899 {
900 return m_TensorInfo;
901 }
902
surmeh01bceff2f2018-03-29 16:29:27 +0100903private:
904 ///< Manages the lifetime of the tensor data.
905 std::vector<T> m_Storage;
906 ///< Describes the layout of the tensor and points to the data in m_Storage.
907 TensorInfo m_TensorInfo;
908};
909
telsoa01c577f2c2018-08-31 09:22:23 +0100910DataType ConvertTfTensorDataType(const tensorflow::DataType tfDataType,
911 const tensorflow::NodeDef& nodeDef)
surmeh01bceff2f2018-03-29 16:29:27 +0100912{
913 switch (tfDataType)
914 {
915 case tensorflow::DT_FLOAT:
916 return DataType::Float32;
917 break;
918 case tensorflow::DT_INT32:
919 return DataType::Signed32;
920 break;
921 default:
telsoa01c577f2c2018-08-31 09:22:23 +0100922 throw ParseException(
923 boost::str(
924 boost::format(
925 "Unknown DataType %1% for node %2% %3%")
926 % tensorflow::DataType_Name(tfDataType)
927 % nodeDef.name()
928 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100929 }
930}
931
932struct ParseTfTensorValueList
933{
934 template<typename DataType>
935 static void Parse(
936 const tensorflow::TensorProto& tfTensor,
937 unsigned int dstElements,
938 std::vector<int8_t>& outputData);
939
940 template <typename DataType>
941 static void ReadData(const void* srcData, unsigned int numSrcElements,
942 std::vector<int8_t>& dstData, unsigned int numDstElements)
943 {
telsoa01c577f2c2018-08-31 09:22:23 +0100944 // If there are no entries in the list, perform no action.
surmeh01bceff2f2018-03-29 16:29:27 +0100945 if (numSrcElements == 0)
946 {
947 return;
948 }
949
telsoa01c577f2c2018-08-31 09:22:23 +0100950 // If no size was provided, use the length of the value list.
surmeh01bceff2f2018-03-29 16:29:27 +0100951 if (numDstElements == 0)
952 {
953 numDstElements = numSrcElements;
954 }
955
telsoa01c577f2c2018-08-31 09:22:23 +0100956 // Allocates memory.
surmeh01bceff2f2018-03-29 16:29:27 +0100957 dstData.resize(std::max(numSrcElements, numDstElements) * sizeof(DataType));
958
959 const DataType* srcTensor = reinterpret_cast<const DataType*>(srcData);
960 DataType* dstTensor = reinterpret_cast<DataType*>(dstData.data());
961
telsoa01c577f2c2018-08-31 09:22:23 +0100962 // Copies the value list entries into the destination.
surmeh01bceff2f2018-03-29 16:29:27 +0100963 std::copy(srcTensor, srcTensor + numSrcElements, dstTensor);
964
965 if (numDstElements > numSrcElements)
966 {
telsoa01c577f2c2018-08-31 09:22:23 +0100967 // Uses the last element in the list to fill the remaining entries.
surmeh01bceff2f2018-03-29 16:29:27 +0100968 std::fill(dstTensor + numSrcElements, dstTensor + numDstElements, srcTensor[numSrcElements - 1]);
969 }
970 }
971
972};
973
974template <>
975void ParseTfTensorValueList::Parse<float>(const tensorflow::TensorProto& tfTensor,
976 unsigned int dstElements, std::vector<int8_t>& outputData)
977{
978 ReadData<float>(tfTensor.float_val().data(), static_cast<unsigned int>(tfTensor.float_val_size()),
979 outputData, dstElements);
980}
981
982template <>
983void ParseTfTensorValueList::Parse<int32_t>(const tensorflow::TensorProto& tfTensor,
984 unsigned int dstElements, std::vector<int8_t>& outputData)
985{
986 ReadData<int32_t>(tfTensor.int_val().data(), static_cast<unsigned int>(tfTensor.int_val_size()),
987 outputData, dstElements);
988}
989
990template <template<typename> class OperatorType, typename T = int8_t>
991struct MakeTfOperation
992{
993 template<typename DataType, class... Args>
994 inline static std::unique_ptr<OperatorType<DataType>> Parse(TfParser* parser, const tensorflow::NodeDef& node,
995 Args&&... args)
996 {
997 return std::make_unique<OperatorType<DataType>>(parser, node, std::forward<Args>(args)...);
998 }
999};
1000
1001template <>
1002struct MakeTfOperation<ParsedConstTfOperation>
1003{
1004 template<typename DataType, class... Args>
1005 inline static std::unique_ptr<ParsedConstTfOperation<DataType>> Parse(TfParser* parser,
1006 const tensorflow::NodeDef& node, const std::vector<int8_t>& tensorData, const TensorInfo& tensorInfo)
1007 {
1008 return std::make_unique<ParsedConstTfOperation<DataType>>(parser, node,
1009 reinterpret_cast<const DataType*>(tensorData.data()), tensorInfo);
1010 }
1011};
1012
1013template <class FuncType>
1014struct InvokeParseFunction
1015{
1016 template<class ResType, class... Args>
1017 inline static ResType Result(DataType dataType, Args&&... args)
1018 {
1019 if (dataType == DataType::Float32)
1020 {
1021 return FuncType::template Parse<float>(std::forward<Args>(args)...);
1022 }
1023 else if (dataType == DataType::Signed32)
1024 {
1025 return FuncType::template Parse<int32_t>(std::forward<Args>(args)...);
1026 }
1027
1028 return ResType();
1029 }
1030
1031 template<class... Args>
1032 inline static void Result(DataType dataType, Args&&... args)
1033 {
1034 if (dataType == DataType::Float32)
1035 {
1036 FuncType::template Parse<float>(std::forward<Args>(args)...);
1037 }
1038 else if (dataType == DataType::Signed32)
1039 {
1040 FuncType::template Parse<int32_t>(std::forward<Args>(args)...);
1041 }
1042 }
1043};
1044
1045ParsedTfOperationPtr TfParser::ParseConst(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
1046{
1047 BOOST_ASSERT(nodeDef.op() == "Const");
1048
1049 if (nodeDef.attr().count("value") == 0)
1050 {
telsoa01c577f2c2018-08-31 09:22:23 +01001051 throw ParseException(
1052 boost::str(
1053 boost::format(
1054 "Value not found for Const node - %1% %2%")
1055 % nodeDef.name()
1056 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001057 }
1058
1059 const tensorflow::TensorProto& tfTensor = nodeDef.attr().at("value").tensor();
1060 const tensorflow::TensorShapeProto& tfTensorShape = tfTensor.tensor_shape();
1061 const tensorflow::DataType tfDataType = ReadMandatoryNodeTypeAttribute(nodeDef, "dtype");
1062
1063 const auto GetDimensionSize = [](auto& d) { return d.size(); };
1064
1065 std::vector<unsigned int> dimensionSizes;
1066 std::transform(tfTensorShape.dim().begin(), tfTensorShape.dim().end(),
1067 std::back_inserter(dimensionSizes), GetDimensionSize);
1068
telsoa01c577f2c2018-08-31 09:22:23 +01001069 // Calculates number of elements.
1070 const DataType dataType = ConvertTfTensorDataType(tfDataType, nodeDef);
surmeh01bceff2f2018-03-29 16:29:27 +01001071 unsigned int numElements = 0U;
1072
1073 if (!dimensionSizes.empty())
1074 {
1075 numElements = std::accumulate(dimensionSizes.begin(), dimensionSizes.end(),
1076 1U, std::multiplies<unsigned int>());
1077 }
1078
1079 std::vector<int8_t> tensorData;
1080
telsoa01c577f2c2018-08-31 09:22:23 +01001081 // Get tensor data from the list of values attribute.
surmeh01bceff2f2018-03-29 16:29:27 +01001082 if (tfTensor.tensor_content().empty())
1083 {
1084 InvokeParseFunction<ParseTfTensorValueList>::Result<void>(dataType, tfTensor, numElements, tensorData);
1085
1086 // If the tensor shape is not defined, but there is a value list, then interpret the data as a 1D
telsoa01c577f2c2018-08-31 09:22:23 +01001087 // tensor of the provided number of elements.
surmeh01bceff2f2018-03-29 16:29:27 +01001088 if (numElements == 0)
1089 {
telsoa01c577f2c2018-08-31 09:22:23 +01001090 const unsigned int tfNumElements =
1091 static_cast<unsigned int>(tensorData.size()) / GetDataTypeSize(dataType);
surmeh01bceff2f2018-03-29 16:29:27 +01001092 dimensionSizes.push_back(tfNumElements);
1093 }
1094 }
telsoa01c577f2c2018-08-31 09:22:23 +01001095 // Gets tensor data from tensor content attribute.
surmeh01bceff2f2018-03-29 16:29:27 +01001096 else
1097 {
1098 tensorData.assign(tfTensor.tensor_content().begin(), tfTensor.tensor_content().end());
1099
telsoa01c577f2c2018-08-31 09:22:23 +01001100 // Checks if a tensor shape is defined for the tensor content.
surmeh01bceff2f2018-03-29 16:29:27 +01001101 if (numElements == 0)
1102 {
telsoa01c577f2c2018-08-31 09:22:23 +01001103 throw ParseException(
1104 boost::str(
1105 boost::format(
1106 "No tensor shape found for Const node - %1% %2%")
1107 % nodeDef.name()
1108 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001109 }
1110 }
1111
telsoa01c577f2c2018-08-31 09:22:23 +01001112 // Const node requires at least a list of values or a content attribute.
surmeh01bceff2f2018-03-29 16:29:27 +01001113 if (tensorData.empty())
1114 {
telsoa01c577f2c2018-08-31 09:22:23 +01001115 throw ParseException(
1116 boost::str(
1117 boost::format(
1118 "No tensor data found for Const node - %1% %2%")
1119 % nodeDef.name()
1120 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001121 }
1122
telsoa01c577f2c2018-08-31 09:22:23 +01001123 const TensorInfo tensorInfo(static_cast<unsigned int>(dimensionSizes.size()),
1124 dimensionSizes.data(),
1125 dataType);
surmeh01bceff2f2018-03-29 16:29:27 +01001126
1127 // If we have a list of values, then the length of the list must be
telsoa01c577f2c2018-08-31 09:22:23 +01001128 // less than or equal to the number of elements implied by the shape argument.
surmeh01bceff2f2018-03-29 16:29:27 +01001129 if (tensorData.size() > tensorInfo.GetNumBytes())
1130 {
telsoa01c577f2c2018-08-31 09:22:23 +01001131 throw ParseException(
1132 boost::str(
1133 boost::format(
1134 "Number of elements (%1%) should be less than or equal "
1135 "to the number of elements implied by the shape argument (%2%) for Const node - %3% %4%")
1136 % (tensorData.size() / GetDataTypeSize(dataType))
1137 % tensorInfo.GetNumElements()
1138 % nodeDef.name()
1139 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001140 }
1141
1142 return InvokeParseFunction<MakeTfOperation<ParsedConstTfOperation>>::Result<ParsedTfOperationPtr>(
1143 dataType, this, nodeDef, tensorData, tensorInfo);
1144}
1145
1146template<typename Type>
1147bool TfParser::HasParsedConstTensor(const std::string & nodeName) const
1148{
1149 auto it = m_ParsedTfOperations.find(nodeName);
jimfly01f6ba7472018-12-04 10:09:52 +00001150 if (it == m_ParsedTfOperations.end())
surmeh01bceff2f2018-03-29 16:29:27 +01001151 {
1152 return false;
1153 }
jimfly01f6ba7472018-12-04 10:09:52 +00001154 return dynamic_cast<ParsedConstTfOperation<Type>*>(it->second.get()) != nullptr;
1155}
1156
1157template<typename Type>
1158bool TfParser::HasParsedConstTensor(ParsedTfOperation* parsedTfOpPtr) const
1159{
1160 return dynamic_cast<ParsedConstTfOperation<Type>*>(parsedTfOpPtr) != nullptr;
surmeh01bceff2f2018-03-29 16:29:27 +01001161}
1162
Saoirse Stewart91c0eff2019-02-27 11:07:57 +00001163unsigned int TfParser::GetConstInputIndex(const std::vector<OutputOfParsedTfOperation>& inputs)
1164{
1165 for (unsigned int i = 0; i < inputs.size(); i++)
1166 {
1167 if (HasParsedConstTensor<int32_t>(inputs[i].m_IndexedValue->GetNode().name()))
1168 {
1169 return i;
1170 }
1171 }
1172 throw ParseException(
1173 boost::str(
1174 boost::format(
1175 "ArmNN only supports operators with constant axis. %1%")
1176 % CHECK_LOCATION().AsString()));
1177
1178}
1179
surmeh01bceff2f2018-03-29 16:29:27 +01001180ParsedTfOperationPtr TfParser::ParseConv2D(const tensorflow::NodeDef& nodeDef,
1181 const tensorflow::GraphDef& graphDef)
1182{
1183 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
1184 IOutputSlot& inputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1185 TensorInfo inputTensorInfo = inputSlot.GetTensorInfo();
1186
1187 if (!HasParsedConstTensor<float>(inputs[1].m_IndexedValue->GetNode().name()))
1188 {
telsoa01c577f2c2018-08-31 09:22:23 +01001189 throw ParseException(
1190 boost::str(
1191 boost::format(
1192 "ArmNN only supports Convolution layers with constant weights for %1%, input %2% %3%")
1193 % nodeDef.name()
1194 % inputs[1].m_IndexedValue->GetNode().name()
1195 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001196 }
1197 ParsedConstTfOperation<float>* weightNode =
1198 boost::polymorphic_downcast<ParsedConstTfOperation<float> *>(inputs[1].m_IndexedValue);
1199
1200 std::string paddingString = ReadMandatoryNodeStringAttribute(nodeDef, "padding");
1201 std::string dataFormat = ReadMandatoryNodeStringAttribute(nodeDef, "data_format");
1202 std::vector<uint32_t> strides = ReadMandatoryNodeUint32ListAttribute(nodeDef, "strides");
1203
telsoa01c577f2c2018-08-31 09:22:23 +01001204 // Read the dilations, if present - only [1,1,1,1] (the default) is supported.
surmeh01bceff2f2018-03-29 16:29:27 +01001205 std::vector<uint32_t> dilations = ReadOptionalNodeUint32ListAttribute(nodeDef, "dilations");
1206 if (!dilations.empty())
1207 {
1208 for (auto dilation : dilations)
1209 {
1210 if (dilation != 1u)
1211 {
telsoa01c577f2c2018-08-31 09:22:23 +01001212 throw ParseException(
1213 boost::str(
1214 boost::format(
1215 "ArmNN only supports Convolution layers with dilations [1,1,1,1] for %1% %2%")
1216 % nodeDef.name()
1217 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001218 }
1219 }
1220 }
1221
1222 Convolution2dDescriptor desc;
1223 desc.m_BiasEnabled = false;
1224
telsoa01c577f2c2018-08-31 09:22:23 +01001225 CHECK_DATA_FORMAT(nodeDef, dataFormat, "Conv2D");
1226
Matteo Martincigh46315822018-11-28 16:22:36 +00001227 DataLayout dataLayout = dataFormat == "NHWC" ? DataLayout::NHWC : DataLayout::NCHW;
surmeh01bceff2f2018-03-29 16:29:27 +01001228
Matteo Martincigh46315822018-11-28 16:22:36 +00001229 desc.m_DataLayout = dataLayout;
surmeh01bceff2f2018-03-29 16:29:27 +01001230
Matteo Martincigh46315822018-11-28 16:22:36 +00001231 DataLayoutIndexed dataLayoutIndexed(dataLayout);
surmeh01bceff2f2018-03-29 16:29:27 +01001232
Matteo Martincigh46315822018-11-28 16:22:36 +00001233 desc.m_StrideX = strides[dataLayoutIndexed.GetWidthIndex()];
1234 desc.m_StrideY = strides[dataLayoutIndexed.GetHeightIndex()];
surmeh01bceff2f2018-03-29 16:29:27 +01001235
Matteo Martincigh46315822018-11-28 16:22:36 +00001236 uint32_t inputHeight = inputTensorInfo.GetShape()[dataLayoutIndexed.GetHeightIndex()];
1237 uint32_t inputWidth = inputTensorInfo.GetShape()[dataLayoutIndexed.GetWidthIndex()];
1238
1239 // Mappings from TensorFlow filter tensors to the ArmNN filter tensors.
1240 // Tensorflow weights are [H, W, In, Out].
1241 // ArmNN weights have to be [Out, H, W, In] when the data layout is NHWC,
1242 // and [Out, In, H, W] when the data layout is NCHW.
1243 PermutationVector permutationVector =
1244 dataLayout == DataLayout::NHWC ?
1245 std::initializer_list<unsigned int>{ 1, 2, 3, 0 } : // NHWC: [H, W, In, Out] -> [Out, H, W, In]
1246 std::initializer_list<unsigned int>{ 2, 3, 1, 0 }; // NCHW: [H, W, In, Out] -> [Out, In, H, W]
1247
1248 // Swizzle the tensor using the given permutation vector.
1249 const TensorInfo& weightTensorInfo = weightNode->GetTensorInfo();
1250 const TensorInfo weightTensorSwizzledInfo = armnnUtils::Permuted(weightTensorInfo, permutationVector);
1251
1252 // Swizzles the content of the tensor's permanent storage into a local storage.
1253 std::vector<float> weightTensorSwizzledData(weightTensorInfo.GetNumElements());
1254 armnnUtils::Permute(weightTensorSwizzledInfo.GetShape(), permutationVector,
Matteo Martincighd5b9e642019-01-04 18:01:21 +00001255 weightNode->GetStorage(), weightTensorSwizzledData.data(), sizeof(float));
Matteo Martincigh46315822018-11-28 16:22:36 +00001256
1257 // Create a weight tensor with the newly swizzled data.
1258 ConstTensor weightTensor(weightTensorSwizzledInfo, weightTensorSwizzledData);
1259
1260 uint32_t weightHeight = weightTensor.GetShape()[dataLayoutIndexed.GetHeightIndex()];
1261 uint32_t weightWidth = weightTensor.GetShape()[dataLayoutIndexed.GetWidthIndex()];
surmeh01bceff2f2018-03-29 16:29:27 +01001262
1263 bool padding = false;
1264 TensorInfo outputInfo;
Matteo Martincigh46315822018-11-28 16:22:36 +00001265 unsigned int outputHeight = 0;
1266 unsigned int outputWidth = 0;
telsoa01c577f2c2018-08-31 09:22:23 +01001267
1268 CHECK_PADDING_TYPE(nodeDef, paddingString);
1269
surmeh01bceff2f2018-03-29 16:29:27 +01001270 if (paddingString == "SAME")
1271 {
1272 padding = true;
Matteo Martincigh46315822018-11-28 16:22:36 +00001273
1274 outputHeight = static_cast<uint32_t>(ceil(static_cast<float>(inputHeight) /
1275 static_cast<float>(desc.m_StrideY)));
1276 outputWidth = static_cast<uint32_t>(ceil(static_cast<float>(inputWidth) /
1277 static_cast<float>(desc.m_StrideX)));
surmeh01bceff2f2018-03-29 16:29:27 +01001278 }
1279 else if (paddingString == "VALID")
1280 {
1281 padding = false;
Matteo Martincigh46315822018-11-28 16:22:36 +00001282
1283 outputHeight = static_cast<uint32_t>(ceil(static_cast<float>(inputHeight - weightHeight + 1) /
1284 static_cast<float>(desc.m_StrideY)));
1285 outputWidth = static_cast<uint32_t>(ceil(static_cast<float>(inputWidth - weightWidth + 1) /
1286 static_cast<float>(desc.m_StrideX)));
1287 }
1288
1289 switch (dataLayout)
1290 {
1291 case DataLayout::NHWC:
1292 outputInfo = TensorInfo({ inputTensorInfo.GetShape()[0],
1293 outputHeight,
1294 outputWidth,
1295 weightTensor.GetShape()[0] },
1296 DataType::Float32);
1297 break;
1298 case DataLayout::NCHW:
1299 default:
surmeh01bceff2f2018-03-29 16:29:27 +01001300 outputInfo = TensorInfo({ inputTensorInfo.GetShape()[0],
1301 weightTensor.GetShape()[0],
Matteo Martincigh46315822018-11-28 16:22:36 +00001302 outputHeight,
1303 outputWidth },
1304 DataType::Float32);
1305 break;
surmeh01bceff2f2018-03-29 16:29:27 +01001306 }
surmeh01bceff2f2018-03-29 16:29:27 +01001307
1308 CalcPadding(inputHeight, weightHeight, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, padding);
1309 CalcPadding(inputWidth, weightWidth, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, padding);
1310
1311 IConnectableLayer* layer = m_Network->AddConvolution2dLayer(desc, weightTensor, nodeDef.name().c_str());
1312 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
Matteo Martincigh46315822018-11-28 16:22:36 +00001313 inputSlot.Connect(layer->GetInputSlot(0));
surmeh01bceff2f2018-03-29 16:29:27 +01001314
1315 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
1316}
1317
1318ParsedTfOperationPtr TfParser::ParseDepthwiseConv2D(const tensorflow::NodeDef& nodeDef,
telsoa01c577f2c2018-08-31 09:22:23 +01001319 const tensorflow::GraphDef& graphDef)
surmeh01bceff2f2018-03-29 16:29:27 +01001320{
1321 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
1322 IOutputSlot& inputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1323 TensorInfo inputTensorInfo = inputSlot.GetTensorInfo();
1324
1325 if (!HasParsedConstTensor<float>(inputs[1].m_IndexedValue->GetNode().name()))
1326 {
telsoa01c577f2c2018-08-31 09:22:23 +01001327 throw ParseException(
1328 boost::str(
1329 boost::format(
1330 "ArmNN only supports Depthwise Convolution layer with constant weights. "
1331 "Non const input found %1% for node %2% %3%")
1332 % inputs[1].m_IndexedValue->GetNode().name()
1333 % nodeDef.name()
1334 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001335 }
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001336
surmeh01bceff2f2018-03-29 16:29:27 +01001337 ParsedConstTfOperation<float>* weightNode =
1338 boost::polymorphic_downcast<ParsedConstTfOperation<float> *>(inputs[1].m_IndexedValue);
1339
surmeh01bceff2f2018-03-29 16:29:27 +01001340 std::string paddingString = ReadMandatoryNodeStringAttribute(nodeDef, "padding");
1341 std::string dataFormat = ReadMandatoryNodeStringAttribute(nodeDef, "data_format");
1342 std::vector<uint32_t> strides = ReadMandatoryNodeUint32ListAttribute(nodeDef, "strides");
1343
1344 DepthwiseConvolution2dDescriptor desc;
1345 desc.m_BiasEnabled = false;
1346
telsoa01c577f2c2018-08-31 09:22:23 +01001347 CHECK_DATA_FORMAT(nodeDef, dataFormat, "DepthwiseConv2dNative");
1348
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001349 DataLayout dataLayout = dataFormat == "NHWC" ? DataLayout::NHWC : DataLayout::NCHW;
surmeh01bceff2f2018-03-29 16:29:27 +01001350
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001351 desc.m_DataLayout = dataLayout;
surmeh01bceff2f2018-03-29 16:29:27 +01001352
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001353 DataLayoutIndexed dataLayoutIndexed(dataLayout);
surmeh01bceff2f2018-03-29 16:29:27 +01001354
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001355 desc.m_StrideX = strides[dataLayoutIndexed.GetWidthIndex()];
1356 desc.m_StrideY = strides[dataLayoutIndexed.GetHeightIndex()];
surmeh01bceff2f2018-03-29 16:29:27 +01001357
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001358 uint32_t inputHeight = inputTensorInfo.GetShape()[dataLayoutIndexed.GetHeightIndex()];
1359 uint32_t inputWidth = inputTensorInfo.GetShape()[dataLayoutIndexed.GetWidthIndex()];
1360
1361 // Mappings from TensorFlow filter tensors to the ArmNN filter tensors.
Matteo Martincigh747ef822018-12-18 09:26:39 +00001362 // Tensorflow weights come in the format [H, W, I, M].
1363 // ArmNN weights have to be [M, I, H, W].
1364 PermutationVector permutationVector{ 2, 3, 1, 0 }; // [H, W, I, M] -> [M, I, H, W]
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001365
1366 // Swizzle the tensor using the given permutation vector.
1367 const TensorInfo& weightTensorInfo = weightNode->GetTensorInfo();
1368 const TensorInfo weightTensorSwizzledInfo = armnnUtils::Permuted(weightTensorInfo, permutationVector);
1369
1370 // Swizzles the content of the tensor's permanent storage into a local storage.
1371 std::vector<float> weightTensorSwizzledData(weightTensorInfo.GetNumElements());
1372 armnnUtils::Permute(weightTensorSwizzledInfo.GetShape(), permutationVector,
Matteo Martincighd5b9e642019-01-04 18:01:21 +00001373 weightNode->GetStorage(), weightTensorSwizzledData.data(), sizeof(float));
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001374
1375 // Create a weight tensor with the newly swizzled data.
1376 ConstTensor weightTensor(weightTensorSwizzledInfo, weightTensorSwizzledData);
1377
Matteo Martincigh747ef822018-12-18 09:26:39 +00001378 uint32_t weightHeight = weightTensor.GetShape()[2];
1379 uint32_t weightWidth = weightTensor.GetShape()[3];
surmeh01bceff2f2018-03-29 16:29:27 +01001380
1381 bool padding = false;
1382 TensorInfo outputInfo;
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001383 unsigned int outputHeight = 0;
1384 unsigned int outputWidth = 0;
telsoa01c577f2c2018-08-31 09:22:23 +01001385
1386 CHECK_PADDING_TYPE(nodeDef, paddingString);
1387
surmeh01bceff2f2018-03-29 16:29:27 +01001388 if (paddingString == "SAME")
1389 {
1390 padding = true;
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001391
1392 outputHeight = static_cast<uint32_t>(ceil(static_cast<float>(inputHeight) /
1393 static_cast<float>(desc.m_StrideY)));
1394 outputWidth = static_cast<uint32_t>(ceil(static_cast<float>(inputWidth) /
1395 static_cast<float>(desc.m_StrideX)));
surmeh01bceff2f2018-03-29 16:29:27 +01001396 }
1397 else if (paddingString == "VALID")
1398 {
1399 padding = false;
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001400
1401 outputHeight = static_cast<uint32_t>(ceil(static_cast<float>(inputHeight - weightHeight + 1) /
1402 static_cast<float>(desc.m_StrideY)));
1403 outputWidth = static_cast<uint32_t>(ceil(static_cast<float>(inputWidth - weightWidth + 1) /
1404 static_cast<float>(desc.m_StrideX)));
1405 }
1406
1407 switch (dataLayout)
1408 {
1409 case DataLayout::NHWC:
1410 outputInfo = TensorInfo({ inputTensorInfo.GetShape()[0],
1411 outputHeight,
1412 outputWidth,
Matteo Martincigh747ef822018-12-18 09:26:39 +00001413 weightTensor.GetShape()[0] * weightTensor.GetShape()[1]},
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001414 DataType::Float32);
1415 break;
1416 case DataLayout::NCHW:
1417 default:
1418 outputInfo = TensorInfo({ inputTensorInfo.GetShape()[0],
1419 weightTensor.GetShape()[0] * weightTensor.GetShape()[1],
1420 outputHeight,
1421 outputWidth },
1422 DataType::Float32);
1423 break;
surmeh01bceff2f2018-03-29 16:29:27 +01001424 }
surmeh01bceff2f2018-03-29 16:29:27 +01001425
1426 CalcPadding(inputHeight, weightHeight, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, padding);
1427 CalcPadding(inputWidth, weightWidth, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, padding);
1428
1429 IConnectableLayer* layer = m_Network->AddDepthwiseConvolution2dLayer(desc, weightTensor, nodeDef.name().c_str());
1430 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001431 inputSlot.Connect(layer->GetInputSlot(0));
surmeh01bceff2f2018-03-29 16:29:27 +01001432
1433 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
1434}
1435
Conor Kennedyc2130a02018-12-05 11:05:54 +00001436TensorInfo OutputShapeOfExpandDims(const tensorflow::NodeDef& nodeDef, TensorInfo inputTensorInfo)
1437{
1438 BOOST_ASSERT(nodeDef.op() == "ExpandDims");
1439
1440 if (inputTensorInfo.GetNumDimensions() > 4) {
1441 throw ParseException(
1442 boost::str(
1443 boost::format(
1444 "Unsupported number of dimensions: %1% for input shape for ExpandDims %2% %3%")
1445 % inputTensorInfo.GetNumDimensions()
1446 % nodeDef.name()
1447 % CHECK_LOCATION().AsString()));
1448 }
1449
1450 std::int32_t expandDim = ReadMandatoryNodeInt32Attribute(nodeDef, "Tdim");
1451
1452 std::int32_t inputDimSize = boost::numeric_cast<int32_t>(inputTensorInfo.GetNumDimensions());
1453 std::vector<uint32_t> outputDims;
1454
1455 // expandDim operation requires: -1-input.dims() <= dim <= input.dims()
1456 if (expandDim >= -1 - inputDimSize && expandDim <= inputDimSize)
1457 {
1458 // add current input shape to outputDims
1459 for (unsigned int i = 0; i < inputTensorInfo.GetNumDimensions(); ++i) {
1460 auto currentDimension = inputTensorInfo.GetShape()[i];
1461 outputDims.push_back(currentDimension);
1462 }
1463
1464 // insert a dimension of 1 at index 'expandDim' of inputs shape
1465 if (expandDim >= 0)
1466 {
1467 auto getPosition = std::next(outputDims.begin() + 0, expandDim);
1468 outputDims.insert(getPosition, 1);
1469 }
1470
1471 // if negative number for 'expandDim' then count backwards from the last element
1472 // and insert 1 dimension at index 'expandDim'
1473 if (expandDim < 0)
1474 {
Matteo Martincighd7cceeb2018-12-06 09:06:29 +00001475 int outputDimSize = boost::numeric_cast<int>(outputDims.size() + 1);
Conor Kennedyc2130a02018-12-05 11:05:54 +00001476 auto getPosition = std::next(outputDims.begin() + outputDimSize, expandDim);
1477 outputDims.insert(getPosition, 1);
1478 }
1479 }
1480 else
1481 {
1482 throw InvalidArgumentException(
1483 boost::str(
1484 boost::format(
1485 "Cannot expand dimension %1% in input tensor with %2% dimension %3%")
1486 % expandDim
1487 % inputDimSize
1488 % CHECK_LOCATION().AsString()));
1489 }
1490
1491 if (outputDims.size() > 4)
1492 {
1493 throw ParseException(
1494 boost::str(
1495 boost::format(
1496 "Unsupported number of dimensions: %1% for output shape for ExpandDims %2% %3%")
1497 % outputDims.size()
1498 % nodeDef.name()
1499 % CHECK_LOCATION().AsString()));
1500 }
1501
1502 TensorShape outShape = TensorShape(static_cast<unsigned int>(outputDims.size()),
1503 outputDims.data());
1504
1505 TensorInfo outTensorInfo = inputTensorInfo;
1506 outTensorInfo.SetShape(outShape);
1507
1508 return outTensorInfo;
1509}
1510
1511ParsedTfOperationPtr TfParser::ParseExpandDims(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
1512{
1513 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
1514
1515 IOutputSlot& prevLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1516 TensorInfo inputTensorInfo = prevLayerOutputSlot.GetTensorInfo();
1517
1518 TensorInfo outputInfo;
1519 outputInfo = OutputShapeOfExpandDims(nodeDef, inputTensorInfo);
1520
1521 ReshapeDescriptor reshapeDesc;
1522 reshapeDesc.m_TargetShape = outputInfo.GetShape();
1523 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, nodeDef.name().c_str());
1524 prevLayerOutputSlot.Connect(layer->GetInputSlot(0));
1525 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
1526
1527 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
1528}
1529
surmeh01bceff2f2018-03-29 16:29:27 +01001530ParsedTfOperationPtr TfParser::ParseFusedBatchNorm(const tensorflow::NodeDef& nodeDef,
1531 const tensorflow::GraphDef& graphDef)
1532{
1533 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 5);
1534
1535 if (!HasParsedConstTensor<float>(inputs[1].m_IndexedValue->GetNode().name()))
1536 {
telsoa01c577f2c2018-08-31 09:22:23 +01001537 throw ParseException(
1538 boost::str(
1539 boost::format(
1540 "ArmNN only supports FusedBatchNormalization layers with constant scale. "
1541 "Input %1%. Node %2% %3%")
1542 % inputs[1].m_IndexedValue->GetNode().name()
1543 % nodeDef.name()
1544 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001545 }
1546 ParsedConstTfOperation<float>* scaleNode =
1547 boost::polymorphic_downcast<ParsedConstTfOperation<float> *>(inputs[1].m_IndexedValue);
1548
1549 if (!HasParsedConstTensor<float>(inputs[2].m_IndexedValue->GetNode().name()))
1550 {
telsoa01c577f2c2018-08-31 09:22:23 +01001551 throw ParseException(
1552 boost::str(
1553 boost::format(
1554 "ArmNN only supports FusedBatchNormalization layers with constant offset. "
1555 "Input %1%. Node %2% %3%")
1556 % inputs[2].m_IndexedValue->GetNode().name()
1557 % nodeDef.name()
1558 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001559 }
1560 ParsedConstTfOperation<float>* offsetNode =
1561 boost::polymorphic_downcast<ParsedConstTfOperation<float> *>(inputs[2].m_IndexedValue);
1562
1563 if (!HasParsedConstTensor<float>(inputs[3].m_IndexedValue->GetNode().name()))
1564 {
telsoa01c577f2c2018-08-31 09:22:23 +01001565 throw ParseException(
1566 boost::str(
1567 boost::format(
1568 "ArmNN only supports FusedBatchNormalization layers with constant mean. "
1569 "Input %1%. Node %2% %3%")
1570 % inputs[3].m_IndexedValue->GetNode().name()
1571 % nodeDef.name()
1572 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001573 }
1574 ParsedConstTfOperation<float>* meanNode =
1575 boost::polymorphic_downcast<ParsedConstTfOperation<float> *>(inputs[3].m_IndexedValue);
1576
1577 if (!HasParsedConstTensor<float>(inputs[4].m_IndexedValue->GetNode().name()))
1578 {
telsoa01c577f2c2018-08-31 09:22:23 +01001579 throw ParseException(
1580 boost::str(
1581 boost::format(
1582 "ArmNN only supports FusedBatchNormalization layers with constant variance. "
1583 "Input %1%. Node %2% %3%")
1584 % inputs[4].m_IndexedValue->GetNode().name()
1585 % nodeDef.name()
1586 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001587 }
1588 ParsedConstTfOperation<float>* varianceNode =
1589 boost::polymorphic_downcast<ParsedConstTfOperation<float> *>(inputs[4].m_IndexedValue);
1590
Matteo Martincigh075c7502018-12-05 13:10:45 +00001591 const std::string dataFormat = ReadMandatoryNodeStringAttribute(nodeDef, "data_format");
1592
1593 CHECK_DATA_FORMAT(nodeDef, dataFormat, "FusedBatchNorm");
1594
telsoa01c577f2c2018-08-31 09:22:23 +01001595 // The descriptor only has the epsilon attribute.
surmeh01bceff2f2018-03-29 16:29:27 +01001596 BatchNormalizationDescriptor desc;
1597 desc.m_Eps = ReadMandatoryNodeFloatAttribute(nodeDef, "epsilon");
Matteo Martincigh075c7502018-12-05 13:10:45 +00001598 desc.m_DataLayout = dataFormat == "NHWC" ? DataLayout::NHWC : DataLayout::NCHW;
surmeh01bceff2f2018-03-29 16:29:27 +01001599
telsoa01c577f2c2018-08-31 09:22:23 +01001600 // Data for the parsed tensor args (scale, offset, mean, variance) must be stored
1601 // locally until the layer is added.
surmeh01bceff2f2018-03-29 16:29:27 +01001602 std::vector<float> scaleTensorData;
Matteo Martincigh482ca852018-12-12 09:20:55 +00001603 ConstTensor scaleTensor = scaleNode->GetConstTensor(scaleTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +01001604
1605 std::vector<float> offsetTensorData;
Matteo Martincigh482ca852018-12-12 09:20:55 +00001606 ConstTensor offsetTensor = offsetNode->GetConstTensor(offsetTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +01001607
1608 std::vector<float> meanTensorData;
Matteo Martincigh482ca852018-12-12 09:20:55 +00001609 ConstTensor meanTensor = meanNode->GetConstTensor(meanTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +01001610
1611 std::vector<float> varianceTensorData;
Matteo Martincigh482ca852018-12-12 09:20:55 +00001612 ConstTensor varianceTensor = varianceNode->GetConstTensor(varianceTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +01001613
1614 IConnectableLayer* layer = m_Network->AddBatchNormalizationLayer(desc,
1615 meanTensor,
1616 varianceTensor,
1617 offsetTensor,
1618 scaleTensor,
1619 nodeDef.name().c_str());
1620
1621 IOutputSlot& inputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1622
Matteo Martincigh075c7502018-12-05 13:10:45 +00001623 layer->GetOutputSlot(0).SetTensorInfo(inputSlot.GetTensorInfo());
1624 inputSlot.Connect(layer->GetInputSlot(0));
surmeh01bceff2f2018-03-29 16:29:27 +01001625
1626 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
1627}
1628
telsoa01c577f2c2018-08-31 09:22:23 +01001629bool TfParser::IsSupportedLeakyReluPattern(const tensorflow::NodeDef& mulNodeDef,
1630 size_t alphaLayerIndex,
1631 const OutputOfParsedTfOperation& otherOp,
1632 armnn::IOutputSlot** outputOfLeakyRelu,
1633 armnn::ActivationDescriptor & desc)
1634{
1635 const tensorflow::NodeDef& otherNodeDef = otherOp.m_IndexedValue->GetNode();
1636
1637 // Verifying all these assumptions hold:
1638 //
1639 // 1, the mulNodeDef is an elementwise multiplication node "Mul"
1640 // 2, the alphaLayerIndex selects a constant node from the inputs of the "Mul" node
1641 // 3, the inputLayerIndex selects a layer which has the same name as otherNodeDef
1642 //
1643
1644 if (mulNodeDef.op() == "Mul")
1645 {
1646 size_t otherLayerIndex = (alphaLayerIndex == 0 ? 1 : 0);
1647 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(mulNodeDef, 2);
1648
1649 BOOST_ASSERT(inputs.size() == 2);
1650 BOOST_ASSERT((otherLayerIndex == 0 || alphaLayerIndex == 0));
1651 BOOST_ASSERT((otherLayerIndex == 1 || alphaLayerIndex == 1));
1652 BOOST_ASSERT(((otherLayerIndex + alphaLayerIndex) == 1));
1653
1654 if (inputs[otherLayerIndex].m_IndexedValue->GetNode().name() == otherNodeDef.name())
1655 {
1656 if (HasParsedConstTensor<float>(inputs[alphaLayerIndex].m_IndexedValue->GetNode().name()))
1657 {
1658 ParsedConstTfOperation<float>* alpha =
1659 boost::polymorphic_downcast<ParsedConstTfOperation<float> *>(
1660 inputs[alphaLayerIndex].m_IndexedValue);
1661
1662 std::vector<float> const_data;
Matteo Martincigh482ca852018-12-12 09:20:55 +00001663 ConstTensor const_tensor = alpha->GetConstTensor(const_data);
telsoa01c577f2c2018-08-31 09:22:23 +01001664
1665 if (const_data.size() == 1)
1666 {
1667 desc.m_Function = ActivationFunction::LeakyReLu;
1668 desc.m_A = const_data[0];
1669
1670 *outputOfLeakyRelu = &(otherOp.m_IndexedValue->ResolveArmnnOutputSlot(otherOp.m_Index));
1671 return true;
1672 }
1673 }
1674 }
1675 }
1676 return false;
1677}
1678
telsoa01c577f2c2018-08-31 09:22:23 +01001679ParsedTfOperationPtr TfParser::ParseMaximum(const tensorflow::NodeDef& nodeDef,
1680 const tensorflow::GraphDef& graphDef)
1681{
1682 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
Sadik Armagan975c09a2018-12-04 10:02:08 +00001683 if (inputs.size() != 2)
1684 {
1685 throw ParseException(
1686 boost::str(
1687 boost::format(
1688 "Maximum expects two inputs!. Got %1% for Node %2% %3%")
1689 % inputs.size()
1690 % nodeDef.name()
1691 % CHECK_LOCATION().AsString()));
1692 }
1693
telsoa01c577f2c2018-08-31 09:22:23 +01001694 auto inputNode0 = inputs[0].m_IndexedValue->GetNode();
1695 auto inputNode1 = inputs[1].m_IndexedValue->GetNode();
1696 IOutputSlot* outputOfLeakyRelu = nullptr;
1697
1698 ActivationDescriptor desc;
1699
Sadik Armagan975c09a2018-12-04 10:02:08 +00001700 // A max node may be part of a LeakyRelu, with one input as a multiplication with a scalar constant,
1701 // i.e. one of the four possible scenarios:
1702 // 1, max(mul(a, x), x)
1703 // 2, max(mul(x, a), x)
1704 // 3, max(x, mul(a, x))
1705 // 4, max(x, mul(x, a))
1706 // These are handled by an activation layer.
telsoa01c577f2c2018-08-31 09:22:23 +01001707
1708 if (IsSupportedLeakyReluPattern(inputNode0, 0, inputs[1], &outputOfLeakyRelu, desc) ||
1709 IsSupportedLeakyReluPattern(inputNode0, 1, inputs[1], &outputOfLeakyRelu, desc) ||
1710 IsSupportedLeakyReluPattern(inputNode1, 0, inputs[0], &outputOfLeakyRelu, desc) ||
1711 IsSupportedLeakyReluPattern(inputNode1, 1, inputs[0], &outputOfLeakyRelu, desc))
1712 {
1713 BOOST_ASSERT(outputOfLeakyRelu != nullptr);
1714
1715 IConnectableLayer* const layer = m_Network->AddActivationLayer(desc, nodeDef.name().c_str());
1716 outputOfLeakyRelu->Connect(layer->GetInputSlot(0));
1717 layer->GetOutputSlot(0).SetTensorInfo(outputOfLeakyRelu->GetTensorInfo());
1718 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
1719 }
1720 else
1721 {
Sadik Armagan975c09a2018-12-04 10:02:08 +00001722 // Anything else is just a maximum layer.
1723
1724 return AddMaximumLayer(nodeDef);
telsoa01c577f2c2018-08-31 09:22:23 +01001725 }
1726}
1727
jimfly0184c70e62018-12-19 13:14:46 +00001728std::pair<armnn::IOutputSlot*, armnn::IOutputSlot*> TfParser::ProcessElementwiseInputSlots(
1729 const tensorflow::NodeDef& nodeDef, const std::string& layerName)
Nattapat Chaimanowong24df8222018-12-04 13:47:02 +00001730{
1731 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
1732
1733 IOutputSlot* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1734 IOutputSlot* input1Slot = &inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
1735 const unsigned int input0Dim = input0Slot->GetTensorInfo().GetNumDimensions();
1736 const unsigned int input1Dim = input1Slot->GetTensorInfo().GetNumDimensions();
1737
1738 if (input0Dim != input1Dim)
1739 {
1740 // broadcasting where input0 and input1 have different number of dimensions
1741 // is only supported for 1D and 4D tensors pair
1742 if (input0Dim == 1 && input1Dim == 4)
1743 {
1744 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot, true, *m_Network, nodeDef);
1745 }
1746 else if (input0Dim == 4 && input1Dim == 1)
1747 {
1748 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, true, *m_Network, nodeDef);
1749 }
1750 else
1751 {
1752 throw ParseException(
jimfly0184c70e62018-12-19 13:14:46 +00001753 boost::str(
1754 boost::format("Unsupported broadcast configuration for %1% operation %2% %3%")
1755 % layerName
1756 % nodeDef.name()
1757 % CHECK_LOCATION().AsString()));
Nattapat Chaimanowong24df8222018-12-04 13:47:02 +00001758 }
1759 }
jimfly0184c70e62018-12-19 13:14:46 +00001760 return {input0Slot, input1Slot};
1761}
Nattapat Chaimanowong24df8222018-12-04 13:47:02 +00001762
kevmay012b4d88e2019-01-24 14:05:09 +00001763ParsedTfOperationPtr TfParser::ProcessComparisonLayer(
1764 IOutputSlot* input0Slot,
1765 IOutputSlot* input1Slot,
1766 IConnectableLayer* const layer,
1767 const tensorflow::NodeDef& nodeDef)
1768{
1769 input0Slot->Connect(layer->GetInputSlot(0));
1770 input1Slot->Connect(layer->GetInputSlot(1));
1771
1772 TensorInfo outputInfo = input0Slot->GetTensorInfo();
1773 outputInfo.SetDataType(DataType::Boolean);
1774 std::vector<unsigned int> outputShape;
1775
1776 const TensorShape& input0Shape = input0Slot->GetTensorInfo().GetShape();
1777 const TensorShape& input1Shape = input1Slot->GetTensorInfo().GetShape();
1778
1779 for (unsigned int i = 0; i < input0Shape.GetNumDimensions(); i++)
1780 {
1781 outputShape.push_back(std::max(input0Shape[i], input1Shape[i]));
1782 }
1783
1784 outputInfo.SetShape(TensorShape(input0Shape.GetNumDimensions(), outputShape.data()));
1785 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
1786
1787 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
1788}
1789
jimfly0184c70e62018-12-19 13:14:46 +00001790ParsedTfOperationPtr TfParser::ProcessElementwiseLayer(
1791 IOutputSlot* input0Slot,
1792 IOutputSlot* input1Slot,
1793 IConnectableLayer* const layer,
1794 const tensorflow::NodeDef& nodeDef)
1795{
Nattapat Chaimanowong24df8222018-12-04 13:47:02 +00001796 input0Slot->Connect(layer->GetInputSlot(0));
1797 input1Slot->Connect(layer->GetInputSlot(1));
1798
1799 TensorInfo outputInfo = input0Slot->GetTensorInfo();
1800 std::vector<unsigned int> outputShape;
1801
1802 const TensorShape& input0Shape = input0Slot->GetTensorInfo().GetShape();
1803 const TensorShape& input1Shape = input1Slot->GetTensorInfo().GetShape();
1804
1805 for (unsigned int i = 0; i < input0Shape.GetNumDimensions(); i++)
1806 {
1807 outputShape.push_back(std::max(input0Shape[i], input1Shape[i]));
1808 }
1809
1810 outputInfo.SetShape(TensorShape(input0Shape.GetNumDimensions(), outputShape.data()));
1811 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
1812
1813 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
1814}
1815
FrancisMurtagh94412af2019-01-24 10:53:39 +00001816ParsedTfOperationPtr TfParser::ParseGather(const tensorflow::NodeDef& nodeDef,
1817 const tensorflow::GraphDef& graphDef)
1818{
1819 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
1820 IOutputSlot& params = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1821 IOutputSlot& indices = inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
1822
1823 // Infer shape of output tensor
1824 unsigned int paramsDim = params.GetTensorInfo().GetNumDimensions();
1825 unsigned int indicesDim = indices.GetTensorInfo().GetNumDimensions();
1826 unsigned int outputDim = paramsDim - 1 + indicesDim;
1827
1828 std::vector<unsigned int> dimSizes;
1829
1830 for (unsigned int i = 0; i < indicesDim; ++i)
1831 {
1832 dimSizes.push_back(indices.GetTensorInfo().GetShape()[i]);
1833 }
1834 for (unsigned int i = 1; i < paramsDim; ++i)
1835 {
1836 dimSizes.push_back(params.GetTensorInfo().GetShape()[i]);
1837 }
1838
1839 const TensorShape& inferredShape = TensorShape(outputDim, dimSizes.data());
1840
1841 const TensorInfo inferredOutputInfo(inferredShape, params.GetTensorInfo().GetDataType());
1842
1843 IConnectableLayer* const layer = m_Network->AddGatherLayer(nodeDef.name().c_str());
1844 layer->GetOutputSlot(0).SetTensorInfo(inferredOutputInfo);
1845
1846 params.Connect(layer->GetInputSlot(0));
1847 indices.Connect(layer->GetInputSlot(1));
1848
1849 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
1850}
1851
jimfly01a06bf312018-12-18 16:24:51 +00001852ParsedTfOperationPtr TfParser::ParseGreater(const tensorflow::NodeDef& nodeDef,
1853 const tensorflow::GraphDef& graphDef)
1854{
1855 std::pair<armnn::IOutputSlot*, armnn::IOutputSlot*> inputLayers = ProcessElementwiseInputSlots(nodeDef, "Greater");
1856 IOutputSlot* input0Slot = inputLayers.first;
1857 IOutputSlot* input1Slot = inputLayers.second;
1858
1859 IConnectableLayer* const layer = m_Network->AddGreaterLayer(nodeDef.name().c_str());
1860
kevmay012b4d88e2019-01-24 14:05:09 +00001861 return ProcessComparisonLayer(input0Slot, input1Slot, layer, nodeDef);
jimfly01a06bf312018-12-18 16:24:51 +00001862}
1863
jimfly0184c70e62018-12-19 13:14:46 +00001864ParsedTfOperationPtr TfParser::ParseEqual(const tensorflow::NodeDef& nodeDef,
1865 const tensorflow::GraphDef& graphDef)
1866{
1867 std::pair<armnn::IOutputSlot*, armnn::IOutputSlot*> inputLayers = ProcessElementwiseInputSlots(nodeDef, "Equal");
1868 IOutputSlot* input0Slot = inputLayers.first;
1869 IOutputSlot* input1Slot = inputLayers.second;
1870
1871 IConnectableLayer* const layer = m_Network->AddEqualLayer(nodeDef.name().c_str());
1872
kevmay012b4d88e2019-01-24 14:05:09 +00001873 return ProcessComparisonLayer(input0Slot, input1Slot, layer, nodeDef);
jimfly0184c70e62018-12-19 13:14:46 +00001874}
1875
1876ParsedTfOperationPtr TfParser::ParseMinimum(const tensorflow::NodeDef& nodeDef,
1877 const tensorflow::GraphDef& graphDef)
1878{
1879 std::pair<armnn::IOutputSlot*, armnn::IOutputSlot*> inputLayers = ProcessElementwiseInputSlots(nodeDef, "Minimum");
1880 IOutputSlot* input0Slot = inputLayers.first;
1881 IOutputSlot* input1Slot = inputLayers.second;
1882
1883 IConnectableLayer* const layer = m_Network->AddMinimumLayer(nodeDef.name().c_str());
1884
1885 return ProcessElementwiseLayer(input0Slot, input1Slot, layer, nodeDef);
1886}
1887
jimfly0123be07e2018-12-04 17:47:22 +00001888ParsedTfOperationPtr TfParser::ParseSub(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
1889{
1890 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
1891
1892 IOutputSlot* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1893 IOutputSlot* input1Slot = &inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
1894
1895 const TensorInfo& input0Info = input0Slot->GetTensorInfo();
1896 const TensorInfo& input1Info = input1Slot->GetTensorInfo();
1897
1898 if (input0Info.GetNumDimensions() == 1)
1899 {
1900 const bool isNHWC = true;
1901 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot, isNHWC, *m_Network, nodeDef);
1902 }
1903
1904 if (input1Info.GetNumDimensions() == 1)
1905 {
1906 const bool isNHWC = true;
1907 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, isNHWC, *m_Network, nodeDef);
1908 }
1909
1910 IConnectableLayer* const layer = m_Network->AddSubtractionLayer(nodeDef.name().c_str());
1911
1912 input0Slot->Connect(layer->GetInputSlot(0));
1913 input1Slot->Connect(layer->GetInputSlot(1));
1914
1915 if (input0Info.GetNumDimensions() == 1)
1916 {
1917 layer->GetOutputSlot(0).SetTensorInfo(input1Slot->GetTensorInfo());
1918 }
1919 else
1920 {
1921 layer->GetOutputSlot(0).SetTensorInfo(input0Slot->GetTensorInfo());
1922 }
1923
1924 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
1925}
1926
jimfly01f6ba7472018-12-04 10:09:52 +00001927unsigned int CheckPaddingTensor(const ConstTensor& paddingTensor,
1928 const TensorInfo& inputTensorInfo,
1929 const std::string& nodeName)
1930{
1931 unsigned int rank = paddingTensor.GetShape()[0];
1932 unsigned int expectedRank = inputTensorInfo.GetNumDimensions();
1933 if (rank != expectedRank)
1934 {
1935 throw ParseException(
1936 boost::str(
1937 boost::format(
1938 "Expected the padding tensor to be of rank %1 not %2 on Node %3 %4.")
1939 % expectedRank
1940 % rank
1941 % nodeName
1942 % CHECK_LOCATION().AsString()));
1943 }
1944 unsigned int second = paddingTensor.GetShape()[1];
1945 if (second != 2)
1946 {
1947 throw ParseException(
1948 boost::str(
1949 boost::format(
1950 "Expected the padding tensor to be of dimensions [%1, 2] not [%1, %2] on Node %3 %4.")
1951 % rank
1952 % second
1953 % nodeName
1954 % CHECK_LOCATION().AsString()));
1955 }
1956 return rank;
1957}
1958
1959TensorInfo CalculatePaddedOutputTensorInfo(const TensorInfo& inputTensorInfo,
1960 const std::vector<std::pair<unsigned int, unsigned int>>& padList)
1961{
1962 unsigned int numDims = inputTensorInfo.GetNumDimensions();
1963 std::vector<unsigned int> outDims;
1964 for (unsigned int i = 0; i < numDims; ++i)
1965 {
1966 unsigned int dimSize = inputTensorInfo.GetShape()[i];
1967 const std::pair<unsigned int, unsigned int>& dimPadding = padList[i];
1968 dimSize += dimPadding.first;
1969 dimSize += dimPadding.second;
1970 outDims.push_back(dimSize);
1971 }
1972 TensorInfo paddedTensorInfo = inputTensorInfo;
1973 unsigned int outDimsSize = static_cast<unsigned int>(outDims.size());
1974 paddedTensorInfo.SetShape(TensorShape{ outDimsSize, outDims.data() });
1975 return paddedTensorInfo;
1976}
1977
1978ParsedTfOperationPtr TfParser::ParsePad(const tensorflow::NodeDef& nodeDef,
1979 const tensorflow::GraphDef& graphDef)
1980{
1981 // input consists of:
1982 // input[0] the tensor which will be padded
1983 // input[1] the tensor holding the padding values
1984 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
1985 IOutputSlot& previousLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1986 TensorInfo inputTensorInfo = previousLayerOutputSlot.GetTensorInfo();
1987 if (!HasParsedConstTensor<int32_t>(inputs[1].m_IndexedValue))
1988 {
1989 throw ParseException(
1990 boost::str(
1991 boost::format(
1992 "ArmNN only supports Pad with constant padding. "
1993 "Input %1%. Node %2% %3%")
1994 % inputs[1].m_IndexedValue->GetNode().name()
1995 % nodeDef.name()
1996 % CHECK_LOCATION().AsString()));
1997
1998 }
1999 ParsedConstTfOperation<int32_t>* paddingTensorOp =
2000 boost::polymorphic_downcast<ParsedConstTfOperation<int32_t>*>(inputs[1].m_IndexedValue);
2001
2002 std::vector<int32_t> paddingTensorData;
Matteo Martincigh482ca852018-12-12 09:20:55 +00002003 ConstTensor paddingTensor = paddingTensorOp->GetConstTensor(paddingTensorData);
jimfly01f6ba7472018-12-04 10:09:52 +00002004 // paddings is an integer tensor with shape [n, 2], where n is the rank of tensor
2005 // and should match the rank of the input tensor that is being padded.
2006 // For each dimension D of input, paddings[D, 0] indicates how many values to add
2007 // before the contents of tensor in that dimension, and paddings[D, 1] indicates how
2008 // many values to add after the contents of tensor in that dimension
2009 // This needs to be translated into a padList for ACL
2010 std::vector<std::pair<unsigned int, unsigned int>> padList;
2011 unsigned int rank = CheckPaddingTensor(paddingTensor, inputTensorInfo, nodeDef.name());
2012 for (unsigned int i = 0; i < rank; ++i)
2013 {
2014 std::pair<unsigned int, unsigned int> paddingForDim;
2015 for (unsigned int j = 0; j < 2; j++)
2016 {
2017 unsigned int index = (i * 2) + j;
2018 int paddingAmount = paddingTensorData[index];
2019 // make sure we can cast to an unsigned value
2020 if (paddingAmount < 0)
2021 {
2022 throw ParseException(
2023 boost::str(
2024 boost::format(
2025 "Negative amount %1 specified at [%2, %3] of padding tensor on Node %4 %5.")
2026 % paddingAmount
2027 % i
2028 % j
2029 % nodeDef.name()
2030 % CHECK_LOCATION().AsString()));
2031 }
2032 if (j == 0)
2033 {
2034 paddingForDim.first = static_cast<unsigned int>(paddingAmount);
2035 }
2036 else
2037 {
2038 paddingForDim.second = static_cast<unsigned int>(paddingAmount);
2039 }
2040 }
2041 padList.push_back(paddingForDim);
2042 }
2043 PadDescriptor padDescriptor(padList);
2044 IConnectableLayer* layer = m_Network->AddPadLayer(padDescriptor, nodeDef.name().c_str());
2045 previousLayerOutputSlot.Connect(layer->GetInputSlot(0));
2046 // Use the padding to calculate the new output tensor shape
2047 TensorInfo outputTensorInfo = CalculatePaddedOutputTensorInfo(inputTensorInfo, padList);
2048 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2049 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2050}
2051
surmeh01bceff2f2018-03-29 16:29:27 +01002052ParsedTfOperationPtr TfParser::ParseConcat(const tensorflow::NodeDef& nodeDef,
2053 const tensorflow::GraphDef& graphDef)
2054{
2055 std::vector<OutputOfConstNodeDef> nodes = GetTfInputNodes(nodeDef);
Matteo Martincighf9afc792018-12-06 12:03:17 +00002056
telsoa01c577f2c2018-08-31 09:22:23 +01002057 // In tensorflow, we have the last input of the Concat layer as the axis for concatenation.
surmeh01bceff2f2018-03-29 16:29:27 +01002058 unsigned int numInputs = static_cast<unsigned int>(nodes.size());
surmeh01bceff2f2018-03-29 16:29:27 +01002059
surmeh01bceff2f2018-03-29 16:29:27 +01002060 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, numInputs);
2061
Saoirse Stewart91c0eff2019-02-27 11:07:57 +00002062 // Constant tensor index
2063 unsigned int index = GetConstInputIndex(inputs);
Matteo Martincighf9afc792018-12-06 12:03:17 +00002064 // Get the axis tensor data
Saoirse Stewart91c0eff2019-02-27 11:07:57 +00002065 ParsedConstTfOperation<int32_t>* shapeNode =
2066 boost::polymorphic_downcast<ParsedConstTfOperation<int32_t>*>(inputs[index].m_IndexedValue);
2067
surmeh01bceff2f2018-03-29 16:29:27 +01002068 std::vector<int32_t> axisTensorData;
Matteo Martincigh482ca852018-12-12 09:20:55 +00002069 shapeNode->GetConstTensor(axisTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +01002070
telsoa01c577f2c2018-08-31 09:22:23 +01002071 // This concatDim indicates the data format: 3 is the NHWC, 1 is the NCHW.
Matteo Martincighf9afc792018-12-06 12:03:17 +00002072 const unsigned int concatDim = static_cast<unsigned int>(axisTensorData[0]);
surmeh01bceff2f2018-03-29 16:29:27 +01002073
telsoa01c577f2c2018-08-31 09:22:23 +01002074 // Armnn supports concatenation along the channel dimension for data formats NHWC and NCHW.
Matteo Martincighf9afc792018-12-06 12:03:17 +00002075 if (concatDim == 0 || concatDim == 2)
surmeh01bceff2f2018-03-29 16:29:27 +01002076 {
telsoa01c577f2c2018-08-31 09:22:23 +01002077 throw ParseException(
Saoirse Stewart91c0eff2019-02-27 11:07:57 +00002078 boost::str(
2079 boost::format(
telsoa01c577f2c2018-08-31 09:22:23 +01002080 "Dimension %1% for concatenation is not supported by Armnn. "
2081 "Node %2% %3%")
Saoirse Stewart91c0eff2019-02-27 11:07:57 +00002082 % concatDim
2083 % nodeDef.name()
2084 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002085 }
2086
Matteo Martincighf9afc792018-12-06 12:03:17 +00002087 unsigned int numConcatViews = numInputs - 1;
2088 OriginsDescriptor concatDescriptor(static_cast<uint32_t>(numConcatViews), MaxNumOfTensorDimensions);
2089 concatDescriptor.SetConcatAxis(concatDim);
2090 TensorShape mergeDims(MaxNumOfTensorDimensions);
2091 unsigned int mergeDim = 0;
2092 for (unsigned int viewIndex = 0; viewIndex < numConcatViews; ++viewIndex)
surmeh01bceff2f2018-03-29 16:29:27 +01002093 {
telsoa01c577f2c2018-08-31 09:22:23 +01002094 // Need to double check whether it should be
Matteo Martincighf9afc792018-12-06 12:03:17 +00002095 IOutputSlot& inputSlot = inputs[viewIndex].m_IndexedValue->ResolveArmnnOutputSlot(inputs[viewIndex].m_Index);
surmeh01bceff2f2018-03-29 16:29:27 +01002096 TensorInfo inputTensorInfo = inputSlot.GetTensorInfo();
2097
Matteo Martincighf9afc792018-12-06 12:03:17 +00002098 // Double check dimensions of the tensors
2099 if (inputTensorInfo.GetNumDimensions() != MaxNumOfTensorDimensions)
2100 {
2101 throw armnn::ParseException(
Saoirse Stewart91c0eff2019-02-27 11:07:57 +00002102 boost::str(
2103 boost::format(
Matteo Martincighf9afc792018-12-06 12:03:17 +00002104 "The number of dimensions: %1% for input tensors of the "
2105 "concatenation op should be %2% %3%")
Saoirse Stewart91c0eff2019-02-27 11:07:57 +00002106 % inputTensorInfo.GetNumDimensions()
2107 % MaxNumOfTensorDimensions
2108 % CHECK_LOCATION().AsString()));
Matteo Martincighf9afc792018-12-06 12:03:17 +00002109 }
2110
2111 // Copy the input tensor shape to mergeDimSizes and initialize the view origin coordinates for the current input
2112 mergeDims = inputTensorInfo.GetShape();
2113 unsigned int* viewOrigin = const_cast<unsigned int*>(concatDescriptor.GetViewOrigin(viewIndex));
2114 std::fill(viewOrigin, viewOrigin + MaxNumOfTensorDimensions, 0);
2115
2116 // Update the view origin coordinates and the merge dimension value
2117 concatDescriptor.SetViewOriginCoord(viewIndex, concatDim, mergeDim);
2118 mergeDim += mergeDims[concatDim];
surmeh01bceff2f2018-03-29 16:29:27 +01002119 }
2120
Matteo Martincighf9afc792018-12-06 12:03:17 +00002121 // Update the output shape
2122 mergeDims[concatDim] = mergeDim;
Jim Flynn906f9462019-05-10 13:55:21 +01002123 armnn::IConnectableLayer *layer = m_Network->AddConcatLayer(concatDescriptor, nodeDef.name().c_str());
surmeh01bceff2f2018-03-29 16:29:27 +01002124
Matteo Martincighf9afc792018-12-06 12:03:17 +00002125 layer->GetOutputSlot(0).SetTensorInfo(armnn::TensorInfo(mergeDims, DataType::Float32));
surmeh01bceff2f2018-03-29 16:29:27 +01002126
Matteo Martincighf9afc792018-12-06 12:03:17 +00002127 for (unsigned int viewIndex = 0; viewIndex < numConcatViews; ++viewIndex)
surmeh01bceff2f2018-03-29 16:29:27 +01002128 {
Matteo Martincighf9afc792018-12-06 12:03:17 +00002129 IOutputSlot& inputSlot = inputs[viewIndex].m_IndexedValue->ResolveArmnnOutputSlot(inputs[viewIndex].m_Index);
2130 inputSlot.Connect(layer->GetInputSlot(viewIndex));
surmeh01bceff2f2018-03-29 16:29:27 +01002131 }
2132
2133 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2134}
2135
2136ParsedTfOperationPtr TfParser::ParseShape(const tensorflow::NodeDef& nodeDef,
2137 const tensorflow::GraphDef& graphDef)
2138{
telsoa01c577f2c2018-08-31 09:22:23 +01002139 // Note: the Shape layer is handled in a special way, because:
2140 // 1. ARMNN doesn't support int32 tensors which it outputs.
2141 // 2. ARMNN works with statically shaped tensors which are known at parse time.
surmeh01bceff2f2018-03-29 16:29:27 +01002142 // 3. because of 1. and 2. we treat the output of Shape as a temporary const int32
telsoa01c577f2c2018-08-31 09:22:23 +01002143 // tensor which may be used as an input to other ops, most likely a Reshape.
surmeh01bceff2f2018-03-29 16:29:27 +01002144
2145 const tensorflow::DataType tfDataType = ReadMandatoryNodeTypeAttribute(nodeDef, "out_type");
2146 if (tfDataType != tensorflow::DT_INT32)
2147 {
telsoa01c577f2c2018-08-31 09:22:23 +01002148 throw ParseException(
2149 boost::str(
2150 boost::format(
2151 "Armnn only supports DT_INT32 as out_type. Got %1% for Node %2% %3%")
2152 % tensorflow::DataType_Name(tfDataType)
2153 % nodeDef.name()
2154 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002155 }
2156
2157 const std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2158 IOutputSlot& prevLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2159 const TensorInfo& prevLayerTensorInfo = prevLayerOutputSlot.GetTensorInfo();
2160 unsigned int prevLayerDimensions = prevLayerTensorInfo.GetNumDimensions();
2161
2162 std::vector<int32_t> shapeTensorData;
2163 shapeTensorData.reserve(prevLayerDimensions);
2164
2165 for (unsigned int i=0; i<prevLayerDimensions; ++i)
2166 {
2167 shapeTensorData.push_back(static_cast<int32_t>(prevLayerTensorInfo.GetShape()[i]));
2168 }
2169
2170 TensorInfo shapeTensorInfo(1, &prevLayerDimensions, DataType::Signed32);
2171
2172 return std::make_unique<ParsedConstTfOperation<int32_t>>(this,
2173 nodeDef,
2174 &shapeTensorData[0],
2175 shapeTensorInfo);
2176}
2177
2178ParsedTfOperationPtr TfParser::ParseReshape(const tensorflow::NodeDef& nodeDef,
2179 const tensorflow::GraphDef& graphDef)
2180{
2181 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
2182 ParsedTfOperation* inputNode = inputs[0].m_IndexedValue;
2183
2184 if (!HasParsedConstTensor<int32_t>(inputs[1].m_IndexedValue->GetNode().name()))
2185 {
telsoa01c577f2c2018-08-31 09:22:23 +01002186 throw ParseException(
2187 boost::str(
2188 boost::format(
2189 "ArmNN only supports Reshape layers with constant shapes. "
2190 "Input %1% Node %2% %3%")
2191 % inputs[1].m_IndexedValue->GetNode().name()
2192 % nodeDef.name()
2193 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002194 }
2195 ParsedConstTfOperation<int32_t>* shapeNode =
2196 boost::polymorphic_downcast<ParsedConstTfOperation<int32_t>*>(inputs[1].m_IndexedValue);
2197
2198 armnn::IOutputSlot& prevLayerOutputSlot = inputNode->ResolveArmnnOutputSlot(inputs[0].m_Index);
2199 TensorInfo inputTensorInfo = prevLayerOutputSlot.GetTensorInfo();
2200
2201 std::vector<int32_t> shapeTensorData;
Matteo Martincigh482ca852018-12-12 09:20:55 +00002202 ConstTensor shapeTensor = shapeNode->GetConstTensor(shapeTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +01002203 const TensorInfo outputTensorInfo = PrepareReshape(inputTensorInfo, shapeTensorData);
2204
2205 TensorShape targetShape = outputTensorInfo.GetShape();
2206 ReshapeDescriptor reshapeDesc;
2207 reshapeDesc.m_TargetShape = targetShape;
2208
2209 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, nodeDef.name().c_str());
2210 prevLayerOutputSlot.Connect(layer->GetInputSlot(0));
2211 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2212
2213 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2214}
2215
2216ParsedTfOperationPtr TfParser::ParseResizeBilinear(const tensorflow::NodeDef& nodeDef,
2217 const tensorflow::GraphDef& graphDef)
2218{
2219 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
2220
2221 if (!HasParsedConstTensor<int32_t>(inputs[1].m_IndexedValue->GetNode().name()))
2222 {
telsoa01c577f2c2018-08-31 09:22:23 +01002223 throw ParseException(
2224 boost::str(
2225 boost::format(
2226 "ArmNN only supports ResizeBilinear layers with constant sizes. "
2227 "Input %1%. Node %2% %3%")
2228 % inputs[1].m_IndexedValue->GetNode().name()
2229 % nodeDef.name()
2230 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002231 }
2232 ParsedConstTfOperation<int32_t>* sizeNode =
2233 boost::polymorphic_downcast<ParsedConstTfOperation<int32_t>*>(inputs[1].m_IndexedValue);
2234
telsoa01c577f2c2018-08-31 09:22:23 +01002235 // Checks the align_corners attribute is not set.
surmeh01bceff2f2018-03-29 16:29:27 +01002236 if (ReadOptionalNodeBoolAttribute(nodeDef, "align_corners", false))
2237 {
telsoa01c577f2c2018-08-31 09:22:23 +01002238 throw ParseException(
2239 boost::str(
2240 boost::format(
2241 "ArmNN only supports ResizeBilinear layers with align_corners set to false. "
2242 "Node %1% %2%")
2243 % nodeDef.name()
2244 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002245 }
2246
telsoa01c577f2c2018-08-31 09:22:23 +01002247 // Data for the parsed tensor args (size) must be stored locally.
surmeh01bceff2f2018-03-29 16:29:27 +01002248 std::vector<int32_t> sizeTensorData;
Matteo Martincigh482ca852018-12-12 09:20:55 +00002249 ConstTensor sizeTensor = sizeNode->GetConstTensor(sizeTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +01002250
telsoa01c577f2c2018-08-31 09:22:23 +01002251 // The descriptor only has target height and width attributes, which we get from the size tensor.
surmeh01bceff2f2018-03-29 16:29:27 +01002252 ResizeBilinearDescriptor desc;
2253 desc.m_TargetHeight = static_cast<uint32_t> (sizeTensorData[0]);
2254 desc.m_TargetWidth = static_cast<uint32_t> (sizeTensorData[1]);
jimfly018a121502018-12-06 16:19:52 +00002255 desc.m_DataLayout = armnn::DataLayout::NHWC;
surmeh01bceff2f2018-03-29 16:29:27 +01002256
2257 IConnectableLayer* layer = m_Network->AddResizeBilinearLayer(desc, nodeDef.name().c_str());
2258
2259 IOutputSlot& inputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2260 TensorInfo inputTensorInfo = inputSlot.GetTensorInfo();
telsoa01c577f2c2018-08-31 09:22:23 +01002261 // The input shape is always in BHWC format, this will be swizzled below; for now,
2262 // get the batch and channels to make up the ArmNN output shape with the target size.
surmeh01bceff2f2018-03-29 16:29:27 +01002263 unsigned int outBatch = inputTensorInfo.GetShape()[0];
2264 unsigned int outChannels = inputTensorInfo.GetShape()[3];
2265 unsigned int outHeight = desc.m_TargetHeight;
2266 unsigned int outWidth = desc.m_TargetWidth;
jimfly018a121502018-12-06 16:19:52 +00002267 TensorShape outShape({outBatch, outHeight, outWidth, outChannels });
telsoa01c577f2c2018-08-31 09:22:23 +01002268 // The output DataType is always Float32, regardless of the input DataType.
surmeh01bceff2f2018-03-29 16:29:27 +01002269 const TensorInfo outputTensorInfo(outShape, armnn::DataType::Float32);
2270 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2271
jimfly018a121502018-12-06 16:19:52 +00002272 inputSlot.Connect(layer->GetInputSlot(0));
surmeh01bceff2f2018-03-29 16:29:27 +01002273
2274 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2275}
2276
2277TensorInfo OutputShapeOfSqueeze(const tensorflow::NodeDef& nodeDef, TensorInfo inputTensorInfo)
2278{
2279 BOOST_ASSERT(nodeDef.op() == "Squeeze");
2280 tensorflow::DataType tfDataType = ReadMandatoryNodeTypeAttribute(nodeDef, "T");
2281
2282 DataType type;
2283 if (tfDataType == tensorflow::DT_FLOAT)
2284 {
2285 type = DataType::Float32;
2286 }
2287 else if (tfDataType == tensorflow::DT_INT32)
2288 {
2289 type = DataType::Signed32;
2290 }
2291 else
2292 {
telsoa01c577f2c2018-08-31 09:22:23 +01002293 throw ParseException(
2294 boost::str(
2295 boost::format("Unsupported DataType %1% for Squeeze operation %2% %3%")
2296 % tensorflow::DataType_Name(tfDataType)
2297 % nodeDef.name()
2298 % CHECK_LOCATION().AsString()));
2299 }
2300
2301
2302 if (inputTensorInfo.GetNumDimensions() > 4)
2303 {
2304 throw ParseException(
2305 boost::str(
2306 boost::format(
2307 "Unsupported number of dimensions: %1% for input shape for Squeeze %2% %3%")
2308 % inputTensorInfo.GetNumDimensions()
2309 % nodeDef.name()
2310 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002311 }
2312
2313 std::vector<uint32_t> squeezeDims = ReadOptionalNodeUint32ListAttribute(nodeDef, "squeeze_dims");
telsoa01c577f2c2018-08-31 09:22:23 +01002314 static const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
2315
surmeh01bceff2f2018-03-29 16:29:27 +01002316 if (squeezeDims.empty())
2317 {
telsoa01c577f2c2018-08-31 09:22:23 +01002318 squeezeDims.assign(dimensionSequence,
2319 dimensionSequence+inputTensorInfo.GetNumDimensions());
surmeh01bceff2f2018-03-29 16:29:27 +01002320 }
2321
2322 std::vector<uint32_t> outputDims;
2323 for(unsigned int i = 0; i < inputTensorInfo.GetNumDimensions(); i++)
2324 {
telsoa01c577f2c2018-08-31 09:22:23 +01002325 bool skipSqueeze = (std::find(squeezeDims.begin(), squeezeDims.end(), i) == squeezeDims.end());
2326 auto currentDimension = inputTensorInfo.GetShape()[i];
2327 if (skipSqueeze || currentDimension != 1)
surmeh01bceff2f2018-03-29 16:29:27 +01002328 {
telsoa01c577f2c2018-08-31 09:22:23 +01002329 outputDims.push_back(currentDimension);
surmeh01bceff2f2018-03-29 16:29:27 +01002330 }
2331 }
2332
2333 if (outputDims.size() > 4)
2334 {
telsoa01c577f2c2018-08-31 09:22:23 +01002335 throw ParseException(
2336 boost::str(
2337 boost::format(
2338 "Unsupported number of dimensions: %1% for output shape for Squeeze %2% %3%")
2339 % outputDims.size()
2340 % nodeDef.name()
2341 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002342 }
2343
telsoa01c577f2c2018-08-31 09:22:23 +01002344 TensorShape outShape = TensorShape(static_cast<unsigned int>(outputDims.size()),
2345 outputDims.data());
2346
2347 TensorInfo outTensorInfo = inputTensorInfo;
2348 outTensorInfo.SetShape(outShape);
2349 outTensorInfo.SetDataType(type);
surmeh01bceff2f2018-03-29 16:29:27 +01002350
2351 return outTensorInfo;
2352}
2353
2354ParsedTfOperationPtr TfParser::ParseSqueeze(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
2355{
2356 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2357
2358 IOutputSlot& prevLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2359 TensorInfo inputTensorInfo = prevLayerOutputSlot.GetTensorInfo();
2360
2361 TensorInfo outputInfo;
2362 outputInfo = OutputShapeOfSqueeze(nodeDef, inputTensorInfo);
2363
2364 ReshapeDescriptor reshapeDesc;
2365 reshapeDesc.m_TargetShape = outputInfo.GetShape();
2366 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, nodeDef.name().c_str());
2367 prevLayerOutputSlot.Connect(layer->GetInputSlot(0));
2368 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
2369
2370 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2371}
2372
2373ParsedTfOperationPtr TfParser::ParseLrn(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
2374{
2375 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2376
2377 NormalizationDescriptor normalizationDescriptor;
2378 normalizationDescriptor.m_NormMethodType = NormalizationAlgorithmMethod::LocalBrightness;
2379 normalizationDescriptor.m_NormChannelType = NormalizationAlgorithmChannel::Across;
2380 normalizationDescriptor.m_Alpha = ReadMandatoryNodeFloatAttribute(nodeDef, "alpha");
2381 normalizationDescriptor.m_Beta = ReadMandatoryNodeFloatAttribute(nodeDef, "beta");
2382 normalizationDescriptor.m_K = ReadMandatoryNodeFloatAttribute(nodeDef, "bias");
2383 normalizationDescriptor.m_NormSize = ReadMandatoryNodeUint32Attribute(nodeDef, "depth_radius");
ruoyan018174f362018-12-04 18:24:08 +00002384 normalizationDescriptor.m_DataLayout = armnn::DataLayout::NHWC;
surmeh01bceff2f2018-03-29 16:29:27 +01002385
2386 // The window size must be an odd value. For a window size of (2 * n + 1), TensorFlow defines depth_radius = n.
2387 normalizationDescriptor.m_NormSize = normalizationDescriptor.m_NormSize * 2 + 1;
2388
2389 IOutputSlot& prevLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
surmeh01bceff2f2018-03-29 16:29:27 +01002390 IConnectableLayer* layer = m_Network->AddNormalizationLayer(normalizationDescriptor,
2391 nodeDef.name().c_str());
ruoyan018174f362018-12-04 18:24:08 +00002392 prevLayerOutputSlot.Connect(layer->GetInputSlot(0));
2393 layer->GetOutputSlot(0).SetTensorInfo(prevLayerOutputSlot.GetTensorInfo());
surmeh01bceff2f2018-03-29 16:29:27 +01002394
2395 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2396}
2397
2398/// An ParsedTfOperation for a MatMul node.
telsoa01c577f2c2018-08-31 09:22:23 +01002399/// Creation of the armnn FullyConnected layer is deferred until it is actually needed, because
2400/// MatMul nodes are often used for the first part of a biased FullyConnected (MatMul followed
2401/// by Add) and in these cases armnn doesn't need a separate layer for the MatMul.
2402///
surmeh01bceff2f2018-03-29 16:29:27 +01002403class ParsedMatMulTfOperation : public DeferredSingleLayerParsedTfOperation
2404{
2405public:
2406 ParsedMatMulTfOperation(TfParser* parser, const tensorflow::NodeDef& node)
2407 : DeferredSingleLayerParsedTfOperation(parser, node)
2408 {
2409 }
2410
2411 void CreateLayerDeferred() override
2412 {
2413 BOOST_ASSERT(m_Layer == nullptr);
2414 m_Layer = m_Parser->AddFullyConnectedLayer(m_Node, nullptr, m_Node.name().c_str());
2415 }
2416};
2417
2418ParsedTfOperationPtr TfParser::ParseMatMul(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
2419{
telsoa01c577f2c2018-08-31 09:22:23 +01002420 // Defers the creation of the layer (see ParsedMatMulTfOperation).
surmeh01bceff2f2018-03-29 16:29:27 +01002421 return std::make_unique<ParsedMatMulTfOperation>(this, nodeDef);
2422}
2423
Ferran Balaguer51dd62f2019-01-11 19:29:18 +00002424ParsedTfOperationPtr TfParser::ParseMean(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
2425{
2426 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
2427 IOutputSlot& inputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2428 TensorInfo inputTensorInfo = inputSlot.GetTensorInfo();
2429
2430 if (inputs.size() != 2)
2431 {
2432 throw ParseException(
2433 boost::str(boost::format("Mean expects two inputs!. Got %1% for Node %2% %3%")
2434 % inputs.size()
2435 % nodeDef.name()
2436 % CHECK_LOCATION().AsString()));
2437 }
2438
2439 bool keepDims = ReadMandatoryNodeBoolAttribute(nodeDef, "keep_dims");
2440
2441 ParsedConstTfOperation<int32_t>* axisNode =
2442 boost::polymorphic_downcast<ParsedConstTfOperation<int32_t>*>(inputs[1].m_IndexedValue);
2443
2444 const TensorInfo& axisTensorInfo = axisNode->GetTensorInfo();
2445
2446 ConstTensor axisTensor(axisTensorInfo, axisNode->GetStorage());
2447 const int* axisData = static_cast<const int*>(axisTensor.GetMemoryArea());
2448
2449 TensorInfo outputTensorInfo;
2450 MeanDescriptor meanDescriptor;
2451 meanDescriptor.m_KeepDims = keepDims;
2452
2453 // Negative axis values are supported so that the process requires
2454 // to convert them into the corresponding positive ones.
2455 // Duplicate values are also removed.
2456 std::vector<int> rawAxisVector(axisData, axisData + axisTensorInfo.GetNumElements());
2457 std::set<unsigned int> positiveAxisSet;
2458 int rank = static_cast<int>(inputTensorInfo.GetNumDimensions());
2459
2460 std::transform(rawAxisVector.begin(), rawAxisVector.end(),
2461 std::inserter(positiveAxisSet, positiveAxisSet.begin()),
2462 [rank](int i) -> unsigned int { return static_cast<unsigned int>((i + rank) % rank); });
2463
2464 CalculateReducedOutputTensoInfo(inputTensorInfo, axisTensorInfo, positiveAxisSet, keepDims, outputTensorInfo);
2465
2466 if (inputTensorInfo.GetNumDimensions() > positiveAxisSet.size())
2467 {
2468 meanDescriptor.m_Axis.assign(positiveAxisSet.begin(), positiveAxisSet.end());
2469 }
2470
2471 IConnectableLayer* layer = m_Network->AddMeanLayer(meanDescriptor, nodeDef.name().c_str());
2472 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2473 inputSlot.Connect(layer->GetInputSlot(0));
2474
2475 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2476}
2477
telsoa01c577f2c2018-08-31 09:22:23 +01002478/// An ParsedTfOperation for a Mul node.
2479/// Creation of the armnn Mul layer is deferred until it is actually needed, because Mul nodes
2480/// are also used for the first part of a leaky relu activation function (Mul followed by Maximum)
2481/// and in these cases armnn doesn't need a separate layer for the Mul.
2482///
2483class ParsedMulTfOperation : public DeferredSingleLayerParsedTfOperation
2484{
2485public:
2486 ParsedMulTfOperation(TfParser* parser, const tensorflow::NodeDef& node)
2487 : DeferredSingleLayerParsedTfOperation(parser, node)
2488 {
2489 }
2490
2491 void CreateLayerDeferred() override
2492 {
2493 BOOST_ASSERT(m_Layer == nullptr);
2494 m_Layer = m_Parser->AddMultiplicationLayer(m_Node);
2495 }
2496};
2497
surmeh01bceff2f2018-03-29 16:29:27 +01002498ParsedTfOperationPtr TfParser::ParseMul(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
2499{
2500 boost::ignore_unused(graphDef);
2501
telsoa01c577f2c2018-08-31 09:22:23 +01002502 return std::make_unique<ParsedMulTfOperation>(this, nodeDef);
surmeh01bceff2f2018-03-29 16:29:27 +01002503}
2504
2505ParsedTfOperationPtr TfParser::ParsePlaceholder(const tensorflow::NodeDef& nodeDef,
2506 const tensorflow::GraphDef& graphDef)
2507{
2508 boost::ignore_unused(graphDef);
2509
2510 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 0);
2511
2512 const LayerBindingId layerId = boost::numeric_cast<LayerBindingId>(m_NetworkInputsBindingInfo.size());
2513
2514 auto it = m_InputShapes.find(nodeDef.name());
2515 if (it == m_InputShapes.end())
2516 {
telsoa01c577f2c2018-08-31 09:22:23 +01002517 throw ParseException(
2518 boost::str(
2519 boost::format(
2520 "Missing input shape for Placeholder '%1%' %2%")
2521 % nodeDef.name()
2522 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002523 }
2524 TensorInfo tensorInfo(it->second, DataType::Float32);
2525
2526 IConnectableLayer* const layer = m_Network->AddInputLayer(layerId, nodeDef.name().c_str());
2527
2528 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
2529
2530 TrackInputBinding(layer, layerId, tensorInfo);
2531
2532 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2533}
2534
saoste01bbd40612018-08-28 15:41:51 +01002535ParsedTfOperationPtr TfParser::ParseRealDiv(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
2536{
2537 boost::ignore_unused(graphDef);
2538 return AddRealDivLayer(nodeDef);
2539}
2540
surmeh01bceff2f2018-03-29 16:29:27 +01002541ParsedTfOperationPtr TfParser::ParseRelu(const tensorflow::NodeDef& nodeDef,
2542 const tensorflow::GraphDef& graphDef)
2543{
2544 boost::ignore_unused(graphDef);
2545
2546 ActivationDescriptor activationDesc;
2547 activationDesc.m_Function = ActivationFunction::ReLu;
2548 return AddActivationLayer(nodeDef, activationDesc);
2549}
2550
2551ParsedTfOperationPtr TfParser::ParseRelu6(const tensorflow::NodeDef& nodeDef,
2552 const tensorflow::GraphDef& graphDef)
2553{
2554 boost::ignore_unused(graphDef);
2555
2556 ActivationDescriptor activationDesc;
2557 activationDesc.m_Function = ActivationFunction::BoundedReLu;
2558 activationDesc.m_A = 6.0f;
2559 activationDesc.m_B = 0.0f;
2560
2561 return AddActivationLayer(nodeDef, activationDesc);
2562}
2563
2564ParsedTfOperationPtr TfParser::ParseSigmoid(const tensorflow::NodeDef& nodeDef,
2565 const tensorflow::GraphDef& graphDef)
2566{
2567 boost::ignore_unused(graphDef);
2568
2569 ActivationDescriptor activationDesc;
2570 activationDesc.m_Function = ActivationFunction::Sigmoid;
2571
2572 return AddActivationLayer(nodeDef, activationDesc);
2573}
2574
Mohamed Nour Abouelseoud7a8892f2019-01-09 14:19:58 +00002575ParsedTfOperationPtr TfParser::ParseRsqrt(const tensorflow::NodeDef &nodeDef,
2576 const tensorflow::GraphDef &graphDef)
2577{
2578 boost::ignore_unused(graphDef);
2579
2580 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2581
2582 IConnectableLayer* const layer = m_Network->AddRsqrtLayer(nodeDef.name().c_str());
2583
2584 IOutputSlot& prevLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2585 prevLayerOutputSlot.Connect(layer->GetInputSlot(0));
2586 layer->GetOutputSlot(0).SetTensorInfo(prevLayerOutputSlot.GetTensorInfo());
2587
2588 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2589}
2590
surmeh01bceff2f2018-03-29 16:29:27 +01002591ParsedTfOperationPtr TfParser::ParseSoftmax(const tensorflow::NodeDef& nodeDef,
2592 const tensorflow::GraphDef& graphDef)
2593{
2594 boost::ignore_unused(graphDef);
2595
2596 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2597
2598 SoftmaxDescriptor softmaxDescriptor;
2599 IConnectableLayer* const layer = m_Network->AddSoftmaxLayer(softmaxDescriptor, nodeDef.name().c_str());
2600
2601 IOutputSlot& prevLayerSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2602 prevLayerSlot.Connect(layer->GetInputSlot(0));
2603 layer->GetOutputSlot(0).SetTensorInfo(prevLayerSlot.GetTensorInfo());
2604
2605 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2606}
2607
Sadik Armagan2ad6cb42018-12-27 11:23:44 +00002608ParsedTfOperationPtr TfParser::ParseSplit(const tensorflow::NodeDef& nodeDef,
2609 const tensorflow::GraphDef& graphDef)
2610{
2611 boost::ignore_unused(graphDef);
2612
2613 std::vector<OutputOfConstNodeDef> nodes = GetTfInputNodes(nodeDef);
2614 unsigned int numInputs = static_cast<unsigned int>(nodes.size());
2615 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, numInputs);
2616
Saoirse Stewart91c0eff2019-02-27 11:07:57 +00002617 // Constant tensor index
2618 unsigned int index = GetConstInputIndex(inputs);
Sadik Armagan2ad6cb42018-12-27 11:23:44 +00002619 // Get the axis tensor data
Saoirse Stewart91c0eff2019-02-27 11:07:57 +00002620 ParsedConstTfOperation<int32_t>* shapeNode =
2621 boost::polymorphic_downcast<ParsedConstTfOperation<int32_t>*>(inputs[index].m_IndexedValue);
2622
Sadik Armagan2ad6cb42018-12-27 11:23:44 +00002623 std::vector<int32_t> axisTensorData;
2624 shapeNode->GetConstTensor(axisTensorData);
2625
2626 // This splitDim indicates the data format: 3 is the NHWC, 1 is the NCHW.
2627 const unsigned int splitDim = static_cast<unsigned int>(axisTensorData[0]);
2628
2629 // Armnn supports split along the channel dimension for data formats NHWC and NCHW.
2630 if (splitDim == 0 || splitDim == 2)
2631 {
Saoirse Stewart91c0eff2019-02-27 11:07:57 +00002632 throw armnn::ParseException(
2633 boost::str(
2634 boost::format(
Sadik Armagan2ad6cb42018-12-27 11:23:44 +00002635 "Dimension %1% for split is not supported by Armnn. "
2636 "Node %2% %3%")
Saoirse Stewart91c0eff2019-02-27 11:07:57 +00002637 % splitDim
2638 % nodeDef.name()
2639 % CHECK_LOCATION().AsString()));
Sadik Armagan2ad6cb42018-12-27 11:23:44 +00002640 }
2641
Saoirse Stewart315258e2019-02-28 11:32:41 +00002642 // As Armnn only supports splitter outputs of the same shape, therefore num_split will be limited to an integer.
2643 uint32_t num_split = ReadMandatoryNodeUint32Attribute(nodeDef, "num_split");
Sadik Armagan2ad6cb42018-12-27 11:23:44 +00002644
Saoirse Stewart91c0eff2019-02-27 11:07:57 +00002645 IOutputSlot& inputSlot = inputs[1 - index].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1 - index].m_Index);
Sadik Armagan2ad6cb42018-12-27 11:23:44 +00002646 TensorInfo inputTensorInfo = inputSlot.GetTensorInfo();
2647
Saoirse Stewart91c0eff2019-02-27 11:07:57 +00002648 auto inputDimSize = inputTensorInfo.GetNumDimensions();
2649
2650 if (inputDimSize != MaxNumOfTensorDimensions)
Sadik Armagan2ad6cb42018-12-27 11:23:44 +00002651 {
2652 throw armnn::ParseException(
Saoirse Stewart91c0eff2019-02-27 11:07:57 +00002653 boost::str(
2654 boost::format(
Sadik Armagan2ad6cb42018-12-27 11:23:44 +00002655 "The number of dimensions: %1% for input tensors of the "
Saoirse Stewart91c0eff2019-02-27 11:07:57 +00002656 "split op should be %2% %3%")
2657 % inputTensorInfo.GetNumDimensions()
2658 % MaxNumOfTensorDimensions
2659 % CHECK_LOCATION().AsString()));
Sadik Armagan2ad6cb42018-12-27 11:23:44 +00002660 }
Sadik Armagan2ad6cb42018-12-27 11:23:44 +00002661
2662 std::vector<unsigned int> splitterDimSizes(inputDimSize);
2663
2664 // Add current input shape to splitterDimSizes
2665 for (unsigned int i = 0; i < inputDimSize; ++i)
2666 {
2667 splitterDimSizes[i] = inputTensorInfo.GetShape()[i];
2668 }
2669
2670 if (splitterDimSizes[splitDim] % num_split != 0)
2671 {
2672 throw ParseException("Number of splits must evenly divide the dimension");
2673 }
2674 splitterDimSizes[splitDim] /= num_split;
2675
2676 SplitterDescriptor splitDesc(num_split);
2677 for (unsigned int g = 0; g < num_split; ++g)
2678 {
2679 // Set the size of the views.
2680 for (unsigned int dimIdx = 0; dimIdx < splitterDimSizes.size(); ++dimIdx)
2681 {
2682 splitDesc.SetViewSize(g, dimIdx, splitterDimSizes[dimIdx]);
2683 }
2684 splitDesc.SetViewOriginCoord(g, splitDim, splitterDimSizes[splitDim] * g);
2685 }
2686
2687 IConnectableLayer *layer = m_Network->AddSplitterLayer(splitDesc, nodeDef.name().c_str());
2688
2689 inputSlot.Connect(layer->GetInputSlot(0));
2690
2691 TensorShape outShape = TensorShape(static_cast<unsigned int>(splitterDimSizes.size()),
2692 splitterDimSizes.data());
2693
2694 for (unsigned int i = 0; i < layer->GetNumOutputSlots(); ++i)
2695 {
2696 layer->GetOutputSlot(i).SetTensorInfo(armnn::TensorInfo(outShape, inputTensorInfo.GetDataType()));
2697 }
2698
2699 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2700}
2701
surmeh01bceff2f2018-03-29 16:29:27 +01002702ParsedTfOperationPtr TfParser::ParseSoftplus(const tensorflow::NodeDef& nodeDef,
2703 const tensorflow::GraphDef& graphDef)
2704{
2705 boost::ignore_unused(graphDef);
2706
2707 ActivationDescriptor activationDesc;
2708 activationDesc.m_Function = ActivationFunction::SoftReLu;
2709
2710 return AddActivationLayer(nodeDef, activationDesc);
2711}
2712
2713ParsedTfOperationPtr TfParser::ParseTanh(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
2714{
2715 boost::ignore_unused(graphDef);
2716
2717 ActivationDescriptor activationDesc;
2718 activationDesc.m_Function = ActivationFunction::TanH;
2719 activationDesc.m_A = 1.0f;
2720 activationDesc.m_B = 1.0f;
2721
2722 return AddActivationLayer(nodeDef, activationDesc);
2723}
2724
2725ParsedTfOperationPtr TfParser::AddActivationLayer(const tensorflow::NodeDef& nodeDef,
2726 ActivationDescriptor& activationDesc)
2727{
2728 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2729
2730 IConnectableLayer* const layer = m_Network->AddActivationLayer(activationDesc, nodeDef.name().c_str());
2731
2732 IOutputSlot& prevLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2733 prevLayerOutputSlot.Connect(layer->GetInputSlot(0));
2734 layer->GetOutputSlot(0).SetTensorInfo(prevLayerOutputSlot.GetTensorInfo());
2735 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2736}
2737
2738ParsedTfOperationPtr TfParser::ParseMaxPool(const tensorflow::NodeDef& nodeDef,
2739 const tensorflow::GraphDef& graphDef)
2740{
2741 return ParsePooling2d(nodeDef, graphDef, PoolingAlgorithm::Max);
2742}
2743
2744ParsedTfOperationPtr TfParser::ParseAvgPool(const tensorflow::NodeDef& nodeDef,
2745 const tensorflow::GraphDef& graphDef)
2746{
2747 return ParsePooling2d(nodeDef, graphDef, PoolingAlgorithm::Average);
2748}
2749
2750ParsedTfOperationPtr TfParser::ParsePooling2d(const tensorflow::NodeDef& nodeDef,
2751 const tensorflow::GraphDef& graphDef, PoolingAlgorithm pooltype)
2752{
2753 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2754 IOutputSlot& inputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2755 TensorInfo inputTensorInfo = inputSlot.GetTensorInfo();
2756
2757 if (inputs.size() != 1)
2758 {
telsoa01c577f2c2018-08-31 09:22:23 +01002759 throw ParseException(
2760 boost::str(
2761 boost::format(
2762 "2D Pooling expects one input!. Got %1% for Node %2% %3%")
2763 % inputs.size()
2764 % nodeDef.name()
2765 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002766 }
2767
2768 std::string paddingString = ReadMandatoryNodeStringAttribute(nodeDef, "padding");
2769 std::string dataFormat = ReadMandatoryNodeStringAttribute(nodeDef, "data_format");
2770 std::vector<uint32_t> strides = ReadMandatoryNodeUint32ListAttribute(nodeDef, "strides");
2771 std::vector<uint32_t> ksize = ReadMandatoryNodeUint32ListAttribute(nodeDef, "ksize"); // size of pool windows
2772
2773 Pooling2dDescriptor pooling2dDescriptor;
FrancisMurtaghf005e312018-12-06 15:26:04 +00002774 pooling2dDescriptor.m_PoolType = pooltype;
2775 pooling2dDescriptor.m_PaddingMethod = PaddingMethod::Exclude;
surmeh01bceff2f2018-03-29 16:29:27 +01002776 pooling2dDescriptor.m_OutputShapeRounding = OutputShapeRounding::Floor;
2777
telsoa01c577f2c2018-08-31 09:22:23 +01002778 CHECK_DATA_FORMAT(nodeDef, dataFormat, "Pooling2D");
FrancisMurtaghf005e312018-12-06 15:26:04 +00002779 DataLayout dataLayout = dataFormat == "NHWC" ? DataLayout::NHWC : DataLayout::NCHW;
2780 pooling2dDescriptor.m_DataLayout = dataLayout;
2781 DataLayoutIndexed dataLayoutIndexed(dataLayout);
telsoa01c577f2c2018-08-31 09:22:23 +01002782
FrancisMurtaghf005e312018-12-06 15:26:04 +00002783 pooling2dDescriptor.m_StrideX = strides[dataLayoutIndexed.GetWidthIndex()];
2784 pooling2dDescriptor.m_StrideY = strides[dataLayoutIndexed.GetHeightIndex()];
2785 pooling2dDescriptor.m_PoolWidth = ksize[dataLayoutIndexed.GetWidthIndex()];
2786 pooling2dDescriptor.m_PoolHeight = ksize[dataLayoutIndexed.GetHeightIndex()];
surmeh01bceff2f2018-03-29 16:29:27 +01002787
FrancisMurtaghf005e312018-12-06 15:26:04 +00002788 uint32_t inputHeight = inputTensorInfo.GetShape()[dataLayoutIndexed.GetHeightIndex()];
2789 uint32_t inputWidth = inputTensorInfo.GetShape()[dataLayoutIndexed.GetWidthIndex()];
surmeh01bceff2f2018-03-29 16:29:27 +01002790
2791 bool padding = false;
2792 TensorInfo outputInfo;
FrancisMurtaghf005e312018-12-06 15:26:04 +00002793 unsigned int outputHeight = 0;
2794 unsigned int outputWidth = 0;
telsoa01c577f2c2018-08-31 09:22:23 +01002795
2796 CHECK_PADDING_TYPE(nodeDef, paddingString);
2797
surmeh01bceff2f2018-03-29 16:29:27 +01002798 if (paddingString == "SAME")
2799 {
2800 padding = true;
FrancisMurtaghf005e312018-12-06 15:26:04 +00002801
2802 outputHeight = static_cast<uint32_t>(ceil(static_cast<float>(inputHeight) /
2803 static_cast<float>(pooling2dDescriptor.m_StrideY)));
2804 outputWidth = static_cast<uint32_t>(ceil(static_cast<float>(inputWidth) /
2805 static_cast<float>(pooling2dDescriptor.m_StrideX)));
surmeh01bceff2f2018-03-29 16:29:27 +01002806 }
2807 else if (paddingString == "VALID")
2808 {
2809 padding = false;
FrancisMurtaghf005e312018-12-06 15:26:04 +00002810
2811 outputHeight = static_cast<uint32_t>(ceil(
2812 static_cast<float>(inputHeight - pooling2dDescriptor.m_PoolHeight + 1) /
2813 static_cast<float>(pooling2dDescriptor.m_StrideY)));
2814 outputWidth = static_cast<uint32_t>(ceil(
2815 static_cast<float>(inputWidth - pooling2dDescriptor.m_PoolWidth + 1) /
2816 static_cast<float>(pooling2dDescriptor.m_StrideX)));
2817 }
2818
2819 switch (dataLayout)
2820 {
2821 case DataLayout::NHWC:
2822 outputInfo = TensorInfo({ inputTensorInfo.GetShape()[0],
2823 outputHeight,
2824 outputWidth,
2825 inputTensorInfo.GetShape()[3] },
2826 DataType::Float32);
2827 break;
2828 case DataLayout::NCHW:
2829 outputInfo = TensorInfo({ inputTensorInfo.GetShape()[0],
2830 inputTensorInfo.GetShape()[1],
2831 outputHeight,
2832 outputWidth },
2833 DataType::Float32);
2834 break;
surmeh01bceff2f2018-03-29 16:29:27 +01002835 }
surmeh01bceff2f2018-03-29 16:29:27 +01002836
2837 CalcPadding(inputWidth, pooling2dDescriptor.m_PoolWidth, pooling2dDescriptor.m_StrideX,
FrancisMurtaghf005e312018-12-06 15:26:04 +00002838 pooling2dDescriptor.m_PadLeft, pooling2dDescriptor.m_PadRight, padding);
surmeh01bceff2f2018-03-29 16:29:27 +01002839 CalcPadding(inputHeight, pooling2dDescriptor.m_PoolHeight, pooling2dDescriptor.m_StrideY,
FrancisMurtaghf005e312018-12-06 15:26:04 +00002840 pooling2dDescriptor.m_PadTop, pooling2dDescriptor.m_PadBottom, padding);
surmeh01bceff2f2018-03-29 16:29:27 +01002841
2842
2843 IConnectableLayer* layer = m_Network->AddPooling2dLayer(pooling2dDescriptor, nodeDef.name().c_str());
2844 if (layer == nullptr)
2845 {
telsoa01c577f2c2018-08-31 09:22:23 +01002846 throw ParseException(
2847 boost::str(
2848 boost::format(
2849 "Failed to add pooling2d layer for %1% %2%")
2850 % nodeDef.name()
2851 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002852 }
2853
2854 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
2855
FrancisMurtaghf005e312018-12-06 15:26:04 +00002856 inputSlot.Connect(layer->GetInputSlot(0));
surmeh01bceff2f2018-03-29 16:29:27 +01002857
2858 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2859}
2860
2861ParsedTfOperationPtr TfParser::AddAdditionLayer(const tensorflow::NodeDef& nodeDef, bool isBiasAdd)
2862{
2863 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
2864
2865 IOutputSlot* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2866 IOutputSlot* input1Slot = &inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
2867
2868 const TensorInfo& input0Info = input0Slot->GetTensorInfo();
2869 const TensorInfo& input1Info = input1Slot->GetTensorInfo();
2870
2871 if (isBiasAdd)
2872 {
2873 // BiasAdd takes bias as a 1D tensor. We need to add a reshape layer to create a 4D tensor
2874 // with the same data in the correct dimension for broadcast in addition.
2875 if(input1Info.GetNumDimensions() != 1)
2876 {
telsoa01c577f2c2018-08-31 09:22:23 +01002877 throw ParseException(
2878 boost::str(
2879 boost::format(
2880 "Unsupported bias for BiasAdd. It should be a 1D vector. "
2881 "Got %1% dimensions for input %2%. Node %3% %4%")
2882 % input1Info.GetNumDimensions()
2883 % inputs[1].m_IndexedValue->GetNode().name()
2884 % nodeDef.name()
2885 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002886 }
2887
2888 const std::string dataFormat = ReadMandatoryNodeStringAttribute(nodeDef, "data_format");
surmeh01bceff2f2018-03-29 16:29:27 +01002889
telsoa01c577f2c2018-08-31 09:22:23 +01002890 CHECK_DATA_FORMAT(nodeDef, dataFormat, "BiasAdd");
saoste01bbd40612018-08-28 15:41:51 +01002891 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, dataFormat == "NHWC", *m_Network, nodeDef);
surmeh01bceff2f2018-03-29 16:29:27 +01002892 }
2893 else
2894 {
2895 if (input0Info.GetNumDimensions() == 1)
2896 {
2897 const bool isNHWC = true;
saoste01bbd40612018-08-28 15:41:51 +01002898 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot, isNHWC, *m_Network, nodeDef);
surmeh01bceff2f2018-03-29 16:29:27 +01002899 }
2900
2901 if (input1Info.GetNumDimensions() == 1)
2902 {
2903 const bool isNHWC = true;
saoste01bbd40612018-08-28 15:41:51 +01002904 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, isNHWC, *m_Network, nodeDef);
surmeh01bceff2f2018-03-29 16:29:27 +01002905 }
2906 }
2907
2908 IConnectableLayer* const layer = m_Network->AddAdditionLayer(nodeDef.name().c_str());
2909
2910 input0Slot->Connect(layer->GetInputSlot(0));
2911 input1Slot->Connect(layer->GetInputSlot(1));
2912
Nattapat Chaimanowongfab64f02019-02-15 16:46:24 +00002913 if (input0Info.GetNumDimensions() == input1Info.GetNumDimensions())
2914 {
2915 const TensorShape& input0Shape = input0Info.GetShape();
2916 const TensorShape& input1Shape = input1Info.GetShape();
2917
2918 std::vector<unsigned int> outputShape;
2919 outputShape.reserve(input0Shape.GetNumDimensions());
2920 TensorInfo outputInfo(input0Info);
2921
2922 for (unsigned int i = 0; i < input0Shape.GetNumDimensions(); i++)
2923 {
2924 outputShape.push_back(std::max(input0Shape[i], input1Shape[i]));
2925 }
2926
2927 outputInfo.SetShape(TensorShape(input0Shape.GetNumDimensions(), outputShape.data()));
2928
2929 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
2930 }
2931 else if (input0Info.GetNumDimensions() == 1 && isBiasAdd == false)
surmeh01bceff2f2018-03-29 16:29:27 +01002932 {
2933 layer->GetOutputSlot(0).SetTensorInfo(input1Slot->GetTensorInfo());
2934 }
2935 else
2936 {
2937 layer->GetOutputSlot(0).SetTensorInfo(input0Slot->GetTensorInfo());
2938 }
2939
2940 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2941}
2942
saoste01bbd40612018-08-28 15:41:51 +01002943ParsedTfOperationPtr TfParser::AddRealDivLayer(const tensorflow::NodeDef& nodeDef)
2944{
2945 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
2946
2947 IConnectableLayer* const layer = m_Network->AddDivisionLayer(nodeDef.name().c_str());
2948 IOutputSlot* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2949 IOutputSlot* input1Slot = &inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
2950
2951 auto const input0NumDims = input0Slot->GetTensorInfo().GetNumDimensions();
2952 auto const input1NumDims = input1Slot->GetTensorInfo().GetNumDimensions();
2953
2954
2955 if (input0NumDims < input1NumDims)
2956 {
2957 const bool isNHWC = true;
2958 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot, isNHWC, *m_Network, nodeDef);
2959 }
2960 if (input1NumDims < input0NumDims)
2961 {
2962 const bool isNHWC = true;
2963 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, isNHWC, *m_Network, nodeDef);
2964 }
2965
2966 input0Slot->Connect(layer->GetInputSlot(0));
2967 input1Slot->Connect(layer->GetInputSlot(1));
2968
2969 if (input0NumDims < input1NumDims)
2970 {
2971 layer->GetOutputSlot(0).SetTensorInfo(input1Slot->GetTensorInfo());
2972 }
2973 else
2974 {
2975 layer->GetOutputSlot(0).SetTensorInfo(input0Slot->GetTensorInfo());
2976
2977 }
2978 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2979}
2980
Sadik Armagan975c09a2018-12-04 10:02:08 +00002981ParsedTfOperationPtr TfParser::AddMaximumLayer(const tensorflow::NodeDef& nodeDef)
2982{
2983 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
2984
2985 IOutputSlot* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2986 IOutputSlot* input1Slot = &inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
2987
2988 auto const input0NumDims = input0Slot->GetTensorInfo().GetNumDimensions();
2989 auto const input1NumDims = input1Slot->GetTensorInfo().GetNumDimensions();
2990
2991 if (input0NumDims < input1NumDims)
2992 {
2993 const bool isNHWC = true;
2994 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot, isNHWC, *m_Network, nodeDef);
2995 }
2996 if (input1NumDims < input0NumDims)
2997 {
2998 const bool isNHWC = true;
2999 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, isNHWC, *m_Network, nodeDef);
3000 }
3001
3002 IConnectableLayer* const layer = m_Network->AddMaximumLayer(nodeDef.name().c_str());
3003
3004 input0Slot->Connect(layer->GetInputSlot(0));
3005 input1Slot->Connect(layer->GetInputSlot(1));
3006
3007 TensorInfo outputInfo = input0Slot->GetTensorInfo();
3008 std::vector<unsigned int> outputShape;
3009
3010 const TensorShape& input0Shape = input0Slot->GetTensorInfo().GetShape();
3011 const TensorShape& input1Shape = input1Slot->GetTensorInfo().GetShape();
3012
3013 for (unsigned int i = 0; i < input0Shape.GetNumDimensions(); i++)
3014 {
3015 outputShape.push_back(std::max(input0Shape[i], input1Shape[i]));
3016 }
3017
3018 outputInfo.SetShape(TensorShape(input0Shape.GetNumDimensions(), outputShape.data()));
3019 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
3020
3021 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
3022}
3023
telsoa01c577f2c2018-08-31 09:22:23 +01003024IConnectableLayer* TfParser::AddMultiplicationLayer(const tensorflow::NodeDef& nodeDef)
3025{
3026 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
3027
3028 IConnectableLayer* const layer = m_Network->AddMultiplicationLayer(nodeDef.name().c_str());
3029 IOutputSlot* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
3030 IOutputSlot* input1Slot = &inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
3031
3032 auto const input0NumDims = input0Slot->GetTensorInfo().GetNumDimensions();
3033 auto const input1NumDims = input1Slot->GetTensorInfo().GetNumDimensions();
3034
3035 if (input0NumDims < input1NumDims)
3036 {
3037 const bool isNHWC = true;
saoste01bbd40612018-08-28 15:41:51 +01003038 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot, isNHWC, *m_Network, nodeDef);
telsoa01c577f2c2018-08-31 09:22:23 +01003039 }
3040 if (input1NumDims < input0NumDims)
3041 {
3042 const bool isNHWC = true;
saoste01bbd40612018-08-28 15:41:51 +01003043 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, isNHWC, *m_Network, nodeDef);
telsoa01c577f2c2018-08-31 09:22:23 +01003044 }
3045
3046 input0Slot->Connect(layer->GetInputSlot(0));
3047 input1Slot->Connect(layer->GetInputSlot(1));
3048
3049 if (input0NumDims < input1NumDims)
3050 {
3051 layer->GetOutputSlot(0).SetTensorInfo(input1Slot->GetTensorInfo());
3052 }
3053 else
3054 {
3055 layer->GetOutputSlot(0).SetTensorInfo(input0Slot->GetTensorInfo());
3056 }
3057 return layer;
3058}
3059
surmeh01bceff2f2018-03-29 16:29:27 +01003060IConnectableLayer* TfParser::AddFullyConnectedLayer(const tensorflow::NodeDef& matMulNodeDef,
3061 const tensorflow::NodeDef* addNodeDef, const char* armnnLayerName)
3062{
telsoa01c577f2c2018-08-31 09:22:23 +01003063 // Finds bias const (if applicable).
surmeh01bceff2f2018-03-29 16:29:27 +01003064 ParsedConstTfOperation<float>* biasNode = nullptr;
3065 if (addNodeDef != nullptr)
3066 {
3067 std::vector<OutputOfParsedTfOperation> addInputs = GetInputParsedTfOperationsChecked(*addNodeDef, 2);
telsoa01c577f2c2018-08-31 09:22:23 +01003068 // Finds our inputs.
surmeh01bceff2f2018-03-29 16:29:27 +01003069 if (HasParsedConstTensor<float>(addInputs[0].m_IndexedValue->GetNode().name()))
3070 {
3071 biasNode = boost::polymorphic_downcast<ParsedConstTfOperation<float>*>(addInputs[0].m_IndexedValue);
3072 }
3073 else if (HasParsedConstTensor<float>(addInputs[1].m_IndexedValue->GetNode().name()))
3074 {
3075 biasNode = boost::polymorphic_downcast<ParsedConstTfOperation<float>*>(addInputs[1].m_IndexedValue);
3076 }
3077 else
3078 {
telsoa01c577f2c2018-08-31 09:22:23 +01003079 throw ParseException(
3080 boost::str(
3081 boost::format(
3082 "ArmNN only supports fully connected layers with constant bias. "
3083 "Inputs %1% and %2%. AddNode %3%. MatMulNode %4% %5%")
3084 % addInputs[0].m_IndexedValue->GetNode().name()
3085 % addInputs[1].m_IndexedValue->GetNode().name()
3086 % addNodeDef->name()
3087 % matMulNodeDef.name()
3088 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003089 }
3090 }
3091
telsoa01c577f2c2018-08-31 09:22:23 +01003092 // Finds matmul inputs.
surmeh01bceff2f2018-03-29 16:29:27 +01003093 ParsedConstTfOperation<float>* weightNode = nullptr;
3094 ParsedTfOperation* inputNode = nullptr;
3095 unsigned int inputIdx = 0;
3096 std::vector<OutputOfParsedTfOperation> mulInputs = GetInputParsedTfOperationsChecked(matMulNodeDef, 2);
3097 if (HasParsedConstTensor<float>(mulInputs[0].m_IndexedValue->GetNode().name()))
3098 {
3099 weightNode = boost::polymorphic_downcast<ParsedConstTfOperation<float>*>(mulInputs[0].m_IndexedValue);
3100 inputNode = mulInputs[1].m_IndexedValue;
3101 inputIdx = mulInputs[1].m_Index;
3102 }
3103 else if (HasParsedConstTensor<float>(mulInputs[1].m_IndexedValue->GetNode().name()))
3104 {
3105 weightNode = boost::polymorphic_downcast<ParsedConstTfOperation<float>*>(mulInputs[1].m_IndexedValue);
3106 inputNode = mulInputs[0].m_IndexedValue;
3107 inputIdx = mulInputs[0].m_Index;
3108 }
3109 else
3110 {
telsoa01c577f2c2018-08-31 09:22:23 +01003111 throw ParseException(
3112 boost::str(
3113 boost::format(
3114 "ArmNN only supports fully connected layers with constant weights. "
3115 "Inputs %1% and %2%. MatMulNode %3% %4%")
3116 % mulInputs[0].m_IndexedValue->GetNode().name()
3117 % mulInputs[1].m_IndexedValue->GetNode().name()
3118 % matMulNodeDef.name()
3119 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003120 }
3121
3122 std::vector<float> weightTensorData;
telsoa01c577f2c2018-08-31 09:22:23 +01003123 // Handles weight.
Matteo Martincigh482ca852018-12-12 09:20:55 +00003124 ConstTensor weights = weightNode->GetConstTensor(weightTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +01003125
3126 FullyConnectedDescriptor desc;
3127 desc.m_BiasEnabled = addNodeDef != nullptr;
3128
3129 IConnectableLayer* layer = nullptr;
telsoa01c577f2c2018-08-31 09:22:23 +01003130 // Makes the layer.
surmeh01bceff2f2018-03-29 16:29:27 +01003131 if (addNodeDef != nullptr)
3132 {
3133 std::vector<float> biasTensorData;
Matteo Martincigh482ca852018-12-12 09:20:55 +00003134 ConstTensor biases = biasNode->GetConstTensor(biasTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +01003135
3136 if (weights.GetShape()[1] != biases.GetShape()[0])
3137 {
telsoa01c577f2c2018-08-31 09:22:23 +01003138 throw ParseException(
3139 boost::str(
3140 boost::format(
3141 "Shape of matmul weights and bias do not match. "
3142 "AddNode %1%. MatMulNode %2% %3%")
3143 % addNodeDef->name()
3144 % matMulNodeDef.name()
3145 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003146 }
3147
3148 layer = m_Network->AddFullyConnectedLayer(desc, weights, biases, armnnLayerName);
3149 }
3150 else
3151 {
3152 layer = m_Network->AddFullyConnectedLayer(desc, weights, armnnLayerName);
3153 }
3154
3155 BOOST_ASSERT(layer != nullptr);
3156
3157 inputNode->ResolveArmnnOutputSlot(inputIdx).Connect(layer->GetInputSlot(0));
3158 unsigned int batches = inputNode->ResolveArmnnOutputSlot(inputIdx).GetTensorInfo().GetShape()[0];
3159
telsoa01c577f2c2018-08-31 09:22:23 +01003160 // Handles output.
surmeh01bceff2f2018-03-29 16:29:27 +01003161 TensorInfo outputInfo({ batches, weights.GetShape()[1] }, DataType::Float32);
3162 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
3163 return layer;
3164}
3165
3166void TfParser::LoadNodeDef(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
3167{
telsoa01c577f2c2018-08-31 09:22:23 +01003168 // Gets the type of the node (assume float).
surmeh01bceff2f2018-03-29 16:29:27 +01003169 tensorflow::DataType type = tensorflow::DT_FLOAT;
3170 if (nodeDef.attr().count("T") != 0)
3171 {
3172 auto attr = nodeDef.attr().at("T");
3173 type = attr.type();
3174 }
3175 else if (nodeDef.attr().count("dtype") != 0)
3176 {
3177 auto attr = nodeDef.attr().at("dtype");
3178 type = attr.type();
3179 }
3180
Ferran Balaguerc602f292019-02-08 17:09:55 +00003181 if ((type != tensorflow::DT_FLOAT && type != tensorflow::DT_INT32) && nodeDef.op() != "Const")
surmeh01bceff2f2018-03-29 16:29:27 +01003182 {
telsoa01c577f2c2018-08-31 09:22:23 +01003183 throw ParseException(
3184 boost::str(
3185 boost::format(
Ferran Balaguerc602f292019-02-08 17:09:55 +00003186 "Currently only FLOAT and INT32 are supported for tensorflow nodes (apart from Const). "
telsoa01c577f2c2018-08-31 09:22:23 +01003187 "Got %1% for Node %2% %3%")
3188 % tensorflow::DataType_Name(type)
3189 % nodeDef.name()
3190 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003191 }
3192
3193 const std::string& operation = nodeDef.op();
narpra016f37f832018-12-21 18:30:00 +00003194 auto itControlInput = std::find(m_ControlInputs.begin(), m_ControlInputs.end(), operation);
3195 if (itControlInput != m_ControlInputs.end())
3196 {
3197 // We currently allow Control Input from TensorFlow graph but we ignore them from ArmNN graph.
3198 return;
3199 }
surmeh01bceff2f2018-03-29 16:29:27 +01003200 auto it = ms_OperationNameToParsingFunctions.find(operation);
3201 if (it != ms_OperationNameToParsingFunctions.end())
3202 {
3203 auto func = it->second;
3204 ParsedTfOperationPtr parsedTfOperation = (this->*func)(nodeDef, graphDef);
3205 ParsedTfOperation* parsedTfOperationRaw = parsedTfOperation.get();
3206
telsoa01c577f2c2018-08-31 09:22:23 +01003207 // Stores the parsed operation so that dependent layers can connect to it.
surmeh01bceff2f2018-03-29 16:29:27 +01003208 auto it = m_ParsedTfOperations.find(nodeDef.name());
3209 if (it != m_ParsedTfOperations.end())
3210 {
3211 throw ParseException(boost::str(boost::format("Name %1% used by more than one node") % nodeDef.name()));
3212 }
3213 m_ParsedTfOperations[nodeDef.name()] = std::move(parsedTfOperation);
3214
telsoa01c577f2c2018-08-31 09:22:23 +01003215 // If this node was requested as an output from the network, then adds an ArmNN output layer.
surmeh01bceff2f2018-03-29 16:29:27 +01003216 if (std::find(m_RequestedOutputs.begin(), m_RequestedOutputs.end(), nodeDef.name()) !=
3217 m_RequestedOutputs.end())
3218 {
3219 auto outId = ParseOutputId(nodeDef.name());
3220 const LayerBindingId layerId = boost::numeric_cast<LayerBindingId>(m_NetworkOutputsBindingInfo.size());
3221 IOutputSlot& prevSlot = parsedTfOperationRaw->ResolveArmnnOutputSlot(outId.m_Index);
3222
3223 TensorInfo tensorInfo = prevSlot.GetTensorInfo();
3224
3225 IConnectableLayer* outputLayer = m_Network->AddOutputLayer(layerId, nodeDef.name().c_str());
3226
3227 prevSlot.Connect(outputLayer->GetInputSlot(0));
3228
3229 TrackOutputBinding(outputLayer, layerId, tensorInfo);
3230 }
3231 }
3232 else
3233 {
telsoa01c577f2c2018-08-31 09:22:23 +01003234 throw ParseException(
3235 boost::str(
3236 boost::format(
3237 "Unsupported operation %1% in tensorflow::GraphDef %2%")
3238 % operation
3239 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003240 }
3241}
3242
3243void TfParser::LoadGraphDef(const tensorflow::GraphDef& graphDef)
3244{
telsoa01c577f2c2018-08-31 09:22:23 +01003245 // Adds all nodes to our map.
surmeh01bceff2f2018-03-29 16:29:27 +01003246 m_NodesByName.clear();
3247 m_NetworkInputsBindingInfo.clear();
3248 m_NetworkOutputsBindingInfo.clear();
3249
3250 for (int i = 0; i < graphDef.node_size(); ++i)
3251 {
3252 const tensorflow::NodeDef& node = graphDef.node(i);
3253 m_NodesByName[node.name()] = &node;
3254 }
3255
Francis Murtaghbb190a62019-04-04 11:16:29 +01003256 // Checks that the input nodes the user has requested exist.
3257 for (const auto& pair : m_InputShapes)
3258 {
3259 const std::string& requestedInputName = pair.first;
3260 auto nodeIt = m_NodesByName.find(requestedInputName);
3261 if (nodeIt == m_NodesByName.end())
3262 {
3263 throw ParseException(
3264 boost::str(
3265 boost::format(
3266 "Couldn't find requested input node '%1%' in graph %2%")
3267 % requestedInputName
3268 % CHECK_LOCATION().AsString()));
3269 }
3270 }
3271
telsoa01c577f2c2018-08-31 09:22:23 +01003272 // Finds the output nodes the user requested.
surmeh01bceff2f2018-03-29 16:29:27 +01003273 std::vector<const tensorflow::NodeDef*> targetNodes;
3274 for (const std::string& requestedOutputName : m_RequestedOutputs)
3275 {
3276 auto nodeIt = m_NodesByName.find(requestedOutputName);
3277 if (nodeIt == m_NodesByName.end())
3278 {
telsoa01c577f2c2018-08-31 09:22:23 +01003279 throw ParseException(
3280 boost::str(
3281 boost::format(
3282 "Couldn't find requested output node '%1%' in graph %2%")
3283 % requestedOutputName
3284 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003285 }
3286 targetNodes.push_back(nodeIt->second);
3287 }
3288
telsoa01c577f2c2018-08-31 09:22:23 +01003289 // Sorts them into a linear ordering such that all inputs of a node are before the node itself.
surmeh01bceff2f2018-03-29 16:29:27 +01003290 std::vector<const tensorflow::NodeDef*> sortedNodes;
3291 if (!armnnUtils::GraphTopologicalSort<const tensorflow::NodeDef*>(
3292 targetNodes,
3293 [this](const tensorflow::NodeDef* node)
3294 {
3295 auto outputs = GetTfInputNodes(*node);
3296 std::vector<const tensorflow::NodeDef*> nodesOnly;
3297 for (const auto & o : outputs) {
3298 nodesOnly.push_back(o.m_IndexedValue);
3299 }
3300 return nodesOnly;
3301 },
3302 sortedNodes))
3303 {
telsoa01c577f2c2018-08-31 09:22:23 +01003304 throw ParseException(
3305 boost::str(
3306 boost::format(
3307 "Cycle detected in graph %1%")
3308 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003309 }
3310
telsoa01c577f2c2018-08-31 09:22:23 +01003311 // Parses each node in order, knowing that all inputs of a node will be processed before the node itself.
surmeh01bceff2f2018-03-29 16:29:27 +01003312 for (const auto& it : sortedNodes)
3313 {
3314 const tensorflow::NodeDef& currentNode = *it;
3315 LoadNodeDef(currentNode, graphDef);
3316 }
3317}
3318
3319INetworkPtr TfParser::CreateNetworkFromTextFile(const char* graphFile,
3320 const std::map<std::string, TensorShape>& inputShapes,
3321 const std::vector<std::string>& requestedOutputs)
3322{
3323 FILE* fd = fopen(graphFile, "r");
3324
3325 if (fd == nullptr)
3326 {
telsoa01c577f2c2018-08-31 09:22:23 +01003327 throw FileNotFoundException(
3328 boost::str(
3329 boost::format(
3330 "Graph file %1% failed to open %2%")
3331 % graphFile
3332 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003333 }
3334
telsoa01c577f2c2018-08-31 09:22:23 +01003335 // Parses the file into a message.
surmeh01bceff2f2018-03-29 16:29:27 +01003336 tensorflow::GraphDef graphDef;
3337 auto input = new google::protobuf::io::FileInputStream(fileno(fd));
3338 bool success = google::protobuf::TextFormat::Parse(input, &graphDef);
3339 delete input;
3340 fclose(fd);
3341
3342 if (!success)
3343 {
telsoa01c577f2c2018-08-31 09:22:23 +01003344 throw ParseException(
3345 boost::str(
3346 boost::format(
3347 "Failed to parse graph file %1%")
3348 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003349 }
3350
3351 return CreateNetworkFromGraphDef(graphDef, inputShapes, requestedOutputs);
3352}
3353
3354INetworkPtr TfParser::CreateNetworkFromString(const char* protoText,
3355 const std::map<std::string, TensorShape>& inputShapes,
3356 const std::vector<std::string>& requestedOutputs)
3357{
telsoa01c577f2c2018-08-31 09:22:23 +01003358 // Parses the string into a message.
surmeh01bceff2f2018-03-29 16:29:27 +01003359 tensorflow::GraphDef graphDef;
3360 bool success = google::protobuf::TextFormat::ParseFromString(protoText, &graphDef);
3361
3362 if (!success)
3363 {
telsoa01c577f2c2018-08-31 09:22:23 +01003364 throw ParseException(
3365 boost::str(
3366 boost::format(
3367 "Failed to parse graph file %1%")
3368 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003369 }
3370
3371 return CreateNetworkFromGraphDef(graphDef, inputShapes, requestedOutputs);
3372}
3373
3374INetworkPtr TfParser::CreateNetworkFromBinaryFile(const char* graphFile,
3375 const std::map<std::string, TensorShape>& inputShapes,
3376 const std::vector<std::string>& requestedOutputs)
3377{
3378 FILE* fd = fopen(graphFile, "rb");
3379
3380 if (fd == nullptr)
3381 {
telsoa01c577f2c2018-08-31 09:22:23 +01003382 throw FileNotFoundException(
3383 boost::str(
3384 boost::format(
3385 "Graph file %1% failed to open %2%")
3386 % graphFile
3387 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003388 }
3389
telsoa01c577f2c2018-08-31 09:22:23 +01003390 // Parses the file into a message.
surmeh01bceff2f2018-03-29 16:29:27 +01003391 tensorflow::GraphDef graphDef;
3392
3393 google::protobuf::io::FileInputStream inStream(fileno(fd));
3394 google::protobuf::io::CodedInputStream codedStream(&inStream);
3395 codedStream.SetTotalBytesLimit(INT_MAX, INT_MAX);
3396 bool success = graphDef.ParseFromCodedStream(&codedStream);
3397 fclose(fd);
3398
3399 if (!success)
3400 {
telsoa01c577f2c2018-08-31 09:22:23 +01003401 throw ParseException(
3402 boost::str(
3403 boost::format(
3404 "Failed to parse protobuf file %1% %2%")
3405 % graphFile
3406 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003407 }
3408
3409 return CreateNetworkFromGraphDef(graphDef, inputShapes, requestedOutputs);
3410}
3411
3412INetworkPtr TfParser::CreateNetworkFromGraphDef(const tensorflow::GraphDef& graphDef,
3413 const std::map<std::string, TensorShape>& inputShapes,
3414 const std::vector<std::string>& requestedOutputs)
3415{
3416 m_Network = INetwork::Create();
3417
3418 m_InputShapes = inputShapes;
3419 if (requestedOutputs.size() == 0)
3420 {
telsoa01c577f2c2018-08-31 09:22:23 +01003421 throw ParseException(
3422 boost::str(
3423 boost::format(
3424 "requestedOutputs must have at least one entry %1%")
3425 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003426 }
3427 m_RequestedOutputs = requestedOutputs;
3428
3429 try
3430 {
3431 LoadGraphDef(graphDef);
3432 }
3433 catch (const ParseException& e)
3434 {
3435 Cleanup();
3436 throw e;
3437 }
3438
3439 Cleanup();
3440
3441 return std::move(m_Network);
3442}
3443
3444void TfParser::Cleanup()
3445{
telsoa01c577f2c2018-08-31 09:22:23 +01003446 // Cleanup, in case we reuse this parser.
surmeh01bceff2f2018-03-29 16:29:27 +01003447 m_InputShapes.clear();
3448 m_RequestedOutputs.clear();
3449 m_NodesByName.clear();
3450 m_ParsedTfOperations.clear();
3451}
3452
3453BindingPointInfo TfParser::GetNetworkInputBindingInfo(const std::string& name) const
3454{
3455 return GetBindingInfo(name, "input", m_NetworkInputsBindingInfo);
3456}
3457
3458BindingPointInfo TfParser::GetNetworkOutputBindingInfo(const std::string& name) const
3459{
3460 return GetBindingInfo(name, "output", m_NetworkOutputsBindingInfo);
3461}
3462
3463std::pair<LayerBindingId, TensorInfo> TfParser::GetBindingInfo(const std::string& layerName,
3464 const char* bindingPointDesc,
3465 const std::unordered_map<std::string, BindingPointInfo>& nameToBindingInfo)
3466{
3467 auto it = nameToBindingInfo.find(layerName);
3468 if (it == nameToBindingInfo.end())
3469 {
telsoa01c577f2c2018-08-31 09:22:23 +01003470 throw InvalidArgumentException(
3471 boost::str(
3472 boost::format(
3473 "Unknown %1% '%2%' %3%")
3474 % bindingPointDesc
3475 % layerName
3476 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003477 }
3478 return it->second;
3479}
3480
3481void TfParser::TrackInputBinding(IConnectableLayer* layer, LayerBindingId id, const TensorInfo& tensorInfo)
3482{
3483 return TrackBindingPoint(layer, id, tensorInfo, "input", m_NetworkInputsBindingInfo);
3484}
3485
3486void TfParser::TrackOutputBinding(IConnectableLayer* layer, LayerBindingId id, const TensorInfo& tensorInfo)
3487{
3488 return TrackBindingPoint(layer, id, tensorInfo, "output", m_NetworkOutputsBindingInfo);
3489}
3490
3491void TfParser::TrackBindingPoint(IConnectableLayer* layer,
3492 LayerBindingId id,
3493 const TensorInfo& tensorInfo,
3494 const char* bindingPointDesc,
3495 std::unordered_map<std::string, BindingPointInfo>& nameToBindingInfo)
3496{
3497 const std::string layerName = layer->GetName();
3498 auto it = nameToBindingInfo.find(layerName);
3499 if (it == nameToBindingInfo.end())
3500 {
3501 nameToBindingInfo[layerName] = std::make_pair(id, tensorInfo);
3502 }
3503 else
3504 {
telsoa01c577f2c2018-08-31 09:22:23 +01003505 throw ParseException(
3506 boost::str(
3507 boost::format(
3508 "Id %1% used by more than one %2% layer %3%")
3509 % id
3510 % bindingPointDesc
3511 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003512 }
3513}
3514
3515} // namespace armnnTfParser