blob: f345d4a6e1a8a09ecc589bccf169e20ee554263c [file] [log] [blame]
telsoa01c577f2c2018-08-31 09:22:23 +01001//
2// Copyright © 2017 Arm Ltd. All rights reserved.
David Beckecb56cd2018-09-05 12:52:57 +01003// SPDX-License-Identifier: MIT
telsoa01c577f2c2018-08-31 09:22:23 +01004//
5#include "TfLiteParser.hpp"
6
7#include <armnn/ArmNN.hpp>
8#include <armnn/Exceptions.hpp>
9#include <armnn/TypesUtils.hpp>
10#include <boost/filesystem.hpp>
11
12// armnnUtils:
Sadik Armagan479045b2018-10-01 11:51:37 +010013#include <ParserHelper.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010014#include <Permute.hpp>
15#include <VerificationHelpers.hpp>
16
17// The generated code based on the Tf Lite schema:
18#include <schema_generated.h>
19
20#include <boost/core/ignore_unused.hpp>
21#include <boost/assert.hpp>
22#include <boost/format.hpp>
23#include <boost/log/trivial.hpp>
Aron Virginas-Tard4f0fea2019-04-09 14:08:06 +010024#include <boost/format.hpp>
25#include <boost/numeric/conversion/cast.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010026
27#include <fstream>
28#include <algorithm>
29#include <limits>
Sadikb94967b2018-09-19 15:30:00 +010030#include <numeric>
keidav011b3e2ea2019-02-21 10:07:37 +000031#include <flatbuffers/flexbuffers.h>
telsoa01c577f2c2018-08-31 09:22:23 +010032
33using namespace armnn;
34using armnn::CheckLocation;
35namespace armnnTfLiteParser
36{
37namespace
38{
jimfly01c25411c2018-11-14 17:47:22 +000039
telsoa01c577f2c2018-08-31 09:22:23 +010040const uint32_t VIRTUAL_OPERATOR_ID = std::numeric_limits<uint32_t>::max();
41
42void CheckSubgraph(const TfLiteParser::ModelPtr & model,
43 size_t subgraphIndex,
44 const CheckLocation & location)
45{
46 if (model.get() == nullptr)
47 {
48 throw ParseException(
49 boost::str(
50 boost::format("%1% was called with invalid (null) model. "
51 "Possible reason is that the model is not yet loaded and Unpack(ed). "
52 "subgraph:%2% at %3%") %
53 location.m_Function %
54 subgraphIndex %
55 location.FileLine()));
56 }
57 else if (subgraphIndex >= model->subgraphs.size())
58 {
59 throw ParseException(
60 boost::str(
61 boost::format("%1% was called with an invalid subgraph index. "
62 "subgraph:%2% at %3%") %
63 location.m_Function %
64 subgraphIndex %
65 location.FileLine()));
66 }
67}
68
69#define CHECK_SUBGRAPH(MODEL, SUBGRAPH_INDEX) \
70 CheckSubgraph(MODEL, SUBGRAPH_INDEX, CHECK_LOCATION())
71
72void CheckModel(const TfLiteParser::ModelPtr & model,
73 size_t subgraphIndex,
74 size_t operatorIndex,
75 const CheckLocation & location)
76{
77 if (model.get() == nullptr)
78 {
79 throw ParseException(
80 boost::str(
81 boost::format("%1% was called with invalid (null) model. "
82 "Possible reason is that the model is not yet loaded and Unpack(ed). "
83 "subgraph:%2% operator:%3% at %4%") %
84 location.m_Function %
85 subgraphIndex %
86 operatorIndex %
87 location.FileLine()));
88 }
89 else if (subgraphIndex >= model->subgraphs.size())
90 {
91 throw ParseException(
92 boost::str(
93 boost::format("%1% was called with an invalid subgraph index. "
94 "subgraph:%2% operator:%3% at %4%") %
95 location.m_Function %
96 subgraphIndex %
97 operatorIndex %
98 location.FileLine()));
99 }
100 else if (operatorIndex >= model->subgraphs[subgraphIndex]->operators.size() &&
101 operatorIndex != VIRTUAL_OPERATOR_ID)
102 {
103 throw ParseException(
104 boost::str(
105 boost::format("%1% was called with an invalid operator index. "
106 "subgraph:%2% operator:%3% at %4%") %
107 location.m_Function %
108 subgraphIndex %
109 operatorIndex %
110 location.FileLine()));
111 }
112}
113
114#define CHECK_MODEL(MODEL, SUBGRAPH_INDEX, OPERATOR_INDEX) \
115 CheckModel(MODEL, SUBGRAPH_INDEX, OPERATOR_INDEX, CHECK_LOCATION())
116
117void CheckTensor(const TfLiteParser::ModelPtr & model,
118 size_t subgraphIndex,
119 size_t tensorIndex,
120 const CheckLocation & location)
121{
122 // not checking model, because I assume CHECK_MODEL already run
123 // and checked that. An assert would do.
124 BOOST_ASSERT_MSG(model.get() != nullptr, "Expecting a valid model in this function");
125
126 // also subgraph index should be checked by CHECK_MODEL so
127 // I only add an assert here
128 BOOST_ASSERT_MSG(subgraphIndex < model->subgraphs.size(), "Expecting a valid subgraph index");
129
130 // the tensor index is the only one to check here
131 if (tensorIndex >= model->subgraphs[subgraphIndex]->tensors.size())
132 {
133 throw ParseException(
134 boost::str(
135 boost::format("%1% was called with an invalid tensor index. "
136 "subgraph:%2% tensor:%3% at %4%") %
137 location.m_Function %
138 subgraphIndex %
139 tensorIndex %
140 location.FileLine()));
141 }
142}
143
144#define CHECK_TENSOR(MODEL, SUBGRAPH_INDEX, TENSOR_INDEX) \
145 CheckTensor(MODEL, SUBGRAPH_INDEX, TENSOR_INDEX, CHECK_LOCATION())
146
147void CheckTensorPtr(TfLiteParser::TensorRawPtr rawPtr,
148 const CheckLocation & location)
149{
150 if (rawPtr == nullptr)
151 {
152 throw ParseException(
153 boost::str(
154 boost::format("%1% was called with a null tensor pointer. "
155 "at %2%") %
156 location.m_Function %
157 location.FileLine()));
158
159 }
160}
161
162#define CHECK_TENSOR_PTR(TENSOR_PTR) \
163 CheckTensorPtr(TENSOR_PTR, CHECK_LOCATION())
164
165void CheckBuffer(const TfLiteParser::ModelPtr & model,
166 size_t bufferIndex,
167 const CheckLocation & location)
168{
169 if (model.get() == nullptr)
170 {
171 throw ParseException(
172 boost::str(
173 boost::format("%1% was called with invalid (null) model. "
174 "Possible reason is that the model is not yet loaded and Unpack(ed). "
175 "buffer:%2% at %3%") %
176 location.m_Function %
177 bufferIndex %
178 location.FileLine()));
179 }
180 else if (bufferIndex >= model->buffers.size())
181 {
182 throw ParseException(
183 boost::str(
184 boost::format("%1% was called with an invalid buffer index. "
185 "buffer index:%2% at %3%") %
186 location.m_Function %
187 bufferIndex %
188 location.FileLine()));
189 }
190 else if (model->buffers[bufferIndex].get() == nullptr)
191 {
192 throw ParseException(
193 boost::str(
194 boost::format("The buffer #%1% is null. %3%") %
195 bufferIndex %
196 location.AsString()));
197 }
198}
199
200#define CHECK_BUFFER(MODEL, BUFFER_INDEX) \
201 CheckBuffer(MODEL, BUFFER_INDEX, CHECK_LOCATION())
202
203void CheckBufferSize(TfLiteParser::BufferRawPtr bufferPtr,
204 const armnn::TensorInfo & tensorInfo,
205 uint32_t bufferId,
206 const CheckLocation & location)
207{
208 if (bufferPtr == nullptr)
209 {
210 throw ParseException(
211 boost::str(
212 boost::format("BufferPtr is null for buffer:%1%. %2%") %
213 bufferId %
214 location.AsString()));
215 }
216 else if(tensorInfo.GetNumElements() > bufferPtr->data.size() ||
217 tensorInfo.GetNumBytes() > bufferPtr->data.size())
218 {
219 std::stringstream ss;
220 ss << "Buffer #" << bufferId << " has " << bufferPtr->data.size() << " bytes. "
221 << "For tensor: " << tensorInfo.GetShape()
222 << " expecting: " << tensorInfo.GetNumBytes() << " bytes and "
223 << tensorInfo.GetNumElements() << " elements. " << location.AsString();
224 throw ParseException(ss.str());
225 }
226}
227
228#define CHECK_BUFFER_SIZE(BUFFER_PTR, TENSOR_INFO, BUFFER_ID) \
229 CheckBufferSize(BUFFER_PTR, TENSOR_INFO, BUFFER_ID, CHECK_LOCATION())
230
231bool IsActivationSupported(tflite::ActivationFunctionType activationType)
232{
233 switch(activationType)
234 {
235 case tflite::ActivationFunctionType_NONE:
236 case tflite::ActivationFunctionType_RELU:
237 case tflite::ActivationFunctionType_RELU6:
238 case tflite::ActivationFunctionType_TANH:
239 {
240 return true;
241 }
242 default:
243 {
244 return false;
245 }
246 }
247}
248
249#define CHECK_SUPPORTED_FUSED_ACTIVATION(OPTION, SUBGRAPH_INDEX, OPERATOR_INDEX) \
250 do { \
251 if (IsActivationSupported(OPTION->fused_activation_function) == false) \
252 { \
253 throw ParseException( \
254 boost::str( \
255 boost::format("TfLite parser doesn't suppport fused activation: " \
256 "%1%/%2% in %3% subgraph:%4% operator:%5% at %6%") % \
257 OPTION->fused_activation_function % \
258 tflite::EnumNameActivationFunctionType(\
259 OPTION->fused_activation_function) % \
260 __func__ % \
261 SUBGRAPH_INDEX % \
262 OPERATOR_INDEX % \
263 CHECK_LOCATION().FileLine())); \
264 } \
265 } while(false)
266
267
268std::vector<unsigned int> AsUnsignedVector(const std::vector<int32_t> & in)
269{
270 std::vector<unsigned int> result;
271 result.reserve(in.size());
272 for (auto & i : in)
273 {
274 result.push_back(CHECKED_NON_NEGATIVE(i));
275 }
276 return result;
277}
278
279void CalcPadding(uint32_t inputSize,
280 uint32_t filterSize,
281 uint32_t stride,
Pablo Tellof0bd6832019-04-26 17:58:13 +0100282 uint32_t dilation,
telsoa01c577f2c2018-08-31 09:22:23 +0100283 uint32_t& paddingFront,
284 uint32_t& paddingBack,
285 tflite::Padding padding)
286{
287 paddingFront = 0;
288 paddingBack = 0;
289 if (padding == tflite::Padding_SAME)
290 {
291 uint32_t outputSize = (inputSize + stride - 1) / stride;
Pablo Tellof0bd6832019-04-26 17:58:13 +0100292 uint32_t dilatedSize = filterSize + (dilation - 1) * (filterSize - 1);
293 uint32_t temp = (outputSize - 1) * stride + dilatedSize;
telsoa01c577f2c2018-08-31 09:22:23 +0100294 if (temp > inputSize)
295 {
296 paddingFront = (temp - inputSize) / 2;
297 paddingBack = (temp - inputSize) - paddingFront;
298 }
299 }
300}
301
Narumol Prangnawarat4628d052019-02-25 17:26:05 +0000302armnn::TensorInfo ToTensorInfo(TfLiteParser::TensorRawPtr tensorPtr, const std::vector<unsigned int>& shapes)
telsoa01c577f2c2018-08-31 09:22:23 +0100303{
304 armnn::DataType type;
305 CHECK_TENSOR_PTR(tensorPtr);
306
307 switch (tensorPtr->type)
308 {
309 case tflite::TensorType_UINT8:
310 type = armnn::DataType::QuantisedAsymm8;
311 break;
312 case tflite::TensorType_FLOAT32:
313 type = armnn::DataType::Float32;
314 break;
315 case tflite::TensorType_INT32:
316 type = armnn::DataType::Signed32;
317 break;
318
319 default:
320 {
321 CheckLocation location = CHECK_LOCATION();
322 throw ParseException(
323 boost::str(
324 boost::format("Unsupported data type %1% = %2% for tensor: %3%. %4%") %
325 tensorPtr->type %
326 tflite::EnumNameTensorType(tensorPtr->type) %
327 tensorPtr->name %
328 location.AsString()));
329 }
330 }
331
332 float quantizationScale = 0.0f;
333 int32_t quantizationOffset = 0;
334
335 if (tensorPtr->quantization.get())
336 {
337 CHECK_VALID_SIZE(tensorPtr->quantization->scale.size(), 0, 1);
338 CHECK_VALID_SIZE(tensorPtr->quantization->zero_point.size(), 0, 1);
339
340 if (tensorPtr->quantization->scale.size() == 1)
341 {
342 quantizationScale = tensorPtr->quantization->scale[0];
343 }
344 if (tensorPtr->quantization->zero_point.size() == 1)
345 {
346 // NOTE: we lose precision here when converting from 64 bit to 32
347 // but this is what we support at the monent in ArmNN
348 quantizationOffset = static_cast<int32_t>(tensorPtr->quantization->zero_point[0]);
349 }
350 }
351
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100352 std::vector<unsigned int> safeShape = shapes;
353 if (safeShape.size() == 0)
354 {
355 safeShape.push_back(1);
356 }
357
telsoa01c577f2c2018-08-31 09:22:23 +0100358 // two statements (on purpose) for easier debugging:
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100359 armnn::TensorInfo result(static_cast<unsigned int>(safeShape.size()),
360 safeShape.data(),
telsoa01c577f2c2018-08-31 09:22:23 +0100361 type,
362 quantizationScale,
363 quantizationOffset);
364 return result;
365}
366
Narumol Prangnawarat4628d052019-02-25 17:26:05 +0000367armnn::TensorInfo ToTensorInfo(TfLiteParser::TensorRawPtr tensorPtr)
368{
369 auto const & dimensions = AsUnsignedVector(tensorPtr->shape);
370 return ToTensorInfo(tensorPtr, dimensions);
371}
372
telsoa01c577f2c2018-08-31 09:22:23 +0100373template<typename T>
374std::pair<armnn::ConstTensor, std::unique_ptr<T[]>>
375CreateConstTensorImpl(TfLiteParser::BufferRawPtr bufferPtr,
376 TfLiteParser::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +0000377 armnn::TensorInfo& tensorInfo,
378 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +0100379{
380 BOOST_ASSERT_MSG(tensorPtr != nullptr, "tensorPtr is null");
381 BOOST_ASSERT_MSG(bufferPtr != nullptr,
382 boost::str(
383 boost::format("Buffer for buffer:%1% is null") % tensorPtr->buffer).c_str());
384
385 std::unique_ptr<T[]> data(new T[tensorInfo.GetNumElements()]);
Matteo Martincigh747ef822018-12-18 09:26:39 +0000386
387 if (permutationVector.has_value() && permutationVector.value().GetSize() > 0)
388 {
389 tensorInfo = armnnUtils::Permuted(tensorInfo, permutationVector.value());
Matteo Martincighd5b9e642019-01-04 18:01:21 +0000390 armnnUtils::Permute(tensorInfo.GetShape(), permutationVector.value(),
391 reinterpret_cast<const T*>(bufferPtr->data.data()), data.get(), sizeof(T));
Matteo Martincigh747ef822018-12-18 09:26:39 +0000392 }
393 else
394 {
395 ::memcpy(data.get(), bufferPtr->data.data(), tensorInfo.GetNumBytes());
396 }
397
telsoa01c577f2c2018-08-31 09:22:23 +0100398 return std::make_pair(ConstTensor(tensorInfo, data.get()), std::move(data));
399}
400
telsoa01c577f2c2018-08-31 09:22:23 +0100401armnn::LayerBindingId GenerateLayerBindingId(size_t subgraphIndex, size_t tensorIndex)
402{
403 // generate the binding id by shifting the tensor id by 8 bit
404 // and add the subgraph id, which allows 256 subgraphs
405 return static_cast<armnn::LayerBindingId>((tensorIndex<<8)+subgraphIndex);
406}
407
Aron Virginas-Tar70672f62019-01-23 14:00:00 +0000408bool CheckShape(const armnn::TensorShape& actual, const std::vector<int32_t>& expected)
409{
410 const unsigned int actualSize = actual.GetNumDimensions();
411 if (actualSize != expected.size())
412 {
413 return false;
414 }
415
416 for (unsigned int i = 0u; i < actualSize; i++)
417 {
418 if (expected[i] < 0 ||
419 actual[i] != static_cast<unsigned int>(expected[i]))
420 {
421 return false;
422 }
423 }
424
425 return true;
426}
427
telsoa01c577f2c2018-08-31 09:22:23 +0100428} // <anonymous>
429
430TfLiteParser::TfLiteParser()
431: m_Network(nullptr, nullptr)
432, m_ParserFunctions(tflite::BuiltinOperator_MAX+1, &TfLiteParser::ParseUnsupportedOperator)
433{
434 // register supported operators
435 m_ParserFunctions[tflite::BuiltinOperator_AVERAGE_POOL_2D] = &TfLiteParser::ParseAveragePool2D;
Bruno Goncalvesdb947e22019-02-08 18:52:21 -0200436 m_ParserFunctions[tflite::BuiltinOperator_BATCH_TO_SPACE_ND] = &TfLiteParser::ParseBatchToSpaceND;
Sadik Armagan479045b2018-10-01 11:51:37 +0100437 m_ParserFunctions[tflite::BuiltinOperator_CONCATENATION] = &TfLiteParser::ParseConcatenation;
telsoa01c577f2c2018-08-31 09:22:23 +0100438 m_ParserFunctions[tflite::BuiltinOperator_CONV_2D] = &TfLiteParser::ParseConv2D;
439 m_ParserFunctions[tflite::BuiltinOperator_DEPTHWISE_CONV_2D] = &TfLiteParser::ParseDepthwiseConv2D;
keidav011b3e2ea2019-02-21 10:07:37 +0000440 m_ParserFunctions[tflite::BuiltinOperator_CUSTOM] = &TfLiteParser::ParseDetectionPostProcess;
Sadik Armagan8853c1f2018-10-22 09:04:18 +0100441 m_ParserFunctions[tflite::BuiltinOperator_FULLY_CONNECTED] = &TfLiteParser::ParseFullyConnected;
Finn Williamsc42c3842019-01-22 14:18:11 +0000442 m_ParserFunctions[tflite::BuiltinOperator_LOGISTIC] = &TfLiteParser::ParseLogistic;
Matthew Jackson28c94572019-07-18 10:47:03 +0100443 m_ParserFunctions[tflite::BuiltinOperator_L2_NORMALIZATION] = &TfLiteParser::ParseL2Normalization;
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +0100444 m_ParserFunctions[tflite::BuiltinOperator_MAX_POOL_2D] = &TfLiteParser::ParseMaxPool2D;
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -0200445 m_ParserFunctions[tflite::BuiltinOperator_MAXIMUM] = &TfLiteParser::ParseMaximum;
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -0200446 m_ParserFunctions[tflite::BuiltinOperator_MINIMUM] = &TfLiteParser::ParseMinimum;
Sadik Armagan58f39192018-09-17 14:14:39 +0100447 m_ParserFunctions[tflite::BuiltinOperator_RELU] = &TfLiteParser::ParseRelu;
448 m_ParserFunctions[tflite::BuiltinOperator_RELU6] = &TfLiteParser::ParseRelu6;
Sadikb94967b2018-09-19 15:30:00 +0100449 m_ParserFunctions[tflite::BuiltinOperator_RESHAPE] = &TfLiteParser::ParseReshape;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -0200450 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_BILINEAR] = &TfLiteParser::ParseResizeBilinear;
Sadik Armagan479045b2018-10-01 11:51:37 +0100451 m_ParserFunctions[tflite::BuiltinOperator_SOFTMAX] = &TfLiteParser::ParseSoftmax;
Bruno Goncalvesbaded142019-02-08 19:02:48 -0200452 m_ParserFunctions[tflite::BuiltinOperator_SPACE_TO_BATCH_ND] = &TfLiteParser::ParseSpaceToBatchND;
Sadik Armagan479045b2018-10-01 11:51:37 +0100453 m_ParserFunctions[tflite::BuiltinOperator_SQUEEZE] = &TfLiteParser::ParseSqueeze;
Bruno Goncalves451d95b2019-02-12 22:59:22 -0200454 m_ParserFunctions[tflite::BuiltinOperator_STRIDED_SLICE] = &TfLiteParser::ParseStridedSlice;
Bruno Goncalvesbbeae262019-02-07 18:37:39 -0200455 m_ParserFunctions[tflite::BuiltinOperator_SUB] = &TfLiteParser::ParseSub;
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -0200456 m_ParserFunctions[tflite::BuiltinOperator_ADD] = &TfLiteParser::ParseAdd;
Bruno Goncalvesf803f782018-12-18 13:40:30 -0200457 m_ParserFunctions[tflite::BuiltinOperator_MUL] = &TfLiteParser::ParseMul;
Bruno Goncalves2235cee2018-12-19 12:51:45 -0200458 m_ParserFunctions[tflite::BuiltinOperator_MEAN] = &TfLiteParser::ParseMean;
Matthew Jacksonbcca1f42019-07-16 11:39:21 +0100459 m_ParserFunctions[tflite::BuiltinOperator_PACK] = &TfLiteParser::ParsePack;
Bruno Goncalves6c2355b2018-12-19 12:52:01 -0200460 m_ParserFunctions[tflite::BuiltinOperator_PAD] = &TfLiteParser::ParsePad;
Nina Drozd0324f482019-04-08 10:52:10 +0100461 m_ParserFunctions[tflite::BuiltinOperator_SPLIT] = &TfLiteParser::ParseSplit;
Nina Drozd99851762019-04-09 09:37:38 +0100462 m_ParserFunctions[tflite::BuiltinOperator_TANH] = &TfLiteParser::ParseTanH;
Nina Drozd200e3802019-04-15 09:47:39 +0100463 m_ParserFunctions[tflite::BuiltinOperator_UNPACK] = &TfLiteParser::ParseUnpack;
telsoa01c577f2c2018-08-31 09:22:23 +0100464}
465
466void TfLiteParser::ResetParser()
467{
468 m_Network = armnn::INetworkPtr(nullptr, nullptr);
469 m_Model = nullptr;
470 m_SubgraphConnections.clear();
471}
472
Bruno Goncalves9c761a62018-12-27 14:20:35 -0200473void TfLiteParser::AddBroadcastReshapeLayer(size_t subgraphIndex,
474 size_t operatorIndex,
475 IConnectableLayer *layer)
476{
477 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
478 BOOST_ASSERT(layer != nullptr);
479
Derek Lambertiff05cc52019-04-26 13:05:17 +0100480 const auto & subgraphPtr = m_Model->subgraphs[subgraphIndex];
481 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
Bruno Goncalves9c761a62018-12-27 14:20:35 -0200482
483 BOOST_ASSERT(operatorPtr->inputs.size() > 1);
484
485 uint32_t reshapedInputId = CHECKED_NON_NEGATIVE(operatorPtr->inputs[0]);
Derek Lambertiff05cc52019-04-26 13:05:17 +0100486 TensorRawPtr tensorPtr = subgraphPtr->tensors[reshapedInputId].get();
Bruno Goncalves9c761a62018-12-27 14:20:35 -0200487 uint32_t inputId = CHECKED_NON_NEGATIVE(operatorPtr->inputs[1]);
Derek Lambertiff05cc52019-04-26 13:05:17 +0100488 TensorRawPtr tensorPtr1 = subgraphPtr->tensors[inputId].get();
Bruno Goncalves9c761a62018-12-27 14:20:35 -0200489
490 armnn::TensorInfo reshapedTensorInfo = ToTensorInfo(tensorPtr);
491 armnn::TensorInfo inputTensorInfo = ToTensorInfo(tensorPtr1);
492
493 if (inputTensorInfo.GetNumDimensions() < reshapedTensorInfo.GetNumDimensions())
494 {
495 uint32_t id = reshapedInputId;
496 reshapedInputId = inputId;
497 inputId = id;
498
499 reshapedTensorInfo = ToTensorInfo(tensorPtr1);
500 inputTensorInfo = ToTensorInfo(tensorPtr);
501 }
502
503 uint32_t numDimensions = inputTensorInfo.GetNumDimensions();
504
505 std::vector<unsigned> reshapedDim;
506 for (unsigned int i = 0; i < reshapedTensorInfo.GetNumDimensions(); ++i)
507 {
508 reshapedDim.push_back(reshapedTensorInfo.GetShape()[i]);
509 }
510
511 std::vector<unsigned int> reshapedDimensions(numDimensions, 1);
512 std::copy_backward (reshapedDim.begin(), reshapedDim.end(), reshapedDimensions.end());
513
514 reshapedTensorInfo.SetShape(armnn::TensorShape{ numDimensions, reshapedDimensions.data() });
515
516 std::string layerName = boost::str(boost::format("Reshape_for:%1%") % layer->GetName());
517 armnn::ReshapeDescriptor desc;
518 desc.m_TargetShape = reshapedTensorInfo.GetShape();
519 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(desc, layerName.c_str());
520
521 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedTensorInfo);
522 reshapeLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(0));
523
524 RegisterInputSlots(subgraphIndex, operatorIndex, reshapeLayer, {reshapedInputId});
525
526 armnn::IInputSlot* input1Slot = &(layer->GetInputSlot(1));
527 RegisterConsumerOfTensor(subgraphIndex, inputId, input1Slot);
528}
529
telsoa01c577f2c2018-08-31 09:22:23 +0100530INetworkPtr TfLiteParser::CreateNetworkFromBinaryFile(const char* graphFile)
531{
532 ResetParser();
533 m_Model = LoadModelFromFile(graphFile);
534 return CreateNetworkFromModel();
535}
536
537INetworkPtr TfLiteParser::CreateNetworkFromBinary(const std::vector<uint8_t> & binaryContent)
538{
539 ResetParser();
540 m_Model = LoadModelFromBinary(binaryContent.data(), binaryContent.size());
541 return CreateNetworkFromModel();
542}
543
544INetworkPtr TfLiteParser::CreateNetworkFromModel()
545{
546 m_Network = INetwork::Create();
547 BOOST_ASSERT(m_Model.get() != nullptr);
548
549 bool failedToCreate = false;
550 std::stringstream errors;
551
552 if (m_Model->subgraphs.size() != 1)
553 {
554 throw ParseException(
555 boost::str(
556 boost::format("Current TfLite parser only supports 1 subgraph. Current one has: %1% %2%") %
557 m_Model->subgraphs.size() %
558 CHECK_LOCATION().AsString()));
559 }
560
561 size_t subgraphIndex = 0;
Derek Lambertiff05cc52019-04-26 13:05:17 +0100562 for (SubgraphPtr const & subgraph : m_Model->subgraphs)
telsoa01c577f2c2018-08-31 09:22:23 +0100563 {
564 m_SubgraphConnections.emplace_back(subgraph->tensors.size());
565
566 size_t operatorIndex = 0;
567 for (OperatorPtr const & op : subgraph->operators)
568 {
569 try
570 {
telsoa01c577f2c2018-08-31 09:22:23 +0100571 auto const & opCodePtr = m_Model->operator_codes[op->opcode_index];
572 auto builtinCode = opCodePtr->builtin_code;
573
574 if (builtinCode > tflite::BuiltinOperator_MAX)
575 {
576 throw ParseException(
577 boost::str(
578 boost::format("Operator code %1% is out of range 0-%2%. "
579 "subgraph:%3% operator idx:%4%. %5%") %
580 builtinCode %
581 tflite::BuiltinOperator_MAX %
582 subgraphIndex %
583 operatorIndex %
584 CHECK_LOCATION().AsString()));
585 }
586
587 // lookup and call the parser function
588 auto & parserFunction = m_ParserFunctions[builtinCode];
589 (this->*parserFunction)(subgraphIndex, operatorIndex);
590 }
591 catch (const ParseException& e)
592 {
593 failedToCreate = true;
594 std::stringstream errorString;
595
596 errorString << "Failed to parse operator #" << operatorIndex
597 << " within subgraph #" << subgraphIndex
598 << " error: " << e.what();
599 BOOST_LOG_TRIVIAL(error) << errorString.str();
600
601 errors << errorString.str() << "\n";
602 }
603 ++operatorIndex;
604 }
605
606 SetupInputLayers(subgraphIndex);
607 SetupOutputLayers(subgraphIndex);
Bruno Goncalves3d7efe92018-12-27 14:21:43 -0200608 SetupConstantLayers(subgraphIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100609
610 ++subgraphIndex;
611 }
612
613 if (failedToCreate)
614 {
615 // we can skip everything and let the outer exception handler deal with the error
616 throw ParseException(errors.str());
617 }
618
619 // establish the connections from the layer outputs to the inputs of the subsequent layers
620 for (size_t subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
621 {
622 for (size_t tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
623 {
624 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot != nullptr)
625 {
626 for (size_t inputSlotIdx = 0;
627 inputSlotIdx < m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size();
628 ++inputSlotIdx)
629 {
630 m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot->Connect(
631 *(m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots[inputSlotIdx]));
632 }
633 }
634 }
635 }
636
637 return std::move(m_Network);
638}
639
640void TfLiteParser::RegisterProducerOfTensor(size_t subgraphIndex,
641 size_t tensorIndex,
642 armnn::IOutputSlot* slot)
643{
644 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
645 BOOST_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
646 BOOST_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
647
648 TensorSlots & tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
649
650 // assuming there is only one producer for that tensor
651 if (tensorSlots.outputSlot != nullptr)
652 {
653 throw ParseException(boost::str(
654 boost::format("Another layer has already registered itself as the producer of "
655 "subgraph:%1% tensor:%2% %3%") %
656 subgraphIndex %
657 tensorIndex %
658 CHECK_LOCATION().AsString()));
659 }
660
661 tensorSlots.outputSlot = slot;
662}
663
664void TfLiteParser::RegisterConsumerOfTensor(size_t subgraphIndex,
665 size_t tensorIndex,
666 armnn::IInputSlot* slot)
667{
668 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
669 BOOST_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
670 BOOST_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
671
672 TensorSlots & tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
673 tensorSlots.inputSlots.push_back(slot);
674}
675
676void TfLiteParser::ParseUnsupportedOperator(size_t subgraphIndex, size_t operatorIndex)
677{
678 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
679 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
680 //
681 auto opcodeIndex = operatorPtr->opcode_index;
682 auto opcode = m_Model->operator_codes[opcodeIndex]->builtin_code;
683
684 throw ParseException(
685 boost::str(
686 boost::format("Operator not supported. "
687 "subgraph:%1% operator:%2% "
688 "opcode_index:%3% opcode:%4% / %5% %6%") %
689 subgraphIndex %
690 operatorIndex %
691 opcodeIndex %
692 opcode %
693 tflite::EnumNameBuiltinOperator(opcode) %
694 CHECK_LOCATION().AsString()));
695}
696
telsoa01c577f2c2018-08-31 09:22:23 +0100697void TfLiteParser::ParseConv2D(size_t subgraphIndex, size_t operatorIndex)
698{
699 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
700
701 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
702 const auto * options = operatorPtr->builtin_options.AsConv2DOptions();
703
704 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
705
706 Convolution2dDescriptor desc;
707 desc.m_BiasEnabled = false;
708 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
709 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +0000710 desc.m_DataLayout = armnn::DataLayout::NHWC;
Pablo Tellof0bd6832019-04-26 17:58:13 +0100711 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
712 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +0000713
telsoa01c577f2c2018-08-31 09:22:23 +0100714 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
715 CHECK_VALID_SIZE(inputs.size(), 2, 3);
716
717 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
718 CHECK_VALID_SIZE(outputs.size(), 1);
719
720 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
721 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
722
723 // assuming input is NHWC
724 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
725 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
726
727 // assuming the filter is OHWI : Output, H, W, Input
728 // which is essentially the same as NHWC
729 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
730 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
731
Pablo Tellof0bd6832019-04-26 17:58:13 +0100732 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
733 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
734 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
735 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +0100736
Matteo Martincigh747ef822018-12-18 09:26:39 +0000737 auto filterTensorAndData = CreateConstTensor(inputs[1],
738 filterTensorInfo,
739 armnn::Optional<armnn::PermutationVector&>());
telsoa01c577f2c2018-08-31 09:22:23 +0100740 armnn::IConnectableLayer* layer;
741
742 auto layerName = boost::str(boost::format("Conv2D:%1%:%2%") % subgraphIndex % operatorIndex);
743
744 if (inputs.size() == 3)
745 {
746 desc.m_BiasEnabled = true;
747 armnn::TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Matteo Martincigh747ef822018-12-18 09:26:39 +0000748 auto biasTensorAndData = CreateConstTensor(inputs[2],
749 biasTensorInfo,
750 armnn::Optional<armnn::PermutationVector&>());
telsoa01c577f2c2018-08-31 09:22:23 +0100751 layer = m_Network->AddConvolution2dLayer(desc,
752 filterTensorAndData.first,
Matteo Martincighfc598e12019-05-14 10:36:13 +0100753 Optional<ConstTensor>(biasTensorAndData.first),
telsoa01c577f2c2018-08-31 09:22:23 +0100754 layerName.c_str());
755 }
756 else
757 {
758 layer = m_Network->AddConvolution2dLayer(desc,
759 filterTensorAndData.first,
Matteo Martincighfc598e12019-05-14 10:36:13 +0100760 EmptyOptional(),
telsoa01c577f2c2018-08-31 09:22:23 +0100761 layerName.c_str());
762 }
763
764 BOOST_ASSERT(layer != nullptr);
765
telsoa01c577f2c2018-08-31 09:22:23 +0100766 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
jimfly01c25411c2018-11-14 17:47:22 +0000767 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +0100768
769 // register the input connection slots for the layer, connections are made after all layers have been created
770 // only the tensors for the inputs are relevant, exclude the const tensors
771 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +0000772 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
telsoa01c577f2c2018-08-31 09:22:23 +0100773
jimfly01c25411c2018-11-14 17:47:22 +0000774 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +0100775 // register the output connection slots for the layer, connections are made after all layers have been created
776 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
777 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
778}
779
780void TfLiteParser::ParseDepthwiseConv2D(size_t subgraphIndex, size_t operatorIndex)
781{
782 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
783
784 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
785 const auto * options = operatorPtr->builtin_options.AsDepthwiseConv2DOptions();
786
787 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
788
789 DepthwiseConvolution2dDescriptor desc;
790 desc.m_BiasEnabled = false;
791 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
792 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +0000793 desc.m_DataLayout = armnn::DataLayout::NHWC;
Matthew Jacksond6a9dee2019-07-22 13:53:24 +0100794 CHECKED_NON_NEGATIVE(options->depth_multiplier);
telsoa01c577f2c2018-08-31 09:22:23 +0100795
796 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
797 CHECK_VALID_SIZE(inputs.size(), 2, 3);
798 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
799 CHECK_VALID_SIZE(outputs.size(), 1);
Pablo Tellof0bd6832019-04-26 17:58:13 +0100800 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
801 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +0000802
telsoa01c577f2c2018-08-31 09:22:23 +0100803 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
804 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
805
Matteo Martincigh747ef822018-12-18 09:26:39 +0000806 // Assuming input is NHWC
telsoa01c577f2c2018-08-31 09:22:23 +0100807 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
808 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
Matteo Martincigh747ef822018-12-18 09:26:39 +0000809
810 // TensorflowLite weights come in the format [1, H, W, I * M]
telsoa01c577f2c2018-08-31 09:22:23 +0100811 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
812 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
813
Matteo Martincigh747ef822018-12-18 09:26:39 +0000814 // Reshape weights as [ H, W, I, M ]
815 filterTensorInfo.SetShape({ filterHeight,
816 filterWidth,
817 inputTensorInfo.GetShape()[3],
818 filterTensorInfo.GetShape()[3] / inputTensorInfo.GetShape()[3] });
819
820 // Mappings from TensorflowLite filter tensors to the ArmNN filter tensors (ArmNN weights have to be [M, I, H, W])
821 PermutationVector permutationVector{ 2, 3, 1, 0 }; // [H, W, I, M] -> [M, I, H, W]
822
Pablo Tellof0bd6832019-04-26 17:58:13 +0100823 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
824 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
825 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
826 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +0100827
Matteo Martincigh747ef822018-12-18 09:26:39 +0000828 auto filterTensorAndData = CreateConstTensor(inputs[1], filterTensorInfo, permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +0100829 armnn::IConnectableLayer* layer;
830 auto layerName = boost::str(boost::format("DepthwiseConv2D:%1%:%2%") % subgraphIndex % operatorIndex);
831
832 if (inputs.size() == 3)
833 {
834 desc.m_BiasEnabled = true;
835 TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Matteo Martincigh747ef822018-12-18 09:26:39 +0000836 auto biasTensorAndData = CreateConstTensor(inputs[2],
837 biasTensorInfo,
838 armnn::Optional<armnn::PermutationVector&>());
telsoa01c577f2c2018-08-31 09:22:23 +0100839 layer = m_Network->AddDepthwiseConvolution2dLayer(desc,
840 filterTensorAndData.first,
Matteo Martincighfc598e12019-05-14 10:36:13 +0100841 Optional<ConstTensor>(biasTensorAndData.first),
telsoa01c577f2c2018-08-31 09:22:23 +0100842 layerName.c_str());
843 }
844 else
845 {
846 layer = m_Network->AddDepthwiseConvolution2dLayer(desc,
847 filterTensorAndData.first,
Matteo Martincighfc598e12019-05-14 10:36:13 +0100848 EmptyOptional(),
telsoa01c577f2c2018-08-31 09:22:23 +0100849 layerName.c_str());
850 }
851 BOOST_ASSERT(layer != nullptr);
852
telsoa01c577f2c2018-08-31 09:22:23 +0100853 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
jimfly01c25411c2018-11-14 17:47:22 +0000854 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +0100855
856 // register the input connection slots for the layer, connections are made after all layers have been created
857 // only the tensors for the inputs are relevant, exclude the const tensors
858 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +0000859 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
telsoa01c577f2c2018-08-31 09:22:23 +0100860
jimfly01c25411c2018-11-14 17:47:22 +0000861 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +0100862 // register the output connection slots for the layer, connections are made after all layers have been created
863 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
864 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
865}
866
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +0100867void TfLiteParser::ParseAveragePool2D(size_t subgraphIndex, size_t operatorIndex)
868{
869 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Average);
870}
871
Bruno Goncalvesdb947e22019-02-08 18:52:21 -0200872void TfLiteParser::ParseBatchToSpaceND(size_t subgraphIndex, size_t operatorIndex)
873{
874 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
875
876 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
877 CHECK_VALID_SIZE(inputs.size(), 3);
878
879 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
880 CHECK_VALID_SIZE(outputs.size(), 1);
881
882 armnn::TensorInfo blockShapeTensorInfo = ToTensorInfo(inputs[1]);
883 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
884
885 armnn::TensorInfo cropsTensorInfo = ToTensorInfo(inputs[2]);
886 BufferRawPtr cropsBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
887
888 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
889 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
890
891 std::vector<unsigned int> cropsVector(cropsTensorInfo.GetNumElements());
892 ::memcpy(cropsVector.data(), cropsBufferPtr->data.data(), cropsTensorInfo.GetNumBytes());
893
894 size_t step = 2;
895 std::vector<std::pair<unsigned int, unsigned int>> crops;
896 for (unsigned int i = 0; i < cropsTensorInfo.GetNumElements() / step; ++i)
897 {
898 crops.emplace_back(cropsVector[i * step], cropsVector[i * step + 1]);
899 }
900
901 armnn::BatchToSpaceNdDescriptor desc;
902 desc.m_BlockShape = blockShape;
903 desc.m_Crops = crops;
904 desc.m_DataLayout = armnn::DataLayout::NHWC;
905
906 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
907
908 auto layerName = boost::str(boost::format("BatchToSpaceND:%1%:%2%") % subgraphIndex % operatorIndex);
909 IConnectableLayer* layer = m_Network->AddBatchToSpaceNdLayer(desc, layerName.c_str());
910
911 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
912
913 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
914 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
915
916 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
917 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
918}
919
Matthew Jackson28c94572019-07-18 10:47:03 +0100920void TfLiteParser::ParseL2Normalization(size_t subgraphIndex, size_t operatorIndex)
921{
922 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
923
924 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
925 CHECK_VALID_SIZE(inputs.size(), 1);
926
927 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
928 CHECK_VALID_SIZE(outputs.size(), 1);
929
930 L2NormalizationDescriptor desc;
931 desc.m_DataLayout = armnn::DataLayout::NHWC;
932 auto layerName = boost::str(boost::format("L2Normalization:%1%:%2%") % subgraphIndex % operatorIndex);
933 IConnectableLayer* layer = m_Network->AddL2NormalizationLayer(desc, layerName.c_str());
934
935 BOOST_ASSERT(layer != nullptr);
936
937 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
938 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
939
940 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
941 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
942
943 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
944 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
945}
946
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +0100947void TfLiteParser::ParseMaxPool2D(size_t subgraphIndex, size_t operatorIndex)
948{
949 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Max);
950}
951
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -0200952void TfLiteParser::ParseMaximum(size_t subgraphIndex, size_t operatorIndex)
953{
954 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
955
956 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
957 CHECK_VALID_SIZE(inputs.size(), 2);
958
959 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
960 CHECK_VALID_SIZE(outputs.size(), 1);
961
962 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
963 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
964
965 auto layerName = boost::str(boost::format("Maximum:%1%:%2%") % subgraphIndex % operatorIndex);
966 IConnectableLayer* layer = m_Network->AddMaximumLayer(layerName.c_str());
967
968 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
969 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
970
971 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
972 if (inputTensorInfo.GetNumDimensions() != input1TensorInfo.GetNumDimensions())
973 {
974 AddBroadcastReshapeLayer(subgraphIndex, operatorIndex, layer);
975 }
976 else
977 {
978 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
979 }
980
981 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
982 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
983}
984
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -0200985void TfLiteParser::ParseMinimum(size_t subgraphIndex, size_t operatorIndex)
986{
987 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
988
989 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
990 CHECK_VALID_SIZE(inputs.size(), 2);
991
992 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
993 CHECK_VALID_SIZE(outputs.size(), 1);
994
995 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
996 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
997
998 auto layerName = boost::str(boost::format("Minimum:%1%:%2%") % subgraphIndex % operatorIndex);
999 IConnectableLayer* layer = m_Network->AddMinimumLayer(layerName.c_str());
1000
1001 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
1002 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1003
1004 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1005 if (inputTensorInfo.GetNumDimensions() != input1TensorInfo.GetNumDimensions())
1006 {
1007 AddBroadcastReshapeLayer(subgraphIndex, operatorIndex, layer);
1008 }
1009 else
1010 {
1011 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
1012 }
1013
1014 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1015 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1016}
1017
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001018void TfLiteParser::ParsePool(size_t subgraphIndex,
1019 size_t operatorIndex,
1020 PoolingAlgorithm algorithm)
1021{
1022 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1023
1024 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1025 const auto * options = operatorPtr->builtin_options.AsPool2DOptions();
1026
1027 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1028
1029 std::string layerName;
1030
1031 switch (algorithm)
1032 {
1033 case PoolingAlgorithm::Average:
1034 layerName =
1035 boost::str(boost::format("AveragePool2D:%1%:%2%") % subgraphIndex % operatorIndex);
1036 break;
1037 case PoolingAlgorithm::Max:
1038 layerName =
1039 boost::str(boost::format("MaxPool2D:%1%:%2%") % subgraphIndex % operatorIndex);
1040 break;
1041 default:
1042 BOOST_ASSERT_MSG(false, "Unsupported Pooling Algorithm");
1043 }
1044
1045 Pooling2dDescriptor desc;
1046
1047 desc.m_PoolType = algorithm;
1048 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1049 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1050 desc.m_PoolWidth = CHECKED_NON_NEGATIVE(options->filter_width);
1051 desc.m_PoolHeight = CHECKED_NON_NEGATIVE(options->filter_height);
1052 desc.m_PaddingMethod = PaddingMethod::Exclude;
1053 desc.m_OutputShapeRounding = OutputShapeRounding::Floor;
jimfly01c25411c2018-11-14 17:47:22 +00001054 desc.m_DataLayout = armnn::DataLayout::NHWC;
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001055
1056 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1057 CHECK_VALID_SIZE(inputs.size(), 1);
1058 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1059
1060 // assuming input is NHWC
1061 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1062 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1063
Pablo Tellof0bd6832019-04-26 17:58:13 +01001064 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, 1u,
1065 desc.m_PadTop, desc.m_PadBottom, options->padding);
1066 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, 1u,
1067 desc.m_PadLeft, desc.m_PadRight, options->padding);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001068
1069 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1070 CHECK_VALID_SIZE(outputs.size(), 1);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001071
1072 IConnectableLayer* layer = m_Network->AddPooling2dLayer(desc, layerName.c_str());
1073
1074 BOOST_ASSERT(layer != nullptr);
1075
jimfly01c25411c2018-11-14 17:47:22 +00001076 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
1077 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001078
1079 // register the input connection slots for the layer, connections are made after all layers have been created
1080 // only the tensors for the inputs are relevant, exclude the const tensors
1081 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +00001082 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001083
jimfly01c25411c2018-11-14 17:47:22 +00001084 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001085 // register the output connection slots for the layer, connections are made after all layers have been created
1086 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1087 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1088}
1089
telsoa01c577f2c2018-08-31 09:22:23 +01001090void TfLiteParser::ParseSoftmax(size_t subgraphIndex, size_t operatorIndex)
1091{
1092 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1093 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1094 const auto * options = operatorPtr->builtin_options.AsSoftmaxOptions();
1095
1096 SoftmaxDescriptor desc;
1097 desc.m_Beta = options->beta;
1098
1099 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1100 CHECK_VALID_SIZE(inputs.size(), 1);
1101 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1102 CHECK_VALID_SIZE(outputs.size(), 1);
1103
1104 auto layerName = boost::str(boost::format("Softmax:%1%:%2%") % subgraphIndex % operatorIndex);
1105 IConnectableLayer* const layer = m_Network->AddSoftmaxLayer(desc, layerName.c_str());
1106
1107 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
1108 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1109
1110 // register the input connection slots for the layer, connections are made after all layers have been created
1111 // only the tensors for the inputs are relevant, exclude the const tensors
1112 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1113 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1114
1115 // register the output connection slots for the layer, connections are made after all layers have been created
1116 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1117 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1118}
1119
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001120void TfLiteParser::ParseSpaceToBatchND(size_t subgraphIndex, size_t operatorIndex)
1121{
1122 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1123
1124 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1125 CHECK_VALID_SIZE(inputs.size(), 3);
1126
1127 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1128 CHECK_VALID_SIZE(outputs.size(), 1);
1129
1130 armnn::TensorInfo blockShapeTensorInfo = ToTensorInfo(inputs[1]);
1131 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1132
1133 armnn::TensorInfo padListTensorInfo = ToTensorInfo(inputs[2]);
1134 BufferRawPtr padListBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1135
1136 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1137 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1138
1139 std::vector<unsigned int> padListVector(padListTensorInfo.GetNumElements());
1140 ::memcpy(padListVector.data(), padListBufferPtr->data.data(), padListTensorInfo.GetNumBytes());
1141
1142 size_t step = 2;
1143 std::vector<std::pair<unsigned int, unsigned int>> padList;
1144 for (unsigned int i = 0; i < padListTensorInfo.GetNumElements() / step; ++i)
1145 {
1146 padList.emplace_back(padListVector[i * step], padListVector[i * step + 1]);
1147 }
1148
1149 armnn::SpaceToBatchNdDescriptor desc;
1150 desc.m_BlockShape = blockShape;
1151 desc.m_PadList = padList;
1152 desc.m_DataLayout = armnn::DataLayout::NHWC;
1153
1154 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
1155
1156 auto layerName = boost::str(boost::format("SpaceToBatchND:%1%:%2%") % subgraphIndex % operatorIndex);
1157 IConnectableLayer* layer = m_Network->AddSpaceToBatchNdLayer(desc, layerName.c_str());
1158
1159 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1160
1161 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1162 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1163
1164 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1165 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1166}
1167
telsoa01c577f2c2018-08-31 09:22:23 +01001168armnn::TensorInfo TfLiteParser::OutputShapeOfSqueeze(const std::vector<uint32_t> & squeezeDimsIn,
1169 const armnn::TensorInfo & inputTensorInfo)
1170{
1171 CHECK_VALID_SIZE(squeezeDimsIn.size(), 0, 1, 2, 3, 4);
1172 std::vector<uint32_t> squeezeDims = squeezeDimsIn;
1173 static const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
1174
1175 if (inputTensorInfo.GetNumDimensions() > 4)
1176 {
1177 std::stringstream ss;
1178 ss << "Input tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
1179 << " shape:" << inputTensorInfo.GetShape() << " "
1180 << CHECK_LOCATION().AsString();
1181 throw ParseException(ss.str());
1182 }
1183
1184 if (squeezeDims.empty())
1185 {
1186 squeezeDims.assign(dimensionSequence,
1187 dimensionSequence+inputTensorInfo.GetNumDimensions());
1188 }
1189
1190 std::vector<uint32_t> outputDims;
1191 for(unsigned int i = 0; i < inputTensorInfo.GetNumDimensions(); i++)
1192 {
1193 bool skipSqueeze = (std::find(squeezeDims.begin(), squeezeDims.end(), i) == squeezeDims.end());
1194 auto currentDimension = inputTensorInfo.GetShape()[i];
1195 if (skipSqueeze || currentDimension != 1)
1196 {
1197 outputDims.push_back(currentDimension);
1198 }
1199 }
1200
1201 if (outputDims.size() > 4)
1202 {
1203 std::stringstream ss;
1204 ss << "Output tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
1205 << " shape:" << inputTensorInfo.GetShape() << " "
1206 << CHECK_LOCATION().AsString();
1207 throw ParseException(ss.str());
1208 }
1209
1210 TensorShape outShape = TensorShape(static_cast<unsigned int>(outputDims.size()),
1211 outputDims.data());
1212
1213 // we need to preserve the tensor type and the quantization data as well
1214 TensorInfo outTensorInfo = inputTensorInfo;
1215 outTensorInfo.SetShape(outShape);
1216
1217 return outTensorInfo;
1218}
1219
1220void TfLiteParser::ParseSqueeze(size_t subgraphIndex, size_t operatorIndex)
1221{
1222 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1223
1224 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1225 CHECK_VALID_SIZE(inputs.size(), 1);
1226
1227 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1228 CHECK_VALID_SIZE(outputs.size(), 1);
1229
1230 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1231 const auto * options = operatorPtr->builtin_options.AsSqueezeOptions();
1232
1233 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1234 armnn::TensorInfo outputTensorInfo =
1235 TfLiteParser::OutputShapeOfSqueeze(AsUnsignedVector(options->squeeze_dims),
1236 inputTensorInfo);
1237
1238 ReshapeDescriptor reshapeDesc;
1239 reshapeDesc.m_TargetShape = outputTensorInfo.GetShape();
1240
1241 auto layerName = boost::str(boost::format("Squeeze:%1%:%2%") % subgraphIndex % operatorIndex);
1242 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
1243 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1244
1245 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1246 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1247
1248 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1249 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1250}
1251
Bruno Goncalves451d95b2019-02-12 22:59:22 -02001252void TfLiteParser::ParseStridedSlice(size_t subgraphIndex, size_t operatorIndex)
1253{
1254 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1255
1256 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1257 CHECK_VALID_SIZE(inputs.size(), 4);
1258
1259 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1260 CHECK_VALID_SIZE(outputs.size(), 1);
1261
1262 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1263 const auto * options = operatorPtr->builtin_options.AsStridedSliceOptions();
1264
1265 StridedSliceDescriptor desc;
1266 desc.m_BeginMask = options->begin_mask;
1267 desc.m_EllipsisMask = options->ellipsis_mask;
1268 desc.m_EndMask = options->end_mask;
1269 desc.m_NewAxisMask = options->new_axis_mask;
1270 desc.m_ShrinkAxisMask = options->shrink_axis_mask;
1271 desc.m_DataLayout = armnn::DataLayout::NHWC;
1272
1273 armnn::TensorInfo beginTensorInfo = ToTensorInfo(inputs[1]);
1274 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1275
1276 std::vector<int> begin(beginTensorInfo.GetNumElements());
1277 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
1278
1279 armnn::TensorInfo endTensorInfo = ToTensorInfo(inputs[2]);
1280 BufferRawPtr endBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1281
1282 std::vector<int> end(endTensorInfo.GetNumElements());
1283 ::memcpy(end.data(), endBufferPtr->data.data(), endTensorInfo.GetNumBytes());
1284
1285 armnn::TensorInfo strideTensorInfo = ToTensorInfo(inputs[3]);
1286 BufferRawPtr strideBufferPtr = GetBuffer(m_Model, inputs[3]->buffer);
1287
1288 std::vector<int> stride(strideTensorInfo.GetNumElements());
1289 ::memcpy(stride.data(), strideBufferPtr->data.data(), strideTensorInfo.GetNumBytes());
1290
1291 desc.m_Begin = begin;
1292 desc.m_End = end;
1293 desc.m_Stride = stride;
1294
1295 auto layerName = boost::str(boost::format("StridedSlice:%1%:%2%") % subgraphIndex % operatorIndex);
1296 IConnectableLayer* layer = m_Network->AddStridedSliceLayer(desc, layerName.c_str());
1297
1298 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
1299 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1300
1301 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1302 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1303
1304 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1305 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1306}
1307
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001308void TfLiteParser::ParseSub(size_t subgraphIndex, size_t operatorIndex)
1309{
1310 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1311
1312 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1313 const auto * options = operatorPtr->builtin_options.AsSubOptions();
1314
1315 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1316 CHECK_VALID_SIZE(inputs.size(), 2);
1317
1318 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1319 CHECK_VALID_SIZE(outputs.size(), 1);
1320
1321 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1322 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1323
1324 auto layerName = boost::str(boost::format("Sub:%1%:%2%") % subgraphIndex % operatorIndex);
1325 IConnectableLayer* layer = m_Network->AddSubtractionLayer(layerName.c_str());
1326
1327 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
1328 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1329
1330 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1331 if (inputTensorInfo.GetNumDimensions() != input1TensorInfo.GetNumDimensions())
1332 {
1333 AddBroadcastReshapeLayer(subgraphIndex, operatorIndex, layer);
1334 }
1335 else
1336 {
1337 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
1338 }
1339
1340 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1341
1342 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1343 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1344}
1345
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001346void TfLiteParser::ParseAdd(size_t subgraphIndex, size_t operatorIndex)
1347{
1348 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1349
1350 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1351 const auto * options = operatorPtr->builtin_options.AsAddOptions();
1352
1353 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1354 CHECK_VALID_SIZE(inputs.size(), 2);
1355
1356 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1357 CHECK_VALID_SIZE(outputs.size(), 1);
1358
Bruno Goncalves9c761a62018-12-27 14:20:35 -02001359 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1360 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1361
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001362 auto layerName = boost::str(boost::format("Add:%1%:%2%") % subgraphIndex % operatorIndex);
1363 IConnectableLayer* layer = m_Network->AddAdditionLayer(layerName.c_str());
1364
1365 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
1366 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1367
1368 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Bruno Goncalves9c761a62018-12-27 14:20:35 -02001369 if (inputTensorInfo.GetNumDimensions() != input1TensorInfo.GetNumDimensions())
1370 {
1371 AddBroadcastReshapeLayer(subgraphIndex, operatorIndex, layer);
1372 }
1373 else
1374 {
1375 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
1376 }
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001377
1378 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1379
1380 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1381 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1382}
1383
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001384void TfLiteParser::ParseMul(size_t subgraphIndex, size_t operatorIndex)
1385{
1386 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1387
1388 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1389 const auto * options = operatorPtr->builtin_options.AsMulOptions();
1390
1391 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1392 CHECK_VALID_SIZE(inputs.size(), 2);
1393
1394 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1395 CHECK_VALID_SIZE(outputs.size(), 1);
1396
Bruno Goncalves9c761a62018-12-27 14:20:35 -02001397 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1398 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1399
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001400 auto layerName = boost::str(boost::format("Mul:%1%:%2%") % subgraphIndex % operatorIndex);
1401 IConnectableLayer* layer = m_Network->AddMultiplicationLayer(layerName.c_str());
1402
1403 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
1404 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1405
1406 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Bruno Goncalves9c761a62018-12-27 14:20:35 -02001407 if (inputTensorInfo.GetNumDimensions() != input1TensorInfo.GetNumDimensions())
1408 {
1409 AddBroadcastReshapeLayer(subgraphIndex, operatorIndex, layer);
1410 }
1411 else
1412 {
1413 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
1414 }
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001415
1416 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1417
1418 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1419 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1420}
1421
Bruno Goncalves2235cee2018-12-19 12:51:45 -02001422void TfLiteParser::ParseMean(size_t subgraphIndex, size_t operatorIndex)
1423{
1424 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1425
1426 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1427
1428 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1429 CHECK_VALID_SIZE(outputs.size(), 1);
1430
1431 armnn::TensorInfo dimTensorInfo = ToTensorInfo(inputs[1]);
1432 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1433
1434 armnn::MeanDescriptor desc;
1435 std::vector<unsigned int> axis(dimTensorInfo.GetNumElements());
1436 ::memcpy(axis.data(), bufferPtr->data.data(), dimTensorInfo.GetNumBytes());
1437 desc.m_Axis = axis;
1438
1439 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1440 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
1441
1442 desc.m_KeepDims =
1443 inputTensorInfo.GetNumDimensions() == outputTensorInfo.GetNumDimensions() ?
1444 true : false;
1445
1446 auto layerName = boost::str(boost::format("Mean:%1%:%2%") % subgraphIndex % operatorIndex);
1447 IConnectableLayer* layer = m_Network->AddMeanLayer(desc, layerName.c_str());
1448
1449 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1450
1451 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1452 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1453
1454 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1455 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1456}
1457
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001458void TfLiteParser::ParsePad(size_t subgraphIndex, size_t operatorIndex)
1459{
1460 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1461
1462 TfLiteParser::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1463
1464 TfLiteParser::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1465 CHECK_VALID_SIZE(outputs.size(), 1);
1466
1467 armnn::TensorInfo padTensorInfo = ToTensorInfo(inputs[1]);
1468 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1469
1470 std::vector<unsigned int> padBuffer(padTensorInfo.GetNumElements());
1471 ::memcpy(padBuffer.data(), bufferPtr->data.data(), padTensorInfo.GetNumBytes());
1472
1473 size_t step = 2;
1474 armnn::PadDescriptor desc;
1475 for (unsigned int i = 0; i < padTensorInfo.GetNumElements() / step; ++i)
1476 {
1477 desc.m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
1478 }
1479
1480 auto layerName = boost::str(boost::format("Pad:%1%:%2%") % subgraphIndex % operatorIndex);
1481 IConnectableLayer* layer = m_Network->AddPadLayer(desc, layerName.c_str());
1482
1483 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
1484 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1485
1486 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1487 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1488
1489 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1490 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1491}
1492
Finn Williamsc42c3842019-01-22 14:18:11 +00001493
Sadik Armagan58f39192018-09-17 14:14:39 +01001494void TfLiteParser::ParseRelu(size_t subgraphIndex, size_t operatorIndex)
1495{
Finn Williamsc42c3842019-01-22 14:18:11 +00001496 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::ReLu);
Sadik Armagan58f39192018-09-17 14:14:39 +01001497}
1498
1499void TfLiteParser::ParseRelu6(size_t subgraphIndex, size_t operatorIndex)
1500{
Finn Williamsc42c3842019-01-22 14:18:11 +00001501 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::BoundedReLu);
1502}
Sadik Armagan58f39192018-09-17 14:14:39 +01001503
Finn Williamsc42c3842019-01-22 14:18:11 +00001504void TfLiteParser::ParseLogistic(size_t subgraphIndex, size_t operatorIndex)
1505{
1506 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::Sigmoid);
1507}
1508
Nina Drozd99851762019-04-09 09:37:38 +01001509void TfLiteParser::ParseTanH(size_t subgraphIndex, size_t operatorIndex)
1510{
1511 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::TanH);
1512}
1513
Finn Williamsc42c3842019-01-22 14:18:11 +00001514
1515void TfLiteParser::ParseActivation(size_t subgraphIndex, size_t operatorIndex, ActivationFunction activationType)
1516{
1517 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan58f39192018-09-17 14:14:39 +01001518 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1519 boost::ignore_unused(operatorPtr);
1520
1521 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1522 CHECK_VALID_SIZE(inputs.size(), 1);
1523
1524 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1525 CHECK_VALID_SIZE(outputs.size(), 1);
1526
Finn Williamsc42c3842019-01-22 14:18:11 +00001527 auto layerName = str(boost::format("Activation:"));
Sadik Armagan58f39192018-09-17 14:14:39 +01001528 ActivationDescriptor activationDesc;
Finn Williamsc42c3842019-01-22 14:18:11 +00001529 activationDesc.m_Function = activationType;
1530
1531 switch (activationType)
1532 {
1533 case ActivationFunction::ReLu:
1534 {
1535 layerName += str(boost::format("RELU:%1%:%2%") % subgraphIndex % operatorIndex);
1536 break;
1537 }
1538 case ActivationFunction::BoundedReLu:
1539 {
1540 layerName += str(boost::format("RELU6:%1%:%2%") % subgraphIndex % operatorIndex);
1541 activationDesc.m_A = 6.0f;
1542 activationDesc.m_B = 0.0f;
1543 break;
1544 }
1545 case ActivationFunction::Sigmoid:
1546 {
1547 layerName += str(boost::format("SIGMOID:%1%:%2%") % subgraphIndex % operatorIndex);
1548 break;
1549 }
Nina Drozd99851762019-04-09 09:37:38 +01001550 case ActivationFunction::TanH:
1551 {
1552 layerName += str(boost::format("TANH:%1%:%2%") % subgraphIndex % operatorIndex);
1553 activationDesc.m_A = 1.0f;
1554 activationDesc.m_B = 1.0f;
1555 break;
1556 }
Finn Williamsc42c3842019-01-22 14:18:11 +00001557 default:
1558 {
1559 throw ParseException(
1560 boost::str(boost::format("Unexpected ActivationFunction[%1%] when creating layerName "
1561 " %2% ") %static_cast<int>(activationType)% CHECK_LOCATION().AsString()));
1562 }
1563 }
1564
1565 IConnectableLayer* const layer = m_Network->AddActivationLayer(activationDesc, layerName.c_str());
Sadik Armagan58f39192018-09-17 14:14:39 +01001566
1567 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
1568 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1569
1570 // register the input connection slots for the layer, connections are made after all layers have been created
1571 // only the tensors for the inputs are relevant, exclude the const tensors
1572 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1573 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1574
1575 // register the output connection slots for the layer, connections are made after all layers have been created
1576 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1577 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1578}
Sadikb94967b2018-09-19 15:30:00 +01001579armnn::TensorInfo TfLiteParser::OutputShapeOfReshape(const armnn::TensorInfo & inputTensorInfo,
1580 const std::vector<int32_t> & targetDimsIn)
1581{
1582 std::vector<unsigned int> outputDims(targetDimsIn.begin(), targetDimsIn.end());
1583 const auto stretchDim = std::find(targetDimsIn.begin(), targetDimsIn.end(), -1);
1584
1585 if (stretchDim != targetDimsIn.end())
1586 {
1587 if (std::find(std::next(stretchDim), targetDimsIn.end(), -1) != targetDimsIn.end())
1588 {
1589 throw ParseException(
1590 boost::str(
1591 boost::format("At most one component of shape can be -1 %1%") % CHECK_LOCATION().AsString()));
1592 }
1593
1594 auto targetNumElements =
1595 boost::numeric_cast<unsigned int>(
1596 std::accumulate(targetDimsIn.begin(), targetDimsIn.end(), -1, std::multiplies<int32_t>()));
1597
1598 auto stretchIndex = static_cast<size_t>(std::distance(targetDimsIn.begin(), stretchDim));
1599 outputDims[stretchIndex] = inputTensorInfo.GetNumElements() / targetNumElements;
1600 }
1601
1602 TensorShape outputShape = TensorShape(static_cast<unsigned int>(outputDims.size()), outputDims.data());
1603
1604 TensorInfo reshapeInfo = inputTensorInfo;
1605 reshapeInfo.SetShape(outputShape);
1606
1607 return reshapeInfo;
1608}
1609
1610void TfLiteParser::ParseReshape(size_t subgraphIndex, size_t operatorIndex)
1611{
1612 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1613
1614 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01001615
1616 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1617 CHECK_VALID_SIZE(outputs.size(), 1);
1618
1619 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1620 const auto * options = operatorPtr->builtin_options.AsReshapeOptions();
1621
1622 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
kevmay0171972a82018-12-17 14:28:03 +00001623 armnn::TensorInfo actualOutputTensorInfo = ToTensorInfo(outputs[0]);
1624 armnn::TensorInfo reshapeOutputTensorInfo =
Sadikb94967b2018-09-19 15:30:00 +01001625 TfLiteParser::OutputShapeOfReshape(inputTensorInfo, options->new_shape);
1626
kevmay0171972a82018-12-17 14:28:03 +00001627 // Check for valid input size and that reshape parameters equal output shape
Aron Virginas-Tar70672f62019-01-23 14:00:00 +00001628 const armnn::TensorShape& reshapeOutputTensorShape = reshapeOutputTensorInfo.GetShape();
1629 if (inputs.size() > 1 && !CheckShape(reshapeOutputTensorShape, outputs[0]->shape))
kevmay0171972a82018-12-17 14:28:03 +00001630 {
1631 std::stringstream ss;
1632 ss << "New shape defined in reshape parameters "
Aron Virginas-Tar70672f62019-01-23 14:00:00 +00001633 << reshapeOutputTensorShape
kevmay0171972a82018-12-17 14:28:03 +00001634 << " does not equal output shape "
1635 << actualOutputTensorInfo.GetShape()
1636 << ": "
1637 << CHECK_LOCATION().AsString();
1638 throw ParseException(ss.str());
1639 }
1640
Sadikb94967b2018-09-19 15:30:00 +01001641 ReshapeDescriptor reshapeDesc;
kevmay0171972a82018-12-17 14:28:03 +00001642 reshapeDesc.m_TargetShape = reshapeOutputTensorInfo.GetShape();
Sadikb94967b2018-09-19 15:30:00 +01001643
1644 auto layerName = boost::str(boost::format("Reshape:%1%:%2%") % subgraphIndex % operatorIndex);
1645 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
kevmay0171972a82018-12-17 14:28:03 +00001646 layer->GetOutputSlot(0).SetTensorInfo(reshapeOutputTensorInfo);
Sadikb94967b2018-09-19 15:30:00 +01001647
1648 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1649 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1650
1651 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1652 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1653}
1654
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02001655void TfLiteParser::ParseResizeBilinear(size_t subgraphIndex, size_t operatorIndex)
1656{
1657 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1658
1659 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1660 CHECK_VALID_SIZE(inputs.size(), 2);
1661
1662 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1663 CHECK_VALID_SIZE(outputs.size(), 1);
1664
1665 armnn::TensorInfo sizeTensorInfo = ToTensorInfo(inputs[1]);
1666
1667 // Data for the parsed tensor args (size) must be stored locally.
1668 std::vector<int32_t> sizeTensorData(sizeTensorInfo.GetNumElements());
1669
1670 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1671 ::memcpy(sizeTensorData.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
1672
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01001673 ResizeDescriptor desc;
1674 desc.m_Method = armnn::ResizeMethod::Bilinear;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02001675 desc.m_TargetHeight = static_cast<uint32_t> (sizeTensorData[0]);
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01001676 desc.m_TargetWidth = static_cast<uint32_t> (sizeTensorData[1]);
1677 desc.m_DataLayout = armnn::DataLayout::NHWC;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02001678
1679 auto layerName = boost::str(boost::format("ResizeBilinear:%1%:%2%") % subgraphIndex % operatorIndex);
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01001680 IConnectableLayer* layer = m_Network->AddResizeLayer(desc, layerName.c_str());
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02001681
1682 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
1683 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1684
1685 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1686 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1687
1688 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1689 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1690}
1691
Sadik Armagan479045b2018-10-01 11:51:37 +01001692void TfLiteParser::ParseConcatenation(size_t subgraphIndex, size_t operatorIndex)
1693{
1694 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1695
1696 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1697 const auto * options = operatorPtr->builtin_options.AsConcatenationOptions();
1698
1699 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1700
1701 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1702 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1703 CHECK_VALID_SIZE(outputs.size(), 1);
1704
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00001705 unsigned int numConcatView = static_cast<unsigned int>(inputs.size());
1706 uint32_t inputRank = ToTensorInfo(inputs[0]).GetNumDimensions();
Sadik Armagan479045b2018-10-01 11:51:37 +01001707
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00001708 const unsigned int concatDimInput = static_cast<unsigned int>(
1709 (static_cast<int>(inputRank) + options->axis) % static_cast<int>(inputRank));
Sadik Armagan479045b2018-10-01 11:51:37 +01001710
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00001711 OriginsDescriptor concatDescriptor(static_cast<uint32_t>(numConcatView), inputRank);
1712 concatDescriptor.SetConcatAxis(concatDimInput);
Sadik Armagan479045b2018-10-01 11:51:37 +01001713
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00001714 unsigned int mergeDimOrigin = 0;
Sadik Armagan479045b2018-10-01 11:51:37 +01001715
1716 for (unsigned int viewIndex = 0; viewIndex < numConcatView; ++viewIndex)
1717 {
1718 TensorInfo inputTensorInfo = ToTensorInfo(inputs[viewIndex]);
1719
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00001720 // This set up concatDescriptor view origin
1721 armnnUtils::ProcessConcatInputTensorInfo(
1722 inputTensorInfo, concatDescriptor, concatDimInput, viewIndex, mergeDimOrigin);
Sadik Armagan479045b2018-10-01 11:51:37 +01001723 }
1724
1725 auto layerName = boost::str(boost::format("Concatenation:%1%:%2%") % subgraphIndex % operatorIndex);
Jim Flynn906f9462019-05-10 13:55:21 +01001726 IConnectableLayer* layer = m_Network->AddConcatLayer(concatDescriptor, layerName.c_str());
Sadik Armagan479045b2018-10-01 11:51:37 +01001727
1728 BOOST_ASSERT(layer != nullptr);
1729
1730 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
1731 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Sadik Armagan479045b2018-10-01 11:51:37 +01001732
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00001733 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Sadik Armagan479045b2018-10-01 11:51:37 +01001734
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00001735 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
Sadik Armagan479045b2018-10-01 11:51:37 +01001736
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00001737 // add fused activation layer
1738 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Sadik Armagan479045b2018-10-01 11:51:37 +01001739
Sadik Armagan479045b2018-10-01 11:51:37 +01001740 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1741 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1742}
1743
Sadik Armagan8853c1f2018-10-22 09:04:18 +01001744void TfLiteParser::ParseFullyConnected(size_t subgraphIndex, size_t operatorIndex)
1745{
1746 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1747
1748 const auto & operatorRfr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1749 const auto options = operatorRfr->builtin_options.AsFullyConnectedOptions();
1750
1751 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1752
1753 FullyConnectedDescriptor desc;
1754 desc.m_BiasEnabled = false;
Nattapat Chaimanowongd8eee592018-10-26 10:24:14 +01001755 desc.m_TransposeWeightMatrix = true;
Sadik Armagan8853c1f2018-10-22 09:04:18 +01001756
1757 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1758 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1759 CHECK_VALID_SIZE(outputs.size(), 1);
1760
1761 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
1762
1763 // Fully Connected Layer accepts two dimensional weights input
1764 int32_t weightsDimension = static_cast<int32_t>(filterTensorInfo.GetNumDimensions());
1765 if (weightsDimension != 2)
1766 {
1767 throw ParseException(
1768 boost::str(
1769 boost::format(
1770 "Dimension %1% for Fully Connected weights is not supported by Armnn. "
1771 "Node %2%")
1772 % weightsDimension
1773 % CHECK_LOCATION().AsString()));
1774 }
1775
Matteo Martincigh747ef822018-12-18 09:26:39 +00001776 auto filterTensorAndData = CreateConstTensor(inputs[1],
1777 filterTensorInfo,
1778 armnn::Optional<armnn::PermutationVector&>());
Sadik Armagan8853c1f2018-10-22 09:04:18 +01001779 armnn::IConnectableLayer* layer;
1780 auto layerName = boost::str(boost::format("FullyConnected:%1%:%2%") % subgraphIndex % operatorIndex);
1781
1782 if (inputs.size() == 3)
1783 {
1784 desc.m_BiasEnabled = true;
1785 TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Matteo Martincigh747ef822018-12-18 09:26:39 +00001786 auto biasTensorAndData = CreateConstTensor(inputs[2],
1787 biasTensorInfo,
1788 armnn::Optional<armnn::PermutationVector&>());
Sadik Armagan8853c1f2018-10-22 09:04:18 +01001789 layer = m_Network->AddFullyConnectedLayer(desc,
1790 filterTensorAndData.first,
Matteo Martincighfc598e12019-05-14 10:36:13 +01001791 Optional<ConstTensor>(biasTensorAndData.first),
Sadik Armagan8853c1f2018-10-22 09:04:18 +01001792 layerName.c_str());
1793 }
1794 else
1795 {
1796 layer = m_Network->AddFullyConnectedLayer(desc,
1797 filterTensorAndData.first,
Matteo Martincighfc598e12019-05-14 10:36:13 +01001798 EmptyOptional(),
Sadik Armagan8853c1f2018-10-22 09:04:18 +01001799 layerName.c_str());
1800 }
1801 BOOST_ASSERT(layer != nullptr);
1802
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01001803 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1804
1805 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1806
1807 if (inputTensorInfo.GetNumDimensions() > 2)
1808 {
1809 // Add reshape to flatten to 2D [batch_size, input_size],
1810 // where "input_size" corresponds to the number of inputs to the layer,
1811 // matching the second dimension of weights,
1812 // and "batch_size" is calculated by dividing the number of elements by "input_size".
1813 std::vector<unsigned int> reshapedDimensions(2);
1814 reshapedDimensions[1] = filterTensorInfo.GetShape()[1];
1815 reshapedDimensions[0] = inputTensorInfo.GetNumElements() / reshapedDimensions[1];
1816
1817 if (inputTensorInfo.GetNumElements() % reshapedDimensions[1] != 0)
1818 {
1819 throw ParseException(
1820 boost::str(
1821 boost::format(
1822 "Failed to deduce input tensor shape from filter size %1%")
1823 % reshapedDimensions[1]
1824 % CHECK_LOCATION().AsString()));
1825 }
1826
1827 armnn::TensorInfo reshapedTensorInfo = ToTensorInfo(inputs[0]);
1828 reshapedTensorInfo.SetShape(armnn::TensorShape{ 2, reshapedDimensions.data() });
1829
1830 std::string reshapeLayerName = boost::str(boost::format("Reshape_for:%1%") % layer->GetName());
1831 armnn::ReshapeDescriptor desc;
1832 desc.m_TargetShape = reshapedTensorInfo.GetShape();
1833 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(desc, layerName.c_str());
1834
1835 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedTensorInfo);
1836 reshapeLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(0));
1837
1838 RegisterInputSlots(subgraphIndex, operatorIndex, reshapeLayer, {inputTensorIndexes[0]});
1839 }
1840 else
1841 {
1842 // register the input connection slot for the layer
1843 // only the tensors for the inputs are relevant, exclude the const tensors
1844 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1845 }
1846
Sadik Armagan8853c1f2018-10-22 09:04:18 +01001847 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
1848 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1849
Sadik Armagan8853c1f2018-10-22 09:04:18 +01001850 // we need to add the activation layer and fortunately we don't need to care about the data layout
1851 armnn::IConnectableLayer* fusedActivationLayer = AddFusedActivationLayer(layer, 0,
1852 options->fused_activation_function);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01001853
Sadik Armagan8853c1f2018-10-22 09:04:18 +01001854 // register the output connection slots for the layer, connections are made after all layers have been created
1855 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1856 RegisterOutputSlots(subgraphIndex, operatorIndex, fusedActivationLayer, {outputTensorIndexes[0]});
1857}
1858
keidav011b3e2ea2019-02-21 10:07:37 +00001859void TfLiteParser::ParseDetectionPostProcess(size_t subgraphIndex, size_t operatorIndex)
1860{
1861 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1862
1863 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1864
1865 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1866 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1867 CHECK_VALID_SIZE(outputs.size(), 4);
1868
1869 // Obtain custom options from flexbuffers
1870 auto custom_options = operatorPtr->custom_options;
1871 const flexbuffers::Map& m = flexbuffers::GetRoot(custom_options.data(), custom_options.size()).AsMap();
1872
1873 // Obtain descriptor information from tf lite
1874 DetectionPostProcessDescriptor desc;
1875 desc.m_MaxDetections = m["max_detections"].AsUInt32();
1876 desc.m_MaxClassesPerDetection = m["max_classes_per_detection"].AsUInt32();
1877 desc.m_NmsScoreThreshold = m["nms_score_threshold"].AsFloat();
1878 desc.m_NmsIouThreshold = m["nms_iou_threshold"].AsFloat();
1879 desc.m_NumClasses = m["num_classes"].AsUInt32();
1880 desc.m_ScaleH = m["h_scale"].AsFloat();
1881 desc.m_ScaleW = m["w_scale"].AsFloat();
1882 desc.m_ScaleX = m["x_scale"].AsFloat();
1883 desc.m_ScaleY = m["y_scale"].AsFloat();
1884
keidav0107d58c72019-02-26 11:57:39 +00001885 if (!(m["use_regular_nms"].IsNull()))
keidav011b3e2ea2019-02-21 10:07:37 +00001886 {
keidav0107d58c72019-02-26 11:57:39 +00001887 desc.m_UseRegularNms = m["use_regular_nms"].AsBool();
keidav011b3e2ea2019-02-21 10:07:37 +00001888 }
1889 if (!(m["detections_per_class"].IsNull()))
1890 {
1891 desc.m_DetectionsPerClass = m["detections_per_class"].AsUInt32();
1892 }
1893
1894 if (desc.m_NmsIouThreshold <= 0.0f || desc.m_NmsIouThreshold > 1.0f)
1895 {
1896 throw InvalidArgumentException("DetectionPostProcessTFLiteParser: Intersection over union threshold "
1897 "must be positive and less than or equal to 1.");
1898 }
1899
1900 armnn::TensorInfo anchorTensorInfo = ToTensorInfo(inputs[2]);
1901 auto anchorTensorAndData = CreateConstTensor(inputs[2], anchorTensorInfo,
1902 armnn::Optional<armnn::PermutationVector&>());
1903
1904 auto layerName = boost::str(boost::format("DetectionPostProcess:%1%:%2%") % subgraphIndex % operatorIndex);
1905 IConnectableLayer* layer = m_Network->AddDetectionPostProcessLayer(desc, anchorTensorAndData.first,
1906 layerName.c_str());
1907
1908 BOOST_ASSERT(layer != nullptr);
1909
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00001910 // The model does not specify the output shapes.
1911 // The output shapes are calculated from the max_detection and max_classes_per_detection.
1912 unsigned int numDetectedBox = desc.m_MaxDetections * desc.m_MaxClassesPerDetection;
1913 m_OverridenOutputShapes.push_back({ 1, numDetectedBox, 4 });
1914 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
1915 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
1916 m_OverridenOutputShapes.push_back({ 1 });
1917
keidav011b3e2ea2019-02-21 10:07:37 +00001918 for (unsigned int i = 0 ; i < outputs.size() ; ++i)
1919 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00001920 armnn::TensorInfo detectionBoxOutputTensorInfo = ToTensorInfo(outputs[i], m_OverridenOutputShapes[i]);
keidav011b3e2ea2019-02-21 10:07:37 +00001921 layer->GetOutputSlot(i).SetTensorInfo(detectionBoxOutputTensorInfo);
1922 }
1923
1924 // Register the input connection slots for the layer, connections are made after all layers have been created
1925 // only the tensors for the inputs are relevant, exclude the const tensors
1926 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1927 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
1928
1929 // Register the output connection slots for the layer, connections are made after all layers have been created
1930 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1931 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0],
1932 outputTensorIndexes[1],
1933 outputTensorIndexes[2],
1934 outputTensorIndexes[3]});
1935}
1936
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01001937/// The TfLite Pack operator is equivalent to the ArmNN Stack operator
1938void TfLiteParser::ParsePack(size_t subgraphIndex, size_t operatorIndex)
1939{
1940 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1941
1942 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1943 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1944 CHECK_VALID_SIZE(outputs.size(), 1);
1945
1946 if (inputs.size() < 1)
1947 {
1948 throw ParseException("Pack must have at least one input.");
1949 }
1950
1951 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1952 const auto* options = operatorPtr->builtin_options.AsPackOptions();
1953
1954 StackDescriptor desc;
1955 desc.m_Axis = static_cast<uint32_t>(options->axis);
1956 desc.m_NumInputs = static_cast<uint32_t>(inputs.size());
1957
1958 // Use the tensor shape of the first input as the "correct" input shape in the descriptor
1959 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1960 desc.m_InputShape = inputTensorInfo.GetShape();
1961
1962 auto layerName = boost::str(boost::format("Pack:%1%:%2%") % subgraphIndex % operatorIndex);
1963 IConnectableLayer* layer = m_Network->AddStackLayer(desc, layerName.c_str());
1964
1965 BOOST_ASSERT(layer != nullptr);
1966
1967 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
1968 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1969
1970 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1971 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
1972
1973 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1974 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1975}
1976
Nina Drozd200e3802019-04-15 09:47:39 +01001977void TfLiteParser::ParseUnpack(size_t subgraphIndex, size_t operatorIndex)
1978{
1979 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1980
1981 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1982 const auto * options = operatorPtr->builtin_options.AsUnpackOptions();
1983
1984 // This unpackAxis indicates the axis to unpack
1985 const unsigned int unpackAxis = CHECKED_NON_NEGATIVE(options->axis);
1986
1987 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1988 CHECK_VALID_SIZE(inputs.size(), 1);
1989
1990 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01001991
1992 if (unpackAxis >= inputTensorInfo.GetNumDimensions())
1993 {
1994 throw ParseException(
1995 boost::str(
1996 boost::format(
1997 "The unpack axis: %1% cannot be greater than or equal to "
1998 "the number of input dimension %2% %3%")
1999 % unpackAxis
2000 % inputTensorInfo.GetNumDimensions()
2001 % CHECK_LOCATION().AsString()));
2002 }
2003
Nina Drozd200e3802019-04-15 09:47:39 +01002004 unsigned int unpackNum = CHECKED_NON_NEGATIVE(options->num);
2005 // If num is not defined, automatically infer from the length of the dimension axis.
2006 if(unpackNum == 0)
2007 {
2008 unpackNum = inputTensorInfo.GetShape()[unpackAxis];
2009 }
2010
2011 // If unpack number cannot be inferred and is still zero, throw ParseException.
2012 if(unpackNum == 0)
2013 {
2014 throw ParseException("Number to unpack must greater than zero.");
2015 }
2016
2017 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2018 CHECK_VALID_SIZE(outputs.size(), unpackNum);
2019
2020 auto inputDimSize = inputTensorInfo.GetNumDimensions();
2021 std::vector<unsigned int> unpackDimSizes(inputDimSize);
2022
2023 // Add current input shape to unpackDimSizes
2024 for (unsigned int i = 0; i < inputDimSize; ++i)
2025 {
2026 unpackDimSizes[i] = inputTensorInfo.GetShape()[i];
2027 }
2028
2029 if (unpackDimSizes[unpackAxis] != unpackNum)
2030 {
2031 throw ParseException("Number to unpack must be the same as length of the dimension to "
2032 "unpack along.");
2033 }
2034
2035 unpackDimSizes[unpackAxis] /= unpackNum;
2036
2037 SplitterDescriptor splitDesc(unpackNum, static_cast<unsigned int>(unpackDimSizes.size()));
2038 for (unsigned int j = 0; j < unpackNum; ++j)
2039 {
2040 // Set the size of the views.
2041 for (unsigned int dimIdx = 0; dimIdx < unpackDimSizes.size(); ++dimIdx)
2042 {
2043 splitDesc.SetViewSize(j, dimIdx, unpackDimSizes[dimIdx]);
2044 }
2045 splitDesc.SetViewOriginCoord(j, unpackAxis, unpackDimSizes[unpackAxis] * j);
2046 }
2047
2048 auto layerName = boost::str(boost::format("Unpack:%1%:%2%") % subgraphIndex % operatorIndex);
2049 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
2050
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002051 TensorShape splitOutShape = TensorShape(static_cast<unsigned int>(unpackDimSizes.size()),
2052 unpackDimSizes.data());
2053
Nina Drozd200e3802019-04-15 09:47:39 +01002054 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2055 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2056
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002057 // Reshape to remove unpacked dimension
2058 unsigned int reshapedNumDimensions = inputDimSize - 1;
2059 std::vector<unsigned int> reshapedDimensions(reshapedNumDimensions);
Nina Drozd200e3802019-04-15 09:47:39 +01002060
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002061 unsigned int reshapeIndex = 0;
2062 for (unsigned int i = 0; i < inputDimSize; ++i)
Nina Drozd200e3802019-04-15 09:47:39 +01002063 {
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002064 if (i == unpackAxis)
2065 {
2066 continue;
2067 }
2068 reshapedDimensions[reshapeIndex++] = unpackDimSizes[i];
Nina Drozd200e3802019-04-15 09:47:39 +01002069 }
2070
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002071 // Create reshape to remove the unpacked dimension for unpack operator of each output from Splitter.
2072 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
2073 {
2074 armnn::TensorInfo reshapedTensorInfo = inputTensorInfo;
2075 reshapedTensorInfo.SetShape(armnn::TensorShape{ reshapedNumDimensions, reshapedDimensions.data() });
2076
2077 std::string reshapeLayerName = boost::str(boost::format("Reshape_for:%1%") % layer->GetName());
2078 armnn::ReshapeDescriptor desc;
2079 desc.m_TargetShape = reshapedTensorInfo.GetShape();
2080 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(desc, layerName.c_str());
2081
2082 layer->GetOutputSlot(k).SetTensorInfo(armnn::TensorInfo(splitOutShape, inputTensorInfo.GetDataType()));
2083 layer->GetOutputSlot(k).Connect(reshapeLayer->GetInputSlot(0));
2084
2085 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedTensorInfo);
2086
2087 uint32_t reshapedOutputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[k]);
2088 armnn::IOutputSlot* slot = &(reshapeLayer->GetOutputSlot(0));
2089 RegisterProducerOfTensor(subgraphIndex, reshapedOutputId, slot);
2090 }
Nina Drozd200e3802019-04-15 09:47:39 +01002091}
2092
Nina Drozd0324f482019-04-08 10:52:10 +01002093void TfLiteParser::ParseSplit(size_t subgraphIndex, size_t operatorIndex)
2094{
2095 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2096
2097 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2098 const auto * options = operatorPtr->builtin_options.AsSplitOptions();
2099
2100 const unsigned int numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
2101
Nina Drozd200e3802019-04-15 09:47:39 +01002102 // If number of splits cannot be inferred and is zero, throw ParseException.
2103 if(numSplits == 0)
2104 {
2105 throw ParseException("Number to splits must greater than zero.");
2106 }
2107
Nina Drozd0324f482019-04-08 10:52:10 +01002108 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2109 CHECK_VALID_SIZE(inputs.size(), 2);
2110 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2111 CHECK_VALID_SIZE(outputs.size(), numSplits);
2112
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002113 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[1]);
2114 armnn::TensorInfo axisTensorInfo = ToTensorInfo(inputs[0]);
Nina Drozd0324f482019-04-08 10:52:10 +01002115
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002116 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
2117 std::vector<unsigned int> axisData(axisTensorInfo.GetNumElements());
2118 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
2119
2120 BOOST_ASSERT(axisTensorInfo.GetNumElements() == 1);
2121 const unsigned int splitDim = axisData[0];
Nina Drozd0324f482019-04-08 10:52:10 +01002122
2123 // Armnn supports split along the channel dimension for data formats NHWC and NCHW.
2124 if (splitDim == 0 || splitDim == 2)
2125 {
2126 throw ParseException(
2127 boost::str(
2128 boost::format(
2129 "Dimension %1% for split is not supported by Armnn. %2%")
2130 % splitDim
2131 % CHECK_LOCATION().AsString()));
2132 }
2133
2134 auto inputDimSize = inputTensorInfo.GetNumDimensions();
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002135 if (inputDimSize > MaxNumOfTensorDimensions)
Nina Drozd0324f482019-04-08 10:52:10 +01002136 {
2137 throw ParseException(
2138 boost::str(
2139 boost::format(
2140 "The number of dimensions: %1% for input tensors of the "
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002141 "split op cannot be greater than %2% %3%")
Nina Drozd0324f482019-04-08 10:52:10 +01002142 % inputTensorInfo.GetNumDimensions()
2143 % MaxNumOfTensorDimensions
2144 % CHECK_LOCATION().AsString()));
2145 }
2146
2147 std::vector<unsigned int> splitterDimSizes(inputDimSize);
2148
2149 // Add current input shape to splitterDimSizes
2150 for (unsigned int i = 0; i < inputDimSize; ++i)
2151 {
2152 splitterDimSizes[i] = inputTensorInfo.GetShape()[i];
2153 }
2154
2155 if (splitterDimSizes[splitDim] % numSplits != 0)
2156 {
2157 throw ParseException("Number of splits must evenly divide the dimension");
2158 }
2159 splitterDimSizes[splitDim] /= numSplits;
2160
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002161 SplitterDescriptor splitDesc(numSplits, inputDimSize);
Nina Drozd0324f482019-04-08 10:52:10 +01002162 for (unsigned int j = 0; j < numSplits; ++j)
2163 {
2164 // Set the size of the views.
2165 for (unsigned int dimIdx = 0; dimIdx < splitterDimSizes.size(); ++dimIdx)
2166 {
2167 splitDesc.SetViewSize(j, dimIdx, splitterDimSizes[dimIdx]);
2168 }
2169 splitDesc.SetViewOriginCoord(j, splitDim, splitterDimSizes[splitDim] * j);
2170 }
2171
2172 auto layerName = boost::str(boost::format("Split:%1%:%2%") % subgraphIndex % operatorIndex);
2173 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
2174
2175 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002176 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[1]});
Nina Drozd0324f482019-04-08 10:52:10 +01002177
2178 TensorShape outShape = TensorShape(static_cast<unsigned int>(splitterDimSizes.size()),
2179 splitterDimSizes.data());
2180
2181 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
2182 {
2183 layer->GetOutputSlot(k).SetTensorInfo(armnn::TensorInfo(outShape,
2184 inputTensorInfo.GetDataType()));
2185 }
2186
2187 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2188 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2189}
2190
Sadik Armagan58f39192018-09-17 14:14:39 +01002191armnn::IConnectableLayer* TfLiteParser::AddFusedActivationLayer(armnn::IConnectableLayer* prevLayer,
2192 unsigned int outputSlot,
2193 tflite::ActivationFunctionType activationType)
telsoa01c577f2c2018-08-31 09:22:23 +01002194{
2195 ActivationDescriptor activationDesc;
2196 std::string layerName = prevLayer->GetName();
2197
2198 switch(activationType)
2199 {
2200 case tflite::ActivationFunctionType_NONE:
2201 {
2202 // this is a no-op: return previous layer
2203 return prevLayer;
2204 }
2205 case tflite::ActivationFunctionType_RELU:
2206 {
2207 activationDesc.m_Function = ActivationFunction::ReLu;
2208 layerName += ":RELU";
2209 break;
2210 }
2211 case tflite::ActivationFunctionType_RELU6:
2212 {
2213 activationDesc.m_Function = ActivationFunction::BoundedReLu;
2214 activationDesc.m_A = 6.0f;
2215 activationDesc.m_B = 0.0f;
2216 layerName += ":RELU6";
2217 break;
2218 }
2219 case tflite::ActivationFunctionType_TANH:
2220 {
2221 activationDesc.m_Function = ActivationFunction::TanH;
2222 activationDesc.m_A = 1.0f;
2223 activationDesc.m_B = 1.0f;
2224 layerName += ":TANH";
2225 break;
2226 }
2227
2228 // I only put these here as a reminder what others we could support
2229 case tflite::ActivationFunctionType_RELU_N1_TO_1:
2230 case tflite::ActivationFunctionType_SIGN_BIT:
2231 default:
2232 {
2233 throw ParseException(
2234 boost::str(
2235 boost::format("TfLite parser doesn't suppport fused activation: "
2236 "%1%/%2% %3% ") %
2237 activationType %
2238 tflite::EnumNameActivationFunctionType(activationType) %
2239 CHECK_LOCATION().AsString()));
2240
2241 }
2242 }
2243
2244 IConnectableLayer* activationLayer =
2245 m_Network->AddActivationLayer(activationDesc, layerName.c_str());
2246
2247 auto & prevOutputSlot = prevLayer->GetOutputSlot(outputSlot);
2248 prevOutputSlot.Connect(activationLayer->GetInputSlot(0));
2249 activationLayer->GetOutputSlot(0).SetTensorInfo(prevOutputSlot.GetTensorInfo());
2250 return activationLayer;
2251}
2252
2253TfLiteParser::ModelPtr TfLiteParser::LoadModelFromFile(const char * fileName)
2254{
2255 if (fileName == nullptr)
2256 {
2257 throw InvalidArgumentException(boost::str(boost::format("Invalid (null) file name %1%") %
2258 CHECK_LOCATION().AsString()));
2259 }
2260 boost::system::error_code errorCode;
2261 boost::filesystem::path pathToFile(fileName);
2262 if (!boost::filesystem::exists(pathToFile, errorCode))
2263 {
2264 throw FileNotFoundException(boost::str(boost::format("Cannot find the file (%1%) errorCode: %2% %3%") %
2265 fileName %
2266 errorCode %
2267 CHECK_LOCATION().AsString()));
2268 }
2269 std::ifstream file(fileName, std::ios::binary);
2270 std::string fileContent((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
2271 return LoadModelFromBinary(reinterpret_cast<const uint8_t *>(fileContent.c_str()),
2272 fileContent.size());
2273}
2274
2275TfLiteParser::ModelPtr TfLiteParser::LoadModelFromBinary(const uint8_t * binaryContent, size_t len)
2276{
2277 if (binaryContent == nullptr)
2278 {
2279 throw InvalidArgumentException(boost::str(boost::format("Invalid (null) binary content %1%") %
2280 CHECK_LOCATION().AsString()));
2281 }
2282 flatbuffers::Verifier verifier(binaryContent, len);
2283 if (verifier.VerifyBuffer<tflite::Model>() == false)
2284 {
2285 throw ParseException(
2286 boost::str(boost::format("Buffer doesn't conform to the expected Tensorflow Lite "
2287 "flatbuffers format. size:%1% %2%") %
2288 len %
2289 CHECK_LOCATION().AsString()));
2290 }
2291 return tflite::UnPackModel(binaryContent);
2292}
2293
2294TfLiteParser::TensorRawPtrVector TfLiteParser::GetInputs(const ModelPtr & model,
2295 size_t subgraphIndex,
2296 size_t operatorIndex)
2297{
2298 CHECK_MODEL(model, subgraphIndex, operatorIndex);
2299
Derek Lambertiff05cc52019-04-26 13:05:17 +01002300 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
2301 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01002302
2303 size_t inputCount = operatorPtr->inputs.size();
2304 TensorRawPtrVector result(inputCount);
2305 for (size_t i=0; i<inputCount; ++i)
2306 {
2307 uint32_t inputId = CHECKED_NON_NEGATIVE(operatorPtr->inputs[i]);
Derek Lambertiff05cc52019-04-26 13:05:17 +01002308 result[i] = subgraphPtr->tensors[inputId].get();
telsoa01c577f2c2018-08-31 09:22:23 +01002309 }
2310 return result;
2311}
2312
2313TfLiteParser::TensorRawPtrVector TfLiteParser::GetOutputs(const ModelPtr & model,
2314 size_t subgraphIndex,
2315 size_t operatorIndex)
2316{
2317 CHECK_MODEL(model, subgraphIndex, operatorIndex);
2318
Derek Lambertiff05cc52019-04-26 13:05:17 +01002319 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
2320 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01002321
2322 size_t outputCount = operatorPtr->outputs.size();
2323 TensorRawPtrVector result(outputCount);
2324 for (size_t i=0; i<outputCount; ++i)
2325 {
2326 uint32_t outputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[i]);
2327 CHECK_TENSOR(model, subgraphIndex, outputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01002328 result[i] = subgraphPtr->tensors[outputId].get();
telsoa01c577f2c2018-08-31 09:22:23 +01002329 }
2330 return result;
2331}
2332
2333TfLiteParser::TensorIdRawPtrVector TfLiteParser::GetSubgraphInputs(const ModelPtr & model,
2334 size_t subgraphIndex)
2335{
2336 CHECK_SUBGRAPH(model, subgraphIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01002337 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01002338
Derek Lambertiff05cc52019-04-26 13:05:17 +01002339 size_t inputCount = subgraphPtr->inputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01002340 TensorIdRawPtrVector result(inputCount);
2341 for (size_t i=0; i<inputCount; ++i)
2342 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01002343 uint32_t inputId = CHECKED_NON_NEGATIVE(subgraphPtr->inputs[i]);
telsoa01c577f2c2018-08-31 09:22:23 +01002344 CHECK_TENSOR(model, subgraphIndex, inputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01002345 result[i] = std::make_pair(inputId, subgraphPtr->tensors[inputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01002346 }
2347 return result;
2348}
2349
2350TfLiteParser::TensorIdRawPtrVector TfLiteParser::GetSubgraphOutputs(const ModelPtr & model,
2351 size_t subgraphIndex)
2352{
2353 CHECK_SUBGRAPH(model, subgraphIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01002354 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01002355
Derek Lambertiff05cc52019-04-26 13:05:17 +01002356 size_t outputCount = subgraphPtr->outputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01002357 TensorIdRawPtrVector result(outputCount);
2358 for (size_t i=0; i<outputCount; ++i)
2359 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01002360 uint32_t outputId = CHECKED_NON_NEGATIVE(subgraphPtr->outputs[i]);
2361 result[i] = std::make_pair(outputId, subgraphPtr->tensors[outputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01002362 }
2363 return result;
2364}
2365
2366std::vector<int32_t>& TfLiteParser::GetInputTensorIds(const ModelPtr& model,
2367 size_t subgraphIndex,
2368 size_t operatorIndex)
2369{
2370 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01002371 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
2372 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01002373 return operatorPtr->inputs;
2374}
2375
2376std::vector<int32_t>& TfLiteParser::GetOutputTensorIds(const ModelPtr& model,
2377 size_t subgraphIndex,
2378 size_t operatorIndex)
2379{
2380 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01002381 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
2382 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01002383 return operatorPtr->outputs;
2384}
2385
2386void TfLiteParser::RegisterInputSlots(size_t subgraphIndex,
2387 size_t operatorIndex,
2388 IConnectableLayer* layer,
2389 const std::vector<unsigned int>& tensorIndexes)
2390{
2391 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2392 BOOST_ASSERT(layer != nullptr);
2393 if (tensorIndexes.size() != layer->GetNumInputSlots())
2394 {
2395 throw ParseException(
2396 boost::str(boost::format("The number of tensor inputs (%1%) does not match the number expected (%2%)"
2397 " for subgraph:%3% operator index:%4% %5%") %
2398 tensorIndexes.size() %
2399 layer->GetNumInputSlots() %
2400 subgraphIndex %
2401 operatorIndex %
2402 CHECK_LOCATION().AsString()));
2403 }
2404
2405 for (unsigned int slotIndex = 0; slotIndex < layer->GetNumInputSlots(); ++slotIndex)
2406 {
2407 unsigned int tensorIndex = tensorIndexes[slotIndex];
2408 armnn::IInputSlot* slot = &(layer->GetInputSlot(slotIndex));
2409 RegisterConsumerOfTensor(subgraphIndex, tensorIndex, slot);
2410 }
2411}
2412
2413void TfLiteParser::RegisterOutputSlots(size_t subgraphIndex,
2414 size_t operatorIndex,
2415 IConnectableLayer* layer,
2416 const std::vector<unsigned int>& tensorIndexes)
2417{
2418 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2419 BOOST_ASSERT(layer != nullptr);
2420 if (tensorIndexes.size() != layer->GetNumOutputSlots())
2421 {
2422 throw ParseException(
2423 boost::str(boost::format("The number of tensor outputs (%1%) does not match the number expected (%2%)"
2424 " for subgraph:%3% operator index:%4% %5%") %
2425 tensorIndexes.size() %
2426 layer->GetNumOutputSlots() %
2427 subgraphIndex %
2428 operatorIndex %
2429 CHECK_LOCATION().AsString()));
2430 }
2431
2432 for (unsigned int slotIndex = 0; slotIndex < layer->GetNumOutputSlots(); ++slotIndex)
2433 {
2434 unsigned int tensorIndex = tensorIndexes[slotIndex];
2435 armnn::IOutputSlot* slot = &(layer->GetOutputSlot(slotIndex));
2436 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
2437 }
2438}
2439
2440void TfLiteParser::SetupInputLayers(size_t subgraphIndex)
2441{
2442 CHECK_SUBGRAPH(m_Model, subgraphIndex);
2443
2444 auto inputs = GetSubgraphInputs(m_Model, subgraphIndex);
2445 for (auto const & tensorIdAndPtr : inputs)
2446 {
2447 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
2448 IConnectableLayer* layer =
2449 m_Network->AddInputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
2450
2451 auto tensorInfo = ToTensorInfo(tensorIdAndPtr.second);
2452 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
2453
2454 RegisterOutputSlots(subgraphIndex,
2455 VIRTUAL_OPERATOR_ID,
2456 layer,
2457 { static_cast<uint32_t>(tensorIdAndPtr.first) });
2458 }
2459}
2460
2461void TfLiteParser::SetupOutputLayers(size_t subgraphIndex)
2462{
2463 CHECK_SUBGRAPH(m_Model, subgraphIndex);
2464
2465 auto outputs = GetSubgraphOutputs(m_Model, subgraphIndex);
2466 for (auto const & tensorIdAndPtr : outputs)
2467 {
2468 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
2469 IConnectableLayer* layer =
2470 m_Network->AddOutputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
2471
2472 RegisterInputSlots(subgraphIndex,
2473 VIRTUAL_OPERATOR_ID,
2474 layer,
2475 { static_cast<uint32_t>(tensorIdAndPtr.first) });
2476 }
2477}
2478
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02002479void TfLiteParser::SetupConstantLayers(size_t subgraphIndex)
2480{
2481 CHECK_SUBGRAPH(m_Model, subgraphIndex);
2482
Derek Lambertiff05cc52019-04-26 13:05:17 +01002483 const auto & subgraphPtr = m_Model->subgraphs[subgraphIndex];
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02002484 for (unsigned int subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
2485 {
2486 for (unsigned int tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
2487 {
2488 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot == nullptr &&
2489 m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size() > 0)
2490 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01002491 TensorRawPtr tensorPtr = subgraphPtr->tensors[tensorIndex].get();
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02002492 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
2493 auto tensorAndData = CreateConstTensor(tensorPtr,
2494 tensorInfo,
2495 armnn::Optional<armnn::PermutationVector&>());
2496
2497 std::string layerName = boost::str(boost::format("Constant:%1%") % tensorPtr->name);
2498 IConnectableLayer *layer =
2499 m_Network->AddConstantLayer(tensorAndData.first, layerName.c_str());
2500
2501 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
2502 RegisterOutputSlots(subgraphIndex,
2503 VIRTUAL_OPERATOR_ID,
2504 layer,
2505 { tensorIndex });
2506
2507 }
2508 }
2509 }
2510}
2511
telsoa01c577f2c2018-08-31 09:22:23 +01002512// example usage: BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
2513TfLiteParser::BufferRawPtr TfLiteParser::GetBuffer(const ModelPtr& model, size_t bufferIndex)
2514{
2515 CHECK_BUFFER(model, bufferIndex);
2516 return model->buffers[bufferIndex].get();
2517}
2518
Matteo Martincigh747ef822018-12-18 09:26:39 +00002519template<typename T>
2520std::pair<armnn::ConstTensor, TfLiteParser::SupportedDataStorage>
2521TfLiteParser::CreateConstTensorAndStoreData(TfLiteParser::BufferRawPtr bufferPtr,
2522 TfLiteParser::TensorRawPtr tensorPtr,
2523 armnn::TensorInfo& tensorInfo,
2524 armnn::Optional<armnn::PermutationVector&> permutationVector)
2525{
2526 auto constData = CreateConstTensorImpl<T>(bufferPtr,
2527 tensorPtr,
2528 tensorInfo,
2529 permutationVector);
2530 TfLiteParser::SupportedDataStorage storage(std::move(constData.second));
2531 return std::make_pair(constData.first, std::move(storage));
2532}
2533
telsoa01c577f2c2018-08-31 09:22:23 +01002534std::pair<armnn::ConstTensor, TfLiteParser::SupportedDataStorage>
2535TfLiteParser::CreateConstTensor(TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +00002536 armnn::TensorInfo& tensorInfo,
2537 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +01002538{
2539 CHECK_TENSOR_PTR(tensorPtr);
2540 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
2541 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
2542
2543 switch (tensorInfo.GetDataType())
2544 {
2545 case armnn::DataType::Float32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00002546 return CreateConstTensorAndStoreData<float>(bufferPtr,
2547 tensorPtr,
2548 tensorInfo,
2549 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01002550 case armnn::DataType::QuantisedAsymm8:
Matteo Martincigh747ef822018-12-18 09:26:39 +00002551 return CreateConstTensorAndStoreData<uint8_t>(bufferPtr,
2552 tensorPtr,
2553 tensorInfo,
2554 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01002555 case armnn::DataType::Signed32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00002556 return CreateConstTensorAndStoreData<int32_t>(bufferPtr,
2557 tensorPtr,
2558 tensorInfo,
2559 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01002560 default:
2561 {
2562 std::stringstream errString;
2563 errString << "Unexpected datatype when creating const tensor: "
2564 << armnn::GetDataTypeName(tensorInfo.GetDataType())
2565 << " shape:" << tensorInfo.GetShape()
2566 << CHECK_LOCATION().AsString();
2567 throw ParseException(errString.str());
2568 }
2569 }
2570}
2571
2572BindingPointInfo TfLiteParser::GetNetworkInputBindingInfo(size_t subgraphId,
2573 const std::string& name) const
2574{
2575 CHECK_SUBGRAPH(m_Model, subgraphId);
2576 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
2577 for (auto const & input : inputs)
2578 {
2579 if (input.second->name == name)
2580 {
2581 auto bindingId = GenerateLayerBindingId(subgraphId, input.first);
2582 return std::make_pair(bindingId, ToTensorInfo(input.second));
2583 }
2584 }
2585
2586 std::stringstream bindings;
2587 for (auto const & input : inputs)
2588 {
2589 bindings << "'" << input.second->name << "' ";
2590 }
2591
2592 throw ParseException(
2593 boost::str(
2594 boost::format("No input binding found for subgraph:%1% and name:%2%. "
2595 "Possible inputs are: [%3%] %4%") %
2596 subgraphId %
2597 name %
2598 bindings.str() %
2599 CHECK_LOCATION().AsString()));
2600}
2601
2602BindingPointInfo TfLiteParser::GetNetworkOutputBindingInfo(size_t subgraphId,
2603 const std::string& name) const
2604{
2605 CHECK_SUBGRAPH(m_Model, subgraphId);
2606 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00002607 for (unsigned int i = 0; i < outputs.size(); ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01002608 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00002609 auto const output = outputs[i];
telsoa01c577f2c2018-08-31 09:22:23 +01002610 if (output.second->name == name)
2611 {
2612 auto bindingId = GenerateLayerBindingId(subgraphId, output.first);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00002613 std::vector<unsigned int> shape = m_OverridenOutputShapes.size() > 0 ?
2614 m_OverridenOutputShapes[i] : AsUnsignedVector(output.second->shape);
2615 return std::make_pair(bindingId, ToTensorInfo(output.second, shape));
telsoa01c577f2c2018-08-31 09:22:23 +01002616 }
2617 }
2618
2619 std::stringstream bindings;
2620 for (auto const & output : outputs)
2621 {
2622 bindings << "'" << output.second->name << "' ";
2623 }
2624
2625 throw ParseException(
2626 boost::str(
2627 boost::format("No output binding found for subgraph:%1% and name:%2%. "
2628 "Possible outputs are: [%3%] %4%") %
2629 subgraphId %
2630 name %
2631 bindings.str() %
2632 CHECK_LOCATION().AsString()));
2633}
2634
2635size_t TfLiteParser::GetSubgraphCount() const
2636{
2637 return m_Model->subgraphs.size();
2638}
2639
2640std::vector<std::string> TfLiteParser::GetSubgraphInputTensorNames(size_t subgraphId) const
2641{
2642 CHECK_SUBGRAPH(m_Model, subgraphId);
2643 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
2644 std::vector<std::string> result;
2645 result.reserve(inputs.size());
2646 for (auto const & input : inputs)
2647 {
2648 result.push_back(input.second->name);
2649 }
2650 return result;
2651}
2652
2653std::vector<std::string> TfLiteParser::GetSubgraphOutputTensorNames(size_t subgraphId) const
2654{
2655 CHECK_SUBGRAPH(m_Model, subgraphId);
2656 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
2657 std::vector<std::string> result;
2658 result.reserve(outputs.size());
2659 for (auto const & output : outputs)
2660 {
2661 result.push_back(output.second->name);
2662 }
2663 return result;
2664}
2665
2666ITfLiteParser* ITfLiteParser::CreateRaw()
2667{
2668 return new TfLiteParser();
2669}
2670
2671ITfLiteParserPtr ITfLiteParser::Create()
2672{
2673 return ITfLiteParserPtr(CreateRaw(), &ITfLiteParser::Destroy);
2674}
2675
2676void ITfLiteParser::Destroy(ITfLiteParser* parser)
2677{
2678 delete parser;
2679}
2680
2681TfLiteParser::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<float[]> && data)
2682: m_FloatData(std::move(data))
2683, m_Uint8Data(nullptr)
2684, m_Int32Data(nullptr)
2685{
2686}
2687
2688TfLiteParser::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<uint8_t[]> && data)
2689: m_FloatData(nullptr)
2690, m_Uint8Data(std::move(data))
2691, m_Int32Data(nullptr)
2692{
2693}
2694
2695TfLiteParser::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int32_t[]> && data)
2696: m_FloatData(nullptr)
2697, m_Uint8Data(nullptr)
2698, m_Int32Data(std::move(data))
2699{
2700}
2701
2702} // armnnTfLiteParser