blob: f6c1ee9d38175a81be7c29edf5c9c30dd377b1e1 [file] [log] [blame]
telsoa01c577f2c2018-08-31 09:22:23 +01001//
Cathal Corbett9c843c32023-01-09 17:51:37 +00002// Copyright © 2022-2023 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 }
Mike Kelly0506ef02023-01-03 16:29:44 +0000319 else
320 {
321 CheckLocation location = CHECK_LOCATION();
322 throw ParseException(
323 fmt::format("Unsupported data type for uint buffer {}, only Signed 32 or Signed 64 are supported. {}",
324 GetDataTypeName(info.GetDataType()),
325 location.AsString()));
326 }
Mike Kelly0d77ae12022-01-07 17:42:27 +0000327 return buffer;
328}
329
telsoa01c577f2c2018-08-31 09:22:23 +0100330#define CHECK_BUFFER_SIZE(BUFFER_PTR, TENSOR_INFO, BUFFER_ID) \
331 CheckBufferSize(BUFFER_PTR, TENSOR_INFO, BUFFER_ID, CHECK_LOCATION())
332
333bool IsActivationSupported(tflite::ActivationFunctionType activationType)
334{
335 switch(activationType)
336 {
337 case tflite::ActivationFunctionType_NONE:
338 case tflite::ActivationFunctionType_RELU:
339 case tflite::ActivationFunctionType_RELU6:
340 case tflite::ActivationFunctionType_TANH:
341 {
342 return true;
343 }
344 default:
345 {
346 return false;
347 }
348 }
349}
350
351#define CHECK_SUPPORTED_FUSED_ACTIVATION(OPTION, SUBGRAPH_INDEX, OPERATOR_INDEX) \
352 do { \
353 if (IsActivationSupported(OPTION->fused_activation_function) == false) \
354 { \
355 throw ParseException( \
James Ward58dec6b2020-09-11 17:32:44 +0100356 fmt::format("TfLite parser doesn't suppport fused activation: " \
357 "{}/{} in {} subgraph:{} operator:{} at {}", \
358 OPTION->fused_activation_function, \
359 tflite::EnumNameActivationFunctionType(\
360 OPTION->fused_activation_function), \
361 __func__, \
362 SUBGRAPH_INDEX, \
363 OPERATOR_INDEX, \
364 CHECK_LOCATION().FileLine())); \
telsoa01c577f2c2018-08-31 09:22:23 +0100365 } \
366 } while(false)
367
368
Mike Kelly0d77ae12022-01-07 17:42:27 +0000369std::vector<unsigned int> AsUnsignedVector(const std::vector<int32_t>& in)
telsoa01c577f2c2018-08-31 09:22:23 +0100370{
371 std::vector<unsigned int> result;
372 result.reserve(in.size());
Mike Kelly0d77ae12022-01-07 17:42:27 +0000373 for (auto& i : in)
telsoa01c577f2c2018-08-31 09:22:23 +0100374 {
mathad01c21025d2021-04-26 10:09:37 +0100375 // If the location of the input data is -1 then the input should be ignored.
376 if (i == -1)
377 {
378 continue;
379 }
telsoa01c577f2c2018-08-31 09:22:23 +0100380 result.push_back(CHECKED_NON_NEGATIVE(i));
381 }
382 return result;
383}
384
Mike Kelly5880b912022-01-28 16:18:54 +0000385bool IsOptionalOperandPresent(int input)
386{
387 return (input >= 0);
388}
389
telsoa01c577f2c2018-08-31 09:22:23 +0100390void CalcPadding(uint32_t inputSize,
391 uint32_t filterSize,
392 uint32_t stride,
Pablo Tellof0bd6832019-04-26 17:58:13 +0100393 uint32_t dilation,
telsoa01c577f2c2018-08-31 09:22:23 +0100394 uint32_t& paddingFront,
395 uint32_t& paddingBack,
396 tflite::Padding padding)
397{
398 paddingFront = 0;
399 paddingBack = 0;
400 if (padding == tflite::Padding_SAME)
401 {
402 uint32_t outputSize = (inputSize + stride - 1) / stride;
Pablo Tellof0bd6832019-04-26 17:58:13 +0100403 uint32_t dilatedSize = filterSize + (dilation - 1) * (filterSize - 1);
404 uint32_t temp = (outputSize - 1) * stride + dilatedSize;
telsoa01c577f2c2018-08-31 09:22:23 +0100405 if (temp > inputSize)
406 {
407 paddingFront = (temp - inputSize) / 2;
408 paddingBack = (temp - inputSize) - paddingFront;
409 }
410 }
411}
412
Kevin May7d96b162021-02-03 17:38:41 +0000413armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr,
Finn Williamsb49ed182021-06-29 15:50:08 +0100414 const std::vector<unsigned int>& shape,
Sadik Armagand109a4d2020-07-28 10:42:13 +0100415 const bool outputTensor = false)
telsoa01c577f2c2018-08-31 09:22:23 +0100416{
417 armnn::DataType type;
418 CHECK_TENSOR_PTR(tensorPtr);
419
420 switch (tensorPtr->type)
421 {
422 case tflite::TensorType_UINT8:
Derek Lambertif90c56d2020-01-10 17:14:08 +0000423 type = armnn::DataType::QAsymmU8;
telsoa01c577f2c2018-08-31 09:22:23 +0100424 break;
425 case tflite::TensorType_FLOAT32:
426 type = armnn::DataType::Float32;
427 break;
Keith Davisb4dd5cc2022-04-07 11:32:00 +0100428 case tflite::TensorType_FLOAT16:
429 type = armnn::DataType::Float16;
430 break;
Finn Williamsed66d142019-12-06 09:55:55 +0000431 case tflite::TensorType_INT8:
Keith Davis67e6c542020-02-19 10:08:33 +0000432 if (tensorPtr->quantization->zero_point.size() == 1)
Ryan OShea03181ff2020-02-07 17:22:22 +0000433 {
Keith Davis0c2eeac2020-02-11 16:51:50 +0000434 // Per-tensor
Ryan OShea03181ff2020-02-07 17:22:22 +0000435 type = armnn::DataType::QAsymmS8;
436 }
437 else
438 {
Keith Davis0c2eeac2020-02-11 16:51:50 +0000439 // Per-channel
Ryan OShea03181ff2020-02-07 17:22:22 +0000440 type = armnn::DataType::QSymmS8;
441 }
Finn Williamsed66d142019-12-06 09:55:55 +0000442 break;
443 case tflite::TensorType_INT16:
Derek Lambertif90c56d2020-01-10 17:14:08 +0000444 type = armnn::DataType::QSymmS16;
Finn Williamsed66d142019-12-06 09:55:55 +0000445 break;
telsoa01c577f2c2018-08-31 09:22:23 +0100446 case tflite::TensorType_INT32:
447 type = armnn::DataType::Signed32;
448 break;
Inki Daed4619e22020-09-10 15:33:54 +0900449 case tflite::TensorType_INT64:
450 type = armnn::DataType::Signed64;
451 break;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100452 case tflite::TensorType_BOOL:
453 type = armnn::DataType::Boolean;
454 break;
telsoa01c577f2c2018-08-31 09:22:23 +0100455 default:
456 {
457 CheckLocation location = CHECK_LOCATION();
458 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100459 fmt::format("Unsupported data type {} = {} for tensor: {}. {}",
460 tensorPtr->type,
461 tflite::EnumNameTensorType(tensorPtr->type),
462 tensorPtr->name,
463 location.AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100464 }
465 }
Finn Williamsb49ed182021-06-29 15:50:08 +0100466 TensorShape tensorShape;
467
468 std::vector<unsigned int> safeShape = shape;
469 if (shape.size() == 0)
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100470 {
471 safeShape.push_back(1);
Finn Williamsb49ed182021-06-29 15:50:08 +0100472 }
473
474 if (!outputTensor)
475 {
476 tensorShape = TensorShape(armnn::numeric_cast<unsigned int>(safeShape.size()), safeShape.data());
477 }
478 else
479 {
Rob Hughesd812a312021-08-06 13:10:53 +0100480 size_t shapeSignatureSize = tensorPtr->shape_signature.size();
Finn Williamsb49ed182021-06-29 15:50:08 +0100481
482 // If a shape signature exists we will use that to infer dynamic tensors
483 if (shapeSignatureSize != 0)
Sadik Armagand109a4d2020-07-28 10:42:13 +0100484 {
Finn Williamsb49ed182021-06-29 15:50:08 +0100485 // If the shape is incompatible with the shape signature override the shape
486 if (shapeSignatureSize != shape.size())
487 {
488 safeShape = {};
489
490 for (unsigned int i = 0; i < shapeSignatureSize; ++i)
491 {
492 unsigned int dim = tensorPtr->shape_signature[i] > -1 ?
493 static_cast<unsigned int>(tensorPtr->shape_signature[i]) : 0;
494 safeShape.push_back(dim);
495 }
496 }
497
Rob Hughesd812a312021-08-06 13:10:53 +0100498 std::unique_ptr<bool[]> dimMask = std::make_unique<bool[]>(tensorPtr->shape_signature.size());
Finn Williamsb49ed182021-06-29 15:50:08 +0100499 for (unsigned int i = 0; i < tensorPtr->shape_signature.size(); ++i)
500 {
501 dimMask[i] = tensorPtr->shape_signature[i] == -1 ? false : true;
502 }
Rob Hughesd812a312021-08-06 13:10:53 +0100503 tensorShape = TensorShape(static_cast<unsigned int>(safeShape.size()), safeShape.data(), dimMask.get());
Finn Williamsb49ed182021-06-29 15:50:08 +0100504 }
505 // If there is no shape signature treat the tensor as dynamic if the shape has a size of zero
506 else if (shape.size() == 0)
507 {
508 tensorShape = TensorShape(1, false);
509 }
510 else
511 {
512 tensorShape = TensorShape(armnn::numeric_cast<unsigned int>(shape.size()), shape.data());
Sadik Armagand109a4d2020-07-28 10:42:13 +0100513 }
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100514 }
515
Keith Davisd305e1a2020-01-22 11:57:54 +0000516 float quantizationScale = 0.0f;
517 int32_t quantizationOffset = 0;
518
519 if (tensorPtr->quantization.get())
520 {
521 if (tensorPtr->quantization->scale.size() <= 1)
522 {
523 CHECK_VALID_SIZE(tensorPtr->quantization->zero_point.size(), 0, 1);
524 CHECK_VALID_SIZE(tensorPtr->quantization->zero_point.size(), 0, 1);
525
526 if (tensorPtr->quantization->scale.size() == 1)
527 {
528 quantizationScale = tensorPtr->quantization->scale[0];
529 }
530 if (tensorPtr->quantization->zero_point.size() == 1)
531 {
532 // NOTE: we lose precision here when converting from 64 bit to 32
Ryan OShea03181ff2020-02-07 17:22:22 +0000533 // but this is what we support at the moment in ArmNN
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100534 quantizationOffset = armnn::numeric_cast<int32_t>(tensorPtr->quantization->zero_point[0]);
Keith Davisd305e1a2020-01-22 11:57:54 +0000535 }
536
Sadik Armagand109a4d2020-07-28 10:42:13 +0100537 armnn::TensorInfo result(tensorShape,
538 type,
539 quantizationScale,
540 quantizationOffset);
Keith Davisd305e1a2020-01-22 11:57:54 +0000541 return result;
542 }
543 else
544 {
545 std::vector<float> quantizationScales;
546 std::vector<int32_t> quantizationOffsets;
547
548 // Scale
549 std::copy(tensorPtr->quantization->scale.begin(),
550 tensorPtr->quantization->scale.end(),
551 std::back_inserter(quantizationScales));
552
Keith Davis0c2eeac2020-02-11 16:51:50 +0000553 // QSymmS8 Per-axis
Sadik Armagand109a4d2020-07-28 10:42:13 +0100554 armnn::TensorInfo result(tensorShape,
555 type,
556 quantizationScales,
Jan Eilers7612bd62021-04-06 17:29:03 +0100557 armnn::numeric_cast<unsigned int>(tensorPtr->quantization->quantized_dimension));
Keith Davisd305e1a2020-01-22 11:57:54 +0000558 return result;
559 }
560 }
561 else
562 {
Sadik Armagand109a4d2020-07-28 10:42:13 +0100563 armnn::TensorInfo result(tensorShape,
Keith Davisd305e1a2020-01-22 11:57:54 +0000564 type,
565 quantizationScale,
566 quantizationOffset);
567 return result;
568 }
telsoa01c577f2c2018-08-31 09:22:23 +0100569}
570
Jan Eilers7612bd62021-04-06 17:29:03 +0100571armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr)
Narumol Prangnawarat4628d052019-02-25 17:26:05 +0000572{
Mike Kelly0d77ae12022-01-07 17:42:27 +0000573 auto const& dimensions = AsUnsignedVector(tensorPtr->shape);
Jan Eilers7612bd62021-04-06 17:29:03 +0100574 return ToTensorInfo(tensorPtr, dimensions);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +0000575}
576
Kevin May7d96b162021-02-03 17:38:41 +0000577armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr,
Sadik Armagand109a4d2020-07-28 10:42:13 +0100578 const bool outputTensor)
579{
Mike Kelly0d77ae12022-01-07 17:42:27 +0000580 auto const& dimensions = AsUnsignedVector(tensorPtr->shape);
Jan Eilers7612bd62021-04-06 17:29:03 +0100581 return ToTensorInfo(tensorPtr, dimensions, outputTensor);
Sadik Armagand109a4d2020-07-28 10:42:13 +0100582}
583
telsoa01c577f2c2018-08-31 09:22:23 +0100584template<typename T>
585std::pair<armnn::ConstTensor, std::unique_ptr<T[]>>
Kevin May7d96b162021-02-03 17:38:41 +0000586CreateConstTensorImpl(TfLiteParserImpl::BufferRawPtr bufferPtr,
587 TfLiteParserImpl::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +0000588 armnn::TensorInfo& tensorInfo,
589 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +0100590{
Jan Eilers8eb25602020-03-09 12:13:48 +0000591 IgnoreUnused(tensorPtr);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100592 ARMNN_ASSERT_MSG(tensorPtr != nullptr, "tensorPtr is null");
593 ARMNN_ASSERT_MSG(bufferPtr != nullptr,
James Ward58dec6b2020-09-11 17:32:44 +0100594 fmt::format("Buffer for buffer:{} is null", tensorPtr->buffer).c_str());
telsoa01c577f2c2018-08-31 09:22:23 +0100595
596 std::unique_ptr<T[]> data(new T[tensorInfo.GetNumElements()]);
Matteo Martincigh747ef822018-12-18 09:26:39 +0000597
598 if (permutationVector.has_value() && permutationVector.value().GetSize() > 0)
599 {
600 tensorInfo = armnnUtils::Permuted(tensorInfo, permutationVector.value());
Matteo Martincighd5b9e642019-01-04 18:01:21 +0000601 armnnUtils::Permute(tensorInfo.GetShape(), permutationVector.value(),
602 reinterpret_cast<const T*>(bufferPtr->data.data()), data.get(), sizeof(T));
Matteo Martincigh747ef822018-12-18 09:26:39 +0000603 }
604 else
605 {
606 ::memcpy(data.get(), bufferPtr->data.data(), tensorInfo.GetNumBytes());
607 }
608
Matthew Sloyan81beae32021-07-13 19:46:11 +0100609 // Make sure isConstant flag is set.
610 tensorInfo.SetConstant();
611
telsoa01c577f2c2018-08-31 09:22:23 +0100612 return std::make_pair(ConstTensor(tensorInfo, data.get()), std::move(data));
613}
614
telsoa01c577f2c2018-08-31 09:22:23 +0100615armnn::LayerBindingId GenerateLayerBindingId(size_t subgraphIndex, size_t tensorIndex)
616{
617 // generate the binding id by shifting the tensor id by 8 bit
618 // and add the subgraph id, which allows 256 subgraphs
619 return static_cast<armnn::LayerBindingId>((tensorIndex<<8)+subgraphIndex);
620}
621
Aron Virginas-Tar70672f62019-01-23 14:00:00 +0000622bool CheckShape(const armnn::TensorShape& actual, const std::vector<int32_t>& expected)
623{
624 const unsigned int actualSize = actual.GetNumDimensions();
625 if (actualSize != expected.size())
626 {
627 return false;
628 }
629
630 for (unsigned int i = 0u; i < actualSize; i++)
631 {
632 if (expected[i] < 0 ||
633 actual[i] != static_cast<unsigned int>(expected[i]))
634 {
635 return false;
636 }
637 }
638
639 return true;
640}
641
Cathal Corbett2b922e22022-09-23 15:49:24 +0100642bool CheckShape(const armnn::TensorShape& actual, const armnn::TensorShape& expected)
643{
644 std::vector<int32_t> expectedVec;
645 for (uint32_t i = 0; i < expected.GetNumDimensions(); i++)
646 {
647 expectedVec.push_back(expected[i]);
648 }
649 return CheckShape(actual, expectedVec);
650}
651
James Conroy05102392020-06-24 15:39:55 +0100652void CheckMatchingQuantization(const TensorInfo& first,
653 const TensorInfo& second,
654 const std::string& descName,
655 std::string const& firstName,
656 std::string const& secondName)
657{
658 if (!first.IsQuantized() ||
659 !second.IsQuantized())
660 {
661 // Not a quantized type, ignore the validation
662 return;
663 }
664
665 DataType firstDataType = first.GetDataType();
666 DataType secondDataType = second.GetDataType();
667
668 if (firstDataType != secondDataType)
669 {
670 throw InvalidArgumentException(descName + ": " + firstName + " and " + secondName +
671 " must be of the same quantized type, " +
672 firstName + " is " + GetDataTypeName(firstDataType) + ", " +
673 secondName + " is " + GetDataTypeName(secondDataType));
674 }
675
676 if (!first.IsTypeSpaceMatch(second))
677 {
678 throw InvalidArgumentException(descName + ": " + firstName + " and " + secondName +
679 " must have the same quantization space, " +
680 firstName + " has offset " + std::to_string(first.GetQuantizationOffset()) +
681 " and scale " + std::to_string(first.GetQuantizationScale()) + ", " +
682 secondName + " has offset " + std::to_string(second.GetQuantizationOffset()) +
683 " and scale " + std::to_string(second.GetQuantizationScale()));
684 }
685}
686
telsoa01c577f2c2018-08-31 09:22:23 +0100687} // <anonymous>
688
Kevin May7d96b162021-02-03 17:38:41 +0000689TfLiteParserImpl::TfLiteParserImpl(const Optional<ITfLiteParser::TfLiteParserOptions>& options)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100690: m_Options(options)
691, m_Network(nullptr, nullptr)
Kevin May7d96b162021-02-03 17:38:41 +0000692, m_ParserFunctions(tflite::BuiltinOperator_MAX+1, &TfLiteParserImpl::ParseUnsupportedOperator)
telsoa01c577f2c2018-08-31 09:22:23 +0100693{
694 // register supported operators
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100695 m_ParserFunctions[tflite::BuiltinOperator_ABS] = &TfLiteParserImpl::ParseAbs;
Kevin May7d96b162021-02-03 17:38:41 +0000696 m_ParserFunctions[tflite::BuiltinOperator_ADD] = &TfLiteParserImpl::ParseAdd;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100697 m_ParserFunctions[tflite::BuiltinOperator_ARG_MIN] = &TfLiteParserImpl::ParseArgMin;
698 m_ParserFunctions[tflite::BuiltinOperator_ARG_MAX] = &TfLiteParserImpl::ParseArgMax;
Kevin May7d96b162021-02-03 17:38:41 +0000699 m_ParserFunctions[tflite::BuiltinOperator_AVERAGE_POOL_2D] = &TfLiteParserImpl::ParseAveragePool2D;
700 m_ParserFunctions[tflite::BuiltinOperator_BATCH_TO_SPACE_ND] = &TfLiteParserImpl::ParseBatchToSpaceND;
Samuel Yapfd3ba5a2022-08-24 17:04:34 +0100701 m_ParserFunctions[tflite::BuiltinOperator_BATCH_MATMUL] = &TfLiteParserImpl::ParseBatchMatMul;
mathad01b392e982021-04-07 12:07:30 +0100702 m_ParserFunctions[tflite::BuiltinOperator_CAST] = &TfLiteParserImpl::ParseCast;
Kevin May7d96b162021-02-03 17:38:41 +0000703 m_ParserFunctions[tflite::BuiltinOperator_CONCATENATION] = &TfLiteParserImpl::ParseConcatenation;
704 m_ParserFunctions[tflite::BuiltinOperator_CONV_2D] = &TfLiteParserImpl::ParseConv2D;
Matthew Sloyan4d217c02021-10-07 11:48:58 +0100705 // Conv3D support was added in TF 2.5, so for backwards compatibility a hash define is needed.
Cathal Corbett80b4ef02022-05-25 11:21:11 +0100706 #if defined(ARMNN_POST_TFLITE_2_4)
Matthew Sloyaneb5f8102021-10-05 17:31:42 +0100707 m_ParserFunctions[tflite::BuiltinOperator_CONV_3D] = &TfLiteParserImpl::ParseConv3D;
Matthew Sloyan4d217c02021-10-07 11:48:58 +0100708 #endif
Kevin May7d96b162021-02-03 17:38:41 +0000709 m_ParserFunctions[tflite::BuiltinOperator_CUSTOM] = &TfLiteParserImpl::ParseCustomOperator;
710 m_ParserFunctions[tflite::BuiltinOperator_DEPTH_TO_SPACE] = &TfLiteParserImpl::ParseDepthToSpace;
711 m_ParserFunctions[tflite::BuiltinOperator_DEPTHWISE_CONV_2D] = &TfLiteParserImpl::ParseDepthwiseConv2D;
712 m_ParserFunctions[tflite::BuiltinOperator_DEQUANTIZE] = &TfLiteParserImpl::ParseDequantize;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100713 m_ParserFunctions[tflite::BuiltinOperator_DIV] = &TfLiteParserImpl::ParseDiv;
Kevin May7d96b162021-02-03 17:38:41 +0000714 m_ParserFunctions[tflite::BuiltinOperator_ELU] = &TfLiteParserImpl::ParseElu;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300715 m_ParserFunctions[tflite::BuiltinOperator_EQUAL] = &TfLiteParserImpl::ParseEqual;
Kevin May7d96b162021-02-03 17:38:41 +0000716 m_ParserFunctions[tflite::BuiltinOperator_EXP] = &TfLiteParserImpl::ParseExp;
Teresa Charlin3ab85482021-06-08 16:59:29 +0100717 m_ParserFunctions[tflite::BuiltinOperator_EXPAND_DIMS] = &TfLiteParserImpl::ParseExpandDims;
Teresa Charlincdbd40b2022-02-25 13:21:55 +0000718 m_ParserFunctions[tflite::BuiltinOperator_FLOOR_DIV] = &TfLiteParserImpl::ParseFloorDiv;
Kevin May7d96b162021-02-03 17:38:41 +0000719 m_ParserFunctions[tflite::BuiltinOperator_FULLY_CONNECTED] = &TfLiteParserImpl::ParseFullyConnected;
720 m_ParserFunctions[tflite::BuiltinOperator_GATHER] = &TfLiteParserImpl::ParseGather;
Teresa Charlin91a53ea2022-04-25 15:47:29 +0100721 m_ParserFunctions[tflite::BuiltinOperator_GATHER_ND] = &TfLiteParserImpl::ParseGatherNd;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300722 m_ParserFunctions[tflite::BuiltinOperator_GREATER] = &TfLiteParserImpl::ParseGreater;
723 m_ParserFunctions[tflite::BuiltinOperator_GREATER_EQUAL] = &TfLiteParserImpl::ParseGreaterOrEqual;
Kevin May7d96b162021-02-03 17:38:41 +0000724 m_ParserFunctions[tflite::BuiltinOperator_HARD_SWISH] = &TfLiteParserImpl::ParseHardSwish;
725 m_ParserFunctions[tflite::BuiltinOperator_LEAKY_RELU] = &TfLiteParserImpl::ParseLeakyRelu;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300726 m_ParserFunctions[tflite::BuiltinOperator_LESS] = &TfLiteParserImpl::ParseLess;
727 m_ParserFunctions[tflite::BuiltinOperator_LESS_EQUAL] = &TfLiteParserImpl::ParseLessOrEqual;
Mike Kelly31dce2b2021-09-01 21:22:37 +0100728 m_ParserFunctions[tflite::BuiltinOperator_LOCAL_RESPONSE_NORMALIZATION]
729 = &TfLiteParserImpl::ParseLocalResponseNormalization;
Teresa Charlin28aa6692022-07-12 11:18:44 +0100730 m_ParserFunctions[tflite::BuiltinOperator_LOG] = &TfLiteParserImpl::ParseLog;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100731 m_ParserFunctions[tflite::BuiltinOperator_LOGICAL_NOT] = &TfLiteParserImpl::ParseLogicalNot;
Kevin May7d96b162021-02-03 17:38:41 +0000732 m_ParserFunctions[tflite::BuiltinOperator_LOGISTIC] = &TfLiteParserImpl::ParseLogistic;
Teresa Charlinfd33a692022-06-29 15:35:57 +0100733 m_ParserFunctions[tflite::BuiltinOperator_LOG_SOFTMAX] = &TfLiteParserImpl::ParseLogSoftmax;
Kevin May7d96b162021-02-03 17:38:41 +0000734 m_ParserFunctions[tflite::BuiltinOperator_L2_NORMALIZATION] = &TfLiteParserImpl::ParseL2Normalization;
735 m_ParserFunctions[tflite::BuiltinOperator_MAX_POOL_2D] = &TfLiteParserImpl::ParseMaxPool2D;
736 m_ParserFunctions[tflite::BuiltinOperator_MAXIMUM] = &TfLiteParserImpl::ParseMaximum;
737 m_ParserFunctions[tflite::BuiltinOperator_MEAN] = &TfLiteParserImpl::ParseMean;
738 m_ParserFunctions[tflite::BuiltinOperator_MINIMUM] = &TfLiteParserImpl::ParseMinimum;
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +0100739 m_ParserFunctions[tflite::BuiltinOperator_MIRROR_PAD] = &TfLiteParserImpl::ParseMirrorPad;
Kevin May7d96b162021-02-03 17:38:41 +0000740 m_ParserFunctions[tflite::BuiltinOperator_MUL] = &TfLiteParserImpl::ParseMul;
741 m_ParserFunctions[tflite::BuiltinOperator_NEG] = &TfLiteParserImpl::ParseNeg;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300742 m_ParserFunctions[tflite::BuiltinOperator_NOT_EQUAL] = &TfLiteParserImpl::ParseNotEqual;
Kevin May7d96b162021-02-03 17:38:41 +0000743 m_ParserFunctions[tflite::BuiltinOperator_PACK] = &TfLiteParserImpl::ParsePack;
744 m_ParserFunctions[tflite::BuiltinOperator_PAD] = &TfLiteParserImpl::ParsePad;
Mike Kelly0d77ae12022-01-07 17:42:27 +0000745 m_ParserFunctions[tflite::BuiltinOperator_PADV2] = &TfLiteParserImpl::ParsePad;
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +0100746 m_ParserFunctions[tflite::BuiltinOperator_PRELU] = &TfLiteParserImpl::ParsePrelu;
Kevin May7d96b162021-02-03 17:38:41 +0000747 m_ParserFunctions[tflite::BuiltinOperator_QUANTIZE] = &TfLiteParserImpl::ParseQuantize;
748 m_ParserFunctions[tflite::BuiltinOperator_RELU] = &TfLiteParserImpl::ParseRelu;
749 m_ParserFunctions[tflite::BuiltinOperator_RELU6] = &TfLiteParserImpl::ParseRelu6;
Sadik Armagana2747482021-02-09 10:28:54 +0000750 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MAX] = &TfLiteParserImpl::ParseReduceMax;
751 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MIN] = &TfLiteParserImpl::ParseReduceMin;
Teresa Charlin4e3e8312021-08-05 12:34:37 +0100752 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_PROD] = &TfLiteParserImpl::ParseReduceProd;
Kevin May7d96b162021-02-03 17:38:41 +0000753 m_ParserFunctions[tflite::BuiltinOperator_RESHAPE] = &TfLiteParserImpl::ParseReshape;
754 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_BILINEAR] = &TfLiteParserImpl::ParseResizeBilinear;
755 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_NEAREST_NEIGHBOR] = &TfLiteParserImpl::ParseResizeNearestNeighbor;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100756 m_ParserFunctions[tflite::BuiltinOperator_RSQRT] = &TfLiteParserImpl::ParseRsqrt;
Teresa Charlinf0fce5b2022-05-04 17:24:43 +0100757 m_ParserFunctions[tflite::BuiltinOperator_SQRT] = &TfLiteParserImpl::ParseSqrt;
Keith Davis0176fd82021-06-01 17:36:32 +0100758 m_ParserFunctions[tflite::BuiltinOperator_SHAPE] = &TfLiteParserImpl::ParseShape;
Teresa Charlin28aa6692022-07-12 11:18:44 +0100759 m_ParserFunctions[tflite::BuiltinOperator_SIN] = &TfLiteParserImpl::ParseSin;
Kevin May7d96b162021-02-03 17:38:41 +0000760 m_ParserFunctions[tflite::BuiltinOperator_SLICE] = &TfLiteParserImpl::ParseSlice;
761 m_ParserFunctions[tflite::BuiltinOperator_SOFTMAX] = &TfLiteParserImpl::ParseSoftmax;
762 m_ParserFunctions[tflite::BuiltinOperator_SPACE_TO_BATCH_ND] = &TfLiteParserImpl::ParseSpaceToBatchND;
763 m_ParserFunctions[tflite::BuiltinOperator_SPLIT] = &TfLiteParserImpl::ParseSplit;
764 m_ParserFunctions[tflite::BuiltinOperator_SPLIT_V] = &TfLiteParserImpl::ParseSplitV;
765 m_ParserFunctions[tflite::BuiltinOperator_SQUEEZE] = &TfLiteParserImpl::ParseSqueeze;
766 m_ParserFunctions[tflite::BuiltinOperator_STRIDED_SLICE] = &TfLiteParserImpl::ParseStridedSlice;
767 m_ParserFunctions[tflite::BuiltinOperator_SUB] = &TfLiteParserImpl::ParseSub;
768 m_ParserFunctions[tflite::BuiltinOperator_SUM] = &TfLiteParserImpl::ParseSum;
769 m_ParserFunctions[tflite::BuiltinOperator_TANH] = &TfLiteParserImpl::ParseTanH;
770 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE] = &TfLiteParserImpl::ParseTranspose;
771 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE_CONV] = &TfLiteParserImpl::ParseTransposeConv;
Mike Kelly5880b912022-01-28 16:18:54 +0000772 m_ParserFunctions[tflite::BuiltinOperator_UNIDIRECTIONAL_SEQUENCE_LSTM]
773 = &TfLiteParserImpl::ParseUnidirectionalSequenceLSTM;
Kevin May7d96b162021-02-03 17:38:41 +0000774 m_ParserFunctions[tflite::BuiltinOperator_UNPACK] = &TfLiteParserImpl::ParseUnpack;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100775
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100776 // register supported custom operators
Kevin May7d96b162021-02-03 17:38:41 +0000777 m_CustomParserFunctions["TFLite_Detection_PostProcess"] = &TfLiteParserImpl::ParseDetectionPostProcess;
telsoa01c577f2c2018-08-31 09:22:23 +0100778}
779
Kevin May7d96b162021-02-03 17:38:41 +0000780void TfLiteParserImpl::ResetParser()
telsoa01c577f2c2018-08-31 09:22:23 +0100781{
782 m_Network = armnn::INetworkPtr(nullptr, nullptr);
783 m_Model = nullptr;
784 m_SubgraphConnections.clear();
Mike Kelly5880b912022-01-28 16:18:54 +0000785 m_OverridenOutputShapes.clear();
786 m_ConstantsToDequantize.clear();
787 m_ConstantsToBeCreated.clear();
telsoa01c577f2c2018-08-31 09:22:23 +0100788}
789
Kevin May7d96b162021-02-03 17:38:41 +0000790INetworkPtr TfLiteParserImpl::CreateNetworkFromBinaryFile(const char* graphFile)
telsoa01c577f2c2018-08-31 09:22:23 +0100791{
792 ResetParser();
793 m_Model = LoadModelFromFile(graphFile);
794 return CreateNetworkFromModel();
795}
796
Mike Kelly0d77ae12022-01-07 17:42:27 +0000797INetworkPtr TfLiteParserImpl::CreateNetworkFromBinary(const std::vector<uint8_t>& binaryContent)
telsoa01c577f2c2018-08-31 09:22:23 +0100798{
799 ResetParser();
800 m_Model = LoadModelFromBinary(binaryContent.data(), binaryContent.size());
801 return CreateNetworkFromModel();
802}
803
Finn Williamsb49ed182021-06-29 15:50:08 +0100804
805armnn::INetworkPtr TfLiteParserImpl::LoadModel(std::unique_ptr<tflite::ModelT> model)
806{
807 ResetParser();
808 m_Model = std::move(model);
809
810 return CreateNetworkFromModel();
811}
812
Kevin May7d96b162021-02-03 17:38:41 +0000813INetworkPtr TfLiteParserImpl::CreateNetworkFromModel()
telsoa01c577f2c2018-08-31 09:22:23 +0100814{
Sadik Armagand109a4d2020-07-28 10:42:13 +0100815
816 using NetworkOptions = std::vector<BackendOptions>;
817 NetworkOptions networkOptions = {};
Mike Kelly80512b02022-05-16 23:10:42 +0100818 if (m_Options)
Sadik Armagand109a4d2020-07-28 10:42:13 +0100819 {
Mike Kelly80512b02022-05-16 23:10:42 +0100820 if (m_Options.value().m_InferAndValidate)
821 {
822 BackendOptions shapeInferenceMethodOption("ShapeInferenceMethod",
823 {
824 { "InferAndValidate", true }
825 });
Sadik Armagand109a4d2020-07-28 10:42:13 +0100826
Mike Kelly80512b02022-05-16 23:10:42 +0100827 networkOptions.push_back(shapeInferenceMethodOption);
828 }
829 if (m_Options.value().m_AllowExpandedDims)
830 {
831 BackendOptions shapeInferenceMethodOption("AllowExpandedDims",
832 {
833 { "AllowExpandedDims", true }
834 });
835
836 networkOptions.push_back(shapeInferenceMethodOption);
837 }
Sadik Armagand109a4d2020-07-28 10:42:13 +0100838 }
Sadik Armagand109a4d2020-07-28 10:42:13 +0100839 m_Network = INetwork::Create(networkOptions);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100840 ARMNN_ASSERT(m_Model.get() != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +0100841
telsoa01c577f2c2018-08-31 09:22:23 +0100842 if (m_Model->subgraphs.size() != 1)
843 {
844 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100845 fmt::format("Current TfLite parser only supports 1 subgraph. Current one has: {} {}",
846 m_Model->subgraphs.size(),
847 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100848 }
849
850 size_t subgraphIndex = 0;
Colm Donelan6350d272020-06-09 16:56:25 +0100851 size_t operatorIndex = 0;
852 try
telsoa01c577f2c2018-08-31 09:22:23 +0100853 {
Colm Donelan6350d272020-06-09 16:56:25 +0100854 for (SubgraphPtr const& subgraph : m_Model->subgraphs)
telsoa01c577f2c2018-08-31 09:22:23 +0100855 {
Colm Donelan6350d272020-06-09 16:56:25 +0100856 m_SubgraphConnections.emplace_back(subgraph->tensors.size());
857 for (OperatorPtr const& op : subgraph->operators)
telsoa01c577f2c2018-08-31 09:22:23 +0100858 {
Colm Donelan6350d272020-06-09 16:56:25 +0100859 auto const& opCodePtr = m_Model->operator_codes[op->opcode_index];
Jim Flynnfca233e2021-09-23 12:16:53 +0100860
861// 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 +0100862#if defined(ARMNN_POST_TFLITE_2_3)
Jim Flynnfca233e2021-09-23 12:16:53 +0100863 auto builtinCode = std::max(opCodePtr->builtin_code,
864 static_cast<tflite::BuiltinOperator>(opCodePtr->deprecated_builtin_code));
865#else
telsoa01c577f2c2018-08-31 09:22:23 +0100866 auto builtinCode = opCodePtr->builtin_code;
Jim Flynnfca233e2021-09-23 12:16:53 +0100867#endif
telsoa01c577f2c2018-08-31 09:22:23 +0100868
869 if (builtinCode > tflite::BuiltinOperator_MAX)
870 {
James Ward58dec6b2020-09-11 17:32:44 +0100871 throw ParseException(fmt::format("Operator code {} is out of range 0-{}. "
872 "subgraph:{} operator idx:{}. {}",
873 builtinCode, tflite::BuiltinOperator_MAX, subgraphIndex,
874 operatorIndex, CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100875 }
876
877 // lookup and call the parser function
Colm Donelan6350d272020-06-09 16:56:25 +0100878 auto& parserFunction = m_ParserFunctions[builtinCode];
telsoa01c577f2c2018-08-31 09:22:23 +0100879 (this->*parserFunction)(subgraphIndex, operatorIndex);
Colm Donelan6350d272020-06-09 16:56:25 +0100880 ++operatorIndex;
telsoa01c577f2c2018-08-31 09:22:23 +0100881 }
telsoa01c577f2c2018-08-31 09:22:23 +0100882
Colm Donelan6350d272020-06-09 16:56:25 +0100883 SetupInputLayers(subgraphIndex);
884 SetupOutputLayers(subgraphIndex);
885 SetupConstantLayers(subgraphIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100886
Colm Donelan6350d272020-06-09 16:56:25 +0100887 ++subgraphIndex;
888 operatorIndex = 0;
telsoa01c577f2c2018-08-31 09:22:23 +0100889 }
telsoa01c577f2c2018-08-31 09:22:23 +0100890 }
Colm Donelan6350d272020-06-09 16:56:25 +0100891 catch (const ParseException& e)
telsoa01c577f2c2018-08-31 09:22:23 +0100892 {
Colm Donelan6350d272020-06-09 16:56:25 +0100893 std::stringstream errorString;
894 errorString << "Failed to parse operator #" << operatorIndex << " within subgraph #"
895 << subgraphIndex << " error: " << e.what();
896 ARMNN_LOG(error) << errorString.str();
897 std::stringstream errors;
898 errors << errorString.str() << "\n";
telsoa01c577f2c2018-08-31 09:22:23 +0100899 throw ParseException(errors.str());
900 }
901
902 // establish the connections from the layer outputs to the inputs of the subsequent layers
Colm Donelan6350d272020-06-09 16:56:25 +0100903 for (subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100904 {
905 for (size_t tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
906 {
907 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot != nullptr)
908 {
909 for (size_t inputSlotIdx = 0;
910 inputSlotIdx < m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size();
911 ++inputSlotIdx)
912 {
913 m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot->Connect(
914 *(m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots[inputSlotIdx]));
915 }
916 }
917 }
918 }
telsoa01c577f2c2018-08-31 09:22:23 +0100919 return std::move(m_Network);
920}
921
Mike Kelly0506ef02023-01-03 16:29:44 +0000922bool TfLiteParserImpl::ShouldConstantTensorBeConverted(TfLiteParserImpl::TensorRawPtr tensorPtr,
923 armnn::DataType inputDataType,
924 armnn::DataType tensorDataType)
Mike Kelly5880b912022-01-28 16:18:54 +0000925{
Mike Kelly0506ef02023-01-03 16:29:44 +0000926 return (TfLiteParserImpl::IsConstTensor(tensorPtr) && inputDataType == DataType::Float32 &&
927 (tensorDataType == DataType::QAsymmU8 ||
928 tensorDataType == DataType::QAsymmS8 ||
929 tensorDataType == DataType::QSymmS8 ||
930 tensorDataType == DataType::Signed32 ||
931 tensorDataType == DataType::Signed64));
Mike Kelly5880b912022-01-28 16:18:54 +0000932}
933
Kevin May7d96b162021-02-03 17:38:41 +0000934void TfLiteParserImpl::RegisterProducerOfTensor(size_t subgraphIndex,
935 size_t tensorIndex,
936 armnn::IOutputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +0100937{
938 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100939 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
940 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100941
942 TensorSlots & tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
943
Nikhil Rajd4d1c312022-08-03 18:20:59 +0100944 if (slot->GetOwningIConnectableLayer().GetType() != LayerType::Constant)
telsoa01c577f2c2018-08-31 09:22:23 +0100945 {
telsoa01c577f2c2018-08-31 09:22:23 +0100946
Nikhil Rajd4d1c312022-08-03 18:20:59 +0100947 // assuming there is only one producer for that tensor
948 if (tensorSlots.outputSlot != nullptr)
949 {
950 throw ParseException(fmt::format("Another layer has already registered itself as the producer of "
951 "subgraph:{} tensor:{} {}",
952 subgraphIndex,
953 tensorIndex,
954 CHECK_LOCATION().AsString()));
955 }
956 }
telsoa01c577f2c2018-08-31 09:22:23 +0100957 tensorSlots.outputSlot = slot;
958}
959
Kevin May7d96b162021-02-03 17:38:41 +0000960void TfLiteParserImpl::RegisterConsumerOfTensor(size_t subgraphIndex,
961 size_t tensorIndex,
962 armnn::IInputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +0100963{
964 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100965 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
966 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100967
Finn Williamsd4fa5452021-03-01 12:31:41 +0000968 TensorSlots& tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +0100969 tensorSlots.inputSlots.push_back(slot);
970}
971
Kevin May7d96b162021-02-03 17:38:41 +0000972void TfLiteParserImpl::ParseCustomOperator(size_t subgraphIndex, size_t operatorIndex)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100973{
974 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
975
976 // NOTE: By default we presume the custom operator is not supported
Kevin May7d96b162021-02-03 17:38:41 +0000977 auto customParserFunction = &TfLiteParserImpl::ParseUnsupportedOperator;
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100978
979 // Identify custom code defined for custom operator
980 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
981 const auto& customCode = m_Model->operator_codes[operatorPtr->opcode_index]->custom_code;
982
983 // Find parser function that correspondes to custom code (if any)
984 auto iterator = m_CustomParserFunctions.find(customCode);
985 if (iterator != m_CustomParserFunctions.end())
986 {
987 customParserFunction = iterator->second;
988 }
989
990 // Run parser function
991 (this->*customParserFunction)(subgraphIndex, operatorIndex);
992}
993
Kevin May7d96b162021-02-03 17:38:41 +0000994void TfLiteParserImpl::ParseUnsupportedOperator(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100995{
996 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100997
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100998 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
999
1000 auto opcodeIndex = operatorPtr->opcode_index;
Jim Flynnfca233e2021-09-23 12:16:53 +01001001
1002// 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 +01001003#if defined(ARMNN_POST_TFLITE_2_3)
Jim Flynnfca233e2021-09-23 12:16:53 +01001004 auto opcode = std::max(m_Model->operator_codes[opcodeIndex]->builtin_code,
1005 static_cast<tflite::BuiltinOperator>(m_Model->operator_codes[opcodeIndex]->deprecated_builtin_code));
1006#else
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001007 auto opcode = m_Model->operator_codes[opcodeIndex]->builtin_code;
Jim Flynnfca233e2021-09-23 12:16:53 +01001008#endif
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001009
1010 if (!m_Options || !m_Options.value().m_StandInLayerForUnsupported)
1011 {
1012 // Do not add StandInLayer, throw ParseException instead
1013 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01001014 fmt::format("Operator not supported. "
1015 "subgraph:{} operator:{} "
1016 "opcode_index:{} opcode:{} / {} {}",
1017 subgraphIndex,
1018 operatorIndex,
1019 opcodeIndex,
1020 opcode,
1021 tflite::EnumNameBuiltinOperator(opcode),
1022 CHECK_LOCATION().AsString()));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001023 }
1024
1025 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1026 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1027
Matthew Sloyan589e3e82020-09-11 16:17:48 +01001028 const unsigned int numInputs = armnn::numeric_cast<unsigned int>(inputs.size());
1029 const unsigned int numOutputs = armnn::numeric_cast<unsigned int>(outputs.size());
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001030
1031 StandInDescriptor descriptor(numInputs, numOutputs);
James Ward58dec6b2020-09-11 17:32:44 +01001032 auto layerName = fmt::format("StandIn:{}:{}:{}", subgraphIndex, operatorIndex, opcode);
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001033
1034 // Add a non-executable StandInLayer as a placeholder for any unsupported operator
1035 IConnectableLayer* layer = m_Network->AddStandInLayer(descriptor, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001036 ARMNN_ASSERT(layer != nullptr);
1037
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001038 for (unsigned int i = 0u; i < numOutputs; ++i)
1039 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01001040 layer->GetOutputSlot(i).SetTensorInfo(ToTensorInfo(outputs[i], true));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001041 }
1042
1043 auto inputTensorIds = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1044 auto outputTensorIds = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1045
1046 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIds);
1047 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIds);
telsoa01c577f2c2018-08-31 09:22:23 +01001048}
1049
mathad01b392e982021-04-07 12:07:30 +01001050void TfLiteParserImpl::ParseCast(size_t subgraphIndex, size_t operatorIndex)
1051{
1052 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1053
1054 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1055 CHECK_VALID_SIZE(inputs.size(), 1);
1056 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1057 CHECK_VALID_SIZE(outputs.size(), 1);
1058
1059 auto layerName = fmt::format("Cast:{}:{}", subgraphIndex, operatorIndex);
1060
1061 IConnectableLayer* layer = m_Network->AddCastLayer(layerName.c_str());
1062 ARMNN_ASSERT(layer != nullptr);
1063
1064 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1065 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1066
1067 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1068 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1069
1070 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1071 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1072}
1073
Kevin May7d96b162021-02-03 17:38:41 +00001074void TfLiteParserImpl::ParseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001075{
1076 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1077
Mike Kelly0d77ae12022-01-07 17:42:27 +00001078 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1079 const auto* options = operatorPtr->builtin_options.AsConv2DOptions();
telsoa01c577f2c2018-08-31 09:22:23 +01001080
1081 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1082
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001083 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1084 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1085 CHECK_VALID_SIZE(outputs.size(), 1);
1086
telsoa01c577f2c2018-08-31 09:22:23 +01001087 Convolution2dDescriptor desc;
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001088 inputs.size() == 3 ?
1089 desc.m_BiasEnabled = true : desc.m_BiasEnabled = false;
telsoa01c577f2c2018-08-31 09:22:23 +01001090 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1091 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +00001092 desc.m_DataLayout = armnn::DataLayout::NHWC;
Pablo Tellof0bd6832019-04-26 17:58:13 +01001093 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1094 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +00001095
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001096 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
telsoa01c577f2c2018-08-31 09:22:23 +01001097 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
1098
1099 // assuming input is NHWC
1100 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001101 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
telsoa01c577f2c2018-08-31 09:22:23 +01001102
1103 // assuming the filter is OHWI : Output, H, W, Input
1104 // which is essentially the same as NHWC
1105 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001106 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
telsoa01c577f2c2018-08-31 09:22:23 +01001107
Pablo Tellof0bd6832019-04-26 17:58:13 +01001108 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1109 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1110 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1111 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +01001112
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001113 // Add the first input and weights tensor to the registration list.
1114 // The constant weights will be added by SetupConstantLayers.
1115 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1116 std::vector<unsigned int> tensorIndexesToRegister = { inputTensorIndexes[0], inputTensorIndexes[1] };
telsoa01c577f2c2018-08-31 09:22:23 +01001117
James Ward58dec6b2020-09-11 17:32:44 +01001118 auto layerName = fmt::format("Conv2D:{}:{}", subgraphIndex, operatorIndex);
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001119 armnn::IConnectableLayer* layer = m_Network->AddConvolution2dLayer(desc, layerName.c_str());
telsoa01c577f2c2018-08-31 09:22:23 +01001120
Mike Kelly0506ef02023-01-03 16:29:44 +00001121 if (ShouldConstantTensorBeConverted(inputs[1], inputTensorInfo.GetDataType(), filterTensorInfo.GetDataType()))
telsoa01c577f2c2018-08-31 09:22:23 +01001122 {
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001123 m_ConstantsToDequantize.emplace_back(inputs[1]->buffer);
telsoa01c577f2c2018-08-31 09:22:23 +01001124 }
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001125
1126 if (desc.m_BiasEnabled)
telsoa01c577f2c2018-08-31 09:22:23 +01001127 {
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001128 armnn::TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
1129
1130 // Add the biases input to the registration list, a constant layer will be added by SetupConstantLayers.
1131 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
1132
Mike Kelly0506ef02023-01-03 16:29:44 +00001133 if (ShouldConstantTensorBeConverted(inputs[2], inputTensorInfo.GetDataType(), biasTensorInfo.GetDataType()))
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001134 {
1135 m_ConstantsToDequantize.emplace_back(inputs[2]->buffer);
1136 }
telsoa01c577f2c2018-08-31 09:22:23 +01001137 }
1138
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001139 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01001140
Sadik Armagand109a4d2020-07-28 10:42:13 +01001141 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
jimfly01c25411c2018-11-14 17:47:22 +00001142 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001143
1144 // register the input connection slots for the layer, connections are made after all layers have been created
1145 // only the tensors for the inputs are relevant, exclude the const tensors
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001146 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
telsoa01c577f2c2018-08-31 09:22:23 +01001147
jimfly01c25411c2018-11-14 17:47:22 +00001148 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +01001149 // register the output connection slots for the layer, connections are made after all layers have been created
1150 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001151 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, { outputTensorIndexes[0] });
telsoa01c577f2c2018-08-31 09:22:23 +01001152}
1153
Matthew Sloyan4d217c02021-10-07 11:48:58 +01001154// Conv3D support was added in TF 2.5, so for backwards compatibility a hash define is needed.
Cathal Corbett80b4ef02022-05-25 11:21:11 +01001155#if defined(ARMNN_POST_TFLITE_2_4)
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001156void TfLiteParserImpl::ParseConv3D(size_t subgraphIndex, size_t operatorIndex)
1157{
1158 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1159
1160 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1161 const auto* options = operatorPtr->builtin_options.AsConv3DOptions();
1162
1163 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1164
1165 Convolution3dDescriptor desc;
1166 desc.m_BiasEnabled = false;
1167 desc.m_DataLayout = armnn::DataLayout::NDHWC;
1168 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1169 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1170 desc.m_StrideZ = CHECKED_NON_NEGATIVE(options->stride_d);
1171 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1172 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
1173 desc.m_DilationZ = CHECKED_NON_NEGATIVE(options->dilation_d_factor);
1174
1175 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1176 CHECK_VALID_SIZE(inputs.size(), 2, 3);
1177
1178 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1179 CHECK_VALID_SIZE(outputs.size(), 1);
1180
1181 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1182 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
1183
1184 // Assuming input is NDHWC
1185 unsigned int inputDepth = inputTensorInfo.GetShape()[1];
1186 unsigned int inputHeight = inputTensorInfo.GetShape()[2];
1187 unsigned int inputWidth = inputTensorInfo.GetShape()[3];
1188
1189 // Assuming the filter is DHWIO : Depth, Height, Width, OutputChannels, InputChannels
1190 unsigned int filterDepth = filterTensorInfo.GetShape()[0];
1191 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1192 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1193
1194 CalcPadding(inputDepth, filterDepth, desc.m_StrideZ,
Teresa Charlin502ab942022-03-23 17:23:07 +00001195 desc.m_DilationZ, desc.m_PadFront, desc.m_PadBack, options->padding);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001196 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1197 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1198 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1199 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
1200
Mike Kelly5880b912022-01-28 16:18:54 +00001201 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo, inputTensorInfo.GetDataType());
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001202
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001203 auto layerName = fmt::format("Conv3D:{}:{}", subgraphIndex, operatorIndex);
1204
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001205 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1206 // Add the first input and weights tensor to the registration list.
1207 // The constant weights will be added by SetupConstantLayers.
1208 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0], inputTensorIndexes[1]};
1209
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001210 if (inputs.size() == 3)
1211 {
1212 desc.m_BiasEnabled = true;
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001213
1214 // Add the biases input to the registration list, a constant layer will be added by SetupConstantLayers.
1215 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001216 }
1217
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001218 armnn::IConnectableLayer* layer = m_Network->AddConvolution3dLayer(desc, layerName.c_str());
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001219 ARMNN_ASSERT(layer != nullptr);
1220
1221 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1222 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1223
1224 // Register the input connection slots for the layer, connections are made after all layers have been created
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001225 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001226
1227 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1228 // Register the output connection slots for the layer, connections are made after all layers have been created
1229 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1230 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1231}
Matthew Sloyan4d217c02021-10-07 11:48:58 +01001232#endif
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001233
Kevin May7d96b162021-02-03 17:38:41 +00001234void TfLiteParserImpl::ParseDepthwiseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001235{
1236 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1237
Mike Kelly0d77ae12022-01-07 17:42:27 +00001238 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1239 const auto* options = operatorPtr->builtin_options.AsDepthwiseConv2DOptions();
telsoa01c577f2c2018-08-31 09:22:23 +01001240
1241 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1242
1243 DepthwiseConvolution2dDescriptor desc;
telsoa01c577f2c2018-08-31 09:22:23 +01001244 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1245 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +00001246 desc.m_DataLayout = armnn::DataLayout::NHWC;
Matthew Jacksond6a9dee2019-07-22 13:53:24 +01001247 CHECKED_NON_NEGATIVE(options->depth_multiplier);
telsoa01c577f2c2018-08-31 09:22:23 +01001248
1249 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1250 CHECK_VALID_SIZE(inputs.size(), 2, 3);
Cathal Corbett06902652022-04-14 17:55:11 +01001251 if (inputs.size() == 3)
1252 {
1253 desc.m_BiasEnabled = true;
1254 }
1255
telsoa01c577f2c2018-08-31 09:22:23 +01001256 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1257 CHECK_VALID_SIZE(outputs.size(), 1);
Pablo Tellof0bd6832019-04-26 17:58:13 +01001258 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1259 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +00001260
telsoa01c577f2c2018-08-31 09:22:23 +01001261 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Jan Eilers7612bd62021-04-06 17:29:03 +01001262 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
telsoa01c577f2c2018-08-31 09:22:23 +01001263
Matteo Martincigh747ef822018-12-18 09:26:39 +00001264 // Assuming input is NHWC
telsoa01c577f2c2018-08-31 09:22:23 +01001265 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1266 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
Matteo Martincigh747ef822018-12-18 09:26:39 +00001267
1268 // TensorflowLite weights come in the format [1, H, W, I * M]
telsoa01c577f2c2018-08-31 09:22:23 +01001269 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1270 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1271
Pablo Tellof0bd6832019-04-26 17:58:13 +01001272 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1273 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1274 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1275 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +01001276
Jan Eilers53ef7952021-06-02 12:01:25 +01001277 // 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 +01001278 auto layerName = fmt::format("DepthwiseConv2D:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001279
Cathal Corbett06902652022-04-14 17:55:11 +01001280 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1281 // Add the first input and weights tensor to the registration list.
1282 // The constant weights will be added by SetupConstantLayers.
1283 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0], inputTensorIndexes[1]};
1284
1285 armnn::IConnectableLayer* layer = m_Network->AddDepthwiseConvolution2dLayer(desc, layerName.c_str());
1286
1287 if (desc.m_BiasEnabled)
telsoa01c577f2c2018-08-31 09:22:23 +01001288 {
1289 desc.m_BiasEnabled = true;
1290 TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Cathal Corbett06902652022-04-14 17:55:11 +01001291
1292 // Add the biases input to the registration list, a constant layer will be added by SetupConstantLayers.
1293 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
telsoa01c577f2c2018-08-31 09:22:23 +01001294 }
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001295 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01001296
Sadik Armagand109a4d2020-07-28 10:42:13 +01001297 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
jimfly01c25411c2018-11-14 17:47:22 +00001298 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001299
1300 // register the input connection slots for the layer, connections are made after all layers have been created
1301 // only the tensors for the inputs are relevant, exclude the const tensors
Cathal Corbett06902652022-04-14 17:55:11 +01001302 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
telsoa01c577f2c2018-08-31 09:22:23 +01001303
jimfly01c25411c2018-11-14 17:47:22 +00001304 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +01001305 // register the output connection slots for the layer, connections are made after all layers have been created
1306 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1307 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1308}
1309
Kevin May7d96b162021-02-03 17:38:41 +00001310void TfLiteParserImpl::ParseDequantize(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsed66d142019-12-06 09:55:55 +00001311{
1312 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1313
1314 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1315 CHECK_VALID_SIZE(inputs.size(), 1);
1316
1317 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1318 CHECK_VALID_SIZE(outputs.size(), 1);
1319
James Ward58dec6b2020-09-11 17:32:44 +01001320 auto layerName = fmt::format("Dequantize:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsed66d142019-12-06 09:55:55 +00001321
1322 IConnectableLayer* layer = m_Network->AddDequantizeLayer(layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001323 ARMNN_ASSERT(layer != nullptr);
Finn Williamsed66d142019-12-06 09:55:55 +00001324
Sadik Armagand109a4d2020-07-28 10:42:13 +01001325 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Finn Williamsed66d142019-12-06 09:55:55 +00001326 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1327
1328 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1329 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1330
1331 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1332 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1333}
1334
Teresa Charlin3ab85482021-06-08 16:59:29 +01001335void TfLiteParserImpl::ParseExpandDims(size_t subgraphIndex, size_t operatorIndex)
1336{
1337 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1338
1339 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1340 CHECK_VALID_SIZE(inputs.size(), 2);
1341
1342 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1343 CHECK_VALID_SIZE(outputs.size(), 1);
1344
1345 auto layerName = fmt::format("ExpandDims:{}:{}", subgraphIndex, operatorIndex);
1346
1347 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1348 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1349
1350 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1351
1352 ReshapeDescriptor reshapeDesc;
Finn Williamsb49ed182021-06-29 15:50:08 +01001353
1354 if (outputTensorInfo.GetShape().AreAllDimensionsSpecified())
1355 {
1356 reshapeDesc.m_TargetShape = outputTensorInfo.GetShape();
1357 }
1358 else
1359 {
1360 int32_t axis = inputs[1]->shape[0];
1361
1362 int32_t inputDimSize = static_cast<int32_t>(inputTensorInfo.GetShape().GetNumDimensions());
1363
1364 if (axis > inputDimSize || axis < 0 - (inputDimSize + 1))
1365 {
1366 throw ParseException("axis must be in range [0 - (inputDimSize + 1), inputDimSize] inclusive");
1367 }
1368
1369 if(axis < 0)
1370 {
1371 axis = inputDimSize + axis + 1;
1372 }
1373
Rob Hughesd812a312021-08-06 13:10:53 +01001374 std::vector<unsigned int> shape(static_cast<unsigned int>(inputDimSize) + 1);
Finn Williamsb49ed182021-06-29 15:50:08 +01001375 unsigned int inputShapeIndex = 0;
1376 for (unsigned int i = 0; i < static_cast<unsigned int>(inputDimSize + 1); ++i)
1377 {
1378 if (i == static_cast<unsigned int>(axis))
1379 {
1380 shape[i] = 1;
1381 }
1382 else
1383 {
1384 shape[i] = inputTensorInfo.GetShape()[inputShapeIndex];
1385 ++inputShapeIndex;
1386 }
1387 }
1388
Rob Hughesd812a312021-08-06 13:10:53 +01001389 reshapeDesc.m_TargetShape = TensorShape(static_cast<unsigned int>(inputDimSize + 1), shape.data());
Finn Williamsb49ed182021-06-29 15:50:08 +01001390 }
Teresa Charlin3ab85482021-06-08 16:59:29 +01001391
1392 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
1393 ARMNN_ASSERT(layer != nullptr);
1394 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1395
1396 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1397 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1398
1399 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1400 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1401}
1402
Kevin May7d96b162021-02-03 17:38:41 +00001403void TfLiteParserImpl::ParseTranspose(size_t subgraphIndex, size_t operatorIndex)
Keith Davis4cd29a02019-09-09 14:49:20 +01001404{
1405 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1406
1407 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Kevin May85d92602019-09-27 17:21:06 +01001408 CHECK_VALID_SIZE(inputs.size(), 1, 2);
Keith Davis4cd29a02019-09-09 14:49:20 +01001409
1410 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1411 CHECK_VALID_SIZE(outputs.size(), 1);
1412
James Ward58dec6b2020-09-11 17:32:44 +01001413 auto layerName = fmt::format("Transpose:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly08759e22020-03-02 11:41:31 +00001414 TransposeDescriptor desc;
Keith Davis4cd29a02019-09-09 14:49:20 +01001415
josh minorba424d22019-11-13 10:55:17 -06001416 if (inputs.size() == 2)
Kevin May85d92602019-09-27 17:21:06 +01001417 {
1418 armnn::TensorInfo permuteTensorInfo = ToTensorInfo(inputs[1]);
1419 BufferRawPtr permuteBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
josh minorba424d22019-11-13 10:55:17 -06001420 auto numPermVecElements = permuteTensorInfo.GetNumElements();
1421 std::vector<unsigned int> permuteShape(numPermVecElements);
Kevin May85d92602019-09-27 17:21:06 +01001422 ::memcpy(permuteShape.data(), permuteBufferPtr->data.data(), permuteTensorInfo.GetNumBytes());
Mike Kelly08759e22020-03-02 11:41:31 +00001423 PermutationVector permutationVector(permuteShape.data(), permuteTensorInfo.GetNumElements());
Kevin May85d92602019-09-27 17:21:06 +01001424
Mike Kelly08759e22020-03-02 11:41:31 +00001425 desc = TransposeDescriptor(permutationVector);
Kevin May85d92602019-09-27 17:21:06 +01001426 }
1427
James Conroy05102392020-06-24 15:39:55 +01001428 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001429 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001430 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Keith Davis4cd29a02019-09-09 14:49:20 +01001431
James Conroy05102392020-06-24 15:39:55 +01001432 IConnectableLayer* layer = m_Network->AddTransposeLayer(desc, layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001433 ARMNN_ASSERT(layer != nullptr);
Keith Davis4cd29a02019-09-09 14:49:20 +01001434 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1435
1436 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1437 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1438
1439 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1440 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1441}
1442
Kevin May7d96b162021-02-03 17:38:41 +00001443void TfLiteParserImpl::ParseTransposeConv(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001444{
1445 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1446
Mike Kelly0d77ae12022-01-07 17:42:27 +00001447 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1448 const auto* options = operatorPtr->builtin_options.AsTransposeConvOptions();
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001449
1450 TransposeConvolution2dDescriptor desc;
1451 desc.m_BiasEnabled = false;
1452 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1453 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1454 desc.m_DataLayout = armnn::DataLayout::NHWC;
1455
1456 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
David Monahan61683802021-01-12 09:11:07 +00001457 if (inputs.size() == 4)
1458 {
1459 desc.m_BiasEnabled = true;
1460 }
1461 else
1462 {
1463 CHECK_VALID_SIZE(inputs.size(), 3);
1464 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001465
1466 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1467 CHECK_VALID_SIZE(outputs.size(), 1);
1468
Colm Donelan0ad3ef12020-07-03 15:54:28 +01001469 if (inputs[0])
1470 {
1471 armnn::TensorInfo tensorInfo = ToTensorInfo(inputs[0]);
1472 std::vector<int> output_shape(tensorInfo.GetNumElements());
1473 if (tensorInfo.GetDataType() == DataType::Signed32)
1474 {
1475 ::memcpy(output_shape.data(), GetBuffer(m_Model, inputs[0]->buffer)->data.data(), tensorInfo.GetNumBytes());
1476 }
1477 if (tensorInfo.GetDataType() == DataType::QAsymmU8)
1478 {
1479 for(unsigned int i=0; i < tensorInfo.GetNumElements(); i++)
1480 {
1481 output_shape[i] = GetBuffer(m_Model, inputs[0]->buffer)->data.data()[i];
1482 }
1483 }
1484 // Change from signed to unsigned int to store in TransposeConvolution2dDescriptor.
1485 for (int dimension : output_shape)
1486 {
1487 desc.m_OutputShape.push_back(static_cast<unsigned int>(dimension));
1488 }
1489 desc.m_OutputShapeEnabled = true;
1490 }
Matthew Jacksonccb25ea2019-08-20 17:18:33 +01001491 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[2]);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001492 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
1493
1494 // TfLite uses NHWC tensors
1495 const unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1496 const unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1497
1498 const unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1499 const unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1500
1501 CalcPadding(inputHeight,
1502 filterHeight,
1503 desc.m_StrideY,
1504 1, // DilationY
1505 desc.m_PadTop,
1506 desc.m_PadBottom,
1507 options->padding);
1508
1509 CalcPadding(inputWidth,
1510 filterWidth,
1511 desc.m_StrideX,
1512 1, // DilationX
1513 desc.m_PadLeft,
1514 desc.m_PadRight,
1515 options->padding);
1516
Mike Kelly5880b912022-01-28 16:18:54 +00001517 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo, inputTensorInfo.GetDataType());
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001518
1519 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01001520 auto layerName = fmt::format("TransposeConv:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001521
David Monahan61683802021-01-12 09:11:07 +00001522 if (desc.m_BiasEnabled)
1523 {
1524 auto biasTensorInfo = ToTensorInfo(inputs[3]);
Mike Kelly5880b912022-01-28 16:18:54 +00001525 auto biasConstTensor = CreateConstTensorNonPermuted(inputs[3], biasTensorInfo, inputTensorInfo.GetDataType());
David Monahan61683802021-01-12 09:11:07 +00001526 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Mike Kelly5880b912022-01-28 16:18:54 +00001527 filterTensorAndData.first,
1528 biasConstTensor.first,
David Monahan61683802021-01-12 09:11:07 +00001529 layerName.c_str());
1530 }
1531 else
1532 {
1533 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Mike Kelly5880b912022-01-28 16:18:54 +00001534 filterTensorAndData.first,
David Monahan61683802021-01-12 09:11:07 +00001535 EmptyOptional(),
1536 layerName.c_str());
1537 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001538
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001539 ARMNN_ASSERT(layer != nullptr);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001540
Sadik Armagand109a4d2020-07-28 10:42:13 +01001541 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001542 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1543
1544 // only the tensors for the inputs are relevant, exclude the const (filter) tensor
1545 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Matthew Jacksonccb25ea2019-08-20 17:18:33 +01001546 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[2]});
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001547
1548 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1549 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1550}
1551
Kevin May7d96b162021-02-03 17:38:41 +00001552void TfLiteParserImpl::ParseAveragePool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001553{
1554 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Average);
1555}
1556
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001557void TfLiteParserImpl::ParseBatchMatMul(size_t subgraphIndex, size_t operatorIndex)
1558{
1559 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1560
1561 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1562 CHECK_VALID_SIZE(inputs.size(), 2);
1563
1564 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1565 CHECK_VALID_SIZE(outputs.size(), 1);
1566
1567 auto layerName = fmt::format("BatchMatMul:{}:{}", subgraphIndex, operatorIndex);
1568
1569 TensorInfo inputXTensorInfo = ToTensorInfo(inputs[0]);
1570 TensorInfo inputYTensorInfo = ToTensorInfo(inputs[1]);
1571
1572 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1573
1574 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1575 const auto* options = operatorPtr->builtin_options.AsBatchMatMulOptions();
1576
Teresa Charlinbc37a6b2022-09-22 10:12:58 +01001577 // Adjoint in tensorflow lite performs transpose operation
1578 BatchMatMulDescriptor descriptor(options->adj_x,
1579 options->adj_y,
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001580 false,
Teresa Charlinbc37a6b2022-09-22 10:12:58 +01001581 false);
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001582 // Arbitrary DataLayout
1583
1584 IConnectableLayer* layer = m_Network->AddBatchMatMulLayer(descriptor, layerName.c_str());
1585 ARMNN_ASSERT(layer != nullptr);
1586
1587 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1588
1589 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1590 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
1591
1592 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1593 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1594}
1595
Kevin May7d96b162021-02-03 17:38:41 +00001596void TfLiteParserImpl::ParseBatchToSpaceND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001597{
1598 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1599
1600 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1601 CHECK_VALID_SIZE(inputs.size(), 3);
1602
1603 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1604 CHECK_VALID_SIZE(outputs.size(), 1);
1605
1606 armnn::TensorInfo blockShapeTensorInfo = ToTensorInfo(inputs[1]);
1607 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1608
1609 armnn::TensorInfo cropsTensorInfo = ToTensorInfo(inputs[2]);
1610 BufferRawPtr cropsBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1611
1612 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1613 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1614
1615 std::vector<unsigned int> cropsVector(cropsTensorInfo.GetNumElements());
1616 ::memcpy(cropsVector.data(), cropsBufferPtr->data.data(), cropsTensorInfo.GetNumBytes());
1617
1618 size_t step = 2;
1619 std::vector<std::pair<unsigned int, unsigned int>> crops;
1620 for (unsigned int i = 0; i < cropsTensorInfo.GetNumElements() / step; ++i)
1621 {
1622 crops.emplace_back(cropsVector[i * step], cropsVector[i * step + 1]);
1623 }
1624
1625 armnn::BatchToSpaceNdDescriptor desc;
1626 desc.m_BlockShape = blockShape;
1627 desc.m_Crops = crops;
1628 desc.m_DataLayout = armnn::DataLayout::NHWC;
1629
James Ward58dec6b2020-09-11 17:32:44 +01001630 auto layerName = fmt::format("BatchToSpaceND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001631
James Conroy05102392020-06-24 15:39:55 +01001632 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001633 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001634 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1635
1636 IConnectableLayer* layer = m_Network->AddBatchToSpaceNdLayer(desc, layerName.c_str());
1637 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001638 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1639
1640 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1641 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1642
1643 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1644 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1645}
1646
Kevin May7d96b162021-02-03 17:38:41 +00001647void TfLiteParserImpl::ParseL2Normalization(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson28c94572019-07-18 10:47:03 +01001648{
1649 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1650
1651 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1652 CHECK_VALID_SIZE(inputs.size(), 1);
1653
1654 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1655 CHECK_VALID_SIZE(outputs.size(), 1);
1656
1657 L2NormalizationDescriptor desc;
1658 desc.m_DataLayout = armnn::DataLayout::NHWC;
James Ward58dec6b2020-09-11 17:32:44 +01001659 auto layerName = fmt::format("L2Normalization:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson28c94572019-07-18 10:47:03 +01001660 IConnectableLayer* layer = m_Network->AddL2NormalizationLayer(desc, layerName.c_str());
1661
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001662 ARMNN_ASSERT(layer != nullptr);
Matthew Jackson28c94572019-07-18 10:47:03 +01001663
Sadik Armagand109a4d2020-07-28 10:42:13 +01001664 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jackson28c94572019-07-18 10:47:03 +01001665 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1666
1667 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1668 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1669
1670 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1671 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1672}
1673
Kevin May7d96b162021-02-03 17:38:41 +00001674void TfLiteParserImpl::ParseMaxPool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001675{
1676 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Max);
1677}
1678
Kevin May7d96b162021-02-03 17:38:41 +00001679void TfLiteParserImpl::ParseMaximum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001680{
1681 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1682
1683 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1684 CHECK_VALID_SIZE(inputs.size(), 2);
1685
1686 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1687 CHECK_VALID_SIZE(outputs.size(), 1);
1688
James Ward58dec6b2020-09-11 17:32:44 +01001689 auto layerName = fmt::format("Maximum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01001690
1691 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1692 TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1693 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001694
Sadik Armagand109a4d2020-07-28 10:42:13 +01001695 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001696 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1697
1698 IConnectableLayer* layer = m_Network->AddMaximumLayer(layerName.c_str());
1699 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001700 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1701
1702 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001703 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001704
1705 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1706 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1707}
1708
Kevin May7d96b162021-02-03 17:38:41 +00001709void TfLiteParserImpl::ParseMinimum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001710{
1711 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1712
1713 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1714 CHECK_VALID_SIZE(inputs.size(), 2);
1715
1716 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1717 CHECK_VALID_SIZE(outputs.size(), 1);
1718
James Ward58dec6b2020-09-11 17:32:44 +01001719 auto layerName = fmt::format("Minimum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01001720
1721 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1722 TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1723 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001724
Sadik Armagand109a4d2020-07-28 10:42:13 +01001725 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001726 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1727
1728 IConnectableLayer* layer = m_Network->AddMinimumLayer(layerName.c_str());
1729 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001730 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1731
1732 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001733 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001734
1735 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1736 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1737}
1738
Kevin May7d96b162021-02-03 17:38:41 +00001739void TfLiteParserImpl::ParsePool(size_t subgraphIndex,
1740 size_t operatorIndex,
1741 PoolingAlgorithm algorithm)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001742{
1743 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1744
Mike Kelly0d77ae12022-01-07 17:42:27 +00001745 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1746 const auto* options = operatorPtr->builtin_options.AsPool2DOptions();
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001747
1748 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1749
1750 std::string layerName;
1751
1752 switch (algorithm)
1753 {
1754 case PoolingAlgorithm::Average:
1755 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01001756 fmt::format("AveragePool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001757 break;
1758 case PoolingAlgorithm::Max:
1759 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01001760 fmt::format("MaxPool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001761 break;
1762 default:
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001763 ARMNN_ASSERT_MSG(false, "Unsupported Pooling Algorithm");
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001764 }
1765
1766 Pooling2dDescriptor desc;
1767
1768 desc.m_PoolType = algorithm;
1769 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1770 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1771 desc.m_PoolWidth = CHECKED_NON_NEGATIVE(options->filter_width);
1772 desc.m_PoolHeight = CHECKED_NON_NEGATIVE(options->filter_height);
1773 desc.m_PaddingMethod = PaddingMethod::Exclude;
1774 desc.m_OutputShapeRounding = OutputShapeRounding::Floor;
jimfly01c25411c2018-11-14 17:47:22 +00001775 desc.m_DataLayout = armnn::DataLayout::NHWC;
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001776
1777 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1778 CHECK_VALID_SIZE(inputs.size(), 1);
1779 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1780
1781 // assuming input is NHWC
1782 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1783 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1784
Pablo Tellof0bd6832019-04-26 17:58:13 +01001785 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, 1u,
1786 desc.m_PadTop, desc.m_PadBottom, options->padding);
1787 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, 1u,
1788 desc.m_PadLeft, desc.m_PadRight, options->padding);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001789
1790 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1791 CHECK_VALID_SIZE(outputs.size(), 1);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001792
Sadik Armagand109a4d2020-07-28 10:42:13 +01001793 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001794 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1795
1796 IConnectableLayer* layer = m_Network->AddPooling2dLayer(desc, layerName.c_str());
1797 ARMNN_ASSERT(layer != nullptr);
jimfly01c25411c2018-11-14 17:47:22 +00001798 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001799
1800 // register the input connection slots for the layer, connections are made after all layers have been created
1801 // only the tensors for the inputs are relevant, exclude the const tensors
1802 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +00001803 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001804
jimfly01c25411c2018-11-14 17:47:22 +00001805 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001806 // register the output connection slots for the layer, connections are made after all layers have been created
1807 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1808 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1809}
1810
Kevin May7d96b162021-02-03 17:38:41 +00001811void TfLiteParserImpl::ParseSlice(size_t subgraphIndex, size_t operatorIndex)
josh minorba424d22019-11-13 10:55:17 -06001812{
1813 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1814
1815 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1816 CHECK_VALID_SIZE(inputs.size(), 3);
1817 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1818 CHECK_VALID_SIZE(outputs.size(), 1);
1819
1820 SliceDescriptor desc;
1821
1822 // set begin tensor info for slice descriptor
1823 armnn::TensorInfo beginTensorInfo = ToTensorInfo(inputs[1]);
1824 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1825
1826 std::vector<unsigned int> begin(beginTensorInfo.GetNumElements());
1827 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
1828
1829 // set size tensor info for slice descriptor
1830 armnn::TensorInfo sizeTensorInfo = ToTensorInfo(inputs[2]);
1831 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1832
Cathal Corbettde33dda2022-09-20 16:40:09 +01001833 std::vector<int> signedSize(sizeTensorInfo.GetNumElements(), 1);
1834
1835 // if size buffer data is not specified, all contents of size vector remain as values of 1
1836 if (sizeBufferPtr->data.data())
1837 {
1838 ::memcpy(signedSize.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
1839 }
1840
josh minorba424d22019-11-13 10:55:17 -06001841 std::vector<unsigned int> size(sizeTensorInfo.GetNumElements());
Mike Kelly7ba84d62021-09-10 15:27:19 +01001842 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1843
1844 for (unsigned int i = 0; i < signedSize.size(); ++i)
1845 {
1846 int signedValue = signedSize[i];
Jim Flynnfca233e2021-09-23 12:16:53 +01001847
Mike Kelly7ba84d62021-09-10 15:27:19 +01001848 if (signedValue < -1 || signedValue > static_cast<int>(inputTensorInfo.GetShape()[i] - begin[i]))
1849 {
1850 throw ParseException(fmt::format("Invalid value for size {} size must be in range "
1851 "[-1, inputDimSize - begin] [-1, {}] inclusive {}",
1852 signedValue,
1853 inputTensorInfo.GetShape()[i] - begin[i],
1854 CHECK_LOCATION().AsString()));
1855 }
1856
1857 if (signedValue == -1)
1858 {
1859 size[i] = inputTensorInfo.GetShape()[i] - begin[i];
1860 }
1861 else
1862 {
1863 size[i] = static_cast<unsigned int>(signedValue);
1864 }
1865 }
1866
josh minorba424d22019-11-13 10:55:17 -06001867 desc = SliceDescriptor(begin, size);
1868
James Ward58dec6b2020-09-11 17:32:44 +01001869 auto layerName = fmt::format("Slice:{}:{}", subgraphIndex, operatorIndex);
josh minorba424d22019-11-13 10:55:17 -06001870
Sadik Armagand109a4d2020-07-28 10:42:13 +01001871 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001872 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1873
1874 IConnectableLayer* const layer = m_Network->AddSliceLayer(desc, layerName.c_str());
josh minorba424d22019-11-13 10:55:17 -06001875 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1876
1877 // register the input connection slots for the layer, connections are made after all layers have been created
1878 // only the tensors for the inputs are relevant, exclude the const tensors
1879 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1880 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1881
1882 // register the output connection slots for the layer, connections are made after all layers have been created
1883 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1884 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1885}
1886
Kevin May7d96b162021-02-03 17:38:41 +00001887void TfLiteParserImpl::ParseSoftmax(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001888{
1889 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00001890 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1891 const auto* options = operatorPtr->builtin_options.AsSoftmaxOptions();
telsoa01c577f2c2018-08-31 09:22:23 +01001892
1893 SoftmaxDescriptor desc;
1894 desc.m_Beta = options->beta;
1895
1896 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1897 CHECK_VALID_SIZE(inputs.size(), 1);
1898 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1899 CHECK_VALID_SIZE(outputs.size(), 1);
1900
James Ward58dec6b2020-09-11 17:32:44 +01001901 auto layerName = fmt::format("Softmax:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001902 IConnectableLayer* const layer = m_Network->AddSoftmaxLayer(desc, layerName.c_str());
1903
Sadik Armagand109a4d2020-07-28 10:42:13 +01001904 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
telsoa01c577f2c2018-08-31 09:22:23 +01001905 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1906
1907 // register the input connection slots for the layer, connections are made after all layers have been created
1908 // only the tensors for the inputs are relevant, exclude the const tensors
1909 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1910 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1911
1912 // register the output connection slots for the layer, connections are made after all layers have been created
1913 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1914 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1915}
1916
Teresa Charlinfd33a692022-06-29 15:35:57 +01001917void TfLiteParserImpl::ParseLogSoftmax(size_t subgraphIndex, size_t operatorIndex)
1918{
1919 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1920
1921 LogSoftmaxDescriptor desc;
1922
1923 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1924 CHECK_VALID_SIZE(inputs.size(), 1);
1925 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1926 CHECK_VALID_SIZE(outputs.size(), 1);
1927
1928 auto layerName = fmt::format("LogSoftmax:{}:{}", subgraphIndex, operatorIndex);
1929 IConnectableLayer* const layer = m_Network->AddLogSoftmaxLayer(desc, layerName.c_str());
1930
1931 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1932 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1933
1934 // register the input connection slots for the layer, connections are made after all layers have been created
1935 // only the tensors for the inputs are relevant, exclude the const tensors
1936 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1937 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1938
1939 // register the output connection slots for the layer, connections are made after all layers have been created
1940 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1941 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1942}
1943
Kevin May7d96b162021-02-03 17:38:41 +00001944void TfLiteParserImpl::ParseSpaceToBatchND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001945{
1946 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1947
1948 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1949 CHECK_VALID_SIZE(inputs.size(), 3);
1950
1951 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1952 CHECK_VALID_SIZE(outputs.size(), 1);
1953
1954 armnn::TensorInfo blockShapeTensorInfo = ToTensorInfo(inputs[1]);
1955 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1956
1957 armnn::TensorInfo padListTensorInfo = ToTensorInfo(inputs[2]);
1958 BufferRawPtr padListBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1959
1960 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1961 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1962
1963 std::vector<unsigned int> padListVector(padListTensorInfo.GetNumElements());
1964 ::memcpy(padListVector.data(), padListBufferPtr->data.data(), padListTensorInfo.GetNumBytes());
1965
1966 size_t step = 2;
1967 std::vector<std::pair<unsigned int, unsigned int>> padList;
1968 for (unsigned int i = 0; i < padListTensorInfo.GetNumElements() / step; ++i)
1969 {
1970 padList.emplace_back(padListVector[i * step], padListVector[i * step + 1]);
1971 }
1972
1973 armnn::SpaceToBatchNdDescriptor desc;
1974 desc.m_BlockShape = blockShape;
1975 desc.m_PadList = padList;
1976 desc.m_DataLayout = armnn::DataLayout::NHWC;
1977
James Ward58dec6b2020-09-11 17:32:44 +01001978 auto layerName = fmt::format("SpaceToBatchND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001979
James Conroy05102392020-06-24 15:39:55 +01001980 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001981 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001982 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1983
1984 IConnectableLayer* layer = m_Network->AddSpaceToBatchNdLayer(desc, layerName.c_str());
1985 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001986 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1987
1988 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1989 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1990
1991 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1992 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1993}
1994
Teresa Charlin3ab85482021-06-08 16:59:29 +01001995armnn::TensorInfo TfLiteParserImpl::OutputShapeOfSqueeze(std::vector<uint32_t> squeezeDims,
Mike Kelly0d77ae12022-01-07 17:42:27 +00001996 const armnn::TensorInfo& inputTensorInfo)
telsoa01c577f2c2018-08-31 09:22:23 +01001997{
Teresa Charlin3ab85482021-06-08 16:59:29 +01001998 CHECK_VALID_SIZE(squeezeDims.size(), 0, 1, 2, 3, 4);
telsoa01c577f2c2018-08-31 09:22:23 +01001999 static const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
2000
2001 if (inputTensorInfo.GetNumDimensions() > 4)
2002 {
2003 std::stringstream ss;
2004 ss << "Input tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
2005 << " shape:" << inputTensorInfo.GetShape() << " "
2006 << CHECK_LOCATION().AsString();
2007 throw ParseException(ss.str());
2008 }
2009
2010 if (squeezeDims.empty())
2011 {
2012 squeezeDims.assign(dimensionSequence,
2013 dimensionSequence+inputTensorInfo.GetNumDimensions());
2014 }
2015
2016 std::vector<uint32_t> outputDims;
2017 for(unsigned int i = 0; i < inputTensorInfo.GetNumDimensions(); i++)
2018 {
2019 bool skipSqueeze = (std::find(squeezeDims.begin(), squeezeDims.end(), i) == squeezeDims.end());
2020 auto currentDimension = inputTensorInfo.GetShape()[i];
2021 if (skipSqueeze || currentDimension != 1)
2022 {
2023 outputDims.push_back(currentDimension);
2024 }
2025 }
2026
2027 if (outputDims.size() > 4)
2028 {
2029 std::stringstream ss;
2030 ss << "Output tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
2031 << " shape:" << inputTensorInfo.GetShape() << " "
2032 << CHECK_LOCATION().AsString();
2033 throw ParseException(ss.str());
2034 }
2035
2036 TensorShape outShape = TensorShape(static_cast<unsigned int>(outputDims.size()),
2037 outputDims.data());
2038
2039 // we need to preserve the tensor type and the quantization data as well
2040 TensorInfo outTensorInfo = inputTensorInfo;
2041 outTensorInfo.SetShape(outShape);
2042
2043 return outTensorInfo;
2044}
2045
Keith Davis0176fd82021-06-01 17:36:32 +01002046void TfLiteParserImpl::ParseShape(size_t subgraphIndex, size_t operatorIndex)
2047{
2048 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2049
2050 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2051 CHECK_VALID_SIZE(inputs.size(), 1);
2052 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2053 CHECK_VALID_SIZE(outputs.size(), 1);
2054
2055 auto layerName = fmt::format("Shape:{}:{}", subgraphIndex, operatorIndex);
2056
2057 IConnectableLayer* layer = m_Network->AddShapeLayer(layerName.c_str());
2058 ARMNN_ASSERT(layer != nullptr);
2059
2060
2061 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
2062 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2063
2064 // Check if output tensor type is Signed32 or Signed64
2065 if (outputTensorInfo.GetDataType() != armnn::DataType::Signed32 &&
2066 outputTensorInfo.GetDataType() != armnn::DataType::Signed64)
2067 {
2068 throw ParseException(
2069 fmt::format(
2070 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
2071 CHECK_LOCATION().AsString()));
2072 }
2073
2074 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2075 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2076
2077 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2078 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2079}
2080
Kevin May7d96b162021-02-03 17:38:41 +00002081void TfLiteParserImpl::ParseSqueeze(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01002082{
2083 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2084
2085 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2086 CHECK_VALID_SIZE(inputs.size(), 1);
2087
2088 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2089 CHECK_VALID_SIZE(outputs.size(), 1);
2090
2091 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2092 const auto * options = operatorPtr->builtin_options.AsSqueezeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01002093 auto layerName = fmt::format("Squeeze:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01002094
2095 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Teresa Charlin3ab85482021-06-08 16:59:29 +01002096
2097 std::vector<uint32_t> squeezeDim;
2098 // A single negative dim index is interpreted as a negative index in python
2099 // Meaning the index will be the shape size plus the negative index value
2100 if (options->squeeze_dims.size() == 1 && options->squeeze_dims[0] < 0)
2101 {
2102 int32_t dim = static_cast<int32_t>(inputTensorInfo.GetShape().GetNumDimensions()) + options->squeeze_dims[0];
2103 squeezeDim.push_back(static_cast<uint32_t>(dim));
2104 }
2105 else
2106 {
2107 squeezeDim = AsUnsignedVector(options->squeeze_dims);
2108 }
2109
2110 armnn::TensorInfo outputTensorInfo = TfLiteParserImpl::OutputShapeOfSqueeze(squeezeDim, inputTensorInfo);
2111
James Conroy05102392020-06-24 15:39:55 +01002112 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
telsoa01c577f2c2018-08-31 09:22:23 +01002113
2114 ReshapeDescriptor reshapeDesc;
2115 reshapeDesc.m_TargetShape = outputTensorInfo.GetShape();
2116
telsoa01c577f2c2018-08-31 09:22:23 +01002117 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002118 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01002119 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2120
2121 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2122 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2123
2124 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2125 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2126}
2127
Kevin May7d96b162021-02-03 17:38:41 +00002128void TfLiteParserImpl::ParseStridedSlice(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002129{
2130 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2131
2132 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2133 CHECK_VALID_SIZE(inputs.size(), 4);
2134
2135 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2136 CHECK_VALID_SIZE(outputs.size(), 1);
2137
Mike Kelly0d77ae12022-01-07 17:42:27 +00002138 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2139 const auto* options = operatorPtr->builtin_options.AsStridedSliceOptions();
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002140
2141 StridedSliceDescriptor desc;
2142 desc.m_BeginMask = options->begin_mask;
2143 desc.m_EllipsisMask = options->ellipsis_mask;
2144 desc.m_EndMask = options->end_mask;
2145 desc.m_NewAxisMask = options->new_axis_mask;
2146 desc.m_ShrinkAxisMask = options->shrink_axis_mask;
2147 desc.m_DataLayout = armnn::DataLayout::NHWC;
2148
2149 armnn::TensorInfo beginTensorInfo = ToTensorInfo(inputs[1]);
2150 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2151
2152 std::vector<int> begin(beginTensorInfo.GetNumElements());
2153 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
2154
2155 armnn::TensorInfo endTensorInfo = ToTensorInfo(inputs[2]);
2156 BufferRawPtr endBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
2157
2158 std::vector<int> end(endTensorInfo.GetNumElements());
2159 ::memcpy(end.data(), endBufferPtr->data.data(), endTensorInfo.GetNumBytes());
2160
2161 armnn::TensorInfo strideTensorInfo = ToTensorInfo(inputs[3]);
2162 BufferRawPtr strideBufferPtr = GetBuffer(m_Model, inputs[3]->buffer);
2163
2164 std::vector<int> stride(strideTensorInfo.GetNumElements());
2165 ::memcpy(stride.data(), strideBufferPtr->data.data(), strideTensorInfo.GetNumBytes());
2166
2167 desc.m_Begin = begin;
2168 desc.m_End = end;
2169 desc.m_Stride = stride;
2170
James Ward58dec6b2020-09-11 17:32:44 +01002171 auto layerName = fmt::format("StridedSlice:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002172 IConnectableLayer* layer = m_Network->AddStridedSliceLayer(desc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002173 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002174
Sadik Armagand109a4d2020-07-28 10:42:13 +01002175 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002176 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2177
2178 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2179 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2180
2181 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2182 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2183}
2184
Kevin May7d96b162021-02-03 17:38:41 +00002185void TfLiteParserImpl::ParseSub(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002186{
2187 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2188
Mike Kelly0d77ae12022-01-07 17:42:27 +00002189 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2190 const auto* options = operatorPtr->builtin_options.AsSubOptions();
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002191
2192 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2193 CHECK_VALID_SIZE(inputs.size(), 2);
2194
2195 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2196 CHECK_VALID_SIZE(outputs.size(), 1);
2197
2198 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2199 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2200
James Ward58dec6b2020-09-11 17:32:44 +01002201 auto layerName = fmt::format("Sub:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002202 IConnectableLayer* layer = m_Network->AddSubtractionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002203 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002204
Sadik Armagand109a4d2020-07-28 10:42:13 +01002205 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002206 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2207
2208 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002209 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002210
2211 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2212
2213 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2214 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2215}
2216
Kevin May7d96b162021-02-03 17:38:41 +00002217void TfLiteParserImpl::ParseDiv(size_t subgraphIndex, size_t operatorIndex)
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302218{
2219 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2220
Mike Kelly0d77ae12022-01-07 17:42:27 +00002221 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2222 const auto* options = operatorPtr->builtin_options.AsDivOptions();
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302223
2224 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2225 CHECK_VALID_SIZE(inputs.size(), 2);
2226
2227 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2228 CHECK_VALID_SIZE(outputs.size(), 1);
2229
2230 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2231 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2232
James Ward58dec6b2020-09-11 17:32:44 +01002233 auto layerName = fmt::format("Div:{}:{}", subgraphIndex, operatorIndex);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302234 IConnectableLayer* layer = m_Network->AddDivisionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002235 ARMNN_ASSERT(layer != nullptr);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302236
Sadik Armagand109a4d2020-07-28 10:42:13 +01002237 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302238 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2239
2240 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002241 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302242 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2243
2244 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2245 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2246}
2247
Teresa Charlincdbd40b2022-02-25 13:21:55 +00002248void TfLiteParserImpl::ParseFloorDiv(size_t subgraphIndex, size_t operatorIndex)
2249{
2250 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2251
2252 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2253 CHECK_VALID_SIZE(inputs.size(), 2);
2254
2255 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2256 CHECK_VALID_SIZE(outputs.size(), 1);
2257
2258 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2259 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2260
2261 auto layerName = fmt::format("Div:{}:{}", subgraphIndex, operatorIndex);
2262 IConnectableLayer* layer = m_Network->AddDivisionLayer(layerName.c_str());
2263 ARMNN_ASSERT(layer != nullptr);
2264
2265 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
2266 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2267
2268 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2269 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2270 layer = AddFusedFloorLayer(layer, 0);
2271
2272 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2273 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2274}
2275
Kevin May7d96b162021-02-03 17:38:41 +00002276void TfLiteParserImpl::ParseAdd(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002277{
2278 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2279
Mike Kelly0d77ae12022-01-07 17:42:27 +00002280 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2281 const auto* options = operatorPtr->builtin_options.AsAddOptions();
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002282
2283 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2284 CHECK_VALID_SIZE(inputs.size(), 2);
2285
2286 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2287 CHECK_VALID_SIZE(outputs.size(), 1);
2288
Bruno Goncalves9c761a62018-12-27 14:20:35 -02002289 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2290 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2291
James Ward58dec6b2020-09-11 17:32:44 +01002292 auto layerName = fmt::format("Add:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002293 IConnectableLayer* layer = m_Network->AddAdditionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002294 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002295
Sadik Armagand109a4d2020-07-28 10:42:13 +01002296 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002297 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2298
2299 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002300 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002301 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2302
2303 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2304 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2305}
2306
Kevin May7d96b162021-02-03 17:38:41 +00002307void TfLiteParserImpl::ParseMul(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002308{
2309 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2310
Mike Kelly0d77ae12022-01-07 17:42:27 +00002311 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2312 const auto* options = operatorPtr->builtin_options.AsMulOptions();
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002313
2314 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2315 CHECK_VALID_SIZE(inputs.size(), 2);
2316
2317 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2318 CHECK_VALID_SIZE(outputs.size(), 1);
2319
Bruno Goncalves9c761a62018-12-27 14:20:35 -02002320 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2321 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2322
James Ward58dec6b2020-09-11 17:32:44 +01002323 auto layerName = fmt::format("Mul:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002324 IConnectableLayer* layer = m_Network->AddMultiplicationLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002325 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002326
Sadik Armagand109a4d2020-07-28 10:42:13 +01002327 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002328 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2329
2330 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002331 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002332 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2333
2334 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2335 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2336}
2337
Kevin May7d96b162021-02-03 17:38:41 +00002338void TfLiteParserImpl::ParseMean(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002339{
2340 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2341
2342 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2343
2344 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2345 CHECK_VALID_SIZE(outputs.size(), 1);
2346
2347 armnn::TensorInfo dimTensorInfo = ToTensorInfo(inputs[1]);
2348 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2349
2350 armnn::MeanDescriptor desc;
2351 std::vector<unsigned int> axis(dimTensorInfo.GetNumElements());
2352 ::memcpy(axis.data(), bufferPtr->data.data(), dimTensorInfo.GetNumBytes());
2353 desc.m_Axis = axis;
2354
2355 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002356 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002357
2358 desc.m_KeepDims =
2359 inputTensorInfo.GetNumDimensions() == outputTensorInfo.GetNumDimensions() ?
2360 true : false;
2361
James Ward58dec6b2020-09-11 17:32:44 +01002362 auto layerName = fmt::format("Mean:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002363 IConnectableLayer* layer = m_Network->AddMeanLayer(desc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002364 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002365
2366 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2367
2368 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2369 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2370
2371 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2372 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2373}
2374
Kevin May7d96b162021-02-03 17:38:41 +00002375void TfLiteParserImpl::ParsePad(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002376{
2377 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2378
Kevin May7d96b162021-02-03 17:38:41 +00002379 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002380
Kevin May7d96b162021-02-03 17:38:41 +00002381 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002382 CHECK_VALID_SIZE(outputs.size(), 1);
2383
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00002384 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002385 armnn::TensorInfo padTensorInfo = ToTensorInfo(inputs[1]);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002386
Mike Kelly0d77ae12022-01-07 17:42:27 +00002387 std::vector<unsigned int> padBuffer = GetUIntBuffer(padTensorInfo, m_Model, inputs[1]->buffer);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002388
2389 size_t step = 2;
2390 armnn::PadDescriptor desc;
Mike Kelly0d77ae12022-01-07 17:42:27 +00002391 auto opcode = GetOpCode(m_Model, subgraphIndex, operatorIndex);
2392
2393 if (opcode == tflite::BuiltinOperator_PAD)
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00002394 {
Mike Kelly0d77ae12022-01-07 17:42:27 +00002395 CHECK_VALID_SIZE(inputs.size(), 2);
2396
2397 if (inputTensorInfo.IsQuantized())
2398 {
2399 desc.m_PadValue = static_cast<float>(inputTensorInfo.GetQuantizationOffset());
2400 }
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00002401 }
Mike Kelly0d77ae12022-01-07 17:42:27 +00002402 else if (opcode == tflite::BuiltinOperator_PADV2)
2403 {
2404 CHECK_VALID_SIZE(inputs.size(), 3);
2405
2406 armnn::TensorInfo padValueTensorInfo = ToTensorInfo(inputs[2]);
2407
2408 if (padValueTensorInfo.GetNumElements() != 1)
2409 {
2410 ARMNN_THROW_PARSE_EXCEPTION("Multiple padding values are not supported in PADV2");
2411 }
2412 BufferRawPtr padValueBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
2413
2414 // Get the pad value from the input tensor
2415 if (padValueBufferPtr->data.size() > 0)
2416 {
2417 switch (padValueTensorInfo.GetDataType())
2418 {
2419 case armnn::DataType::Float32:
2420 {
2421 std::vector<float> padValueBuffer(padValueTensorInfo.GetNumElements());
2422 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2423 desc.m_PadValue = padValueBuffer[0];
2424 break;
2425 }
2426 case armnn::DataType::QAsymmU8:
2427 {
2428 std::vector<uint8_t> padValueBuffer(padValueTensorInfo.GetNumElements());
2429 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2430 desc.m_PadValue = armnn::Dequantize<uint8_t>(padValueBuffer[0],
2431 padValueTensorInfo.GetQuantizationScale(),
2432 padValueTensorInfo.GetQuantizationOffset());
2433 break;
2434 }
2435 case armnn::DataType::QAsymmS8:
2436 case armnn::DataType::QSymmS8:
2437 {
2438 std::vector<int8_t> padValueBuffer(padValueTensorInfo.GetNumElements());
2439 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2440 desc.m_PadValue = armnn::Dequantize<int8_t>(padValueBuffer[0],
2441 padValueTensorInfo.GetQuantizationScale(),
2442 padValueTensorInfo.GetQuantizationOffset());
2443 break;
2444 }
2445 default: ARMNN_THROW_PARSE_EXCEPTION("Unsupported DataType");
2446 }
2447 }
2448 else if (inputTensorInfo.IsQuantized())
2449 {
2450 desc.m_PadValue = static_cast<float>(inputTensorInfo.GetQuantizationOffset());
2451 }
2452 }
2453
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002454 for (unsigned int i = 0; i < padTensorInfo.GetNumElements() / step; ++i)
2455 {
2456 desc.m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
2457 }
2458
Mike Kelly0d77ae12022-01-07 17:42:27 +00002459 auto layerName = (opcode == tflite::BuiltinOperator_PAD) ? fmt::format("Pad:{}:{}", subgraphIndex, operatorIndex)
2460 : fmt::format("PadV2:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002461 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01002462
2463 IConnectableLayer* layer = m_Network->AddPadLayer(desc, layerName.c_str());
2464 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002465 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2466
2467 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2468 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2469
2470 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2471 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2472}
2473
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +01002474void TfLiteParserImpl::ParseMirrorPad(size_t subgraphIndex, size_t operatorIndex)
2475{
2476 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2477
2478 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2479 CHECK_VALID_SIZE(inputs.size(), 2);
2480
2481 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2482 CHECK_VALID_SIZE(outputs.size(), 1);
2483
2484 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2485
2486 armnn::TensorInfo padTensorInfo = ToTensorInfo(inputs[1]);
2487 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2488
2489 std::vector<unsigned int> padBuffer(padTensorInfo.GetNumElements());
2490 ::memcpy(padBuffer.data(), bufferPtr->data.data(), padTensorInfo.GetNumBytes());
2491
2492 size_t step = 2;
2493 armnn::PadDescriptor desc;
2494 for (unsigned int i = 0; i < padTensorInfo.GetNumElements() / step; ++i)
2495 {
2496 desc.m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
2497 }
2498
2499 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2500 const auto* options = operatorPtr->builtin_options.AsMirrorPadOptions();
2501
2502 if (options->mode == tflite::MirrorPadMode_REFLECT)
2503 {
2504 desc.m_PaddingMode = PaddingMode::Reflect;
2505 }
2506 else if (options->mode == tflite::MirrorPadMode_SYMMETRIC)
2507 {
2508 desc.m_PaddingMode = PaddingMode::Symmetric;
2509 }
2510 else
2511 {
2512 ARMNN_THROW_PARSE_EXCEPTION("PaddingMode must be either REFLECT or SYMMETRIC");
2513 }
2514
2515 // If padding mode is Reflect then both paddings must be no greater than inputShape(i) - 1.
2516 // If padding mode is Symmetric then both paddings must be no greater than inputShape(i).
2517 auto inputShape = inputTensorInfo.GetShape();
2518 auto padList = desc.m_PadList;
2519
2520 const unsigned int isReflect = static_cast<unsigned int>(desc.m_PaddingMode == PaddingMode::Reflect);
2521 for(unsigned int i = 0; i < padList.size(); ++i)
2522 {
2523 if(padList.at(i).first > (inputShape[i] - isReflect) ||
2524 padList.at(i).second > (inputShape[i] - isReflect))
2525 {
2526 ARMNN_THROW_PARSE_EXCEPTION("Padding values must be less (Reflect) or "
2527 "equal (Symmetric) to the dimension size.");
2528 }
2529 }
2530
2531 auto layerName = fmt::format("MirrorPad:{}:{}", subgraphIndex, operatorIndex);
2532 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
2533
2534 IConnectableLayer* layer = m_Network->AddPadLayer(desc, layerName.c_str());
2535 ARMNN_ASSERT(layer != nullptr);
2536 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2537
2538 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2539 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2540
2541 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2542 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2543}
2544
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01002545void TfLiteParserImpl::ParsePrelu(size_t subgraphIndex, size_t operatorIndex)
2546{
2547 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2548
2549 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2550 CHECK_VALID_SIZE(inputs.size(), 2);
2551
2552 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2553 CHECK_VALID_SIZE(outputs.size(), 1);
2554
2555 auto layerName = fmt::format("Prelu:{}:{}", subgraphIndex, operatorIndex);
2556
2557 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2558 armnn::TensorInfo alphaTensorInfo = ToTensorInfo(inputs[1]);
2559 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
2560 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
2561
2562 IConnectableLayer* layer = m_Network->AddPreluLayer(layerName.c_str());
2563 ARMNN_ASSERT(layer != nullptr);
2564 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2565
2566 if (IsConstTensor(inputs[1]))
2567 {
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01002568 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawaratbf99b5f2021-05-27 09:55:43 +01002569 armnn::IInputSlot* slot = &(layer->GetInputSlot(0));
2570 RegisterConsumerOfTensor(subgraphIndex, inputTensorIndexes[0], slot);
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01002571
Mike Kelly5880b912022-01-28 16:18:54 +00002572 auto alphaTensorAndData = CreateConstTensorNonPermuted(inputs[1], alphaTensorInfo,
2573 inputTensorInfo.GetDataType());
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01002574 std::string constLayerName = fmt::format("Constant:{}", inputs[1]->name);
2575 IConnectableLayer* constLayer =
Mike Kelly5880b912022-01-28 16:18:54 +00002576 m_Network->AddConstantLayer(alphaTensorAndData.first, constLayerName.c_str());
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01002577 ARMNN_ASSERT(constLayer != nullptr);
2578
2579 constLayer->GetOutputSlot(0).SetTensorInfo(alphaTensorInfo);
2580 constLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(1));
2581 RegisterOutputSlots(subgraphIndex,
2582 VIRTUAL_OPERATOR_ID,
2583 constLayer,
2584 { inputTensorIndexes[1] });
2585 }
2586 else
2587 {
2588 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2589 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIndexes);
2590 }
2591
2592 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2593 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2594}
2595
Kevin May7d96b162021-02-03 17:38:41 +00002596void TfLiteParserImpl::ParseQuantize(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan66dedc72019-12-10 16:32:07 +00002597{
2598 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2599
2600 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2601 CHECK_VALID_SIZE(inputs.size(), 1);
2602
2603 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2604 CHECK_VALID_SIZE(outputs.size(), 1);
2605
James Ward58dec6b2020-09-11 17:32:44 +01002606 auto layerName = fmt::format("Quantize:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan66dedc72019-12-10 16:32:07 +00002607
2608 IConnectableLayer* layer = m_Network->AddQuantizeLayer(layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002609 ARMNN_ASSERT(layer != nullptr);
Sadik Armagan66dedc72019-12-10 16:32:07 +00002610
Sadik Armagand109a4d2020-07-28 10:42:13 +01002611 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan66dedc72019-12-10 16:32:07 +00002612 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2613
2614 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2615 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2616
2617 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2618 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2619}
Finn Williamsc42c3842019-01-22 14:18:11 +00002620
Kevin May7d96b162021-02-03 17:38:41 +00002621void TfLiteParserImpl::ParseRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01002622{
Finn Williamsc42c3842019-01-22 14:18:11 +00002623 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::ReLu);
Sadik Armagan58f39192018-09-17 14:14:39 +01002624}
2625
Kevin May7d96b162021-02-03 17:38:41 +00002626void TfLiteParserImpl::ParseRelu6(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01002627{
Finn Williamsc42c3842019-01-22 14:18:11 +00002628 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::BoundedReLu);
2629}
Sadik Armagan58f39192018-09-17 14:14:39 +01002630
Kevin May7d96b162021-02-03 17:38:41 +00002631void TfLiteParserImpl::ParseLeakyRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan12239e72020-05-27 11:06:17 +01002632{
Jan Eilers2f746b32020-07-28 14:00:06 +01002633 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::LeakyReLu);
Sadik Armagan12239e72020-05-27 11:06:17 +01002634}
2635
Kevin May7d96b162021-02-03 17:38:41 +00002636void TfLiteParserImpl::ParseLogistic(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsc42c3842019-01-22 14:18:11 +00002637{
2638 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::Sigmoid);
2639}
2640
Kevin May7d96b162021-02-03 17:38:41 +00002641void TfLiteParserImpl::ParseTanH(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd99851762019-04-09 09:37:38 +01002642{
2643 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::TanH);
2644}
2645
Kevin May7d96b162021-02-03 17:38:41 +00002646void TfLiteParserImpl::ParseElu(size_t subgraphIndex, size_t operatorIndex)
Matthew Sloyan7515d072020-12-16 12:50:01 +00002647{
2648 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::Elu);
2649}
2650
Kevin May7d96b162021-02-03 17:38:41 +00002651void TfLiteParserImpl::ParseHardSwish(size_t subgraphIndex, size_t operatorIndex)
Jan Eilers2f746b32020-07-28 14:00:06 +01002652{
2653 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::HardSwish);
2654}
Finn Williamsc42c3842019-01-22 14:18:11 +00002655
Kevin May7d96b162021-02-03 17:38:41 +00002656void TfLiteParserImpl::ParseActivation(size_t subgraphIndex, size_t operatorIndex, ActivationFunction activationType)
Finn Williamsc42c3842019-01-22 14:18:11 +00002657{
2658 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00002659 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Jan Eilers8eb25602020-03-09 12:13:48 +00002660 IgnoreUnused(operatorPtr);
Sadik Armagan58f39192018-09-17 14:14:39 +01002661
2662 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2663 CHECK_VALID_SIZE(inputs.size(), 1);
2664
2665 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2666 CHECK_VALID_SIZE(outputs.size(), 1);
2667
James Ward58dec6b2020-09-11 17:32:44 +01002668 auto layerName = fmt::format("Activation:");
Sadik Armagan58f39192018-09-17 14:14:39 +01002669 ActivationDescriptor activationDesc;
Finn Williamsc42c3842019-01-22 14:18:11 +00002670 activationDesc.m_Function = activationType;
2671
2672 switch (activationType)
2673 {
2674 case ActivationFunction::ReLu:
2675 {
James Ward58dec6b2020-09-11 17:32:44 +01002676 layerName += fmt::format("RELU:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002677 break;
2678 }
2679 case ActivationFunction::BoundedReLu:
2680 {
James Ward58dec6b2020-09-11 17:32:44 +01002681 layerName += fmt::format("RELU6:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002682 activationDesc.m_A = 6.0f;
2683 activationDesc.m_B = 0.0f;
2684 break;
2685 }
2686 case ActivationFunction::Sigmoid:
2687 {
James Ward58dec6b2020-09-11 17:32:44 +01002688 layerName += fmt::format("SIGMOID:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002689 break;
2690 }
Nina Drozd99851762019-04-09 09:37:38 +01002691 case ActivationFunction::TanH:
2692 {
James Ward58dec6b2020-09-11 17:32:44 +01002693 layerName += fmt::format("TANH:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd99851762019-04-09 09:37:38 +01002694 activationDesc.m_A = 1.0f;
2695 activationDesc.m_B = 1.0f;
2696 break;
2697 }
Sadik Armagan12239e72020-05-27 11:06:17 +01002698 case ActivationFunction::LeakyReLu:
2699 {
James Ward58dec6b2020-09-11 17:32:44 +01002700 layerName += fmt::format("LEAKYRELU:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00002701 const auto* options = operatorPtr->builtin_options.AsLeakyReluOptions();
Sadik Armagan12239e72020-05-27 11:06:17 +01002702 activationDesc.m_A = options->alpha;
2703 break;
2704 }
Matthew Sloyan7515d072020-12-16 12:50:01 +00002705 case ActivationFunction::Elu:
2706 {
2707 layerName += fmt::format("ELU:{}:{}", subgraphIndex, operatorIndex);
2708 activationDesc.m_A = 1.0f;
2709 break;
2710 }
Jan Eilers2f746b32020-07-28 14:00:06 +01002711 case ActivationFunction::HardSwish:
Matthew Sloyan7515d072020-12-16 12:50:01 +00002712 {
James Ward58dec6b2020-09-11 17:32:44 +01002713 layerName += fmt::format("HARDSWISH:{}:{}", subgraphIndex, operatorIndex);
Jan Eilers2f746b32020-07-28 14:00:06 +01002714 break;
Matthew Sloyan7515d072020-12-16 12:50:01 +00002715 }
Finn Williamsc42c3842019-01-22 14:18:11 +00002716 default:
2717 {
2718 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002719 fmt::format("Unexpected ActivationFunction[{}] when creating layerName {} ",
2720 static_cast<int>(activationType), CHECK_LOCATION().AsString()));
Finn Williamsc42c3842019-01-22 14:18:11 +00002721 }
2722 }
2723
2724 IConnectableLayer* const layer = m_Network->AddActivationLayer(activationDesc, layerName.c_str());
Sadik Armagan58f39192018-09-17 14:14:39 +01002725
Sadik Armagand109a4d2020-07-28 10:42:13 +01002726 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan58f39192018-09-17 14:14:39 +01002727 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2728
2729 // register the input connection slots for the layer, connections are made after all layers have been created
2730 // only the tensors for the inputs are relevant, exclude the const tensors
2731 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2732 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2733
2734 // register the output connection slots for the layer, connections are made after all layers have been created
2735 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2736 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2737}
Mike Kelly0d77ae12022-01-07 17:42:27 +00002738armnn::TensorInfo TfLiteParserImpl::OutputShapeOfReshape(const armnn::TensorInfo& inputTensorInfo,
2739 const std::vector<int32_t>& targetDimsIn)
Sadikb94967b2018-09-19 15:30:00 +01002740{
2741 std::vector<unsigned int> outputDims(targetDimsIn.begin(), targetDimsIn.end());
2742 const auto stretchDim = std::find(targetDimsIn.begin(), targetDimsIn.end(), -1);
2743
2744 if (stretchDim != targetDimsIn.end())
2745 {
2746 if (std::find(std::next(stretchDim), targetDimsIn.end(), -1) != targetDimsIn.end())
2747 {
2748 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002749 fmt::format("At most one component of shape can be -1 {}", CHECK_LOCATION().AsString()));
Sadikb94967b2018-09-19 15:30:00 +01002750 }
2751
2752 auto targetNumElements =
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002753 armnn::numeric_cast<unsigned int>(
Sadikb94967b2018-09-19 15:30:00 +01002754 std::accumulate(targetDimsIn.begin(), targetDimsIn.end(), -1, std::multiplies<int32_t>()));
2755
2756 auto stretchIndex = static_cast<size_t>(std::distance(targetDimsIn.begin(), stretchDim));
2757 outputDims[stretchIndex] = inputTensorInfo.GetNumElements() / targetNumElements;
2758 }
2759
2760 TensorShape outputShape = TensorShape(static_cast<unsigned int>(outputDims.size()), outputDims.data());
2761
2762 TensorInfo reshapeInfo = inputTensorInfo;
2763 reshapeInfo.SetShape(outputShape);
2764
2765 return reshapeInfo;
2766}
2767
Kevin May7d96b162021-02-03 17:38:41 +00002768void TfLiteParserImpl::ParseReshape(size_t subgraphIndex, size_t operatorIndex)
Sadikb94967b2018-09-19 15:30:00 +01002769{
2770 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2771
2772 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01002773
2774 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2775 CHECK_VALID_SIZE(outputs.size(), 1);
2776
Mike Kelly0d77ae12022-01-07 17:42:27 +00002777 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2778 const auto* options = operatorPtr->builtin_options.AsReshapeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01002779 auto layerName = fmt::format("Reshape:{}:{}", subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01002780
2781 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
kevmay0171972a82018-12-17 14:28:03 +00002782 armnn::TensorInfo actualOutputTensorInfo = ToTensorInfo(outputs[0]);
James Conroy05102392020-06-24 15:39:55 +01002783 CheckMatchingQuantization(inputTensorInfo, actualOutputTensorInfo, layerName, "Input 0", "Output 0");
Derek Lambertic9e52792020-03-11 11:42:26 +00002784
Jan Eilersbac9b352020-07-13 13:40:24 +01002785 // Extracting new shape for the output
2786 // There are two ways it can be passed
2787 // * First is to define the target shape in the operator built-in options
2788 // * Second is to pass it as a second input tensor
Derek Lambertic9e52792020-03-11 11:42:26 +00002789 std::vector<int32_t> targetShape;
Jan Eilersbac9b352020-07-13 13:40:24 +01002790 bool targetShapeFound = false;
2791 // Check if built-in options were given
2792 if (options != nullptr)
Derek Lambertic9e52792020-03-11 11:42:26 +00002793 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002794 // make sure the parameter is given
2795 if (options->new_shape.empty() == false)
Derek Lambertic9e52792020-03-11 11:42:26 +00002796 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002797 targetShape = options->new_shape;
2798 targetShapeFound = true;
Derek Lambertif4a953f2020-03-17 14:25:57 +00002799 }
Derek Lambertic9e52792020-03-11 11:42:26 +00002800 }
Jan Eilersbac9b352020-07-13 13:40:24 +01002801
2802 // If there is no built-in option given or if the built-in new_shape parameter was empty
2803 if (!targetShapeFound)
Derek Lambertic9e52792020-03-11 11:42:26 +00002804 {
Teresa Charlin6a056a42021-12-01 10:25:43 +00002805 // Check for a second input tensor
2806 if (inputs.size() > 1 && inputs[1] != nullptr)
Jan Eilersbac9b352020-07-13 13:40:24 +01002807 {
2808 if (inputs[1]->is_variable)
2809 {
2810 ARMNN_THROW_PARSE_EXCEPTION( "Target shapes defined in non-const input tensors is not supported");
2811 }
2812
2813 if (inputs[1]->shape.size() != 1)
2814 {
2815 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not a 1D tensor");
2816 }
2817
2818 if (inputs[1]->type != tflite::TensorType_INT32)
2819 {
2820 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not an int32 type");
2821 }
2822
Teresa Charlin6a056a42021-12-01 10:25:43 +00002823 // Extract target shape from input
2824 auto bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2825 auto values = reinterpret_cast<const int32_t*>(bufferPtr->data.data());
Cathal Corbettd2f73232021-12-10 13:38:52 +00002826 if (values)
Sadik Armagan19a1c032021-01-20 12:17:00 +00002827 {
Cathal Corbettd2f73232021-12-10 13:38:52 +00002828 for (int i = 0; i < inputs[1]->shape[0]; ++i)
2829 {
2830 targetShape.push_back(values[i]);
2831 }
Sadik Armagan19a1c032021-01-20 12:17:00 +00002832 }
Cathal Corbettd2f73232021-12-10 13:38:52 +00002833 else
Jan Eilersbac9b352020-07-13 13:40:24 +01002834 {
Cathal Corbettd2f73232021-12-10 13:38:52 +00002835 try
2836 {
2837 // We attempt to infer during Runtime.
2838 TensorShape reshapeShapes = ToTensorInfo(inputs[1]).GetShape();
2839 // The parser only supports shape (batch, -1) or (-1) for non-constant shape input.
2840 if (reshapeShapes[0] > 2)
2841 {
2842 throw ParseException(fmt::format("Invalid input shape '{}' in Reshape layer '{}' {}. "
2843 "When inferring during runtime, the parser only supports "
2844 "shape (batch, -1) or (-1) for target shape input.",
2845 reshapeShapes[0],
2846 layerName,
2847 CHECK_LOCATION().AsString()));
2848 }
2849
2850 const int32_t numInputElements = inputTensorInfo.GetNumElements();
2851 const int32_t inputTensorShape = inputTensorInfo.GetShape()[0];
2852 if (reshapeShapes[0] == 1)
2853 {
2854 targetShape = {numInputElements};
2855 }
2856 else if (reshapeShapes[0] == 2)
2857 {
2858 targetShape = {inputTensorShape, numInputElements / inputTensorShape};
2859 }
2860 }
2861 catch (const std::exception& exc)
2862 {
2863 ARMNN_THROW_PARSE_EXCEPTION("Failed attempt to infer during runtime the target shape input for "
2864 "Reshape operation. Reshape operator target shape input buffer data "
2865 "is null. " << exc.what());
2866 }
Jan Eilersbac9b352020-07-13 13:40:24 +01002867 }
2868 }
2869 else
Derek Lambertic9e52792020-03-11 11:42:26 +00002870 {
2871 ARMNN_THROW_PARSE_EXCEPTION("Target shape not defined in reshape parameters or input tensor. "
2872 "At least one method required");
2873 }
Derek Lambertic9e52792020-03-11 11:42:26 +00002874 }
2875
kevmay0171972a82018-12-17 14:28:03 +00002876 armnn::TensorInfo reshapeOutputTensorInfo =
Kevin May7d96b162021-02-03 17:38:41 +00002877 TfLiteParserImpl::OutputShapeOfReshape(inputTensorInfo, targetShape);
Sadikb94967b2018-09-19 15:30:00 +01002878
kevmay0171972a82018-12-17 14:28:03 +00002879 // Check for valid input size and that reshape parameters equal output shape
Cathal Corbett2b922e22022-09-23 15:49:24 +01002880 // The output shape can be provided to us in 2 ways:
2881 // 1. through the normal 'shape' parameter given by outputs[indx]->shape
2882 // 2. through additional parameter 'shape_signature' given by outputs[indx]->buffer.
2883 // This parameter can sometimes contain -1 value not visible in the 'shape' parameter.
Aron Virginas-Tar70672f62019-01-23 14:00:00 +00002884 const armnn::TensorShape& reshapeOutputTensorShape = reshapeOutputTensorInfo.GetShape();
2885 if (inputs.size() > 1 && !CheckShape(reshapeOutputTensorShape, outputs[0]->shape))
kevmay0171972a82018-12-17 14:28:03 +00002886 {
Cathal Corbett2b922e22022-09-23 15:49:24 +01002887 // Attempt to extract output shape from secondary 'shape_signature'
2888 // parameter and try to CheckShape() with this param.
2889 std::vector<int32_t> secondaryOutputTargetShape = outputs[0]->shape_signature;
2890
2891 // if outputs[0]->shape_signature contain a -1 value, we need to compute its actual value
2892 // from reshape input in order to correctly verify reshape parameters equal output shape
2893 armnn::TensorInfo secondaryReshapeOutputTensorInfo =
2894 TfLiteParserImpl::OutputShapeOfReshape(inputTensorInfo, secondaryOutputTargetShape);
2895
2896 if (!CheckShape(reshapeOutputTensorShape, secondaryReshapeOutputTensorInfo.GetShape()))
2897 {
2898 std::stringstream ss;
2899 ss << "New shape defined in reshape parameters "
2900 << reshapeOutputTensorShape
2901 << " does not equal output shape "
2902 << actualOutputTensorInfo.GetShape()
2903 << ": "
2904 << CHECK_LOCATION().AsString();
2905 throw ParseException(ss.str());
2906 }
kevmay0171972a82018-12-17 14:28:03 +00002907 }
2908
Sadikb94967b2018-09-19 15:30:00 +01002909 ReshapeDescriptor reshapeDesc;
kevmay0171972a82018-12-17 14:28:03 +00002910 reshapeDesc.m_TargetShape = reshapeOutputTensorInfo.GetShape();
Sadikb94967b2018-09-19 15:30:00 +01002911
Sadikb94967b2018-09-19 15:30:00 +01002912 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002913 ARMNN_ASSERT(layer != nullptr);
kevmay0171972a82018-12-17 14:28:03 +00002914 layer->GetOutputSlot(0).SetTensorInfo(reshapeOutputTensorInfo);
Sadikb94967b2018-09-19 15:30:00 +01002915
2916 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2917 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2918
2919 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2920 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2921}
2922
Kevin May7d96b162021-02-03 17:38:41 +00002923void TfLiteParserImpl::ParseResizeBilinear(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002924{
Sadik Armagana3b31f02019-12-05 09:08:53 +00002925 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::Bilinear);
2926}
2927
Kevin May7d96b162021-02-03 17:38:41 +00002928void TfLiteParserImpl::ParseResizeNearestNeighbor(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagana3b31f02019-12-05 09:08:53 +00002929{
2930 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::NearestNeighbor);
2931}
2932
Kevin May7d96b162021-02-03 17:38:41 +00002933void TfLiteParserImpl::ParseResize(size_t subgraphIndex, size_t operatorIndex, ResizeMethod resizeMethod)
Sadik Armagana3b31f02019-12-05 09:08:53 +00002934{
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002935 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2936
2937 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2938 CHECK_VALID_SIZE(inputs.size(), 2);
2939
2940 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2941 CHECK_VALID_SIZE(outputs.size(), 1);
2942
2943 armnn::TensorInfo sizeTensorInfo = ToTensorInfo(inputs[1]);
2944
2945 // Data for the parsed tensor args (size) must be stored locally.
2946 std::vector<int32_t> sizeTensorData(sizeTensorInfo.GetNumElements());
2947
2948 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2949 ::memcpy(sizeTensorData.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
2950
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01002951 ResizeDescriptor desc;
Sadik Armagana3b31f02019-12-05 09:08:53 +00002952 desc.m_Method = resizeMethod;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002953 desc.m_TargetHeight = static_cast<uint32_t> (sizeTensorData[0]);
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01002954 desc.m_TargetWidth = static_cast<uint32_t> (sizeTensorData[1]);
2955 desc.m_DataLayout = armnn::DataLayout::NHWC;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002956
James Ward58dec6b2020-09-11 17:32:44 +01002957 auto layerName = fmt::format("Resize:");
Sadik Armagana3b31f02019-12-05 09:08:53 +00002958
2959 switch (resizeMethod)
2960 {
2961 case ResizeMethod::Bilinear:
2962 {
James Ward58dec6b2020-09-11 17:32:44 +01002963 layerName += fmt::format("BILINEAR:{}:{}", subgraphIndex, operatorIndex);
Sang-Hoon Park820eb142020-01-08 10:25:24 +00002964
2965 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2966 const auto * options = operatorPtr->builtin_options.AsResizeBilinearOptions();
2967
David Monahan4a0c9b92020-05-30 09:48:39 +01002968 desc.m_AlignCorners = options->align_corners;
Sadik Armagana3b31f02019-12-05 09:08:53 +00002969 break;
2970 }
2971 case ResizeMethod::NearestNeighbor:
2972 {
James Ward58dec6b2020-09-11 17:32:44 +01002973 layerName += fmt::format("NEARESTNEIGHBOR:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagana3b31f02019-12-05 09:08:53 +00002974 break;
2975 }
2976 default:
2977 {
2978 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002979 fmt::format("Unexpected ResizeMethod[{}] when creating layerName {} ",
2980 static_cast<int>(resizeMethod), CHECK_LOCATION().AsString()));
Sadik Armagana3b31f02019-12-05 09:08:53 +00002981 }
2982 }
2983
James Conroy05102392020-06-24 15:39:55 +01002984 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002985 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01002986 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
2987
2988 IConnectableLayer* layer = m_Network->AddResizeLayer(desc, layerName.c_str());
2989 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002990 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2991
2992 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2993 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2994
2995 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2996 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2997}
2998
Kevin May7d96b162021-02-03 17:38:41 +00002999void TfLiteParserImpl::ParseConcatenation(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan479045b2018-10-01 11:51:37 +01003000{
3001 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3002
Mike Kelly0d77ae12022-01-07 17:42:27 +00003003 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3004 const auto* options = operatorPtr->builtin_options.AsConcatenationOptions();
Sadik Armagan479045b2018-10-01 11:51:37 +01003005
3006 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
3007
3008 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3009 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3010 CHECK_VALID_SIZE(outputs.size(), 1);
3011
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003012 unsigned int numConcatView = static_cast<unsigned int>(inputs.size());
3013 uint32_t inputRank = ToTensorInfo(inputs[0]).GetNumDimensions();
Sadik Armagan479045b2018-10-01 11:51:37 +01003014
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003015 const unsigned int concatDimInput = static_cast<unsigned int>(
3016 (static_cast<int>(inputRank) + options->axis) % static_cast<int>(inputRank));
Sadik Armagan479045b2018-10-01 11:51:37 +01003017
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003018 OriginsDescriptor concatDescriptor(static_cast<uint32_t>(numConcatView), inputRank);
3019 concatDescriptor.SetConcatAxis(concatDimInput);
Sadik Armagan479045b2018-10-01 11:51:37 +01003020
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003021 unsigned int mergeDimOrigin = 0;
Sadik Armagan479045b2018-10-01 11:51:37 +01003022
3023 for (unsigned int viewIndex = 0; viewIndex < numConcatView; ++viewIndex)
3024 {
3025 TensorInfo inputTensorInfo = ToTensorInfo(inputs[viewIndex]);
3026
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003027 // This set up concatDescriptor view origin
3028 armnnUtils::ProcessConcatInputTensorInfo(
3029 inputTensorInfo, concatDescriptor, concatDimInput, viewIndex, mergeDimOrigin);
Sadik Armagan479045b2018-10-01 11:51:37 +01003030 }
3031
James Ward58dec6b2020-09-11 17:32:44 +01003032 auto layerName = fmt::format("Concatenation:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagand109a4d2020-07-28 10:42:13 +01003033 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01003034
Jim Flynn906f9462019-05-10 13:55:21 +01003035 IConnectableLayer* layer = m_Network->AddConcatLayer(concatDescriptor, layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003036 ARMNN_ASSERT(layer != nullptr);
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003037 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Sadik Armagan479045b2018-10-01 11:51:37 +01003038
James Conroy05102392020-06-24 15:39:55 +01003039 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003040 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
Sadik Armagan479045b2018-10-01 11:51:37 +01003041
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003042 // add fused activation layer
3043 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Sadik Armagan479045b2018-10-01 11:51:37 +01003044
Sadik Armagan479045b2018-10-01 11:51:37 +01003045 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3046 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3047}
3048
Kevin May7d96b162021-02-03 17:38:41 +00003049void TfLiteParserImpl::ParseFullyConnected(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003050{
3051 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3052
Mike Kelly0d77ae12022-01-07 17:42:27 +00003053 const auto& operatorRfr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003054 const auto options = operatorRfr->builtin_options.AsFullyConnectedOptions();
3055
3056 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
3057
3058 FullyConnectedDescriptor desc;
3059 desc.m_BiasEnabled = false;
Nattapat Chaimanowongd8eee592018-10-26 10:24:14 +01003060 desc.m_TransposeWeightMatrix = true;
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003061
3062 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3063 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3064 CHECK_VALID_SIZE(outputs.size(), 1);
3065
3066 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
3067
3068 // Fully Connected Layer accepts two dimensional weights input
3069 int32_t weightsDimension = static_cast<int32_t>(filterTensorInfo.GetNumDimensions());
3070 if (weightsDimension != 2)
3071 {
3072 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003073 fmt::format("Dimension {} for Fully Connected weights is not supported by Armnn. "
3074 "Node {}",
3075 weightsDimension,
3076 CHECK_LOCATION().AsString()));
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003077 }
3078
Matthew Jackson74bf7da2019-08-16 16:51:42 +01003079 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01003080 auto layerName = fmt::format("FullyConnected:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003081
Matthew Sloyan81beae32021-07-13 19:46:11 +01003082 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3083 // Add the first input tensor to the registration list
3084 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0]};
3085 std::vector<unsigned int> ignoreInputWhenRegister = {};
Mike Kelly5880b912022-01-28 16:18:54 +00003086 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003087
3088 desc.m_ConstantWeights = IsConstTensor(inputs[1]);
3089
Matthew Sloyan81beae32021-07-13 19:46:11 +01003090 // Add the weights input to the registration list, constant layers will be added by SetupConstantLayers if constant.
3091 tensorIndexesToRegister.emplace_back(inputTensorIndexes[1]);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003092
Mike Kelly0506ef02023-01-03 16:29:44 +00003093 if (ShouldConstantTensorBeConverted(inputs[1], inputTensorInfo.GetDataType(), filterTensorInfo.GetDataType()))
Mike Kelly5880b912022-01-28 16:18:54 +00003094 {
3095 m_ConstantsToDequantize.emplace_back(inputs[1]->buffer);
3096 }
3097
Finn Williamsd4fa5452021-03-01 12:31:41 +00003098 if (inputs.size() == 3)
3099 {
3100 desc.m_BiasEnabled = true;
Mike Kelly5880b912022-01-28 16:18:54 +00003101 armnn::TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Matthew Sloyan81beae32021-07-13 19:46:11 +01003102
3103 // Add the biases input to the registration list, constant layer will be added by SetupConstantLayers.
3104 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
Mike Kelly5880b912022-01-28 16:18:54 +00003105
Mike Kelly0506ef02023-01-03 16:29:44 +00003106 if (ShouldConstantTensorBeConverted(inputs[2], inputTensorInfo.GetDataType(), biasTensorInfo.GetDataType()))
Mike Kelly5880b912022-01-28 16:18:54 +00003107 {
3108 m_ConstantsToDequantize.emplace_back(inputs[2]->buffer);
3109 }
Finn Williamsd4fa5452021-03-01 12:31:41 +00003110 }
3111
Matthew Sloyan81beae32021-07-13 19:46:11 +01003112 // Filters and biases are always passed to fully connected as inputs
3113 layer = m_Network->AddFullyConnectedLayer(desc, layerName.c_str());
Finn Williamsd4fa5452021-03-01 12:31:41 +00003114
3115 ARMNN_ASSERT(layer != nullptr);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003116
Finn Williamsd4fa5452021-03-01 12:31:41 +00003117 unsigned int startingSlotIndex = 0;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003118 if (inputTensorInfo.GetNumDimensions() > 2)
3119 {
3120 // Add reshape to flatten to 2D [batch_size, input_size],
3121 // where "input_size" corresponds to the number of inputs to the layer,
3122 // matching the second dimension of weights,
3123 // and "batch_size" is calculated by dividing the number of elements by "input_size".
3124 std::vector<unsigned int> reshapedDimensions(2);
3125 reshapedDimensions[1] = filterTensorInfo.GetShape()[1];
3126 reshapedDimensions[0] = inputTensorInfo.GetNumElements() / reshapedDimensions[1];
3127
3128 if (inputTensorInfo.GetNumElements() % reshapedDimensions[1] != 0)
3129 {
3130 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003131 fmt::format("Failed to deduce input tensor shape from filter size {} {}",
3132 reshapedDimensions[1],
3133 CHECK_LOCATION().AsString()));
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003134 }
3135
3136 armnn::TensorInfo reshapedTensorInfo = ToTensorInfo(inputs[0]);
3137 reshapedTensorInfo.SetShape(armnn::TensorShape{ 2, reshapedDimensions.data() });
3138
James Ward58dec6b2020-09-11 17:32:44 +01003139 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Finn Williamsd4fa5452021-03-01 12:31:41 +00003140 armnn::ReshapeDescriptor reshapeDescriptor;
3141 reshapeDescriptor.m_TargetShape = reshapedTensorInfo.GetShape();
3142 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(reshapeDescriptor, layerName.c_str());
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003143
3144 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedTensorInfo);
3145 reshapeLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(0));
3146
3147 RegisterInputSlots(subgraphIndex, operatorIndex, reshapeLayer, {inputTensorIndexes[0]});
Finn Williamsd4fa5452021-03-01 12:31:41 +00003148 // Fc layer connects to the reshape layer, so we skip the first input slot when registering fc's input slots
3149 tensorIndexesToRegister.erase(tensorIndexesToRegister.begin());
3150 startingSlotIndex = 1;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003151 }
Finn Williamsd4fa5452021-03-01 12:31:41 +00003152
3153 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister, startingSlotIndex);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003154
Sadik Armagand109a4d2020-07-28 10:42:13 +01003155 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003156 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3157
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003158 // we need to add the activation layer and fortunately we don't need to care about the data layout
3159 armnn::IConnectableLayer* fusedActivationLayer = AddFusedActivationLayer(layer, 0,
3160 options->fused_activation_function);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003161
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003162 // register the output connection slots for the layer, connections are made after all layers have been created
3163 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3164 RegisterOutputSlots(subgraphIndex, operatorIndex, fusedActivationLayer, {outputTensorIndexes[0]});
3165}
3166
Kevin May7d96b162021-02-03 17:38:41 +00003167void TfLiteParserImpl::ParseDetectionPostProcess(size_t subgraphIndex, size_t operatorIndex)
keidav011b3e2ea2019-02-21 10:07:37 +00003168{
3169 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3170
Mike Kelly0d77ae12022-01-07 17:42:27 +00003171 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
keidav011b3e2ea2019-02-21 10:07:37 +00003172
3173 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3174 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3175 CHECK_VALID_SIZE(outputs.size(), 4);
3176
3177 // Obtain custom options from flexbuffers
3178 auto custom_options = operatorPtr->custom_options;
3179 const flexbuffers::Map& m = flexbuffers::GetRoot(custom_options.data(), custom_options.size()).AsMap();
3180
3181 // Obtain descriptor information from tf lite
3182 DetectionPostProcessDescriptor desc;
3183 desc.m_MaxDetections = m["max_detections"].AsUInt32();
3184 desc.m_MaxClassesPerDetection = m["max_classes_per_detection"].AsUInt32();
3185 desc.m_NmsScoreThreshold = m["nms_score_threshold"].AsFloat();
3186 desc.m_NmsIouThreshold = m["nms_iou_threshold"].AsFloat();
3187 desc.m_NumClasses = m["num_classes"].AsUInt32();
3188 desc.m_ScaleH = m["h_scale"].AsFloat();
3189 desc.m_ScaleW = m["w_scale"].AsFloat();
3190 desc.m_ScaleX = m["x_scale"].AsFloat();
3191 desc.m_ScaleY = m["y_scale"].AsFloat();
3192
keidav0107d58c72019-02-26 11:57:39 +00003193 if (!(m["use_regular_nms"].IsNull()))
keidav011b3e2ea2019-02-21 10:07:37 +00003194 {
keidav0107d58c72019-02-26 11:57:39 +00003195 desc.m_UseRegularNms = m["use_regular_nms"].AsBool();
keidav011b3e2ea2019-02-21 10:07:37 +00003196 }
3197 if (!(m["detections_per_class"].IsNull()))
3198 {
3199 desc.m_DetectionsPerClass = m["detections_per_class"].AsUInt32();
3200 }
3201
3202 if (desc.m_NmsIouThreshold <= 0.0f || desc.m_NmsIouThreshold > 1.0f)
3203 {
3204 throw InvalidArgumentException("DetectionPostProcessTFLiteParser: Intersection over union threshold "
3205 "must be positive and less than or equal to 1.");
3206 }
3207
3208 armnn::TensorInfo anchorTensorInfo = ToTensorInfo(inputs[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003209 auto anchorTensorAndData = CreateConstTensorNonPermuted(inputs[2], anchorTensorInfo);
keidav011b3e2ea2019-02-21 10:07:37 +00003210
James Ward58dec6b2020-09-11 17:32:44 +01003211 auto layerName = fmt::format("DetectionPostProcess:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003212 IConnectableLayer* layer = m_Network->AddDetectionPostProcessLayer(desc, anchorTensorAndData,
keidav011b3e2ea2019-02-21 10:07:37 +00003213 layerName.c_str());
3214
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003215 ARMNN_ASSERT(layer != nullptr);
keidav011b3e2ea2019-02-21 10:07:37 +00003216
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003217 // The model does not specify the output shapes.
3218 // The output shapes are calculated from the max_detection and max_classes_per_detection.
3219 unsigned int numDetectedBox = desc.m_MaxDetections * desc.m_MaxClassesPerDetection;
3220 m_OverridenOutputShapes.push_back({ 1, numDetectedBox, 4 });
3221 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
3222 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
3223 m_OverridenOutputShapes.push_back({ 1 });
3224
keidav011b3e2ea2019-02-21 10:07:37 +00003225 for (unsigned int i = 0 ; i < outputs.size() ; ++i)
3226 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003227 armnn::TensorInfo detectionBoxOutputTensorInfo = ToTensorInfo(outputs[i], m_OverridenOutputShapes[i]);
keidav011b3e2ea2019-02-21 10:07:37 +00003228 layer->GetOutputSlot(i).SetTensorInfo(detectionBoxOutputTensorInfo);
3229 }
3230
3231 // Register the input connection slots for the layer, connections are made after all layers have been created
3232 // only the tensors for the inputs are relevant, exclude the const tensors
3233 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3234 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
3235
3236 // Register the output connection slots for the layer, connections are made after all layers have been created
3237 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3238 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0],
3239 outputTensorIndexes[1],
3240 outputTensorIndexes[2],
3241 outputTensorIndexes[3]});
3242}
3243
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003244/// The TfLite Pack operator is equivalent to the ArmNN Stack operator
Kevin May7d96b162021-02-03 17:38:41 +00003245void TfLiteParserImpl::ParsePack(size_t subgraphIndex, size_t operatorIndex)
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003246{
3247 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3248
3249 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3250 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3251 CHECK_VALID_SIZE(outputs.size(), 1);
3252
3253 if (inputs.size() < 1)
3254 {
3255 throw ParseException("Pack must have at least one input.");
3256 }
3257
3258 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3259 const auto* options = operatorPtr->builtin_options.AsPackOptions();
3260
3261 StackDescriptor desc;
3262 desc.m_Axis = static_cast<uint32_t>(options->axis);
3263 desc.m_NumInputs = static_cast<uint32_t>(inputs.size());
3264
3265 // Use the tensor shape of the first input as the "correct" input shape in the descriptor
3266 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3267 desc.m_InputShape = inputTensorInfo.GetShape();
3268
James Ward58dec6b2020-09-11 17:32:44 +01003269 auto layerName = fmt::format("Pack:{}:{}", subgraphIndex, operatorIndex);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003270 IConnectableLayer* layer = m_Network->AddStackLayer(desc, layerName.c_str());
3271
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003272 ARMNN_ASSERT(layer != nullptr);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003273
Sadik Armagand109a4d2020-07-28 10:42:13 +01003274 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003275 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3276
3277 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3278 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
3279
3280 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3281 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3282}
3283
Mike Kelly5880b912022-01-28 16:18:54 +00003284void TfLiteParserImpl::ParseUnidirectionalSequenceLSTM(size_t subgraphIndex, size_t operatorIndex)
3285{
3286 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3287
3288 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3289 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3290
3291 if (inputs.size() < 2)
3292 {
3293 throw ParseException("UnidirectionalSequenceLSTM must have at least 2 input.");
3294 }
3295
3296 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3297 const auto& subgraphPtr = m_Model->subgraphs[subgraphIndex];
3298 const auto nodeParams = operatorPtr->builtin_options.AsUnidirectionalSequenceLSTMOptions();
3299 CHECK_SUPPORTED_FUSED_ACTIVATION(nodeParams, subgraphIndex, operatorIndex);
3300 auto inputTensorInfo = ToTensorInfo(inputs[0]);
3301 auto outputTensorInfo = ToTensorInfo(outputs[0]);
3302
3303 // Set the params structure for the AddUnidirectionalSequenceLstmLayer call
3304 // Please refer to each operand at
3305 // https://www.tensorflow.org/mlir/tfl_ops#tflunidirectional_sequence_lstm_tflunidirectionalsequencelstmop
3306 armnn::LstmInputParams params;
3307
3308 if (IsOptionalOperandPresent(operatorPtr->inputs[1]))
3309 {
3310 params.m_InputToInputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[1]].get(),
3311 inputTensorInfo).first;
3312 }
3313
3314 params.m_InputToForgetWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[2]].get(),
3315 inputTensorInfo).first;
3316 params.m_InputToCellWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[3]].get(),
3317 inputTensorInfo).first;
3318 params.m_InputToOutputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[4]].get(),
3319 inputTensorInfo).first;
3320
3321 // Recurrent weight tensors of size {n_cell, n_output}
3322 if (IsOptionalOperandPresent(operatorPtr->inputs[5]))
3323 {
3324 params.m_RecurrentToInputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[5]].get(),
3325 inputTensorInfo).first;
3326 }
3327
3328 params.m_RecurrentToForgetWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[6]].get(),
3329 inputTensorInfo).first;
3330 params.m_RecurrentToCellWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[7]].get(),
3331 inputTensorInfo).first;
3332 params.m_RecurrentToOutputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[8]].get(),
3333 inputTensorInfo).first;
3334
3335 // Peephole weights tensors of size {n_cell}, representing a diagonal matrix.
3336 if (IsOptionalOperandPresent(operatorPtr->inputs[9]))
3337 {
3338 params.m_CellToInputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[9]].get(),
3339 inputTensorInfo).first;
3340 }
3341
3342 if (IsOptionalOperandPresent(operatorPtr->inputs[10]))
3343 {
3344 params.m_CellToForgetWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[10]].get(),
3345 inputTensorInfo).first;
3346 }
3347
3348 if (IsOptionalOperandPresent(operatorPtr->inputs[11]))
3349 {
3350 params.m_CellToOutputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[11]].get(),
3351 inputTensorInfo).first;
3352 }
3353
3354 // Gates bias tensors of size {n_cell}
3355 if (IsOptionalOperandPresent(operatorPtr->inputs[12]))
3356 {
3357 params.m_InputGateBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[12]].get(),
3358 inputTensorInfo).first;
3359 }
3360
3361 params.m_ForgetGateBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[13]].get(),
3362 inputTensorInfo).first;
3363 params.m_CellBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[14]].get(),
3364 inputTensorInfo).first;
3365 params.m_OutputGateBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[15]].get(),
3366 inputTensorInfo).first;
3367
3368 // Projection weight tensor of size {n_output, n_cell}
3369 if (IsOptionalOperandPresent(operatorPtr->inputs[16]))
3370 {
3371 params.m_ProjectionWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[16]].get(),
3372 inputTensorInfo).first;
3373 }
3374 // Projection bias tensor of size {n_output}
3375 if (IsOptionalOperandPresent(operatorPtr->inputs[17]))
3376 {
3377 params.m_ProjectionBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[17]].get(),
3378 inputTensorInfo).first;
3379 }
3380
3381 // These state tensors are defined as variable tensors, and will be modified by this op.
3382 armnn::TensorInfo outputStateInInfo = ToTensorInfo(subgraphPtr->tensors[operatorPtr->inputs[18]].get());
3383 m_ConstantsToBeCreated.push_back(operatorPtr->inputs[18]);
3384 armnn::TensorInfo cellStateInInfo = ToTensorInfo(subgraphPtr->tensors[operatorPtr->inputs[19]].get());
3385 m_ConstantsToBeCreated.push_back(operatorPtr->inputs[19]);
3386
3387 // Layer norm coefficient tensors of size {n_cell}, representing a diagonal matrix.
3388 if (inputs.size() >= 21 && IsOptionalOperandPresent(operatorPtr->inputs[20]))
3389 {
3390 params.m_InputLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[20]].get(),
3391 inputTensorInfo).first;
3392 }
3393
3394 if (inputs.size() >= 22 && IsOptionalOperandPresent(operatorPtr->inputs[21]))
3395 {
3396 params.m_ForgetLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[21]].get(),
3397 inputTensorInfo).first;
3398 }
3399
3400 if (inputs.size() >= 23 && IsOptionalOperandPresent(operatorPtr->inputs[22]))
3401 {
3402 params.m_CellLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[22]].get(),
3403 inputTensorInfo).first;
3404 }
3405
3406 if (inputs.size() >= 24 && IsOptionalOperandPresent(operatorPtr->inputs[23]))
3407 {
3408 params.m_OutputLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[23]].get(),
3409 inputTensorInfo).first;
3410 }
3411
3412 // set the layer descriptor
3413 armnn::UnidirectionalSequenceLstmDescriptor desc;
3414 desc.m_ActivationFunc = nodeParams->fused_activation_function;
3415 desc.m_ClippingThresCell = nodeParams->cell_clip;
3416 desc.m_ClippingThresProj = nodeParams->proj_clip;
3417 desc.m_CifgEnabled = (params.m_InputToInputWeights == nullptr
3418 || params.m_RecurrentToInputWeights == nullptr
3419 || params.m_InputGateBias == nullptr);
3420 desc.m_PeepholeEnabled = (params.m_CellToForgetWeights != nullptr || params.m_CellToOutputWeights != nullptr);
3421 desc.m_ProjectionEnabled = (params.m_ProjectionWeights != nullptr);
3422 desc.m_LayerNormEnabled = (params.m_InputLayerNormWeights != nullptr
3423 || params.m_ForgetLayerNormWeights != nullptr
3424 || params.m_CellLayerNormWeights != nullptr
3425 || params.m_OutputLayerNormWeights != nullptr);
3426 desc.m_TimeMajor = nodeParams->time_major;
3427
Mike Kellyc0800a32022-06-15 10:57:52 +01003428 if (operatorPtr->intermediates.size() > 3 && desc.m_LayerNormEnabled)
Mike Kelly5880b912022-01-28 16:18:54 +00003429 {
3430 auto inputIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[0]].get(),
3431 inputTensorInfo).first;
3432 auto inputIntermediateTensorInfo = inputIntermediate->GetInfo();
3433 desc.m_InputIntermediateScale = inputIntermediateTensorInfo.GetQuantizationScale();
3434
3435 auto forgetIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[1]].get(),
3436 inputTensorInfo).first;
3437 auto forgetIntermediateTensorInfo = forgetIntermediate->GetInfo();
3438 desc.m_ForgetIntermediateScale = forgetIntermediateTensorInfo.GetQuantizationScale();
3439
3440 auto cellIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[2]].get(),
3441 inputTensorInfo).first;
3442 auto cellIntermediateTensorInfo = cellIntermediate->GetInfo();
3443 desc.m_CellIntermediateScale = cellIntermediateTensorInfo.GetQuantizationScale();
3444
3445 auto outputIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[3]].get(),
3446 inputTensorInfo).first;
3447 auto outputIntermediateTensorInfo = outputIntermediate->GetInfo();
3448 desc.m_OutputIntermediateScale = outputIntermediateTensorInfo.GetQuantizationScale();
3449 }
3450 else
3451 {
3452 float defaultIntermediate = std::pow(2, -12);
3453 desc.m_InputIntermediateScale = defaultIntermediate;
3454 desc.m_ForgetIntermediateScale = defaultIntermediate;
3455 desc.m_CellIntermediateScale = defaultIntermediate;
3456 desc.m_OutputIntermediateScale = defaultIntermediate;
3457 }
3458
Mike Kellyc0800a32022-06-15 10:57:52 +01003459 if (operatorPtr->intermediates.size() > 4)
3460 {
3461 auto hiddentensor = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[4]].get(),
3462 inputTensorInfo).first;
Mike Kelly5880b912022-01-28 16:18:54 +00003463
Mike Kellyc0800a32022-06-15 10:57:52 +01003464 desc.m_HiddenStateScale = hiddentensor->GetInfo().GetQuantizationScale();
3465 desc.m_HiddenStateZeroPoint = hiddentensor->GetInfo().GetQuantizationOffset();
3466 }
Mike Kelly5880b912022-01-28 16:18:54 +00003467 unsigned int batchSize = inputTensorInfo.GetShape()[0];
3468 unsigned int outputSize = outputTensorInfo.GetShape()[2];
3469 unsigned int numUnits = cellStateInInfo.GetShape()[1];
3470
3471 armnn::DataType dataType = inputTensorInfo.GetDataType();
3472 float qScale = inputTensorInfo.GetQuantizationScale();
3473 float qOffset = inputTensorInfo.GetQuantizationOffset();
3474
3475 armnn::TensorInfo scratchBufferTensorInfo({batchSize, numUnits * 3}, dataType, qScale, qOffset);
3476 if (!desc.m_CifgEnabled)
3477 {
3478 scratchBufferTensorInfo = armnn::TensorInfo({batchSize, numUnits * 4}, dataType, qScale, qOffset);
3479 }
3480 armnn::TensorInfo cellStateOutTensorInfo({batchSize, numUnits},
3481 cellStateInInfo.GetDataType(),
3482 cellStateInInfo.GetQuantizationScale(),
3483 cellStateInInfo.GetQuantizationOffset());
3484 armnn::TensorInfo outputStateOutTensorInfo({batchSize, outputSize}, dataType, qScale, qOffset);
3485
3486 armnn::LstmInputParamsInfo paramsInfo;
3487 paramsInfo.m_InputToForgetWeights = &(params.m_InputToForgetWeights->GetInfo());
3488 paramsInfo.m_InputToCellWeights = &(params.m_InputToCellWeights->GetInfo());
3489 paramsInfo.m_InputToOutputWeights = &(params.m_InputToOutputWeights->GetInfo());
3490 paramsInfo.m_RecurrentToForgetWeights = &(params.m_RecurrentToForgetWeights->GetInfo());
3491 paramsInfo.m_RecurrentToCellWeights = &(params.m_RecurrentToCellWeights->GetInfo());
3492 paramsInfo.m_RecurrentToOutputWeights = &(params.m_RecurrentToOutputWeights->GetInfo());
3493 paramsInfo.m_ForgetGateBias = &(params.m_ForgetGateBias->GetInfo());
3494 paramsInfo.m_CellBias = &(params.m_CellBias->GetInfo());
3495 paramsInfo.m_OutputGateBias = &(params.m_OutputGateBias->GetInfo());
3496
3497 if (!desc.m_CifgEnabled)
3498 {
3499 paramsInfo.m_InputToInputWeights = &(params.m_InputToInputWeights->GetInfo());
3500 paramsInfo.m_RecurrentToInputWeights = &(params.m_RecurrentToInputWeights->GetInfo());
3501 if (params.m_CellToInputWeights != nullptr)
3502 {
3503 paramsInfo.m_CellToInputWeights = &(params.m_CellToInputWeights->GetInfo());
3504 }
3505 paramsInfo.m_InputGateBias = &(params.m_InputGateBias->GetInfo());
3506 }
3507
3508 if (desc.m_ProjectionEnabled)
3509 {
3510 paramsInfo.m_ProjectionWeights = &(params.m_ProjectionWeights->GetInfo());
3511 if (params.m_ProjectionBias != nullptr)
3512 {
3513 paramsInfo.m_ProjectionBias = &(params.m_ProjectionBias->GetInfo());
3514 }
3515 }
3516
3517 if (desc.m_PeepholeEnabled)
3518 {
3519 paramsInfo.m_CellToForgetWeights = &(params.m_CellToForgetWeights->GetInfo());
3520 paramsInfo.m_CellToOutputWeights = &(params.m_CellToOutputWeights->GetInfo());
3521 }
3522
3523 if (desc.m_LayerNormEnabled)
3524 {
3525 if(!desc.m_CifgEnabled)
3526 {
3527 paramsInfo.m_InputLayerNormWeights = &(params.m_InputLayerNormWeights->GetInfo());
3528 }
3529 paramsInfo.m_ForgetLayerNormWeights = &(params.m_ForgetLayerNormWeights->GetInfo());
3530 paramsInfo.m_CellLayerNormWeights = &(params.m_CellLayerNormWeights->GetInfo());
3531 paramsInfo.m_OutputLayerNormWeights = &(params.m_OutputLayerNormWeights->GetInfo());
3532 }
3533
3534 auto layerName = fmt::format("UnidirectionalSequenceLSTM:{}:{}", subgraphIndex, operatorIndex);
3535 armnn::IConnectableLayer* layer = m_Network->AddUnidirectionalSequenceLstmLayer(desc, params);
3536 ARMNN_ASSERT(layer != nullptr);
3537
3538 // register the input connection slots for the layer, connections are made after all layers have been created
3539 // only the tensors for the inputs are relevant, exclude the const tensors
3540 auto inputTensorIndexes = AsUnsignedVector({operatorPtr->inputs[0],
3541 operatorPtr->inputs[18],
3542 operatorPtr->inputs[19]});
3543 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0],
3544 inputTensorIndexes[1],
3545 inputTensorIndexes[2]});
3546
3547 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3548
3549 layer->GetOutputSlot(0).SetTensorInfo(outputStateOutTensorInfo);
3550 layer->GetOutputSlot(1).SetTensorInfo(cellStateOutTensorInfo);
3551 layer->GetOutputSlot(2).SetTensorInfo(outputTensorInfo);
3552
3553 unsigned int tensorIndex = outputTensorIndexes[0];
3554 armnn::IOutputSlot* slot = &(layer->GetOutputSlot(2));
3555 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
3556}
3557
Kevin May7d96b162021-02-03 17:38:41 +00003558void TfLiteParserImpl::ParseUnpack(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd200e3802019-04-15 09:47:39 +01003559{
3560 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3561
Mike Kelly0d77ae12022-01-07 17:42:27 +00003562 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3563 const auto* options = operatorPtr->builtin_options.AsUnpackOptions();
Nina Drozd200e3802019-04-15 09:47:39 +01003564
3565 // This unpackAxis indicates the axis to unpack
3566 const unsigned int unpackAxis = CHECKED_NON_NEGATIVE(options->axis);
3567
3568 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3569 CHECK_VALID_SIZE(inputs.size(), 1);
3570
3571 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003572
3573 if (unpackAxis >= inputTensorInfo.GetNumDimensions())
3574 {
3575 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003576 fmt::format("The unpack axis: {} cannot be greater than or equal to "
3577 "the number of input dimension {} {}",
3578 unpackAxis,
3579 inputTensorInfo.GetNumDimensions(),
3580 CHECK_LOCATION().AsString()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003581 }
3582
Nina Drozd200e3802019-04-15 09:47:39 +01003583 unsigned int unpackNum = CHECKED_NON_NEGATIVE(options->num);
3584 // If num is not defined, automatically infer from the length of the dimension axis.
3585 if(unpackNum == 0)
3586 {
3587 unpackNum = inputTensorInfo.GetShape()[unpackAxis];
3588 }
3589
3590 // If unpack number cannot be inferred and is still zero, throw ParseException.
3591 if(unpackNum == 0)
3592 {
3593 throw ParseException("Number to unpack must greater than zero.");
3594 }
3595
3596 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3597 CHECK_VALID_SIZE(outputs.size(), unpackNum);
3598
3599 auto inputDimSize = inputTensorInfo.GetNumDimensions();
3600 std::vector<unsigned int> unpackDimSizes(inputDimSize);
3601
3602 // Add current input shape to unpackDimSizes
3603 for (unsigned int i = 0; i < inputDimSize; ++i)
3604 {
3605 unpackDimSizes[i] = inputTensorInfo.GetShape()[i];
3606 }
3607
3608 if (unpackDimSizes[unpackAxis] != unpackNum)
3609 {
3610 throw ParseException("Number to unpack must be the same as length of the dimension to "
3611 "unpack along.");
3612 }
3613
3614 unpackDimSizes[unpackAxis] /= unpackNum;
3615
3616 SplitterDescriptor splitDesc(unpackNum, static_cast<unsigned int>(unpackDimSizes.size()));
3617 for (unsigned int j = 0; j < unpackNum; ++j)
3618 {
3619 // Set the size of the views.
3620 for (unsigned int dimIdx = 0; dimIdx < unpackDimSizes.size(); ++dimIdx)
3621 {
3622 splitDesc.SetViewSize(j, dimIdx, unpackDimSizes[dimIdx]);
3623 }
3624 splitDesc.SetViewOriginCoord(j, unpackAxis, unpackDimSizes[unpackAxis] * j);
3625 }
3626
James Ward58dec6b2020-09-11 17:32:44 +01003627 auto layerName = fmt::format("Unpack:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd200e3802019-04-15 09:47:39 +01003628 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01003629 ARMNN_ASSERT(layer != nullptr);
Nina Drozd200e3802019-04-15 09:47:39 +01003630
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003631 TensorShape splitOutShape = TensorShape(static_cast<unsigned int>(unpackDimSizes.size()),
3632 unpackDimSizes.data());
3633
Nina Drozd200e3802019-04-15 09:47:39 +01003634 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3635 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3636
Finn Williamsb49ed182021-06-29 15:50:08 +01003637 std::vector<unsigned int> reshapeDims;
3638 for (unsigned int axis = 0; axis < splitOutShape.GetNumDimensions(); ++axis)
3639 {
3640 if (axis != unpackAxis)
3641 {
3642 reshapeDims.push_back(splitOutShape[axis]);
3643 }
3644 }
3645
3646 TensorShape reshapeOutputShape(splitOutShape.GetNumDimensions() -1, reshapeDims.data());
3647
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003648 // Create reshape to remove the unpacked dimension for unpack operator of each output from Splitter.
3649 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
3650 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01003651 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[k], true);
James Ward58dec6b2020-09-11 17:32:44 +01003652 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003653 armnn::ReshapeDescriptor desc;
Finn Williamsb49ed182021-06-29 15:50:08 +01003654 desc.m_TargetShape = reshapeOutputShape;
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003655 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(desc, layerName.c_str());
3656
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01003657 layer->GetOutputSlot(k).SetTensorInfo(armnn::TensorInfo(splitOutShape,
3658 outputTensorInfo.GetDataType(),
3659 outputTensorInfo.GetQuantizationScale(),
3660 outputTensorInfo.GetQuantizationOffset()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003661 layer->GetOutputSlot(k).Connect(reshapeLayer->GetInputSlot(0));
3662
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01003663 reshapeLayer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003664
3665 uint32_t reshapedOutputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[k]);
3666 armnn::IOutputSlot* slot = &(reshapeLayer->GetOutputSlot(0));
3667 RegisterProducerOfTensor(subgraphIndex, reshapedOutputId, slot);
3668 }
Nina Drozd200e3802019-04-15 09:47:39 +01003669}
3670
Kevin May7d96b162021-02-03 17:38:41 +00003671void TfLiteParserImpl::ParseSplit(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd0324f482019-04-08 10:52:10 +01003672{
3673 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3674
Mike Kelly0d77ae12022-01-07 17:42:27 +00003675 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3676 const auto* options = operatorPtr->builtin_options.AsSplitOptions();
Nina Drozd0324f482019-04-08 10:52:10 +01003677
3678 const unsigned int numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
3679
Nina Drozd200e3802019-04-15 09:47:39 +01003680 // If number of splits cannot be inferred and is zero, throw ParseException.
3681 if(numSplits == 0)
3682 {
3683 throw ParseException("Number to splits must greater than zero.");
3684 }
3685
Nina Drozd0324f482019-04-08 10:52:10 +01003686 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3687 CHECK_VALID_SIZE(inputs.size(), 2);
3688 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3689 CHECK_VALID_SIZE(outputs.size(), numSplits);
3690
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003691 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[1]);
3692 armnn::TensorInfo axisTensorInfo = ToTensorInfo(inputs[0]);
3693 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
Nina Drozd0324f482019-04-08 10:52:10 +01003694
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003695 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003696 if (axisBufferPtr == nullptr)
3697 {
3698 throw ParseException(
3699 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
3700 CHECK_LOCATION().AsString()));
3701 }
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003702
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003703 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
3704 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
3705 int32_t axis = axisData[0];
3706
3707 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3708 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3709 {
3710 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
3711 // E.g. Rank 4 tensor can have axis in range [-4, 3)
3712 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
3713 throw ParseException(
3714 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3715 axis,
3716 CHECK_LOCATION().AsString()));
3717 }
3718
3719 const unsigned int splitDim = armnnUtils::GetUnsignedAxis(inputTensorInfo.GetNumDimensions(), axis);
Nina Drozd0324f482019-04-08 10:52:10 +01003720
Nina Drozd0324f482019-04-08 10:52:10 +01003721 auto inputDimSize = inputTensorInfo.GetNumDimensions();
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003722 if (inputDimSize > MaxNumOfTensorDimensions)
Nina Drozd0324f482019-04-08 10:52:10 +01003723 {
3724 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003725 fmt::format("The number of dimensions: {} for input tensors of the split op cannot be greater than {} {}",
3726 inputTensorInfo.GetNumDimensions(),
3727 MaxNumOfTensorDimensions,
3728 CHECK_LOCATION().AsString()));
Nina Drozd0324f482019-04-08 10:52:10 +01003729 }
3730
3731 std::vector<unsigned int> splitterDimSizes(inputDimSize);
3732
3733 // Add current input shape to splitterDimSizes
3734 for (unsigned int i = 0; i < inputDimSize; ++i)
3735 {
3736 splitterDimSizes[i] = inputTensorInfo.GetShape()[i];
3737 }
3738
3739 if (splitterDimSizes[splitDim] % numSplits != 0)
3740 {
3741 throw ParseException("Number of splits must evenly divide the dimension");
3742 }
3743 splitterDimSizes[splitDim] /= numSplits;
3744
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003745 SplitterDescriptor splitDesc(numSplits, inputDimSize);
Nina Drozd0324f482019-04-08 10:52:10 +01003746 for (unsigned int j = 0; j < numSplits; ++j)
3747 {
3748 // Set the size of the views.
3749 for (unsigned int dimIdx = 0; dimIdx < splitterDimSizes.size(); ++dimIdx)
3750 {
3751 splitDesc.SetViewSize(j, dimIdx, splitterDimSizes[dimIdx]);
3752 }
3753 splitDesc.SetViewOriginCoord(j, splitDim, splitterDimSizes[splitDim] * j);
3754 }
3755
James Ward58dec6b2020-09-11 17:32:44 +01003756 auto layerName = fmt::format("Split:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd0324f482019-04-08 10:52:10 +01003757 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01003758 ARMNN_ASSERT(layer != nullptr);
Nina Drozd0324f482019-04-08 10:52:10 +01003759
3760 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003761 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[1]});
Nina Drozd0324f482019-04-08 10:52:10 +01003762
Nina Drozd0324f482019-04-08 10:52:10 +01003763 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
3764 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01003765 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Francis Murtagh98d6b3d2019-10-21 10:52:54 +01003766 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
Nina Drozd0324f482019-04-08 10:52:10 +01003767 }
3768
3769 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3770 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3771}
3772
Derek Lambertif0176992020-04-28 13:37:49 +01003773unsigned int ComputeWrappedIndex(int idx, unsigned int numDimsIn)
3774{
3775 int numDims = armnn::numeric_cast<int>(numDimsIn);
3776 int v = idx < 0 ? numDims + idx : idx;
3777 ARMNN_ASSERT(v >= 0);
3778 ARMNN_ASSERT(v < numDims);
3779
3780 return static_cast<unsigned int>(v);
3781}
3782
Kevin May7d96b162021-02-03 17:38:41 +00003783void TfLiteParserImpl::ParseSplitV(size_t subgraphIndex, size_t operatorIndex)
Derek Lambertif0176992020-04-28 13:37:49 +01003784{
3785 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3786
Mike Kelly0d77ae12022-01-07 17:42:27 +00003787 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3788 const auto* options = operatorPtr->builtin_options.AsSplitVOptions();
Derek Lambertif0176992020-04-28 13:37:49 +01003789
3790 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3791 CHECK_VALID_SIZE(inputs.size(), 3);
3792
3793 auto& inputTensor = inputs[0];
3794 auto& splitsTensor = inputs[1];
3795 auto& axisTensor = inputs[2];
3796
3797 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputTensor);
3798 armnn::TensorInfo splitsInfo = ToTensorInfo(splitsTensor);
3799 armnn::TensorInfo axisTensorInfo = ToTensorInfo(axisTensor);
3800 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
3801
3802 // Inputs
3803 auto inputDimSize = inputTensorInfo.GetNumDimensions();
3804 if (inputDimSize > MaxNumOfTensorDimensions)
3805 {
3806 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003807 fmt::format("The number of dimensions: {} for input tensors of the "
3808 "SplitV op cannot be greater than {} {}",
3809 inputTensorInfo.GetNumDimensions(),
3810 MaxNumOfTensorDimensions,
3811 CHECK_LOCATION().AsString()));
Derek Lambertif0176992020-04-28 13:37:49 +01003812 }
3813
3814 // Get split axis
3815 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, axisTensor->buffer);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003816 if (axisBufferPtr == nullptr)
3817 {
3818 throw ParseException(
3819 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
3820 CHECK_LOCATION().AsString()));
3821 }
3822
Derek Lambertif0176992020-04-28 13:37:49 +01003823 std::vector<int> axisData(axisTensorInfo.GetNumElements());
3824 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003825 int32_t axis = axisData[0];
3826
3827 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3828 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3829 {
3830 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
3831 // E.g. Rank 4 tensor can have axis in range [-4, 3)
3832 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
3833 throw ParseException(
3834 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3835 axis,
3836 CHECK_LOCATION().AsString()));
3837 }
3838 const unsigned int splitDim = ComputeWrappedIndex(axis, inputTensorInfo.GetNumDimensions());
Derek Lambertif0176992020-04-28 13:37:49 +01003839
Derek Lambertif0176992020-04-28 13:37:49 +01003840 // Set split sizes
Derek Lambertif0176992020-04-28 13:37:49 +01003841 CHECK_VALID_SIZE(splitsInfo.GetNumDimensions(), 1);
Ryan OShea86704732020-05-26 11:41:04 +01003842 unsigned int numSplits{0};
3843
3844 if(options)
Derek Lambertif0176992020-04-28 13:37:49 +01003845 {
3846 numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
Derek Lambertif0176992020-04-28 13:37:49 +01003847 }
3848 else
3849 {
Ryan OShea86704732020-05-26 11:41:04 +01003850 numSplits = splitsInfo.GetNumElements();
Derek Lambertif0176992020-04-28 13:37:49 +01003851 }
3852
3853 if (numSplits <=0)
3854 {
3855 throw ParseException("SplitV has invalid number of splits");
3856 }
3857
Jan Eilersc0761e92020-06-29 16:48:44 +01003858 std::vector<int> splitsData(numSplits);
Ryan OShea86704732020-05-26 11:41:04 +01003859 BufferRawPtr splitsBufferPtr = GetBuffer(m_Model, splitsTensor->buffer);
Jan Eilersc0761e92020-06-29 16:48:44 +01003860 ::memcpy(splitsData.data(), splitsBufferPtr->data.data(), splitsInfo.GetNumBytes());
Ryan OShea86704732020-05-26 11:41:04 +01003861
Jan Eilersc0761e92020-06-29 16:48:44 +01003862 unsigned int idx = 0;
Ryan OShea86704732020-05-26 11:41:04 +01003863 int numInferred{0};
3864 unsigned int inferIdx{0};
3865 int splitSum{0};
3866 for (auto split : splitsData)
3867 {
3868 if (split < 0)
3869 {
3870 numInferred++;
3871 inferIdx = idx;
3872 }
3873 else
3874 {
3875 splitSum += split;
3876 }
3877 idx++;
3878 }
3879 // Check for inferred Axis
3880 if (numInferred == 0)
3881 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01003882 if (splitSum != armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]))
Ryan OShea86704732020-05-26 11:41:04 +01003883 {
3884 throw ParseException("SplitV split_sizes does not sum to the dimension of value along split_dim.");
3885 }
3886 }
3887 else if (numInferred == 1)
3888 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01003889 splitsData[inferIdx] = armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]) - splitSum;
Ryan OShea86704732020-05-26 11:41:04 +01003890 }
3891 else
3892 {
3893 throw ParseException("Cannot infer split size for more than one split");
3894 }
3895
Derek Lambertif0176992020-04-28 13:37:49 +01003896 //Ouput size validation
3897 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3898 CHECK_VALID_SIZE(outputs.size(), numSplits);
3899
3900 // Setup Armnn descriptor
3901 SplitterDescriptor splitDesc(numSplits, inputDimSize);
3902 unsigned int accumSplit = 0;
3903 for (unsigned int j = 0; j < numSplits; ++j)
3904 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01003905 unsigned int splitSize = armnn::numeric_cast<unsigned int>(splitsData[j]);
Derek Lambertif0176992020-04-28 13:37:49 +01003906
3907 // Set the size of the views.
3908 for (unsigned int dimIdx = 0; dimIdx < inputTensorInfo.GetNumDimensions(); ++dimIdx)
3909 {
3910 unsigned int dimSize = inputTensorInfo.GetShape()[dimIdx];
3911 if (dimIdx == splitDim)
3912 {
3913 dimSize = splitSize;
3914 }
3915 splitDesc.SetViewSize(j, dimIdx, dimSize);
3916 }
3917
3918 splitDesc.SetViewOriginCoord(j, splitDim, accumSplit);
3919 accumSplit += splitSize;
3920 }
3921
James Ward58dec6b2020-09-11 17:32:44 +01003922 auto layerName = fmt::format("SplitV:{}:{}", subgraphIndex, operatorIndex);
Derek Lambertif0176992020-04-28 13:37:49 +01003923 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01003924 ARMNN_ASSERT(layer != nullptr);
Derek Lambertif0176992020-04-28 13:37:49 +01003925
3926 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3927 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3928
3929 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
3930 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01003931 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Derek Lambertif0176992020-04-28 13:37:49 +01003932 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
3933 }
3934
3935 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3936 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3937}
3938
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003939void TfLiteParserImpl::ParseArgMin(size_t subgraphIndex, size_t operatorIndex)
3940{
3941 ParseArgMinMax(subgraphIndex, operatorIndex, armnn::ArgMinMaxFunction::Min);
3942}
3943
Kevin May7d96b162021-02-03 17:38:41 +00003944void TfLiteParserImpl::ParseArgMax(size_t subgraphIndex, size_t operatorIndex)
Inki Daed4619e22020-09-10 15:33:54 +09003945{
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003946 ParseArgMinMax(subgraphIndex, operatorIndex, armnn::ArgMinMaxFunction::Max);
3947}
3948
3949void TfLiteParserImpl::ParseArgMinMax(size_t subgraphIndex, size_t operatorIndex, ArgMinMaxFunction argMinMaxFunction)
3950{
Inki Daed4619e22020-09-10 15:33:54 +09003951 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3952 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3953 CHECK_VALID_SIZE(inputs.size(), 2);
3954
3955 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3956 CHECK_VALID_SIZE(outputs.size(), 1);
3957
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003958 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3959 armnn::TensorInfo axisTensorInfo = ToTensorInfo(inputs[1]);
Inki Daed4619e22020-09-10 15:33:54 +09003960 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003961 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003962
3963 // Check if output tensor type is Signed32 or Signed64
Mike Kelly1f140f72021-04-06 12:25:55 +01003964 if (outputTensorInfo.GetDataType() != armnn::DataType::Signed32 &&
3965 outputTensorInfo.GetDataType() != armnn::DataType::Signed64)
3966 {
3967 throw ParseException(
3968 fmt::format(
3969 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
3970 CHECK_LOCATION().AsString()));
3971 }
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003972
3973 // Get const axis value from model and set it to descriptor.
3974 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
3975 if (axisBufferPtr == nullptr)
3976 {
3977 throw ParseException(
3978 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
3979 CHECK_LOCATION().AsString()));
3980 }
3981
3982 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
3983 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
3984 int32_t axis = axisData.front();
3985
3986 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3987 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3988 {
3989 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
3990 // E.g. Rank 4 tensor can have axis in range [-4, 3)
3991 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
3992 throw ParseException(
3993 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3994 axis,
3995 CHECK_LOCATION().AsString()));
3996 }
3997
3998 ArgMinMaxDescriptor desc;
3999 desc.m_Axis = axis;
4000 desc.m_Function = argMinMaxFunction;
4001
4002 // Register a ArgMin/ArgMax layer.
4003 auto layerName = argMinMaxFunction == ArgMinMaxFunction::Max ? "ArgMax:{}:{}" : "ArgMin:{}:{}";
4004 auto layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
4005 IConnectableLayer *layer = m_Network->AddArgMinMaxLayer(desc, layerNameFormatted.c_str());
4006 ARMNN_ASSERT(layer != nullptr);
Inki Daed4619e22020-09-10 15:33:54 +09004007 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4008
4009 // Register input tensor to the layer.
4010 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4011 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4012
4013 // Register output tensor to the layer.
4014 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4015 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
4016}
4017
Kevin May7d96b162021-02-03 17:38:41 +00004018void TfLiteParserImpl::ParseGather(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00004019{
4020 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4021
Kevin May7d96b162021-02-03 17:38:41 +00004022 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004023 CHECK_VALID_SIZE(inputs.size(), 2);
Kevin May7d96b162021-02-03 17:38:41 +00004024 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004025 CHECK_VALID_SIZE(outputs.size(), 1);
4026
4027 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
4028 armnn::TensorInfo indicesTensorInfo = ToTensorInfo(inputs[1]);
4029 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
4030
4031 armnn::GatherDescriptor gatherDescriptor;
4032
Mike Kelly0d77ae12022-01-07 17:42:27 +00004033 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4034 const auto* options = operatorPtr->builtin_options.AsGatherOptions();
Sadik Armagan26868492021-01-22 14:25:31 +00004035 auto axis = options->axis;
4036
4037 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
4038 auto indicesDimensions = indicesTensorInfo.GetNumDimensions();
4039 auto outputDimensions = outputTensorInfo.GetNumDimensions();
4040 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
4041 {
4042 throw ParseException(
4043 fmt::format("Operation has invalid axis: {} It is out of bounds [ -{}, {} ) {}",
4044 axis,
4045 inputDimensions, inputDimensions,
4046 CHECK_LOCATION().AsString()));
4047 }
4048 if (outputDimensions != static_cast<unsigned int>(inputDimensions) + indicesDimensions - 1)
4049 {
4050 throw ParseException(
4051 fmt::format("Operation has invalid output dimensions: {} Output must be an ({} + {} - 1) -D tensor {}",
4052 outputDimensions,
4053 inputDimensions, indicesDimensions,
4054 CHECK_LOCATION().AsString()));
4055 }
4056
4057 gatherDescriptor.m_Axis = axis;
4058
4059 auto layerName = fmt::format("Gather:{}:{}", subgraphIndex, operatorIndex);
4060 IConnectableLayer* layer = m_Network->AddGatherLayer(gatherDescriptor, layerName.c_str());
4061 ARMNN_ASSERT(layer != nullptr);
4062 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4063
4064 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4065 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
4066
4067 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4068 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4069}
4070
Teresa Charlin91a53ea2022-04-25 15:47:29 +01004071void TfLiteParserImpl::ParseGatherNd(size_t subgraphIndex, size_t operatorIndex)
4072{
4073 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4074
4075 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4076 CHECK_VALID_SIZE(inputs.size(), 2);
4077 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4078 CHECK_VALID_SIZE(outputs.size(), 1);
4079
4080 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
4081 armnn::TensorInfo indicesTensorInfo = ToTensorInfo(inputs[1]);
4082 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
4083
4084 auto layerName = fmt::format("GatherNd:{}:{}", subgraphIndex, operatorIndex);
4085 IConnectableLayer* layer = m_Network->AddGatherNdLayer(layerName.c_str());
4086 ARMNN_ASSERT(layer != nullptr);
4087 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4088
4089 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4090 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
4091
4092 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4093 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4094}
4095
Kevin May7d96b162021-02-03 17:38:41 +00004096void TfLiteParserImpl::ParseDepthToSpace(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00004097{
4098 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4099
Kevin May7d96b162021-02-03 17:38:41 +00004100 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004101 CHECK_VALID_SIZE(inputs.size(), 1);
Kevin May7d96b162021-02-03 17:38:41 +00004102 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004103 CHECK_VALID_SIZE(outputs.size(), 1);
4104
4105 armnn::DepthToSpaceDescriptor descriptor;
4106
Mike Kelly0d77ae12022-01-07 17:42:27 +00004107 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4108 const auto* options = operatorPtr->builtin_options.AsDepthToSpaceOptions();
Sadik Armagan26868492021-01-22 14:25:31 +00004109 auto blockSize = options->block_size;
4110 if (blockSize < 2)
4111 {
4112 throw ParseException(
4113 fmt::format("Operation has invalid block size: {} Block size should be >= 2 {}",
4114 blockSize,
4115 CHECK_LOCATION().AsString()));
4116 }
4117 descriptor.m_BlockSize = armnn::numeric_cast<uint32_t>(blockSize);
4118
4119 auto layerName = fmt::format("DepthToSpace:{}:{}", subgraphIndex, operatorIndex);
4120 IConnectableLayer* layer = m_Network->AddDepthToSpaceLayer(descriptor, layerName.c_str());
4121 ARMNN_ASSERT(layer != nullptr);
4122 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
4123 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4124
4125 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4126 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4127
4128 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4129 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4130}
4131
Kevin May7d96b162021-02-03 17:38:41 +00004132void TfLiteParserImpl::ParseSum(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004133{
Sadik Armagana2747482021-02-09 10:28:54 +00004134 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Sum);
4135}
4136
Teresa Charlin4e3e8312021-08-05 12:34:37 +01004137void TfLiteParserImpl::ParseReduceProd(size_t subgraphIndex, size_t operatorIndex)
4138{
4139 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Prod);
4140}
4141
Sadik Armagana2747482021-02-09 10:28:54 +00004142void TfLiteParserImpl::ParseReduceMax(size_t subgraphIndex, size_t operatorIndex)
4143{
4144 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Max);
4145}
4146
4147void TfLiteParserImpl::ParseReduceMin(size_t subgraphIndex, size_t operatorIndex)
4148{
4149 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Min);
4150}
4151
4152void TfLiteParserImpl::ParseReduce(size_t subgraphIndex, size_t operatorIndex, ReduceOperation reduceOperation)
4153{
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004154 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4155
Mike Kelly0d77ae12022-01-07 17:42:27 +00004156 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4157 const auto* options = operatorPtr->builtin_options.AsReducerOptions();
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004158
4159 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4160 CHECK_VALID_SIZE(inputs.size(), 2);
4161
4162 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4163 CHECK_VALID_SIZE(outputs.size(), 1);
4164
Sadik Armagana2747482021-02-09 10:28:54 +00004165 auto layerName = fmt::format("Reduce:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004166
4167 armnn::TensorInfo inputTensorInfo0 = ToTensorInfo(inputs[0]);
4168 armnn::TensorInfo inputTensorInfo1 = ToTensorInfo(inputs[1]);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004169
4170 ReduceDescriptor desc;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004171 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
4172 // Get const axis value from model and set it to descriptor.
4173 if (axisBufferPtr != nullptr)
4174 {
Sadik Armagan49bdb792021-02-11 13:57:07 +00004175 std::vector<int32_t> axisData(inputTensorInfo1.GetNumElements());
4176 ::memcpy(axisData.data(), axisBufferPtr->data.data(), inputTensorInfo1.GetNumBytes());
4177
4178 // Convert the axis to unsigned int and remove duplicates.
4179 auto rank = static_cast<int32_t>(inputTensorInfo0.GetNumDimensions());
4180 std::set<unsigned int> uniqueAxis;
4181 std::transform(axisData.begin(),
4182 axisData.end(),
4183 std::inserter(uniqueAxis, uniqueAxis.begin()),
4184 [rank](int i)->unsigned int{
4185 return static_cast<uint32_t>(((i + rank) % rank)); });
4186 desc.m_vAxis.assign(uniqueAxis.begin(), uniqueAxis.end());
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004187 }
Sadik Armagana2747482021-02-09 10:28:54 +00004188 else
4189 {
4190 for (uint32_t i = 0; i < inputTensorInfo0.GetNumDimensions(); ++i)
4191 {
4192 desc.m_vAxis.push_back(i);
4193 }
4194 }
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004195
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004196 desc.m_KeepDims = options->keep_dims;
Sadik Armagana2747482021-02-09 10:28:54 +00004197 desc.m_ReduceOperation = reduceOperation;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004198
4199 // Register a new layer object, Sum.
Mike Kelly0d77ae12022-01-07 17:42:27 +00004200 IConnectableLayer* layer = m_Network->AddReduceLayer(desc, layerName.c_str());
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004201
4202 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
4203 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4204
4205 // Register input tensor to the layer.
4206 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4207 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4208
4209 // Register output tensor to the layer.
4210 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4211 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
4212}
4213
Mike Kelly31dce2b2021-09-01 21:22:37 +01004214void TfLiteParserImpl::ParseLocalResponseNormalization(size_t subgraphIndex, size_t operatorIndex)
4215{
4216 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4217
4218 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4219 CHECK_VALID_SIZE(inputs.size(), 1);
4220
4221 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4222 CHECK_VALID_SIZE(outputs.size(), 1);
4223
4224 auto layerName = fmt::format("LRN:{}:{}", subgraphIndex, operatorIndex);
4225 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
4226
4227 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
4228
4229 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4230 const auto* options = operatorPtr->builtin_options.AsLocalResponseNormalizationOptions();
4231
4232 armnn::NormalizationDescriptor descriptor;
4233 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
4234 descriptor.m_NormChannelType = armnn::NormalizationAlgorithmChannel::Across;
4235 descriptor.m_NormMethodType = armnn::NormalizationAlgorithmMethod::LocalBrightness;
4236 descriptor.m_NormSize = static_cast<uint32_t>(options->radius);
4237 descriptor.m_K = options->bias;
4238 descriptor.m_Alpha = options->alpha;
4239 descriptor.m_Beta = options->beta;
4240
4241 // ArmNN expects normSize to be the full size of the normalization
4242 // window rather than the radius as in TfLite.
4243 descriptor.m_NormSize = 1 + (2 * descriptor.m_NormSize);
4244
4245 IConnectableLayer* layer = m_Network->AddNormalizationLayer(descriptor, layerNameFormatted.c_str());
4246 ARMNN_ASSERT(layer != nullptr);
4247
4248 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
4249 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4250
4251 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4252 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4253
4254 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4255 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4256}
4257
Teresa Charlin28aa6692022-07-12 11:18:44 +01004258void TfLiteParserImpl::ParseAbs(size_t subgraphIndex, size_t operatorIndex)
4259{
4260 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Abs);
4261}
4262
4263void TfLiteParserImpl::ParseExp(size_t subgraphIndex, size_t operatorIndex)
4264{
4265 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Exp);
4266}
4267
4268void TfLiteParserImpl::ParseLog(size_t subgraphIndex, size_t operatorIndex)
4269{
4270 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Log);
4271}
4272
Matthew Sloyaned7fce42021-04-15 20:46:24 +01004273void TfLiteParserImpl::ParseLogicalNot(size_t subgraphIndex, size_t operatorIndex)
4274{
4275 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::LogicalNot);
4276}
4277
4278void TfLiteParserImpl::ParseNeg(size_t subgraphIndex, size_t operatorIndex)
4279{
4280 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Neg);
4281}
4282
4283void TfLiteParserImpl::ParseRsqrt(size_t subgraphIndex, size_t operatorIndex)
4284{
4285 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Rsqrt);
4286}
4287
Teresa Charlin28aa6692022-07-12 11:18:44 +01004288void TfLiteParserImpl::ParseSin(size_t subgraphIndex, size_t operatorIndex)
4289{
4290 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Sin);
4291}
4292
Teresa Charlinf0fce5b2022-05-04 17:24:43 +01004293void TfLiteParserImpl::ParseSqrt(size_t subgraphIndex, size_t operatorIndex)
4294{
4295 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Sqrt);
4296}
4297
Matthew Sloyaned7fce42021-04-15 20:46:24 +01004298void TfLiteParserImpl::ParseElementwiseUnary(size_t subgraphIndex, size_t operatorIndex, UnaryOperation unaryOperation)
4299{
4300 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4301
4302 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4303 CHECK_VALID_SIZE(inputs.size(), 1);
4304
4305 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4306 CHECK_VALID_SIZE(outputs.size(), 1);
4307
4308 std::string layerName = std::string(GetUnaryOperationAsCString(unaryOperation)) + ":{}:{}";
4309 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
4310
4311 ElementwiseUnaryDescriptor desc;
4312 desc.m_Operation = unaryOperation;
4313 IConnectableLayer* layer = m_Network->AddElementwiseUnaryLayer(desc, layerNameFormatted.c_str());
4314 ARMNN_ASSERT(layer != nullptr);
4315
4316 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
4317 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4318
4319 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4320 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4321
4322 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4323 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
4324}
4325
Bruno Goncalves2d0eb862021-07-11 14:10:15 -03004326void TfLiteParserImpl::ParseEqual(size_t subgraphIndex, size_t operatorIndex)
4327{
4328 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::Equal);
4329}
4330
4331void TfLiteParserImpl::ParseNotEqual(size_t subgraphIndex, size_t operatorIndex)
4332{
4333 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::NotEqual);
4334}
4335
4336void TfLiteParserImpl::ParseGreater(size_t subgraphIndex, size_t operatorIndex)
4337{
4338 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::Greater);
4339}
4340
4341void TfLiteParserImpl::ParseGreaterOrEqual(size_t subgraphIndex, size_t operatorIndex)
4342{
4343 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::GreaterOrEqual);
4344}
4345
4346void TfLiteParserImpl::ParseLess(size_t subgraphIndex, size_t operatorIndex)
4347{
4348 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::Less);
4349}
4350
4351void TfLiteParserImpl::ParseLessOrEqual(size_t subgraphIndex, size_t operatorIndex)
4352{
4353 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::LessOrEqual);
4354}
4355
4356void TfLiteParserImpl::ParseComparison(size_t subgraphIndex, size_t operatorIndex,
4357 ComparisonOperation comparisonOperation)
4358{
4359 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4360
4361 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4362 CHECK_VALID_SIZE(inputs.size(), 2);
4363
4364 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4365 CHECK_VALID_SIZE(outputs.size(), 1);
4366
4367 auto layerName = std::string(GetComparisonOperationAsCString(comparisonOperation)) + ":{}:{}";
4368 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
4369
4370 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
4371 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
4372 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerNameFormatted, "Input 0", "Input 1");
4373
4374 ComparisonDescriptor desc;
4375 desc.m_Operation = comparisonOperation;
4376 IConnectableLayer* layer = m_Network->AddComparisonLayer(desc, layerNameFormatted.c_str());
4377 ARMNN_ASSERT(layer != nullptr);
4378
4379 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
4380 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4381
4382 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4383 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
4384
4385 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4386 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4387}
4388
Kevin May7d96b162021-02-03 17:38:41 +00004389armnn::IConnectableLayer* TfLiteParserImpl::AddFusedActivationLayer(armnn::IConnectableLayer* prevLayer,
4390 unsigned int outputSlot,
4391 tflite::ActivationFunctionType activationType)
telsoa01c577f2c2018-08-31 09:22:23 +01004392{
4393 ActivationDescriptor activationDesc;
4394 std::string layerName = prevLayer->GetName();
4395
4396 switch(activationType)
4397 {
4398 case tflite::ActivationFunctionType_NONE:
4399 {
4400 // this is a no-op: return previous layer
4401 return prevLayer;
4402 }
4403 case tflite::ActivationFunctionType_RELU:
4404 {
4405 activationDesc.m_Function = ActivationFunction::ReLu;
4406 layerName += ":RELU";
4407 break;
4408 }
4409 case tflite::ActivationFunctionType_RELU6:
4410 {
4411 activationDesc.m_Function = ActivationFunction::BoundedReLu;
4412 activationDesc.m_A = 6.0f;
4413 activationDesc.m_B = 0.0f;
4414 layerName += ":RELU6";
4415 break;
4416 }
4417 case tflite::ActivationFunctionType_TANH:
4418 {
4419 activationDesc.m_Function = ActivationFunction::TanH;
4420 activationDesc.m_A = 1.0f;
4421 activationDesc.m_B = 1.0f;
4422 layerName += ":TANH";
4423 break;
4424 }
4425
4426 // I only put these here as a reminder what others we could support
4427 case tflite::ActivationFunctionType_RELU_N1_TO_1:
4428 case tflite::ActivationFunctionType_SIGN_BIT:
4429 default:
4430 {
4431 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004432 fmt::format("TfLite parser doesn't suppport fused activation: "
4433 "{}/{} {} ",
4434 activationType,
4435 tflite::EnumNameActivationFunctionType(activationType),
4436 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004437
4438 }
4439 }
4440
4441 IConnectableLayer* activationLayer =
4442 m_Network->AddActivationLayer(activationDesc, layerName.c_str());
4443
4444 auto & prevOutputSlot = prevLayer->GetOutputSlot(outputSlot);
4445 prevOutputSlot.Connect(activationLayer->GetInputSlot(0));
4446 activationLayer->GetOutputSlot(0).SetTensorInfo(prevOutputSlot.GetTensorInfo());
4447 return activationLayer;
4448}
4449
Teresa Charlincdbd40b2022-02-25 13:21:55 +00004450armnn::IConnectableLayer* TfLiteParserImpl::AddFusedFloorLayer(armnn::IConnectableLayer* prevLayer,
4451 unsigned int outputSlot)
4452{
Teresa Charlin725728e2022-05-05 13:33:33 +01004453
4454 auto& prevOutputSlot = prevLayer->GetOutputSlot(outputSlot);
4455 DataType dataType = prevOutputSlot.GetTensorInfo().GetDataType();
4456
4457 if (dataType == DataType::Signed32)
4458 {
4459 return prevLayer;
4460 }
4461
Teresa Charlincdbd40b2022-02-25 13:21:55 +00004462 std::string layerName = prevLayer->GetName();
4463 IConnectableLayer* floorLayer = m_Network->AddFloorLayer(layerName.c_str());
4464
Teresa Charlincdbd40b2022-02-25 13:21:55 +00004465 prevOutputSlot.Connect(floorLayer->GetInputSlot(0));
4466 floorLayer->GetOutputSlot(0).SetTensorInfo(prevOutputSlot.GetTensorInfo());
Teresa Charlin725728e2022-05-05 13:33:33 +01004467
Teresa Charlincdbd40b2022-02-25 13:21:55 +00004468 return floorLayer;
4469}
4470
Mike Kelly0d77ae12022-01-07 17:42:27 +00004471TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromFile(const char* fileName)
telsoa01c577f2c2018-08-31 09:22:23 +01004472{
4473 if (fileName == nullptr)
4474 {
James Ward58dec6b2020-09-11 17:32:44 +01004475 throw InvalidArgumentException(fmt::format("Invalid (null) file name {}",
telsoa01c577f2c2018-08-31 09:22:23 +01004476 CHECK_LOCATION().AsString()));
4477 }
Francis Murtagh532a29d2020-06-29 11:50:01 +01004478 std::error_code errorCode;
4479 fs::path pathToFile(fileName);
4480 if (!fs::exists(pathToFile, errorCode))
telsoa01c577f2c2018-08-31 09:22:23 +01004481 {
James Ward58dec6b2020-09-11 17:32:44 +01004482 //fmt::format() could not be used here (format error)
4483 std::stringstream msg;
4484 msg << "Cannot find the file (" << fileName << ") errorCode: " << errorCode
4485 << " " << CHECK_LOCATION().AsString();
4486
4487 throw FileNotFoundException(msg.str());
telsoa01c577f2c2018-08-31 09:22:23 +01004488 }
4489 std::ifstream file(fileName, std::ios::binary);
4490 std::string fileContent((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
4491 return LoadModelFromBinary(reinterpret_cast<const uint8_t *>(fileContent.c_str()),
4492 fileContent.size());
4493}
4494
Mike Kelly0d77ae12022-01-07 17:42:27 +00004495TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromBinary(const uint8_t* binaryContent, size_t len)
telsoa01c577f2c2018-08-31 09:22:23 +01004496{
4497 if (binaryContent == nullptr)
4498 {
James Ward58dec6b2020-09-11 17:32:44 +01004499 throw InvalidArgumentException(fmt::format("Invalid (null) binary content {}",
telsoa01c577f2c2018-08-31 09:22:23 +01004500 CHECK_LOCATION().AsString()));
4501 }
4502 flatbuffers::Verifier verifier(binaryContent, len);
4503 if (verifier.VerifyBuffer<tflite::Model>() == false)
4504 {
4505 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004506 fmt::format("Buffer doesn't conform to the expected Tensorflow Lite "
4507 "flatbuffers format. size:{} {}",
4508 len,
4509 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004510 }
4511 return tflite::UnPackModel(binaryContent);
4512}
4513
Mike Kelly0d77ae12022-01-07 17:42:27 +00004514TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetInputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00004515 size_t subgraphIndex,
4516 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004517{
4518 CHECK_MODEL(model, subgraphIndex, operatorIndex);
4519
Mike Kelly0d77ae12022-01-07 17:42:27 +00004520 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4521 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004522
4523 size_t inputCount = operatorPtr->inputs.size();
mathad01c21025d2021-04-26 10:09:37 +01004524 TensorRawPtrVector result;
Mike Kelly0d77ae12022-01-07 17:42:27 +00004525 for (size_t i = 0; i < inputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004526 {
mathad01c21025d2021-04-26 10:09:37 +01004527 // If the input location is -1 then assume input is turned off.
4528 if (operatorPtr->inputs[i] == -1)
4529 {
4530 continue;
4531 }
4532 else
4533 {
4534 uint32_t inputId = CHECKED_NON_NEGATIVE(operatorPtr->inputs[i]);
4535 result.push_back(subgraphPtr->tensors[inputId].get());
4536 }
telsoa01c577f2c2018-08-31 09:22:23 +01004537 }
4538 return result;
4539}
4540
Mike Kelly0d77ae12022-01-07 17:42:27 +00004541TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetOutputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00004542 size_t subgraphIndex,
4543 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004544{
4545 CHECK_MODEL(model, subgraphIndex, operatorIndex);
4546
Mike Kelly0d77ae12022-01-07 17:42:27 +00004547 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4548 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004549
4550 size_t outputCount = operatorPtr->outputs.size();
4551 TensorRawPtrVector result(outputCount);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004552 for (size_t i = 0; i < outputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004553 {
4554 uint32_t outputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[i]);
4555 CHECK_TENSOR(model, subgraphIndex, outputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01004556 result[i] = subgraphPtr->tensors[outputId].get();
telsoa01c577f2c2018-08-31 09:22:23 +01004557 }
4558 return result;
4559}
4560
Mike Kelly0d77ae12022-01-07 17:42:27 +00004561TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphInputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00004562 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004563{
4564 CHECK_SUBGRAPH(model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004565 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004566
Derek Lambertiff05cc52019-04-26 13:05:17 +01004567 size_t inputCount = subgraphPtr->inputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01004568 TensorIdRawPtrVector result(inputCount);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004569 for (size_t i = 0; i < inputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004570 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01004571 uint32_t inputId = CHECKED_NON_NEGATIVE(subgraphPtr->inputs[i]);
telsoa01c577f2c2018-08-31 09:22:23 +01004572 CHECK_TENSOR(model, subgraphIndex, inputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01004573 result[i] = std::make_pair(inputId, subgraphPtr->tensors[inputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01004574 }
4575 return result;
4576}
4577
Mike Kelly0d77ae12022-01-07 17:42:27 +00004578TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphOutputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00004579 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004580{
4581 CHECK_SUBGRAPH(model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004582 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004583
Derek Lambertiff05cc52019-04-26 13:05:17 +01004584 size_t outputCount = subgraphPtr->outputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01004585 TensorIdRawPtrVector result(outputCount);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004586 for (size_t i = 0; i < outputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004587 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01004588 uint32_t outputId = CHECKED_NON_NEGATIVE(subgraphPtr->outputs[i]);
4589 result[i] = std::make_pair(outputId, subgraphPtr->tensors[outputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01004590 }
4591 return result;
4592}
4593
Kevin May7d96b162021-02-03 17:38:41 +00004594std::vector<int32_t>& TfLiteParserImpl::GetInputTensorIds(const ModelPtr& model,
4595 size_t subgraphIndex,
4596 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004597{
4598 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004599 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4600 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004601 return operatorPtr->inputs;
4602}
4603
Kevin May7d96b162021-02-03 17:38:41 +00004604std::vector<int32_t>& TfLiteParserImpl::GetOutputTensorIds(const ModelPtr& model,
4605 size_t subgraphIndex,
4606 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004607{
4608 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004609 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4610 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004611 return operatorPtr->outputs;
4612}
4613
Kevin May7d96b162021-02-03 17:38:41 +00004614void TfLiteParserImpl::RegisterInputSlots(size_t subgraphIndex,
4615 size_t operatorIndex,
4616 IConnectableLayer* layer,
Finn Williamsd4fa5452021-03-01 12:31:41 +00004617 const std::vector<unsigned int>& tensorIndexes,
4618 unsigned int startingSlotIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004619{
4620 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01004621 ARMNN_ASSERT(layer != nullptr);
Matthew Sloyan81beae32021-07-13 19:46:11 +01004622
Finn Williamsd4fa5452021-03-01 12:31:41 +00004623 if (tensorIndexes.size() + startingSlotIndex != layer->GetNumInputSlots())
telsoa01c577f2c2018-08-31 09:22:23 +01004624 {
4625 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004626 fmt::format("The number of tensor inputs ({}) does not match the number expected ({})"
4627 " for subgraph:{} operator index:{} {}",
4628 tensorIndexes.size(),
4629 layer->GetNumInputSlots(),
4630 subgraphIndex,
4631 operatorIndex,
4632 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004633 }
4634
Finn Williamsd4fa5452021-03-01 12:31:41 +00004635 for (unsigned int index = 0; index < tensorIndexes.size() ; ++index)
telsoa01c577f2c2018-08-31 09:22:23 +01004636 {
Finn Williamsd4fa5452021-03-01 12:31:41 +00004637 unsigned int tensorIndex = tensorIndexes[index];
4638 armnn::IInputSlot* slot = &(layer->GetInputSlot(startingSlotIndex + index));
telsoa01c577f2c2018-08-31 09:22:23 +01004639 RegisterConsumerOfTensor(subgraphIndex, tensorIndex, slot);
4640 }
4641}
4642
Kevin May7d96b162021-02-03 17:38:41 +00004643void TfLiteParserImpl::RegisterOutputSlots(size_t subgraphIndex,
4644 size_t operatorIndex,
4645 IConnectableLayer* layer,
4646 const std::vector<unsigned int>& tensorIndexes)
telsoa01c577f2c2018-08-31 09:22:23 +01004647{
4648 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01004649 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01004650 if (tensorIndexes.size() != layer->GetNumOutputSlots())
4651 {
4652 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004653 fmt::format("The number of tensor outputs ({}) does not match the number expected ({})"
4654 " for subgraph:{} operator index:{} {}",
4655 tensorIndexes.size(),
4656 layer->GetNumOutputSlots(),
4657 subgraphIndex,
4658 operatorIndex,
4659 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004660 }
4661
4662 for (unsigned int slotIndex = 0; slotIndex < layer->GetNumOutputSlots(); ++slotIndex)
4663 {
4664 unsigned int tensorIndex = tensorIndexes[slotIndex];
4665 armnn::IOutputSlot* slot = &(layer->GetOutputSlot(slotIndex));
4666 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
4667 }
4668}
4669
Kevin May7d96b162021-02-03 17:38:41 +00004670void TfLiteParserImpl::SetupInputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004671{
4672 CHECK_SUBGRAPH(m_Model, subgraphIndex);
4673
4674 auto inputs = GetSubgraphInputs(m_Model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004675 for (auto const& tensorIdAndPtr : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004676 {
4677 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
4678 IConnectableLayer* layer =
4679 m_Network->AddInputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
4680
4681 auto tensorInfo = ToTensorInfo(tensorIdAndPtr.second);
4682 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
4683
4684 RegisterOutputSlots(subgraphIndex,
4685 VIRTUAL_OPERATOR_ID,
4686 layer,
4687 { static_cast<uint32_t>(tensorIdAndPtr.first) });
4688 }
4689}
4690
Kevin May7d96b162021-02-03 17:38:41 +00004691void TfLiteParserImpl::SetupOutputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004692{
4693 CHECK_SUBGRAPH(m_Model, subgraphIndex);
4694
4695 auto outputs = GetSubgraphOutputs(m_Model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004696 for (auto const& tensorIdAndPtr : outputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004697 {
4698 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
4699 IConnectableLayer* layer =
4700 m_Network->AddOutputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
4701
4702 RegisterInputSlots(subgraphIndex,
4703 VIRTUAL_OPERATOR_ID,
4704 layer,
4705 { static_cast<uint32_t>(tensorIdAndPtr.first) });
4706 }
4707}
4708
Mike Kelly5880b912022-01-28 16:18:54 +00004709void TfLiteParserImpl::SetupConstantLayers(size_t subgraph)
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004710{
Mike Kelly5880b912022-01-28 16:18:54 +00004711 CHECK_SUBGRAPH(m_Model, subgraph);
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004712
Mike Kelly5880b912022-01-28 16:18:54 +00004713 const auto & subgraphPtr = m_Model->subgraphs[subgraph];
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004714 for (unsigned int subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
4715 {
4716 for (unsigned int tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
4717 {
4718 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot == nullptr &&
4719 m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size() > 0)
4720 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01004721 TensorRawPtr tensorPtr = subgraphPtr->tensors[tensorIndex].get();
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004722
Mike Kelly5880b912022-01-28 16:18:54 +00004723 if (IsConstTensor(tensorPtr))
Matthew Sloyan81beae32021-07-13 19:46:11 +01004724 {
4725 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
Mike Kelly5880b912022-01-28 16:18:54 +00004726 armnn::DataType dataType = tensorInfo.GetDataType();
4727
4728 if (std::find(m_ConstantsToDequantize.begin(), m_ConstantsToDequantize.end(), tensorPtr->buffer)
4729 != m_ConstantsToDequantize.end())
4730 {
4731 dataType = DataType::Float32;
4732 }
4733 auto tensorAndData = CreateConstTensorNonPermuted(tensorPtr, tensorInfo, dataType);
4734
4735 std::string layerName = fmt::format("Constant:{}", tensorPtr->name);
4736 IConnectableLayer *layer = m_Network->AddConstantLayer(tensorAndData.first, layerName.c_str());
4737
4738 layer->GetOutputSlot(0).SetTensorInfo(tensorAndData.first.GetInfo());
4739 RegisterOutputSlots(subgraphIndex,
4740 VIRTUAL_OPERATOR_ID,
4741 layer,
4742 { tensorIndex });
4743 }
4744 else if (ShouldConstantTensorBeCreated(tensorIndex))
4745 {
4746 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
4747 armnn::DataType dataType = tensorInfo.GetDataType();
4748
4749 if (std::find(m_ConstantsToDequantize.begin(), m_ConstantsToDequantize.end(), tensorPtr->buffer)
4750 != m_ConstantsToDequantize.end())
4751 {
4752 dataType = DataType::Float32;
4753 }
4754 // Make sure isConstant flag is set.
4755 tensorInfo.SetConstant();
4756 tensorInfo.SetDataType(dataType);
4757
4758 auto tensorAndData = ConstTensor(tensorInfo, std::vector<uint8_t>(tensorInfo.GetNumBytes()));
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004759
Matthew Sloyan81beae32021-07-13 19:46:11 +01004760 std::string layerName = fmt::format("Constant:{}", tensorPtr->name);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004761 IConnectableLayer* layer = m_Network->AddConstantLayer(tensorAndData, layerName.c_str());
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004762
Matthew Sloyan81beae32021-07-13 19:46:11 +01004763 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
4764 RegisterOutputSlots(subgraphIndex,
4765 VIRTUAL_OPERATOR_ID,
4766 layer,
Mike Kelly5880b912022-01-28 16:18:54 +00004767 {tensorIndex});
Matthew Sloyan81beae32021-07-13 19:46:11 +01004768 }
4769 else
4770 {
4771 throw ParseException(
4772 fmt::format("Invalid Tensor: Tensor should be constant. {}",
4773 CHECK_LOCATION().AsString()));
4774 }
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004775 }
4776 }
4777 }
4778}
4779
telsoa01c577f2c2018-08-31 09:22:23 +01004780// example usage: BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Kevin May7d96b162021-02-03 17:38:41 +00004781TfLiteParserImpl::BufferRawPtr TfLiteParserImpl::GetBuffer(const ModelPtr& model, size_t bufferIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004782{
4783 CHECK_BUFFER(model, bufferIndex);
4784 return model->buffers[bufferIndex].get();
4785}
4786
Matteo Martincigh747ef822018-12-18 09:26:39 +00004787template<typename T>
Kevin May7d96b162021-02-03 17:38:41 +00004788std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
4789TfLiteParserImpl::CreateConstTensorAndStoreData(TfLiteParserImpl::BufferRawPtr bufferPtr,
4790 TfLiteParserImpl::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +00004791 armnn::TensorInfo& tensorInfo,
4792 armnn::Optional<armnn::PermutationVector&> permutationVector)
4793{
Matthew Sloyan81beae32021-07-13 19:46:11 +01004794 // Make sure isConstant flag is set.
4795 tensorInfo.SetConstant();
4796
Matteo Martincigh747ef822018-12-18 09:26:39 +00004797 auto constData = CreateConstTensorImpl<T>(bufferPtr,
4798 tensorPtr,
4799 tensorInfo,
4800 permutationVector);
Kevin May7d96b162021-02-03 17:38:41 +00004801 TfLiteParserImpl::SupportedDataStorage storage(std::move(constData.second));
Matteo Martincigh747ef822018-12-18 09:26:39 +00004802 return std::make_pair(constData.first, std::move(storage));
4803}
4804
Mike Kelly5880b912022-01-28 16:18:54 +00004805bool TfLiteParserImpl::ShouldConstantTensorBeCreated(unsigned int tensorIndex)
4806{
4807 // If the TensorIndex appears in the list of ConstantsToBeCreated then return true
4808 return (std::find(m_ConstantsToBeCreated.begin(), m_ConstantsToBeCreated.end(), tensorIndex)
4809 != m_ConstantsToBeCreated.end());
4810}
4811
Finn Williamsd4fa5452021-03-01 12:31:41 +00004812bool TfLiteParserImpl::IsConstTensor(TensorRawPtr tensorPtr)
4813{
4814 CHECK_TENSOR_PTR(tensorPtr);
mathad01bf7edb62021-04-20 16:12:45 +01004815 bool isConst = true;
4816
4817 auto buffer = GetBuffer(m_Model, tensorPtr->buffer);
4818 if (buffer->data.size() == 0)
4819 {
4820 isConst = false;
4821 }
4822
4823 return isConst;
Finn Williamsd4fa5452021-03-01 12:31:41 +00004824}
4825
Kevin May7d96b162021-02-03 17:38:41 +00004826std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
Finn Williamsd4fa5452021-03-01 12:31:41 +00004827TfLiteParserImpl::CreateConstTensorPermuted(TensorRawPtr tensorPtr,
4828 armnn::TensorInfo& tensorInfo,
4829 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +01004830{
4831 CHECK_TENSOR_PTR(tensorPtr);
4832 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
4833 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
4834
Matthew Sloyan81beae32021-07-13 19:46:11 +01004835 // Make sure isConstant flag is set.
4836 tensorInfo.SetConstant();
4837
telsoa01c577f2c2018-08-31 09:22:23 +01004838 switch (tensorInfo.GetDataType())
4839 {
4840 case armnn::DataType::Float32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00004841 return CreateConstTensorAndStoreData<float>(bufferPtr,
4842 tensorPtr,
4843 tensorInfo,
4844 permutationVector);
Derek Lambertif90c56d2020-01-10 17:14:08 +00004845 case armnn::DataType::QAsymmU8:
Matteo Martincigh747ef822018-12-18 09:26:39 +00004846 return CreateConstTensorAndStoreData<uint8_t>(bufferPtr,
4847 tensorPtr,
4848 tensorInfo,
4849 permutationVector);
Keith Davisd305e1a2020-01-22 11:57:54 +00004850 case armnn::DataType::QSymmS8:
4851 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
4852 tensorPtr,
4853 tensorInfo,
4854 permutationVector);
Keith Davis67e6c542020-02-19 10:08:33 +00004855 case armnn::DataType::QAsymmS8:
4856 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
4857 tensorPtr,
4858 tensorInfo,
4859 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01004860 case armnn::DataType::Signed32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00004861 return CreateConstTensorAndStoreData<int32_t>(bufferPtr,
4862 tensorPtr,
4863 tensorInfo,
4864 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01004865 default:
4866 {
4867 std::stringstream errString;
4868 errString << "Unexpected datatype when creating const tensor: "
4869 << armnn::GetDataTypeName(tensorInfo.GetDataType())
4870 << " shape:" << tensorInfo.GetShape()
4871 << CHECK_LOCATION().AsString();
4872 throw ParseException(errString.str());
4873 }
4874 }
4875}
4876
Finn Williamsd4fa5452021-03-01 12:31:41 +00004877armnn::ConstTensor TfLiteParserImpl::CreateConstTensorNonPermuted(TensorRawPtr tensorPtr,
4878 armnn::TensorInfo& tensorInfo)
4879{
4880 CHECK_TENSOR_PTR(tensorPtr);
4881 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
4882 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
4883
Matthew Sloyan81beae32021-07-13 19:46:11 +01004884 // Make sure isConstant flag is set.
4885 tensorInfo.SetConstant();
4886
Finn Williamsd4fa5452021-03-01 12:31:41 +00004887 return ConstTensor(tensorInfo, bufferPtr->data.data());
4888}
4889
Mike Kelly5880b912022-01-28 16:18:54 +00004890std::pair<armnn::ConstTensor, std::unique_ptr<float[]>>
4891TfLiteParserImpl::CreateConstTensorNonPermuted(TensorRawPtr tensorPtr,
4892 armnn::TensorInfo& tensorInfo,
4893 armnn::DataType inputDataType)
4894{
4895 CHECK_TENSOR_PTR(tensorPtr);
4896 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
4897 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
4898
4899 // Make sure isConstant flag is set.
4900 tensorInfo.SetConstant();
4901
Mike Kelly0506ef02023-01-03 16:29:44 +00004902 if (inputDataType == DataType::Float32 && tensorInfo.GetDataType() != DataType::Float32)
Mike Kelly5880b912022-01-28 16:18:54 +00004903 {
Mike Kelly0506ef02023-01-03 16:29:44 +00004904 try
4905 {
4906 TensorInfo constTensorInfo(tensorInfo.GetShape(), DataType::Float32, 0.0f, 0, true);
4907 std::unique_ptr<float[]> data = armnnUtils::ToFloatArray(bufferPtr->data, tensorInfo);
4908 return std::make_pair(ConstTensor(constTensorInfo, data.get()), std::move(data));
4909 }
Cathal Corbett9c843c32023-01-09 17:51:37 +00004910 catch (InvalidArgumentException&)
Mike Kelly0506ef02023-01-03 16:29:44 +00004911 {
4912 throw ParseException(
4913 fmt::format("Unsupported input/weights combination: Input {} not supported with Weights {}",
4914 GetDataTypeName(DataType::Float32),
4915 GetDataTypeName(tensorInfo.GetDataType()),
4916 CHECK_LOCATION().AsString()));
4917 }
Mike Kelly5880b912022-01-28 16:18:54 +00004918 }
4919 else
4920 {
4921 return std::make_pair(ConstTensor(tensorInfo, bufferPtr->data.data()), std::unique_ptr<float[]>());
4922 }
4923}
4924
4925std::pair<armnn::ConstTensor*, std::unique_ptr<float[]>>
4926TfLiteParserImpl::CreateConstTensorPtr(TensorRawPtr tensorPtr, armnn::TensorInfo& inputTensorInfo)
4927{
4928 CHECK_TENSOR_PTR(tensorPtr);
4929 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
4930 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
4931 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
4932
4933 // Make sure isConstant flag is set.
4934 tensorInfo.SetConstant();
4935
4936 if (inputTensorInfo.GetDataType() == DataType::Float32 && tensorInfo.GetDataType() != DataType::Float32)
4937 {
Mike Kelly0506ef02023-01-03 16:29:44 +00004938 try
4939 {
4940 TensorInfo constTensorInfo(tensorInfo.GetShape(), DataType::Float32, 0.0f, 0, true);
4941 std::unique_ptr<float[]> data = armnnUtils::ToFloatArray(bufferPtr->data, tensorInfo);
4942 return std::make_pair(new ConstTensor(constTensorInfo, data.get()), std::move(data));
4943 }
Cathal Corbett9c843c32023-01-09 17:51:37 +00004944 catch (InvalidArgumentException&)
Mike Kelly0506ef02023-01-03 16:29:44 +00004945 {
4946 throw ParseException(
4947 fmt::format("Unsupported input/weights combination: Input {} not supported with Weights {}",
4948 GetDataTypeName(DataType::Float32),
4949 GetDataTypeName(tensorInfo.GetDataType()),
4950 CHECK_LOCATION().AsString()));
4951 }
Mike Kelly5880b912022-01-28 16:18:54 +00004952 }
4953 else
4954 {
4955 return std::make_pair(new ConstTensor(tensorInfo, bufferPtr->data.data()), std::unique_ptr<float[]>());
4956 }
4957}
4958
Kevin May7d96b162021-02-03 17:38:41 +00004959BindingPointInfo TfLiteParserImpl::GetNetworkInputBindingInfo(size_t subgraphId,
4960 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01004961{
4962 CHECK_SUBGRAPH(m_Model, subgraphId);
4963 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004964 for (auto const& input : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004965 {
4966 if (input.second->name == name)
4967 {
4968 auto bindingId = GenerateLayerBindingId(subgraphId, input.first);
Colm Donelan4bc993b2021-11-09 20:39:10 +00004969 auto inputTensorInfo = ToTensorInfo(input.second);
4970 // Input tensors are always treated as constant tensors during network execution.
4971 inputTensorInfo.SetConstant(true);
4972 return std::make_pair(bindingId, inputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01004973 }
4974 }
4975
4976 std::stringstream bindings;
Mike Kelly0d77ae12022-01-07 17:42:27 +00004977 for (auto const& input : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004978 {
4979 bindings << "'" << input.second->name << "' ";
4980 }
4981
4982 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004983 fmt::format("No input binding found for subgraph:{} and name:{}. "
4984 "Possible inputs are: [{}] {}",
4985 subgraphId,
4986 name,
4987 bindings.str(),
4988 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004989}
4990
Kevin May7d96b162021-02-03 17:38:41 +00004991BindingPointInfo TfLiteParserImpl::GetNetworkOutputBindingInfo(size_t subgraphId,
4992 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01004993{
4994 CHECK_SUBGRAPH(m_Model, subgraphId);
4995 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00004996 for (unsigned int i = 0; i < outputs.size(); ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004997 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00004998 auto const output = outputs[i];
telsoa01c577f2c2018-08-31 09:22:23 +01004999 if (output.second->name == name)
5000 {
5001 auto bindingId = GenerateLayerBindingId(subgraphId, output.first);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00005002 std::vector<unsigned int> shape = m_OverridenOutputShapes.size() > 0 ?
5003 m_OverridenOutputShapes[i] : AsUnsignedVector(output.second->shape);
5004 return std::make_pair(bindingId, ToTensorInfo(output.second, shape));
telsoa01c577f2c2018-08-31 09:22:23 +01005005 }
5006 }
5007
5008 std::stringstream bindings;
Mike Kelly0d77ae12022-01-07 17:42:27 +00005009 for (auto const& output : outputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005010 {
5011 bindings << "'" << output.second->name << "' ";
5012 }
5013
5014 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01005015 fmt::format("No output binding found for subgraph:{} and name:{}. "
5016 "Possible outputs are: [{}] {}",
5017 subgraphId,
5018 name,
5019 bindings.str(),
5020 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01005021}
5022
Kevin May7d96b162021-02-03 17:38:41 +00005023size_t TfLiteParserImpl::GetSubgraphCount() const
telsoa01c577f2c2018-08-31 09:22:23 +01005024{
5025 return m_Model->subgraphs.size();
5026}
5027
Kevin May7d96b162021-02-03 17:38:41 +00005028std::vector<std::string> TfLiteParserImpl::GetSubgraphInputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01005029{
5030 CHECK_SUBGRAPH(m_Model, subgraphId);
5031 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
5032 std::vector<std::string> result;
5033 result.reserve(inputs.size());
Mike Kelly0d77ae12022-01-07 17:42:27 +00005034 for (auto const& input : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005035 {
5036 result.push_back(input.second->name);
5037 }
5038 return result;
5039}
5040
Kevin May7d96b162021-02-03 17:38:41 +00005041std::vector<std::string> TfLiteParserImpl::GetSubgraphOutputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01005042{
5043 CHECK_SUBGRAPH(m_Model, subgraphId);
5044 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
5045 std::vector<std::string> result;
5046 result.reserve(outputs.size());
Mike Kelly0d77ae12022-01-07 17:42:27 +00005047 for (auto const& output : outputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005048 {
5049 result.push_back(output.second->name);
5050 }
5051 return result;
5052}
5053
Matthew Sloyanac001ee2021-02-03 10:43:04 +00005054const std::string TfLiteParserImpl::GetVersion()
5055{
5056 return TFLITE_PARSER_VERSION;
5057}
5058
Mike Kelly0d77ae12022-01-07 17:42:27 +00005059TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<float[]>&& data)
telsoa01c577f2c2018-08-31 09:22:23 +01005060: m_FloatData(std::move(data))
5061, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00005062, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01005063, m_Int32Data(nullptr)
5064{
5065}
5066
Mike Kelly0d77ae12022-01-07 17:42:27 +00005067TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<uint8_t[]>&& data)
telsoa01c577f2c2018-08-31 09:22:23 +01005068: m_FloatData(nullptr)
5069, m_Uint8Data(std::move(data))
Keith Davisd305e1a2020-01-22 11:57:54 +00005070, m_Int8Data(nullptr)
5071, m_Int32Data(nullptr)
5072{
5073}
5074
Mike Kelly0d77ae12022-01-07 17:42:27 +00005075TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int8_t[]>&& data)
Keith Davisd305e1a2020-01-22 11:57:54 +00005076: m_FloatData(nullptr)
5077, m_Uint8Data(nullptr)
5078, m_Int8Data(std::move(data))
telsoa01c577f2c2018-08-31 09:22:23 +01005079, m_Int32Data(nullptr)
5080{
5081}
5082
Mike Kelly0d77ae12022-01-07 17:42:27 +00005083TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int32_t[]>&& data)
telsoa01c577f2c2018-08-31 09:22:23 +01005084: m_FloatData(nullptr)
5085, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00005086, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01005087, m_Int32Data(std::move(data))
5088{
5089}
5090
5091} // armnnTfLiteParser