blob: b3f5b560eba4a3e4220597c4bd04082a5087e0d2 [file] [log] [blame]
telsoa01c577f2c2018-08-31 09:22:23 +01001//
Mike Kelly04d82292023-01-19 18:29:40 +00002// Copyright © 2017-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{
telsoa01c577f2c2018-08-31 09:22:23 +0100190 // the tensor index is the only one to check here
191 if (tensorIndex >= model->subgraphs[subgraphIndex]->tensors.size())
192 {
193 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100194 fmt::format("{} was called with an invalid tensor index. "
195 "subgraph:{} tensor:{} at {}",
196 location.m_Function,
197 subgraphIndex,
198 tensorIndex,
199 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100200 }
201}
202
203#define CHECK_TENSOR(MODEL, SUBGRAPH_INDEX, TENSOR_INDEX) \
204 CheckTensor(MODEL, SUBGRAPH_INDEX, TENSOR_INDEX, CHECK_LOCATION())
205
Kevin May7d96b162021-02-03 17:38:41 +0000206void CheckTensorPtr(TfLiteParserImpl::TensorRawPtr rawPtr,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000207 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100208{
209 if (rawPtr == nullptr)
210 {
211 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100212 fmt::format("{} was called with a null tensor pointer at {}", location.m_Function, location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100213 }
214}
215
216#define CHECK_TENSOR_PTR(TENSOR_PTR) \
217 CheckTensorPtr(TENSOR_PTR, CHECK_LOCATION())
218
Mike Kelly0d77ae12022-01-07 17:42:27 +0000219void CheckBuffer(const TfLiteParserImpl::ModelPtr& model,
telsoa01c577f2c2018-08-31 09:22:23 +0100220 size_t bufferIndex,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000221 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100222{
223 if (model.get() == nullptr)
224 {
225 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100226 fmt::format("{} was called with invalid (null) model. "
227 "Possible reason is that the model is not yet loaded and Unpack(ed). "
228 "buffer:{} at {}",
229 location.m_Function,
230 bufferIndex,
231 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100232 }
233 else if (bufferIndex >= model->buffers.size())
234 {
235 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100236 fmt::format("{} was called with an invalid buffer index. "
237 "buffer index:{} at {}",
238 location.m_Function,
239 bufferIndex,
240 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100241 }
242 else if (model->buffers[bufferIndex].get() == nullptr)
243 {
244 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100245 fmt::format("The buffer #{} is null. {}",
246 bufferIndex,
247 location.AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100248 }
249}
250
251#define CHECK_BUFFER(MODEL, BUFFER_INDEX) \
252 CheckBuffer(MODEL, BUFFER_INDEX, CHECK_LOCATION())
253
Kevin May7d96b162021-02-03 17:38:41 +0000254void CheckBufferSize(TfLiteParserImpl::BufferRawPtr bufferPtr,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000255 const armnn::TensorInfo& tensorInfo,
telsoa01c577f2c2018-08-31 09:22:23 +0100256 uint32_t bufferId,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000257 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100258{
259 if (bufferPtr == nullptr)
260 {
261 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100262 fmt::format("BufferPtr is null for buffer:{}. {}",
263 bufferId,
264 location.AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100265 }
266 else if(tensorInfo.GetNumElements() > bufferPtr->data.size() ||
267 tensorInfo.GetNumBytes() > bufferPtr->data.size())
268 {
269 std::stringstream ss;
270 ss << "Buffer #" << bufferId << " has " << bufferPtr->data.size() << " bytes. "
271 << "For tensor: " << tensorInfo.GetShape()
272 << " expecting: " << tensorInfo.GetNumBytes() << " bytes and "
273 << tensorInfo.GetNumElements() << " elements. " << location.AsString();
274 throw ParseException(ss.str());
275 }
276}
277
Mike Kelly0d77ae12022-01-07 17:42:27 +0000278
279tflite::BuiltinOperator GetOpCode(const TfLiteParserImpl::ModelPtr& model, size_t subgraphIndex, size_t operatorIndex)
280{
281 const auto& operatorPtr = model->subgraphs[subgraphIndex]->operators[operatorIndex];
282 auto opcodeIndex = operatorPtr->opcode_index;
283
284// work around the introduction of the deprecated_builtin_code introduced in 2.4 in a backwards compatible manner
285#if defined(ARMNN_POST_TFLITE_2_3)
286 auto opcode = std::max(model->operator_codes[opcodeIndex]->builtin_code,
287 static_cast<tflite::BuiltinOperator>(model->operator_codes[opcodeIndex]->deprecated_builtin_code));
288#else
289 auto opcode = model->operator_codes[opcodeIndex]->builtin_code;
290#endif
291 return opcode;
292}
293
294std::vector<unsigned int> GetUIntBuffer(armnn::TensorInfo info,
295 const TfLiteParserImpl::ModelPtr& model,
296 size_t bufferIndex)
297{
298 TfLiteParserImpl::BufferRawPtr bufferPtr = TfLiteParserImpl::GetBuffer(model, bufferIndex);
299 std::vector<unsigned int> buffer(info.GetNumElements());
300
301 if (info.GetDataType() == DataType::Signed32)
302 {
303 ::memcpy(buffer.data(), bufferPtr->data.data(), bufferPtr->data.size());
304 }
305 else if (info.GetDataType() == DataType::Signed64)
306 {
307 std::vector<uint64_t> uint64Buffer(info.GetNumElements());
308 ::memcpy(uint64Buffer.data(), bufferPtr->data.data(), bufferPtr->data.size());
309 buffer.assign(std::begin(uint64Buffer), std::end(uint64Buffer));
310 }
Mike Kelly0506ef02023-01-03 16:29:44 +0000311 else
312 {
313 CheckLocation location = CHECK_LOCATION();
314 throw ParseException(
315 fmt::format("Unsupported data type for uint buffer {}, only Signed 32 or Signed 64 are supported. {}",
316 GetDataTypeName(info.GetDataType()),
317 location.AsString()));
318 }
Mike Kelly0d77ae12022-01-07 17:42:27 +0000319 return buffer;
320}
321
telsoa01c577f2c2018-08-31 09:22:23 +0100322#define CHECK_BUFFER_SIZE(BUFFER_PTR, TENSOR_INFO, BUFFER_ID) \
323 CheckBufferSize(BUFFER_PTR, TENSOR_INFO, BUFFER_ID, CHECK_LOCATION())
324
325bool IsActivationSupported(tflite::ActivationFunctionType activationType)
326{
327 switch(activationType)
328 {
329 case tflite::ActivationFunctionType_NONE:
330 case tflite::ActivationFunctionType_RELU:
331 case tflite::ActivationFunctionType_RELU6:
332 case tflite::ActivationFunctionType_TANH:
333 {
334 return true;
335 }
336 default:
337 {
338 return false;
339 }
340 }
341}
342
343#define CHECK_SUPPORTED_FUSED_ACTIVATION(OPTION, SUBGRAPH_INDEX, OPERATOR_INDEX) \
344 do { \
345 if (IsActivationSupported(OPTION->fused_activation_function) == false) \
346 { \
347 throw ParseException( \
Mike Kelly377fb212023-01-10 15:55:28 +0000348 fmt::format("TfLite parser doesn't support fused activation: " \
James Ward58dec6b2020-09-11 17:32:44 +0100349 "{}/{} in {} subgraph:{} operator:{} at {}", \
350 OPTION->fused_activation_function, \
351 tflite::EnumNameActivationFunctionType(\
352 OPTION->fused_activation_function), \
353 __func__, \
354 SUBGRAPH_INDEX, \
355 OPERATOR_INDEX, \
356 CHECK_LOCATION().FileLine())); \
telsoa01c577f2c2018-08-31 09:22:23 +0100357 } \
358 } while(false)
359
360
Mike Kelly0d77ae12022-01-07 17:42:27 +0000361std::vector<unsigned int> AsUnsignedVector(const std::vector<int32_t>& in)
telsoa01c577f2c2018-08-31 09:22:23 +0100362{
363 std::vector<unsigned int> result;
364 result.reserve(in.size());
Mike Kelly0d77ae12022-01-07 17:42:27 +0000365 for (auto& i : in)
telsoa01c577f2c2018-08-31 09:22:23 +0100366 {
mathad01c21025d2021-04-26 10:09:37 +0100367 // If the location of the input data is -1 then the input should be ignored.
368 if (i == -1)
369 {
370 continue;
371 }
telsoa01c577f2c2018-08-31 09:22:23 +0100372 result.push_back(CHECKED_NON_NEGATIVE(i));
373 }
374 return result;
375}
376
Mike Kelly5880b912022-01-28 16:18:54 +0000377bool IsOptionalOperandPresent(int input)
378{
379 return (input >= 0);
380}
381
telsoa01c577f2c2018-08-31 09:22:23 +0100382void CalcPadding(uint32_t inputSize,
383 uint32_t filterSize,
384 uint32_t stride,
Pablo Tellof0bd6832019-04-26 17:58:13 +0100385 uint32_t dilation,
telsoa01c577f2c2018-08-31 09:22:23 +0100386 uint32_t& paddingFront,
387 uint32_t& paddingBack,
388 tflite::Padding padding)
389{
390 paddingFront = 0;
391 paddingBack = 0;
392 if (padding == tflite::Padding_SAME)
393 {
394 uint32_t outputSize = (inputSize + stride - 1) / stride;
Pablo Tellof0bd6832019-04-26 17:58:13 +0100395 uint32_t dilatedSize = filterSize + (dilation - 1) * (filterSize - 1);
396 uint32_t temp = (outputSize - 1) * stride + dilatedSize;
telsoa01c577f2c2018-08-31 09:22:23 +0100397 if (temp > inputSize)
398 {
399 paddingFront = (temp - inputSize) / 2;
400 paddingBack = (temp - inputSize) - paddingFront;
401 }
402 }
403}
404
Teresa Charlin024ef0b2023-04-26 11:19:03 +0100405// Function that calculates explicit padding when the output shape is known.
406// At the moment the output is only given as an input parameter in Transpose Convolution,
407// not in Convolution and Depthwise Convolution
408void CalcPadding(uint32_t inputSize,
409 uint32_t filterSize,
410 uint32_t stride,
411 uint32_t dilation,
412 uint32_t& paddingFront,
413 uint32_t& paddingBack,
414 tflite::Padding padding,
415 uint32_t outputSize)
416{
417 IgnoreUnused(dilation);
418 paddingFront = 0;
419 paddingBack = 0;
420 if (padding == tflite::Padding_SAME)
421 {
422 uint32_t totalPadding = (inputSize - 1) * stride + filterSize - outputSize;
423 paddingFront = totalPadding / 2;
424 paddingBack = totalPadding - paddingFront;
425 }
426}
427
Kevin May7d96b162021-02-03 17:38:41 +0000428armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr,
Finn Williamsb49ed182021-06-29 15:50:08 +0100429 const std::vector<unsigned int>& shape,
Sadik Armagand109a4d2020-07-28 10:42:13 +0100430 const bool outputTensor = false)
telsoa01c577f2c2018-08-31 09:22:23 +0100431{
432 armnn::DataType type;
433 CHECK_TENSOR_PTR(tensorPtr);
434
435 switch (tensorPtr->type)
436 {
437 case tflite::TensorType_UINT8:
Derek Lambertif90c56d2020-01-10 17:14:08 +0000438 type = armnn::DataType::QAsymmU8;
telsoa01c577f2c2018-08-31 09:22:23 +0100439 break;
440 case tflite::TensorType_FLOAT32:
441 type = armnn::DataType::Float32;
442 break;
Keith Davisb4dd5cc2022-04-07 11:32:00 +0100443 case tflite::TensorType_FLOAT16:
444 type = armnn::DataType::Float16;
445 break;
Finn Williamsed66d142019-12-06 09:55:55 +0000446 case tflite::TensorType_INT8:
Keith Davis67e6c542020-02-19 10:08:33 +0000447 if (tensorPtr->quantization->zero_point.size() == 1)
Ryan OShea03181ff2020-02-07 17:22:22 +0000448 {
Keith Davis0c2eeac2020-02-11 16:51:50 +0000449 // Per-tensor
Ryan OShea03181ff2020-02-07 17:22:22 +0000450 type = armnn::DataType::QAsymmS8;
451 }
452 else
453 {
Keith Davis0c2eeac2020-02-11 16:51:50 +0000454 // Per-channel
Ryan OShea03181ff2020-02-07 17:22:22 +0000455 type = armnn::DataType::QSymmS8;
456 }
Finn Williamsed66d142019-12-06 09:55:55 +0000457 break;
458 case tflite::TensorType_INT16:
Derek Lambertif90c56d2020-01-10 17:14:08 +0000459 type = armnn::DataType::QSymmS16;
Finn Williamsed66d142019-12-06 09:55:55 +0000460 break;
telsoa01c577f2c2018-08-31 09:22:23 +0100461 case tflite::TensorType_INT32:
462 type = armnn::DataType::Signed32;
463 break;
Inki Daed4619e22020-09-10 15:33:54 +0900464 case tflite::TensorType_INT64:
465 type = armnn::DataType::Signed64;
466 break;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100467 case tflite::TensorType_BOOL:
468 type = armnn::DataType::Boolean;
469 break;
telsoa01c577f2c2018-08-31 09:22:23 +0100470 default:
471 {
472 CheckLocation location = CHECK_LOCATION();
473 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100474 fmt::format("Unsupported data type {} = {} for tensor: {}. {}",
475 tensorPtr->type,
476 tflite::EnumNameTensorType(tensorPtr->type),
477 tensorPtr->name,
478 location.AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100479 }
480 }
Finn Williamsb49ed182021-06-29 15:50:08 +0100481 TensorShape tensorShape;
482
483 std::vector<unsigned int> safeShape = shape;
484 if (shape.size() == 0)
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100485 {
486 safeShape.push_back(1);
Finn Williamsb49ed182021-06-29 15:50:08 +0100487 }
488
489 if (!outputTensor)
490 {
491 tensorShape = TensorShape(armnn::numeric_cast<unsigned int>(safeShape.size()), safeShape.data());
492 }
493 else
494 {
Rob Hughesd812a312021-08-06 13:10:53 +0100495 size_t shapeSignatureSize = tensorPtr->shape_signature.size();
Finn Williamsb49ed182021-06-29 15:50:08 +0100496
497 // If a shape signature exists we will use that to infer dynamic tensors
498 if (shapeSignatureSize != 0)
Sadik Armagand109a4d2020-07-28 10:42:13 +0100499 {
Finn Williamsb49ed182021-06-29 15:50:08 +0100500 // If the shape is incompatible with the shape signature override the shape
501 if (shapeSignatureSize != shape.size())
502 {
503 safeShape = {};
504
505 for (unsigned int i = 0; i < shapeSignatureSize; ++i)
506 {
507 unsigned int dim = tensorPtr->shape_signature[i] > -1 ?
508 static_cast<unsigned int>(tensorPtr->shape_signature[i]) : 0;
509 safeShape.push_back(dim);
510 }
511 }
512
Rob Hughesd812a312021-08-06 13:10:53 +0100513 std::unique_ptr<bool[]> dimMask = std::make_unique<bool[]>(tensorPtr->shape_signature.size());
Mike Kelly04d82292023-01-19 18:29:40 +0000514 bool batchOnly = true;
Finn Williamsb49ed182021-06-29 15:50:08 +0100515 for (unsigned int i = 0; i < tensorPtr->shape_signature.size(); ++i)
516 {
Mike Kelly04d82292023-01-19 18:29:40 +0000517 dimMask[i] = tensorPtr->shape_signature[i] != -1;
518
519 if (i > 0 && !dimMask[i])
520 {
521 batchOnly = false;
522 }
523 }
524 if (batchOnly)
525 {
526 dimMask[0] = true;
Finn Williamsb49ed182021-06-29 15:50:08 +0100527 }
Rob Hughesd812a312021-08-06 13:10:53 +0100528 tensorShape = TensorShape(static_cast<unsigned int>(safeShape.size()), safeShape.data(), dimMask.get());
Finn Williamsb49ed182021-06-29 15:50:08 +0100529 }
530 // If there is no shape signature treat the tensor as dynamic if the shape has a size of zero
531 else if (shape.size() == 0)
532 {
533 tensorShape = TensorShape(1, false);
534 }
535 else
536 {
537 tensorShape = TensorShape(armnn::numeric_cast<unsigned int>(shape.size()), shape.data());
Sadik Armagand109a4d2020-07-28 10:42:13 +0100538 }
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100539 }
540
Teresa Charlinacb3ec52023-04-03 19:57:00 +0100541 float quantizationScale = 1.0f;
Keith Davisd305e1a2020-01-22 11:57:54 +0000542 int32_t quantizationOffset = 0;
543
544 if (tensorPtr->quantization.get())
545 {
546 if (tensorPtr->quantization->scale.size() <= 1)
547 {
548 CHECK_VALID_SIZE(tensorPtr->quantization->zero_point.size(), 0, 1);
549 CHECK_VALID_SIZE(tensorPtr->quantization->zero_point.size(), 0, 1);
550
551 if (tensorPtr->quantization->scale.size() == 1)
552 {
553 quantizationScale = tensorPtr->quantization->scale[0];
554 }
555 if (tensorPtr->quantization->zero_point.size() == 1)
556 {
557 // NOTE: we lose precision here when converting from 64 bit to 32
Ryan OShea03181ff2020-02-07 17:22:22 +0000558 // but this is what we support at the moment in ArmNN
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100559 quantizationOffset = armnn::numeric_cast<int32_t>(tensorPtr->quantization->zero_point[0]);
Keith Davisd305e1a2020-01-22 11:57:54 +0000560 }
561
Sadik Armagand109a4d2020-07-28 10:42:13 +0100562 armnn::TensorInfo result(tensorShape,
563 type,
564 quantizationScale,
565 quantizationOffset);
Keith Davisd305e1a2020-01-22 11:57:54 +0000566 return result;
567 }
568 else
569 {
570 std::vector<float> quantizationScales;
571 std::vector<int32_t> quantizationOffsets;
572
573 // Scale
574 std::copy(tensorPtr->quantization->scale.begin(),
575 tensorPtr->quantization->scale.end(),
576 std::back_inserter(quantizationScales));
577
Keith Davis0c2eeac2020-02-11 16:51:50 +0000578 // QSymmS8 Per-axis
Sadik Armagand109a4d2020-07-28 10:42:13 +0100579 armnn::TensorInfo result(tensorShape,
580 type,
581 quantizationScales,
Jan Eilers7612bd62021-04-06 17:29:03 +0100582 armnn::numeric_cast<unsigned int>(tensorPtr->quantization->quantized_dimension));
Keith Davisd305e1a2020-01-22 11:57:54 +0000583 return result;
584 }
585 }
586 else
587 {
Sadik Armagand109a4d2020-07-28 10:42:13 +0100588 armnn::TensorInfo result(tensorShape,
Keith Davisd305e1a2020-01-22 11:57:54 +0000589 type,
590 quantizationScale,
591 quantizationOffset);
592 return result;
593 }
telsoa01c577f2c2018-08-31 09:22:23 +0100594}
595
Kevin May7d96b162021-02-03 17:38:41 +0000596armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr,
Mike Kelly377fb212023-01-10 15:55:28 +0000597 const bool outputTensor = false)
Sadik Armagand109a4d2020-07-28 10:42:13 +0100598{
Mike Kelly0d77ae12022-01-07 17:42:27 +0000599 auto const& dimensions = AsUnsignedVector(tensorPtr->shape);
Jan Eilers7612bd62021-04-06 17:29:03 +0100600 return ToTensorInfo(tensorPtr, dimensions, outputTensor);
Sadik Armagand109a4d2020-07-28 10:42:13 +0100601}
602
telsoa01c577f2c2018-08-31 09:22:23 +0100603template<typename T>
604std::pair<armnn::ConstTensor, std::unique_ptr<T[]>>
Kevin May7d96b162021-02-03 17:38:41 +0000605CreateConstTensorImpl(TfLiteParserImpl::BufferRawPtr bufferPtr,
606 TfLiteParserImpl::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +0000607 armnn::TensorInfo& tensorInfo,
608 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +0100609{
Jan Eilers8eb25602020-03-09 12:13:48 +0000610 IgnoreUnused(tensorPtr);
Ryan OSheac229b3f2023-06-27 22:34:54 +0100611
612 if (!tensorPtr)
613 {
614 throw armnn::ParseException(fmt::format("Tensor pointer is null {}", CHECK_LOCATION().AsString()));
615 }
616
617 if (!bufferPtr)
618 {
619 throw armnn::ParseException(fmt::format("Buffer for buffer:{} is null", tensorPtr->buffer).c_str());
620 }
telsoa01c577f2c2018-08-31 09:22:23 +0100621
622 std::unique_ptr<T[]> data(new T[tensorInfo.GetNumElements()]);
Matteo Martincigh747ef822018-12-18 09:26:39 +0000623
624 if (permutationVector.has_value() && permutationVector.value().GetSize() > 0)
625 {
626 tensorInfo = armnnUtils::Permuted(tensorInfo, permutationVector.value());
Matteo Martincighd5b9e642019-01-04 18:01:21 +0000627 armnnUtils::Permute(tensorInfo.GetShape(), permutationVector.value(),
628 reinterpret_cast<const T*>(bufferPtr->data.data()), data.get(), sizeof(T));
Matteo Martincigh747ef822018-12-18 09:26:39 +0000629 }
630 else
631 {
632 ::memcpy(data.get(), bufferPtr->data.data(), tensorInfo.GetNumBytes());
633 }
634
Matthew Sloyan81beae32021-07-13 19:46:11 +0100635 // Make sure isConstant flag is set.
636 tensorInfo.SetConstant();
637
telsoa01c577f2c2018-08-31 09:22:23 +0100638 return std::make_pair(ConstTensor(tensorInfo, data.get()), std::move(data));
639}
640
telsoa01c577f2c2018-08-31 09:22:23 +0100641armnn::LayerBindingId GenerateLayerBindingId(size_t subgraphIndex, size_t tensorIndex)
642{
643 // generate the binding id by shifting the tensor id by 8 bit
644 // and add the subgraph id, which allows 256 subgraphs
645 return static_cast<armnn::LayerBindingId>((tensorIndex<<8)+subgraphIndex);
646}
647
Aron Virginas-Tar70672f62019-01-23 14:00:00 +0000648bool CheckShape(const armnn::TensorShape& actual, const std::vector<int32_t>& expected)
649{
650 const unsigned int actualSize = actual.GetNumDimensions();
651 if (actualSize != expected.size())
652 {
653 return false;
654 }
655
656 for (unsigned int i = 0u; i < actualSize; i++)
657 {
658 if (expected[i] < 0 ||
659 actual[i] != static_cast<unsigned int>(expected[i]))
660 {
661 return false;
662 }
663 }
664
665 return true;
666}
667
Cathal Corbett2b922e22022-09-23 15:49:24 +0100668bool CheckShape(const armnn::TensorShape& actual, const armnn::TensorShape& expected)
669{
670 std::vector<int32_t> expectedVec;
671 for (uint32_t i = 0; i < expected.GetNumDimensions(); i++)
672 {
673 expectedVec.push_back(expected[i]);
674 }
675 return CheckShape(actual, expectedVec);
676}
677
James Conroy05102392020-06-24 15:39:55 +0100678void CheckMatchingQuantization(const TensorInfo& first,
679 const TensorInfo& second,
680 const std::string& descName,
681 std::string const& firstName,
682 std::string const& secondName)
683{
684 if (!first.IsQuantized() ||
685 !second.IsQuantized())
686 {
687 // Not a quantized type, ignore the validation
688 return;
689 }
690
691 DataType firstDataType = first.GetDataType();
692 DataType secondDataType = second.GetDataType();
693
694 if (firstDataType != secondDataType)
695 {
696 throw InvalidArgumentException(descName + ": " + firstName + " and " + secondName +
697 " must be of the same quantized type, " +
698 firstName + " is " + GetDataTypeName(firstDataType) + ", " +
699 secondName + " is " + GetDataTypeName(secondDataType));
700 }
701
702 if (!first.IsTypeSpaceMatch(second))
703 {
704 throw InvalidArgumentException(descName + ": " + firstName + " and " + secondName +
705 " must have the same quantization space, " +
706 firstName + " has offset " + std::to_string(first.GetQuantizationOffset()) +
707 " and scale " + std::to_string(first.GetQuantizationScale()) + ", " +
708 secondName + " has offset " + std::to_string(second.GetQuantizationOffset()) +
709 " and scale " + std::to_string(second.GetQuantizationScale()));
710 }
711}
712
Mike Kelly377fb212023-01-10 15:55:28 +0000713bool IsDynamic(TfLiteParserImpl::TensorRawPtr tensorPtr)
714{
715 auto shape = tensorPtr->shape;
716
717 if (shape.empty())
718 {
719 return true;
720 }
721 auto shapeSig = tensorPtr->shape_signature;
722
723 if (shapeSig.empty())
724 {
725 return false;
726 }
727
728 for (unsigned int i = 0; i < shapeSig.size() ; ++i)
729 {
730 if (shapeSig[i] == -1)
731 {
732 return true;
733 }
734 }
735 return false;
736}
737
telsoa01c577f2c2018-08-31 09:22:23 +0100738} // <anonymous>
739
Kevin May7d96b162021-02-03 17:38:41 +0000740TfLiteParserImpl::TfLiteParserImpl(const Optional<ITfLiteParser::TfLiteParserOptions>& options)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100741: m_Options(options)
742, m_Network(nullptr, nullptr)
Kevin May7d96b162021-02-03 17:38:41 +0000743, m_ParserFunctions(tflite::BuiltinOperator_MAX+1, &TfLiteParserImpl::ParseUnsupportedOperator)
telsoa01c577f2c2018-08-31 09:22:23 +0100744{
745 // register supported operators
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100746 m_ParserFunctions[tflite::BuiltinOperator_ABS] = &TfLiteParserImpl::ParseAbs;
Kevin May7d96b162021-02-03 17:38:41 +0000747 m_ParserFunctions[tflite::BuiltinOperator_ADD] = &TfLiteParserImpl::ParseAdd;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100748 m_ParserFunctions[tflite::BuiltinOperator_ARG_MIN] = &TfLiteParserImpl::ParseArgMin;
749 m_ParserFunctions[tflite::BuiltinOperator_ARG_MAX] = &TfLiteParserImpl::ParseArgMax;
Kevin May7d96b162021-02-03 17:38:41 +0000750 m_ParserFunctions[tflite::BuiltinOperator_AVERAGE_POOL_2D] = &TfLiteParserImpl::ParseAveragePool2D;
751 m_ParserFunctions[tflite::BuiltinOperator_BATCH_TO_SPACE_ND] = &TfLiteParserImpl::ParseBatchToSpaceND;
Samuel Yapfd3ba5a2022-08-24 17:04:34 +0100752 m_ParserFunctions[tflite::BuiltinOperator_BATCH_MATMUL] = &TfLiteParserImpl::ParseBatchMatMul;
Idriss Chaouch564c13d2023-09-01 17:58:38 +0100753 m_ParserFunctions[tflite::BuiltinOperator_BROADCAST_TO] = &TfLiteParserImpl::ParseBroadcastTo;
Teresa Charlin93f0ad02023-03-23 15:28:02 +0000754 m_ParserFunctions[tflite::BuiltinOperator_CEIL] = &TfLiteParserImpl::ParseCeil;
mathad01b392e982021-04-07 12:07:30 +0100755 m_ParserFunctions[tflite::BuiltinOperator_CAST] = &TfLiteParserImpl::ParseCast;
Kevin May7d96b162021-02-03 17:38:41 +0000756 m_ParserFunctions[tflite::BuiltinOperator_CONCATENATION] = &TfLiteParserImpl::ParseConcatenation;
757 m_ParserFunctions[tflite::BuiltinOperator_CONV_2D] = &TfLiteParserImpl::ParseConv2D;
Matthew Sloyan4d217c02021-10-07 11:48:58 +0100758 // Conv3D support was added in TF 2.5, so for backwards compatibility a hash define is needed.
Cathal Corbett80b4ef02022-05-25 11:21:11 +0100759 #if defined(ARMNN_POST_TFLITE_2_4)
Matthew Sloyaneb5f8102021-10-05 17:31:42 +0100760 m_ParserFunctions[tflite::BuiltinOperator_CONV_3D] = &TfLiteParserImpl::ParseConv3D;
Matthew Sloyan4d217c02021-10-07 11:48:58 +0100761 #endif
Kevin May7d96b162021-02-03 17:38:41 +0000762 m_ParserFunctions[tflite::BuiltinOperator_CUSTOM] = &TfLiteParserImpl::ParseCustomOperator;
763 m_ParserFunctions[tflite::BuiltinOperator_DEPTH_TO_SPACE] = &TfLiteParserImpl::ParseDepthToSpace;
764 m_ParserFunctions[tflite::BuiltinOperator_DEPTHWISE_CONV_2D] = &TfLiteParserImpl::ParseDepthwiseConv2D;
765 m_ParserFunctions[tflite::BuiltinOperator_DEQUANTIZE] = &TfLiteParserImpl::ParseDequantize;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100766 m_ParserFunctions[tflite::BuiltinOperator_DIV] = &TfLiteParserImpl::ParseDiv;
Kevin May7d96b162021-02-03 17:38:41 +0000767 m_ParserFunctions[tflite::BuiltinOperator_ELU] = &TfLiteParserImpl::ParseElu;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300768 m_ParserFunctions[tflite::BuiltinOperator_EQUAL] = &TfLiteParserImpl::ParseEqual;
Kevin May7d96b162021-02-03 17:38:41 +0000769 m_ParserFunctions[tflite::BuiltinOperator_EXP] = &TfLiteParserImpl::ParseExp;
Teresa Charlin3ab85482021-06-08 16:59:29 +0100770 m_ParserFunctions[tflite::BuiltinOperator_EXPAND_DIMS] = &TfLiteParserImpl::ParseExpandDims;
Teresa Charlincdbd40b2022-02-25 13:21:55 +0000771 m_ParserFunctions[tflite::BuiltinOperator_FLOOR_DIV] = &TfLiteParserImpl::ParseFloorDiv;
Kevin May7d96b162021-02-03 17:38:41 +0000772 m_ParserFunctions[tflite::BuiltinOperator_FULLY_CONNECTED] = &TfLiteParserImpl::ParseFullyConnected;
773 m_ParserFunctions[tflite::BuiltinOperator_GATHER] = &TfLiteParserImpl::ParseGather;
Teresa Charlin077cddb2023-09-15 15:19:21 +0100774 m_ParserFunctions[tflite::BuiltinOperator_GELU] = &TfLiteParserImpl::ParseGelu;
Teresa Charlin91a53ea2022-04-25 15:47:29 +0100775 m_ParserFunctions[tflite::BuiltinOperator_GATHER_ND] = &TfLiteParserImpl::ParseGatherNd;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300776 m_ParserFunctions[tflite::BuiltinOperator_GREATER] = &TfLiteParserImpl::ParseGreater;
777 m_ParserFunctions[tflite::BuiltinOperator_GREATER_EQUAL] = &TfLiteParserImpl::ParseGreaterOrEqual;
Kevin May7d96b162021-02-03 17:38:41 +0000778 m_ParserFunctions[tflite::BuiltinOperator_HARD_SWISH] = &TfLiteParserImpl::ParseHardSwish;
779 m_ParserFunctions[tflite::BuiltinOperator_LEAKY_RELU] = &TfLiteParserImpl::ParseLeakyRelu;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300780 m_ParserFunctions[tflite::BuiltinOperator_LESS] = &TfLiteParserImpl::ParseLess;
781 m_ParserFunctions[tflite::BuiltinOperator_LESS_EQUAL] = &TfLiteParserImpl::ParseLessOrEqual;
Mike Kelly31dce2b2021-09-01 21:22:37 +0100782 m_ParserFunctions[tflite::BuiltinOperator_LOCAL_RESPONSE_NORMALIZATION]
783 = &TfLiteParserImpl::ParseLocalResponseNormalization;
Teresa Charlin28aa6692022-07-12 11:18:44 +0100784 m_ParserFunctions[tflite::BuiltinOperator_LOG] = &TfLiteParserImpl::ParseLog;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100785 m_ParserFunctions[tflite::BuiltinOperator_LOGICAL_NOT] = &TfLiteParserImpl::ParseLogicalNot;
Kevin May7d96b162021-02-03 17:38:41 +0000786 m_ParserFunctions[tflite::BuiltinOperator_LOGISTIC] = &TfLiteParserImpl::ParseLogistic;
Teresa Charlinfd33a692022-06-29 15:35:57 +0100787 m_ParserFunctions[tflite::BuiltinOperator_LOG_SOFTMAX] = &TfLiteParserImpl::ParseLogSoftmax;
Kevin May7d96b162021-02-03 17:38:41 +0000788 m_ParserFunctions[tflite::BuiltinOperator_L2_NORMALIZATION] = &TfLiteParserImpl::ParseL2Normalization;
789 m_ParserFunctions[tflite::BuiltinOperator_MAX_POOL_2D] = &TfLiteParserImpl::ParseMaxPool2D;
790 m_ParserFunctions[tflite::BuiltinOperator_MAXIMUM] = &TfLiteParserImpl::ParseMaximum;
791 m_ParserFunctions[tflite::BuiltinOperator_MEAN] = &TfLiteParserImpl::ParseMean;
792 m_ParserFunctions[tflite::BuiltinOperator_MINIMUM] = &TfLiteParserImpl::ParseMinimum;
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +0100793 m_ParserFunctions[tflite::BuiltinOperator_MIRROR_PAD] = &TfLiteParserImpl::ParseMirrorPad;
Kevin May7d96b162021-02-03 17:38:41 +0000794 m_ParserFunctions[tflite::BuiltinOperator_MUL] = &TfLiteParserImpl::ParseMul;
795 m_ParserFunctions[tflite::BuiltinOperator_NEG] = &TfLiteParserImpl::ParseNeg;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300796 m_ParserFunctions[tflite::BuiltinOperator_NOT_EQUAL] = &TfLiteParserImpl::ParseNotEqual;
Kevin May7d96b162021-02-03 17:38:41 +0000797 m_ParserFunctions[tflite::BuiltinOperator_PACK] = &TfLiteParserImpl::ParsePack;
798 m_ParserFunctions[tflite::BuiltinOperator_PAD] = &TfLiteParserImpl::ParsePad;
Mike Kelly0d77ae12022-01-07 17:42:27 +0000799 m_ParserFunctions[tflite::BuiltinOperator_PADV2] = &TfLiteParserImpl::ParsePad;
John Mcloughlin0ec00872023-05-15 17:03:49 +0100800 m_ParserFunctions[tflite::BuiltinOperator_POW] = &TfLiteParserImpl::ParsePower;
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +0100801 m_ParserFunctions[tflite::BuiltinOperator_PRELU] = &TfLiteParserImpl::ParsePrelu;
Kevin May7d96b162021-02-03 17:38:41 +0000802 m_ParserFunctions[tflite::BuiltinOperator_QUANTIZE] = &TfLiteParserImpl::ParseQuantize;
803 m_ParserFunctions[tflite::BuiltinOperator_RELU] = &TfLiteParserImpl::ParseRelu;
804 m_ParserFunctions[tflite::BuiltinOperator_RELU6] = &TfLiteParserImpl::ParseRelu6;
Sadik Armagana2747482021-02-09 10:28:54 +0000805 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MAX] = &TfLiteParserImpl::ParseReduceMax;
806 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MIN] = &TfLiteParserImpl::ParseReduceMin;
Teresa Charlin4e3e8312021-08-05 12:34:37 +0100807 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_PROD] = &TfLiteParserImpl::ParseReduceProd;
Kevin May7d96b162021-02-03 17:38:41 +0000808 m_ParserFunctions[tflite::BuiltinOperator_RESHAPE] = &TfLiteParserImpl::ParseReshape;
809 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_BILINEAR] = &TfLiteParserImpl::ParseResizeBilinear;
810 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_NEAREST_NEIGHBOR] = &TfLiteParserImpl::ParseResizeNearestNeighbor;
Tianle Chenge5a30ff2023-07-03 11:24:12 +0100811 m_ParserFunctions[tflite::BuiltinOperator_REVERSE_V2] = &TfLiteParserImpl::ParseReverseV2;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100812 m_ParserFunctions[tflite::BuiltinOperator_RSQRT] = &TfLiteParserImpl::ParseRsqrt;
Teresa Charlinf0fce5b2022-05-04 17:24:43 +0100813 m_ParserFunctions[tflite::BuiltinOperator_SQRT] = &TfLiteParserImpl::ParseSqrt;
Keith Davis0176fd82021-06-01 17:36:32 +0100814 m_ParserFunctions[tflite::BuiltinOperator_SHAPE] = &TfLiteParserImpl::ParseShape;
Teresa Charlin28aa6692022-07-12 11:18:44 +0100815 m_ParserFunctions[tflite::BuiltinOperator_SIN] = &TfLiteParserImpl::ParseSin;
Kevin May7d96b162021-02-03 17:38:41 +0000816 m_ParserFunctions[tflite::BuiltinOperator_SLICE] = &TfLiteParserImpl::ParseSlice;
817 m_ParserFunctions[tflite::BuiltinOperator_SOFTMAX] = &TfLiteParserImpl::ParseSoftmax;
818 m_ParserFunctions[tflite::BuiltinOperator_SPACE_TO_BATCH_ND] = &TfLiteParserImpl::ParseSpaceToBatchND;
Teresa Charlin2a764ad2023-02-24 18:17:31 +0000819 m_ParserFunctions[tflite::BuiltinOperator_SPACE_TO_DEPTH] = &TfLiteParserImpl::ParseSpaceToDepth;
Kevin May7d96b162021-02-03 17:38:41 +0000820 m_ParserFunctions[tflite::BuiltinOperator_SPLIT] = &TfLiteParserImpl::ParseSplit;
821 m_ParserFunctions[tflite::BuiltinOperator_SPLIT_V] = &TfLiteParserImpl::ParseSplitV;
822 m_ParserFunctions[tflite::BuiltinOperator_SQUEEZE] = &TfLiteParserImpl::ParseSqueeze;
Teresa Charlin6963b332023-07-11 11:35:41 +0100823 m_ParserFunctions[tflite::BuiltinOperator_SQUARE] = &TfLiteParserImpl::ParseSquare;
John Mcloughlin0ec00872023-05-15 17:03:49 +0100824 m_ParserFunctions[tflite::BuiltinOperator_SQUARED_DIFFERENCE] = &TfLiteParserImpl::ParseSquaredDifference;
Kevin May7d96b162021-02-03 17:38:41 +0000825 m_ParserFunctions[tflite::BuiltinOperator_STRIDED_SLICE] = &TfLiteParserImpl::ParseStridedSlice;
826 m_ParserFunctions[tflite::BuiltinOperator_SUB] = &TfLiteParserImpl::ParseSub;
827 m_ParserFunctions[tflite::BuiltinOperator_SUM] = &TfLiteParserImpl::ParseSum;
828 m_ParserFunctions[tflite::BuiltinOperator_TANH] = &TfLiteParserImpl::ParseTanH;
Teresa Charlin777008b2023-07-26 10:07:55 +0100829 m_ParserFunctions[tflite::BuiltinOperator_TILE] = &TfLiteParserImpl::ParseTile;
Kevin May7d96b162021-02-03 17:38:41 +0000830 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE] = &TfLiteParserImpl::ParseTranspose;
831 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE_CONV] = &TfLiteParserImpl::ParseTransposeConv;
Mike Kelly5880b912022-01-28 16:18:54 +0000832 m_ParserFunctions[tflite::BuiltinOperator_UNIDIRECTIONAL_SEQUENCE_LSTM]
833 = &TfLiteParserImpl::ParseUnidirectionalSequenceLSTM;
Kevin May7d96b162021-02-03 17:38:41 +0000834 m_ParserFunctions[tflite::BuiltinOperator_UNPACK] = &TfLiteParserImpl::ParseUnpack;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100835
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100836 // register supported custom operators
Kevin May7d96b162021-02-03 17:38:41 +0000837 m_CustomParserFunctions["TFLite_Detection_PostProcess"] = &TfLiteParserImpl::ParseDetectionPostProcess;
telsoa01c577f2c2018-08-31 09:22:23 +0100838}
839
Mike Kelly377fb212023-01-10 15:55:28 +0000840armnn::TensorInfo TfLiteParserImpl::InputTensorInfo(size_t subgraphIndex,
841 size_t operatorIndex,
842 int input)
843{
844 const auto& subgraphPtr = m_Model->subgraphs[subgraphIndex];
845 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
846
847 uint32_t inputId = CHECKED_NON_NEGATIVE(operatorPtr->inputs[input]);
848 auto search = armnnTfLiteParser::TfLiteParserImpl::m_TensorInfos.find(inputId);
849
850 if (search != m_TensorInfos.end())
851 {
852 return m_TensorInfos[inputId];
853 }
854 else
855 {
856 auto tensorInfo = ::armnnTfLiteParser::ToTensorInfo(subgraphPtr->tensors[inputId].get());
857 m_TensorInfos.insert({ inputId, tensorInfo });
858 return tensorInfo;
859 }
860}
861
862armnn::TensorInfo TfLiteParserImpl::OutputTensorInfoFromInputs(size_t subgraphIndex,
863 size_t operatorIndex,
864 armnn::IConnectableLayer* layer,
865 int output,
866 std::vector<int> inputs)
867{
868 const auto& subgraphPtr = m_Model->subgraphs[subgraphIndex];
869 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
870
871 uint32_t outputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[output]);
872
873 auto outputSearch = armnnTfLiteParser::TfLiteParserImpl::m_TensorInfos.find(outputId);
874
875 if (outputSearch != m_TensorInfos.end())
876 {
877 return m_TensorInfos[outputId];
878 }
879
880 const auto& outputTensorPtr = subgraphPtr->tensors[outputId].get();
881 TensorInfo tensor = ::armnnTfLiteParser::ToTensorInfo(outputTensorPtr, true);
882
883 if (IsDynamic(outputTensorPtr))
884 {
885 if (inputs.empty())
886 {
887 for (unsigned int i = 0; i < layer->GetNumInputSlots(); ++i)
888 {
889 inputs.emplace_back(i);
890 }
891 }
892 auto inputTensorIds = GetInputTensorIds(m_Model, subgraphIndex, operatorIndex);
893 std::vector<armnn::TensorShape> inputShapes;
894
895 for (unsigned int i = 0; i < inputs.size(); ++i)
896 {
897 uint32_t inputId = CHECKED_NON_NEGATIVE(operatorPtr->inputs[inputs[i]]);
898 auto search = armnnTfLiteParser::TfLiteParserImpl::m_TensorInfos.find(inputId);
899
900 if (search != m_TensorInfos.end())
901 {
902 auto &inputTensorInfo = m_TensorInfos[inputId];
903 inputShapes.push_back(inputTensorInfo.GetShape());
904 }
905 else
906 {
Mike Kelly377fb212023-01-10 15:55:28 +0000907 auto inputTensorInfo = ::armnnTfLiteParser::ToTensorInfo(subgraphPtr->tensors[inputId].get());
908 m_TensorInfos.insert({ inputId, inputTensorInfo});
909 inputShapes.push_back(inputTensorInfo.GetShape());
910 }
911 }
912 const auto outputShape = layer->InferOutputShapes(inputShapes)[output];
913 tensor.SetShape(outputShape);
914 }
915 m_TensorInfos.insert({ outputId, tensor});
916 return tensor;
917}
918
919armnn::TensorInfo TfLiteParserImpl::OutputTensorInfoFromShapes(size_t subgraphIndex,
920 size_t operatorIndex,
921 armnn::IConnectableLayer* layer,
922 int output,
923 std::vector<armnn::TensorShape> inputShapes)
924{
925 const auto& subgraphPtr = m_Model->subgraphs[subgraphIndex];
926 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
927
928 uint32_t outputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[output]);
929 const auto& outputTensorPtr = subgraphPtr->tensors[outputId].get();
930 TensorInfo tensor = ::armnnTfLiteParser::ToTensorInfo(outputTensorPtr, true);
931
932 if (IsDynamic(outputTensorPtr))
933 {
934 const auto outputShape = layer->InferOutputShapes(inputShapes)[output];
935 tensor.SetShape(outputShape);
936 }
937 m_TensorInfos.insert({ outputId, tensor});
938 return tensor;
939}
940
Kevin May7d96b162021-02-03 17:38:41 +0000941void TfLiteParserImpl::ResetParser()
telsoa01c577f2c2018-08-31 09:22:23 +0100942{
943 m_Network = armnn::INetworkPtr(nullptr, nullptr);
944 m_Model = nullptr;
945 m_SubgraphConnections.clear();
Mike Kelly377fb212023-01-10 15:55:28 +0000946 m_OverriddenOutputShapes.clear();
Mike Kelly5880b912022-01-28 16:18:54 +0000947 m_ConstantsToDequantize.clear();
948 m_ConstantsToBeCreated.clear();
Mike Kelly377fb212023-01-10 15:55:28 +0000949 m_TensorInfos.clear();
telsoa01c577f2c2018-08-31 09:22:23 +0100950}
951
Kevin May7d96b162021-02-03 17:38:41 +0000952INetworkPtr TfLiteParserImpl::CreateNetworkFromBinaryFile(const char* graphFile)
telsoa01c577f2c2018-08-31 09:22:23 +0100953{
954 ResetParser();
955 m_Model = LoadModelFromFile(graphFile);
956 return CreateNetworkFromModel();
957}
958
Mike Kelly0d77ae12022-01-07 17:42:27 +0000959INetworkPtr TfLiteParserImpl::CreateNetworkFromBinary(const std::vector<uint8_t>& binaryContent)
telsoa01c577f2c2018-08-31 09:22:23 +0100960{
961 ResetParser();
962 m_Model = LoadModelFromBinary(binaryContent.data(), binaryContent.size());
963 return CreateNetworkFromModel();
964}
965
Finn Williamsb49ed182021-06-29 15:50:08 +0100966
967armnn::INetworkPtr TfLiteParserImpl::LoadModel(std::unique_ptr<tflite::ModelT> model)
968{
969 ResetParser();
970 m_Model = std::move(model);
971
972 return CreateNetworkFromModel();
973}
974
Kevin May7d96b162021-02-03 17:38:41 +0000975INetworkPtr TfLiteParserImpl::CreateNetworkFromModel()
telsoa01c577f2c2018-08-31 09:22:23 +0100976{
Sadik Armagand109a4d2020-07-28 10:42:13 +0100977
978 using NetworkOptions = std::vector<BackendOptions>;
979 NetworkOptions networkOptions = {};
Mike Kelly80512b02022-05-16 23:10:42 +0100980 if (m_Options)
Sadik Armagand109a4d2020-07-28 10:42:13 +0100981 {
Mike Kelly80512b02022-05-16 23:10:42 +0100982 if (m_Options.value().m_InferAndValidate)
983 {
984 BackendOptions shapeInferenceMethodOption("ShapeInferenceMethod",
985 {
986 { "InferAndValidate", true }
987 });
Sadik Armagand109a4d2020-07-28 10:42:13 +0100988
Mike Kelly80512b02022-05-16 23:10:42 +0100989 networkOptions.push_back(shapeInferenceMethodOption);
990 }
991 if (m_Options.value().m_AllowExpandedDims)
992 {
993 BackendOptions shapeInferenceMethodOption("AllowExpandedDims",
994 {
995 { "AllowExpandedDims", true }
996 });
997
998 networkOptions.push_back(shapeInferenceMethodOption);
999 }
Sadik Armagand109a4d2020-07-28 10:42:13 +01001000 }
Sadik Armagand109a4d2020-07-28 10:42:13 +01001001 m_Network = INetwork::Create(networkOptions);
Ryan OSheac229b3f2023-06-27 22:34:54 +01001002
1003 if (m_Model.get() == nullptr)
1004 {
1005 throw ParseException(fmt::format("Tflite Model pointer is null {}", CHECK_LOCATION().AsString()));
1006 }
telsoa01c577f2c2018-08-31 09:22:23 +01001007
telsoa01c577f2c2018-08-31 09:22:23 +01001008 if (m_Model->subgraphs.size() != 1)
1009 {
1010 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01001011 fmt::format("Current TfLite parser only supports 1 subgraph. Current one has: {} {}",
1012 m_Model->subgraphs.size(),
1013 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01001014 }
1015
1016 size_t subgraphIndex = 0;
Colm Donelan6350d272020-06-09 16:56:25 +01001017 size_t operatorIndex = 0;
1018 try
telsoa01c577f2c2018-08-31 09:22:23 +01001019 {
Colm Donelan6350d272020-06-09 16:56:25 +01001020 for (SubgraphPtr const& subgraph : m_Model->subgraphs)
telsoa01c577f2c2018-08-31 09:22:23 +01001021 {
Mike Kelly377fb212023-01-10 15:55:28 +00001022 SetupInputLayerTensorInfos(subgraphIndex);
1023 SetupConstantLayerTensorInfos(subgraphIndex);
1024
Colm Donelan6350d272020-06-09 16:56:25 +01001025 m_SubgraphConnections.emplace_back(subgraph->tensors.size());
1026 for (OperatorPtr const& op : subgraph->operators)
telsoa01c577f2c2018-08-31 09:22:23 +01001027 {
Colm Donelan6350d272020-06-09 16:56:25 +01001028 auto const& opCodePtr = m_Model->operator_codes[op->opcode_index];
Jim Flynnfca233e2021-09-23 12:16:53 +01001029
1030// 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 +01001031#if defined(ARMNN_POST_TFLITE_2_3)
Jim Flynnfca233e2021-09-23 12:16:53 +01001032 auto builtinCode = std::max(opCodePtr->builtin_code,
1033 static_cast<tflite::BuiltinOperator>(opCodePtr->deprecated_builtin_code));
1034#else
telsoa01c577f2c2018-08-31 09:22:23 +01001035 auto builtinCode = opCodePtr->builtin_code;
Jim Flynnfca233e2021-09-23 12:16:53 +01001036#endif
telsoa01c577f2c2018-08-31 09:22:23 +01001037
1038 if (builtinCode > tflite::BuiltinOperator_MAX)
1039 {
James Ward58dec6b2020-09-11 17:32:44 +01001040 throw ParseException(fmt::format("Operator code {} is out of range 0-{}. "
1041 "subgraph:{} operator idx:{}. {}",
1042 builtinCode, tflite::BuiltinOperator_MAX, subgraphIndex,
1043 operatorIndex, CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01001044 }
1045
1046 // lookup and call the parser function
Colm Donelan6350d272020-06-09 16:56:25 +01001047 auto& parserFunction = m_ParserFunctions[builtinCode];
telsoa01c577f2c2018-08-31 09:22:23 +01001048 (this->*parserFunction)(subgraphIndex, operatorIndex);
Colm Donelan6350d272020-06-09 16:56:25 +01001049 ++operatorIndex;
telsoa01c577f2c2018-08-31 09:22:23 +01001050 }
telsoa01c577f2c2018-08-31 09:22:23 +01001051
Colm Donelan6350d272020-06-09 16:56:25 +01001052 SetupInputLayers(subgraphIndex);
1053 SetupOutputLayers(subgraphIndex);
1054 SetupConstantLayers(subgraphIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001055
Colm Donelan6350d272020-06-09 16:56:25 +01001056 ++subgraphIndex;
1057 operatorIndex = 0;
telsoa01c577f2c2018-08-31 09:22:23 +01001058 }
telsoa01c577f2c2018-08-31 09:22:23 +01001059 }
Colm Donelan6350d272020-06-09 16:56:25 +01001060 catch (const ParseException& e)
telsoa01c577f2c2018-08-31 09:22:23 +01001061 {
Colm Donelan6350d272020-06-09 16:56:25 +01001062 std::stringstream errorString;
1063 errorString << "Failed to parse operator #" << operatorIndex << " within subgraph #"
1064 << subgraphIndex << " error: " << e.what();
1065 ARMNN_LOG(error) << errorString.str();
1066 std::stringstream errors;
1067 errors << errorString.str() << "\n";
telsoa01c577f2c2018-08-31 09:22:23 +01001068 throw ParseException(errors.str());
1069 }
1070
1071 // establish the connections from the layer outputs to the inputs of the subsequent layers
Colm Donelan6350d272020-06-09 16:56:25 +01001072 for (subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001073 {
1074 for (size_t tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
1075 {
1076 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot != nullptr)
1077 {
1078 for (size_t inputSlotIdx = 0;
1079 inputSlotIdx < m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size();
1080 ++inputSlotIdx)
1081 {
1082 m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot->Connect(
1083 *(m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots[inputSlotIdx]));
1084 }
1085 }
1086 }
1087 }
telsoa01c577f2c2018-08-31 09:22:23 +01001088 return std::move(m_Network);
1089}
1090
Mike Kelly0506ef02023-01-03 16:29:44 +00001091bool TfLiteParserImpl::ShouldConstantTensorBeConverted(TfLiteParserImpl::TensorRawPtr tensorPtr,
1092 armnn::DataType inputDataType,
1093 armnn::DataType tensorDataType)
Mike Kelly5880b912022-01-28 16:18:54 +00001094{
Mike Kelly0506ef02023-01-03 16:29:44 +00001095 return (TfLiteParserImpl::IsConstTensor(tensorPtr) && inputDataType == DataType::Float32 &&
1096 (tensorDataType == DataType::QAsymmU8 ||
1097 tensorDataType == DataType::QAsymmS8 ||
1098 tensorDataType == DataType::QSymmS8 ||
1099 tensorDataType == DataType::Signed32 ||
1100 tensorDataType == DataType::Signed64));
Mike Kelly5880b912022-01-28 16:18:54 +00001101}
1102
Kevin May7d96b162021-02-03 17:38:41 +00001103void TfLiteParserImpl::RegisterProducerOfTensor(size_t subgraphIndex,
1104 size_t tensorIndex,
1105 armnn::IOutputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +01001106{
1107 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001108
1109 TensorSlots & tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
1110
Nikhil Rajd4d1c312022-08-03 18:20:59 +01001111 if (slot->GetOwningIConnectableLayer().GetType() != LayerType::Constant)
telsoa01c577f2c2018-08-31 09:22:23 +01001112 {
telsoa01c577f2c2018-08-31 09:22:23 +01001113
Nikhil Rajd4d1c312022-08-03 18:20:59 +01001114 // assuming there is only one producer for that tensor
1115 if (tensorSlots.outputSlot != nullptr)
1116 {
1117 throw ParseException(fmt::format("Another layer has already registered itself as the producer of "
1118 "subgraph:{} tensor:{} {}",
1119 subgraphIndex,
1120 tensorIndex,
1121 CHECK_LOCATION().AsString()));
1122 }
1123 }
telsoa01c577f2c2018-08-31 09:22:23 +01001124 tensorSlots.outputSlot = slot;
1125}
1126
Kevin May7d96b162021-02-03 17:38:41 +00001127void TfLiteParserImpl::RegisterConsumerOfTensor(size_t subgraphIndex,
1128 size_t tensorIndex,
1129 armnn::IInputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +01001130{
1131 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001132
Finn Williamsd4fa5452021-03-01 12:31:41 +00001133 TensorSlots& tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01001134 tensorSlots.inputSlots.push_back(slot);
1135}
1136
Kevin May7d96b162021-02-03 17:38:41 +00001137void TfLiteParserImpl::ParseCustomOperator(size_t subgraphIndex, size_t operatorIndex)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001138{
1139 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1140
1141 // NOTE: By default we presume the custom operator is not supported
Kevin May7d96b162021-02-03 17:38:41 +00001142 auto customParserFunction = &TfLiteParserImpl::ParseUnsupportedOperator;
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001143
1144 // Identify custom code defined for custom operator
1145 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1146 const auto& customCode = m_Model->operator_codes[operatorPtr->opcode_index]->custom_code;
1147
Mike Kelly377fb212023-01-10 15:55:28 +00001148 // Find parser function that corresponds to custom code (if any)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001149 auto iterator = m_CustomParserFunctions.find(customCode);
1150 if (iterator != m_CustomParserFunctions.end())
1151 {
1152 customParserFunction = iterator->second;
1153 }
1154
1155 // Run parser function
1156 (this->*customParserFunction)(subgraphIndex, operatorIndex);
1157}
1158
Kevin May7d96b162021-02-03 17:38:41 +00001159void TfLiteParserImpl::ParseUnsupportedOperator(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001160{
1161 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001162
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001163 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1164
1165 auto opcodeIndex = operatorPtr->opcode_index;
Jim Flynnfca233e2021-09-23 12:16:53 +01001166
1167// 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 +01001168#if defined(ARMNN_POST_TFLITE_2_3)
Jim Flynnfca233e2021-09-23 12:16:53 +01001169 auto opcode = std::max(m_Model->operator_codes[opcodeIndex]->builtin_code,
1170 static_cast<tflite::BuiltinOperator>(m_Model->operator_codes[opcodeIndex]->deprecated_builtin_code));
1171#else
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001172 auto opcode = m_Model->operator_codes[opcodeIndex]->builtin_code;
Jim Flynnfca233e2021-09-23 12:16:53 +01001173#endif
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001174
1175 if (!m_Options || !m_Options.value().m_StandInLayerForUnsupported)
1176 {
1177 // Do not add StandInLayer, throw ParseException instead
1178 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01001179 fmt::format("Operator not supported. "
1180 "subgraph:{} operator:{} "
1181 "opcode_index:{} opcode:{} / {} {}",
1182 subgraphIndex,
1183 operatorIndex,
1184 opcodeIndex,
1185 opcode,
1186 tflite::EnumNameBuiltinOperator(opcode),
1187 CHECK_LOCATION().AsString()));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001188 }
1189
1190 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1191 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1192
Matthew Sloyan589e3e82020-09-11 16:17:48 +01001193 const unsigned int numInputs = armnn::numeric_cast<unsigned int>(inputs.size());
1194 const unsigned int numOutputs = armnn::numeric_cast<unsigned int>(outputs.size());
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001195
1196 StandInDescriptor descriptor(numInputs, numOutputs);
James Ward58dec6b2020-09-11 17:32:44 +01001197 auto layerName = fmt::format("StandIn:{}:{}:{}", subgraphIndex, operatorIndex, opcode);
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001198
1199 // Add a non-executable StandInLayer as a placeholder for any unsupported operator
1200 IConnectableLayer* layer = m_Network->AddStandInLayer(descriptor, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01001201
1202 if (!layer)
1203 {
1204 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1205 operatorIndex, CHECK_LOCATION().AsString()));
1206 }
James Conroy05102392020-06-24 15:39:55 +01001207
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001208 for (unsigned int i = 0u; i < numOutputs; ++i)
1209 {
Mike Kelly04d82292023-01-19 18:29:40 +00001210 layer->GetOutputSlot(i).SetTensorInfo(ToTensorInfo(outputs[0], true));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001211 }
1212
1213 auto inputTensorIds = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1214 auto outputTensorIds = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1215
1216 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIds);
1217 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIds);
telsoa01c577f2c2018-08-31 09:22:23 +01001218}
1219
mathad01b392e982021-04-07 12:07:30 +01001220void TfLiteParserImpl::ParseCast(size_t subgraphIndex, size_t operatorIndex)
1221{
1222 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1223
1224 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1225 CHECK_VALID_SIZE(inputs.size(), 1);
1226 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1227 CHECK_VALID_SIZE(outputs.size(), 1);
1228
1229 auto layerName = fmt::format("Cast:{}:{}", subgraphIndex, operatorIndex);
1230
1231 IConnectableLayer* layer = m_Network->AddCastLayer(layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01001232
1233 if (!layer)
1234 {
1235 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1236 operatorIndex, CHECK_LOCATION().AsString()));
1237 }
mathad01b392e982021-04-07 12:07:30 +01001238
Mike Kelly377fb212023-01-10 15:55:28 +00001239 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
mathad01b392e982021-04-07 12:07:30 +01001240 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1241
1242 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1243 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1244
1245 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1246 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1247}
1248
Kevin May7d96b162021-02-03 17:38:41 +00001249void TfLiteParserImpl::ParseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001250{
1251 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1252
Mike Kelly0d77ae12022-01-07 17:42:27 +00001253 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1254 const auto* options = operatorPtr->builtin_options.AsConv2DOptions();
telsoa01c577f2c2018-08-31 09:22:23 +01001255
1256 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1257
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001258 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1259 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1260 CHECK_VALID_SIZE(outputs.size(), 1);
1261
telsoa01c577f2c2018-08-31 09:22:23 +01001262 Convolution2dDescriptor desc;
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001263 inputs.size() == 3 ?
1264 desc.m_BiasEnabled = true : desc.m_BiasEnabled = false;
telsoa01c577f2c2018-08-31 09:22:23 +01001265 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1266 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +00001267 desc.m_DataLayout = armnn::DataLayout::NHWC;
Pablo Tellof0bd6832019-04-26 17:58:13 +01001268 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1269 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +00001270
Mike Kelly377fb212023-01-10 15:55:28 +00001271 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
1272 armnn::TensorInfo filterTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
telsoa01c577f2c2018-08-31 09:22:23 +01001273
1274 // assuming input is NHWC
1275 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001276 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
telsoa01c577f2c2018-08-31 09:22:23 +01001277
1278 // assuming the filter is OHWI : Output, H, W, Input
1279 // which is essentially the same as NHWC
1280 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001281 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
telsoa01c577f2c2018-08-31 09:22:23 +01001282
Pablo Tellof0bd6832019-04-26 17:58:13 +01001283 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1284 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1285 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1286 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +01001287
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001288 // Add the first input and weights tensor to the registration list.
1289 // The constant weights will be added by SetupConstantLayers.
1290 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1291 std::vector<unsigned int> tensorIndexesToRegister = { inputTensorIndexes[0], inputTensorIndexes[1] };
telsoa01c577f2c2018-08-31 09:22:23 +01001292
James Ward58dec6b2020-09-11 17:32:44 +01001293 auto layerName = fmt::format("Conv2D:{}:{}", subgraphIndex, operatorIndex);
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001294 armnn::IConnectableLayer* layer = m_Network->AddConvolution2dLayer(desc, layerName.c_str());
telsoa01c577f2c2018-08-31 09:22:23 +01001295
Mike Kelly0506ef02023-01-03 16:29:44 +00001296 if (ShouldConstantTensorBeConverted(inputs[1], inputTensorInfo.GetDataType(), filterTensorInfo.GetDataType()))
telsoa01c577f2c2018-08-31 09:22:23 +01001297 {
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001298 m_ConstantsToDequantize.emplace_back(inputs[1]->buffer);
telsoa01c577f2c2018-08-31 09:22:23 +01001299 }
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001300
1301 if (desc.m_BiasEnabled)
telsoa01c577f2c2018-08-31 09:22:23 +01001302 {
Mike Kelly377fb212023-01-10 15:55:28 +00001303 armnn::TensorInfo biasTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001304
1305 // Add the biases input to the registration list, a constant layer will be added by SetupConstantLayers.
1306 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
1307
Mike Kelly0506ef02023-01-03 16:29:44 +00001308 if (ShouldConstantTensorBeConverted(inputs[2], inputTensorInfo.GetDataType(), biasTensorInfo.GetDataType()))
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001309 {
1310 m_ConstantsToDequantize.emplace_back(inputs[2]->buffer);
1311 }
telsoa01c577f2c2018-08-31 09:22:23 +01001312 }
1313
Ryan OSheac229b3f2023-06-27 22:34:54 +01001314 if (!layer)
1315 {
1316 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1317 operatorIndex, CHECK_LOCATION().AsString()));
1318 }
telsoa01c577f2c2018-08-31 09:22:23 +01001319
Mike Kelly377fb212023-01-10 15:55:28 +00001320 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
jimfly01c25411c2018-11-14 17:47:22 +00001321 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001322
1323 // register the input connection slots for the layer, connections are made after all layers have been created
1324 // only the tensors for the inputs are relevant, exclude the const tensors
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001325 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
telsoa01c577f2c2018-08-31 09:22:23 +01001326
jimfly01c25411c2018-11-14 17:47:22 +00001327 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +01001328 // register the output connection slots for the layer, connections are made after all layers have been created
1329 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001330 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, { outputTensorIndexes[0] });
telsoa01c577f2c2018-08-31 09:22:23 +01001331}
1332
Matthew Sloyan4d217c02021-10-07 11:48:58 +01001333// Conv3D support was added in TF 2.5, so for backwards compatibility a hash define is needed.
Cathal Corbett80b4ef02022-05-25 11:21:11 +01001334#if defined(ARMNN_POST_TFLITE_2_4)
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001335void TfLiteParserImpl::ParseConv3D(size_t subgraphIndex, size_t operatorIndex)
1336{
1337 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1338
1339 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1340 const auto* options = operatorPtr->builtin_options.AsConv3DOptions();
1341
1342 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1343
1344 Convolution3dDescriptor desc;
1345 desc.m_BiasEnabled = false;
1346 desc.m_DataLayout = armnn::DataLayout::NDHWC;
1347 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1348 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1349 desc.m_StrideZ = CHECKED_NON_NEGATIVE(options->stride_d);
1350 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1351 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
1352 desc.m_DilationZ = CHECKED_NON_NEGATIVE(options->dilation_d_factor);
1353
1354 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1355 CHECK_VALID_SIZE(inputs.size(), 2, 3);
1356
1357 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1358 CHECK_VALID_SIZE(outputs.size(), 1);
1359
Mike Kelly377fb212023-01-10 15:55:28 +00001360 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
1361 armnn::TensorInfo filterTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001362
1363 // Assuming input is NDHWC
1364 unsigned int inputDepth = inputTensorInfo.GetShape()[1];
1365 unsigned int inputHeight = inputTensorInfo.GetShape()[2];
1366 unsigned int inputWidth = inputTensorInfo.GetShape()[3];
1367
1368 // Assuming the filter is DHWIO : Depth, Height, Width, OutputChannels, InputChannels
1369 unsigned int filterDepth = filterTensorInfo.GetShape()[0];
1370 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1371 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1372
1373 CalcPadding(inputDepth, filterDepth, desc.m_StrideZ,
Teresa Charlin502ab942022-03-23 17:23:07 +00001374 desc.m_DilationZ, desc.m_PadFront, desc.m_PadBack, options->padding);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001375 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1376 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1377 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1378 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
1379
Mike Kelly5880b912022-01-28 16:18:54 +00001380 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo, inputTensorInfo.GetDataType());
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001381
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001382 auto layerName = fmt::format("Conv3D:{}:{}", subgraphIndex, operatorIndex);
1383
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001384 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1385 // Add the first input and weights tensor to the registration list.
1386 // The constant weights will be added by SetupConstantLayers.
1387 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0], inputTensorIndexes[1]};
1388
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001389 if (inputs.size() == 3)
1390 {
1391 desc.m_BiasEnabled = true;
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001392
1393 // Add the biases input to the registration list, a constant layer will be added by SetupConstantLayers.
1394 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001395 }
1396
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001397 armnn::IConnectableLayer* layer = m_Network->AddConvolution3dLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01001398
1399 if (!layer)
1400 {
1401 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1402 operatorIndex, CHECK_LOCATION().AsString()));
1403 }
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001404
Mike Kelly377fb212023-01-10 15:55:28 +00001405 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001406 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1407
1408 // Register the input connection slots for the layer, connections are made after all layers have been created
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001409 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001410
1411 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1412 // Register the output connection slots for the layer, connections are made after all layers have been created
1413 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1414 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1415}
Matthew Sloyan4d217c02021-10-07 11:48:58 +01001416#endif
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001417
Kevin May7d96b162021-02-03 17:38:41 +00001418void TfLiteParserImpl::ParseDepthwiseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001419{
1420 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1421
Mike Kelly0d77ae12022-01-07 17:42:27 +00001422 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1423 const auto* options = operatorPtr->builtin_options.AsDepthwiseConv2DOptions();
telsoa01c577f2c2018-08-31 09:22:23 +01001424
1425 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1426
1427 DepthwiseConvolution2dDescriptor desc;
telsoa01c577f2c2018-08-31 09:22:23 +01001428 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1429 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +00001430 desc.m_DataLayout = armnn::DataLayout::NHWC;
Matthew Jacksond6a9dee2019-07-22 13:53:24 +01001431 CHECKED_NON_NEGATIVE(options->depth_multiplier);
telsoa01c577f2c2018-08-31 09:22:23 +01001432
1433 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1434 CHECK_VALID_SIZE(inputs.size(), 2, 3);
Cathal Corbett06902652022-04-14 17:55:11 +01001435 if (inputs.size() == 3)
1436 {
1437 desc.m_BiasEnabled = true;
1438 }
1439
telsoa01c577f2c2018-08-31 09:22:23 +01001440 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1441 CHECK_VALID_SIZE(outputs.size(), 1);
Pablo Tellof0bd6832019-04-26 17:58:13 +01001442 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1443 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +00001444
Mike Kelly377fb212023-01-10 15:55:28 +00001445 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
1446 armnn::TensorInfo filterTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
telsoa01c577f2c2018-08-31 09:22:23 +01001447
Matteo Martincigh747ef822018-12-18 09:26:39 +00001448 // Assuming input is NHWC
telsoa01c577f2c2018-08-31 09:22:23 +01001449 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1450 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
Matteo Martincigh747ef822018-12-18 09:26:39 +00001451
1452 // TensorflowLite weights come in the format [1, H, W, I * M]
telsoa01c577f2c2018-08-31 09:22:23 +01001453 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1454 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1455
Pablo Tellof0bd6832019-04-26 17:58:13 +01001456 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1457 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1458 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1459 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +01001460
Jan Eilers53ef7952021-06-02 12:01:25 +01001461 // 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 +01001462 auto layerName = fmt::format("DepthwiseConv2D:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001463
Cathal Corbett06902652022-04-14 17:55:11 +01001464 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1465 // Add the first input and weights tensor to the registration list.
1466 // The constant weights will be added by SetupConstantLayers.
1467 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0], inputTensorIndexes[1]};
1468
1469 armnn::IConnectableLayer* layer = m_Network->AddDepthwiseConvolution2dLayer(desc, layerName.c_str());
1470
1471 if (desc.m_BiasEnabled)
telsoa01c577f2c2018-08-31 09:22:23 +01001472 {
1473 desc.m_BiasEnabled = true;
Mike Kelly377fb212023-01-10 15:55:28 +00001474 TensorInfo biasTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
Cathal Corbett06902652022-04-14 17:55:11 +01001475
1476 // Add the biases input to the registration list, a constant layer will be added by SetupConstantLayers.
1477 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
telsoa01c577f2c2018-08-31 09:22:23 +01001478 }
Ryan OSheac229b3f2023-06-27 22:34:54 +01001479
1480 if (!layer)
1481 {
1482 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1483 operatorIndex, CHECK_LOCATION().AsString()));
1484 }
telsoa01c577f2c2018-08-31 09:22:23 +01001485
Mike Kelly377fb212023-01-10 15:55:28 +00001486 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
jimfly01c25411c2018-11-14 17:47:22 +00001487 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001488
1489 // register the input connection slots for the layer, connections are made after all layers have been created
1490 // only the tensors for the inputs are relevant, exclude the const tensors
Cathal Corbett06902652022-04-14 17:55:11 +01001491 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
telsoa01c577f2c2018-08-31 09:22:23 +01001492
jimfly01c25411c2018-11-14 17:47:22 +00001493 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +01001494 // register the output connection slots for the layer, connections are made after all layers have been created
1495 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1496 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1497}
1498
Kevin May7d96b162021-02-03 17:38:41 +00001499void TfLiteParserImpl::ParseDequantize(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsed66d142019-12-06 09:55:55 +00001500{
1501 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1502
1503 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1504 CHECK_VALID_SIZE(inputs.size(), 1);
1505
1506 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1507 CHECK_VALID_SIZE(outputs.size(), 1);
1508
James Ward58dec6b2020-09-11 17:32:44 +01001509 auto layerName = fmt::format("Dequantize:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsed66d142019-12-06 09:55:55 +00001510
1511 IConnectableLayer* layer = m_Network->AddDequantizeLayer(layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01001512
1513 if (!layer)
1514 {
1515 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1516 operatorIndex, CHECK_LOCATION().AsString()));
1517 }
Finn Williamsed66d142019-12-06 09:55:55 +00001518
Mike Kelly377fb212023-01-10 15:55:28 +00001519 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Finn Williamsed66d142019-12-06 09:55:55 +00001520 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1521
1522 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1523 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1524
1525 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1526 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1527}
1528
Teresa Charlin3ab85482021-06-08 16:59:29 +01001529void TfLiteParserImpl::ParseExpandDims(size_t subgraphIndex, size_t operatorIndex)
1530{
1531 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1532
1533 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1534 CHECK_VALID_SIZE(inputs.size(), 2);
1535
1536 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1537 CHECK_VALID_SIZE(outputs.size(), 1);
1538
1539 auto layerName = fmt::format("ExpandDims:{}:{}", subgraphIndex, operatorIndex);
1540
Mike Kelly377fb212023-01-10 15:55:28 +00001541 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Teresa Charlin3ab85482021-06-08 16:59:29 +01001542 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Teresa Charlin3ab85482021-06-08 16:59:29 +01001543 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1544
Teresa Charlina7a605a2023-06-14 14:51:17 +01001545 armnn::TensorInfo axisTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
1546
1547 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1548 if (axisBufferPtr == nullptr)
1549 {
1550 throw ParseException(fmt::format("{}: Operation has invalid inputs. Failed to read axis.",
1551 CHECK_LOCATION().AsString()));
1552 }
1553
1554 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
1555 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
1556 int32_t axis = axisData[0];
1557
1558 auto inputRank = static_cast<int32_t>(inputTensorInfo.GetShape().GetNumDimensions());
1559 auto outputRank = inputRank + 1;
1560 if((axis < -1 * outputRank) || (outputRank <= axis))
1561 {
1562 throw ParseException(fmt::format("{}: Axis {} is not within [-{}, {}) range.",
1563 CHECK_LOCATION().AsString(), axis, outputRank, outputRank));
1564 }
1565
1566 axis = axis < 0 ? (axis + outputRank) : axis;
1567
1568 std::vector<unsigned int> shape(static_cast<unsigned int>(outputRank));
1569 unsigned int inputShapeIndex = 0;
1570 for (unsigned int i = 0; i < static_cast<unsigned int>(outputRank); ++i)
1571 {
1572 if (i == static_cast<unsigned int>(axis))
1573 {
1574 shape[i] = 1;
1575 }
1576 else
1577 {
1578 shape[i] = inputTensorInfo.GetShape()[inputShapeIndex];
1579 ++inputShapeIndex;
1580 }
1581 }
1582
Teresa Charlin3ab85482021-06-08 16:59:29 +01001583 ReshapeDescriptor reshapeDesc;
Teresa Charlina7a605a2023-06-14 14:51:17 +01001584 reshapeDesc.m_TargetShape = TensorShape(static_cast<unsigned int>(outputRank), shape.data());
1585 outputTensorInfo.SetShape(reshapeDesc.m_TargetShape);
Teresa Charlin3ab85482021-06-08 16:59:29 +01001586
1587 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01001588
1589 if (!layer)
1590 {
1591 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1592 operatorIndex, CHECK_LOCATION().AsString()));
1593 } layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Teresa Charlin3ab85482021-06-08 16:59:29 +01001594
Teresa Charlina7a605a2023-06-14 14:51:17 +01001595 auto outputTensorIds = GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex);
1596 m_TensorInfos[outputTensorIds[0]] = outputTensorInfo;
1597
Teresa Charlin3ab85482021-06-08 16:59:29 +01001598 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1599 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1600
1601 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1602 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1603}
1604
Kevin May7d96b162021-02-03 17:38:41 +00001605void TfLiteParserImpl::ParseTranspose(size_t subgraphIndex, size_t operatorIndex)
Keith Davis4cd29a02019-09-09 14:49:20 +01001606{
1607 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1608
1609 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Kevin May85d92602019-09-27 17:21:06 +01001610 CHECK_VALID_SIZE(inputs.size(), 1, 2);
Keith Davis4cd29a02019-09-09 14:49:20 +01001611
1612 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1613 CHECK_VALID_SIZE(outputs.size(), 1);
1614
James Ward58dec6b2020-09-11 17:32:44 +01001615 auto layerName = fmt::format("Transpose:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly08759e22020-03-02 11:41:31 +00001616 TransposeDescriptor desc;
Keith Davis4cd29a02019-09-09 14:49:20 +01001617
josh minorba424d22019-11-13 10:55:17 -06001618 if (inputs.size() == 2)
Kevin May85d92602019-09-27 17:21:06 +01001619 {
Mike Kelly377fb212023-01-10 15:55:28 +00001620 armnn::TensorInfo permuteTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Kevin May85d92602019-09-27 17:21:06 +01001621 BufferRawPtr permuteBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
josh minorba424d22019-11-13 10:55:17 -06001622 auto numPermVecElements = permuteTensorInfo.GetNumElements();
1623 std::vector<unsigned int> permuteShape(numPermVecElements);
Kevin May85d92602019-09-27 17:21:06 +01001624 ::memcpy(permuteShape.data(), permuteBufferPtr->data.data(), permuteTensorInfo.GetNumBytes());
Mike Kelly08759e22020-03-02 11:41:31 +00001625 PermutationVector permutationVector(permuteShape.data(), permuteTensorInfo.GetNumElements());
Kevin May85d92602019-09-27 17:21:06 +01001626
Mike Kelly08759e22020-03-02 11:41:31 +00001627 desc = TransposeDescriptor(permutationVector);
Kevin May85d92602019-09-27 17:21:06 +01001628 }
Mike Kelly377fb212023-01-10 15:55:28 +00001629 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Keith Davis4cd29a02019-09-09 14:49:20 +01001630
James Conroy05102392020-06-24 15:39:55 +01001631 IConnectableLayer* layer = m_Network->AddTransposeLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01001632
1633 if (!layer)
1634 {
1635 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1636 operatorIndex, CHECK_LOCATION().AsString()));
1637 }
Mike Kelly377fb212023-01-10 15:55:28 +00001638
1639 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
1640 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Keith Davis4cd29a02019-09-09 14:49:20 +01001641 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1642
1643 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1644 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1645
1646 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1647 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1648}
1649
Kevin May7d96b162021-02-03 17:38:41 +00001650void TfLiteParserImpl::ParseTransposeConv(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001651{
1652 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1653
Mike Kelly0d77ae12022-01-07 17:42:27 +00001654 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1655 const auto* options = operatorPtr->builtin_options.AsTransposeConvOptions();
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001656
1657 TransposeConvolution2dDescriptor desc;
1658 desc.m_BiasEnabled = false;
1659 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1660 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1661 desc.m_DataLayout = armnn::DataLayout::NHWC;
1662
1663 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
David Monahan61683802021-01-12 09:11:07 +00001664 if (inputs.size() == 4)
1665 {
1666 desc.m_BiasEnabled = true;
1667 }
1668 else
1669 {
1670 CHECK_VALID_SIZE(inputs.size(), 3);
1671 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001672
1673 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1674 CHECK_VALID_SIZE(outputs.size(), 1);
1675
Teresa Charlin024ef0b2023-04-26 11:19:03 +01001676
1677 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
1678 armnn::TensorInfo filterTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
1679
1680 // TfLite uses NHWC tensors
1681 const unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1682 const unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1683
1684 const unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1685 const unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1686
Ryan OSheaf0a35b82023-02-21 18:32:30 +00001687 // This block determines the output shape of the transpose convolution. If the output shape tensor ptr is not null
1688 // And the tensor is a constant, we can access the data at load time and set the output shape of the
1689 // layer. If this is not constant, We do not have access to the shape data, so we have to use
1690 // infer output shape and skip this code block.
1691 if (inputs[0] && IsConstTensor(inputs[0]))
Colm Donelan0ad3ef12020-07-03 15:54:28 +01001692 {
Mike Kelly377fb212023-01-10 15:55:28 +00001693 armnn::TensorInfo tensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Colm Donelan0ad3ef12020-07-03 15:54:28 +01001694 std::vector<int> output_shape(tensorInfo.GetNumElements());
Mike Kelly377fb212023-01-10 15:55:28 +00001695
Colm Donelan0ad3ef12020-07-03 15:54:28 +01001696 if (tensorInfo.GetDataType() == DataType::Signed32)
1697 {
1698 ::memcpy(output_shape.data(), GetBuffer(m_Model, inputs[0]->buffer)->data.data(), tensorInfo.GetNumBytes());
1699 }
1700 if (tensorInfo.GetDataType() == DataType::QAsymmU8)
1701 {
1702 for(unsigned int i=0; i < tensorInfo.GetNumElements(); i++)
1703 {
1704 output_shape[i] = GetBuffer(m_Model, inputs[0]->buffer)->data.data()[i];
1705 }
1706 }
1707 // Change from signed to unsigned int to store in TransposeConvolution2dDescriptor.
1708 for (int dimension : output_shape)
1709 {
1710 desc.m_OutputShape.push_back(static_cast<unsigned int>(dimension));
1711 }
1712 desc.m_OutputShapeEnabled = true;
Teresa Charlin024ef0b2023-04-26 11:19:03 +01001713
1714 // TfLite uses NHWC tensors
1715 const unsigned int outputHeight = desc.m_OutputShape[1];
1716 const unsigned int outputWidth = desc.m_OutputShape[2];
1717
1718 CalcPadding(inputHeight,
1719 filterHeight,
1720 desc.m_StrideY,
1721 1, // DilationY
1722 desc.m_PadTop,
1723 desc.m_PadBottom,
1724 options->padding,
1725 outputHeight);
1726
1727 CalcPadding(inputWidth,
1728 filterWidth,
1729 desc.m_StrideX,
1730 1, // DilationX
1731 desc.m_PadLeft,
1732 desc.m_PadRight,
1733 options->padding,
1734 outputWidth);
Colm Donelan0ad3ef12020-07-03 15:54:28 +01001735 }
Teresa Charlin024ef0b2023-04-26 11:19:03 +01001736 else
1737 {
1738 CalcPadding(inputHeight,
1739 filterHeight,
1740 desc.m_StrideY,
1741 1, // DilationY
1742 desc.m_PadTop,
1743 desc.m_PadBottom,
1744 options->padding);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001745
Teresa Charlin024ef0b2023-04-26 11:19:03 +01001746 CalcPadding(inputWidth,
1747 filterWidth,
1748 desc.m_StrideX,
1749 1, // DilationX
1750 desc.m_PadLeft,
1751 desc.m_PadRight,
1752 options->padding);
1753 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001754
Mike Kelly5880b912022-01-28 16:18:54 +00001755 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo, inputTensorInfo.GetDataType());
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001756
1757 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01001758 auto layerName = fmt::format("TransposeConv:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001759
David Monahan61683802021-01-12 09:11:07 +00001760 if (desc.m_BiasEnabled)
1761 {
Mike Kelly377fb212023-01-10 15:55:28 +00001762 auto biasTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 3);
Mike Kelly5880b912022-01-28 16:18:54 +00001763 auto biasConstTensor = CreateConstTensorNonPermuted(inputs[3], biasTensorInfo, inputTensorInfo.GetDataType());
David Monahan61683802021-01-12 09:11:07 +00001764 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Mike Kelly5880b912022-01-28 16:18:54 +00001765 filterTensorAndData.first,
1766 biasConstTensor.first,
David Monahan61683802021-01-12 09:11:07 +00001767 layerName.c_str());
1768 }
1769 else
1770 {
1771 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Mike Kelly5880b912022-01-28 16:18:54 +00001772 filterTensorAndData.first,
David Monahan61683802021-01-12 09:11:07 +00001773 EmptyOptional(),
1774 layerName.c_str());
1775 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001776
Ryan OSheac229b3f2023-06-27 22:34:54 +01001777 if (!layer)
1778 {
1779 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1780 operatorIndex, CHECK_LOCATION().AsString()));
1781 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001782
Mike Kelly377fb212023-01-10 15:55:28 +00001783 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0 , { 2, 1 });
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001784 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1785
1786 // only the tensors for the inputs are relevant, exclude the const (filter) tensor
1787 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Matthew Jacksonccb25ea2019-08-20 17:18:33 +01001788 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[2]});
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001789
1790 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1791 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1792}
1793
Kevin May7d96b162021-02-03 17:38:41 +00001794void TfLiteParserImpl::ParseAveragePool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001795{
1796 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Average);
1797}
1798
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001799void TfLiteParserImpl::ParseBatchMatMul(size_t subgraphIndex, size_t operatorIndex)
1800{
1801 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1802
1803 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1804 CHECK_VALID_SIZE(inputs.size(), 2);
1805
1806 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1807 CHECK_VALID_SIZE(outputs.size(), 1);
1808
1809 auto layerName = fmt::format("BatchMatMul:{}:{}", subgraphIndex, operatorIndex);
1810
Mike Kelly377fb212023-01-10 15:55:28 +00001811 TensorInfo inputXTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
1812 TensorInfo inputYTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001813
1814 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1815 const auto* options = operatorPtr->builtin_options.AsBatchMatMulOptions();
1816
Teresa Charlinbc37a6b2022-09-22 10:12:58 +01001817 // Adjoint in tensorflow lite performs transpose operation
1818 BatchMatMulDescriptor descriptor(options->adj_x,
1819 options->adj_y,
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001820 false,
Teresa Charlinbc37a6b2022-09-22 10:12:58 +01001821 false);
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001822 // Arbitrary DataLayout
1823
1824 IConnectableLayer* layer = m_Network->AddBatchMatMulLayer(descriptor, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01001825
1826 if (!layer)
1827 {
1828 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1829 operatorIndex, CHECK_LOCATION().AsString()));
1830 }
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001831
Mike Kelly377fb212023-01-10 15:55:28 +00001832 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001833 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1834
1835 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1836 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
1837
1838 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1839 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1840}
1841
Kevin May7d96b162021-02-03 17:38:41 +00001842void TfLiteParserImpl::ParseBatchToSpaceND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001843{
1844 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1845
1846 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1847 CHECK_VALID_SIZE(inputs.size(), 3);
1848
1849 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1850 CHECK_VALID_SIZE(outputs.size(), 1);
1851
Mike Kelly377fb212023-01-10 15:55:28 +00001852 armnn::TensorInfo blockShapeTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001853 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1854
Mike Kelly377fb212023-01-10 15:55:28 +00001855 armnn::TensorInfo cropsTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001856 BufferRawPtr cropsBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1857
1858 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1859 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1860
1861 std::vector<unsigned int> cropsVector(cropsTensorInfo.GetNumElements());
1862 ::memcpy(cropsVector.data(), cropsBufferPtr->data.data(), cropsTensorInfo.GetNumBytes());
1863
1864 size_t step = 2;
1865 std::vector<std::pair<unsigned int, unsigned int>> crops;
1866 for (unsigned int i = 0; i < cropsTensorInfo.GetNumElements() / step; ++i)
1867 {
1868 crops.emplace_back(cropsVector[i * step], cropsVector[i * step + 1]);
1869 }
1870
1871 armnn::BatchToSpaceNdDescriptor desc;
1872 desc.m_BlockShape = blockShape;
1873 desc.m_Crops = crops;
1874 desc.m_DataLayout = armnn::DataLayout::NHWC;
1875
James Ward58dec6b2020-09-11 17:32:44 +01001876 auto layerName = fmt::format("BatchToSpaceND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001877
Mike Kelly377fb212023-01-10 15:55:28 +00001878 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
James Conroy05102392020-06-24 15:39:55 +01001879
1880 IConnectableLayer* layer = m_Network->AddBatchToSpaceNdLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01001881
1882 if (!layer)
1883 {
1884 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1885 operatorIndex, CHECK_LOCATION().AsString()));
1886 }
Mike Kelly377fb212023-01-10 15:55:28 +00001887
1888 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
1889 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001890 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1891
1892 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1893 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1894
1895 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1896 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1897}
1898
Idriss Chaouch564c13d2023-09-01 17:58:38 +01001899void TfLiteParserImpl::ParseBroadcastTo(size_t subgraphIndex, size_t operatorIndex)
1900{
1901 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1902
1903 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1904 CHECK_VALID_SIZE(inputs.size(), 2);
1905
1906 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1907 CHECK_VALID_SIZE(outputs.size(), 1);
1908
1909 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1910 TensorInfo shapeTensorInfo = ToTensorInfo(inputs[1]);
1911 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
1912
1913 auto layerName = fmt::format("Broadcast_to:{}:{}", subgraphIndex, operatorIndex);
1914
1915 BroadcastToDescriptor descriptor;
1916
1917 auto shapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1918 if (shapeBufferPtr != nullptr)
1919 {
1920 std::vector<unsigned int> targetShape;
1921 unsigned int numElement = shapeTensorInfo.GetNumElements();
1922 auto shapeData = reinterpret_cast<const int32_t*>(shapeBufferPtr->data.data());
1923 if (shapeData)
1924 {
1925 for (unsigned int i = 0; i < numElement; ++i)
1926 {
1927 targetShape.push_back(armnn::numeric_cast<unsigned int>(shapeData[i]));
1928 }
1929 descriptor.m_BroadcastToShape = TensorShape(numElement, targetShape.data());
1930 }
1931 /// get dataShape from outputShape if missing
1932 else
1933 {
1934 if(outputTensorInfo.GetShape().GetNumElements() <= 1)
1935 {
1936 ARMNN_THROW_PARSE_EXCEPTION("For Broadcast_to layer, "
1937 "data and output shape are not found in the buffer.");
1938 }
1939 descriptor.m_BroadcastToShape = outputTensorInfo.GetShape();
1940 }
1941 }
1942 else
1943 {
1944 ARMNN_THROW_PARSE_EXCEPTION("For Broadcast_to layer, Shape data was not found in the buffer.");
1945 }
1946
1947 IConnectableLayer* layer = m_Network->AddBroadcastToLayer(descriptor, layerName.c_str());
1948 ARMNN_ASSERT(layer != nullptr);
1949
1950 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1951
1952 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1953 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1954
1955 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1956 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1957}
1958
Kevin May7d96b162021-02-03 17:38:41 +00001959void TfLiteParserImpl::ParseL2Normalization(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson28c94572019-07-18 10:47:03 +01001960{
1961 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1962
1963 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1964 CHECK_VALID_SIZE(inputs.size(), 1);
1965
1966 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1967 CHECK_VALID_SIZE(outputs.size(), 1);
1968
1969 L2NormalizationDescriptor desc;
1970 desc.m_DataLayout = armnn::DataLayout::NHWC;
James Ward58dec6b2020-09-11 17:32:44 +01001971 auto layerName = fmt::format("L2Normalization:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson28c94572019-07-18 10:47:03 +01001972 IConnectableLayer* layer = m_Network->AddL2NormalizationLayer(desc, layerName.c_str());
1973
Ryan OSheac229b3f2023-06-27 22:34:54 +01001974 if (!layer)
1975 {
1976 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1977 operatorIndex, CHECK_LOCATION().AsString()));
1978 }
Matthew Jackson28c94572019-07-18 10:47:03 +01001979
Mike Kelly377fb212023-01-10 15:55:28 +00001980 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Matthew Jackson28c94572019-07-18 10:47:03 +01001981 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1982
1983 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1984 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1985
1986 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1987 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1988}
1989
Kevin May7d96b162021-02-03 17:38:41 +00001990void TfLiteParserImpl::ParseMaxPool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001991{
1992 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Max);
1993}
1994
Kevin May7d96b162021-02-03 17:38:41 +00001995void TfLiteParserImpl::ParseMaximum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001996{
1997 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1998
1999 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2000 CHECK_VALID_SIZE(inputs.size(), 2);
2001
2002 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2003 CHECK_VALID_SIZE(outputs.size(), 1);
2004
James Ward58dec6b2020-09-11 17:32:44 +01002005 auto layerName = fmt::format("Maximum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01002006
Mike Kelly377fb212023-01-10 15:55:28 +00002007 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2008 TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
James Conroy05102392020-06-24 15:39:55 +01002009 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02002010
Mike Kelly3ec30772023-03-08 13:47:17 +00002011 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::Maximum, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002012
2013 if (!layer)
2014 {
2015 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2016 operatorIndex, CHECK_LOCATION().AsString()));
2017 }
Mike Kelly377fb212023-01-10 15:55:28 +00002018
2019 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
2020 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02002021 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2022
2023 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002024 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02002025
2026 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2027 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2028}
2029
Kevin May7d96b162021-02-03 17:38:41 +00002030void TfLiteParserImpl::ParseMinimum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02002031{
2032 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2033
2034 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2035 CHECK_VALID_SIZE(inputs.size(), 2);
2036
2037 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2038 CHECK_VALID_SIZE(outputs.size(), 1);
2039
James Ward58dec6b2020-09-11 17:32:44 +01002040 auto layerName = fmt::format("Minimum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01002041
Mike Kelly377fb212023-01-10 15:55:28 +00002042 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2043 TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
James Conroy05102392020-06-24 15:39:55 +01002044 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02002045
Mike Kelly3ec30772023-03-08 13:47:17 +00002046 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::Minimum, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002047
2048 if (!layer)
2049 {
2050 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2051 operatorIndex, CHECK_LOCATION().AsString()));
2052 }
Mike Kelly377fb212023-01-10 15:55:28 +00002053
2054 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
2055 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02002056 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2057
2058 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002059 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02002060
2061 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2062 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2063}
2064
Kevin May7d96b162021-02-03 17:38:41 +00002065void TfLiteParserImpl::ParsePool(size_t subgraphIndex,
2066 size_t operatorIndex,
2067 PoolingAlgorithm algorithm)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002068{
2069 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2070
Mike Kelly0d77ae12022-01-07 17:42:27 +00002071 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2072 const auto* options = operatorPtr->builtin_options.AsPool2DOptions();
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002073
2074 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
2075
2076 std::string layerName;
2077
2078 switch (algorithm)
2079 {
2080 case PoolingAlgorithm::Average:
2081 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01002082 fmt::format("AveragePool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002083 break;
2084 case PoolingAlgorithm::Max:
2085 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01002086 fmt::format("MaxPool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002087 break;
2088 default:
Ryan OSheac229b3f2023-06-27 22:34:54 +01002089 throw ParseException(fmt::format("Unsupported Pooling Algorithm {}", CHECK_LOCATION().AsString()));
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002090 }
2091
2092 Pooling2dDescriptor desc;
2093
2094 desc.m_PoolType = algorithm;
2095 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
2096 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
2097 desc.m_PoolWidth = CHECKED_NON_NEGATIVE(options->filter_width);
2098 desc.m_PoolHeight = CHECKED_NON_NEGATIVE(options->filter_height);
2099 desc.m_PaddingMethod = PaddingMethod::Exclude;
2100 desc.m_OutputShapeRounding = OutputShapeRounding::Floor;
jimfly01c25411c2018-11-14 17:47:22 +00002101 desc.m_DataLayout = armnn::DataLayout::NHWC;
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002102
2103 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2104 CHECK_VALID_SIZE(inputs.size(), 1);
Mike Kelly377fb212023-01-10 15:55:28 +00002105 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002106
2107 // assuming input is NHWC
2108 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
2109 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
2110
Pablo Tellof0bd6832019-04-26 17:58:13 +01002111 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, 1u,
2112 desc.m_PadTop, desc.m_PadBottom, options->padding);
2113 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, 1u,
2114 desc.m_PadLeft, desc.m_PadRight, options->padding);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002115
2116 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2117 CHECK_VALID_SIZE(outputs.size(), 1);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002118
James Conroy05102392020-06-24 15:39:55 +01002119 IConnectableLayer* layer = m_Network->AddPooling2dLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002120
2121 if (!layer)
2122 {
2123 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2124 operatorIndex, CHECK_LOCATION().AsString()));
2125 }
Mike Kelly377fb212023-01-10 15:55:28 +00002126
2127 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
2128 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
jimfly01c25411c2018-11-14 17:47:22 +00002129 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002130
2131 // register the input connection slots for the layer, connections are made after all layers have been created
2132 // only the tensors for the inputs are relevant, exclude the const tensors
2133 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +00002134 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002135
jimfly01c25411c2018-11-14 17:47:22 +00002136 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002137 // register the output connection slots for the layer, connections are made after all layers have been created
2138 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2139 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2140}
2141
Kevin May7d96b162021-02-03 17:38:41 +00002142void TfLiteParserImpl::ParseSlice(size_t subgraphIndex, size_t operatorIndex)
josh minorba424d22019-11-13 10:55:17 -06002143{
2144 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2145
2146 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2147 CHECK_VALID_SIZE(inputs.size(), 3);
2148 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2149 CHECK_VALID_SIZE(outputs.size(), 1);
2150
2151 SliceDescriptor desc;
2152
2153 // set begin tensor info for slice descriptor
Mike Kelly377fb212023-01-10 15:55:28 +00002154 armnn::TensorInfo beginTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
josh minorba424d22019-11-13 10:55:17 -06002155 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2156
2157 std::vector<unsigned int> begin(beginTensorInfo.GetNumElements());
2158 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
2159
2160 // set size tensor info for slice descriptor
Mike Kelly377fb212023-01-10 15:55:28 +00002161 armnn::TensorInfo sizeTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
josh minorba424d22019-11-13 10:55:17 -06002162 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
2163
Cathal Corbettde33dda2022-09-20 16:40:09 +01002164 std::vector<int> signedSize(sizeTensorInfo.GetNumElements(), 1);
2165
2166 // if size buffer data is not specified, all contents of size vector remain as values of 1
2167 if (sizeBufferPtr->data.data())
2168 {
2169 ::memcpy(signedSize.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
2170 }
2171
josh minorba424d22019-11-13 10:55:17 -06002172 std::vector<unsigned int> size(sizeTensorInfo.GetNumElements());
Mike Kelly377fb212023-01-10 15:55:28 +00002173 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Mike Kelly7ba84d62021-09-10 15:27:19 +01002174
2175 for (unsigned int i = 0; i < signedSize.size(); ++i)
2176 {
2177 int signedValue = signedSize[i];
Jim Flynnfca233e2021-09-23 12:16:53 +01002178
Mike Kelly7ba84d62021-09-10 15:27:19 +01002179 if (signedValue < -1 || signedValue > static_cast<int>(inputTensorInfo.GetShape()[i] - begin[i]))
2180 {
2181 throw ParseException(fmt::format("Invalid value for size {} size must be in range "
2182 "[-1, inputDimSize - begin] [-1, {}] inclusive {}",
2183 signedValue,
2184 inputTensorInfo.GetShape()[i] - begin[i],
2185 CHECK_LOCATION().AsString()));
2186 }
2187
2188 if (signedValue == -1)
2189 {
2190 size[i] = inputTensorInfo.GetShape()[i] - begin[i];
2191 }
2192 else
2193 {
2194 size[i] = static_cast<unsigned int>(signedValue);
2195 }
2196 }
2197
josh minorba424d22019-11-13 10:55:17 -06002198 desc = SliceDescriptor(begin, size);
2199
James Ward58dec6b2020-09-11 17:32:44 +01002200 auto layerName = fmt::format("Slice:{}:{}", subgraphIndex, operatorIndex);
josh minorba424d22019-11-13 10:55:17 -06002201
James Conroy05102392020-06-24 15:39:55 +01002202 IConnectableLayer* const layer = m_Network->AddSliceLayer(desc, layerName.c_str());
Mike Kelly377fb212023-01-10 15:55:28 +00002203
2204 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
2205 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
josh minorba424d22019-11-13 10:55:17 -06002206 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2207
2208 // register the input connection slots for the layer, connections are made after all layers have been created
2209 // only the tensors for the inputs are relevant, exclude the const tensors
2210 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2211 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2212
2213 // register the output connection slots for the layer, connections are made after all layers have been created
2214 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2215 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2216}
2217
Kevin May7d96b162021-02-03 17:38:41 +00002218void TfLiteParserImpl::ParseSoftmax(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01002219{
2220 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00002221 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2222 const auto* options = operatorPtr->builtin_options.AsSoftmaxOptions();
telsoa01c577f2c2018-08-31 09:22:23 +01002223
2224 SoftmaxDescriptor desc;
2225 desc.m_Beta = options->beta;
2226
2227 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2228 CHECK_VALID_SIZE(inputs.size(), 1);
2229 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2230 CHECK_VALID_SIZE(outputs.size(), 1);
2231
James Ward58dec6b2020-09-11 17:32:44 +01002232 auto layerName = fmt::format("Softmax:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01002233 IConnectableLayer* const layer = m_Network->AddSoftmaxLayer(desc, layerName.c_str());
2234
Mike Kelly377fb212023-01-10 15:55:28 +00002235 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
telsoa01c577f2c2018-08-31 09:22:23 +01002236 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2237
2238 // register the input connection slots for the layer, connections are made after all layers have been created
2239 // only the tensors for the inputs are relevant, exclude the const tensors
2240 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2241 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2242
2243 // register the output connection slots for the layer, connections are made after all layers have been created
2244 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2245 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2246}
2247
Teresa Charlinfd33a692022-06-29 15:35:57 +01002248void TfLiteParserImpl::ParseLogSoftmax(size_t subgraphIndex, size_t operatorIndex)
2249{
2250 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2251
2252 LogSoftmaxDescriptor desc;
2253
2254 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2255 CHECK_VALID_SIZE(inputs.size(), 1);
2256 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2257 CHECK_VALID_SIZE(outputs.size(), 1);
2258
2259 auto layerName = fmt::format("LogSoftmax:{}:{}", subgraphIndex, operatorIndex);
2260 IConnectableLayer* const layer = m_Network->AddLogSoftmaxLayer(desc, layerName.c_str());
2261
Mike Kelly377fb212023-01-10 15:55:28 +00002262 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Teresa Charlinfd33a692022-06-29 15:35:57 +01002263 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2264
2265 // register the input connection slots for the layer, connections are made after all layers have been created
2266 // only the tensors for the inputs are relevant, exclude the const tensors
2267 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2268 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2269
2270 // register the output connection slots for the layer, connections are made after all layers have been created
2271 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2272 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2273}
2274
Kevin May7d96b162021-02-03 17:38:41 +00002275void TfLiteParserImpl::ParseSpaceToBatchND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbaded142019-02-08 19:02:48 -02002276{
2277 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2278
2279 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2280 CHECK_VALID_SIZE(inputs.size(), 3);
2281
2282 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2283 CHECK_VALID_SIZE(outputs.size(), 1);
2284
Mike Kelly377fb212023-01-10 15:55:28 +00002285 armnn::TensorInfo blockShapeTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02002286 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2287
Mike Kelly377fb212023-01-10 15:55:28 +00002288 armnn::TensorInfo padListTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02002289 BufferRawPtr padListBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
2290
2291 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
2292 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
2293
2294 std::vector<unsigned int> padListVector(padListTensorInfo.GetNumElements());
2295 ::memcpy(padListVector.data(), padListBufferPtr->data.data(), padListTensorInfo.GetNumBytes());
2296
2297 size_t step = 2;
2298 std::vector<std::pair<unsigned int, unsigned int>> padList;
2299 for (unsigned int i = 0; i < padListTensorInfo.GetNumElements() / step; ++i)
2300 {
2301 padList.emplace_back(padListVector[i * step], padListVector[i * step + 1]);
2302 }
2303
2304 armnn::SpaceToBatchNdDescriptor desc;
2305 desc.m_BlockShape = blockShape;
2306 desc.m_PadList = padList;
2307 desc.m_DataLayout = armnn::DataLayout::NHWC;
2308
James Ward58dec6b2020-09-11 17:32:44 +01002309 auto layerName = fmt::format("SpaceToBatchND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02002310
Mike Kelly377fb212023-01-10 15:55:28 +00002311 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
James Conroy05102392020-06-24 15:39:55 +01002312
2313 IConnectableLayer* layer = m_Network->AddSpaceToBatchNdLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002314
2315 if (!layer)
2316 {
2317 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2318 operatorIndex, CHECK_LOCATION().AsString()));
2319 }
Mike Kelly377fb212023-01-10 15:55:28 +00002320
2321 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
2322 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Bruno Goncalvesbaded142019-02-08 19:02:48 -02002323 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2324
2325 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2326 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2327
2328 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2329 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2330}
2331
Teresa Charlin2a764ad2023-02-24 18:17:31 +00002332void TfLiteParserImpl::ParseSpaceToDepth(size_t subgraphIndex, size_t operatorIndex)
2333{
2334 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2335
2336 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2337 CHECK_VALID_SIZE(inputs.size(), 1);
2338 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2339 CHECK_VALID_SIZE(outputs.size(), 1);
2340
2341 armnn::SpaceToDepthDescriptor descriptor;
2342
2343 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2344 const auto* options = operatorPtr->builtin_options.AsSpaceToDepthOptions();
2345 auto blockSize = options->block_size;
2346 if (blockSize < 2)
2347 {
2348 throw ParseException(
2349 fmt::format("Operation has invalid block size: {} Block size should be >= 2 {}",
2350 blockSize,
2351 CHECK_LOCATION().AsString()));
2352 }
2353 descriptor.m_BlockSize = armnn::numeric_cast<uint32_t>(blockSize);
2354
2355 auto layerName = fmt::format("SpaceToDepth:{}:{}", subgraphIndex, operatorIndex);
2356 IConnectableLayer* layer = m_Network->AddSpaceToDepthLayer(descriptor, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002357
2358 if (!layer)
2359 {
2360 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2361 operatorIndex, CHECK_LOCATION().AsString()));
2362 }
2363
Teresa Charlin2a764ad2023-02-24 18:17:31 +00002364 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
2365 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2366
2367 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2368 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2369
2370 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2371 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2372}
2373
Teresa Charlin3ab85482021-06-08 16:59:29 +01002374armnn::TensorInfo TfLiteParserImpl::OutputShapeOfSqueeze(std::vector<uint32_t> squeezeDims,
Mike Kelly0d77ae12022-01-07 17:42:27 +00002375 const armnn::TensorInfo& inputTensorInfo)
telsoa01c577f2c2018-08-31 09:22:23 +01002376{
Teresa Charlin3ab85482021-06-08 16:59:29 +01002377 CHECK_VALID_SIZE(squeezeDims.size(), 0, 1, 2, 3, 4);
telsoa01c577f2c2018-08-31 09:22:23 +01002378 static const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
2379
2380 if (inputTensorInfo.GetNumDimensions() > 4)
2381 {
2382 std::stringstream ss;
2383 ss << "Input tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
2384 << " shape:" << inputTensorInfo.GetShape() << " "
2385 << CHECK_LOCATION().AsString();
2386 throw ParseException(ss.str());
2387 }
2388
2389 if (squeezeDims.empty())
2390 {
2391 squeezeDims.assign(dimensionSequence,
2392 dimensionSequence+inputTensorInfo.GetNumDimensions());
2393 }
2394
2395 std::vector<uint32_t> outputDims;
2396 for(unsigned int i = 0; i < inputTensorInfo.GetNumDimensions(); i++)
2397 {
2398 bool skipSqueeze = (std::find(squeezeDims.begin(), squeezeDims.end(), i) == squeezeDims.end());
2399 auto currentDimension = inputTensorInfo.GetShape()[i];
2400 if (skipSqueeze || currentDimension != 1)
2401 {
2402 outputDims.push_back(currentDimension);
2403 }
2404 }
2405
2406 if (outputDims.size() > 4)
2407 {
2408 std::stringstream ss;
2409 ss << "Output tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
2410 << " shape:" << inputTensorInfo.GetShape() << " "
2411 << CHECK_LOCATION().AsString();
2412 throw ParseException(ss.str());
2413 }
2414
2415 TensorShape outShape = TensorShape(static_cast<unsigned int>(outputDims.size()),
2416 outputDims.data());
2417
2418 // we need to preserve the tensor type and the quantization data as well
2419 TensorInfo outTensorInfo = inputTensorInfo;
2420 outTensorInfo.SetShape(outShape);
2421
2422 return outTensorInfo;
2423}
2424
Keith Davis0176fd82021-06-01 17:36:32 +01002425void TfLiteParserImpl::ParseShape(size_t subgraphIndex, size_t operatorIndex)
2426{
2427 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2428
2429 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2430 CHECK_VALID_SIZE(inputs.size(), 1);
2431 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2432 CHECK_VALID_SIZE(outputs.size(), 1);
2433
2434 auto layerName = fmt::format("Shape:{}:{}", subgraphIndex, operatorIndex);
2435
2436 IConnectableLayer* layer = m_Network->AddShapeLayer(layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002437
2438 if (!layer)
2439 {
2440 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2441 operatorIndex, CHECK_LOCATION().AsString()));
2442 }
Keith Davis0176fd82021-06-01 17:36:32 +01002443
Mike Kelly377fb212023-01-10 15:55:28 +00002444 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Keith Davis0176fd82021-06-01 17:36:32 +01002445 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2446
2447 // Check if output tensor type is Signed32 or Signed64
2448 if (outputTensorInfo.GetDataType() != armnn::DataType::Signed32 &&
2449 outputTensorInfo.GetDataType() != armnn::DataType::Signed64)
2450 {
2451 throw ParseException(
2452 fmt::format(
2453 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
2454 CHECK_LOCATION().AsString()));
2455 }
2456
2457 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2458 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2459
2460 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2461 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2462}
2463
Kevin May7d96b162021-02-03 17:38:41 +00002464void TfLiteParserImpl::ParseSqueeze(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01002465{
2466 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2467
2468 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2469 CHECK_VALID_SIZE(inputs.size(), 1);
2470
2471 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2472 CHECK_VALID_SIZE(outputs.size(), 1);
2473
2474 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2475 const auto * options = operatorPtr->builtin_options.AsSqueezeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01002476 auto layerName = fmt::format("Squeeze:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01002477
Mike Kelly377fb212023-01-10 15:55:28 +00002478 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Teresa Charlin3ab85482021-06-08 16:59:29 +01002479
2480 std::vector<uint32_t> squeezeDim;
2481 // A single negative dim index is interpreted as a negative index in python
2482 // Meaning the index will be the shape size plus the negative index value
2483 if (options->squeeze_dims.size() == 1 && options->squeeze_dims[0] < 0)
2484 {
2485 int32_t dim = static_cast<int32_t>(inputTensorInfo.GetShape().GetNumDimensions()) + options->squeeze_dims[0];
2486 squeezeDim.push_back(static_cast<uint32_t>(dim));
2487 }
2488 else
2489 {
2490 squeezeDim = AsUnsignedVector(options->squeeze_dims);
2491 }
2492
2493 armnn::TensorInfo outputTensorInfo = TfLiteParserImpl::OutputShapeOfSqueeze(squeezeDim, inputTensorInfo);
2494
James Conroy05102392020-06-24 15:39:55 +01002495 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
telsoa01c577f2c2018-08-31 09:22:23 +01002496
2497 ReshapeDescriptor reshapeDesc;
2498 reshapeDesc.m_TargetShape = outputTensorInfo.GetShape();
2499
Mike Kellyb2293702023-02-14 17:16:12 +00002500 auto outputTensorIds = GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex);
2501 m_TensorInfos[outputTensorIds[0]] = outputTensorInfo;
2502
telsoa01c577f2c2018-08-31 09:22:23 +01002503 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002504
2505 if (!layer)
2506 {
2507 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2508 operatorIndex, CHECK_LOCATION().AsString()));
2509 }
2510
telsoa01c577f2c2018-08-31 09:22:23 +01002511 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2512
2513 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2514 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2515
2516 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2517 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2518}
2519
Kevin May7d96b162021-02-03 17:38:41 +00002520void TfLiteParserImpl::ParseStridedSlice(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002521{
2522 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2523
2524 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2525 CHECK_VALID_SIZE(inputs.size(), 4);
2526
2527 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2528 CHECK_VALID_SIZE(outputs.size(), 1);
2529
Mike Kelly0d77ae12022-01-07 17:42:27 +00002530 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2531 const auto* options = operatorPtr->builtin_options.AsStridedSliceOptions();
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002532
2533 StridedSliceDescriptor desc;
2534 desc.m_BeginMask = options->begin_mask;
2535 desc.m_EllipsisMask = options->ellipsis_mask;
2536 desc.m_EndMask = options->end_mask;
2537 desc.m_NewAxisMask = options->new_axis_mask;
2538 desc.m_ShrinkAxisMask = options->shrink_axis_mask;
2539 desc.m_DataLayout = armnn::DataLayout::NHWC;
2540
Mike Kelly377fb212023-01-10 15:55:28 +00002541 armnn::TensorInfo beginTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002542 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2543
2544 std::vector<int> begin(beginTensorInfo.GetNumElements());
David Monahan39085f72023-07-28 11:37:29 +01002545 if (beginBufferPtr->data.data() != nullptr)
2546 {
2547 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
2548 }
2549 else
2550 {
2551 throw ParseException("ParseStridedSlice: Invalid input - the begin vector is null");
2552 }
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002553
Mike Kelly377fb212023-01-10 15:55:28 +00002554 armnn::TensorInfo endTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002555 BufferRawPtr endBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
2556
2557 std::vector<int> end(endTensorInfo.GetNumElements());
David Monahan39085f72023-07-28 11:37:29 +01002558 if (endBufferPtr->data.data() != nullptr)
2559 {
2560 ::memcpy(end.data(), endBufferPtr->data.data(), endTensorInfo.GetNumBytes());
2561 }
2562 else
2563 {
2564 throw ParseException("ParseStridedSlice: Invalid input - the end vector is null");
2565 }
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002566
Mike Kelly377fb212023-01-10 15:55:28 +00002567 armnn::TensorInfo strideTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 3);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002568 BufferRawPtr strideBufferPtr = GetBuffer(m_Model, inputs[3]->buffer);
2569
2570 std::vector<int> stride(strideTensorInfo.GetNumElements());
David Monahan39085f72023-07-28 11:37:29 +01002571
2572 if (strideBufferPtr->data.data() != nullptr)
2573 {
2574 ::memcpy(stride.data(), strideBufferPtr->data.data(), strideTensorInfo.GetNumBytes());
2575 }
2576 else
2577 {
2578 throw ParseException("ParseStridedSlice: Invalid input - the stride vector is null");
2579 }
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002580
2581 desc.m_Begin = begin;
2582 desc.m_End = end;
2583 desc.m_Stride = stride;
2584
James Ward58dec6b2020-09-11 17:32:44 +01002585 auto layerName = fmt::format("StridedSlice:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002586 IConnectableLayer* layer = m_Network->AddStridedSliceLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002587
2588 if (!layer)
2589 {
2590 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2591 operatorIndex, CHECK_LOCATION().AsString()));
2592 }
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002593
Mike Kelly377fb212023-01-10 15:55:28 +00002594 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002595 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2596
2597 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2598 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2599
2600 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2601 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2602}
2603
Kevin May7d96b162021-02-03 17:38:41 +00002604void TfLiteParserImpl::ParseSub(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002605{
2606 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2607
Mike Kelly0d77ae12022-01-07 17:42:27 +00002608 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2609 const auto* options = operatorPtr->builtin_options.AsSubOptions();
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002610
2611 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2612 CHECK_VALID_SIZE(inputs.size(), 2);
2613
2614 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2615 CHECK_VALID_SIZE(outputs.size(), 1);
2616
Mike Kelly377fb212023-01-10 15:55:28 +00002617 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2618 armnn::TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002619
James Ward58dec6b2020-09-11 17:32:44 +01002620 auto layerName = fmt::format("Sub:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly3ec30772023-03-08 13:47:17 +00002621 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::Sub, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002622
2623 if (!layer)
2624 {
2625 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2626 operatorIndex, CHECK_LOCATION().AsString()));
2627 }
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002628
Mike Kelly377fb212023-01-10 15:55:28 +00002629 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002630 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2631
2632 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002633 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Teresa Charlind04873f2023-05-23 14:16:28 +01002634 if (options)
2635 {
2636 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2637 }
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002638
2639 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2640 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2641}
2642
Kevin May7d96b162021-02-03 17:38:41 +00002643void TfLiteParserImpl::ParseDiv(size_t subgraphIndex, size_t operatorIndex)
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302644{
2645 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2646
Mike Kelly0d77ae12022-01-07 17:42:27 +00002647 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2648 const auto* options = operatorPtr->builtin_options.AsDivOptions();
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302649
2650 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2651 CHECK_VALID_SIZE(inputs.size(), 2);
2652
2653 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2654 CHECK_VALID_SIZE(outputs.size(), 1);
2655
Mike Kelly377fb212023-01-10 15:55:28 +00002656 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2657 armnn::TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302658
James Ward58dec6b2020-09-11 17:32:44 +01002659 auto layerName = fmt::format("Div:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly3ec30772023-03-08 13:47:17 +00002660 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::Div, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002661
2662 if (!layer)
2663 {
2664 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2665 operatorIndex, CHECK_LOCATION().AsString()));
2666 }
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302667
Mike Kelly377fb212023-01-10 15:55:28 +00002668 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302669 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2670
2671 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002672 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Teresa Charlind04873f2023-05-23 14:16:28 +01002673 if (options)
2674 {
2675 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2676 }
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302677
2678 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2679 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2680}
2681
Teresa Charlincdbd40b2022-02-25 13:21:55 +00002682void TfLiteParserImpl::ParseFloorDiv(size_t subgraphIndex, size_t operatorIndex)
2683{
2684 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2685
2686 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2687 CHECK_VALID_SIZE(inputs.size(), 2);
2688
2689 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2690 CHECK_VALID_SIZE(outputs.size(), 1);
2691
Mike Kelly377fb212023-01-10 15:55:28 +00002692 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2693 armnn::TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Teresa Charlincdbd40b2022-02-25 13:21:55 +00002694
2695 auto layerName = fmt::format("Div:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly3ec30772023-03-08 13:47:17 +00002696 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::Div, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002697
2698 if (!layer)
2699 {
2700 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2701 operatorIndex, CHECK_LOCATION().AsString()));
2702 }
Teresa Charlincdbd40b2022-02-25 13:21:55 +00002703
Mike Kelly377fb212023-01-10 15:55:28 +00002704 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Teresa Charlincdbd40b2022-02-25 13:21:55 +00002705 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2706
2707 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2708 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2709 layer = AddFusedFloorLayer(layer, 0);
2710
2711 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2712 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2713}
2714
Kevin May7d96b162021-02-03 17:38:41 +00002715void TfLiteParserImpl::ParseAdd(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002716{
2717 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2718
Mike Kelly0d77ae12022-01-07 17:42:27 +00002719 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2720 const auto* options = operatorPtr->builtin_options.AsAddOptions();
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002721
2722 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2723 CHECK_VALID_SIZE(inputs.size(), 2);
2724
2725 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2726 CHECK_VALID_SIZE(outputs.size(), 1);
2727
Mike Kelly377fb212023-01-10 15:55:28 +00002728 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2729 armnn::TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalves9c761a62018-12-27 14:20:35 -02002730
James Ward58dec6b2020-09-11 17:32:44 +01002731 auto layerName = fmt::format("Add:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly3ec30772023-03-08 13:47:17 +00002732 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::Add, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002733
2734 if (!layer)
2735 {
2736 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2737 operatorIndex, CHECK_LOCATION().AsString()));
2738 }
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002739
Mike Kelly377fb212023-01-10 15:55:28 +00002740 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002741 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2742
2743 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002744 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Teresa Charlind04873f2023-05-23 14:16:28 +01002745 if (options)
2746 {
2747 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2748 }
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002749
2750 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2751 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2752}
2753
Kevin May7d96b162021-02-03 17:38:41 +00002754void TfLiteParserImpl::ParseMul(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002755{
2756 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2757
Mike Kelly0d77ae12022-01-07 17:42:27 +00002758 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2759 const auto* options = operatorPtr->builtin_options.AsMulOptions();
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002760
2761 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2762 CHECK_VALID_SIZE(inputs.size(), 2);
2763
2764 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2765 CHECK_VALID_SIZE(outputs.size(), 1);
2766
Mike Kelly377fb212023-01-10 15:55:28 +00002767 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2768 armnn::TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalves9c761a62018-12-27 14:20:35 -02002769
James Ward58dec6b2020-09-11 17:32:44 +01002770 auto layerName = fmt::format("Mul:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly3ec30772023-03-08 13:47:17 +00002771 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::Mul, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002772
2773 if (!layer)
2774 {
2775 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2776 operatorIndex, CHECK_LOCATION().AsString()));
2777 }
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002778
Mike Kelly377fb212023-01-10 15:55:28 +00002779 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002780 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2781
2782 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002783 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Teresa Charlind04873f2023-05-23 14:16:28 +01002784 if (options)
2785 {
2786 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2787 }
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002788
2789 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2790 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2791}
2792
Kevin May7d96b162021-02-03 17:38:41 +00002793void TfLiteParserImpl::ParseMean(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002794{
2795 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2796
2797 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2798
2799 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2800 CHECK_VALID_SIZE(outputs.size(), 1);
2801
Teresa Charlin046e2cb2023-03-28 17:20:19 +01002802 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2803 TensorInfo dimTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002804
2805 armnn::MeanDescriptor desc;
Teresa Charlin046e2cb2023-03-28 17:20:19 +01002806 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2807 // Get const axis value from model and set it to descriptor.
2808 if (axisBufferPtr != nullptr)
2809 {
2810 std::vector<int32_t> axisData(dimTensorInfo.GetNumElements());
2811 ::memcpy(axisData.data(), axisBufferPtr->data.data(), dimTensorInfo.GetNumBytes());
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002812
Teresa Charlin046e2cb2023-03-28 17:20:19 +01002813 // Convert the axis to unsigned int and remove duplicates.
2814 auto rank = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
2815 std::set<unsigned int> uniqueAxis;
2816 std::transform(axisData.begin(),
2817 axisData.end(),
2818 std::inserter(uniqueAxis, uniqueAxis.begin()),
2819 [rank](int i)->unsigned int{
2820 return static_cast<uint32_t>(((i + rank) % rank)); });
2821 desc.m_Axis.assign(uniqueAxis.begin(), uniqueAxis.end());
2822 }
2823 else
2824 {
2825 for (uint32_t i = 0; i < inputTensorInfo.GetNumDimensions(); ++i)
2826 {
2827 desc.m_Axis.push_back(i);
2828 }
2829 }
2830
Sadik Armagand109a4d2020-07-28 10:42:13 +01002831 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002832
Teresa Charlin046e2cb2023-03-28 17:20:19 +01002833 desc.m_KeepDims = inputTensorInfo.GetNumDimensions() == outputTensorInfo.GetNumDimensions() ? true : false;
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002834
James Ward58dec6b2020-09-11 17:32:44 +01002835 auto layerName = fmt::format("Mean:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002836 IConnectableLayer* layer = m_Network->AddMeanLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002837
2838 if (!layer)
2839 {
2840 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2841 operatorIndex, CHECK_LOCATION().AsString()));
2842 }
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002843
Mike Kelly377fb212023-01-10 15:55:28 +00002844 outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002845 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2846
2847 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2848 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2849
2850 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2851 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2852}
2853
Kevin May7d96b162021-02-03 17:38:41 +00002854void TfLiteParserImpl::ParsePad(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002855{
2856 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2857
Kevin May7d96b162021-02-03 17:38:41 +00002858 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002859
Kevin May7d96b162021-02-03 17:38:41 +00002860 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002861 CHECK_VALID_SIZE(outputs.size(), 1);
2862
Mike Kelly377fb212023-01-10 15:55:28 +00002863 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2864 armnn::TensorInfo padTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002865
Mike Kelly0d77ae12022-01-07 17:42:27 +00002866 std::vector<unsigned int> padBuffer = GetUIntBuffer(padTensorInfo, m_Model, inputs[1]->buffer);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002867
2868 size_t step = 2;
2869 armnn::PadDescriptor desc;
Mike Kelly0d77ae12022-01-07 17:42:27 +00002870 auto opcode = GetOpCode(m_Model, subgraphIndex, operatorIndex);
2871
2872 if (opcode == tflite::BuiltinOperator_PAD)
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00002873 {
Mike Kelly0d77ae12022-01-07 17:42:27 +00002874 CHECK_VALID_SIZE(inputs.size(), 2);
2875
2876 if (inputTensorInfo.IsQuantized())
2877 {
2878 desc.m_PadValue = static_cast<float>(inputTensorInfo.GetQuantizationOffset());
2879 }
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00002880 }
Mike Kelly0d77ae12022-01-07 17:42:27 +00002881 else if (opcode == tflite::BuiltinOperator_PADV2)
2882 {
2883 CHECK_VALID_SIZE(inputs.size(), 3);
2884
Mike Kelly377fb212023-01-10 15:55:28 +00002885 armnn::TensorInfo padValueTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
Mike Kelly0d77ae12022-01-07 17:42:27 +00002886
2887 if (padValueTensorInfo.GetNumElements() != 1)
2888 {
2889 ARMNN_THROW_PARSE_EXCEPTION("Multiple padding values are not supported in PADV2");
2890 }
2891 BufferRawPtr padValueBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
2892
2893 // Get the pad value from the input tensor
2894 if (padValueBufferPtr->data.size() > 0)
2895 {
2896 switch (padValueTensorInfo.GetDataType())
2897 {
2898 case armnn::DataType::Float32:
2899 {
2900 std::vector<float> padValueBuffer(padValueTensorInfo.GetNumElements());
2901 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2902 desc.m_PadValue = padValueBuffer[0];
2903 break;
2904 }
2905 case armnn::DataType::QAsymmU8:
2906 {
2907 std::vector<uint8_t> padValueBuffer(padValueTensorInfo.GetNumElements());
2908 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2909 desc.m_PadValue = armnn::Dequantize<uint8_t>(padValueBuffer[0],
2910 padValueTensorInfo.GetQuantizationScale(),
2911 padValueTensorInfo.GetQuantizationOffset());
2912 break;
2913 }
2914 case armnn::DataType::QAsymmS8:
2915 case armnn::DataType::QSymmS8:
2916 {
2917 std::vector<int8_t> padValueBuffer(padValueTensorInfo.GetNumElements());
2918 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2919 desc.m_PadValue = armnn::Dequantize<int8_t>(padValueBuffer[0],
2920 padValueTensorInfo.GetQuantizationScale(),
2921 padValueTensorInfo.GetQuantizationOffset());
2922 break;
2923 }
2924 default: ARMNN_THROW_PARSE_EXCEPTION("Unsupported DataType");
2925 }
2926 }
2927 else if (inputTensorInfo.IsQuantized())
2928 {
2929 desc.m_PadValue = static_cast<float>(inputTensorInfo.GetQuantizationOffset());
2930 }
2931 }
2932
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002933 for (unsigned int i = 0; i < padTensorInfo.GetNumElements() / step; ++i)
2934 {
2935 desc.m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
2936 }
2937
Mike Kelly0d77ae12022-01-07 17:42:27 +00002938 auto layerName = (opcode == tflite::BuiltinOperator_PAD) ? fmt::format("Pad:{}:{}", subgraphIndex, operatorIndex)
2939 : fmt::format("PadV2:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01002940
2941 IConnectableLayer* layer = m_Network->AddPadLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002942
2943 if (!layer)
2944 {
2945 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2946 operatorIndex, CHECK_LOCATION().AsString()));
2947 }
2948
Mike Kelly377fb212023-01-10 15:55:28 +00002949 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002950 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2951
2952 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2953 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2954
2955 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2956 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2957}
2958
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +01002959void TfLiteParserImpl::ParseMirrorPad(size_t subgraphIndex, size_t operatorIndex)
2960{
2961 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2962
2963 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2964 CHECK_VALID_SIZE(inputs.size(), 2);
2965
2966 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2967 CHECK_VALID_SIZE(outputs.size(), 1);
2968
Mike Kelly377fb212023-01-10 15:55:28 +00002969 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +01002970
Mike Kelly377fb212023-01-10 15:55:28 +00002971 armnn::TensorInfo padTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +01002972 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2973
2974 std::vector<unsigned int> padBuffer(padTensorInfo.GetNumElements());
2975 ::memcpy(padBuffer.data(), bufferPtr->data.data(), padTensorInfo.GetNumBytes());
2976
2977 size_t step = 2;
2978 armnn::PadDescriptor desc;
2979 for (unsigned int i = 0; i < padTensorInfo.GetNumElements() / step; ++i)
2980 {
2981 desc.m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
2982 }
2983
2984 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2985 const auto* options = operatorPtr->builtin_options.AsMirrorPadOptions();
2986
2987 if (options->mode == tflite::MirrorPadMode_REFLECT)
2988 {
2989 desc.m_PaddingMode = PaddingMode::Reflect;
2990 }
2991 else if (options->mode == tflite::MirrorPadMode_SYMMETRIC)
2992 {
2993 desc.m_PaddingMode = PaddingMode::Symmetric;
2994 }
2995 else
2996 {
2997 ARMNN_THROW_PARSE_EXCEPTION("PaddingMode must be either REFLECT or SYMMETRIC");
2998 }
2999
3000 // If padding mode is Reflect then both paddings must be no greater than inputShape(i) - 1.
3001 // If padding mode is Symmetric then both paddings must be no greater than inputShape(i).
3002 auto inputShape = inputTensorInfo.GetShape();
3003 auto padList = desc.m_PadList;
3004
3005 const unsigned int isReflect = static_cast<unsigned int>(desc.m_PaddingMode == PaddingMode::Reflect);
3006 for(unsigned int i = 0; i < padList.size(); ++i)
3007 {
3008 if(padList.at(i).first > (inputShape[i] - isReflect) ||
3009 padList.at(i).second > (inputShape[i] - isReflect))
3010 {
3011 ARMNN_THROW_PARSE_EXCEPTION("Padding values must be less (Reflect) or "
3012 "equal (Symmetric) to the dimension size.");
3013 }
3014 }
3015
3016 auto layerName = fmt::format("MirrorPad:{}:{}", subgraphIndex, operatorIndex);
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +01003017
3018 IConnectableLayer* layer = m_Network->AddPadLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01003019
3020 if (!layer)
3021 {
3022 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3023 operatorIndex, CHECK_LOCATION().AsString()));
3024 }
3025
Mike Kelly377fb212023-01-10 15:55:28 +00003026 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +01003027 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3028
3029 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3030 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3031
3032 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3033 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3034}
3035
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01003036void TfLiteParserImpl::ParsePrelu(size_t subgraphIndex, size_t operatorIndex)
3037{
3038 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3039
3040 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3041 CHECK_VALID_SIZE(inputs.size(), 2);
3042
3043 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3044 CHECK_VALID_SIZE(outputs.size(), 1);
3045
3046 auto layerName = fmt::format("Prelu:{}:{}", subgraphIndex, operatorIndex);
3047
Mike Kelly377fb212023-01-10 15:55:28 +00003048 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
3049 armnn::TensorInfo alphaTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01003050
3051 IConnectableLayer* layer = m_Network->AddPreluLayer(layerName.c_str());
Mike Kelly377fb212023-01-10 15:55:28 +00003052
Ryan OSheac229b3f2023-06-27 22:34:54 +01003053 if (!layer)
3054 {
3055 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3056 operatorIndex, CHECK_LOCATION().AsString()));
3057 }
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01003058
3059 if (IsConstTensor(inputs[1]))
3060 {
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01003061 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawaratbf99b5f2021-05-27 09:55:43 +01003062 armnn::IInputSlot* slot = &(layer->GetInputSlot(0));
3063 RegisterConsumerOfTensor(subgraphIndex, inputTensorIndexes[0], slot);
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01003064
Mike Kelly5880b912022-01-28 16:18:54 +00003065 auto alphaTensorAndData = CreateConstTensorNonPermuted(inputs[1], alphaTensorInfo,
3066 inputTensorInfo.GetDataType());
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01003067 std::string constLayerName = fmt::format("Constant:{}", inputs[1]->name);
3068 IConnectableLayer* constLayer =
Mike Kelly5880b912022-01-28 16:18:54 +00003069 m_Network->AddConstantLayer(alphaTensorAndData.first, constLayerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01003070
3071 if (!constLayer)
3072 {
3073 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3074 operatorIndex, CHECK_LOCATION().AsString()));
3075 }
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01003076
3077 constLayer->GetOutputSlot(0).SetTensorInfo(alphaTensorInfo);
3078 constLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(1));
3079 RegisterOutputSlots(subgraphIndex,
3080 VIRTUAL_OPERATOR_ID,
3081 constLayer,
3082 { inputTensorIndexes[1] });
3083 }
3084 else
3085 {
3086 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3087 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIndexes);
3088 }
3089
Mike Kelly377fb212023-01-10 15:55:28 +00003090 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
3091 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
3092 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3093
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01003094 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3095 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3096}
3097
Kevin May7d96b162021-02-03 17:38:41 +00003098void TfLiteParserImpl::ParseQuantize(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan66dedc72019-12-10 16:32:07 +00003099{
3100 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3101
3102 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3103 CHECK_VALID_SIZE(inputs.size(), 1);
3104
3105 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3106 CHECK_VALID_SIZE(outputs.size(), 1);
3107
James Ward58dec6b2020-09-11 17:32:44 +01003108 auto layerName = fmt::format("Quantize:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan66dedc72019-12-10 16:32:07 +00003109
3110 IConnectableLayer* layer = m_Network->AddQuantizeLayer(layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01003111
3112 if (!layer)
3113 {
3114 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3115 operatorIndex, CHECK_LOCATION().AsString()));
3116 }
Sadik Armagan66dedc72019-12-10 16:32:07 +00003117
Mike Kelly377fb212023-01-10 15:55:28 +00003118 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Sadik Armagan66dedc72019-12-10 16:32:07 +00003119 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3120
3121 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3122 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3123
3124 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3125 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3126}
Finn Williamsc42c3842019-01-22 14:18:11 +00003127
Kevin May7d96b162021-02-03 17:38:41 +00003128void TfLiteParserImpl::ParseRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01003129{
Finn Williamsc42c3842019-01-22 14:18:11 +00003130 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::ReLu);
Sadik Armagan58f39192018-09-17 14:14:39 +01003131}
3132
Kevin May7d96b162021-02-03 17:38:41 +00003133void TfLiteParserImpl::ParseRelu6(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01003134{
Finn Williamsc42c3842019-01-22 14:18:11 +00003135 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::BoundedReLu);
3136}
Sadik Armagan58f39192018-09-17 14:14:39 +01003137
Kevin May7d96b162021-02-03 17:38:41 +00003138void TfLiteParserImpl::ParseLeakyRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan12239e72020-05-27 11:06:17 +01003139{
Jan Eilers2f746b32020-07-28 14:00:06 +01003140 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::LeakyReLu);
Sadik Armagan12239e72020-05-27 11:06:17 +01003141}
3142
Kevin May7d96b162021-02-03 17:38:41 +00003143void TfLiteParserImpl::ParseLogistic(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsc42c3842019-01-22 14:18:11 +00003144{
3145 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::Sigmoid);
3146}
3147
Kevin May7d96b162021-02-03 17:38:41 +00003148void TfLiteParserImpl::ParseTanH(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd99851762019-04-09 09:37:38 +01003149{
3150 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::TanH);
3151}
3152
Kevin May7d96b162021-02-03 17:38:41 +00003153void TfLiteParserImpl::ParseElu(size_t subgraphIndex, size_t operatorIndex)
Matthew Sloyan7515d072020-12-16 12:50:01 +00003154{
3155 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::Elu);
3156}
3157
Kevin May7d96b162021-02-03 17:38:41 +00003158void TfLiteParserImpl::ParseHardSwish(size_t subgraphIndex, size_t operatorIndex)
Jan Eilers2f746b32020-07-28 14:00:06 +01003159{
3160 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::HardSwish);
3161}
Finn Williamsc42c3842019-01-22 14:18:11 +00003162
Teresa Charlin077cddb2023-09-15 15:19:21 +01003163void TfLiteParserImpl::ParseGelu(size_t subgraphIndex, size_t operatorIndex)
3164{
3165 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::Gelu);
3166}
3167
Kevin May7d96b162021-02-03 17:38:41 +00003168void TfLiteParserImpl::ParseActivation(size_t subgraphIndex, size_t operatorIndex, ActivationFunction activationType)
Finn Williamsc42c3842019-01-22 14:18:11 +00003169{
3170 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00003171 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Jan Eilers8eb25602020-03-09 12:13:48 +00003172 IgnoreUnused(operatorPtr);
Sadik Armagan58f39192018-09-17 14:14:39 +01003173
3174 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3175 CHECK_VALID_SIZE(inputs.size(), 1);
3176
3177 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3178 CHECK_VALID_SIZE(outputs.size(), 1);
3179
James Ward58dec6b2020-09-11 17:32:44 +01003180 auto layerName = fmt::format("Activation:");
Sadik Armagan58f39192018-09-17 14:14:39 +01003181 ActivationDescriptor activationDesc;
Finn Williamsc42c3842019-01-22 14:18:11 +00003182 activationDesc.m_Function = activationType;
3183
3184 switch (activationType)
3185 {
3186 case ActivationFunction::ReLu:
3187 {
James Ward58dec6b2020-09-11 17:32:44 +01003188 layerName += fmt::format("RELU:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00003189 break;
3190 }
3191 case ActivationFunction::BoundedReLu:
3192 {
James Ward58dec6b2020-09-11 17:32:44 +01003193 layerName += fmt::format("RELU6:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00003194 activationDesc.m_A = 6.0f;
3195 activationDesc.m_B = 0.0f;
3196 break;
3197 }
3198 case ActivationFunction::Sigmoid:
3199 {
James Ward58dec6b2020-09-11 17:32:44 +01003200 layerName += fmt::format("SIGMOID:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00003201 break;
3202 }
Nina Drozd99851762019-04-09 09:37:38 +01003203 case ActivationFunction::TanH:
3204 {
James Ward58dec6b2020-09-11 17:32:44 +01003205 layerName += fmt::format("TANH:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd99851762019-04-09 09:37:38 +01003206 activationDesc.m_A = 1.0f;
3207 activationDesc.m_B = 1.0f;
3208 break;
3209 }
Sadik Armagan12239e72020-05-27 11:06:17 +01003210 case ActivationFunction::LeakyReLu:
3211 {
James Ward58dec6b2020-09-11 17:32:44 +01003212 layerName += fmt::format("LEAKYRELU:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00003213 const auto* options = operatorPtr->builtin_options.AsLeakyReluOptions();
Sadik Armagan12239e72020-05-27 11:06:17 +01003214 activationDesc.m_A = options->alpha;
3215 break;
3216 }
Matthew Sloyan7515d072020-12-16 12:50:01 +00003217 case ActivationFunction::Elu:
3218 {
3219 layerName += fmt::format("ELU:{}:{}", subgraphIndex, operatorIndex);
3220 activationDesc.m_A = 1.0f;
3221 break;
3222 }
Jan Eilers2f746b32020-07-28 14:00:06 +01003223 case ActivationFunction::HardSwish:
Matthew Sloyan7515d072020-12-16 12:50:01 +00003224 {
James Ward58dec6b2020-09-11 17:32:44 +01003225 layerName += fmt::format("HARDSWISH:{}:{}", subgraphIndex, operatorIndex);
Jan Eilers2f746b32020-07-28 14:00:06 +01003226 break;
Matthew Sloyan7515d072020-12-16 12:50:01 +00003227 }
Teresa Charlin077cddb2023-09-15 15:19:21 +01003228 case ActivationFunction::Gelu:
3229 {
3230 layerName += fmt::format("GELU:{}:{}", subgraphIndex, operatorIndex);
3231 break;
3232 }
Finn Williamsc42c3842019-01-22 14:18:11 +00003233 default:
3234 {
3235 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003236 fmt::format("Unexpected ActivationFunction[{}] when creating layerName {} ",
3237 static_cast<int>(activationType), CHECK_LOCATION().AsString()));
Finn Williamsc42c3842019-01-22 14:18:11 +00003238 }
3239 }
3240
3241 IConnectableLayer* const layer = m_Network->AddActivationLayer(activationDesc, layerName.c_str());
Sadik Armagan58f39192018-09-17 14:14:39 +01003242
Mike Kelly377fb212023-01-10 15:55:28 +00003243 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Sadik Armagan58f39192018-09-17 14:14:39 +01003244 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3245
3246 // register the input connection slots for the layer, connections are made after all layers have been created
3247 // only the tensors for the inputs are relevant, exclude the const tensors
3248 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3249 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3250
3251 // register the output connection slots for the layer, connections are made after all layers have been created
3252 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3253 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3254}
Tianle Cheng20773482023-10-03 12:01:11 +01003255
Mike Kelly0d77ae12022-01-07 17:42:27 +00003256armnn::TensorInfo TfLiteParserImpl::OutputShapeOfReshape(const armnn::TensorInfo& inputTensorInfo,
3257 const std::vector<int32_t>& targetDimsIn)
Sadikb94967b2018-09-19 15:30:00 +01003258{
3259 std::vector<unsigned int> outputDims(targetDimsIn.begin(), targetDimsIn.end());
3260 const auto stretchDim = std::find(targetDimsIn.begin(), targetDimsIn.end(), -1);
3261
3262 if (stretchDim != targetDimsIn.end())
3263 {
3264 if (std::find(std::next(stretchDim), targetDimsIn.end(), -1) != targetDimsIn.end())
3265 {
3266 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003267 fmt::format("At most one component of shape can be -1 {}", CHECK_LOCATION().AsString()));
Sadikb94967b2018-09-19 15:30:00 +01003268 }
3269
3270 auto targetNumElements =
Matthew Sloyan589e3e82020-09-11 16:17:48 +01003271 armnn::numeric_cast<unsigned int>(
Sadikb94967b2018-09-19 15:30:00 +01003272 std::accumulate(targetDimsIn.begin(), targetDimsIn.end(), -1, std::multiplies<int32_t>()));
3273
3274 auto stretchIndex = static_cast<size_t>(std::distance(targetDimsIn.begin(), stretchDim));
Tianle Cheng20773482023-10-03 12:01:11 +01003275
3276 if (targetNumElements == 0)
3277 {
3278 if (inputTensorInfo.GetNumElements() == 0)
3279 {
3280 outputDims[stretchIndex] = 0;
3281 }
3282 else
3283 {
3284 throw ParseException(
3285 fmt::format("Input to reshape is a tensor with elements, but the requested shape has 0. {}",
3286 CHECK_LOCATION().AsString()));
3287 }
3288 }
3289 else
3290 {
3291 outputDims[stretchIndex] = inputTensorInfo.GetNumElements() / targetNumElements;
3292 }
Sadikb94967b2018-09-19 15:30:00 +01003293 }
3294
3295 TensorShape outputShape = TensorShape(static_cast<unsigned int>(outputDims.size()), outputDims.data());
3296
3297 TensorInfo reshapeInfo = inputTensorInfo;
3298 reshapeInfo.SetShape(outputShape);
3299
3300 return reshapeInfo;
3301}
3302
Kevin May7d96b162021-02-03 17:38:41 +00003303void TfLiteParserImpl::ParseReshape(size_t subgraphIndex, size_t operatorIndex)
Sadikb94967b2018-09-19 15:30:00 +01003304{
3305 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3306
3307 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01003308
3309 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3310 CHECK_VALID_SIZE(outputs.size(), 1);
3311
Mike Kelly0d77ae12022-01-07 17:42:27 +00003312 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3313 const auto* options = operatorPtr->builtin_options.AsReshapeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01003314 auto layerName = fmt::format("Reshape:{}:{}", subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01003315
Mike Kelly377fb212023-01-10 15:55:28 +00003316 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
kevmay0171972a82018-12-17 14:28:03 +00003317 armnn::TensorInfo actualOutputTensorInfo = ToTensorInfo(outputs[0]);
James Conroy05102392020-06-24 15:39:55 +01003318 CheckMatchingQuantization(inputTensorInfo, actualOutputTensorInfo, layerName, "Input 0", "Output 0");
Derek Lambertic9e52792020-03-11 11:42:26 +00003319
Jan Eilersbac9b352020-07-13 13:40:24 +01003320 // Extracting new shape for the output
3321 // There are two ways it can be passed
3322 // * First is to define the target shape in the operator built-in options
3323 // * Second is to pass it as a second input tensor
Derek Lambertic9e52792020-03-11 11:42:26 +00003324 std::vector<int32_t> targetShape;
Jan Eilersbac9b352020-07-13 13:40:24 +01003325 bool targetShapeFound = false;
3326 // Check if built-in options were given
3327 if (options != nullptr)
Derek Lambertic9e52792020-03-11 11:42:26 +00003328 {
Jan Eilersbac9b352020-07-13 13:40:24 +01003329 // make sure the parameter is given
3330 if (options->new_shape.empty() == false)
Derek Lambertic9e52792020-03-11 11:42:26 +00003331 {
Jan Eilersbac9b352020-07-13 13:40:24 +01003332 targetShape = options->new_shape;
3333 targetShapeFound = true;
Derek Lambertif4a953f2020-03-17 14:25:57 +00003334 }
Derek Lambertic9e52792020-03-11 11:42:26 +00003335 }
Jan Eilersbac9b352020-07-13 13:40:24 +01003336
3337 // If there is no built-in option given or if the built-in new_shape parameter was empty
3338 if (!targetShapeFound)
Derek Lambertic9e52792020-03-11 11:42:26 +00003339 {
Teresa Charlin6a056a42021-12-01 10:25:43 +00003340 // Check for a second input tensor
3341 if (inputs.size() > 1 && inputs[1] != nullptr)
Jan Eilersbac9b352020-07-13 13:40:24 +01003342 {
3343 if (inputs[1]->is_variable)
3344 {
3345 ARMNN_THROW_PARSE_EXCEPTION( "Target shapes defined in non-const input tensors is not supported");
3346 }
3347
3348 if (inputs[1]->shape.size() != 1)
3349 {
3350 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not a 1D tensor");
3351 }
3352
3353 if (inputs[1]->type != tflite::TensorType_INT32)
3354 {
3355 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not an int32 type");
3356 }
3357
Teresa Charlin6a056a42021-12-01 10:25:43 +00003358 // Extract target shape from input
3359 auto bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
3360 auto values = reinterpret_cast<const int32_t*>(bufferPtr->data.data());
Cathal Corbettd2f73232021-12-10 13:38:52 +00003361 if (values)
Sadik Armagan19a1c032021-01-20 12:17:00 +00003362 {
Cathal Corbettd2f73232021-12-10 13:38:52 +00003363 for (int i = 0; i < inputs[1]->shape[0]; ++i)
3364 {
3365 targetShape.push_back(values[i]);
3366 }
Sadik Armagan19a1c032021-01-20 12:17:00 +00003367 }
Cathal Corbettd2f73232021-12-10 13:38:52 +00003368 else
Jan Eilersbac9b352020-07-13 13:40:24 +01003369 {
Cathal Corbettd2f73232021-12-10 13:38:52 +00003370 try
3371 {
3372 // We attempt to infer during Runtime.
Mike Kelly04d82292023-01-19 18:29:40 +00003373 TensorShape reshapeShapes = ToTensorInfo(inputs[1]).GetShape();
3374
3375 if (reshapeShapes[0] == actualOutputTensorInfo.GetNumDimensions())
3376 {
3377 for (unsigned int i = 0; i < actualOutputTensorInfo.GetShape().GetNumDimensions(); ++i)
3378 {
3379 targetShape.push_back(actualOutputTensorInfo.GetShape()[i]);
3380 }
3381 }
Cathal Corbettd2f73232021-12-10 13:38:52 +00003382 // The parser only supports shape (batch, -1) or (-1) for non-constant shape input.
Mike Kelly04d82292023-01-19 18:29:40 +00003383 else if (reshapeShapes[0] > 2)
Cathal Corbettd2f73232021-12-10 13:38:52 +00003384 {
3385 throw ParseException(fmt::format("Invalid input shape '{}' in Reshape layer '{}' {}. "
3386 "When inferring during runtime, the parser only supports "
3387 "shape (batch, -1) or (-1) for target shape input.",
3388 reshapeShapes[0],
3389 layerName,
3390 CHECK_LOCATION().AsString()));
3391 }
Mike Kelly04d82292023-01-19 18:29:40 +00003392 else
Cathal Corbettd2f73232021-12-10 13:38:52 +00003393 {
Mike Kelly04d82292023-01-19 18:29:40 +00003394 const int32_t numInputElements = inputTensorInfo.GetNumElements();
3395 const int32_t inputTensorShape = inputTensorInfo.GetShape()[0];
3396 if (reshapeShapes[0] == 1)
3397 {
3398 targetShape = {numInputElements};
3399 }
3400 else if (reshapeShapes[0] == 2)
3401 {
3402 targetShape = {inputTensorShape, numInputElements / inputTensorShape};
3403 }
Cathal Corbettd2f73232021-12-10 13:38:52 +00003404 }
3405 }
3406 catch (const std::exception& exc)
3407 {
3408 ARMNN_THROW_PARSE_EXCEPTION("Failed attempt to infer during runtime the target shape input for "
3409 "Reshape operation. Reshape operator target shape input buffer data "
3410 "is null. " << exc.what());
3411 }
Jan Eilersbac9b352020-07-13 13:40:24 +01003412 }
3413 }
3414 else
Derek Lambertic9e52792020-03-11 11:42:26 +00003415 {
3416 ARMNN_THROW_PARSE_EXCEPTION("Target shape not defined in reshape parameters or input tensor. "
3417 "At least one method required");
3418 }
Derek Lambertic9e52792020-03-11 11:42:26 +00003419 }
3420
kevmay0171972a82018-12-17 14:28:03 +00003421 armnn::TensorInfo reshapeOutputTensorInfo =
Kevin May7d96b162021-02-03 17:38:41 +00003422 TfLiteParserImpl::OutputShapeOfReshape(inputTensorInfo, targetShape);
Sadikb94967b2018-09-19 15:30:00 +01003423
kevmay0171972a82018-12-17 14:28:03 +00003424 // Check for valid input size and that reshape parameters equal output shape
Cathal Corbett2b922e22022-09-23 15:49:24 +01003425 // The output shape can be provided to us in 2 ways:
3426 // 1. through the normal 'shape' parameter given by outputs[indx]->shape
3427 // 2. through additional parameter 'shape_signature' given by outputs[indx]->buffer.
3428 // This parameter can sometimes contain -1 value not visible in the 'shape' parameter.
Aron Virginas-Tar70672f62019-01-23 14:00:00 +00003429 const armnn::TensorShape& reshapeOutputTensorShape = reshapeOutputTensorInfo.GetShape();
3430 if (inputs.size() > 1 && !CheckShape(reshapeOutputTensorShape, outputs[0]->shape))
kevmay0171972a82018-12-17 14:28:03 +00003431 {
Cathal Corbett2b922e22022-09-23 15:49:24 +01003432 // Attempt to extract output shape from secondary 'shape_signature'
3433 // parameter and try to CheckShape() with this param.
3434 std::vector<int32_t> secondaryOutputTargetShape = outputs[0]->shape_signature;
3435
3436 // if outputs[0]->shape_signature contain a -1 value, we need to compute its actual value
3437 // from reshape input in order to correctly verify reshape parameters equal output shape
3438 armnn::TensorInfo secondaryReshapeOutputTensorInfo =
3439 TfLiteParserImpl::OutputShapeOfReshape(inputTensorInfo, secondaryOutputTargetShape);
3440
3441 if (!CheckShape(reshapeOutputTensorShape, secondaryReshapeOutputTensorInfo.GetShape()))
3442 {
3443 std::stringstream ss;
3444 ss << "New shape defined in reshape parameters "
3445 << reshapeOutputTensorShape
3446 << " does not equal output shape "
3447 << actualOutputTensorInfo.GetShape()
3448 << ": "
3449 << CHECK_LOCATION().AsString();
3450 throw ParseException(ss.str());
3451 }
kevmay0171972a82018-12-17 14:28:03 +00003452 }
Mike Kelly377fb212023-01-10 15:55:28 +00003453 auto outputTensorIds = GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex);
kevmay0171972a82018-12-17 14:28:03 +00003454
Sadikb94967b2018-09-19 15:30:00 +01003455 ReshapeDescriptor reshapeDesc;
kevmay0171972a82018-12-17 14:28:03 +00003456 reshapeDesc.m_TargetShape = reshapeOutputTensorInfo.GetShape();
Mike Kelly377fb212023-01-10 15:55:28 +00003457 m_TensorInfos[outputTensorIds[0]] = reshapeOutputTensorInfo;
Sadikb94967b2018-09-19 15:30:00 +01003458
Sadikb94967b2018-09-19 15:30:00 +01003459 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01003460
3461 if (!layer)
3462 {
3463 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3464 operatorIndex, CHECK_LOCATION().AsString()));
3465 }
3466
kevmay0171972a82018-12-17 14:28:03 +00003467 layer->GetOutputSlot(0).SetTensorInfo(reshapeOutputTensorInfo);
Sadikb94967b2018-09-19 15:30:00 +01003468
3469 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3470 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3471
3472 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3473 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3474}
3475
Kevin May7d96b162021-02-03 17:38:41 +00003476void TfLiteParserImpl::ParseResizeBilinear(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02003477{
Sadik Armagana3b31f02019-12-05 09:08:53 +00003478 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::Bilinear);
3479}
3480
Kevin May7d96b162021-02-03 17:38:41 +00003481void TfLiteParserImpl::ParseResizeNearestNeighbor(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagana3b31f02019-12-05 09:08:53 +00003482{
3483 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::NearestNeighbor);
3484}
3485
Kevin May7d96b162021-02-03 17:38:41 +00003486void TfLiteParserImpl::ParseResize(size_t subgraphIndex, size_t operatorIndex, ResizeMethod resizeMethod)
Sadik Armagana3b31f02019-12-05 09:08:53 +00003487{
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02003488 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3489
3490 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3491 CHECK_VALID_SIZE(inputs.size(), 2);
3492
3493 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3494 CHECK_VALID_SIZE(outputs.size(), 1);
3495
Mike Kelly377fb212023-01-10 15:55:28 +00003496 armnn::TensorInfo sizeTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02003497
3498 // Data for the parsed tensor args (size) must be stored locally.
3499 std::vector<int32_t> sizeTensorData(sizeTensorInfo.GetNumElements());
3500
3501 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
3502 ::memcpy(sizeTensorData.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
3503
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01003504 ResizeDescriptor desc;
Sadik Armagana3b31f02019-12-05 09:08:53 +00003505 desc.m_Method = resizeMethod;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02003506 desc.m_TargetHeight = static_cast<uint32_t> (sizeTensorData[0]);
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01003507 desc.m_TargetWidth = static_cast<uint32_t> (sizeTensorData[1]);
3508 desc.m_DataLayout = armnn::DataLayout::NHWC;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02003509
James Ward58dec6b2020-09-11 17:32:44 +01003510 auto layerName = fmt::format("Resize:");
Sadik Armagana3b31f02019-12-05 09:08:53 +00003511
3512 switch (resizeMethod)
3513 {
3514 case ResizeMethod::Bilinear:
3515 {
James Ward58dec6b2020-09-11 17:32:44 +01003516 layerName += fmt::format("BILINEAR:{}:{}", subgraphIndex, operatorIndex);
Sang-Hoon Park820eb142020-01-08 10:25:24 +00003517
3518 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3519 const auto * options = operatorPtr->builtin_options.AsResizeBilinearOptions();
3520
David Monahan4a0c9b92020-05-30 09:48:39 +01003521 desc.m_AlignCorners = options->align_corners;
Sadik Armagana3b31f02019-12-05 09:08:53 +00003522 break;
3523 }
3524 case ResizeMethod::NearestNeighbor:
3525 {
James Ward58dec6b2020-09-11 17:32:44 +01003526 layerName += fmt::format("NEARESTNEIGHBOR:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagana3b31f02019-12-05 09:08:53 +00003527 break;
3528 }
3529 default:
3530 {
3531 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003532 fmt::format("Unexpected ResizeMethod[{}] when creating layerName {} ",
3533 static_cast<int>(resizeMethod), CHECK_LOCATION().AsString()));
Sadik Armagana3b31f02019-12-05 09:08:53 +00003534 }
3535 }
3536
Mike Kelly377fb212023-01-10 15:55:28 +00003537 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
James Conroy05102392020-06-24 15:39:55 +01003538
3539 IConnectableLayer* layer = m_Network->AddResizeLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01003540
3541 if (!layer)
3542 {
3543 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3544 operatorIndex, CHECK_LOCATION().AsString()));
3545 }
3546
Mike Kelly377fb212023-01-10 15:55:28 +00003547 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
3548 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02003549 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3550
3551 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3552 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3553
3554 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3555 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3556}
3557
Tianle Chenge5a30ff2023-07-03 11:24:12 +01003558void TfLiteParserImpl::ParseReverseV2(size_t subgraphIndex, size_t operatorIndex)
3559{
3560 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3561
3562 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3563 CHECK_VALID_SIZE(inputs.size(), 2);
3564
3565 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3566 CHECK_VALID_SIZE(outputs.size(), 1);
3567
3568 auto layerName = fmt::format("ReverseV2:{}:{}", subgraphIndex, operatorIndex);
3569
3570 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3571 TensorInfo axisTensorInfo = ToTensorInfo(inputs[1]);
3572 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
3573
Tracy Narinebb8d7592023-07-13 16:50:54 +01003574 IConnectableLayer* layer = m_Network->AddReverseV2Layer(layerName.c_str());
Tianle Chenge5a30ff2023-07-03 11:24:12 +01003575 ARMNN_ASSERT(layer != nullptr);
3576
3577 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3578
3579 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Tracy Narinebb8d7592023-07-13 16:50:54 +01003580 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Tianle Chenge5a30ff2023-07-03 11:24:12 +01003581
3582 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3583 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3584}
3585
Teresa Charlin777008b2023-07-26 10:07:55 +01003586void TfLiteParserImpl::ParseTile(size_t subgraphIndex, size_t operatorIndex)
3587{
3588 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3589
3590 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3591 CHECK_VALID_SIZE(inputs.size(), 2);
3592
3593 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3594 CHECK_VALID_SIZE(outputs.size(), 1);
3595
3596 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3597 TensorInfo multiplesTensorInfo = ToTensorInfo(inputs[1]);
3598 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
3599
3600 auto layerName = fmt::format("Tile:{}:{}", subgraphIndex, operatorIndex);
3601
3602 TileDescriptor descriptor;
3603
3604 BufferRawPtr multiplesBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
3605 if (multiplesBufferPtr != nullptr)
3606 {
3607 std::vector<int32_t> multiplesData(multiplesTensorInfo.GetNumElements());
3608 ::memcpy(multiplesData.data(), multiplesBufferPtr->data.data(), multiplesTensorInfo.GetNumBytes());
3609 descriptor.m_Multiples.assign(multiplesData.begin(), multiplesData.end());
3610 }
3611 else
3612 {
3613 ARMNN_THROW_PARSE_EXCEPTION("For Tile layer, Multiples data was not found in the buffer.");
3614 }
3615
3616 IConnectableLayer* layer = m_Network->AddTileLayer(descriptor, layerName.c_str());
3617 ARMNN_ASSERT(layer != nullptr);
3618
3619 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3620
3621 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3622 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3623
3624 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3625 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3626}
3627
Kevin May7d96b162021-02-03 17:38:41 +00003628void TfLiteParserImpl::ParseConcatenation(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan479045b2018-10-01 11:51:37 +01003629{
3630 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3631
Mike Kelly0d77ae12022-01-07 17:42:27 +00003632 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3633 const auto* options = operatorPtr->builtin_options.AsConcatenationOptions();
Sadik Armagan479045b2018-10-01 11:51:37 +01003634
3635 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
3636
3637 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3638 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Mike Kelly377fb212023-01-10 15:55:28 +00003639 auto inputTensorIds = GetInputTensorIds(m_Model, subgraphIndex, operatorIndex);
3640
Sadik Armagan479045b2018-10-01 11:51:37 +01003641 CHECK_VALID_SIZE(outputs.size(), 1);
3642
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003643 unsigned int numConcatView = static_cast<unsigned int>(inputs.size());
Mike Kelly377fb212023-01-10 15:55:28 +00003644 uint32_t inputRank = InputTensorInfo(subgraphIndex, operatorIndex, 0).GetNumDimensions();
Sadik Armagan479045b2018-10-01 11:51:37 +01003645
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003646 const unsigned int concatDimInput = static_cast<unsigned int>(
Mike Kelly377fb212023-01-10 15:55:28 +00003647 (static_cast<int>(inputRank) + options->axis) % static_cast<int>(inputRank));
Sadik Armagan479045b2018-10-01 11:51:37 +01003648
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003649 OriginsDescriptor concatDescriptor(static_cast<uint32_t>(numConcatView), inputRank);
3650 concatDescriptor.SetConcatAxis(concatDimInput);
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003651 unsigned int mergeDimOrigin = 0;
Sadik Armagan479045b2018-10-01 11:51:37 +01003652
3653 for (unsigned int viewIndex = 0; viewIndex < numConcatView; ++viewIndex)
3654 {
Mike Kelly377fb212023-01-10 15:55:28 +00003655 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, viewIndex);
Sadik Armagan479045b2018-10-01 11:51:37 +01003656
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003657 // This set up concatDescriptor view origin
3658 armnnUtils::ProcessConcatInputTensorInfo(
Mike Kelly377fb212023-01-10 15:55:28 +00003659 inputTensorInfo, concatDescriptor, concatDimInput, viewIndex, mergeDimOrigin);
Sadik Armagan479045b2018-10-01 11:51:37 +01003660 }
3661
James Ward58dec6b2020-09-11 17:32:44 +01003662 auto layerName = fmt::format("Concatenation:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01003663
Jim Flynn906f9462019-05-10 13:55:21 +01003664 IConnectableLayer* layer = m_Network->AddConcatLayer(concatDescriptor, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01003665
3666 if (!layer)
3667 {
3668 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3669 operatorIndex, CHECK_LOCATION().AsString()));
3670 }
3671
Mike Kelly377fb212023-01-10 15:55:28 +00003672 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {});
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003673 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Sadik Armagan479045b2018-10-01 11:51:37 +01003674
James Conroy05102392020-06-24 15:39:55 +01003675 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003676 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
Sadik Armagan479045b2018-10-01 11:51:37 +01003677
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003678 // add fused activation layer
3679 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Sadik Armagan479045b2018-10-01 11:51:37 +01003680
Sadik Armagan479045b2018-10-01 11:51:37 +01003681 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3682 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3683}
3684
Kevin May7d96b162021-02-03 17:38:41 +00003685void TfLiteParserImpl::ParseFullyConnected(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003686{
3687 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3688
Mike Kelly0d77ae12022-01-07 17:42:27 +00003689 const auto& operatorRfr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003690 const auto options = operatorRfr->builtin_options.AsFullyConnectedOptions();
3691
3692 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
3693
3694 FullyConnectedDescriptor desc;
3695 desc.m_BiasEnabled = false;
Nattapat Chaimanowongd8eee592018-10-26 10:24:14 +01003696 desc.m_TransposeWeightMatrix = true;
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003697
3698 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3699 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3700 CHECK_VALID_SIZE(outputs.size(), 1);
3701
Mike Kelly377fb212023-01-10 15:55:28 +00003702 armnn::TensorInfo filterTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003703
3704 // Fully Connected Layer accepts two dimensional weights input
3705 int32_t weightsDimension = static_cast<int32_t>(filterTensorInfo.GetNumDimensions());
3706 if (weightsDimension != 2)
3707 {
3708 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003709 fmt::format("Dimension {} for Fully Connected weights is not supported by Armnn. "
3710 "Node {}",
3711 weightsDimension,
3712 CHECK_LOCATION().AsString()));
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003713 }
3714
Matthew Jackson74bf7da2019-08-16 16:51:42 +01003715 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01003716 auto layerName = fmt::format("FullyConnected:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003717
Matthew Sloyan81beae32021-07-13 19:46:11 +01003718 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3719 // Add the first input tensor to the registration list
3720 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0]};
Mike Kelly377fb212023-01-10 15:55:28 +00003721 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003722
3723 desc.m_ConstantWeights = IsConstTensor(inputs[1]);
3724
Matthew Sloyan81beae32021-07-13 19:46:11 +01003725 // Add the weights input to the registration list, constant layers will be added by SetupConstantLayers if constant.
3726 tensorIndexesToRegister.emplace_back(inputTensorIndexes[1]);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003727
Mike Kelly0506ef02023-01-03 16:29:44 +00003728 if (ShouldConstantTensorBeConverted(inputs[1], inputTensorInfo.GetDataType(), filterTensorInfo.GetDataType()))
Mike Kelly5880b912022-01-28 16:18:54 +00003729 {
3730 m_ConstantsToDequantize.emplace_back(inputs[1]->buffer);
3731 }
3732
Finn Williamsd4fa5452021-03-01 12:31:41 +00003733 if (inputs.size() == 3)
3734 {
3735 desc.m_BiasEnabled = true;
Mike Kelly377fb212023-01-10 15:55:28 +00003736 armnn::TensorInfo biasTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
Matthew Sloyan81beae32021-07-13 19:46:11 +01003737
3738 // Add the biases input to the registration list, constant layer will be added by SetupConstantLayers.
3739 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
Mike Kelly5880b912022-01-28 16:18:54 +00003740
Mike Kelly0506ef02023-01-03 16:29:44 +00003741 if (ShouldConstantTensorBeConverted(inputs[2], inputTensorInfo.GetDataType(), biasTensorInfo.GetDataType()))
Mike Kelly5880b912022-01-28 16:18:54 +00003742 {
3743 m_ConstantsToDequantize.emplace_back(inputs[2]->buffer);
3744 }
Finn Williamsd4fa5452021-03-01 12:31:41 +00003745 }
3746
Matthew Sloyan81beae32021-07-13 19:46:11 +01003747 // Filters and biases are always passed to fully connected as inputs
3748 layer = m_Network->AddFullyConnectedLayer(desc, layerName.c_str());
Finn Williamsd4fa5452021-03-01 12:31:41 +00003749
Ryan OSheac229b3f2023-06-27 22:34:54 +01003750 if (!layer)
3751 {
3752 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3753 operatorIndex, CHECK_LOCATION().AsString()));
3754 }
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003755
Finn Williamsd4fa5452021-03-01 12:31:41 +00003756 unsigned int startingSlotIndex = 0;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003757 if (inputTensorInfo.GetNumDimensions() > 2)
3758 {
3759 // Add reshape to flatten to 2D [batch_size, input_size],
3760 // where "input_size" corresponds to the number of inputs to the layer,
3761 // matching the second dimension of weights,
3762 // and "batch_size" is calculated by dividing the number of elements by "input_size".
3763 std::vector<unsigned int> reshapedDimensions(2);
3764 reshapedDimensions[1] = filterTensorInfo.GetShape()[1];
3765 reshapedDimensions[0] = inputTensorInfo.GetNumElements() / reshapedDimensions[1];
3766
3767 if (inputTensorInfo.GetNumElements() % reshapedDimensions[1] != 0)
3768 {
3769 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003770 fmt::format("Failed to deduce input tensor shape from filter size {} {}",
3771 reshapedDimensions[1],
3772 CHECK_LOCATION().AsString()));
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003773 }
3774
Mike Kelly377fb212023-01-10 15:55:28 +00003775 armnn::TensorInfo reshapedTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003776 reshapedTensorInfo.SetShape(armnn::TensorShape{ 2, reshapedDimensions.data() });
Mike Kelly377fb212023-01-10 15:55:28 +00003777 inputTensorInfo = reshapedTensorInfo;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003778
James Ward58dec6b2020-09-11 17:32:44 +01003779 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Finn Williamsd4fa5452021-03-01 12:31:41 +00003780 armnn::ReshapeDescriptor reshapeDescriptor;
3781 reshapeDescriptor.m_TargetShape = reshapedTensorInfo.GetShape();
Mike Kelly04d82292023-01-19 18:29:40 +00003782 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(reshapeDescriptor,
3783 reshapeLayerName.c_str());
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003784
3785 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedTensorInfo);
3786 reshapeLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(0));
3787
3788 RegisterInputSlots(subgraphIndex, operatorIndex, reshapeLayer, {inputTensorIndexes[0]});
Finn Williamsd4fa5452021-03-01 12:31:41 +00003789 // Fc layer connects to the reshape layer, so we skip the first input slot when registering fc's input slots
3790 tensorIndexesToRegister.erase(tensorIndexesToRegister.begin());
3791 startingSlotIndex = 1;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003792 }
Finn Williamsd4fa5452021-03-01 12:31:41 +00003793
3794 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister, startingSlotIndex);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003795
Mike Kelly377fb212023-01-10 15:55:28 +00003796 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromShapes(subgraphIndex, operatorIndex, layer, 0,
3797 { inputTensorInfo.GetShape(),
3798 filterTensorInfo.GetShape() });
Mike Kelly04d82292023-01-19 18:29:40 +00003799
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003800 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3801
Mike Kelly04d82292023-01-19 18:29:40 +00003802 if (outputTensorInfo.GetNumDimensions() > 2)
3803 {
3804 // Calculate reshape to flatten to 2D [batch_size, input_size]
3805 std::vector<unsigned int> reshapedDimensions(2);
3806 reshapedDimensions[1] = filterTensorInfo.GetShape()[0];
3807 reshapedDimensions[0] = outputTensorInfo.GetNumElements() / reshapedDimensions[1];
3808 armnn::TensorInfo reshapedOutputTensorInfo = outputTensorInfo;
3809 if (outputTensorInfo.GetNumElements() % reshapedDimensions[1] != 0)
3810 {
3811 throw ParseException(
3812 fmt::format("Failed to deduce output tensor shape from filter size {} {}",
3813 reshapedDimensions[1],
3814 CHECK_LOCATION().AsString()));
3815 }
3816 reshapedOutputTensorInfo.SetShape(armnn::TensorShape{ 2, reshapedDimensions.data() });
3817 layer->GetOutputSlot(0).SetTensorInfo(reshapedOutputTensorInfo);
3818
3819 std::string reshapeLayerName = fmt::format("ExpandDims:{}:{}", subgraphIndex, operatorIndex);
3820 layer = AddReshapeLayer(layer, 0, reshapeLayerName, outputTensorInfo);
3821 }
3822
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003823 // we need to add the activation layer and fortunately we don't need to care about the data layout
3824 armnn::IConnectableLayer* fusedActivationLayer = AddFusedActivationLayer(layer, 0,
3825 options->fused_activation_function);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003826
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003827 // register the output connection slots for the layer, connections are made after all layers have been created
3828 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3829 RegisterOutputSlots(subgraphIndex, operatorIndex, fusedActivationLayer, {outputTensorIndexes[0]});
Mike Kelly04d82292023-01-19 18:29:40 +00003830
3831 m_TensorInfos[outputTensorIndexes[0]] = layer->GetOutputSlot(0).GetTensorInfo();
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003832}
3833
Kevin May7d96b162021-02-03 17:38:41 +00003834void TfLiteParserImpl::ParseDetectionPostProcess(size_t subgraphIndex, size_t operatorIndex)
keidav011b3e2ea2019-02-21 10:07:37 +00003835{
3836 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3837
Mike Kelly0d77ae12022-01-07 17:42:27 +00003838 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
keidav011b3e2ea2019-02-21 10:07:37 +00003839
3840 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3841 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3842 CHECK_VALID_SIZE(outputs.size(), 4);
3843
3844 // Obtain custom options from flexbuffers
3845 auto custom_options = operatorPtr->custom_options;
3846 const flexbuffers::Map& m = flexbuffers::GetRoot(custom_options.data(), custom_options.size()).AsMap();
3847
3848 // Obtain descriptor information from tf lite
3849 DetectionPostProcessDescriptor desc;
3850 desc.m_MaxDetections = m["max_detections"].AsUInt32();
3851 desc.m_MaxClassesPerDetection = m["max_classes_per_detection"].AsUInt32();
3852 desc.m_NmsScoreThreshold = m["nms_score_threshold"].AsFloat();
3853 desc.m_NmsIouThreshold = m["nms_iou_threshold"].AsFloat();
3854 desc.m_NumClasses = m["num_classes"].AsUInt32();
3855 desc.m_ScaleH = m["h_scale"].AsFloat();
3856 desc.m_ScaleW = m["w_scale"].AsFloat();
3857 desc.m_ScaleX = m["x_scale"].AsFloat();
3858 desc.m_ScaleY = m["y_scale"].AsFloat();
3859
keidav0107d58c72019-02-26 11:57:39 +00003860 if (!(m["use_regular_nms"].IsNull()))
keidav011b3e2ea2019-02-21 10:07:37 +00003861 {
keidav0107d58c72019-02-26 11:57:39 +00003862 desc.m_UseRegularNms = m["use_regular_nms"].AsBool();
keidav011b3e2ea2019-02-21 10:07:37 +00003863 }
3864 if (!(m["detections_per_class"].IsNull()))
3865 {
3866 desc.m_DetectionsPerClass = m["detections_per_class"].AsUInt32();
3867 }
3868
3869 if (desc.m_NmsIouThreshold <= 0.0f || desc.m_NmsIouThreshold > 1.0f)
3870 {
3871 throw InvalidArgumentException("DetectionPostProcessTFLiteParser: Intersection over union threshold "
3872 "must be positive and less than or equal to 1.");
3873 }
3874
Mike Kelly377fb212023-01-10 15:55:28 +00003875 armnn::TensorInfo anchorTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003876 auto anchorTensorAndData = CreateConstTensorNonPermuted(inputs[2], anchorTensorInfo);
keidav011b3e2ea2019-02-21 10:07:37 +00003877
James Ward58dec6b2020-09-11 17:32:44 +01003878 auto layerName = fmt::format("DetectionPostProcess:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003879 IConnectableLayer* layer = m_Network->AddDetectionPostProcessLayer(desc, anchorTensorAndData,
keidav011b3e2ea2019-02-21 10:07:37 +00003880 layerName.c_str());
3881
Ryan OSheac229b3f2023-06-27 22:34:54 +01003882 if (!layer)
3883 {
3884 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3885 operatorIndex, CHECK_LOCATION().AsString()));
3886 }
keidav011b3e2ea2019-02-21 10:07:37 +00003887
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003888 // The model does not specify the output shapes.
3889 // The output shapes are calculated from the max_detection and max_classes_per_detection.
3890 unsigned int numDetectedBox = desc.m_MaxDetections * desc.m_MaxClassesPerDetection;
Mike Kelly377fb212023-01-10 15:55:28 +00003891 m_OverriddenOutputShapes.push_back({ 1, numDetectedBox, 4 });
3892 m_OverriddenOutputShapes.push_back({ 1, numDetectedBox });
3893 m_OverriddenOutputShapes.push_back({ 1, numDetectedBox });
3894 m_OverriddenOutputShapes.push_back({ 1 });
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003895
keidav011b3e2ea2019-02-21 10:07:37 +00003896 for (unsigned int i = 0 ; i < outputs.size() ; ++i)
3897 {
Mike Kelly377fb212023-01-10 15:55:28 +00003898 armnn::TensorInfo detectionBoxOutputTensorInfo = ToTensorInfo(outputs[i], m_OverriddenOutputShapes[i]);
keidav011b3e2ea2019-02-21 10:07:37 +00003899 layer->GetOutputSlot(i).SetTensorInfo(detectionBoxOutputTensorInfo);
3900 }
3901
3902 // Register the input connection slots for the layer, connections are made after all layers have been created
3903 // only the tensors for the inputs are relevant, exclude the const tensors
3904 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3905 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
3906
3907 // Register the output connection slots for the layer, connections are made after all layers have been created
3908 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3909 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0],
3910 outputTensorIndexes[1],
3911 outputTensorIndexes[2],
3912 outputTensorIndexes[3]});
3913}
3914
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003915/// The TfLite Pack operator is equivalent to the ArmNN Stack operator
Kevin May7d96b162021-02-03 17:38:41 +00003916void TfLiteParserImpl::ParsePack(size_t subgraphIndex, size_t operatorIndex)
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003917{
3918 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3919
3920 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3921 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3922 CHECK_VALID_SIZE(outputs.size(), 1);
3923
3924 if (inputs.size() < 1)
3925 {
3926 throw ParseException("Pack must have at least one input.");
3927 }
3928
3929 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3930 const auto* options = operatorPtr->builtin_options.AsPackOptions();
3931
3932 StackDescriptor desc;
3933 desc.m_Axis = static_cast<uint32_t>(options->axis);
3934 desc.m_NumInputs = static_cast<uint32_t>(inputs.size());
3935
3936 // Use the tensor shape of the first input as the "correct" input shape in the descriptor
Mike Kelly377fb212023-01-10 15:55:28 +00003937 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003938 desc.m_InputShape = inputTensorInfo.GetShape();
3939
James Ward58dec6b2020-09-11 17:32:44 +01003940 auto layerName = fmt::format("Pack:{}:{}", subgraphIndex, operatorIndex);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003941 IConnectableLayer* layer = m_Network->AddStackLayer(desc, layerName.c_str());
3942
Ryan OSheac229b3f2023-06-27 22:34:54 +01003943 if (!layer)
3944 {
3945 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3946 operatorIndex, CHECK_LOCATION().AsString()));
3947 }
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003948
Mike Kelly377fb212023-01-10 15:55:28 +00003949 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {});
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003950 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3951
3952 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3953 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
3954
3955 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3956 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3957}
3958
Mike Kelly5880b912022-01-28 16:18:54 +00003959void TfLiteParserImpl::ParseUnidirectionalSequenceLSTM(size_t subgraphIndex, size_t operatorIndex)
3960{
3961 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3962
3963 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3964 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3965
3966 if (inputs.size() < 2)
3967 {
3968 throw ParseException("UnidirectionalSequenceLSTM must have at least 2 input.");
3969 }
3970
3971 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3972 const auto& subgraphPtr = m_Model->subgraphs[subgraphIndex];
3973 const auto nodeParams = operatorPtr->builtin_options.AsUnidirectionalSequenceLSTMOptions();
3974 CHECK_SUPPORTED_FUSED_ACTIVATION(nodeParams, subgraphIndex, operatorIndex);
Mike Kelly377fb212023-01-10 15:55:28 +00003975 auto inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Mike Kelly5880b912022-01-28 16:18:54 +00003976 auto outputTensorInfo = ToTensorInfo(outputs[0]);
3977
3978 // Set the params structure for the AddUnidirectionalSequenceLstmLayer call
3979 // Please refer to each operand at
3980 // https://www.tensorflow.org/mlir/tfl_ops#tflunidirectional_sequence_lstm_tflunidirectionalsequencelstmop
3981 armnn::LstmInputParams params;
3982
3983 if (IsOptionalOperandPresent(operatorPtr->inputs[1]))
3984 {
3985 params.m_InputToInputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[1]].get(),
3986 inputTensorInfo).first;
3987 }
3988
3989 params.m_InputToForgetWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[2]].get(),
3990 inputTensorInfo).first;
3991 params.m_InputToCellWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[3]].get(),
3992 inputTensorInfo).first;
3993 params.m_InputToOutputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[4]].get(),
3994 inputTensorInfo).first;
3995
3996 // Recurrent weight tensors of size {n_cell, n_output}
3997 if (IsOptionalOperandPresent(operatorPtr->inputs[5]))
3998 {
3999 params.m_RecurrentToInputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[5]].get(),
4000 inputTensorInfo).first;
4001 }
4002
4003 params.m_RecurrentToForgetWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[6]].get(),
4004 inputTensorInfo).first;
4005 params.m_RecurrentToCellWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[7]].get(),
4006 inputTensorInfo).first;
4007 params.m_RecurrentToOutputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[8]].get(),
4008 inputTensorInfo).first;
4009
4010 // Peephole weights tensors of size {n_cell}, representing a diagonal matrix.
4011 if (IsOptionalOperandPresent(operatorPtr->inputs[9]))
4012 {
4013 params.m_CellToInputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[9]].get(),
4014 inputTensorInfo).first;
4015 }
4016
4017 if (IsOptionalOperandPresent(operatorPtr->inputs[10]))
4018 {
4019 params.m_CellToForgetWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[10]].get(),
4020 inputTensorInfo).first;
4021 }
4022
4023 if (IsOptionalOperandPresent(operatorPtr->inputs[11]))
4024 {
4025 params.m_CellToOutputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[11]].get(),
4026 inputTensorInfo).first;
4027 }
4028
4029 // Gates bias tensors of size {n_cell}
4030 if (IsOptionalOperandPresent(operatorPtr->inputs[12]))
4031 {
4032 params.m_InputGateBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[12]].get(),
4033 inputTensorInfo).first;
4034 }
4035
4036 params.m_ForgetGateBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[13]].get(),
4037 inputTensorInfo).first;
4038 params.m_CellBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[14]].get(),
4039 inputTensorInfo).first;
4040 params.m_OutputGateBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[15]].get(),
4041 inputTensorInfo).first;
4042
4043 // Projection weight tensor of size {n_output, n_cell}
4044 if (IsOptionalOperandPresent(operatorPtr->inputs[16]))
4045 {
4046 params.m_ProjectionWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[16]].get(),
4047 inputTensorInfo).first;
4048 }
4049 // Projection bias tensor of size {n_output}
4050 if (IsOptionalOperandPresent(operatorPtr->inputs[17]))
4051 {
4052 params.m_ProjectionBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[17]].get(),
4053 inputTensorInfo).first;
4054 }
4055
4056 // These state tensors are defined as variable tensors, and will be modified by this op.
4057 armnn::TensorInfo outputStateInInfo = ToTensorInfo(subgraphPtr->tensors[operatorPtr->inputs[18]].get());
4058 m_ConstantsToBeCreated.push_back(operatorPtr->inputs[18]);
4059 armnn::TensorInfo cellStateInInfo = ToTensorInfo(subgraphPtr->tensors[operatorPtr->inputs[19]].get());
4060 m_ConstantsToBeCreated.push_back(operatorPtr->inputs[19]);
4061
4062 // Layer norm coefficient tensors of size {n_cell}, representing a diagonal matrix.
4063 if (inputs.size() >= 21 && IsOptionalOperandPresent(operatorPtr->inputs[20]))
4064 {
4065 params.m_InputLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[20]].get(),
4066 inputTensorInfo).first;
4067 }
4068
4069 if (inputs.size() >= 22 && IsOptionalOperandPresent(operatorPtr->inputs[21]))
4070 {
4071 params.m_ForgetLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[21]].get(),
4072 inputTensorInfo).first;
4073 }
4074
4075 if (inputs.size() >= 23 && IsOptionalOperandPresent(operatorPtr->inputs[22]))
4076 {
4077 params.m_CellLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[22]].get(),
4078 inputTensorInfo).first;
4079 }
4080
4081 if (inputs.size() >= 24 && IsOptionalOperandPresent(operatorPtr->inputs[23]))
4082 {
4083 params.m_OutputLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[23]].get(),
4084 inputTensorInfo).first;
4085 }
4086
4087 // set the layer descriptor
4088 armnn::UnidirectionalSequenceLstmDescriptor desc;
4089 desc.m_ActivationFunc = nodeParams->fused_activation_function;
4090 desc.m_ClippingThresCell = nodeParams->cell_clip;
4091 desc.m_ClippingThresProj = nodeParams->proj_clip;
4092 desc.m_CifgEnabled = (params.m_InputToInputWeights == nullptr
4093 || params.m_RecurrentToInputWeights == nullptr
4094 || params.m_InputGateBias == nullptr);
4095 desc.m_PeepholeEnabled = (params.m_CellToForgetWeights != nullptr || params.m_CellToOutputWeights != nullptr);
4096 desc.m_ProjectionEnabled = (params.m_ProjectionWeights != nullptr);
4097 desc.m_LayerNormEnabled = (params.m_InputLayerNormWeights != nullptr
4098 || params.m_ForgetLayerNormWeights != nullptr
4099 || params.m_CellLayerNormWeights != nullptr
4100 || params.m_OutputLayerNormWeights != nullptr);
4101 desc.m_TimeMajor = nodeParams->time_major;
4102
Mike Kellyc0800a32022-06-15 10:57:52 +01004103 if (operatorPtr->intermediates.size() > 3 && desc.m_LayerNormEnabled)
Mike Kelly5880b912022-01-28 16:18:54 +00004104 {
4105 auto inputIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[0]].get(),
4106 inputTensorInfo).first;
4107 auto inputIntermediateTensorInfo = inputIntermediate->GetInfo();
4108 desc.m_InputIntermediateScale = inputIntermediateTensorInfo.GetQuantizationScale();
4109
4110 auto forgetIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[1]].get(),
4111 inputTensorInfo).first;
4112 auto forgetIntermediateTensorInfo = forgetIntermediate->GetInfo();
4113 desc.m_ForgetIntermediateScale = forgetIntermediateTensorInfo.GetQuantizationScale();
4114
4115 auto cellIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[2]].get(),
4116 inputTensorInfo).first;
4117 auto cellIntermediateTensorInfo = cellIntermediate->GetInfo();
4118 desc.m_CellIntermediateScale = cellIntermediateTensorInfo.GetQuantizationScale();
4119
4120 auto outputIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[3]].get(),
4121 inputTensorInfo).first;
4122 auto outputIntermediateTensorInfo = outputIntermediate->GetInfo();
4123 desc.m_OutputIntermediateScale = outputIntermediateTensorInfo.GetQuantizationScale();
4124 }
4125 else
4126 {
4127 float defaultIntermediate = std::pow(2, -12);
4128 desc.m_InputIntermediateScale = defaultIntermediate;
4129 desc.m_ForgetIntermediateScale = defaultIntermediate;
4130 desc.m_CellIntermediateScale = defaultIntermediate;
4131 desc.m_OutputIntermediateScale = defaultIntermediate;
4132 }
4133
Mike Kellyc0800a32022-06-15 10:57:52 +01004134 if (operatorPtr->intermediates.size() > 4)
4135 {
4136 auto hiddentensor = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[4]].get(),
4137 inputTensorInfo).first;
Mike Kelly5880b912022-01-28 16:18:54 +00004138
Mike Kellyc0800a32022-06-15 10:57:52 +01004139 desc.m_HiddenStateScale = hiddentensor->GetInfo().GetQuantizationScale();
4140 desc.m_HiddenStateZeroPoint = hiddentensor->GetInfo().GetQuantizationOffset();
4141 }
Narumol Prangnawarat5f941242023-08-11 16:09:26 +01004142 unsigned int batchSize = desc.m_TimeMajor ? inputTensorInfo.GetShape()[1] : inputTensorInfo.GetShape()[0];
Mike Kelly5880b912022-01-28 16:18:54 +00004143 unsigned int outputSize = outputTensorInfo.GetShape()[2];
4144 unsigned int numUnits = cellStateInInfo.GetShape()[1];
4145
4146 armnn::DataType dataType = inputTensorInfo.GetDataType();
4147 float qScale = inputTensorInfo.GetQuantizationScale();
4148 float qOffset = inputTensorInfo.GetQuantizationOffset();
4149
4150 armnn::TensorInfo scratchBufferTensorInfo({batchSize, numUnits * 3}, dataType, qScale, qOffset);
4151 if (!desc.m_CifgEnabled)
4152 {
4153 scratchBufferTensorInfo = armnn::TensorInfo({batchSize, numUnits * 4}, dataType, qScale, qOffset);
4154 }
4155 armnn::TensorInfo cellStateOutTensorInfo({batchSize, numUnits},
4156 cellStateInInfo.GetDataType(),
4157 cellStateInInfo.GetQuantizationScale(),
4158 cellStateInInfo.GetQuantizationOffset());
4159 armnn::TensorInfo outputStateOutTensorInfo({batchSize, outputSize}, dataType, qScale, qOffset);
4160
4161 armnn::LstmInputParamsInfo paramsInfo;
4162 paramsInfo.m_InputToForgetWeights = &(params.m_InputToForgetWeights->GetInfo());
4163 paramsInfo.m_InputToCellWeights = &(params.m_InputToCellWeights->GetInfo());
4164 paramsInfo.m_InputToOutputWeights = &(params.m_InputToOutputWeights->GetInfo());
4165 paramsInfo.m_RecurrentToForgetWeights = &(params.m_RecurrentToForgetWeights->GetInfo());
4166 paramsInfo.m_RecurrentToCellWeights = &(params.m_RecurrentToCellWeights->GetInfo());
4167 paramsInfo.m_RecurrentToOutputWeights = &(params.m_RecurrentToOutputWeights->GetInfo());
4168 paramsInfo.m_ForgetGateBias = &(params.m_ForgetGateBias->GetInfo());
4169 paramsInfo.m_CellBias = &(params.m_CellBias->GetInfo());
4170 paramsInfo.m_OutputGateBias = &(params.m_OutputGateBias->GetInfo());
4171
4172 if (!desc.m_CifgEnabled)
4173 {
4174 paramsInfo.m_InputToInputWeights = &(params.m_InputToInputWeights->GetInfo());
4175 paramsInfo.m_RecurrentToInputWeights = &(params.m_RecurrentToInputWeights->GetInfo());
4176 if (params.m_CellToInputWeights != nullptr)
4177 {
4178 paramsInfo.m_CellToInputWeights = &(params.m_CellToInputWeights->GetInfo());
4179 }
4180 paramsInfo.m_InputGateBias = &(params.m_InputGateBias->GetInfo());
4181 }
4182
4183 if (desc.m_ProjectionEnabled)
4184 {
4185 paramsInfo.m_ProjectionWeights = &(params.m_ProjectionWeights->GetInfo());
4186 if (params.m_ProjectionBias != nullptr)
4187 {
4188 paramsInfo.m_ProjectionBias = &(params.m_ProjectionBias->GetInfo());
4189 }
4190 }
4191
4192 if (desc.m_PeepholeEnabled)
4193 {
4194 paramsInfo.m_CellToForgetWeights = &(params.m_CellToForgetWeights->GetInfo());
4195 paramsInfo.m_CellToOutputWeights = &(params.m_CellToOutputWeights->GetInfo());
4196 }
4197
4198 if (desc.m_LayerNormEnabled)
4199 {
4200 if(!desc.m_CifgEnabled)
4201 {
4202 paramsInfo.m_InputLayerNormWeights = &(params.m_InputLayerNormWeights->GetInfo());
4203 }
4204 paramsInfo.m_ForgetLayerNormWeights = &(params.m_ForgetLayerNormWeights->GetInfo());
4205 paramsInfo.m_CellLayerNormWeights = &(params.m_CellLayerNormWeights->GetInfo());
4206 paramsInfo.m_OutputLayerNormWeights = &(params.m_OutputLayerNormWeights->GetInfo());
4207 }
4208
4209 auto layerName = fmt::format("UnidirectionalSequenceLSTM:{}:{}", subgraphIndex, operatorIndex);
4210 armnn::IConnectableLayer* layer = m_Network->AddUnidirectionalSequenceLstmLayer(desc, params);
Ryan OSheac229b3f2023-06-27 22:34:54 +01004211
4212 if (!layer)
4213 {
4214 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
4215 operatorIndex, CHECK_LOCATION().AsString()));
4216 }
Mike Kelly5880b912022-01-28 16:18:54 +00004217
4218 // register the input connection slots for the layer, connections are made after all layers have been created
4219 // only the tensors for the inputs are relevant, exclude the const tensors
4220 auto inputTensorIndexes = AsUnsignedVector({operatorPtr->inputs[0],
4221 operatorPtr->inputs[18],
4222 operatorPtr->inputs[19]});
4223 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0],
4224 inputTensorIndexes[1],
4225 inputTensorIndexes[2]});
4226
4227 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4228
4229 layer->GetOutputSlot(0).SetTensorInfo(outputStateOutTensorInfo);
4230 layer->GetOutputSlot(1).SetTensorInfo(cellStateOutTensorInfo);
4231 layer->GetOutputSlot(2).SetTensorInfo(outputTensorInfo);
4232
4233 unsigned int tensorIndex = outputTensorIndexes[0];
4234 armnn::IOutputSlot* slot = &(layer->GetOutputSlot(2));
4235 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
4236}
4237
Kevin May7d96b162021-02-03 17:38:41 +00004238void TfLiteParserImpl::ParseUnpack(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd200e3802019-04-15 09:47:39 +01004239{
4240 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4241
Mike Kelly0d77ae12022-01-07 17:42:27 +00004242 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4243 const auto* options = operatorPtr->builtin_options.AsUnpackOptions();
Nina Drozd200e3802019-04-15 09:47:39 +01004244
4245 // This unpackAxis indicates the axis to unpack
4246 const unsigned int unpackAxis = CHECKED_NON_NEGATIVE(options->axis);
4247
4248 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4249 CHECK_VALID_SIZE(inputs.size(), 1);
4250
Mike Kelly377fb212023-01-10 15:55:28 +00004251 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01004252
4253 if (unpackAxis >= inputTensorInfo.GetNumDimensions())
4254 {
4255 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004256 fmt::format("The unpack axis: {} cannot be greater than or equal to "
4257 "the number of input dimension {} {}",
4258 unpackAxis,
4259 inputTensorInfo.GetNumDimensions(),
4260 CHECK_LOCATION().AsString()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01004261 }
4262
Nina Drozd200e3802019-04-15 09:47:39 +01004263 unsigned int unpackNum = CHECKED_NON_NEGATIVE(options->num);
4264 // If num is not defined, automatically infer from the length of the dimension axis.
4265 if(unpackNum == 0)
4266 {
4267 unpackNum = inputTensorInfo.GetShape()[unpackAxis];
4268 }
4269
4270 // If unpack number cannot be inferred and is still zero, throw ParseException.
4271 if(unpackNum == 0)
4272 {
4273 throw ParseException("Number to unpack must greater than zero.");
4274 }
4275
4276 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4277 CHECK_VALID_SIZE(outputs.size(), unpackNum);
4278
4279 auto inputDimSize = inputTensorInfo.GetNumDimensions();
4280 std::vector<unsigned int> unpackDimSizes(inputDimSize);
4281
4282 // Add current input shape to unpackDimSizes
4283 for (unsigned int i = 0; i < inputDimSize; ++i)
4284 {
4285 unpackDimSizes[i] = inputTensorInfo.GetShape()[i];
4286 }
4287
4288 if (unpackDimSizes[unpackAxis] != unpackNum)
4289 {
4290 throw ParseException("Number to unpack must be the same as length of the dimension to "
4291 "unpack along.");
4292 }
4293
4294 unpackDimSizes[unpackAxis] /= unpackNum;
4295
4296 SplitterDescriptor splitDesc(unpackNum, static_cast<unsigned int>(unpackDimSizes.size()));
4297 for (unsigned int j = 0; j < unpackNum; ++j)
4298 {
4299 // Set the size of the views.
4300 for (unsigned int dimIdx = 0; dimIdx < unpackDimSizes.size(); ++dimIdx)
4301 {
4302 splitDesc.SetViewSize(j, dimIdx, unpackDimSizes[dimIdx]);
4303 }
4304 splitDesc.SetViewOriginCoord(j, unpackAxis, unpackDimSizes[unpackAxis] * j);
4305 }
Mike Kelly363b5722023-10-11 14:25:50 +01004306 splitDesc.SetAxis(unpackAxis);
James Ward58dec6b2020-09-11 17:32:44 +01004307 auto layerName = fmt::format("Unpack:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd200e3802019-04-15 09:47:39 +01004308 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01004309
4310 if (!layer)
4311 {
4312 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
4313 operatorIndex, CHECK_LOCATION().AsString()));
4314 }
Nina Drozd200e3802019-04-15 09:47:39 +01004315
Narumol Prangnawarat672de572019-04-23 15:28:06 +01004316 TensorShape splitOutShape = TensorShape(static_cast<unsigned int>(unpackDimSizes.size()),
4317 unpackDimSizes.data());
4318
Nina Drozd200e3802019-04-15 09:47:39 +01004319 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4320 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4321
Finn Williamsb49ed182021-06-29 15:50:08 +01004322 std::vector<unsigned int> reshapeDims;
4323 for (unsigned int axis = 0; axis < splitOutShape.GetNumDimensions(); ++axis)
4324 {
4325 if (axis != unpackAxis)
4326 {
4327 reshapeDims.push_back(splitOutShape[axis]);
4328 }
4329 }
4330
4331 TensorShape reshapeOutputShape(splitOutShape.GetNumDimensions() -1, reshapeDims.data());
4332
Narumol Prangnawarat672de572019-04-23 15:28:06 +01004333 // Create reshape to remove the unpacked dimension for unpack operator of each output from Splitter.
4334 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
4335 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01004336 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[k], true);
James Ward58dec6b2020-09-11 17:32:44 +01004337 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Narumol Prangnawarat672de572019-04-23 15:28:06 +01004338 armnn::ReshapeDescriptor desc;
Finn Williamsb49ed182021-06-29 15:50:08 +01004339 desc.m_TargetShape = reshapeOutputShape;
Narumol Prangnawarat672de572019-04-23 15:28:06 +01004340 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(desc, layerName.c_str());
4341
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01004342 layer->GetOutputSlot(k).SetTensorInfo(armnn::TensorInfo(splitOutShape,
4343 outputTensorInfo.GetDataType(),
4344 outputTensorInfo.GetQuantizationScale(),
4345 outputTensorInfo.GetQuantizationOffset()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01004346 layer->GetOutputSlot(k).Connect(reshapeLayer->GetInputSlot(0));
4347
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01004348 reshapeLayer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01004349
4350 uint32_t reshapedOutputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[k]);
4351 armnn::IOutputSlot* slot = &(reshapeLayer->GetOutputSlot(0));
4352 RegisterProducerOfTensor(subgraphIndex, reshapedOutputId, slot);
4353 }
Nina Drozd200e3802019-04-15 09:47:39 +01004354}
4355
Kevin May7d96b162021-02-03 17:38:41 +00004356void TfLiteParserImpl::ParseSplit(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd0324f482019-04-08 10:52:10 +01004357{
4358 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4359
Mike Kelly0d77ae12022-01-07 17:42:27 +00004360 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4361 const auto* options = operatorPtr->builtin_options.AsSplitOptions();
Nina Drozd0324f482019-04-08 10:52:10 +01004362
4363 const unsigned int numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
4364
Nina Drozd200e3802019-04-15 09:47:39 +01004365 // If number of splits cannot be inferred and is zero, throw ParseException.
4366 if(numSplits == 0)
4367 {
4368 throw ParseException("Number to splits must greater than zero.");
4369 }
4370
Nina Drozd0324f482019-04-08 10:52:10 +01004371 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4372 CHECK_VALID_SIZE(inputs.size(), 2);
4373 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4374 CHECK_VALID_SIZE(outputs.size(), numSplits);
4375
Mike Kelly377fb212023-01-10 15:55:28 +00004376 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
4377 armnn::TensorInfo axisTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Ryan OSheac229b3f2023-06-27 22:34:54 +01004378
4379 if (axisTensorInfo.GetNumElements() != 1)
4380 {
4381 throw ParseException(fmt::format("Axis tensor can only have 1 element {}",
4382 CHECK_LOCATION().AsString()));
4383 }
Nina Drozd0324f482019-04-08 10:52:10 +01004384
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01004385 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01004386 if (axisBufferPtr == nullptr)
4387 {
4388 throw ParseException(
4389 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
4390 CHECK_LOCATION().AsString()));
4391 }
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01004392
Matthew Sloyaned7fce42021-04-15 20:46:24 +01004393 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
4394 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
4395 int32_t axis = axisData[0];
4396
4397 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
4398 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
4399 {
4400 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
4401 // E.g. Rank 4 tensor can have axis in range [-4, 3)
4402 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
4403 throw ParseException(
4404 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
4405 axis,
4406 CHECK_LOCATION().AsString()));
4407 }
4408
4409 const unsigned int splitDim = armnnUtils::GetUnsignedAxis(inputTensorInfo.GetNumDimensions(), axis);
Nina Drozd0324f482019-04-08 10:52:10 +01004410
Nina Drozd0324f482019-04-08 10:52:10 +01004411 auto inputDimSize = inputTensorInfo.GetNumDimensions();
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01004412 if (inputDimSize > MaxNumOfTensorDimensions)
Nina Drozd0324f482019-04-08 10:52:10 +01004413 {
4414 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004415 fmt::format("The number of dimensions: {} for input tensors of the split op cannot be greater than {} {}",
4416 inputTensorInfo.GetNumDimensions(),
4417 MaxNumOfTensorDimensions,
4418 CHECK_LOCATION().AsString()));
Nina Drozd0324f482019-04-08 10:52:10 +01004419 }
4420
4421 std::vector<unsigned int> splitterDimSizes(inputDimSize);
4422
4423 // Add current input shape to splitterDimSizes
4424 for (unsigned int i = 0; i < inputDimSize; ++i)
4425 {
4426 splitterDimSizes[i] = inputTensorInfo.GetShape()[i];
4427 }
4428
4429 if (splitterDimSizes[splitDim] % numSplits != 0)
4430 {
4431 throw ParseException("Number of splits must evenly divide the dimension");
4432 }
4433 splitterDimSizes[splitDim] /= numSplits;
4434
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01004435 SplitterDescriptor splitDesc(numSplits, inputDimSize);
Nina Drozd0324f482019-04-08 10:52:10 +01004436 for (unsigned int j = 0; j < numSplits; ++j)
4437 {
4438 // Set the size of the views.
4439 for (unsigned int dimIdx = 0; dimIdx < splitterDimSizes.size(); ++dimIdx)
4440 {
4441 splitDesc.SetViewSize(j, dimIdx, splitterDimSizes[dimIdx]);
4442 }
4443 splitDesc.SetViewOriginCoord(j, splitDim, splitterDimSizes[splitDim] * j);
4444 }
Mike Kelly363b5722023-10-11 14:25:50 +01004445 if (axisTensorInfo.GetNumElements() == 1)
4446 {
4447 splitDesc.SetAxis(axis);
4448 }
James Ward58dec6b2020-09-11 17:32:44 +01004449 auto layerName = fmt::format("Split:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd0324f482019-04-08 10:52:10 +01004450 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01004451
4452 if (!layer)
4453 {
4454 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
4455 operatorIndex, CHECK_LOCATION().AsString()));
4456 }
Nina Drozd0324f482019-04-08 10:52:10 +01004457
4458 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01004459 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[1]});
Nina Drozd0324f482019-04-08 10:52:10 +01004460
Nina Drozd0324f482019-04-08 10:52:10 +01004461 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
4462 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01004463 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Francis Murtagh98d6b3d2019-10-21 10:52:54 +01004464 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
Nina Drozd0324f482019-04-08 10:52:10 +01004465 }
4466
4467 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4468 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
4469}
4470
Derek Lambertif0176992020-04-28 13:37:49 +01004471unsigned int ComputeWrappedIndex(int idx, unsigned int numDimsIn)
4472{
4473 int numDims = armnn::numeric_cast<int>(numDimsIn);
4474 int v = idx < 0 ? numDims + idx : idx;
Ryan OSheac229b3f2023-06-27 22:34:54 +01004475
4476 if (v < 0 || v > numDims)
4477 {
4478 throw ParseException(fmt::format("Unable to compute index {}", CHECK_LOCATION().AsString()));
4479 }
Derek Lambertif0176992020-04-28 13:37:49 +01004480
4481 return static_cast<unsigned int>(v);
4482}
4483
Kevin May7d96b162021-02-03 17:38:41 +00004484void TfLiteParserImpl::ParseSplitV(size_t subgraphIndex, size_t operatorIndex)
Derek Lambertif0176992020-04-28 13:37:49 +01004485{
4486 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4487
Mike Kelly0d77ae12022-01-07 17:42:27 +00004488 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4489 const auto* options = operatorPtr->builtin_options.AsSplitVOptions();
Derek Lambertif0176992020-04-28 13:37:49 +01004490
4491 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4492 CHECK_VALID_SIZE(inputs.size(), 3);
4493
4494 auto& inputTensor = inputs[0];
4495 auto& splitsTensor = inputs[1];
4496 auto& axisTensor = inputs[2];
4497
4498 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputTensor);
4499 armnn::TensorInfo splitsInfo = ToTensorInfo(splitsTensor);
4500 armnn::TensorInfo axisTensorInfo = ToTensorInfo(axisTensor);
Ryan OSheac229b3f2023-06-27 22:34:54 +01004501
4502 if (axisTensorInfo.GetNumElements() != 1)
4503 {
4504 throw ParseException(fmt::format("Axis tensor can only have 1 element {}",
4505 CHECK_LOCATION().AsString()));
4506 }
Derek Lambertif0176992020-04-28 13:37:49 +01004507
4508 // Inputs
4509 auto inputDimSize = inputTensorInfo.GetNumDimensions();
4510 if (inputDimSize > MaxNumOfTensorDimensions)
4511 {
4512 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004513 fmt::format("The number of dimensions: {} for input tensors of the "
4514 "SplitV op cannot be greater than {} {}",
4515 inputTensorInfo.GetNumDimensions(),
4516 MaxNumOfTensorDimensions,
4517 CHECK_LOCATION().AsString()));
Derek Lambertif0176992020-04-28 13:37:49 +01004518 }
4519
4520 // Get split axis
4521 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, axisTensor->buffer);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01004522 if (axisBufferPtr == nullptr)
4523 {
4524 throw ParseException(
4525 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
4526 CHECK_LOCATION().AsString()));
4527 }
4528
Derek Lambertif0176992020-04-28 13:37:49 +01004529 std::vector<int> axisData(axisTensorInfo.GetNumElements());
4530 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
Matthew Sloyaned7fce42021-04-15 20:46:24 +01004531 int32_t axis = axisData[0];
4532
4533 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
4534 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
4535 {
4536 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
4537 // E.g. Rank 4 tensor can have axis in range [-4, 3)
4538 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
4539 throw ParseException(
4540 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
4541 axis,
4542 CHECK_LOCATION().AsString()));
4543 }
4544 const unsigned int splitDim = ComputeWrappedIndex(axis, inputTensorInfo.GetNumDimensions());
Derek Lambertif0176992020-04-28 13:37:49 +01004545
Derek Lambertif0176992020-04-28 13:37:49 +01004546 // Set split sizes
Derek Lambertif0176992020-04-28 13:37:49 +01004547 CHECK_VALID_SIZE(splitsInfo.GetNumDimensions(), 1);
Ryan OShea86704732020-05-26 11:41:04 +01004548 unsigned int numSplits{0};
4549
4550 if(options)
Derek Lambertif0176992020-04-28 13:37:49 +01004551 {
4552 numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
Derek Lambertif0176992020-04-28 13:37:49 +01004553 }
4554 else
4555 {
Ryan OShea86704732020-05-26 11:41:04 +01004556 numSplits = splitsInfo.GetNumElements();
Derek Lambertif0176992020-04-28 13:37:49 +01004557 }
4558
4559 if (numSplits <=0)
4560 {
4561 throw ParseException("SplitV has invalid number of splits");
4562 }
4563
Jan Eilersc0761e92020-06-29 16:48:44 +01004564 std::vector<int> splitsData(numSplits);
Ryan OShea86704732020-05-26 11:41:04 +01004565 BufferRawPtr splitsBufferPtr = GetBuffer(m_Model, splitsTensor->buffer);
Jan Eilersc0761e92020-06-29 16:48:44 +01004566 ::memcpy(splitsData.data(), splitsBufferPtr->data.data(), splitsInfo.GetNumBytes());
Ryan OShea86704732020-05-26 11:41:04 +01004567
Jan Eilersc0761e92020-06-29 16:48:44 +01004568 unsigned int idx = 0;
Ryan OShea86704732020-05-26 11:41:04 +01004569 int numInferred{0};
4570 unsigned int inferIdx{0};
4571 int splitSum{0};
4572 for (auto split : splitsData)
4573 {
4574 if (split < 0)
4575 {
4576 numInferred++;
4577 inferIdx = idx;
4578 }
4579 else
4580 {
4581 splitSum += split;
4582 }
4583 idx++;
4584 }
4585 // Check for inferred Axis
4586 if (numInferred == 0)
4587 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01004588 if (splitSum != armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]))
Ryan OShea86704732020-05-26 11:41:04 +01004589 {
4590 throw ParseException("SplitV split_sizes does not sum to the dimension of value along split_dim.");
4591 }
4592 }
4593 else if (numInferred == 1)
4594 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01004595 splitsData[inferIdx] = armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]) - splitSum;
Ryan OShea86704732020-05-26 11:41:04 +01004596 }
4597 else
4598 {
4599 throw ParseException("Cannot infer split size for more than one split");
4600 }
4601
Derek Lambertif0176992020-04-28 13:37:49 +01004602 //Ouput size validation
4603 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4604 CHECK_VALID_SIZE(outputs.size(), numSplits);
4605
4606 // Setup Armnn descriptor
4607 SplitterDescriptor splitDesc(numSplits, inputDimSize);
4608 unsigned int accumSplit = 0;
4609 for (unsigned int j = 0; j < numSplits; ++j)
4610 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01004611 unsigned int splitSize = armnn::numeric_cast<unsigned int>(splitsData[j]);
Derek Lambertif0176992020-04-28 13:37:49 +01004612
4613 // Set the size of the views.
4614 for (unsigned int dimIdx = 0; dimIdx < inputTensorInfo.GetNumDimensions(); ++dimIdx)
4615 {
4616 unsigned int dimSize = inputTensorInfo.GetShape()[dimIdx];
4617 if (dimIdx == splitDim)
4618 {
4619 dimSize = splitSize;
4620 }
4621 splitDesc.SetViewSize(j, dimIdx, dimSize);
4622 }
4623
4624 splitDesc.SetViewOriginCoord(j, splitDim, accumSplit);
4625 accumSplit += splitSize;
4626 }
Mike Kelly363b5722023-10-11 14:25:50 +01004627 splitDesc.SetAxis(axis);
Derek Lambertif0176992020-04-28 13:37:49 +01004628
James Ward58dec6b2020-09-11 17:32:44 +01004629 auto layerName = fmt::format("SplitV:{}:{}", subgraphIndex, operatorIndex);
Derek Lambertif0176992020-04-28 13:37:49 +01004630 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01004631
4632 if (!layer)
4633 {
4634 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
4635 operatorIndex, CHECK_LOCATION().AsString()));
4636 }
Derek Lambertif0176992020-04-28 13:37:49 +01004637
4638 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4639 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4640
4641 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
4642 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01004643 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Derek Lambertif0176992020-04-28 13:37:49 +01004644 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
4645 }
4646
4647 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4648 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
4649}
4650
Matthew Sloyan28f177c2021-04-09 14:38:52 +01004651void TfLiteParserImpl::ParseArgMin(size_t subgraphIndex, size_t operatorIndex)
4652{
4653 ParseArgMinMax(subgraphIndex, operatorIndex, armnn::ArgMinMaxFunction::Min);
4654}
4655
Kevin May7d96b162021-02-03 17:38:41 +00004656void TfLiteParserImpl::ParseArgMax(size_t subgraphIndex, size_t operatorIndex)
Inki Daed4619e22020-09-10 15:33:54 +09004657{
Matthew Sloyan28f177c2021-04-09 14:38:52 +01004658 ParseArgMinMax(subgraphIndex, operatorIndex, armnn::ArgMinMaxFunction::Max);
4659}
4660
4661void TfLiteParserImpl::ParseArgMinMax(size_t subgraphIndex, size_t operatorIndex, ArgMinMaxFunction argMinMaxFunction)
4662{
Inki Daed4619e22020-09-10 15:33:54 +09004663 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4664 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4665 CHECK_VALID_SIZE(inputs.size(), 2);
4666
4667 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4668 CHECK_VALID_SIZE(outputs.size(), 1);
4669
Mike Kelly377fb212023-01-10 15:55:28 +00004670 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
4671 armnn::TensorInfo axisTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Inki Daed4619e22020-09-10 15:33:54 +09004672 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
Ryan OSheac229b3f2023-06-27 22:34:54 +01004673
4674 if (axisTensorInfo.GetNumElements() != 1)
4675 {
4676 throw ParseException(fmt::format("Axis tensor can only have 1 element {}",
4677 CHECK_LOCATION().AsString()));
4678 }
Matthew Sloyan28f177c2021-04-09 14:38:52 +01004679
4680 // Check if output tensor type is Signed32 or Signed64
Mike Kelly1f140f72021-04-06 12:25:55 +01004681 if (outputTensorInfo.GetDataType() != armnn::DataType::Signed32 &&
4682 outputTensorInfo.GetDataType() != armnn::DataType::Signed64)
4683 {
4684 throw ParseException(
4685 fmt::format(
4686 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
4687 CHECK_LOCATION().AsString()));
4688 }
Matthew Sloyan28f177c2021-04-09 14:38:52 +01004689
4690 // Get const axis value from model and set it to descriptor.
4691 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
4692 if (axisBufferPtr == nullptr)
4693 {
4694 throw ParseException(
4695 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
4696 CHECK_LOCATION().AsString()));
4697 }
4698
4699 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
4700 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
4701 int32_t axis = axisData.front();
4702
4703 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
4704 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
4705 {
4706 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
4707 // E.g. Rank 4 tensor can have axis in range [-4, 3)
4708 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
4709 throw ParseException(
4710 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
4711 axis,
4712 CHECK_LOCATION().AsString()));
4713 }
4714
4715 ArgMinMaxDescriptor desc;
4716 desc.m_Axis = axis;
4717 desc.m_Function = argMinMaxFunction;
4718
4719 // Register a ArgMin/ArgMax layer.
4720 auto layerName = argMinMaxFunction == ArgMinMaxFunction::Max ? "ArgMax:{}:{}" : "ArgMin:{}:{}";
4721 auto layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
4722 IConnectableLayer *layer = m_Network->AddArgMinMaxLayer(desc, layerNameFormatted.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01004723
4724 if (!layer)
4725 {
4726 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
4727 operatorIndex, CHECK_LOCATION().AsString()));
4728 }
4729
Mike Kelly377fb212023-01-10 15:55:28 +00004730 outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Inki Daed4619e22020-09-10 15:33:54 +09004731 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4732
4733 // Register input tensor to the layer.
4734 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4735 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4736
4737 // Register output tensor to the layer.
4738 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4739 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
4740}
4741
Kevin May7d96b162021-02-03 17:38:41 +00004742void TfLiteParserImpl::ParseGather(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00004743{
4744 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4745
Kevin May7d96b162021-02-03 17:38:41 +00004746 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004747 CHECK_VALID_SIZE(inputs.size(), 2);
Kevin May7d96b162021-02-03 17:38:41 +00004748 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004749 CHECK_VALID_SIZE(outputs.size(), 1);
4750
Mike Kelly377fb212023-01-10 15:55:28 +00004751 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
4752 armnn::TensorInfo indicesTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
4753 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
Sadik Armagan26868492021-01-22 14:25:31 +00004754
4755 armnn::GatherDescriptor gatherDescriptor;
4756
Mike Kelly0d77ae12022-01-07 17:42:27 +00004757 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4758 const auto* options = operatorPtr->builtin_options.AsGatherOptions();
Sadik Armagan26868492021-01-22 14:25:31 +00004759 auto axis = options->axis;
4760
Mike Kelly377fb212023-01-10 15:55:28 +00004761 auto layerName = fmt::format("Gather:{}:{}", subgraphIndex, operatorIndex);
4762
Sadik Armagan26868492021-01-22 14:25:31 +00004763 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
4764 auto indicesDimensions = indicesTensorInfo.GetNumDimensions();
4765 auto outputDimensions = outputTensorInfo.GetNumDimensions();
4766 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
4767 {
4768 throw ParseException(
4769 fmt::format("Operation has invalid axis: {} It is out of bounds [ -{}, {} ) {}",
4770 axis,
4771 inputDimensions, inputDimensions,
4772 CHECK_LOCATION().AsString()));
4773 }
4774 if (outputDimensions != static_cast<unsigned int>(inputDimensions) + indicesDimensions - 1)
4775 {
4776 throw ParseException(
4777 fmt::format("Operation has invalid output dimensions: {} Output must be an ({} + {} - 1) -D tensor {}",
4778 outputDimensions,
4779 inputDimensions, indicesDimensions,
4780 CHECK_LOCATION().AsString()));
4781 }
4782
4783 gatherDescriptor.m_Axis = axis;
4784
Sadik Armagan26868492021-01-22 14:25:31 +00004785 IConnectableLayer* layer = m_Network->AddGatherLayer(gatherDescriptor, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01004786
4787 if (!layer)
4788 {
4789 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
4790 operatorIndex, CHECK_LOCATION().AsString()));
4791 }
4792
Mike Kelly377fb212023-01-10 15:55:28 +00004793 outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Sadik Armagan26868492021-01-22 14:25:31 +00004794 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4795
4796 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4797 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
4798
4799 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4800 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4801}
4802
Teresa Charlin91a53ea2022-04-25 15:47:29 +01004803void TfLiteParserImpl::ParseGatherNd(size_t subgraphIndex, size_t operatorIndex)
4804{
4805 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4806
4807 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4808 CHECK_VALID_SIZE(inputs.size(), 2);
4809 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4810 CHECK_VALID_SIZE(outputs.size(), 1);
4811
Mike Kelly377fb212023-01-10 15:55:28 +00004812 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
4813 armnn::TensorInfo indicesTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Teresa Charlin91a53ea2022-04-25 15:47:29 +01004814
4815 auto layerName = fmt::format("GatherNd:{}:{}", subgraphIndex, operatorIndex);
4816 IConnectableLayer* layer = m_Network->AddGatherNdLayer(layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01004817
4818 if (!layer)
4819 {
4820 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
4821 operatorIndex, CHECK_LOCATION().AsString()));
4822 }
4823
Mike Kelly377fb212023-01-10 15:55:28 +00004824 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Teresa Charlin91a53ea2022-04-25 15:47:29 +01004825 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4826
4827 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4828 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
4829
4830 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4831 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4832}
4833
Kevin May7d96b162021-02-03 17:38:41 +00004834void TfLiteParserImpl::ParseDepthToSpace(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00004835{
4836 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4837
Kevin May7d96b162021-02-03 17:38:41 +00004838 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004839 CHECK_VALID_SIZE(inputs.size(), 1);
Kevin May7d96b162021-02-03 17:38:41 +00004840 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004841 CHECK_VALID_SIZE(outputs.size(), 1);
4842
4843 armnn::DepthToSpaceDescriptor descriptor;
4844
Mike Kelly0d77ae12022-01-07 17:42:27 +00004845 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4846 const auto* options = operatorPtr->builtin_options.AsDepthToSpaceOptions();
Sadik Armagan26868492021-01-22 14:25:31 +00004847 auto blockSize = options->block_size;
4848 if (blockSize < 2)
4849 {
4850 throw ParseException(
4851 fmt::format("Operation has invalid block size: {} Block size should be >= 2 {}",
4852 blockSize,
4853 CHECK_LOCATION().AsString()));
4854 }
4855 descriptor.m_BlockSize = armnn::numeric_cast<uint32_t>(blockSize);
4856
4857 auto layerName = fmt::format("DepthToSpace:{}:{}", subgraphIndex, operatorIndex);
4858 IConnectableLayer* layer = m_Network->AddDepthToSpaceLayer(descriptor, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01004859
4860 if (!layer)
4861 {
4862 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
4863 operatorIndex, CHECK_LOCATION().AsString()));
4864 }
4865
Mike Kelly377fb212023-01-10 15:55:28 +00004866 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Sadik Armagan26868492021-01-22 14:25:31 +00004867 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4868
4869 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4870 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4871
4872 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4873 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4874}
4875
Kevin May7d96b162021-02-03 17:38:41 +00004876void TfLiteParserImpl::ParseSum(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004877{
Sadik Armagana2747482021-02-09 10:28:54 +00004878 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Sum);
4879}
4880
Teresa Charlin4e3e8312021-08-05 12:34:37 +01004881void TfLiteParserImpl::ParseReduceProd(size_t subgraphIndex, size_t operatorIndex)
4882{
4883 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Prod);
4884}
4885
Sadik Armagana2747482021-02-09 10:28:54 +00004886void TfLiteParserImpl::ParseReduceMax(size_t subgraphIndex, size_t operatorIndex)
4887{
4888 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Max);
4889}
4890
4891void TfLiteParserImpl::ParseReduceMin(size_t subgraphIndex, size_t operatorIndex)
4892{
4893 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Min);
4894}
4895
4896void TfLiteParserImpl::ParseReduce(size_t subgraphIndex, size_t operatorIndex, ReduceOperation reduceOperation)
4897{
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004898 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4899
Mike Kelly0d77ae12022-01-07 17:42:27 +00004900 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4901 const auto* options = operatorPtr->builtin_options.AsReducerOptions();
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004902
4903 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4904 CHECK_VALID_SIZE(inputs.size(), 2);
4905
4906 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4907 CHECK_VALID_SIZE(outputs.size(), 1);
4908
Sadik Armagana2747482021-02-09 10:28:54 +00004909 auto layerName = fmt::format("Reduce:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004910
Mike Kelly377fb212023-01-10 15:55:28 +00004911 armnn::TensorInfo inputTensorInfo0 = InputTensorInfo(subgraphIndex, operatorIndex, 0);
4912 armnn::TensorInfo inputTensorInfo1 = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004913
4914 ReduceDescriptor desc;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004915 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
4916 // Get const axis value from model and set it to descriptor.
4917 if (axisBufferPtr != nullptr)
4918 {
Sadik Armagan49bdb792021-02-11 13:57:07 +00004919 std::vector<int32_t> axisData(inputTensorInfo1.GetNumElements());
4920 ::memcpy(axisData.data(), axisBufferPtr->data.data(), inputTensorInfo1.GetNumBytes());
4921
4922 // Convert the axis to unsigned int and remove duplicates.
4923 auto rank = static_cast<int32_t>(inputTensorInfo0.GetNumDimensions());
4924 std::set<unsigned int> uniqueAxis;
4925 std::transform(axisData.begin(),
4926 axisData.end(),
4927 std::inserter(uniqueAxis, uniqueAxis.begin()),
4928 [rank](int i)->unsigned int{
4929 return static_cast<uint32_t>(((i + rank) % rank)); });
4930 desc.m_vAxis.assign(uniqueAxis.begin(), uniqueAxis.end());
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004931 }
Sadik Armagana2747482021-02-09 10:28:54 +00004932 else
4933 {
4934 for (uint32_t i = 0; i < inputTensorInfo0.GetNumDimensions(); ++i)
4935 {
4936 desc.m_vAxis.push_back(i);
4937 }
4938 }
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004939
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004940 desc.m_KeepDims = options->keep_dims;
Sadik Armagana2747482021-02-09 10:28:54 +00004941 desc.m_ReduceOperation = reduceOperation;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004942
4943 // Register a new layer object, Sum.
Mike Kelly0d77ae12022-01-07 17:42:27 +00004944 IConnectableLayer* layer = m_Network->AddReduceLayer(desc, layerName.c_str());
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004945
Mike Kelly377fb212023-01-10 15:55:28 +00004946 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004947 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4948
4949 // Register input tensor to the layer.
4950 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4951 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4952
4953 // Register output tensor to the layer.
4954 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4955 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
4956}
4957
Mike Kelly31dce2b2021-09-01 21:22:37 +01004958void TfLiteParserImpl::ParseLocalResponseNormalization(size_t subgraphIndex, size_t operatorIndex)
4959{
4960 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4961
4962 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4963 CHECK_VALID_SIZE(inputs.size(), 1);
4964
4965 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4966 CHECK_VALID_SIZE(outputs.size(), 1);
4967
4968 auto layerName = fmt::format("LRN:{}:{}", subgraphIndex, operatorIndex);
4969 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
4970
Mike Kelly377fb212023-01-10 15:55:28 +00004971 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Mike Kelly31dce2b2021-09-01 21:22:37 +01004972
4973 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4974 const auto* options = operatorPtr->builtin_options.AsLocalResponseNormalizationOptions();
4975
4976 armnn::NormalizationDescriptor descriptor;
4977 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
4978 descriptor.m_NormChannelType = armnn::NormalizationAlgorithmChannel::Across;
4979 descriptor.m_NormMethodType = armnn::NormalizationAlgorithmMethod::LocalBrightness;
4980 descriptor.m_NormSize = static_cast<uint32_t>(options->radius);
4981 descriptor.m_K = options->bias;
4982 descriptor.m_Alpha = options->alpha;
4983 descriptor.m_Beta = options->beta;
4984
4985 // ArmNN expects normSize to be the full size of the normalization
4986 // window rather than the radius as in TfLite.
4987 descriptor.m_NormSize = 1 + (2 * descriptor.m_NormSize);
4988
4989 IConnectableLayer* layer = m_Network->AddNormalizationLayer(descriptor, layerNameFormatted.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01004990
4991 if (!layer)
4992 {
4993 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
4994 operatorIndex, CHECK_LOCATION().AsString()));
4995 }
Mike Kelly31dce2b2021-09-01 21:22:37 +01004996
Mike Kelly377fb212023-01-10 15:55:28 +00004997 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Mike Kelly31dce2b2021-09-01 21:22:37 +01004998 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4999
5000 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
5001 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
5002
5003 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
5004 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
5005}
5006
Teresa Charlin28aa6692022-07-12 11:18:44 +01005007void TfLiteParserImpl::ParseAbs(size_t subgraphIndex, size_t operatorIndex)
5008{
5009 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Abs);
5010}
5011
Teresa Charlin93f0ad02023-03-23 15:28:02 +00005012void TfLiteParserImpl::ParseCeil(size_t subgraphIndex, size_t operatorIndex)
5013{
5014 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Ceil);
5015}
5016
Teresa Charlin28aa6692022-07-12 11:18:44 +01005017void TfLiteParserImpl::ParseExp(size_t subgraphIndex, size_t operatorIndex)
5018{
5019 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Exp);
5020}
5021
5022void TfLiteParserImpl::ParseLog(size_t subgraphIndex, size_t operatorIndex)
5023{
5024 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Log);
5025}
5026
Matthew Sloyaned7fce42021-04-15 20:46:24 +01005027void TfLiteParserImpl::ParseLogicalNot(size_t subgraphIndex, size_t operatorIndex)
5028{
5029 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::LogicalNot);
5030}
5031
5032void TfLiteParserImpl::ParseNeg(size_t subgraphIndex, size_t operatorIndex)
5033{
5034 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Neg);
5035}
5036
John Mcloughlin0ec00872023-05-15 17:03:49 +01005037void TfLiteParserImpl::ParsePower(size_t subgraphIndex, size_t operatorIndex)
5038{
5039 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
5040
5041 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
5042 CHECK_VALID_SIZE(inputs.size(), 2);
5043
5044 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
5045 CHECK_VALID_SIZE(outputs.size(), 1);
5046
5047 auto layerName = fmt::format("Power:{}:{}", subgraphIndex, operatorIndex);
5048
5049 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
5050 TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
5051 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
5052
5053 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::Power, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01005054
5055 if (!layer)
5056 {
5057 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
5058 operatorIndex, CHECK_LOCATION().AsString()));
5059 }
John Mcloughlin0ec00872023-05-15 17:03:49 +01005060
5061 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
5062 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
5063 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
5064
5065 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
5066 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
5067
5068 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
5069 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
5070}
5071
Matthew Sloyaned7fce42021-04-15 20:46:24 +01005072void TfLiteParserImpl::ParseRsqrt(size_t subgraphIndex, size_t operatorIndex)
5073{
5074 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Rsqrt);
5075}
5076
Teresa Charlin28aa6692022-07-12 11:18:44 +01005077void TfLiteParserImpl::ParseSin(size_t subgraphIndex, size_t operatorIndex)
5078{
5079 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Sin);
5080}
5081
Teresa Charlinf0fce5b2022-05-04 17:24:43 +01005082void TfLiteParserImpl::ParseSqrt(size_t subgraphIndex, size_t operatorIndex)
5083{
5084 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Sqrt);
5085}
5086
Teresa Charlin6963b332023-07-11 11:35:41 +01005087void TfLiteParserImpl::ParseSquare(size_t subgraphIndex, size_t operatorIndex)
5088{
5089 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
5090
5091 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
5092 CHECK_VALID_SIZE(inputs.size(), 1);
5093
5094 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
5095 CHECK_VALID_SIZE(outputs.size(), 1);
5096
5097 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
5098
5099 auto layerName = fmt::format("Square:{}:{}", subgraphIndex, operatorIndex);
5100 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::Mul, layerName.c_str());
5101 ARMNN_ASSERT(layer != nullptr);
5102
5103 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 0});
5104 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
5105 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
5106
5107 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
5108 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[0]});
5109
5110 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
5111 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
5112}
5113
John Mcloughlin0ec00872023-05-15 17:03:49 +01005114void TfLiteParserImpl::ParseSquaredDifference(size_t subgraphIndex, size_t operatorIndex)
5115{
5116 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
5117
5118 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
5119 CHECK_VALID_SIZE(inputs.size(), 2);
5120
5121 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
5122 CHECK_VALID_SIZE(outputs.size(), 1);
5123
5124 auto layerName = fmt::format("SquaredDifference:{}:{}", subgraphIndex, operatorIndex);
5125
5126 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
5127 TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
John Mcloughlin0ec00872023-05-15 17:03:49 +01005128
5129 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::SqDiff, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01005130
5131 if (!layer)
5132 {
5133 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
5134 operatorIndex, CHECK_LOCATION().AsString()));
5135 }
John Mcloughlin0ec00872023-05-15 17:03:49 +01005136
5137 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
John Mcloughlin0ec00872023-05-15 17:03:49 +01005138 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
5139
5140 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
5141 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
5142
5143 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
5144 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
5145}
5146
Matthew Sloyaned7fce42021-04-15 20:46:24 +01005147void TfLiteParserImpl::ParseElementwiseUnary(size_t subgraphIndex, size_t operatorIndex, UnaryOperation unaryOperation)
5148{
5149 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
5150
5151 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
5152 CHECK_VALID_SIZE(inputs.size(), 1);
5153
5154 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
5155 CHECK_VALID_SIZE(outputs.size(), 1);
5156
5157 std::string layerName = std::string(GetUnaryOperationAsCString(unaryOperation)) + ":{}:{}";
5158 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
5159
5160 ElementwiseUnaryDescriptor desc;
5161 desc.m_Operation = unaryOperation;
5162 IConnectableLayer* layer = m_Network->AddElementwiseUnaryLayer(desc, layerNameFormatted.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01005163
5164 if (!layer)
5165 {
5166 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
5167 operatorIndex, CHECK_LOCATION().AsString()));
5168 }
Matthew Sloyaned7fce42021-04-15 20:46:24 +01005169
Mike Kelly377fb212023-01-10 15:55:28 +00005170 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Matthew Sloyaned7fce42021-04-15 20:46:24 +01005171 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
5172
5173 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
5174 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
5175
5176 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
5177 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
5178}
5179
Bruno Goncalves2d0eb862021-07-11 14:10:15 -03005180void TfLiteParserImpl::ParseEqual(size_t subgraphIndex, size_t operatorIndex)
5181{
5182 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::Equal);
5183}
5184
5185void TfLiteParserImpl::ParseNotEqual(size_t subgraphIndex, size_t operatorIndex)
5186{
5187 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::NotEqual);
5188}
5189
5190void TfLiteParserImpl::ParseGreater(size_t subgraphIndex, size_t operatorIndex)
5191{
5192 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::Greater);
5193}
5194
5195void TfLiteParserImpl::ParseGreaterOrEqual(size_t subgraphIndex, size_t operatorIndex)
5196{
5197 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::GreaterOrEqual);
5198}
5199
5200void TfLiteParserImpl::ParseLess(size_t subgraphIndex, size_t operatorIndex)
5201{
5202 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::Less);
5203}
5204
5205void TfLiteParserImpl::ParseLessOrEqual(size_t subgraphIndex, size_t operatorIndex)
5206{
5207 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::LessOrEqual);
5208}
5209
5210void TfLiteParserImpl::ParseComparison(size_t subgraphIndex, size_t operatorIndex,
5211 ComparisonOperation comparisonOperation)
5212{
5213 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
5214
5215 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
5216 CHECK_VALID_SIZE(inputs.size(), 2);
5217
5218 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
5219 CHECK_VALID_SIZE(outputs.size(), 1);
5220
5221 auto layerName = std::string(GetComparisonOperationAsCString(comparisonOperation)) + ":{}:{}";
5222 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
5223
Mike Kelly377fb212023-01-10 15:55:28 +00005224 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
5225 armnn::TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalves2d0eb862021-07-11 14:10:15 -03005226 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerNameFormatted, "Input 0", "Input 1");
5227
5228 ComparisonDescriptor desc;
5229 desc.m_Operation = comparisonOperation;
5230 IConnectableLayer* layer = m_Network->AddComparisonLayer(desc, layerNameFormatted.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01005231
5232 if (!layer)
5233 {
5234 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
5235 operatorIndex, CHECK_LOCATION().AsString()));
5236 }
Bruno Goncalves2d0eb862021-07-11 14:10:15 -03005237
Mike Kelly377fb212023-01-10 15:55:28 +00005238 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Bruno Goncalves2d0eb862021-07-11 14:10:15 -03005239 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
5240
5241 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
5242 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
5243
5244 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
5245 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
5246}
5247
Mike Kelly04d82292023-01-19 18:29:40 +00005248armnn::IConnectableLayer* TfLiteParserImpl::AddReshapeLayer(armnn::IConnectableLayer* layer,
5249 unsigned int outputSlot,
5250 std::string reshapeLayerName,
5251 armnn::TensorInfo outputShape)
5252{
5253 ReshapeDescriptor desc;
5254 desc.m_TargetShape = outputShape.GetShape();
5255
5256 IConnectableLayer* reshapeLayer =
5257 m_Network->AddReshapeLayer(desc, reshapeLayerName.c_str());
5258
5259 auto & prevOutputSlot = layer->GetOutputSlot(outputSlot);
5260 prevOutputSlot.Connect(reshapeLayer->GetInputSlot(0));
5261 reshapeLayer->GetOutputSlot(0).SetTensorInfo(outputShape);
5262 return reshapeLayer;
5263}
5264
Kevin May7d96b162021-02-03 17:38:41 +00005265armnn::IConnectableLayer* TfLiteParserImpl::AddFusedActivationLayer(armnn::IConnectableLayer* prevLayer,
5266 unsigned int outputSlot,
5267 tflite::ActivationFunctionType activationType)
telsoa01c577f2c2018-08-31 09:22:23 +01005268{
5269 ActivationDescriptor activationDesc;
5270 std::string layerName = prevLayer->GetName();
5271
5272 switch(activationType)
5273 {
5274 case tflite::ActivationFunctionType_NONE:
5275 {
5276 // this is a no-op: return previous layer
5277 return prevLayer;
5278 }
5279 case tflite::ActivationFunctionType_RELU:
5280 {
5281 activationDesc.m_Function = ActivationFunction::ReLu;
5282 layerName += ":RELU";
5283 break;
5284 }
5285 case tflite::ActivationFunctionType_RELU6:
5286 {
5287 activationDesc.m_Function = ActivationFunction::BoundedReLu;
5288 activationDesc.m_A = 6.0f;
5289 activationDesc.m_B = 0.0f;
5290 layerName += ":RELU6";
5291 break;
5292 }
5293 case tflite::ActivationFunctionType_TANH:
5294 {
5295 activationDesc.m_Function = ActivationFunction::TanH;
5296 activationDesc.m_A = 1.0f;
5297 activationDesc.m_B = 1.0f;
5298 layerName += ":TANH";
5299 break;
5300 }
5301
5302 // I only put these here as a reminder what others we could support
5303 case tflite::ActivationFunctionType_RELU_N1_TO_1:
5304 case tflite::ActivationFunctionType_SIGN_BIT:
5305 default:
5306 {
5307 throw ParseException(
Mike Kelly377fb212023-01-10 15:55:28 +00005308 fmt::format("TfLite parser doesn't support fused activation: "
James Ward58dec6b2020-09-11 17:32:44 +01005309 "{}/{} {} ",
5310 activationType,
5311 tflite::EnumNameActivationFunctionType(activationType),
5312 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01005313
5314 }
5315 }
5316
5317 IConnectableLayer* activationLayer =
5318 m_Network->AddActivationLayer(activationDesc, layerName.c_str());
5319
5320 auto & prevOutputSlot = prevLayer->GetOutputSlot(outputSlot);
5321 prevOutputSlot.Connect(activationLayer->GetInputSlot(0));
5322 activationLayer->GetOutputSlot(0).SetTensorInfo(prevOutputSlot.GetTensorInfo());
5323 return activationLayer;
5324}
5325
Teresa Charlincdbd40b2022-02-25 13:21:55 +00005326armnn::IConnectableLayer* TfLiteParserImpl::AddFusedFloorLayer(armnn::IConnectableLayer* prevLayer,
5327 unsigned int outputSlot)
5328{
Teresa Charlin725728e2022-05-05 13:33:33 +01005329
5330 auto& prevOutputSlot = prevLayer->GetOutputSlot(outputSlot);
5331 DataType dataType = prevOutputSlot.GetTensorInfo().GetDataType();
5332
5333 if (dataType == DataType::Signed32)
5334 {
5335 return prevLayer;
5336 }
5337
Teresa Charlincdbd40b2022-02-25 13:21:55 +00005338 std::string layerName = prevLayer->GetName();
5339 IConnectableLayer* floorLayer = m_Network->AddFloorLayer(layerName.c_str());
5340
Teresa Charlincdbd40b2022-02-25 13:21:55 +00005341 prevOutputSlot.Connect(floorLayer->GetInputSlot(0));
5342 floorLayer->GetOutputSlot(0).SetTensorInfo(prevOutputSlot.GetTensorInfo());
Teresa Charlin725728e2022-05-05 13:33:33 +01005343
Teresa Charlincdbd40b2022-02-25 13:21:55 +00005344 return floorLayer;
5345}
5346
Mike Kelly0d77ae12022-01-07 17:42:27 +00005347TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromFile(const char* fileName)
telsoa01c577f2c2018-08-31 09:22:23 +01005348{
5349 if (fileName == nullptr)
5350 {
James Ward58dec6b2020-09-11 17:32:44 +01005351 throw InvalidArgumentException(fmt::format("Invalid (null) file name {}",
telsoa01c577f2c2018-08-31 09:22:23 +01005352 CHECK_LOCATION().AsString()));
5353 }
Francis Murtagh532a29d2020-06-29 11:50:01 +01005354 std::error_code errorCode;
5355 fs::path pathToFile(fileName);
5356 if (!fs::exists(pathToFile, errorCode))
telsoa01c577f2c2018-08-31 09:22:23 +01005357 {
James Ward58dec6b2020-09-11 17:32:44 +01005358 //fmt::format() could not be used here (format error)
5359 std::stringstream msg;
5360 msg << "Cannot find the file (" << fileName << ") errorCode: " << errorCode
5361 << " " << CHECK_LOCATION().AsString();
James Ward58dec6b2020-09-11 17:32:44 +01005362 throw FileNotFoundException(msg.str());
telsoa01c577f2c2018-08-31 09:22:23 +01005363 }
Colm Donelan0dfb2652023-06-22 10:19:17 +01005364 if (!fs::is_regular_file(pathToFile))
5365 {
5366 // Exclude non regular files.
5367 throw InvalidArgumentException(fmt::format("File \"{}\" is not a regular file and cannot be loaded.",
5368 pathToFile.c_str()));
5369 }
5370
telsoa01c577f2c2018-08-31 09:22:23 +01005371 std::ifstream file(fileName, std::ios::binary);
5372 std::string fileContent((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
5373 return LoadModelFromBinary(reinterpret_cast<const uint8_t *>(fileContent.c_str()),
5374 fileContent.size());
5375}
5376
Mike Kelly0d77ae12022-01-07 17:42:27 +00005377TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromBinary(const uint8_t* binaryContent, size_t len)
telsoa01c577f2c2018-08-31 09:22:23 +01005378{
5379 if (binaryContent == nullptr)
5380 {
James Ward58dec6b2020-09-11 17:32:44 +01005381 throw InvalidArgumentException(fmt::format("Invalid (null) binary content {}",
telsoa01c577f2c2018-08-31 09:22:23 +01005382 CHECK_LOCATION().AsString()));
5383 }
5384 flatbuffers::Verifier verifier(binaryContent, len);
5385 if (verifier.VerifyBuffer<tflite::Model>() == false)
5386 {
5387 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01005388 fmt::format("Buffer doesn't conform to the expected Tensorflow Lite "
5389 "flatbuffers format. size:{} {}",
5390 len,
5391 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01005392 }
5393 return tflite::UnPackModel(binaryContent);
5394}
5395
Mike Kelly0d77ae12022-01-07 17:42:27 +00005396TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetInputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00005397 size_t subgraphIndex,
5398 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005399{
5400 CHECK_MODEL(model, subgraphIndex, operatorIndex);
5401
Mike Kelly0d77ae12022-01-07 17:42:27 +00005402 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
5403 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01005404
5405 size_t inputCount = operatorPtr->inputs.size();
mathad01c21025d2021-04-26 10:09:37 +01005406 TensorRawPtrVector result;
Mike Kelly0d77ae12022-01-07 17:42:27 +00005407 for (size_t i = 0; i < inputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01005408 {
mathad01c21025d2021-04-26 10:09:37 +01005409 // If the input location is -1 then assume input is turned off.
5410 if (operatorPtr->inputs[i] == -1)
5411 {
5412 continue;
5413 }
5414 else
5415 {
5416 uint32_t inputId = CHECKED_NON_NEGATIVE(operatorPtr->inputs[i]);
5417 result.push_back(subgraphPtr->tensors[inputId].get());
5418 }
telsoa01c577f2c2018-08-31 09:22:23 +01005419 }
5420 return result;
5421}
5422
Mike Kelly0d77ae12022-01-07 17:42:27 +00005423TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetOutputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00005424 size_t subgraphIndex,
5425 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005426{
5427 CHECK_MODEL(model, subgraphIndex, operatorIndex);
5428
Mike Kelly0d77ae12022-01-07 17:42:27 +00005429 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
5430 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01005431
5432 size_t outputCount = operatorPtr->outputs.size();
5433 TensorRawPtrVector result(outputCount);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005434 for (size_t i = 0; i < outputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01005435 {
5436 uint32_t outputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[i]);
5437 CHECK_TENSOR(model, subgraphIndex, outputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01005438 result[i] = subgraphPtr->tensors[outputId].get();
telsoa01c577f2c2018-08-31 09:22:23 +01005439 }
5440 return result;
5441}
5442
Mike Kelly0d77ae12022-01-07 17:42:27 +00005443TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphInputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00005444 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005445{
5446 CHECK_SUBGRAPH(model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005447 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01005448
Derek Lambertiff05cc52019-04-26 13:05:17 +01005449 size_t inputCount = subgraphPtr->inputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01005450 TensorIdRawPtrVector result(inputCount);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005451 for (size_t i = 0; i < inputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01005452 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01005453 uint32_t inputId = CHECKED_NON_NEGATIVE(subgraphPtr->inputs[i]);
telsoa01c577f2c2018-08-31 09:22:23 +01005454 CHECK_TENSOR(model, subgraphIndex, inputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01005455 result[i] = std::make_pair(inputId, subgraphPtr->tensors[inputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01005456 }
5457 return result;
5458}
5459
Mike Kelly0d77ae12022-01-07 17:42:27 +00005460TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphOutputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00005461 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005462{
5463 CHECK_SUBGRAPH(model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005464 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01005465
Derek Lambertiff05cc52019-04-26 13:05:17 +01005466 size_t outputCount = subgraphPtr->outputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01005467 TensorIdRawPtrVector result(outputCount);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005468 for (size_t i = 0; i < outputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01005469 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01005470 uint32_t outputId = CHECKED_NON_NEGATIVE(subgraphPtr->outputs[i]);
5471 result[i] = std::make_pair(outputId, subgraphPtr->tensors[outputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01005472 }
5473 return result;
5474}
5475
Kevin May7d96b162021-02-03 17:38:41 +00005476std::vector<int32_t>& TfLiteParserImpl::GetInputTensorIds(const ModelPtr& model,
5477 size_t subgraphIndex,
5478 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005479{
5480 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005481 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
5482 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01005483 return operatorPtr->inputs;
5484}
5485
Kevin May7d96b162021-02-03 17:38:41 +00005486std::vector<int32_t>& TfLiteParserImpl::GetOutputTensorIds(const ModelPtr& model,
5487 size_t subgraphIndex,
5488 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005489{
5490 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005491 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
5492 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01005493 return operatorPtr->outputs;
5494}
5495
Kevin May7d96b162021-02-03 17:38:41 +00005496void TfLiteParserImpl::RegisterInputSlots(size_t subgraphIndex,
5497 size_t operatorIndex,
5498 IConnectableLayer* layer,
Finn Williamsd4fa5452021-03-01 12:31:41 +00005499 const std::vector<unsigned int>& tensorIndexes,
5500 unsigned int startingSlotIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005501{
5502 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Ryan OSheac229b3f2023-06-27 22:34:54 +01005503
5504 if (!layer)
5505 {
5506 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
5507 operatorIndex, CHECK_LOCATION().AsString()));
5508 }
Matthew Sloyan81beae32021-07-13 19:46:11 +01005509
Finn Williamsd4fa5452021-03-01 12:31:41 +00005510 if (tensorIndexes.size() + startingSlotIndex != layer->GetNumInputSlots())
telsoa01c577f2c2018-08-31 09:22:23 +01005511 {
5512 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01005513 fmt::format("The number of tensor inputs ({}) does not match the number expected ({})"
5514 " for subgraph:{} operator index:{} {}",
5515 tensorIndexes.size(),
5516 layer->GetNumInputSlots(),
5517 subgraphIndex,
5518 operatorIndex,
5519 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01005520 }
5521
Finn Williamsd4fa5452021-03-01 12:31:41 +00005522 for (unsigned int index = 0; index < tensorIndexes.size() ; ++index)
telsoa01c577f2c2018-08-31 09:22:23 +01005523 {
Finn Williamsd4fa5452021-03-01 12:31:41 +00005524 unsigned int tensorIndex = tensorIndexes[index];
5525 armnn::IInputSlot* slot = &(layer->GetInputSlot(startingSlotIndex + index));
telsoa01c577f2c2018-08-31 09:22:23 +01005526 RegisterConsumerOfTensor(subgraphIndex, tensorIndex, slot);
5527 }
5528}
5529
Kevin May7d96b162021-02-03 17:38:41 +00005530void TfLiteParserImpl::RegisterOutputSlots(size_t subgraphIndex,
5531 size_t operatorIndex,
5532 IConnectableLayer* layer,
5533 const std::vector<unsigned int>& tensorIndexes)
telsoa01c577f2c2018-08-31 09:22:23 +01005534{
5535 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Ryan OSheac229b3f2023-06-27 22:34:54 +01005536
5537 if (!layer)
5538 {
5539 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
5540 operatorIndex, CHECK_LOCATION().AsString()));
5541 }
5542
telsoa01c577f2c2018-08-31 09:22:23 +01005543 if (tensorIndexes.size() != layer->GetNumOutputSlots())
5544 {
5545 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01005546 fmt::format("The number of tensor outputs ({}) does not match the number expected ({})"
5547 " for subgraph:{} operator index:{} {}",
5548 tensorIndexes.size(),
5549 layer->GetNumOutputSlots(),
5550 subgraphIndex,
5551 operatorIndex,
5552 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01005553 }
5554
5555 for (unsigned int slotIndex = 0; slotIndex < layer->GetNumOutputSlots(); ++slotIndex)
5556 {
5557 unsigned int tensorIndex = tensorIndexes[slotIndex];
5558 armnn::IOutputSlot* slot = &(layer->GetOutputSlot(slotIndex));
5559 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
5560 }
5561}
5562
Mike Kelly377fb212023-01-10 15:55:28 +00005563void TfLiteParserImpl::SetupInputLayerTensorInfos(size_t subgraphIndex)
5564{
5565 CHECK_SUBGRAPH(m_Model, subgraphIndex);
5566
5567 auto inputs = GetSubgraphInputs(m_Model, subgraphIndex);
5568 for (auto const& tensorIdAndPtr : inputs)
5569 {
5570 auto tensorInfo = ToTensorInfo(tensorIdAndPtr.second);
5571 m_TensorInfos.insert({tensorIdAndPtr.first, tensorInfo});
5572 }
5573}
5574
Kevin May7d96b162021-02-03 17:38:41 +00005575void TfLiteParserImpl::SetupInputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005576{
5577 CHECK_SUBGRAPH(m_Model, subgraphIndex);
5578
5579 auto inputs = GetSubgraphInputs(m_Model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005580 for (auto const& tensorIdAndPtr : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005581 {
5582 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
5583 IConnectableLayer* layer =
5584 m_Network->AddInputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
5585
5586 auto tensorInfo = ToTensorInfo(tensorIdAndPtr.second);
5587 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
5588
5589 RegisterOutputSlots(subgraphIndex,
5590 VIRTUAL_OPERATOR_ID,
5591 layer,
5592 { static_cast<uint32_t>(tensorIdAndPtr.first) });
5593 }
5594}
5595
Kevin May7d96b162021-02-03 17:38:41 +00005596void TfLiteParserImpl::SetupOutputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005597{
5598 CHECK_SUBGRAPH(m_Model, subgraphIndex);
5599
5600 auto outputs = GetSubgraphOutputs(m_Model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005601 for (auto const& tensorIdAndPtr : outputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005602 {
5603 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
5604 IConnectableLayer* layer =
5605 m_Network->AddOutputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
5606
5607 RegisterInputSlots(subgraphIndex,
5608 VIRTUAL_OPERATOR_ID,
5609 layer,
5610 { static_cast<uint32_t>(tensorIdAndPtr.first) });
5611 }
5612}
5613
Mike Kelly377fb212023-01-10 15:55:28 +00005614void TfLiteParserImpl::SetupConstantLayerTensorInfos(size_t subgraph)
5615{
5616 CHECK_SUBGRAPH(m_Model, subgraph);
5617
5618 const auto & subgraphPtr = m_Model->subgraphs[subgraph];
5619 for (unsigned int subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
5620 {
5621 for (unsigned int tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
5622 {
5623 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot == nullptr &&
5624 m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size() > 0)
5625 {
5626 TensorRawPtr tensorPtr = subgraphPtr->tensors[tensorIndex].get();
5627
5628 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
5629
5630 m_TensorInfos.insert({tensorIndex, tensorInfo});
5631 }
5632 }
5633 }
5634}
5635
Mike Kelly5880b912022-01-28 16:18:54 +00005636void TfLiteParserImpl::SetupConstantLayers(size_t subgraph)
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02005637{
Mike Kelly5880b912022-01-28 16:18:54 +00005638 CHECK_SUBGRAPH(m_Model, subgraph);
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02005639
Mike Kelly5880b912022-01-28 16:18:54 +00005640 const auto & subgraphPtr = m_Model->subgraphs[subgraph];
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02005641 for (unsigned int subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
5642 {
5643 for (unsigned int tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
5644 {
5645 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot == nullptr &&
5646 m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size() > 0)
5647 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01005648 TensorRawPtr tensorPtr = subgraphPtr->tensors[tensorIndex].get();
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02005649
Mike Kelly5880b912022-01-28 16:18:54 +00005650 if (IsConstTensor(tensorPtr))
Matthew Sloyan81beae32021-07-13 19:46:11 +01005651 {
5652 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
Mike Kelly5880b912022-01-28 16:18:54 +00005653 armnn::DataType dataType = tensorInfo.GetDataType();
5654
5655 if (std::find(m_ConstantsToDequantize.begin(), m_ConstantsToDequantize.end(), tensorPtr->buffer)
5656 != m_ConstantsToDequantize.end())
5657 {
5658 dataType = DataType::Float32;
5659 }
5660 auto tensorAndData = CreateConstTensorNonPermuted(tensorPtr, tensorInfo, dataType);
5661
5662 std::string layerName = fmt::format("Constant:{}", tensorPtr->name);
5663 IConnectableLayer *layer = m_Network->AddConstantLayer(tensorAndData.first, layerName.c_str());
5664
5665 layer->GetOutputSlot(0).SetTensorInfo(tensorAndData.first.GetInfo());
5666 RegisterOutputSlots(subgraphIndex,
5667 VIRTUAL_OPERATOR_ID,
5668 layer,
5669 { tensorIndex });
5670 }
5671 else if (ShouldConstantTensorBeCreated(tensorIndex))
5672 {
5673 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
5674 armnn::DataType dataType = tensorInfo.GetDataType();
5675
5676 if (std::find(m_ConstantsToDequantize.begin(), m_ConstantsToDequantize.end(), tensorPtr->buffer)
5677 != m_ConstantsToDequantize.end())
5678 {
5679 dataType = DataType::Float32;
5680 }
5681 // Make sure isConstant flag is set.
5682 tensorInfo.SetConstant();
5683 tensorInfo.SetDataType(dataType);
5684
5685 auto tensorAndData = ConstTensor(tensorInfo, std::vector<uint8_t>(tensorInfo.GetNumBytes()));
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02005686
Matthew Sloyan81beae32021-07-13 19:46:11 +01005687 std::string layerName = fmt::format("Constant:{}", tensorPtr->name);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005688 IConnectableLayer* layer = m_Network->AddConstantLayer(tensorAndData, layerName.c_str());
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02005689
Matthew Sloyan81beae32021-07-13 19:46:11 +01005690 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
5691 RegisterOutputSlots(subgraphIndex,
5692 VIRTUAL_OPERATOR_ID,
5693 layer,
Mike Kelly5880b912022-01-28 16:18:54 +00005694 {tensorIndex});
Matthew Sloyan81beae32021-07-13 19:46:11 +01005695 }
5696 else
5697 {
5698 throw ParseException(
5699 fmt::format("Invalid Tensor: Tensor should be constant. {}",
5700 CHECK_LOCATION().AsString()));
5701 }
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02005702 }
5703 }
5704 }
5705}
5706
telsoa01c577f2c2018-08-31 09:22:23 +01005707// example usage: BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Kevin May7d96b162021-02-03 17:38:41 +00005708TfLiteParserImpl::BufferRawPtr TfLiteParserImpl::GetBuffer(const ModelPtr& model, size_t bufferIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005709{
5710 CHECK_BUFFER(model, bufferIndex);
5711 return model->buffers[bufferIndex].get();
5712}
5713
Matteo Martincigh747ef822018-12-18 09:26:39 +00005714template<typename T>
Kevin May7d96b162021-02-03 17:38:41 +00005715std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
5716TfLiteParserImpl::CreateConstTensorAndStoreData(TfLiteParserImpl::BufferRawPtr bufferPtr,
5717 TfLiteParserImpl::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +00005718 armnn::TensorInfo& tensorInfo,
5719 armnn::Optional<armnn::PermutationVector&> permutationVector)
5720{
Matthew Sloyan81beae32021-07-13 19:46:11 +01005721 // Make sure isConstant flag is set.
5722 tensorInfo.SetConstant();
5723
Matteo Martincigh747ef822018-12-18 09:26:39 +00005724 auto constData = CreateConstTensorImpl<T>(bufferPtr,
5725 tensorPtr,
5726 tensorInfo,
5727 permutationVector);
Kevin May7d96b162021-02-03 17:38:41 +00005728 TfLiteParserImpl::SupportedDataStorage storage(std::move(constData.second));
Matteo Martincigh747ef822018-12-18 09:26:39 +00005729 return std::make_pair(constData.first, std::move(storage));
5730}
5731
Mike Kelly5880b912022-01-28 16:18:54 +00005732bool TfLiteParserImpl::ShouldConstantTensorBeCreated(unsigned int tensorIndex)
5733{
5734 // If the TensorIndex appears in the list of ConstantsToBeCreated then return true
5735 return (std::find(m_ConstantsToBeCreated.begin(), m_ConstantsToBeCreated.end(), tensorIndex)
5736 != m_ConstantsToBeCreated.end());
5737}
5738
Finn Williamsd4fa5452021-03-01 12:31:41 +00005739bool TfLiteParserImpl::IsConstTensor(TensorRawPtr tensorPtr)
5740{
5741 CHECK_TENSOR_PTR(tensorPtr);
mathad01bf7edb62021-04-20 16:12:45 +01005742 bool isConst = true;
5743
5744 auto buffer = GetBuffer(m_Model, tensorPtr->buffer);
5745 if (buffer->data.size() == 0)
5746 {
5747 isConst = false;
5748 }
5749
5750 return isConst;
Finn Williamsd4fa5452021-03-01 12:31:41 +00005751}
5752
Kevin May7d96b162021-02-03 17:38:41 +00005753std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
Finn Williamsd4fa5452021-03-01 12:31:41 +00005754TfLiteParserImpl::CreateConstTensorPermuted(TensorRawPtr tensorPtr,
5755 armnn::TensorInfo& tensorInfo,
5756 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +01005757{
5758 CHECK_TENSOR_PTR(tensorPtr);
5759 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
5760 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
5761
Matthew Sloyan81beae32021-07-13 19:46:11 +01005762 // Make sure isConstant flag is set.
5763 tensorInfo.SetConstant();
5764
telsoa01c577f2c2018-08-31 09:22:23 +01005765 switch (tensorInfo.GetDataType())
5766 {
5767 case armnn::DataType::Float32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00005768 return CreateConstTensorAndStoreData<float>(bufferPtr,
5769 tensorPtr,
5770 tensorInfo,
5771 permutationVector);
Derek Lambertif90c56d2020-01-10 17:14:08 +00005772 case armnn::DataType::QAsymmU8:
Matteo Martincigh747ef822018-12-18 09:26:39 +00005773 return CreateConstTensorAndStoreData<uint8_t>(bufferPtr,
5774 tensorPtr,
5775 tensorInfo,
5776 permutationVector);
Keith Davisd305e1a2020-01-22 11:57:54 +00005777 case armnn::DataType::QSymmS8:
5778 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
5779 tensorPtr,
5780 tensorInfo,
5781 permutationVector);
Keith Davis67e6c542020-02-19 10:08:33 +00005782 case armnn::DataType::QAsymmS8:
5783 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
5784 tensorPtr,
5785 tensorInfo,
5786 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01005787 case armnn::DataType::Signed32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00005788 return CreateConstTensorAndStoreData<int32_t>(bufferPtr,
5789 tensorPtr,
5790 tensorInfo,
5791 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01005792 default:
5793 {
5794 std::stringstream errString;
5795 errString << "Unexpected datatype when creating const tensor: "
5796 << armnn::GetDataTypeName(tensorInfo.GetDataType())
5797 << " shape:" << tensorInfo.GetShape()
5798 << CHECK_LOCATION().AsString();
5799 throw ParseException(errString.str());
5800 }
5801 }
5802}
5803
Finn Williamsd4fa5452021-03-01 12:31:41 +00005804armnn::ConstTensor TfLiteParserImpl::CreateConstTensorNonPermuted(TensorRawPtr tensorPtr,
5805 armnn::TensorInfo& tensorInfo)
5806{
5807 CHECK_TENSOR_PTR(tensorPtr);
5808 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
5809 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
5810
Matthew Sloyan81beae32021-07-13 19:46:11 +01005811 // Make sure isConstant flag is set.
5812 tensorInfo.SetConstant();
5813
Finn Williamsd4fa5452021-03-01 12:31:41 +00005814 return ConstTensor(tensorInfo, bufferPtr->data.data());
5815}
5816
Mike Kelly5880b912022-01-28 16:18:54 +00005817std::pair<armnn::ConstTensor, std::unique_ptr<float[]>>
5818TfLiteParserImpl::CreateConstTensorNonPermuted(TensorRawPtr tensorPtr,
5819 armnn::TensorInfo& tensorInfo,
5820 armnn::DataType inputDataType)
5821{
5822 CHECK_TENSOR_PTR(tensorPtr);
5823 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
5824 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
5825
5826 // Make sure isConstant flag is set.
5827 tensorInfo.SetConstant();
5828
Mike Kelly0506ef02023-01-03 16:29:44 +00005829 if (inputDataType == DataType::Float32 && tensorInfo.GetDataType() != DataType::Float32)
Mike Kelly5880b912022-01-28 16:18:54 +00005830 {
Mike Kelly0506ef02023-01-03 16:29:44 +00005831 try
5832 {
5833 TensorInfo constTensorInfo(tensorInfo.GetShape(), DataType::Float32, 0.0f, 0, true);
5834 std::unique_ptr<float[]> data = armnnUtils::ToFloatArray(bufferPtr->data, tensorInfo);
5835 return std::make_pair(ConstTensor(constTensorInfo, data.get()), std::move(data));
5836 }
Cathal Corbett9c843c32023-01-09 17:51:37 +00005837 catch (InvalidArgumentException&)
Mike Kelly0506ef02023-01-03 16:29:44 +00005838 {
5839 throw ParseException(
5840 fmt::format("Unsupported input/weights combination: Input {} not supported with Weights {}",
5841 GetDataTypeName(DataType::Float32),
5842 GetDataTypeName(tensorInfo.GetDataType()),
5843 CHECK_LOCATION().AsString()));
5844 }
Mike Kelly5880b912022-01-28 16:18:54 +00005845 }
5846 else
5847 {
5848 return std::make_pair(ConstTensor(tensorInfo, bufferPtr->data.data()), std::unique_ptr<float[]>());
5849 }
5850}
5851
5852std::pair<armnn::ConstTensor*, std::unique_ptr<float[]>>
5853TfLiteParserImpl::CreateConstTensorPtr(TensorRawPtr tensorPtr, armnn::TensorInfo& inputTensorInfo)
5854{
5855 CHECK_TENSOR_PTR(tensorPtr);
5856 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
5857 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
5858 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
5859
5860 // Make sure isConstant flag is set.
5861 tensorInfo.SetConstant();
5862
5863 if (inputTensorInfo.GetDataType() == DataType::Float32 && tensorInfo.GetDataType() != DataType::Float32)
5864 {
Mike Kelly0506ef02023-01-03 16:29:44 +00005865 try
5866 {
5867 TensorInfo constTensorInfo(tensorInfo.GetShape(), DataType::Float32, 0.0f, 0, true);
5868 std::unique_ptr<float[]> data = armnnUtils::ToFloatArray(bufferPtr->data, tensorInfo);
5869 return std::make_pair(new ConstTensor(constTensorInfo, data.get()), std::move(data));
5870 }
Cathal Corbett9c843c32023-01-09 17:51:37 +00005871 catch (InvalidArgumentException&)
Mike Kelly0506ef02023-01-03 16:29:44 +00005872 {
5873 throw ParseException(
5874 fmt::format("Unsupported input/weights combination: Input {} not supported with Weights {}",
5875 GetDataTypeName(DataType::Float32),
5876 GetDataTypeName(tensorInfo.GetDataType()),
5877 CHECK_LOCATION().AsString()));
5878 }
Mike Kelly5880b912022-01-28 16:18:54 +00005879 }
5880 else
5881 {
5882 return std::make_pair(new ConstTensor(tensorInfo, bufferPtr->data.data()), std::unique_ptr<float[]>());
5883 }
5884}
5885
Kevin May7d96b162021-02-03 17:38:41 +00005886BindingPointInfo TfLiteParserImpl::GetNetworkInputBindingInfo(size_t subgraphId,
5887 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01005888{
5889 CHECK_SUBGRAPH(m_Model, subgraphId);
5890 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005891 for (auto const& input : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005892 {
5893 if (input.second->name == name)
5894 {
5895 auto bindingId = GenerateLayerBindingId(subgraphId, input.first);
Colm Donelan4bc993b2021-11-09 20:39:10 +00005896 auto inputTensorInfo = ToTensorInfo(input.second);
5897 // Input tensors are always treated as constant tensors during network execution.
5898 inputTensorInfo.SetConstant(true);
5899 return std::make_pair(bindingId, inputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01005900 }
5901 }
5902
5903 std::stringstream bindings;
Mike Kelly0d77ae12022-01-07 17:42:27 +00005904 for (auto const& input : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005905 {
5906 bindings << "'" << input.second->name << "' ";
5907 }
5908
5909 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01005910 fmt::format("No input binding found for subgraph:{} and name:{}. "
5911 "Possible inputs are: [{}] {}",
5912 subgraphId,
5913 name,
5914 bindings.str(),
5915 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01005916}
5917
Kevin May7d96b162021-02-03 17:38:41 +00005918BindingPointInfo TfLiteParserImpl::GetNetworkOutputBindingInfo(size_t subgraphId,
5919 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01005920{
5921 CHECK_SUBGRAPH(m_Model, subgraphId);
5922 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00005923 for (unsigned int i = 0; i < outputs.size(); ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01005924 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00005925 auto const output = outputs[i];
telsoa01c577f2c2018-08-31 09:22:23 +01005926 if (output.second->name == name)
5927 {
5928 auto bindingId = GenerateLayerBindingId(subgraphId, output.first);
Mike Kelly377fb212023-01-10 15:55:28 +00005929 std::vector<unsigned int> shape = m_OverriddenOutputShapes.size() > 0 ?
5930 m_OverriddenOutputShapes[i] : AsUnsignedVector(output.second->shape);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00005931 return std::make_pair(bindingId, ToTensorInfo(output.second, shape));
telsoa01c577f2c2018-08-31 09:22:23 +01005932 }
5933 }
5934
5935 std::stringstream bindings;
Mike Kelly0d77ae12022-01-07 17:42:27 +00005936 for (auto const& output : outputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005937 {
5938 bindings << "'" << output.second->name << "' ";
5939 }
5940
5941 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01005942 fmt::format("No output binding found for subgraph:{} and name:{}. "
5943 "Possible outputs are: [{}] {}",
5944 subgraphId,
5945 name,
5946 bindings.str(),
5947 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01005948}
5949
Kevin May7d96b162021-02-03 17:38:41 +00005950size_t TfLiteParserImpl::GetSubgraphCount() const
telsoa01c577f2c2018-08-31 09:22:23 +01005951{
5952 return m_Model->subgraphs.size();
5953}
5954
Kevin May7d96b162021-02-03 17:38:41 +00005955std::vector<std::string> TfLiteParserImpl::GetSubgraphInputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01005956{
5957 CHECK_SUBGRAPH(m_Model, subgraphId);
5958 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
5959 std::vector<std::string> result;
5960 result.reserve(inputs.size());
Mike Kelly0d77ae12022-01-07 17:42:27 +00005961 for (auto const& input : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005962 {
5963 result.push_back(input.second->name);
5964 }
5965 return result;
5966}
5967
Kevin May7d96b162021-02-03 17:38:41 +00005968std::vector<std::string> TfLiteParserImpl::GetSubgraphOutputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01005969{
5970 CHECK_SUBGRAPH(m_Model, subgraphId);
5971 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
5972 std::vector<std::string> result;
5973 result.reserve(outputs.size());
Mike Kelly0d77ae12022-01-07 17:42:27 +00005974 for (auto const& output : outputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005975 {
5976 result.push_back(output.second->name);
5977 }
5978 return result;
5979}
5980
Matthew Sloyanac001ee2021-02-03 10:43:04 +00005981const std::string TfLiteParserImpl::GetVersion()
5982{
5983 return TFLITE_PARSER_VERSION;
5984}
5985
Mike Kelly0d77ae12022-01-07 17:42:27 +00005986TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<float[]>&& data)
telsoa01c577f2c2018-08-31 09:22:23 +01005987: m_FloatData(std::move(data))
5988, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00005989, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01005990, m_Int32Data(nullptr)
5991{
5992}
5993
Mike Kelly0d77ae12022-01-07 17:42:27 +00005994TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<uint8_t[]>&& data)
telsoa01c577f2c2018-08-31 09:22:23 +01005995: m_FloatData(nullptr)
5996, m_Uint8Data(std::move(data))
Keith Davisd305e1a2020-01-22 11:57:54 +00005997, m_Int8Data(nullptr)
5998, m_Int32Data(nullptr)
5999{
6000}
6001
Mike Kelly0d77ae12022-01-07 17:42:27 +00006002TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int8_t[]>&& data)
Keith Davisd305e1a2020-01-22 11:57:54 +00006003: m_FloatData(nullptr)
6004, m_Uint8Data(nullptr)
6005, m_Int8Data(std::move(data))
telsoa01c577f2c2018-08-31 09:22:23 +01006006, m_Int32Data(nullptr)
6007{
6008}
6009
Mike Kelly0d77ae12022-01-07 17:42:27 +00006010TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int32_t[]>&& data)
telsoa01c577f2c2018-08-31 09:22:23 +01006011: m_FloatData(nullptr)
6012, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00006013, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01006014, m_Int32Data(std::move(data))
6015{
6016}
6017
6018} // armnnTfLiteParser