blob: a68839c20e03e07c3ef7cda8a2b83173f963698d [file] [log] [blame]
telsoa01c577f2c2018-08-31 09:22:23 +01001//
Mike Kellyc5789ca2020-07-06 19:24:15 +01002// Copyright © 2017 Arm Ltd and Contributors. All rights reserved.
David Beckecb56cd2018-09-05 12:52:57 +01003// SPDX-License-Identifier: MIT
telsoa01c577f2c2018-08-31 09:22:23 +01004//
Matteo Martincighe011d202019-11-28 11:35:47 +00005
telsoa01c577f2c2018-08-31 09:22:23 +01006#include "TfLiteParser.hpp"
7
Matthew Sloyanac001ee2021-02-03 10:43:04 +00008#include "armnnTfLiteParser/Version.hpp"
9
Sadik Armagand109a4d2020-07-28 10:42:13 +010010#include <armnn/BackendOptions.hpp>
Matthew Bentham39ef3e52020-01-20 10:09:09 +000011#include <armnn/Descriptors.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010012#include <armnn/Exceptions.hpp>
Derek Lamberti08446972019-11-26 16:38:31 +000013#include <armnn/Logging.hpp>
James Conroy05102392020-06-24 15:39:55 +010014#include <armnn/Tensor.hpp>
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +000015#include <armnnUtils/TensorUtils.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010016#include <armnn/TypesUtils.hpp>
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +010017#include <armnn/utility/Assert.hpp>
Jan Eilers8eb25602020-03-09 12:13:48 +000018#include <armnn/utility/IgnoreUnused.hpp>
Derek Lambertif0176992020-04-28 13:37:49 +010019#include <armnn/utility/NumericCast.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010020
21// armnnUtils:
Matteo Martincighe011d202019-11-28 11:35:47 +000022#include <armnnUtils/Permute.hpp>
Francis Murtagh532a29d2020-06-29 11:50:01 +010023#include <Filesystem.hpp>
Matteo Martincighe011d202019-11-28 11:35:47 +000024
Sadik Armagan479045b2018-10-01 11:51:37 +010025#include <ParserHelper.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010026#include <VerificationHelpers.hpp>
27
28// The generated code based on the Tf Lite schema:
29#include <schema_generated.h>
30
Matteo Martincighe011d202019-11-28 11:35:47 +000031#include <flatbuffers/flexbuffers.h>
32
James Ward58dec6b2020-09-11 17:32:44 +010033#include <fmt/format.h>
telsoa01c577f2c2018-08-31 09:22:23 +010034
telsoa01c577f2c2018-08-31 09:22:23 +010035#include <algorithm>
Matthew Sloyanac001ee2021-02-03 10:43:04 +000036#include <fstream>
37#include <iostream>
telsoa01c577f2c2018-08-31 09:22:23 +010038#include <limits>
Sadikb94967b2018-09-19 15:30:00 +010039#include <numeric>
Derek Lambertic9e52792020-03-11 11:42:26 +000040#include <sstream>
41
42#define ARMNN_THROW_PARSE_EXCEPTION(msg) \
43 { \
44 throw armnn::ParseException( static_cast<const std::stringstream&>( std::stringstream() << msg \
45 << ": " \
46 << CHECK_LOCATION().AsString()).str()); \
47 }
telsoa01c577f2c2018-08-31 09:22:23 +010048
49using namespace armnn;
50using armnn::CheckLocation;
51namespace armnnTfLiteParser
52{
Kevin May7d96b162021-02-03 17:38:41 +000053
54ITfLiteParser::ITfLiteParser(const armnn::Optional<TfLiteParserOptions>& options) :
55 pTfLiteParserImpl(new TfLiteParserImpl(options)) {}
56
57ITfLiteParser::~ITfLiteParser() = default;
58
59ITfLiteParser* ITfLiteParser::CreateRaw(const armnn::Optional<TfLiteParserOptions>& options)
60{
61 return new ITfLiteParser(options);
62}
63
64ITfLiteParserPtr ITfLiteParser::Create(const armnn::Optional<TfLiteParserOptions>& options)
65{
66 return ITfLiteParserPtr(CreateRaw(options), &ITfLiteParser::Destroy);
67}
68
69void ITfLiteParser::Destroy(ITfLiteParser* parser)
70{
71 delete parser;
72}
73
74armnn::INetworkPtr ITfLiteParser::CreateNetworkFromBinaryFile(const char* graphFile)
75{
76 return pTfLiteParserImpl->CreateNetworkFromBinaryFile(graphFile);
77}
78
79armnn::INetworkPtr ITfLiteParser::CreateNetworkFromBinary(const std::vector<uint8_t> & binaryContent)
80{
81 return pTfLiteParserImpl->CreateNetworkFromBinary(binaryContent);
82}
83
84BindingPointInfo ITfLiteParser::GetNetworkInputBindingInfo(size_t subgraphId,
85 const std::string& name) const
86{
87 return pTfLiteParserImpl->GetNetworkInputBindingInfo(subgraphId, name);
88}
89
90BindingPointInfo ITfLiteParser::GetNetworkOutputBindingInfo(size_t subgraphId,
91 const std::string& name) const
92{
93 return pTfLiteParserImpl->GetNetworkOutputBindingInfo(subgraphId, name);
94}
95
96size_t ITfLiteParser::GetSubgraphCount() const
97{
98 return pTfLiteParserImpl->GetSubgraphCount();
99}
100
101std::vector<std::string> ITfLiteParser::GetSubgraphInputTensorNames(size_t subgraphId) const
102{
103 return pTfLiteParserImpl->GetSubgraphInputTensorNames(subgraphId);
104}
105
106std::vector<std::string> ITfLiteParser::GetSubgraphOutputTensorNames(size_t subgraphId) const
107{
108 return pTfLiteParserImpl->GetSubgraphOutputTensorNames(subgraphId);
109}
110
telsoa01c577f2c2018-08-31 09:22:23 +0100111namespace
112{
jimfly01c25411c2018-11-14 17:47:22 +0000113
telsoa01c577f2c2018-08-31 09:22:23 +0100114const uint32_t VIRTUAL_OPERATOR_ID = std::numeric_limits<uint32_t>::max();
115
Kevin May7d96b162021-02-03 17:38:41 +0000116void CheckSubgraph(const TfLiteParserImpl::ModelPtr & model,
telsoa01c577f2c2018-08-31 09:22:23 +0100117 size_t subgraphIndex,
118 const CheckLocation & location)
119{
120 if (model.get() == nullptr)
121 {
122 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100123 fmt::format("{} was called with invalid (null) model. "
124 "Possible reason is that the model is not yet loaded and Unpack(ed). "
125 "subgraph:{} at {}",
126 location.m_Function,
127 subgraphIndex,
128 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100129 }
130 else if (subgraphIndex >= model->subgraphs.size())
131 {
132 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100133 fmt::format("{} was called with an invalid subgraph index. "
134 "subgraph:{} at {}",
135 location.m_Function,
136 subgraphIndex,
137 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100138 }
139}
140
141#define CHECK_SUBGRAPH(MODEL, SUBGRAPH_INDEX) \
142 CheckSubgraph(MODEL, SUBGRAPH_INDEX, CHECK_LOCATION())
143
Kevin May7d96b162021-02-03 17:38:41 +0000144void CheckModel(const TfLiteParserImpl::ModelPtr & model,
telsoa01c577f2c2018-08-31 09:22:23 +0100145 size_t subgraphIndex,
146 size_t operatorIndex,
147 const CheckLocation & location)
148{
149 if (model.get() == nullptr)
150 {
151 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100152 fmt::format("{} was called with invalid (null) model. "
153 "Possible reason is that the model is not yet loaded and Unpack(ed). "
154 "subgraph:{} operator:{} at {}",
155 location.m_Function,
156 subgraphIndex,
157 operatorIndex,
158 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100159 }
160 else if (subgraphIndex >= model->subgraphs.size())
161 {
162 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100163 fmt::format("{} was called with an invalid subgraph index. "
164 "subgraph:{} operator:{} at {}",
165 location.m_Function,
166 subgraphIndex,
167 operatorIndex,
168 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100169 }
170 else if (operatorIndex >= model->subgraphs[subgraphIndex]->operators.size() &&
171 operatorIndex != VIRTUAL_OPERATOR_ID)
172 {
173 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100174 fmt::format("{} was called with an invalid operator index. "
175 "subgraph:{} operator:{} at {}",
176 location.m_Function,
177 subgraphIndex,
178 operatorIndex,
179 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100180 }
181}
182
183#define CHECK_MODEL(MODEL, SUBGRAPH_INDEX, OPERATOR_INDEX) \
184 CheckModel(MODEL, SUBGRAPH_INDEX, OPERATOR_INDEX, CHECK_LOCATION())
185
Kevin May7d96b162021-02-03 17:38:41 +0000186void CheckTensor(const TfLiteParserImpl::ModelPtr & model,
telsoa01c577f2c2018-08-31 09:22:23 +0100187 size_t subgraphIndex,
188 size_t tensorIndex,
189 const CheckLocation & location)
190{
191 // not checking model, because I assume CHECK_MODEL already run
192 // and checked that. An assert would do.
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100193 ARMNN_ASSERT_MSG(model.get() != nullptr, "Expecting a valid model in this function");
telsoa01c577f2c2018-08-31 09:22:23 +0100194
195 // also subgraph index should be checked by CHECK_MODEL so
196 // I only add an assert here
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100197 ARMNN_ASSERT_MSG(subgraphIndex < model->subgraphs.size(), "Expecting a valid subgraph index");
telsoa01c577f2c2018-08-31 09:22:23 +0100198
199 // the tensor index is the only one to check here
200 if (tensorIndex >= model->subgraphs[subgraphIndex]->tensors.size())
201 {
202 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100203 fmt::format("{} was called with an invalid tensor index. "
204 "subgraph:{} tensor:{} at {}",
205 location.m_Function,
206 subgraphIndex,
207 tensorIndex,
208 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100209 }
210}
211
212#define CHECK_TENSOR(MODEL, SUBGRAPH_INDEX, TENSOR_INDEX) \
213 CheckTensor(MODEL, SUBGRAPH_INDEX, TENSOR_INDEX, CHECK_LOCATION())
214
Kevin May7d96b162021-02-03 17:38:41 +0000215void CheckTensorPtr(TfLiteParserImpl::TensorRawPtr rawPtr,
telsoa01c577f2c2018-08-31 09:22:23 +0100216 const CheckLocation & location)
217{
218 if (rawPtr == nullptr)
219 {
220 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100221 fmt::format("{} was called with a null tensor pointer at {}", location.m_Function, location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100222 }
223}
224
225#define CHECK_TENSOR_PTR(TENSOR_PTR) \
226 CheckTensorPtr(TENSOR_PTR, CHECK_LOCATION())
227
Kevin May7d96b162021-02-03 17:38:41 +0000228void CheckBuffer(const TfLiteParserImpl::ModelPtr & model,
telsoa01c577f2c2018-08-31 09:22:23 +0100229 size_t bufferIndex,
230 const CheckLocation & location)
231{
232 if (model.get() == nullptr)
233 {
234 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100235 fmt::format("{} was called with invalid (null) model. "
236 "Possible reason is that the model is not yet loaded and Unpack(ed). "
237 "buffer:{} at {}",
238 location.m_Function,
239 bufferIndex,
240 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100241 }
242 else if (bufferIndex >= model->buffers.size())
243 {
244 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100245 fmt::format("{} was called with an invalid buffer index. "
246 "buffer index:{} at {}",
247 location.m_Function,
248 bufferIndex,
249 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100250 }
251 else if (model->buffers[bufferIndex].get() == nullptr)
252 {
253 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100254 fmt::format("The buffer #{} is null. {}",
255 bufferIndex,
256 location.AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100257 }
258}
259
260#define CHECK_BUFFER(MODEL, BUFFER_INDEX) \
261 CheckBuffer(MODEL, BUFFER_INDEX, CHECK_LOCATION())
262
Kevin May7d96b162021-02-03 17:38:41 +0000263void CheckBufferSize(TfLiteParserImpl::BufferRawPtr bufferPtr,
telsoa01c577f2c2018-08-31 09:22:23 +0100264 const armnn::TensorInfo & tensorInfo,
265 uint32_t bufferId,
266 const CheckLocation & location)
267{
268 if (bufferPtr == nullptr)
269 {
270 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100271 fmt::format("BufferPtr is null for buffer:{}. {}",
272 bufferId,
273 location.AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100274 }
275 else if(tensorInfo.GetNumElements() > bufferPtr->data.size() ||
276 tensorInfo.GetNumBytes() > bufferPtr->data.size())
277 {
278 std::stringstream ss;
279 ss << "Buffer #" << bufferId << " has " << bufferPtr->data.size() << " bytes. "
280 << "For tensor: " << tensorInfo.GetShape()
281 << " expecting: " << tensorInfo.GetNumBytes() << " bytes and "
282 << tensorInfo.GetNumElements() << " elements. " << location.AsString();
283 throw ParseException(ss.str());
284 }
285}
286
287#define CHECK_BUFFER_SIZE(BUFFER_PTR, TENSOR_INFO, BUFFER_ID) \
288 CheckBufferSize(BUFFER_PTR, TENSOR_INFO, BUFFER_ID, CHECK_LOCATION())
289
290bool IsActivationSupported(tflite::ActivationFunctionType activationType)
291{
292 switch(activationType)
293 {
294 case tflite::ActivationFunctionType_NONE:
295 case tflite::ActivationFunctionType_RELU:
296 case tflite::ActivationFunctionType_RELU6:
297 case tflite::ActivationFunctionType_TANH:
298 {
299 return true;
300 }
301 default:
302 {
303 return false;
304 }
305 }
306}
307
308#define CHECK_SUPPORTED_FUSED_ACTIVATION(OPTION, SUBGRAPH_INDEX, OPERATOR_INDEX) \
309 do { \
310 if (IsActivationSupported(OPTION->fused_activation_function) == false) \
311 { \
312 throw ParseException( \
James Ward58dec6b2020-09-11 17:32:44 +0100313 fmt::format("TfLite parser doesn't suppport fused activation: " \
314 "{}/{} in {} subgraph:{} operator:{} at {}", \
315 OPTION->fused_activation_function, \
316 tflite::EnumNameActivationFunctionType(\
317 OPTION->fused_activation_function), \
318 __func__, \
319 SUBGRAPH_INDEX, \
320 OPERATOR_INDEX, \
321 CHECK_LOCATION().FileLine())); \
telsoa01c577f2c2018-08-31 09:22:23 +0100322 } \
323 } while(false)
324
325
326std::vector<unsigned int> AsUnsignedVector(const std::vector<int32_t> & in)
327{
328 std::vector<unsigned int> result;
329 result.reserve(in.size());
330 for (auto & i : in)
331 {
332 result.push_back(CHECKED_NON_NEGATIVE(i));
333 }
334 return result;
335}
336
337void CalcPadding(uint32_t inputSize,
338 uint32_t filterSize,
339 uint32_t stride,
Pablo Tellof0bd6832019-04-26 17:58:13 +0100340 uint32_t dilation,
telsoa01c577f2c2018-08-31 09:22:23 +0100341 uint32_t& paddingFront,
342 uint32_t& paddingBack,
343 tflite::Padding padding)
344{
345 paddingFront = 0;
346 paddingBack = 0;
347 if (padding == tflite::Padding_SAME)
348 {
349 uint32_t outputSize = (inputSize + stride - 1) / stride;
Pablo Tellof0bd6832019-04-26 17:58:13 +0100350 uint32_t dilatedSize = filterSize + (dilation - 1) * (filterSize - 1);
351 uint32_t temp = (outputSize - 1) * stride + dilatedSize;
telsoa01c577f2c2018-08-31 09:22:23 +0100352 if (temp > inputSize)
353 {
354 paddingFront = (temp - inputSize) / 2;
355 paddingBack = (temp - inputSize) - paddingFront;
356 }
357 }
358}
359
Kevin May7d96b162021-02-03 17:38:41 +0000360armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr,
Sadik Armagand109a4d2020-07-28 10:42:13 +0100361 const std::vector<unsigned int>& shapes,
362 const armnn::PermutationVector& dimensionMappings = {0, 1, 2, 3},
363 const bool outputTensor = false)
telsoa01c577f2c2018-08-31 09:22:23 +0100364{
365 armnn::DataType type;
366 CHECK_TENSOR_PTR(tensorPtr);
367
368 switch (tensorPtr->type)
369 {
370 case tflite::TensorType_UINT8:
Derek Lambertif90c56d2020-01-10 17:14:08 +0000371 type = armnn::DataType::QAsymmU8;
telsoa01c577f2c2018-08-31 09:22:23 +0100372 break;
373 case tflite::TensorType_FLOAT32:
374 type = armnn::DataType::Float32;
375 break;
Finn Williamsed66d142019-12-06 09:55:55 +0000376 case tflite::TensorType_INT8:
Keith Davis67e6c542020-02-19 10:08:33 +0000377 if (tensorPtr->quantization->zero_point.size() == 1)
Ryan OShea03181ff2020-02-07 17:22:22 +0000378 {
Keith Davis0c2eeac2020-02-11 16:51:50 +0000379 // Per-tensor
Ryan OShea03181ff2020-02-07 17:22:22 +0000380 type = armnn::DataType::QAsymmS8;
381 }
382 else
383 {
Keith Davis0c2eeac2020-02-11 16:51:50 +0000384 // Per-channel
Ryan OShea03181ff2020-02-07 17:22:22 +0000385 type = armnn::DataType::QSymmS8;
386 }
Finn Williamsed66d142019-12-06 09:55:55 +0000387 break;
388 case tflite::TensorType_INT16:
Derek Lambertif90c56d2020-01-10 17:14:08 +0000389 type = armnn::DataType::QSymmS16;
Finn Williamsed66d142019-12-06 09:55:55 +0000390 break;
telsoa01c577f2c2018-08-31 09:22:23 +0100391 case tflite::TensorType_INT32:
392 type = armnn::DataType::Signed32;
393 break;
Inki Daed4619e22020-09-10 15:33:54 +0900394 case tflite::TensorType_INT64:
395 type = armnn::DataType::Signed64;
396 break;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100397 case tflite::TensorType_BOOL:
398 type = armnn::DataType::Boolean;
399 break;
telsoa01c577f2c2018-08-31 09:22:23 +0100400 default:
401 {
402 CheckLocation location = CHECK_LOCATION();
403 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100404 fmt::format("Unsupported data type {} = {} for tensor: {}. {}",
405 tensorPtr->type,
406 tflite::EnumNameTensorType(tensorPtr->type),
407 tensorPtr->name,
408 location.AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100409 }
410 }
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100411 std::vector<unsigned int> safeShape = shapes;
Sadik Armagand109a4d2020-07-28 10:42:13 +0100412 bool isDynamic = false;
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100413 if (safeShape.size() == 0)
414 {
415 safeShape.push_back(1);
Sadik Armagand109a4d2020-07-28 10:42:13 +0100416 if (outputTensor)
417 {
418 isDynamic = true;
419 }
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100420 }
421
Keith Davisd305e1a2020-01-22 11:57:54 +0000422 float quantizationScale = 0.0f;
423 int32_t quantizationOffset = 0;
424
425 if (tensorPtr->quantization.get())
426 {
427 if (tensorPtr->quantization->scale.size() <= 1)
428 {
429 CHECK_VALID_SIZE(tensorPtr->quantization->zero_point.size(), 0, 1);
430 CHECK_VALID_SIZE(tensorPtr->quantization->zero_point.size(), 0, 1);
431
432 if (tensorPtr->quantization->scale.size() == 1)
433 {
434 quantizationScale = tensorPtr->quantization->scale[0];
435 }
436 if (tensorPtr->quantization->zero_point.size() == 1)
437 {
438 // NOTE: we lose precision here when converting from 64 bit to 32
Ryan OShea03181ff2020-02-07 17:22:22 +0000439 // but this is what we support at the moment in ArmNN
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100440 quantizationOffset = armnn::numeric_cast<int32_t>(tensorPtr->quantization->zero_point[0]);
Keith Davisd305e1a2020-01-22 11:57:54 +0000441 }
442
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100443 TensorShape tensorShape(armnn::numeric_cast<unsigned int>(safeShape.size()),
Sadik Armagand109a4d2020-07-28 10:42:13 +0100444 safeShape.data());
445 if (isDynamic)
446 {
447 tensorShape = TensorShape(1, false);
448 }
449 armnn::TensorInfo result(tensorShape,
450 type,
451 quantizationScale,
452 quantizationOffset);
Keith Davisd305e1a2020-01-22 11:57:54 +0000453 return result;
454 }
455 else
456 {
457 std::vector<float> quantizationScales;
458 std::vector<int32_t> quantizationOffsets;
459
460 // Scale
461 std::copy(tensorPtr->quantization->scale.begin(),
462 tensorPtr->quantization->scale.end(),
463 std::back_inserter(quantizationScales));
464
Keith Davis0c2eeac2020-02-11 16:51:50 +0000465 // QSymmS8 Per-axis
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100466 TensorShape tensorShape(armnn::numeric_cast<unsigned int>(safeShape.size()),
Sadik Armagand109a4d2020-07-28 10:42:13 +0100467 safeShape.data());
468 if (isDynamic)
469 {
470 tensorShape = TensorShape(1, false);
471 }
472 armnn::TensorInfo result(tensorShape,
473 type,
474 quantizationScales,
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100475 dimensionMappings[armnn::numeric_cast<unsigned int>(
Sadik Armagand109a4d2020-07-28 10:42:13 +0100476 tensorPtr->quantization->quantized_dimension)]);
Keith Davisd305e1a2020-01-22 11:57:54 +0000477 return result;
478 }
479 }
480 else
481 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100482 TensorShape tensorShape(armnn::numeric_cast<unsigned int>(safeShape.size()),
Sadik Armagand109a4d2020-07-28 10:42:13 +0100483 safeShape.data());
484 if (isDynamic)
485 {
486 tensorShape = TensorShape(1, false);
487 }
488 armnn::TensorInfo result(tensorShape,
Keith Davisd305e1a2020-01-22 11:57:54 +0000489 type,
490 quantizationScale,
491 quantizationOffset);
492 return result;
493 }
telsoa01c577f2c2018-08-31 09:22:23 +0100494}
495
Kevin May7d96b162021-02-03 17:38:41 +0000496armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr,
Keith Davis0c2eeac2020-02-11 16:51:50 +0000497 const armnn::PermutationVector& dimensionMappings = {0, 1, 2, 3})
Narumol Prangnawarat4628d052019-02-25 17:26:05 +0000498{
499 auto const & dimensions = AsUnsignedVector(tensorPtr->shape);
Keith Davis0c2eeac2020-02-11 16:51:50 +0000500 return ToTensorInfo(tensorPtr, dimensions, dimensionMappings);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +0000501}
502
Kevin May7d96b162021-02-03 17:38:41 +0000503armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr,
Sadik Armagand109a4d2020-07-28 10:42:13 +0100504 const bool outputTensor)
505{
506 auto const & dimensions = AsUnsignedVector(tensorPtr->shape);
507 const armnn::PermutationVector& dimensionMappings = {0, 1, 2, 3};
508 return ToTensorInfo(tensorPtr, dimensions, dimensionMappings, outputTensor);
509}
510
telsoa01c577f2c2018-08-31 09:22:23 +0100511template<typename T>
512std::pair<armnn::ConstTensor, std::unique_ptr<T[]>>
Kevin May7d96b162021-02-03 17:38:41 +0000513CreateConstTensorImpl(TfLiteParserImpl::BufferRawPtr bufferPtr,
514 TfLiteParserImpl::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +0000515 armnn::TensorInfo& tensorInfo,
516 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +0100517{
Jan Eilers8eb25602020-03-09 12:13:48 +0000518 IgnoreUnused(tensorPtr);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100519 ARMNN_ASSERT_MSG(tensorPtr != nullptr, "tensorPtr is null");
520 ARMNN_ASSERT_MSG(bufferPtr != nullptr,
James Ward58dec6b2020-09-11 17:32:44 +0100521 fmt::format("Buffer for buffer:{} is null", tensorPtr->buffer).c_str());
telsoa01c577f2c2018-08-31 09:22:23 +0100522
523 std::unique_ptr<T[]> data(new T[tensorInfo.GetNumElements()]);
Matteo Martincigh747ef822018-12-18 09:26:39 +0000524
525 if (permutationVector.has_value() && permutationVector.value().GetSize() > 0)
526 {
527 tensorInfo = armnnUtils::Permuted(tensorInfo, permutationVector.value());
Matteo Martincighd5b9e642019-01-04 18:01:21 +0000528 armnnUtils::Permute(tensorInfo.GetShape(), permutationVector.value(),
529 reinterpret_cast<const T*>(bufferPtr->data.data()), data.get(), sizeof(T));
Matteo Martincigh747ef822018-12-18 09:26:39 +0000530 }
531 else
532 {
533 ::memcpy(data.get(), bufferPtr->data.data(), tensorInfo.GetNumBytes());
534 }
535
telsoa01c577f2c2018-08-31 09:22:23 +0100536 return std::make_pair(ConstTensor(tensorInfo, data.get()), std::move(data));
537}
538
telsoa01c577f2c2018-08-31 09:22:23 +0100539armnn::LayerBindingId GenerateLayerBindingId(size_t subgraphIndex, size_t tensorIndex)
540{
541 // generate the binding id by shifting the tensor id by 8 bit
542 // and add the subgraph id, which allows 256 subgraphs
543 return static_cast<armnn::LayerBindingId>((tensorIndex<<8)+subgraphIndex);
544}
545
Aron Virginas-Tar70672f62019-01-23 14:00:00 +0000546bool CheckShape(const armnn::TensorShape& actual, const std::vector<int32_t>& expected)
547{
548 const unsigned int actualSize = actual.GetNumDimensions();
549 if (actualSize != expected.size())
550 {
551 return false;
552 }
553
554 for (unsigned int i = 0u; i < actualSize; i++)
555 {
556 if (expected[i] < 0 ||
557 actual[i] != static_cast<unsigned int>(expected[i]))
558 {
559 return false;
560 }
561 }
562
563 return true;
564}
565
James Conroy05102392020-06-24 15:39:55 +0100566void CheckMatchingQuantization(const TensorInfo& first,
567 const TensorInfo& second,
568 const std::string& descName,
569 std::string const& firstName,
570 std::string const& secondName)
571{
572 if (!first.IsQuantized() ||
573 !second.IsQuantized())
574 {
575 // Not a quantized type, ignore the validation
576 return;
577 }
578
579 DataType firstDataType = first.GetDataType();
580 DataType secondDataType = second.GetDataType();
581
582 if (firstDataType != secondDataType)
583 {
584 throw InvalidArgumentException(descName + ": " + firstName + " and " + secondName +
585 " must be of the same quantized type, " +
586 firstName + " is " + GetDataTypeName(firstDataType) + ", " +
587 secondName + " is " + GetDataTypeName(secondDataType));
588 }
589
590 if (!first.IsTypeSpaceMatch(second))
591 {
592 throw InvalidArgumentException(descName + ": " + firstName + " and " + secondName +
593 " must have the same quantization space, " +
594 firstName + " has offset " + std::to_string(first.GetQuantizationOffset()) +
595 " and scale " + std::to_string(first.GetQuantizationScale()) + ", " +
596 secondName + " has offset " + std::to_string(second.GetQuantizationOffset()) +
597 " and scale " + std::to_string(second.GetQuantizationScale()));
598 }
599}
600
telsoa01c577f2c2018-08-31 09:22:23 +0100601} // <anonymous>
602
Kevin May7d96b162021-02-03 17:38:41 +0000603TfLiteParserImpl::TfLiteParserImpl(const Optional<ITfLiteParser::TfLiteParserOptions>& options)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100604: m_Options(options)
605, m_Network(nullptr, nullptr)
Kevin May7d96b162021-02-03 17:38:41 +0000606, m_ParserFunctions(tflite::BuiltinOperator_MAX+1, &TfLiteParserImpl::ParseUnsupportedOperator)
telsoa01c577f2c2018-08-31 09:22:23 +0100607{
608 // register supported operators
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100609 m_ParserFunctions[tflite::BuiltinOperator_ABS] = &TfLiteParserImpl::ParseAbs;
Kevin May7d96b162021-02-03 17:38:41 +0000610 m_ParserFunctions[tflite::BuiltinOperator_ADD] = &TfLiteParserImpl::ParseAdd;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100611 m_ParserFunctions[tflite::BuiltinOperator_ARG_MIN] = &TfLiteParserImpl::ParseArgMin;
612 m_ParserFunctions[tflite::BuiltinOperator_ARG_MAX] = &TfLiteParserImpl::ParseArgMax;
Kevin May7d96b162021-02-03 17:38:41 +0000613 m_ParserFunctions[tflite::BuiltinOperator_AVERAGE_POOL_2D] = &TfLiteParserImpl::ParseAveragePool2D;
614 m_ParserFunctions[tflite::BuiltinOperator_BATCH_TO_SPACE_ND] = &TfLiteParserImpl::ParseBatchToSpaceND;
mathad01b392e982021-04-07 12:07:30 +0100615 m_ParserFunctions[tflite::BuiltinOperator_CAST] = &TfLiteParserImpl::ParseCast;
Kevin May7d96b162021-02-03 17:38:41 +0000616 m_ParserFunctions[tflite::BuiltinOperator_CONCATENATION] = &TfLiteParserImpl::ParseConcatenation;
617 m_ParserFunctions[tflite::BuiltinOperator_CONV_2D] = &TfLiteParserImpl::ParseConv2D;
618 m_ParserFunctions[tflite::BuiltinOperator_CUSTOM] = &TfLiteParserImpl::ParseCustomOperator;
619 m_ParserFunctions[tflite::BuiltinOperator_DEPTH_TO_SPACE] = &TfLiteParserImpl::ParseDepthToSpace;
620 m_ParserFunctions[tflite::BuiltinOperator_DEPTHWISE_CONV_2D] = &TfLiteParserImpl::ParseDepthwiseConv2D;
621 m_ParserFunctions[tflite::BuiltinOperator_DEQUANTIZE] = &TfLiteParserImpl::ParseDequantize;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100622 m_ParserFunctions[tflite::BuiltinOperator_DIV] = &TfLiteParserImpl::ParseDiv;
Kevin May7d96b162021-02-03 17:38:41 +0000623 m_ParserFunctions[tflite::BuiltinOperator_ELU] = &TfLiteParserImpl::ParseElu;
624 m_ParserFunctions[tflite::BuiltinOperator_EXP] = &TfLiteParserImpl::ParseExp;
625 m_ParserFunctions[tflite::BuiltinOperator_FULLY_CONNECTED] = &TfLiteParserImpl::ParseFullyConnected;
626 m_ParserFunctions[tflite::BuiltinOperator_GATHER] = &TfLiteParserImpl::ParseGather;
627 m_ParserFunctions[tflite::BuiltinOperator_HARD_SWISH] = &TfLiteParserImpl::ParseHardSwish;
628 m_ParserFunctions[tflite::BuiltinOperator_LEAKY_RELU] = &TfLiteParserImpl::ParseLeakyRelu;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100629 m_ParserFunctions[tflite::BuiltinOperator_LOGICAL_NOT] = &TfLiteParserImpl::ParseLogicalNot;
Kevin May7d96b162021-02-03 17:38:41 +0000630 m_ParserFunctions[tflite::BuiltinOperator_LOGISTIC] = &TfLiteParserImpl::ParseLogistic;
631 m_ParserFunctions[tflite::BuiltinOperator_L2_NORMALIZATION] = &TfLiteParserImpl::ParseL2Normalization;
632 m_ParserFunctions[tflite::BuiltinOperator_MAX_POOL_2D] = &TfLiteParserImpl::ParseMaxPool2D;
633 m_ParserFunctions[tflite::BuiltinOperator_MAXIMUM] = &TfLiteParserImpl::ParseMaximum;
634 m_ParserFunctions[tflite::BuiltinOperator_MEAN] = &TfLiteParserImpl::ParseMean;
635 m_ParserFunctions[tflite::BuiltinOperator_MINIMUM] = &TfLiteParserImpl::ParseMinimum;
636 m_ParserFunctions[tflite::BuiltinOperator_MUL] = &TfLiteParserImpl::ParseMul;
637 m_ParserFunctions[tflite::BuiltinOperator_NEG] = &TfLiteParserImpl::ParseNeg;
638 m_ParserFunctions[tflite::BuiltinOperator_PACK] = &TfLiteParserImpl::ParsePack;
639 m_ParserFunctions[tflite::BuiltinOperator_PAD] = &TfLiteParserImpl::ParsePad;
640 m_ParserFunctions[tflite::BuiltinOperator_QUANTIZE] = &TfLiteParserImpl::ParseQuantize;
641 m_ParserFunctions[tflite::BuiltinOperator_RELU] = &TfLiteParserImpl::ParseRelu;
642 m_ParserFunctions[tflite::BuiltinOperator_RELU6] = &TfLiteParserImpl::ParseRelu6;
Sadik Armagana2747482021-02-09 10:28:54 +0000643 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MAX] = &TfLiteParserImpl::ParseReduceMax;
644 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MIN] = &TfLiteParserImpl::ParseReduceMin;
Kevin May7d96b162021-02-03 17:38:41 +0000645 m_ParserFunctions[tflite::BuiltinOperator_RESHAPE] = &TfLiteParserImpl::ParseReshape;
646 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_BILINEAR] = &TfLiteParserImpl::ParseResizeBilinear;
647 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_NEAREST_NEIGHBOR] = &TfLiteParserImpl::ParseResizeNearestNeighbor;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100648 m_ParserFunctions[tflite::BuiltinOperator_RSQRT] = &TfLiteParserImpl::ParseRsqrt;
Kevin May7d96b162021-02-03 17:38:41 +0000649 m_ParserFunctions[tflite::BuiltinOperator_SLICE] = &TfLiteParserImpl::ParseSlice;
650 m_ParserFunctions[tflite::BuiltinOperator_SOFTMAX] = &TfLiteParserImpl::ParseSoftmax;
651 m_ParserFunctions[tflite::BuiltinOperator_SPACE_TO_BATCH_ND] = &TfLiteParserImpl::ParseSpaceToBatchND;
652 m_ParserFunctions[tflite::BuiltinOperator_SPLIT] = &TfLiteParserImpl::ParseSplit;
653 m_ParserFunctions[tflite::BuiltinOperator_SPLIT_V] = &TfLiteParserImpl::ParseSplitV;
654 m_ParserFunctions[tflite::BuiltinOperator_SQUEEZE] = &TfLiteParserImpl::ParseSqueeze;
655 m_ParserFunctions[tflite::BuiltinOperator_STRIDED_SLICE] = &TfLiteParserImpl::ParseStridedSlice;
656 m_ParserFunctions[tflite::BuiltinOperator_SUB] = &TfLiteParserImpl::ParseSub;
657 m_ParserFunctions[tflite::BuiltinOperator_SUM] = &TfLiteParserImpl::ParseSum;
658 m_ParserFunctions[tflite::BuiltinOperator_TANH] = &TfLiteParserImpl::ParseTanH;
659 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE] = &TfLiteParserImpl::ParseTranspose;
660 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE_CONV] = &TfLiteParserImpl::ParseTransposeConv;
661 m_ParserFunctions[tflite::BuiltinOperator_UNPACK] = &TfLiteParserImpl::ParseUnpack;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100662
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100663 // register supported custom operators
Kevin May7d96b162021-02-03 17:38:41 +0000664 m_CustomParserFunctions["TFLite_Detection_PostProcess"] = &TfLiteParserImpl::ParseDetectionPostProcess;
telsoa01c577f2c2018-08-31 09:22:23 +0100665}
666
Kevin May7d96b162021-02-03 17:38:41 +0000667void TfLiteParserImpl::ResetParser()
telsoa01c577f2c2018-08-31 09:22:23 +0100668{
669 m_Network = armnn::INetworkPtr(nullptr, nullptr);
670 m_Model = nullptr;
671 m_SubgraphConnections.clear();
672}
673
Kevin May7d96b162021-02-03 17:38:41 +0000674INetworkPtr TfLiteParserImpl::CreateNetworkFromBinaryFile(const char* graphFile)
telsoa01c577f2c2018-08-31 09:22:23 +0100675{
676 ResetParser();
677 m_Model = LoadModelFromFile(graphFile);
678 return CreateNetworkFromModel();
679}
680
Kevin May7d96b162021-02-03 17:38:41 +0000681INetworkPtr TfLiteParserImpl::CreateNetworkFromBinary(const std::vector<uint8_t> & binaryContent)
telsoa01c577f2c2018-08-31 09:22:23 +0100682{
683 ResetParser();
684 m_Model = LoadModelFromBinary(binaryContent.data(), binaryContent.size());
685 return CreateNetworkFromModel();
686}
687
Kevin May7d96b162021-02-03 17:38:41 +0000688INetworkPtr TfLiteParserImpl::CreateNetworkFromModel()
telsoa01c577f2c2018-08-31 09:22:23 +0100689{
Sadik Armagand109a4d2020-07-28 10:42:13 +0100690
691 using NetworkOptions = std::vector<BackendOptions>;
692 NetworkOptions networkOptions = {};
693 if (m_Options && m_Options.value().m_InferAndValidate)
694 {
695 BackendOptions shapeInferenceMethodOption("ShapeInferenceMethod",
696 {
697 { "InferAndValidate", true }
698 });
699
700 networkOptions.push_back(shapeInferenceMethodOption);
701 }
702
703 m_Network = INetwork::Create(networkOptions);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100704 ARMNN_ASSERT(m_Model.get() != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +0100705
telsoa01c577f2c2018-08-31 09:22:23 +0100706 if (m_Model->subgraphs.size() != 1)
707 {
708 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100709 fmt::format("Current TfLite parser only supports 1 subgraph. Current one has: {} {}",
710 m_Model->subgraphs.size(),
711 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100712 }
713
714 size_t subgraphIndex = 0;
Colm Donelan6350d272020-06-09 16:56:25 +0100715 size_t operatorIndex = 0;
716 try
telsoa01c577f2c2018-08-31 09:22:23 +0100717 {
Colm Donelan6350d272020-06-09 16:56:25 +0100718 for (SubgraphPtr const& subgraph : m_Model->subgraphs)
telsoa01c577f2c2018-08-31 09:22:23 +0100719 {
Colm Donelan6350d272020-06-09 16:56:25 +0100720 m_SubgraphConnections.emplace_back(subgraph->tensors.size());
721 for (OperatorPtr const& op : subgraph->operators)
telsoa01c577f2c2018-08-31 09:22:23 +0100722 {
Colm Donelan6350d272020-06-09 16:56:25 +0100723 auto const& opCodePtr = m_Model->operator_codes[op->opcode_index];
telsoa01c577f2c2018-08-31 09:22:23 +0100724 auto builtinCode = opCodePtr->builtin_code;
725
726 if (builtinCode > tflite::BuiltinOperator_MAX)
727 {
James Ward58dec6b2020-09-11 17:32:44 +0100728 throw ParseException(fmt::format("Operator code {} is out of range 0-{}. "
729 "subgraph:{} operator idx:{}. {}",
730 builtinCode, tflite::BuiltinOperator_MAX, subgraphIndex,
731 operatorIndex, CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100732 }
733
734 // lookup and call the parser function
Colm Donelan6350d272020-06-09 16:56:25 +0100735 auto& parserFunction = m_ParserFunctions[builtinCode];
telsoa01c577f2c2018-08-31 09:22:23 +0100736 (this->*parserFunction)(subgraphIndex, operatorIndex);
Colm Donelan6350d272020-06-09 16:56:25 +0100737 ++operatorIndex;
telsoa01c577f2c2018-08-31 09:22:23 +0100738 }
telsoa01c577f2c2018-08-31 09:22:23 +0100739
Colm Donelan6350d272020-06-09 16:56:25 +0100740 SetupInputLayers(subgraphIndex);
741 SetupOutputLayers(subgraphIndex);
742 SetupConstantLayers(subgraphIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100743
Colm Donelan6350d272020-06-09 16:56:25 +0100744 ++subgraphIndex;
745 operatorIndex = 0;
telsoa01c577f2c2018-08-31 09:22:23 +0100746 }
telsoa01c577f2c2018-08-31 09:22:23 +0100747 }
Colm Donelan6350d272020-06-09 16:56:25 +0100748 catch (const ParseException& e)
telsoa01c577f2c2018-08-31 09:22:23 +0100749 {
Colm Donelan6350d272020-06-09 16:56:25 +0100750 std::stringstream errorString;
751 errorString << "Failed to parse operator #" << operatorIndex << " within subgraph #"
752 << subgraphIndex << " error: " << e.what();
753 ARMNN_LOG(error) << errorString.str();
754 std::stringstream errors;
755 errors << errorString.str() << "\n";
telsoa01c577f2c2018-08-31 09:22:23 +0100756 throw ParseException(errors.str());
757 }
758
759 // establish the connections from the layer outputs to the inputs of the subsequent layers
Colm Donelan6350d272020-06-09 16:56:25 +0100760 for (subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100761 {
762 for (size_t tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
763 {
764 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot != nullptr)
765 {
766 for (size_t inputSlotIdx = 0;
767 inputSlotIdx < m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size();
768 ++inputSlotIdx)
769 {
770 m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot->Connect(
771 *(m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots[inputSlotIdx]));
772 }
773 }
774 }
775 }
776
777 return std::move(m_Network);
778}
779
Kevin May7d96b162021-02-03 17:38:41 +0000780void TfLiteParserImpl::RegisterProducerOfTensor(size_t subgraphIndex,
781 size_t tensorIndex,
782 armnn::IOutputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +0100783{
784 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100785 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
786 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100787
788 TensorSlots & tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
789
790 // assuming there is only one producer for that tensor
791 if (tensorSlots.outputSlot != nullptr)
792 {
James Ward58dec6b2020-09-11 17:32:44 +0100793 throw ParseException(fmt::format("Another layer has already registered itself as the producer of "
794 "subgraph:{} tensor:{} {}",
795 subgraphIndex,
796 tensorIndex,
797 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100798 }
799
800 tensorSlots.outputSlot = slot;
801}
802
Kevin May7d96b162021-02-03 17:38:41 +0000803void TfLiteParserImpl::RegisterConsumerOfTensor(size_t subgraphIndex,
804 size_t tensorIndex,
805 armnn::IInputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +0100806{
807 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100808 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
809 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100810
Finn Williamsd4fa5452021-03-01 12:31:41 +0000811 TensorSlots& tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +0100812 tensorSlots.inputSlots.push_back(slot);
813}
814
Kevin May7d96b162021-02-03 17:38:41 +0000815void TfLiteParserImpl::ParseCustomOperator(size_t subgraphIndex, size_t operatorIndex)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100816{
817 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
818
819 // NOTE: By default we presume the custom operator is not supported
Kevin May7d96b162021-02-03 17:38:41 +0000820 auto customParserFunction = &TfLiteParserImpl::ParseUnsupportedOperator;
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100821
822 // Identify custom code defined for custom operator
823 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
824 const auto& customCode = m_Model->operator_codes[operatorPtr->opcode_index]->custom_code;
825
826 // Find parser function that correspondes to custom code (if any)
827 auto iterator = m_CustomParserFunctions.find(customCode);
828 if (iterator != m_CustomParserFunctions.end())
829 {
830 customParserFunction = iterator->second;
831 }
832
833 // Run parser function
834 (this->*customParserFunction)(subgraphIndex, operatorIndex);
835}
836
Kevin May7d96b162021-02-03 17:38:41 +0000837void TfLiteParserImpl::ParseUnsupportedOperator(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100838{
839 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100840
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100841 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
842
843 auto opcodeIndex = operatorPtr->opcode_index;
844 auto opcode = m_Model->operator_codes[opcodeIndex]->builtin_code;
845
846 if (!m_Options || !m_Options.value().m_StandInLayerForUnsupported)
847 {
848 // Do not add StandInLayer, throw ParseException instead
849 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100850 fmt::format("Operator not supported. "
851 "subgraph:{} operator:{} "
852 "opcode_index:{} opcode:{} / {} {}",
853 subgraphIndex,
854 operatorIndex,
855 opcodeIndex,
856 opcode,
857 tflite::EnumNameBuiltinOperator(opcode),
858 CHECK_LOCATION().AsString()));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100859 }
860
861 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
862 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
863
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100864 const unsigned int numInputs = armnn::numeric_cast<unsigned int>(inputs.size());
865 const unsigned int numOutputs = armnn::numeric_cast<unsigned int>(outputs.size());
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100866
867 StandInDescriptor descriptor(numInputs, numOutputs);
James Ward58dec6b2020-09-11 17:32:44 +0100868 auto layerName = fmt::format("StandIn:{}:{}:{}", subgraphIndex, operatorIndex, opcode);
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100869
870 // Add a non-executable StandInLayer as a placeholder for any unsupported operator
871 IConnectableLayer* layer = m_Network->AddStandInLayer(descriptor, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +0100872 ARMNN_ASSERT(layer != nullptr);
873
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100874 for (unsigned int i = 0u; i < numOutputs; ++i)
875 {
Sadik Armagand109a4d2020-07-28 10:42:13 +0100876 layer->GetOutputSlot(i).SetTensorInfo(ToTensorInfo(outputs[i], true));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100877 }
878
879 auto inputTensorIds = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
880 auto outputTensorIds = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
881
882 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIds);
883 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIds);
telsoa01c577f2c2018-08-31 09:22:23 +0100884}
885
mathad01b392e982021-04-07 12:07:30 +0100886void TfLiteParserImpl::ParseCast(size_t subgraphIndex, size_t operatorIndex)
887{
888 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
889
890 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
891 CHECK_VALID_SIZE(inputs.size(), 1);
892 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
893 CHECK_VALID_SIZE(outputs.size(), 1);
894
895 auto layerName = fmt::format("Cast:{}:{}", subgraphIndex, operatorIndex);
896
897 IConnectableLayer* layer = m_Network->AddCastLayer(layerName.c_str());
898 ARMNN_ASSERT(layer != nullptr);
899
900 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
901 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
902
903 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
904 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
905
906 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
907 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
908}
909
Kevin May7d96b162021-02-03 17:38:41 +0000910void TfLiteParserImpl::ParseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100911{
912 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
913
914 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
915 const auto * options = operatorPtr->builtin_options.AsConv2DOptions();
916
917 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
918
919 Convolution2dDescriptor desc;
920 desc.m_BiasEnabled = false;
921 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
922 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +0000923 desc.m_DataLayout = armnn::DataLayout::NHWC;
Pablo Tellof0bd6832019-04-26 17:58:13 +0100924 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
925 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +0000926
telsoa01c577f2c2018-08-31 09:22:23 +0100927 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
928 CHECK_VALID_SIZE(inputs.size(), 2, 3);
929
930 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
931 CHECK_VALID_SIZE(outputs.size(), 1);
932
933 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
934 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
935
936 // assuming input is NHWC
937 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
938 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
939
940 // assuming the filter is OHWI : Output, H, W, Input
941 // which is essentially the same as NHWC
942 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
943 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
944
Pablo Tellof0bd6832019-04-26 17:58:13 +0100945 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
946 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
947 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
948 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +0100949
Finn Williamsd4fa5452021-03-01 12:31:41 +0000950 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo);
Matthew Jackson74bf7da2019-08-16 16:51:42 +0100951 armnn::IConnectableLayer* layer = nullptr;
telsoa01c577f2c2018-08-31 09:22:23 +0100952
James Ward58dec6b2020-09-11 17:32:44 +0100953 auto layerName = fmt::format("Conv2D:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100954
955 if (inputs.size() == 3)
956 {
957 desc.m_BiasEnabled = true;
958 armnn::TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +0000959 auto biasTensorAndData = CreateConstTensorNonPermuted(inputs[2], biasTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +0100960 layer = m_Network->AddConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +0000961 filterTensorAndData,
962 Optional<ConstTensor>(biasTensorAndData),
telsoa01c577f2c2018-08-31 09:22:23 +0100963 layerName.c_str());
964 }
965 else
966 {
967 layer = m_Network->AddConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +0000968 filterTensorAndData,
Matteo Martincighfc598e12019-05-14 10:36:13 +0100969 EmptyOptional(),
telsoa01c577f2c2018-08-31 09:22:23 +0100970 layerName.c_str());
971 }
972
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100973 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +0100974
Sadik Armagand109a4d2020-07-28 10:42:13 +0100975 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
jimfly01c25411c2018-11-14 17:47:22 +0000976 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +0100977
978 // register the input connection slots for the layer, connections are made after all layers have been created
979 // only the tensors for the inputs are relevant, exclude the const tensors
980 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +0000981 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
telsoa01c577f2c2018-08-31 09:22:23 +0100982
jimfly01c25411c2018-11-14 17:47:22 +0000983 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +0100984 // register the output connection slots for the layer, connections are made after all layers have been created
985 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
986 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
987}
988
Kevin May7d96b162021-02-03 17:38:41 +0000989void TfLiteParserImpl::ParseDepthwiseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100990{
991 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
992
993 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
994 const auto * options = operatorPtr->builtin_options.AsDepthwiseConv2DOptions();
995
996 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
997
998 DepthwiseConvolution2dDescriptor desc;
999 desc.m_BiasEnabled = false;
1000 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1001 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +00001002 desc.m_DataLayout = armnn::DataLayout::NHWC;
Matthew Jacksond6a9dee2019-07-22 13:53:24 +01001003 CHECKED_NON_NEGATIVE(options->depth_multiplier);
telsoa01c577f2c2018-08-31 09:22:23 +01001004
1005 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1006 CHECK_VALID_SIZE(inputs.size(), 2, 3);
1007 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1008 CHECK_VALID_SIZE(outputs.size(), 1);
Pablo Tellof0bd6832019-04-26 17:58:13 +01001009 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1010 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +00001011
Keith Davis0c2eeac2020-02-11 16:51:50 +00001012 // Mappings from TensorflowLite filter tensors to the ArmNN filter tensors (ArmNN weights have to be [M, I, H, W])
1013 PermutationVector permutationVector{ 2, 3, 1, 0 }; // [H, W, I, M] -> [M, I, H, W]
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001014
telsoa01c577f2c2018-08-31 09:22:23 +01001015 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Keith Davis0c2eeac2020-02-11 16:51:50 +00001016 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1], permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01001017
Matteo Martincigh747ef822018-12-18 09:26:39 +00001018 // Assuming input is NHWC
telsoa01c577f2c2018-08-31 09:22:23 +01001019 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1020 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
Matteo Martincigh747ef822018-12-18 09:26:39 +00001021
1022 // TensorflowLite weights come in the format [1, H, W, I * M]
telsoa01c577f2c2018-08-31 09:22:23 +01001023 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1024 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1025
Matteo Martincigh747ef822018-12-18 09:26:39 +00001026 // Reshape weights as [ H, W, I, M ]
1027 filterTensorInfo.SetShape({ filterHeight,
1028 filterWidth,
1029 inputTensorInfo.GetShape()[3],
1030 filterTensorInfo.GetShape()[3] / inputTensorInfo.GetShape()[3] });
1031
Pablo Tellof0bd6832019-04-26 17:58:13 +01001032 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1033 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1034 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1035 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +01001036
Finn Williamsd4fa5452021-03-01 12:31:41 +00001037 auto filterTensorAndData = CreateConstTensorPermuted(inputs[1], filterTensorInfo, permutationVector);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001038 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01001039 auto layerName = fmt::format("DepthwiseConv2D:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001040
1041 if (inputs.size() == 3)
1042 {
1043 desc.m_BiasEnabled = true;
1044 TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00001045 auto biasTensorAndData = CreateConstTensorNonPermuted(inputs[2], biasTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001046 layer = m_Network->AddDepthwiseConvolution2dLayer(desc,
1047 filterTensorAndData.first,
Finn Williamsd4fa5452021-03-01 12:31:41 +00001048 Optional<ConstTensor>(biasTensorAndData),
telsoa01c577f2c2018-08-31 09:22:23 +01001049 layerName.c_str());
1050 }
1051 else
1052 {
1053 layer = m_Network->AddDepthwiseConvolution2dLayer(desc,
1054 filterTensorAndData.first,
Matteo Martincighfc598e12019-05-14 10:36:13 +01001055 EmptyOptional(),
telsoa01c577f2c2018-08-31 09:22:23 +01001056 layerName.c_str());
1057 }
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001058 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01001059
Sadik Armagand109a4d2020-07-28 10:42:13 +01001060 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
jimfly01c25411c2018-11-14 17:47:22 +00001061 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001062
1063 // register the input connection slots for the layer, connections are made after all layers have been created
1064 // only the tensors for the inputs are relevant, exclude the const tensors
1065 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +00001066 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
telsoa01c577f2c2018-08-31 09:22:23 +01001067
jimfly01c25411c2018-11-14 17:47:22 +00001068 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +01001069 // register the output connection slots for the layer, connections are made after all layers have been created
1070 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1071 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1072}
1073
Kevin May7d96b162021-02-03 17:38:41 +00001074void TfLiteParserImpl::ParseDequantize(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsed66d142019-12-06 09:55:55 +00001075{
1076 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1077
1078 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1079 CHECK_VALID_SIZE(inputs.size(), 1);
1080
1081 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1082 CHECK_VALID_SIZE(outputs.size(), 1);
1083
James Ward58dec6b2020-09-11 17:32:44 +01001084 auto layerName = fmt::format("Dequantize:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsed66d142019-12-06 09:55:55 +00001085
1086 IConnectableLayer* layer = m_Network->AddDequantizeLayer(layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001087 ARMNN_ASSERT(layer != nullptr);
Finn Williamsed66d142019-12-06 09:55:55 +00001088
Sadik Armagand109a4d2020-07-28 10:42:13 +01001089 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Finn Williamsed66d142019-12-06 09:55:55 +00001090 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1091
1092 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1093 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1094
1095 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1096 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1097}
1098
Kevin May7d96b162021-02-03 17:38:41 +00001099void TfLiteParserImpl::ParseTranspose(size_t subgraphIndex, size_t operatorIndex)
Keith Davis4cd29a02019-09-09 14:49:20 +01001100{
1101 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1102
1103 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Kevin May85d92602019-09-27 17:21:06 +01001104 CHECK_VALID_SIZE(inputs.size(), 1, 2);
Keith Davis4cd29a02019-09-09 14:49:20 +01001105
1106 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1107 CHECK_VALID_SIZE(outputs.size(), 1);
1108
James Ward58dec6b2020-09-11 17:32:44 +01001109 auto layerName = fmt::format("Transpose:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly08759e22020-03-02 11:41:31 +00001110 TransposeDescriptor desc;
Keith Davis4cd29a02019-09-09 14:49:20 +01001111
josh minorba424d22019-11-13 10:55:17 -06001112 if (inputs.size() == 2)
Kevin May85d92602019-09-27 17:21:06 +01001113 {
1114 armnn::TensorInfo permuteTensorInfo = ToTensorInfo(inputs[1]);
1115 BufferRawPtr permuteBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
josh minorba424d22019-11-13 10:55:17 -06001116 auto numPermVecElements = permuteTensorInfo.GetNumElements();
1117 std::vector<unsigned int> permuteShape(numPermVecElements);
Kevin May85d92602019-09-27 17:21:06 +01001118 ::memcpy(permuteShape.data(), permuteBufferPtr->data.data(), permuteTensorInfo.GetNumBytes());
Mike Kelly08759e22020-03-02 11:41:31 +00001119 PermutationVector permutationVector(permuteShape.data(), permuteTensorInfo.GetNumElements());
Kevin May85d92602019-09-27 17:21:06 +01001120
Mike Kelly08759e22020-03-02 11:41:31 +00001121 desc = TransposeDescriptor(permutationVector);
Kevin May85d92602019-09-27 17:21:06 +01001122 }
1123
James Conroy05102392020-06-24 15:39:55 +01001124 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001125 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001126 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Keith Davis4cd29a02019-09-09 14:49:20 +01001127
James Conroy05102392020-06-24 15:39:55 +01001128 IConnectableLayer* layer = m_Network->AddTransposeLayer(desc, layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001129 ARMNN_ASSERT(layer != nullptr);
Keith Davis4cd29a02019-09-09 14:49:20 +01001130 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1131
1132 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1133 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1134
1135 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1136 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1137}
1138
Kevin May7d96b162021-02-03 17:38:41 +00001139void TfLiteParserImpl::ParseTransposeConv(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001140{
1141 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1142
1143 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1144 const auto * options = operatorPtr->builtin_options.AsTransposeConvOptions();
1145
1146 TransposeConvolution2dDescriptor desc;
1147 desc.m_BiasEnabled = false;
1148 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1149 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1150 desc.m_DataLayout = armnn::DataLayout::NHWC;
1151
1152 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
David Monahan61683802021-01-12 09:11:07 +00001153 if (inputs.size() == 4)
1154 {
1155 desc.m_BiasEnabled = true;
1156 }
1157 else
1158 {
1159 CHECK_VALID_SIZE(inputs.size(), 3);
1160 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001161
1162 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1163 CHECK_VALID_SIZE(outputs.size(), 1);
1164
Colm Donelan0ad3ef12020-07-03 15:54:28 +01001165 if (inputs[0])
1166 {
1167 armnn::TensorInfo tensorInfo = ToTensorInfo(inputs[0]);
1168 std::vector<int> output_shape(tensorInfo.GetNumElements());
1169 if (tensorInfo.GetDataType() == DataType::Signed32)
1170 {
1171 ::memcpy(output_shape.data(), GetBuffer(m_Model, inputs[0]->buffer)->data.data(), tensorInfo.GetNumBytes());
1172 }
1173 if (tensorInfo.GetDataType() == DataType::QAsymmU8)
1174 {
1175 for(unsigned int i=0; i < tensorInfo.GetNumElements(); i++)
1176 {
1177 output_shape[i] = GetBuffer(m_Model, inputs[0]->buffer)->data.data()[i];
1178 }
1179 }
1180 // Change from signed to unsigned int to store in TransposeConvolution2dDescriptor.
1181 for (int dimension : output_shape)
1182 {
1183 desc.m_OutputShape.push_back(static_cast<unsigned int>(dimension));
1184 }
1185 desc.m_OutputShapeEnabled = true;
1186 }
Matthew Jacksonccb25ea2019-08-20 17:18:33 +01001187 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[2]);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001188 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
1189
1190 // TfLite uses NHWC tensors
1191 const unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1192 const unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1193
1194 const unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1195 const unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1196
1197 CalcPadding(inputHeight,
1198 filterHeight,
1199 desc.m_StrideY,
1200 1, // DilationY
1201 desc.m_PadTop,
1202 desc.m_PadBottom,
1203 options->padding);
1204
1205 CalcPadding(inputWidth,
1206 filterWidth,
1207 desc.m_StrideX,
1208 1, // DilationX
1209 desc.m_PadLeft,
1210 desc.m_PadRight,
1211 options->padding);
1212
Finn Williamsd4fa5452021-03-01 12:31:41 +00001213 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001214
1215 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01001216 auto layerName = fmt::format("TransposeConv:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001217
David Monahan61683802021-01-12 09:11:07 +00001218 if (desc.m_BiasEnabled)
1219 {
1220 auto biasTensorInfo = ToTensorInfo(inputs[3]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00001221 auto biasConstTensor = CreateConstTensorNonPermuted(inputs[3], biasTensorInfo);
David Monahan61683802021-01-12 09:11:07 +00001222 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +00001223 filterTensorAndData,
1224 biasConstTensor,
David Monahan61683802021-01-12 09:11:07 +00001225 layerName.c_str());
1226 }
1227 else
1228 {
1229 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +00001230 filterTensorAndData,
David Monahan61683802021-01-12 09:11:07 +00001231 EmptyOptional(),
1232 layerName.c_str());
1233 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001234
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001235 ARMNN_ASSERT(layer != nullptr);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001236
Sadik Armagand109a4d2020-07-28 10:42:13 +01001237 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001238 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1239
1240 // only the tensors for the inputs are relevant, exclude the const (filter) tensor
1241 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Matthew Jacksonccb25ea2019-08-20 17:18:33 +01001242 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[2]});
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001243
1244 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1245 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1246}
1247
Kevin May7d96b162021-02-03 17:38:41 +00001248void TfLiteParserImpl::ParseAveragePool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001249{
1250 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Average);
1251}
1252
Kevin May7d96b162021-02-03 17:38:41 +00001253void TfLiteParserImpl::ParseBatchToSpaceND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001254{
1255 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1256
1257 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1258 CHECK_VALID_SIZE(inputs.size(), 3);
1259
1260 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1261 CHECK_VALID_SIZE(outputs.size(), 1);
1262
1263 armnn::TensorInfo blockShapeTensorInfo = ToTensorInfo(inputs[1]);
1264 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1265
1266 armnn::TensorInfo cropsTensorInfo = ToTensorInfo(inputs[2]);
1267 BufferRawPtr cropsBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1268
1269 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1270 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1271
1272 std::vector<unsigned int> cropsVector(cropsTensorInfo.GetNumElements());
1273 ::memcpy(cropsVector.data(), cropsBufferPtr->data.data(), cropsTensorInfo.GetNumBytes());
1274
1275 size_t step = 2;
1276 std::vector<std::pair<unsigned int, unsigned int>> crops;
1277 for (unsigned int i = 0; i < cropsTensorInfo.GetNumElements() / step; ++i)
1278 {
1279 crops.emplace_back(cropsVector[i * step], cropsVector[i * step + 1]);
1280 }
1281
1282 armnn::BatchToSpaceNdDescriptor desc;
1283 desc.m_BlockShape = blockShape;
1284 desc.m_Crops = crops;
1285 desc.m_DataLayout = armnn::DataLayout::NHWC;
1286
James Ward58dec6b2020-09-11 17:32:44 +01001287 auto layerName = fmt::format("BatchToSpaceND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001288
James Conroy05102392020-06-24 15:39:55 +01001289 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001290 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001291 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1292
1293 IConnectableLayer* layer = m_Network->AddBatchToSpaceNdLayer(desc, layerName.c_str());
1294 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001295 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1296
1297 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1298 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1299
1300 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1301 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1302}
1303
Kevin May7d96b162021-02-03 17:38:41 +00001304void TfLiteParserImpl::ParseL2Normalization(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson28c94572019-07-18 10:47:03 +01001305{
1306 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1307
1308 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1309 CHECK_VALID_SIZE(inputs.size(), 1);
1310
1311 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1312 CHECK_VALID_SIZE(outputs.size(), 1);
1313
1314 L2NormalizationDescriptor desc;
1315 desc.m_DataLayout = armnn::DataLayout::NHWC;
James Ward58dec6b2020-09-11 17:32:44 +01001316 auto layerName = fmt::format("L2Normalization:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson28c94572019-07-18 10:47:03 +01001317 IConnectableLayer* layer = m_Network->AddL2NormalizationLayer(desc, layerName.c_str());
1318
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001319 ARMNN_ASSERT(layer != nullptr);
Matthew Jackson28c94572019-07-18 10:47:03 +01001320
Sadik Armagand109a4d2020-07-28 10:42:13 +01001321 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jackson28c94572019-07-18 10:47:03 +01001322 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1323
1324 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1325 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1326
1327 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1328 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1329}
1330
Kevin May7d96b162021-02-03 17:38:41 +00001331void TfLiteParserImpl::ParseMaxPool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001332{
1333 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Max);
1334}
1335
Kevin May7d96b162021-02-03 17:38:41 +00001336void TfLiteParserImpl::ParseMaximum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001337{
1338 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1339
1340 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1341 CHECK_VALID_SIZE(inputs.size(), 2);
1342
1343 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1344 CHECK_VALID_SIZE(outputs.size(), 1);
1345
James Ward58dec6b2020-09-11 17:32:44 +01001346 auto layerName = fmt::format("Maximum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01001347
1348 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1349 TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1350 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001351
Sadik Armagand109a4d2020-07-28 10:42:13 +01001352 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001353 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1354
1355 IConnectableLayer* layer = m_Network->AddMaximumLayer(layerName.c_str());
1356 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001357 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1358
1359 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001360 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001361
1362 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1363 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1364}
1365
Kevin May7d96b162021-02-03 17:38:41 +00001366void TfLiteParserImpl::ParseMinimum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001367{
1368 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1369
1370 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1371 CHECK_VALID_SIZE(inputs.size(), 2);
1372
1373 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1374 CHECK_VALID_SIZE(outputs.size(), 1);
1375
James Ward58dec6b2020-09-11 17:32:44 +01001376 auto layerName = fmt::format("Minimum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01001377
1378 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1379 TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1380 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001381
Sadik Armagand109a4d2020-07-28 10:42:13 +01001382 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001383 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1384
1385 IConnectableLayer* layer = m_Network->AddMinimumLayer(layerName.c_str());
1386 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001387 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1388
1389 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001390 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001391
1392 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1393 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1394}
1395
Kevin May7d96b162021-02-03 17:38:41 +00001396void TfLiteParserImpl::ParsePool(size_t subgraphIndex,
1397 size_t operatorIndex,
1398 PoolingAlgorithm algorithm)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001399{
1400 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1401
1402 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1403 const auto * options = operatorPtr->builtin_options.AsPool2DOptions();
1404
1405 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1406
1407 std::string layerName;
1408
1409 switch (algorithm)
1410 {
1411 case PoolingAlgorithm::Average:
1412 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01001413 fmt::format("AveragePool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001414 break;
1415 case PoolingAlgorithm::Max:
1416 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01001417 fmt::format("MaxPool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001418 break;
1419 default:
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001420 ARMNN_ASSERT_MSG(false, "Unsupported Pooling Algorithm");
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001421 }
1422
1423 Pooling2dDescriptor desc;
1424
1425 desc.m_PoolType = algorithm;
1426 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1427 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1428 desc.m_PoolWidth = CHECKED_NON_NEGATIVE(options->filter_width);
1429 desc.m_PoolHeight = CHECKED_NON_NEGATIVE(options->filter_height);
1430 desc.m_PaddingMethod = PaddingMethod::Exclude;
1431 desc.m_OutputShapeRounding = OutputShapeRounding::Floor;
jimfly01c25411c2018-11-14 17:47:22 +00001432 desc.m_DataLayout = armnn::DataLayout::NHWC;
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001433
1434 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1435 CHECK_VALID_SIZE(inputs.size(), 1);
1436 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1437
1438 // assuming input is NHWC
1439 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1440 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1441
Pablo Tellof0bd6832019-04-26 17:58:13 +01001442 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, 1u,
1443 desc.m_PadTop, desc.m_PadBottom, options->padding);
1444 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, 1u,
1445 desc.m_PadLeft, desc.m_PadRight, options->padding);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001446
1447 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1448 CHECK_VALID_SIZE(outputs.size(), 1);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001449
Sadik Armagand109a4d2020-07-28 10:42:13 +01001450 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001451 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1452
1453 IConnectableLayer* layer = m_Network->AddPooling2dLayer(desc, layerName.c_str());
1454 ARMNN_ASSERT(layer != nullptr);
jimfly01c25411c2018-11-14 17:47:22 +00001455 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001456
1457 // register the input connection slots for the layer, connections are made after all layers have been created
1458 // only the tensors for the inputs are relevant, exclude the const tensors
1459 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +00001460 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001461
jimfly01c25411c2018-11-14 17:47:22 +00001462 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001463 // register the output connection slots for the layer, connections are made after all layers have been created
1464 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1465 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1466}
1467
Kevin May7d96b162021-02-03 17:38:41 +00001468void TfLiteParserImpl::ParseSlice(size_t subgraphIndex, size_t operatorIndex)
josh minorba424d22019-11-13 10:55:17 -06001469{
1470 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1471
1472 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1473 CHECK_VALID_SIZE(inputs.size(), 3);
1474 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1475 CHECK_VALID_SIZE(outputs.size(), 1);
1476
1477 SliceDescriptor desc;
1478
1479 // set begin tensor info for slice descriptor
1480 armnn::TensorInfo beginTensorInfo = ToTensorInfo(inputs[1]);
1481 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1482
1483 std::vector<unsigned int> begin(beginTensorInfo.GetNumElements());
1484 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
1485
1486 // set size tensor info for slice descriptor
1487 armnn::TensorInfo sizeTensorInfo = ToTensorInfo(inputs[2]);
1488 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1489
1490 std::vector<unsigned int> size(sizeTensorInfo.GetNumElements());
1491 ::memcpy(size.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
1492 desc = SliceDescriptor(begin, size);
1493
James Ward58dec6b2020-09-11 17:32:44 +01001494 auto layerName = fmt::format("Slice:{}:{}", subgraphIndex, operatorIndex);
josh minorba424d22019-11-13 10:55:17 -06001495
James Conroy05102392020-06-24 15:39:55 +01001496 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001497 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001498 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1499
1500 IConnectableLayer* const layer = m_Network->AddSliceLayer(desc, layerName.c_str());
josh minorba424d22019-11-13 10:55:17 -06001501 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1502
1503 // register the input connection slots for the layer, connections are made after all layers have been created
1504 // only the tensors for the inputs are relevant, exclude the const tensors
1505 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1506 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1507
1508 // register the output connection slots for the layer, connections are made after all layers have been created
1509 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1510 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1511}
1512
Kevin May7d96b162021-02-03 17:38:41 +00001513void TfLiteParserImpl::ParseSoftmax(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001514{
1515 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1516 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1517 const auto * options = operatorPtr->builtin_options.AsSoftmaxOptions();
1518
1519 SoftmaxDescriptor desc;
1520 desc.m_Beta = options->beta;
1521
1522 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1523 CHECK_VALID_SIZE(inputs.size(), 1);
1524 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1525 CHECK_VALID_SIZE(outputs.size(), 1);
1526
James Ward58dec6b2020-09-11 17:32:44 +01001527 auto layerName = fmt::format("Softmax:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001528 IConnectableLayer* const layer = m_Network->AddSoftmaxLayer(desc, layerName.c_str());
1529
Sadik Armagand109a4d2020-07-28 10:42:13 +01001530 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
telsoa01c577f2c2018-08-31 09:22:23 +01001531 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1532
1533 // register the input connection slots for the layer, connections are made after all layers have been created
1534 // only the tensors for the inputs are relevant, exclude the const tensors
1535 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1536 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1537
1538 // register the output connection slots for the layer, connections are made after all layers have been created
1539 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1540 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1541}
1542
Kevin May7d96b162021-02-03 17:38:41 +00001543void TfLiteParserImpl::ParseSpaceToBatchND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001544{
1545 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1546
1547 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1548 CHECK_VALID_SIZE(inputs.size(), 3);
1549
1550 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1551 CHECK_VALID_SIZE(outputs.size(), 1);
1552
1553 armnn::TensorInfo blockShapeTensorInfo = ToTensorInfo(inputs[1]);
1554 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1555
1556 armnn::TensorInfo padListTensorInfo = ToTensorInfo(inputs[2]);
1557 BufferRawPtr padListBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1558
1559 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1560 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1561
1562 std::vector<unsigned int> padListVector(padListTensorInfo.GetNumElements());
1563 ::memcpy(padListVector.data(), padListBufferPtr->data.data(), padListTensorInfo.GetNumBytes());
1564
1565 size_t step = 2;
1566 std::vector<std::pair<unsigned int, unsigned int>> padList;
1567 for (unsigned int i = 0; i < padListTensorInfo.GetNumElements() / step; ++i)
1568 {
1569 padList.emplace_back(padListVector[i * step], padListVector[i * step + 1]);
1570 }
1571
1572 armnn::SpaceToBatchNdDescriptor desc;
1573 desc.m_BlockShape = blockShape;
1574 desc.m_PadList = padList;
1575 desc.m_DataLayout = armnn::DataLayout::NHWC;
1576
James Ward58dec6b2020-09-11 17:32:44 +01001577 auto layerName = fmt::format("SpaceToBatchND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001578
James Conroy05102392020-06-24 15:39:55 +01001579 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001580 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001581 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1582
1583 IConnectableLayer* layer = m_Network->AddSpaceToBatchNdLayer(desc, layerName.c_str());
1584 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001585 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1586
1587 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1588 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1589
1590 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1591 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1592}
1593
Kevin May7d96b162021-02-03 17:38:41 +00001594armnn::TensorInfo TfLiteParserImpl::OutputShapeOfSqueeze(const std::vector<uint32_t> & squeezeDimsIn,
1595 const armnn::TensorInfo & inputTensorInfo)
telsoa01c577f2c2018-08-31 09:22:23 +01001596{
1597 CHECK_VALID_SIZE(squeezeDimsIn.size(), 0, 1, 2, 3, 4);
1598 std::vector<uint32_t> squeezeDims = squeezeDimsIn;
1599 static const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
1600
1601 if (inputTensorInfo.GetNumDimensions() > 4)
1602 {
1603 std::stringstream ss;
1604 ss << "Input tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
1605 << " shape:" << inputTensorInfo.GetShape() << " "
1606 << CHECK_LOCATION().AsString();
1607 throw ParseException(ss.str());
1608 }
1609
1610 if (squeezeDims.empty())
1611 {
1612 squeezeDims.assign(dimensionSequence,
1613 dimensionSequence+inputTensorInfo.GetNumDimensions());
1614 }
1615
1616 std::vector<uint32_t> outputDims;
1617 for(unsigned int i = 0; i < inputTensorInfo.GetNumDimensions(); i++)
1618 {
1619 bool skipSqueeze = (std::find(squeezeDims.begin(), squeezeDims.end(), i) == squeezeDims.end());
1620 auto currentDimension = inputTensorInfo.GetShape()[i];
1621 if (skipSqueeze || currentDimension != 1)
1622 {
1623 outputDims.push_back(currentDimension);
1624 }
1625 }
1626
1627 if (outputDims.size() > 4)
1628 {
1629 std::stringstream ss;
1630 ss << "Output tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
1631 << " shape:" << inputTensorInfo.GetShape() << " "
1632 << CHECK_LOCATION().AsString();
1633 throw ParseException(ss.str());
1634 }
1635
1636 TensorShape outShape = TensorShape(static_cast<unsigned int>(outputDims.size()),
1637 outputDims.data());
1638
1639 // we need to preserve the tensor type and the quantization data as well
1640 TensorInfo outTensorInfo = inputTensorInfo;
1641 outTensorInfo.SetShape(outShape);
1642
1643 return outTensorInfo;
1644}
1645
Kevin May7d96b162021-02-03 17:38:41 +00001646void TfLiteParserImpl::ParseSqueeze(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001647{
1648 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1649
1650 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1651 CHECK_VALID_SIZE(inputs.size(), 1);
1652
1653 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1654 CHECK_VALID_SIZE(outputs.size(), 1);
1655
1656 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1657 const auto * options = operatorPtr->builtin_options.AsSqueezeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01001658 auto layerName = fmt::format("Squeeze:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001659
1660 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1661 armnn::TensorInfo outputTensorInfo =
Kevin May7d96b162021-02-03 17:38:41 +00001662 TfLiteParserImpl::OutputShapeOfSqueeze(AsUnsignedVector(options->squeeze_dims),
telsoa01c577f2c2018-08-31 09:22:23 +01001663 inputTensorInfo);
James Conroy05102392020-06-24 15:39:55 +01001664 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
telsoa01c577f2c2018-08-31 09:22:23 +01001665
1666 ReshapeDescriptor reshapeDesc;
1667 reshapeDesc.m_TargetShape = outputTensorInfo.GetShape();
1668
telsoa01c577f2c2018-08-31 09:22:23 +01001669 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001670 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01001671 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1672
1673 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1674 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1675
1676 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1677 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1678}
1679
Kevin May7d96b162021-02-03 17:38:41 +00001680void TfLiteParserImpl::ParseStridedSlice(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves451d95b2019-02-12 22:59:22 -02001681{
1682 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1683
1684 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1685 CHECK_VALID_SIZE(inputs.size(), 4);
1686
1687 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1688 CHECK_VALID_SIZE(outputs.size(), 1);
1689
1690 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1691 const auto * options = operatorPtr->builtin_options.AsStridedSliceOptions();
1692
1693 StridedSliceDescriptor desc;
1694 desc.m_BeginMask = options->begin_mask;
1695 desc.m_EllipsisMask = options->ellipsis_mask;
1696 desc.m_EndMask = options->end_mask;
1697 desc.m_NewAxisMask = options->new_axis_mask;
1698 desc.m_ShrinkAxisMask = options->shrink_axis_mask;
1699 desc.m_DataLayout = armnn::DataLayout::NHWC;
1700
1701 armnn::TensorInfo beginTensorInfo = ToTensorInfo(inputs[1]);
1702 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1703
1704 std::vector<int> begin(beginTensorInfo.GetNumElements());
1705 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
1706
1707 armnn::TensorInfo endTensorInfo = ToTensorInfo(inputs[2]);
1708 BufferRawPtr endBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1709
1710 std::vector<int> end(endTensorInfo.GetNumElements());
1711 ::memcpy(end.data(), endBufferPtr->data.data(), endTensorInfo.GetNumBytes());
1712
1713 armnn::TensorInfo strideTensorInfo = ToTensorInfo(inputs[3]);
1714 BufferRawPtr strideBufferPtr = GetBuffer(m_Model, inputs[3]->buffer);
1715
1716 std::vector<int> stride(strideTensorInfo.GetNumElements());
1717 ::memcpy(stride.data(), strideBufferPtr->data.data(), strideTensorInfo.GetNumBytes());
1718
1719 desc.m_Begin = begin;
1720 desc.m_End = end;
1721 desc.m_Stride = stride;
1722
James Ward58dec6b2020-09-11 17:32:44 +01001723 auto layerName = fmt::format("StridedSlice:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02001724 IConnectableLayer* layer = m_Network->AddStridedSliceLayer(desc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001725 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02001726
Sadik Armagand109a4d2020-07-28 10:42:13 +01001727 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02001728 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1729
1730 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1731 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1732
1733 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1734 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1735}
1736
Kevin May7d96b162021-02-03 17:38:41 +00001737void TfLiteParserImpl::ParseSub(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001738{
1739 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1740
1741 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1742 const auto * options = operatorPtr->builtin_options.AsSubOptions();
1743
1744 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1745 CHECK_VALID_SIZE(inputs.size(), 2);
1746
1747 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1748 CHECK_VALID_SIZE(outputs.size(), 1);
1749
1750 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1751 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1752
James Ward58dec6b2020-09-11 17:32:44 +01001753 auto layerName = fmt::format("Sub:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001754 IConnectableLayer* layer = m_Network->AddSubtractionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001755 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001756
Sadik Armagand109a4d2020-07-28 10:42:13 +01001757 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001758 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1759
1760 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001761 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001762
1763 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1764
1765 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1766 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1767}
1768
Kevin May7d96b162021-02-03 17:38:41 +00001769void TfLiteParserImpl::ParseDiv(size_t subgraphIndex, size_t operatorIndex)
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301770{
1771 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1772
1773 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1774 const auto * options = operatorPtr->builtin_options.AsDivOptions();
1775
1776 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1777 CHECK_VALID_SIZE(inputs.size(), 2);
1778
1779 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1780 CHECK_VALID_SIZE(outputs.size(), 1);
1781
1782 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1783 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1784
James Ward58dec6b2020-09-11 17:32:44 +01001785 auto layerName = fmt::format("Div:{}:{}", subgraphIndex, operatorIndex);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301786 IConnectableLayer* layer = m_Network->AddDivisionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001787 ARMNN_ASSERT(layer != nullptr);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301788
Sadik Armagand109a4d2020-07-28 10:42:13 +01001789 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301790 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1791
1792 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001793 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301794 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1795
1796 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1797 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1798}
1799
Kevin May7d96b162021-02-03 17:38:41 +00001800void TfLiteParserImpl::ParseAdd(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001801{
1802 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1803
1804 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1805 const auto * options = operatorPtr->builtin_options.AsAddOptions();
1806
1807 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1808 CHECK_VALID_SIZE(inputs.size(), 2);
1809
1810 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1811 CHECK_VALID_SIZE(outputs.size(), 1);
1812
Bruno Goncalves9c761a62018-12-27 14:20:35 -02001813 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1814 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1815
James Ward58dec6b2020-09-11 17:32:44 +01001816 auto layerName = fmt::format("Add:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001817 IConnectableLayer* layer = m_Network->AddAdditionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001818 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001819
Sadik Armagand109a4d2020-07-28 10:42:13 +01001820 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001821 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1822
1823 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001824 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001825 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1826
1827 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1828 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1829}
1830
Kevin May7d96b162021-02-03 17:38:41 +00001831void TfLiteParserImpl::ParseMul(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001832{
1833 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1834
1835 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1836 const auto * options = operatorPtr->builtin_options.AsMulOptions();
1837
1838 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1839 CHECK_VALID_SIZE(inputs.size(), 2);
1840
1841 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1842 CHECK_VALID_SIZE(outputs.size(), 1);
1843
Bruno Goncalves9c761a62018-12-27 14:20:35 -02001844 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1845 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1846
James Ward58dec6b2020-09-11 17:32:44 +01001847 auto layerName = fmt::format("Mul:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001848 IConnectableLayer* layer = m_Network->AddMultiplicationLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001849 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001850
Sadik Armagand109a4d2020-07-28 10:42:13 +01001851 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001852 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1853
1854 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001855 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001856 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1857
1858 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1859 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1860}
1861
Kevin May7d96b162021-02-03 17:38:41 +00001862void TfLiteParserImpl::ParseMean(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves2235cee2018-12-19 12:51:45 -02001863{
1864 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1865
1866 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1867
1868 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1869 CHECK_VALID_SIZE(outputs.size(), 1);
1870
1871 armnn::TensorInfo dimTensorInfo = ToTensorInfo(inputs[1]);
1872 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1873
1874 armnn::MeanDescriptor desc;
1875 std::vector<unsigned int> axis(dimTensorInfo.GetNumElements());
1876 ::memcpy(axis.data(), bufferPtr->data.data(), dimTensorInfo.GetNumBytes());
1877 desc.m_Axis = axis;
1878
1879 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001880 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02001881
1882 desc.m_KeepDims =
1883 inputTensorInfo.GetNumDimensions() == outputTensorInfo.GetNumDimensions() ?
1884 true : false;
1885
James Ward58dec6b2020-09-11 17:32:44 +01001886 auto layerName = fmt::format("Mean:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02001887 IConnectableLayer* layer = m_Network->AddMeanLayer(desc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001888 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02001889
1890 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1891
1892 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1893 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1894
1895 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1896 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1897}
1898
Kevin May7d96b162021-02-03 17:38:41 +00001899void TfLiteParserImpl::ParsePad(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001900{
1901 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1902
Kevin May7d96b162021-02-03 17:38:41 +00001903 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001904
Kevin May7d96b162021-02-03 17:38:41 +00001905 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001906 CHECK_VALID_SIZE(outputs.size(), 1);
1907
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00001908 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1909
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001910 armnn::TensorInfo padTensorInfo = ToTensorInfo(inputs[1]);
1911 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1912
1913 std::vector<unsigned int> padBuffer(padTensorInfo.GetNumElements());
1914 ::memcpy(padBuffer.data(), bufferPtr->data.data(), padTensorInfo.GetNumBytes());
1915
1916 size_t step = 2;
1917 armnn::PadDescriptor desc;
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00001918 if (inputTensorInfo.IsQuantized())
1919 {
1920 desc.m_PadValue = static_cast<float>(inputTensorInfo.GetQuantizationOffset());
1921 }
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001922 for (unsigned int i = 0; i < padTensorInfo.GetNumElements() / step; ++i)
1923 {
1924 desc.m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
1925 }
1926
James Ward58dec6b2020-09-11 17:32:44 +01001927 auto layerName = fmt::format("Pad:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001928 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001929
1930 IConnectableLayer* layer = m_Network->AddPadLayer(desc, layerName.c_str());
1931 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001932 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1933
1934 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1935 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1936
1937 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1938 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1939}
1940
Kevin May7d96b162021-02-03 17:38:41 +00001941void TfLiteParserImpl::ParseQuantize(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan66dedc72019-12-10 16:32:07 +00001942{
1943 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1944
1945 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1946 CHECK_VALID_SIZE(inputs.size(), 1);
1947
1948 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1949 CHECK_VALID_SIZE(outputs.size(), 1);
1950
James Ward58dec6b2020-09-11 17:32:44 +01001951 auto layerName = fmt::format("Quantize:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan66dedc72019-12-10 16:32:07 +00001952
1953 IConnectableLayer* layer = m_Network->AddQuantizeLayer(layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001954 ARMNN_ASSERT(layer != nullptr);
Sadik Armagan66dedc72019-12-10 16:32:07 +00001955
Sadik Armagand109a4d2020-07-28 10:42:13 +01001956 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan66dedc72019-12-10 16:32:07 +00001957 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1958
1959 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1960 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1961
1962 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1963 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1964}
Finn Williamsc42c3842019-01-22 14:18:11 +00001965
Kevin May7d96b162021-02-03 17:38:41 +00001966void TfLiteParserImpl::ParseRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01001967{
Finn Williamsc42c3842019-01-22 14:18:11 +00001968 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::ReLu);
Sadik Armagan58f39192018-09-17 14:14:39 +01001969}
1970
Kevin May7d96b162021-02-03 17:38:41 +00001971void TfLiteParserImpl::ParseRelu6(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01001972{
Finn Williamsc42c3842019-01-22 14:18:11 +00001973 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::BoundedReLu);
1974}
Sadik Armagan58f39192018-09-17 14:14:39 +01001975
Kevin May7d96b162021-02-03 17:38:41 +00001976void TfLiteParserImpl::ParseLeakyRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan12239e72020-05-27 11:06:17 +01001977{
Jan Eilers2f746b32020-07-28 14:00:06 +01001978 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::LeakyReLu);
Sadik Armagan12239e72020-05-27 11:06:17 +01001979}
1980
Kevin May7d96b162021-02-03 17:38:41 +00001981void TfLiteParserImpl::ParseLogistic(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsc42c3842019-01-22 14:18:11 +00001982{
1983 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::Sigmoid);
1984}
1985
Kevin May7d96b162021-02-03 17:38:41 +00001986void TfLiteParserImpl::ParseTanH(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd99851762019-04-09 09:37:38 +01001987{
1988 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::TanH);
1989}
1990
Kevin May7d96b162021-02-03 17:38:41 +00001991void TfLiteParserImpl::ParseElu(size_t subgraphIndex, size_t operatorIndex)
Matthew Sloyan7515d072020-12-16 12:50:01 +00001992{
1993 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::Elu);
1994}
1995
Kevin May7d96b162021-02-03 17:38:41 +00001996void TfLiteParserImpl::ParseHardSwish(size_t subgraphIndex, size_t operatorIndex)
Jan Eilers2f746b32020-07-28 14:00:06 +01001997{
1998 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::HardSwish);
1999}
Finn Williamsc42c3842019-01-22 14:18:11 +00002000
Kevin May7d96b162021-02-03 17:38:41 +00002001void TfLiteParserImpl::ParseActivation(size_t subgraphIndex, size_t operatorIndex, ActivationFunction activationType)
Finn Williamsc42c3842019-01-22 14:18:11 +00002002{
2003 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan58f39192018-09-17 14:14:39 +01002004 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Jan Eilers8eb25602020-03-09 12:13:48 +00002005 IgnoreUnused(operatorPtr);
Sadik Armagan58f39192018-09-17 14:14:39 +01002006
2007 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2008 CHECK_VALID_SIZE(inputs.size(), 1);
2009
2010 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2011 CHECK_VALID_SIZE(outputs.size(), 1);
2012
James Ward58dec6b2020-09-11 17:32:44 +01002013 auto layerName = fmt::format("Activation:");
Sadik Armagan58f39192018-09-17 14:14:39 +01002014 ActivationDescriptor activationDesc;
Finn Williamsc42c3842019-01-22 14:18:11 +00002015 activationDesc.m_Function = activationType;
2016
2017 switch (activationType)
2018 {
2019 case ActivationFunction::ReLu:
2020 {
James Ward58dec6b2020-09-11 17:32:44 +01002021 layerName += fmt::format("RELU:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002022 break;
2023 }
2024 case ActivationFunction::BoundedReLu:
2025 {
James Ward58dec6b2020-09-11 17:32:44 +01002026 layerName += fmt::format("RELU6:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002027 activationDesc.m_A = 6.0f;
2028 activationDesc.m_B = 0.0f;
2029 break;
2030 }
2031 case ActivationFunction::Sigmoid:
2032 {
James Ward58dec6b2020-09-11 17:32:44 +01002033 layerName += fmt::format("SIGMOID:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002034 break;
2035 }
Nina Drozd99851762019-04-09 09:37:38 +01002036 case ActivationFunction::TanH:
2037 {
James Ward58dec6b2020-09-11 17:32:44 +01002038 layerName += fmt::format("TANH:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd99851762019-04-09 09:37:38 +01002039 activationDesc.m_A = 1.0f;
2040 activationDesc.m_B = 1.0f;
2041 break;
2042 }
Sadik Armagan12239e72020-05-27 11:06:17 +01002043 case ActivationFunction::LeakyReLu:
2044 {
James Ward58dec6b2020-09-11 17:32:44 +01002045 layerName += fmt::format("LEAKYRELU:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan12239e72020-05-27 11:06:17 +01002046 const auto * options = operatorPtr->builtin_options.AsLeakyReluOptions();
2047 activationDesc.m_A = options->alpha;
2048 break;
2049 }
Matthew Sloyan7515d072020-12-16 12:50:01 +00002050 case ActivationFunction::Elu:
2051 {
2052 layerName += fmt::format("ELU:{}:{}", subgraphIndex, operatorIndex);
2053 activationDesc.m_A = 1.0f;
2054 break;
2055 }
Jan Eilers2f746b32020-07-28 14:00:06 +01002056 case ActivationFunction::HardSwish:
Matthew Sloyan7515d072020-12-16 12:50:01 +00002057 {
James Ward58dec6b2020-09-11 17:32:44 +01002058 layerName += fmt::format("HARDSWISH:{}:{}", subgraphIndex, operatorIndex);
Jan Eilers2f746b32020-07-28 14:00:06 +01002059 break;
Matthew Sloyan7515d072020-12-16 12:50:01 +00002060 }
Finn Williamsc42c3842019-01-22 14:18:11 +00002061 default:
2062 {
2063 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002064 fmt::format("Unexpected ActivationFunction[{}] when creating layerName {} ",
2065 static_cast<int>(activationType), CHECK_LOCATION().AsString()));
Finn Williamsc42c3842019-01-22 14:18:11 +00002066 }
2067 }
2068
2069 IConnectableLayer* const layer = m_Network->AddActivationLayer(activationDesc, layerName.c_str());
Sadik Armagan58f39192018-09-17 14:14:39 +01002070
Sadik Armagand109a4d2020-07-28 10:42:13 +01002071 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan58f39192018-09-17 14:14:39 +01002072 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2073
2074 // register the input connection slots for the layer, connections are made after all layers have been created
2075 // only the tensors for the inputs are relevant, exclude the const tensors
2076 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2077 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2078
2079 // register the output connection slots for the layer, connections are made after all layers have been created
2080 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2081 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2082}
Kevin May7d96b162021-02-03 17:38:41 +00002083armnn::TensorInfo TfLiteParserImpl::OutputShapeOfReshape(const armnn::TensorInfo & inputTensorInfo,
2084 const std::vector<int32_t> & targetDimsIn)
Sadikb94967b2018-09-19 15:30:00 +01002085{
2086 std::vector<unsigned int> outputDims(targetDimsIn.begin(), targetDimsIn.end());
2087 const auto stretchDim = std::find(targetDimsIn.begin(), targetDimsIn.end(), -1);
2088
2089 if (stretchDim != targetDimsIn.end())
2090 {
2091 if (std::find(std::next(stretchDim), targetDimsIn.end(), -1) != targetDimsIn.end())
2092 {
2093 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002094 fmt::format("At most one component of shape can be -1 {}", CHECK_LOCATION().AsString()));
Sadikb94967b2018-09-19 15:30:00 +01002095 }
2096
2097 auto targetNumElements =
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002098 armnn::numeric_cast<unsigned int>(
Sadikb94967b2018-09-19 15:30:00 +01002099 std::accumulate(targetDimsIn.begin(), targetDimsIn.end(), -1, std::multiplies<int32_t>()));
2100
2101 auto stretchIndex = static_cast<size_t>(std::distance(targetDimsIn.begin(), stretchDim));
2102 outputDims[stretchIndex] = inputTensorInfo.GetNumElements() / targetNumElements;
2103 }
2104
2105 TensorShape outputShape = TensorShape(static_cast<unsigned int>(outputDims.size()), outputDims.data());
2106
2107 TensorInfo reshapeInfo = inputTensorInfo;
2108 reshapeInfo.SetShape(outputShape);
2109
2110 return reshapeInfo;
2111}
2112
Kevin May7d96b162021-02-03 17:38:41 +00002113void TfLiteParserImpl::ParseReshape(size_t subgraphIndex, size_t operatorIndex)
Sadikb94967b2018-09-19 15:30:00 +01002114{
2115 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2116
2117 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01002118
2119 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2120 CHECK_VALID_SIZE(outputs.size(), 1);
2121
2122 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2123 const auto * options = operatorPtr->builtin_options.AsReshapeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01002124 auto layerName = fmt::format("Reshape:{}:{}", subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01002125
2126 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
kevmay0171972a82018-12-17 14:28:03 +00002127 armnn::TensorInfo actualOutputTensorInfo = ToTensorInfo(outputs[0]);
James Conroy05102392020-06-24 15:39:55 +01002128 CheckMatchingQuantization(inputTensorInfo, actualOutputTensorInfo, layerName, "Input 0", "Output 0");
Derek Lambertic9e52792020-03-11 11:42:26 +00002129
Jan Eilersbac9b352020-07-13 13:40:24 +01002130 // Extracting new shape for the output
2131 // There are two ways it can be passed
2132 // * First is to define the target shape in the operator built-in options
2133 // * Second is to pass it as a second input tensor
Derek Lambertic9e52792020-03-11 11:42:26 +00002134 std::vector<int32_t> targetShape;
Jan Eilersbac9b352020-07-13 13:40:24 +01002135 bool targetShapeFound = false;
2136 // Check if built-in options were given
2137 if (options != nullptr)
Derek Lambertic9e52792020-03-11 11:42:26 +00002138 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002139 // make sure the parameter is given
2140 if (options->new_shape.empty() == false)
Derek Lambertic9e52792020-03-11 11:42:26 +00002141 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002142 targetShape = options->new_shape;
2143 targetShapeFound = true;
Derek Lambertif4a953f2020-03-17 14:25:57 +00002144 }
Derek Lambertic9e52792020-03-11 11:42:26 +00002145 }
Jan Eilersbac9b352020-07-13 13:40:24 +01002146
2147 // If there is no built-in option given or if the built-in new_shape parameter was empty
2148 if (!targetShapeFound)
Derek Lambertic9e52792020-03-11 11:42:26 +00002149 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002150 // Check for a second input tensor
2151 if (inputs.size() > 1 && inputs[1] != nullptr)
2152 {
2153 if (inputs[1]->is_variable)
2154 {
2155 ARMNN_THROW_PARSE_EXCEPTION( "Target shapes defined in non-const input tensors is not supported");
2156 }
2157
2158 if (inputs[1]->shape.size() != 1)
2159 {
2160 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not a 1D tensor");
2161 }
2162
2163 if (inputs[1]->type != tflite::TensorType_INT32)
2164 {
2165 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not an int32 type");
2166 }
2167
2168 // Extract target shape from input
2169 auto bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2170 auto values = reinterpret_cast<const int32_t*>(bufferPtr->data.data());
Sadik Armagan19a1c032021-01-20 12:17:00 +00002171 if (!values)
2172 {
2173 ARMNN_THROW_PARSE_EXCEPTION("Reshape operator target shape input buffer data is null");
2174 }
Jan Eilersbac9b352020-07-13 13:40:24 +01002175 for (int i=0; i < inputs[1]->shape[0]; ++i)
2176 {
2177 targetShape.push_back(values[i]);
2178 }
2179 }
2180 else
Derek Lambertic9e52792020-03-11 11:42:26 +00002181 {
2182 ARMNN_THROW_PARSE_EXCEPTION("Target shape not defined in reshape parameters or input tensor. "
2183 "At least one method required");
2184 }
Derek Lambertic9e52792020-03-11 11:42:26 +00002185 }
2186
kevmay0171972a82018-12-17 14:28:03 +00002187 armnn::TensorInfo reshapeOutputTensorInfo =
Kevin May7d96b162021-02-03 17:38:41 +00002188 TfLiteParserImpl::OutputShapeOfReshape(inputTensorInfo, targetShape);
Sadikb94967b2018-09-19 15:30:00 +01002189
kevmay0171972a82018-12-17 14:28:03 +00002190 // Check for valid input size and that reshape parameters equal output shape
Aron Virginas-Tar70672f62019-01-23 14:00:00 +00002191 const armnn::TensorShape& reshapeOutputTensorShape = reshapeOutputTensorInfo.GetShape();
2192 if (inputs.size() > 1 && !CheckShape(reshapeOutputTensorShape, outputs[0]->shape))
kevmay0171972a82018-12-17 14:28:03 +00002193 {
2194 std::stringstream ss;
2195 ss << "New shape defined in reshape parameters "
Aron Virginas-Tar70672f62019-01-23 14:00:00 +00002196 << reshapeOutputTensorShape
kevmay0171972a82018-12-17 14:28:03 +00002197 << " does not equal output shape "
2198 << actualOutputTensorInfo.GetShape()
2199 << ": "
2200 << CHECK_LOCATION().AsString();
2201 throw ParseException(ss.str());
2202 }
2203
Sadikb94967b2018-09-19 15:30:00 +01002204 ReshapeDescriptor reshapeDesc;
kevmay0171972a82018-12-17 14:28:03 +00002205 reshapeDesc.m_TargetShape = reshapeOutputTensorInfo.GetShape();
Sadikb94967b2018-09-19 15:30:00 +01002206
Sadikb94967b2018-09-19 15:30:00 +01002207 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002208 ARMNN_ASSERT(layer != nullptr);
kevmay0171972a82018-12-17 14:28:03 +00002209 layer->GetOutputSlot(0).SetTensorInfo(reshapeOutputTensorInfo);
Sadikb94967b2018-09-19 15:30:00 +01002210
2211 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2212 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2213
2214 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2215 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2216}
2217
Kevin May7d96b162021-02-03 17:38:41 +00002218void TfLiteParserImpl::ParseResizeBilinear(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002219{
Sadik Armagana3b31f02019-12-05 09:08:53 +00002220 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::Bilinear);
2221}
2222
Kevin May7d96b162021-02-03 17:38:41 +00002223void TfLiteParserImpl::ParseResizeNearestNeighbor(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagana3b31f02019-12-05 09:08:53 +00002224{
2225 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::NearestNeighbor);
2226}
2227
Kevin May7d96b162021-02-03 17:38:41 +00002228void TfLiteParserImpl::ParseResize(size_t subgraphIndex, size_t operatorIndex, ResizeMethod resizeMethod)
Sadik Armagana3b31f02019-12-05 09:08:53 +00002229{
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002230 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2231
2232 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2233 CHECK_VALID_SIZE(inputs.size(), 2);
2234
2235 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2236 CHECK_VALID_SIZE(outputs.size(), 1);
2237
2238 armnn::TensorInfo sizeTensorInfo = ToTensorInfo(inputs[1]);
2239
2240 // Data for the parsed tensor args (size) must be stored locally.
2241 std::vector<int32_t> sizeTensorData(sizeTensorInfo.GetNumElements());
2242
2243 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2244 ::memcpy(sizeTensorData.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
2245
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01002246 ResizeDescriptor desc;
Sadik Armagana3b31f02019-12-05 09:08:53 +00002247 desc.m_Method = resizeMethod;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002248 desc.m_TargetHeight = static_cast<uint32_t> (sizeTensorData[0]);
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01002249 desc.m_TargetWidth = static_cast<uint32_t> (sizeTensorData[1]);
2250 desc.m_DataLayout = armnn::DataLayout::NHWC;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002251
James Ward58dec6b2020-09-11 17:32:44 +01002252 auto layerName = fmt::format("Resize:");
Sadik Armagana3b31f02019-12-05 09:08:53 +00002253
2254 switch (resizeMethod)
2255 {
2256 case ResizeMethod::Bilinear:
2257 {
James Ward58dec6b2020-09-11 17:32:44 +01002258 layerName += fmt::format("BILINEAR:{}:{}", subgraphIndex, operatorIndex);
Sang-Hoon Park820eb142020-01-08 10:25:24 +00002259
2260 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2261 const auto * options = operatorPtr->builtin_options.AsResizeBilinearOptions();
2262
David Monahan4a0c9b92020-05-30 09:48:39 +01002263 desc.m_AlignCorners = options->align_corners;
Sadik Armagana3b31f02019-12-05 09:08:53 +00002264 break;
2265 }
2266 case ResizeMethod::NearestNeighbor:
2267 {
James Ward58dec6b2020-09-11 17:32:44 +01002268 layerName += fmt::format("NEARESTNEIGHBOR:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagana3b31f02019-12-05 09:08:53 +00002269 break;
2270 }
2271 default:
2272 {
2273 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002274 fmt::format("Unexpected ResizeMethod[{}] when creating layerName {} ",
2275 static_cast<int>(resizeMethod), CHECK_LOCATION().AsString()));
Sadik Armagana3b31f02019-12-05 09:08:53 +00002276 }
2277 }
2278
James Conroy05102392020-06-24 15:39:55 +01002279 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002280 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01002281 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
2282
2283 IConnectableLayer* layer = m_Network->AddResizeLayer(desc, layerName.c_str());
2284 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002285 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2286
2287 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2288 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2289
2290 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2291 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2292}
2293
Kevin May7d96b162021-02-03 17:38:41 +00002294void TfLiteParserImpl::ParseConcatenation(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan479045b2018-10-01 11:51:37 +01002295{
2296 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2297
2298 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2299 const auto * options = operatorPtr->builtin_options.AsConcatenationOptions();
2300
2301 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
2302
2303 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2304 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2305 CHECK_VALID_SIZE(outputs.size(), 1);
2306
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002307 unsigned int numConcatView = static_cast<unsigned int>(inputs.size());
2308 uint32_t inputRank = ToTensorInfo(inputs[0]).GetNumDimensions();
Sadik Armagan479045b2018-10-01 11:51:37 +01002309
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002310 const unsigned int concatDimInput = static_cast<unsigned int>(
2311 (static_cast<int>(inputRank) + options->axis) % static_cast<int>(inputRank));
Sadik Armagan479045b2018-10-01 11:51:37 +01002312
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002313 OriginsDescriptor concatDescriptor(static_cast<uint32_t>(numConcatView), inputRank);
2314 concatDescriptor.SetConcatAxis(concatDimInput);
Sadik Armagan479045b2018-10-01 11:51:37 +01002315
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002316 unsigned int mergeDimOrigin = 0;
Sadik Armagan479045b2018-10-01 11:51:37 +01002317
2318 for (unsigned int viewIndex = 0; viewIndex < numConcatView; ++viewIndex)
2319 {
2320 TensorInfo inputTensorInfo = ToTensorInfo(inputs[viewIndex]);
2321
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002322 // This set up concatDescriptor view origin
2323 armnnUtils::ProcessConcatInputTensorInfo(
2324 inputTensorInfo, concatDescriptor, concatDimInput, viewIndex, mergeDimOrigin);
Sadik Armagan479045b2018-10-01 11:51:37 +01002325 }
2326
James Ward58dec6b2020-09-11 17:32:44 +01002327 auto layerName = fmt::format("Concatenation:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002328 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01002329
Jim Flynn906f9462019-05-10 13:55:21 +01002330 IConnectableLayer* layer = m_Network->AddConcatLayer(concatDescriptor, layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002331 ARMNN_ASSERT(layer != nullptr);
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002332 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Sadik Armagan479045b2018-10-01 11:51:37 +01002333
James Conroy05102392020-06-24 15:39:55 +01002334 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002335 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
Sadik Armagan479045b2018-10-01 11:51:37 +01002336
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002337 // add fused activation layer
2338 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Sadik Armagan479045b2018-10-01 11:51:37 +01002339
Sadik Armagan479045b2018-10-01 11:51:37 +01002340 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2341 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2342}
2343
Kevin May7d96b162021-02-03 17:38:41 +00002344void TfLiteParserImpl::ParseFullyConnected(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002345{
2346 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2347
2348 const auto & operatorRfr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2349 const auto options = operatorRfr->builtin_options.AsFullyConnectedOptions();
2350
2351 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
2352
2353 FullyConnectedDescriptor desc;
2354 desc.m_BiasEnabled = false;
Nattapat Chaimanowongd8eee592018-10-26 10:24:14 +01002355 desc.m_TransposeWeightMatrix = true;
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002356
2357 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2358 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2359 CHECK_VALID_SIZE(outputs.size(), 1);
2360
2361 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
2362
2363 // Fully Connected Layer accepts two dimensional weights input
2364 int32_t weightsDimension = static_cast<int32_t>(filterTensorInfo.GetNumDimensions());
2365 if (weightsDimension != 2)
2366 {
2367 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002368 fmt::format("Dimension {} for Fully Connected weights is not supported by Armnn. "
2369 "Node {}",
2370 weightsDimension,
2371 CHECK_LOCATION().AsString()));
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002372 }
2373
Matthew Jackson74bf7da2019-08-16 16:51:42 +01002374 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01002375 auto layerName = fmt::format("FullyConnected:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002376
Finn Williamsd4fa5452021-03-01 12:31:41 +00002377 Optional<ConstTensor> filterOptionalConstTensor;
2378
2379 desc.m_ConstantWeights = IsConstTensor(inputs[1]);
2380
2381 // Either both weights and biases need to be inputs or both weights and biases need to be constant
2382 if (inputs.size() == 3 && desc.m_ConstantWeights != IsConstTensor(inputs[2]))
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002383 {
Finn Williamsd4fa5452021-03-01 12:31:41 +00002384 throw ParseException(
2385 fmt::format("Weights and bias are not compatible."
2386 "Node {}",
2387 CHECK_LOCATION().AsString()));
2388 }
2389
2390 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2391 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0]};
2392 if (desc.m_ConstantWeights)
2393 {
2394 filterOptionalConstTensor = Optional<ConstTensor>(CreateConstTensorNonPermuted(inputs[1], filterTensorInfo));
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002395 }
2396 else
2397 {
Finn Williamsd4fa5452021-03-01 12:31:41 +00002398 // Non const weights will need to be registered as inputs
2399 tensorIndexesToRegister.emplace_back(inputTensorIndexes[1]);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002400 }
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002401
Finn Williamsd4fa5452021-03-01 12:31:41 +00002402 Optional<ConstTensor> biasOptionalConstTensor;
2403 if (inputs.size() == 3)
2404 {
2405 desc.m_BiasEnabled = true;
2406 if (desc.m_ConstantWeights)
2407 {
2408 TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
2409 biasOptionalConstTensor = Optional<ConstTensor>(CreateConstTensorNonPermuted(inputs[2], biasTensorInfo));
2410 }
2411 else
2412 {
2413 // Non const biases will need to be registered as inputs
2414 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
2415 }
2416 }
2417
2418 layer = m_Network->AddFullyConnectedLayer(desc,
2419 filterOptionalConstTensor,
2420 biasOptionalConstTensor,
2421 layerName.c_str());
2422
2423 ARMNN_ASSERT(layer != nullptr);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002424 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2425
Finn Williamsd4fa5452021-03-01 12:31:41 +00002426 unsigned int startingSlotIndex = 0;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002427 if (inputTensorInfo.GetNumDimensions() > 2)
2428 {
2429 // Add reshape to flatten to 2D [batch_size, input_size],
2430 // where "input_size" corresponds to the number of inputs to the layer,
2431 // matching the second dimension of weights,
2432 // and "batch_size" is calculated by dividing the number of elements by "input_size".
2433 std::vector<unsigned int> reshapedDimensions(2);
2434 reshapedDimensions[1] = filterTensorInfo.GetShape()[1];
2435 reshapedDimensions[0] = inputTensorInfo.GetNumElements() / reshapedDimensions[1];
2436
2437 if (inputTensorInfo.GetNumElements() % reshapedDimensions[1] != 0)
2438 {
2439 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002440 fmt::format("Failed to deduce input tensor shape from filter size {} {}",
2441 reshapedDimensions[1],
2442 CHECK_LOCATION().AsString()));
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002443 }
2444
2445 armnn::TensorInfo reshapedTensorInfo = ToTensorInfo(inputs[0]);
2446 reshapedTensorInfo.SetShape(armnn::TensorShape{ 2, reshapedDimensions.data() });
2447
James Ward58dec6b2020-09-11 17:32:44 +01002448 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Finn Williamsd4fa5452021-03-01 12:31:41 +00002449 armnn::ReshapeDescriptor reshapeDescriptor;
2450 reshapeDescriptor.m_TargetShape = reshapedTensorInfo.GetShape();
2451 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(reshapeDescriptor, layerName.c_str());
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002452
2453 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedTensorInfo);
2454 reshapeLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(0));
2455
2456 RegisterInputSlots(subgraphIndex, operatorIndex, reshapeLayer, {inputTensorIndexes[0]});
Finn Williamsd4fa5452021-03-01 12:31:41 +00002457 // Fc layer connects to the reshape layer, so we skip the first input slot when registering fc's input slots
2458 tensorIndexesToRegister.erase(tensorIndexesToRegister.begin());
2459 startingSlotIndex = 1;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002460 }
Finn Williamsd4fa5452021-03-01 12:31:41 +00002461
2462 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister, startingSlotIndex);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002463
Sadik Armagand109a4d2020-07-28 10:42:13 +01002464 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002465 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2466
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002467 // we need to add the activation layer and fortunately we don't need to care about the data layout
2468 armnn::IConnectableLayer* fusedActivationLayer = AddFusedActivationLayer(layer, 0,
2469 options->fused_activation_function);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002470
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002471 // register the output connection slots for the layer, connections are made after all layers have been created
2472 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2473 RegisterOutputSlots(subgraphIndex, operatorIndex, fusedActivationLayer, {outputTensorIndexes[0]});
2474}
2475
Kevin May7d96b162021-02-03 17:38:41 +00002476void TfLiteParserImpl::ParseDetectionPostProcess(size_t subgraphIndex, size_t operatorIndex)
keidav011b3e2ea2019-02-21 10:07:37 +00002477{
2478 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2479
2480 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2481
2482 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2483 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2484 CHECK_VALID_SIZE(outputs.size(), 4);
2485
2486 // Obtain custom options from flexbuffers
2487 auto custom_options = operatorPtr->custom_options;
2488 const flexbuffers::Map& m = flexbuffers::GetRoot(custom_options.data(), custom_options.size()).AsMap();
2489
2490 // Obtain descriptor information from tf lite
2491 DetectionPostProcessDescriptor desc;
2492 desc.m_MaxDetections = m["max_detections"].AsUInt32();
2493 desc.m_MaxClassesPerDetection = m["max_classes_per_detection"].AsUInt32();
2494 desc.m_NmsScoreThreshold = m["nms_score_threshold"].AsFloat();
2495 desc.m_NmsIouThreshold = m["nms_iou_threshold"].AsFloat();
2496 desc.m_NumClasses = m["num_classes"].AsUInt32();
2497 desc.m_ScaleH = m["h_scale"].AsFloat();
2498 desc.m_ScaleW = m["w_scale"].AsFloat();
2499 desc.m_ScaleX = m["x_scale"].AsFloat();
2500 desc.m_ScaleY = m["y_scale"].AsFloat();
2501
keidav0107d58c72019-02-26 11:57:39 +00002502 if (!(m["use_regular_nms"].IsNull()))
keidav011b3e2ea2019-02-21 10:07:37 +00002503 {
keidav0107d58c72019-02-26 11:57:39 +00002504 desc.m_UseRegularNms = m["use_regular_nms"].AsBool();
keidav011b3e2ea2019-02-21 10:07:37 +00002505 }
2506 if (!(m["detections_per_class"].IsNull()))
2507 {
2508 desc.m_DetectionsPerClass = m["detections_per_class"].AsUInt32();
2509 }
2510
2511 if (desc.m_NmsIouThreshold <= 0.0f || desc.m_NmsIouThreshold > 1.0f)
2512 {
2513 throw InvalidArgumentException("DetectionPostProcessTFLiteParser: Intersection over union threshold "
2514 "must be positive and less than or equal to 1.");
2515 }
2516
2517 armnn::TensorInfo anchorTensorInfo = ToTensorInfo(inputs[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00002518 auto anchorTensorAndData = CreateConstTensorNonPermuted(inputs[2], anchorTensorInfo);
keidav011b3e2ea2019-02-21 10:07:37 +00002519
James Ward58dec6b2020-09-11 17:32:44 +01002520 auto layerName = fmt::format("DetectionPostProcess:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsd4fa5452021-03-01 12:31:41 +00002521 IConnectableLayer* layer = m_Network->AddDetectionPostProcessLayer(desc, anchorTensorAndData,
keidav011b3e2ea2019-02-21 10:07:37 +00002522 layerName.c_str());
2523
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002524 ARMNN_ASSERT(layer != nullptr);
keidav011b3e2ea2019-02-21 10:07:37 +00002525
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00002526 // The model does not specify the output shapes.
2527 // The output shapes are calculated from the max_detection and max_classes_per_detection.
2528 unsigned int numDetectedBox = desc.m_MaxDetections * desc.m_MaxClassesPerDetection;
2529 m_OverridenOutputShapes.push_back({ 1, numDetectedBox, 4 });
2530 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
2531 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
2532 m_OverridenOutputShapes.push_back({ 1 });
2533
keidav011b3e2ea2019-02-21 10:07:37 +00002534 for (unsigned int i = 0 ; i < outputs.size() ; ++i)
2535 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00002536 armnn::TensorInfo detectionBoxOutputTensorInfo = ToTensorInfo(outputs[i], m_OverridenOutputShapes[i]);
keidav011b3e2ea2019-02-21 10:07:37 +00002537 layer->GetOutputSlot(i).SetTensorInfo(detectionBoxOutputTensorInfo);
2538 }
2539
2540 // Register the input connection slots for the layer, connections are made after all layers have been created
2541 // only the tensors for the inputs are relevant, exclude the const tensors
2542 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2543 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2544
2545 // Register the output connection slots for the layer, connections are made after all layers have been created
2546 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2547 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0],
2548 outputTensorIndexes[1],
2549 outputTensorIndexes[2],
2550 outputTensorIndexes[3]});
2551}
2552
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002553/// The TfLite Pack operator is equivalent to the ArmNN Stack operator
Kevin May7d96b162021-02-03 17:38:41 +00002554void TfLiteParserImpl::ParsePack(size_t subgraphIndex, size_t operatorIndex)
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002555{
2556 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2557
2558 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2559 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2560 CHECK_VALID_SIZE(outputs.size(), 1);
2561
2562 if (inputs.size() < 1)
2563 {
2564 throw ParseException("Pack must have at least one input.");
2565 }
2566
2567 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2568 const auto* options = operatorPtr->builtin_options.AsPackOptions();
2569
2570 StackDescriptor desc;
2571 desc.m_Axis = static_cast<uint32_t>(options->axis);
2572 desc.m_NumInputs = static_cast<uint32_t>(inputs.size());
2573
2574 // Use the tensor shape of the first input as the "correct" input shape in the descriptor
2575 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2576 desc.m_InputShape = inputTensorInfo.GetShape();
2577
James Ward58dec6b2020-09-11 17:32:44 +01002578 auto layerName = fmt::format("Pack:{}:{}", subgraphIndex, operatorIndex);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002579 IConnectableLayer* layer = m_Network->AddStackLayer(desc, layerName.c_str());
2580
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002581 ARMNN_ASSERT(layer != nullptr);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002582
Sadik Armagand109a4d2020-07-28 10:42:13 +01002583 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002584 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2585
2586 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2587 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
2588
2589 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2590 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2591}
2592
Kevin May7d96b162021-02-03 17:38:41 +00002593void TfLiteParserImpl::ParseUnpack(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd200e3802019-04-15 09:47:39 +01002594{
2595 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2596
2597 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2598 const auto * options = operatorPtr->builtin_options.AsUnpackOptions();
2599
2600 // This unpackAxis indicates the axis to unpack
2601 const unsigned int unpackAxis = CHECKED_NON_NEGATIVE(options->axis);
2602
2603 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2604 CHECK_VALID_SIZE(inputs.size(), 1);
2605
2606 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002607
2608 if (unpackAxis >= inputTensorInfo.GetNumDimensions())
2609 {
2610 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002611 fmt::format("The unpack axis: {} cannot be greater than or equal to "
2612 "the number of input dimension {} {}",
2613 unpackAxis,
2614 inputTensorInfo.GetNumDimensions(),
2615 CHECK_LOCATION().AsString()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002616 }
2617
Nina Drozd200e3802019-04-15 09:47:39 +01002618 unsigned int unpackNum = CHECKED_NON_NEGATIVE(options->num);
2619 // If num is not defined, automatically infer from the length of the dimension axis.
2620 if(unpackNum == 0)
2621 {
2622 unpackNum = inputTensorInfo.GetShape()[unpackAxis];
2623 }
2624
2625 // If unpack number cannot be inferred and is still zero, throw ParseException.
2626 if(unpackNum == 0)
2627 {
2628 throw ParseException("Number to unpack must greater than zero.");
2629 }
2630
2631 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2632 CHECK_VALID_SIZE(outputs.size(), unpackNum);
2633
2634 auto inputDimSize = inputTensorInfo.GetNumDimensions();
2635 std::vector<unsigned int> unpackDimSizes(inputDimSize);
2636
2637 // Add current input shape to unpackDimSizes
2638 for (unsigned int i = 0; i < inputDimSize; ++i)
2639 {
2640 unpackDimSizes[i] = inputTensorInfo.GetShape()[i];
2641 }
2642
2643 if (unpackDimSizes[unpackAxis] != unpackNum)
2644 {
2645 throw ParseException("Number to unpack must be the same as length of the dimension to "
2646 "unpack along.");
2647 }
2648
2649 unpackDimSizes[unpackAxis] /= unpackNum;
2650
2651 SplitterDescriptor splitDesc(unpackNum, static_cast<unsigned int>(unpackDimSizes.size()));
2652 for (unsigned int j = 0; j < unpackNum; ++j)
2653 {
2654 // Set the size of the views.
2655 for (unsigned int dimIdx = 0; dimIdx < unpackDimSizes.size(); ++dimIdx)
2656 {
2657 splitDesc.SetViewSize(j, dimIdx, unpackDimSizes[dimIdx]);
2658 }
2659 splitDesc.SetViewOriginCoord(j, unpackAxis, unpackDimSizes[unpackAxis] * j);
2660 }
2661
James Ward58dec6b2020-09-11 17:32:44 +01002662 auto layerName = fmt::format("Unpack:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd200e3802019-04-15 09:47:39 +01002663 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002664 ARMNN_ASSERT(layer != nullptr);
Nina Drozd200e3802019-04-15 09:47:39 +01002665
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002666 TensorShape splitOutShape = TensorShape(static_cast<unsigned int>(unpackDimSizes.size()),
2667 unpackDimSizes.data());
2668
Nina Drozd200e3802019-04-15 09:47:39 +01002669 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2670 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2671
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002672 // Create reshape to remove the unpacked dimension for unpack operator of each output from Splitter.
2673 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
2674 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01002675 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[k], true);
James Ward58dec6b2020-09-11 17:32:44 +01002676 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002677 armnn::ReshapeDescriptor desc;
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01002678 desc.m_TargetShape = outputTensorInfo.GetShape();
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002679 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(desc, layerName.c_str());
2680
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01002681 layer->GetOutputSlot(k).SetTensorInfo(armnn::TensorInfo(splitOutShape,
2682 outputTensorInfo.GetDataType(),
2683 outputTensorInfo.GetQuantizationScale(),
2684 outputTensorInfo.GetQuantizationOffset()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002685 layer->GetOutputSlot(k).Connect(reshapeLayer->GetInputSlot(0));
2686
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01002687 reshapeLayer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002688
2689 uint32_t reshapedOutputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[k]);
2690 armnn::IOutputSlot* slot = &(reshapeLayer->GetOutputSlot(0));
2691 RegisterProducerOfTensor(subgraphIndex, reshapedOutputId, slot);
2692 }
Nina Drozd200e3802019-04-15 09:47:39 +01002693}
2694
Kevin May7d96b162021-02-03 17:38:41 +00002695void TfLiteParserImpl::ParseSplit(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd0324f482019-04-08 10:52:10 +01002696{
2697 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2698
2699 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2700 const auto * options = operatorPtr->builtin_options.AsSplitOptions();
2701
2702 const unsigned int numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
2703
Nina Drozd200e3802019-04-15 09:47:39 +01002704 // If number of splits cannot be inferred and is zero, throw ParseException.
2705 if(numSplits == 0)
2706 {
2707 throw ParseException("Number to splits must greater than zero.");
2708 }
2709
Nina Drozd0324f482019-04-08 10:52:10 +01002710 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2711 CHECK_VALID_SIZE(inputs.size(), 2);
2712 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2713 CHECK_VALID_SIZE(outputs.size(), numSplits);
2714
Matthew Sloyaned7fce42021-04-15 20:46:24 +01002715 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[1]);
2716 armnn::TensorInfo axisTensorInfo = ToTensorInfo(inputs[0]);
2717 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
Nina Drozd0324f482019-04-08 10:52:10 +01002718
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002719 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01002720 if (axisBufferPtr == nullptr)
2721 {
2722 throw ParseException(
2723 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
2724 CHECK_LOCATION().AsString()));
2725 }
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002726
Matthew Sloyaned7fce42021-04-15 20:46:24 +01002727 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
2728 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
2729 int32_t axis = axisData[0];
2730
2731 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
2732 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
2733 {
2734 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
2735 // E.g. Rank 4 tensor can have axis in range [-4, 3)
2736 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
2737 throw ParseException(
2738 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
2739 axis,
2740 CHECK_LOCATION().AsString()));
2741 }
2742
2743 const unsigned int splitDim = armnnUtils::GetUnsignedAxis(inputTensorInfo.GetNumDimensions(), axis);
Nina Drozd0324f482019-04-08 10:52:10 +01002744
Nina Drozd0324f482019-04-08 10:52:10 +01002745 auto inputDimSize = inputTensorInfo.GetNumDimensions();
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002746 if (inputDimSize > MaxNumOfTensorDimensions)
Nina Drozd0324f482019-04-08 10:52:10 +01002747 {
2748 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002749 fmt::format("The number of dimensions: {} for input tensors of the split op cannot be greater than {} {}",
2750 inputTensorInfo.GetNumDimensions(),
2751 MaxNumOfTensorDimensions,
2752 CHECK_LOCATION().AsString()));
Nina Drozd0324f482019-04-08 10:52:10 +01002753 }
2754
2755 std::vector<unsigned int> splitterDimSizes(inputDimSize);
2756
2757 // Add current input shape to splitterDimSizes
2758 for (unsigned int i = 0; i < inputDimSize; ++i)
2759 {
2760 splitterDimSizes[i] = inputTensorInfo.GetShape()[i];
2761 }
2762
2763 if (splitterDimSizes[splitDim] % numSplits != 0)
2764 {
2765 throw ParseException("Number of splits must evenly divide the dimension");
2766 }
2767 splitterDimSizes[splitDim] /= numSplits;
2768
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002769 SplitterDescriptor splitDesc(numSplits, inputDimSize);
Nina Drozd0324f482019-04-08 10:52:10 +01002770 for (unsigned int j = 0; j < numSplits; ++j)
2771 {
2772 // Set the size of the views.
2773 for (unsigned int dimIdx = 0; dimIdx < splitterDimSizes.size(); ++dimIdx)
2774 {
2775 splitDesc.SetViewSize(j, dimIdx, splitterDimSizes[dimIdx]);
2776 }
2777 splitDesc.SetViewOriginCoord(j, splitDim, splitterDimSizes[splitDim] * j);
2778 }
2779
James Ward58dec6b2020-09-11 17:32:44 +01002780 auto layerName = fmt::format("Split:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd0324f482019-04-08 10:52:10 +01002781 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002782 ARMNN_ASSERT(layer != nullptr);
Nina Drozd0324f482019-04-08 10:52:10 +01002783
2784 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002785 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[1]});
Nina Drozd0324f482019-04-08 10:52:10 +01002786
Nina Drozd0324f482019-04-08 10:52:10 +01002787 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
2788 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01002789 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Francis Murtagh98d6b3d2019-10-21 10:52:54 +01002790 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
Nina Drozd0324f482019-04-08 10:52:10 +01002791 }
2792
2793 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2794 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2795}
2796
Derek Lambertif0176992020-04-28 13:37:49 +01002797unsigned int ComputeWrappedIndex(int idx, unsigned int numDimsIn)
2798{
2799 int numDims = armnn::numeric_cast<int>(numDimsIn);
2800 int v = idx < 0 ? numDims + idx : idx;
2801 ARMNN_ASSERT(v >= 0);
2802 ARMNN_ASSERT(v < numDims);
2803
2804 return static_cast<unsigned int>(v);
2805}
2806
Kevin May7d96b162021-02-03 17:38:41 +00002807void TfLiteParserImpl::ParseSplitV(size_t subgraphIndex, size_t operatorIndex)
Derek Lambertif0176992020-04-28 13:37:49 +01002808{
2809 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2810
2811 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Ryan OShea86704732020-05-26 11:41:04 +01002812 const auto * options = operatorPtr->builtin_options.AsSplitVOptions();
Derek Lambertif0176992020-04-28 13:37:49 +01002813
2814 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2815 CHECK_VALID_SIZE(inputs.size(), 3);
2816
2817 auto& inputTensor = inputs[0];
2818 auto& splitsTensor = inputs[1];
2819 auto& axisTensor = inputs[2];
2820
2821 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputTensor);
2822 armnn::TensorInfo splitsInfo = ToTensorInfo(splitsTensor);
2823 armnn::TensorInfo axisTensorInfo = ToTensorInfo(axisTensor);
2824 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
2825
2826 // Inputs
2827 auto inputDimSize = inputTensorInfo.GetNumDimensions();
2828 if (inputDimSize > MaxNumOfTensorDimensions)
2829 {
2830 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002831 fmt::format("The number of dimensions: {} for input tensors of the "
2832 "SplitV op cannot be greater than {} {}",
2833 inputTensorInfo.GetNumDimensions(),
2834 MaxNumOfTensorDimensions,
2835 CHECK_LOCATION().AsString()));
Derek Lambertif0176992020-04-28 13:37:49 +01002836 }
2837
2838 // Get split axis
2839 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, axisTensor->buffer);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01002840 if (axisBufferPtr == nullptr)
2841 {
2842 throw ParseException(
2843 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
2844 CHECK_LOCATION().AsString()));
2845 }
2846
Derek Lambertif0176992020-04-28 13:37:49 +01002847 std::vector<int> axisData(axisTensorInfo.GetNumElements());
2848 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
Matthew Sloyaned7fce42021-04-15 20:46:24 +01002849 int32_t axis = axisData[0];
2850
2851 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
2852 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
2853 {
2854 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
2855 // E.g. Rank 4 tensor can have axis in range [-4, 3)
2856 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
2857 throw ParseException(
2858 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
2859 axis,
2860 CHECK_LOCATION().AsString()));
2861 }
2862 const unsigned int splitDim = ComputeWrappedIndex(axis, inputTensorInfo.GetNumDimensions());
Derek Lambertif0176992020-04-28 13:37:49 +01002863
Derek Lambertif0176992020-04-28 13:37:49 +01002864 // Set split sizes
Derek Lambertif0176992020-04-28 13:37:49 +01002865 CHECK_VALID_SIZE(splitsInfo.GetNumDimensions(), 1);
Ryan OShea86704732020-05-26 11:41:04 +01002866 unsigned int numSplits{0};
2867
2868 if(options)
Derek Lambertif0176992020-04-28 13:37:49 +01002869 {
2870 numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
Derek Lambertif0176992020-04-28 13:37:49 +01002871 }
2872 else
2873 {
Ryan OShea86704732020-05-26 11:41:04 +01002874 numSplits = splitsInfo.GetNumElements();
Derek Lambertif0176992020-04-28 13:37:49 +01002875 }
2876
2877 if (numSplits <=0)
2878 {
2879 throw ParseException("SplitV has invalid number of splits");
2880 }
2881
Jan Eilersc0761e92020-06-29 16:48:44 +01002882 std::vector<int> splitsData(numSplits);
Ryan OShea86704732020-05-26 11:41:04 +01002883 BufferRawPtr splitsBufferPtr = GetBuffer(m_Model, splitsTensor->buffer);
Jan Eilersc0761e92020-06-29 16:48:44 +01002884 ::memcpy(splitsData.data(), splitsBufferPtr->data.data(), splitsInfo.GetNumBytes());
Ryan OShea86704732020-05-26 11:41:04 +01002885
Jan Eilersc0761e92020-06-29 16:48:44 +01002886 unsigned int idx = 0;
Ryan OShea86704732020-05-26 11:41:04 +01002887 int numInferred{0};
2888 unsigned int inferIdx{0};
2889 int splitSum{0};
2890 for (auto split : splitsData)
2891 {
2892 if (split < 0)
2893 {
2894 numInferred++;
2895 inferIdx = idx;
2896 }
2897 else
2898 {
2899 splitSum += split;
2900 }
2901 idx++;
2902 }
2903 // Check for inferred Axis
2904 if (numInferred == 0)
2905 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002906 if (splitSum != armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]))
Ryan OShea86704732020-05-26 11:41:04 +01002907 {
2908 throw ParseException("SplitV split_sizes does not sum to the dimension of value along split_dim.");
2909 }
2910 }
2911 else if (numInferred == 1)
2912 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002913 splitsData[inferIdx] = armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]) - splitSum;
Ryan OShea86704732020-05-26 11:41:04 +01002914 }
2915 else
2916 {
2917 throw ParseException("Cannot infer split size for more than one split");
2918 }
2919
Derek Lambertif0176992020-04-28 13:37:49 +01002920 //Ouput size validation
2921 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2922 CHECK_VALID_SIZE(outputs.size(), numSplits);
2923
2924 // Setup Armnn descriptor
2925 SplitterDescriptor splitDesc(numSplits, inputDimSize);
2926 unsigned int accumSplit = 0;
2927 for (unsigned int j = 0; j < numSplits; ++j)
2928 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002929 unsigned int splitSize = armnn::numeric_cast<unsigned int>(splitsData[j]);
Derek Lambertif0176992020-04-28 13:37:49 +01002930
2931 // Set the size of the views.
2932 for (unsigned int dimIdx = 0; dimIdx < inputTensorInfo.GetNumDimensions(); ++dimIdx)
2933 {
2934 unsigned int dimSize = inputTensorInfo.GetShape()[dimIdx];
2935 if (dimIdx == splitDim)
2936 {
2937 dimSize = splitSize;
2938 }
2939 splitDesc.SetViewSize(j, dimIdx, dimSize);
2940 }
2941
2942 splitDesc.SetViewOriginCoord(j, splitDim, accumSplit);
2943 accumSplit += splitSize;
2944 }
2945
James Ward58dec6b2020-09-11 17:32:44 +01002946 auto layerName = fmt::format("SplitV:{}:{}", subgraphIndex, operatorIndex);
Derek Lambertif0176992020-04-28 13:37:49 +01002947 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002948 ARMNN_ASSERT(layer != nullptr);
Derek Lambertif0176992020-04-28 13:37:49 +01002949
2950 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2951 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2952
2953 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
2954 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01002955 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Derek Lambertif0176992020-04-28 13:37:49 +01002956 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
2957 }
2958
2959 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2960 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2961}
2962
Matthew Sloyan28f177c2021-04-09 14:38:52 +01002963void TfLiteParserImpl::ParseArgMin(size_t subgraphIndex, size_t operatorIndex)
2964{
2965 ParseArgMinMax(subgraphIndex, operatorIndex, armnn::ArgMinMaxFunction::Min);
2966}
2967
Kevin May7d96b162021-02-03 17:38:41 +00002968void TfLiteParserImpl::ParseArgMax(size_t subgraphIndex, size_t operatorIndex)
Inki Daed4619e22020-09-10 15:33:54 +09002969{
Matthew Sloyan28f177c2021-04-09 14:38:52 +01002970 ParseArgMinMax(subgraphIndex, operatorIndex, armnn::ArgMinMaxFunction::Max);
2971}
2972
2973void TfLiteParserImpl::ParseArgMinMax(size_t subgraphIndex, size_t operatorIndex, ArgMinMaxFunction argMinMaxFunction)
2974{
Inki Daed4619e22020-09-10 15:33:54 +09002975 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2976 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2977 CHECK_VALID_SIZE(inputs.size(), 2);
2978
2979 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2980 CHECK_VALID_SIZE(outputs.size(), 1);
2981
Matthew Sloyan28f177c2021-04-09 14:38:52 +01002982 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2983 armnn::TensorInfo axisTensorInfo = ToTensorInfo(inputs[1]);
Inki Daed4619e22020-09-10 15:33:54 +09002984 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01002985 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
Matthew Sloyan28f177c2021-04-09 14:38:52 +01002986
2987 // Check if output tensor type is Signed32 or Signed64
Mike Kelly1f140f72021-04-06 12:25:55 +01002988 if (outputTensorInfo.GetDataType() != armnn::DataType::Signed32 &&
2989 outputTensorInfo.GetDataType() != armnn::DataType::Signed64)
2990 {
2991 throw ParseException(
2992 fmt::format(
2993 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
2994 CHECK_LOCATION().AsString()));
2995 }
Matthew Sloyan28f177c2021-04-09 14:38:52 +01002996
2997 // Get const axis value from model and set it to descriptor.
2998 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2999 if (axisBufferPtr == nullptr)
3000 {
3001 throw ParseException(
3002 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
3003 CHECK_LOCATION().AsString()));
3004 }
3005
3006 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
3007 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
3008 int32_t axis = axisData.front();
3009
3010 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3011 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3012 {
3013 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
3014 // E.g. Rank 4 tensor can have axis in range [-4, 3)
3015 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
3016 throw ParseException(
3017 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3018 axis,
3019 CHECK_LOCATION().AsString()));
3020 }
3021
3022 ArgMinMaxDescriptor desc;
3023 desc.m_Axis = axis;
3024 desc.m_Function = argMinMaxFunction;
3025
3026 // Register a ArgMin/ArgMax layer.
3027 auto layerName = argMinMaxFunction == ArgMinMaxFunction::Max ? "ArgMax:{}:{}" : "ArgMin:{}:{}";
3028 auto layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
3029 IConnectableLayer *layer = m_Network->AddArgMinMaxLayer(desc, layerNameFormatted.c_str());
3030 ARMNN_ASSERT(layer != nullptr);
Inki Daed4619e22020-09-10 15:33:54 +09003031 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3032
3033 // Register input tensor to the layer.
3034 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3035 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3036
3037 // Register output tensor to the layer.
3038 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3039 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3040}
3041
Kevin May7d96b162021-02-03 17:38:41 +00003042void TfLiteParserImpl::ParseGather(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00003043{
3044 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3045
Kevin May7d96b162021-02-03 17:38:41 +00003046 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00003047 CHECK_VALID_SIZE(inputs.size(), 2);
Kevin May7d96b162021-02-03 17:38:41 +00003048 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00003049 CHECK_VALID_SIZE(outputs.size(), 1);
3050
3051 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3052 armnn::TensorInfo indicesTensorInfo = ToTensorInfo(inputs[1]);
3053 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
3054
3055 armnn::GatherDescriptor gatherDescriptor;
3056
3057 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3058 const auto * options = operatorPtr->builtin_options.AsGatherOptions();
3059 auto axis = options->axis;
3060
3061 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3062 auto indicesDimensions = indicesTensorInfo.GetNumDimensions();
3063 auto outputDimensions = outputTensorInfo.GetNumDimensions();
3064 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3065 {
3066 throw ParseException(
3067 fmt::format("Operation has invalid axis: {} It is out of bounds [ -{}, {} ) {}",
3068 axis,
3069 inputDimensions, inputDimensions,
3070 CHECK_LOCATION().AsString()));
3071 }
3072 if (outputDimensions != static_cast<unsigned int>(inputDimensions) + indicesDimensions - 1)
3073 {
3074 throw ParseException(
3075 fmt::format("Operation has invalid output dimensions: {} Output must be an ({} + {} - 1) -D tensor {}",
3076 outputDimensions,
3077 inputDimensions, indicesDimensions,
3078 CHECK_LOCATION().AsString()));
3079 }
3080
3081 gatherDescriptor.m_Axis = axis;
3082
3083 auto layerName = fmt::format("Gather:{}:{}", subgraphIndex, operatorIndex);
3084 IConnectableLayer* layer = m_Network->AddGatherLayer(gatherDescriptor, layerName.c_str());
3085 ARMNN_ASSERT(layer != nullptr);
3086 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3087
3088 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3089 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
3090
3091 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3092 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3093}
3094
Kevin May7d96b162021-02-03 17:38:41 +00003095void TfLiteParserImpl::ParseDepthToSpace(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00003096{
3097 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3098
Kevin May7d96b162021-02-03 17:38:41 +00003099 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00003100 CHECK_VALID_SIZE(inputs.size(), 1);
Kevin May7d96b162021-02-03 17:38:41 +00003101 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00003102 CHECK_VALID_SIZE(outputs.size(), 1);
3103
3104 armnn::DepthToSpaceDescriptor descriptor;
3105
3106 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3107 const auto * options = operatorPtr->builtin_options.AsDepthToSpaceOptions();
3108 auto blockSize = options->block_size;
3109 if (blockSize < 2)
3110 {
3111 throw ParseException(
3112 fmt::format("Operation has invalid block size: {} Block size should be >= 2 {}",
3113 blockSize,
3114 CHECK_LOCATION().AsString()));
3115 }
3116 descriptor.m_BlockSize = armnn::numeric_cast<uint32_t>(blockSize);
3117
3118 auto layerName = fmt::format("DepthToSpace:{}:{}", subgraphIndex, operatorIndex);
3119 IConnectableLayer* layer = m_Network->AddDepthToSpaceLayer(descriptor, layerName.c_str());
3120 ARMNN_ASSERT(layer != nullptr);
3121 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
3122 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3123
3124 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3125 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3126
3127 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3128 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3129}
3130
Kevin May7d96b162021-02-03 17:38:41 +00003131void TfLiteParserImpl::ParseSum(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003132{
Sadik Armagana2747482021-02-09 10:28:54 +00003133 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Sum);
3134}
3135
3136void TfLiteParserImpl::ParseReduceMax(size_t subgraphIndex, size_t operatorIndex)
3137{
3138 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Max);
3139}
3140
3141void TfLiteParserImpl::ParseReduceMin(size_t subgraphIndex, size_t operatorIndex)
3142{
3143 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Min);
3144}
3145
3146void TfLiteParserImpl::ParseReduce(size_t subgraphIndex, size_t operatorIndex, ReduceOperation reduceOperation)
3147{
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003148 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3149
3150 const auto &operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3151 const auto *options = operatorPtr->builtin_options.AsReducerOptions();
3152
3153 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3154 CHECK_VALID_SIZE(inputs.size(), 2);
3155
3156 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3157 CHECK_VALID_SIZE(outputs.size(), 1);
3158
Sadik Armagana2747482021-02-09 10:28:54 +00003159 auto layerName = fmt::format("Reduce:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003160
3161 armnn::TensorInfo inputTensorInfo0 = ToTensorInfo(inputs[0]);
3162 armnn::TensorInfo inputTensorInfo1 = ToTensorInfo(inputs[1]);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003163
3164 ReduceDescriptor desc;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003165 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
3166 // Get const axis value from model and set it to descriptor.
3167 if (axisBufferPtr != nullptr)
3168 {
Sadik Armagan49bdb792021-02-11 13:57:07 +00003169 std::vector<int32_t> axisData(inputTensorInfo1.GetNumElements());
3170 ::memcpy(axisData.data(), axisBufferPtr->data.data(), inputTensorInfo1.GetNumBytes());
3171
3172 // Convert the axis to unsigned int and remove duplicates.
3173 auto rank = static_cast<int32_t>(inputTensorInfo0.GetNumDimensions());
3174 std::set<unsigned int> uniqueAxis;
3175 std::transform(axisData.begin(),
3176 axisData.end(),
3177 std::inserter(uniqueAxis, uniqueAxis.begin()),
3178 [rank](int i)->unsigned int{
3179 return static_cast<uint32_t>(((i + rank) % rank)); });
3180 desc.m_vAxis.assign(uniqueAxis.begin(), uniqueAxis.end());
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003181 }
Sadik Armagana2747482021-02-09 10:28:54 +00003182 else
3183 {
3184 for (uint32_t i = 0; i < inputTensorInfo0.GetNumDimensions(); ++i)
3185 {
3186 desc.m_vAxis.push_back(i);
3187 }
3188 }
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003189
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003190 desc.m_KeepDims = options->keep_dims;
Sadik Armagana2747482021-02-09 10:28:54 +00003191 desc.m_ReduceOperation = reduceOperation;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003192
3193 // Register a new layer object, Sum.
3194 IConnectableLayer *layer = m_Network->AddReduceLayer(desc, layerName.c_str());
3195
3196 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
3197 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3198
3199 // Register input tensor to the layer.
3200 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3201 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3202
3203 // Register output tensor to the layer.
3204 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3205 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3206}
3207
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003208void TfLiteParserImpl::ParseAbs(size_t subgraphIndex, size_t operatorIndex)
3209{
3210 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Abs);
3211}
3212
3213void TfLiteParserImpl::ParseExp(size_t subgraphIndex, size_t operatorIndex)
3214{
3215 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Exp);
3216}
3217
3218void TfLiteParserImpl::ParseLogicalNot(size_t subgraphIndex, size_t operatorIndex)
3219{
3220 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::LogicalNot);
3221}
3222
3223void TfLiteParserImpl::ParseNeg(size_t subgraphIndex, size_t operatorIndex)
3224{
3225 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Neg);
3226}
3227
3228void TfLiteParserImpl::ParseRsqrt(size_t subgraphIndex, size_t operatorIndex)
3229{
3230 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Rsqrt);
3231}
3232
3233void TfLiteParserImpl::ParseElementwiseUnary(size_t subgraphIndex, size_t operatorIndex, UnaryOperation unaryOperation)
3234{
3235 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3236
3237 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3238 CHECK_VALID_SIZE(inputs.size(), 1);
3239
3240 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3241 CHECK_VALID_SIZE(outputs.size(), 1);
3242
3243 std::string layerName = std::string(GetUnaryOperationAsCString(unaryOperation)) + ":{}:{}";
3244 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
3245
3246 ElementwiseUnaryDescriptor desc;
3247 desc.m_Operation = unaryOperation;
3248 IConnectableLayer* layer = m_Network->AddElementwiseUnaryLayer(desc, layerNameFormatted.c_str());
3249 ARMNN_ASSERT(layer != nullptr);
3250
3251 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
3252 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3253
3254 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3255 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3256
3257 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3258 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3259}
3260
Kevin May7d96b162021-02-03 17:38:41 +00003261armnn::IConnectableLayer* TfLiteParserImpl::AddFusedActivationLayer(armnn::IConnectableLayer* prevLayer,
3262 unsigned int outputSlot,
3263 tflite::ActivationFunctionType activationType)
telsoa01c577f2c2018-08-31 09:22:23 +01003264{
3265 ActivationDescriptor activationDesc;
3266 std::string layerName = prevLayer->GetName();
3267
3268 switch(activationType)
3269 {
3270 case tflite::ActivationFunctionType_NONE:
3271 {
3272 // this is a no-op: return previous layer
3273 return prevLayer;
3274 }
3275 case tflite::ActivationFunctionType_RELU:
3276 {
3277 activationDesc.m_Function = ActivationFunction::ReLu;
3278 layerName += ":RELU";
3279 break;
3280 }
3281 case tflite::ActivationFunctionType_RELU6:
3282 {
3283 activationDesc.m_Function = ActivationFunction::BoundedReLu;
3284 activationDesc.m_A = 6.0f;
3285 activationDesc.m_B = 0.0f;
3286 layerName += ":RELU6";
3287 break;
3288 }
3289 case tflite::ActivationFunctionType_TANH:
3290 {
3291 activationDesc.m_Function = ActivationFunction::TanH;
3292 activationDesc.m_A = 1.0f;
3293 activationDesc.m_B = 1.0f;
3294 layerName += ":TANH";
3295 break;
3296 }
3297
3298 // I only put these here as a reminder what others we could support
3299 case tflite::ActivationFunctionType_RELU_N1_TO_1:
3300 case tflite::ActivationFunctionType_SIGN_BIT:
3301 default:
3302 {
3303 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003304 fmt::format("TfLite parser doesn't suppport fused activation: "
3305 "{}/{} {} ",
3306 activationType,
3307 tflite::EnumNameActivationFunctionType(activationType),
3308 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003309
3310 }
3311 }
3312
3313 IConnectableLayer* activationLayer =
3314 m_Network->AddActivationLayer(activationDesc, layerName.c_str());
3315
3316 auto & prevOutputSlot = prevLayer->GetOutputSlot(outputSlot);
3317 prevOutputSlot.Connect(activationLayer->GetInputSlot(0));
3318 activationLayer->GetOutputSlot(0).SetTensorInfo(prevOutputSlot.GetTensorInfo());
3319 return activationLayer;
3320}
3321
Kevin May7d96b162021-02-03 17:38:41 +00003322TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromFile(const char * fileName)
telsoa01c577f2c2018-08-31 09:22:23 +01003323{
3324 if (fileName == nullptr)
3325 {
James Ward58dec6b2020-09-11 17:32:44 +01003326 throw InvalidArgumentException(fmt::format("Invalid (null) file name {}",
telsoa01c577f2c2018-08-31 09:22:23 +01003327 CHECK_LOCATION().AsString()));
3328 }
Francis Murtagh532a29d2020-06-29 11:50:01 +01003329 std::error_code errorCode;
3330 fs::path pathToFile(fileName);
3331 if (!fs::exists(pathToFile, errorCode))
telsoa01c577f2c2018-08-31 09:22:23 +01003332 {
James Ward58dec6b2020-09-11 17:32:44 +01003333 //fmt::format() could not be used here (format error)
3334 std::stringstream msg;
3335 msg << "Cannot find the file (" << fileName << ") errorCode: " << errorCode
3336 << " " << CHECK_LOCATION().AsString();
3337
3338 throw FileNotFoundException(msg.str());
telsoa01c577f2c2018-08-31 09:22:23 +01003339 }
3340 std::ifstream file(fileName, std::ios::binary);
3341 std::string fileContent((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
3342 return LoadModelFromBinary(reinterpret_cast<const uint8_t *>(fileContent.c_str()),
3343 fileContent.size());
3344}
3345
Kevin May7d96b162021-02-03 17:38:41 +00003346TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromBinary(const uint8_t * binaryContent, size_t len)
telsoa01c577f2c2018-08-31 09:22:23 +01003347{
3348 if (binaryContent == nullptr)
3349 {
James Ward58dec6b2020-09-11 17:32:44 +01003350 throw InvalidArgumentException(fmt::format("Invalid (null) binary content {}",
telsoa01c577f2c2018-08-31 09:22:23 +01003351 CHECK_LOCATION().AsString()));
3352 }
3353 flatbuffers::Verifier verifier(binaryContent, len);
3354 if (verifier.VerifyBuffer<tflite::Model>() == false)
3355 {
3356 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003357 fmt::format("Buffer doesn't conform to the expected Tensorflow Lite "
3358 "flatbuffers format. size:{} {}",
3359 len,
3360 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003361 }
3362 return tflite::UnPackModel(binaryContent);
3363}
3364
Kevin May7d96b162021-02-03 17:38:41 +00003365TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetInputs(const ModelPtr & model,
3366 size_t subgraphIndex,
3367 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003368{
3369 CHECK_MODEL(model, subgraphIndex, operatorIndex);
3370
Derek Lambertiff05cc52019-04-26 13:05:17 +01003371 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3372 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003373
3374 size_t inputCount = operatorPtr->inputs.size();
3375 TensorRawPtrVector result(inputCount);
3376 for (size_t i=0; i<inputCount; ++i)
3377 {
3378 uint32_t inputId = CHECKED_NON_NEGATIVE(operatorPtr->inputs[i]);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003379 result[i] = subgraphPtr->tensors[inputId].get();
telsoa01c577f2c2018-08-31 09:22:23 +01003380 }
3381 return result;
3382}
3383
Kevin May7d96b162021-02-03 17:38:41 +00003384TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetOutputs(const ModelPtr & model,
3385 size_t subgraphIndex,
3386 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003387{
3388 CHECK_MODEL(model, subgraphIndex, operatorIndex);
3389
Derek Lambertiff05cc52019-04-26 13:05:17 +01003390 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3391 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003392
3393 size_t outputCount = operatorPtr->outputs.size();
3394 TensorRawPtrVector result(outputCount);
3395 for (size_t i=0; i<outputCount; ++i)
3396 {
3397 uint32_t outputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[i]);
3398 CHECK_TENSOR(model, subgraphIndex, outputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003399 result[i] = subgraphPtr->tensors[outputId].get();
telsoa01c577f2c2018-08-31 09:22:23 +01003400 }
3401 return result;
3402}
3403
Kevin May7d96b162021-02-03 17:38:41 +00003404TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphInputs(const ModelPtr & model,
3405 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003406{
3407 CHECK_SUBGRAPH(model, subgraphIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003408 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003409
Derek Lambertiff05cc52019-04-26 13:05:17 +01003410 size_t inputCount = subgraphPtr->inputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01003411 TensorIdRawPtrVector result(inputCount);
3412 for (size_t i=0; i<inputCount; ++i)
3413 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01003414 uint32_t inputId = CHECKED_NON_NEGATIVE(subgraphPtr->inputs[i]);
telsoa01c577f2c2018-08-31 09:22:23 +01003415 CHECK_TENSOR(model, subgraphIndex, inputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003416 result[i] = std::make_pair(inputId, subgraphPtr->tensors[inputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01003417 }
3418 return result;
3419}
3420
Kevin May7d96b162021-02-03 17:38:41 +00003421TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphOutputs(const ModelPtr & model,
3422 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003423{
3424 CHECK_SUBGRAPH(model, subgraphIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003425 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003426
Derek Lambertiff05cc52019-04-26 13:05:17 +01003427 size_t outputCount = subgraphPtr->outputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01003428 TensorIdRawPtrVector result(outputCount);
3429 for (size_t i=0; i<outputCount; ++i)
3430 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01003431 uint32_t outputId = CHECKED_NON_NEGATIVE(subgraphPtr->outputs[i]);
3432 result[i] = std::make_pair(outputId, subgraphPtr->tensors[outputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01003433 }
3434 return result;
3435}
3436
Kevin May7d96b162021-02-03 17:38:41 +00003437std::vector<int32_t>& TfLiteParserImpl::GetInputTensorIds(const ModelPtr& model,
3438 size_t subgraphIndex,
3439 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003440{
3441 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003442 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3443 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003444 return operatorPtr->inputs;
3445}
3446
Kevin May7d96b162021-02-03 17:38:41 +00003447std::vector<int32_t>& TfLiteParserImpl::GetOutputTensorIds(const ModelPtr& model,
3448 size_t subgraphIndex,
3449 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003450{
3451 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003452 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3453 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003454 return operatorPtr->outputs;
3455}
3456
Kevin May7d96b162021-02-03 17:38:41 +00003457void TfLiteParserImpl::RegisterInputSlots(size_t subgraphIndex,
3458 size_t operatorIndex,
3459 IConnectableLayer* layer,
Finn Williamsd4fa5452021-03-01 12:31:41 +00003460 const std::vector<unsigned int>& tensorIndexes,
3461 unsigned int startingSlotIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003462{
3463 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003464 ARMNN_ASSERT(layer != nullptr);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003465 if (tensorIndexes.size() + startingSlotIndex != layer->GetNumInputSlots())
telsoa01c577f2c2018-08-31 09:22:23 +01003466 {
3467 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003468 fmt::format("The number of tensor inputs ({}) does not match the number expected ({})"
3469 " for subgraph:{} operator index:{} {}",
3470 tensorIndexes.size(),
3471 layer->GetNumInputSlots(),
3472 subgraphIndex,
3473 operatorIndex,
3474 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003475 }
3476
Finn Williamsd4fa5452021-03-01 12:31:41 +00003477 for (unsigned int index = 0; index < tensorIndexes.size() ; ++index)
telsoa01c577f2c2018-08-31 09:22:23 +01003478 {
Finn Williamsd4fa5452021-03-01 12:31:41 +00003479 unsigned int tensorIndex = tensorIndexes[index];
3480 armnn::IInputSlot* slot = &(layer->GetInputSlot(startingSlotIndex + index));
telsoa01c577f2c2018-08-31 09:22:23 +01003481 RegisterConsumerOfTensor(subgraphIndex, tensorIndex, slot);
3482 }
3483}
3484
Kevin May7d96b162021-02-03 17:38:41 +00003485void TfLiteParserImpl::RegisterOutputSlots(size_t subgraphIndex,
3486 size_t operatorIndex,
3487 IConnectableLayer* layer,
3488 const std::vector<unsigned int>& tensorIndexes)
telsoa01c577f2c2018-08-31 09:22:23 +01003489{
3490 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003491 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01003492 if (tensorIndexes.size() != layer->GetNumOutputSlots())
3493 {
3494 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003495 fmt::format("The number of tensor outputs ({}) does not match the number expected ({})"
3496 " for subgraph:{} operator index:{} {}",
3497 tensorIndexes.size(),
3498 layer->GetNumOutputSlots(),
3499 subgraphIndex,
3500 operatorIndex,
3501 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003502 }
3503
3504 for (unsigned int slotIndex = 0; slotIndex < layer->GetNumOutputSlots(); ++slotIndex)
3505 {
3506 unsigned int tensorIndex = tensorIndexes[slotIndex];
3507 armnn::IOutputSlot* slot = &(layer->GetOutputSlot(slotIndex));
3508 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
3509 }
3510}
3511
Kevin May7d96b162021-02-03 17:38:41 +00003512void TfLiteParserImpl::SetupInputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003513{
3514 CHECK_SUBGRAPH(m_Model, subgraphIndex);
3515
3516 auto inputs = GetSubgraphInputs(m_Model, subgraphIndex);
3517 for (auto const & tensorIdAndPtr : inputs)
3518 {
3519 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
3520 IConnectableLayer* layer =
3521 m_Network->AddInputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
3522
3523 auto tensorInfo = ToTensorInfo(tensorIdAndPtr.second);
3524 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
3525
3526 RegisterOutputSlots(subgraphIndex,
3527 VIRTUAL_OPERATOR_ID,
3528 layer,
3529 { static_cast<uint32_t>(tensorIdAndPtr.first) });
3530 }
3531}
3532
Kevin May7d96b162021-02-03 17:38:41 +00003533void TfLiteParserImpl::SetupOutputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003534{
3535 CHECK_SUBGRAPH(m_Model, subgraphIndex);
3536
3537 auto outputs = GetSubgraphOutputs(m_Model, subgraphIndex);
3538 for (auto const & tensorIdAndPtr : outputs)
3539 {
3540 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
3541 IConnectableLayer* layer =
3542 m_Network->AddOutputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
3543
3544 RegisterInputSlots(subgraphIndex,
3545 VIRTUAL_OPERATOR_ID,
3546 layer,
3547 { static_cast<uint32_t>(tensorIdAndPtr.first) });
3548 }
3549}
3550
Kevin May7d96b162021-02-03 17:38:41 +00003551void TfLiteParserImpl::SetupConstantLayers(size_t subgraphIndex)
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003552{
3553 CHECK_SUBGRAPH(m_Model, subgraphIndex);
3554
Derek Lambertiff05cc52019-04-26 13:05:17 +01003555 const auto & subgraphPtr = m_Model->subgraphs[subgraphIndex];
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003556 for (unsigned int subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
3557 {
3558 for (unsigned int tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
3559 {
3560 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot == nullptr &&
3561 m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size() > 0)
3562 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01003563 TensorRawPtr tensorPtr = subgraphPtr->tensors[tensorIndex].get();
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003564 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003565 auto tensorAndData = CreateConstTensorNonPermuted(tensorPtr, tensorInfo);
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003566
James Ward58dec6b2020-09-11 17:32:44 +01003567 std::string layerName = fmt::format("Constant:{}", tensorPtr->name);
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003568 IConnectableLayer *layer =
Finn Williamsd4fa5452021-03-01 12:31:41 +00003569 m_Network->AddConstantLayer(tensorAndData, layerName.c_str());
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003570
3571 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
3572 RegisterOutputSlots(subgraphIndex,
3573 VIRTUAL_OPERATOR_ID,
3574 layer,
3575 { tensorIndex });
3576
3577 }
3578 }
3579 }
3580}
3581
telsoa01c577f2c2018-08-31 09:22:23 +01003582// example usage: BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Kevin May7d96b162021-02-03 17:38:41 +00003583TfLiteParserImpl::BufferRawPtr TfLiteParserImpl::GetBuffer(const ModelPtr& model, size_t bufferIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003584{
3585 CHECK_BUFFER(model, bufferIndex);
3586 return model->buffers[bufferIndex].get();
3587}
3588
Matteo Martincigh747ef822018-12-18 09:26:39 +00003589template<typename T>
Kevin May7d96b162021-02-03 17:38:41 +00003590std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
3591TfLiteParserImpl::CreateConstTensorAndStoreData(TfLiteParserImpl::BufferRawPtr bufferPtr,
3592 TfLiteParserImpl::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +00003593 armnn::TensorInfo& tensorInfo,
3594 armnn::Optional<armnn::PermutationVector&> permutationVector)
3595{
3596 auto constData = CreateConstTensorImpl<T>(bufferPtr,
3597 tensorPtr,
3598 tensorInfo,
3599 permutationVector);
Kevin May7d96b162021-02-03 17:38:41 +00003600 TfLiteParserImpl::SupportedDataStorage storage(std::move(constData.second));
Matteo Martincigh747ef822018-12-18 09:26:39 +00003601 return std::make_pair(constData.first, std::move(storage));
3602}
3603
Finn Williamsd4fa5452021-03-01 12:31:41 +00003604bool TfLiteParserImpl::IsConstTensor(TensorRawPtr tensorPtr)
3605{
3606 CHECK_TENSOR_PTR(tensorPtr);
3607 return !tensorPtr->is_variable;
3608}
3609
3610
Kevin May7d96b162021-02-03 17:38:41 +00003611std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
Finn Williamsd4fa5452021-03-01 12:31:41 +00003612TfLiteParserImpl::CreateConstTensorPermuted(TensorRawPtr tensorPtr,
3613 armnn::TensorInfo& tensorInfo,
3614 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +01003615{
3616 CHECK_TENSOR_PTR(tensorPtr);
3617 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
3618 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
3619
3620 switch (tensorInfo.GetDataType())
3621 {
3622 case armnn::DataType::Float32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00003623 return CreateConstTensorAndStoreData<float>(bufferPtr,
3624 tensorPtr,
3625 tensorInfo,
3626 permutationVector);
Derek Lambertif90c56d2020-01-10 17:14:08 +00003627 case armnn::DataType::QAsymmU8:
Matteo Martincigh747ef822018-12-18 09:26:39 +00003628 return CreateConstTensorAndStoreData<uint8_t>(bufferPtr,
3629 tensorPtr,
3630 tensorInfo,
3631 permutationVector);
Keith Davisd305e1a2020-01-22 11:57:54 +00003632 case armnn::DataType::QSymmS8:
3633 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
3634 tensorPtr,
3635 tensorInfo,
3636 permutationVector);
Keith Davis67e6c542020-02-19 10:08:33 +00003637 case armnn::DataType::QAsymmS8:
3638 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
3639 tensorPtr,
3640 tensorInfo,
3641 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01003642 case armnn::DataType::Signed32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00003643 return CreateConstTensorAndStoreData<int32_t>(bufferPtr,
3644 tensorPtr,
3645 tensorInfo,
3646 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01003647 default:
3648 {
3649 std::stringstream errString;
3650 errString << "Unexpected datatype when creating const tensor: "
3651 << armnn::GetDataTypeName(tensorInfo.GetDataType())
3652 << " shape:" << tensorInfo.GetShape()
3653 << CHECK_LOCATION().AsString();
3654 throw ParseException(errString.str());
3655 }
3656 }
3657}
3658
Finn Williamsd4fa5452021-03-01 12:31:41 +00003659armnn::ConstTensor TfLiteParserImpl::CreateConstTensorNonPermuted(TensorRawPtr tensorPtr,
3660 armnn::TensorInfo& tensorInfo)
3661{
3662 CHECK_TENSOR_PTR(tensorPtr);
3663 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
3664 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
3665
3666 return ConstTensor(tensorInfo, bufferPtr->data.data());
3667}
3668
Kevin May7d96b162021-02-03 17:38:41 +00003669BindingPointInfo TfLiteParserImpl::GetNetworkInputBindingInfo(size_t subgraphId,
3670 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01003671{
3672 CHECK_SUBGRAPH(m_Model, subgraphId);
3673 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
3674 for (auto const & input : inputs)
3675 {
3676 if (input.second->name == name)
3677 {
3678 auto bindingId = GenerateLayerBindingId(subgraphId, input.first);
3679 return std::make_pair(bindingId, ToTensorInfo(input.second));
3680 }
3681 }
3682
3683 std::stringstream bindings;
3684 for (auto const & input : inputs)
3685 {
3686 bindings << "'" << input.second->name << "' ";
3687 }
3688
3689 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003690 fmt::format("No input binding found for subgraph:{} and name:{}. "
3691 "Possible inputs are: [{}] {}",
3692 subgraphId,
3693 name,
3694 bindings.str(),
3695 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003696}
3697
Kevin May7d96b162021-02-03 17:38:41 +00003698BindingPointInfo TfLiteParserImpl::GetNetworkOutputBindingInfo(size_t subgraphId,
3699 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01003700{
3701 CHECK_SUBGRAPH(m_Model, subgraphId);
3702 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003703 for (unsigned int i = 0; i < outputs.size(); ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01003704 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003705 auto const output = outputs[i];
telsoa01c577f2c2018-08-31 09:22:23 +01003706 if (output.second->name == name)
3707 {
3708 auto bindingId = GenerateLayerBindingId(subgraphId, output.first);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003709 std::vector<unsigned int> shape = m_OverridenOutputShapes.size() > 0 ?
3710 m_OverridenOutputShapes[i] : AsUnsignedVector(output.second->shape);
3711 return std::make_pair(bindingId, ToTensorInfo(output.second, shape));
telsoa01c577f2c2018-08-31 09:22:23 +01003712 }
3713 }
3714
3715 std::stringstream bindings;
3716 for (auto const & output : outputs)
3717 {
3718 bindings << "'" << output.second->name << "' ";
3719 }
3720
3721 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003722 fmt::format("No output binding found for subgraph:{} and name:{}. "
3723 "Possible outputs are: [{}] {}",
3724 subgraphId,
3725 name,
3726 bindings.str(),
3727 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003728}
3729
Kevin May7d96b162021-02-03 17:38:41 +00003730size_t TfLiteParserImpl::GetSubgraphCount() const
telsoa01c577f2c2018-08-31 09:22:23 +01003731{
3732 return m_Model->subgraphs.size();
3733}
3734
Kevin May7d96b162021-02-03 17:38:41 +00003735std::vector<std::string> TfLiteParserImpl::GetSubgraphInputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01003736{
3737 CHECK_SUBGRAPH(m_Model, subgraphId);
3738 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
3739 std::vector<std::string> result;
3740 result.reserve(inputs.size());
3741 for (auto const & input : inputs)
3742 {
3743 result.push_back(input.second->name);
3744 }
3745 return result;
3746}
3747
Kevin May7d96b162021-02-03 17:38:41 +00003748std::vector<std::string> TfLiteParserImpl::GetSubgraphOutputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01003749{
3750 CHECK_SUBGRAPH(m_Model, subgraphId);
3751 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
3752 std::vector<std::string> result;
3753 result.reserve(outputs.size());
3754 for (auto const & output : outputs)
3755 {
3756 result.push_back(output.second->name);
3757 }
3758 return result;
3759}
3760
Matthew Sloyanac001ee2021-02-03 10:43:04 +00003761const std::string TfLiteParserImpl::GetVersion()
3762{
3763 return TFLITE_PARSER_VERSION;
3764}
3765
Kevin May7d96b162021-02-03 17:38:41 +00003766TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<float[]> && data)
telsoa01c577f2c2018-08-31 09:22:23 +01003767: m_FloatData(std::move(data))
3768, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00003769, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01003770, m_Int32Data(nullptr)
3771{
3772}
3773
Kevin May7d96b162021-02-03 17:38:41 +00003774TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<uint8_t[]> && data)
telsoa01c577f2c2018-08-31 09:22:23 +01003775: m_FloatData(nullptr)
3776, m_Uint8Data(std::move(data))
Keith Davisd305e1a2020-01-22 11:57:54 +00003777, m_Int8Data(nullptr)
3778, m_Int32Data(nullptr)
3779{
3780}
3781
Kevin May7d96b162021-02-03 17:38:41 +00003782TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int8_t[]> && data)
Keith Davisd305e1a2020-01-22 11:57:54 +00003783: m_FloatData(nullptr)
3784, m_Uint8Data(nullptr)
3785, m_Int8Data(std::move(data))
telsoa01c577f2c2018-08-31 09:22:23 +01003786, m_Int32Data(nullptr)
3787{
3788}
3789
Kevin May7d96b162021-02-03 17:38:41 +00003790TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int32_t[]> && data)
telsoa01c577f2c2018-08-31 09:22:23 +01003791: m_FloatData(nullptr)
3792, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00003793, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01003794, m_Int32Data(std::move(data))
3795{
3796}
3797
3798} // armnnTfLiteParser