blob: a26f3e5f04a9a42c58e93f82eaff034dceef6e33 [file] [log] [blame]
telsoa01c577f2c2018-08-31 09:22:23 +01001//
Teresa Charlinfd33a692022-06-29 15:35:57 +01002// Copyright © 2022 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"
Mike Kelly5880b912022-01-28 16:18:54 +00009#include "armnn/LstmParams.hpp"
Matthew Sloyanac001ee2021-02-03 10:43:04 +000010
Sadik Armagand109a4d2020-07-28 10:42:13 +010011#include <armnn/BackendOptions.hpp>
Matthew Bentham39ef3e52020-01-20 10:09:09 +000012#include <armnn/Descriptors.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010013#include <armnn/Exceptions.hpp>
Derek Lamberti08446972019-11-26 16:38:31 +000014#include <armnn/Logging.hpp>
James Conroy05102392020-06-24 15:39:55 +010015#include <armnn/Tensor.hpp>
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +000016#include <armnnUtils/TensorUtils.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010017#include <armnn/TypesUtils.hpp>
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +010018#include <armnn/utility/Assert.hpp>
Jan Eilers8eb25602020-03-09 12:13:48 +000019#include <armnn/utility/IgnoreUnused.hpp>
Derek Lambertif0176992020-04-28 13:37:49 +010020#include <armnn/utility/NumericCast.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010021
22// armnnUtils:
Matteo Martincighe011d202019-11-28 11:35:47 +000023#include <armnnUtils/Permute.hpp>
Rob Hughes9542f902021-07-14 09:48:54 +010024#include <armnnUtils/Filesystem.hpp>
Matteo Martincighe011d202019-11-28 11:35:47 +000025
Sadik Armagan479045b2018-10-01 11:51:37 +010026#include <ParserHelper.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010027#include <VerificationHelpers.hpp>
28
29// The generated code based on the Tf Lite schema:
30#include <schema_generated.h>
31
Matteo Martincighe011d202019-11-28 11:35:47 +000032#include <flatbuffers/flexbuffers.h>
33
James Ward58dec6b2020-09-11 17:32:44 +010034#include <fmt/format.h>
telsoa01c577f2c2018-08-31 09:22:23 +010035
telsoa01c577f2c2018-08-31 09:22:23 +010036#include <algorithm>
Matthew Sloyanac001ee2021-02-03 10:43:04 +000037#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
41#define ARMNN_THROW_PARSE_EXCEPTION(msg) \
42 { \
43 throw armnn::ParseException( static_cast<const std::stringstream&>( std::stringstream() << msg \
44 << ": " \
45 << CHECK_LOCATION().AsString()).str()); \
46 }
telsoa01c577f2c2018-08-31 09:22:23 +010047
48using namespace armnn;
49using armnn::CheckLocation;
50namespace armnnTfLiteParser
51{
Kevin May7d96b162021-02-03 17:38:41 +000052
53ITfLiteParser::ITfLiteParser(const armnn::Optional<TfLiteParserOptions>& options) :
54 pTfLiteParserImpl(new TfLiteParserImpl(options)) {}
55
56ITfLiteParser::~ITfLiteParser() = default;
57
58ITfLiteParser* ITfLiteParser::CreateRaw(const armnn::Optional<TfLiteParserOptions>& options)
59{
60 return new ITfLiteParser(options);
61}
62
63ITfLiteParserPtr ITfLiteParser::Create(const armnn::Optional<TfLiteParserOptions>& options)
64{
65 return ITfLiteParserPtr(CreateRaw(options), &ITfLiteParser::Destroy);
66}
67
68void ITfLiteParser::Destroy(ITfLiteParser* parser)
69{
70 delete parser;
71}
72
73armnn::INetworkPtr ITfLiteParser::CreateNetworkFromBinaryFile(const char* graphFile)
74{
75 return pTfLiteParserImpl->CreateNetworkFromBinaryFile(graphFile);
76}
77
Mike Kelly0d77ae12022-01-07 17:42:27 +000078armnn::INetworkPtr ITfLiteParser::CreateNetworkFromBinary(const std::vector<uint8_t>& binaryContent)
Kevin May7d96b162021-02-03 17:38:41 +000079{
80 return pTfLiteParserImpl->CreateNetworkFromBinary(binaryContent);
81}
82
83BindingPointInfo ITfLiteParser::GetNetworkInputBindingInfo(size_t subgraphId,
84 const std::string& name) const
85{
86 return pTfLiteParserImpl->GetNetworkInputBindingInfo(subgraphId, name);
87}
88
89BindingPointInfo ITfLiteParser::GetNetworkOutputBindingInfo(size_t subgraphId,
90 const std::string& name) const
91{
92 return pTfLiteParserImpl->GetNetworkOutputBindingInfo(subgraphId, name);
93}
94
95size_t ITfLiteParser::GetSubgraphCount() const
96{
97 return pTfLiteParserImpl->GetSubgraphCount();
98}
99
100std::vector<std::string> ITfLiteParser::GetSubgraphInputTensorNames(size_t subgraphId) const
101{
102 return pTfLiteParserImpl->GetSubgraphInputTensorNames(subgraphId);
103}
104
105std::vector<std::string> ITfLiteParser::GetSubgraphOutputTensorNames(size_t subgraphId) const
106{
107 return pTfLiteParserImpl->GetSubgraphOutputTensorNames(subgraphId);
108}
109
telsoa01c577f2c2018-08-31 09:22:23 +0100110namespace
111{
jimfly01c25411c2018-11-14 17:47:22 +0000112
telsoa01c577f2c2018-08-31 09:22:23 +0100113const uint32_t VIRTUAL_OPERATOR_ID = std::numeric_limits<uint32_t>::max();
114
Mike Kelly0d77ae12022-01-07 17:42:27 +0000115void CheckSubgraph(const TfLiteParserImpl::ModelPtr& model,
telsoa01c577f2c2018-08-31 09:22:23 +0100116 size_t subgraphIndex,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000117 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100118{
119 if (model.get() == nullptr)
120 {
121 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100122 fmt::format("{} was called with invalid (null) model. "
123 "Possible reason is that the model is not yet loaded and Unpack(ed). "
124 "subgraph:{} at {}",
125 location.m_Function,
126 subgraphIndex,
127 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100128 }
129 else if (subgraphIndex >= model->subgraphs.size())
130 {
131 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100132 fmt::format("{} was called with an invalid subgraph index. "
133 "subgraph:{} at {}",
134 location.m_Function,
135 subgraphIndex,
136 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100137 }
138}
139
140#define CHECK_SUBGRAPH(MODEL, SUBGRAPH_INDEX) \
141 CheckSubgraph(MODEL, SUBGRAPH_INDEX, CHECK_LOCATION())
142
Mike Kelly0d77ae12022-01-07 17:42:27 +0000143void CheckModel(const TfLiteParserImpl::ModelPtr& model,
telsoa01c577f2c2018-08-31 09:22:23 +0100144 size_t subgraphIndex,
145 size_t operatorIndex,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000146 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100147{
148 if (model.get() == nullptr)
149 {
150 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100151 fmt::format("{} was called with invalid (null) model. "
152 "Possible reason is that the model is not yet loaded and Unpack(ed). "
153 "subgraph:{} operator:{} at {}",
154 location.m_Function,
155 subgraphIndex,
156 operatorIndex,
157 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100158 }
159 else if (subgraphIndex >= model->subgraphs.size())
160 {
161 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100162 fmt::format("{} was called with an invalid subgraph index. "
163 "subgraph:{} operator:{} at {}",
164 location.m_Function,
165 subgraphIndex,
166 operatorIndex,
167 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100168 }
169 else if (operatorIndex >= model->subgraphs[subgraphIndex]->operators.size() &&
170 operatorIndex != VIRTUAL_OPERATOR_ID)
171 {
172 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100173 fmt::format("{} was called with an invalid operator index. "
174 "subgraph:{} operator:{} at {}",
175 location.m_Function,
176 subgraphIndex,
177 operatorIndex,
178 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100179 }
180}
181
182#define CHECK_MODEL(MODEL, SUBGRAPH_INDEX, OPERATOR_INDEX) \
183 CheckModel(MODEL, SUBGRAPH_INDEX, OPERATOR_INDEX, CHECK_LOCATION())
184
Mike Kelly0d77ae12022-01-07 17:42:27 +0000185void CheckTensor(const TfLiteParserImpl::ModelPtr& model,
telsoa01c577f2c2018-08-31 09:22:23 +0100186 size_t subgraphIndex,
187 size_t tensorIndex,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000188 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100189{
190 // not checking model, because I assume CHECK_MODEL already run
191 // and checked that. An assert would do.
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100192 ARMNN_ASSERT_MSG(model.get() != nullptr, "Expecting a valid model in this function");
telsoa01c577f2c2018-08-31 09:22:23 +0100193
194 // also subgraph index should be checked by CHECK_MODEL so
195 // I only add an assert here
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100196 ARMNN_ASSERT_MSG(subgraphIndex < model->subgraphs.size(), "Expecting a valid subgraph index");
telsoa01c577f2c2018-08-31 09:22:23 +0100197
198 // the tensor index is the only one to check here
199 if (tensorIndex >= model->subgraphs[subgraphIndex]->tensors.size())
200 {
201 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100202 fmt::format("{} was called with an invalid tensor index. "
203 "subgraph:{} tensor:{} at {}",
204 location.m_Function,
205 subgraphIndex,
206 tensorIndex,
207 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100208 }
209}
210
211#define CHECK_TENSOR(MODEL, SUBGRAPH_INDEX, TENSOR_INDEX) \
212 CheckTensor(MODEL, SUBGRAPH_INDEX, TENSOR_INDEX, CHECK_LOCATION())
213
Kevin May7d96b162021-02-03 17:38:41 +0000214void CheckTensorPtr(TfLiteParserImpl::TensorRawPtr rawPtr,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000215 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100216{
217 if (rawPtr == nullptr)
218 {
219 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100220 fmt::format("{} was called with a null tensor pointer at {}", location.m_Function, location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100221 }
222}
223
224#define CHECK_TENSOR_PTR(TENSOR_PTR) \
225 CheckTensorPtr(TENSOR_PTR, CHECK_LOCATION())
226
Mike Kelly0d77ae12022-01-07 17:42:27 +0000227void CheckBuffer(const TfLiteParserImpl::ModelPtr& model,
telsoa01c577f2c2018-08-31 09:22:23 +0100228 size_t bufferIndex,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000229 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100230{
231 if (model.get() == nullptr)
232 {
233 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100234 fmt::format("{} was called with invalid (null) model. "
235 "Possible reason is that the model is not yet loaded and Unpack(ed). "
236 "buffer:{} at {}",
237 location.m_Function,
238 bufferIndex,
239 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100240 }
241 else if (bufferIndex >= model->buffers.size())
242 {
243 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100244 fmt::format("{} was called with an invalid buffer index. "
245 "buffer index:{} at {}",
246 location.m_Function,
247 bufferIndex,
248 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100249 }
250 else if (model->buffers[bufferIndex].get() == nullptr)
251 {
252 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100253 fmt::format("The buffer #{} is null. {}",
254 bufferIndex,
255 location.AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100256 }
257}
258
259#define CHECK_BUFFER(MODEL, BUFFER_INDEX) \
260 CheckBuffer(MODEL, BUFFER_INDEX, CHECK_LOCATION())
261
Kevin May7d96b162021-02-03 17:38:41 +0000262void CheckBufferSize(TfLiteParserImpl::BufferRawPtr bufferPtr,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000263 const armnn::TensorInfo& tensorInfo,
telsoa01c577f2c2018-08-31 09:22:23 +0100264 uint32_t bufferId,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000265 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100266{
267 if (bufferPtr == nullptr)
268 {
269 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100270 fmt::format("BufferPtr is null for buffer:{}. {}",
271 bufferId,
272 location.AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100273 }
274 else if(tensorInfo.GetNumElements() > bufferPtr->data.size() ||
275 tensorInfo.GetNumBytes() > bufferPtr->data.size())
276 {
277 std::stringstream ss;
278 ss << "Buffer #" << bufferId << " has " << bufferPtr->data.size() << " bytes. "
279 << "For tensor: " << tensorInfo.GetShape()
280 << " expecting: " << tensorInfo.GetNumBytes() << " bytes and "
281 << tensorInfo.GetNumElements() << " elements. " << location.AsString();
282 throw ParseException(ss.str());
283 }
284}
285
Mike Kelly0d77ae12022-01-07 17:42:27 +0000286
287tflite::BuiltinOperator GetOpCode(const TfLiteParserImpl::ModelPtr& model, size_t subgraphIndex, size_t operatorIndex)
288{
289 const auto& operatorPtr = model->subgraphs[subgraphIndex]->operators[operatorIndex];
290 auto opcodeIndex = operatorPtr->opcode_index;
291
292// work around the introduction of the deprecated_builtin_code introduced in 2.4 in a backwards compatible manner
293#if defined(ARMNN_POST_TFLITE_2_3)
294 auto opcode = std::max(model->operator_codes[opcodeIndex]->builtin_code,
295 static_cast<tflite::BuiltinOperator>(model->operator_codes[opcodeIndex]->deprecated_builtin_code));
296#else
297 auto opcode = model->operator_codes[opcodeIndex]->builtin_code;
298#endif
299 return opcode;
300}
301
302std::vector<unsigned int> GetUIntBuffer(armnn::TensorInfo info,
303 const TfLiteParserImpl::ModelPtr& model,
304 size_t bufferIndex)
305{
306 TfLiteParserImpl::BufferRawPtr bufferPtr = TfLiteParserImpl::GetBuffer(model, bufferIndex);
307 std::vector<unsigned int> buffer(info.GetNumElements());
308
309 if (info.GetDataType() == DataType::Signed32)
310 {
311 ::memcpy(buffer.data(), bufferPtr->data.data(), bufferPtr->data.size());
312 }
313 else if (info.GetDataType() == DataType::Signed64)
314 {
315 std::vector<uint64_t> uint64Buffer(info.GetNumElements());
316 ::memcpy(uint64Buffer.data(), bufferPtr->data.data(), bufferPtr->data.size());
317 buffer.assign(std::begin(uint64Buffer), std::end(uint64Buffer));
318 }
319 return buffer;
320}
321
telsoa01c577f2c2018-08-31 09:22:23 +0100322#define CHECK_BUFFER_SIZE(BUFFER_PTR, TENSOR_INFO, BUFFER_ID) \
323 CheckBufferSize(BUFFER_PTR, TENSOR_INFO, BUFFER_ID, CHECK_LOCATION())
324
325bool IsActivationSupported(tflite::ActivationFunctionType activationType)
326{
327 switch(activationType)
328 {
329 case tflite::ActivationFunctionType_NONE:
330 case tflite::ActivationFunctionType_RELU:
331 case tflite::ActivationFunctionType_RELU6:
332 case tflite::ActivationFunctionType_TANH:
333 {
334 return true;
335 }
336 default:
337 {
338 return false;
339 }
340 }
341}
342
343#define CHECK_SUPPORTED_FUSED_ACTIVATION(OPTION, SUBGRAPH_INDEX, OPERATOR_INDEX) \
344 do { \
345 if (IsActivationSupported(OPTION->fused_activation_function) == false) \
346 { \
347 throw ParseException( \
James Ward58dec6b2020-09-11 17:32:44 +0100348 fmt::format("TfLite parser doesn't suppport fused activation: " \
349 "{}/{} in {} subgraph:{} operator:{} at {}", \
350 OPTION->fused_activation_function, \
351 tflite::EnumNameActivationFunctionType(\
352 OPTION->fused_activation_function), \
353 __func__, \
354 SUBGRAPH_INDEX, \
355 OPERATOR_INDEX, \
356 CHECK_LOCATION().FileLine())); \
telsoa01c577f2c2018-08-31 09:22:23 +0100357 } \
358 } while(false)
359
360
Mike Kelly0d77ae12022-01-07 17:42:27 +0000361std::vector<unsigned int> AsUnsignedVector(const std::vector<int32_t>& in)
telsoa01c577f2c2018-08-31 09:22:23 +0100362{
363 std::vector<unsigned int> result;
364 result.reserve(in.size());
Mike Kelly0d77ae12022-01-07 17:42:27 +0000365 for (auto& i : in)
telsoa01c577f2c2018-08-31 09:22:23 +0100366 {
mathad01c21025d2021-04-26 10:09:37 +0100367 // If the location of the input data is -1 then the input should be ignored.
368 if (i == -1)
369 {
370 continue;
371 }
telsoa01c577f2c2018-08-31 09:22:23 +0100372 result.push_back(CHECKED_NON_NEGATIVE(i));
373 }
374 return result;
375}
376
Mike Kelly5880b912022-01-28 16:18:54 +0000377bool IsOptionalOperandPresent(int input)
378{
379 return (input >= 0);
380}
381
telsoa01c577f2c2018-08-31 09:22:23 +0100382void CalcPadding(uint32_t inputSize,
383 uint32_t filterSize,
384 uint32_t stride,
Pablo Tellof0bd6832019-04-26 17:58:13 +0100385 uint32_t dilation,
telsoa01c577f2c2018-08-31 09:22:23 +0100386 uint32_t& paddingFront,
387 uint32_t& paddingBack,
388 tflite::Padding padding)
389{
390 paddingFront = 0;
391 paddingBack = 0;
392 if (padding == tflite::Padding_SAME)
393 {
394 uint32_t outputSize = (inputSize + stride - 1) / stride;
Pablo Tellof0bd6832019-04-26 17:58:13 +0100395 uint32_t dilatedSize = filterSize + (dilation - 1) * (filterSize - 1);
396 uint32_t temp = (outputSize - 1) * stride + dilatedSize;
telsoa01c577f2c2018-08-31 09:22:23 +0100397 if (temp > inputSize)
398 {
399 paddingFront = (temp - inputSize) / 2;
400 paddingBack = (temp - inputSize) - paddingFront;
401 }
402 }
403}
404
Kevin May7d96b162021-02-03 17:38:41 +0000405armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr,
Finn Williamsb49ed182021-06-29 15:50:08 +0100406 const std::vector<unsigned int>& shape,
Sadik Armagand109a4d2020-07-28 10:42:13 +0100407 const bool outputTensor = false)
telsoa01c577f2c2018-08-31 09:22:23 +0100408{
409 armnn::DataType type;
410 CHECK_TENSOR_PTR(tensorPtr);
411
412 switch (tensorPtr->type)
413 {
414 case tflite::TensorType_UINT8:
Derek Lambertif90c56d2020-01-10 17:14:08 +0000415 type = armnn::DataType::QAsymmU8;
telsoa01c577f2c2018-08-31 09:22:23 +0100416 break;
417 case tflite::TensorType_FLOAT32:
418 type = armnn::DataType::Float32;
419 break;
Keith Davisb4dd5cc2022-04-07 11:32:00 +0100420 case tflite::TensorType_FLOAT16:
421 type = armnn::DataType::Float16;
422 break;
Finn Williamsed66d142019-12-06 09:55:55 +0000423 case tflite::TensorType_INT8:
Keith Davis67e6c542020-02-19 10:08:33 +0000424 if (tensorPtr->quantization->zero_point.size() == 1)
Ryan OShea03181ff2020-02-07 17:22:22 +0000425 {
Keith Davis0c2eeac2020-02-11 16:51:50 +0000426 // Per-tensor
Ryan OShea03181ff2020-02-07 17:22:22 +0000427 type = armnn::DataType::QAsymmS8;
428 }
429 else
430 {
Keith Davis0c2eeac2020-02-11 16:51:50 +0000431 // Per-channel
Ryan OShea03181ff2020-02-07 17:22:22 +0000432 type = armnn::DataType::QSymmS8;
433 }
Finn Williamsed66d142019-12-06 09:55:55 +0000434 break;
435 case tflite::TensorType_INT16:
Derek Lambertif90c56d2020-01-10 17:14:08 +0000436 type = armnn::DataType::QSymmS16;
Finn Williamsed66d142019-12-06 09:55:55 +0000437 break;
telsoa01c577f2c2018-08-31 09:22:23 +0100438 case tflite::TensorType_INT32:
439 type = armnn::DataType::Signed32;
440 break;
Inki Daed4619e22020-09-10 15:33:54 +0900441 case tflite::TensorType_INT64:
442 type = armnn::DataType::Signed64;
443 break;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100444 case tflite::TensorType_BOOL:
445 type = armnn::DataType::Boolean;
446 break;
telsoa01c577f2c2018-08-31 09:22:23 +0100447 default:
448 {
449 CheckLocation location = CHECK_LOCATION();
450 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100451 fmt::format("Unsupported data type {} = {} for tensor: {}. {}",
452 tensorPtr->type,
453 tflite::EnumNameTensorType(tensorPtr->type),
454 tensorPtr->name,
455 location.AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100456 }
457 }
Finn Williamsb49ed182021-06-29 15:50:08 +0100458 TensorShape tensorShape;
459
460 std::vector<unsigned int> safeShape = shape;
461 if (shape.size() == 0)
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100462 {
463 safeShape.push_back(1);
Finn Williamsb49ed182021-06-29 15:50:08 +0100464 }
465
466 if (!outputTensor)
467 {
468 tensorShape = TensorShape(armnn::numeric_cast<unsigned int>(safeShape.size()), safeShape.data());
469 }
470 else
471 {
Rob Hughesd812a312021-08-06 13:10:53 +0100472 size_t shapeSignatureSize = tensorPtr->shape_signature.size();
Finn Williamsb49ed182021-06-29 15:50:08 +0100473
474 // If a shape signature exists we will use that to infer dynamic tensors
475 if (shapeSignatureSize != 0)
Sadik Armagand109a4d2020-07-28 10:42:13 +0100476 {
Finn Williamsb49ed182021-06-29 15:50:08 +0100477 // If the shape is incompatible with the shape signature override the shape
478 if (shapeSignatureSize != shape.size())
479 {
480 safeShape = {};
481
482 for (unsigned int i = 0; i < shapeSignatureSize; ++i)
483 {
484 unsigned int dim = tensorPtr->shape_signature[i] > -1 ?
485 static_cast<unsigned int>(tensorPtr->shape_signature[i]) : 0;
486 safeShape.push_back(dim);
487 }
488 }
489
Rob Hughesd812a312021-08-06 13:10:53 +0100490 std::unique_ptr<bool[]> dimMask = std::make_unique<bool[]>(tensorPtr->shape_signature.size());
Finn Williamsb49ed182021-06-29 15:50:08 +0100491 for (unsigned int i = 0; i < tensorPtr->shape_signature.size(); ++i)
492 {
493 dimMask[i] = tensorPtr->shape_signature[i] == -1 ? false : true;
494 }
Rob Hughesd812a312021-08-06 13:10:53 +0100495 tensorShape = TensorShape(static_cast<unsigned int>(safeShape.size()), safeShape.data(), dimMask.get());
Finn Williamsb49ed182021-06-29 15:50:08 +0100496 }
497 // If there is no shape signature treat the tensor as dynamic if the shape has a size of zero
498 else if (shape.size() == 0)
499 {
500 tensorShape = TensorShape(1, false);
501 }
502 else
503 {
504 tensorShape = TensorShape(armnn::numeric_cast<unsigned int>(shape.size()), shape.data());
Sadik Armagand109a4d2020-07-28 10:42:13 +0100505 }
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100506 }
507
Keith Davisd305e1a2020-01-22 11:57:54 +0000508 float quantizationScale = 0.0f;
509 int32_t quantizationOffset = 0;
510
511 if (tensorPtr->quantization.get())
512 {
513 if (tensorPtr->quantization->scale.size() <= 1)
514 {
515 CHECK_VALID_SIZE(tensorPtr->quantization->zero_point.size(), 0, 1);
516 CHECK_VALID_SIZE(tensorPtr->quantization->zero_point.size(), 0, 1);
517
518 if (tensorPtr->quantization->scale.size() == 1)
519 {
520 quantizationScale = tensorPtr->quantization->scale[0];
521 }
522 if (tensorPtr->quantization->zero_point.size() == 1)
523 {
524 // NOTE: we lose precision here when converting from 64 bit to 32
Ryan OShea03181ff2020-02-07 17:22:22 +0000525 // but this is what we support at the moment in ArmNN
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100526 quantizationOffset = armnn::numeric_cast<int32_t>(tensorPtr->quantization->zero_point[0]);
Keith Davisd305e1a2020-01-22 11:57:54 +0000527 }
528
Sadik Armagand109a4d2020-07-28 10:42:13 +0100529 armnn::TensorInfo result(tensorShape,
530 type,
531 quantizationScale,
532 quantizationOffset);
Keith Davisd305e1a2020-01-22 11:57:54 +0000533 return result;
534 }
535 else
536 {
537 std::vector<float> quantizationScales;
538 std::vector<int32_t> quantizationOffsets;
539
540 // Scale
541 std::copy(tensorPtr->quantization->scale.begin(),
542 tensorPtr->quantization->scale.end(),
543 std::back_inserter(quantizationScales));
544
Keith Davis0c2eeac2020-02-11 16:51:50 +0000545 // QSymmS8 Per-axis
Sadik Armagand109a4d2020-07-28 10:42:13 +0100546 armnn::TensorInfo result(tensorShape,
547 type,
548 quantizationScales,
Jan Eilers7612bd62021-04-06 17:29:03 +0100549 armnn::numeric_cast<unsigned int>(tensorPtr->quantization->quantized_dimension));
Keith Davisd305e1a2020-01-22 11:57:54 +0000550 return result;
551 }
552 }
553 else
554 {
Sadik Armagand109a4d2020-07-28 10:42:13 +0100555 armnn::TensorInfo result(tensorShape,
Keith Davisd305e1a2020-01-22 11:57:54 +0000556 type,
557 quantizationScale,
558 quantizationOffset);
559 return result;
560 }
telsoa01c577f2c2018-08-31 09:22:23 +0100561}
562
Jan Eilers7612bd62021-04-06 17:29:03 +0100563armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr)
Narumol Prangnawarat4628d052019-02-25 17:26:05 +0000564{
Mike Kelly0d77ae12022-01-07 17:42:27 +0000565 auto const& dimensions = AsUnsignedVector(tensorPtr->shape);
Jan Eilers7612bd62021-04-06 17:29:03 +0100566 return ToTensorInfo(tensorPtr, dimensions);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +0000567}
568
Kevin May7d96b162021-02-03 17:38:41 +0000569armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr,
Sadik Armagand109a4d2020-07-28 10:42:13 +0100570 const bool outputTensor)
571{
Mike Kelly0d77ae12022-01-07 17:42:27 +0000572 auto const& dimensions = AsUnsignedVector(tensorPtr->shape);
Jan Eilers7612bd62021-04-06 17:29:03 +0100573 return ToTensorInfo(tensorPtr, dimensions, outputTensor);
Sadik Armagand109a4d2020-07-28 10:42:13 +0100574}
575
telsoa01c577f2c2018-08-31 09:22:23 +0100576template<typename T>
577std::pair<armnn::ConstTensor, std::unique_ptr<T[]>>
Kevin May7d96b162021-02-03 17:38:41 +0000578CreateConstTensorImpl(TfLiteParserImpl::BufferRawPtr bufferPtr,
579 TfLiteParserImpl::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +0000580 armnn::TensorInfo& tensorInfo,
581 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +0100582{
Jan Eilers8eb25602020-03-09 12:13:48 +0000583 IgnoreUnused(tensorPtr);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100584 ARMNN_ASSERT_MSG(tensorPtr != nullptr, "tensorPtr is null");
585 ARMNN_ASSERT_MSG(bufferPtr != nullptr,
James Ward58dec6b2020-09-11 17:32:44 +0100586 fmt::format("Buffer for buffer:{} is null", tensorPtr->buffer).c_str());
telsoa01c577f2c2018-08-31 09:22:23 +0100587
588 std::unique_ptr<T[]> data(new T[tensorInfo.GetNumElements()]);
Matteo Martincigh747ef822018-12-18 09:26:39 +0000589
590 if (permutationVector.has_value() && permutationVector.value().GetSize() > 0)
591 {
592 tensorInfo = armnnUtils::Permuted(tensorInfo, permutationVector.value());
Matteo Martincighd5b9e642019-01-04 18:01:21 +0000593 armnnUtils::Permute(tensorInfo.GetShape(), permutationVector.value(),
594 reinterpret_cast<const T*>(bufferPtr->data.data()), data.get(), sizeof(T));
Matteo Martincigh747ef822018-12-18 09:26:39 +0000595 }
596 else
597 {
598 ::memcpy(data.get(), bufferPtr->data.data(), tensorInfo.GetNumBytes());
599 }
600
Matthew Sloyan81beae32021-07-13 19:46:11 +0100601 // Make sure isConstant flag is set.
602 tensorInfo.SetConstant();
603
telsoa01c577f2c2018-08-31 09:22:23 +0100604 return std::make_pair(ConstTensor(tensorInfo, data.get()), std::move(data));
605}
606
telsoa01c577f2c2018-08-31 09:22:23 +0100607armnn::LayerBindingId GenerateLayerBindingId(size_t subgraphIndex, size_t tensorIndex)
608{
609 // generate the binding id by shifting the tensor id by 8 bit
610 // and add the subgraph id, which allows 256 subgraphs
611 return static_cast<armnn::LayerBindingId>((tensorIndex<<8)+subgraphIndex);
612}
613
Aron Virginas-Tar70672f62019-01-23 14:00:00 +0000614bool CheckShape(const armnn::TensorShape& actual, const std::vector<int32_t>& expected)
615{
616 const unsigned int actualSize = actual.GetNumDimensions();
617 if (actualSize != expected.size())
618 {
619 return false;
620 }
621
622 for (unsigned int i = 0u; i < actualSize; i++)
623 {
624 if (expected[i] < 0 ||
625 actual[i] != static_cast<unsigned int>(expected[i]))
626 {
627 return false;
628 }
629 }
630
631 return true;
632}
633
James Conroy05102392020-06-24 15:39:55 +0100634void CheckMatchingQuantization(const TensorInfo& first,
635 const TensorInfo& second,
636 const std::string& descName,
637 std::string const& firstName,
638 std::string const& secondName)
639{
640 if (!first.IsQuantized() ||
641 !second.IsQuantized())
642 {
643 // Not a quantized type, ignore the validation
644 return;
645 }
646
647 DataType firstDataType = first.GetDataType();
648 DataType secondDataType = second.GetDataType();
649
650 if (firstDataType != secondDataType)
651 {
652 throw InvalidArgumentException(descName + ": " + firstName + " and " + secondName +
653 " must be of the same quantized type, " +
654 firstName + " is " + GetDataTypeName(firstDataType) + ", " +
655 secondName + " is " + GetDataTypeName(secondDataType));
656 }
657
658 if (!first.IsTypeSpaceMatch(second))
659 {
660 throw InvalidArgumentException(descName + ": " + firstName + " and " + secondName +
661 " must have the same quantization space, " +
662 firstName + " has offset " + std::to_string(first.GetQuantizationOffset()) +
663 " and scale " + std::to_string(first.GetQuantizationScale()) + ", " +
664 secondName + " has offset " + std::to_string(second.GetQuantizationOffset()) +
665 " and scale " + std::to_string(second.GetQuantizationScale()));
666 }
667}
668
telsoa01c577f2c2018-08-31 09:22:23 +0100669} // <anonymous>
670
Kevin May7d96b162021-02-03 17:38:41 +0000671TfLiteParserImpl::TfLiteParserImpl(const Optional<ITfLiteParser::TfLiteParserOptions>& options)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100672: m_Options(options)
673, m_Network(nullptr, nullptr)
Kevin May7d96b162021-02-03 17:38:41 +0000674, m_ParserFunctions(tflite::BuiltinOperator_MAX+1, &TfLiteParserImpl::ParseUnsupportedOperator)
telsoa01c577f2c2018-08-31 09:22:23 +0100675{
676 // register supported operators
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100677 m_ParserFunctions[tflite::BuiltinOperator_ABS] = &TfLiteParserImpl::ParseAbs;
Kevin May7d96b162021-02-03 17:38:41 +0000678 m_ParserFunctions[tflite::BuiltinOperator_ADD] = &TfLiteParserImpl::ParseAdd;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100679 m_ParserFunctions[tflite::BuiltinOperator_ARG_MIN] = &TfLiteParserImpl::ParseArgMin;
680 m_ParserFunctions[tflite::BuiltinOperator_ARG_MAX] = &TfLiteParserImpl::ParseArgMax;
Kevin May7d96b162021-02-03 17:38:41 +0000681 m_ParserFunctions[tflite::BuiltinOperator_AVERAGE_POOL_2D] = &TfLiteParserImpl::ParseAveragePool2D;
682 m_ParserFunctions[tflite::BuiltinOperator_BATCH_TO_SPACE_ND] = &TfLiteParserImpl::ParseBatchToSpaceND;
Samuel Yapfd3ba5a2022-08-24 17:04:34 +0100683 m_ParserFunctions[tflite::BuiltinOperator_BATCH_MATMUL] = &TfLiteParserImpl::ParseBatchMatMul;
mathad01b392e982021-04-07 12:07:30 +0100684 m_ParserFunctions[tflite::BuiltinOperator_CAST] = &TfLiteParserImpl::ParseCast;
Kevin May7d96b162021-02-03 17:38:41 +0000685 m_ParserFunctions[tflite::BuiltinOperator_CONCATENATION] = &TfLiteParserImpl::ParseConcatenation;
686 m_ParserFunctions[tflite::BuiltinOperator_CONV_2D] = &TfLiteParserImpl::ParseConv2D;
Matthew Sloyan4d217c02021-10-07 11:48:58 +0100687 // Conv3D support was added in TF 2.5, so for backwards compatibility a hash define is needed.
Cathal Corbett80b4ef02022-05-25 11:21:11 +0100688 #if defined(ARMNN_POST_TFLITE_2_4)
Matthew Sloyaneb5f8102021-10-05 17:31:42 +0100689 m_ParserFunctions[tflite::BuiltinOperator_CONV_3D] = &TfLiteParserImpl::ParseConv3D;
Matthew Sloyan4d217c02021-10-07 11:48:58 +0100690 #endif
Kevin May7d96b162021-02-03 17:38:41 +0000691 m_ParserFunctions[tflite::BuiltinOperator_CUSTOM] = &TfLiteParserImpl::ParseCustomOperator;
692 m_ParserFunctions[tflite::BuiltinOperator_DEPTH_TO_SPACE] = &TfLiteParserImpl::ParseDepthToSpace;
693 m_ParserFunctions[tflite::BuiltinOperator_DEPTHWISE_CONV_2D] = &TfLiteParserImpl::ParseDepthwiseConv2D;
694 m_ParserFunctions[tflite::BuiltinOperator_DEQUANTIZE] = &TfLiteParserImpl::ParseDequantize;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100695 m_ParserFunctions[tflite::BuiltinOperator_DIV] = &TfLiteParserImpl::ParseDiv;
Kevin May7d96b162021-02-03 17:38:41 +0000696 m_ParserFunctions[tflite::BuiltinOperator_ELU] = &TfLiteParserImpl::ParseElu;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300697 m_ParserFunctions[tflite::BuiltinOperator_EQUAL] = &TfLiteParserImpl::ParseEqual;
Kevin May7d96b162021-02-03 17:38:41 +0000698 m_ParserFunctions[tflite::BuiltinOperator_EXP] = &TfLiteParserImpl::ParseExp;
Teresa Charlin3ab85482021-06-08 16:59:29 +0100699 m_ParserFunctions[tflite::BuiltinOperator_EXPAND_DIMS] = &TfLiteParserImpl::ParseExpandDims;
Teresa Charlincdbd40b2022-02-25 13:21:55 +0000700 m_ParserFunctions[tflite::BuiltinOperator_FLOOR_DIV] = &TfLiteParserImpl::ParseFloorDiv;
Kevin May7d96b162021-02-03 17:38:41 +0000701 m_ParserFunctions[tflite::BuiltinOperator_FULLY_CONNECTED] = &TfLiteParserImpl::ParseFullyConnected;
702 m_ParserFunctions[tflite::BuiltinOperator_GATHER] = &TfLiteParserImpl::ParseGather;
Teresa Charlin91a53ea2022-04-25 15:47:29 +0100703 m_ParserFunctions[tflite::BuiltinOperator_GATHER_ND] = &TfLiteParserImpl::ParseGatherNd;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300704 m_ParserFunctions[tflite::BuiltinOperator_GREATER] = &TfLiteParserImpl::ParseGreater;
705 m_ParserFunctions[tflite::BuiltinOperator_GREATER_EQUAL] = &TfLiteParserImpl::ParseGreaterOrEqual;
Kevin May7d96b162021-02-03 17:38:41 +0000706 m_ParserFunctions[tflite::BuiltinOperator_HARD_SWISH] = &TfLiteParserImpl::ParseHardSwish;
707 m_ParserFunctions[tflite::BuiltinOperator_LEAKY_RELU] = &TfLiteParserImpl::ParseLeakyRelu;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300708 m_ParserFunctions[tflite::BuiltinOperator_LESS] = &TfLiteParserImpl::ParseLess;
709 m_ParserFunctions[tflite::BuiltinOperator_LESS_EQUAL] = &TfLiteParserImpl::ParseLessOrEqual;
Mike Kelly31dce2b2021-09-01 21:22:37 +0100710 m_ParserFunctions[tflite::BuiltinOperator_LOCAL_RESPONSE_NORMALIZATION]
711 = &TfLiteParserImpl::ParseLocalResponseNormalization;
Teresa Charlin28aa6692022-07-12 11:18:44 +0100712 m_ParserFunctions[tflite::BuiltinOperator_LOG] = &TfLiteParserImpl::ParseLog;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100713 m_ParserFunctions[tflite::BuiltinOperator_LOGICAL_NOT] = &TfLiteParserImpl::ParseLogicalNot;
Kevin May7d96b162021-02-03 17:38:41 +0000714 m_ParserFunctions[tflite::BuiltinOperator_LOGISTIC] = &TfLiteParserImpl::ParseLogistic;
Teresa Charlinfd33a692022-06-29 15:35:57 +0100715 m_ParserFunctions[tflite::BuiltinOperator_LOG_SOFTMAX] = &TfLiteParserImpl::ParseLogSoftmax;
Kevin May7d96b162021-02-03 17:38:41 +0000716 m_ParserFunctions[tflite::BuiltinOperator_L2_NORMALIZATION] = &TfLiteParserImpl::ParseL2Normalization;
717 m_ParserFunctions[tflite::BuiltinOperator_MAX_POOL_2D] = &TfLiteParserImpl::ParseMaxPool2D;
718 m_ParserFunctions[tflite::BuiltinOperator_MAXIMUM] = &TfLiteParserImpl::ParseMaximum;
719 m_ParserFunctions[tflite::BuiltinOperator_MEAN] = &TfLiteParserImpl::ParseMean;
720 m_ParserFunctions[tflite::BuiltinOperator_MINIMUM] = &TfLiteParserImpl::ParseMinimum;
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +0100721 m_ParserFunctions[tflite::BuiltinOperator_MIRROR_PAD] = &TfLiteParserImpl::ParseMirrorPad;
Kevin May7d96b162021-02-03 17:38:41 +0000722 m_ParserFunctions[tflite::BuiltinOperator_MUL] = &TfLiteParserImpl::ParseMul;
723 m_ParserFunctions[tflite::BuiltinOperator_NEG] = &TfLiteParserImpl::ParseNeg;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300724 m_ParserFunctions[tflite::BuiltinOperator_NOT_EQUAL] = &TfLiteParserImpl::ParseNotEqual;
Kevin May7d96b162021-02-03 17:38:41 +0000725 m_ParserFunctions[tflite::BuiltinOperator_PACK] = &TfLiteParserImpl::ParsePack;
726 m_ParserFunctions[tflite::BuiltinOperator_PAD] = &TfLiteParserImpl::ParsePad;
Mike Kelly0d77ae12022-01-07 17:42:27 +0000727 m_ParserFunctions[tflite::BuiltinOperator_PADV2] = &TfLiteParserImpl::ParsePad;
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +0100728 m_ParserFunctions[tflite::BuiltinOperator_PRELU] = &TfLiteParserImpl::ParsePrelu;
Kevin May7d96b162021-02-03 17:38:41 +0000729 m_ParserFunctions[tflite::BuiltinOperator_QUANTIZE] = &TfLiteParserImpl::ParseQuantize;
730 m_ParserFunctions[tflite::BuiltinOperator_RELU] = &TfLiteParserImpl::ParseRelu;
731 m_ParserFunctions[tflite::BuiltinOperator_RELU6] = &TfLiteParserImpl::ParseRelu6;
Sadik Armagana2747482021-02-09 10:28:54 +0000732 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MAX] = &TfLiteParserImpl::ParseReduceMax;
733 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MIN] = &TfLiteParserImpl::ParseReduceMin;
Teresa Charlin4e3e8312021-08-05 12:34:37 +0100734 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_PROD] = &TfLiteParserImpl::ParseReduceProd;
Kevin May7d96b162021-02-03 17:38:41 +0000735 m_ParserFunctions[tflite::BuiltinOperator_RESHAPE] = &TfLiteParserImpl::ParseReshape;
736 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_BILINEAR] = &TfLiteParserImpl::ParseResizeBilinear;
737 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_NEAREST_NEIGHBOR] = &TfLiteParserImpl::ParseResizeNearestNeighbor;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100738 m_ParserFunctions[tflite::BuiltinOperator_RSQRT] = &TfLiteParserImpl::ParseRsqrt;
Teresa Charlinf0fce5b2022-05-04 17:24:43 +0100739 m_ParserFunctions[tflite::BuiltinOperator_SQRT] = &TfLiteParserImpl::ParseSqrt;
Keith Davis0176fd82021-06-01 17:36:32 +0100740 m_ParserFunctions[tflite::BuiltinOperator_SHAPE] = &TfLiteParserImpl::ParseShape;
Teresa Charlin28aa6692022-07-12 11:18:44 +0100741 m_ParserFunctions[tflite::BuiltinOperator_SIN] = &TfLiteParserImpl::ParseSin;
Kevin May7d96b162021-02-03 17:38:41 +0000742 m_ParserFunctions[tflite::BuiltinOperator_SLICE] = &TfLiteParserImpl::ParseSlice;
743 m_ParserFunctions[tflite::BuiltinOperator_SOFTMAX] = &TfLiteParserImpl::ParseSoftmax;
744 m_ParserFunctions[tflite::BuiltinOperator_SPACE_TO_BATCH_ND] = &TfLiteParserImpl::ParseSpaceToBatchND;
745 m_ParserFunctions[tflite::BuiltinOperator_SPLIT] = &TfLiteParserImpl::ParseSplit;
746 m_ParserFunctions[tflite::BuiltinOperator_SPLIT_V] = &TfLiteParserImpl::ParseSplitV;
747 m_ParserFunctions[tflite::BuiltinOperator_SQUEEZE] = &TfLiteParserImpl::ParseSqueeze;
748 m_ParserFunctions[tflite::BuiltinOperator_STRIDED_SLICE] = &TfLiteParserImpl::ParseStridedSlice;
749 m_ParserFunctions[tflite::BuiltinOperator_SUB] = &TfLiteParserImpl::ParseSub;
750 m_ParserFunctions[tflite::BuiltinOperator_SUM] = &TfLiteParserImpl::ParseSum;
751 m_ParserFunctions[tflite::BuiltinOperator_TANH] = &TfLiteParserImpl::ParseTanH;
752 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE] = &TfLiteParserImpl::ParseTranspose;
753 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE_CONV] = &TfLiteParserImpl::ParseTransposeConv;
Mike Kelly5880b912022-01-28 16:18:54 +0000754 m_ParserFunctions[tflite::BuiltinOperator_UNIDIRECTIONAL_SEQUENCE_LSTM]
755 = &TfLiteParserImpl::ParseUnidirectionalSequenceLSTM;
Kevin May7d96b162021-02-03 17:38:41 +0000756 m_ParserFunctions[tflite::BuiltinOperator_UNPACK] = &TfLiteParserImpl::ParseUnpack;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100757
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100758 // register supported custom operators
Kevin May7d96b162021-02-03 17:38:41 +0000759 m_CustomParserFunctions["TFLite_Detection_PostProcess"] = &TfLiteParserImpl::ParseDetectionPostProcess;
telsoa01c577f2c2018-08-31 09:22:23 +0100760}
761
Kevin May7d96b162021-02-03 17:38:41 +0000762void TfLiteParserImpl::ResetParser()
telsoa01c577f2c2018-08-31 09:22:23 +0100763{
764 m_Network = armnn::INetworkPtr(nullptr, nullptr);
765 m_Model = nullptr;
766 m_SubgraphConnections.clear();
Mike Kelly5880b912022-01-28 16:18:54 +0000767 m_OverridenOutputShapes.clear();
768 m_ConstantsToDequantize.clear();
769 m_ConstantsToBeCreated.clear();
telsoa01c577f2c2018-08-31 09:22:23 +0100770}
771
Kevin May7d96b162021-02-03 17:38:41 +0000772INetworkPtr TfLiteParserImpl::CreateNetworkFromBinaryFile(const char* graphFile)
telsoa01c577f2c2018-08-31 09:22:23 +0100773{
774 ResetParser();
775 m_Model = LoadModelFromFile(graphFile);
776 return CreateNetworkFromModel();
777}
778
Mike Kelly0d77ae12022-01-07 17:42:27 +0000779INetworkPtr TfLiteParserImpl::CreateNetworkFromBinary(const std::vector<uint8_t>& binaryContent)
telsoa01c577f2c2018-08-31 09:22:23 +0100780{
781 ResetParser();
782 m_Model = LoadModelFromBinary(binaryContent.data(), binaryContent.size());
783 return CreateNetworkFromModel();
784}
785
Finn Williamsb49ed182021-06-29 15:50:08 +0100786
787armnn::INetworkPtr TfLiteParserImpl::LoadModel(std::unique_ptr<tflite::ModelT> model)
788{
789 ResetParser();
790 m_Model = std::move(model);
791
792 return CreateNetworkFromModel();
793}
794
Kevin May7d96b162021-02-03 17:38:41 +0000795INetworkPtr TfLiteParserImpl::CreateNetworkFromModel()
telsoa01c577f2c2018-08-31 09:22:23 +0100796{
Sadik Armagand109a4d2020-07-28 10:42:13 +0100797
798 using NetworkOptions = std::vector<BackendOptions>;
799 NetworkOptions networkOptions = {};
Mike Kelly80512b02022-05-16 23:10:42 +0100800 if (m_Options)
Sadik Armagand109a4d2020-07-28 10:42:13 +0100801 {
Mike Kelly80512b02022-05-16 23:10:42 +0100802 if (m_Options.value().m_InferAndValidate)
803 {
804 BackendOptions shapeInferenceMethodOption("ShapeInferenceMethod",
805 {
806 { "InferAndValidate", true }
807 });
Sadik Armagand109a4d2020-07-28 10:42:13 +0100808
Mike Kelly80512b02022-05-16 23:10:42 +0100809 networkOptions.push_back(shapeInferenceMethodOption);
810 }
811 if (m_Options.value().m_AllowExpandedDims)
812 {
813 BackendOptions shapeInferenceMethodOption("AllowExpandedDims",
814 {
815 { "AllowExpandedDims", true }
816 });
817
818 networkOptions.push_back(shapeInferenceMethodOption);
819 }
Sadik Armagand109a4d2020-07-28 10:42:13 +0100820 }
Sadik Armagand109a4d2020-07-28 10:42:13 +0100821 m_Network = INetwork::Create(networkOptions);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100822 ARMNN_ASSERT(m_Model.get() != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +0100823
telsoa01c577f2c2018-08-31 09:22:23 +0100824 if (m_Model->subgraphs.size() != 1)
825 {
826 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100827 fmt::format("Current TfLite parser only supports 1 subgraph. Current one has: {} {}",
828 m_Model->subgraphs.size(),
829 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100830 }
831
832 size_t subgraphIndex = 0;
Colm Donelan6350d272020-06-09 16:56:25 +0100833 size_t operatorIndex = 0;
834 try
telsoa01c577f2c2018-08-31 09:22:23 +0100835 {
Colm Donelan6350d272020-06-09 16:56:25 +0100836 for (SubgraphPtr const& subgraph : m_Model->subgraphs)
telsoa01c577f2c2018-08-31 09:22:23 +0100837 {
Colm Donelan6350d272020-06-09 16:56:25 +0100838 m_SubgraphConnections.emplace_back(subgraph->tensors.size());
839 for (OperatorPtr const& op : subgraph->operators)
telsoa01c577f2c2018-08-31 09:22:23 +0100840 {
Colm Donelan6350d272020-06-09 16:56:25 +0100841 auto const& opCodePtr = m_Model->operator_codes[op->opcode_index];
Jim Flynnfca233e2021-09-23 12:16:53 +0100842
843// work around the introduction of the deprecated_builtin_code introduced in 2.4 in a backwards compatible manner
Matthew Sloyan4d217c02021-10-07 11:48:58 +0100844#if defined(ARMNN_POST_TFLITE_2_3)
Jim Flynnfca233e2021-09-23 12:16:53 +0100845 auto builtinCode = std::max(opCodePtr->builtin_code,
846 static_cast<tflite::BuiltinOperator>(opCodePtr->deprecated_builtin_code));
847#else
telsoa01c577f2c2018-08-31 09:22:23 +0100848 auto builtinCode = opCodePtr->builtin_code;
Jim Flynnfca233e2021-09-23 12:16:53 +0100849#endif
telsoa01c577f2c2018-08-31 09:22:23 +0100850
851 if (builtinCode > tflite::BuiltinOperator_MAX)
852 {
James Ward58dec6b2020-09-11 17:32:44 +0100853 throw ParseException(fmt::format("Operator code {} is out of range 0-{}. "
854 "subgraph:{} operator idx:{}. {}",
855 builtinCode, tflite::BuiltinOperator_MAX, subgraphIndex,
856 operatorIndex, CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100857 }
858
859 // lookup and call the parser function
Colm Donelan6350d272020-06-09 16:56:25 +0100860 auto& parserFunction = m_ParserFunctions[builtinCode];
telsoa01c577f2c2018-08-31 09:22:23 +0100861 (this->*parserFunction)(subgraphIndex, operatorIndex);
Colm Donelan6350d272020-06-09 16:56:25 +0100862 ++operatorIndex;
telsoa01c577f2c2018-08-31 09:22:23 +0100863 }
telsoa01c577f2c2018-08-31 09:22:23 +0100864
Colm Donelan6350d272020-06-09 16:56:25 +0100865 SetupInputLayers(subgraphIndex);
866 SetupOutputLayers(subgraphIndex);
867 SetupConstantLayers(subgraphIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100868
Colm Donelan6350d272020-06-09 16:56:25 +0100869 ++subgraphIndex;
870 operatorIndex = 0;
telsoa01c577f2c2018-08-31 09:22:23 +0100871 }
telsoa01c577f2c2018-08-31 09:22:23 +0100872 }
Colm Donelan6350d272020-06-09 16:56:25 +0100873 catch (const ParseException& e)
telsoa01c577f2c2018-08-31 09:22:23 +0100874 {
Colm Donelan6350d272020-06-09 16:56:25 +0100875 std::stringstream errorString;
876 errorString << "Failed to parse operator #" << operatorIndex << " within subgraph #"
877 << subgraphIndex << " error: " << e.what();
878 ARMNN_LOG(error) << errorString.str();
879 std::stringstream errors;
880 errors << errorString.str() << "\n";
telsoa01c577f2c2018-08-31 09:22:23 +0100881 throw ParseException(errors.str());
882 }
883
884 // establish the connections from the layer outputs to the inputs of the subsequent layers
Colm Donelan6350d272020-06-09 16:56:25 +0100885 for (subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100886 {
887 for (size_t tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
888 {
889 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot != nullptr)
890 {
891 for (size_t inputSlotIdx = 0;
892 inputSlotIdx < m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size();
893 ++inputSlotIdx)
894 {
895 m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot->Connect(
896 *(m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots[inputSlotIdx]));
897 }
898 }
899 }
900 }
telsoa01c577f2c2018-08-31 09:22:23 +0100901 return std::move(m_Network);
902}
903
Mike Kelly5880b912022-01-28 16:18:54 +0000904std::unique_ptr<float[]> AsFloatArray(TfLiteParserImpl::BufferRawPtr bufferPtr,
905 const TensorInfo& tensorInfo)
906{
907 if (tensorInfo.GetDataType() == DataType::QAsymmS8 || tensorInfo.GetDataType() == DataType::QSymmS8 ||
908 tensorInfo.GetDataType() == DataType::QAsymmU8)
909 {
910 std::unique_ptr<float[]> buffer(new float[tensorInfo.GetNumElements()]);
911
912 if (tensorInfo.HasPerAxisQuantization())
913 {
914 unsigned int axis = tensorInfo.GetQuantizationDim().value();
915 auto axisDimensionality = tensorInfo.GetShape()[axis];
916 auto axisFactor = armnnUtils::GetNumElementsAfter(tensorInfo.GetShape(), axis);
917
918 for (unsigned int i = 0; i < tensorInfo.GetNumDimensions(); ++i)
919 {
920 unsigned int axisIndex = (i / axisFactor) % axisDimensionality;
921 buffer[i] = Dequantize<int8_t>(bufferPtr->data[i], tensorInfo.GetQuantizationScales()[axisIndex],
922 tensorInfo.GetQuantizationOffset());
923 }
924 }
925 else
926 {
927 for (unsigned int i = 0; i < tensorInfo.GetNumElements(); ++i)
928 {
929 buffer[i] = Dequantize<int8_t>(bufferPtr->data[i], tensorInfo.GetQuantizationScale(),
930 tensorInfo.GetQuantizationOffset());
931 }
932 }
933 return buffer;
934 }
935 throw ParseException(
936 fmt::format("Unsupported input/weights combination: Input {} not supported with Weights {}",
937 GetDataTypeName(DataType::Float32),
938 GetDataTypeName(tensorInfo.GetDataType()),
939 CHECK_LOCATION().AsString()));
940}
941
Kevin May7d96b162021-02-03 17:38:41 +0000942void TfLiteParserImpl::RegisterProducerOfTensor(size_t subgraphIndex,
943 size_t tensorIndex,
944 armnn::IOutputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +0100945{
946 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100947 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
948 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100949
950 TensorSlots & tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
951
Nikhil Rajd4d1c312022-08-03 18:20:59 +0100952 if (slot->GetOwningIConnectableLayer().GetType() != LayerType::Constant)
telsoa01c577f2c2018-08-31 09:22:23 +0100953 {
telsoa01c577f2c2018-08-31 09:22:23 +0100954
Nikhil Rajd4d1c312022-08-03 18:20:59 +0100955 // assuming there is only one producer for that tensor
956 if (tensorSlots.outputSlot != nullptr)
957 {
958 throw ParseException(fmt::format("Another layer has already registered itself as the producer of "
959 "subgraph:{} tensor:{} {}",
960 subgraphIndex,
961 tensorIndex,
962 CHECK_LOCATION().AsString()));
963 }
964 }
telsoa01c577f2c2018-08-31 09:22:23 +0100965 tensorSlots.outputSlot = slot;
966}
967
Kevin May7d96b162021-02-03 17:38:41 +0000968void TfLiteParserImpl::RegisterConsumerOfTensor(size_t subgraphIndex,
969 size_t tensorIndex,
970 armnn::IInputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +0100971{
972 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100973 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
974 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100975
Finn Williamsd4fa5452021-03-01 12:31:41 +0000976 TensorSlots& tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +0100977 tensorSlots.inputSlots.push_back(slot);
978}
979
Kevin May7d96b162021-02-03 17:38:41 +0000980void TfLiteParserImpl::ParseCustomOperator(size_t subgraphIndex, size_t operatorIndex)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100981{
982 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
983
984 // NOTE: By default we presume the custom operator is not supported
Kevin May7d96b162021-02-03 17:38:41 +0000985 auto customParserFunction = &TfLiteParserImpl::ParseUnsupportedOperator;
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100986
987 // Identify custom code defined for custom operator
988 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
989 const auto& customCode = m_Model->operator_codes[operatorPtr->opcode_index]->custom_code;
990
991 // Find parser function that correspondes to custom code (if any)
992 auto iterator = m_CustomParserFunctions.find(customCode);
993 if (iterator != m_CustomParserFunctions.end())
994 {
995 customParserFunction = iterator->second;
996 }
997
998 // Run parser function
999 (this->*customParserFunction)(subgraphIndex, operatorIndex);
1000}
1001
Kevin May7d96b162021-02-03 17:38:41 +00001002void TfLiteParserImpl::ParseUnsupportedOperator(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001003{
1004 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001005
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001006 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1007
1008 auto opcodeIndex = operatorPtr->opcode_index;
Jim Flynnfca233e2021-09-23 12:16:53 +01001009
1010// work around the introduction of the deprecated_builtin_code introduced in 2.4 in a backwards compatible manner
Matthew Sloyan4d217c02021-10-07 11:48:58 +01001011#if defined(ARMNN_POST_TFLITE_2_3)
Jim Flynnfca233e2021-09-23 12:16:53 +01001012 auto opcode = std::max(m_Model->operator_codes[opcodeIndex]->builtin_code,
1013 static_cast<tflite::BuiltinOperator>(m_Model->operator_codes[opcodeIndex]->deprecated_builtin_code));
1014#else
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001015 auto opcode = m_Model->operator_codes[opcodeIndex]->builtin_code;
Jim Flynnfca233e2021-09-23 12:16:53 +01001016#endif
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001017
1018 if (!m_Options || !m_Options.value().m_StandInLayerForUnsupported)
1019 {
1020 // Do not add StandInLayer, throw ParseException instead
1021 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01001022 fmt::format("Operator not supported. "
1023 "subgraph:{} operator:{} "
1024 "opcode_index:{} opcode:{} / {} {}",
1025 subgraphIndex,
1026 operatorIndex,
1027 opcodeIndex,
1028 opcode,
1029 tflite::EnumNameBuiltinOperator(opcode),
1030 CHECK_LOCATION().AsString()));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001031 }
1032
1033 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1034 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1035
Matthew Sloyan589e3e82020-09-11 16:17:48 +01001036 const unsigned int numInputs = armnn::numeric_cast<unsigned int>(inputs.size());
1037 const unsigned int numOutputs = armnn::numeric_cast<unsigned int>(outputs.size());
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001038
1039 StandInDescriptor descriptor(numInputs, numOutputs);
James Ward58dec6b2020-09-11 17:32:44 +01001040 auto layerName = fmt::format("StandIn:{}:{}:{}", subgraphIndex, operatorIndex, opcode);
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001041
1042 // Add a non-executable StandInLayer as a placeholder for any unsupported operator
1043 IConnectableLayer* layer = m_Network->AddStandInLayer(descriptor, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001044 ARMNN_ASSERT(layer != nullptr);
1045
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001046 for (unsigned int i = 0u; i < numOutputs; ++i)
1047 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01001048 layer->GetOutputSlot(i).SetTensorInfo(ToTensorInfo(outputs[i], true));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001049 }
1050
1051 auto inputTensorIds = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1052 auto outputTensorIds = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1053
1054 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIds);
1055 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIds);
telsoa01c577f2c2018-08-31 09:22:23 +01001056}
1057
mathad01b392e982021-04-07 12:07:30 +01001058void TfLiteParserImpl::ParseCast(size_t subgraphIndex, size_t operatorIndex)
1059{
1060 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1061
1062 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1063 CHECK_VALID_SIZE(inputs.size(), 1);
1064 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1065 CHECK_VALID_SIZE(outputs.size(), 1);
1066
1067 auto layerName = fmt::format("Cast:{}:{}", subgraphIndex, operatorIndex);
1068
1069 IConnectableLayer* layer = m_Network->AddCastLayer(layerName.c_str());
1070 ARMNN_ASSERT(layer != nullptr);
1071
1072 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1073 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1074
1075 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1076 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1077
1078 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1079 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1080}
1081
Kevin May7d96b162021-02-03 17:38:41 +00001082void TfLiteParserImpl::ParseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001083{
1084 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1085
Mike Kelly0d77ae12022-01-07 17:42:27 +00001086 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1087 const auto* options = operatorPtr->builtin_options.AsConv2DOptions();
telsoa01c577f2c2018-08-31 09:22:23 +01001088
1089 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1090
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001091 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1092 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1093 CHECK_VALID_SIZE(outputs.size(), 1);
1094
telsoa01c577f2c2018-08-31 09:22:23 +01001095 Convolution2dDescriptor desc;
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001096 inputs.size() == 3 ?
1097 desc.m_BiasEnabled = true : desc.m_BiasEnabled = false;
telsoa01c577f2c2018-08-31 09:22:23 +01001098 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1099 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +00001100 desc.m_DataLayout = armnn::DataLayout::NHWC;
Pablo Tellof0bd6832019-04-26 17:58:13 +01001101 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1102 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +00001103
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001104 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
telsoa01c577f2c2018-08-31 09:22:23 +01001105 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
1106
1107 // assuming input is NHWC
1108 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001109 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
telsoa01c577f2c2018-08-31 09:22:23 +01001110
1111 // assuming the filter is OHWI : Output, H, W, Input
1112 // which is essentially the same as NHWC
1113 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001114 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
telsoa01c577f2c2018-08-31 09:22:23 +01001115
Pablo Tellof0bd6832019-04-26 17:58:13 +01001116 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1117 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1118 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1119 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +01001120
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001121 // Add the first input and weights tensor to the registration list.
1122 // The constant weights will be added by SetupConstantLayers.
1123 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1124 std::vector<unsigned int> tensorIndexesToRegister = { inputTensorIndexes[0], inputTensorIndexes[1] };
telsoa01c577f2c2018-08-31 09:22:23 +01001125
James Ward58dec6b2020-09-11 17:32:44 +01001126 auto layerName = fmt::format("Conv2D:{}:{}", subgraphIndex, operatorIndex);
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001127 armnn::IConnectableLayer* layer = m_Network->AddConvolution2dLayer(desc, layerName.c_str());
telsoa01c577f2c2018-08-31 09:22:23 +01001128
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001129 if (IsConstTensor(inputs[1]) && inputTensorInfo.GetDataType() == DataType::Float32 &&
1130 (filterTensorInfo.GetDataType() == DataType::QAsymmU8 ||
1131 filterTensorInfo.GetDataType() == DataType::QAsymmS8))
telsoa01c577f2c2018-08-31 09:22:23 +01001132 {
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001133 m_ConstantsToDequantize.emplace_back(inputs[1]->buffer);
telsoa01c577f2c2018-08-31 09:22:23 +01001134 }
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001135
1136 if (desc.m_BiasEnabled)
telsoa01c577f2c2018-08-31 09:22:23 +01001137 {
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001138 armnn::TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
1139
1140 // Add the biases input to the registration list, a constant layer will be added by SetupConstantLayers.
1141 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
1142
1143 if (IsConstTensor(inputs[2]) && inputTensorInfo.GetDataType() == DataType::Float32 &&
1144 (filterTensorInfo.GetDataType() == DataType::QAsymmU8 ||
1145 filterTensorInfo.GetDataType() == DataType::QAsymmS8))
1146 {
1147 m_ConstantsToDequantize.emplace_back(inputs[2]->buffer);
1148 }
telsoa01c577f2c2018-08-31 09:22:23 +01001149 }
1150
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001151 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01001152
Sadik Armagand109a4d2020-07-28 10:42:13 +01001153 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
jimfly01c25411c2018-11-14 17:47:22 +00001154 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001155
1156 // register the input connection slots for the layer, connections are made after all layers have been created
1157 // only the tensors for the inputs are relevant, exclude the const tensors
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001158 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
telsoa01c577f2c2018-08-31 09:22:23 +01001159
jimfly01c25411c2018-11-14 17:47:22 +00001160 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +01001161 // register the output connection slots for the layer, connections are made after all layers have been created
1162 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001163 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, { outputTensorIndexes[0] });
telsoa01c577f2c2018-08-31 09:22:23 +01001164}
1165
Matthew Sloyan4d217c02021-10-07 11:48:58 +01001166// Conv3D support was added in TF 2.5, so for backwards compatibility a hash define is needed.
Cathal Corbett80b4ef02022-05-25 11:21:11 +01001167#if defined(ARMNN_POST_TFLITE_2_4)
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001168void TfLiteParserImpl::ParseConv3D(size_t subgraphIndex, size_t operatorIndex)
1169{
1170 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1171
1172 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1173 const auto* options = operatorPtr->builtin_options.AsConv3DOptions();
1174
1175 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1176
1177 Convolution3dDescriptor desc;
1178 desc.m_BiasEnabled = false;
1179 desc.m_DataLayout = armnn::DataLayout::NDHWC;
1180 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1181 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1182 desc.m_StrideZ = CHECKED_NON_NEGATIVE(options->stride_d);
1183 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1184 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
1185 desc.m_DilationZ = CHECKED_NON_NEGATIVE(options->dilation_d_factor);
1186
1187 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1188 CHECK_VALID_SIZE(inputs.size(), 2, 3);
1189
1190 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1191 CHECK_VALID_SIZE(outputs.size(), 1);
1192
1193 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1194 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
1195
1196 // Assuming input is NDHWC
1197 unsigned int inputDepth = inputTensorInfo.GetShape()[1];
1198 unsigned int inputHeight = inputTensorInfo.GetShape()[2];
1199 unsigned int inputWidth = inputTensorInfo.GetShape()[3];
1200
1201 // Assuming the filter is DHWIO : Depth, Height, Width, OutputChannels, InputChannels
1202 unsigned int filterDepth = filterTensorInfo.GetShape()[0];
1203 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1204 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1205
1206 CalcPadding(inputDepth, filterDepth, desc.m_StrideZ,
Teresa Charlin502ab942022-03-23 17:23:07 +00001207 desc.m_DilationZ, desc.m_PadFront, desc.m_PadBack, options->padding);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001208 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1209 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1210 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1211 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
1212
Mike Kelly5880b912022-01-28 16:18:54 +00001213 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo, inputTensorInfo.GetDataType());
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001214
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001215 auto layerName = fmt::format("Conv3D:{}:{}", subgraphIndex, operatorIndex);
1216
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001217 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1218 // Add the first input and weights tensor to the registration list.
1219 // The constant weights will be added by SetupConstantLayers.
1220 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0], inputTensorIndexes[1]};
1221
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001222 if (inputs.size() == 3)
1223 {
1224 desc.m_BiasEnabled = true;
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001225
1226 // Add the biases input to the registration list, a constant layer will be added by SetupConstantLayers.
1227 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001228 }
1229
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001230 armnn::IConnectableLayer* layer = m_Network->AddConvolution3dLayer(desc, layerName.c_str());
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001231 ARMNN_ASSERT(layer != nullptr);
1232
1233 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1234 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1235
1236 // Register the input connection slots for the layer, connections are made after all layers have been created
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001237 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001238
1239 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1240 // Register the output connection slots for the layer, connections are made after all layers have been created
1241 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1242 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1243}
Matthew Sloyan4d217c02021-10-07 11:48:58 +01001244#endif
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001245
Kevin May7d96b162021-02-03 17:38:41 +00001246void TfLiteParserImpl::ParseDepthwiseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001247{
1248 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1249
Mike Kelly0d77ae12022-01-07 17:42:27 +00001250 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1251 const auto* options = operatorPtr->builtin_options.AsDepthwiseConv2DOptions();
telsoa01c577f2c2018-08-31 09:22:23 +01001252
1253 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1254
1255 DepthwiseConvolution2dDescriptor desc;
telsoa01c577f2c2018-08-31 09:22:23 +01001256 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1257 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +00001258 desc.m_DataLayout = armnn::DataLayout::NHWC;
Matthew Jacksond6a9dee2019-07-22 13:53:24 +01001259 CHECKED_NON_NEGATIVE(options->depth_multiplier);
telsoa01c577f2c2018-08-31 09:22:23 +01001260
1261 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1262 CHECK_VALID_SIZE(inputs.size(), 2, 3);
Cathal Corbett06902652022-04-14 17:55:11 +01001263 if (inputs.size() == 3)
1264 {
1265 desc.m_BiasEnabled = true;
1266 }
1267
telsoa01c577f2c2018-08-31 09:22:23 +01001268 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1269 CHECK_VALID_SIZE(outputs.size(), 1);
Pablo Tellof0bd6832019-04-26 17:58:13 +01001270 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1271 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +00001272
telsoa01c577f2c2018-08-31 09:22:23 +01001273 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Jan Eilers7612bd62021-04-06 17:29:03 +01001274 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
telsoa01c577f2c2018-08-31 09:22:23 +01001275
Matteo Martincigh747ef822018-12-18 09:26:39 +00001276 // Assuming input is NHWC
telsoa01c577f2c2018-08-31 09:22:23 +01001277 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1278 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
Matteo Martincigh747ef822018-12-18 09:26:39 +00001279
1280 // TensorflowLite weights come in the format [1, H, W, I * M]
telsoa01c577f2c2018-08-31 09:22:23 +01001281 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1282 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1283
Pablo Tellof0bd6832019-04-26 17:58:13 +01001284 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1285 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1286 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1287 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +01001288
Jan Eilers53ef7952021-06-02 12:01:25 +01001289 // ArmNN uses the same filter tensor layout at TfLite [1, H, W, O] no need for any permutation
James Ward58dec6b2020-09-11 17:32:44 +01001290 auto layerName = fmt::format("DepthwiseConv2D:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001291
Cathal Corbett06902652022-04-14 17:55:11 +01001292 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1293 // Add the first input and weights tensor to the registration list.
1294 // The constant weights will be added by SetupConstantLayers.
1295 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0], inputTensorIndexes[1]};
1296
1297 armnn::IConnectableLayer* layer = m_Network->AddDepthwiseConvolution2dLayer(desc, layerName.c_str());
1298
1299 if (desc.m_BiasEnabled)
telsoa01c577f2c2018-08-31 09:22:23 +01001300 {
1301 desc.m_BiasEnabled = true;
1302 TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Cathal Corbett06902652022-04-14 17:55:11 +01001303
1304 // Add the biases input to the registration list, a constant layer will be added by SetupConstantLayers.
1305 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
telsoa01c577f2c2018-08-31 09:22:23 +01001306 }
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001307 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01001308
Sadik Armagand109a4d2020-07-28 10:42:13 +01001309 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
jimfly01c25411c2018-11-14 17:47:22 +00001310 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001311
1312 // register the input connection slots for the layer, connections are made after all layers have been created
1313 // only the tensors for the inputs are relevant, exclude the const tensors
Cathal Corbett06902652022-04-14 17:55:11 +01001314 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
telsoa01c577f2c2018-08-31 09:22:23 +01001315
jimfly01c25411c2018-11-14 17:47:22 +00001316 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +01001317 // register the output connection slots for the layer, connections are made after all layers have been created
1318 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1319 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1320}
1321
Kevin May7d96b162021-02-03 17:38:41 +00001322void TfLiteParserImpl::ParseDequantize(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsed66d142019-12-06 09:55:55 +00001323{
1324 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1325
1326 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1327 CHECK_VALID_SIZE(inputs.size(), 1);
1328
1329 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1330 CHECK_VALID_SIZE(outputs.size(), 1);
1331
James Ward58dec6b2020-09-11 17:32:44 +01001332 auto layerName = fmt::format("Dequantize:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsed66d142019-12-06 09:55:55 +00001333
1334 IConnectableLayer* layer = m_Network->AddDequantizeLayer(layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001335 ARMNN_ASSERT(layer != nullptr);
Finn Williamsed66d142019-12-06 09:55:55 +00001336
Sadik Armagand109a4d2020-07-28 10:42:13 +01001337 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Finn Williamsed66d142019-12-06 09:55:55 +00001338 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1339
1340 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1341 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1342
1343 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1344 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1345}
1346
Teresa Charlin3ab85482021-06-08 16:59:29 +01001347void TfLiteParserImpl::ParseExpandDims(size_t subgraphIndex, size_t operatorIndex)
1348{
1349 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1350
1351 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1352 CHECK_VALID_SIZE(inputs.size(), 2);
1353
1354 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1355 CHECK_VALID_SIZE(outputs.size(), 1);
1356
1357 auto layerName = fmt::format("ExpandDims:{}:{}", subgraphIndex, operatorIndex);
1358
1359 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1360 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1361
1362 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1363
1364 ReshapeDescriptor reshapeDesc;
Finn Williamsb49ed182021-06-29 15:50:08 +01001365
1366 if (outputTensorInfo.GetShape().AreAllDimensionsSpecified())
1367 {
1368 reshapeDesc.m_TargetShape = outputTensorInfo.GetShape();
1369 }
1370 else
1371 {
1372 int32_t axis = inputs[1]->shape[0];
1373
1374 int32_t inputDimSize = static_cast<int32_t>(inputTensorInfo.GetShape().GetNumDimensions());
1375
1376 if (axis > inputDimSize || axis < 0 - (inputDimSize + 1))
1377 {
1378 throw ParseException("axis must be in range [0 - (inputDimSize + 1), inputDimSize] inclusive");
1379 }
1380
1381 if(axis < 0)
1382 {
1383 axis = inputDimSize + axis + 1;
1384 }
1385
Rob Hughesd812a312021-08-06 13:10:53 +01001386 std::vector<unsigned int> shape(static_cast<unsigned int>(inputDimSize) + 1);
Finn Williamsb49ed182021-06-29 15:50:08 +01001387 unsigned int inputShapeIndex = 0;
1388 for (unsigned int i = 0; i < static_cast<unsigned int>(inputDimSize + 1); ++i)
1389 {
1390 if (i == static_cast<unsigned int>(axis))
1391 {
1392 shape[i] = 1;
1393 }
1394 else
1395 {
1396 shape[i] = inputTensorInfo.GetShape()[inputShapeIndex];
1397 ++inputShapeIndex;
1398 }
1399 }
1400
Rob Hughesd812a312021-08-06 13:10:53 +01001401 reshapeDesc.m_TargetShape = TensorShape(static_cast<unsigned int>(inputDimSize + 1), shape.data());
Finn Williamsb49ed182021-06-29 15:50:08 +01001402 }
Teresa Charlin3ab85482021-06-08 16:59:29 +01001403
1404 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
1405 ARMNN_ASSERT(layer != nullptr);
1406 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1407
1408 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1409 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1410
1411 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1412 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1413}
1414
Kevin May7d96b162021-02-03 17:38:41 +00001415void TfLiteParserImpl::ParseTranspose(size_t subgraphIndex, size_t operatorIndex)
Keith Davis4cd29a02019-09-09 14:49:20 +01001416{
1417 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1418
1419 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Kevin May85d92602019-09-27 17:21:06 +01001420 CHECK_VALID_SIZE(inputs.size(), 1, 2);
Keith Davis4cd29a02019-09-09 14:49:20 +01001421
1422 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1423 CHECK_VALID_SIZE(outputs.size(), 1);
1424
James Ward58dec6b2020-09-11 17:32:44 +01001425 auto layerName = fmt::format("Transpose:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly08759e22020-03-02 11:41:31 +00001426 TransposeDescriptor desc;
Keith Davis4cd29a02019-09-09 14:49:20 +01001427
josh minorba424d22019-11-13 10:55:17 -06001428 if (inputs.size() == 2)
Kevin May85d92602019-09-27 17:21:06 +01001429 {
1430 armnn::TensorInfo permuteTensorInfo = ToTensorInfo(inputs[1]);
1431 BufferRawPtr permuteBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
josh minorba424d22019-11-13 10:55:17 -06001432 auto numPermVecElements = permuteTensorInfo.GetNumElements();
1433 std::vector<unsigned int> permuteShape(numPermVecElements);
Kevin May85d92602019-09-27 17:21:06 +01001434 ::memcpy(permuteShape.data(), permuteBufferPtr->data.data(), permuteTensorInfo.GetNumBytes());
Mike Kelly08759e22020-03-02 11:41:31 +00001435 PermutationVector permutationVector(permuteShape.data(), permuteTensorInfo.GetNumElements());
Kevin May85d92602019-09-27 17:21:06 +01001436
Mike Kelly08759e22020-03-02 11:41:31 +00001437 desc = TransposeDescriptor(permutationVector);
Kevin May85d92602019-09-27 17:21:06 +01001438 }
1439
James Conroy05102392020-06-24 15:39:55 +01001440 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001441 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001442 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Keith Davis4cd29a02019-09-09 14:49:20 +01001443
James Conroy05102392020-06-24 15:39:55 +01001444 IConnectableLayer* layer = m_Network->AddTransposeLayer(desc, layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001445 ARMNN_ASSERT(layer != nullptr);
Keith Davis4cd29a02019-09-09 14:49:20 +01001446 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1447
1448 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1449 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1450
1451 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1452 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1453}
1454
Kevin May7d96b162021-02-03 17:38:41 +00001455void TfLiteParserImpl::ParseTransposeConv(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001456{
1457 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1458
Mike Kelly0d77ae12022-01-07 17:42:27 +00001459 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1460 const auto* options = operatorPtr->builtin_options.AsTransposeConvOptions();
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001461
1462 TransposeConvolution2dDescriptor desc;
1463 desc.m_BiasEnabled = false;
1464 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1465 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1466 desc.m_DataLayout = armnn::DataLayout::NHWC;
1467
1468 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
David Monahan61683802021-01-12 09:11:07 +00001469 if (inputs.size() == 4)
1470 {
1471 desc.m_BiasEnabled = true;
1472 }
1473 else
1474 {
1475 CHECK_VALID_SIZE(inputs.size(), 3);
1476 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001477
1478 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1479 CHECK_VALID_SIZE(outputs.size(), 1);
1480
Colm Donelan0ad3ef12020-07-03 15:54:28 +01001481 if (inputs[0])
1482 {
1483 armnn::TensorInfo tensorInfo = ToTensorInfo(inputs[0]);
1484 std::vector<int> output_shape(tensorInfo.GetNumElements());
1485 if (tensorInfo.GetDataType() == DataType::Signed32)
1486 {
1487 ::memcpy(output_shape.data(), GetBuffer(m_Model, inputs[0]->buffer)->data.data(), tensorInfo.GetNumBytes());
1488 }
1489 if (tensorInfo.GetDataType() == DataType::QAsymmU8)
1490 {
1491 for(unsigned int i=0; i < tensorInfo.GetNumElements(); i++)
1492 {
1493 output_shape[i] = GetBuffer(m_Model, inputs[0]->buffer)->data.data()[i];
1494 }
1495 }
1496 // Change from signed to unsigned int to store in TransposeConvolution2dDescriptor.
1497 for (int dimension : output_shape)
1498 {
1499 desc.m_OutputShape.push_back(static_cast<unsigned int>(dimension));
1500 }
1501 desc.m_OutputShapeEnabled = true;
1502 }
Matthew Jacksonccb25ea2019-08-20 17:18:33 +01001503 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[2]);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001504 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
1505
1506 // TfLite uses NHWC tensors
1507 const unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1508 const unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1509
1510 const unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1511 const unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1512
1513 CalcPadding(inputHeight,
1514 filterHeight,
1515 desc.m_StrideY,
1516 1, // DilationY
1517 desc.m_PadTop,
1518 desc.m_PadBottom,
1519 options->padding);
1520
1521 CalcPadding(inputWidth,
1522 filterWidth,
1523 desc.m_StrideX,
1524 1, // DilationX
1525 desc.m_PadLeft,
1526 desc.m_PadRight,
1527 options->padding);
1528
Mike Kelly5880b912022-01-28 16:18:54 +00001529 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo, inputTensorInfo.GetDataType());
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001530
1531 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01001532 auto layerName = fmt::format("TransposeConv:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001533
David Monahan61683802021-01-12 09:11:07 +00001534 if (desc.m_BiasEnabled)
1535 {
1536 auto biasTensorInfo = ToTensorInfo(inputs[3]);
Mike Kelly5880b912022-01-28 16:18:54 +00001537 auto biasConstTensor = CreateConstTensorNonPermuted(inputs[3], biasTensorInfo, inputTensorInfo.GetDataType());
David Monahan61683802021-01-12 09:11:07 +00001538 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Mike Kelly5880b912022-01-28 16:18:54 +00001539 filterTensorAndData.first,
1540 biasConstTensor.first,
David Monahan61683802021-01-12 09:11:07 +00001541 layerName.c_str());
1542 }
1543 else
1544 {
1545 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Mike Kelly5880b912022-01-28 16:18:54 +00001546 filterTensorAndData.first,
David Monahan61683802021-01-12 09:11:07 +00001547 EmptyOptional(),
1548 layerName.c_str());
1549 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001550
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001551 ARMNN_ASSERT(layer != nullptr);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001552
Sadik Armagand109a4d2020-07-28 10:42:13 +01001553 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001554 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1555
1556 // only the tensors for the inputs are relevant, exclude the const (filter) tensor
1557 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Matthew Jacksonccb25ea2019-08-20 17:18:33 +01001558 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[2]});
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001559
1560 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1561 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1562}
1563
Kevin May7d96b162021-02-03 17:38:41 +00001564void TfLiteParserImpl::ParseAveragePool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001565{
1566 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Average);
1567}
1568
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001569void TfLiteParserImpl::ParseBatchMatMul(size_t subgraphIndex, size_t operatorIndex)
1570{
1571 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1572
1573 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1574 CHECK_VALID_SIZE(inputs.size(), 2);
1575
1576 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1577 CHECK_VALID_SIZE(outputs.size(), 1);
1578
1579 auto layerName = fmt::format("BatchMatMul:{}:{}", subgraphIndex, operatorIndex);
1580
1581 TensorInfo inputXTensorInfo = ToTensorInfo(inputs[0]);
1582 TensorInfo inputYTensorInfo = ToTensorInfo(inputs[1]);
1583
1584 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1585
1586 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1587 const auto* options = operatorPtr->builtin_options.AsBatchMatMulOptions();
1588
1589 BatchMatMulDescriptor descriptor(false,
1590 false,
1591 options->adj_x,
1592 options->adj_y);
1593 // Arbitrary DataLayout
1594
1595 IConnectableLayer* layer = m_Network->AddBatchMatMulLayer(descriptor, layerName.c_str());
1596 ARMNN_ASSERT(layer != nullptr);
1597
1598 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1599
1600 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1601 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
1602
1603 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1604 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1605}
1606
Kevin May7d96b162021-02-03 17:38:41 +00001607void TfLiteParserImpl::ParseBatchToSpaceND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001608{
1609 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1610
1611 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1612 CHECK_VALID_SIZE(inputs.size(), 3);
1613
1614 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1615 CHECK_VALID_SIZE(outputs.size(), 1);
1616
1617 armnn::TensorInfo blockShapeTensorInfo = ToTensorInfo(inputs[1]);
1618 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1619
1620 armnn::TensorInfo cropsTensorInfo = ToTensorInfo(inputs[2]);
1621 BufferRawPtr cropsBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1622
1623 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1624 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1625
1626 std::vector<unsigned int> cropsVector(cropsTensorInfo.GetNumElements());
1627 ::memcpy(cropsVector.data(), cropsBufferPtr->data.data(), cropsTensorInfo.GetNumBytes());
1628
1629 size_t step = 2;
1630 std::vector<std::pair<unsigned int, unsigned int>> crops;
1631 for (unsigned int i = 0; i < cropsTensorInfo.GetNumElements() / step; ++i)
1632 {
1633 crops.emplace_back(cropsVector[i * step], cropsVector[i * step + 1]);
1634 }
1635
1636 armnn::BatchToSpaceNdDescriptor desc;
1637 desc.m_BlockShape = blockShape;
1638 desc.m_Crops = crops;
1639 desc.m_DataLayout = armnn::DataLayout::NHWC;
1640
James Ward58dec6b2020-09-11 17:32:44 +01001641 auto layerName = fmt::format("BatchToSpaceND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001642
James Conroy05102392020-06-24 15:39:55 +01001643 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001644 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001645 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1646
1647 IConnectableLayer* layer = m_Network->AddBatchToSpaceNdLayer(desc, layerName.c_str());
1648 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001649 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1650
1651 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1652 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1653
1654 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1655 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1656}
1657
Kevin May7d96b162021-02-03 17:38:41 +00001658void TfLiteParserImpl::ParseL2Normalization(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson28c94572019-07-18 10:47:03 +01001659{
1660 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1661
1662 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1663 CHECK_VALID_SIZE(inputs.size(), 1);
1664
1665 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1666 CHECK_VALID_SIZE(outputs.size(), 1);
1667
1668 L2NormalizationDescriptor desc;
1669 desc.m_DataLayout = armnn::DataLayout::NHWC;
James Ward58dec6b2020-09-11 17:32:44 +01001670 auto layerName = fmt::format("L2Normalization:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson28c94572019-07-18 10:47:03 +01001671 IConnectableLayer* layer = m_Network->AddL2NormalizationLayer(desc, layerName.c_str());
1672
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001673 ARMNN_ASSERT(layer != nullptr);
Matthew Jackson28c94572019-07-18 10:47:03 +01001674
Sadik Armagand109a4d2020-07-28 10:42:13 +01001675 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jackson28c94572019-07-18 10:47:03 +01001676 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1677
1678 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1679 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1680
1681 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1682 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1683}
1684
Kevin May7d96b162021-02-03 17:38:41 +00001685void TfLiteParserImpl::ParseMaxPool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001686{
1687 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Max);
1688}
1689
Kevin May7d96b162021-02-03 17:38:41 +00001690void TfLiteParserImpl::ParseMaximum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001691{
1692 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1693
1694 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1695 CHECK_VALID_SIZE(inputs.size(), 2);
1696
1697 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1698 CHECK_VALID_SIZE(outputs.size(), 1);
1699
James Ward58dec6b2020-09-11 17:32:44 +01001700 auto layerName = fmt::format("Maximum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01001701
1702 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1703 TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1704 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001705
Sadik Armagand109a4d2020-07-28 10:42:13 +01001706 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001707 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1708
1709 IConnectableLayer* layer = m_Network->AddMaximumLayer(layerName.c_str());
1710 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001711 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1712
1713 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001714 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001715
1716 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1717 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1718}
1719
Kevin May7d96b162021-02-03 17:38:41 +00001720void TfLiteParserImpl::ParseMinimum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001721{
1722 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1723
1724 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1725 CHECK_VALID_SIZE(inputs.size(), 2);
1726
1727 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1728 CHECK_VALID_SIZE(outputs.size(), 1);
1729
James Ward58dec6b2020-09-11 17:32:44 +01001730 auto layerName = fmt::format("Minimum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01001731
1732 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1733 TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1734 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001735
Sadik Armagand109a4d2020-07-28 10:42:13 +01001736 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001737 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1738
1739 IConnectableLayer* layer = m_Network->AddMinimumLayer(layerName.c_str());
1740 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001741 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1742
1743 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001744 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001745
1746 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1747 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1748}
1749
Kevin May7d96b162021-02-03 17:38:41 +00001750void TfLiteParserImpl::ParsePool(size_t subgraphIndex,
1751 size_t operatorIndex,
1752 PoolingAlgorithm algorithm)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001753{
1754 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1755
Mike Kelly0d77ae12022-01-07 17:42:27 +00001756 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1757 const auto* options = operatorPtr->builtin_options.AsPool2DOptions();
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001758
1759 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1760
1761 std::string layerName;
1762
1763 switch (algorithm)
1764 {
1765 case PoolingAlgorithm::Average:
1766 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01001767 fmt::format("AveragePool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001768 break;
1769 case PoolingAlgorithm::Max:
1770 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01001771 fmt::format("MaxPool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001772 break;
1773 default:
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001774 ARMNN_ASSERT_MSG(false, "Unsupported Pooling Algorithm");
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001775 }
1776
1777 Pooling2dDescriptor desc;
1778
1779 desc.m_PoolType = algorithm;
1780 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1781 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1782 desc.m_PoolWidth = CHECKED_NON_NEGATIVE(options->filter_width);
1783 desc.m_PoolHeight = CHECKED_NON_NEGATIVE(options->filter_height);
1784 desc.m_PaddingMethod = PaddingMethod::Exclude;
1785 desc.m_OutputShapeRounding = OutputShapeRounding::Floor;
jimfly01c25411c2018-11-14 17:47:22 +00001786 desc.m_DataLayout = armnn::DataLayout::NHWC;
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001787
1788 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1789 CHECK_VALID_SIZE(inputs.size(), 1);
1790 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1791
1792 // assuming input is NHWC
1793 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1794 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1795
Pablo Tellof0bd6832019-04-26 17:58:13 +01001796 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, 1u,
1797 desc.m_PadTop, desc.m_PadBottom, options->padding);
1798 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, 1u,
1799 desc.m_PadLeft, desc.m_PadRight, options->padding);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001800
1801 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1802 CHECK_VALID_SIZE(outputs.size(), 1);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001803
Sadik Armagand109a4d2020-07-28 10:42:13 +01001804 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001805 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1806
1807 IConnectableLayer* layer = m_Network->AddPooling2dLayer(desc, layerName.c_str());
1808 ARMNN_ASSERT(layer != nullptr);
jimfly01c25411c2018-11-14 17:47:22 +00001809 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001810
1811 // register the input connection slots for the layer, connections are made after all layers have been created
1812 // only the tensors for the inputs are relevant, exclude the const tensors
1813 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +00001814 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001815
jimfly01c25411c2018-11-14 17:47:22 +00001816 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001817 // register the output connection slots for the layer, connections are made after all layers have been created
1818 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1819 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1820}
1821
Kevin May7d96b162021-02-03 17:38:41 +00001822void TfLiteParserImpl::ParseSlice(size_t subgraphIndex, size_t operatorIndex)
josh minorba424d22019-11-13 10:55:17 -06001823{
1824 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1825
1826 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1827 CHECK_VALID_SIZE(inputs.size(), 3);
1828 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1829 CHECK_VALID_SIZE(outputs.size(), 1);
1830
1831 SliceDescriptor desc;
1832
1833 // set begin tensor info for slice descriptor
1834 armnn::TensorInfo beginTensorInfo = ToTensorInfo(inputs[1]);
1835 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1836
1837 std::vector<unsigned int> begin(beginTensorInfo.GetNumElements());
1838 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
1839
1840 // set size tensor info for slice descriptor
1841 armnn::TensorInfo sizeTensorInfo = ToTensorInfo(inputs[2]);
1842 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1843
Cathal Corbettde33dda2022-09-20 16:40:09 +01001844 std::vector<int> signedSize(sizeTensorInfo.GetNumElements(), 1);
1845
1846 // if size buffer data is not specified, all contents of size vector remain as values of 1
1847 if (sizeBufferPtr->data.data())
1848 {
1849 ::memcpy(signedSize.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
1850 }
1851
josh minorba424d22019-11-13 10:55:17 -06001852 std::vector<unsigned int> size(sizeTensorInfo.GetNumElements());
Mike Kelly7ba84d62021-09-10 15:27:19 +01001853 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1854
1855 for (unsigned int i = 0; i < signedSize.size(); ++i)
1856 {
1857 int signedValue = signedSize[i];
Jim Flynnfca233e2021-09-23 12:16:53 +01001858
Mike Kelly7ba84d62021-09-10 15:27:19 +01001859 if (signedValue < -1 || signedValue > static_cast<int>(inputTensorInfo.GetShape()[i] - begin[i]))
1860 {
1861 throw ParseException(fmt::format("Invalid value for size {} size must be in range "
1862 "[-1, inputDimSize - begin] [-1, {}] inclusive {}",
1863 signedValue,
1864 inputTensorInfo.GetShape()[i] - begin[i],
1865 CHECK_LOCATION().AsString()));
1866 }
1867
1868 if (signedValue == -1)
1869 {
1870 size[i] = inputTensorInfo.GetShape()[i] - begin[i];
1871 }
1872 else
1873 {
1874 size[i] = static_cast<unsigned int>(signedValue);
1875 }
1876 }
1877
josh minorba424d22019-11-13 10:55:17 -06001878 desc = SliceDescriptor(begin, size);
1879
James Ward58dec6b2020-09-11 17:32:44 +01001880 auto layerName = fmt::format("Slice:{}:{}", subgraphIndex, operatorIndex);
josh minorba424d22019-11-13 10:55:17 -06001881
Sadik Armagand109a4d2020-07-28 10:42:13 +01001882 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001883 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1884
1885 IConnectableLayer* const layer = m_Network->AddSliceLayer(desc, layerName.c_str());
josh minorba424d22019-11-13 10:55:17 -06001886 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1887
1888 // register the input connection slots for the layer, connections are made after all layers have been created
1889 // only the tensors for the inputs are relevant, exclude the const tensors
1890 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1891 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1892
1893 // register the output connection slots for the layer, connections are made after all layers have been created
1894 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1895 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1896}
1897
Kevin May7d96b162021-02-03 17:38:41 +00001898void TfLiteParserImpl::ParseSoftmax(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001899{
1900 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00001901 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1902 const auto* options = operatorPtr->builtin_options.AsSoftmaxOptions();
telsoa01c577f2c2018-08-31 09:22:23 +01001903
1904 SoftmaxDescriptor desc;
1905 desc.m_Beta = options->beta;
1906
1907 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1908 CHECK_VALID_SIZE(inputs.size(), 1);
1909 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1910 CHECK_VALID_SIZE(outputs.size(), 1);
1911
James Ward58dec6b2020-09-11 17:32:44 +01001912 auto layerName = fmt::format("Softmax:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001913 IConnectableLayer* const layer = m_Network->AddSoftmaxLayer(desc, layerName.c_str());
1914
Sadik Armagand109a4d2020-07-28 10:42:13 +01001915 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
telsoa01c577f2c2018-08-31 09:22:23 +01001916 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1917
1918 // register the input connection slots for the layer, connections are made after all layers have been created
1919 // only the tensors for the inputs are relevant, exclude the const tensors
1920 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1921 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1922
1923 // register the output connection slots for the layer, connections are made after all layers have been created
1924 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1925 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1926}
1927
Teresa Charlinfd33a692022-06-29 15:35:57 +01001928void TfLiteParserImpl::ParseLogSoftmax(size_t subgraphIndex, size_t operatorIndex)
1929{
1930 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1931
1932 LogSoftmaxDescriptor desc;
1933
1934 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1935 CHECK_VALID_SIZE(inputs.size(), 1);
1936 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1937 CHECK_VALID_SIZE(outputs.size(), 1);
1938
1939 auto layerName = fmt::format("LogSoftmax:{}:{}", subgraphIndex, operatorIndex);
1940 IConnectableLayer* const layer = m_Network->AddLogSoftmaxLayer(desc, layerName.c_str());
1941
1942 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1943 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1944
1945 // register the input connection slots for the layer, connections are made after all layers have been created
1946 // only the tensors for the inputs are relevant, exclude the const tensors
1947 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1948 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1949
1950 // register the output connection slots for the layer, connections are made after all layers have been created
1951 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1952 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1953}
1954
Kevin May7d96b162021-02-03 17:38:41 +00001955void TfLiteParserImpl::ParseSpaceToBatchND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001956{
1957 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1958
1959 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1960 CHECK_VALID_SIZE(inputs.size(), 3);
1961
1962 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1963 CHECK_VALID_SIZE(outputs.size(), 1);
1964
1965 armnn::TensorInfo blockShapeTensorInfo = ToTensorInfo(inputs[1]);
1966 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1967
1968 armnn::TensorInfo padListTensorInfo = ToTensorInfo(inputs[2]);
1969 BufferRawPtr padListBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1970
1971 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1972 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1973
1974 std::vector<unsigned int> padListVector(padListTensorInfo.GetNumElements());
1975 ::memcpy(padListVector.data(), padListBufferPtr->data.data(), padListTensorInfo.GetNumBytes());
1976
1977 size_t step = 2;
1978 std::vector<std::pair<unsigned int, unsigned int>> padList;
1979 for (unsigned int i = 0; i < padListTensorInfo.GetNumElements() / step; ++i)
1980 {
1981 padList.emplace_back(padListVector[i * step], padListVector[i * step + 1]);
1982 }
1983
1984 armnn::SpaceToBatchNdDescriptor desc;
1985 desc.m_BlockShape = blockShape;
1986 desc.m_PadList = padList;
1987 desc.m_DataLayout = armnn::DataLayout::NHWC;
1988
James Ward58dec6b2020-09-11 17:32:44 +01001989 auto layerName = fmt::format("SpaceToBatchND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001990
James Conroy05102392020-06-24 15:39:55 +01001991 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001992 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001993 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1994
1995 IConnectableLayer* layer = m_Network->AddSpaceToBatchNdLayer(desc, layerName.c_str());
1996 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001997 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1998
1999 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2000 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2001
2002 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2003 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2004}
2005
Teresa Charlin3ab85482021-06-08 16:59:29 +01002006armnn::TensorInfo TfLiteParserImpl::OutputShapeOfSqueeze(std::vector<uint32_t> squeezeDims,
Mike Kelly0d77ae12022-01-07 17:42:27 +00002007 const armnn::TensorInfo& inputTensorInfo)
telsoa01c577f2c2018-08-31 09:22:23 +01002008{
Teresa Charlin3ab85482021-06-08 16:59:29 +01002009 CHECK_VALID_SIZE(squeezeDims.size(), 0, 1, 2, 3, 4);
telsoa01c577f2c2018-08-31 09:22:23 +01002010 static const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
2011
2012 if (inputTensorInfo.GetNumDimensions() > 4)
2013 {
2014 std::stringstream ss;
2015 ss << "Input tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
2016 << " shape:" << inputTensorInfo.GetShape() << " "
2017 << CHECK_LOCATION().AsString();
2018 throw ParseException(ss.str());
2019 }
2020
2021 if (squeezeDims.empty())
2022 {
2023 squeezeDims.assign(dimensionSequence,
2024 dimensionSequence+inputTensorInfo.GetNumDimensions());
2025 }
2026
2027 std::vector<uint32_t> outputDims;
2028 for(unsigned int i = 0; i < inputTensorInfo.GetNumDimensions(); i++)
2029 {
2030 bool skipSqueeze = (std::find(squeezeDims.begin(), squeezeDims.end(), i) == squeezeDims.end());
2031 auto currentDimension = inputTensorInfo.GetShape()[i];
2032 if (skipSqueeze || currentDimension != 1)
2033 {
2034 outputDims.push_back(currentDimension);
2035 }
2036 }
2037
2038 if (outputDims.size() > 4)
2039 {
2040 std::stringstream ss;
2041 ss << "Output tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
2042 << " shape:" << inputTensorInfo.GetShape() << " "
2043 << CHECK_LOCATION().AsString();
2044 throw ParseException(ss.str());
2045 }
2046
2047 TensorShape outShape = TensorShape(static_cast<unsigned int>(outputDims.size()),
2048 outputDims.data());
2049
2050 // we need to preserve the tensor type and the quantization data as well
2051 TensorInfo outTensorInfo = inputTensorInfo;
2052 outTensorInfo.SetShape(outShape);
2053
2054 return outTensorInfo;
2055}
2056
Keith Davis0176fd82021-06-01 17:36:32 +01002057void TfLiteParserImpl::ParseShape(size_t subgraphIndex, size_t operatorIndex)
2058{
2059 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2060
2061 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2062 CHECK_VALID_SIZE(inputs.size(), 1);
2063 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2064 CHECK_VALID_SIZE(outputs.size(), 1);
2065
2066 auto layerName = fmt::format("Shape:{}:{}", subgraphIndex, operatorIndex);
2067
2068 IConnectableLayer* layer = m_Network->AddShapeLayer(layerName.c_str());
2069 ARMNN_ASSERT(layer != nullptr);
2070
2071
2072 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
2073 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2074
2075 // Check if output tensor type is Signed32 or Signed64
2076 if (outputTensorInfo.GetDataType() != armnn::DataType::Signed32 &&
2077 outputTensorInfo.GetDataType() != armnn::DataType::Signed64)
2078 {
2079 throw ParseException(
2080 fmt::format(
2081 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
2082 CHECK_LOCATION().AsString()));
2083 }
2084
2085 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2086 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2087
2088 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2089 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2090}
2091
Kevin May7d96b162021-02-03 17:38:41 +00002092void TfLiteParserImpl::ParseSqueeze(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01002093{
2094 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2095
2096 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2097 CHECK_VALID_SIZE(inputs.size(), 1);
2098
2099 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2100 CHECK_VALID_SIZE(outputs.size(), 1);
2101
2102 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2103 const auto * options = operatorPtr->builtin_options.AsSqueezeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01002104 auto layerName = fmt::format("Squeeze:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01002105
2106 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Teresa Charlin3ab85482021-06-08 16:59:29 +01002107
2108 std::vector<uint32_t> squeezeDim;
2109 // A single negative dim index is interpreted as a negative index in python
2110 // Meaning the index will be the shape size plus the negative index value
2111 if (options->squeeze_dims.size() == 1 && options->squeeze_dims[0] < 0)
2112 {
2113 int32_t dim = static_cast<int32_t>(inputTensorInfo.GetShape().GetNumDimensions()) + options->squeeze_dims[0];
2114 squeezeDim.push_back(static_cast<uint32_t>(dim));
2115 }
2116 else
2117 {
2118 squeezeDim = AsUnsignedVector(options->squeeze_dims);
2119 }
2120
2121 armnn::TensorInfo outputTensorInfo = TfLiteParserImpl::OutputShapeOfSqueeze(squeezeDim, inputTensorInfo);
2122
James Conroy05102392020-06-24 15:39:55 +01002123 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
telsoa01c577f2c2018-08-31 09:22:23 +01002124
2125 ReshapeDescriptor reshapeDesc;
2126 reshapeDesc.m_TargetShape = outputTensorInfo.GetShape();
2127
telsoa01c577f2c2018-08-31 09:22:23 +01002128 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002129 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01002130 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2131
2132 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2133 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2134
2135 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2136 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2137}
2138
Kevin May7d96b162021-02-03 17:38:41 +00002139void TfLiteParserImpl::ParseStridedSlice(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002140{
2141 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2142
2143 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2144 CHECK_VALID_SIZE(inputs.size(), 4);
2145
2146 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2147 CHECK_VALID_SIZE(outputs.size(), 1);
2148
Mike Kelly0d77ae12022-01-07 17:42:27 +00002149 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2150 const auto* options = operatorPtr->builtin_options.AsStridedSliceOptions();
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002151
2152 StridedSliceDescriptor desc;
2153 desc.m_BeginMask = options->begin_mask;
2154 desc.m_EllipsisMask = options->ellipsis_mask;
2155 desc.m_EndMask = options->end_mask;
2156 desc.m_NewAxisMask = options->new_axis_mask;
2157 desc.m_ShrinkAxisMask = options->shrink_axis_mask;
2158 desc.m_DataLayout = armnn::DataLayout::NHWC;
2159
2160 armnn::TensorInfo beginTensorInfo = ToTensorInfo(inputs[1]);
2161 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2162
2163 std::vector<int> begin(beginTensorInfo.GetNumElements());
2164 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
2165
2166 armnn::TensorInfo endTensorInfo = ToTensorInfo(inputs[2]);
2167 BufferRawPtr endBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
2168
2169 std::vector<int> end(endTensorInfo.GetNumElements());
2170 ::memcpy(end.data(), endBufferPtr->data.data(), endTensorInfo.GetNumBytes());
2171
2172 armnn::TensorInfo strideTensorInfo = ToTensorInfo(inputs[3]);
2173 BufferRawPtr strideBufferPtr = GetBuffer(m_Model, inputs[3]->buffer);
2174
2175 std::vector<int> stride(strideTensorInfo.GetNumElements());
2176 ::memcpy(stride.data(), strideBufferPtr->data.data(), strideTensorInfo.GetNumBytes());
2177
2178 desc.m_Begin = begin;
2179 desc.m_End = end;
2180 desc.m_Stride = stride;
2181
James Ward58dec6b2020-09-11 17:32:44 +01002182 auto layerName = fmt::format("StridedSlice:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002183 IConnectableLayer* layer = m_Network->AddStridedSliceLayer(desc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002184 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002185
Sadik Armagand109a4d2020-07-28 10:42:13 +01002186 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002187 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2188
2189 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2190 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2191
2192 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2193 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2194}
2195
Kevin May7d96b162021-02-03 17:38:41 +00002196void TfLiteParserImpl::ParseSub(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002197{
2198 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2199
Mike Kelly0d77ae12022-01-07 17:42:27 +00002200 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2201 const auto* options = operatorPtr->builtin_options.AsSubOptions();
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002202
2203 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2204 CHECK_VALID_SIZE(inputs.size(), 2);
2205
2206 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2207 CHECK_VALID_SIZE(outputs.size(), 1);
2208
2209 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2210 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2211
James Ward58dec6b2020-09-11 17:32:44 +01002212 auto layerName = fmt::format("Sub:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002213 IConnectableLayer* layer = m_Network->AddSubtractionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002214 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002215
Sadik Armagand109a4d2020-07-28 10:42:13 +01002216 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002217 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2218
2219 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002220 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002221
2222 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2223
2224 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2225 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2226}
2227
Kevin May7d96b162021-02-03 17:38:41 +00002228void TfLiteParserImpl::ParseDiv(size_t subgraphIndex, size_t operatorIndex)
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302229{
2230 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2231
Mike Kelly0d77ae12022-01-07 17:42:27 +00002232 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2233 const auto* options = operatorPtr->builtin_options.AsDivOptions();
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302234
2235 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2236 CHECK_VALID_SIZE(inputs.size(), 2);
2237
2238 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2239 CHECK_VALID_SIZE(outputs.size(), 1);
2240
2241 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2242 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2243
James Ward58dec6b2020-09-11 17:32:44 +01002244 auto layerName = fmt::format("Div:{}:{}", subgraphIndex, operatorIndex);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302245 IConnectableLayer* layer = m_Network->AddDivisionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002246 ARMNN_ASSERT(layer != nullptr);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302247
Sadik Armagand109a4d2020-07-28 10:42:13 +01002248 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302249 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2250
2251 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002252 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302253 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2254
2255 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2256 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2257}
2258
Teresa Charlincdbd40b2022-02-25 13:21:55 +00002259void TfLiteParserImpl::ParseFloorDiv(size_t subgraphIndex, size_t operatorIndex)
2260{
2261 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2262
2263 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2264 CHECK_VALID_SIZE(inputs.size(), 2);
2265
2266 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2267 CHECK_VALID_SIZE(outputs.size(), 1);
2268
2269 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2270 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2271
2272 auto layerName = fmt::format("Div:{}:{}", subgraphIndex, operatorIndex);
2273 IConnectableLayer* layer = m_Network->AddDivisionLayer(layerName.c_str());
2274 ARMNN_ASSERT(layer != nullptr);
2275
2276 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
2277 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2278
2279 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2280 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2281 layer = AddFusedFloorLayer(layer, 0);
2282
2283 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2284 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2285}
2286
Kevin May7d96b162021-02-03 17:38:41 +00002287void TfLiteParserImpl::ParseAdd(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002288{
2289 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2290
Mike Kelly0d77ae12022-01-07 17:42:27 +00002291 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2292 const auto* options = operatorPtr->builtin_options.AsAddOptions();
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002293
2294 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2295 CHECK_VALID_SIZE(inputs.size(), 2);
2296
2297 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2298 CHECK_VALID_SIZE(outputs.size(), 1);
2299
Bruno Goncalves9c761a62018-12-27 14:20:35 -02002300 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2301 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2302
James Ward58dec6b2020-09-11 17:32:44 +01002303 auto layerName = fmt::format("Add:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002304 IConnectableLayer* layer = m_Network->AddAdditionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002305 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002306
Sadik Armagand109a4d2020-07-28 10:42:13 +01002307 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002308 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2309
2310 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002311 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002312 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2313
2314 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2315 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2316}
2317
Kevin May7d96b162021-02-03 17:38:41 +00002318void TfLiteParserImpl::ParseMul(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002319{
2320 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2321
Mike Kelly0d77ae12022-01-07 17:42:27 +00002322 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2323 const auto* options = operatorPtr->builtin_options.AsMulOptions();
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002324
2325 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2326 CHECK_VALID_SIZE(inputs.size(), 2);
2327
2328 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2329 CHECK_VALID_SIZE(outputs.size(), 1);
2330
Bruno Goncalves9c761a62018-12-27 14:20:35 -02002331 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2332 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2333
James Ward58dec6b2020-09-11 17:32:44 +01002334 auto layerName = fmt::format("Mul:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002335 IConnectableLayer* layer = m_Network->AddMultiplicationLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002336 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002337
Sadik Armagand109a4d2020-07-28 10:42:13 +01002338 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002339 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2340
2341 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002342 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002343 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2344
2345 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2346 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2347}
2348
Kevin May7d96b162021-02-03 17:38:41 +00002349void TfLiteParserImpl::ParseMean(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002350{
2351 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2352
2353 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2354
2355 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2356 CHECK_VALID_SIZE(outputs.size(), 1);
2357
2358 armnn::TensorInfo dimTensorInfo = ToTensorInfo(inputs[1]);
2359 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2360
2361 armnn::MeanDescriptor desc;
2362 std::vector<unsigned int> axis(dimTensorInfo.GetNumElements());
2363 ::memcpy(axis.data(), bufferPtr->data.data(), dimTensorInfo.GetNumBytes());
2364 desc.m_Axis = axis;
2365
2366 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002367 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002368
2369 desc.m_KeepDims =
2370 inputTensorInfo.GetNumDimensions() == outputTensorInfo.GetNumDimensions() ?
2371 true : false;
2372
James Ward58dec6b2020-09-11 17:32:44 +01002373 auto layerName = fmt::format("Mean:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002374 IConnectableLayer* layer = m_Network->AddMeanLayer(desc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002375 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002376
2377 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2378
2379 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2380 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2381
2382 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2383 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2384}
2385
Kevin May7d96b162021-02-03 17:38:41 +00002386void TfLiteParserImpl::ParsePad(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002387{
2388 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2389
Kevin May7d96b162021-02-03 17:38:41 +00002390 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002391
Kevin May7d96b162021-02-03 17:38:41 +00002392 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002393 CHECK_VALID_SIZE(outputs.size(), 1);
2394
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00002395 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002396 armnn::TensorInfo padTensorInfo = ToTensorInfo(inputs[1]);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002397
Mike Kelly0d77ae12022-01-07 17:42:27 +00002398 std::vector<unsigned int> padBuffer = GetUIntBuffer(padTensorInfo, m_Model, inputs[1]->buffer);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002399
2400 size_t step = 2;
2401 armnn::PadDescriptor desc;
Mike Kelly0d77ae12022-01-07 17:42:27 +00002402 auto opcode = GetOpCode(m_Model, subgraphIndex, operatorIndex);
2403
2404 if (opcode == tflite::BuiltinOperator_PAD)
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00002405 {
Mike Kelly0d77ae12022-01-07 17:42:27 +00002406 CHECK_VALID_SIZE(inputs.size(), 2);
2407
2408 if (inputTensorInfo.IsQuantized())
2409 {
2410 desc.m_PadValue = static_cast<float>(inputTensorInfo.GetQuantizationOffset());
2411 }
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00002412 }
Mike Kelly0d77ae12022-01-07 17:42:27 +00002413 else if (opcode == tflite::BuiltinOperator_PADV2)
2414 {
2415 CHECK_VALID_SIZE(inputs.size(), 3);
2416
2417 armnn::TensorInfo padValueTensorInfo = ToTensorInfo(inputs[2]);
2418
2419 if (padValueTensorInfo.GetNumElements() != 1)
2420 {
2421 ARMNN_THROW_PARSE_EXCEPTION("Multiple padding values are not supported in PADV2");
2422 }
2423 BufferRawPtr padValueBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
2424
2425 // Get the pad value from the input tensor
2426 if (padValueBufferPtr->data.size() > 0)
2427 {
2428 switch (padValueTensorInfo.GetDataType())
2429 {
2430 case armnn::DataType::Float32:
2431 {
2432 std::vector<float> padValueBuffer(padValueTensorInfo.GetNumElements());
2433 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2434 desc.m_PadValue = padValueBuffer[0];
2435 break;
2436 }
2437 case armnn::DataType::QAsymmU8:
2438 {
2439 std::vector<uint8_t> padValueBuffer(padValueTensorInfo.GetNumElements());
2440 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2441 desc.m_PadValue = armnn::Dequantize<uint8_t>(padValueBuffer[0],
2442 padValueTensorInfo.GetQuantizationScale(),
2443 padValueTensorInfo.GetQuantizationOffset());
2444 break;
2445 }
2446 case armnn::DataType::QAsymmS8:
2447 case armnn::DataType::QSymmS8:
2448 {
2449 std::vector<int8_t> padValueBuffer(padValueTensorInfo.GetNumElements());
2450 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2451 desc.m_PadValue = armnn::Dequantize<int8_t>(padValueBuffer[0],
2452 padValueTensorInfo.GetQuantizationScale(),
2453 padValueTensorInfo.GetQuantizationOffset());
2454 break;
2455 }
2456 default: ARMNN_THROW_PARSE_EXCEPTION("Unsupported DataType");
2457 }
2458 }
2459 else if (inputTensorInfo.IsQuantized())
2460 {
2461 desc.m_PadValue = static_cast<float>(inputTensorInfo.GetQuantizationOffset());
2462 }
2463 }
2464
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002465 for (unsigned int i = 0; i < padTensorInfo.GetNumElements() / step; ++i)
2466 {
2467 desc.m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
2468 }
2469
Mike Kelly0d77ae12022-01-07 17:42:27 +00002470 auto layerName = (opcode == tflite::BuiltinOperator_PAD) ? fmt::format("Pad:{}:{}", subgraphIndex, operatorIndex)
2471 : fmt::format("PadV2:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002472 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01002473
2474 IConnectableLayer* layer = m_Network->AddPadLayer(desc, layerName.c_str());
2475 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002476 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2477
2478 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2479 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2480
2481 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2482 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2483}
2484
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +01002485void TfLiteParserImpl::ParseMirrorPad(size_t subgraphIndex, size_t operatorIndex)
2486{
2487 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2488
2489 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2490 CHECK_VALID_SIZE(inputs.size(), 2);
2491
2492 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2493 CHECK_VALID_SIZE(outputs.size(), 1);
2494
2495 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2496
2497 armnn::TensorInfo padTensorInfo = ToTensorInfo(inputs[1]);
2498 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2499
2500 std::vector<unsigned int> padBuffer(padTensorInfo.GetNumElements());
2501 ::memcpy(padBuffer.data(), bufferPtr->data.data(), padTensorInfo.GetNumBytes());
2502
2503 size_t step = 2;
2504 armnn::PadDescriptor desc;
2505 for (unsigned int i = 0; i < padTensorInfo.GetNumElements() / step; ++i)
2506 {
2507 desc.m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
2508 }
2509
2510 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2511 const auto* options = operatorPtr->builtin_options.AsMirrorPadOptions();
2512
2513 if (options->mode == tflite::MirrorPadMode_REFLECT)
2514 {
2515 desc.m_PaddingMode = PaddingMode::Reflect;
2516 }
2517 else if (options->mode == tflite::MirrorPadMode_SYMMETRIC)
2518 {
2519 desc.m_PaddingMode = PaddingMode::Symmetric;
2520 }
2521 else
2522 {
2523 ARMNN_THROW_PARSE_EXCEPTION("PaddingMode must be either REFLECT or SYMMETRIC");
2524 }
2525
2526 // If padding mode is Reflect then both paddings must be no greater than inputShape(i) - 1.
2527 // If padding mode is Symmetric then both paddings must be no greater than inputShape(i).
2528 auto inputShape = inputTensorInfo.GetShape();
2529 auto padList = desc.m_PadList;
2530
2531 const unsigned int isReflect = static_cast<unsigned int>(desc.m_PaddingMode == PaddingMode::Reflect);
2532 for(unsigned int i = 0; i < padList.size(); ++i)
2533 {
2534 if(padList.at(i).first > (inputShape[i] - isReflect) ||
2535 padList.at(i).second > (inputShape[i] - isReflect))
2536 {
2537 ARMNN_THROW_PARSE_EXCEPTION("Padding values must be less (Reflect) or "
2538 "equal (Symmetric) to the dimension size.");
2539 }
2540 }
2541
2542 auto layerName = fmt::format("MirrorPad:{}:{}", subgraphIndex, operatorIndex);
2543 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
2544
2545 IConnectableLayer* layer = m_Network->AddPadLayer(desc, layerName.c_str());
2546 ARMNN_ASSERT(layer != nullptr);
2547 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2548
2549 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2550 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2551
2552 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2553 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2554}
2555
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01002556void TfLiteParserImpl::ParsePrelu(size_t subgraphIndex, size_t operatorIndex)
2557{
2558 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2559
2560 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2561 CHECK_VALID_SIZE(inputs.size(), 2);
2562
2563 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2564 CHECK_VALID_SIZE(outputs.size(), 1);
2565
2566 auto layerName = fmt::format("Prelu:{}:{}", subgraphIndex, operatorIndex);
2567
2568 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2569 armnn::TensorInfo alphaTensorInfo = ToTensorInfo(inputs[1]);
2570 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
2571 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
2572
2573 IConnectableLayer* layer = m_Network->AddPreluLayer(layerName.c_str());
2574 ARMNN_ASSERT(layer != nullptr);
2575 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2576
2577 if (IsConstTensor(inputs[1]))
2578 {
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01002579 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawaratbf99b5f2021-05-27 09:55:43 +01002580 armnn::IInputSlot* slot = &(layer->GetInputSlot(0));
2581 RegisterConsumerOfTensor(subgraphIndex, inputTensorIndexes[0], slot);
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01002582
Mike Kelly5880b912022-01-28 16:18:54 +00002583 auto alphaTensorAndData = CreateConstTensorNonPermuted(inputs[1], alphaTensorInfo,
2584 inputTensorInfo.GetDataType());
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01002585 std::string constLayerName = fmt::format("Constant:{}", inputs[1]->name);
2586 IConnectableLayer* constLayer =
Mike Kelly5880b912022-01-28 16:18:54 +00002587 m_Network->AddConstantLayer(alphaTensorAndData.first, constLayerName.c_str());
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01002588 ARMNN_ASSERT(constLayer != nullptr);
2589
2590 constLayer->GetOutputSlot(0).SetTensorInfo(alphaTensorInfo);
2591 constLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(1));
2592 RegisterOutputSlots(subgraphIndex,
2593 VIRTUAL_OPERATOR_ID,
2594 constLayer,
2595 { inputTensorIndexes[1] });
2596 }
2597 else
2598 {
2599 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2600 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIndexes);
2601 }
2602
2603 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2604 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2605}
2606
Kevin May7d96b162021-02-03 17:38:41 +00002607void TfLiteParserImpl::ParseQuantize(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan66dedc72019-12-10 16:32:07 +00002608{
2609 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2610
2611 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2612 CHECK_VALID_SIZE(inputs.size(), 1);
2613
2614 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2615 CHECK_VALID_SIZE(outputs.size(), 1);
2616
James Ward58dec6b2020-09-11 17:32:44 +01002617 auto layerName = fmt::format("Quantize:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan66dedc72019-12-10 16:32:07 +00002618
2619 IConnectableLayer* layer = m_Network->AddQuantizeLayer(layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002620 ARMNN_ASSERT(layer != nullptr);
Sadik Armagan66dedc72019-12-10 16:32:07 +00002621
Sadik Armagand109a4d2020-07-28 10:42:13 +01002622 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan66dedc72019-12-10 16:32:07 +00002623 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2624
2625 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2626 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2627
2628 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2629 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2630}
Finn Williamsc42c3842019-01-22 14:18:11 +00002631
Kevin May7d96b162021-02-03 17:38:41 +00002632void TfLiteParserImpl::ParseRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01002633{
Finn Williamsc42c3842019-01-22 14:18:11 +00002634 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::ReLu);
Sadik Armagan58f39192018-09-17 14:14:39 +01002635}
2636
Kevin May7d96b162021-02-03 17:38:41 +00002637void TfLiteParserImpl::ParseRelu6(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01002638{
Finn Williamsc42c3842019-01-22 14:18:11 +00002639 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::BoundedReLu);
2640}
Sadik Armagan58f39192018-09-17 14:14:39 +01002641
Kevin May7d96b162021-02-03 17:38:41 +00002642void TfLiteParserImpl::ParseLeakyRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan12239e72020-05-27 11:06:17 +01002643{
Jan Eilers2f746b32020-07-28 14:00:06 +01002644 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::LeakyReLu);
Sadik Armagan12239e72020-05-27 11:06:17 +01002645}
2646
Kevin May7d96b162021-02-03 17:38:41 +00002647void TfLiteParserImpl::ParseLogistic(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsc42c3842019-01-22 14:18:11 +00002648{
2649 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::Sigmoid);
2650}
2651
Kevin May7d96b162021-02-03 17:38:41 +00002652void TfLiteParserImpl::ParseTanH(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd99851762019-04-09 09:37:38 +01002653{
2654 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::TanH);
2655}
2656
Kevin May7d96b162021-02-03 17:38:41 +00002657void TfLiteParserImpl::ParseElu(size_t subgraphIndex, size_t operatorIndex)
Matthew Sloyan7515d072020-12-16 12:50:01 +00002658{
2659 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::Elu);
2660}
2661
Kevin May7d96b162021-02-03 17:38:41 +00002662void TfLiteParserImpl::ParseHardSwish(size_t subgraphIndex, size_t operatorIndex)
Jan Eilers2f746b32020-07-28 14:00:06 +01002663{
2664 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::HardSwish);
2665}
Finn Williamsc42c3842019-01-22 14:18:11 +00002666
Kevin May7d96b162021-02-03 17:38:41 +00002667void TfLiteParserImpl::ParseActivation(size_t subgraphIndex, size_t operatorIndex, ActivationFunction activationType)
Finn Williamsc42c3842019-01-22 14:18:11 +00002668{
2669 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00002670 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Jan Eilers8eb25602020-03-09 12:13:48 +00002671 IgnoreUnused(operatorPtr);
Sadik Armagan58f39192018-09-17 14:14:39 +01002672
2673 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2674 CHECK_VALID_SIZE(inputs.size(), 1);
2675
2676 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2677 CHECK_VALID_SIZE(outputs.size(), 1);
2678
James Ward58dec6b2020-09-11 17:32:44 +01002679 auto layerName = fmt::format("Activation:");
Sadik Armagan58f39192018-09-17 14:14:39 +01002680 ActivationDescriptor activationDesc;
Finn Williamsc42c3842019-01-22 14:18:11 +00002681 activationDesc.m_Function = activationType;
2682
2683 switch (activationType)
2684 {
2685 case ActivationFunction::ReLu:
2686 {
James Ward58dec6b2020-09-11 17:32:44 +01002687 layerName += fmt::format("RELU:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002688 break;
2689 }
2690 case ActivationFunction::BoundedReLu:
2691 {
James Ward58dec6b2020-09-11 17:32:44 +01002692 layerName += fmt::format("RELU6:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002693 activationDesc.m_A = 6.0f;
2694 activationDesc.m_B = 0.0f;
2695 break;
2696 }
2697 case ActivationFunction::Sigmoid:
2698 {
James Ward58dec6b2020-09-11 17:32:44 +01002699 layerName += fmt::format("SIGMOID:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002700 break;
2701 }
Nina Drozd99851762019-04-09 09:37:38 +01002702 case ActivationFunction::TanH:
2703 {
James Ward58dec6b2020-09-11 17:32:44 +01002704 layerName += fmt::format("TANH:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd99851762019-04-09 09:37:38 +01002705 activationDesc.m_A = 1.0f;
2706 activationDesc.m_B = 1.0f;
2707 break;
2708 }
Sadik Armagan12239e72020-05-27 11:06:17 +01002709 case ActivationFunction::LeakyReLu:
2710 {
James Ward58dec6b2020-09-11 17:32:44 +01002711 layerName += fmt::format("LEAKYRELU:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00002712 const auto* options = operatorPtr->builtin_options.AsLeakyReluOptions();
Sadik Armagan12239e72020-05-27 11:06:17 +01002713 activationDesc.m_A = options->alpha;
2714 break;
2715 }
Matthew Sloyan7515d072020-12-16 12:50:01 +00002716 case ActivationFunction::Elu:
2717 {
2718 layerName += fmt::format("ELU:{}:{}", subgraphIndex, operatorIndex);
2719 activationDesc.m_A = 1.0f;
2720 break;
2721 }
Jan Eilers2f746b32020-07-28 14:00:06 +01002722 case ActivationFunction::HardSwish:
Matthew Sloyan7515d072020-12-16 12:50:01 +00002723 {
James Ward58dec6b2020-09-11 17:32:44 +01002724 layerName += fmt::format("HARDSWISH:{}:{}", subgraphIndex, operatorIndex);
Jan Eilers2f746b32020-07-28 14:00:06 +01002725 break;
Matthew Sloyan7515d072020-12-16 12:50:01 +00002726 }
Finn Williamsc42c3842019-01-22 14:18:11 +00002727 default:
2728 {
2729 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002730 fmt::format("Unexpected ActivationFunction[{}] when creating layerName {} ",
2731 static_cast<int>(activationType), CHECK_LOCATION().AsString()));
Finn Williamsc42c3842019-01-22 14:18:11 +00002732 }
2733 }
2734
2735 IConnectableLayer* const layer = m_Network->AddActivationLayer(activationDesc, layerName.c_str());
Sadik Armagan58f39192018-09-17 14:14:39 +01002736
Sadik Armagand109a4d2020-07-28 10:42:13 +01002737 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan58f39192018-09-17 14:14:39 +01002738 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2739
2740 // register the input connection slots for the layer, connections are made after all layers have been created
2741 // only the tensors for the inputs are relevant, exclude the const tensors
2742 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2743 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2744
2745 // register the output connection slots for the layer, connections are made after all layers have been created
2746 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2747 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2748}
Mike Kelly0d77ae12022-01-07 17:42:27 +00002749armnn::TensorInfo TfLiteParserImpl::OutputShapeOfReshape(const armnn::TensorInfo& inputTensorInfo,
2750 const std::vector<int32_t>& targetDimsIn)
Sadikb94967b2018-09-19 15:30:00 +01002751{
2752 std::vector<unsigned int> outputDims(targetDimsIn.begin(), targetDimsIn.end());
2753 const auto stretchDim = std::find(targetDimsIn.begin(), targetDimsIn.end(), -1);
2754
2755 if (stretchDim != targetDimsIn.end())
2756 {
2757 if (std::find(std::next(stretchDim), targetDimsIn.end(), -1) != targetDimsIn.end())
2758 {
2759 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002760 fmt::format("At most one component of shape can be -1 {}", CHECK_LOCATION().AsString()));
Sadikb94967b2018-09-19 15:30:00 +01002761 }
2762
2763 auto targetNumElements =
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002764 armnn::numeric_cast<unsigned int>(
Sadikb94967b2018-09-19 15:30:00 +01002765 std::accumulate(targetDimsIn.begin(), targetDimsIn.end(), -1, std::multiplies<int32_t>()));
2766
2767 auto stretchIndex = static_cast<size_t>(std::distance(targetDimsIn.begin(), stretchDim));
2768 outputDims[stretchIndex] = inputTensorInfo.GetNumElements() / targetNumElements;
2769 }
2770
2771 TensorShape outputShape = TensorShape(static_cast<unsigned int>(outputDims.size()), outputDims.data());
2772
2773 TensorInfo reshapeInfo = inputTensorInfo;
2774 reshapeInfo.SetShape(outputShape);
2775
2776 return reshapeInfo;
2777}
2778
Kevin May7d96b162021-02-03 17:38:41 +00002779void TfLiteParserImpl::ParseReshape(size_t subgraphIndex, size_t operatorIndex)
Sadikb94967b2018-09-19 15:30:00 +01002780{
2781 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2782
2783 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01002784
2785 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2786 CHECK_VALID_SIZE(outputs.size(), 1);
2787
Mike Kelly0d77ae12022-01-07 17:42:27 +00002788 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2789 const auto* options = operatorPtr->builtin_options.AsReshapeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01002790 auto layerName = fmt::format("Reshape:{}:{}", subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01002791
2792 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
kevmay0171972a82018-12-17 14:28:03 +00002793 armnn::TensorInfo actualOutputTensorInfo = ToTensorInfo(outputs[0]);
James Conroy05102392020-06-24 15:39:55 +01002794 CheckMatchingQuantization(inputTensorInfo, actualOutputTensorInfo, layerName, "Input 0", "Output 0");
Derek Lambertic9e52792020-03-11 11:42:26 +00002795
Jan Eilersbac9b352020-07-13 13:40:24 +01002796 // Extracting new shape for the output
2797 // There are two ways it can be passed
2798 // * First is to define the target shape in the operator built-in options
2799 // * Second is to pass it as a second input tensor
Derek Lambertic9e52792020-03-11 11:42:26 +00002800 std::vector<int32_t> targetShape;
Jan Eilersbac9b352020-07-13 13:40:24 +01002801 bool targetShapeFound = false;
2802 // Check if built-in options were given
2803 if (options != nullptr)
Derek Lambertic9e52792020-03-11 11:42:26 +00002804 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002805 // make sure the parameter is given
2806 if (options->new_shape.empty() == false)
Derek Lambertic9e52792020-03-11 11:42:26 +00002807 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002808 targetShape = options->new_shape;
2809 targetShapeFound = true;
Derek Lambertif4a953f2020-03-17 14:25:57 +00002810 }
Derek Lambertic9e52792020-03-11 11:42:26 +00002811 }
Jan Eilersbac9b352020-07-13 13:40:24 +01002812
2813 // If there is no built-in option given or if the built-in new_shape parameter was empty
2814 if (!targetShapeFound)
Derek Lambertic9e52792020-03-11 11:42:26 +00002815 {
Teresa Charlin6a056a42021-12-01 10:25:43 +00002816 // Check for a second input tensor
2817 if (inputs.size() > 1 && inputs[1] != nullptr)
Jan Eilersbac9b352020-07-13 13:40:24 +01002818 {
2819 if (inputs[1]->is_variable)
2820 {
2821 ARMNN_THROW_PARSE_EXCEPTION( "Target shapes defined in non-const input tensors is not supported");
2822 }
2823
2824 if (inputs[1]->shape.size() != 1)
2825 {
2826 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not a 1D tensor");
2827 }
2828
2829 if (inputs[1]->type != tflite::TensorType_INT32)
2830 {
2831 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not an int32 type");
2832 }
2833
Teresa Charlin6a056a42021-12-01 10:25:43 +00002834 // Extract target shape from input
2835 auto bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2836 auto values = reinterpret_cast<const int32_t*>(bufferPtr->data.data());
Cathal Corbettd2f73232021-12-10 13:38:52 +00002837 if (values)
Sadik Armagan19a1c032021-01-20 12:17:00 +00002838 {
Cathal Corbettd2f73232021-12-10 13:38:52 +00002839 for (int i = 0; i < inputs[1]->shape[0]; ++i)
2840 {
2841 targetShape.push_back(values[i]);
2842 }
Sadik Armagan19a1c032021-01-20 12:17:00 +00002843 }
Cathal Corbettd2f73232021-12-10 13:38:52 +00002844 else
Jan Eilersbac9b352020-07-13 13:40:24 +01002845 {
Cathal Corbettd2f73232021-12-10 13:38:52 +00002846 try
2847 {
2848 // We attempt to infer during Runtime.
2849 TensorShape reshapeShapes = ToTensorInfo(inputs[1]).GetShape();
2850 // The parser only supports shape (batch, -1) or (-1) for non-constant shape input.
2851 if (reshapeShapes[0] > 2)
2852 {
2853 throw ParseException(fmt::format("Invalid input shape '{}' in Reshape layer '{}' {}. "
2854 "When inferring during runtime, the parser only supports "
2855 "shape (batch, -1) or (-1) for target shape input.",
2856 reshapeShapes[0],
2857 layerName,
2858 CHECK_LOCATION().AsString()));
2859 }
2860
2861 const int32_t numInputElements = inputTensorInfo.GetNumElements();
2862 const int32_t inputTensorShape = inputTensorInfo.GetShape()[0];
2863 if (reshapeShapes[0] == 1)
2864 {
2865 targetShape = {numInputElements};
2866 }
2867 else if (reshapeShapes[0] == 2)
2868 {
2869 targetShape = {inputTensorShape, numInputElements / inputTensorShape};
2870 }
2871 }
2872 catch (const std::exception& exc)
2873 {
2874 ARMNN_THROW_PARSE_EXCEPTION("Failed attempt to infer during runtime the target shape input for "
2875 "Reshape operation. Reshape operator target shape input buffer data "
2876 "is null. " << exc.what());
2877 }
Jan Eilersbac9b352020-07-13 13:40:24 +01002878 }
2879 }
2880 else
Derek Lambertic9e52792020-03-11 11:42:26 +00002881 {
2882 ARMNN_THROW_PARSE_EXCEPTION("Target shape not defined in reshape parameters or input tensor. "
2883 "At least one method required");
2884 }
Derek Lambertic9e52792020-03-11 11:42:26 +00002885 }
2886
kevmay0171972a82018-12-17 14:28:03 +00002887 armnn::TensorInfo reshapeOutputTensorInfo =
Kevin May7d96b162021-02-03 17:38:41 +00002888 TfLiteParserImpl::OutputShapeOfReshape(inputTensorInfo, targetShape);
Sadikb94967b2018-09-19 15:30:00 +01002889
kevmay0171972a82018-12-17 14:28:03 +00002890 // Check for valid input size and that reshape parameters equal output shape
Aron Virginas-Tar70672f62019-01-23 14:00:00 +00002891 const armnn::TensorShape& reshapeOutputTensorShape = reshapeOutputTensorInfo.GetShape();
2892 if (inputs.size() > 1 && !CheckShape(reshapeOutputTensorShape, outputs[0]->shape))
kevmay0171972a82018-12-17 14:28:03 +00002893 {
2894 std::stringstream ss;
2895 ss << "New shape defined in reshape parameters "
Aron Virginas-Tar70672f62019-01-23 14:00:00 +00002896 << reshapeOutputTensorShape
kevmay0171972a82018-12-17 14:28:03 +00002897 << " does not equal output shape "
2898 << actualOutputTensorInfo.GetShape()
2899 << ": "
2900 << CHECK_LOCATION().AsString();
2901 throw ParseException(ss.str());
2902 }
2903
Sadikb94967b2018-09-19 15:30:00 +01002904 ReshapeDescriptor reshapeDesc;
kevmay0171972a82018-12-17 14:28:03 +00002905 reshapeDesc.m_TargetShape = reshapeOutputTensorInfo.GetShape();
Sadikb94967b2018-09-19 15:30:00 +01002906
Sadikb94967b2018-09-19 15:30:00 +01002907 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002908 ARMNN_ASSERT(layer != nullptr);
kevmay0171972a82018-12-17 14:28:03 +00002909 layer->GetOutputSlot(0).SetTensorInfo(reshapeOutputTensorInfo);
Sadikb94967b2018-09-19 15:30:00 +01002910
2911 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2912 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2913
2914 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2915 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2916}
2917
Kevin May7d96b162021-02-03 17:38:41 +00002918void TfLiteParserImpl::ParseResizeBilinear(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002919{
Sadik Armagana3b31f02019-12-05 09:08:53 +00002920 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::Bilinear);
2921}
2922
Kevin May7d96b162021-02-03 17:38:41 +00002923void TfLiteParserImpl::ParseResizeNearestNeighbor(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagana3b31f02019-12-05 09:08:53 +00002924{
2925 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::NearestNeighbor);
2926}
2927
Kevin May7d96b162021-02-03 17:38:41 +00002928void TfLiteParserImpl::ParseResize(size_t subgraphIndex, size_t operatorIndex, ResizeMethod resizeMethod)
Sadik Armagana3b31f02019-12-05 09:08:53 +00002929{
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002930 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2931
2932 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2933 CHECK_VALID_SIZE(inputs.size(), 2);
2934
2935 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2936 CHECK_VALID_SIZE(outputs.size(), 1);
2937
2938 armnn::TensorInfo sizeTensorInfo = ToTensorInfo(inputs[1]);
2939
2940 // Data for the parsed tensor args (size) must be stored locally.
2941 std::vector<int32_t> sizeTensorData(sizeTensorInfo.GetNumElements());
2942
2943 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2944 ::memcpy(sizeTensorData.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
2945
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01002946 ResizeDescriptor desc;
Sadik Armagana3b31f02019-12-05 09:08:53 +00002947 desc.m_Method = resizeMethod;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002948 desc.m_TargetHeight = static_cast<uint32_t> (sizeTensorData[0]);
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01002949 desc.m_TargetWidth = static_cast<uint32_t> (sizeTensorData[1]);
2950 desc.m_DataLayout = armnn::DataLayout::NHWC;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002951
James Ward58dec6b2020-09-11 17:32:44 +01002952 auto layerName = fmt::format("Resize:");
Sadik Armagana3b31f02019-12-05 09:08:53 +00002953
2954 switch (resizeMethod)
2955 {
2956 case ResizeMethod::Bilinear:
2957 {
James Ward58dec6b2020-09-11 17:32:44 +01002958 layerName += fmt::format("BILINEAR:{}:{}", subgraphIndex, operatorIndex);
Sang-Hoon Park820eb142020-01-08 10:25:24 +00002959
2960 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2961 const auto * options = operatorPtr->builtin_options.AsResizeBilinearOptions();
2962
David Monahan4a0c9b92020-05-30 09:48:39 +01002963 desc.m_AlignCorners = options->align_corners;
Sadik Armagana3b31f02019-12-05 09:08:53 +00002964 break;
2965 }
2966 case ResizeMethod::NearestNeighbor:
2967 {
James Ward58dec6b2020-09-11 17:32:44 +01002968 layerName += fmt::format("NEARESTNEIGHBOR:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagana3b31f02019-12-05 09:08:53 +00002969 break;
2970 }
2971 default:
2972 {
2973 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002974 fmt::format("Unexpected ResizeMethod[{}] when creating layerName {} ",
2975 static_cast<int>(resizeMethod), CHECK_LOCATION().AsString()));
Sadik Armagana3b31f02019-12-05 09:08:53 +00002976 }
2977 }
2978
James Conroy05102392020-06-24 15:39:55 +01002979 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002980 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01002981 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
2982
2983 IConnectableLayer* layer = m_Network->AddResizeLayer(desc, layerName.c_str());
2984 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002985 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2986
2987 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2988 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2989
2990 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2991 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2992}
2993
Kevin May7d96b162021-02-03 17:38:41 +00002994void TfLiteParserImpl::ParseConcatenation(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan479045b2018-10-01 11:51:37 +01002995{
2996 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2997
Mike Kelly0d77ae12022-01-07 17:42:27 +00002998 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2999 const auto* options = operatorPtr->builtin_options.AsConcatenationOptions();
Sadik Armagan479045b2018-10-01 11:51:37 +01003000
3001 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
3002
3003 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3004 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3005 CHECK_VALID_SIZE(outputs.size(), 1);
3006
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003007 unsigned int numConcatView = static_cast<unsigned int>(inputs.size());
3008 uint32_t inputRank = ToTensorInfo(inputs[0]).GetNumDimensions();
Sadik Armagan479045b2018-10-01 11:51:37 +01003009
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003010 const unsigned int concatDimInput = static_cast<unsigned int>(
3011 (static_cast<int>(inputRank) + options->axis) % static_cast<int>(inputRank));
Sadik Armagan479045b2018-10-01 11:51:37 +01003012
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003013 OriginsDescriptor concatDescriptor(static_cast<uint32_t>(numConcatView), inputRank);
3014 concatDescriptor.SetConcatAxis(concatDimInput);
Sadik Armagan479045b2018-10-01 11:51:37 +01003015
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003016 unsigned int mergeDimOrigin = 0;
Sadik Armagan479045b2018-10-01 11:51:37 +01003017
3018 for (unsigned int viewIndex = 0; viewIndex < numConcatView; ++viewIndex)
3019 {
3020 TensorInfo inputTensorInfo = ToTensorInfo(inputs[viewIndex]);
3021
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003022 // This set up concatDescriptor view origin
3023 armnnUtils::ProcessConcatInputTensorInfo(
3024 inputTensorInfo, concatDescriptor, concatDimInput, viewIndex, mergeDimOrigin);
Sadik Armagan479045b2018-10-01 11:51:37 +01003025 }
3026
James Ward58dec6b2020-09-11 17:32:44 +01003027 auto layerName = fmt::format("Concatenation:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagand109a4d2020-07-28 10:42:13 +01003028 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01003029
Jim Flynn906f9462019-05-10 13:55:21 +01003030 IConnectableLayer* layer = m_Network->AddConcatLayer(concatDescriptor, layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003031 ARMNN_ASSERT(layer != nullptr);
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003032 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Sadik Armagan479045b2018-10-01 11:51:37 +01003033
James Conroy05102392020-06-24 15:39:55 +01003034 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003035 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
Sadik Armagan479045b2018-10-01 11:51:37 +01003036
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003037 // add fused activation layer
3038 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Sadik Armagan479045b2018-10-01 11:51:37 +01003039
Sadik Armagan479045b2018-10-01 11:51:37 +01003040 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3041 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3042}
3043
Kevin May7d96b162021-02-03 17:38:41 +00003044void TfLiteParserImpl::ParseFullyConnected(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003045{
3046 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3047
Mike Kelly0d77ae12022-01-07 17:42:27 +00003048 const auto& operatorRfr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003049 const auto options = operatorRfr->builtin_options.AsFullyConnectedOptions();
3050
3051 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
3052
3053 FullyConnectedDescriptor desc;
3054 desc.m_BiasEnabled = false;
Nattapat Chaimanowongd8eee592018-10-26 10:24:14 +01003055 desc.m_TransposeWeightMatrix = true;
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003056
3057 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3058 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3059 CHECK_VALID_SIZE(outputs.size(), 1);
3060
3061 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
3062
3063 // Fully Connected Layer accepts two dimensional weights input
3064 int32_t weightsDimension = static_cast<int32_t>(filterTensorInfo.GetNumDimensions());
3065 if (weightsDimension != 2)
3066 {
3067 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003068 fmt::format("Dimension {} for Fully Connected weights is not supported by Armnn. "
3069 "Node {}",
3070 weightsDimension,
3071 CHECK_LOCATION().AsString()));
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003072 }
3073
Matthew Jackson74bf7da2019-08-16 16:51:42 +01003074 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01003075 auto layerName = fmt::format("FullyConnected:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003076
Matthew Sloyan81beae32021-07-13 19:46:11 +01003077 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3078 // Add the first input tensor to the registration list
3079 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0]};
3080 std::vector<unsigned int> ignoreInputWhenRegister = {};
Mike Kelly5880b912022-01-28 16:18:54 +00003081 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003082
3083 desc.m_ConstantWeights = IsConstTensor(inputs[1]);
3084
Matthew Sloyan81beae32021-07-13 19:46:11 +01003085 // Add the weights input to the registration list, constant layers will be added by SetupConstantLayers if constant.
3086 tensorIndexesToRegister.emplace_back(inputTensorIndexes[1]);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003087
Mike Kelly5880b912022-01-28 16:18:54 +00003088 if (desc.m_ConstantWeights && inputTensorInfo.GetDataType() == DataType::Float32 &&
3089 (filterTensorInfo.GetDataType() == DataType::QAsymmU8 ||
3090 filterTensorInfo.GetDataType() == DataType::QAsymmS8))
3091 {
3092 m_ConstantsToDequantize.emplace_back(inputs[1]->buffer);
3093 }
3094
Finn Williamsd4fa5452021-03-01 12:31:41 +00003095 if (inputs.size() == 3)
3096 {
3097 desc.m_BiasEnabled = true;
Mike Kelly5880b912022-01-28 16:18:54 +00003098 armnn::TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Matthew Sloyan81beae32021-07-13 19:46:11 +01003099
3100 // Add the biases input to the registration list, constant layer will be added by SetupConstantLayers.
3101 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
Mike Kelly5880b912022-01-28 16:18:54 +00003102
3103 if (desc.m_ConstantWeights && inputTensorInfo.GetDataType() == DataType::Float32 &&
3104 (biasTensorInfo.GetDataType() == DataType::QAsymmU8 ||
3105 biasTensorInfo.GetDataType() == DataType::QAsymmS8))
3106 {
3107 m_ConstantsToDequantize.emplace_back(inputs[2]->buffer);
3108 }
Finn Williamsd4fa5452021-03-01 12:31:41 +00003109 }
3110
Matthew Sloyan81beae32021-07-13 19:46:11 +01003111 // Filters and biases are always passed to fully connected as inputs
3112 layer = m_Network->AddFullyConnectedLayer(desc, layerName.c_str());
Finn Williamsd4fa5452021-03-01 12:31:41 +00003113
3114 ARMNN_ASSERT(layer != nullptr);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003115
Finn Williamsd4fa5452021-03-01 12:31:41 +00003116 unsigned int startingSlotIndex = 0;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003117 if (inputTensorInfo.GetNumDimensions() > 2)
3118 {
3119 // Add reshape to flatten to 2D [batch_size, input_size],
3120 // where "input_size" corresponds to the number of inputs to the layer,
3121 // matching the second dimension of weights,
3122 // and "batch_size" is calculated by dividing the number of elements by "input_size".
3123 std::vector<unsigned int> reshapedDimensions(2);
3124 reshapedDimensions[1] = filterTensorInfo.GetShape()[1];
3125 reshapedDimensions[0] = inputTensorInfo.GetNumElements() / reshapedDimensions[1];
3126
3127 if (inputTensorInfo.GetNumElements() % reshapedDimensions[1] != 0)
3128 {
3129 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003130 fmt::format("Failed to deduce input tensor shape from filter size {} {}",
3131 reshapedDimensions[1],
3132 CHECK_LOCATION().AsString()));
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003133 }
3134
3135 armnn::TensorInfo reshapedTensorInfo = ToTensorInfo(inputs[0]);
3136 reshapedTensorInfo.SetShape(armnn::TensorShape{ 2, reshapedDimensions.data() });
3137
James Ward58dec6b2020-09-11 17:32:44 +01003138 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Finn Williamsd4fa5452021-03-01 12:31:41 +00003139 armnn::ReshapeDescriptor reshapeDescriptor;
3140 reshapeDescriptor.m_TargetShape = reshapedTensorInfo.GetShape();
3141 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(reshapeDescriptor, layerName.c_str());
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003142
3143 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedTensorInfo);
3144 reshapeLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(0));
3145
3146 RegisterInputSlots(subgraphIndex, operatorIndex, reshapeLayer, {inputTensorIndexes[0]});
Finn Williamsd4fa5452021-03-01 12:31:41 +00003147 // Fc layer connects to the reshape layer, so we skip the first input slot when registering fc's input slots
3148 tensorIndexesToRegister.erase(tensorIndexesToRegister.begin());
3149 startingSlotIndex = 1;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003150 }
Finn Williamsd4fa5452021-03-01 12:31:41 +00003151
3152 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister, startingSlotIndex);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003153
Sadik Armagand109a4d2020-07-28 10:42:13 +01003154 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003155 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3156
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003157 // we need to add the activation layer and fortunately we don't need to care about the data layout
3158 armnn::IConnectableLayer* fusedActivationLayer = AddFusedActivationLayer(layer, 0,
3159 options->fused_activation_function);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003160
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003161 // register the output connection slots for the layer, connections are made after all layers have been created
3162 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3163 RegisterOutputSlots(subgraphIndex, operatorIndex, fusedActivationLayer, {outputTensorIndexes[0]});
3164}
3165
Kevin May7d96b162021-02-03 17:38:41 +00003166void TfLiteParserImpl::ParseDetectionPostProcess(size_t subgraphIndex, size_t operatorIndex)
keidav011b3e2ea2019-02-21 10:07:37 +00003167{
3168 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3169
Mike Kelly0d77ae12022-01-07 17:42:27 +00003170 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
keidav011b3e2ea2019-02-21 10:07:37 +00003171
3172 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3173 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3174 CHECK_VALID_SIZE(outputs.size(), 4);
3175
3176 // Obtain custom options from flexbuffers
3177 auto custom_options = operatorPtr->custom_options;
3178 const flexbuffers::Map& m = flexbuffers::GetRoot(custom_options.data(), custom_options.size()).AsMap();
3179
3180 // Obtain descriptor information from tf lite
3181 DetectionPostProcessDescriptor desc;
3182 desc.m_MaxDetections = m["max_detections"].AsUInt32();
3183 desc.m_MaxClassesPerDetection = m["max_classes_per_detection"].AsUInt32();
3184 desc.m_NmsScoreThreshold = m["nms_score_threshold"].AsFloat();
3185 desc.m_NmsIouThreshold = m["nms_iou_threshold"].AsFloat();
3186 desc.m_NumClasses = m["num_classes"].AsUInt32();
3187 desc.m_ScaleH = m["h_scale"].AsFloat();
3188 desc.m_ScaleW = m["w_scale"].AsFloat();
3189 desc.m_ScaleX = m["x_scale"].AsFloat();
3190 desc.m_ScaleY = m["y_scale"].AsFloat();
3191
keidav0107d58c72019-02-26 11:57:39 +00003192 if (!(m["use_regular_nms"].IsNull()))
keidav011b3e2ea2019-02-21 10:07:37 +00003193 {
keidav0107d58c72019-02-26 11:57:39 +00003194 desc.m_UseRegularNms = m["use_regular_nms"].AsBool();
keidav011b3e2ea2019-02-21 10:07:37 +00003195 }
3196 if (!(m["detections_per_class"].IsNull()))
3197 {
3198 desc.m_DetectionsPerClass = m["detections_per_class"].AsUInt32();
3199 }
3200
3201 if (desc.m_NmsIouThreshold <= 0.0f || desc.m_NmsIouThreshold > 1.0f)
3202 {
3203 throw InvalidArgumentException("DetectionPostProcessTFLiteParser: Intersection over union threshold "
3204 "must be positive and less than or equal to 1.");
3205 }
3206
3207 armnn::TensorInfo anchorTensorInfo = ToTensorInfo(inputs[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003208 auto anchorTensorAndData = CreateConstTensorNonPermuted(inputs[2], anchorTensorInfo);
keidav011b3e2ea2019-02-21 10:07:37 +00003209
James Ward58dec6b2020-09-11 17:32:44 +01003210 auto layerName = fmt::format("DetectionPostProcess:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003211 IConnectableLayer* layer = m_Network->AddDetectionPostProcessLayer(desc, anchorTensorAndData,
keidav011b3e2ea2019-02-21 10:07:37 +00003212 layerName.c_str());
3213
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003214 ARMNN_ASSERT(layer != nullptr);
keidav011b3e2ea2019-02-21 10:07:37 +00003215
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003216 // The model does not specify the output shapes.
3217 // The output shapes are calculated from the max_detection and max_classes_per_detection.
3218 unsigned int numDetectedBox = desc.m_MaxDetections * desc.m_MaxClassesPerDetection;
3219 m_OverridenOutputShapes.push_back({ 1, numDetectedBox, 4 });
3220 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
3221 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
3222 m_OverridenOutputShapes.push_back({ 1 });
3223
keidav011b3e2ea2019-02-21 10:07:37 +00003224 for (unsigned int i = 0 ; i < outputs.size() ; ++i)
3225 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003226 armnn::TensorInfo detectionBoxOutputTensorInfo = ToTensorInfo(outputs[i], m_OverridenOutputShapes[i]);
keidav011b3e2ea2019-02-21 10:07:37 +00003227 layer->GetOutputSlot(i).SetTensorInfo(detectionBoxOutputTensorInfo);
3228 }
3229
3230 // Register the input connection slots for the layer, connections are made after all layers have been created
3231 // only the tensors for the inputs are relevant, exclude the const tensors
3232 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3233 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
3234
3235 // Register the output connection slots for the layer, connections are made after all layers have been created
3236 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3237 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0],
3238 outputTensorIndexes[1],
3239 outputTensorIndexes[2],
3240 outputTensorIndexes[3]});
3241}
3242
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003243/// The TfLite Pack operator is equivalent to the ArmNN Stack operator
Kevin May7d96b162021-02-03 17:38:41 +00003244void TfLiteParserImpl::ParsePack(size_t subgraphIndex, size_t operatorIndex)
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003245{
3246 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3247
3248 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3249 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3250 CHECK_VALID_SIZE(outputs.size(), 1);
3251
3252 if (inputs.size() < 1)
3253 {
3254 throw ParseException("Pack must have at least one input.");
3255 }
3256
3257 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3258 const auto* options = operatorPtr->builtin_options.AsPackOptions();
3259
3260 StackDescriptor desc;
3261 desc.m_Axis = static_cast<uint32_t>(options->axis);
3262 desc.m_NumInputs = static_cast<uint32_t>(inputs.size());
3263
3264 // Use the tensor shape of the first input as the "correct" input shape in the descriptor
3265 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3266 desc.m_InputShape = inputTensorInfo.GetShape();
3267
James Ward58dec6b2020-09-11 17:32:44 +01003268 auto layerName = fmt::format("Pack:{}:{}", subgraphIndex, operatorIndex);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003269 IConnectableLayer* layer = m_Network->AddStackLayer(desc, layerName.c_str());
3270
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003271 ARMNN_ASSERT(layer != nullptr);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003272
Sadik Armagand109a4d2020-07-28 10:42:13 +01003273 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003274 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3275
3276 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3277 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
3278
3279 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3280 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3281}
3282
Mike Kelly5880b912022-01-28 16:18:54 +00003283void TfLiteParserImpl::ParseUnidirectionalSequenceLSTM(size_t subgraphIndex, size_t operatorIndex)
3284{
3285 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3286
3287 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3288 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3289
3290 if (inputs.size() < 2)
3291 {
3292 throw ParseException("UnidirectionalSequenceLSTM must have at least 2 input.");
3293 }
3294
3295 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3296 const auto& subgraphPtr = m_Model->subgraphs[subgraphIndex];
3297 const auto nodeParams = operatorPtr->builtin_options.AsUnidirectionalSequenceLSTMOptions();
3298 CHECK_SUPPORTED_FUSED_ACTIVATION(nodeParams, subgraphIndex, operatorIndex);
3299 auto inputTensorInfo = ToTensorInfo(inputs[0]);
3300 auto outputTensorInfo = ToTensorInfo(outputs[0]);
3301
3302 // Set the params structure for the AddUnidirectionalSequenceLstmLayer call
3303 // Please refer to each operand at
3304 // https://www.tensorflow.org/mlir/tfl_ops#tflunidirectional_sequence_lstm_tflunidirectionalsequencelstmop
3305 armnn::LstmInputParams params;
3306
3307 if (IsOptionalOperandPresent(operatorPtr->inputs[1]))
3308 {
3309 params.m_InputToInputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[1]].get(),
3310 inputTensorInfo).first;
3311 }
3312
3313 params.m_InputToForgetWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[2]].get(),
3314 inputTensorInfo).first;
3315 params.m_InputToCellWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[3]].get(),
3316 inputTensorInfo).first;
3317 params.m_InputToOutputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[4]].get(),
3318 inputTensorInfo).first;
3319
3320 // Recurrent weight tensors of size {n_cell, n_output}
3321 if (IsOptionalOperandPresent(operatorPtr->inputs[5]))
3322 {
3323 params.m_RecurrentToInputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[5]].get(),
3324 inputTensorInfo).first;
3325 }
3326
3327 params.m_RecurrentToForgetWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[6]].get(),
3328 inputTensorInfo).first;
3329 params.m_RecurrentToCellWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[7]].get(),
3330 inputTensorInfo).first;
3331 params.m_RecurrentToOutputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[8]].get(),
3332 inputTensorInfo).first;
3333
3334 // Peephole weights tensors of size {n_cell}, representing a diagonal matrix.
3335 if (IsOptionalOperandPresent(operatorPtr->inputs[9]))
3336 {
3337 params.m_CellToInputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[9]].get(),
3338 inputTensorInfo).first;
3339 }
3340
3341 if (IsOptionalOperandPresent(operatorPtr->inputs[10]))
3342 {
3343 params.m_CellToForgetWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[10]].get(),
3344 inputTensorInfo).first;
3345 }
3346
3347 if (IsOptionalOperandPresent(operatorPtr->inputs[11]))
3348 {
3349 params.m_CellToOutputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[11]].get(),
3350 inputTensorInfo).first;
3351 }
3352
3353 // Gates bias tensors of size {n_cell}
3354 if (IsOptionalOperandPresent(operatorPtr->inputs[12]))
3355 {
3356 params.m_InputGateBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[12]].get(),
3357 inputTensorInfo).first;
3358 }
3359
3360 params.m_ForgetGateBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[13]].get(),
3361 inputTensorInfo).first;
3362 params.m_CellBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[14]].get(),
3363 inputTensorInfo).first;
3364 params.m_OutputGateBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[15]].get(),
3365 inputTensorInfo).first;
3366
3367 // Projection weight tensor of size {n_output, n_cell}
3368 if (IsOptionalOperandPresent(operatorPtr->inputs[16]))
3369 {
3370 params.m_ProjectionWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[16]].get(),
3371 inputTensorInfo).first;
3372 }
3373 // Projection bias tensor of size {n_output}
3374 if (IsOptionalOperandPresent(operatorPtr->inputs[17]))
3375 {
3376 params.m_ProjectionBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[17]].get(),
3377 inputTensorInfo).first;
3378 }
3379
3380 // These state tensors are defined as variable tensors, and will be modified by this op.
3381 armnn::TensorInfo outputStateInInfo = ToTensorInfo(subgraphPtr->tensors[operatorPtr->inputs[18]].get());
3382 m_ConstantsToBeCreated.push_back(operatorPtr->inputs[18]);
3383 armnn::TensorInfo cellStateInInfo = ToTensorInfo(subgraphPtr->tensors[operatorPtr->inputs[19]].get());
3384 m_ConstantsToBeCreated.push_back(operatorPtr->inputs[19]);
3385
3386 // Layer norm coefficient tensors of size {n_cell}, representing a diagonal matrix.
3387 if (inputs.size() >= 21 && IsOptionalOperandPresent(operatorPtr->inputs[20]))
3388 {
3389 params.m_InputLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[20]].get(),
3390 inputTensorInfo).first;
3391 }
3392
3393 if (inputs.size() >= 22 && IsOptionalOperandPresent(operatorPtr->inputs[21]))
3394 {
3395 params.m_ForgetLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[21]].get(),
3396 inputTensorInfo).first;
3397 }
3398
3399 if (inputs.size() >= 23 && IsOptionalOperandPresent(operatorPtr->inputs[22]))
3400 {
3401 params.m_CellLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[22]].get(),
3402 inputTensorInfo).first;
3403 }
3404
3405 if (inputs.size() >= 24 && IsOptionalOperandPresent(operatorPtr->inputs[23]))
3406 {
3407 params.m_OutputLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[23]].get(),
3408 inputTensorInfo).first;
3409 }
3410
3411 // set the layer descriptor
3412 armnn::UnidirectionalSequenceLstmDescriptor desc;
3413 desc.m_ActivationFunc = nodeParams->fused_activation_function;
3414 desc.m_ClippingThresCell = nodeParams->cell_clip;
3415 desc.m_ClippingThresProj = nodeParams->proj_clip;
3416 desc.m_CifgEnabled = (params.m_InputToInputWeights == nullptr
3417 || params.m_RecurrentToInputWeights == nullptr
3418 || params.m_InputGateBias == nullptr);
3419 desc.m_PeepholeEnabled = (params.m_CellToForgetWeights != nullptr || params.m_CellToOutputWeights != nullptr);
3420 desc.m_ProjectionEnabled = (params.m_ProjectionWeights != nullptr);
3421 desc.m_LayerNormEnabled = (params.m_InputLayerNormWeights != nullptr
3422 || params.m_ForgetLayerNormWeights != nullptr
3423 || params.m_CellLayerNormWeights != nullptr
3424 || params.m_OutputLayerNormWeights != nullptr);
3425 desc.m_TimeMajor = nodeParams->time_major;
3426
Mike Kellyc0800a32022-06-15 10:57:52 +01003427 if (operatorPtr->intermediates.size() > 3 && desc.m_LayerNormEnabled)
Mike Kelly5880b912022-01-28 16:18:54 +00003428 {
3429 auto inputIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[0]].get(),
3430 inputTensorInfo).first;
3431 auto inputIntermediateTensorInfo = inputIntermediate->GetInfo();
3432 desc.m_InputIntermediateScale = inputIntermediateTensorInfo.GetQuantizationScale();
3433
3434 auto forgetIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[1]].get(),
3435 inputTensorInfo).first;
3436 auto forgetIntermediateTensorInfo = forgetIntermediate->GetInfo();
3437 desc.m_ForgetIntermediateScale = forgetIntermediateTensorInfo.GetQuantizationScale();
3438
3439 auto cellIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[2]].get(),
3440 inputTensorInfo).first;
3441 auto cellIntermediateTensorInfo = cellIntermediate->GetInfo();
3442 desc.m_CellIntermediateScale = cellIntermediateTensorInfo.GetQuantizationScale();
3443
3444 auto outputIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[3]].get(),
3445 inputTensorInfo).first;
3446 auto outputIntermediateTensorInfo = outputIntermediate->GetInfo();
3447 desc.m_OutputIntermediateScale = outputIntermediateTensorInfo.GetQuantizationScale();
3448 }
3449 else
3450 {
3451 float defaultIntermediate = std::pow(2, -12);
3452 desc.m_InputIntermediateScale = defaultIntermediate;
3453 desc.m_ForgetIntermediateScale = defaultIntermediate;
3454 desc.m_CellIntermediateScale = defaultIntermediate;
3455 desc.m_OutputIntermediateScale = defaultIntermediate;
3456 }
3457
Mike Kellyc0800a32022-06-15 10:57:52 +01003458 if (operatorPtr->intermediates.size() > 4)
3459 {
3460 auto hiddentensor = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[4]].get(),
3461 inputTensorInfo).first;
Mike Kelly5880b912022-01-28 16:18:54 +00003462
Mike Kellyc0800a32022-06-15 10:57:52 +01003463 desc.m_HiddenStateScale = hiddentensor->GetInfo().GetQuantizationScale();
3464 desc.m_HiddenStateZeroPoint = hiddentensor->GetInfo().GetQuantizationOffset();
3465 }
Mike Kelly5880b912022-01-28 16:18:54 +00003466 unsigned int batchSize = inputTensorInfo.GetShape()[0];
3467 unsigned int outputSize = outputTensorInfo.GetShape()[2];
3468 unsigned int numUnits = cellStateInInfo.GetShape()[1];
3469
3470 armnn::DataType dataType = inputTensorInfo.GetDataType();
3471 float qScale = inputTensorInfo.GetQuantizationScale();
3472 float qOffset = inputTensorInfo.GetQuantizationOffset();
3473
3474 armnn::TensorInfo scratchBufferTensorInfo({batchSize, numUnits * 3}, dataType, qScale, qOffset);
3475 if (!desc.m_CifgEnabled)
3476 {
3477 scratchBufferTensorInfo = armnn::TensorInfo({batchSize, numUnits * 4}, dataType, qScale, qOffset);
3478 }
3479 armnn::TensorInfo cellStateOutTensorInfo({batchSize, numUnits},
3480 cellStateInInfo.GetDataType(),
3481 cellStateInInfo.GetQuantizationScale(),
3482 cellStateInInfo.GetQuantizationOffset());
3483 armnn::TensorInfo outputStateOutTensorInfo({batchSize, outputSize}, dataType, qScale, qOffset);
3484
3485 armnn::LstmInputParamsInfo paramsInfo;
3486 paramsInfo.m_InputToForgetWeights = &(params.m_InputToForgetWeights->GetInfo());
3487 paramsInfo.m_InputToCellWeights = &(params.m_InputToCellWeights->GetInfo());
3488 paramsInfo.m_InputToOutputWeights = &(params.m_InputToOutputWeights->GetInfo());
3489 paramsInfo.m_RecurrentToForgetWeights = &(params.m_RecurrentToForgetWeights->GetInfo());
3490 paramsInfo.m_RecurrentToCellWeights = &(params.m_RecurrentToCellWeights->GetInfo());
3491 paramsInfo.m_RecurrentToOutputWeights = &(params.m_RecurrentToOutputWeights->GetInfo());
3492 paramsInfo.m_ForgetGateBias = &(params.m_ForgetGateBias->GetInfo());
3493 paramsInfo.m_CellBias = &(params.m_CellBias->GetInfo());
3494 paramsInfo.m_OutputGateBias = &(params.m_OutputGateBias->GetInfo());
3495
3496 if (!desc.m_CifgEnabled)
3497 {
3498 paramsInfo.m_InputToInputWeights = &(params.m_InputToInputWeights->GetInfo());
3499 paramsInfo.m_RecurrentToInputWeights = &(params.m_RecurrentToInputWeights->GetInfo());
3500 if (params.m_CellToInputWeights != nullptr)
3501 {
3502 paramsInfo.m_CellToInputWeights = &(params.m_CellToInputWeights->GetInfo());
3503 }
3504 paramsInfo.m_InputGateBias = &(params.m_InputGateBias->GetInfo());
3505 }
3506
3507 if (desc.m_ProjectionEnabled)
3508 {
3509 paramsInfo.m_ProjectionWeights = &(params.m_ProjectionWeights->GetInfo());
3510 if (params.m_ProjectionBias != nullptr)
3511 {
3512 paramsInfo.m_ProjectionBias = &(params.m_ProjectionBias->GetInfo());
3513 }
3514 }
3515
3516 if (desc.m_PeepholeEnabled)
3517 {
3518 paramsInfo.m_CellToForgetWeights = &(params.m_CellToForgetWeights->GetInfo());
3519 paramsInfo.m_CellToOutputWeights = &(params.m_CellToOutputWeights->GetInfo());
3520 }
3521
3522 if (desc.m_LayerNormEnabled)
3523 {
3524 if(!desc.m_CifgEnabled)
3525 {
3526 paramsInfo.m_InputLayerNormWeights = &(params.m_InputLayerNormWeights->GetInfo());
3527 }
3528 paramsInfo.m_ForgetLayerNormWeights = &(params.m_ForgetLayerNormWeights->GetInfo());
3529 paramsInfo.m_CellLayerNormWeights = &(params.m_CellLayerNormWeights->GetInfo());
3530 paramsInfo.m_OutputLayerNormWeights = &(params.m_OutputLayerNormWeights->GetInfo());
3531 }
3532
3533 auto layerName = fmt::format("UnidirectionalSequenceLSTM:{}:{}", subgraphIndex, operatorIndex);
3534 armnn::IConnectableLayer* layer = m_Network->AddUnidirectionalSequenceLstmLayer(desc, params);
3535 ARMNN_ASSERT(layer != nullptr);
3536
3537 // register the input connection slots for the layer, connections are made after all layers have been created
3538 // only the tensors for the inputs are relevant, exclude the const tensors
3539 auto inputTensorIndexes = AsUnsignedVector({operatorPtr->inputs[0],
3540 operatorPtr->inputs[18],
3541 operatorPtr->inputs[19]});
3542 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0],
3543 inputTensorIndexes[1],
3544 inputTensorIndexes[2]});
3545
3546 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3547
3548 layer->GetOutputSlot(0).SetTensorInfo(outputStateOutTensorInfo);
3549 layer->GetOutputSlot(1).SetTensorInfo(cellStateOutTensorInfo);
3550 layer->GetOutputSlot(2).SetTensorInfo(outputTensorInfo);
3551
3552 unsigned int tensorIndex = outputTensorIndexes[0];
3553 armnn::IOutputSlot* slot = &(layer->GetOutputSlot(2));
3554 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
3555}
3556
Kevin May7d96b162021-02-03 17:38:41 +00003557void TfLiteParserImpl::ParseUnpack(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd200e3802019-04-15 09:47:39 +01003558{
3559 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3560
Mike Kelly0d77ae12022-01-07 17:42:27 +00003561 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3562 const auto* options = operatorPtr->builtin_options.AsUnpackOptions();
Nina Drozd200e3802019-04-15 09:47:39 +01003563
3564 // This unpackAxis indicates the axis to unpack
3565 const unsigned int unpackAxis = CHECKED_NON_NEGATIVE(options->axis);
3566
3567 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3568 CHECK_VALID_SIZE(inputs.size(), 1);
3569
3570 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003571
3572 if (unpackAxis >= inputTensorInfo.GetNumDimensions())
3573 {
3574 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003575 fmt::format("The unpack axis: {} cannot be greater than or equal to "
3576 "the number of input dimension {} {}",
3577 unpackAxis,
3578 inputTensorInfo.GetNumDimensions(),
3579 CHECK_LOCATION().AsString()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003580 }
3581
Nina Drozd200e3802019-04-15 09:47:39 +01003582 unsigned int unpackNum = CHECKED_NON_NEGATIVE(options->num);
3583 // If num is not defined, automatically infer from the length of the dimension axis.
3584 if(unpackNum == 0)
3585 {
3586 unpackNum = inputTensorInfo.GetShape()[unpackAxis];
3587 }
3588
3589 // If unpack number cannot be inferred and is still zero, throw ParseException.
3590 if(unpackNum == 0)
3591 {
3592 throw ParseException("Number to unpack must greater than zero.");
3593 }
3594
3595 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3596 CHECK_VALID_SIZE(outputs.size(), unpackNum);
3597
3598 auto inputDimSize = inputTensorInfo.GetNumDimensions();
3599 std::vector<unsigned int> unpackDimSizes(inputDimSize);
3600
3601 // Add current input shape to unpackDimSizes
3602 for (unsigned int i = 0; i < inputDimSize; ++i)
3603 {
3604 unpackDimSizes[i] = inputTensorInfo.GetShape()[i];
3605 }
3606
3607 if (unpackDimSizes[unpackAxis] != unpackNum)
3608 {
3609 throw ParseException("Number to unpack must be the same as length of the dimension to "
3610 "unpack along.");
3611 }
3612
3613 unpackDimSizes[unpackAxis] /= unpackNum;
3614
3615 SplitterDescriptor splitDesc(unpackNum, static_cast<unsigned int>(unpackDimSizes.size()));
3616 for (unsigned int j = 0; j < unpackNum; ++j)
3617 {
3618 // Set the size of the views.
3619 for (unsigned int dimIdx = 0; dimIdx < unpackDimSizes.size(); ++dimIdx)
3620 {
3621 splitDesc.SetViewSize(j, dimIdx, unpackDimSizes[dimIdx]);
3622 }
3623 splitDesc.SetViewOriginCoord(j, unpackAxis, unpackDimSizes[unpackAxis] * j);
3624 }
3625
James Ward58dec6b2020-09-11 17:32:44 +01003626 auto layerName = fmt::format("Unpack:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd200e3802019-04-15 09:47:39 +01003627 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01003628 ARMNN_ASSERT(layer != nullptr);
Nina Drozd200e3802019-04-15 09:47:39 +01003629
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003630 TensorShape splitOutShape = TensorShape(static_cast<unsigned int>(unpackDimSizes.size()),
3631 unpackDimSizes.data());
3632
Nina Drozd200e3802019-04-15 09:47:39 +01003633 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3634 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3635
Finn Williamsb49ed182021-06-29 15:50:08 +01003636 std::vector<unsigned int> reshapeDims;
3637 for (unsigned int axis = 0; axis < splitOutShape.GetNumDimensions(); ++axis)
3638 {
3639 if (axis != unpackAxis)
3640 {
3641 reshapeDims.push_back(splitOutShape[axis]);
3642 }
3643 }
3644
3645 TensorShape reshapeOutputShape(splitOutShape.GetNumDimensions() -1, reshapeDims.data());
3646
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003647 // Create reshape to remove the unpacked dimension for unpack operator of each output from Splitter.
3648 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
3649 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01003650 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[k], true);
James Ward58dec6b2020-09-11 17:32:44 +01003651 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003652 armnn::ReshapeDescriptor desc;
Finn Williamsb49ed182021-06-29 15:50:08 +01003653 desc.m_TargetShape = reshapeOutputShape;
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003654 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(desc, layerName.c_str());
3655
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01003656 layer->GetOutputSlot(k).SetTensorInfo(armnn::TensorInfo(splitOutShape,
3657 outputTensorInfo.GetDataType(),
3658 outputTensorInfo.GetQuantizationScale(),
3659 outputTensorInfo.GetQuantizationOffset()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003660 layer->GetOutputSlot(k).Connect(reshapeLayer->GetInputSlot(0));
3661
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01003662 reshapeLayer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003663
3664 uint32_t reshapedOutputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[k]);
3665 armnn::IOutputSlot* slot = &(reshapeLayer->GetOutputSlot(0));
3666 RegisterProducerOfTensor(subgraphIndex, reshapedOutputId, slot);
3667 }
Nina Drozd200e3802019-04-15 09:47:39 +01003668}
3669
Kevin May7d96b162021-02-03 17:38:41 +00003670void TfLiteParserImpl::ParseSplit(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd0324f482019-04-08 10:52:10 +01003671{
3672 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3673
Mike Kelly0d77ae12022-01-07 17:42:27 +00003674 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3675 const auto* options = operatorPtr->builtin_options.AsSplitOptions();
Nina Drozd0324f482019-04-08 10:52:10 +01003676
3677 const unsigned int numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
3678
Nina Drozd200e3802019-04-15 09:47:39 +01003679 // If number of splits cannot be inferred and is zero, throw ParseException.
3680 if(numSplits == 0)
3681 {
3682 throw ParseException("Number to splits must greater than zero.");
3683 }
3684
Nina Drozd0324f482019-04-08 10:52:10 +01003685 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3686 CHECK_VALID_SIZE(inputs.size(), 2);
3687 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3688 CHECK_VALID_SIZE(outputs.size(), numSplits);
3689
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003690 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[1]);
3691 armnn::TensorInfo axisTensorInfo = ToTensorInfo(inputs[0]);
3692 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
Nina Drozd0324f482019-04-08 10:52:10 +01003693
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003694 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003695 if (axisBufferPtr == nullptr)
3696 {
3697 throw ParseException(
3698 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
3699 CHECK_LOCATION().AsString()));
3700 }
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003701
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003702 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
3703 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
3704 int32_t axis = axisData[0];
3705
3706 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3707 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3708 {
3709 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
3710 // E.g. Rank 4 tensor can have axis in range [-4, 3)
3711 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
3712 throw ParseException(
3713 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3714 axis,
3715 CHECK_LOCATION().AsString()));
3716 }
3717
3718 const unsigned int splitDim = armnnUtils::GetUnsignedAxis(inputTensorInfo.GetNumDimensions(), axis);
Nina Drozd0324f482019-04-08 10:52:10 +01003719
Nina Drozd0324f482019-04-08 10:52:10 +01003720 auto inputDimSize = inputTensorInfo.GetNumDimensions();
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003721 if (inputDimSize > MaxNumOfTensorDimensions)
Nina Drozd0324f482019-04-08 10:52:10 +01003722 {
3723 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003724 fmt::format("The number of dimensions: {} for input tensors of the split op cannot be greater than {} {}",
3725 inputTensorInfo.GetNumDimensions(),
3726 MaxNumOfTensorDimensions,
3727 CHECK_LOCATION().AsString()));
Nina Drozd0324f482019-04-08 10:52:10 +01003728 }
3729
3730 std::vector<unsigned int> splitterDimSizes(inputDimSize);
3731
3732 // Add current input shape to splitterDimSizes
3733 for (unsigned int i = 0; i < inputDimSize; ++i)
3734 {
3735 splitterDimSizes[i] = inputTensorInfo.GetShape()[i];
3736 }
3737
3738 if (splitterDimSizes[splitDim] % numSplits != 0)
3739 {
3740 throw ParseException("Number of splits must evenly divide the dimension");
3741 }
3742 splitterDimSizes[splitDim] /= numSplits;
3743
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003744 SplitterDescriptor splitDesc(numSplits, inputDimSize);
Nina Drozd0324f482019-04-08 10:52:10 +01003745 for (unsigned int j = 0; j < numSplits; ++j)
3746 {
3747 // Set the size of the views.
3748 for (unsigned int dimIdx = 0; dimIdx < splitterDimSizes.size(); ++dimIdx)
3749 {
3750 splitDesc.SetViewSize(j, dimIdx, splitterDimSizes[dimIdx]);
3751 }
3752 splitDesc.SetViewOriginCoord(j, splitDim, splitterDimSizes[splitDim] * j);
3753 }
3754
James Ward58dec6b2020-09-11 17:32:44 +01003755 auto layerName = fmt::format("Split:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd0324f482019-04-08 10:52:10 +01003756 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01003757 ARMNN_ASSERT(layer != nullptr);
Nina Drozd0324f482019-04-08 10:52:10 +01003758
3759 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003760 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[1]});
Nina Drozd0324f482019-04-08 10:52:10 +01003761
Nina Drozd0324f482019-04-08 10:52:10 +01003762 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
3763 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01003764 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Francis Murtagh98d6b3d2019-10-21 10:52:54 +01003765 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
Nina Drozd0324f482019-04-08 10:52:10 +01003766 }
3767
3768 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3769 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3770}
3771
Derek Lambertif0176992020-04-28 13:37:49 +01003772unsigned int ComputeWrappedIndex(int idx, unsigned int numDimsIn)
3773{
3774 int numDims = armnn::numeric_cast<int>(numDimsIn);
3775 int v = idx < 0 ? numDims + idx : idx;
3776 ARMNN_ASSERT(v >= 0);
3777 ARMNN_ASSERT(v < numDims);
3778
3779 return static_cast<unsigned int>(v);
3780}
3781
Kevin May7d96b162021-02-03 17:38:41 +00003782void TfLiteParserImpl::ParseSplitV(size_t subgraphIndex, size_t operatorIndex)
Derek Lambertif0176992020-04-28 13:37:49 +01003783{
3784 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3785
Mike Kelly0d77ae12022-01-07 17:42:27 +00003786 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3787 const auto* options = operatorPtr->builtin_options.AsSplitVOptions();
Derek Lambertif0176992020-04-28 13:37:49 +01003788
3789 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3790 CHECK_VALID_SIZE(inputs.size(), 3);
3791
3792 auto& inputTensor = inputs[0];
3793 auto& splitsTensor = inputs[1];
3794 auto& axisTensor = inputs[2];
3795
3796 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputTensor);
3797 armnn::TensorInfo splitsInfo = ToTensorInfo(splitsTensor);
3798 armnn::TensorInfo axisTensorInfo = ToTensorInfo(axisTensor);
3799 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
3800
3801 // Inputs
3802 auto inputDimSize = inputTensorInfo.GetNumDimensions();
3803 if (inputDimSize > MaxNumOfTensorDimensions)
3804 {
3805 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003806 fmt::format("The number of dimensions: {} for input tensors of the "
3807 "SplitV op cannot be greater than {} {}",
3808 inputTensorInfo.GetNumDimensions(),
3809 MaxNumOfTensorDimensions,
3810 CHECK_LOCATION().AsString()));
Derek Lambertif0176992020-04-28 13:37:49 +01003811 }
3812
3813 // Get split axis
3814 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, axisTensor->buffer);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003815 if (axisBufferPtr == nullptr)
3816 {
3817 throw ParseException(
3818 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
3819 CHECK_LOCATION().AsString()));
3820 }
3821
Derek Lambertif0176992020-04-28 13:37:49 +01003822 std::vector<int> axisData(axisTensorInfo.GetNumElements());
3823 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003824 int32_t axis = axisData[0];
3825
3826 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3827 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3828 {
3829 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
3830 // E.g. Rank 4 tensor can have axis in range [-4, 3)
3831 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
3832 throw ParseException(
3833 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3834 axis,
3835 CHECK_LOCATION().AsString()));
3836 }
3837 const unsigned int splitDim = ComputeWrappedIndex(axis, inputTensorInfo.GetNumDimensions());
Derek Lambertif0176992020-04-28 13:37:49 +01003838
Derek Lambertif0176992020-04-28 13:37:49 +01003839 // Set split sizes
Derek Lambertif0176992020-04-28 13:37:49 +01003840 CHECK_VALID_SIZE(splitsInfo.GetNumDimensions(), 1);
Ryan OShea86704732020-05-26 11:41:04 +01003841 unsigned int numSplits{0};
3842
3843 if(options)
Derek Lambertif0176992020-04-28 13:37:49 +01003844 {
3845 numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
Derek Lambertif0176992020-04-28 13:37:49 +01003846 }
3847 else
3848 {
Ryan OShea86704732020-05-26 11:41:04 +01003849 numSplits = splitsInfo.GetNumElements();
Derek Lambertif0176992020-04-28 13:37:49 +01003850 }
3851
3852 if (numSplits <=0)
3853 {
3854 throw ParseException("SplitV has invalid number of splits");
3855 }
3856
Jan Eilersc0761e92020-06-29 16:48:44 +01003857 std::vector<int> splitsData(numSplits);
Ryan OShea86704732020-05-26 11:41:04 +01003858 BufferRawPtr splitsBufferPtr = GetBuffer(m_Model, splitsTensor->buffer);
Jan Eilersc0761e92020-06-29 16:48:44 +01003859 ::memcpy(splitsData.data(), splitsBufferPtr->data.data(), splitsInfo.GetNumBytes());
Ryan OShea86704732020-05-26 11:41:04 +01003860
Jan Eilersc0761e92020-06-29 16:48:44 +01003861 unsigned int idx = 0;
Ryan OShea86704732020-05-26 11:41:04 +01003862 int numInferred{0};
3863 unsigned int inferIdx{0};
3864 int splitSum{0};
3865 for (auto split : splitsData)
3866 {
3867 if (split < 0)
3868 {
3869 numInferred++;
3870 inferIdx = idx;
3871 }
3872 else
3873 {
3874 splitSum += split;
3875 }
3876 idx++;
3877 }
3878 // Check for inferred Axis
3879 if (numInferred == 0)
3880 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01003881 if (splitSum != armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]))
Ryan OShea86704732020-05-26 11:41:04 +01003882 {
3883 throw ParseException("SplitV split_sizes does not sum to the dimension of value along split_dim.");
3884 }
3885 }
3886 else if (numInferred == 1)
3887 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01003888 splitsData[inferIdx] = armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]) - splitSum;
Ryan OShea86704732020-05-26 11:41:04 +01003889 }
3890 else
3891 {
3892 throw ParseException("Cannot infer split size for more than one split");
3893 }
3894
Derek Lambertif0176992020-04-28 13:37:49 +01003895 //Ouput size validation
3896 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3897 CHECK_VALID_SIZE(outputs.size(), numSplits);
3898
3899 // Setup Armnn descriptor
3900 SplitterDescriptor splitDesc(numSplits, inputDimSize);
3901 unsigned int accumSplit = 0;
3902 for (unsigned int j = 0; j < numSplits; ++j)
3903 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01003904 unsigned int splitSize = armnn::numeric_cast<unsigned int>(splitsData[j]);
Derek Lambertif0176992020-04-28 13:37:49 +01003905
3906 // Set the size of the views.
3907 for (unsigned int dimIdx = 0; dimIdx < inputTensorInfo.GetNumDimensions(); ++dimIdx)
3908 {
3909 unsigned int dimSize = inputTensorInfo.GetShape()[dimIdx];
3910 if (dimIdx == splitDim)
3911 {
3912 dimSize = splitSize;
3913 }
3914 splitDesc.SetViewSize(j, dimIdx, dimSize);
3915 }
3916
3917 splitDesc.SetViewOriginCoord(j, splitDim, accumSplit);
3918 accumSplit += splitSize;
3919 }
3920
James Ward58dec6b2020-09-11 17:32:44 +01003921 auto layerName = fmt::format("SplitV:{}:{}", subgraphIndex, operatorIndex);
Derek Lambertif0176992020-04-28 13:37:49 +01003922 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01003923 ARMNN_ASSERT(layer != nullptr);
Derek Lambertif0176992020-04-28 13:37:49 +01003924
3925 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3926 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3927
3928 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
3929 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01003930 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Derek Lambertif0176992020-04-28 13:37:49 +01003931 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
3932 }
3933
3934 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3935 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3936}
3937
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003938void TfLiteParserImpl::ParseArgMin(size_t subgraphIndex, size_t operatorIndex)
3939{
3940 ParseArgMinMax(subgraphIndex, operatorIndex, armnn::ArgMinMaxFunction::Min);
3941}
3942
Kevin May7d96b162021-02-03 17:38:41 +00003943void TfLiteParserImpl::ParseArgMax(size_t subgraphIndex, size_t operatorIndex)
Inki Daed4619e22020-09-10 15:33:54 +09003944{
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003945 ParseArgMinMax(subgraphIndex, operatorIndex, armnn::ArgMinMaxFunction::Max);
3946}
3947
3948void TfLiteParserImpl::ParseArgMinMax(size_t subgraphIndex, size_t operatorIndex, ArgMinMaxFunction argMinMaxFunction)
3949{
Inki Daed4619e22020-09-10 15:33:54 +09003950 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3951 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3952 CHECK_VALID_SIZE(inputs.size(), 2);
3953
3954 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3955 CHECK_VALID_SIZE(outputs.size(), 1);
3956
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003957 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3958 armnn::TensorInfo axisTensorInfo = ToTensorInfo(inputs[1]);
Inki Daed4619e22020-09-10 15:33:54 +09003959 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003960 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003961
3962 // Check if output tensor type is Signed32 or Signed64
Mike Kelly1f140f72021-04-06 12:25:55 +01003963 if (outputTensorInfo.GetDataType() != armnn::DataType::Signed32 &&
3964 outputTensorInfo.GetDataType() != armnn::DataType::Signed64)
3965 {
3966 throw ParseException(
3967 fmt::format(
3968 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
3969 CHECK_LOCATION().AsString()));
3970 }
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003971
3972 // Get const axis value from model and set it to descriptor.
3973 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
3974 if (axisBufferPtr == nullptr)
3975 {
3976 throw ParseException(
3977 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
3978 CHECK_LOCATION().AsString()));
3979 }
3980
3981 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
3982 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
3983 int32_t axis = axisData.front();
3984
3985 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3986 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3987 {
3988 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
3989 // E.g. Rank 4 tensor can have axis in range [-4, 3)
3990 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
3991 throw ParseException(
3992 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3993 axis,
3994 CHECK_LOCATION().AsString()));
3995 }
3996
3997 ArgMinMaxDescriptor desc;
3998 desc.m_Axis = axis;
3999 desc.m_Function = argMinMaxFunction;
4000
4001 // Register a ArgMin/ArgMax layer.
4002 auto layerName = argMinMaxFunction == ArgMinMaxFunction::Max ? "ArgMax:{}:{}" : "ArgMin:{}:{}";
4003 auto layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
4004 IConnectableLayer *layer = m_Network->AddArgMinMaxLayer(desc, layerNameFormatted.c_str());
4005 ARMNN_ASSERT(layer != nullptr);
Inki Daed4619e22020-09-10 15:33:54 +09004006 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4007
4008 // Register input tensor to the layer.
4009 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4010 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4011
4012 // Register output tensor to the layer.
4013 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4014 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
4015}
4016
Kevin May7d96b162021-02-03 17:38:41 +00004017void TfLiteParserImpl::ParseGather(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00004018{
4019 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4020
Kevin May7d96b162021-02-03 17:38:41 +00004021 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004022 CHECK_VALID_SIZE(inputs.size(), 2);
Kevin May7d96b162021-02-03 17:38:41 +00004023 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004024 CHECK_VALID_SIZE(outputs.size(), 1);
4025
4026 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
4027 armnn::TensorInfo indicesTensorInfo = ToTensorInfo(inputs[1]);
4028 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
4029
4030 armnn::GatherDescriptor gatherDescriptor;
4031
Mike Kelly0d77ae12022-01-07 17:42:27 +00004032 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4033 const auto* options = operatorPtr->builtin_options.AsGatherOptions();
Sadik Armagan26868492021-01-22 14:25:31 +00004034 auto axis = options->axis;
4035
4036 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
4037 auto indicesDimensions = indicesTensorInfo.GetNumDimensions();
4038 auto outputDimensions = outputTensorInfo.GetNumDimensions();
4039 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
4040 {
4041 throw ParseException(
4042 fmt::format("Operation has invalid axis: {} It is out of bounds [ -{}, {} ) {}",
4043 axis,
4044 inputDimensions, inputDimensions,
4045 CHECK_LOCATION().AsString()));
4046 }
4047 if (outputDimensions != static_cast<unsigned int>(inputDimensions) + indicesDimensions - 1)
4048 {
4049 throw ParseException(
4050 fmt::format("Operation has invalid output dimensions: {} Output must be an ({} + {} - 1) -D tensor {}",
4051 outputDimensions,
4052 inputDimensions, indicesDimensions,
4053 CHECK_LOCATION().AsString()));
4054 }
4055
4056 gatherDescriptor.m_Axis = axis;
4057
4058 auto layerName = fmt::format("Gather:{}:{}", subgraphIndex, operatorIndex);
4059 IConnectableLayer* layer = m_Network->AddGatherLayer(gatherDescriptor, layerName.c_str());
4060 ARMNN_ASSERT(layer != nullptr);
4061 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4062
4063 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4064 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
4065
4066 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4067 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4068}
4069
Teresa Charlin91a53ea2022-04-25 15:47:29 +01004070void TfLiteParserImpl::ParseGatherNd(size_t subgraphIndex, size_t operatorIndex)
4071{
4072 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4073
4074 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4075 CHECK_VALID_SIZE(inputs.size(), 2);
4076 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4077 CHECK_VALID_SIZE(outputs.size(), 1);
4078
4079 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
4080 armnn::TensorInfo indicesTensorInfo = ToTensorInfo(inputs[1]);
4081 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
4082
4083 auto layerName = fmt::format("GatherNd:{}:{}", subgraphIndex, operatorIndex);
4084 IConnectableLayer* layer = m_Network->AddGatherNdLayer(layerName.c_str());
4085 ARMNN_ASSERT(layer != nullptr);
4086 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4087
4088 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4089 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
4090
4091 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4092 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4093}
4094
Kevin May7d96b162021-02-03 17:38:41 +00004095void TfLiteParserImpl::ParseDepthToSpace(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00004096{
4097 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4098
Kevin May7d96b162021-02-03 17:38:41 +00004099 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004100 CHECK_VALID_SIZE(inputs.size(), 1);
Kevin May7d96b162021-02-03 17:38:41 +00004101 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004102 CHECK_VALID_SIZE(outputs.size(), 1);
4103
4104 armnn::DepthToSpaceDescriptor descriptor;
4105
Mike Kelly0d77ae12022-01-07 17:42:27 +00004106 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4107 const auto* options = operatorPtr->builtin_options.AsDepthToSpaceOptions();
Sadik Armagan26868492021-01-22 14:25:31 +00004108 auto blockSize = options->block_size;
4109 if (blockSize < 2)
4110 {
4111 throw ParseException(
4112 fmt::format("Operation has invalid block size: {} Block size should be >= 2 {}",
4113 blockSize,
4114 CHECK_LOCATION().AsString()));
4115 }
4116 descriptor.m_BlockSize = armnn::numeric_cast<uint32_t>(blockSize);
4117
4118 auto layerName = fmt::format("DepthToSpace:{}:{}", subgraphIndex, operatorIndex);
4119 IConnectableLayer* layer = m_Network->AddDepthToSpaceLayer(descriptor, layerName.c_str());
4120 ARMNN_ASSERT(layer != nullptr);
4121 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
4122 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4123
4124 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4125 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4126
4127 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4128 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4129}
4130
Kevin May7d96b162021-02-03 17:38:41 +00004131void TfLiteParserImpl::ParseSum(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004132{
Sadik Armagana2747482021-02-09 10:28:54 +00004133 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Sum);
4134}
4135
Teresa Charlin4e3e8312021-08-05 12:34:37 +01004136void TfLiteParserImpl::ParseReduceProd(size_t subgraphIndex, size_t operatorIndex)
4137{
4138 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Prod);
4139}
4140
Sadik Armagana2747482021-02-09 10:28:54 +00004141void TfLiteParserImpl::ParseReduceMax(size_t subgraphIndex, size_t operatorIndex)
4142{
4143 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Max);
4144}
4145
4146void TfLiteParserImpl::ParseReduceMin(size_t subgraphIndex, size_t operatorIndex)
4147{
4148 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Min);
4149}
4150
4151void TfLiteParserImpl::ParseReduce(size_t subgraphIndex, size_t operatorIndex, ReduceOperation reduceOperation)
4152{
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004153 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4154
Mike Kelly0d77ae12022-01-07 17:42:27 +00004155 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4156 const auto* options = operatorPtr->builtin_options.AsReducerOptions();
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004157
4158 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4159 CHECK_VALID_SIZE(inputs.size(), 2);
4160
4161 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4162 CHECK_VALID_SIZE(outputs.size(), 1);
4163
Sadik Armagana2747482021-02-09 10:28:54 +00004164 auto layerName = fmt::format("Reduce:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004165
4166 armnn::TensorInfo inputTensorInfo0 = ToTensorInfo(inputs[0]);
4167 armnn::TensorInfo inputTensorInfo1 = ToTensorInfo(inputs[1]);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004168
4169 ReduceDescriptor desc;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004170 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
4171 // Get const axis value from model and set it to descriptor.
4172 if (axisBufferPtr != nullptr)
4173 {
Sadik Armagan49bdb792021-02-11 13:57:07 +00004174 std::vector<int32_t> axisData(inputTensorInfo1.GetNumElements());
4175 ::memcpy(axisData.data(), axisBufferPtr->data.data(), inputTensorInfo1.GetNumBytes());
4176
4177 // Convert the axis to unsigned int and remove duplicates.
4178 auto rank = static_cast<int32_t>(inputTensorInfo0.GetNumDimensions());
4179 std::set<unsigned int> uniqueAxis;
4180 std::transform(axisData.begin(),
4181 axisData.end(),
4182 std::inserter(uniqueAxis, uniqueAxis.begin()),
4183 [rank](int i)->unsigned int{
4184 return static_cast<uint32_t>(((i + rank) % rank)); });
4185 desc.m_vAxis.assign(uniqueAxis.begin(), uniqueAxis.end());
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004186 }
Sadik Armagana2747482021-02-09 10:28:54 +00004187 else
4188 {
4189 for (uint32_t i = 0; i < inputTensorInfo0.GetNumDimensions(); ++i)
4190 {
4191 desc.m_vAxis.push_back(i);
4192 }
4193 }
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004194
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004195 desc.m_KeepDims = options->keep_dims;
Sadik Armagana2747482021-02-09 10:28:54 +00004196 desc.m_ReduceOperation = reduceOperation;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004197
4198 // Register a new layer object, Sum.
Mike Kelly0d77ae12022-01-07 17:42:27 +00004199 IConnectableLayer* layer = m_Network->AddReduceLayer(desc, layerName.c_str());
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004200
4201 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
4202 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4203
4204 // Register input tensor to the layer.
4205 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4206 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4207
4208 // Register output tensor to the layer.
4209 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4210 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
4211}
4212
Mike Kelly31dce2b2021-09-01 21:22:37 +01004213void TfLiteParserImpl::ParseLocalResponseNormalization(size_t subgraphIndex, size_t operatorIndex)
4214{
4215 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4216
4217 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4218 CHECK_VALID_SIZE(inputs.size(), 1);
4219
4220 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4221 CHECK_VALID_SIZE(outputs.size(), 1);
4222
4223 auto layerName = fmt::format("LRN:{}:{}", subgraphIndex, operatorIndex);
4224 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
4225
4226 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
4227
4228 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4229 const auto* options = operatorPtr->builtin_options.AsLocalResponseNormalizationOptions();
4230
4231 armnn::NormalizationDescriptor descriptor;
4232 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
4233 descriptor.m_NormChannelType = armnn::NormalizationAlgorithmChannel::Across;
4234 descriptor.m_NormMethodType = armnn::NormalizationAlgorithmMethod::LocalBrightness;
4235 descriptor.m_NormSize = static_cast<uint32_t>(options->radius);
4236 descriptor.m_K = options->bias;
4237 descriptor.m_Alpha = options->alpha;
4238 descriptor.m_Beta = options->beta;
4239
4240 // ArmNN expects normSize to be the full size of the normalization
4241 // window rather than the radius as in TfLite.
4242 descriptor.m_NormSize = 1 + (2 * descriptor.m_NormSize);
4243
4244 IConnectableLayer* layer = m_Network->AddNormalizationLayer(descriptor, layerNameFormatted.c_str());
4245 ARMNN_ASSERT(layer != nullptr);
4246
4247 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
4248 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4249
4250 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4251 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4252
4253 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4254 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4255}
4256
Teresa Charlin28aa6692022-07-12 11:18:44 +01004257void TfLiteParserImpl::ParseAbs(size_t subgraphIndex, size_t operatorIndex)
4258{
4259 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Abs);
4260}
4261
4262void TfLiteParserImpl::ParseExp(size_t subgraphIndex, size_t operatorIndex)
4263{
4264 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Exp);
4265}
4266
4267void TfLiteParserImpl::ParseLog(size_t subgraphIndex, size_t operatorIndex)
4268{
4269 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Log);
4270}
4271
Matthew Sloyaned7fce42021-04-15 20:46:24 +01004272void TfLiteParserImpl::ParseLogicalNot(size_t subgraphIndex, size_t operatorIndex)
4273{
4274 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::LogicalNot);
4275}
4276
4277void TfLiteParserImpl::ParseNeg(size_t subgraphIndex, size_t operatorIndex)
4278{
4279 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Neg);
4280}
4281
4282void TfLiteParserImpl::ParseRsqrt(size_t subgraphIndex, size_t operatorIndex)
4283{
4284 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Rsqrt);
4285}
4286
Teresa Charlin28aa6692022-07-12 11:18:44 +01004287void TfLiteParserImpl::ParseSin(size_t subgraphIndex, size_t operatorIndex)
4288{
4289 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Sin);
4290}
4291
Teresa Charlinf0fce5b2022-05-04 17:24:43 +01004292void TfLiteParserImpl::ParseSqrt(size_t subgraphIndex, size_t operatorIndex)
4293{
4294 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Sqrt);
4295}
4296
Matthew Sloyaned7fce42021-04-15 20:46:24 +01004297void TfLiteParserImpl::ParseElementwiseUnary(size_t subgraphIndex, size_t operatorIndex, UnaryOperation unaryOperation)
4298{
4299 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4300
4301 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4302 CHECK_VALID_SIZE(inputs.size(), 1);
4303
4304 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4305 CHECK_VALID_SIZE(outputs.size(), 1);
4306
4307 std::string layerName = std::string(GetUnaryOperationAsCString(unaryOperation)) + ":{}:{}";
4308 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
4309
4310 ElementwiseUnaryDescriptor desc;
4311 desc.m_Operation = unaryOperation;
4312 IConnectableLayer* layer = m_Network->AddElementwiseUnaryLayer(desc, layerNameFormatted.c_str());
4313 ARMNN_ASSERT(layer != nullptr);
4314
4315 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
4316 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4317
4318 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4319 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4320
4321 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4322 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
4323}
4324
Bruno Goncalves2d0eb862021-07-11 14:10:15 -03004325void TfLiteParserImpl::ParseEqual(size_t subgraphIndex, size_t operatorIndex)
4326{
4327 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::Equal);
4328}
4329
4330void TfLiteParserImpl::ParseNotEqual(size_t subgraphIndex, size_t operatorIndex)
4331{
4332 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::NotEqual);
4333}
4334
4335void TfLiteParserImpl::ParseGreater(size_t subgraphIndex, size_t operatorIndex)
4336{
4337 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::Greater);
4338}
4339
4340void TfLiteParserImpl::ParseGreaterOrEqual(size_t subgraphIndex, size_t operatorIndex)
4341{
4342 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::GreaterOrEqual);
4343}
4344
4345void TfLiteParserImpl::ParseLess(size_t subgraphIndex, size_t operatorIndex)
4346{
4347 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::Less);
4348}
4349
4350void TfLiteParserImpl::ParseLessOrEqual(size_t subgraphIndex, size_t operatorIndex)
4351{
4352 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::LessOrEqual);
4353}
4354
4355void TfLiteParserImpl::ParseComparison(size_t subgraphIndex, size_t operatorIndex,
4356 ComparisonOperation comparisonOperation)
4357{
4358 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4359
4360 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4361 CHECK_VALID_SIZE(inputs.size(), 2);
4362
4363 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4364 CHECK_VALID_SIZE(outputs.size(), 1);
4365
4366 auto layerName = std::string(GetComparisonOperationAsCString(comparisonOperation)) + ":{}:{}";
4367 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
4368
4369 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
4370 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
4371 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerNameFormatted, "Input 0", "Input 1");
4372
4373 ComparisonDescriptor desc;
4374 desc.m_Operation = comparisonOperation;
4375 IConnectableLayer* layer = m_Network->AddComparisonLayer(desc, layerNameFormatted.c_str());
4376 ARMNN_ASSERT(layer != nullptr);
4377
4378 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
4379 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4380
4381 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4382 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
4383
4384 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4385 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4386}
4387
Kevin May7d96b162021-02-03 17:38:41 +00004388armnn::IConnectableLayer* TfLiteParserImpl::AddFusedActivationLayer(armnn::IConnectableLayer* prevLayer,
4389 unsigned int outputSlot,
4390 tflite::ActivationFunctionType activationType)
telsoa01c577f2c2018-08-31 09:22:23 +01004391{
4392 ActivationDescriptor activationDesc;
4393 std::string layerName = prevLayer->GetName();
4394
4395 switch(activationType)
4396 {
4397 case tflite::ActivationFunctionType_NONE:
4398 {
4399 // this is a no-op: return previous layer
4400 return prevLayer;
4401 }
4402 case tflite::ActivationFunctionType_RELU:
4403 {
4404 activationDesc.m_Function = ActivationFunction::ReLu;
4405 layerName += ":RELU";
4406 break;
4407 }
4408 case tflite::ActivationFunctionType_RELU6:
4409 {
4410 activationDesc.m_Function = ActivationFunction::BoundedReLu;
4411 activationDesc.m_A = 6.0f;
4412 activationDesc.m_B = 0.0f;
4413 layerName += ":RELU6";
4414 break;
4415 }
4416 case tflite::ActivationFunctionType_TANH:
4417 {
4418 activationDesc.m_Function = ActivationFunction::TanH;
4419 activationDesc.m_A = 1.0f;
4420 activationDesc.m_B = 1.0f;
4421 layerName += ":TANH";
4422 break;
4423 }
4424
4425 // I only put these here as a reminder what others we could support
4426 case tflite::ActivationFunctionType_RELU_N1_TO_1:
4427 case tflite::ActivationFunctionType_SIGN_BIT:
4428 default:
4429 {
4430 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004431 fmt::format("TfLite parser doesn't suppport fused activation: "
4432 "{}/{} {} ",
4433 activationType,
4434 tflite::EnumNameActivationFunctionType(activationType),
4435 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004436
4437 }
4438 }
4439
4440 IConnectableLayer* activationLayer =
4441 m_Network->AddActivationLayer(activationDesc, layerName.c_str());
4442
4443 auto & prevOutputSlot = prevLayer->GetOutputSlot(outputSlot);
4444 prevOutputSlot.Connect(activationLayer->GetInputSlot(0));
4445 activationLayer->GetOutputSlot(0).SetTensorInfo(prevOutputSlot.GetTensorInfo());
4446 return activationLayer;
4447}
4448
Teresa Charlincdbd40b2022-02-25 13:21:55 +00004449armnn::IConnectableLayer* TfLiteParserImpl::AddFusedFloorLayer(armnn::IConnectableLayer* prevLayer,
4450 unsigned int outputSlot)
4451{
Teresa Charlin725728e2022-05-05 13:33:33 +01004452
4453 auto& prevOutputSlot = prevLayer->GetOutputSlot(outputSlot);
4454 DataType dataType = prevOutputSlot.GetTensorInfo().GetDataType();
4455
4456 if (dataType == DataType::Signed32)
4457 {
4458 return prevLayer;
4459 }
4460
Teresa Charlincdbd40b2022-02-25 13:21:55 +00004461 std::string layerName = prevLayer->GetName();
4462 IConnectableLayer* floorLayer = m_Network->AddFloorLayer(layerName.c_str());
4463
Teresa Charlincdbd40b2022-02-25 13:21:55 +00004464 prevOutputSlot.Connect(floorLayer->GetInputSlot(0));
4465 floorLayer->GetOutputSlot(0).SetTensorInfo(prevOutputSlot.GetTensorInfo());
Teresa Charlin725728e2022-05-05 13:33:33 +01004466
Teresa Charlincdbd40b2022-02-25 13:21:55 +00004467 return floorLayer;
4468}
4469
Mike Kelly0d77ae12022-01-07 17:42:27 +00004470TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromFile(const char* fileName)
telsoa01c577f2c2018-08-31 09:22:23 +01004471{
4472 if (fileName == nullptr)
4473 {
James Ward58dec6b2020-09-11 17:32:44 +01004474 throw InvalidArgumentException(fmt::format("Invalid (null) file name {}",
telsoa01c577f2c2018-08-31 09:22:23 +01004475 CHECK_LOCATION().AsString()));
4476 }
Francis Murtagh532a29d2020-06-29 11:50:01 +01004477 std::error_code errorCode;
4478 fs::path pathToFile(fileName);
4479 if (!fs::exists(pathToFile, errorCode))
telsoa01c577f2c2018-08-31 09:22:23 +01004480 {
James Ward58dec6b2020-09-11 17:32:44 +01004481 //fmt::format() could not be used here (format error)
4482 std::stringstream msg;
4483 msg << "Cannot find the file (" << fileName << ") errorCode: " << errorCode
4484 << " " << CHECK_LOCATION().AsString();
4485
4486 throw FileNotFoundException(msg.str());
telsoa01c577f2c2018-08-31 09:22:23 +01004487 }
4488 std::ifstream file(fileName, std::ios::binary);
4489 std::string fileContent((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
4490 return LoadModelFromBinary(reinterpret_cast<const uint8_t *>(fileContent.c_str()),
4491 fileContent.size());
4492}
4493
Mike Kelly0d77ae12022-01-07 17:42:27 +00004494TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromBinary(const uint8_t* binaryContent, size_t len)
telsoa01c577f2c2018-08-31 09:22:23 +01004495{
4496 if (binaryContent == nullptr)
4497 {
James Ward58dec6b2020-09-11 17:32:44 +01004498 throw InvalidArgumentException(fmt::format("Invalid (null) binary content {}",
telsoa01c577f2c2018-08-31 09:22:23 +01004499 CHECK_LOCATION().AsString()));
4500 }
4501 flatbuffers::Verifier verifier(binaryContent, len);
4502 if (verifier.VerifyBuffer<tflite::Model>() == false)
4503 {
4504 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004505 fmt::format("Buffer doesn't conform to the expected Tensorflow Lite "
4506 "flatbuffers format. size:{} {}",
4507 len,
4508 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004509 }
4510 return tflite::UnPackModel(binaryContent);
4511}
4512
Mike Kelly0d77ae12022-01-07 17:42:27 +00004513TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetInputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00004514 size_t subgraphIndex,
4515 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004516{
4517 CHECK_MODEL(model, subgraphIndex, operatorIndex);
4518
Mike Kelly0d77ae12022-01-07 17:42:27 +00004519 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4520 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004521
4522 size_t inputCount = operatorPtr->inputs.size();
mathad01c21025d2021-04-26 10:09:37 +01004523 TensorRawPtrVector result;
Mike Kelly0d77ae12022-01-07 17:42:27 +00004524 for (size_t i = 0; i < inputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004525 {
mathad01c21025d2021-04-26 10:09:37 +01004526 // If the input location is -1 then assume input is turned off.
4527 if (operatorPtr->inputs[i] == -1)
4528 {
4529 continue;
4530 }
4531 else
4532 {
4533 uint32_t inputId = CHECKED_NON_NEGATIVE(operatorPtr->inputs[i]);
4534 result.push_back(subgraphPtr->tensors[inputId].get());
4535 }
telsoa01c577f2c2018-08-31 09:22:23 +01004536 }
4537 return result;
4538}
4539
Mike Kelly0d77ae12022-01-07 17:42:27 +00004540TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetOutputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00004541 size_t subgraphIndex,
4542 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004543{
4544 CHECK_MODEL(model, subgraphIndex, operatorIndex);
4545
Mike Kelly0d77ae12022-01-07 17:42:27 +00004546 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4547 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004548
4549 size_t outputCount = operatorPtr->outputs.size();
4550 TensorRawPtrVector result(outputCount);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004551 for (size_t i = 0; i < outputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004552 {
4553 uint32_t outputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[i]);
4554 CHECK_TENSOR(model, subgraphIndex, outputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01004555 result[i] = subgraphPtr->tensors[outputId].get();
telsoa01c577f2c2018-08-31 09:22:23 +01004556 }
4557 return result;
4558}
4559
Mike Kelly0d77ae12022-01-07 17:42:27 +00004560TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphInputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00004561 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004562{
4563 CHECK_SUBGRAPH(model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004564 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004565
Derek Lambertiff05cc52019-04-26 13:05:17 +01004566 size_t inputCount = subgraphPtr->inputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01004567 TensorIdRawPtrVector result(inputCount);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004568 for (size_t i = 0; i < inputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004569 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01004570 uint32_t inputId = CHECKED_NON_NEGATIVE(subgraphPtr->inputs[i]);
telsoa01c577f2c2018-08-31 09:22:23 +01004571 CHECK_TENSOR(model, subgraphIndex, inputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01004572 result[i] = std::make_pair(inputId, subgraphPtr->tensors[inputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01004573 }
4574 return result;
4575}
4576
Mike Kelly0d77ae12022-01-07 17:42:27 +00004577TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphOutputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00004578 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004579{
4580 CHECK_SUBGRAPH(model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004581 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004582
Derek Lambertiff05cc52019-04-26 13:05:17 +01004583 size_t outputCount = subgraphPtr->outputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01004584 TensorIdRawPtrVector result(outputCount);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004585 for (size_t i = 0; i < outputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004586 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01004587 uint32_t outputId = CHECKED_NON_NEGATIVE(subgraphPtr->outputs[i]);
4588 result[i] = std::make_pair(outputId, subgraphPtr->tensors[outputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01004589 }
4590 return result;
4591}
4592
Kevin May7d96b162021-02-03 17:38:41 +00004593std::vector<int32_t>& TfLiteParserImpl::GetInputTensorIds(const ModelPtr& model,
4594 size_t subgraphIndex,
4595 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004596{
4597 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004598 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4599 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004600 return operatorPtr->inputs;
4601}
4602
Kevin May7d96b162021-02-03 17:38:41 +00004603std::vector<int32_t>& TfLiteParserImpl::GetOutputTensorIds(const ModelPtr& model,
4604 size_t subgraphIndex,
4605 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004606{
4607 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004608 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4609 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004610 return operatorPtr->outputs;
4611}
4612
Kevin May7d96b162021-02-03 17:38:41 +00004613void TfLiteParserImpl::RegisterInputSlots(size_t subgraphIndex,
4614 size_t operatorIndex,
4615 IConnectableLayer* layer,
Finn Williamsd4fa5452021-03-01 12:31:41 +00004616 const std::vector<unsigned int>& tensorIndexes,
4617 unsigned int startingSlotIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004618{
4619 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01004620 ARMNN_ASSERT(layer != nullptr);
Matthew Sloyan81beae32021-07-13 19:46:11 +01004621
Finn Williamsd4fa5452021-03-01 12:31:41 +00004622 if (tensorIndexes.size() + startingSlotIndex != layer->GetNumInputSlots())
telsoa01c577f2c2018-08-31 09:22:23 +01004623 {
4624 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004625 fmt::format("The number of tensor inputs ({}) does not match the number expected ({})"
4626 " for subgraph:{} operator index:{} {}",
4627 tensorIndexes.size(),
4628 layer->GetNumInputSlots(),
4629 subgraphIndex,
4630 operatorIndex,
4631 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004632 }
4633
Finn Williamsd4fa5452021-03-01 12:31:41 +00004634 for (unsigned int index = 0; index < tensorIndexes.size() ; ++index)
telsoa01c577f2c2018-08-31 09:22:23 +01004635 {
Finn Williamsd4fa5452021-03-01 12:31:41 +00004636 unsigned int tensorIndex = tensorIndexes[index];
4637 armnn::IInputSlot* slot = &(layer->GetInputSlot(startingSlotIndex + index));
telsoa01c577f2c2018-08-31 09:22:23 +01004638 RegisterConsumerOfTensor(subgraphIndex, tensorIndex, slot);
4639 }
4640}
4641
Kevin May7d96b162021-02-03 17:38:41 +00004642void TfLiteParserImpl::RegisterOutputSlots(size_t subgraphIndex,
4643 size_t operatorIndex,
4644 IConnectableLayer* layer,
4645 const std::vector<unsigned int>& tensorIndexes)
telsoa01c577f2c2018-08-31 09:22:23 +01004646{
4647 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01004648 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01004649 if (tensorIndexes.size() != layer->GetNumOutputSlots())
4650 {
4651 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004652 fmt::format("The number of tensor outputs ({}) does not match the number expected ({})"
4653 " for subgraph:{} operator index:{} {}",
4654 tensorIndexes.size(),
4655 layer->GetNumOutputSlots(),
4656 subgraphIndex,
4657 operatorIndex,
4658 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004659 }
4660
4661 for (unsigned int slotIndex = 0; slotIndex < layer->GetNumOutputSlots(); ++slotIndex)
4662 {
4663 unsigned int tensorIndex = tensorIndexes[slotIndex];
4664 armnn::IOutputSlot* slot = &(layer->GetOutputSlot(slotIndex));
4665 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
4666 }
4667}
4668
Kevin May7d96b162021-02-03 17:38:41 +00004669void TfLiteParserImpl::SetupInputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004670{
4671 CHECK_SUBGRAPH(m_Model, subgraphIndex);
4672
4673 auto inputs = GetSubgraphInputs(m_Model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004674 for (auto const& tensorIdAndPtr : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004675 {
4676 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
4677 IConnectableLayer* layer =
4678 m_Network->AddInputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
4679
4680 auto tensorInfo = ToTensorInfo(tensorIdAndPtr.second);
4681 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
4682
4683 RegisterOutputSlots(subgraphIndex,
4684 VIRTUAL_OPERATOR_ID,
4685 layer,
4686 { static_cast<uint32_t>(tensorIdAndPtr.first) });
4687 }
4688}
4689
Kevin May7d96b162021-02-03 17:38:41 +00004690void TfLiteParserImpl::SetupOutputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004691{
4692 CHECK_SUBGRAPH(m_Model, subgraphIndex);
4693
4694 auto outputs = GetSubgraphOutputs(m_Model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004695 for (auto const& tensorIdAndPtr : outputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004696 {
4697 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
4698 IConnectableLayer* layer =
4699 m_Network->AddOutputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
4700
4701 RegisterInputSlots(subgraphIndex,
4702 VIRTUAL_OPERATOR_ID,
4703 layer,
4704 { static_cast<uint32_t>(tensorIdAndPtr.first) });
4705 }
4706}
4707
Mike Kelly5880b912022-01-28 16:18:54 +00004708void TfLiteParserImpl::SetupConstantLayers(size_t subgraph)
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004709{
Mike Kelly5880b912022-01-28 16:18:54 +00004710 CHECK_SUBGRAPH(m_Model, subgraph);
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004711
Mike Kelly5880b912022-01-28 16:18:54 +00004712 const auto & subgraphPtr = m_Model->subgraphs[subgraph];
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004713 for (unsigned int subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
4714 {
4715 for (unsigned int tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
4716 {
4717 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot == nullptr &&
4718 m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size() > 0)
4719 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01004720 TensorRawPtr tensorPtr = subgraphPtr->tensors[tensorIndex].get();
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004721
Mike Kelly5880b912022-01-28 16:18:54 +00004722 if (IsConstTensor(tensorPtr))
Matthew Sloyan81beae32021-07-13 19:46:11 +01004723 {
4724 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
Mike Kelly5880b912022-01-28 16:18:54 +00004725 armnn::DataType dataType = tensorInfo.GetDataType();
4726
4727 if (std::find(m_ConstantsToDequantize.begin(), m_ConstantsToDequantize.end(), tensorPtr->buffer)
4728 != m_ConstantsToDequantize.end())
4729 {
4730 dataType = DataType::Float32;
4731 }
4732 auto tensorAndData = CreateConstTensorNonPermuted(tensorPtr, tensorInfo, dataType);
4733
4734 std::string layerName = fmt::format("Constant:{}", tensorPtr->name);
4735 IConnectableLayer *layer = m_Network->AddConstantLayer(tensorAndData.first, layerName.c_str());
4736
4737 layer->GetOutputSlot(0).SetTensorInfo(tensorAndData.first.GetInfo());
4738 RegisterOutputSlots(subgraphIndex,
4739 VIRTUAL_OPERATOR_ID,
4740 layer,
4741 { tensorIndex });
4742 }
4743 else if (ShouldConstantTensorBeCreated(tensorIndex))
4744 {
4745 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
4746 armnn::DataType dataType = tensorInfo.GetDataType();
4747
4748 if (std::find(m_ConstantsToDequantize.begin(), m_ConstantsToDequantize.end(), tensorPtr->buffer)
4749 != m_ConstantsToDequantize.end())
4750 {
4751 dataType = DataType::Float32;
4752 }
4753 // Make sure isConstant flag is set.
4754 tensorInfo.SetConstant();
4755 tensorInfo.SetDataType(dataType);
4756
4757 auto tensorAndData = ConstTensor(tensorInfo, std::vector<uint8_t>(tensorInfo.GetNumBytes()));
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004758
Matthew Sloyan81beae32021-07-13 19:46:11 +01004759 std::string layerName = fmt::format("Constant:{}", tensorPtr->name);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004760 IConnectableLayer* layer = m_Network->AddConstantLayer(tensorAndData, layerName.c_str());
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004761
Matthew Sloyan81beae32021-07-13 19:46:11 +01004762 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
4763 RegisterOutputSlots(subgraphIndex,
4764 VIRTUAL_OPERATOR_ID,
4765 layer,
Mike Kelly5880b912022-01-28 16:18:54 +00004766 {tensorIndex});
Matthew Sloyan81beae32021-07-13 19:46:11 +01004767 }
4768 else
4769 {
4770 throw ParseException(
4771 fmt::format("Invalid Tensor: Tensor should be constant. {}",
4772 CHECK_LOCATION().AsString()));
4773 }
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004774 }
4775 }
4776 }
4777}
4778
telsoa01c577f2c2018-08-31 09:22:23 +01004779// example usage: BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Kevin May7d96b162021-02-03 17:38:41 +00004780TfLiteParserImpl::BufferRawPtr TfLiteParserImpl::GetBuffer(const ModelPtr& model, size_t bufferIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004781{
4782 CHECK_BUFFER(model, bufferIndex);
4783 return model->buffers[bufferIndex].get();
4784}
4785
Matteo Martincigh747ef822018-12-18 09:26:39 +00004786template<typename T>
Kevin May7d96b162021-02-03 17:38:41 +00004787std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
4788TfLiteParserImpl::CreateConstTensorAndStoreData(TfLiteParserImpl::BufferRawPtr bufferPtr,
4789 TfLiteParserImpl::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +00004790 armnn::TensorInfo& tensorInfo,
4791 armnn::Optional<armnn::PermutationVector&> permutationVector)
4792{
Matthew Sloyan81beae32021-07-13 19:46:11 +01004793 // Make sure isConstant flag is set.
4794 tensorInfo.SetConstant();
4795
Matteo Martincigh747ef822018-12-18 09:26:39 +00004796 auto constData = CreateConstTensorImpl<T>(bufferPtr,
4797 tensorPtr,
4798 tensorInfo,
4799 permutationVector);
Kevin May7d96b162021-02-03 17:38:41 +00004800 TfLiteParserImpl::SupportedDataStorage storage(std::move(constData.second));
Matteo Martincigh747ef822018-12-18 09:26:39 +00004801 return std::make_pair(constData.first, std::move(storage));
4802}
4803
Mike Kelly5880b912022-01-28 16:18:54 +00004804bool TfLiteParserImpl::ShouldConstantTensorBeCreated(unsigned int tensorIndex)
4805{
4806 // If the TensorIndex appears in the list of ConstantsToBeCreated then return true
4807 return (std::find(m_ConstantsToBeCreated.begin(), m_ConstantsToBeCreated.end(), tensorIndex)
4808 != m_ConstantsToBeCreated.end());
4809}
4810
Finn Williamsd4fa5452021-03-01 12:31:41 +00004811bool TfLiteParserImpl::IsConstTensor(TensorRawPtr tensorPtr)
4812{
4813 CHECK_TENSOR_PTR(tensorPtr);
mathad01bf7edb62021-04-20 16:12:45 +01004814 bool isConst = true;
4815
4816 auto buffer = GetBuffer(m_Model, tensorPtr->buffer);
4817 if (buffer->data.size() == 0)
4818 {
4819 isConst = false;
4820 }
4821
4822 return isConst;
Finn Williamsd4fa5452021-03-01 12:31:41 +00004823}
4824
Kevin May7d96b162021-02-03 17:38:41 +00004825std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
Finn Williamsd4fa5452021-03-01 12:31:41 +00004826TfLiteParserImpl::CreateConstTensorPermuted(TensorRawPtr tensorPtr,
4827 armnn::TensorInfo& tensorInfo,
4828 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +01004829{
4830 CHECK_TENSOR_PTR(tensorPtr);
4831 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
4832 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
4833
Matthew Sloyan81beae32021-07-13 19:46:11 +01004834 // Make sure isConstant flag is set.
4835 tensorInfo.SetConstant();
4836
telsoa01c577f2c2018-08-31 09:22:23 +01004837 switch (tensorInfo.GetDataType())
4838 {
4839 case armnn::DataType::Float32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00004840 return CreateConstTensorAndStoreData<float>(bufferPtr,
4841 tensorPtr,
4842 tensorInfo,
4843 permutationVector);
Derek Lambertif90c56d2020-01-10 17:14:08 +00004844 case armnn::DataType::QAsymmU8:
Matteo Martincigh747ef822018-12-18 09:26:39 +00004845 return CreateConstTensorAndStoreData<uint8_t>(bufferPtr,
4846 tensorPtr,
4847 tensorInfo,
4848 permutationVector);
Keith Davisd305e1a2020-01-22 11:57:54 +00004849 case armnn::DataType::QSymmS8:
4850 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
4851 tensorPtr,
4852 tensorInfo,
4853 permutationVector);
Keith Davis67e6c542020-02-19 10:08:33 +00004854 case armnn::DataType::QAsymmS8:
4855 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
4856 tensorPtr,
4857 tensorInfo,
4858 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01004859 case armnn::DataType::Signed32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00004860 return CreateConstTensorAndStoreData<int32_t>(bufferPtr,
4861 tensorPtr,
4862 tensorInfo,
4863 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01004864 default:
4865 {
4866 std::stringstream errString;
4867 errString << "Unexpected datatype when creating const tensor: "
4868 << armnn::GetDataTypeName(tensorInfo.GetDataType())
4869 << " shape:" << tensorInfo.GetShape()
4870 << CHECK_LOCATION().AsString();
4871 throw ParseException(errString.str());
4872 }
4873 }
4874}
4875
Finn Williamsd4fa5452021-03-01 12:31:41 +00004876armnn::ConstTensor TfLiteParserImpl::CreateConstTensorNonPermuted(TensorRawPtr tensorPtr,
4877 armnn::TensorInfo& tensorInfo)
4878{
4879 CHECK_TENSOR_PTR(tensorPtr);
4880 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
4881 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
4882
Matthew Sloyan81beae32021-07-13 19:46:11 +01004883 // Make sure isConstant flag is set.
4884 tensorInfo.SetConstant();
4885
Finn Williamsd4fa5452021-03-01 12:31:41 +00004886 return ConstTensor(tensorInfo, bufferPtr->data.data());
4887}
4888
Mike Kelly5880b912022-01-28 16:18:54 +00004889std::pair<armnn::ConstTensor, std::unique_ptr<float[]>>
4890TfLiteParserImpl::CreateConstTensorNonPermuted(TensorRawPtr tensorPtr,
4891 armnn::TensorInfo& tensorInfo,
4892 armnn::DataType inputDataType)
4893{
4894 CHECK_TENSOR_PTR(tensorPtr);
4895 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
4896 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
4897
4898 // Make sure isConstant flag is set.
4899 tensorInfo.SetConstant();
4900
4901 if (inputDataType == DataType::Float32 && tensorInfo.GetDataType() != DataType::Float32)
4902 {
4903 TensorInfo constTensorInfo(tensorInfo.GetShape(), DataType::Float32, 0.0f, 0, true);
4904 std::unique_ptr<float[]> data = AsFloatArray(bufferPtr, tensorInfo);
4905 return std::make_pair(ConstTensor(constTensorInfo, data.get()), std::move(data));
4906 }
4907 else
4908 {
4909 return std::make_pair(ConstTensor(tensorInfo, bufferPtr->data.data()), std::unique_ptr<float[]>());
4910 }
4911}
4912
4913std::pair<armnn::ConstTensor*, std::unique_ptr<float[]>>
4914TfLiteParserImpl::CreateConstTensorPtr(TensorRawPtr tensorPtr, armnn::TensorInfo& inputTensorInfo)
4915{
4916 CHECK_TENSOR_PTR(tensorPtr);
4917 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
4918 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
4919 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
4920
4921 // Make sure isConstant flag is set.
4922 tensorInfo.SetConstant();
4923
4924 if (inputTensorInfo.GetDataType() == DataType::Float32 && tensorInfo.GetDataType() != DataType::Float32)
4925 {
4926 TensorInfo constTensorInfo(tensorInfo.GetShape(), DataType::Float32, 0.0f, 0, true);
4927 std::unique_ptr<float[]> data = AsFloatArray(bufferPtr, tensorInfo);
4928 return std::make_pair(new ConstTensor(constTensorInfo, data.get()), std::move(data));
4929 }
4930 else
4931 {
4932 return std::make_pair(new ConstTensor(tensorInfo, bufferPtr->data.data()), std::unique_ptr<float[]>());
4933 }
4934}
4935
Kevin May7d96b162021-02-03 17:38:41 +00004936BindingPointInfo TfLiteParserImpl::GetNetworkInputBindingInfo(size_t subgraphId,
4937 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01004938{
4939 CHECK_SUBGRAPH(m_Model, subgraphId);
4940 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004941 for (auto const& input : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004942 {
4943 if (input.second->name == name)
4944 {
4945 auto bindingId = GenerateLayerBindingId(subgraphId, input.first);
Colm Donelan4bc993b2021-11-09 20:39:10 +00004946 auto inputTensorInfo = ToTensorInfo(input.second);
4947 // Input tensors are always treated as constant tensors during network execution.
4948 inputTensorInfo.SetConstant(true);
4949 return std::make_pair(bindingId, inputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01004950 }
4951 }
4952
4953 std::stringstream bindings;
Mike Kelly0d77ae12022-01-07 17:42:27 +00004954 for (auto const& input : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004955 {
4956 bindings << "'" << input.second->name << "' ";
4957 }
4958
4959 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004960 fmt::format("No input binding found for subgraph:{} and name:{}. "
4961 "Possible inputs are: [{}] {}",
4962 subgraphId,
4963 name,
4964 bindings.str(),
4965 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004966}
4967
Kevin May7d96b162021-02-03 17:38:41 +00004968BindingPointInfo TfLiteParserImpl::GetNetworkOutputBindingInfo(size_t subgraphId,
4969 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01004970{
4971 CHECK_SUBGRAPH(m_Model, subgraphId);
4972 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00004973 for (unsigned int i = 0; i < outputs.size(); ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004974 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00004975 auto const output = outputs[i];
telsoa01c577f2c2018-08-31 09:22:23 +01004976 if (output.second->name == name)
4977 {
4978 auto bindingId = GenerateLayerBindingId(subgraphId, output.first);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00004979 std::vector<unsigned int> shape = m_OverridenOutputShapes.size() > 0 ?
4980 m_OverridenOutputShapes[i] : AsUnsignedVector(output.second->shape);
4981 return std::make_pair(bindingId, ToTensorInfo(output.second, shape));
telsoa01c577f2c2018-08-31 09:22:23 +01004982 }
4983 }
4984
4985 std::stringstream bindings;
Mike Kelly0d77ae12022-01-07 17:42:27 +00004986 for (auto const& output : outputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004987 {
4988 bindings << "'" << output.second->name << "' ";
4989 }
4990
4991 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004992 fmt::format("No output binding found for subgraph:{} and name:{}. "
4993 "Possible outputs are: [{}] {}",
4994 subgraphId,
4995 name,
4996 bindings.str(),
4997 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004998}
4999
Kevin May7d96b162021-02-03 17:38:41 +00005000size_t TfLiteParserImpl::GetSubgraphCount() const
telsoa01c577f2c2018-08-31 09:22:23 +01005001{
5002 return m_Model->subgraphs.size();
5003}
5004
Kevin May7d96b162021-02-03 17:38:41 +00005005std::vector<std::string> TfLiteParserImpl::GetSubgraphInputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01005006{
5007 CHECK_SUBGRAPH(m_Model, subgraphId);
5008 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
5009 std::vector<std::string> result;
5010 result.reserve(inputs.size());
Mike Kelly0d77ae12022-01-07 17:42:27 +00005011 for (auto const& input : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005012 {
5013 result.push_back(input.second->name);
5014 }
5015 return result;
5016}
5017
Kevin May7d96b162021-02-03 17:38:41 +00005018std::vector<std::string> TfLiteParserImpl::GetSubgraphOutputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01005019{
5020 CHECK_SUBGRAPH(m_Model, subgraphId);
5021 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
5022 std::vector<std::string> result;
5023 result.reserve(outputs.size());
Mike Kelly0d77ae12022-01-07 17:42:27 +00005024 for (auto const& output : outputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005025 {
5026 result.push_back(output.second->name);
5027 }
5028 return result;
5029}
5030
Matthew Sloyanac001ee2021-02-03 10:43:04 +00005031const std::string TfLiteParserImpl::GetVersion()
5032{
5033 return TFLITE_PARSER_VERSION;
5034}
5035
Mike Kelly0d77ae12022-01-07 17:42:27 +00005036TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<float[]>&& data)
telsoa01c577f2c2018-08-31 09:22:23 +01005037: m_FloatData(std::move(data))
5038, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00005039, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01005040, m_Int32Data(nullptr)
5041{
5042}
5043
Mike Kelly0d77ae12022-01-07 17:42:27 +00005044TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<uint8_t[]>&& data)
telsoa01c577f2c2018-08-31 09:22:23 +01005045: m_FloatData(nullptr)
5046, m_Uint8Data(std::move(data))
Keith Davisd305e1a2020-01-22 11:57:54 +00005047, m_Int8Data(nullptr)
5048, m_Int32Data(nullptr)
5049{
5050}
5051
Mike Kelly0d77ae12022-01-07 17:42:27 +00005052TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int8_t[]>&& data)
Keith Davisd305e1a2020-01-22 11:57:54 +00005053: m_FloatData(nullptr)
5054, m_Uint8Data(nullptr)
5055, m_Int8Data(std::move(data))
telsoa01c577f2c2018-08-31 09:22:23 +01005056, m_Int32Data(nullptr)
5057{
5058}
5059
Mike Kelly0d77ae12022-01-07 17:42:27 +00005060TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int32_t[]>&& data)
telsoa01c577f2c2018-08-31 09:22:23 +01005061: m_FloatData(nullptr)
5062, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00005063, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01005064, m_Int32Data(std::move(data))
5065{
5066}
5067
5068} // armnnTfLiteParser