blob: b5fe6be075cde09bbf32f3e43928b26847cd2b5d [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>
surmeh01bceff2f2018-03-29 16:29:27 +010023#include <boost/polymorphic_cast.hpp>
24
surmeh01bceff2f2018-03-29 16:29:27 +010025#include <numeric>
surmeh01bceff2f2018-03-29 16:29:27 +010026
Matteo Martincigh46315822018-11-28 16:22:36 +000027using namespace armnnUtils;
surmeh01bceff2f2018-03-29 16:29:27 +010028using namespace armnn;
29
30namespace armnnTfParser
31{
32namespace
33{
34
35const PermutationVector NHWCToArmNN = { 0, 2, 3, 1 };
36const PermutationVector ArmNNToNHWC = { 0, 3, 1, 2 };
37
surmeh01bceff2f2018-03-29 16:29:27 +010038
39template <typename Callable>
40void ReadMandatoryNodeAttributeImpl(const tensorflow::NodeDef& nodeDef,
41 const std::string& attribName,
42 tensorflow::AttrValue::ValueCase expectedValueCase,
43 Callable callable)
44{
45 auto iter = nodeDef.attr().find(attribName);
46 if (iter != nodeDef.attr().end())
47 {
48 const auto& attrValue = iter->second;
49 if (attrValue.value_case() == expectedValueCase)
50 {
51 callable(attrValue);
52 }
53 else
54 {
telsoa01c577f2c2018-08-31 09:22:23 +010055 throw ParseException(
56 boost::str(
57 boost::format(
58 "Attribute %1% of node %2% expected to have %3% as tensorflow::AttrValue::ValueCase, "
59 "but found %4% instead %5%")
60 % attribName
61 % nodeDef.name()
62 % static_cast<int>(expectedValueCase)
63 % static_cast<int>(attrValue.value_case())
64 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +010065 }
66 }
67 else
68 {
telsoa01c577f2c2018-08-31 09:22:23 +010069 throw ParseException(
70 boost::str(
71 boost::format(
72 "Could not find required attribute %1% in node %2% %3%")
73 % attribName
74 % nodeDef.name()
75 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +010076 }
77}
78
79template <typename Callable>
80void ReadOptionalNodeAttributeImpl(const tensorflow::NodeDef& nodeDef,
81 const std::string& attribName,
82 tensorflow::AttrValue::ValueCase expectedValueCase,
83 Callable callable)
84{
85 auto iter = nodeDef.attr().find(attribName);
86 if (iter != nodeDef.attr().end())
87 {
88 const auto& attrValue = iter->second;
89 if (attrValue.value_case() == expectedValueCase)
90 {
91 callable(attrValue);
92 }
93 else
94 {
telsoa01c577f2c2018-08-31 09:22:23 +010095 throw ParseException(
96 boost::str(
97 boost::format(
98 "Attribute %1% of node %2% expected to have %3% as tensorflow::AttrValue::ValueCase, "
99 "but found %4% instead %5%")
100 % attribName
101 % nodeDef.name()
102 % static_cast<int>(expectedValueCase)
103 % static_cast<int>(attrValue.value_case())
104 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100105 }
106 }
107}
108
109float ReadMandatoryNodeFloatAttribute(const tensorflow::NodeDef& nodeDef, const std::string& name)
110{
111 float attribValue = 0.0f;
112 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kF,
113 [&attribValue](const tensorflow::AttrValue& attrValue)
114 {
115 attribValue = attrValue.f();
116 });
117 return attribValue;
118}
119
Conor Kennedyc2130a02018-12-05 11:05:54 +0000120int32_t ReadMandatoryNodeInt32Attribute(const tensorflow::NodeDef& nodeDef, const std::string& name)
121{
122 int32_t attribValue = 0u;
123 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kI,
124 [&attribValue](const tensorflow::AttrValue& attrValue)
125 {
126 attribValue = static_cast<int32_t>(attrValue.i());
127 });
128 return attribValue;
129}
130
Ferran Balaguer51dd62f2019-01-11 19:29:18 +0000131bool ReadMandatoryNodeBoolAttribute(const tensorflow::NodeDef& nodeDef, const std::string& name)
132{
133 bool attribValue = false;
134 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kB,
135 [&attribValue](const tensorflow::AttrValue& attrValue)
136 {
137 attribValue = static_cast<bool>(attrValue.b());
138 });
139 return attribValue;
140}
141
surmeh01bceff2f2018-03-29 16:29:27 +0100142uint32_t ReadMandatoryNodeUint32Attribute(const tensorflow::NodeDef& nodeDef, const std::string& name)
143{
144 uint32_t attribValue = 0u;
145 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kI,
146 [&attribValue](const tensorflow::AttrValue& attrValue)
147 {
148 attribValue = static_cast<uint32_t>(attrValue.i());
149 });
150 return attribValue;
151}
152
153std::string ReadMandatoryNodeStringAttribute(const tensorflow::NodeDef& nodeDef, const std::string& name)
154{
155 std::string attribValue = "";
156 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kS,
157 [&attribValue](const tensorflow::AttrValue& attrValue)
158 {
159 attribValue = attrValue.s();
160 });
161 return attribValue;
162}
163
164std::vector<uint32_t> ReadMandatoryNodeUint32ListAttribute(const tensorflow::NodeDef& nodeDef,
165 const std::string& name)
166{
167 std::vector<uint32_t> attriList;
168 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kList,
169 [&attriList](const tensorflow::AttrValue& attrValue)
170 {
171 for (int attriNum = 0; attriNum < attrValue.list().i_size(); ++attriNum)
172 {
173 attriList.push_back(static_cast<uint32_t>(attrValue.list().i(attriNum)));
174 }
175 });
176
177 return attriList;
178}
179
180std::vector<uint32_t> ReadOptionalNodeUint32ListAttribute(const tensorflow::NodeDef& nodeDef,
181 const std::string& name)
182{
183 std::vector<uint32_t> attriList;
184 ReadOptionalNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kList,
185 [&attriList](const tensorflow::AttrValue& attrValue)
186 {
187 for (int attriNum = 0; attriNum < attrValue.list().i_size(); ++attriNum)
188 {
189 attriList.push_back(static_cast<uint32_t>(attrValue.list().i(attriNum)));
190 }
191 });
192
193 return attriList;
194}
195
196bool ReadOptionalNodeBoolAttribute(const tensorflow::NodeDef& nodeDef,
197 const std::string& name,
198 bool defaultValue = false)
199{
200 bool attribValue = defaultValue;
201 ReadOptionalNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kB,
202 [&attribValue](const tensorflow::AttrValue& attrValue)
203 {
204 attribValue = attrValue.b();
205 });
206 return attribValue;
207}
208
209tensorflow::DataType ReadMandatoryNodeTypeAttribute(const tensorflow::NodeDef& nodeDef, const std::string& name)
210{
211 tensorflow::DataType attribValue = tensorflow::DT_INVALID;
212 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kType,
213 [&attribValue](const tensorflow::AttrValue& attrValue)
214 {
215 attribValue = attrValue.type();
216 });
217 return attribValue;
218}
219
220TensorInfo PrepareReshape(const TensorInfo& input, const std::vector<int32_t>& targetDims)
221{
222 std::vector<unsigned int> outDims(targetDims.begin(), targetDims.end());
223 const auto stretchDim = std::find(targetDims.begin(), targetDims.end(), -1);
224
225 if (stretchDim != targetDims.end())
226 {
227 if (std::find(std::next(stretchDim), targetDims.end(), -1) != targetDims.end())
228 {
telsoa01c577f2c2018-08-31 09:22:23 +0100229 throw ParseException(
230 boost::str(
231 boost::format(
232 "At most one component of shape can be -1 %1%")
233 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100234 }
235
telsoa01c577f2c2018-08-31 09:22:23 +0100236 auto targetNumElements =
237 boost::numeric_cast<unsigned int>(
238 std::accumulate(targetDims.begin(), targetDims.end(), -1, std::multiplies<int32_t>()));
surmeh01bceff2f2018-03-29 16:29:27 +0100239 auto stretchIndex = static_cast<size_t>(std::distance(targetDims.begin(), stretchDim));
240 outDims[stretchIndex] = input.GetNumElements() / targetNumElements;
241 }
242
243 TensorInfo reshapeInfo = input;
244 reshapeInfo.SetShape(TensorShape{ static_cast<unsigned int>(outDims.size()), outDims.data() });
245
246 return reshapeInfo;
247}
248
telsoa01c577f2c2018-08-31 09:22:23 +0100249// We need the input0Slot to guide the reshape for input1Slot.
saoste01bbd40612018-08-28 15:41:51 +0100250IOutputSlot* AddBroadcastReshapeLayer(IOutputSlot* input0Slot, IOutputSlot* input1Slot, bool isNHWC,
251 INetwork& m_Network, const tensorflow::NodeDef& nodeDef)
surmeh01bceff2f2018-03-29 16:29:27 +0100252{
253 const TensorInfo& input1Info = input1Slot->GetTensorInfo();
254 const TensorInfo inputTensorInfo = input0Slot->GetTensorInfo();
255 const unsigned int matchDim = inputTensorInfo.GetNumDimensions() - (isNHWC ? 1 : 3);
256 std::array<unsigned int, MaxNumOfTensorDimensions> reshapedDimensions;
257 std::fill_n(reshapedDimensions.begin(), inputTensorInfo.GetNumDimensions(), 1);
258 reshapedDimensions[matchDim] = input1Info.GetShape()[0];
259
260 armnn::TensorInfo reshapedInfo = input1Info;
261 reshapedInfo.SetShape(TensorShape{ inputTensorInfo.GetNumDimensions(), reshapedDimensions.data() });
262
263 const std::string reshapeLayerName = "reshape_for-" + nodeDef.name();
264 ReshapeDescriptor reshapeDesc;
265 reshapeDesc.m_TargetShape = reshapedInfo.GetShape();
266 IConnectableLayer* const reshapeLayer = m_Network.AddReshapeLayer(reshapeDesc, reshapeLayerName.c_str());
267
268 input1Slot->Connect(reshapeLayer->GetInputSlot(0));
269 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedInfo);
270
271 input1Slot = &reshapeLayer->GetOutputSlot(0);
272
273 return input1Slot;
274}
275
276OutputId ParseOutputId(const std::string & name)
277{
278 unsigned int outputNum = 0;
279 size_t colonPos = name.find_last_of(":");
280 if (colonPos != std::string::npos)
281 {
282 int n = std::stoi(name.substr(colonPos+1));
283 if (n<0 || n>100)
284 {
telsoa01c577f2c2018-08-31 09:22:23 +0100285 throw ParseException(
286 boost::str(
287 boost::format(
288 "Output tensor id is out of range for %1% %2%")
289 % name
290 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100291 }
292 outputNum = static_cast<unsigned int>(n);
293 }
294 return OutputId(name.substr(0,colonPos),outputNum);
295}
296
telsoa01c577f2c2018-08-31 09:22:23 +0100297#define CHECK_DATA_FORMAT(NODE_DEF, FORMAT, NODE_TYPE) \
298 if( FORMAT != "NHWC" && FORMAT != "NCHW" ) \
299 { \
300 throw ParseException( \
301 boost::str( \
302 boost::format( \
303 "Unsupported data format %1% passed for %2% node %3%. " \
304 "Only NHWC and NCHW supported %4%") \
305 % FORMAT \
306 % NODE_TYPE \
307 % NODE_DEF.name() \
308 % CHECK_LOCATION().AsString())); \
309 }
310
311#define CHECK_PADDING_TYPE(NODE_DEF, PADDING) \
312 if(PADDING != "SAME" && PADDING != "VALID" ) \
313 { \
314 throw ParseException( \
315 boost::str( \
316 boost::format( \
317 "Only 'SAME' and 'VALID' padding supported. Got %1% for %2% %3%") \
318 % PADDING \
319 % NODE_DEF.name() \
320 % CHECK_LOCATION().AsString())); \
321 } \
322
surmeh01bceff2f2018-03-29 16:29:27 +0100323} // namespace
324
325const std::map<std::string, TfParser::OperationParsingFunction> TfParser::ms_OperationNameToParsingFunctions = {
326 { "Const", &TfParser::ParseConst },
327 { "Add", &TfParser::ParseAdd },
Ferran Balaguerfbdad032018-12-28 18:15:24 +0000328 { "AddN", &TfParser::ParseAddN },
surmeh01bceff2f2018-03-29 16:29:27 +0100329 { "BiasAdd", &TfParser::ParseBiasAdd },
330 { "Identity", &TfParser::ParseIdentity },
331 { "Conv2D", &TfParser::ParseConv2D },
332 { "DepthwiseConv2dNative", &TfParser::ParseDepthwiseConv2D },
Conor Kennedyc2130a02018-12-05 11:05:54 +0000333 { "ExpandDims", &TfParser::ParseExpandDims },
surmeh01bceff2f2018-03-29 16:29:27 +0100334 { "FusedBatchNorm", &TfParser::ParseFusedBatchNorm },
FrancisMurtagh94412af2019-01-24 10:53:39 +0000335 { "Gather", &TfParser::ParseGather},
jimfly01a06bf312018-12-18 16:24:51 +0000336 { "Greater", &TfParser::ParseGreater},
surmeh01bceff2f2018-03-29 16:29:27 +0100337 { "ConcatV2", &TfParser::ParseConcat },
338 { "LRN", &TfParser::ParseLrn },
339 { "MatMul", &TfParser::ParseMatMul },
Ferran Balaguer51dd62f2019-01-11 19:29:18 +0000340 { "Mean", &TfParser::ParseMean },
surmeh01bceff2f2018-03-29 16:29:27 +0100341 { "Mul", &TfParser::ParseMul },
342 { "Placeholder", &TfParser::ParsePlaceholder },
saoste01bbd40612018-08-28 15:41:51 +0100343 { "RealDiv", &TfParser::ParseRealDiv },
surmeh01bceff2f2018-03-29 16:29:27 +0100344 { "Relu", &TfParser::ParseRelu },
345 { "Relu6", &TfParser::ParseRelu6 },
346 { "Reshape", &TfParser::ParseReshape },
347 { "ResizeBilinear", &TfParser::ParseResizeBilinear },
Mohamed Nour Abouelseoud7a8892f2019-01-09 14:19:58 +0000348 { "Rsqrt", &TfParser::ParseRsqrt },
surmeh01bceff2f2018-03-29 16:29:27 +0100349 { "Shape", &TfParser::ParseShape },
350 { "Squeeze", &TfParser::ParseSqueeze },
351 { "Sigmoid", &TfParser::ParseSigmoid },
352 { "Softmax", &TfParser::ParseSoftmax },
353 { "Softplus", &TfParser::ParseSoftplus },
Sadik Armagan2ad6cb42018-12-27 11:23:44 +0000354 { "Split", &TfParser::ParseSplit },
surmeh01bceff2f2018-03-29 16:29:27 +0100355 { "Tanh", &TfParser::ParseTanh },
356 { "MaxPool", &TfParser::ParseMaxPool },
357 { "AvgPool", &TfParser::ParseAvgPool },
telsoa01c577f2c2018-08-31 09:22:23 +0100358 { "Maximum", &TfParser::ParseMaximum },
Nattapat Chaimanowong24df8222018-12-04 13:47:02 +0000359 { "Minimum", &TfParser::ParseMinimum },
jimfly0184c70e62018-12-19 13:14:46 +0000360 { "Equal", &TfParser::ParseEqual },
jimfly01f6ba7472018-12-04 10:09:52 +0000361 { "Pad", &TfParser::ParsePad },
narpra016f37f832018-12-21 18:30:00 +0000362 { "Sub", &TfParser::ParseSub }
363};
364
365const std::list<std::string> TfParser::m_ControlInputs = {
366 "Assert"
surmeh01bceff2f2018-03-29 16:29:27 +0100367};
368
369ITfParser* ITfParser::CreateRaw()
370{
371 return new TfParser();
372}
373
374ITfParserPtr ITfParser::Create()
375{
376 return ITfParserPtr(CreateRaw(), &ITfParser::Destroy);
377}
378
379void ITfParser::Destroy(ITfParser* parser)
380{
381 delete parser;
382}
383
384inline void CalculateSamePadding(uint32_t inputSize, uint32_t stride,
385 uint32_t filterSize, bool samePadding,
386 uint32_t* paddingFront, uint32_t* paddingBack) {
387 *paddingFront = 0;
388 *paddingBack = 0;
389
390 if (samePadding) {
391 uint32_t outputSize = (inputSize + stride - 1) / stride;
392 uint32_t temp = (outputSize - 1) * stride + filterSize;
393 if (temp > inputSize) {
394 *paddingFront = (temp - inputSize) / 2;
395 *paddingBack = (temp - inputSize) - *paddingFront;
396 }
397 }
398}
399
400void CalcPadding(uint32_t input, uint32_t kernel, uint32_t stride, uint32_t& outPadHead, uint32_t& outPadTail,
401 bool samePadding)
402{
403 CalculateSamePadding(input, stride, kernel, samePadding, &outPadHead, &outPadTail);
404}
405
406/// An Abstract base class which represents a single tensorflow operation (node)
407/// that has been (potentially partially) converted to Armnn.
408/// It may not yet have been fully converted into actual Armnn layers.
409class ParsedTfOperation
410{
411public:
412 ParsedTfOperation(TfParser* parser, const tensorflow::NodeDef& node)
413 : m_Parser(parser)
414 , m_Node(node)
415 {
416 }
417
418 virtual ~ParsedTfOperation() {};
419
420 const tensorflow::NodeDef& GetNode() const { return m_Node; }
421
422 /// Gets the ArmNN IOutputSlot corresponding to the given output index of the Tensorflow operation.
423 /// This may result in the creation of Armnn layers if this was deferred (e.g. see ParsedConstTfOperation).
424 virtual IOutputSlot& ResolveArmnnOutputSlot(unsigned int tfOutputIndex) = 0;
425
426 /// If this operation is an Identity then this will follow return the 'parent' operation (recursively).
427 virtual ParsedTfOperation* ResolveIdentityOperations()
428 {
429 return this;
430 }
431
432protected:
433 TfParser* m_Parser;
434 const tensorflow::NodeDef& m_Node;
435};
436
437/// An ParsedTfOperation where the Armnn equivalent is a single layer,
438/// with output slots that correspond directly to the Tf node outputs.
439class SingleLayerParsedTfOperation : public ParsedTfOperation
440{
441public:
442 SingleLayerParsedTfOperation(TfParser* parser, const tensorflow::NodeDef& node, IConnectableLayer* layer)
443 : ParsedTfOperation(parser, node)
444 , m_Layer(layer)
445 {
446 }
447
448 IOutputSlot& ResolveArmnnOutputSlot(unsigned int tfOutputIndex) override
449 {
450 BOOST_ASSERT(m_Layer);
telsoa01c577f2c2018-08-31 09:22:23 +0100451 // Assumes one-to-one mapping between Tf and armnn output slots.
surmeh01bceff2f2018-03-29 16:29:27 +0100452 unsigned int armnnOutputSlotIdx = tfOutputIndex;
453 if (armnnOutputSlotIdx >= m_Layer->GetNumOutputSlots())
454 {
455 throw ParseException(
telsoa01c577f2c2018-08-31 09:22:23 +0100456 boost::str(
457 boost::format(
458 "The requested output slot #%1% "
459 "for %2% does not exist %3%")
460 % armnnOutputSlotIdx
461 % m_Layer->GetName()
462 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100463 }
464 return m_Layer->GetOutputSlot(armnnOutputSlotIdx);
465 }
466
467protected:
468 IConnectableLayer* m_Layer;
469};
470
telsoa01c577f2c2018-08-31 09:22:23 +0100471/// A SingleLayerParsedTfOperation for deferred layer creation.
surmeh01bceff2f2018-03-29 16:29:27 +0100472class DeferredSingleLayerParsedTfOperation : public SingleLayerParsedTfOperation
473{
474public:
475 DeferredSingleLayerParsedTfOperation(TfParser* parser, const tensorflow::NodeDef& node)
476 : SingleLayerParsedTfOperation(parser, node, nullptr)
477 {
478 }
479
480 IOutputSlot& ResolveArmnnOutputSlot(unsigned int tfOutputIndex) override
481 {
482 if (!m_Layer)
483 {
484 CreateLayerDeferred();
485 }
486 return SingleLayerParsedTfOperation::ResolveArmnnOutputSlot(tfOutputIndex);
487 }
488
489private:
490 virtual void CreateLayerDeferred() = 0;
491};
492
493
494TfParser::TfParser()
495 : m_Network(nullptr, nullptr)
496{
497}
498
499
500const tensorflow::NodeDef* TfParser::ResolveIdentityNode(const tensorflow::NodeDef* nodeDef)
501{
502 if (nodeDef->op() != "Identity")
503 {
504 return nodeDef;
505 }
506
507 if (nodeDef->input_size() != 1)
508 {
telsoa01c577f2c2018-08-31 09:22:23 +0100509 throw ParseException(
510 boost::str(
511 boost::format(
512 "Identity node should have a single input! %1% has %2% inputs %3%")
513 % nodeDef->name()
514 % nodeDef->input_size()
515 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100516 }
517
518 auto it = m_NodesByName.find(nodeDef->input(0));
519 if (it != m_NodesByName.end())
520 {
521 const tensorflow::NodeDef* inputNode = it->second;
522 return ResolveIdentityNode(inputNode);
523 }
524 else
525 {
telsoa01c577f2c2018-08-31 09:22:23 +0100526 throw ParseException(
527 boost::str(
528 boost::format(
529 "Cannot find what the Identity node %1% is linked to! %2%")
530 % nodeDef->name()
531 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100532 }
533}
534
535std::vector<OutputOfConstNodeDef>
536TfParser::GetTfInputNodes(const tensorflow::NodeDef& nodeDef) const
537{
538 std::vector<OutputOfConstNodeDef> ret;
539
surmeh013537c2c2018-05-18 16:31:43 +0100540 if (nodeDef.op() == "Const")
541 {
542 // For some reason const node can have "Control Inputs". We ignore them for now.
543 return ret;
544 }
545
surmeh01bceff2f2018-03-29 16:29:27 +0100546 ret.reserve(boost::numeric_cast<size_t>(nodeDef.input_size()));
547 for (int j = 0; j < nodeDef.input_size(); ++j)
548 {
549 OutputId outputId = ParseOutputId(nodeDef.input(j));
surmeh013537c2c2018-05-18 16:31:43 +0100550
551 if (nodeDef.input(j)[0] == '^') // I couldn't find a better test for control inputs.
552 {
narpra016f37f832018-12-21 18:30:00 +0000553 // We currently allow Control Input from TensorFlow graph but we ignore them from ArmNN graph.
554 continue;
surmeh013537c2c2018-05-18 16:31:43 +0100555 }
556
surmeh01bceff2f2018-03-29 16:29:27 +0100557 auto inputIt = m_NodesByName.find(outputId.m_IndexedValue);
558 if (inputIt == m_NodesByName.end())
559 {
560 throw ParseException(
telsoa01c577f2c2018-08-31 09:22:23 +0100561 boost::str(
562 boost::format(
563 "Can't find node '%1%', which is listed as an input of '%2%' %3%")
564 % nodeDef.input(j)
565 % nodeDef.name()
566 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100567 }
568 ret.push_back(OutputOfConstNodeDef(inputIt->second,outputId.m_Index));
569 }
570
571 return ret;
572}
573
574std::vector<OutputOfParsedTfOperation>
575TfParser::GetInputParsedTfOperationsChecked(const tensorflow::NodeDef& nodeDef,
576 std::size_t expectedNumInputs)
577{
telsoa01c577f2c2018-08-31 09:22:23 +0100578 // Fetches the tensorflow nodes connected as inputs and validate the size.
surmeh01bceff2f2018-03-29 16:29:27 +0100579 std::vector<OutputOfConstNodeDef> nodes = GetTfInputNodes(nodeDef);
580 const std::size_t numInputs = nodes.size();
581 if (numInputs != expectedNumInputs)
582 {
telsoa01c577f2c2018-08-31 09:22:23 +0100583 throw ParseException(
584 boost::str(
585 boost::format(
586 "Unexpected number of inputs for node %1%. Expected %2%, found %3% %4%")
587 % nodeDef.name()
588 % expectedNumInputs
589 % numInputs
590 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100591 }
telsoa01c577f2c2018-08-31 09:22:23 +0100592 // Fetches the corresponding ParsedTfOperation operations
surmeh01bceff2f2018-03-29 16:29:27 +0100593 std::vector<OutputOfParsedTfOperation> result;
594 for (auto&& node : nodes)
595 {
596 auto it = m_ParsedTfOperations.find(node.m_IndexedValue->name());
597 if (it == m_ParsedTfOperations.end())
598 {
telsoa01c577f2c2018-08-31 09:22:23 +0100599 throw ParseException(
600 boost::str(
601 boost::format(
602 "Node with name '%1%' has not been parsed %2%")
603 % node.m_IndexedValue->name()
604 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100605 }
606 ParsedTfOperation* parsedOp = it->second.get();
607 // Transparently 'skip' any Identity operations. This simplifies the logic inside the ParseXXX() functions.
608 parsedOp = parsedOp->ResolveIdentityOperations();
609 result.push_back(OutputOfParsedTfOperation(parsedOp,node.m_Index));
610 }
611 return result;
612}
613
Ferran Balaguerfbdad032018-12-28 18:15:24 +0000614IConnectableLayer* TfParser::CreateAdditionLayer(
615 const tensorflow::NodeDef& nodeDef,
616 IOutputSlot* input0Slot,
617 IOutputSlot* input1Slot,
618 const std::string& layerName)
619{
620 const TensorInfo& input0Info = input0Slot->GetTensorInfo();
621 const TensorInfo& input1Info = input1Slot->GetTensorInfo();
622
623 const unsigned int input0Dim = input0Info.GetNumDimensions();
624 const unsigned int input1Dim = input1Info.GetNumDimensions();
625 if (input0Dim != input1Dim)
626 {
627 // broadcasting where input0 and input1 have different number of dimensions
628 // is only supported for 1D and 4D tensors pair
629 if (input0Dim == 1 && input1Dim == 4)
630 {
631 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot, true, *m_Network, nodeDef);
632 }
633 else if (input0Dim == 4 && input1Dim == 1)
634 {
635 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, true, *m_Network, nodeDef);
636 }
637 else
638 {
639 throw ParseException(
640 boost::str(
641 boost::format("Unsupported broadcast configuration for %1% operation %2% %3%")
642 % layerName
643 % nodeDef.name()
644 % CHECK_LOCATION().AsString()));
645 }
646 }
647 IConnectableLayer* const layer = m_Network->AddAdditionLayer(layerName.c_str());
648
649 input0Slot->Connect(layer->GetInputSlot(0));
650 input1Slot->Connect(layer->GetInputSlot(1));
651
652 // Ensure the output tensor has the correct dimensions even if a broadcast has been done
653 TensorInfo outputInfo = input0Slot->GetTensorInfo();
654 std::vector<unsigned int> outputShape;
655
656 const TensorShape& input0Shape = input0Slot->GetTensorInfo().GetShape();
657 const TensorShape& input1Shape = input1Slot->GetTensorInfo().GetShape();
658
659 for (unsigned int i = 0; i < input0Shape.GetNumDimensions(); i++)
660 {
661 outputShape.push_back(std::max(input0Shape[i], input1Shape[i]));
662 }
663
664 outputInfo.SetShape(TensorShape(input0Shape.GetNumDimensions(), outputShape.data()));
665 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
666
667 return layer;
668}
669
670IConnectableLayer* TfParser::CreateAdditionLayer(
671 const tensorflow::NodeDef& nodeDef,
672 IConnectableLayer* layerOne,
673 IConnectableLayer* layerTwo,
674 unsigned int numberOfAddition,
675 unsigned long numberOfLayersToConnect,
676 bool isOdd)
677{
678 IOutputSlot* input0Slot = &layerOne->GetOutputSlot(0);
679 IOutputSlot* input1Slot = &layerTwo->GetOutputSlot(0);
680 std::string layerName(nodeDef.name());
681 if (isOdd || numberOfLayersToConnect != 2)
682 {
683 // we are not connecting the final layer
684 layerName.append("_addN_").append(std::to_string(numberOfAddition));
685 }
686 return CreateAdditionLayer(nodeDef, input0Slot, input1Slot, layerName);
687}
688
689IConnectableLayer* TfParser::CreateAdditionLayer(
690 const tensorflow::NodeDef& nodeDef,
691 const OutputOfParsedTfOperation& opOne,
692 const OutputOfParsedTfOperation& opTwo,
693 unsigned int numberOfAddition)
694{
695 IOutputSlot* input0Slot = &opOne.m_IndexedValue->ResolveArmnnOutputSlot(opOne.m_Index);
696 IOutputSlot* input1Slot = &opTwo.m_IndexedValue->ResolveArmnnOutputSlot(opTwo.m_Index);
697 std::string layerName(nodeDef.name());
698 layerName.append("_addN_").append(std::to_string(numberOfAddition));
699 return CreateAdditionLayer(nodeDef, input0Slot, input1Slot, layerName);
700}
701
702IConnectableLayer* TfParser::CreateAdditionLayer(
703 const tensorflow::NodeDef& nodeDef,
704 const OutputOfParsedTfOperation& op,
705 IConnectableLayer* layer)
706{
707 IOutputSlot* input0Slot = &op.m_IndexedValue->ResolveArmnnOutputSlot(op.m_Index);
708 IOutputSlot* input1Slot = &layer->GetOutputSlot(0);
709 return CreateAdditionLayer(nodeDef, input0Slot, input1Slot, nodeDef.name());
710}
711
712ParsedTfOperationPtr TfParser::ParseAddN(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
713{
714 uint32_t numberOfInputs = ReadMandatoryNodeUint32Attribute(nodeDef, "N");
715 if (numberOfInputs < 2)
716 {
717 // should never happen
718 throw ParseException(
719 boost::str(
720 boost::format(
721 "AddN Node with name '%1%' has less than two (%2) inputs %3%")
722 % nodeDef.name()
723 % std::to_string(numberOfInputs)
724 % CHECK_LOCATION().AsString()));
725 }
726 else if (numberOfInputs == 2)
727 {
728 //this is the same as a simple Add operation
729 return AddAdditionLayer(nodeDef, false);
730 }
731 else
732 {
733 // build a binary tree of Add layers and return the final Add as the return from the function
734 // if we have an odd number of inputs then the final Add will consist of a layer connecting to an
735 // OutputOfParsedTfOperation, otherwise it will be two layers being added together
736 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, numberOfInputs);
737 unsigned int numberOfAdditions = 0;
738 std::vector<IConnectableLayer*> layers;
739 // NOTE: at this point we will have a minimum of three inputs
740 for (unsigned int i = 0; i < numberOfInputs; ++i)
741 {
742 // every time i is odd we have two inputs to process.
743 bool onSecondItem = i % 2;
744 if (onSecondItem)
745 {
746 ++numberOfAdditions;
747 IConnectableLayer* newLayer = CreateAdditionLayer(
748 nodeDef, inputs[ i - 1], inputs[i], numberOfAdditions);
749 layers.push_back(newLayer);
750 }
751 }
752
753 std::vector<IConnectableLayer*> layersToConnect(layers);
754 unsigned long numberOfLayersToConnect = layersToConnect.size();
755 bool isOdd = numberOfInputs % 2;
756
757 while (numberOfLayersToConnect > 1)
758 {
759 layers.clear();
760 for (unsigned long i = 0; i < numberOfLayersToConnect; ++i) {
761 bool onSecondItem = i % 2;
762 if (onSecondItem) {
763 ++numberOfAdditions;
764 IConnectableLayer* newLayer = CreateAdditionLayer(
765 nodeDef,
766 layersToConnect[i - 1],
767 layersToConnect[i],
768 numberOfAdditions,
769 numberOfLayersToConnect,
770 isOdd);
771 layers.push_back(newLayer);
772 }
773 }
774 //OK... need to go again... maybe
775 layersToConnect = layers;
776 numberOfLayersToConnect = layersToConnect.size();
777 }
778 IConnectableLayer* finalLayer = layersToConnect[0];
779 // if we had an odd number of inputs we need to connect the final layer to the
780 // last OutputOfParsedTfOperation in order to create the last Add layer we will
781 // be handing back.
782 if (isOdd)
783 {
784 // connect the final layer to the last op
785 finalLayer = CreateAdditionLayer(nodeDef, inputs[numberOfInputs - 1], finalLayer);
786 }
787 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, finalLayer);
788 }
789}
790
surmeh01bceff2f2018-03-29 16:29:27 +0100791ParsedTfOperationPtr TfParser::ParseAdd(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
792{
793 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
794
telsoa01c577f2c2018-08-31 09:22:23 +0100795 // If one of the inputs is a MatMul and the other is a const, then we handle both nodes
796 // together as FullyConnected.
surmeh01bceff2f2018-03-29 16:29:27 +0100797 if (inputs[0].m_IndexedValue->GetNode().op() == "MatMul" &&
798 HasParsedConstTensor<float>(inputs[1].m_IndexedValue->GetNode().name()))
799 {
800 IConnectableLayer* layer =
801 AddFullyConnectedLayer(inputs[0].m_IndexedValue->GetNode(),
802 &nodeDef,nodeDef.name().c_str());
803 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
804 }
805 else if (HasParsedConstTensor<float>(inputs[0].m_IndexedValue->GetNode().name()) &&
806 inputs[1].m_IndexedValue->GetNode().op() == "MatMul")
807 {
808 IConnectableLayer* layer =
809 AddFullyConnectedLayer(inputs[1].m_IndexedValue->GetNode(),
810 &nodeDef,nodeDef.name().c_str());
811 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
812 }
813 else
814 {
telsoa01c577f2c2018-08-31 09:22:23 +0100815 // Otherwise it's just a regular addition.
surmeh01bceff2f2018-03-29 16:29:27 +0100816 return AddAdditionLayer(nodeDef);
817 }
818}
819
820ParsedTfOperationPtr TfParser::ParseBiasAdd(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
821{
822 return AddAdditionLayer(nodeDef, true);
823}
824
825/// An ParsedTfOperation which forwards to another (used for Identity nodes).
826class ParsedIdentityTfOperation : public ParsedTfOperation
827{
828public:
829 ParsedIdentityTfOperation(TfParser* parser, const tensorflow::NodeDef& node, ParsedTfOperation* representative)
830 : ParsedTfOperation(parser, node)
831 , m_Representative(representative)
832 {
833 }
834
835 virtual IOutputSlot& ResolveArmnnOutputSlot(unsigned int tfOutputIndex) override
836 {
837 BOOST_ASSERT(m_Representative);
838 return m_Representative->ResolveArmnnOutputSlot(tfOutputIndex);
839 }
840
841 virtual ParsedTfOperation* ResolveIdentityOperations() override
842 {
843 return m_Representative->ResolveIdentityOperations();
844 }
845
846private:
847 ParsedTfOperation* m_Representative;
848};
849
850ParsedTfOperationPtr TfParser::ParseIdentity(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
851{
852 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
853 // Any requests for the output slots of this node should be forwarded to the node connected as input.
854 return std::make_unique<ParsedIdentityTfOperation>(this, nodeDef, inputs[0].m_IndexedValue);
855}
856
857/// An ParsedTfOperation for a Const node.
858/// Creation of the armnn ConstLayer is deferred until it is actually needed, because Const nodes are mostly used
859/// for weight inputs to MatMul/Conv2D nodes and in these cases armnn doesn't need a ConstLayer.
860template <typename T>
861class ParsedConstTfOperation : public DeferredSingleLayerParsedTfOperation
862{
863public:
864 ParsedConstTfOperation(TfParser* parser, const tensorflow::NodeDef& node,
865 const T* tensorData, const TensorInfo& tensorInfo)
866 : DeferredSingleLayerParsedTfOperation(parser, node),
867 m_Storage(tensorData, tensorData + tensorInfo.GetNumElements()),
868 m_TensorInfo(tensorInfo)
869 {
Nattapat Chaimanowong649dd952019-01-22 16:10:44 +0000870 BOOST_ASSERT(GetDataTypeSize(tensorInfo.GetDataType()) == sizeof(T));
surmeh01bceff2f2018-03-29 16:29:27 +0100871 }
872
873 void CreateLayerDeferred() override
874 {
875 BOOST_ASSERT(m_Layer == nullptr);
876 m_Layer = m_Parser->m_Network->AddConstantLayer(ConstTensor(m_TensorInfo, m_Storage), m_Node.name().c_str());
877 m_Layer->GetOutputSlot(0).SetTensorInfo(m_TensorInfo);
878 }
879
Matteo Martincigh482ca852018-12-12 09:20:55 +0000880 ConstTensor GetConstTensor(std::vector<T>& outputTensorData) const
surmeh01bceff2f2018-03-29 16:29:27 +0100881 {
surmeh01bceff2f2018-03-29 16:29:27 +0100882 outputTensorData.resize(m_TensorInfo.GetNumElements());
883
Matteo Martincigh482ca852018-12-12 09:20:55 +0000884 memcpy(outputTensorData.data(), m_Storage.data(), m_TensorInfo.GetNumBytes());
885
telsoa01c577f2c2018-08-31 09:22:23 +0100886 // Updates the result to point to the user provided storage.
Matteo Martincigh482ca852018-12-12 09:20:55 +0000887 ConstTensor constTensor(m_TensorInfo, outputTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +0100888 return constTensor;
889 }
890
Matteo Martincigh46315822018-11-28 16:22:36 +0000891 const T* GetStorage() const
892 {
893 return m_Storage.data();
894 }
895
896 const TensorInfo& GetTensorInfo() const
897 {
898 return m_TensorInfo;
899 }
900
surmeh01bceff2f2018-03-29 16:29:27 +0100901private:
902 ///< Manages the lifetime of the tensor data.
903 std::vector<T> m_Storage;
904 ///< Describes the layout of the tensor and points to the data in m_Storage.
905 TensorInfo m_TensorInfo;
906};
907
telsoa01c577f2c2018-08-31 09:22:23 +0100908DataType ConvertTfTensorDataType(const tensorflow::DataType tfDataType,
909 const tensorflow::NodeDef& nodeDef)
surmeh01bceff2f2018-03-29 16:29:27 +0100910{
911 switch (tfDataType)
912 {
913 case tensorflow::DT_FLOAT:
914 return DataType::Float32;
915 break;
916 case tensorflow::DT_INT32:
917 return DataType::Signed32;
918 break;
919 default:
telsoa01c577f2c2018-08-31 09:22:23 +0100920 throw ParseException(
921 boost::str(
922 boost::format(
923 "Unknown DataType %1% for node %2% %3%")
924 % tensorflow::DataType_Name(tfDataType)
925 % nodeDef.name()
926 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +0100927 }
928}
929
930struct ParseTfTensorValueList
931{
932 template<typename DataType>
933 static void Parse(
934 const tensorflow::TensorProto& tfTensor,
935 unsigned int dstElements,
936 std::vector<int8_t>& outputData);
937
938 template <typename DataType>
939 static void ReadData(const void* srcData, unsigned int numSrcElements,
940 std::vector<int8_t>& dstData, unsigned int numDstElements)
941 {
telsoa01c577f2c2018-08-31 09:22:23 +0100942 // If there are no entries in the list, perform no action.
surmeh01bceff2f2018-03-29 16:29:27 +0100943 if (numSrcElements == 0)
944 {
945 return;
946 }
947
telsoa01c577f2c2018-08-31 09:22:23 +0100948 // If no size was provided, use the length of the value list.
surmeh01bceff2f2018-03-29 16:29:27 +0100949 if (numDstElements == 0)
950 {
951 numDstElements = numSrcElements;
952 }
953
telsoa01c577f2c2018-08-31 09:22:23 +0100954 // Allocates memory.
surmeh01bceff2f2018-03-29 16:29:27 +0100955 dstData.resize(std::max(numSrcElements, numDstElements) * sizeof(DataType));
956
957 const DataType* srcTensor = reinterpret_cast<const DataType*>(srcData);
958 DataType* dstTensor = reinterpret_cast<DataType*>(dstData.data());
959
telsoa01c577f2c2018-08-31 09:22:23 +0100960 // Copies the value list entries into the destination.
surmeh01bceff2f2018-03-29 16:29:27 +0100961 std::copy(srcTensor, srcTensor + numSrcElements, dstTensor);
962
963 if (numDstElements > numSrcElements)
964 {
telsoa01c577f2c2018-08-31 09:22:23 +0100965 // Uses the last element in the list to fill the remaining entries.
surmeh01bceff2f2018-03-29 16:29:27 +0100966 std::fill(dstTensor + numSrcElements, dstTensor + numDstElements, srcTensor[numSrcElements - 1]);
967 }
968 }
969
970};
971
972template <>
973void ParseTfTensorValueList::Parse<float>(const tensorflow::TensorProto& tfTensor,
974 unsigned int dstElements, std::vector<int8_t>& outputData)
975{
976 ReadData<float>(tfTensor.float_val().data(), static_cast<unsigned int>(tfTensor.float_val_size()),
977 outputData, dstElements);
978}
979
980template <>
981void ParseTfTensorValueList::Parse<int32_t>(const tensorflow::TensorProto& tfTensor,
982 unsigned int dstElements, std::vector<int8_t>& outputData)
983{
984 ReadData<int32_t>(tfTensor.int_val().data(), static_cast<unsigned int>(tfTensor.int_val_size()),
985 outputData, dstElements);
986}
987
988template <template<typename> class OperatorType, typename T = int8_t>
989struct MakeTfOperation
990{
991 template<typename DataType, class... Args>
992 inline static std::unique_ptr<OperatorType<DataType>> Parse(TfParser* parser, const tensorflow::NodeDef& node,
993 Args&&... args)
994 {
995 return std::make_unique<OperatorType<DataType>>(parser, node, std::forward<Args>(args)...);
996 }
997};
998
999template <>
1000struct MakeTfOperation<ParsedConstTfOperation>
1001{
1002 template<typename DataType, class... Args>
1003 inline static std::unique_ptr<ParsedConstTfOperation<DataType>> Parse(TfParser* parser,
1004 const tensorflow::NodeDef& node, const std::vector<int8_t>& tensorData, const TensorInfo& tensorInfo)
1005 {
1006 return std::make_unique<ParsedConstTfOperation<DataType>>(parser, node,
1007 reinterpret_cast<const DataType*>(tensorData.data()), tensorInfo);
1008 }
1009};
1010
1011template <class FuncType>
1012struct InvokeParseFunction
1013{
1014 template<class ResType, class... Args>
1015 inline static ResType Result(DataType dataType, Args&&... args)
1016 {
1017 if (dataType == DataType::Float32)
1018 {
1019 return FuncType::template Parse<float>(std::forward<Args>(args)...);
1020 }
1021 else if (dataType == DataType::Signed32)
1022 {
1023 return FuncType::template Parse<int32_t>(std::forward<Args>(args)...);
1024 }
1025
1026 return ResType();
1027 }
1028
1029 template<class... Args>
1030 inline static void Result(DataType dataType, Args&&... args)
1031 {
1032 if (dataType == DataType::Float32)
1033 {
1034 FuncType::template Parse<float>(std::forward<Args>(args)...);
1035 }
1036 else if (dataType == DataType::Signed32)
1037 {
1038 FuncType::template Parse<int32_t>(std::forward<Args>(args)...);
1039 }
1040 }
1041};
1042
1043ParsedTfOperationPtr TfParser::ParseConst(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
1044{
1045 BOOST_ASSERT(nodeDef.op() == "Const");
1046
1047 if (nodeDef.attr().count("value") == 0)
1048 {
telsoa01c577f2c2018-08-31 09:22:23 +01001049 throw ParseException(
1050 boost::str(
1051 boost::format(
1052 "Value not found for Const node - %1% %2%")
1053 % nodeDef.name()
1054 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001055 }
1056
1057 const tensorflow::TensorProto& tfTensor = nodeDef.attr().at("value").tensor();
1058 const tensorflow::TensorShapeProto& tfTensorShape = tfTensor.tensor_shape();
1059 const tensorflow::DataType tfDataType = ReadMandatoryNodeTypeAttribute(nodeDef, "dtype");
1060
1061 const auto GetDimensionSize = [](auto& d) { return d.size(); };
1062
1063 std::vector<unsigned int> dimensionSizes;
1064 std::transform(tfTensorShape.dim().begin(), tfTensorShape.dim().end(),
1065 std::back_inserter(dimensionSizes), GetDimensionSize);
1066
telsoa01c577f2c2018-08-31 09:22:23 +01001067 // Calculates number of elements.
1068 const DataType dataType = ConvertTfTensorDataType(tfDataType, nodeDef);
surmeh01bceff2f2018-03-29 16:29:27 +01001069 unsigned int numElements = 0U;
1070
1071 if (!dimensionSizes.empty())
1072 {
1073 numElements = std::accumulate(dimensionSizes.begin(), dimensionSizes.end(),
1074 1U, std::multiplies<unsigned int>());
1075 }
1076
1077 std::vector<int8_t> tensorData;
1078
telsoa01c577f2c2018-08-31 09:22:23 +01001079 // Get tensor data from the list of values attribute.
surmeh01bceff2f2018-03-29 16:29:27 +01001080 if (tfTensor.tensor_content().empty())
1081 {
1082 InvokeParseFunction<ParseTfTensorValueList>::Result<void>(dataType, tfTensor, numElements, tensorData);
1083
1084 // 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 +01001085 // tensor of the provided number of elements.
surmeh01bceff2f2018-03-29 16:29:27 +01001086 if (numElements == 0)
1087 {
telsoa01c577f2c2018-08-31 09:22:23 +01001088 const unsigned int tfNumElements =
1089 static_cast<unsigned int>(tensorData.size()) / GetDataTypeSize(dataType);
surmeh01bceff2f2018-03-29 16:29:27 +01001090 dimensionSizes.push_back(tfNumElements);
1091 }
1092 }
telsoa01c577f2c2018-08-31 09:22:23 +01001093 // Gets tensor data from tensor content attribute.
surmeh01bceff2f2018-03-29 16:29:27 +01001094 else
1095 {
1096 tensorData.assign(tfTensor.tensor_content().begin(), tfTensor.tensor_content().end());
1097
telsoa01c577f2c2018-08-31 09:22:23 +01001098 // Checks if a tensor shape is defined for the tensor content.
surmeh01bceff2f2018-03-29 16:29:27 +01001099 if (numElements == 0)
1100 {
telsoa01c577f2c2018-08-31 09:22:23 +01001101 throw ParseException(
1102 boost::str(
1103 boost::format(
1104 "No tensor shape found for Const node - %1% %2%")
1105 % nodeDef.name()
1106 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001107 }
1108 }
1109
telsoa01c577f2c2018-08-31 09:22:23 +01001110 // Const node requires at least a list of values or a content attribute.
surmeh01bceff2f2018-03-29 16:29:27 +01001111 if (tensorData.empty())
1112 {
telsoa01c577f2c2018-08-31 09:22:23 +01001113 throw ParseException(
1114 boost::str(
1115 boost::format(
1116 "No tensor data found for Const node - %1% %2%")
1117 % nodeDef.name()
1118 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001119 }
1120
telsoa01c577f2c2018-08-31 09:22:23 +01001121 const TensorInfo tensorInfo(static_cast<unsigned int>(dimensionSizes.size()),
1122 dimensionSizes.data(),
1123 dataType);
surmeh01bceff2f2018-03-29 16:29:27 +01001124
1125 // If we have a list of values, then the length of the list must be
telsoa01c577f2c2018-08-31 09:22:23 +01001126 // less than or equal to the number of elements implied by the shape argument.
surmeh01bceff2f2018-03-29 16:29:27 +01001127 if (tensorData.size() > tensorInfo.GetNumBytes())
1128 {
telsoa01c577f2c2018-08-31 09:22:23 +01001129 throw ParseException(
1130 boost::str(
1131 boost::format(
1132 "Number of elements (%1%) should be less than or equal "
1133 "to the number of elements implied by the shape argument (%2%) for Const node - %3% %4%")
1134 % (tensorData.size() / GetDataTypeSize(dataType))
1135 % tensorInfo.GetNumElements()
1136 % nodeDef.name()
1137 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001138 }
1139
1140 return InvokeParseFunction<MakeTfOperation<ParsedConstTfOperation>>::Result<ParsedTfOperationPtr>(
1141 dataType, this, nodeDef, tensorData, tensorInfo);
1142}
1143
1144template<typename Type>
1145bool TfParser::HasParsedConstTensor(const std::string & nodeName) const
1146{
1147 auto it = m_ParsedTfOperations.find(nodeName);
jimfly01f6ba7472018-12-04 10:09:52 +00001148 if (it == m_ParsedTfOperations.end())
surmeh01bceff2f2018-03-29 16:29:27 +01001149 {
1150 return false;
1151 }
jimfly01f6ba7472018-12-04 10:09:52 +00001152 return dynamic_cast<ParsedConstTfOperation<Type>*>(it->second.get()) != nullptr;
1153}
1154
1155template<typename Type>
1156bool TfParser::HasParsedConstTensor(ParsedTfOperation* parsedTfOpPtr) const
1157{
1158 return dynamic_cast<ParsedConstTfOperation<Type>*>(parsedTfOpPtr) != nullptr;
surmeh01bceff2f2018-03-29 16:29:27 +01001159}
1160
1161ParsedTfOperationPtr TfParser::ParseConv2D(const tensorflow::NodeDef& nodeDef,
1162 const tensorflow::GraphDef& graphDef)
1163{
1164 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
1165 IOutputSlot& inputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1166 TensorInfo inputTensorInfo = inputSlot.GetTensorInfo();
1167
1168 if (!HasParsedConstTensor<float>(inputs[1].m_IndexedValue->GetNode().name()))
1169 {
telsoa01c577f2c2018-08-31 09:22:23 +01001170 throw ParseException(
1171 boost::str(
1172 boost::format(
1173 "ArmNN only supports Convolution layers with constant weights for %1%, input %2% %3%")
1174 % nodeDef.name()
1175 % inputs[1].m_IndexedValue->GetNode().name()
1176 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001177 }
1178 ParsedConstTfOperation<float>* weightNode =
1179 boost::polymorphic_downcast<ParsedConstTfOperation<float> *>(inputs[1].m_IndexedValue);
1180
1181 std::string paddingString = ReadMandatoryNodeStringAttribute(nodeDef, "padding");
1182 std::string dataFormat = ReadMandatoryNodeStringAttribute(nodeDef, "data_format");
1183 std::vector<uint32_t> strides = ReadMandatoryNodeUint32ListAttribute(nodeDef, "strides");
1184
telsoa01c577f2c2018-08-31 09:22:23 +01001185 // Read the dilations, if present - only [1,1,1,1] (the default) is supported.
surmeh01bceff2f2018-03-29 16:29:27 +01001186 std::vector<uint32_t> dilations = ReadOptionalNodeUint32ListAttribute(nodeDef, "dilations");
1187 if (!dilations.empty())
1188 {
1189 for (auto dilation : dilations)
1190 {
1191 if (dilation != 1u)
1192 {
telsoa01c577f2c2018-08-31 09:22:23 +01001193 throw ParseException(
1194 boost::str(
1195 boost::format(
1196 "ArmNN only supports Convolution layers with dilations [1,1,1,1] for %1% %2%")
1197 % nodeDef.name()
1198 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001199 }
1200 }
1201 }
1202
1203 Convolution2dDescriptor desc;
1204 desc.m_BiasEnabled = false;
1205
telsoa01c577f2c2018-08-31 09:22:23 +01001206 CHECK_DATA_FORMAT(nodeDef, dataFormat, "Conv2D");
1207
Matteo Martincigh46315822018-11-28 16:22:36 +00001208 DataLayout dataLayout = dataFormat == "NHWC" ? DataLayout::NHWC : DataLayout::NCHW;
surmeh01bceff2f2018-03-29 16:29:27 +01001209
Matteo Martincigh46315822018-11-28 16:22:36 +00001210 desc.m_DataLayout = dataLayout;
surmeh01bceff2f2018-03-29 16:29:27 +01001211
Matteo Martincigh46315822018-11-28 16:22:36 +00001212 DataLayoutIndexed dataLayoutIndexed(dataLayout);
surmeh01bceff2f2018-03-29 16:29:27 +01001213
Matteo Martincigh46315822018-11-28 16:22:36 +00001214 desc.m_StrideX = strides[dataLayoutIndexed.GetWidthIndex()];
1215 desc.m_StrideY = strides[dataLayoutIndexed.GetHeightIndex()];
surmeh01bceff2f2018-03-29 16:29:27 +01001216
Matteo Martincigh46315822018-11-28 16:22:36 +00001217 uint32_t inputHeight = inputTensorInfo.GetShape()[dataLayoutIndexed.GetHeightIndex()];
1218 uint32_t inputWidth = inputTensorInfo.GetShape()[dataLayoutIndexed.GetWidthIndex()];
1219
1220 // Mappings from TensorFlow filter tensors to the ArmNN filter tensors.
1221 // Tensorflow weights are [H, W, In, Out].
1222 // ArmNN weights have to be [Out, H, W, In] when the data layout is NHWC,
1223 // and [Out, In, H, W] when the data layout is NCHW.
1224 PermutationVector permutationVector =
1225 dataLayout == DataLayout::NHWC ?
1226 std::initializer_list<unsigned int>{ 1, 2, 3, 0 } : // NHWC: [H, W, In, Out] -> [Out, H, W, In]
1227 std::initializer_list<unsigned int>{ 2, 3, 1, 0 }; // NCHW: [H, W, In, Out] -> [Out, In, H, W]
1228
1229 // Swizzle the tensor using the given permutation vector.
1230 const TensorInfo& weightTensorInfo = weightNode->GetTensorInfo();
1231 const TensorInfo weightTensorSwizzledInfo = armnnUtils::Permuted(weightTensorInfo, permutationVector);
1232
1233 // Swizzles the content of the tensor's permanent storage into a local storage.
1234 std::vector<float> weightTensorSwizzledData(weightTensorInfo.GetNumElements());
1235 armnnUtils::Permute(weightTensorSwizzledInfo.GetShape(), permutationVector,
Matteo Martincighd5b9e642019-01-04 18:01:21 +00001236 weightNode->GetStorage(), weightTensorSwizzledData.data(), sizeof(float));
Matteo Martincigh46315822018-11-28 16:22:36 +00001237
1238 // Create a weight tensor with the newly swizzled data.
1239 ConstTensor weightTensor(weightTensorSwizzledInfo, weightTensorSwizzledData);
1240
1241 uint32_t weightHeight = weightTensor.GetShape()[dataLayoutIndexed.GetHeightIndex()];
1242 uint32_t weightWidth = weightTensor.GetShape()[dataLayoutIndexed.GetWidthIndex()];
surmeh01bceff2f2018-03-29 16:29:27 +01001243
1244 bool padding = false;
1245 TensorInfo outputInfo;
Matteo Martincigh46315822018-11-28 16:22:36 +00001246 unsigned int outputHeight = 0;
1247 unsigned int outputWidth = 0;
telsoa01c577f2c2018-08-31 09:22:23 +01001248
1249 CHECK_PADDING_TYPE(nodeDef, paddingString);
1250
surmeh01bceff2f2018-03-29 16:29:27 +01001251 if (paddingString == "SAME")
1252 {
1253 padding = true;
Matteo Martincigh46315822018-11-28 16:22:36 +00001254
1255 outputHeight = static_cast<uint32_t>(ceil(static_cast<float>(inputHeight) /
1256 static_cast<float>(desc.m_StrideY)));
1257 outputWidth = static_cast<uint32_t>(ceil(static_cast<float>(inputWidth) /
1258 static_cast<float>(desc.m_StrideX)));
surmeh01bceff2f2018-03-29 16:29:27 +01001259 }
1260 else if (paddingString == "VALID")
1261 {
1262 padding = false;
Matteo Martincigh46315822018-11-28 16:22:36 +00001263
1264 outputHeight = static_cast<uint32_t>(ceil(static_cast<float>(inputHeight - weightHeight + 1) /
1265 static_cast<float>(desc.m_StrideY)));
1266 outputWidth = static_cast<uint32_t>(ceil(static_cast<float>(inputWidth - weightWidth + 1) /
1267 static_cast<float>(desc.m_StrideX)));
1268 }
1269
1270 switch (dataLayout)
1271 {
1272 case DataLayout::NHWC:
1273 outputInfo = TensorInfo({ inputTensorInfo.GetShape()[0],
1274 outputHeight,
1275 outputWidth,
1276 weightTensor.GetShape()[0] },
1277 DataType::Float32);
1278 break;
1279 case DataLayout::NCHW:
1280 default:
surmeh01bceff2f2018-03-29 16:29:27 +01001281 outputInfo = TensorInfo({ inputTensorInfo.GetShape()[0],
1282 weightTensor.GetShape()[0],
Matteo Martincigh46315822018-11-28 16:22:36 +00001283 outputHeight,
1284 outputWidth },
1285 DataType::Float32);
1286 break;
surmeh01bceff2f2018-03-29 16:29:27 +01001287 }
surmeh01bceff2f2018-03-29 16:29:27 +01001288
1289 CalcPadding(inputHeight, weightHeight, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, padding);
1290 CalcPadding(inputWidth, weightWidth, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, padding);
1291
1292 IConnectableLayer* layer = m_Network->AddConvolution2dLayer(desc, weightTensor, nodeDef.name().c_str());
1293 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
Matteo Martincigh46315822018-11-28 16:22:36 +00001294 inputSlot.Connect(layer->GetInputSlot(0));
surmeh01bceff2f2018-03-29 16:29:27 +01001295
1296 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
1297}
1298
1299ParsedTfOperationPtr TfParser::ParseDepthwiseConv2D(const tensorflow::NodeDef& nodeDef,
telsoa01c577f2c2018-08-31 09:22:23 +01001300 const tensorflow::GraphDef& graphDef)
surmeh01bceff2f2018-03-29 16:29:27 +01001301{
1302 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
1303 IOutputSlot& inputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1304 TensorInfo inputTensorInfo = inputSlot.GetTensorInfo();
1305
1306 if (!HasParsedConstTensor<float>(inputs[1].m_IndexedValue->GetNode().name()))
1307 {
telsoa01c577f2c2018-08-31 09:22:23 +01001308 throw ParseException(
1309 boost::str(
1310 boost::format(
1311 "ArmNN only supports Depthwise Convolution layer with constant weights. "
1312 "Non const input found %1% for node %2% %3%")
1313 % inputs[1].m_IndexedValue->GetNode().name()
1314 % nodeDef.name()
1315 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001316 }
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001317
surmeh01bceff2f2018-03-29 16:29:27 +01001318 ParsedConstTfOperation<float>* weightNode =
1319 boost::polymorphic_downcast<ParsedConstTfOperation<float> *>(inputs[1].m_IndexedValue);
1320
surmeh01bceff2f2018-03-29 16:29:27 +01001321 std::string paddingString = ReadMandatoryNodeStringAttribute(nodeDef, "padding");
1322 std::string dataFormat = ReadMandatoryNodeStringAttribute(nodeDef, "data_format");
1323 std::vector<uint32_t> strides = ReadMandatoryNodeUint32ListAttribute(nodeDef, "strides");
1324
1325 DepthwiseConvolution2dDescriptor desc;
1326 desc.m_BiasEnabled = false;
1327
telsoa01c577f2c2018-08-31 09:22:23 +01001328 CHECK_DATA_FORMAT(nodeDef, dataFormat, "DepthwiseConv2dNative");
1329
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001330 DataLayout dataLayout = dataFormat == "NHWC" ? DataLayout::NHWC : DataLayout::NCHW;
surmeh01bceff2f2018-03-29 16:29:27 +01001331
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001332 desc.m_DataLayout = dataLayout;
surmeh01bceff2f2018-03-29 16:29:27 +01001333
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001334 DataLayoutIndexed dataLayoutIndexed(dataLayout);
surmeh01bceff2f2018-03-29 16:29:27 +01001335
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001336 desc.m_StrideX = strides[dataLayoutIndexed.GetWidthIndex()];
1337 desc.m_StrideY = strides[dataLayoutIndexed.GetHeightIndex()];
surmeh01bceff2f2018-03-29 16:29:27 +01001338
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001339 uint32_t inputHeight = inputTensorInfo.GetShape()[dataLayoutIndexed.GetHeightIndex()];
1340 uint32_t inputWidth = inputTensorInfo.GetShape()[dataLayoutIndexed.GetWidthIndex()];
1341
1342 // Mappings from TensorFlow filter tensors to the ArmNN filter tensors.
Matteo Martincigh747ef822018-12-18 09:26:39 +00001343 // Tensorflow weights come in the format [H, W, I, M].
1344 // ArmNN weights have to be [M, I, H, W].
1345 PermutationVector permutationVector{ 2, 3, 1, 0 }; // [H, W, I, M] -> [M, I, H, W]
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001346
1347 // Swizzle the tensor using the given permutation vector.
1348 const TensorInfo& weightTensorInfo = weightNode->GetTensorInfo();
1349 const TensorInfo weightTensorSwizzledInfo = armnnUtils::Permuted(weightTensorInfo, permutationVector);
1350
1351 // Swizzles the content of the tensor's permanent storage into a local storage.
1352 std::vector<float> weightTensorSwizzledData(weightTensorInfo.GetNumElements());
1353 armnnUtils::Permute(weightTensorSwizzledInfo.GetShape(), permutationVector,
Matteo Martincighd5b9e642019-01-04 18:01:21 +00001354 weightNode->GetStorage(), weightTensorSwizzledData.data(), sizeof(float));
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001355
1356 // Create a weight tensor with the newly swizzled data.
1357 ConstTensor weightTensor(weightTensorSwizzledInfo, weightTensorSwizzledData);
1358
Matteo Martincigh747ef822018-12-18 09:26:39 +00001359 uint32_t weightHeight = weightTensor.GetShape()[2];
1360 uint32_t weightWidth = weightTensor.GetShape()[3];
surmeh01bceff2f2018-03-29 16:29:27 +01001361
1362 bool padding = false;
1363 TensorInfo outputInfo;
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001364 unsigned int outputHeight = 0;
1365 unsigned int outputWidth = 0;
telsoa01c577f2c2018-08-31 09:22:23 +01001366
1367 CHECK_PADDING_TYPE(nodeDef, paddingString);
1368
surmeh01bceff2f2018-03-29 16:29:27 +01001369 if (paddingString == "SAME")
1370 {
1371 padding = true;
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001372
1373 outputHeight = static_cast<uint32_t>(ceil(static_cast<float>(inputHeight) /
1374 static_cast<float>(desc.m_StrideY)));
1375 outputWidth = static_cast<uint32_t>(ceil(static_cast<float>(inputWidth) /
1376 static_cast<float>(desc.m_StrideX)));
surmeh01bceff2f2018-03-29 16:29:27 +01001377 }
1378 else if (paddingString == "VALID")
1379 {
1380 padding = false;
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001381
1382 outputHeight = static_cast<uint32_t>(ceil(static_cast<float>(inputHeight - weightHeight + 1) /
1383 static_cast<float>(desc.m_StrideY)));
1384 outputWidth = static_cast<uint32_t>(ceil(static_cast<float>(inputWidth - weightWidth + 1) /
1385 static_cast<float>(desc.m_StrideX)));
1386 }
1387
1388 switch (dataLayout)
1389 {
1390 case DataLayout::NHWC:
1391 outputInfo = TensorInfo({ inputTensorInfo.GetShape()[0],
1392 outputHeight,
1393 outputWidth,
Matteo Martincigh747ef822018-12-18 09:26:39 +00001394 weightTensor.GetShape()[0] * weightTensor.GetShape()[1]},
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001395 DataType::Float32);
1396 break;
1397 case DataLayout::NCHW:
1398 default:
1399 outputInfo = TensorInfo({ inputTensorInfo.GetShape()[0],
1400 weightTensor.GetShape()[0] * weightTensor.GetShape()[1],
1401 outputHeight,
1402 outputWidth },
1403 DataType::Float32);
1404 break;
surmeh01bceff2f2018-03-29 16:29:27 +01001405 }
surmeh01bceff2f2018-03-29 16:29:27 +01001406
1407 CalcPadding(inputHeight, weightHeight, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, padding);
1408 CalcPadding(inputWidth, weightWidth, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, padding);
1409
1410 IConnectableLayer* layer = m_Network->AddDepthwiseConvolution2dLayer(desc, weightTensor, nodeDef.name().c_str());
1411 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
Ferran Balaguer6a669d72018-12-11 10:29:05 +00001412 inputSlot.Connect(layer->GetInputSlot(0));
surmeh01bceff2f2018-03-29 16:29:27 +01001413
1414 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
1415}
1416
Conor Kennedyc2130a02018-12-05 11:05:54 +00001417TensorInfo OutputShapeOfExpandDims(const tensorflow::NodeDef& nodeDef, TensorInfo inputTensorInfo)
1418{
1419 BOOST_ASSERT(nodeDef.op() == "ExpandDims");
1420
1421 if (inputTensorInfo.GetNumDimensions() > 4) {
1422 throw ParseException(
1423 boost::str(
1424 boost::format(
1425 "Unsupported number of dimensions: %1% for input shape for ExpandDims %2% %3%")
1426 % inputTensorInfo.GetNumDimensions()
1427 % nodeDef.name()
1428 % CHECK_LOCATION().AsString()));
1429 }
1430
1431 std::int32_t expandDim = ReadMandatoryNodeInt32Attribute(nodeDef, "Tdim");
1432
1433 std::int32_t inputDimSize = boost::numeric_cast<int32_t>(inputTensorInfo.GetNumDimensions());
1434 std::vector<uint32_t> outputDims;
1435
1436 // expandDim operation requires: -1-input.dims() <= dim <= input.dims()
1437 if (expandDim >= -1 - inputDimSize && expandDim <= inputDimSize)
1438 {
1439 // add current input shape to outputDims
1440 for (unsigned int i = 0; i < inputTensorInfo.GetNumDimensions(); ++i) {
1441 auto currentDimension = inputTensorInfo.GetShape()[i];
1442 outputDims.push_back(currentDimension);
1443 }
1444
1445 // insert a dimension of 1 at index 'expandDim' of inputs shape
1446 if (expandDim >= 0)
1447 {
1448 auto getPosition = std::next(outputDims.begin() + 0, expandDim);
1449 outputDims.insert(getPosition, 1);
1450 }
1451
1452 // if negative number for 'expandDim' then count backwards from the last element
1453 // and insert 1 dimension at index 'expandDim'
1454 if (expandDim < 0)
1455 {
Matteo Martincighd7cceeb2018-12-06 09:06:29 +00001456 int outputDimSize = boost::numeric_cast<int>(outputDims.size() + 1);
Conor Kennedyc2130a02018-12-05 11:05:54 +00001457 auto getPosition = std::next(outputDims.begin() + outputDimSize, expandDim);
1458 outputDims.insert(getPosition, 1);
1459 }
1460 }
1461 else
1462 {
1463 throw InvalidArgumentException(
1464 boost::str(
1465 boost::format(
1466 "Cannot expand dimension %1% in input tensor with %2% dimension %3%")
1467 % expandDim
1468 % inputDimSize
1469 % CHECK_LOCATION().AsString()));
1470 }
1471
1472 if (outputDims.size() > 4)
1473 {
1474 throw ParseException(
1475 boost::str(
1476 boost::format(
1477 "Unsupported number of dimensions: %1% for output shape for ExpandDims %2% %3%")
1478 % outputDims.size()
1479 % nodeDef.name()
1480 % CHECK_LOCATION().AsString()));
1481 }
1482
1483 TensorShape outShape = TensorShape(static_cast<unsigned int>(outputDims.size()),
1484 outputDims.data());
1485
1486 TensorInfo outTensorInfo = inputTensorInfo;
1487 outTensorInfo.SetShape(outShape);
1488
1489 return outTensorInfo;
1490}
1491
1492ParsedTfOperationPtr TfParser::ParseExpandDims(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
1493{
1494 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
1495
1496 IOutputSlot& prevLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1497 TensorInfo inputTensorInfo = prevLayerOutputSlot.GetTensorInfo();
1498
1499 TensorInfo outputInfo;
1500 outputInfo = OutputShapeOfExpandDims(nodeDef, inputTensorInfo);
1501
1502 ReshapeDescriptor reshapeDesc;
1503 reshapeDesc.m_TargetShape = outputInfo.GetShape();
1504 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, nodeDef.name().c_str());
1505 prevLayerOutputSlot.Connect(layer->GetInputSlot(0));
1506 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
1507
1508 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
1509}
1510
surmeh01bceff2f2018-03-29 16:29:27 +01001511ParsedTfOperationPtr TfParser::ParseFusedBatchNorm(const tensorflow::NodeDef& nodeDef,
1512 const tensorflow::GraphDef& graphDef)
1513{
1514 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 5);
1515
1516 if (!HasParsedConstTensor<float>(inputs[1].m_IndexedValue->GetNode().name()))
1517 {
telsoa01c577f2c2018-08-31 09:22:23 +01001518 throw ParseException(
1519 boost::str(
1520 boost::format(
1521 "ArmNN only supports FusedBatchNormalization layers with constant scale. "
1522 "Input %1%. Node %2% %3%")
1523 % inputs[1].m_IndexedValue->GetNode().name()
1524 % nodeDef.name()
1525 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001526 }
1527 ParsedConstTfOperation<float>* scaleNode =
1528 boost::polymorphic_downcast<ParsedConstTfOperation<float> *>(inputs[1].m_IndexedValue);
1529
1530 if (!HasParsedConstTensor<float>(inputs[2].m_IndexedValue->GetNode().name()))
1531 {
telsoa01c577f2c2018-08-31 09:22:23 +01001532 throw ParseException(
1533 boost::str(
1534 boost::format(
1535 "ArmNN only supports FusedBatchNormalization layers with constant offset. "
1536 "Input %1%. Node %2% %3%")
1537 % inputs[2].m_IndexedValue->GetNode().name()
1538 % nodeDef.name()
1539 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001540 }
1541 ParsedConstTfOperation<float>* offsetNode =
1542 boost::polymorphic_downcast<ParsedConstTfOperation<float> *>(inputs[2].m_IndexedValue);
1543
1544 if (!HasParsedConstTensor<float>(inputs[3].m_IndexedValue->GetNode().name()))
1545 {
telsoa01c577f2c2018-08-31 09:22:23 +01001546 throw ParseException(
1547 boost::str(
1548 boost::format(
1549 "ArmNN only supports FusedBatchNormalization layers with constant mean. "
1550 "Input %1%. Node %2% %3%")
1551 % inputs[3].m_IndexedValue->GetNode().name()
1552 % nodeDef.name()
1553 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001554 }
1555 ParsedConstTfOperation<float>* meanNode =
1556 boost::polymorphic_downcast<ParsedConstTfOperation<float> *>(inputs[3].m_IndexedValue);
1557
1558 if (!HasParsedConstTensor<float>(inputs[4].m_IndexedValue->GetNode().name()))
1559 {
telsoa01c577f2c2018-08-31 09:22:23 +01001560 throw ParseException(
1561 boost::str(
1562 boost::format(
1563 "ArmNN only supports FusedBatchNormalization layers with constant variance. "
1564 "Input %1%. Node %2% %3%")
1565 % inputs[4].m_IndexedValue->GetNode().name()
1566 % nodeDef.name()
1567 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01001568 }
1569 ParsedConstTfOperation<float>* varianceNode =
1570 boost::polymorphic_downcast<ParsedConstTfOperation<float> *>(inputs[4].m_IndexedValue);
1571
Matteo Martincigh075c7502018-12-05 13:10:45 +00001572 const std::string dataFormat = ReadMandatoryNodeStringAttribute(nodeDef, "data_format");
1573
1574 CHECK_DATA_FORMAT(nodeDef, dataFormat, "FusedBatchNorm");
1575
telsoa01c577f2c2018-08-31 09:22:23 +01001576 // The descriptor only has the epsilon attribute.
surmeh01bceff2f2018-03-29 16:29:27 +01001577 BatchNormalizationDescriptor desc;
1578 desc.m_Eps = ReadMandatoryNodeFloatAttribute(nodeDef, "epsilon");
Matteo Martincigh075c7502018-12-05 13:10:45 +00001579 desc.m_DataLayout = dataFormat == "NHWC" ? DataLayout::NHWC : DataLayout::NCHW;
surmeh01bceff2f2018-03-29 16:29:27 +01001580
telsoa01c577f2c2018-08-31 09:22:23 +01001581 // Data for the parsed tensor args (scale, offset, mean, variance) must be stored
1582 // locally until the layer is added.
surmeh01bceff2f2018-03-29 16:29:27 +01001583 std::vector<float> scaleTensorData;
Matteo Martincigh482ca852018-12-12 09:20:55 +00001584 ConstTensor scaleTensor = scaleNode->GetConstTensor(scaleTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +01001585
1586 std::vector<float> offsetTensorData;
Matteo Martincigh482ca852018-12-12 09:20:55 +00001587 ConstTensor offsetTensor = offsetNode->GetConstTensor(offsetTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +01001588
1589 std::vector<float> meanTensorData;
Matteo Martincigh482ca852018-12-12 09:20:55 +00001590 ConstTensor meanTensor = meanNode->GetConstTensor(meanTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +01001591
1592 std::vector<float> varianceTensorData;
Matteo Martincigh482ca852018-12-12 09:20:55 +00001593 ConstTensor varianceTensor = varianceNode->GetConstTensor(varianceTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +01001594
1595 IConnectableLayer* layer = m_Network->AddBatchNormalizationLayer(desc,
1596 meanTensor,
1597 varianceTensor,
1598 offsetTensor,
1599 scaleTensor,
1600 nodeDef.name().c_str());
1601
1602 IOutputSlot& inputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1603
Matteo Martincigh075c7502018-12-05 13:10:45 +00001604 layer->GetOutputSlot(0).SetTensorInfo(inputSlot.GetTensorInfo());
1605 inputSlot.Connect(layer->GetInputSlot(0));
surmeh01bceff2f2018-03-29 16:29:27 +01001606
1607 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
1608}
1609
telsoa01c577f2c2018-08-31 09:22:23 +01001610bool TfParser::IsSupportedLeakyReluPattern(const tensorflow::NodeDef& mulNodeDef,
1611 size_t alphaLayerIndex,
1612 const OutputOfParsedTfOperation& otherOp,
1613 armnn::IOutputSlot** outputOfLeakyRelu,
1614 armnn::ActivationDescriptor & desc)
1615{
1616 const tensorflow::NodeDef& otherNodeDef = otherOp.m_IndexedValue->GetNode();
1617
1618 // Verifying all these assumptions hold:
1619 //
1620 // 1, the mulNodeDef is an elementwise multiplication node "Mul"
1621 // 2, the alphaLayerIndex selects a constant node from the inputs of the "Mul" node
1622 // 3, the inputLayerIndex selects a layer which has the same name as otherNodeDef
1623 //
1624
1625 if (mulNodeDef.op() == "Mul")
1626 {
1627 size_t otherLayerIndex = (alphaLayerIndex == 0 ? 1 : 0);
1628 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(mulNodeDef, 2);
1629
1630 BOOST_ASSERT(inputs.size() == 2);
1631 BOOST_ASSERT((otherLayerIndex == 0 || alphaLayerIndex == 0));
1632 BOOST_ASSERT((otherLayerIndex == 1 || alphaLayerIndex == 1));
1633 BOOST_ASSERT(((otherLayerIndex + alphaLayerIndex) == 1));
1634
1635 if (inputs[otherLayerIndex].m_IndexedValue->GetNode().name() == otherNodeDef.name())
1636 {
1637 if (HasParsedConstTensor<float>(inputs[alphaLayerIndex].m_IndexedValue->GetNode().name()))
1638 {
1639 ParsedConstTfOperation<float>* alpha =
1640 boost::polymorphic_downcast<ParsedConstTfOperation<float> *>(
1641 inputs[alphaLayerIndex].m_IndexedValue);
1642
1643 std::vector<float> const_data;
Matteo Martincigh482ca852018-12-12 09:20:55 +00001644 ConstTensor const_tensor = alpha->GetConstTensor(const_data);
telsoa01c577f2c2018-08-31 09:22:23 +01001645
1646 if (const_data.size() == 1)
1647 {
1648 desc.m_Function = ActivationFunction::LeakyReLu;
1649 desc.m_A = const_data[0];
1650
1651 *outputOfLeakyRelu = &(otherOp.m_IndexedValue->ResolveArmnnOutputSlot(otherOp.m_Index));
1652 return true;
1653 }
1654 }
1655 }
1656 }
1657 return false;
1658}
1659
telsoa01c577f2c2018-08-31 09:22:23 +01001660ParsedTfOperationPtr TfParser::ParseMaximum(const tensorflow::NodeDef& nodeDef,
1661 const tensorflow::GraphDef& graphDef)
1662{
1663 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
Sadik Armagan975c09a2018-12-04 10:02:08 +00001664 if (inputs.size() != 2)
1665 {
1666 throw ParseException(
1667 boost::str(
1668 boost::format(
1669 "Maximum expects two inputs!. Got %1% for Node %2% %3%")
1670 % inputs.size()
1671 % nodeDef.name()
1672 % CHECK_LOCATION().AsString()));
1673 }
1674
telsoa01c577f2c2018-08-31 09:22:23 +01001675 auto inputNode0 = inputs[0].m_IndexedValue->GetNode();
1676 auto inputNode1 = inputs[1].m_IndexedValue->GetNode();
1677 IOutputSlot* outputOfLeakyRelu = nullptr;
1678
1679 ActivationDescriptor desc;
1680
Sadik Armagan975c09a2018-12-04 10:02:08 +00001681 // A max node may be part of a LeakyRelu, with one input as a multiplication with a scalar constant,
1682 // i.e. one of the four possible scenarios:
1683 // 1, max(mul(a, x), x)
1684 // 2, max(mul(x, a), x)
1685 // 3, max(x, mul(a, x))
1686 // 4, max(x, mul(x, a))
1687 // These are handled by an activation layer.
telsoa01c577f2c2018-08-31 09:22:23 +01001688
1689 if (IsSupportedLeakyReluPattern(inputNode0, 0, inputs[1], &outputOfLeakyRelu, desc) ||
1690 IsSupportedLeakyReluPattern(inputNode0, 1, inputs[1], &outputOfLeakyRelu, desc) ||
1691 IsSupportedLeakyReluPattern(inputNode1, 0, inputs[0], &outputOfLeakyRelu, desc) ||
1692 IsSupportedLeakyReluPattern(inputNode1, 1, inputs[0], &outputOfLeakyRelu, desc))
1693 {
1694 BOOST_ASSERT(outputOfLeakyRelu != nullptr);
1695
1696 IConnectableLayer* const layer = m_Network->AddActivationLayer(desc, nodeDef.name().c_str());
1697 outputOfLeakyRelu->Connect(layer->GetInputSlot(0));
1698 layer->GetOutputSlot(0).SetTensorInfo(outputOfLeakyRelu->GetTensorInfo());
1699 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
1700 }
1701 else
1702 {
Sadik Armagan975c09a2018-12-04 10:02:08 +00001703 // Anything else is just a maximum layer.
1704
1705 return AddMaximumLayer(nodeDef);
telsoa01c577f2c2018-08-31 09:22:23 +01001706 }
1707}
1708
jimfly0184c70e62018-12-19 13:14:46 +00001709std::pair<armnn::IOutputSlot*, armnn::IOutputSlot*> TfParser::ProcessElementwiseInputSlots(
1710 const tensorflow::NodeDef& nodeDef, const std::string& layerName)
Nattapat Chaimanowong24df8222018-12-04 13:47:02 +00001711{
1712 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
1713
1714 IOutputSlot* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1715 IOutputSlot* input1Slot = &inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
1716 const unsigned int input0Dim = input0Slot->GetTensorInfo().GetNumDimensions();
1717 const unsigned int input1Dim = input1Slot->GetTensorInfo().GetNumDimensions();
1718
1719 if (input0Dim != input1Dim)
1720 {
1721 // broadcasting where input0 and input1 have different number of dimensions
1722 // is only supported for 1D and 4D tensors pair
1723 if (input0Dim == 1 && input1Dim == 4)
1724 {
1725 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot, true, *m_Network, nodeDef);
1726 }
1727 else if (input0Dim == 4 && input1Dim == 1)
1728 {
1729 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, true, *m_Network, nodeDef);
1730 }
1731 else
1732 {
1733 throw ParseException(
jimfly0184c70e62018-12-19 13:14:46 +00001734 boost::str(
1735 boost::format("Unsupported broadcast configuration for %1% operation %2% %3%")
1736 % layerName
1737 % nodeDef.name()
1738 % CHECK_LOCATION().AsString()));
Nattapat Chaimanowong24df8222018-12-04 13:47:02 +00001739 }
1740 }
jimfly0184c70e62018-12-19 13:14:46 +00001741 return {input0Slot, input1Slot};
1742}
Nattapat Chaimanowong24df8222018-12-04 13:47:02 +00001743
kevmay012b4d88e2019-01-24 14:05:09 +00001744ParsedTfOperationPtr TfParser::ProcessComparisonLayer(
1745 IOutputSlot* input0Slot,
1746 IOutputSlot* input1Slot,
1747 IConnectableLayer* const layer,
1748 const tensorflow::NodeDef& nodeDef)
1749{
1750 input0Slot->Connect(layer->GetInputSlot(0));
1751 input1Slot->Connect(layer->GetInputSlot(1));
1752
1753 TensorInfo outputInfo = input0Slot->GetTensorInfo();
1754 outputInfo.SetDataType(DataType::Boolean);
1755 std::vector<unsigned int> outputShape;
1756
1757 const TensorShape& input0Shape = input0Slot->GetTensorInfo().GetShape();
1758 const TensorShape& input1Shape = input1Slot->GetTensorInfo().GetShape();
1759
1760 for (unsigned int i = 0; i < input0Shape.GetNumDimensions(); i++)
1761 {
1762 outputShape.push_back(std::max(input0Shape[i], input1Shape[i]));
1763 }
1764
1765 outputInfo.SetShape(TensorShape(input0Shape.GetNumDimensions(), outputShape.data()));
1766 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
1767
1768 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
1769}
1770
jimfly0184c70e62018-12-19 13:14:46 +00001771ParsedTfOperationPtr TfParser::ProcessElementwiseLayer(
1772 IOutputSlot* input0Slot,
1773 IOutputSlot* input1Slot,
1774 IConnectableLayer* const layer,
1775 const tensorflow::NodeDef& nodeDef)
1776{
Nattapat Chaimanowong24df8222018-12-04 13:47:02 +00001777 input0Slot->Connect(layer->GetInputSlot(0));
1778 input1Slot->Connect(layer->GetInputSlot(1));
1779
1780 TensorInfo outputInfo = input0Slot->GetTensorInfo();
1781 std::vector<unsigned int> outputShape;
1782
1783 const TensorShape& input0Shape = input0Slot->GetTensorInfo().GetShape();
1784 const TensorShape& input1Shape = input1Slot->GetTensorInfo().GetShape();
1785
1786 for (unsigned int i = 0; i < input0Shape.GetNumDimensions(); i++)
1787 {
1788 outputShape.push_back(std::max(input0Shape[i], input1Shape[i]));
1789 }
1790
1791 outputInfo.SetShape(TensorShape(input0Shape.GetNumDimensions(), outputShape.data()));
1792 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
1793
1794 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
1795}
1796
FrancisMurtagh94412af2019-01-24 10:53:39 +00001797ParsedTfOperationPtr TfParser::ParseGather(const tensorflow::NodeDef& nodeDef,
1798 const tensorflow::GraphDef& graphDef)
1799{
1800 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
1801 IOutputSlot& params = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1802 IOutputSlot& indices = inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
1803
1804 // Infer shape of output tensor
1805 unsigned int paramsDim = params.GetTensorInfo().GetNumDimensions();
1806 unsigned int indicesDim = indices.GetTensorInfo().GetNumDimensions();
1807 unsigned int outputDim = paramsDim - 1 + indicesDim;
1808
1809 std::vector<unsigned int> dimSizes;
1810
1811 for (unsigned int i = 0; i < indicesDim; ++i)
1812 {
1813 dimSizes.push_back(indices.GetTensorInfo().GetShape()[i]);
1814 }
1815 for (unsigned int i = 1; i < paramsDim; ++i)
1816 {
1817 dimSizes.push_back(params.GetTensorInfo().GetShape()[i]);
1818 }
1819
1820 const TensorShape& inferredShape = TensorShape(outputDim, dimSizes.data());
1821
1822 const TensorInfo inferredOutputInfo(inferredShape, params.GetTensorInfo().GetDataType());
1823
1824 IConnectableLayer* const layer = m_Network->AddGatherLayer(nodeDef.name().c_str());
1825 layer->GetOutputSlot(0).SetTensorInfo(inferredOutputInfo);
1826
1827 params.Connect(layer->GetInputSlot(0));
1828 indices.Connect(layer->GetInputSlot(1));
1829
1830 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
1831}
1832
jimfly01a06bf312018-12-18 16:24:51 +00001833ParsedTfOperationPtr TfParser::ParseGreater(const tensorflow::NodeDef& nodeDef,
1834 const tensorflow::GraphDef& graphDef)
1835{
1836 std::pair<armnn::IOutputSlot*, armnn::IOutputSlot*> inputLayers = ProcessElementwiseInputSlots(nodeDef, "Greater");
1837 IOutputSlot* input0Slot = inputLayers.first;
1838 IOutputSlot* input1Slot = inputLayers.second;
1839
1840 IConnectableLayer* const layer = m_Network->AddGreaterLayer(nodeDef.name().c_str());
1841
kevmay012b4d88e2019-01-24 14:05:09 +00001842 return ProcessComparisonLayer(input0Slot, input1Slot, layer, nodeDef);
jimfly01a06bf312018-12-18 16:24:51 +00001843}
1844
jimfly0184c70e62018-12-19 13:14:46 +00001845ParsedTfOperationPtr TfParser::ParseEqual(const tensorflow::NodeDef& nodeDef,
1846 const tensorflow::GraphDef& graphDef)
1847{
1848 std::pair<armnn::IOutputSlot*, armnn::IOutputSlot*> inputLayers = ProcessElementwiseInputSlots(nodeDef, "Equal");
1849 IOutputSlot* input0Slot = inputLayers.first;
1850 IOutputSlot* input1Slot = inputLayers.second;
1851
1852 IConnectableLayer* const layer = m_Network->AddEqualLayer(nodeDef.name().c_str());
1853
kevmay012b4d88e2019-01-24 14:05:09 +00001854 return ProcessComparisonLayer(input0Slot, input1Slot, layer, nodeDef);
jimfly0184c70e62018-12-19 13:14:46 +00001855}
1856
1857ParsedTfOperationPtr TfParser::ParseMinimum(const tensorflow::NodeDef& nodeDef,
1858 const tensorflow::GraphDef& graphDef)
1859{
1860 std::pair<armnn::IOutputSlot*, armnn::IOutputSlot*> inputLayers = ProcessElementwiseInputSlots(nodeDef, "Minimum");
1861 IOutputSlot* input0Slot = inputLayers.first;
1862 IOutputSlot* input1Slot = inputLayers.second;
1863
1864 IConnectableLayer* const layer = m_Network->AddMinimumLayer(nodeDef.name().c_str());
1865
1866 return ProcessElementwiseLayer(input0Slot, input1Slot, layer, nodeDef);
1867}
1868
jimfly0123be07e2018-12-04 17:47:22 +00001869ParsedTfOperationPtr TfParser::ParseSub(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
1870{
1871 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
1872
1873 IOutputSlot* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1874 IOutputSlot* input1Slot = &inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
1875
1876 const TensorInfo& input0Info = input0Slot->GetTensorInfo();
1877 const TensorInfo& input1Info = input1Slot->GetTensorInfo();
1878
1879 if (input0Info.GetNumDimensions() == 1)
1880 {
1881 const bool isNHWC = true;
1882 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot, isNHWC, *m_Network, nodeDef);
1883 }
1884
1885 if (input1Info.GetNumDimensions() == 1)
1886 {
1887 const bool isNHWC = true;
1888 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, isNHWC, *m_Network, nodeDef);
1889 }
1890
1891 IConnectableLayer* const layer = m_Network->AddSubtractionLayer(nodeDef.name().c_str());
1892
1893 input0Slot->Connect(layer->GetInputSlot(0));
1894 input1Slot->Connect(layer->GetInputSlot(1));
1895
1896 if (input0Info.GetNumDimensions() == 1)
1897 {
1898 layer->GetOutputSlot(0).SetTensorInfo(input1Slot->GetTensorInfo());
1899 }
1900 else
1901 {
1902 layer->GetOutputSlot(0).SetTensorInfo(input0Slot->GetTensorInfo());
1903 }
1904
1905 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
1906}
1907
jimfly01f6ba7472018-12-04 10:09:52 +00001908unsigned int CheckPaddingTensor(const ConstTensor& paddingTensor,
1909 const TensorInfo& inputTensorInfo,
1910 const std::string& nodeName)
1911{
1912 unsigned int rank = paddingTensor.GetShape()[0];
1913 unsigned int expectedRank = inputTensorInfo.GetNumDimensions();
1914 if (rank != expectedRank)
1915 {
1916 throw ParseException(
1917 boost::str(
1918 boost::format(
1919 "Expected the padding tensor to be of rank %1 not %2 on Node %3 %4.")
1920 % expectedRank
1921 % rank
1922 % nodeName
1923 % CHECK_LOCATION().AsString()));
1924 }
1925 unsigned int second = paddingTensor.GetShape()[1];
1926 if (second != 2)
1927 {
1928 throw ParseException(
1929 boost::str(
1930 boost::format(
1931 "Expected the padding tensor to be of dimensions [%1, 2] not [%1, %2] on Node %3 %4.")
1932 % rank
1933 % second
1934 % nodeName
1935 % CHECK_LOCATION().AsString()));
1936 }
1937 return rank;
1938}
1939
1940TensorInfo CalculatePaddedOutputTensorInfo(const TensorInfo& inputTensorInfo,
1941 const std::vector<std::pair<unsigned int, unsigned int>>& padList)
1942{
1943 unsigned int numDims = inputTensorInfo.GetNumDimensions();
1944 std::vector<unsigned int> outDims;
1945 for (unsigned int i = 0; i < numDims; ++i)
1946 {
1947 unsigned int dimSize = inputTensorInfo.GetShape()[i];
1948 const std::pair<unsigned int, unsigned int>& dimPadding = padList[i];
1949 dimSize += dimPadding.first;
1950 dimSize += dimPadding.second;
1951 outDims.push_back(dimSize);
1952 }
1953 TensorInfo paddedTensorInfo = inputTensorInfo;
1954 unsigned int outDimsSize = static_cast<unsigned int>(outDims.size());
1955 paddedTensorInfo.SetShape(TensorShape{ outDimsSize, outDims.data() });
1956 return paddedTensorInfo;
1957}
1958
1959ParsedTfOperationPtr TfParser::ParsePad(const tensorflow::NodeDef& nodeDef,
1960 const tensorflow::GraphDef& graphDef)
1961{
1962 // input consists of:
1963 // input[0] the tensor which will be padded
1964 // input[1] the tensor holding the padding values
1965 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
1966 IOutputSlot& previousLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1967 TensorInfo inputTensorInfo = previousLayerOutputSlot.GetTensorInfo();
1968 if (!HasParsedConstTensor<int32_t>(inputs[1].m_IndexedValue))
1969 {
1970 throw ParseException(
1971 boost::str(
1972 boost::format(
1973 "ArmNN only supports Pad with constant padding. "
1974 "Input %1%. Node %2% %3%")
1975 % inputs[1].m_IndexedValue->GetNode().name()
1976 % nodeDef.name()
1977 % CHECK_LOCATION().AsString()));
1978
1979 }
1980 ParsedConstTfOperation<int32_t>* paddingTensorOp =
1981 boost::polymorphic_downcast<ParsedConstTfOperation<int32_t>*>(inputs[1].m_IndexedValue);
1982
1983 std::vector<int32_t> paddingTensorData;
Matteo Martincigh482ca852018-12-12 09:20:55 +00001984 ConstTensor paddingTensor = paddingTensorOp->GetConstTensor(paddingTensorData);
jimfly01f6ba7472018-12-04 10:09:52 +00001985 // paddings is an integer tensor with shape [n, 2], where n is the rank of tensor
1986 // and should match the rank of the input tensor that is being padded.
1987 // For each dimension D of input, paddings[D, 0] indicates how many values to add
1988 // before the contents of tensor in that dimension, and paddings[D, 1] indicates how
1989 // many values to add after the contents of tensor in that dimension
1990 // This needs to be translated into a padList for ACL
1991 std::vector<std::pair<unsigned int, unsigned int>> padList;
1992 unsigned int rank = CheckPaddingTensor(paddingTensor, inputTensorInfo, nodeDef.name());
1993 for (unsigned int i = 0; i < rank; ++i)
1994 {
1995 std::pair<unsigned int, unsigned int> paddingForDim;
1996 for (unsigned int j = 0; j < 2; j++)
1997 {
1998 unsigned int index = (i * 2) + j;
1999 int paddingAmount = paddingTensorData[index];
2000 // make sure we can cast to an unsigned value
2001 if (paddingAmount < 0)
2002 {
2003 throw ParseException(
2004 boost::str(
2005 boost::format(
2006 "Negative amount %1 specified at [%2, %3] of padding tensor on Node %4 %5.")
2007 % paddingAmount
2008 % i
2009 % j
2010 % nodeDef.name()
2011 % CHECK_LOCATION().AsString()));
2012 }
2013 if (j == 0)
2014 {
2015 paddingForDim.first = static_cast<unsigned int>(paddingAmount);
2016 }
2017 else
2018 {
2019 paddingForDim.second = static_cast<unsigned int>(paddingAmount);
2020 }
2021 }
2022 padList.push_back(paddingForDim);
2023 }
2024 PadDescriptor padDescriptor(padList);
2025 IConnectableLayer* layer = m_Network->AddPadLayer(padDescriptor, nodeDef.name().c_str());
2026 previousLayerOutputSlot.Connect(layer->GetInputSlot(0));
2027 // Use the padding to calculate the new output tensor shape
2028 TensorInfo outputTensorInfo = CalculatePaddedOutputTensorInfo(inputTensorInfo, padList);
2029 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2030 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2031}
2032
surmeh01bceff2f2018-03-29 16:29:27 +01002033ParsedTfOperationPtr TfParser::ParseConcat(const tensorflow::NodeDef& nodeDef,
2034 const tensorflow::GraphDef& graphDef)
2035{
2036 std::vector<OutputOfConstNodeDef> nodes = GetTfInputNodes(nodeDef);
Matteo Martincighf9afc792018-12-06 12:03:17 +00002037
telsoa01c577f2c2018-08-31 09:22:23 +01002038 // In tensorflow, we have the last input of the Concat layer as the axis for concatenation.
surmeh01bceff2f2018-03-29 16:29:27 +01002039 unsigned int numInputs = static_cast<unsigned int>(nodes.size());
surmeh01bceff2f2018-03-29 16:29:27 +01002040
surmeh01bceff2f2018-03-29 16:29:27 +01002041 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, numInputs);
2042
telsoa01c577f2c2018-08-31 09:22:23 +01002043 // The last input is the axis for concatenation.
surmeh01bceff2f2018-03-29 16:29:27 +01002044 if (!HasParsedConstTensor<int32_t>(inputs[numInputs - 1].m_IndexedValue->GetNode().name()))
2045 {
telsoa01c577f2c2018-08-31 09:22:23 +01002046 throw ParseException(
2047 boost::str(
2048 boost::format(
2049 "ArmNN only supports Concat with constant axis. "
2050 "Input %1%. Node %2% %3%")
2051 % inputs[numInputs - 1].m_IndexedValue->GetNode().name()
2052 % nodeDef.name()
2053 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002054 }
2055 ParsedConstTfOperation<int32_t>* shapeNode =
2056 boost::polymorphic_downcast<ParsedConstTfOperation<int32_t>*>(inputs[numInputs - 1].m_IndexedValue);
2057
Matteo Martincighf9afc792018-12-06 12:03:17 +00002058 // Get the axis tensor data
surmeh01bceff2f2018-03-29 16:29:27 +01002059 std::vector<int32_t> axisTensorData;
Matteo Martincigh482ca852018-12-12 09:20:55 +00002060 shapeNode->GetConstTensor(axisTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +01002061
telsoa01c577f2c2018-08-31 09:22:23 +01002062 // This concatDim indicates the data format: 3 is the NHWC, 1 is the NCHW.
Matteo Martincighf9afc792018-12-06 12:03:17 +00002063 const unsigned int concatDim = static_cast<unsigned int>(axisTensorData[0]);
surmeh01bceff2f2018-03-29 16:29:27 +01002064
telsoa01c577f2c2018-08-31 09:22:23 +01002065 // Armnn supports concatenation along the channel dimension for data formats NHWC and NCHW.
Matteo Martincighf9afc792018-12-06 12:03:17 +00002066 if (concatDim == 0 || concatDim == 2)
surmeh01bceff2f2018-03-29 16:29:27 +01002067 {
telsoa01c577f2c2018-08-31 09:22:23 +01002068 throw ParseException(
2069 boost::str(
2070 boost::format(
2071 "Dimension %1% for concatenation is not supported by Armnn. "
2072 "Node %2% %3%")
Matteo Martincighf9afc792018-12-06 12:03:17 +00002073 % concatDim
telsoa01c577f2c2018-08-31 09:22:23 +01002074 % nodeDef.name()
2075 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002076 }
2077
Matteo Martincighf9afc792018-12-06 12:03:17 +00002078 unsigned int numConcatViews = numInputs - 1;
2079 OriginsDescriptor concatDescriptor(static_cast<uint32_t>(numConcatViews), MaxNumOfTensorDimensions);
2080 concatDescriptor.SetConcatAxis(concatDim);
2081 TensorShape mergeDims(MaxNumOfTensorDimensions);
2082 unsigned int mergeDim = 0;
2083 for (unsigned int viewIndex = 0; viewIndex < numConcatViews; ++viewIndex)
surmeh01bceff2f2018-03-29 16:29:27 +01002084 {
telsoa01c577f2c2018-08-31 09:22:23 +01002085 // Need to double check whether it should be
Matteo Martincighf9afc792018-12-06 12:03:17 +00002086 IOutputSlot& inputSlot = inputs[viewIndex].m_IndexedValue->ResolveArmnnOutputSlot(inputs[viewIndex].m_Index);
surmeh01bceff2f2018-03-29 16:29:27 +01002087 TensorInfo inputTensorInfo = inputSlot.GetTensorInfo();
2088
Matteo Martincighf9afc792018-12-06 12:03:17 +00002089 // Double check dimensions of the tensors
2090 if (inputTensorInfo.GetNumDimensions() != MaxNumOfTensorDimensions)
2091 {
2092 throw armnn::ParseException(
2093 boost::str(
2094 boost::format(
2095 "The number of dimensions: %1% for input tensors of the "
2096 "concatenation op should be %2% %3%")
2097 % inputTensorInfo.GetNumDimensions()
2098 % MaxNumOfTensorDimensions
2099 % CHECK_LOCATION().AsString()));
2100 }
2101
2102 // Copy the input tensor shape to mergeDimSizes and initialize the view origin coordinates for the current input
2103 mergeDims = inputTensorInfo.GetShape();
2104 unsigned int* viewOrigin = const_cast<unsigned int*>(concatDescriptor.GetViewOrigin(viewIndex));
2105 std::fill(viewOrigin, viewOrigin + MaxNumOfTensorDimensions, 0);
2106
2107 // Update the view origin coordinates and the merge dimension value
2108 concatDescriptor.SetViewOriginCoord(viewIndex, concatDim, mergeDim);
2109 mergeDim += mergeDims[concatDim];
surmeh01bceff2f2018-03-29 16:29:27 +01002110 }
2111
Matteo Martincighf9afc792018-12-06 12:03:17 +00002112 // Update the output shape
2113 mergeDims[concatDim] = mergeDim;
surmeh01bceff2f2018-03-29 16:29:27 +01002114 armnn::IConnectableLayer *layer = m_Network->AddMergerLayer(concatDescriptor, nodeDef.name().c_str());
2115
Matteo Martincighf9afc792018-12-06 12:03:17 +00002116 layer->GetOutputSlot(0).SetTensorInfo(armnn::TensorInfo(mergeDims, DataType::Float32));
surmeh01bceff2f2018-03-29 16:29:27 +01002117
Matteo Martincighf9afc792018-12-06 12:03:17 +00002118 for (unsigned int viewIndex = 0; viewIndex < numConcatViews; ++viewIndex)
surmeh01bceff2f2018-03-29 16:29:27 +01002119 {
Matteo Martincighf9afc792018-12-06 12:03:17 +00002120 IOutputSlot& inputSlot = inputs[viewIndex].m_IndexedValue->ResolveArmnnOutputSlot(inputs[viewIndex].m_Index);
2121 inputSlot.Connect(layer->GetInputSlot(viewIndex));
surmeh01bceff2f2018-03-29 16:29:27 +01002122 }
2123
2124 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2125}
2126
2127ParsedTfOperationPtr TfParser::ParseShape(const tensorflow::NodeDef& nodeDef,
2128 const tensorflow::GraphDef& graphDef)
2129{
telsoa01c577f2c2018-08-31 09:22:23 +01002130 // Note: the Shape layer is handled in a special way, because:
2131 // 1. ARMNN doesn't support int32 tensors which it outputs.
2132 // 2. ARMNN works with statically shaped tensors which are known at parse time.
surmeh01bceff2f2018-03-29 16:29:27 +01002133 // 3. because of 1. and 2. we treat the output of Shape as a temporary const int32
telsoa01c577f2c2018-08-31 09:22:23 +01002134 // tensor which may be used as an input to other ops, most likely a Reshape.
surmeh01bceff2f2018-03-29 16:29:27 +01002135
2136 const tensorflow::DataType tfDataType = ReadMandatoryNodeTypeAttribute(nodeDef, "out_type");
2137 if (tfDataType != tensorflow::DT_INT32)
2138 {
telsoa01c577f2c2018-08-31 09:22:23 +01002139 throw ParseException(
2140 boost::str(
2141 boost::format(
2142 "Armnn only supports DT_INT32 as out_type. Got %1% for Node %2% %3%")
2143 % tensorflow::DataType_Name(tfDataType)
2144 % nodeDef.name()
2145 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002146 }
2147
2148 const std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2149 IOutputSlot& prevLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2150 const TensorInfo& prevLayerTensorInfo = prevLayerOutputSlot.GetTensorInfo();
2151 unsigned int prevLayerDimensions = prevLayerTensorInfo.GetNumDimensions();
2152
2153 std::vector<int32_t> shapeTensorData;
2154 shapeTensorData.reserve(prevLayerDimensions);
2155
2156 for (unsigned int i=0; i<prevLayerDimensions; ++i)
2157 {
2158 shapeTensorData.push_back(static_cast<int32_t>(prevLayerTensorInfo.GetShape()[i]));
2159 }
2160
2161 TensorInfo shapeTensorInfo(1, &prevLayerDimensions, DataType::Signed32);
2162
2163 return std::make_unique<ParsedConstTfOperation<int32_t>>(this,
2164 nodeDef,
2165 &shapeTensorData[0],
2166 shapeTensorInfo);
2167}
2168
2169ParsedTfOperationPtr TfParser::ParseReshape(const tensorflow::NodeDef& nodeDef,
2170 const tensorflow::GraphDef& graphDef)
2171{
2172 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
2173 ParsedTfOperation* inputNode = inputs[0].m_IndexedValue;
2174
2175 if (!HasParsedConstTensor<int32_t>(inputs[1].m_IndexedValue->GetNode().name()))
2176 {
telsoa01c577f2c2018-08-31 09:22:23 +01002177 throw ParseException(
2178 boost::str(
2179 boost::format(
2180 "ArmNN only supports Reshape layers with constant shapes. "
2181 "Input %1% Node %2% %3%")
2182 % inputs[1].m_IndexedValue->GetNode().name()
2183 % nodeDef.name()
2184 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002185 }
2186 ParsedConstTfOperation<int32_t>* shapeNode =
2187 boost::polymorphic_downcast<ParsedConstTfOperation<int32_t>*>(inputs[1].m_IndexedValue);
2188
2189 armnn::IOutputSlot& prevLayerOutputSlot = inputNode->ResolveArmnnOutputSlot(inputs[0].m_Index);
2190 TensorInfo inputTensorInfo = prevLayerOutputSlot.GetTensorInfo();
2191
2192 std::vector<int32_t> shapeTensorData;
Matteo Martincigh482ca852018-12-12 09:20:55 +00002193 ConstTensor shapeTensor = shapeNode->GetConstTensor(shapeTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +01002194 const TensorInfo outputTensorInfo = PrepareReshape(inputTensorInfo, shapeTensorData);
2195
2196 TensorShape targetShape = outputTensorInfo.GetShape();
2197 ReshapeDescriptor reshapeDesc;
2198 reshapeDesc.m_TargetShape = targetShape;
2199
2200 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, nodeDef.name().c_str());
2201 prevLayerOutputSlot.Connect(layer->GetInputSlot(0));
2202 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2203
2204 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2205}
2206
2207ParsedTfOperationPtr TfParser::ParseResizeBilinear(const tensorflow::NodeDef& nodeDef,
2208 const tensorflow::GraphDef& graphDef)
2209{
2210 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
2211
2212 if (!HasParsedConstTensor<int32_t>(inputs[1].m_IndexedValue->GetNode().name()))
2213 {
telsoa01c577f2c2018-08-31 09:22:23 +01002214 throw ParseException(
2215 boost::str(
2216 boost::format(
2217 "ArmNN only supports ResizeBilinear layers with constant sizes. "
2218 "Input %1%. Node %2% %3%")
2219 % inputs[1].m_IndexedValue->GetNode().name()
2220 % nodeDef.name()
2221 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002222 }
2223 ParsedConstTfOperation<int32_t>* sizeNode =
2224 boost::polymorphic_downcast<ParsedConstTfOperation<int32_t>*>(inputs[1].m_IndexedValue);
2225
telsoa01c577f2c2018-08-31 09:22:23 +01002226 // Checks the align_corners attribute is not set.
surmeh01bceff2f2018-03-29 16:29:27 +01002227 if (ReadOptionalNodeBoolAttribute(nodeDef, "align_corners", false))
2228 {
telsoa01c577f2c2018-08-31 09:22:23 +01002229 throw ParseException(
2230 boost::str(
2231 boost::format(
2232 "ArmNN only supports ResizeBilinear layers with align_corners set to false. "
2233 "Node %1% %2%")
2234 % nodeDef.name()
2235 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002236 }
2237
telsoa01c577f2c2018-08-31 09:22:23 +01002238 // Data for the parsed tensor args (size) must be stored locally.
surmeh01bceff2f2018-03-29 16:29:27 +01002239 std::vector<int32_t> sizeTensorData;
Matteo Martincigh482ca852018-12-12 09:20:55 +00002240 ConstTensor sizeTensor = sizeNode->GetConstTensor(sizeTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +01002241
telsoa01c577f2c2018-08-31 09:22:23 +01002242 // The descriptor only has target height and width attributes, which we get from the size tensor.
surmeh01bceff2f2018-03-29 16:29:27 +01002243 ResizeBilinearDescriptor desc;
2244 desc.m_TargetHeight = static_cast<uint32_t> (sizeTensorData[0]);
2245 desc.m_TargetWidth = static_cast<uint32_t> (sizeTensorData[1]);
jimfly018a121502018-12-06 16:19:52 +00002246 desc.m_DataLayout = armnn::DataLayout::NHWC;
surmeh01bceff2f2018-03-29 16:29:27 +01002247
2248 IConnectableLayer* layer = m_Network->AddResizeBilinearLayer(desc, nodeDef.name().c_str());
2249
2250 IOutputSlot& inputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2251 TensorInfo inputTensorInfo = inputSlot.GetTensorInfo();
telsoa01c577f2c2018-08-31 09:22:23 +01002252 // The input shape is always in BHWC format, this will be swizzled below; for now,
2253 // get the batch and channels to make up the ArmNN output shape with the target size.
surmeh01bceff2f2018-03-29 16:29:27 +01002254 unsigned int outBatch = inputTensorInfo.GetShape()[0];
2255 unsigned int outChannels = inputTensorInfo.GetShape()[3];
2256 unsigned int outHeight = desc.m_TargetHeight;
2257 unsigned int outWidth = desc.m_TargetWidth;
jimfly018a121502018-12-06 16:19:52 +00002258 TensorShape outShape({outBatch, outHeight, outWidth, outChannels });
telsoa01c577f2c2018-08-31 09:22:23 +01002259 // The output DataType is always Float32, regardless of the input DataType.
surmeh01bceff2f2018-03-29 16:29:27 +01002260 const TensorInfo outputTensorInfo(outShape, armnn::DataType::Float32);
2261 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2262
jimfly018a121502018-12-06 16:19:52 +00002263 inputSlot.Connect(layer->GetInputSlot(0));
surmeh01bceff2f2018-03-29 16:29:27 +01002264
2265 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2266}
2267
2268TensorInfo OutputShapeOfSqueeze(const tensorflow::NodeDef& nodeDef, TensorInfo inputTensorInfo)
2269{
2270 BOOST_ASSERT(nodeDef.op() == "Squeeze");
2271 tensorflow::DataType tfDataType = ReadMandatoryNodeTypeAttribute(nodeDef, "T");
2272
2273 DataType type;
2274 if (tfDataType == tensorflow::DT_FLOAT)
2275 {
2276 type = DataType::Float32;
2277 }
2278 else if (tfDataType == tensorflow::DT_INT32)
2279 {
2280 type = DataType::Signed32;
2281 }
2282 else
2283 {
telsoa01c577f2c2018-08-31 09:22:23 +01002284 throw ParseException(
2285 boost::str(
2286 boost::format("Unsupported DataType %1% for Squeeze operation %2% %3%")
2287 % tensorflow::DataType_Name(tfDataType)
2288 % nodeDef.name()
2289 % CHECK_LOCATION().AsString()));
2290 }
2291
2292
2293 if (inputTensorInfo.GetNumDimensions() > 4)
2294 {
2295 throw ParseException(
2296 boost::str(
2297 boost::format(
2298 "Unsupported number of dimensions: %1% for input shape for Squeeze %2% %3%")
2299 % inputTensorInfo.GetNumDimensions()
2300 % nodeDef.name()
2301 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002302 }
2303
2304 std::vector<uint32_t> squeezeDims = ReadOptionalNodeUint32ListAttribute(nodeDef, "squeeze_dims");
telsoa01c577f2c2018-08-31 09:22:23 +01002305 static const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
2306
surmeh01bceff2f2018-03-29 16:29:27 +01002307 if (squeezeDims.empty())
2308 {
telsoa01c577f2c2018-08-31 09:22:23 +01002309 squeezeDims.assign(dimensionSequence,
2310 dimensionSequence+inputTensorInfo.GetNumDimensions());
surmeh01bceff2f2018-03-29 16:29:27 +01002311 }
2312
2313 std::vector<uint32_t> outputDims;
2314 for(unsigned int i = 0; i < inputTensorInfo.GetNumDimensions(); i++)
2315 {
telsoa01c577f2c2018-08-31 09:22:23 +01002316 bool skipSqueeze = (std::find(squeezeDims.begin(), squeezeDims.end(), i) == squeezeDims.end());
2317 auto currentDimension = inputTensorInfo.GetShape()[i];
2318 if (skipSqueeze || currentDimension != 1)
surmeh01bceff2f2018-03-29 16:29:27 +01002319 {
telsoa01c577f2c2018-08-31 09:22:23 +01002320 outputDims.push_back(currentDimension);
surmeh01bceff2f2018-03-29 16:29:27 +01002321 }
2322 }
2323
2324 if (outputDims.size() > 4)
2325 {
telsoa01c577f2c2018-08-31 09:22:23 +01002326 throw ParseException(
2327 boost::str(
2328 boost::format(
2329 "Unsupported number of dimensions: %1% for output shape for Squeeze %2% %3%")
2330 % outputDims.size()
2331 % nodeDef.name()
2332 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002333 }
2334
telsoa01c577f2c2018-08-31 09:22:23 +01002335 TensorShape outShape = TensorShape(static_cast<unsigned int>(outputDims.size()),
2336 outputDims.data());
2337
2338 TensorInfo outTensorInfo = inputTensorInfo;
2339 outTensorInfo.SetShape(outShape);
2340 outTensorInfo.SetDataType(type);
surmeh01bceff2f2018-03-29 16:29:27 +01002341
2342 return outTensorInfo;
2343}
2344
2345ParsedTfOperationPtr TfParser::ParseSqueeze(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
2346{
2347 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2348
2349 IOutputSlot& prevLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2350 TensorInfo inputTensorInfo = prevLayerOutputSlot.GetTensorInfo();
2351
2352 TensorInfo outputInfo;
2353 outputInfo = OutputShapeOfSqueeze(nodeDef, inputTensorInfo);
2354
2355 ReshapeDescriptor reshapeDesc;
2356 reshapeDesc.m_TargetShape = outputInfo.GetShape();
2357 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, nodeDef.name().c_str());
2358 prevLayerOutputSlot.Connect(layer->GetInputSlot(0));
2359 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
2360
2361 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2362}
2363
2364ParsedTfOperationPtr TfParser::ParseLrn(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
2365{
2366 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2367
2368 NormalizationDescriptor normalizationDescriptor;
2369 normalizationDescriptor.m_NormMethodType = NormalizationAlgorithmMethod::LocalBrightness;
2370 normalizationDescriptor.m_NormChannelType = NormalizationAlgorithmChannel::Across;
2371 normalizationDescriptor.m_Alpha = ReadMandatoryNodeFloatAttribute(nodeDef, "alpha");
2372 normalizationDescriptor.m_Beta = ReadMandatoryNodeFloatAttribute(nodeDef, "beta");
2373 normalizationDescriptor.m_K = ReadMandatoryNodeFloatAttribute(nodeDef, "bias");
2374 normalizationDescriptor.m_NormSize = ReadMandatoryNodeUint32Attribute(nodeDef, "depth_radius");
ruoyan018174f362018-12-04 18:24:08 +00002375 normalizationDescriptor.m_DataLayout = armnn::DataLayout::NHWC;
surmeh01bceff2f2018-03-29 16:29:27 +01002376
2377 // The window size must be an odd value. For a window size of (2 * n + 1), TensorFlow defines depth_radius = n.
2378 normalizationDescriptor.m_NormSize = normalizationDescriptor.m_NormSize * 2 + 1;
2379
2380 IOutputSlot& prevLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
surmeh01bceff2f2018-03-29 16:29:27 +01002381 IConnectableLayer* layer = m_Network->AddNormalizationLayer(normalizationDescriptor,
2382 nodeDef.name().c_str());
ruoyan018174f362018-12-04 18:24:08 +00002383 prevLayerOutputSlot.Connect(layer->GetInputSlot(0));
2384 layer->GetOutputSlot(0).SetTensorInfo(prevLayerOutputSlot.GetTensorInfo());
surmeh01bceff2f2018-03-29 16:29:27 +01002385
2386 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2387}
2388
2389/// An ParsedTfOperation for a MatMul node.
telsoa01c577f2c2018-08-31 09:22:23 +01002390/// Creation of the armnn FullyConnected layer is deferred until it is actually needed, because
2391/// MatMul nodes are often used for the first part of a biased FullyConnected (MatMul followed
2392/// by Add) and in these cases armnn doesn't need a separate layer for the MatMul.
2393///
surmeh01bceff2f2018-03-29 16:29:27 +01002394class ParsedMatMulTfOperation : public DeferredSingleLayerParsedTfOperation
2395{
2396public:
2397 ParsedMatMulTfOperation(TfParser* parser, const tensorflow::NodeDef& node)
2398 : DeferredSingleLayerParsedTfOperation(parser, node)
2399 {
2400 }
2401
2402 void CreateLayerDeferred() override
2403 {
2404 BOOST_ASSERT(m_Layer == nullptr);
2405 m_Layer = m_Parser->AddFullyConnectedLayer(m_Node, nullptr, m_Node.name().c_str());
2406 }
2407};
2408
2409ParsedTfOperationPtr TfParser::ParseMatMul(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
2410{
telsoa01c577f2c2018-08-31 09:22:23 +01002411 // Defers the creation of the layer (see ParsedMatMulTfOperation).
surmeh01bceff2f2018-03-29 16:29:27 +01002412 return std::make_unique<ParsedMatMulTfOperation>(this, nodeDef);
2413}
2414
Ferran Balaguer51dd62f2019-01-11 19:29:18 +00002415ParsedTfOperationPtr TfParser::ParseMean(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
2416{
2417 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
2418 IOutputSlot& inputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2419 TensorInfo inputTensorInfo = inputSlot.GetTensorInfo();
2420
2421 if (inputs.size() != 2)
2422 {
2423 throw ParseException(
2424 boost::str(boost::format("Mean expects two inputs!. Got %1% for Node %2% %3%")
2425 % inputs.size()
2426 % nodeDef.name()
2427 % CHECK_LOCATION().AsString()));
2428 }
2429
2430 bool keepDims = ReadMandatoryNodeBoolAttribute(nodeDef, "keep_dims");
2431
2432 ParsedConstTfOperation<int32_t>* axisNode =
2433 boost::polymorphic_downcast<ParsedConstTfOperation<int32_t>*>(inputs[1].m_IndexedValue);
2434
2435 const TensorInfo& axisTensorInfo = axisNode->GetTensorInfo();
2436
2437 ConstTensor axisTensor(axisTensorInfo, axisNode->GetStorage());
2438 const int* axisData = static_cast<const int*>(axisTensor.GetMemoryArea());
2439
2440 TensorInfo outputTensorInfo;
2441 MeanDescriptor meanDescriptor;
2442 meanDescriptor.m_KeepDims = keepDims;
2443
2444 // Negative axis values are supported so that the process requires
2445 // to convert them into the corresponding positive ones.
2446 // Duplicate values are also removed.
2447 std::vector<int> rawAxisVector(axisData, axisData + axisTensorInfo.GetNumElements());
2448 std::set<unsigned int> positiveAxisSet;
2449 int rank = static_cast<int>(inputTensorInfo.GetNumDimensions());
2450
2451 std::transform(rawAxisVector.begin(), rawAxisVector.end(),
2452 std::inserter(positiveAxisSet, positiveAxisSet.begin()),
2453 [rank](int i) -> unsigned int { return static_cast<unsigned int>((i + rank) % rank); });
2454
2455 CalculateReducedOutputTensoInfo(inputTensorInfo, axisTensorInfo, positiveAxisSet, keepDims, outputTensorInfo);
2456
2457 if (inputTensorInfo.GetNumDimensions() > positiveAxisSet.size())
2458 {
2459 meanDescriptor.m_Axis.assign(positiveAxisSet.begin(), positiveAxisSet.end());
2460 }
2461
2462 IConnectableLayer* layer = m_Network->AddMeanLayer(meanDescriptor, nodeDef.name().c_str());
2463 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2464 inputSlot.Connect(layer->GetInputSlot(0));
2465
2466 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2467}
2468
telsoa01c577f2c2018-08-31 09:22:23 +01002469/// An ParsedTfOperation for a Mul node.
2470/// Creation of the armnn Mul layer is deferred until it is actually needed, because Mul nodes
2471/// are also used for the first part of a leaky relu activation function (Mul followed by Maximum)
2472/// and in these cases armnn doesn't need a separate layer for the Mul.
2473///
2474class ParsedMulTfOperation : public DeferredSingleLayerParsedTfOperation
2475{
2476public:
2477 ParsedMulTfOperation(TfParser* parser, const tensorflow::NodeDef& node)
2478 : DeferredSingleLayerParsedTfOperation(parser, node)
2479 {
2480 }
2481
2482 void CreateLayerDeferred() override
2483 {
2484 BOOST_ASSERT(m_Layer == nullptr);
2485 m_Layer = m_Parser->AddMultiplicationLayer(m_Node);
2486 }
2487};
2488
surmeh01bceff2f2018-03-29 16:29:27 +01002489ParsedTfOperationPtr TfParser::ParseMul(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
2490{
2491 boost::ignore_unused(graphDef);
2492
telsoa01c577f2c2018-08-31 09:22:23 +01002493 return std::make_unique<ParsedMulTfOperation>(this, nodeDef);
surmeh01bceff2f2018-03-29 16:29:27 +01002494}
2495
2496ParsedTfOperationPtr TfParser::ParsePlaceholder(const tensorflow::NodeDef& nodeDef,
2497 const tensorflow::GraphDef& graphDef)
2498{
2499 boost::ignore_unused(graphDef);
2500
2501 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 0);
2502
2503 const LayerBindingId layerId = boost::numeric_cast<LayerBindingId>(m_NetworkInputsBindingInfo.size());
2504
2505 auto it = m_InputShapes.find(nodeDef.name());
2506 if (it == m_InputShapes.end())
2507 {
telsoa01c577f2c2018-08-31 09:22:23 +01002508 throw ParseException(
2509 boost::str(
2510 boost::format(
2511 "Missing input shape for Placeholder '%1%' %2%")
2512 % nodeDef.name()
2513 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01002514 }
2515 TensorInfo tensorInfo(it->second, DataType::Float32);
2516
2517 IConnectableLayer* const layer = m_Network->AddInputLayer(layerId, nodeDef.name().c_str());
2518
2519 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
2520
2521 TrackInputBinding(layer, layerId, tensorInfo);
2522
2523 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2524}
2525
saoste01bbd40612018-08-28 15:41:51 +01002526ParsedTfOperationPtr TfParser::ParseRealDiv(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
2527{
2528 boost::ignore_unused(graphDef);
2529 return AddRealDivLayer(nodeDef);
2530}
2531
surmeh01bceff2f2018-03-29 16:29:27 +01002532ParsedTfOperationPtr TfParser::ParseRelu(const tensorflow::NodeDef& nodeDef,
2533 const tensorflow::GraphDef& graphDef)
2534{
2535 boost::ignore_unused(graphDef);
2536
2537 ActivationDescriptor activationDesc;
2538 activationDesc.m_Function = ActivationFunction::ReLu;
2539 return AddActivationLayer(nodeDef, activationDesc);
2540}
2541
2542ParsedTfOperationPtr TfParser::ParseRelu6(const tensorflow::NodeDef& nodeDef,
2543 const tensorflow::GraphDef& graphDef)
2544{
2545 boost::ignore_unused(graphDef);
2546
2547 ActivationDescriptor activationDesc;
2548 activationDesc.m_Function = ActivationFunction::BoundedReLu;
2549 activationDesc.m_A = 6.0f;
2550 activationDesc.m_B = 0.0f;
2551
2552 return AddActivationLayer(nodeDef, activationDesc);
2553}
2554
2555ParsedTfOperationPtr TfParser::ParseSigmoid(const tensorflow::NodeDef& nodeDef,
2556 const tensorflow::GraphDef& graphDef)
2557{
2558 boost::ignore_unused(graphDef);
2559
2560 ActivationDescriptor activationDesc;
2561 activationDesc.m_Function = ActivationFunction::Sigmoid;
2562
2563 return AddActivationLayer(nodeDef, activationDesc);
2564}
2565
Mohamed Nour Abouelseoud7a8892f2019-01-09 14:19:58 +00002566ParsedTfOperationPtr TfParser::ParseRsqrt(const tensorflow::NodeDef &nodeDef,
2567 const tensorflow::GraphDef &graphDef)
2568{
2569 boost::ignore_unused(graphDef);
2570
2571 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2572
2573 IConnectableLayer* const layer = m_Network->AddRsqrtLayer(nodeDef.name().c_str());
2574
2575 IOutputSlot& prevLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2576 prevLayerOutputSlot.Connect(layer->GetInputSlot(0));
2577 layer->GetOutputSlot(0).SetTensorInfo(prevLayerOutputSlot.GetTensorInfo());
2578
2579 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2580}
2581
surmeh01bceff2f2018-03-29 16:29:27 +01002582ParsedTfOperationPtr TfParser::ParseSoftmax(const tensorflow::NodeDef& nodeDef,
2583 const tensorflow::GraphDef& graphDef)
2584{
2585 boost::ignore_unused(graphDef);
2586
2587 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2588
2589 SoftmaxDescriptor softmaxDescriptor;
2590 IConnectableLayer* const layer = m_Network->AddSoftmaxLayer(softmaxDescriptor, nodeDef.name().c_str());
2591
2592 IOutputSlot& prevLayerSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2593 prevLayerSlot.Connect(layer->GetInputSlot(0));
2594 layer->GetOutputSlot(0).SetTensorInfo(prevLayerSlot.GetTensorInfo());
2595
2596 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2597}
2598
Sadik Armagan2ad6cb42018-12-27 11:23:44 +00002599ParsedTfOperationPtr TfParser::ParseSplit(const tensorflow::NodeDef& nodeDef,
2600 const tensorflow::GraphDef& graphDef)
2601{
2602 boost::ignore_unused(graphDef);
2603
2604 std::vector<OutputOfConstNodeDef> nodes = GetTfInputNodes(nodeDef);
2605 unsigned int numInputs = static_cast<unsigned int>(nodes.size());
2606 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, numInputs);
2607
2608 // The last input is the axis for split operation.
2609 if (!HasParsedConstTensor<int32_t>(inputs[numInputs - 1].m_IndexedValue->GetNode().name()))
2610 {
2611 throw ParseException(
2612 boost::str(
2613 boost::format(
2614 "ArmNN only supports split with constant axis. "
2615 "Input %1%. Node %2% %3%")
2616 % inputs[numInputs - 1].m_IndexedValue->GetNode().name()
2617 % nodeDef.name()
2618 % CHECK_LOCATION().AsString()));
2619 }
2620 ParsedConstTfOperation<int32_t>* shapeNode =
2621 boost::polymorphic_downcast<ParsedConstTfOperation<int32_t>*>(inputs[numInputs - 1].m_IndexedValue);
2622
2623 // Get the axis tensor data
2624 std::vector<int32_t> axisTensorData;
2625 shapeNode->GetConstTensor(axisTensorData);
2626
2627 // This splitDim indicates the data format: 3 is the NHWC, 1 is the NCHW.
2628 const unsigned int splitDim = static_cast<unsigned int>(axisTensorData[0]);
2629
2630 // Armnn supports split along the channel dimension for data formats NHWC and NCHW.
2631 if (splitDim == 0 || splitDim == 2)
2632 {
2633 throw ParseException(
2634 boost::str(
2635 boost::format(
2636 "Dimension %1% for split is not supported by Armnn. "
2637 "Node %2% %3%")
2638 % splitDim
2639 % nodeDef.name()
2640 % CHECK_LOCATION().AsString()));
2641 }
2642
2643 // As Armnn only supports splitter outputs of the same shape, therefore num_splits will be limited to an integer.
2644 uint32_t num_split = ReadMandatoryNodeUint32Attribute(nodeDef, "num_or_size_splits");
2645
2646 IOutputSlot& inputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2647 TensorInfo inputTensorInfo = inputSlot.GetTensorInfo();
2648
2649 if (inputTensorInfo.GetNumDimensions() != MaxNumOfTensorDimensions)
2650 {
2651 throw armnn::ParseException(
2652 boost::str(
2653 boost::format(
2654 "The number of dimensions: %1% for input tensors of the "
2655 "splitter op should be %2% %3%")
2656 % inputTensorInfo.GetNumDimensions()
2657 % MaxNumOfTensorDimensions
2658 % CHECK_LOCATION().AsString()));
2659 }
2660 auto inputDimSize = inputTensorInfo.GetNumDimensions();
2661
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
2913 if (input0Info.GetNumDimensions() == 1 && isBiasAdd == false)
2914 {
2915 layer->GetOutputSlot(0).SetTensorInfo(input1Slot->GetTensorInfo());
2916 }
2917 else
2918 {
2919 layer->GetOutputSlot(0).SetTensorInfo(input0Slot->GetTensorInfo());
2920 }
2921
2922 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2923}
2924
saoste01bbd40612018-08-28 15:41:51 +01002925ParsedTfOperationPtr TfParser::AddRealDivLayer(const tensorflow::NodeDef& nodeDef)
2926{
2927 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
2928
2929 IConnectableLayer* const layer = m_Network->AddDivisionLayer(nodeDef.name().c_str());
2930 IOutputSlot* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2931 IOutputSlot* input1Slot = &inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
2932
2933 auto const input0NumDims = input0Slot->GetTensorInfo().GetNumDimensions();
2934 auto const input1NumDims = input1Slot->GetTensorInfo().GetNumDimensions();
2935
2936
2937 if (input0NumDims < input1NumDims)
2938 {
2939 const bool isNHWC = true;
2940 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot, isNHWC, *m_Network, nodeDef);
2941 }
2942 if (input1NumDims < input0NumDims)
2943 {
2944 const bool isNHWC = true;
2945 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, isNHWC, *m_Network, nodeDef);
2946 }
2947
2948 input0Slot->Connect(layer->GetInputSlot(0));
2949 input1Slot->Connect(layer->GetInputSlot(1));
2950
2951 if (input0NumDims < input1NumDims)
2952 {
2953 layer->GetOutputSlot(0).SetTensorInfo(input1Slot->GetTensorInfo());
2954 }
2955 else
2956 {
2957 layer->GetOutputSlot(0).SetTensorInfo(input0Slot->GetTensorInfo());
2958
2959 }
2960 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
2961}
2962
Sadik Armagan975c09a2018-12-04 10:02:08 +00002963ParsedTfOperationPtr TfParser::AddMaximumLayer(const tensorflow::NodeDef& nodeDef)
2964{
2965 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
2966
2967 IOutputSlot* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2968 IOutputSlot* input1Slot = &inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
2969
2970 auto const input0NumDims = input0Slot->GetTensorInfo().GetNumDimensions();
2971 auto const input1NumDims = input1Slot->GetTensorInfo().GetNumDimensions();
2972
2973 if (input0NumDims < input1NumDims)
2974 {
2975 const bool isNHWC = true;
2976 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot, isNHWC, *m_Network, nodeDef);
2977 }
2978 if (input1NumDims < input0NumDims)
2979 {
2980 const bool isNHWC = true;
2981 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, isNHWC, *m_Network, nodeDef);
2982 }
2983
2984 IConnectableLayer* const layer = m_Network->AddMaximumLayer(nodeDef.name().c_str());
2985
2986 input0Slot->Connect(layer->GetInputSlot(0));
2987 input1Slot->Connect(layer->GetInputSlot(1));
2988
2989 TensorInfo outputInfo = input0Slot->GetTensorInfo();
2990 std::vector<unsigned int> outputShape;
2991
2992 const TensorShape& input0Shape = input0Slot->GetTensorInfo().GetShape();
2993 const TensorShape& input1Shape = input1Slot->GetTensorInfo().GetShape();
2994
2995 for (unsigned int i = 0; i < input0Shape.GetNumDimensions(); i++)
2996 {
2997 outputShape.push_back(std::max(input0Shape[i], input1Shape[i]));
2998 }
2999
3000 outputInfo.SetShape(TensorShape(input0Shape.GetNumDimensions(), outputShape.data()));
3001 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
3002
3003 return std::make_unique<SingleLayerParsedTfOperation>(this, nodeDef, layer);
3004}
3005
telsoa01c577f2c2018-08-31 09:22:23 +01003006IConnectableLayer* TfParser::AddMultiplicationLayer(const tensorflow::NodeDef& nodeDef)
3007{
3008 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
3009
3010 IConnectableLayer* const layer = m_Network->AddMultiplicationLayer(nodeDef.name().c_str());
3011 IOutputSlot* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
3012 IOutputSlot* input1Slot = &inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
3013
3014 auto const input0NumDims = input0Slot->GetTensorInfo().GetNumDimensions();
3015 auto const input1NumDims = input1Slot->GetTensorInfo().GetNumDimensions();
3016
3017 if (input0NumDims < input1NumDims)
3018 {
3019 const bool isNHWC = true;
saoste01bbd40612018-08-28 15:41:51 +01003020 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot, isNHWC, *m_Network, nodeDef);
telsoa01c577f2c2018-08-31 09:22:23 +01003021 }
3022 if (input1NumDims < input0NumDims)
3023 {
3024 const bool isNHWC = true;
saoste01bbd40612018-08-28 15:41:51 +01003025 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, isNHWC, *m_Network, nodeDef);
telsoa01c577f2c2018-08-31 09:22:23 +01003026 }
3027
3028 input0Slot->Connect(layer->GetInputSlot(0));
3029 input1Slot->Connect(layer->GetInputSlot(1));
3030
3031 if (input0NumDims < input1NumDims)
3032 {
3033 layer->GetOutputSlot(0).SetTensorInfo(input1Slot->GetTensorInfo());
3034 }
3035 else
3036 {
3037 layer->GetOutputSlot(0).SetTensorInfo(input0Slot->GetTensorInfo());
3038 }
3039 return layer;
3040}
3041
surmeh01bceff2f2018-03-29 16:29:27 +01003042IConnectableLayer* TfParser::AddFullyConnectedLayer(const tensorflow::NodeDef& matMulNodeDef,
3043 const tensorflow::NodeDef* addNodeDef, const char* armnnLayerName)
3044{
telsoa01c577f2c2018-08-31 09:22:23 +01003045 // Finds bias const (if applicable).
surmeh01bceff2f2018-03-29 16:29:27 +01003046 ParsedConstTfOperation<float>* biasNode = nullptr;
3047 if (addNodeDef != nullptr)
3048 {
3049 std::vector<OutputOfParsedTfOperation> addInputs = GetInputParsedTfOperationsChecked(*addNodeDef, 2);
telsoa01c577f2c2018-08-31 09:22:23 +01003050 // Finds our inputs.
surmeh01bceff2f2018-03-29 16:29:27 +01003051 if (HasParsedConstTensor<float>(addInputs[0].m_IndexedValue->GetNode().name()))
3052 {
3053 biasNode = boost::polymorphic_downcast<ParsedConstTfOperation<float>*>(addInputs[0].m_IndexedValue);
3054 }
3055 else if (HasParsedConstTensor<float>(addInputs[1].m_IndexedValue->GetNode().name()))
3056 {
3057 biasNode = boost::polymorphic_downcast<ParsedConstTfOperation<float>*>(addInputs[1].m_IndexedValue);
3058 }
3059 else
3060 {
telsoa01c577f2c2018-08-31 09:22:23 +01003061 throw ParseException(
3062 boost::str(
3063 boost::format(
3064 "ArmNN only supports fully connected layers with constant bias. "
3065 "Inputs %1% and %2%. AddNode %3%. MatMulNode %4% %5%")
3066 % addInputs[0].m_IndexedValue->GetNode().name()
3067 % addInputs[1].m_IndexedValue->GetNode().name()
3068 % addNodeDef->name()
3069 % matMulNodeDef.name()
3070 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003071 }
3072 }
3073
telsoa01c577f2c2018-08-31 09:22:23 +01003074 // Finds matmul inputs.
surmeh01bceff2f2018-03-29 16:29:27 +01003075 ParsedConstTfOperation<float>* weightNode = nullptr;
3076 ParsedTfOperation* inputNode = nullptr;
3077 unsigned int inputIdx = 0;
3078 std::vector<OutputOfParsedTfOperation> mulInputs = GetInputParsedTfOperationsChecked(matMulNodeDef, 2);
3079 if (HasParsedConstTensor<float>(mulInputs[0].m_IndexedValue->GetNode().name()))
3080 {
3081 weightNode = boost::polymorphic_downcast<ParsedConstTfOperation<float>*>(mulInputs[0].m_IndexedValue);
3082 inputNode = mulInputs[1].m_IndexedValue;
3083 inputIdx = mulInputs[1].m_Index;
3084 }
3085 else if (HasParsedConstTensor<float>(mulInputs[1].m_IndexedValue->GetNode().name()))
3086 {
3087 weightNode = boost::polymorphic_downcast<ParsedConstTfOperation<float>*>(mulInputs[1].m_IndexedValue);
3088 inputNode = mulInputs[0].m_IndexedValue;
3089 inputIdx = mulInputs[0].m_Index;
3090 }
3091 else
3092 {
telsoa01c577f2c2018-08-31 09:22:23 +01003093 throw ParseException(
3094 boost::str(
3095 boost::format(
3096 "ArmNN only supports fully connected layers with constant weights. "
3097 "Inputs %1% and %2%. MatMulNode %3% %4%")
3098 % mulInputs[0].m_IndexedValue->GetNode().name()
3099 % mulInputs[1].m_IndexedValue->GetNode().name()
3100 % matMulNodeDef.name()
3101 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003102 }
3103
3104 std::vector<float> weightTensorData;
telsoa01c577f2c2018-08-31 09:22:23 +01003105 // Handles weight.
Matteo Martincigh482ca852018-12-12 09:20:55 +00003106 ConstTensor weights = weightNode->GetConstTensor(weightTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +01003107
3108 FullyConnectedDescriptor desc;
3109 desc.m_BiasEnabled = addNodeDef != nullptr;
3110
3111 IConnectableLayer* layer = nullptr;
telsoa01c577f2c2018-08-31 09:22:23 +01003112 // Makes the layer.
surmeh01bceff2f2018-03-29 16:29:27 +01003113 if (addNodeDef != nullptr)
3114 {
3115 std::vector<float> biasTensorData;
Matteo Martincigh482ca852018-12-12 09:20:55 +00003116 ConstTensor biases = biasNode->GetConstTensor(biasTensorData);
surmeh01bceff2f2018-03-29 16:29:27 +01003117
3118 if (weights.GetShape()[1] != biases.GetShape()[0])
3119 {
telsoa01c577f2c2018-08-31 09:22:23 +01003120 throw ParseException(
3121 boost::str(
3122 boost::format(
3123 "Shape of matmul weights and bias do not match. "
3124 "AddNode %1%. MatMulNode %2% %3%")
3125 % addNodeDef->name()
3126 % matMulNodeDef.name()
3127 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003128 }
3129
3130 layer = m_Network->AddFullyConnectedLayer(desc, weights, biases, armnnLayerName);
3131 }
3132 else
3133 {
3134 layer = m_Network->AddFullyConnectedLayer(desc, weights, armnnLayerName);
3135 }
3136
3137 BOOST_ASSERT(layer != nullptr);
3138
3139 inputNode->ResolveArmnnOutputSlot(inputIdx).Connect(layer->GetInputSlot(0));
3140 unsigned int batches = inputNode->ResolveArmnnOutputSlot(inputIdx).GetTensorInfo().GetShape()[0];
3141
telsoa01c577f2c2018-08-31 09:22:23 +01003142 // Handles output.
surmeh01bceff2f2018-03-29 16:29:27 +01003143 TensorInfo outputInfo({ batches, weights.GetShape()[1] }, DataType::Float32);
3144 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
3145 return layer;
3146}
3147
3148void TfParser::LoadNodeDef(const tensorflow::NodeDef& nodeDef, const tensorflow::GraphDef& graphDef)
3149{
telsoa01c577f2c2018-08-31 09:22:23 +01003150 // Gets the type of the node (assume float).
surmeh01bceff2f2018-03-29 16:29:27 +01003151 tensorflow::DataType type = tensorflow::DT_FLOAT;
3152 if (nodeDef.attr().count("T") != 0)
3153 {
3154 auto attr = nodeDef.attr().at("T");
3155 type = attr.type();
3156 }
3157 else if (nodeDef.attr().count("dtype") != 0)
3158 {
3159 auto attr = nodeDef.attr().at("dtype");
3160 type = attr.type();
3161 }
3162
Ferran Balaguerc602f292019-02-08 17:09:55 +00003163 if ((type != tensorflow::DT_FLOAT && type != tensorflow::DT_INT32) && nodeDef.op() != "Const")
surmeh01bceff2f2018-03-29 16:29:27 +01003164 {
telsoa01c577f2c2018-08-31 09:22:23 +01003165 throw ParseException(
3166 boost::str(
3167 boost::format(
Ferran Balaguerc602f292019-02-08 17:09:55 +00003168 "Currently only FLOAT and INT32 are supported for tensorflow nodes (apart from Const). "
telsoa01c577f2c2018-08-31 09:22:23 +01003169 "Got %1% for Node %2% %3%")
3170 % tensorflow::DataType_Name(type)
3171 % nodeDef.name()
3172 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003173 }
3174
3175 const std::string& operation = nodeDef.op();
narpra016f37f832018-12-21 18:30:00 +00003176 auto itControlInput = std::find(m_ControlInputs.begin(), m_ControlInputs.end(), operation);
3177 if (itControlInput != m_ControlInputs.end())
3178 {
3179 // We currently allow Control Input from TensorFlow graph but we ignore them from ArmNN graph.
3180 return;
3181 }
surmeh01bceff2f2018-03-29 16:29:27 +01003182 auto it = ms_OperationNameToParsingFunctions.find(operation);
3183 if (it != ms_OperationNameToParsingFunctions.end())
3184 {
3185 auto func = it->second;
3186 ParsedTfOperationPtr parsedTfOperation = (this->*func)(nodeDef, graphDef);
3187 ParsedTfOperation* parsedTfOperationRaw = parsedTfOperation.get();
3188
telsoa01c577f2c2018-08-31 09:22:23 +01003189 // Stores the parsed operation so that dependent layers can connect to it.
surmeh01bceff2f2018-03-29 16:29:27 +01003190 auto it = m_ParsedTfOperations.find(nodeDef.name());
3191 if (it != m_ParsedTfOperations.end())
3192 {
3193 throw ParseException(boost::str(boost::format("Name %1% used by more than one node") % nodeDef.name()));
3194 }
3195 m_ParsedTfOperations[nodeDef.name()] = std::move(parsedTfOperation);
3196
telsoa01c577f2c2018-08-31 09:22:23 +01003197 // If this node was requested as an output from the network, then adds an ArmNN output layer.
surmeh01bceff2f2018-03-29 16:29:27 +01003198 if (std::find(m_RequestedOutputs.begin(), m_RequestedOutputs.end(), nodeDef.name()) !=
3199 m_RequestedOutputs.end())
3200 {
3201 auto outId = ParseOutputId(nodeDef.name());
3202 const LayerBindingId layerId = boost::numeric_cast<LayerBindingId>(m_NetworkOutputsBindingInfo.size());
3203 IOutputSlot& prevSlot = parsedTfOperationRaw->ResolveArmnnOutputSlot(outId.m_Index);
3204
3205 TensorInfo tensorInfo = prevSlot.GetTensorInfo();
3206
3207 IConnectableLayer* outputLayer = m_Network->AddOutputLayer(layerId, nodeDef.name().c_str());
3208
3209 prevSlot.Connect(outputLayer->GetInputSlot(0));
3210
3211 TrackOutputBinding(outputLayer, layerId, tensorInfo);
3212 }
3213 }
3214 else
3215 {
telsoa01c577f2c2018-08-31 09:22:23 +01003216 throw ParseException(
3217 boost::str(
3218 boost::format(
3219 "Unsupported operation %1% in tensorflow::GraphDef %2%")
3220 % operation
3221 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003222 }
3223}
3224
3225void TfParser::LoadGraphDef(const tensorflow::GraphDef& graphDef)
3226{
telsoa01c577f2c2018-08-31 09:22:23 +01003227 // Adds all nodes to our map.
surmeh01bceff2f2018-03-29 16:29:27 +01003228 m_NodesByName.clear();
3229 m_NetworkInputsBindingInfo.clear();
3230 m_NetworkOutputsBindingInfo.clear();
3231
3232 for (int i = 0; i < graphDef.node_size(); ++i)
3233 {
3234 const tensorflow::NodeDef& node = graphDef.node(i);
3235 m_NodesByName[node.name()] = &node;
3236 }
3237
telsoa01c577f2c2018-08-31 09:22:23 +01003238 // Finds the output nodes the user requested.
surmeh01bceff2f2018-03-29 16:29:27 +01003239 std::vector<const tensorflow::NodeDef*> targetNodes;
3240 for (const std::string& requestedOutputName : m_RequestedOutputs)
3241 {
3242 auto nodeIt = m_NodesByName.find(requestedOutputName);
3243 if (nodeIt == m_NodesByName.end())
3244 {
telsoa01c577f2c2018-08-31 09:22:23 +01003245 throw ParseException(
3246 boost::str(
3247 boost::format(
3248 "Couldn't find requested output node '%1%' in graph %2%")
3249 % requestedOutputName
3250 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003251 }
3252 targetNodes.push_back(nodeIt->second);
3253 }
3254
telsoa01c577f2c2018-08-31 09:22:23 +01003255 // Sorts them into a linear ordering such that all inputs of a node are before the node itself.
surmeh01bceff2f2018-03-29 16:29:27 +01003256 std::vector<const tensorflow::NodeDef*> sortedNodes;
3257 if (!armnnUtils::GraphTopologicalSort<const tensorflow::NodeDef*>(
3258 targetNodes,
3259 [this](const tensorflow::NodeDef* node)
3260 {
3261 auto outputs = GetTfInputNodes(*node);
3262 std::vector<const tensorflow::NodeDef*> nodesOnly;
3263 for (const auto & o : outputs) {
3264 nodesOnly.push_back(o.m_IndexedValue);
3265 }
3266 return nodesOnly;
3267 },
3268 sortedNodes))
3269 {
telsoa01c577f2c2018-08-31 09:22:23 +01003270 throw ParseException(
3271 boost::str(
3272 boost::format(
3273 "Cycle detected in graph %1%")
3274 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003275 }
3276
telsoa01c577f2c2018-08-31 09:22:23 +01003277 // 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 +01003278 for (const auto& it : sortedNodes)
3279 {
3280 const tensorflow::NodeDef& currentNode = *it;
3281 LoadNodeDef(currentNode, graphDef);
3282 }
3283}
3284
3285INetworkPtr TfParser::CreateNetworkFromTextFile(const char* graphFile,
3286 const std::map<std::string, TensorShape>& inputShapes,
3287 const std::vector<std::string>& requestedOutputs)
3288{
3289 FILE* fd = fopen(graphFile, "r");
3290
3291 if (fd == nullptr)
3292 {
telsoa01c577f2c2018-08-31 09:22:23 +01003293 throw FileNotFoundException(
3294 boost::str(
3295 boost::format(
3296 "Graph file %1% failed to open %2%")
3297 % graphFile
3298 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003299 }
3300
telsoa01c577f2c2018-08-31 09:22:23 +01003301 // Parses the file into a message.
surmeh01bceff2f2018-03-29 16:29:27 +01003302 tensorflow::GraphDef graphDef;
3303 auto input = new google::protobuf::io::FileInputStream(fileno(fd));
3304 bool success = google::protobuf::TextFormat::Parse(input, &graphDef);
3305 delete input;
3306 fclose(fd);
3307
3308 if (!success)
3309 {
telsoa01c577f2c2018-08-31 09:22:23 +01003310 throw ParseException(
3311 boost::str(
3312 boost::format(
3313 "Failed to parse graph file %1%")
3314 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003315 }
3316
3317 return CreateNetworkFromGraphDef(graphDef, inputShapes, requestedOutputs);
3318}
3319
3320INetworkPtr TfParser::CreateNetworkFromString(const char* protoText,
3321 const std::map<std::string, TensorShape>& inputShapes,
3322 const std::vector<std::string>& requestedOutputs)
3323{
telsoa01c577f2c2018-08-31 09:22:23 +01003324 // Parses the string into a message.
surmeh01bceff2f2018-03-29 16:29:27 +01003325 tensorflow::GraphDef graphDef;
3326 bool success = google::protobuf::TextFormat::ParseFromString(protoText, &graphDef);
3327
3328 if (!success)
3329 {
telsoa01c577f2c2018-08-31 09:22:23 +01003330 throw ParseException(
3331 boost::str(
3332 boost::format(
3333 "Failed to parse graph file %1%")
3334 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003335 }
3336
3337 return CreateNetworkFromGraphDef(graphDef, inputShapes, requestedOutputs);
3338}
3339
3340INetworkPtr TfParser::CreateNetworkFromBinaryFile(const char* graphFile,
3341 const std::map<std::string, TensorShape>& inputShapes,
3342 const std::vector<std::string>& requestedOutputs)
3343{
3344 FILE* fd = fopen(graphFile, "rb");
3345
3346 if (fd == nullptr)
3347 {
telsoa01c577f2c2018-08-31 09:22:23 +01003348 throw FileNotFoundException(
3349 boost::str(
3350 boost::format(
3351 "Graph file %1% failed to open %2%")
3352 % graphFile
3353 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003354 }
3355
telsoa01c577f2c2018-08-31 09:22:23 +01003356 // Parses the file into a message.
surmeh01bceff2f2018-03-29 16:29:27 +01003357 tensorflow::GraphDef graphDef;
3358
3359 google::protobuf::io::FileInputStream inStream(fileno(fd));
3360 google::protobuf::io::CodedInputStream codedStream(&inStream);
3361 codedStream.SetTotalBytesLimit(INT_MAX, INT_MAX);
3362 bool success = graphDef.ParseFromCodedStream(&codedStream);
3363 fclose(fd);
3364
3365 if (!success)
3366 {
telsoa01c577f2c2018-08-31 09:22:23 +01003367 throw ParseException(
3368 boost::str(
3369 boost::format(
3370 "Failed to parse protobuf file %1% %2%")
3371 % graphFile
3372 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003373 }
3374
3375 return CreateNetworkFromGraphDef(graphDef, inputShapes, requestedOutputs);
3376}
3377
3378INetworkPtr TfParser::CreateNetworkFromGraphDef(const tensorflow::GraphDef& graphDef,
3379 const std::map<std::string, TensorShape>& inputShapes,
3380 const std::vector<std::string>& requestedOutputs)
3381{
3382 m_Network = INetwork::Create();
3383
3384 m_InputShapes = inputShapes;
3385 if (requestedOutputs.size() == 0)
3386 {
telsoa01c577f2c2018-08-31 09:22:23 +01003387 throw ParseException(
3388 boost::str(
3389 boost::format(
3390 "requestedOutputs must have at least one entry %1%")
3391 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003392 }
3393 m_RequestedOutputs = requestedOutputs;
3394
3395 try
3396 {
3397 LoadGraphDef(graphDef);
3398 }
3399 catch (const ParseException& e)
3400 {
3401 Cleanup();
3402 throw e;
3403 }
3404
3405 Cleanup();
3406
3407 return std::move(m_Network);
3408}
3409
3410void TfParser::Cleanup()
3411{
telsoa01c577f2c2018-08-31 09:22:23 +01003412 // Cleanup, in case we reuse this parser.
surmeh01bceff2f2018-03-29 16:29:27 +01003413 m_InputShapes.clear();
3414 m_RequestedOutputs.clear();
3415 m_NodesByName.clear();
3416 m_ParsedTfOperations.clear();
3417}
3418
3419BindingPointInfo TfParser::GetNetworkInputBindingInfo(const std::string& name) const
3420{
3421 return GetBindingInfo(name, "input", m_NetworkInputsBindingInfo);
3422}
3423
3424BindingPointInfo TfParser::GetNetworkOutputBindingInfo(const std::string& name) const
3425{
3426 return GetBindingInfo(name, "output", m_NetworkOutputsBindingInfo);
3427}
3428
3429std::pair<LayerBindingId, TensorInfo> TfParser::GetBindingInfo(const std::string& layerName,
3430 const char* bindingPointDesc,
3431 const std::unordered_map<std::string, BindingPointInfo>& nameToBindingInfo)
3432{
3433 auto it = nameToBindingInfo.find(layerName);
3434 if (it == nameToBindingInfo.end())
3435 {
telsoa01c577f2c2018-08-31 09:22:23 +01003436 throw InvalidArgumentException(
3437 boost::str(
3438 boost::format(
3439 "Unknown %1% '%2%' %3%")
3440 % bindingPointDesc
3441 % layerName
3442 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003443 }
3444 return it->second;
3445}
3446
3447void TfParser::TrackInputBinding(IConnectableLayer* layer, LayerBindingId id, const TensorInfo& tensorInfo)
3448{
3449 return TrackBindingPoint(layer, id, tensorInfo, "input", m_NetworkInputsBindingInfo);
3450}
3451
3452void TfParser::TrackOutputBinding(IConnectableLayer* layer, LayerBindingId id, const TensorInfo& tensorInfo)
3453{
3454 return TrackBindingPoint(layer, id, tensorInfo, "output", m_NetworkOutputsBindingInfo);
3455}
3456
3457void TfParser::TrackBindingPoint(IConnectableLayer* layer,
3458 LayerBindingId id,
3459 const TensorInfo& tensorInfo,
3460 const char* bindingPointDesc,
3461 std::unordered_map<std::string, BindingPointInfo>& nameToBindingInfo)
3462{
3463 const std::string layerName = layer->GetName();
3464 auto it = nameToBindingInfo.find(layerName);
3465 if (it == nameToBindingInfo.end())
3466 {
3467 nameToBindingInfo[layerName] = std::make_pair(id, tensorInfo);
3468 }
3469 else
3470 {
telsoa01c577f2c2018-08-31 09:22:23 +01003471 throw ParseException(
3472 boost::str(
3473 boost::format(
3474 "Id %1% used by more than one %2% layer %3%")
3475 % id
3476 % bindingPointDesc
3477 % CHECK_LOCATION().AsString()));
surmeh01bceff2f2018-03-29 16:29:27 +01003478 }
3479}
3480
3481} // namespace armnnTfParser