blob: 3fd81ff973259acec12ff878ff72d4d8048d43d7 [file] [log] [blame]
telsoa01c577f2c2018-08-31 09:22:23 +01001//
Teresa Charlince7f51f2024-03-05 15:33:10 +00002// Copyright © 2017-2024 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 Charlince7f51f2024-03-05 15:33:10 +0000813 m_ParserFunctions[tflite::BuiltinOperator_SCATTER_ND] = &TfLiteParserImpl::ParseScatterNd;
Teresa Charlinf0fce5b2022-05-04 17:24:43 +0100814 m_ParserFunctions[tflite::BuiltinOperator_SQRT] = &TfLiteParserImpl::ParseSqrt;
Keith Davis0176fd82021-06-01 17:36:32 +0100815 m_ParserFunctions[tflite::BuiltinOperator_SHAPE] = &TfLiteParserImpl::ParseShape;
Teresa Charlin28aa6692022-07-12 11:18:44 +0100816 m_ParserFunctions[tflite::BuiltinOperator_SIN] = &TfLiteParserImpl::ParseSin;
Kevin May7d96b162021-02-03 17:38:41 +0000817 m_ParserFunctions[tflite::BuiltinOperator_SLICE] = &TfLiteParserImpl::ParseSlice;
818 m_ParserFunctions[tflite::BuiltinOperator_SOFTMAX] = &TfLiteParserImpl::ParseSoftmax;
819 m_ParserFunctions[tflite::BuiltinOperator_SPACE_TO_BATCH_ND] = &TfLiteParserImpl::ParseSpaceToBatchND;
Teresa Charlin2a764ad2023-02-24 18:17:31 +0000820 m_ParserFunctions[tflite::BuiltinOperator_SPACE_TO_DEPTH] = &TfLiteParserImpl::ParseSpaceToDepth;
Kevin May7d96b162021-02-03 17:38:41 +0000821 m_ParserFunctions[tflite::BuiltinOperator_SPLIT] = &TfLiteParserImpl::ParseSplit;
822 m_ParserFunctions[tflite::BuiltinOperator_SPLIT_V] = &TfLiteParserImpl::ParseSplitV;
823 m_ParserFunctions[tflite::BuiltinOperator_SQUEEZE] = &TfLiteParserImpl::ParseSqueeze;
Teresa Charlin6963b332023-07-11 11:35:41 +0100824 m_ParserFunctions[tflite::BuiltinOperator_SQUARE] = &TfLiteParserImpl::ParseSquare;
John Mcloughlin0ec00872023-05-15 17:03:49 +0100825 m_ParserFunctions[tflite::BuiltinOperator_SQUARED_DIFFERENCE] = &TfLiteParserImpl::ParseSquaredDifference;
Kevin May7d96b162021-02-03 17:38:41 +0000826 m_ParserFunctions[tflite::BuiltinOperator_STRIDED_SLICE] = &TfLiteParserImpl::ParseStridedSlice;
827 m_ParserFunctions[tflite::BuiltinOperator_SUB] = &TfLiteParserImpl::ParseSub;
828 m_ParserFunctions[tflite::BuiltinOperator_SUM] = &TfLiteParserImpl::ParseSum;
829 m_ParserFunctions[tflite::BuiltinOperator_TANH] = &TfLiteParserImpl::ParseTanH;
Teresa Charlin777008b2023-07-26 10:07:55 +0100830 m_ParserFunctions[tflite::BuiltinOperator_TILE] = &TfLiteParserImpl::ParseTile;
Kevin May7d96b162021-02-03 17:38:41 +0000831 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE] = &TfLiteParserImpl::ParseTranspose;
832 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE_CONV] = &TfLiteParserImpl::ParseTransposeConv;
Mike Kelly5880b912022-01-28 16:18:54 +0000833 m_ParserFunctions[tflite::BuiltinOperator_UNIDIRECTIONAL_SEQUENCE_LSTM]
834 = &TfLiteParserImpl::ParseUnidirectionalSequenceLSTM;
Kevin May7d96b162021-02-03 17:38:41 +0000835 m_ParserFunctions[tflite::BuiltinOperator_UNPACK] = &TfLiteParserImpl::ParseUnpack;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100836
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100837 // register supported custom operators
Kevin May7d96b162021-02-03 17:38:41 +0000838 m_CustomParserFunctions["TFLite_Detection_PostProcess"] = &TfLiteParserImpl::ParseDetectionPostProcess;
telsoa01c577f2c2018-08-31 09:22:23 +0100839}
840
Mike Kelly377fb212023-01-10 15:55:28 +0000841armnn::TensorInfo TfLiteParserImpl::InputTensorInfo(size_t subgraphIndex,
842 size_t operatorIndex,
843 int input)
844{
845 const auto& subgraphPtr = m_Model->subgraphs[subgraphIndex];
846 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
847
848 uint32_t inputId = CHECKED_NON_NEGATIVE(operatorPtr->inputs[input]);
849 auto search = armnnTfLiteParser::TfLiteParserImpl::m_TensorInfos.find(inputId);
850
851 if (search != m_TensorInfos.end())
852 {
853 return m_TensorInfos[inputId];
854 }
855 else
856 {
857 auto tensorInfo = ::armnnTfLiteParser::ToTensorInfo(subgraphPtr->tensors[inputId].get());
858 m_TensorInfos.insert({ inputId, tensorInfo });
859 return tensorInfo;
860 }
861}
862
863armnn::TensorInfo TfLiteParserImpl::OutputTensorInfoFromInputs(size_t subgraphIndex,
864 size_t operatorIndex,
865 armnn::IConnectableLayer* layer,
866 int output,
867 std::vector<int> inputs)
868{
869 const auto& subgraphPtr = m_Model->subgraphs[subgraphIndex];
870 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
871
872 uint32_t outputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[output]);
873
874 auto outputSearch = armnnTfLiteParser::TfLiteParserImpl::m_TensorInfos.find(outputId);
875
876 if (outputSearch != m_TensorInfos.end())
877 {
878 return m_TensorInfos[outputId];
879 }
880
881 const auto& outputTensorPtr = subgraphPtr->tensors[outputId].get();
882 TensorInfo tensor = ::armnnTfLiteParser::ToTensorInfo(outputTensorPtr, true);
883
884 if (IsDynamic(outputTensorPtr))
885 {
886 if (inputs.empty())
887 {
888 for (unsigned int i = 0; i < layer->GetNumInputSlots(); ++i)
889 {
890 inputs.emplace_back(i);
891 }
892 }
893 auto inputTensorIds = GetInputTensorIds(m_Model, subgraphIndex, operatorIndex);
894 std::vector<armnn::TensorShape> inputShapes;
895
896 for (unsigned int i = 0; i < inputs.size(); ++i)
897 {
898 uint32_t inputId = CHECKED_NON_NEGATIVE(operatorPtr->inputs[inputs[i]]);
899 auto search = armnnTfLiteParser::TfLiteParserImpl::m_TensorInfos.find(inputId);
900
901 if (search != m_TensorInfos.end())
902 {
903 auto &inputTensorInfo = m_TensorInfos[inputId];
904 inputShapes.push_back(inputTensorInfo.GetShape());
905 }
906 else
907 {
Mike Kelly377fb212023-01-10 15:55:28 +0000908 auto inputTensorInfo = ::armnnTfLiteParser::ToTensorInfo(subgraphPtr->tensors[inputId].get());
909 m_TensorInfos.insert({ inputId, inputTensorInfo});
910 inputShapes.push_back(inputTensorInfo.GetShape());
911 }
912 }
913 const auto outputShape = layer->InferOutputShapes(inputShapes)[output];
914 tensor.SetShape(outputShape);
915 }
916 m_TensorInfos.insert({ outputId, tensor});
917 return tensor;
918}
919
920armnn::TensorInfo TfLiteParserImpl::OutputTensorInfoFromShapes(size_t subgraphIndex,
921 size_t operatorIndex,
922 armnn::IConnectableLayer* layer,
923 int output,
924 std::vector<armnn::TensorShape> inputShapes)
925{
926 const auto& subgraphPtr = m_Model->subgraphs[subgraphIndex];
927 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
928
929 uint32_t outputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[output]);
930 const auto& outputTensorPtr = subgraphPtr->tensors[outputId].get();
931 TensorInfo tensor = ::armnnTfLiteParser::ToTensorInfo(outputTensorPtr, true);
932
933 if (IsDynamic(outputTensorPtr))
934 {
935 const auto outputShape = layer->InferOutputShapes(inputShapes)[output];
936 tensor.SetShape(outputShape);
937 }
938 m_TensorInfos.insert({ outputId, tensor});
939 return tensor;
940}
941
Kevin May7d96b162021-02-03 17:38:41 +0000942void TfLiteParserImpl::ResetParser()
telsoa01c577f2c2018-08-31 09:22:23 +0100943{
944 m_Network = armnn::INetworkPtr(nullptr, nullptr);
945 m_Model = nullptr;
946 m_SubgraphConnections.clear();
Mike Kelly377fb212023-01-10 15:55:28 +0000947 m_OverriddenOutputShapes.clear();
Mike Kelly5880b912022-01-28 16:18:54 +0000948 m_ConstantsToDequantize.clear();
949 m_ConstantsToBeCreated.clear();
Mike Kelly377fb212023-01-10 15:55:28 +0000950 m_TensorInfos.clear();
telsoa01c577f2c2018-08-31 09:22:23 +0100951}
952
Kevin May7d96b162021-02-03 17:38:41 +0000953INetworkPtr TfLiteParserImpl::CreateNetworkFromBinaryFile(const char* graphFile)
telsoa01c577f2c2018-08-31 09:22:23 +0100954{
955 ResetParser();
956 m_Model = LoadModelFromFile(graphFile);
957 return CreateNetworkFromModel();
958}
959
Mike Kelly0d77ae12022-01-07 17:42:27 +0000960INetworkPtr TfLiteParserImpl::CreateNetworkFromBinary(const std::vector<uint8_t>& binaryContent)
telsoa01c577f2c2018-08-31 09:22:23 +0100961{
962 ResetParser();
963 m_Model = LoadModelFromBinary(binaryContent.data(), binaryContent.size());
964 return CreateNetworkFromModel();
965}
966
Finn Williamsb49ed182021-06-29 15:50:08 +0100967
968armnn::INetworkPtr TfLiteParserImpl::LoadModel(std::unique_ptr<tflite::ModelT> model)
969{
970 ResetParser();
971 m_Model = std::move(model);
972
973 return CreateNetworkFromModel();
974}
975
Kevin May7d96b162021-02-03 17:38:41 +0000976INetworkPtr TfLiteParserImpl::CreateNetworkFromModel()
telsoa01c577f2c2018-08-31 09:22:23 +0100977{
Sadik Armagand109a4d2020-07-28 10:42:13 +0100978
979 using NetworkOptions = std::vector<BackendOptions>;
980 NetworkOptions networkOptions = {};
Mike Kelly80512b02022-05-16 23:10:42 +0100981 if (m_Options)
Sadik Armagand109a4d2020-07-28 10:42:13 +0100982 {
Mike Kelly80512b02022-05-16 23:10:42 +0100983 if (m_Options.value().m_InferAndValidate)
984 {
985 BackendOptions shapeInferenceMethodOption("ShapeInferenceMethod",
986 {
987 { "InferAndValidate", true }
988 });
Sadik Armagand109a4d2020-07-28 10:42:13 +0100989
Mike Kelly80512b02022-05-16 23:10:42 +0100990 networkOptions.push_back(shapeInferenceMethodOption);
991 }
992 if (m_Options.value().m_AllowExpandedDims)
993 {
994 BackendOptions shapeInferenceMethodOption("AllowExpandedDims",
995 {
996 { "AllowExpandedDims", true }
997 });
998
999 networkOptions.push_back(shapeInferenceMethodOption);
1000 }
Sadik Armagand109a4d2020-07-28 10:42:13 +01001001 }
Sadik Armagand109a4d2020-07-28 10:42:13 +01001002 m_Network = INetwork::Create(networkOptions);
Ryan OSheac229b3f2023-06-27 22:34:54 +01001003
1004 if (m_Model.get() == nullptr)
1005 {
1006 throw ParseException(fmt::format("Tflite Model pointer is null {}", CHECK_LOCATION().AsString()));
1007 }
telsoa01c577f2c2018-08-31 09:22:23 +01001008
Colm Donelan58125042023-11-08 21:11:05 +00001009 // Identify which subgraph we are going to parse. We only support one subgraph but there may be validation
1010 // subgraphs still stored in the model. We'll ignore these. In the tflite code base they are identified by
1011 // their name beginning with "VALIDATION:".
1012 size_t subgraphIndex = 0;
1013 uint8_t usableSubgraphs = 0;
1014 for (size_t i = 0; i < m_Model->subgraphs.size(); i++)
telsoa01c577f2c2018-08-31 09:22:23 +01001015 {
Colm Donelan58125042023-11-08 21:11:05 +00001016 if (m_Model->subgraphs[i]->name.rfind("VALIDATION:", 0) != 0)
1017 {
1018 usableSubgraphs++;
1019 subgraphIndex = i;
1020 }
telsoa01c577f2c2018-08-31 09:22:23 +01001021 }
1022
Colm Donelan58125042023-11-08 21:11:05 +00001023 if (usableSubgraphs > 1)
1024 {
1025 throw ParseException(
1026 fmt::format("Current TfLite parser only supports 1 non validation subgraph. This model has: {} {}",
1027 usableSubgraphs, CHECK_LOCATION().AsString()));
1028 }
1029
Colm Donelan6350d272020-06-09 16:56:25 +01001030 size_t operatorIndex = 0;
1031 try
telsoa01c577f2c2018-08-31 09:22:23 +01001032 {
Colm Donelan58125042023-11-08 21:11:05 +00001033 const SubgraphPtr& subgraph = m_Model->subgraphs[subgraphIndex];
1034 SetupInputLayerTensorInfos(subgraphIndex);
1035 SetupConstantLayerTensorInfos(subgraphIndex);
Mike Kelly377fb212023-01-10 15:55:28 +00001036
Colm Donelan58125042023-11-08 21:11:05 +00001037 m_SubgraphConnections.emplace_back(subgraph->tensors.size());
1038 for (const OperatorPtr& op : subgraph->operators)
1039 {
1040 const auto& opCodePtr = m_Model->operator_codes[op->opcode_index];
Jim Flynnfca233e2021-09-23 12:16:53 +01001041
1042// 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 +01001043#if defined(ARMNN_POST_TFLITE_2_3)
Colm Donelan58125042023-11-08 21:11:05 +00001044 auto builtinCode = std::max(opCodePtr->builtin_code,
1045 static_cast<tflite::BuiltinOperator>(opCodePtr->deprecated_builtin_code));
Jim Flynnfca233e2021-09-23 12:16:53 +01001046#else
Colm Donelan58125042023-11-08 21:11:05 +00001047 auto builtinCode = opCodePtr->builtin_code;
Jim Flynnfca233e2021-09-23 12:16:53 +01001048#endif
telsoa01c577f2c2018-08-31 09:22:23 +01001049
Colm Donelan58125042023-11-08 21:11:05 +00001050 if (builtinCode > tflite::BuiltinOperator_MAX)
1051 {
1052 throw ParseException(fmt::format("Operator code {} is out of range 0-{}. "
1053 "subgraph:{} operator idx:{}. {}",
1054 builtinCode, tflite::BuiltinOperator_MAX, subgraphIndex,
1055 operatorIndex, CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01001056 }
telsoa01c577f2c2018-08-31 09:22:23 +01001057
Colm Donelan58125042023-11-08 21:11:05 +00001058 // lookup and call the parser function
1059 auto& parserFunction = m_ParserFunctions[builtinCode];
1060 (this->*parserFunction)(subgraphIndex, operatorIndex);
1061 ++operatorIndex;
telsoa01c577f2c2018-08-31 09:22:23 +01001062 }
Colm Donelan58125042023-11-08 21:11:05 +00001063
1064 SetupInputLayers(subgraphIndex);
1065 SetupOutputLayers(subgraphIndex);
1066 SetupConstantLayers(subgraphIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001067 }
Colm Donelan6350d272020-06-09 16:56:25 +01001068 catch (const ParseException& e)
telsoa01c577f2c2018-08-31 09:22:23 +01001069 {
Colm Donelan6350d272020-06-09 16:56:25 +01001070 std::stringstream errorString;
1071 errorString << "Failed to parse operator #" << operatorIndex << " within subgraph #"
1072 << subgraphIndex << " error: " << e.what();
1073 ARMNN_LOG(error) << errorString.str();
1074 std::stringstream errors;
1075 errors << errorString.str() << "\n";
telsoa01c577f2c2018-08-31 09:22:23 +01001076 throw ParseException(errors.str());
1077 }
1078
1079 // establish the connections from the layer outputs to the inputs of the subsequent layers
Colm Donelan6350d272020-06-09 16:56:25 +01001080 for (subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001081 {
1082 for (size_t tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
1083 {
1084 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot != nullptr)
1085 {
1086 for (size_t inputSlotIdx = 0;
1087 inputSlotIdx < m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size();
1088 ++inputSlotIdx)
1089 {
1090 m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot->Connect(
1091 *(m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots[inputSlotIdx]));
1092 }
1093 }
1094 }
1095 }
telsoa01c577f2c2018-08-31 09:22:23 +01001096 return std::move(m_Network);
1097}
1098
Mike Kelly0506ef02023-01-03 16:29:44 +00001099bool TfLiteParserImpl::ShouldConstantTensorBeConverted(TfLiteParserImpl::TensorRawPtr tensorPtr,
1100 armnn::DataType inputDataType,
1101 armnn::DataType tensorDataType)
Mike Kelly5880b912022-01-28 16:18:54 +00001102{
Mike Kelly0506ef02023-01-03 16:29:44 +00001103 return (TfLiteParserImpl::IsConstTensor(tensorPtr) && inputDataType == DataType::Float32 &&
1104 (tensorDataType == DataType::QAsymmU8 ||
1105 tensorDataType == DataType::QAsymmS8 ||
1106 tensorDataType == DataType::QSymmS8 ||
1107 tensorDataType == DataType::Signed32 ||
1108 tensorDataType == DataType::Signed64));
Mike Kelly5880b912022-01-28 16:18:54 +00001109}
1110
Kevin May7d96b162021-02-03 17:38:41 +00001111void TfLiteParserImpl::RegisterProducerOfTensor(size_t subgraphIndex,
1112 size_t tensorIndex,
1113 armnn::IOutputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +01001114{
1115 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001116
1117 TensorSlots & tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
1118
Nikhil Rajd4d1c312022-08-03 18:20:59 +01001119 if (slot->GetOwningIConnectableLayer().GetType() != LayerType::Constant)
telsoa01c577f2c2018-08-31 09:22:23 +01001120 {
telsoa01c577f2c2018-08-31 09:22:23 +01001121
Nikhil Rajd4d1c312022-08-03 18:20:59 +01001122 // assuming there is only one producer for that tensor
1123 if (tensorSlots.outputSlot != nullptr)
1124 {
1125 throw ParseException(fmt::format("Another layer has already registered itself as the producer of "
1126 "subgraph:{} tensor:{} {}",
1127 subgraphIndex,
1128 tensorIndex,
1129 CHECK_LOCATION().AsString()));
1130 }
1131 }
telsoa01c577f2c2018-08-31 09:22:23 +01001132 tensorSlots.outputSlot = slot;
1133}
1134
Kevin May7d96b162021-02-03 17:38:41 +00001135void TfLiteParserImpl::RegisterConsumerOfTensor(size_t subgraphIndex,
1136 size_t tensorIndex,
1137 armnn::IInputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +01001138{
1139 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001140
Finn Williamsd4fa5452021-03-01 12:31:41 +00001141 TensorSlots& tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01001142 tensorSlots.inputSlots.push_back(slot);
1143}
1144
Kevin May7d96b162021-02-03 17:38:41 +00001145void TfLiteParserImpl::ParseCustomOperator(size_t subgraphIndex, size_t operatorIndex)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001146{
1147 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1148
1149 // NOTE: By default we presume the custom operator is not supported
Kevin May7d96b162021-02-03 17:38:41 +00001150 auto customParserFunction = &TfLiteParserImpl::ParseUnsupportedOperator;
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001151
1152 // Identify custom code defined for custom operator
1153 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1154 const auto& customCode = m_Model->operator_codes[operatorPtr->opcode_index]->custom_code;
1155
Mike Kelly377fb212023-01-10 15:55:28 +00001156 // Find parser function that corresponds to custom code (if any)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001157 auto iterator = m_CustomParserFunctions.find(customCode);
1158 if (iterator != m_CustomParserFunctions.end())
1159 {
1160 customParserFunction = iterator->second;
1161 }
1162
1163 // Run parser function
1164 (this->*customParserFunction)(subgraphIndex, operatorIndex);
1165}
1166
Kevin May7d96b162021-02-03 17:38:41 +00001167void TfLiteParserImpl::ParseUnsupportedOperator(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001168{
1169 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001170
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001171 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1172
1173 auto opcodeIndex = operatorPtr->opcode_index;
Jim Flynnfca233e2021-09-23 12:16:53 +01001174
1175// 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 +01001176#if defined(ARMNN_POST_TFLITE_2_3)
Jim Flynnfca233e2021-09-23 12:16:53 +01001177 auto opcode = std::max(m_Model->operator_codes[opcodeIndex]->builtin_code,
1178 static_cast<tflite::BuiltinOperator>(m_Model->operator_codes[opcodeIndex]->deprecated_builtin_code));
1179#else
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001180 auto opcode = m_Model->operator_codes[opcodeIndex]->builtin_code;
Jim Flynnfca233e2021-09-23 12:16:53 +01001181#endif
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001182
1183 if (!m_Options || !m_Options.value().m_StandInLayerForUnsupported)
1184 {
1185 // Do not add StandInLayer, throw ParseException instead
1186 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01001187 fmt::format("Operator not supported. "
1188 "subgraph:{} operator:{} "
1189 "opcode_index:{} opcode:{} / {} {}",
1190 subgraphIndex,
1191 operatorIndex,
1192 opcodeIndex,
1193 opcode,
1194 tflite::EnumNameBuiltinOperator(opcode),
1195 CHECK_LOCATION().AsString()));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001196 }
1197
1198 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1199 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1200
Matthew Sloyan589e3e82020-09-11 16:17:48 +01001201 const unsigned int numInputs = armnn::numeric_cast<unsigned int>(inputs.size());
1202 const unsigned int numOutputs = armnn::numeric_cast<unsigned int>(outputs.size());
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001203
1204 StandInDescriptor descriptor(numInputs, numOutputs);
James Ward58dec6b2020-09-11 17:32:44 +01001205 auto layerName = fmt::format("StandIn:{}:{}:{}", subgraphIndex, operatorIndex, opcode);
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001206
1207 // Add a non-executable StandInLayer as a placeholder for any unsupported operator
1208 IConnectableLayer* layer = m_Network->AddStandInLayer(descriptor, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01001209
1210 if (!layer)
1211 {
1212 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1213 operatorIndex, CHECK_LOCATION().AsString()));
1214 }
James Conroy05102392020-06-24 15:39:55 +01001215
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001216 for (unsigned int i = 0u; i < numOutputs; ++i)
1217 {
Mike Kelly04d82292023-01-19 18:29:40 +00001218 layer->GetOutputSlot(i).SetTensorInfo(ToTensorInfo(outputs[0], true));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001219 }
1220
1221 auto inputTensorIds = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1222 auto outputTensorIds = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1223
1224 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIds);
1225 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIds);
telsoa01c577f2c2018-08-31 09:22:23 +01001226}
1227
mathad01b392e982021-04-07 12:07:30 +01001228void TfLiteParserImpl::ParseCast(size_t subgraphIndex, size_t operatorIndex)
1229{
1230 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1231
1232 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1233 CHECK_VALID_SIZE(inputs.size(), 1);
1234 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1235 CHECK_VALID_SIZE(outputs.size(), 1);
1236
1237 auto layerName = fmt::format("Cast:{}:{}", subgraphIndex, operatorIndex);
1238
1239 IConnectableLayer* layer = m_Network->AddCastLayer(layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01001240
1241 if (!layer)
1242 {
1243 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1244 operatorIndex, CHECK_LOCATION().AsString()));
1245 }
mathad01b392e982021-04-07 12:07:30 +01001246
Mike Kelly377fb212023-01-10 15:55:28 +00001247 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
mathad01b392e982021-04-07 12:07:30 +01001248 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1249
1250 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1251 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1252
1253 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1254 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1255}
1256
Kevin May7d96b162021-02-03 17:38:41 +00001257void TfLiteParserImpl::ParseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001258{
1259 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1260
Mike Kelly0d77ae12022-01-07 17:42:27 +00001261 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1262 const auto* options = operatorPtr->builtin_options.AsConv2DOptions();
telsoa01c577f2c2018-08-31 09:22:23 +01001263
1264 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1265
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001266 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1267 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1268 CHECK_VALID_SIZE(outputs.size(), 1);
1269
telsoa01c577f2c2018-08-31 09:22:23 +01001270 Convolution2dDescriptor desc;
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001271 inputs.size() == 3 ?
1272 desc.m_BiasEnabled = true : desc.m_BiasEnabled = false;
telsoa01c577f2c2018-08-31 09:22:23 +01001273 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1274 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +00001275 desc.m_DataLayout = armnn::DataLayout::NHWC;
Pablo Tellof0bd6832019-04-26 17:58:13 +01001276 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1277 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +00001278
Mike Kelly377fb212023-01-10 15:55:28 +00001279 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
1280 armnn::TensorInfo filterTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
telsoa01c577f2c2018-08-31 09:22:23 +01001281
1282 // assuming input is NHWC
1283 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001284 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
telsoa01c577f2c2018-08-31 09:22:23 +01001285
1286 // assuming the filter is OHWI : Output, H, W, Input
1287 // which is essentially the same as NHWC
1288 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001289 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
telsoa01c577f2c2018-08-31 09:22:23 +01001290
Pablo Tellof0bd6832019-04-26 17:58:13 +01001291 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1292 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1293 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1294 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +01001295
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001296 // Add the first input and weights tensor to the registration list.
1297 // The constant weights will be added by SetupConstantLayers.
1298 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1299 std::vector<unsigned int> tensorIndexesToRegister = { inputTensorIndexes[0], inputTensorIndexes[1] };
telsoa01c577f2c2018-08-31 09:22:23 +01001300
James Ward58dec6b2020-09-11 17:32:44 +01001301 auto layerName = fmt::format("Conv2D:{}:{}", subgraphIndex, operatorIndex);
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001302 armnn::IConnectableLayer* layer = m_Network->AddConvolution2dLayer(desc, layerName.c_str());
telsoa01c577f2c2018-08-31 09:22:23 +01001303
Mike Kelly0506ef02023-01-03 16:29:44 +00001304 if (ShouldConstantTensorBeConverted(inputs[1], inputTensorInfo.GetDataType(), filterTensorInfo.GetDataType()))
telsoa01c577f2c2018-08-31 09:22:23 +01001305 {
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001306 m_ConstantsToDequantize.emplace_back(inputs[1]->buffer);
telsoa01c577f2c2018-08-31 09:22:23 +01001307 }
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001308
1309 if (desc.m_BiasEnabled)
telsoa01c577f2c2018-08-31 09:22:23 +01001310 {
Mike Kelly377fb212023-01-10 15:55:28 +00001311 armnn::TensorInfo biasTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001312
1313 // Add the biases input to the registration list, a constant layer will be added by SetupConstantLayers.
1314 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
1315
Mike Kelly0506ef02023-01-03 16:29:44 +00001316 if (ShouldConstantTensorBeConverted(inputs[2], inputTensorInfo.GetDataType(), biasTensorInfo.GetDataType()))
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001317 {
1318 m_ConstantsToDequantize.emplace_back(inputs[2]->buffer);
1319 }
telsoa01c577f2c2018-08-31 09:22:23 +01001320 }
1321
Ryan OSheac229b3f2023-06-27 22:34:54 +01001322 if (!layer)
1323 {
1324 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1325 operatorIndex, CHECK_LOCATION().AsString()));
1326 }
telsoa01c577f2c2018-08-31 09:22:23 +01001327
Mike Kelly377fb212023-01-10 15:55:28 +00001328 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
jimfly01c25411c2018-11-14 17:47:22 +00001329 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001330
1331 // register the input connection slots for the layer, connections are made after all layers have been created
1332 // only the tensors for the inputs are relevant, exclude the const tensors
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001333 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
telsoa01c577f2c2018-08-31 09:22:23 +01001334
jimfly01c25411c2018-11-14 17:47:22 +00001335 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +01001336 // register the output connection slots for the layer, connections are made after all layers have been created
1337 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001338 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, { outputTensorIndexes[0] });
telsoa01c577f2c2018-08-31 09:22:23 +01001339}
1340
Matthew Sloyan4d217c02021-10-07 11:48:58 +01001341// Conv3D support was added in TF 2.5, so for backwards compatibility a hash define is needed.
Cathal Corbett80b4ef02022-05-25 11:21:11 +01001342#if defined(ARMNN_POST_TFLITE_2_4)
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001343void TfLiteParserImpl::ParseConv3D(size_t subgraphIndex, size_t operatorIndex)
1344{
1345 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1346
1347 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1348 const auto* options = operatorPtr->builtin_options.AsConv3DOptions();
1349
1350 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1351
1352 Convolution3dDescriptor desc;
1353 desc.m_BiasEnabled = false;
1354 desc.m_DataLayout = armnn::DataLayout::NDHWC;
1355 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1356 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1357 desc.m_StrideZ = CHECKED_NON_NEGATIVE(options->stride_d);
1358 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1359 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
1360 desc.m_DilationZ = CHECKED_NON_NEGATIVE(options->dilation_d_factor);
1361
1362 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1363 CHECK_VALID_SIZE(inputs.size(), 2, 3);
1364
1365 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1366 CHECK_VALID_SIZE(outputs.size(), 1);
1367
Mike Kelly377fb212023-01-10 15:55:28 +00001368 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
1369 armnn::TensorInfo filterTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001370
1371 // Assuming input is NDHWC
1372 unsigned int inputDepth = inputTensorInfo.GetShape()[1];
1373 unsigned int inputHeight = inputTensorInfo.GetShape()[2];
1374 unsigned int inputWidth = inputTensorInfo.GetShape()[3];
1375
1376 // Assuming the filter is DHWIO : Depth, Height, Width, OutputChannels, InputChannels
1377 unsigned int filterDepth = filterTensorInfo.GetShape()[0];
1378 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1379 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1380
1381 CalcPadding(inputDepth, filterDepth, desc.m_StrideZ,
Teresa Charlin502ab942022-03-23 17:23:07 +00001382 desc.m_DilationZ, desc.m_PadFront, desc.m_PadBack, options->padding);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001383 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1384 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1385 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1386 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
1387
Mike Kelly5880b912022-01-28 16:18:54 +00001388 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo, inputTensorInfo.GetDataType());
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001389
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001390 auto layerName = fmt::format("Conv3D:{}:{}", subgraphIndex, operatorIndex);
1391
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001392 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1393 // Add the first input and weights tensor to the registration list.
1394 // The constant weights will be added by SetupConstantLayers.
1395 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0], inputTensorIndexes[1]};
1396
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001397 if (inputs.size() == 3)
1398 {
1399 desc.m_BiasEnabled = true;
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001400
1401 // Add the biases input to the registration list, a constant layer will be added by SetupConstantLayers.
1402 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001403 }
1404
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001405 armnn::IConnectableLayer* layer = m_Network->AddConvolution3dLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01001406
1407 if (!layer)
1408 {
1409 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1410 operatorIndex, CHECK_LOCATION().AsString()));
1411 }
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001412
Mike Kelly377fb212023-01-10 15:55:28 +00001413 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001414 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1415
1416 // Register the input connection slots for the layer, connections are made after all layers have been created
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001417 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001418
1419 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1420 // Register the output connection slots for the layer, connections are made after all layers have been created
1421 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1422 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1423}
Matthew Sloyan4d217c02021-10-07 11:48:58 +01001424#endif
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001425
Kevin May7d96b162021-02-03 17:38:41 +00001426void TfLiteParserImpl::ParseDepthwiseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001427{
1428 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1429
Mike Kelly0d77ae12022-01-07 17:42:27 +00001430 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1431 const auto* options = operatorPtr->builtin_options.AsDepthwiseConv2DOptions();
telsoa01c577f2c2018-08-31 09:22:23 +01001432
1433 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1434
1435 DepthwiseConvolution2dDescriptor desc;
telsoa01c577f2c2018-08-31 09:22:23 +01001436 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1437 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +00001438 desc.m_DataLayout = armnn::DataLayout::NHWC;
Matthew Jacksond6a9dee2019-07-22 13:53:24 +01001439 CHECKED_NON_NEGATIVE(options->depth_multiplier);
telsoa01c577f2c2018-08-31 09:22:23 +01001440
1441 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1442 CHECK_VALID_SIZE(inputs.size(), 2, 3);
Cathal Corbett06902652022-04-14 17:55:11 +01001443 if (inputs.size() == 3)
1444 {
1445 desc.m_BiasEnabled = true;
1446 }
1447
telsoa01c577f2c2018-08-31 09:22:23 +01001448 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1449 CHECK_VALID_SIZE(outputs.size(), 1);
Pablo Tellof0bd6832019-04-26 17:58:13 +01001450 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1451 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +00001452
Mike Kelly377fb212023-01-10 15:55:28 +00001453 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
1454 armnn::TensorInfo filterTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
telsoa01c577f2c2018-08-31 09:22:23 +01001455
Matteo Martincigh747ef822018-12-18 09:26:39 +00001456 // Assuming input is NHWC
telsoa01c577f2c2018-08-31 09:22:23 +01001457 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1458 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
Matteo Martincigh747ef822018-12-18 09:26:39 +00001459
1460 // TensorflowLite weights come in the format [1, H, W, I * M]
telsoa01c577f2c2018-08-31 09:22:23 +01001461 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1462 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1463
Pablo Tellof0bd6832019-04-26 17:58:13 +01001464 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1465 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1466 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1467 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +01001468
Jan Eilers53ef7952021-06-02 12:01:25 +01001469 // 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 +01001470 auto layerName = fmt::format("DepthwiseConv2D:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001471
Cathal Corbett06902652022-04-14 17:55:11 +01001472 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1473 // Add the first input and weights tensor to the registration list.
1474 // The constant weights will be added by SetupConstantLayers.
1475 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0], inputTensorIndexes[1]};
1476
1477 armnn::IConnectableLayer* layer = m_Network->AddDepthwiseConvolution2dLayer(desc, layerName.c_str());
1478
1479 if (desc.m_BiasEnabled)
telsoa01c577f2c2018-08-31 09:22:23 +01001480 {
1481 desc.m_BiasEnabled = true;
Mike Kelly377fb212023-01-10 15:55:28 +00001482 TensorInfo biasTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
Cathal Corbett06902652022-04-14 17:55:11 +01001483
1484 // Add the biases input to the registration list, a constant layer will be added by SetupConstantLayers.
1485 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
telsoa01c577f2c2018-08-31 09:22:23 +01001486 }
Ryan OSheac229b3f2023-06-27 22:34:54 +01001487
1488 if (!layer)
1489 {
1490 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1491 operatorIndex, CHECK_LOCATION().AsString()));
1492 }
telsoa01c577f2c2018-08-31 09:22:23 +01001493
Mike Kelly377fb212023-01-10 15:55:28 +00001494 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
jimfly01c25411c2018-11-14 17:47:22 +00001495 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001496
1497 // register the input connection slots for the layer, connections are made after all layers have been created
1498 // only the tensors for the inputs are relevant, exclude the const tensors
Cathal Corbett06902652022-04-14 17:55:11 +01001499 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
telsoa01c577f2c2018-08-31 09:22:23 +01001500
jimfly01c25411c2018-11-14 17:47:22 +00001501 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +01001502 // register the output connection slots for the layer, connections are made after all layers have been created
1503 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1504 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1505}
1506
Kevin May7d96b162021-02-03 17:38:41 +00001507void TfLiteParserImpl::ParseDequantize(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsed66d142019-12-06 09:55:55 +00001508{
1509 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1510
1511 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1512 CHECK_VALID_SIZE(inputs.size(), 1);
1513
1514 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1515 CHECK_VALID_SIZE(outputs.size(), 1);
1516
James Ward58dec6b2020-09-11 17:32:44 +01001517 auto layerName = fmt::format("Dequantize:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsed66d142019-12-06 09:55:55 +00001518
1519 IConnectableLayer* layer = m_Network->AddDequantizeLayer(layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01001520
1521 if (!layer)
1522 {
1523 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1524 operatorIndex, CHECK_LOCATION().AsString()));
1525 }
Finn Williamsed66d142019-12-06 09:55:55 +00001526
Mike Kelly377fb212023-01-10 15:55:28 +00001527 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Finn Williamsed66d142019-12-06 09:55:55 +00001528 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1529
1530 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1531 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1532
1533 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1534 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1535}
1536
Teresa Charlin3ab85482021-06-08 16:59:29 +01001537void TfLiteParserImpl::ParseExpandDims(size_t subgraphIndex, size_t operatorIndex)
1538{
1539 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1540
1541 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1542 CHECK_VALID_SIZE(inputs.size(), 2);
1543
1544 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1545 CHECK_VALID_SIZE(outputs.size(), 1);
1546
1547 auto layerName = fmt::format("ExpandDims:{}:{}", subgraphIndex, operatorIndex);
1548
Mike Kelly377fb212023-01-10 15:55:28 +00001549 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Teresa Charlin3ab85482021-06-08 16:59:29 +01001550 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Teresa Charlin3ab85482021-06-08 16:59:29 +01001551 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1552
Teresa Charlina7a605a2023-06-14 14:51:17 +01001553 armnn::TensorInfo axisTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
1554
1555 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1556 if (axisBufferPtr == nullptr)
1557 {
1558 throw ParseException(fmt::format("{}: Operation has invalid inputs. Failed to read axis.",
1559 CHECK_LOCATION().AsString()));
1560 }
1561
1562 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
1563 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
1564 int32_t axis = axisData[0];
1565
1566 auto inputRank = static_cast<int32_t>(inputTensorInfo.GetShape().GetNumDimensions());
1567 auto outputRank = inputRank + 1;
1568 if((axis < -1 * outputRank) || (outputRank <= axis))
1569 {
1570 throw ParseException(fmt::format("{}: Axis {} is not within [-{}, {}) range.",
1571 CHECK_LOCATION().AsString(), axis, outputRank, outputRank));
1572 }
1573
1574 axis = axis < 0 ? (axis + outputRank) : axis;
1575
1576 std::vector<unsigned int> shape(static_cast<unsigned int>(outputRank));
1577 unsigned int inputShapeIndex = 0;
1578 for (unsigned int i = 0; i < static_cast<unsigned int>(outputRank); ++i)
1579 {
1580 if (i == static_cast<unsigned int>(axis))
1581 {
1582 shape[i] = 1;
1583 }
1584 else
1585 {
1586 shape[i] = inputTensorInfo.GetShape()[inputShapeIndex];
1587 ++inputShapeIndex;
1588 }
1589 }
1590
Teresa Charlin3ab85482021-06-08 16:59:29 +01001591 ReshapeDescriptor reshapeDesc;
Teresa Charlina7a605a2023-06-14 14:51:17 +01001592 reshapeDesc.m_TargetShape = TensorShape(static_cast<unsigned int>(outputRank), shape.data());
1593 outputTensorInfo.SetShape(reshapeDesc.m_TargetShape);
Teresa Charlin3ab85482021-06-08 16:59:29 +01001594
1595 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01001596
1597 if (!layer)
1598 {
1599 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1600 operatorIndex, CHECK_LOCATION().AsString()));
1601 } layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Teresa Charlin3ab85482021-06-08 16:59:29 +01001602
Teresa Charlina7a605a2023-06-14 14:51:17 +01001603 auto outputTensorIds = GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex);
1604 m_TensorInfos[outputTensorIds[0]] = outputTensorInfo;
1605
Teresa Charlin3ab85482021-06-08 16:59:29 +01001606 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1607 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1608
1609 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1610 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1611}
1612
Kevin May7d96b162021-02-03 17:38:41 +00001613void TfLiteParserImpl::ParseTranspose(size_t subgraphIndex, size_t operatorIndex)
Keith Davis4cd29a02019-09-09 14:49:20 +01001614{
1615 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1616
1617 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Kevin May85d92602019-09-27 17:21:06 +01001618 CHECK_VALID_SIZE(inputs.size(), 1, 2);
Keith Davis4cd29a02019-09-09 14:49:20 +01001619
1620 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1621 CHECK_VALID_SIZE(outputs.size(), 1);
1622
James Ward58dec6b2020-09-11 17:32:44 +01001623 auto layerName = fmt::format("Transpose:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly08759e22020-03-02 11:41:31 +00001624 TransposeDescriptor desc;
Keith Davis4cd29a02019-09-09 14:49:20 +01001625
josh minorba424d22019-11-13 10:55:17 -06001626 if (inputs.size() == 2)
Kevin May85d92602019-09-27 17:21:06 +01001627 {
Mike Kelly377fb212023-01-10 15:55:28 +00001628 armnn::TensorInfo permuteTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Kevin May85d92602019-09-27 17:21:06 +01001629 BufferRawPtr permuteBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
josh minorba424d22019-11-13 10:55:17 -06001630 auto numPermVecElements = permuteTensorInfo.GetNumElements();
1631 std::vector<unsigned int> permuteShape(numPermVecElements);
Kevin May85d92602019-09-27 17:21:06 +01001632 ::memcpy(permuteShape.data(), permuteBufferPtr->data.data(), permuteTensorInfo.GetNumBytes());
Mike Kelly08759e22020-03-02 11:41:31 +00001633 PermutationVector permutationVector(permuteShape.data(), permuteTensorInfo.GetNumElements());
Kevin May85d92602019-09-27 17:21:06 +01001634
Mike Kelly08759e22020-03-02 11:41:31 +00001635 desc = TransposeDescriptor(permutationVector);
Kevin May85d92602019-09-27 17:21:06 +01001636 }
Mike Kelly377fb212023-01-10 15:55:28 +00001637 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Keith Davis4cd29a02019-09-09 14:49:20 +01001638
James Conroy05102392020-06-24 15:39:55 +01001639 IConnectableLayer* layer = m_Network->AddTransposeLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01001640
1641 if (!layer)
1642 {
1643 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1644 operatorIndex, CHECK_LOCATION().AsString()));
1645 }
Mike Kelly377fb212023-01-10 15:55:28 +00001646
1647 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
1648 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Keith Davis4cd29a02019-09-09 14:49:20 +01001649 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1650
1651 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1652 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1653
1654 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1655 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1656}
1657
Kevin May7d96b162021-02-03 17:38:41 +00001658void TfLiteParserImpl::ParseTransposeConv(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001659{
1660 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1661
Mike Kelly0d77ae12022-01-07 17:42:27 +00001662 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1663 const auto* options = operatorPtr->builtin_options.AsTransposeConvOptions();
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001664
1665 TransposeConvolution2dDescriptor desc;
1666 desc.m_BiasEnabled = false;
1667 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1668 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1669 desc.m_DataLayout = armnn::DataLayout::NHWC;
1670
1671 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
David Monahan61683802021-01-12 09:11:07 +00001672 if (inputs.size() == 4)
1673 {
1674 desc.m_BiasEnabled = true;
1675 }
1676 else
1677 {
1678 CHECK_VALID_SIZE(inputs.size(), 3);
1679 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001680
1681 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1682 CHECK_VALID_SIZE(outputs.size(), 1);
1683
Teresa Charlin024ef0b2023-04-26 11:19:03 +01001684
1685 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
1686 armnn::TensorInfo filterTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
1687
1688 // TfLite uses NHWC tensors
1689 const unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1690 const unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1691
1692 const unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1693 const unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1694
Ryan OSheaf0a35b82023-02-21 18:32:30 +00001695 // This block determines the output shape of the transpose convolution. If the output shape tensor ptr is not null
1696 // And the tensor is a constant, we can access the data at load time and set the output shape of the
1697 // layer. If this is not constant, We do not have access to the shape data, so we have to use
1698 // infer output shape and skip this code block.
1699 if (inputs[0] && IsConstTensor(inputs[0]))
Colm Donelan0ad3ef12020-07-03 15:54:28 +01001700 {
Mike Kelly377fb212023-01-10 15:55:28 +00001701 armnn::TensorInfo tensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Colm Donelan0ad3ef12020-07-03 15:54:28 +01001702 std::vector<int> output_shape(tensorInfo.GetNumElements());
Mike Kelly377fb212023-01-10 15:55:28 +00001703
Colm Donelan0ad3ef12020-07-03 15:54:28 +01001704 if (tensorInfo.GetDataType() == DataType::Signed32)
1705 {
1706 ::memcpy(output_shape.data(), GetBuffer(m_Model, inputs[0]->buffer)->data.data(), tensorInfo.GetNumBytes());
1707 }
1708 if (tensorInfo.GetDataType() == DataType::QAsymmU8)
1709 {
1710 for(unsigned int i=0; i < tensorInfo.GetNumElements(); i++)
1711 {
1712 output_shape[i] = GetBuffer(m_Model, inputs[0]->buffer)->data.data()[i];
1713 }
1714 }
1715 // Change from signed to unsigned int to store in TransposeConvolution2dDescriptor.
1716 for (int dimension : output_shape)
1717 {
1718 desc.m_OutputShape.push_back(static_cast<unsigned int>(dimension));
1719 }
1720 desc.m_OutputShapeEnabled = true;
Teresa Charlin024ef0b2023-04-26 11:19:03 +01001721
1722 // TfLite uses NHWC tensors
1723 const unsigned int outputHeight = desc.m_OutputShape[1];
1724 const unsigned int outputWidth = desc.m_OutputShape[2];
1725
1726 CalcPadding(inputHeight,
1727 filterHeight,
1728 desc.m_StrideY,
1729 1, // DilationY
1730 desc.m_PadTop,
1731 desc.m_PadBottom,
1732 options->padding,
1733 outputHeight);
1734
1735 CalcPadding(inputWidth,
1736 filterWidth,
1737 desc.m_StrideX,
1738 1, // DilationX
1739 desc.m_PadLeft,
1740 desc.m_PadRight,
1741 options->padding,
1742 outputWidth);
Colm Donelan0ad3ef12020-07-03 15:54:28 +01001743 }
Teresa Charlin024ef0b2023-04-26 11:19:03 +01001744 else
1745 {
1746 CalcPadding(inputHeight,
1747 filterHeight,
1748 desc.m_StrideY,
1749 1, // DilationY
1750 desc.m_PadTop,
1751 desc.m_PadBottom,
1752 options->padding);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001753
Teresa Charlin024ef0b2023-04-26 11:19:03 +01001754 CalcPadding(inputWidth,
1755 filterWidth,
1756 desc.m_StrideX,
1757 1, // DilationX
1758 desc.m_PadLeft,
1759 desc.m_PadRight,
1760 options->padding);
1761 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001762
Mike Kelly5880b912022-01-28 16:18:54 +00001763 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo, inputTensorInfo.GetDataType());
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001764
1765 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01001766 auto layerName = fmt::format("TransposeConv:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001767
David Monahan61683802021-01-12 09:11:07 +00001768 if (desc.m_BiasEnabled)
1769 {
Mike Kelly377fb212023-01-10 15:55:28 +00001770 auto biasTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 3);
Mike Kelly5880b912022-01-28 16:18:54 +00001771 auto biasConstTensor = CreateConstTensorNonPermuted(inputs[3], biasTensorInfo, inputTensorInfo.GetDataType());
David Monahan61683802021-01-12 09:11:07 +00001772 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Mike Kelly5880b912022-01-28 16:18:54 +00001773 filterTensorAndData.first,
1774 biasConstTensor.first,
David Monahan61683802021-01-12 09:11:07 +00001775 layerName.c_str());
1776 }
1777 else
1778 {
1779 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Mike Kelly5880b912022-01-28 16:18:54 +00001780 filterTensorAndData.first,
David Monahan61683802021-01-12 09:11:07 +00001781 EmptyOptional(),
1782 layerName.c_str());
1783 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001784
Ryan OSheac229b3f2023-06-27 22:34:54 +01001785 if (!layer)
1786 {
1787 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1788 operatorIndex, CHECK_LOCATION().AsString()));
1789 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001790
Mike Kelly377fb212023-01-10 15:55:28 +00001791 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0 , { 2, 1 });
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001792 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1793
1794 // only the tensors for the inputs are relevant, exclude the const (filter) tensor
1795 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Matthew Jacksonccb25ea2019-08-20 17:18:33 +01001796 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[2]});
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001797
1798 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1799 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1800}
1801
Kevin May7d96b162021-02-03 17:38:41 +00001802void TfLiteParserImpl::ParseAveragePool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001803{
1804 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Average);
1805}
1806
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001807void TfLiteParserImpl::ParseBatchMatMul(size_t subgraphIndex, size_t operatorIndex)
1808{
1809 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1810
1811 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1812 CHECK_VALID_SIZE(inputs.size(), 2);
1813
1814 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1815 CHECK_VALID_SIZE(outputs.size(), 1);
1816
1817 auto layerName = fmt::format("BatchMatMul:{}:{}", subgraphIndex, operatorIndex);
1818
Mike Kelly377fb212023-01-10 15:55:28 +00001819 TensorInfo inputXTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
1820 TensorInfo inputYTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001821
1822 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1823 const auto* options = operatorPtr->builtin_options.AsBatchMatMulOptions();
1824
Teresa Charlinbc37a6b2022-09-22 10:12:58 +01001825 // Adjoint in tensorflow lite performs transpose operation
1826 BatchMatMulDescriptor descriptor(options->adj_x,
1827 options->adj_y,
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001828 false,
Teresa Charlinbc37a6b2022-09-22 10:12:58 +01001829 false);
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001830 // Arbitrary DataLayout
1831
1832 IConnectableLayer* layer = m_Network->AddBatchMatMulLayer(descriptor, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01001833
1834 if (!layer)
1835 {
1836 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1837 operatorIndex, CHECK_LOCATION().AsString()));
1838 }
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001839
Mike Kelly377fb212023-01-10 15:55:28 +00001840 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001841 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1842
1843 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1844 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
1845
1846 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1847 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1848}
1849
Kevin May7d96b162021-02-03 17:38:41 +00001850void TfLiteParserImpl::ParseBatchToSpaceND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001851{
1852 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1853
1854 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1855 CHECK_VALID_SIZE(inputs.size(), 3);
1856
1857 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1858 CHECK_VALID_SIZE(outputs.size(), 1);
1859
Mike Kelly377fb212023-01-10 15:55:28 +00001860 armnn::TensorInfo blockShapeTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001861 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1862
Mike Kelly377fb212023-01-10 15:55:28 +00001863 armnn::TensorInfo cropsTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001864 BufferRawPtr cropsBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1865
1866 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1867 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1868
1869 std::vector<unsigned int> cropsVector(cropsTensorInfo.GetNumElements());
1870 ::memcpy(cropsVector.data(), cropsBufferPtr->data.data(), cropsTensorInfo.GetNumBytes());
1871
1872 size_t step = 2;
1873 std::vector<std::pair<unsigned int, unsigned int>> crops;
1874 for (unsigned int i = 0; i < cropsTensorInfo.GetNumElements() / step; ++i)
1875 {
1876 crops.emplace_back(cropsVector[i * step], cropsVector[i * step + 1]);
1877 }
1878
1879 armnn::BatchToSpaceNdDescriptor desc;
1880 desc.m_BlockShape = blockShape;
1881 desc.m_Crops = crops;
1882 desc.m_DataLayout = armnn::DataLayout::NHWC;
1883
James Ward58dec6b2020-09-11 17:32:44 +01001884 auto layerName = fmt::format("BatchToSpaceND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001885
Mike Kelly377fb212023-01-10 15:55:28 +00001886 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
James Conroy05102392020-06-24 15:39:55 +01001887
1888 IConnectableLayer* layer = m_Network->AddBatchToSpaceNdLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01001889
1890 if (!layer)
1891 {
1892 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1893 operatorIndex, CHECK_LOCATION().AsString()));
1894 }
Mike Kelly377fb212023-01-10 15:55:28 +00001895
1896 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
1897 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001898 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1899
1900 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1901 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1902
1903 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1904 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1905}
1906
Idriss Chaouch564c13d2023-09-01 17:58:38 +01001907void TfLiteParserImpl::ParseBroadcastTo(size_t subgraphIndex, size_t operatorIndex)
1908{
1909 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1910
1911 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1912 CHECK_VALID_SIZE(inputs.size(), 2);
1913
1914 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1915 CHECK_VALID_SIZE(outputs.size(), 1);
1916
1917 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1918 TensorInfo shapeTensorInfo = ToTensorInfo(inputs[1]);
1919 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
1920
1921 auto layerName = fmt::format("Broadcast_to:{}:{}", subgraphIndex, operatorIndex);
1922
1923 BroadcastToDescriptor descriptor;
1924
1925 auto shapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1926 if (shapeBufferPtr != nullptr)
1927 {
1928 std::vector<unsigned int> targetShape;
1929 unsigned int numElement = shapeTensorInfo.GetNumElements();
1930 auto shapeData = reinterpret_cast<const int32_t*>(shapeBufferPtr->data.data());
1931 if (shapeData)
1932 {
1933 for (unsigned int i = 0; i < numElement; ++i)
1934 {
1935 targetShape.push_back(armnn::numeric_cast<unsigned int>(shapeData[i]));
1936 }
1937 descriptor.m_BroadcastToShape = TensorShape(numElement, targetShape.data());
1938 }
1939 /// get dataShape from outputShape if missing
1940 else
1941 {
1942 if(outputTensorInfo.GetShape().GetNumElements() <= 1)
1943 {
1944 ARMNN_THROW_PARSE_EXCEPTION("For Broadcast_to layer, "
1945 "data and output shape are not found in the buffer.");
1946 }
1947 descriptor.m_BroadcastToShape = outputTensorInfo.GetShape();
1948 }
1949 }
1950 else
1951 {
1952 ARMNN_THROW_PARSE_EXCEPTION("For Broadcast_to layer, Shape data was not found in the buffer.");
1953 }
1954
1955 IConnectableLayer* layer = m_Network->AddBroadcastToLayer(descriptor, layerName.c_str());
1956 ARMNN_ASSERT(layer != nullptr);
1957
1958 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1959
1960 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1961 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1962
1963 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1964 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1965}
1966
Kevin May7d96b162021-02-03 17:38:41 +00001967void TfLiteParserImpl::ParseL2Normalization(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson28c94572019-07-18 10:47:03 +01001968{
1969 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1970
1971 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1972 CHECK_VALID_SIZE(inputs.size(), 1);
1973
1974 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1975 CHECK_VALID_SIZE(outputs.size(), 1);
1976
1977 L2NormalizationDescriptor desc;
1978 desc.m_DataLayout = armnn::DataLayout::NHWC;
James Ward58dec6b2020-09-11 17:32:44 +01001979 auto layerName = fmt::format("L2Normalization:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson28c94572019-07-18 10:47:03 +01001980 IConnectableLayer* layer = m_Network->AddL2NormalizationLayer(desc, layerName.c_str());
1981
Ryan OSheac229b3f2023-06-27 22:34:54 +01001982 if (!layer)
1983 {
1984 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
1985 operatorIndex, CHECK_LOCATION().AsString()));
1986 }
Matthew Jackson28c94572019-07-18 10:47:03 +01001987
Mike Kelly377fb212023-01-10 15:55:28 +00001988 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Matthew Jackson28c94572019-07-18 10:47:03 +01001989 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1990
1991 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1992 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1993
1994 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1995 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1996}
1997
Kevin May7d96b162021-02-03 17:38:41 +00001998void TfLiteParserImpl::ParseMaxPool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001999{
2000 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Max);
2001}
2002
Kevin May7d96b162021-02-03 17:38:41 +00002003void TfLiteParserImpl::ParseMaximum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02002004{
2005 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2006
2007 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2008 CHECK_VALID_SIZE(inputs.size(), 2);
2009
2010 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2011 CHECK_VALID_SIZE(outputs.size(), 1);
2012
James Ward58dec6b2020-09-11 17:32:44 +01002013 auto layerName = fmt::format("Maximum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01002014
Mike Kelly377fb212023-01-10 15:55:28 +00002015 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2016 TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
James Conroy05102392020-06-24 15:39:55 +01002017 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02002018
Mike Kelly3ec30772023-03-08 13:47:17 +00002019 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::Maximum, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002020
2021 if (!layer)
2022 {
2023 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2024 operatorIndex, CHECK_LOCATION().AsString()));
2025 }
Mike Kelly377fb212023-01-10 15:55:28 +00002026
2027 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
2028 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02002029 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2030
2031 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002032 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02002033
2034 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2035 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2036}
2037
Kevin May7d96b162021-02-03 17:38:41 +00002038void TfLiteParserImpl::ParseMinimum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02002039{
2040 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2041
2042 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2043 CHECK_VALID_SIZE(inputs.size(), 2);
2044
2045 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2046 CHECK_VALID_SIZE(outputs.size(), 1);
2047
James Ward58dec6b2020-09-11 17:32:44 +01002048 auto layerName = fmt::format("Minimum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01002049
Mike Kelly377fb212023-01-10 15:55:28 +00002050 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2051 TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
James Conroy05102392020-06-24 15:39:55 +01002052 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02002053
Mike Kelly3ec30772023-03-08 13:47:17 +00002054 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::Minimum, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002055
2056 if (!layer)
2057 {
2058 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2059 operatorIndex, CHECK_LOCATION().AsString()));
2060 }
Mike Kelly377fb212023-01-10 15:55:28 +00002061
2062 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
2063 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02002064 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2065
2066 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002067 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02002068
2069 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2070 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2071}
2072
Kevin May7d96b162021-02-03 17:38:41 +00002073void TfLiteParserImpl::ParsePool(size_t subgraphIndex,
2074 size_t operatorIndex,
2075 PoolingAlgorithm algorithm)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002076{
2077 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2078
Mike Kelly0d77ae12022-01-07 17:42:27 +00002079 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2080 const auto* options = operatorPtr->builtin_options.AsPool2DOptions();
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002081
2082 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
2083
2084 std::string layerName;
2085
2086 switch (algorithm)
2087 {
2088 case PoolingAlgorithm::Average:
2089 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01002090 fmt::format("AveragePool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002091 break;
2092 case PoolingAlgorithm::Max:
2093 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01002094 fmt::format("MaxPool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002095 break;
2096 default:
Ryan OSheac229b3f2023-06-27 22:34:54 +01002097 throw ParseException(fmt::format("Unsupported Pooling Algorithm {}", CHECK_LOCATION().AsString()));
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002098 }
2099
2100 Pooling2dDescriptor desc;
2101
2102 desc.m_PoolType = algorithm;
2103 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
2104 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
2105 desc.m_PoolWidth = CHECKED_NON_NEGATIVE(options->filter_width);
2106 desc.m_PoolHeight = CHECKED_NON_NEGATIVE(options->filter_height);
2107 desc.m_PaddingMethod = PaddingMethod::Exclude;
2108 desc.m_OutputShapeRounding = OutputShapeRounding::Floor;
jimfly01c25411c2018-11-14 17:47:22 +00002109 desc.m_DataLayout = armnn::DataLayout::NHWC;
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002110
2111 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2112 CHECK_VALID_SIZE(inputs.size(), 1);
Mike Kelly377fb212023-01-10 15:55:28 +00002113 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002114
2115 // assuming input is NHWC
2116 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
2117 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
2118
Pablo Tellof0bd6832019-04-26 17:58:13 +01002119 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, 1u,
2120 desc.m_PadTop, desc.m_PadBottom, options->padding);
2121 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, 1u,
2122 desc.m_PadLeft, desc.m_PadRight, options->padding);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002123
2124 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2125 CHECK_VALID_SIZE(outputs.size(), 1);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002126
James Conroy05102392020-06-24 15:39:55 +01002127 IConnectableLayer* layer = m_Network->AddPooling2dLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002128
2129 if (!layer)
2130 {
2131 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2132 operatorIndex, CHECK_LOCATION().AsString()));
2133 }
Mike Kelly377fb212023-01-10 15:55:28 +00002134
2135 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
2136 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
jimfly01c25411c2018-11-14 17:47:22 +00002137 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002138
2139 // register the input connection slots for the layer, connections are made after all layers have been created
2140 // only the tensors for the inputs are relevant, exclude the const tensors
2141 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +00002142 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002143
jimfly01c25411c2018-11-14 17:47:22 +00002144 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01002145 // register the output connection slots for the layer, connections are made after all layers have been created
2146 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2147 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2148}
2149
Kevin May7d96b162021-02-03 17:38:41 +00002150void TfLiteParserImpl::ParseSlice(size_t subgraphIndex, size_t operatorIndex)
josh minorba424d22019-11-13 10:55:17 -06002151{
2152 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2153
2154 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2155 CHECK_VALID_SIZE(inputs.size(), 3);
2156 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2157 CHECK_VALID_SIZE(outputs.size(), 1);
2158
2159 SliceDescriptor desc;
2160
2161 // set begin tensor info for slice descriptor
Mike Kelly377fb212023-01-10 15:55:28 +00002162 armnn::TensorInfo beginTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
josh minorba424d22019-11-13 10:55:17 -06002163 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2164
2165 std::vector<unsigned int> begin(beginTensorInfo.GetNumElements());
2166 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
2167
2168 // set size tensor info for slice descriptor
Mike Kelly377fb212023-01-10 15:55:28 +00002169 armnn::TensorInfo sizeTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
josh minorba424d22019-11-13 10:55:17 -06002170 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
2171
Cathal Corbettde33dda2022-09-20 16:40:09 +01002172 std::vector<int> signedSize(sizeTensorInfo.GetNumElements(), 1);
2173
2174 // if size buffer data is not specified, all contents of size vector remain as values of 1
2175 if (sizeBufferPtr->data.data())
2176 {
2177 ::memcpy(signedSize.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
2178 }
2179
josh minorba424d22019-11-13 10:55:17 -06002180 std::vector<unsigned int> size(sizeTensorInfo.GetNumElements());
Mike Kelly377fb212023-01-10 15:55:28 +00002181 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Mike Kelly7ba84d62021-09-10 15:27:19 +01002182
2183 for (unsigned int i = 0; i < signedSize.size(); ++i)
2184 {
2185 int signedValue = signedSize[i];
Jim Flynnfca233e2021-09-23 12:16:53 +01002186
Mike Kelly7ba84d62021-09-10 15:27:19 +01002187 if (signedValue < -1 || signedValue > static_cast<int>(inputTensorInfo.GetShape()[i] - begin[i]))
2188 {
2189 throw ParseException(fmt::format("Invalid value for size {} size must be in range "
2190 "[-1, inputDimSize - begin] [-1, {}] inclusive {}",
2191 signedValue,
2192 inputTensorInfo.GetShape()[i] - begin[i],
2193 CHECK_LOCATION().AsString()));
2194 }
2195
2196 if (signedValue == -1)
2197 {
2198 size[i] = inputTensorInfo.GetShape()[i] - begin[i];
2199 }
2200 else
2201 {
2202 size[i] = static_cast<unsigned int>(signedValue);
2203 }
2204 }
2205
josh minorba424d22019-11-13 10:55:17 -06002206 desc = SliceDescriptor(begin, size);
2207
James Ward58dec6b2020-09-11 17:32:44 +01002208 auto layerName = fmt::format("Slice:{}:{}", subgraphIndex, operatorIndex);
josh minorba424d22019-11-13 10:55:17 -06002209
James Conroy05102392020-06-24 15:39:55 +01002210 IConnectableLayer* const layer = m_Network->AddSliceLayer(desc, layerName.c_str());
Mike Kelly377fb212023-01-10 15:55:28 +00002211
2212 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
2213 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
josh minorba424d22019-11-13 10:55:17 -06002214 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2215
2216 // register the input connection slots for the layer, connections are made after all layers have been created
2217 // only the tensors for the inputs are relevant, exclude the const tensors
2218 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2219 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2220
2221 // register the output connection slots for the layer, connections are made after all layers have been created
2222 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2223 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2224}
2225
Kevin May7d96b162021-02-03 17:38:41 +00002226void TfLiteParserImpl::ParseSoftmax(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01002227{
2228 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00002229 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2230 const auto* options = operatorPtr->builtin_options.AsSoftmaxOptions();
telsoa01c577f2c2018-08-31 09:22:23 +01002231
2232 SoftmaxDescriptor desc;
2233 desc.m_Beta = options->beta;
2234
2235 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2236 CHECK_VALID_SIZE(inputs.size(), 1);
2237 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2238 CHECK_VALID_SIZE(outputs.size(), 1);
2239
James Ward58dec6b2020-09-11 17:32:44 +01002240 auto layerName = fmt::format("Softmax:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01002241 IConnectableLayer* const layer = m_Network->AddSoftmaxLayer(desc, layerName.c_str());
2242
Mike Kelly377fb212023-01-10 15:55:28 +00002243 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
telsoa01c577f2c2018-08-31 09:22:23 +01002244 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2245
2246 // register the input connection slots for the layer, connections are made after all layers have been created
2247 // only the tensors for the inputs are relevant, exclude the const tensors
2248 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2249 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2250
2251 // register the output connection slots for the layer, connections are made after all layers have been created
2252 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2253 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2254}
2255
Teresa Charlinfd33a692022-06-29 15:35:57 +01002256void TfLiteParserImpl::ParseLogSoftmax(size_t subgraphIndex, size_t operatorIndex)
2257{
2258 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2259
2260 LogSoftmaxDescriptor desc;
2261
2262 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2263 CHECK_VALID_SIZE(inputs.size(), 1);
2264 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2265 CHECK_VALID_SIZE(outputs.size(), 1);
2266
2267 auto layerName = fmt::format("LogSoftmax:{}:{}", subgraphIndex, operatorIndex);
2268 IConnectableLayer* const layer = m_Network->AddLogSoftmaxLayer(desc, layerName.c_str());
2269
Mike Kelly377fb212023-01-10 15:55:28 +00002270 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Teresa Charlinfd33a692022-06-29 15:35:57 +01002271 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2272
2273 // register the input connection slots for the layer, connections are made after all layers have been created
2274 // only the tensors for the inputs are relevant, exclude the const tensors
2275 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2276 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2277
2278 // register the output connection slots for the layer, connections are made after all layers have been created
2279 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2280 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2281}
2282
Teresa Charlince7f51f2024-03-05 15:33:10 +00002283void TfLiteParserImpl::ParseScatterNd(size_t subgraphIndex, size_t operatorIndex)
2284{
2285 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2286
2287 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2288 CHECK_VALID_SIZE(inputs.size(), 3);
2289 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2290 CHECK_VALID_SIZE(outputs.size(), 1);
2291
2292 armnn::TensorInfo indicesTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2293 armnn::TensorInfo updatesTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
2294 armnn::TensorInfo shapeTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
2295 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
2296
2297 // TFLite currently only have these options: update and no input given, just shape.
2298 armnn::ScatterNdDescriptor descriptor(armnn::ScatterNdFunction::Update, false);
2299
2300 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2301 const auto* options = operatorPtr->builtin_options.AsScatterNdOptions();
2302 IgnoreUnused(options);
2303
2304 auto layerName = fmt::format("ScatterND:{}:{}", subgraphIndex, operatorIndex);
2305
2306 IConnectableLayer* layer = m_Network->AddScatterNdLayer(descriptor, layerName.c_str());
2307
2308 if (!layer)
2309 {
2310 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2311 operatorIndex, CHECK_LOCATION().AsString()));
2312 }
2313
2314 outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1, 2});
2315 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2316
2317 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2318 RegisterInputSlots(subgraphIndex,
2319 operatorIndex,
2320 layer,
2321 {inputTensorIndexes[2], inputTensorIndexes[0], inputTensorIndexes[1]});
2322
2323 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2324 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2325}
2326
Kevin May7d96b162021-02-03 17:38:41 +00002327void TfLiteParserImpl::ParseSpaceToBatchND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbaded142019-02-08 19:02:48 -02002328{
2329 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2330
2331 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2332 CHECK_VALID_SIZE(inputs.size(), 3);
2333
2334 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2335 CHECK_VALID_SIZE(outputs.size(), 1);
2336
Mike Kelly377fb212023-01-10 15:55:28 +00002337 armnn::TensorInfo blockShapeTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02002338 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2339
Mike Kelly377fb212023-01-10 15:55:28 +00002340 armnn::TensorInfo padListTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02002341 BufferRawPtr padListBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
2342
2343 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
2344 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
2345
2346 std::vector<unsigned int> padListVector(padListTensorInfo.GetNumElements());
2347 ::memcpy(padListVector.data(), padListBufferPtr->data.data(), padListTensorInfo.GetNumBytes());
2348
2349 size_t step = 2;
2350 std::vector<std::pair<unsigned int, unsigned int>> padList;
2351 for (unsigned int i = 0; i < padListTensorInfo.GetNumElements() / step; ++i)
2352 {
2353 padList.emplace_back(padListVector[i * step], padListVector[i * step + 1]);
2354 }
2355
2356 armnn::SpaceToBatchNdDescriptor desc;
2357 desc.m_BlockShape = blockShape;
2358 desc.m_PadList = padList;
2359 desc.m_DataLayout = armnn::DataLayout::NHWC;
2360
James Ward58dec6b2020-09-11 17:32:44 +01002361 auto layerName = fmt::format("SpaceToBatchND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02002362
Mike Kelly377fb212023-01-10 15:55:28 +00002363 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
James Conroy05102392020-06-24 15:39:55 +01002364
2365 IConnectableLayer* layer = m_Network->AddSpaceToBatchNdLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002366
2367 if (!layer)
2368 {
2369 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2370 operatorIndex, CHECK_LOCATION().AsString()));
2371 }
Mike Kelly377fb212023-01-10 15:55:28 +00002372
2373 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
2374 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Bruno Goncalvesbaded142019-02-08 19:02:48 -02002375 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2376
2377 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2378 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2379
2380 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2381 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2382}
2383
Teresa Charlin2a764ad2023-02-24 18:17:31 +00002384void TfLiteParserImpl::ParseSpaceToDepth(size_t subgraphIndex, size_t operatorIndex)
2385{
2386 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2387
2388 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2389 CHECK_VALID_SIZE(inputs.size(), 1);
2390 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2391 CHECK_VALID_SIZE(outputs.size(), 1);
2392
2393 armnn::SpaceToDepthDescriptor descriptor;
2394
2395 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2396 const auto* options = operatorPtr->builtin_options.AsSpaceToDepthOptions();
2397 auto blockSize = options->block_size;
2398 if (blockSize < 2)
2399 {
2400 throw ParseException(
2401 fmt::format("Operation has invalid block size: {} Block size should be >= 2 {}",
2402 blockSize,
2403 CHECK_LOCATION().AsString()));
2404 }
2405 descriptor.m_BlockSize = armnn::numeric_cast<uint32_t>(blockSize);
2406
2407 auto layerName = fmt::format("SpaceToDepth:{}:{}", subgraphIndex, operatorIndex);
2408 IConnectableLayer* layer = m_Network->AddSpaceToDepthLayer(descriptor, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002409
2410 if (!layer)
2411 {
2412 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2413 operatorIndex, CHECK_LOCATION().AsString()));
2414 }
2415
Teresa Charlin2a764ad2023-02-24 18:17:31 +00002416 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
2417 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2418
2419 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2420 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2421
2422 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2423 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2424}
2425
Teresa Charlin3ab85482021-06-08 16:59:29 +01002426armnn::TensorInfo TfLiteParserImpl::OutputShapeOfSqueeze(std::vector<uint32_t> squeezeDims,
Mike Kelly0d77ae12022-01-07 17:42:27 +00002427 const armnn::TensorInfo& inputTensorInfo)
telsoa01c577f2c2018-08-31 09:22:23 +01002428{
Teresa Charlin3ab85482021-06-08 16:59:29 +01002429 CHECK_VALID_SIZE(squeezeDims.size(), 0, 1, 2, 3, 4);
telsoa01c577f2c2018-08-31 09:22:23 +01002430 static const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
2431
2432 if (inputTensorInfo.GetNumDimensions() > 4)
2433 {
2434 std::stringstream ss;
2435 ss << "Input tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
2436 << " shape:" << inputTensorInfo.GetShape() << " "
2437 << CHECK_LOCATION().AsString();
2438 throw ParseException(ss.str());
2439 }
2440
2441 if (squeezeDims.empty())
2442 {
2443 squeezeDims.assign(dimensionSequence,
2444 dimensionSequence+inputTensorInfo.GetNumDimensions());
2445 }
2446
2447 std::vector<uint32_t> outputDims;
2448 for(unsigned int i = 0; i < inputTensorInfo.GetNumDimensions(); i++)
2449 {
2450 bool skipSqueeze = (std::find(squeezeDims.begin(), squeezeDims.end(), i) == squeezeDims.end());
2451 auto currentDimension = inputTensorInfo.GetShape()[i];
2452 if (skipSqueeze || currentDimension != 1)
2453 {
2454 outputDims.push_back(currentDimension);
2455 }
2456 }
2457
2458 if (outputDims.size() > 4)
2459 {
2460 std::stringstream ss;
2461 ss << "Output tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
2462 << " shape:" << inputTensorInfo.GetShape() << " "
2463 << CHECK_LOCATION().AsString();
2464 throw ParseException(ss.str());
2465 }
2466
2467 TensorShape outShape = TensorShape(static_cast<unsigned int>(outputDims.size()),
2468 outputDims.data());
2469
2470 // we need to preserve the tensor type and the quantization data as well
2471 TensorInfo outTensorInfo = inputTensorInfo;
2472 outTensorInfo.SetShape(outShape);
2473
2474 return outTensorInfo;
2475}
2476
Keith Davis0176fd82021-06-01 17:36:32 +01002477void TfLiteParserImpl::ParseShape(size_t subgraphIndex, size_t operatorIndex)
2478{
2479 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2480
2481 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2482 CHECK_VALID_SIZE(inputs.size(), 1);
2483 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2484 CHECK_VALID_SIZE(outputs.size(), 1);
2485
2486 auto layerName = fmt::format("Shape:{}:{}", subgraphIndex, operatorIndex);
2487
2488 IConnectableLayer* layer = m_Network->AddShapeLayer(layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002489
2490 if (!layer)
2491 {
2492 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2493 operatorIndex, CHECK_LOCATION().AsString()));
2494 }
Keith Davis0176fd82021-06-01 17:36:32 +01002495
Mike Kelly377fb212023-01-10 15:55:28 +00002496 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Keith Davis0176fd82021-06-01 17:36:32 +01002497 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2498
2499 // Check if output tensor type is Signed32 or Signed64
2500 if (outputTensorInfo.GetDataType() != armnn::DataType::Signed32 &&
2501 outputTensorInfo.GetDataType() != armnn::DataType::Signed64)
2502 {
2503 throw ParseException(
2504 fmt::format(
2505 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
2506 CHECK_LOCATION().AsString()));
2507 }
2508
2509 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2510 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2511
2512 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2513 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2514}
2515
Kevin May7d96b162021-02-03 17:38:41 +00002516void TfLiteParserImpl::ParseSqueeze(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01002517{
2518 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2519
2520 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2521 CHECK_VALID_SIZE(inputs.size(), 1);
2522
2523 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2524 CHECK_VALID_SIZE(outputs.size(), 1);
2525
2526 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2527 const auto * options = operatorPtr->builtin_options.AsSqueezeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01002528 auto layerName = fmt::format("Squeeze:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01002529
Mike Kelly377fb212023-01-10 15:55:28 +00002530 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Teresa Charlin3ab85482021-06-08 16:59:29 +01002531
2532 std::vector<uint32_t> squeezeDim;
2533 // A single negative dim index is interpreted as a negative index in python
2534 // Meaning the index will be the shape size plus the negative index value
2535 if (options->squeeze_dims.size() == 1 && options->squeeze_dims[0] < 0)
2536 {
2537 int32_t dim = static_cast<int32_t>(inputTensorInfo.GetShape().GetNumDimensions()) + options->squeeze_dims[0];
2538 squeezeDim.push_back(static_cast<uint32_t>(dim));
2539 }
2540 else
2541 {
2542 squeezeDim = AsUnsignedVector(options->squeeze_dims);
2543 }
2544
2545 armnn::TensorInfo outputTensorInfo = TfLiteParserImpl::OutputShapeOfSqueeze(squeezeDim, inputTensorInfo);
2546
James Conroy05102392020-06-24 15:39:55 +01002547 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
telsoa01c577f2c2018-08-31 09:22:23 +01002548
2549 ReshapeDescriptor reshapeDesc;
2550 reshapeDesc.m_TargetShape = outputTensorInfo.GetShape();
2551
Mike Kellyb2293702023-02-14 17:16:12 +00002552 auto outputTensorIds = GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex);
2553 m_TensorInfos[outputTensorIds[0]] = outputTensorInfo;
2554
telsoa01c577f2c2018-08-31 09:22:23 +01002555 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002556
2557 if (!layer)
2558 {
2559 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2560 operatorIndex, CHECK_LOCATION().AsString()));
2561 }
2562
telsoa01c577f2c2018-08-31 09:22:23 +01002563 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2564
2565 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2566 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2567
2568 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2569 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2570}
2571
Kevin May7d96b162021-02-03 17:38:41 +00002572void TfLiteParserImpl::ParseStridedSlice(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002573{
2574 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2575
2576 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2577 CHECK_VALID_SIZE(inputs.size(), 4);
2578
2579 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2580 CHECK_VALID_SIZE(outputs.size(), 1);
2581
Mike Kelly0d77ae12022-01-07 17:42:27 +00002582 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2583 const auto* options = operatorPtr->builtin_options.AsStridedSliceOptions();
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002584
2585 StridedSliceDescriptor desc;
2586 desc.m_BeginMask = options->begin_mask;
2587 desc.m_EllipsisMask = options->ellipsis_mask;
2588 desc.m_EndMask = options->end_mask;
2589 desc.m_NewAxisMask = options->new_axis_mask;
2590 desc.m_ShrinkAxisMask = options->shrink_axis_mask;
2591 desc.m_DataLayout = armnn::DataLayout::NHWC;
2592
Mike Kelly377fb212023-01-10 15:55:28 +00002593 armnn::TensorInfo beginTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002594 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2595
2596 std::vector<int> begin(beginTensorInfo.GetNumElements());
David Monahan39085f72023-07-28 11:37:29 +01002597 if (beginBufferPtr->data.data() != nullptr)
2598 {
2599 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
2600 }
2601 else
2602 {
2603 throw ParseException("ParseStridedSlice: Invalid input - the begin vector is null");
2604 }
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002605
Mike Kelly377fb212023-01-10 15:55:28 +00002606 armnn::TensorInfo endTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002607 BufferRawPtr endBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
2608
2609 std::vector<int> end(endTensorInfo.GetNumElements());
David Monahan39085f72023-07-28 11:37:29 +01002610 if (endBufferPtr->data.data() != nullptr)
2611 {
2612 ::memcpy(end.data(), endBufferPtr->data.data(), endTensorInfo.GetNumBytes());
2613 }
2614 else
2615 {
2616 throw ParseException("ParseStridedSlice: Invalid input - the end vector is null");
2617 }
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002618
Mike Kelly377fb212023-01-10 15:55:28 +00002619 armnn::TensorInfo strideTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 3);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002620 BufferRawPtr strideBufferPtr = GetBuffer(m_Model, inputs[3]->buffer);
2621
2622 std::vector<int> stride(strideTensorInfo.GetNumElements());
David Monahan39085f72023-07-28 11:37:29 +01002623
2624 if (strideBufferPtr->data.data() != nullptr)
2625 {
2626 ::memcpy(stride.data(), strideBufferPtr->data.data(), strideTensorInfo.GetNumBytes());
2627 }
2628 else
2629 {
2630 throw ParseException("ParseStridedSlice: Invalid input - the stride vector is null");
2631 }
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002632
2633 desc.m_Begin = begin;
2634 desc.m_End = end;
2635 desc.m_Stride = stride;
2636
James Ward58dec6b2020-09-11 17:32:44 +01002637 auto layerName = fmt::format("StridedSlice:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002638 IConnectableLayer* layer = m_Network->AddStridedSliceLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002639
2640 if (!layer)
2641 {
2642 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2643 operatorIndex, CHECK_LOCATION().AsString()));
2644 }
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002645
Mike Kelly377fb212023-01-10 15:55:28 +00002646 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002647 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2648
2649 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2650 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2651
2652 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2653 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2654}
2655
Kevin May7d96b162021-02-03 17:38:41 +00002656void TfLiteParserImpl::ParseSub(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002657{
2658 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2659
Mike Kelly0d77ae12022-01-07 17:42:27 +00002660 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2661 const auto* options = operatorPtr->builtin_options.AsSubOptions();
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002662
2663 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2664 CHECK_VALID_SIZE(inputs.size(), 2);
2665
2666 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2667 CHECK_VALID_SIZE(outputs.size(), 1);
2668
Mike Kelly377fb212023-01-10 15:55:28 +00002669 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2670 armnn::TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002671
James Ward58dec6b2020-09-11 17:32:44 +01002672 auto layerName = fmt::format("Sub:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly3ec30772023-03-08 13:47:17 +00002673 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::Sub, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002674
2675 if (!layer)
2676 {
2677 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2678 operatorIndex, CHECK_LOCATION().AsString()));
2679 }
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002680
Mike Kelly377fb212023-01-10 15:55:28 +00002681 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002682 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2683
2684 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002685 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Teresa Charlind04873f2023-05-23 14:16:28 +01002686 if (options)
2687 {
2688 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2689 }
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002690
2691 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2692 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2693}
2694
Kevin May7d96b162021-02-03 17:38:41 +00002695void TfLiteParserImpl::ParseDiv(size_t subgraphIndex, size_t operatorIndex)
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302696{
2697 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2698
Mike Kelly0d77ae12022-01-07 17:42:27 +00002699 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2700 const auto* options = operatorPtr->builtin_options.AsDivOptions();
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302701
2702 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2703 CHECK_VALID_SIZE(inputs.size(), 2);
2704
2705 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2706 CHECK_VALID_SIZE(outputs.size(), 1);
2707
Mike Kelly377fb212023-01-10 15:55:28 +00002708 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2709 armnn::TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302710
James Ward58dec6b2020-09-11 17:32:44 +01002711 auto layerName = fmt::format("Div:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly3ec30772023-03-08 13:47:17 +00002712 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::Div, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002713
2714 if (!layer)
2715 {
2716 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2717 operatorIndex, CHECK_LOCATION().AsString()));
2718 }
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302719
Mike Kelly377fb212023-01-10 15:55:28 +00002720 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302721 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2722
2723 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002724 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Teresa Charlind04873f2023-05-23 14:16:28 +01002725 if (options)
2726 {
2727 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2728 }
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302729
2730 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2731 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2732}
2733
Teresa Charlincdbd40b2022-02-25 13:21:55 +00002734void TfLiteParserImpl::ParseFloorDiv(size_t subgraphIndex, size_t operatorIndex)
2735{
2736 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2737
2738 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2739 CHECK_VALID_SIZE(inputs.size(), 2);
2740
2741 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2742 CHECK_VALID_SIZE(outputs.size(), 1);
2743
Mike Kelly377fb212023-01-10 15:55:28 +00002744 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2745 armnn::TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Teresa Charlincdbd40b2022-02-25 13:21:55 +00002746
2747 auto layerName = fmt::format("Div:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly3ec30772023-03-08 13:47:17 +00002748 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::Div, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002749
2750 if (!layer)
2751 {
2752 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2753 operatorIndex, CHECK_LOCATION().AsString()));
2754 }
Teresa Charlincdbd40b2022-02-25 13:21:55 +00002755
Mike Kelly377fb212023-01-10 15:55:28 +00002756 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Teresa Charlincdbd40b2022-02-25 13:21:55 +00002757 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2758
2759 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2760 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2761 layer = AddFusedFloorLayer(layer, 0);
2762
2763 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2764 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2765}
2766
Kevin May7d96b162021-02-03 17:38:41 +00002767void TfLiteParserImpl::ParseAdd(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002768{
2769 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2770
Mike Kelly0d77ae12022-01-07 17:42:27 +00002771 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2772 const auto* options = operatorPtr->builtin_options.AsAddOptions();
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002773
2774 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2775 CHECK_VALID_SIZE(inputs.size(), 2);
2776
2777 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2778 CHECK_VALID_SIZE(outputs.size(), 1);
2779
Mike Kelly377fb212023-01-10 15:55:28 +00002780 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2781 armnn::TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalves9c761a62018-12-27 14:20:35 -02002782
James Ward58dec6b2020-09-11 17:32:44 +01002783 auto layerName = fmt::format("Add:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly3ec30772023-03-08 13:47:17 +00002784 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::Add, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002785
2786 if (!layer)
2787 {
2788 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2789 operatorIndex, CHECK_LOCATION().AsString()));
2790 }
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002791
Mike Kelly377fb212023-01-10 15:55:28 +00002792 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002793 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2794
2795 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002796 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Teresa Charlind04873f2023-05-23 14:16:28 +01002797 if (options)
2798 {
2799 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2800 }
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002801
2802 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2803 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2804}
2805
Kevin May7d96b162021-02-03 17:38:41 +00002806void TfLiteParserImpl::ParseMul(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002807{
2808 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2809
Mike Kelly0d77ae12022-01-07 17:42:27 +00002810 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2811 const auto* options = operatorPtr->builtin_options.AsMulOptions();
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002812
2813 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2814 CHECK_VALID_SIZE(inputs.size(), 2);
2815
2816 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2817 CHECK_VALID_SIZE(outputs.size(), 1);
2818
Mike Kelly377fb212023-01-10 15:55:28 +00002819 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2820 armnn::TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalves9c761a62018-12-27 14:20:35 -02002821
James Ward58dec6b2020-09-11 17:32:44 +01002822 auto layerName = fmt::format("Mul:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly3ec30772023-03-08 13:47:17 +00002823 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::Mul, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002824
2825 if (!layer)
2826 {
2827 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2828 operatorIndex, CHECK_LOCATION().AsString()));
2829 }
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002830
Mike Kelly377fb212023-01-10 15:55:28 +00002831 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002832 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2833
2834 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002835 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Teresa Charlind04873f2023-05-23 14:16:28 +01002836 if (options)
2837 {
2838 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2839 }
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002840
2841 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2842 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2843}
2844
Kevin May7d96b162021-02-03 17:38:41 +00002845void TfLiteParserImpl::ParseMean(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002846{
2847 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2848
2849 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2850
2851 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2852 CHECK_VALID_SIZE(outputs.size(), 1);
2853
Teresa Charlin046e2cb2023-03-28 17:20:19 +01002854 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2855 TensorInfo dimTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002856
2857 armnn::MeanDescriptor desc;
Teresa Charlin046e2cb2023-03-28 17:20:19 +01002858 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2859 // Get const axis value from model and set it to descriptor.
2860 if (axisBufferPtr != nullptr)
2861 {
2862 std::vector<int32_t> axisData(dimTensorInfo.GetNumElements());
2863 ::memcpy(axisData.data(), axisBufferPtr->data.data(), dimTensorInfo.GetNumBytes());
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002864
Teresa Charlin046e2cb2023-03-28 17:20:19 +01002865 // Convert the axis to unsigned int and remove duplicates.
2866 auto rank = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
2867 std::set<unsigned int> uniqueAxis;
2868 std::transform(axisData.begin(),
2869 axisData.end(),
2870 std::inserter(uniqueAxis, uniqueAxis.begin()),
2871 [rank](int i)->unsigned int{
2872 return static_cast<uint32_t>(((i + rank) % rank)); });
2873 desc.m_Axis.assign(uniqueAxis.begin(), uniqueAxis.end());
2874 }
2875 else
2876 {
2877 for (uint32_t i = 0; i < inputTensorInfo.GetNumDimensions(); ++i)
2878 {
2879 desc.m_Axis.push_back(i);
2880 }
2881 }
2882
Sadik Armagand109a4d2020-07-28 10:42:13 +01002883 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002884
Teresa Charlin046e2cb2023-03-28 17:20:19 +01002885 desc.m_KeepDims = inputTensorInfo.GetNumDimensions() == outputTensorInfo.GetNumDimensions() ? true : false;
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002886
James Ward58dec6b2020-09-11 17:32:44 +01002887 auto layerName = fmt::format("Mean:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002888 IConnectableLayer* layer = m_Network->AddMeanLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002889
2890 if (!layer)
2891 {
2892 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2893 operatorIndex, CHECK_LOCATION().AsString()));
2894 }
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002895
Mike Kelly377fb212023-01-10 15:55:28 +00002896 outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002897 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2898
2899 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2900 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2901
2902 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2903 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2904}
2905
Kevin May7d96b162021-02-03 17:38:41 +00002906void TfLiteParserImpl::ParsePad(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002907{
2908 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2909
Kevin May7d96b162021-02-03 17:38:41 +00002910 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002911
Kevin May7d96b162021-02-03 17:38:41 +00002912 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002913 CHECK_VALID_SIZE(outputs.size(), 1);
2914
Mike Kelly377fb212023-01-10 15:55:28 +00002915 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
2916 armnn::TensorInfo padTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002917
Mike Kelly0d77ae12022-01-07 17:42:27 +00002918 std::vector<unsigned int> padBuffer = GetUIntBuffer(padTensorInfo, m_Model, inputs[1]->buffer);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002919
2920 size_t step = 2;
2921 armnn::PadDescriptor desc;
Mike Kelly0d77ae12022-01-07 17:42:27 +00002922 auto opcode = GetOpCode(m_Model, subgraphIndex, operatorIndex);
2923
2924 if (opcode == tflite::BuiltinOperator_PAD)
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00002925 {
Mike Kelly0d77ae12022-01-07 17:42:27 +00002926 CHECK_VALID_SIZE(inputs.size(), 2);
2927
2928 if (inputTensorInfo.IsQuantized())
2929 {
2930 desc.m_PadValue = static_cast<float>(inputTensorInfo.GetQuantizationOffset());
2931 }
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00002932 }
Mike Kelly0d77ae12022-01-07 17:42:27 +00002933 else if (opcode == tflite::BuiltinOperator_PADV2)
2934 {
2935 CHECK_VALID_SIZE(inputs.size(), 3);
2936
Mike Kelly377fb212023-01-10 15:55:28 +00002937 armnn::TensorInfo padValueTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
Mike Kelly0d77ae12022-01-07 17:42:27 +00002938
2939 if (padValueTensorInfo.GetNumElements() != 1)
2940 {
2941 ARMNN_THROW_PARSE_EXCEPTION("Multiple padding values are not supported in PADV2");
2942 }
2943 BufferRawPtr padValueBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
2944
2945 // Get the pad value from the input tensor
2946 if (padValueBufferPtr->data.size() > 0)
2947 {
2948 switch (padValueTensorInfo.GetDataType())
2949 {
2950 case armnn::DataType::Float32:
2951 {
2952 std::vector<float> padValueBuffer(padValueTensorInfo.GetNumElements());
2953 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2954 desc.m_PadValue = padValueBuffer[0];
2955 break;
2956 }
2957 case armnn::DataType::QAsymmU8:
2958 {
2959 std::vector<uint8_t> padValueBuffer(padValueTensorInfo.GetNumElements());
2960 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2961 desc.m_PadValue = armnn::Dequantize<uint8_t>(padValueBuffer[0],
2962 padValueTensorInfo.GetQuantizationScale(),
2963 padValueTensorInfo.GetQuantizationOffset());
2964 break;
2965 }
2966 case armnn::DataType::QAsymmS8:
2967 case armnn::DataType::QSymmS8:
2968 {
2969 std::vector<int8_t> padValueBuffer(padValueTensorInfo.GetNumElements());
2970 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2971 desc.m_PadValue = armnn::Dequantize<int8_t>(padValueBuffer[0],
2972 padValueTensorInfo.GetQuantizationScale(),
2973 padValueTensorInfo.GetQuantizationOffset());
2974 break;
2975 }
2976 default: ARMNN_THROW_PARSE_EXCEPTION("Unsupported DataType");
2977 }
2978 }
2979 else if (inputTensorInfo.IsQuantized())
2980 {
2981 desc.m_PadValue = static_cast<float>(inputTensorInfo.GetQuantizationOffset());
2982 }
2983 }
2984
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002985 for (unsigned int i = 0; i < padTensorInfo.GetNumElements() / step; ++i)
2986 {
2987 desc.m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
2988 }
2989
Mike Kelly0d77ae12022-01-07 17:42:27 +00002990 auto layerName = (opcode == tflite::BuiltinOperator_PAD) ? fmt::format("Pad:{}:{}", subgraphIndex, operatorIndex)
2991 : fmt::format("PadV2:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01002992
2993 IConnectableLayer* layer = m_Network->AddPadLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01002994
2995 if (!layer)
2996 {
2997 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
2998 operatorIndex, CHECK_LOCATION().AsString()));
2999 }
3000
Mike Kelly377fb212023-01-10 15:55:28 +00003001 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02003002 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3003
3004 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3005 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3006
3007 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3008 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3009}
3010
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +01003011void TfLiteParserImpl::ParseMirrorPad(size_t subgraphIndex, size_t operatorIndex)
3012{
3013 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3014
3015 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3016 CHECK_VALID_SIZE(inputs.size(), 2);
3017
3018 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3019 CHECK_VALID_SIZE(outputs.size(), 1);
3020
Mike Kelly377fb212023-01-10 15:55:28 +00003021 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +01003022
Mike Kelly377fb212023-01-10 15:55:28 +00003023 armnn::TensorInfo padTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +01003024 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
3025
3026 std::vector<unsigned int> padBuffer(padTensorInfo.GetNumElements());
3027 ::memcpy(padBuffer.data(), bufferPtr->data.data(), padTensorInfo.GetNumBytes());
3028
3029 size_t step = 2;
3030 armnn::PadDescriptor desc;
3031 for (unsigned int i = 0; i < padTensorInfo.GetNumElements() / step; ++i)
3032 {
3033 desc.m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
3034 }
3035
3036 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3037 const auto* options = operatorPtr->builtin_options.AsMirrorPadOptions();
3038
3039 if (options->mode == tflite::MirrorPadMode_REFLECT)
3040 {
3041 desc.m_PaddingMode = PaddingMode::Reflect;
3042 }
3043 else if (options->mode == tflite::MirrorPadMode_SYMMETRIC)
3044 {
3045 desc.m_PaddingMode = PaddingMode::Symmetric;
3046 }
3047 else
3048 {
3049 ARMNN_THROW_PARSE_EXCEPTION("PaddingMode must be either REFLECT or SYMMETRIC");
3050 }
3051
3052 // If padding mode is Reflect then both paddings must be no greater than inputShape(i) - 1.
3053 // If padding mode is Symmetric then both paddings must be no greater than inputShape(i).
3054 auto inputShape = inputTensorInfo.GetShape();
3055 auto padList = desc.m_PadList;
3056
3057 const unsigned int isReflect = static_cast<unsigned int>(desc.m_PaddingMode == PaddingMode::Reflect);
3058 for(unsigned int i = 0; i < padList.size(); ++i)
3059 {
3060 if(padList.at(i).first > (inputShape[i] - isReflect) ||
3061 padList.at(i).second > (inputShape[i] - isReflect))
3062 {
3063 ARMNN_THROW_PARSE_EXCEPTION("Padding values must be less (Reflect) or "
3064 "equal (Symmetric) to the dimension size.");
3065 }
3066 }
3067
3068 auto layerName = fmt::format("MirrorPad:{}:{}", subgraphIndex, operatorIndex);
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +01003069
3070 IConnectableLayer* layer = m_Network->AddPadLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01003071
3072 if (!layer)
3073 {
3074 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3075 operatorIndex, CHECK_LOCATION().AsString()));
3076 }
3077
Mike Kelly377fb212023-01-10 15:55:28 +00003078 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +01003079 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3080
3081 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3082 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3083
3084 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3085 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3086}
3087
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01003088void TfLiteParserImpl::ParsePrelu(size_t subgraphIndex, size_t operatorIndex)
3089{
3090 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3091
3092 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3093 CHECK_VALID_SIZE(inputs.size(), 2);
3094
3095 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3096 CHECK_VALID_SIZE(outputs.size(), 1);
3097
3098 auto layerName = fmt::format("Prelu:{}:{}", subgraphIndex, operatorIndex);
3099
Mike Kelly377fb212023-01-10 15:55:28 +00003100 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
3101 armnn::TensorInfo alphaTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01003102
3103 IConnectableLayer* layer = m_Network->AddPreluLayer(layerName.c_str());
Mike Kelly377fb212023-01-10 15:55:28 +00003104
Ryan OSheac229b3f2023-06-27 22:34:54 +01003105 if (!layer)
3106 {
3107 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3108 operatorIndex, CHECK_LOCATION().AsString()));
3109 }
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01003110
3111 if (IsConstTensor(inputs[1]))
3112 {
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01003113 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawaratbf99b5f2021-05-27 09:55:43 +01003114 armnn::IInputSlot* slot = &(layer->GetInputSlot(0));
3115 RegisterConsumerOfTensor(subgraphIndex, inputTensorIndexes[0], slot);
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01003116
Mike Kelly5880b912022-01-28 16:18:54 +00003117 auto alphaTensorAndData = CreateConstTensorNonPermuted(inputs[1], alphaTensorInfo,
3118 inputTensorInfo.GetDataType());
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01003119 std::string constLayerName = fmt::format("Constant:{}", inputs[1]->name);
3120 IConnectableLayer* constLayer =
Mike Kelly5880b912022-01-28 16:18:54 +00003121 m_Network->AddConstantLayer(alphaTensorAndData.first, constLayerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01003122
3123 if (!constLayer)
3124 {
3125 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3126 operatorIndex, CHECK_LOCATION().AsString()));
3127 }
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01003128
3129 constLayer->GetOutputSlot(0).SetTensorInfo(alphaTensorInfo);
3130 constLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(1));
3131 RegisterOutputSlots(subgraphIndex,
3132 VIRTUAL_OPERATOR_ID,
3133 constLayer,
3134 { inputTensorIndexes[1] });
3135 }
3136 else
3137 {
3138 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3139 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIndexes);
3140 }
3141
Mike Kelly377fb212023-01-10 15:55:28 +00003142 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Mike Kelly377fb212023-01-10 15:55:28 +00003143 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3144
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01003145 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3146 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3147}
3148
Kevin May7d96b162021-02-03 17:38:41 +00003149void TfLiteParserImpl::ParseQuantize(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan66dedc72019-12-10 16:32:07 +00003150{
3151 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3152
3153 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3154 CHECK_VALID_SIZE(inputs.size(), 1);
3155
3156 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3157 CHECK_VALID_SIZE(outputs.size(), 1);
3158
James Ward58dec6b2020-09-11 17:32:44 +01003159 auto layerName = fmt::format("Quantize:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan66dedc72019-12-10 16:32:07 +00003160
3161 IConnectableLayer* layer = m_Network->AddQuantizeLayer(layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01003162
3163 if (!layer)
3164 {
3165 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3166 operatorIndex, CHECK_LOCATION().AsString()));
3167 }
Sadik Armagan66dedc72019-12-10 16:32:07 +00003168
Mike Kelly377fb212023-01-10 15:55:28 +00003169 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Sadik Armagan66dedc72019-12-10 16:32:07 +00003170 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3171
3172 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3173 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3174
3175 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3176 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3177}
Finn Williamsc42c3842019-01-22 14:18:11 +00003178
Kevin May7d96b162021-02-03 17:38:41 +00003179void TfLiteParserImpl::ParseRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01003180{
Finn Williamsc42c3842019-01-22 14:18:11 +00003181 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::ReLu);
Sadik Armagan58f39192018-09-17 14:14:39 +01003182}
3183
Kevin May7d96b162021-02-03 17:38:41 +00003184void TfLiteParserImpl::ParseRelu6(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01003185{
Finn Williamsc42c3842019-01-22 14:18:11 +00003186 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::BoundedReLu);
3187}
Sadik Armagan58f39192018-09-17 14:14:39 +01003188
Kevin May7d96b162021-02-03 17:38:41 +00003189void TfLiteParserImpl::ParseLeakyRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan12239e72020-05-27 11:06:17 +01003190{
Jan Eilers2f746b32020-07-28 14:00:06 +01003191 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::LeakyReLu);
Sadik Armagan12239e72020-05-27 11:06:17 +01003192}
3193
Kevin May7d96b162021-02-03 17:38:41 +00003194void TfLiteParserImpl::ParseLogistic(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsc42c3842019-01-22 14:18:11 +00003195{
3196 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::Sigmoid);
3197}
3198
Kevin May7d96b162021-02-03 17:38:41 +00003199void TfLiteParserImpl::ParseTanH(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd99851762019-04-09 09:37:38 +01003200{
3201 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::TanH);
3202}
3203
Kevin May7d96b162021-02-03 17:38:41 +00003204void TfLiteParserImpl::ParseElu(size_t subgraphIndex, size_t operatorIndex)
Matthew Sloyan7515d072020-12-16 12:50:01 +00003205{
3206 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::Elu);
3207}
3208
Kevin May7d96b162021-02-03 17:38:41 +00003209void TfLiteParserImpl::ParseHardSwish(size_t subgraphIndex, size_t operatorIndex)
Jan Eilers2f746b32020-07-28 14:00:06 +01003210{
3211 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::HardSwish);
3212}
Finn Williamsc42c3842019-01-22 14:18:11 +00003213
Teresa Charlin077cddb2023-09-15 15:19:21 +01003214void TfLiteParserImpl::ParseGelu(size_t subgraphIndex, size_t operatorIndex)
3215{
3216 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::Gelu);
3217}
3218
Kevin May7d96b162021-02-03 17:38:41 +00003219void TfLiteParserImpl::ParseActivation(size_t subgraphIndex, size_t operatorIndex, ActivationFunction activationType)
Finn Williamsc42c3842019-01-22 14:18:11 +00003220{
3221 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00003222 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Jan Eilers8eb25602020-03-09 12:13:48 +00003223 IgnoreUnused(operatorPtr);
Sadik Armagan58f39192018-09-17 14:14:39 +01003224
3225 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3226 CHECK_VALID_SIZE(inputs.size(), 1);
3227
3228 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3229 CHECK_VALID_SIZE(outputs.size(), 1);
3230
James Ward58dec6b2020-09-11 17:32:44 +01003231 auto layerName = fmt::format("Activation:");
Sadik Armagan58f39192018-09-17 14:14:39 +01003232 ActivationDescriptor activationDesc;
Finn Williamsc42c3842019-01-22 14:18:11 +00003233 activationDesc.m_Function = activationType;
3234
3235 switch (activationType)
3236 {
3237 case ActivationFunction::ReLu:
3238 {
James Ward58dec6b2020-09-11 17:32:44 +01003239 layerName += fmt::format("RELU:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00003240 break;
3241 }
3242 case ActivationFunction::BoundedReLu:
3243 {
James Ward58dec6b2020-09-11 17:32:44 +01003244 layerName += fmt::format("RELU6:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00003245 activationDesc.m_A = 6.0f;
3246 activationDesc.m_B = 0.0f;
3247 break;
3248 }
3249 case ActivationFunction::Sigmoid:
3250 {
James Ward58dec6b2020-09-11 17:32:44 +01003251 layerName += fmt::format("SIGMOID:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00003252 break;
3253 }
Nina Drozd99851762019-04-09 09:37:38 +01003254 case ActivationFunction::TanH:
3255 {
James Ward58dec6b2020-09-11 17:32:44 +01003256 layerName += fmt::format("TANH:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd99851762019-04-09 09:37:38 +01003257 activationDesc.m_A = 1.0f;
3258 activationDesc.m_B = 1.0f;
3259 break;
3260 }
Sadik Armagan12239e72020-05-27 11:06:17 +01003261 case ActivationFunction::LeakyReLu:
3262 {
James Ward58dec6b2020-09-11 17:32:44 +01003263 layerName += fmt::format("LEAKYRELU:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00003264 const auto* options = operatorPtr->builtin_options.AsLeakyReluOptions();
Sadik Armagan12239e72020-05-27 11:06:17 +01003265 activationDesc.m_A = options->alpha;
3266 break;
3267 }
Matthew Sloyan7515d072020-12-16 12:50:01 +00003268 case ActivationFunction::Elu:
3269 {
3270 layerName += fmt::format("ELU:{}:{}", subgraphIndex, operatorIndex);
3271 activationDesc.m_A = 1.0f;
3272 break;
3273 }
Jan Eilers2f746b32020-07-28 14:00:06 +01003274 case ActivationFunction::HardSwish:
Matthew Sloyan7515d072020-12-16 12:50:01 +00003275 {
James Ward58dec6b2020-09-11 17:32:44 +01003276 layerName += fmt::format("HARDSWISH:{}:{}", subgraphIndex, operatorIndex);
Jan Eilers2f746b32020-07-28 14:00:06 +01003277 break;
Matthew Sloyan7515d072020-12-16 12:50:01 +00003278 }
Teresa Charlin077cddb2023-09-15 15:19:21 +01003279 case ActivationFunction::Gelu:
3280 {
3281 layerName += fmt::format("GELU:{}:{}", subgraphIndex, operatorIndex);
3282 break;
3283 }
Finn Williamsc42c3842019-01-22 14:18:11 +00003284 default:
3285 {
3286 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003287 fmt::format("Unexpected ActivationFunction[{}] when creating layerName {} ",
3288 static_cast<int>(activationType), CHECK_LOCATION().AsString()));
Finn Williamsc42c3842019-01-22 14:18:11 +00003289 }
3290 }
3291
3292 IConnectableLayer* const layer = m_Network->AddActivationLayer(activationDesc, layerName.c_str());
Sadik Armagan58f39192018-09-17 14:14:39 +01003293
Mike Kelly377fb212023-01-10 15:55:28 +00003294 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Sadik Armagan58f39192018-09-17 14:14:39 +01003295 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3296
3297 // register the input connection slots for the layer, connections are made after all layers have been created
3298 // only the tensors for the inputs are relevant, exclude the const tensors
3299 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3300 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3301
3302 // register the output connection slots for the layer, connections are made after all layers have been created
3303 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3304 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3305}
Tianle Cheng20773482023-10-03 12:01:11 +01003306
Mike Kelly0d77ae12022-01-07 17:42:27 +00003307armnn::TensorInfo TfLiteParserImpl::OutputShapeOfReshape(const armnn::TensorInfo& inputTensorInfo,
3308 const std::vector<int32_t>& targetDimsIn)
Sadikb94967b2018-09-19 15:30:00 +01003309{
3310 std::vector<unsigned int> outputDims(targetDimsIn.begin(), targetDimsIn.end());
3311 const auto stretchDim = std::find(targetDimsIn.begin(), targetDimsIn.end(), -1);
3312
3313 if (stretchDim != targetDimsIn.end())
3314 {
3315 if (std::find(std::next(stretchDim), targetDimsIn.end(), -1) != targetDimsIn.end())
3316 {
3317 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003318 fmt::format("At most one component of shape can be -1 {}", CHECK_LOCATION().AsString()));
Sadikb94967b2018-09-19 15:30:00 +01003319 }
3320
3321 auto targetNumElements =
Matthew Sloyan589e3e82020-09-11 16:17:48 +01003322 armnn::numeric_cast<unsigned int>(
Sadikb94967b2018-09-19 15:30:00 +01003323 std::accumulate(targetDimsIn.begin(), targetDimsIn.end(), -1, std::multiplies<int32_t>()));
3324
3325 auto stretchIndex = static_cast<size_t>(std::distance(targetDimsIn.begin(), stretchDim));
Tianle Cheng20773482023-10-03 12:01:11 +01003326
3327 if (targetNumElements == 0)
3328 {
3329 if (inputTensorInfo.GetNumElements() == 0)
3330 {
3331 outputDims[stretchIndex] = 0;
3332 }
3333 else
3334 {
3335 throw ParseException(
3336 fmt::format("Input to reshape is a tensor with elements, but the requested shape has 0. {}",
3337 CHECK_LOCATION().AsString()));
3338 }
3339 }
3340 else
3341 {
3342 outputDims[stretchIndex] = inputTensorInfo.GetNumElements() / targetNumElements;
3343 }
Sadikb94967b2018-09-19 15:30:00 +01003344 }
3345
3346 TensorShape outputShape = TensorShape(static_cast<unsigned int>(outputDims.size()), outputDims.data());
3347
3348 TensorInfo reshapeInfo = inputTensorInfo;
3349 reshapeInfo.SetShape(outputShape);
3350
3351 return reshapeInfo;
3352}
3353
Kevin May7d96b162021-02-03 17:38:41 +00003354void TfLiteParserImpl::ParseReshape(size_t subgraphIndex, size_t operatorIndex)
Sadikb94967b2018-09-19 15:30:00 +01003355{
3356 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3357
3358 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01003359
3360 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3361 CHECK_VALID_SIZE(outputs.size(), 1);
3362
Mike Kelly0d77ae12022-01-07 17:42:27 +00003363 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3364 const auto* options = operatorPtr->builtin_options.AsReshapeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01003365 auto layerName = fmt::format("Reshape:{}:{}", subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01003366
Mike Kelly377fb212023-01-10 15:55:28 +00003367 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
kevmay0171972a82018-12-17 14:28:03 +00003368 armnn::TensorInfo actualOutputTensorInfo = ToTensorInfo(outputs[0]);
James Conroy05102392020-06-24 15:39:55 +01003369 CheckMatchingQuantization(inputTensorInfo, actualOutputTensorInfo, layerName, "Input 0", "Output 0");
Derek Lambertic9e52792020-03-11 11:42:26 +00003370
Jan Eilersbac9b352020-07-13 13:40:24 +01003371 // Extracting new shape for the output
3372 // There are two ways it can be passed
3373 // * First is to define the target shape in the operator built-in options
3374 // * Second is to pass it as a second input tensor
Derek Lambertic9e52792020-03-11 11:42:26 +00003375 std::vector<int32_t> targetShape;
Jan Eilersbac9b352020-07-13 13:40:24 +01003376 bool targetShapeFound = false;
3377 // Check if built-in options were given
3378 if (options != nullptr)
Derek Lambertic9e52792020-03-11 11:42:26 +00003379 {
Jan Eilersbac9b352020-07-13 13:40:24 +01003380 // make sure the parameter is given
3381 if (options->new_shape.empty() == false)
Derek Lambertic9e52792020-03-11 11:42:26 +00003382 {
Jan Eilersbac9b352020-07-13 13:40:24 +01003383 targetShape = options->new_shape;
3384 targetShapeFound = true;
Derek Lambertif4a953f2020-03-17 14:25:57 +00003385 }
Derek Lambertic9e52792020-03-11 11:42:26 +00003386 }
Jan Eilersbac9b352020-07-13 13:40:24 +01003387
3388 // If there is no built-in option given or if the built-in new_shape parameter was empty
3389 if (!targetShapeFound)
Derek Lambertic9e52792020-03-11 11:42:26 +00003390 {
Teresa Charlin6a056a42021-12-01 10:25:43 +00003391 // Check for a second input tensor
3392 if (inputs.size() > 1 && inputs[1] != nullptr)
Jan Eilersbac9b352020-07-13 13:40:24 +01003393 {
3394 if (inputs[1]->is_variable)
3395 {
3396 ARMNN_THROW_PARSE_EXCEPTION( "Target shapes defined in non-const input tensors is not supported");
3397 }
3398
3399 if (inputs[1]->shape.size() != 1)
3400 {
3401 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not a 1D tensor");
3402 }
3403
3404 if (inputs[1]->type != tflite::TensorType_INT32)
3405 {
3406 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not an int32 type");
3407 }
3408
Teresa Charlin6a056a42021-12-01 10:25:43 +00003409 // Extract target shape from input
3410 auto bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
3411 auto values = reinterpret_cast<const int32_t*>(bufferPtr->data.data());
Cathal Corbettd2f73232021-12-10 13:38:52 +00003412 if (values)
Sadik Armagan19a1c032021-01-20 12:17:00 +00003413 {
Cathal Corbettd2f73232021-12-10 13:38:52 +00003414 for (int i = 0; i < inputs[1]->shape[0]; ++i)
3415 {
3416 targetShape.push_back(values[i]);
3417 }
Sadik Armagan19a1c032021-01-20 12:17:00 +00003418 }
Cathal Corbettd2f73232021-12-10 13:38:52 +00003419 else
Jan Eilersbac9b352020-07-13 13:40:24 +01003420 {
Cathal Corbettd2f73232021-12-10 13:38:52 +00003421 try
3422 {
3423 // We attempt to infer during Runtime.
Mike Kelly04d82292023-01-19 18:29:40 +00003424 TensorShape reshapeShapes = ToTensorInfo(inputs[1]).GetShape();
3425
3426 if (reshapeShapes[0] == actualOutputTensorInfo.GetNumDimensions())
3427 {
3428 for (unsigned int i = 0; i < actualOutputTensorInfo.GetShape().GetNumDimensions(); ++i)
3429 {
3430 targetShape.push_back(actualOutputTensorInfo.GetShape()[i]);
3431 }
3432 }
Cathal Corbettd2f73232021-12-10 13:38:52 +00003433 // The parser only supports shape (batch, -1) or (-1) for non-constant shape input.
Mike Kelly04d82292023-01-19 18:29:40 +00003434 else if (reshapeShapes[0] > 2)
Cathal Corbettd2f73232021-12-10 13:38:52 +00003435 {
3436 throw ParseException(fmt::format("Invalid input shape '{}' in Reshape layer '{}' {}. "
3437 "When inferring during runtime, the parser only supports "
3438 "shape (batch, -1) or (-1) for target shape input.",
3439 reshapeShapes[0],
3440 layerName,
3441 CHECK_LOCATION().AsString()));
3442 }
Mike Kelly04d82292023-01-19 18:29:40 +00003443 else
Cathal Corbettd2f73232021-12-10 13:38:52 +00003444 {
Mike Kelly04d82292023-01-19 18:29:40 +00003445 const int32_t numInputElements = inputTensorInfo.GetNumElements();
3446 const int32_t inputTensorShape = inputTensorInfo.GetShape()[0];
3447 if (reshapeShapes[0] == 1)
3448 {
3449 targetShape = {numInputElements};
3450 }
3451 else if (reshapeShapes[0] == 2)
3452 {
3453 targetShape = {inputTensorShape, numInputElements / inputTensorShape};
3454 }
Cathal Corbettd2f73232021-12-10 13:38:52 +00003455 }
3456 }
3457 catch (const std::exception& exc)
3458 {
3459 ARMNN_THROW_PARSE_EXCEPTION("Failed attempt to infer during runtime the target shape input for "
3460 "Reshape operation. Reshape operator target shape input buffer data "
3461 "is null. " << exc.what());
3462 }
Jan Eilersbac9b352020-07-13 13:40:24 +01003463 }
3464 }
3465 else
Derek Lambertic9e52792020-03-11 11:42:26 +00003466 {
3467 ARMNN_THROW_PARSE_EXCEPTION("Target shape not defined in reshape parameters or input tensor. "
3468 "At least one method required");
3469 }
Derek Lambertic9e52792020-03-11 11:42:26 +00003470 }
3471
kevmay0171972a82018-12-17 14:28:03 +00003472 armnn::TensorInfo reshapeOutputTensorInfo =
Kevin May7d96b162021-02-03 17:38:41 +00003473 TfLiteParserImpl::OutputShapeOfReshape(inputTensorInfo, targetShape);
Sadikb94967b2018-09-19 15:30:00 +01003474
kevmay0171972a82018-12-17 14:28:03 +00003475 // Check for valid input size and that reshape parameters equal output shape
Cathal Corbett2b922e22022-09-23 15:49:24 +01003476 // The output shape can be provided to us in 2 ways:
3477 // 1. through the normal 'shape' parameter given by outputs[indx]->shape
3478 // 2. through additional parameter 'shape_signature' given by outputs[indx]->buffer.
3479 // This parameter can sometimes contain -1 value not visible in the 'shape' parameter.
Aron Virginas-Tar70672f62019-01-23 14:00:00 +00003480 const armnn::TensorShape& reshapeOutputTensorShape = reshapeOutputTensorInfo.GetShape();
3481 if (inputs.size() > 1 && !CheckShape(reshapeOutputTensorShape, outputs[0]->shape))
kevmay0171972a82018-12-17 14:28:03 +00003482 {
Cathal Corbett2b922e22022-09-23 15:49:24 +01003483 // Attempt to extract output shape from secondary 'shape_signature'
3484 // parameter and try to CheckShape() with this param.
3485 std::vector<int32_t> secondaryOutputTargetShape = outputs[0]->shape_signature;
3486
3487 // if outputs[0]->shape_signature contain a -1 value, we need to compute its actual value
3488 // from reshape input in order to correctly verify reshape parameters equal output shape
3489 armnn::TensorInfo secondaryReshapeOutputTensorInfo =
3490 TfLiteParserImpl::OutputShapeOfReshape(inputTensorInfo, secondaryOutputTargetShape);
3491
3492 if (!CheckShape(reshapeOutputTensorShape, secondaryReshapeOutputTensorInfo.GetShape()))
3493 {
3494 std::stringstream ss;
3495 ss << "New shape defined in reshape parameters "
3496 << reshapeOutputTensorShape
3497 << " does not equal output shape "
3498 << actualOutputTensorInfo.GetShape()
3499 << ": "
3500 << CHECK_LOCATION().AsString();
3501 throw ParseException(ss.str());
3502 }
kevmay0171972a82018-12-17 14:28:03 +00003503 }
Mike Kelly377fb212023-01-10 15:55:28 +00003504 auto outputTensorIds = GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex);
kevmay0171972a82018-12-17 14:28:03 +00003505
Sadikb94967b2018-09-19 15:30:00 +01003506 ReshapeDescriptor reshapeDesc;
kevmay0171972a82018-12-17 14:28:03 +00003507 reshapeDesc.m_TargetShape = reshapeOutputTensorInfo.GetShape();
Mike Kelly377fb212023-01-10 15:55:28 +00003508 m_TensorInfos[outputTensorIds[0]] = reshapeOutputTensorInfo;
Sadikb94967b2018-09-19 15:30:00 +01003509
Sadikb94967b2018-09-19 15:30:00 +01003510 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01003511
3512 if (!layer)
3513 {
3514 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3515 operatorIndex, CHECK_LOCATION().AsString()));
3516 }
3517
kevmay0171972a82018-12-17 14:28:03 +00003518 layer->GetOutputSlot(0).SetTensorInfo(reshapeOutputTensorInfo);
Sadikb94967b2018-09-19 15:30:00 +01003519
3520 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3521 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3522
3523 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3524 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3525}
3526
Kevin May7d96b162021-02-03 17:38:41 +00003527void TfLiteParserImpl::ParseResizeBilinear(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02003528{
Sadik Armagana3b31f02019-12-05 09:08:53 +00003529 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::Bilinear);
3530}
3531
Kevin May7d96b162021-02-03 17:38:41 +00003532void TfLiteParserImpl::ParseResizeNearestNeighbor(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagana3b31f02019-12-05 09:08:53 +00003533{
3534 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::NearestNeighbor);
3535}
3536
Kevin May7d96b162021-02-03 17:38:41 +00003537void TfLiteParserImpl::ParseResize(size_t subgraphIndex, size_t operatorIndex, ResizeMethod resizeMethod)
Sadik Armagana3b31f02019-12-05 09:08:53 +00003538{
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02003539 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3540
3541 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3542 CHECK_VALID_SIZE(inputs.size(), 2);
3543
3544 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3545 CHECK_VALID_SIZE(outputs.size(), 1);
3546
Mike Kelly377fb212023-01-10 15:55:28 +00003547 armnn::TensorInfo sizeTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02003548
3549 // Data for the parsed tensor args (size) must be stored locally.
3550 std::vector<int32_t> sizeTensorData(sizeTensorInfo.GetNumElements());
3551
3552 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
3553 ::memcpy(sizeTensorData.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
3554
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01003555 ResizeDescriptor desc;
Sadik Armagana3b31f02019-12-05 09:08:53 +00003556 desc.m_Method = resizeMethod;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02003557 desc.m_TargetHeight = static_cast<uint32_t> (sizeTensorData[0]);
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01003558 desc.m_TargetWidth = static_cast<uint32_t> (sizeTensorData[1]);
3559 desc.m_DataLayout = armnn::DataLayout::NHWC;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02003560
James Ward58dec6b2020-09-11 17:32:44 +01003561 auto layerName = fmt::format("Resize:");
Sadik Armagana3b31f02019-12-05 09:08:53 +00003562
3563 switch (resizeMethod)
3564 {
3565 case ResizeMethod::Bilinear:
3566 {
James Ward58dec6b2020-09-11 17:32:44 +01003567 layerName += fmt::format("BILINEAR:{}:{}", subgraphIndex, operatorIndex);
Sang-Hoon Park820eb142020-01-08 10:25:24 +00003568
3569 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3570 const auto * options = operatorPtr->builtin_options.AsResizeBilinearOptions();
3571
David Monahan4a0c9b92020-05-30 09:48:39 +01003572 desc.m_AlignCorners = options->align_corners;
Sadik Armagana3b31f02019-12-05 09:08:53 +00003573 break;
3574 }
3575 case ResizeMethod::NearestNeighbor:
3576 {
James Ward58dec6b2020-09-11 17:32:44 +01003577 layerName += fmt::format("NEARESTNEIGHBOR:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagana3b31f02019-12-05 09:08:53 +00003578 break;
3579 }
3580 default:
3581 {
3582 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003583 fmt::format("Unexpected ResizeMethod[{}] when creating layerName {} ",
3584 static_cast<int>(resizeMethod), CHECK_LOCATION().AsString()));
Sadik Armagana3b31f02019-12-05 09:08:53 +00003585 }
3586 }
3587
Mike Kelly377fb212023-01-10 15:55:28 +00003588 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
James Conroy05102392020-06-24 15:39:55 +01003589
3590 IConnectableLayer* layer = m_Network->AddResizeLayer(desc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01003591
3592 if (!layer)
3593 {
3594 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3595 operatorIndex, CHECK_LOCATION().AsString()));
3596 }
3597
Mike Kelly377fb212023-01-10 15:55:28 +00003598 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
3599 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02003600 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3601
3602 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3603 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3604
3605 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3606 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3607}
3608
Tianle Chenge5a30ff2023-07-03 11:24:12 +01003609void TfLiteParserImpl::ParseReverseV2(size_t subgraphIndex, size_t operatorIndex)
3610{
3611 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3612
3613 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3614 CHECK_VALID_SIZE(inputs.size(), 2);
3615
3616 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3617 CHECK_VALID_SIZE(outputs.size(), 1);
3618
3619 auto layerName = fmt::format("ReverseV2:{}:{}", subgraphIndex, operatorIndex);
3620
3621 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3622 TensorInfo axisTensorInfo = ToTensorInfo(inputs[1]);
3623 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
3624
Tracy Narinebb8d7592023-07-13 16:50:54 +01003625 IConnectableLayer* layer = m_Network->AddReverseV2Layer(layerName.c_str());
Tianle Chenge5a30ff2023-07-03 11:24:12 +01003626 ARMNN_ASSERT(layer != nullptr);
3627
3628 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3629
3630 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Tracy Narinebb8d7592023-07-13 16:50:54 +01003631 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Tianle Chenge5a30ff2023-07-03 11:24:12 +01003632
3633 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3634 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3635}
3636
Teresa Charlin777008b2023-07-26 10:07:55 +01003637void TfLiteParserImpl::ParseTile(size_t subgraphIndex, size_t operatorIndex)
3638{
3639 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3640
3641 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3642 CHECK_VALID_SIZE(inputs.size(), 2);
3643
3644 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3645 CHECK_VALID_SIZE(outputs.size(), 1);
3646
3647 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3648 TensorInfo multiplesTensorInfo = ToTensorInfo(inputs[1]);
3649 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
3650
3651 auto layerName = fmt::format("Tile:{}:{}", subgraphIndex, operatorIndex);
3652
3653 TileDescriptor descriptor;
3654
3655 BufferRawPtr multiplesBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
3656 if (multiplesBufferPtr != nullptr)
3657 {
3658 std::vector<int32_t> multiplesData(multiplesTensorInfo.GetNumElements());
3659 ::memcpy(multiplesData.data(), multiplesBufferPtr->data.data(), multiplesTensorInfo.GetNumBytes());
3660 descriptor.m_Multiples.assign(multiplesData.begin(), multiplesData.end());
3661 }
3662 else
3663 {
3664 ARMNN_THROW_PARSE_EXCEPTION("For Tile layer, Multiples data was not found in the buffer.");
3665 }
3666
3667 IConnectableLayer* layer = m_Network->AddTileLayer(descriptor, layerName.c_str());
3668 ARMNN_ASSERT(layer != nullptr);
3669
3670 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3671
3672 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3673 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3674
3675 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3676 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3677}
3678
Kevin May7d96b162021-02-03 17:38:41 +00003679void TfLiteParserImpl::ParseConcatenation(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan479045b2018-10-01 11:51:37 +01003680{
3681 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3682
Mike Kelly0d77ae12022-01-07 17:42:27 +00003683 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3684 const auto* options = operatorPtr->builtin_options.AsConcatenationOptions();
Sadik Armagan479045b2018-10-01 11:51:37 +01003685
3686 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
3687
3688 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3689 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Mike Kelly377fb212023-01-10 15:55:28 +00003690 auto inputTensorIds = GetInputTensorIds(m_Model, subgraphIndex, operatorIndex);
3691
Sadik Armagan479045b2018-10-01 11:51:37 +01003692 CHECK_VALID_SIZE(outputs.size(), 1);
3693
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003694 unsigned int numConcatView = static_cast<unsigned int>(inputs.size());
Mike Kelly377fb212023-01-10 15:55:28 +00003695 uint32_t inputRank = InputTensorInfo(subgraphIndex, operatorIndex, 0).GetNumDimensions();
Sadik Armagan479045b2018-10-01 11:51:37 +01003696
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003697 const unsigned int concatDimInput = static_cast<unsigned int>(
Mike Kelly377fb212023-01-10 15:55:28 +00003698 (static_cast<int>(inputRank) + options->axis) % static_cast<int>(inputRank));
Sadik Armagan479045b2018-10-01 11:51:37 +01003699
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003700 OriginsDescriptor concatDescriptor(static_cast<uint32_t>(numConcatView), inputRank);
3701 concatDescriptor.SetConcatAxis(concatDimInput);
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003702 unsigned int mergeDimOrigin = 0;
Sadik Armagan479045b2018-10-01 11:51:37 +01003703
3704 for (unsigned int viewIndex = 0; viewIndex < numConcatView; ++viewIndex)
3705 {
Mike Kelly377fb212023-01-10 15:55:28 +00003706 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, viewIndex);
Sadik Armagan479045b2018-10-01 11:51:37 +01003707
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003708 // This set up concatDescriptor view origin
3709 armnnUtils::ProcessConcatInputTensorInfo(
Mike Kelly377fb212023-01-10 15:55:28 +00003710 inputTensorInfo, concatDescriptor, concatDimInput, viewIndex, mergeDimOrigin);
Sadik Armagan479045b2018-10-01 11:51:37 +01003711 }
3712
James Ward58dec6b2020-09-11 17:32:44 +01003713 auto layerName = fmt::format("Concatenation:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01003714
Jim Flynn906f9462019-05-10 13:55:21 +01003715 IConnectableLayer* layer = m_Network->AddConcatLayer(concatDescriptor, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01003716
3717 if (!layer)
3718 {
3719 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3720 operatorIndex, CHECK_LOCATION().AsString()));
3721 }
3722
Mike Kelly377fb212023-01-10 15:55:28 +00003723 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {});
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003724 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Sadik Armagan479045b2018-10-01 11:51:37 +01003725
James Conroy05102392020-06-24 15:39:55 +01003726 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003727 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
Sadik Armagan479045b2018-10-01 11:51:37 +01003728
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003729 // add fused activation layer
3730 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Sadik Armagan479045b2018-10-01 11:51:37 +01003731
Sadik Armagan479045b2018-10-01 11:51:37 +01003732 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3733 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3734}
3735
Kevin May7d96b162021-02-03 17:38:41 +00003736void TfLiteParserImpl::ParseFullyConnected(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003737{
3738 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3739
Mike Kelly0d77ae12022-01-07 17:42:27 +00003740 const auto& operatorRfr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003741 const auto options = operatorRfr->builtin_options.AsFullyConnectedOptions();
3742
3743 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
3744
3745 FullyConnectedDescriptor desc;
3746 desc.m_BiasEnabled = false;
Nattapat Chaimanowongd8eee592018-10-26 10:24:14 +01003747 desc.m_TransposeWeightMatrix = true;
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003748
3749 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3750 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3751 CHECK_VALID_SIZE(outputs.size(), 1);
3752
Mike Kelly377fb212023-01-10 15:55:28 +00003753 armnn::TensorInfo filterTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003754
3755 // Fully Connected Layer accepts two dimensional weights input
3756 int32_t weightsDimension = static_cast<int32_t>(filterTensorInfo.GetNumDimensions());
3757 if (weightsDimension != 2)
3758 {
3759 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003760 fmt::format("Dimension {} for Fully Connected weights is not supported by Armnn. "
3761 "Node {}",
3762 weightsDimension,
3763 CHECK_LOCATION().AsString()));
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003764 }
3765
Matthew Jackson74bf7da2019-08-16 16:51:42 +01003766 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01003767 auto layerName = fmt::format("FullyConnected:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003768
Matthew Sloyan81beae32021-07-13 19:46:11 +01003769 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3770 // Add the first input tensor to the registration list
3771 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0]};
Mike Kelly377fb212023-01-10 15:55:28 +00003772 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003773
3774 desc.m_ConstantWeights = IsConstTensor(inputs[1]);
3775
Matthew Sloyan81beae32021-07-13 19:46:11 +01003776 // Add the weights input to the registration list, constant layers will be added by SetupConstantLayers if constant.
3777 tensorIndexesToRegister.emplace_back(inputTensorIndexes[1]);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003778
Mike Kelly0506ef02023-01-03 16:29:44 +00003779 if (ShouldConstantTensorBeConverted(inputs[1], inputTensorInfo.GetDataType(), filterTensorInfo.GetDataType()))
Mike Kelly5880b912022-01-28 16:18:54 +00003780 {
3781 m_ConstantsToDequantize.emplace_back(inputs[1]->buffer);
3782 }
3783
Finn Williamsd4fa5452021-03-01 12:31:41 +00003784 if (inputs.size() == 3)
3785 {
3786 desc.m_BiasEnabled = true;
Mike Kelly377fb212023-01-10 15:55:28 +00003787 armnn::TensorInfo biasTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
Matthew Sloyan81beae32021-07-13 19:46:11 +01003788
3789 // Add the biases input to the registration list, constant layer will be added by SetupConstantLayers.
3790 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
Mike Kelly5880b912022-01-28 16:18:54 +00003791
Mike Kelly0506ef02023-01-03 16:29:44 +00003792 if (ShouldConstantTensorBeConverted(inputs[2], inputTensorInfo.GetDataType(), biasTensorInfo.GetDataType()))
Mike Kelly5880b912022-01-28 16:18:54 +00003793 {
3794 m_ConstantsToDequantize.emplace_back(inputs[2]->buffer);
3795 }
Finn Williamsd4fa5452021-03-01 12:31:41 +00003796 }
3797
Matthew Sloyan81beae32021-07-13 19:46:11 +01003798 // Filters and biases are always passed to fully connected as inputs
3799 layer = m_Network->AddFullyConnectedLayer(desc, layerName.c_str());
Finn Williamsd4fa5452021-03-01 12:31:41 +00003800
Ryan OSheac229b3f2023-06-27 22:34:54 +01003801 if (!layer)
3802 {
3803 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3804 operatorIndex, CHECK_LOCATION().AsString()));
3805 }
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003806
Finn Williamsd4fa5452021-03-01 12:31:41 +00003807 unsigned int startingSlotIndex = 0;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003808 if (inputTensorInfo.GetNumDimensions() > 2)
3809 {
3810 // Add reshape to flatten to 2D [batch_size, input_size],
3811 // where "input_size" corresponds to the number of inputs to the layer,
3812 // matching the second dimension of weights,
3813 // and "batch_size" is calculated by dividing the number of elements by "input_size".
3814 std::vector<unsigned int> reshapedDimensions(2);
3815 reshapedDimensions[1] = filterTensorInfo.GetShape()[1];
3816 reshapedDimensions[0] = inputTensorInfo.GetNumElements() / reshapedDimensions[1];
3817
3818 if (inputTensorInfo.GetNumElements() % reshapedDimensions[1] != 0)
3819 {
3820 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003821 fmt::format("Failed to deduce input tensor shape from filter size {} {}",
3822 reshapedDimensions[1],
3823 CHECK_LOCATION().AsString()));
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003824 }
3825
Mike Kelly377fb212023-01-10 15:55:28 +00003826 armnn::TensorInfo reshapedTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003827 reshapedTensorInfo.SetShape(armnn::TensorShape{ 2, reshapedDimensions.data() });
Mike Kelly377fb212023-01-10 15:55:28 +00003828 inputTensorInfo = reshapedTensorInfo;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003829
James Ward58dec6b2020-09-11 17:32:44 +01003830 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Finn Williamsd4fa5452021-03-01 12:31:41 +00003831 armnn::ReshapeDescriptor reshapeDescriptor;
3832 reshapeDescriptor.m_TargetShape = reshapedTensorInfo.GetShape();
Mike Kelly04d82292023-01-19 18:29:40 +00003833 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(reshapeDescriptor,
3834 reshapeLayerName.c_str());
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003835
3836 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedTensorInfo);
3837 reshapeLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(0));
3838
3839 RegisterInputSlots(subgraphIndex, operatorIndex, reshapeLayer, {inputTensorIndexes[0]});
Finn Williamsd4fa5452021-03-01 12:31:41 +00003840 // Fc layer connects to the reshape layer, so we skip the first input slot when registering fc's input slots
3841 tensorIndexesToRegister.erase(tensorIndexesToRegister.begin());
3842 startingSlotIndex = 1;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003843 }
Finn Williamsd4fa5452021-03-01 12:31:41 +00003844
3845 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister, startingSlotIndex);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003846
Mike Kelly377fb212023-01-10 15:55:28 +00003847 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromShapes(subgraphIndex, operatorIndex, layer, 0,
3848 { inputTensorInfo.GetShape(),
3849 filterTensorInfo.GetShape() });
Mike Kelly04d82292023-01-19 18:29:40 +00003850
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003851 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3852
Mike Kelly04d82292023-01-19 18:29:40 +00003853 if (outputTensorInfo.GetNumDimensions() > 2)
3854 {
3855 // Calculate reshape to flatten to 2D [batch_size, input_size]
3856 std::vector<unsigned int> reshapedDimensions(2);
3857 reshapedDimensions[1] = filterTensorInfo.GetShape()[0];
3858 reshapedDimensions[0] = outputTensorInfo.GetNumElements() / reshapedDimensions[1];
3859 armnn::TensorInfo reshapedOutputTensorInfo = outputTensorInfo;
3860 if (outputTensorInfo.GetNumElements() % reshapedDimensions[1] != 0)
3861 {
3862 throw ParseException(
3863 fmt::format("Failed to deduce output tensor shape from filter size {} {}",
3864 reshapedDimensions[1],
3865 CHECK_LOCATION().AsString()));
3866 }
3867 reshapedOutputTensorInfo.SetShape(armnn::TensorShape{ 2, reshapedDimensions.data() });
3868 layer->GetOutputSlot(0).SetTensorInfo(reshapedOutputTensorInfo);
3869
3870 std::string reshapeLayerName = fmt::format("ExpandDims:{}:{}", subgraphIndex, operatorIndex);
3871 layer = AddReshapeLayer(layer, 0, reshapeLayerName, outputTensorInfo);
3872 }
3873
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003874 // we need to add the activation layer and fortunately we don't need to care about the data layout
3875 armnn::IConnectableLayer* fusedActivationLayer = AddFusedActivationLayer(layer, 0,
3876 options->fused_activation_function);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003877
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003878 // register the output connection slots for the layer, connections are made after all layers have been created
3879 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3880 RegisterOutputSlots(subgraphIndex, operatorIndex, fusedActivationLayer, {outputTensorIndexes[0]});
Mike Kelly04d82292023-01-19 18:29:40 +00003881
3882 m_TensorInfos[outputTensorIndexes[0]] = layer->GetOutputSlot(0).GetTensorInfo();
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003883}
3884
Kevin May7d96b162021-02-03 17:38:41 +00003885void TfLiteParserImpl::ParseDetectionPostProcess(size_t subgraphIndex, size_t operatorIndex)
keidav011b3e2ea2019-02-21 10:07:37 +00003886{
3887 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3888
Mike Kelly0d77ae12022-01-07 17:42:27 +00003889 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
keidav011b3e2ea2019-02-21 10:07:37 +00003890
3891 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3892 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3893 CHECK_VALID_SIZE(outputs.size(), 4);
3894
3895 // Obtain custom options from flexbuffers
3896 auto custom_options = operatorPtr->custom_options;
3897 const flexbuffers::Map& m = flexbuffers::GetRoot(custom_options.data(), custom_options.size()).AsMap();
3898
3899 // Obtain descriptor information from tf lite
3900 DetectionPostProcessDescriptor desc;
3901 desc.m_MaxDetections = m["max_detections"].AsUInt32();
3902 desc.m_MaxClassesPerDetection = m["max_classes_per_detection"].AsUInt32();
3903 desc.m_NmsScoreThreshold = m["nms_score_threshold"].AsFloat();
3904 desc.m_NmsIouThreshold = m["nms_iou_threshold"].AsFloat();
3905 desc.m_NumClasses = m["num_classes"].AsUInt32();
3906 desc.m_ScaleH = m["h_scale"].AsFloat();
3907 desc.m_ScaleW = m["w_scale"].AsFloat();
3908 desc.m_ScaleX = m["x_scale"].AsFloat();
3909 desc.m_ScaleY = m["y_scale"].AsFloat();
3910
keidav0107d58c72019-02-26 11:57:39 +00003911 if (!(m["use_regular_nms"].IsNull()))
keidav011b3e2ea2019-02-21 10:07:37 +00003912 {
keidav0107d58c72019-02-26 11:57:39 +00003913 desc.m_UseRegularNms = m["use_regular_nms"].AsBool();
keidav011b3e2ea2019-02-21 10:07:37 +00003914 }
3915 if (!(m["detections_per_class"].IsNull()))
3916 {
3917 desc.m_DetectionsPerClass = m["detections_per_class"].AsUInt32();
3918 }
3919
3920 if (desc.m_NmsIouThreshold <= 0.0f || desc.m_NmsIouThreshold > 1.0f)
3921 {
3922 throw InvalidArgumentException("DetectionPostProcessTFLiteParser: Intersection over union threshold "
3923 "must be positive and less than or equal to 1.");
3924 }
3925
Mike Kelly377fb212023-01-10 15:55:28 +00003926 armnn::TensorInfo anchorTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 2);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003927 auto anchorTensorAndData = CreateConstTensorNonPermuted(inputs[2], anchorTensorInfo);
keidav011b3e2ea2019-02-21 10:07:37 +00003928
James Ward58dec6b2020-09-11 17:32:44 +01003929 auto layerName = fmt::format("DetectionPostProcess:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003930 IConnectableLayer* layer = m_Network->AddDetectionPostProcessLayer(desc, anchorTensorAndData,
keidav011b3e2ea2019-02-21 10:07:37 +00003931 layerName.c_str());
3932
Ryan OSheac229b3f2023-06-27 22:34:54 +01003933 if (!layer)
3934 {
3935 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3936 operatorIndex, CHECK_LOCATION().AsString()));
3937 }
keidav011b3e2ea2019-02-21 10:07:37 +00003938
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003939 // The model does not specify the output shapes.
3940 // The output shapes are calculated from the max_detection and max_classes_per_detection.
3941 unsigned int numDetectedBox = desc.m_MaxDetections * desc.m_MaxClassesPerDetection;
Mike Kelly377fb212023-01-10 15:55:28 +00003942 m_OverriddenOutputShapes.push_back({ 1, numDetectedBox, 4 });
3943 m_OverriddenOutputShapes.push_back({ 1, numDetectedBox });
3944 m_OverriddenOutputShapes.push_back({ 1, numDetectedBox });
3945 m_OverriddenOutputShapes.push_back({ 1 });
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003946
keidav011b3e2ea2019-02-21 10:07:37 +00003947 for (unsigned int i = 0 ; i < outputs.size() ; ++i)
3948 {
Mike Kelly377fb212023-01-10 15:55:28 +00003949 armnn::TensorInfo detectionBoxOutputTensorInfo = ToTensorInfo(outputs[i], m_OverriddenOutputShapes[i]);
keidav011b3e2ea2019-02-21 10:07:37 +00003950 layer->GetOutputSlot(i).SetTensorInfo(detectionBoxOutputTensorInfo);
3951 }
3952
3953 // Register the input connection slots for the layer, connections are made after all layers have been created
3954 // only the tensors for the inputs are relevant, exclude the const tensors
3955 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3956 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
3957
3958 // Register the output connection slots for the layer, connections are made after all layers have been created
3959 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3960 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0],
3961 outputTensorIndexes[1],
3962 outputTensorIndexes[2],
3963 outputTensorIndexes[3]});
3964}
3965
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003966/// The TfLite Pack operator is equivalent to the ArmNN Stack operator
Kevin May7d96b162021-02-03 17:38:41 +00003967void TfLiteParserImpl::ParsePack(size_t subgraphIndex, size_t operatorIndex)
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003968{
3969 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3970
3971 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3972 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3973 CHECK_VALID_SIZE(outputs.size(), 1);
3974
3975 if (inputs.size() < 1)
3976 {
3977 throw ParseException("Pack must have at least one input.");
3978 }
3979
3980 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3981 const auto* options = operatorPtr->builtin_options.AsPackOptions();
3982
3983 StackDescriptor desc;
3984 desc.m_Axis = static_cast<uint32_t>(options->axis);
3985 desc.m_NumInputs = static_cast<uint32_t>(inputs.size());
3986
3987 // Use the tensor shape of the first input as the "correct" input shape in the descriptor
Mike Kelly377fb212023-01-10 15:55:28 +00003988 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003989 desc.m_InputShape = inputTensorInfo.GetShape();
3990
James Ward58dec6b2020-09-11 17:32:44 +01003991 auto layerName = fmt::format("Pack:{}:{}", subgraphIndex, operatorIndex);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003992 IConnectableLayer* layer = m_Network->AddStackLayer(desc, layerName.c_str());
3993
Ryan OSheac229b3f2023-06-27 22:34:54 +01003994 if (!layer)
3995 {
3996 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
3997 operatorIndex, CHECK_LOCATION().AsString()));
3998 }
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003999
Mike Kelly377fb212023-01-10 15:55:28 +00004000 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {});
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01004001 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4002
4003 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4004 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
4005
4006 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4007 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4008}
4009
Mike Kelly5880b912022-01-28 16:18:54 +00004010void TfLiteParserImpl::ParseUnidirectionalSequenceLSTM(size_t subgraphIndex, size_t operatorIndex)
4011{
4012 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4013
4014 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4015 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4016
4017 if (inputs.size() < 2)
4018 {
4019 throw ParseException("UnidirectionalSequenceLSTM must have at least 2 input.");
4020 }
4021
4022 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4023 const auto& subgraphPtr = m_Model->subgraphs[subgraphIndex];
4024 const auto nodeParams = operatorPtr->builtin_options.AsUnidirectionalSequenceLSTMOptions();
4025 CHECK_SUPPORTED_FUSED_ACTIVATION(nodeParams, subgraphIndex, operatorIndex);
Mike Kelly377fb212023-01-10 15:55:28 +00004026 auto inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Mike Kelly5880b912022-01-28 16:18:54 +00004027 auto outputTensorInfo = ToTensorInfo(outputs[0]);
4028
4029 // Set the params structure for the AddUnidirectionalSequenceLstmLayer call
4030 // Please refer to each operand at
4031 // https://www.tensorflow.org/mlir/tfl_ops#tflunidirectional_sequence_lstm_tflunidirectionalsequencelstmop
4032 armnn::LstmInputParams params;
4033
4034 if (IsOptionalOperandPresent(operatorPtr->inputs[1]))
4035 {
4036 params.m_InputToInputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[1]].get(),
4037 inputTensorInfo).first;
4038 }
4039
4040 params.m_InputToForgetWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[2]].get(),
4041 inputTensorInfo).first;
4042 params.m_InputToCellWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[3]].get(),
4043 inputTensorInfo).first;
4044 params.m_InputToOutputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[4]].get(),
4045 inputTensorInfo).first;
4046
4047 // Recurrent weight tensors of size {n_cell, n_output}
4048 if (IsOptionalOperandPresent(operatorPtr->inputs[5]))
4049 {
4050 params.m_RecurrentToInputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[5]].get(),
4051 inputTensorInfo).first;
4052 }
4053
4054 params.m_RecurrentToForgetWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[6]].get(),
4055 inputTensorInfo).first;
4056 params.m_RecurrentToCellWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[7]].get(),
4057 inputTensorInfo).first;
4058 params.m_RecurrentToOutputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[8]].get(),
4059 inputTensorInfo).first;
4060
4061 // Peephole weights tensors of size {n_cell}, representing a diagonal matrix.
4062 if (IsOptionalOperandPresent(operatorPtr->inputs[9]))
4063 {
4064 params.m_CellToInputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[9]].get(),
4065 inputTensorInfo).first;
4066 }
4067
4068 if (IsOptionalOperandPresent(operatorPtr->inputs[10]))
4069 {
4070 params.m_CellToForgetWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[10]].get(),
4071 inputTensorInfo).first;
4072 }
4073
4074 if (IsOptionalOperandPresent(operatorPtr->inputs[11]))
4075 {
4076 params.m_CellToOutputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[11]].get(),
4077 inputTensorInfo).first;
4078 }
4079
4080 // Gates bias tensors of size {n_cell}
4081 if (IsOptionalOperandPresent(operatorPtr->inputs[12]))
4082 {
4083 params.m_InputGateBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[12]].get(),
4084 inputTensorInfo).first;
4085 }
4086
4087 params.m_ForgetGateBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[13]].get(),
4088 inputTensorInfo).first;
4089 params.m_CellBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[14]].get(),
4090 inputTensorInfo).first;
4091 params.m_OutputGateBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[15]].get(),
4092 inputTensorInfo).first;
4093
4094 // Projection weight tensor of size {n_output, n_cell}
4095 if (IsOptionalOperandPresent(operatorPtr->inputs[16]))
4096 {
4097 params.m_ProjectionWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[16]].get(),
4098 inputTensorInfo).first;
4099 }
4100 // Projection bias tensor of size {n_output}
4101 if (IsOptionalOperandPresent(operatorPtr->inputs[17]))
4102 {
4103 params.m_ProjectionBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[17]].get(),
4104 inputTensorInfo).first;
4105 }
4106
4107 // These state tensors are defined as variable tensors, and will be modified by this op.
4108 armnn::TensorInfo outputStateInInfo = ToTensorInfo(subgraphPtr->tensors[operatorPtr->inputs[18]].get());
4109 m_ConstantsToBeCreated.push_back(operatorPtr->inputs[18]);
4110 armnn::TensorInfo cellStateInInfo = ToTensorInfo(subgraphPtr->tensors[operatorPtr->inputs[19]].get());
4111 m_ConstantsToBeCreated.push_back(operatorPtr->inputs[19]);
4112
4113 // Layer norm coefficient tensors of size {n_cell}, representing a diagonal matrix.
4114 if (inputs.size() >= 21 && IsOptionalOperandPresent(operatorPtr->inputs[20]))
4115 {
4116 params.m_InputLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[20]].get(),
4117 inputTensorInfo).first;
4118 }
4119
4120 if (inputs.size() >= 22 && IsOptionalOperandPresent(operatorPtr->inputs[21]))
4121 {
4122 params.m_ForgetLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[21]].get(),
4123 inputTensorInfo).first;
4124 }
4125
4126 if (inputs.size() >= 23 && IsOptionalOperandPresent(operatorPtr->inputs[22]))
4127 {
4128 params.m_CellLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[22]].get(),
4129 inputTensorInfo).first;
4130 }
4131
4132 if (inputs.size() >= 24 && IsOptionalOperandPresent(operatorPtr->inputs[23]))
4133 {
4134 params.m_OutputLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[23]].get(),
4135 inputTensorInfo).first;
4136 }
4137
4138 // set the layer descriptor
4139 armnn::UnidirectionalSequenceLstmDescriptor desc;
4140 desc.m_ActivationFunc = nodeParams->fused_activation_function;
4141 desc.m_ClippingThresCell = nodeParams->cell_clip;
4142 desc.m_ClippingThresProj = nodeParams->proj_clip;
4143 desc.m_CifgEnabled = (params.m_InputToInputWeights == nullptr
4144 || params.m_RecurrentToInputWeights == nullptr
4145 || params.m_InputGateBias == nullptr);
4146 desc.m_PeepholeEnabled = (params.m_CellToForgetWeights != nullptr || params.m_CellToOutputWeights != nullptr);
4147 desc.m_ProjectionEnabled = (params.m_ProjectionWeights != nullptr);
4148 desc.m_LayerNormEnabled = (params.m_InputLayerNormWeights != nullptr
4149 || params.m_ForgetLayerNormWeights != nullptr
4150 || params.m_CellLayerNormWeights != nullptr
4151 || params.m_OutputLayerNormWeights != nullptr);
4152 desc.m_TimeMajor = nodeParams->time_major;
4153
Mike Kellyc0800a32022-06-15 10:57:52 +01004154 if (operatorPtr->intermediates.size() > 3 && desc.m_LayerNormEnabled)
Mike Kelly5880b912022-01-28 16:18:54 +00004155 {
4156 auto inputIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[0]].get(),
4157 inputTensorInfo).first;
4158 auto inputIntermediateTensorInfo = inputIntermediate->GetInfo();
4159 desc.m_InputIntermediateScale = inputIntermediateTensorInfo.GetQuantizationScale();
4160
4161 auto forgetIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[1]].get(),
4162 inputTensorInfo).first;
4163 auto forgetIntermediateTensorInfo = forgetIntermediate->GetInfo();
4164 desc.m_ForgetIntermediateScale = forgetIntermediateTensorInfo.GetQuantizationScale();
4165
4166 auto cellIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[2]].get(),
4167 inputTensorInfo).first;
4168 auto cellIntermediateTensorInfo = cellIntermediate->GetInfo();
4169 desc.m_CellIntermediateScale = cellIntermediateTensorInfo.GetQuantizationScale();
4170
4171 auto outputIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[3]].get(),
4172 inputTensorInfo).first;
4173 auto outputIntermediateTensorInfo = outputIntermediate->GetInfo();
4174 desc.m_OutputIntermediateScale = outputIntermediateTensorInfo.GetQuantizationScale();
4175 }
4176 else
4177 {
4178 float defaultIntermediate = std::pow(2, -12);
4179 desc.m_InputIntermediateScale = defaultIntermediate;
4180 desc.m_ForgetIntermediateScale = defaultIntermediate;
4181 desc.m_CellIntermediateScale = defaultIntermediate;
4182 desc.m_OutputIntermediateScale = defaultIntermediate;
4183 }
4184
Mike Kellyc0800a32022-06-15 10:57:52 +01004185 if (operatorPtr->intermediates.size() > 4)
4186 {
4187 auto hiddentensor = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[4]].get(),
4188 inputTensorInfo).first;
Mike Kelly5880b912022-01-28 16:18:54 +00004189
Mike Kellyc0800a32022-06-15 10:57:52 +01004190 desc.m_HiddenStateScale = hiddentensor->GetInfo().GetQuantizationScale();
4191 desc.m_HiddenStateZeroPoint = hiddentensor->GetInfo().GetQuantizationOffset();
4192 }
Narumol Prangnawarat5f941242023-08-11 16:09:26 +01004193 unsigned int batchSize = desc.m_TimeMajor ? inputTensorInfo.GetShape()[1] : inputTensorInfo.GetShape()[0];
Mike Kelly5880b912022-01-28 16:18:54 +00004194 unsigned int outputSize = outputTensorInfo.GetShape()[2];
4195 unsigned int numUnits = cellStateInInfo.GetShape()[1];
4196
4197 armnn::DataType dataType = inputTensorInfo.GetDataType();
4198 float qScale = inputTensorInfo.GetQuantizationScale();
4199 float qOffset = inputTensorInfo.GetQuantizationOffset();
4200
4201 armnn::TensorInfo scratchBufferTensorInfo({batchSize, numUnits * 3}, dataType, qScale, qOffset);
4202 if (!desc.m_CifgEnabled)
4203 {
4204 scratchBufferTensorInfo = armnn::TensorInfo({batchSize, numUnits * 4}, dataType, qScale, qOffset);
4205 }
4206 armnn::TensorInfo cellStateOutTensorInfo({batchSize, numUnits},
4207 cellStateInInfo.GetDataType(),
4208 cellStateInInfo.GetQuantizationScale(),
4209 cellStateInInfo.GetQuantizationOffset());
4210 armnn::TensorInfo outputStateOutTensorInfo({batchSize, outputSize}, dataType, qScale, qOffset);
4211
4212 armnn::LstmInputParamsInfo paramsInfo;
4213 paramsInfo.m_InputToForgetWeights = &(params.m_InputToForgetWeights->GetInfo());
4214 paramsInfo.m_InputToCellWeights = &(params.m_InputToCellWeights->GetInfo());
4215 paramsInfo.m_InputToOutputWeights = &(params.m_InputToOutputWeights->GetInfo());
4216 paramsInfo.m_RecurrentToForgetWeights = &(params.m_RecurrentToForgetWeights->GetInfo());
4217 paramsInfo.m_RecurrentToCellWeights = &(params.m_RecurrentToCellWeights->GetInfo());
4218 paramsInfo.m_RecurrentToOutputWeights = &(params.m_RecurrentToOutputWeights->GetInfo());
4219 paramsInfo.m_ForgetGateBias = &(params.m_ForgetGateBias->GetInfo());
4220 paramsInfo.m_CellBias = &(params.m_CellBias->GetInfo());
4221 paramsInfo.m_OutputGateBias = &(params.m_OutputGateBias->GetInfo());
4222
4223 if (!desc.m_CifgEnabled)
4224 {
4225 paramsInfo.m_InputToInputWeights = &(params.m_InputToInputWeights->GetInfo());
4226 paramsInfo.m_RecurrentToInputWeights = &(params.m_RecurrentToInputWeights->GetInfo());
4227 if (params.m_CellToInputWeights != nullptr)
4228 {
4229 paramsInfo.m_CellToInputWeights = &(params.m_CellToInputWeights->GetInfo());
4230 }
4231 paramsInfo.m_InputGateBias = &(params.m_InputGateBias->GetInfo());
4232 }
4233
4234 if (desc.m_ProjectionEnabled)
4235 {
4236 paramsInfo.m_ProjectionWeights = &(params.m_ProjectionWeights->GetInfo());
4237 if (params.m_ProjectionBias != nullptr)
4238 {
4239 paramsInfo.m_ProjectionBias = &(params.m_ProjectionBias->GetInfo());
4240 }
4241 }
4242
4243 if (desc.m_PeepholeEnabled)
4244 {
4245 paramsInfo.m_CellToForgetWeights = &(params.m_CellToForgetWeights->GetInfo());
4246 paramsInfo.m_CellToOutputWeights = &(params.m_CellToOutputWeights->GetInfo());
4247 }
4248
4249 if (desc.m_LayerNormEnabled)
4250 {
4251 if(!desc.m_CifgEnabled)
4252 {
4253 paramsInfo.m_InputLayerNormWeights = &(params.m_InputLayerNormWeights->GetInfo());
4254 }
4255 paramsInfo.m_ForgetLayerNormWeights = &(params.m_ForgetLayerNormWeights->GetInfo());
4256 paramsInfo.m_CellLayerNormWeights = &(params.m_CellLayerNormWeights->GetInfo());
4257 paramsInfo.m_OutputLayerNormWeights = &(params.m_OutputLayerNormWeights->GetInfo());
4258 }
4259
4260 auto layerName = fmt::format("UnidirectionalSequenceLSTM:{}:{}", subgraphIndex, operatorIndex);
4261 armnn::IConnectableLayer* layer = m_Network->AddUnidirectionalSequenceLstmLayer(desc, params);
Ryan OSheac229b3f2023-06-27 22:34:54 +01004262
4263 if (!layer)
4264 {
4265 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
4266 operatorIndex, CHECK_LOCATION().AsString()));
4267 }
Mike Kelly5880b912022-01-28 16:18:54 +00004268
4269 // register the input connection slots for the layer, connections are made after all layers have been created
4270 // only the tensors for the inputs are relevant, exclude the const tensors
4271 auto inputTensorIndexes = AsUnsignedVector({operatorPtr->inputs[0],
4272 operatorPtr->inputs[18],
4273 operatorPtr->inputs[19]});
4274 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0],
4275 inputTensorIndexes[1],
4276 inputTensorIndexes[2]});
4277
4278 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4279
4280 layer->GetOutputSlot(0).SetTensorInfo(outputStateOutTensorInfo);
4281 layer->GetOutputSlot(1).SetTensorInfo(cellStateOutTensorInfo);
4282 layer->GetOutputSlot(2).SetTensorInfo(outputTensorInfo);
4283
4284 unsigned int tensorIndex = outputTensorIndexes[0];
4285 armnn::IOutputSlot* slot = &(layer->GetOutputSlot(2));
4286 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
4287}
4288
Kevin May7d96b162021-02-03 17:38:41 +00004289void TfLiteParserImpl::ParseUnpack(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd200e3802019-04-15 09:47:39 +01004290{
4291 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4292
Mike Kelly0d77ae12022-01-07 17:42:27 +00004293 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4294 const auto* options = operatorPtr->builtin_options.AsUnpackOptions();
Nina Drozd200e3802019-04-15 09:47:39 +01004295
4296 // This unpackAxis indicates the axis to unpack
4297 const unsigned int unpackAxis = CHECKED_NON_NEGATIVE(options->axis);
4298
4299 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4300 CHECK_VALID_SIZE(inputs.size(), 1);
4301
Mike Kelly377fb212023-01-10 15:55:28 +00004302 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01004303
4304 if (unpackAxis >= inputTensorInfo.GetNumDimensions())
4305 {
4306 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004307 fmt::format("The unpack axis: {} cannot be greater than or equal to "
4308 "the number of input dimension {} {}",
4309 unpackAxis,
4310 inputTensorInfo.GetNumDimensions(),
4311 CHECK_LOCATION().AsString()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01004312 }
4313
Nina Drozd200e3802019-04-15 09:47:39 +01004314 unsigned int unpackNum = CHECKED_NON_NEGATIVE(options->num);
4315 // If num is not defined, automatically infer from the length of the dimension axis.
4316 if(unpackNum == 0)
4317 {
4318 unpackNum = inputTensorInfo.GetShape()[unpackAxis];
4319 }
4320
4321 // If unpack number cannot be inferred and is still zero, throw ParseException.
4322 if(unpackNum == 0)
4323 {
4324 throw ParseException("Number to unpack must greater than zero.");
4325 }
4326
4327 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4328 CHECK_VALID_SIZE(outputs.size(), unpackNum);
4329
4330 auto inputDimSize = inputTensorInfo.GetNumDimensions();
4331 std::vector<unsigned int> unpackDimSizes(inputDimSize);
4332
4333 // Add current input shape to unpackDimSizes
4334 for (unsigned int i = 0; i < inputDimSize; ++i)
4335 {
4336 unpackDimSizes[i] = inputTensorInfo.GetShape()[i];
4337 }
4338
4339 if (unpackDimSizes[unpackAxis] != unpackNum)
4340 {
4341 throw ParseException("Number to unpack must be the same as length of the dimension to "
4342 "unpack along.");
4343 }
4344
4345 unpackDimSizes[unpackAxis] /= unpackNum;
4346
4347 SplitterDescriptor splitDesc(unpackNum, static_cast<unsigned int>(unpackDimSizes.size()));
4348 for (unsigned int j = 0; j < unpackNum; ++j)
4349 {
4350 // Set the size of the views.
4351 for (unsigned int dimIdx = 0; dimIdx < unpackDimSizes.size(); ++dimIdx)
4352 {
4353 splitDesc.SetViewSize(j, dimIdx, unpackDimSizes[dimIdx]);
4354 }
4355 splitDesc.SetViewOriginCoord(j, unpackAxis, unpackDimSizes[unpackAxis] * j);
4356 }
Mike Kelly363b5722023-10-11 14:25:50 +01004357 splitDesc.SetAxis(unpackAxis);
James Ward58dec6b2020-09-11 17:32:44 +01004358 auto layerName = fmt::format("Unpack:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd200e3802019-04-15 09:47:39 +01004359 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01004360
4361 if (!layer)
4362 {
4363 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
4364 operatorIndex, CHECK_LOCATION().AsString()));
4365 }
Nina Drozd200e3802019-04-15 09:47:39 +01004366
Narumol Prangnawarat672de572019-04-23 15:28:06 +01004367 TensorShape splitOutShape = TensorShape(static_cast<unsigned int>(unpackDimSizes.size()),
4368 unpackDimSizes.data());
4369
Nina Drozd200e3802019-04-15 09:47:39 +01004370 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4371 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4372
Finn Williamsb49ed182021-06-29 15:50:08 +01004373 std::vector<unsigned int> reshapeDims;
4374 for (unsigned int axis = 0; axis < splitOutShape.GetNumDimensions(); ++axis)
4375 {
4376 if (axis != unpackAxis)
4377 {
4378 reshapeDims.push_back(splitOutShape[axis]);
4379 }
4380 }
4381
4382 TensorShape reshapeOutputShape(splitOutShape.GetNumDimensions() -1, reshapeDims.data());
4383
Narumol Prangnawarat672de572019-04-23 15:28:06 +01004384 // Create reshape to remove the unpacked dimension for unpack operator of each output from Splitter.
4385 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
4386 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01004387 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[k], true);
James Ward58dec6b2020-09-11 17:32:44 +01004388 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Narumol Prangnawarat672de572019-04-23 15:28:06 +01004389 armnn::ReshapeDescriptor desc;
Finn Williamsb49ed182021-06-29 15:50:08 +01004390 desc.m_TargetShape = reshapeOutputShape;
Narumol Prangnawarat672de572019-04-23 15:28:06 +01004391 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(desc, layerName.c_str());
4392
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01004393 layer->GetOutputSlot(k).SetTensorInfo(armnn::TensorInfo(splitOutShape,
4394 outputTensorInfo.GetDataType(),
4395 outputTensorInfo.GetQuantizationScale(),
4396 outputTensorInfo.GetQuantizationOffset()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01004397 layer->GetOutputSlot(k).Connect(reshapeLayer->GetInputSlot(0));
4398
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01004399 reshapeLayer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01004400
4401 uint32_t reshapedOutputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[k]);
4402 armnn::IOutputSlot* slot = &(reshapeLayer->GetOutputSlot(0));
4403 RegisterProducerOfTensor(subgraphIndex, reshapedOutputId, slot);
4404 }
Nina Drozd200e3802019-04-15 09:47:39 +01004405}
4406
Kevin May7d96b162021-02-03 17:38:41 +00004407void TfLiteParserImpl::ParseSplit(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd0324f482019-04-08 10:52:10 +01004408{
4409 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4410
Mike Kelly0d77ae12022-01-07 17:42:27 +00004411 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4412 const auto* options = operatorPtr->builtin_options.AsSplitOptions();
Nina Drozd0324f482019-04-08 10:52:10 +01004413
4414 const unsigned int numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
4415
Nina Drozd200e3802019-04-15 09:47:39 +01004416 // If number of splits cannot be inferred and is zero, throw ParseException.
4417 if(numSplits == 0)
4418 {
4419 throw ParseException("Number to splits must greater than zero.");
4420 }
4421
Nina Drozd0324f482019-04-08 10:52:10 +01004422 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4423 CHECK_VALID_SIZE(inputs.size(), 2);
4424 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4425 CHECK_VALID_SIZE(outputs.size(), numSplits);
4426
Mike Kelly377fb212023-01-10 15:55:28 +00004427 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
4428 armnn::TensorInfo axisTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Ryan OSheac229b3f2023-06-27 22:34:54 +01004429
4430 if (axisTensorInfo.GetNumElements() != 1)
4431 {
4432 throw ParseException(fmt::format("Axis tensor can only have 1 element {}",
4433 CHECK_LOCATION().AsString()));
4434 }
Nina Drozd0324f482019-04-08 10:52:10 +01004435
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01004436 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01004437 if (axisBufferPtr == nullptr)
4438 {
4439 throw ParseException(
4440 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
4441 CHECK_LOCATION().AsString()));
4442 }
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01004443
Matthew Sloyaned7fce42021-04-15 20:46:24 +01004444 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
4445 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
4446 int32_t axis = axisData[0];
4447
4448 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
4449 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
4450 {
4451 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
4452 // E.g. Rank 4 tensor can have axis in range [-4, 3)
4453 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
4454 throw ParseException(
4455 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
4456 axis,
4457 CHECK_LOCATION().AsString()));
4458 }
4459
4460 const unsigned int splitDim = armnnUtils::GetUnsignedAxis(inputTensorInfo.GetNumDimensions(), axis);
Nina Drozd0324f482019-04-08 10:52:10 +01004461
Nina Drozd0324f482019-04-08 10:52:10 +01004462 auto inputDimSize = inputTensorInfo.GetNumDimensions();
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01004463 if (inputDimSize > MaxNumOfTensorDimensions)
Nina Drozd0324f482019-04-08 10:52:10 +01004464 {
4465 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004466 fmt::format("The number of dimensions: {} for input tensors of the split op cannot be greater than {} {}",
4467 inputTensorInfo.GetNumDimensions(),
4468 MaxNumOfTensorDimensions,
4469 CHECK_LOCATION().AsString()));
Nina Drozd0324f482019-04-08 10:52:10 +01004470 }
4471
4472 std::vector<unsigned int> splitterDimSizes(inputDimSize);
4473
4474 // Add current input shape to splitterDimSizes
4475 for (unsigned int i = 0; i < inputDimSize; ++i)
4476 {
4477 splitterDimSizes[i] = inputTensorInfo.GetShape()[i];
4478 }
4479
4480 if (splitterDimSizes[splitDim] % numSplits != 0)
4481 {
4482 throw ParseException("Number of splits must evenly divide the dimension");
4483 }
4484 splitterDimSizes[splitDim] /= numSplits;
4485
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01004486 SplitterDescriptor splitDesc(numSplits, inputDimSize);
Nina Drozd0324f482019-04-08 10:52:10 +01004487 for (unsigned int j = 0; j < numSplits; ++j)
4488 {
4489 // Set the size of the views.
4490 for (unsigned int dimIdx = 0; dimIdx < splitterDimSizes.size(); ++dimIdx)
4491 {
4492 splitDesc.SetViewSize(j, dimIdx, splitterDimSizes[dimIdx]);
4493 }
4494 splitDesc.SetViewOriginCoord(j, splitDim, splitterDimSizes[splitDim] * j);
4495 }
Mike Kelly363b5722023-10-11 14:25:50 +01004496 if (axisTensorInfo.GetNumElements() == 1)
4497 {
4498 splitDesc.SetAxis(axis);
4499 }
James Ward58dec6b2020-09-11 17:32:44 +01004500 auto layerName = fmt::format("Split:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd0324f482019-04-08 10:52:10 +01004501 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01004502
4503 if (!layer)
4504 {
4505 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
4506 operatorIndex, CHECK_LOCATION().AsString()));
4507 }
Nina Drozd0324f482019-04-08 10:52:10 +01004508
4509 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01004510 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[1]});
Nina Drozd0324f482019-04-08 10:52:10 +01004511
Nina Drozd0324f482019-04-08 10:52:10 +01004512 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
4513 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01004514 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Francis Murtagh98d6b3d2019-10-21 10:52:54 +01004515 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
Nina Drozd0324f482019-04-08 10:52:10 +01004516 }
4517
4518 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4519 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
4520}
4521
Derek Lambertif0176992020-04-28 13:37:49 +01004522unsigned int ComputeWrappedIndex(int idx, unsigned int numDimsIn)
4523{
4524 int numDims = armnn::numeric_cast<int>(numDimsIn);
4525 int v = idx < 0 ? numDims + idx : idx;
Ryan OSheac229b3f2023-06-27 22:34:54 +01004526
4527 if (v < 0 || v > numDims)
4528 {
4529 throw ParseException(fmt::format("Unable to compute index {}", CHECK_LOCATION().AsString()));
4530 }
Derek Lambertif0176992020-04-28 13:37:49 +01004531
4532 return static_cast<unsigned int>(v);
4533}
4534
Kevin May7d96b162021-02-03 17:38:41 +00004535void TfLiteParserImpl::ParseSplitV(size_t subgraphIndex, size_t operatorIndex)
Derek Lambertif0176992020-04-28 13:37:49 +01004536{
4537 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4538
Mike Kelly0d77ae12022-01-07 17:42:27 +00004539 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4540 const auto* options = operatorPtr->builtin_options.AsSplitVOptions();
Derek Lambertif0176992020-04-28 13:37:49 +01004541
4542 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4543 CHECK_VALID_SIZE(inputs.size(), 3);
4544
4545 auto& inputTensor = inputs[0];
4546 auto& splitsTensor = inputs[1];
4547 auto& axisTensor = inputs[2];
4548
4549 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputTensor);
4550 armnn::TensorInfo splitsInfo = ToTensorInfo(splitsTensor);
4551 armnn::TensorInfo axisTensorInfo = ToTensorInfo(axisTensor);
Ryan OSheac229b3f2023-06-27 22:34:54 +01004552
4553 if (axisTensorInfo.GetNumElements() != 1)
4554 {
4555 throw ParseException(fmt::format("Axis tensor can only have 1 element {}",
4556 CHECK_LOCATION().AsString()));
4557 }
Derek Lambertif0176992020-04-28 13:37:49 +01004558
4559 // Inputs
4560 auto inputDimSize = inputTensorInfo.GetNumDimensions();
4561 if (inputDimSize > MaxNumOfTensorDimensions)
4562 {
4563 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004564 fmt::format("The number of dimensions: {} for input tensors of the "
4565 "SplitV op cannot be greater than {} {}",
4566 inputTensorInfo.GetNumDimensions(),
4567 MaxNumOfTensorDimensions,
4568 CHECK_LOCATION().AsString()));
Derek Lambertif0176992020-04-28 13:37:49 +01004569 }
4570
4571 // Get split axis
4572 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, axisTensor->buffer);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01004573 if (axisBufferPtr == nullptr)
4574 {
4575 throw ParseException(
4576 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
4577 CHECK_LOCATION().AsString()));
4578 }
4579
Derek Lambertif0176992020-04-28 13:37:49 +01004580 std::vector<int> axisData(axisTensorInfo.GetNumElements());
4581 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
Matthew Sloyaned7fce42021-04-15 20:46:24 +01004582 int32_t axis = axisData[0];
4583
4584 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
4585 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
4586 {
4587 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
4588 // E.g. Rank 4 tensor can have axis in range [-4, 3)
4589 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
4590 throw ParseException(
4591 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
4592 axis,
4593 CHECK_LOCATION().AsString()));
4594 }
4595 const unsigned int splitDim = ComputeWrappedIndex(axis, inputTensorInfo.GetNumDimensions());
Derek Lambertif0176992020-04-28 13:37:49 +01004596
Derek Lambertif0176992020-04-28 13:37:49 +01004597 // Set split sizes
Derek Lambertif0176992020-04-28 13:37:49 +01004598 CHECK_VALID_SIZE(splitsInfo.GetNumDimensions(), 1);
Ryan OShea86704732020-05-26 11:41:04 +01004599 unsigned int numSplits{0};
4600
4601 if(options)
Derek Lambertif0176992020-04-28 13:37:49 +01004602 {
4603 numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
Derek Lambertif0176992020-04-28 13:37:49 +01004604 }
4605 else
4606 {
Ryan OShea86704732020-05-26 11:41:04 +01004607 numSplits = splitsInfo.GetNumElements();
Derek Lambertif0176992020-04-28 13:37:49 +01004608 }
4609
4610 if (numSplits <=0)
4611 {
4612 throw ParseException("SplitV has invalid number of splits");
4613 }
4614
Jan Eilersc0761e92020-06-29 16:48:44 +01004615 std::vector<int> splitsData(numSplits);
Ryan OShea86704732020-05-26 11:41:04 +01004616 BufferRawPtr splitsBufferPtr = GetBuffer(m_Model, splitsTensor->buffer);
Jan Eilersc0761e92020-06-29 16:48:44 +01004617 ::memcpy(splitsData.data(), splitsBufferPtr->data.data(), splitsInfo.GetNumBytes());
Ryan OShea86704732020-05-26 11:41:04 +01004618
Jan Eilersc0761e92020-06-29 16:48:44 +01004619 unsigned int idx = 0;
Ryan OShea86704732020-05-26 11:41:04 +01004620 int numInferred{0};
4621 unsigned int inferIdx{0};
4622 int splitSum{0};
4623 for (auto split : splitsData)
4624 {
4625 if (split < 0)
4626 {
4627 numInferred++;
4628 inferIdx = idx;
4629 }
4630 else
4631 {
4632 splitSum += split;
4633 }
4634 idx++;
4635 }
4636 // Check for inferred Axis
4637 if (numInferred == 0)
4638 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01004639 if (splitSum != armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]))
Ryan OShea86704732020-05-26 11:41:04 +01004640 {
4641 throw ParseException("SplitV split_sizes does not sum to the dimension of value along split_dim.");
4642 }
4643 }
4644 else if (numInferred == 1)
4645 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01004646 splitsData[inferIdx] = armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]) - splitSum;
Ryan OShea86704732020-05-26 11:41:04 +01004647 }
4648 else
4649 {
4650 throw ParseException("Cannot infer split size for more than one split");
4651 }
4652
Derek Lambertif0176992020-04-28 13:37:49 +01004653 //Ouput size validation
4654 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4655 CHECK_VALID_SIZE(outputs.size(), numSplits);
4656
4657 // Setup Armnn descriptor
4658 SplitterDescriptor splitDesc(numSplits, inputDimSize);
4659 unsigned int accumSplit = 0;
4660 for (unsigned int j = 0; j < numSplits; ++j)
4661 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01004662 unsigned int splitSize = armnn::numeric_cast<unsigned int>(splitsData[j]);
Derek Lambertif0176992020-04-28 13:37:49 +01004663
4664 // Set the size of the views.
4665 for (unsigned int dimIdx = 0; dimIdx < inputTensorInfo.GetNumDimensions(); ++dimIdx)
4666 {
4667 unsigned int dimSize = inputTensorInfo.GetShape()[dimIdx];
4668 if (dimIdx == splitDim)
4669 {
4670 dimSize = splitSize;
4671 }
4672 splitDesc.SetViewSize(j, dimIdx, dimSize);
4673 }
4674
4675 splitDesc.SetViewOriginCoord(j, splitDim, accumSplit);
4676 accumSplit += splitSize;
4677 }
Mike Kelly363b5722023-10-11 14:25:50 +01004678 splitDesc.SetAxis(axis);
Derek Lambertif0176992020-04-28 13:37:49 +01004679
James Ward58dec6b2020-09-11 17:32:44 +01004680 auto layerName = fmt::format("SplitV:{}:{}", subgraphIndex, operatorIndex);
Derek Lambertif0176992020-04-28 13:37:49 +01004681 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01004682
4683 if (!layer)
4684 {
4685 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
4686 operatorIndex, CHECK_LOCATION().AsString()));
4687 }
Derek Lambertif0176992020-04-28 13:37:49 +01004688
4689 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4690 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4691
4692 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
4693 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01004694 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Derek Lambertif0176992020-04-28 13:37:49 +01004695 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
4696 }
4697
4698 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4699 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
4700}
4701
Matthew Sloyan28f177c2021-04-09 14:38:52 +01004702void TfLiteParserImpl::ParseArgMin(size_t subgraphIndex, size_t operatorIndex)
4703{
4704 ParseArgMinMax(subgraphIndex, operatorIndex, armnn::ArgMinMaxFunction::Min);
4705}
4706
Kevin May7d96b162021-02-03 17:38:41 +00004707void TfLiteParserImpl::ParseArgMax(size_t subgraphIndex, size_t operatorIndex)
Inki Daed4619e22020-09-10 15:33:54 +09004708{
Matthew Sloyan28f177c2021-04-09 14:38:52 +01004709 ParseArgMinMax(subgraphIndex, operatorIndex, armnn::ArgMinMaxFunction::Max);
4710}
4711
4712void TfLiteParserImpl::ParseArgMinMax(size_t subgraphIndex, size_t operatorIndex, ArgMinMaxFunction argMinMaxFunction)
4713{
Inki Daed4619e22020-09-10 15:33:54 +09004714 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4715 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4716 CHECK_VALID_SIZE(inputs.size(), 2);
4717
4718 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4719 CHECK_VALID_SIZE(outputs.size(), 1);
4720
Mike Kelly377fb212023-01-10 15:55:28 +00004721 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
4722 armnn::TensorInfo axisTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Inki Daed4619e22020-09-10 15:33:54 +09004723 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
Ryan OSheac229b3f2023-06-27 22:34:54 +01004724
4725 if (axisTensorInfo.GetNumElements() != 1)
4726 {
4727 throw ParseException(fmt::format("Axis tensor can only have 1 element {}",
4728 CHECK_LOCATION().AsString()));
4729 }
Matthew Sloyan28f177c2021-04-09 14:38:52 +01004730
4731 // Check if output tensor type is Signed32 or Signed64
Mike Kelly1f140f72021-04-06 12:25:55 +01004732 if (outputTensorInfo.GetDataType() != armnn::DataType::Signed32 &&
4733 outputTensorInfo.GetDataType() != armnn::DataType::Signed64)
4734 {
4735 throw ParseException(
4736 fmt::format(
4737 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
4738 CHECK_LOCATION().AsString()));
4739 }
Matthew Sloyan28f177c2021-04-09 14:38:52 +01004740
4741 // Get const axis value from model and set it to descriptor.
4742 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
4743 if (axisBufferPtr == nullptr)
4744 {
4745 throw ParseException(
4746 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
4747 CHECK_LOCATION().AsString()));
4748 }
4749
4750 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
4751 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
4752 int32_t axis = axisData.front();
4753
4754 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
4755 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
4756 {
4757 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
4758 // E.g. Rank 4 tensor can have axis in range [-4, 3)
4759 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
4760 throw ParseException(
4761 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
4762 axis,
4763 CHECK_LOCATION().AsString()));
4764 }
4765
4766 ArgMinMaxDescriptor desc;
4767 desc.m_Axis = axis;
4768 desc.m_Function = argMinMaxFunction;
4769
4770 // Register a ArgMin/ArgMax layer.
4771 auto layerName = argMinMaxFunction == ArgMinMaxFunction::Max ? "ArgMax:{}:{}" : "ArgMin:{}:{}";
4772 auto layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
4773 IConnectableLayer *layer = m_Network->AddArgMinMaxLayer(desc, layerNameFormatted.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01004774
4775 if (!layer)
4776 {
4777 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
4778 operatorIndex, CHECK_LOCATION().AsString()));
4779 }
4780
Mike Kelly377fb212023-01-10 15:55:28 +00004781 outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Inki Daed4619e22020-09-10 15:33:54 +09004782 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4783
4784 // Register input tensor to the layer.
4785 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4786 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4787
4788 // Register output tensor to the layer.
4789 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4790 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
4791}
4792
Kevin May7d96b162021-02-03 17:38:41 +00004793void TfLiteParserImpl::ParseGather(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00004794{
4795 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4796
Kevin May7d96b162021-02-03 17:38:41 +00004797 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004798 CHECK_VALID_SIZE(inputs.size(), 2);
Kevin May7d96b162021-02-03 17:38:41 +00004799 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004800 CHECK_VALID_SIZE(outputs.size(), 1);
4801
Mike Kelly377fb212023-01-10 15:55:28 +00004802 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
4803 armnn::TensorInfo indicesTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
4804 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
Sadik Armagan26868492021-01-22 14:25:31 +00004805
4806 armnn::GatherDescriptor gatherDescriptor;
4807
Mike Kelly0d77ae12022-01-07 17:42:27 +00004808 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4809 const auto* options = operatorPtr->builtin_options.AsGatherOptions();
Sadik Armagan26868492021-01-22 14:25:31 +00004810 auto axis = options->axis;
4811
Mike Kelly377fb212023-01-10 15:55:28 +00004812 auto layerName = fmt::format("Gather:{}:{}", subgraphIndex, operatorIndex);
4813
Sadik Armagan26868492021-01-22 14:25:31 +00004814 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
4815 auto indicesDimensions = indicesTensorInfo.GetNumDimensions();
4816 auto outputDimensions = outputTensorInfo.GetNumDimensions();
4817 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
4818 {
4819 throw ParseException(
4820 fmt::format("Operation has invalid axis: {} It is out of bounds [ -{}, {} ) {}",
4821 axis,
4822 inputDimensions, inputDimensions,
4823 CHECK_LOCATION().AsString()));
4824 }
4825 if (outputDimensions != static_cast<unsigned int>(inputDimensions) + indicesDimensions - 1)
4826 {
4827 throw ParseException(
4828 fmt::format("Operation has invalid output dimensions: {} Output must be an ({} + {} - 1) -D tensor {}",
4829 outputDimensions,
4830 inputDimensions, indicesDimensions,
4831 CHECK_LOCATION().AsString()));
4832 }
4833
4834 gatherDescriptor.m_Axis = axis;
4835
Sadik Armagan26868492021-01-22 14:25:31 +00004836 IConnectableLayer* layer = m_Network->AddGatherLayer(gatherDescriptor, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01004837
4838 if (!layer)
4839 {
4840 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
4841 operatorIndex, CHECK_LOCATION().AsString()));
4842 }
4843
Mike Kelly377fb212023-01-10 15:55:28 +00004844 outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Sadik Armagan26868492021-01-22 14:25:31 +00004845 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4846
4847 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4848 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
4849
4850 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4851 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4852}
4853
Teresa Charlin91a53ea2022-04-25 15:47:29 +01004854void TfLiteParserImpl::ParseGatherNd(size_t subgraphIndex, size_t operatorIndex)
4855{
4856 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4857
4858 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4859 CHECK_VALID_SIZE(inputs.size(), 2);
4860 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4861 CHECK_VALID_SIZE(outputs.size(), 1);
4862
Mike Kelly377fb212023-01-10 15:55:28 +00004863 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
4864 armnn::TensorInfo indicesTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Teresa Charlin91a53ea2022-04-25 15:47:29 +01004865
4866 auto layerName = fmt::format("GatherNd:{}:{}", subgraphIndex, operatorIndex);
4867 IConnectableLayer* layer = m_Network->AddGatherNdLayer(layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01004868
4869 if (!layer)
4870 {
4871 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
4872 operatorIndex, CHECK_LOCATION().AsString()));
4873 }
4874
Mike Kelly377fb212023-01-10 15:55:28 +00004875 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Teresa Charlin91a53ea2022-04-25 15:47:29 +01004876 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4877
4878 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4879 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
4880
4881 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4882 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4883}
4884
Kevin May7d96b162021-02-03 17:38:41 +00004885void TfLiteParserImpl::ParseDepthToSpace(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00004886{
4887 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4888
Kevin May7d96b162021-02-03 17:38:41 +00004889 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004890 CHECK_VALID_SIZE(inputs.size(), 1);
Kevin May7d96b162021-02-03 17:38:41 +00004891 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004892 CHECK_VALID_SIZE(outputs.size(), 1);
4893
4894 armnn::DepthToSpaceDescriptor descriptor;
4895
Mike Kelly0d77ae12022-01-07 17:42:27 +00004896 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4897 const auto* options = operatorPtr->builtin_options.AsDepthToSpaceOptions();
Sadik Armagan26868492021-01-22 14:25:31 +00004898 auto blockSize = options->block_size;
4899 if (blockSize < 2)
4900 {
4901 throw ParseException(
4902 fmt::format("Operation has invalid block size: {} Block size should be >= 2 {}",
4903 blockSize,
4904 CHECK_LOCATION().AsString()));
4905 }
4906 descriptor.m_BlockSize = armnn::numeric_cast<uint32_t>(blockSize);
4907
4908 auto layerName = fmt::format("DepthToSpace:{}:{}", subgraphIndex, operatorIndex);
4909 IConnectableLayer* layer = m_Network->AddDepthToSpaceLayer(descriptor, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01004910
4911 if (!layer)
4912 {
4913 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
4914 operatorIndex, CHECK_LOCATION().AsString()));
4915 }
4916
Mike Kelly377fb212023-01-10 15:55:28 +00004917 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Sadik Armagan26868492021-01-22 14:25:31 +00004918 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4919
4920 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4921 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4922
4923 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4924 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4925}
4926
Kevin May7d96b162021-02-03 17:38:41 +00004927void TfLiteParserImpl::ParseSum(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004928{
Sadik Armagana2747482021-02-09 10:28:54 +00004929 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Sum);
4930}
4931
Teresa Charlin4e3e8312021-08-05 12:34:37 +01004932void TfLiteParserImpl::ParseReduceProd(size_t subgraphIndex, size_t operatorIndex)
4933{
4934 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Prod);
4935}
4936
Sadik Armagana2747482021-02-09 10:28:54 +00004937void TfLiteParserImpl::ParseReduceMax(size_t subgraphIndex, size_t operatorIndex)
4938{
4939 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Max);
4940}
4941
4942void TfLiteParserImpl::ParseReduceMin(size_t subgraphIndex, size_t operatorIndex)
4943{
4944 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Min);
4945}
4946
4947void TfLiteParserImpl::ParseReduce(size_t subgraphIndex, size_t operatorIndex, ReduceOperation reduceOperation)
4948{
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004949 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4950
Mike Kelly0d77ae12022-01-07 17:42:27 +00004951 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4952 const auto* options = operatorPtr->builtin_options.AsReducerOptions();
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004953
4954 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4955 CHECK_VALID_SIZE(inputs.size(), 2);
4956
4957 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4958 CHECK_VALID_SIZE(outputs.size(), 1);
4959
Sadik Armagana2747482021-02-09 10:28:54 +00004960 auto layerName = fmt::format("Reduce:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004961
Mike Kelly377fb212023-01-10 15:55:28 +00004962 armnn::TensorInfo inputTensorInfo0 = InputTensorInfo(subgraphIndex, operatorIndex, 0);
4963 armnn::TensorInfo inputTensorInfo1 = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004964
4965 ReduceDescriptor desc;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004966 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
4967 // Get const axis value from model and set it to descriptor.
4968 if (axisBufferPtr != nullptr)
4969 {
Sadik Armagan49bdb792021-02-11 13:57:07 +00004970 std::vector<int32_t> axisData(inputTensorInfo1.GetNumElements());
4971 ::memcpy(axisData.data(), axisBufferPtr->data.data(), inputTensorInfo1.GetNumBytes());
4972
4973 // Convert the axis to unsigned int and remove duplicates.
4974 auto rank = static_cast<int32_t>(inputTensorInfo0.GetNumDimensions());
4975 std::set<unsigned int> uniqueAxis;
4976 std::transform(axisData.begin(),
4977 axisData.end(),
4978 std::inserter(uniqueAxis, uniqueAxis.begin()),
4979 [rank](int i)->unsigned int{
4980 return static_cast<uint32_t>(((i + rank) % rank)); });
4981 desc.m_vAxis.assign(uniqueAxis.begin(), uniqueAxis.end());
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004982 }
Sadik Armagana2747482021-02-09 10:28:54 +00004983 else
4984 {
4985 for (uint32_t i = 0; i < inputTensorInfo0.GetNumDimensions(); ++i)
4986 {
4987 desc.m_vAxis.push_back(i);
4988 }
4989 }
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004990
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004991 desc.m_KeepDims = options->keep_dims;
Sadik Armagana2747482021-02-09 10:28:54 +00004992 desc.m_ReduceOperation = reduceOperation;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004993
4994 // Register a new layer object, Sum.
Mike Kelly0d77ae12022-01-07 17:42:27 +00004995 IConnectableLayer* layer = m_Network->AddReduceLayer(desc, layerName.c_str());
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004996
Mike Kelly377fb212023-01-10 15:55:28 +00004997 armnn::TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004998 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4999
5000 // Register input tensor to the layer.
5001 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
5002 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
5003
5004 // Register output tensor to the layer.
5005 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
5006 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
5007}
5008
Mike Kelly31dce2b2021-09-01 21:22:37 +01005009void TfLiteParserImpl::ParseLocalResponseNormalization(size_t subgraphIndex, size_t operatorIndex)
5010{
5011 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
5012
5013 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
5014 CHECK_VALID_SIZE(inputs.size(), 1);
5015
5016 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
5017 CHECK_VALID_SIZE(outputs.size(), 1);
5018
5019 auto layerName = fmt::format("LRN:{}:{}", subgraphIndex, operatorIndex);
5020 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
5021
Mike Kelly377fb212023-01-10 15:55:28 +00005022 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
Mike Kelly31dce2b2021-09-01 21:22:37 +01005023
5024 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
5025 const auto* options = operatorPtr->builtin_options.AsLocalResponseNormalizationOptions();
5026
5027 armnn::NormalizationDescriptor descriptor;
5028 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
5029 descriptor.m_NormChannelType = armnn::NormalizationAlgorithmChannel::Across;
5030 descriptor.m_NormMethodType = armnn::NormalizationAlgorithmMethod::LocalBrightness;
5031 descriptor.m_NormSize = static_cast<uint32_t>(options->radius);
5032 descriptor.m_K = options->bias;
5033 descriptor.m_Alpha = options->alpha;
5034 descriptor.m_Beta = options->beta;
5035
5036 // ArmNN expects normSize to be the full size of the normalization
5037 // window rather than the radius as in TfLite.
5038 descriptor.m_NormSize = 1 + (2 * descriptor.m_NormSize);
5039
5040 IConnectableLayer* layer = m_Network->AddNormalizationLayer(descriptor, layerNameFormatted.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01005041
5042 if (!layer)
5043 {
5044 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
5045 operatorIndex, CHECK_LOCATION().AsString()));
5046 }
Mike Kelly31dce2b2021-09-01 21:22:37 +01005047
Mike Kelly377fb212023-01-10 15:55:28 +00005048 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Mike Kelly31dce2b2021-09-01 21:22:37 +01005049 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
5050
5051 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
5052 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
5053
5054 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
5055 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
5056}
5057
Teresa Charlin28aa6692022-07-12 11:18:44 +01005058void TfLiteParserImpl::ParseAbs(size_t subgraphIndex, size_t operatorIndex)
5059{
5060 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Abs);
5061}
5062
Teresa Charlin93f0ad02023-03-23 15:28:02 +00005063void TfLiteParserImpl::ParseCeil(size_t subgraphIndex, size_t operatorIndex)
5064{
5065 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Ceil);
5066}
5067
Teresa Charlin28aa6692022-07-12 11:18:44 +01005068void TfLiteParserImpl::ParseExp(size_t subgraphIndex, size_t operatorIndex)
5069{
5070 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Exp);
5071}
5072
5073void TfLiteParserImpl::ParseLog(size_t subgraphIndex, size_t operatorIndex)
5074{
5075 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Log);
5076}
5077
Matthew Sloyaned7fce42021-04-15 20:46:24 +01005078void TfLiteParserImpl::ParseLogicalNot(size_t subgraphIndex, size_t operatorIndex)
5079{
5080 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::LogicalNot);
5081}
5082
5083void TfLiteParserImpl::ParseNeg(size_t subgraphIndex, size_t operatorIndex)
5084{
5085 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Neg);
5086}
5087
John Mcloughlin0ec00872023-05-15 17:03:49 +01005088void TfLiteParserImpl::ParsePower(size_t subgraphIndex, size_t operatorIndex)
5089{
5090 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
5091
5092 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
5093 CHECK_VALID_SIZE(inputs.size(), 2);
5094
5095 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
5096 CHECK_VALID_SIZE(outputs.size(), 1);
5097
5098 auto layerName = fmt::format("Power:{}:{}", subgraphIndex, operatorIndex);
5099
5100 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
5101 TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
5102 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
5103
5104 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::Power, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01005105
5106 if (!layer)
5107 {
5108 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
5109 operatorIndex, CHECK_LOCATION().AsString()));
5110 }
John Mcloughlin0ec00872023-05-15 17:03:49 +01005111
5112 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
5113 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
5114 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
5115
5116 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
5117 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
5118
5119 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
5120 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
5121}
5122
Matthew Sloyaned7fce42021-04-15 20:46:24 +01005123void TfLiteParserImpl::ParseRsqrt(size_t subgraphIndex, size_t operatorIndex)
5124{
5125 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Rsqrt);
5126}
5127
Teresa Charlin28aa6692022-07-12 11:18:44 +01005128void TfLiteParserImpl::ParseSin(size_t subgraphIndex, size_t operatorIndex)
5129{
5130 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Sin);
5131}
5132
Teresa Charlinf0fce5b2022-05-04 17:24:43 +01005133void TfLiteParserImpl::ParseSqrt(size_t subgraphIndex, size_t operatorIndex)
5134{
5135 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Sqrt);
5136}
5137
Teresa Charlin6963b332023-07-11 11:35:41 +01005138void TfLiteParserImpl::ParseSquare(size_t subgraphIndex, size_t operatorIndex)
5139{
5140 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
5141
5142 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
5143 CHECK_VALID_SIZE(inputs.size(), 1);
5144
5145 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
5146 CHECK_VALID_SIZE(outputs.size(), 1);
5147
5148 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
5149
5150 auto layerName = fmt::format("Square:{}:{}", subgraphIndex, operatorIndex);
5151 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::Mul, layerName.c_str());
5152 ARMNN_ASSERT(layer != nullptr);
5153
5154 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 0});
5155 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
5156 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
5157
5158 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
5159 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[0]});
5160
5161 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
5162 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
5163}
5164
John Mcloughlin0ec00872023-05-15 17:03:49 +01005165void TfLiteParserImpl::ParseSquaredDifference(size_t subgraphIndex, size_t operatorIndex)
5166{
5167 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
5168
5169 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
5170 CHECK_VALID_SIZE(inputs.size(), 2);
5171
5172 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
5173 CHECK_VALID_SIZE(outputs.size(), 1);
5174
5175 auto layerName = fmt::format("SquaredDifference:{}:{}", subgraphIndex, operatorIndex);
5176
5177 TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
5178 TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
John Mcloughlin0ec00872023-05-15 17:03:49 +01005179
5180 IConnectableLayer* layer = m_Network->AddElementwiseBinaryLayer(BinaryOperation::SqDiff, layerName.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01005181
5182 if (!layer)
5183 {
5184 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
5185 operatorIndex, CHECK_LOCATION().AsString()));
5186 }
John Mcloughlin0ec00872023-05-15 17:03:49 +01005187
5188 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
John Mcloughlin0ec00872023-05-15 17:03:49 +01005189 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
5190
5191 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
5192 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
5193
5194 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
5195 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
5196}
5197
Matthew Sloyaned7fce42021-04-15 20:46:24 +01005198void TfLiteParserImpl::ParseElementwiseUnary(size_t subgraphIndex, size_t operatorIndex, UnaryOperation unaryOperation)
5199{
5200 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
5201
5202 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
5203 CHECK_VALID_SIZE(inputs.size(), 1);
5204
5205 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
5206 CHECK_VALID_SIZE(outputs.size(), 1);
5207
5208 std::string layerName = std::string(GetUnaryOperationAsCString(unaryOperation)) + ":{}:{}";
5209 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
5210
5211 ElementwiseUnaryDescriptor desc;
5212 desc.m_Operation = unaryOperation;
5213 IConnectableLayer* layer = m_Network->AddElementwiseUnaryLayer(desc, layerNameFormatted.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01005214
5215 if (!layer)
5216 {
5217 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
5218 operatorIndex, CHECK_LOCATION().AsString()));
5219 }
Matthew Sloyaned7fce42021-04-15 20:46:24 +01005220
Mike Kelly377fb212023-01-10 15:55:28 +00005221 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0});
Matthew Sloyaned7fce42021-04-15 20:46:24 +01005222 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
5223
5224 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
5225 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
5226
5227 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
5228 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
5229}
5230
Bruno Goncalves2d0eb862021-07-11 14:10:15 -03005231void TfLiteParserImpl::ParseEqual(size_t subgraphIndex, size_t operatorIndex)
5232{
5233 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::Equal);
5234}
5235
5236void TfLiteParserImpl::ParseNotEqual(size_t subgraphIndex, size_t operatorIndex)
5237{
5238 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::NotEqual);
5239}
5240
5241void TfLiteParserImpl::ParseGreater(size_t subgraphIndex, size_t operatorIndex)
5242{
5243 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::Greater);
5244}
5245
5246void TfLiteParserImpl::ParseGreaterOrEqual(size_t subgraphIndex, size_t operatorIndex)
5247{
5248 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::GreaterOrEqual);
5249}
5250
5251void TfLiteParserImpl::ParseLess(size_t subgraphIndex, size_t operatorIndex)
5252{
5253 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::Less);
5254}
5255
5256void TfLiteParserImpl::ParseLessOrEqual(size_t subgraphIndex, size_t operatorIndex)
5257{
5258 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::LessOrEqual);
5259}
5260
5261void TfLiteParserImpl::ParseComparison(size_t subgraphIndex, size_t operatorIndex,
5262 ComparisonOperation comparisonOperation)
5263{
5264 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
5265
5266 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
5267 CHECK_VALID_SIZE(inputs.size(), 2);
5268
5269 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
5270 CHECK_VALID_SIZE(outputs.size(), 1);
5271
5272 auto layerName = std::string(GetComparisonOperationAsCString(comparisonOperation)) + ":{}:{}";
5273 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
5274
Mike Kelly377fb212023-01-10 15:55:28 +00005275 armnn::TensorInfo inputTensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 0);
5276 armnn::TensorInfo input1TensorInfo = InputTensorInfo(subgraphIndex, operatorIndex, 1);
Bruno Goncalves2d0eb862021-07-11 14:10:15 -03005277 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerNameFormatted, "Input 0", "Input 1");
5278
5279 ComparisonDescriptor desc;
5280 desc.m_Operation = comparisonOperation;
5281 IConnectableLayer* layer = m_Network->AddComparisonLayer(desc, layerNameFormatted.c_str());
Ryan OSheac229b3f2023-06-27 22:34:54 +01005282
5283 if (!layer)
5284 {
5285 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
5286 operatorIndex, CHECK_LOCATION().AsString()));
5287 }
Bruno Goncalves2d0eb862021-07-11 14:10:15 -03005288
Mike Kelly377fb212023-01-10 15:55:28 +00005289 TensorInfo outputTensorInfo = OutputTensorInfoFromInputs(subgraphIndex, operatorIndex, layer, 0, {0, 1});
Bruno Goncalves2d0eb862021-07-11 14:10:15 -03005290 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
5291
5292 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
5293 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
5294
5295 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
5296 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
5297}
5298
Mike Kelly04d82292023-01-19 18:29:40 +00005299armnn::IConnectableLayer* TfLiteParserImpl::AddReshapeLayer(armnn::IConnectableLayer* layer,
5300 unsigned int outputSlot,
5301 std::string reshapeLayerName,
5302 armnn::TensorInfo outputShape)
5303{
5304 ReshapeDescriptor desc;
5305 desc.m_TargetShape = outputShape.GetShape();
5306
5307 IConnectableLayer* reshapeLayer =
5308 m_Network->AddReshapeLayer(desc, reshapeLayerName.c_str());
5309
5310 auto & prevOutputSlot = layer->GetOutputSlot(outputSlot);
5311 prevOutputSlot.Connect(reshapeLayer->GetInputSlot(0));
5312 reshapeLayer->GetOutputSlot(0).SetTensorInfo(outputShape);
5313 return reshapeLayer;
5314}
5315
Kevin May7d96b162021-02-03 17:38:41 +00005316armnn::IConnectableLayer* TfLiteParserImpl::AddFusedActivationLayer(armnn::IConnectableLayer* prevLayer,
5317 unsigned int outputSlot,
5318 tflite::ActivationFunctionType activationType)
telsoa01c577f2c2018-08-31 09:22:23 +01005319{
5320 ActivationDescriptor activationDesc;
5321 std::string layerName = prevLayer->GetName();
5322
5323 switch(activationType)
5324 {
5325 case tflite::ActivationFunctionType_NONE:
5326 {
5327 // this is a no-op: return previous layer
5328 return prevLayer;
5329 }
5330 case tflite::ActivationFunctionType_RELU:
5331 {
5332 activationDesc.m_Function = ActivationFunction::ReLu;
5333 layerName += ":RELU";
5334 break;
5335 }
5336 case tflite::ActivationFunctionType_RELU6:
5337 {
5338 activationDesc.m_Function = ActivationFunction::BoundedReLu;
5339 activationDesc.m_A = 6.0f;
5340 activationDesc.m_B = 0.0f;
5341 layerName += ":RELU6";
5342 break;
5343 }
5344 case tflite::ActivationFunctionType_TANH:
5345 {
5346 activationDesc.m_Function = ActivationFunction::TanH;
5347 activationDesc.m_A = 1.0f;
5348 activationDesc.m_B = 1.0f;
5349 layerName += ":TANH";
5350 break;
5351 }
5352
5353 // I only put these here as a reminder what others we could support
5354 case tflite::ActivationFunctionType_RELU_N1_TO_1:
5355 case tflite::ActivationFunctionType_SIGN_BIT:
5356 default:
5357 {
5358 throw ParseException(
Mike Kelly377fb212023-01-10 15:55:28 +00005359 fmt::format("TfLite parser doesn't support fused activation: "
James Ward58dec6b2020-09-11 17:32:44 +01005360 "{}/{} {} ",
5361 activationType,
5362 tflite::EnumNameActivationFunctionType(activationType),
5363 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01005364
5365 }
5366 }
5367
5368 IConnectableLayer* activationLayer =
5369 m_Network->AddActivationLayer(activationDesc, layerName.c_str());
5370
5371 auto & prevOutputSlot = prevLayer->GetOutputSlot(outputSlot);
5372 prevOutputSlot.Connect(activationLayer->GetInputSlot(0));
5373 activationLayer->GetOutputSlot(0).SetTensorInfo(prevOutputSlot.GetTensorInfo());
5374 return activationLayer;
5375}
5376
Teresa Charlincdbd40b2022-02-25 13:21:55 +00005377armnn::IConnectableLayer* TfLiteParserImpl::AddFusedFloorLayer(armnn::IConnectableLayer* prevLayer,
5378 unsigned int outputSlot)
5379{
Teresa Charlin725728e2022-05-05 13:33:33 +01005380
5381 auto& prevOutputSlot = prevLayer->GetOutputSlot(outputSlot);
5382 DataType dataType = prevOutputSlot.GetTensorInfo().GetDataType();
5383
5384 if (dataType == DataType::Signed32)
5385 {
5386 return prevLayer;
5387 }
5388
Teresa Charlincdbd40b2022-02-25 13:21:55 +00005389 std::string layerName = prevLayer->GetName();
5390 IConnectableLayer* floorLayer = m_Network->AddFloorLayer(layerName.c_str());
5391
Teresa Charlincdbd40b2022-02-25 13:21:55 +00005392 prevOutputSlot.Connect(floorLayer->GetInputSlot(0));
5393 floorLayer->GetOutputSlot(0).SetTensorInfo(prevOutputSlot.GetTensorInfo());
Teresa Charlin725728e2022-05-05 13:33:33 +01005394
Teresa Charlincdbd40b2022-02-25 13:21:55 +00005395 return floorLayer;
5396}
5397
Mike Kelly0d77ae12022-01-07 17:42:27 +00005398TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromFile(const char* fileName)
telsoa01c577f2c2018-08-31 09:22:23 +01005399{
5400 if (fileName == nullptr)
5401 {
James Ward58dec6b2020-09-11 17:32:44 +01005402 throw InvalidArgumentException(fmt::format("Invalid (null) file name {}",
telsoa01c577f2c2018-08-31 09:22:23 +01005403 CHECK_LOCATION().AsString()));
5404 }
Francis Murtagh532a29d2020-06-29 11:50:01 +01005405 std::error_code errorCode;
5406 fs::path pathToFile(fileName);
5407 if (!fs::exists(pathToFile, errorCode))
telsoa01c577f2c2018-08-31 09:22:23 +01005408 {
James Ward58dec6b2020-09-11 17:32:44 +01005409 //fmt::format() could not be used here (format error)
5410 std::stringstream msg;
5411 msg << "Cannot find the file (" << fileName << ") errorCode: " << errorCode
5412 << " " << CHECK_LOCATION().AsString();
James Ward58dec6b2020-09-11 17:32:44 +01005413 throw FileNotFoundException(msg.str());
telsoa01c577f2c2018-08-31 09:22:23 +01005414 }
Colm Donelan0dfb2652023-06-22 10:19:17 +01005415 if (!fs::is_regular_file(pathToFile))
5416 {
5417 // Exclude non regular files.
5418 throw InvalidArgumentException(fmt::format("File \"{}\" is not a regular file and cannot be loaded.",
5419 pathToFile.c_str()));
5420 }
5421
telsoa01c577f2c2018-08-31 09:22:23 +01005422 std::ifstream file(fileName, std::ios::binary);
5423 std::string fileContent((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
5424 return LoadModelFromBinary(reinterpret_cast<const uint8_t *>(fileContent.c_str()),
5425 fileContent.size());
5426}
5427
Mike Kelly0d77ae12022-01-07 17:42:27 +00005428TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromBinary(const uint8_t* binaryContent, size_t len)
telsoa01c577f2c2018-08-31 09:22:23 +01005429{
5430 if (binaryContent == nullptr)
5431 {
James Ward58dec6b2020-09-11 17:32:44 +01005432 throw InvalidArgumentException(fmt::format("Invalid (null) binary content {}",
telsoa01c577f2c2018-08-31 09:22:23 +01005433 CHECK_LOCATION().AsString()));
5434 }
5435 flatbuffers::Verifier verifier(binaryContent, len);
5436 if (verifier.VerifyBuffer<tflite::Model>() == false)
5437 {
5438 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01005439 fmt::format("Buffer doesn't conform to the expected Tensorflow Lite "
5440 "flatbuffers format. size:{} {}",
5441 len,
5442 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01005443 }
5444 return tflite::UnPackModel(binaryContent);
5445}
5446
Mike Kelly0d77ae12022-01-07 17:42:27 +00005447TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetInputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00005448 size_t subgraphIndex,
5449 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005450{
5451 CHECK_MODEL(model, subgraphIndex, operatorIndex);
5452
Mike Kelly0d77ae12022-01-07 17:42:27 +00005453 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
5454 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01005455
5456 size_t inputCount = operatorPtr->inputs.size();
mathad01c21025d2021-04-26 10:09:37 +01005457 TensorRawPtrVector result;
Mike Kelly0d77ae12022-01-07 17:42:27 +00005458 for (size_t i = 0; i < inputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01005459 {
mathad01c21025d2021-04-26 10:09:37 +01005460 // If the input location is -1 then assume input is turned off.
5461 if (operatorPtr->inputs[i] == -1)
5462 {
5463 continue;
5464 }
5465 else
5466 {
5467 uint32_t inputId = CHECKED_NON_NEGATIVE(operatorPtr->inputs[i]);
5468 result.push_back(subgraphPtr->tensors[inputId].get());
5469 }
telsoa01c577f2c2018-08-31 09:22:23 +01005470 }
5471 return result;
5472}
5473
Mike Kelly0d77ae12022-01-07 17:42:27 +00005474TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetOutputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00005475 size_t subgraphIndex,
5476 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005477{
5478 CHECK_MODEL(model, subgraphIndex, operatorIndex);
5479
Mike Kelly0d77ae12022-01-07 17:42:27 +00005480 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
5481 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01005482
5483 size_t outputCount = operatorPtr->outputs.size();
5484 TensorRawPtrVector result(outputCount);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005485 for (size_t i = 0; i < outputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01005486 {
5487 uint32_t outputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[i]);
5488 CHECK_TENSOR(model, subgraphIndex, outputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01005489 result[i] = subgraphPtr->tensors[outputId].get();
telsoa01c577f2c2018-08-31 09:22:23 +01005490 }
5491 return result;
5492}
5493
Mike Kelly0d77ae12022-01-07 17:42:27 +00005494TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphInputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00005495 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005496{
5497 CHECK_SUBGRAPH(model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005498 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01005499
Derek Lambertiff05cc52019-04-26 13:05:17 +01005500 size_t inputCount = subgraphPtr->inputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01005501 TensorIdRawPtrVector result(inputCount);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005502 for (size_t i = 0; i < inputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01005503 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01005504 uint32_t inputId = CHECKED_NON_NEGATIVE(subgraphPtr->inputs[i]);
telsoa01c577f2c2018-08-31 09:22:23 +01005505 CHECK_TENSOR(model, subgraphIndex, inputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01005506 result[i] = std::make_pair(inputId, subgraphPtr->tensors[inputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01005507 }
5508 return result;
5509}
5510
Mike Kelly0d77ae12022-01-07 17:42:27 +00005511TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphOutputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00005512 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005513{
5514 CHECK_SUBGRAPH(model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005515 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01005516
Derek Lambertiff05cc52019-04-26 13:05:17 +01005517 size_t outputCount = subgraphPtr->outputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01005518 TensorIdRawPtrVector result(outputCount);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005519 for (size_t i = 0; i < outputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01005520 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01005521 uint32_t outputId = CHECKED_NON_NEGATIVE(subgraphPtr->outputs[i]);
5522 result[i] = std::make_pair(outputId, subgraphPtr->tensors[outputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01005523 }
5524 return result;
5525}
5526
Kevin May7d96b162021-02-03 17:38:41 +00005527std::vector<int32_t>& TfLiteParserImpl::GetInputTensorIds(const ModelPtr& model,
5528 size_t subgraphIndex,
5529 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005530{
5531 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005532 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
5533 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01005534 return operatorPtr->inputs;
5535}
5536
Kevin May7d96b162021-02-03 17:38:41 +00005537std::vector<int32_t>& TfLiteParserImpl::GetOutputTensorIds(const ModelPtr& model,
5538 size_t subgraphIndex,
5539 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005540{
5541 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005542 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
5543 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01005544 return operatorPtr->outputs;
5545}
5546
Kevin May7d96b162021-02-03 17:38:41 +00005547void TfLiteParserImpl::RegisterInputSlots(size_t subgraphIndex,
5548 size_t operatorIndex,
5549 IConnectableLayer* layer,
Finn Williamsd4fa5452021-03-01 12:31:41 +00005550 const std::vector<unsigned int>& tensorIndexes,
5551 unsigned int startingSlotIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005552{
5553 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Ryan OSheac229b3f2023-06-27 22:34:54 +01005554
5555 if (!layer)
5556 {
5557 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
5558 operatorIndex, CHECK_LOCATION().AsString()));
5559 }
Matthew Sloyan81beae32021-07-13 19:46:11 +01005560
Finn Williamsd4fa5452021-03-01 12:31:41 +00005561 if (tensorIndexes.size() + startingSlotIndex != layer->GetNumInputSlots())
telsoa01c577f2c2018-08-31 09:22:23 +01005562 {
5563 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01005564 fmt::format("The number of tensor inputs ({}) does not match the number expected ({})"
5565 " for subgraph:{} operator index:{} {}",
5566 tensorIndexes.size(),
5567 layer->GetNumInputSlots(),
5568 subgraphIndex,
5569 operatorIndex,
5570 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01005571 }
5572
Finn Williamsd4fa5452021-03-01 12:31:41 +00005573 for (unsigned int index = 0; index < tensorIndexes.size() ; ++index)
telsoa01c577f2c2018-08-31 09:22:23 +01005574 {
Finn Williamsd4fa5452021-03-01 12:31:41 +00005575 unsigned int tensorIndex = tensorIndexes[index];
5576 armnn::IInputSlot* slot = &(layer->GetInputSlot(startingSlotIndex + index));
telsoa01c577f2c2018-08-31 09:22:23 +01005577 RegisterConsumerOfTensor(subgraphIndex, tensorIndex, slot);
5578 }
5579}
5580
Kevin May7d96b162021-02-03 17:38:41 +00005581void TfLiteParserImpl::RegisterOutputSlots(size_t subgraphIndex,
5582 size_t operatorIndex,
5583 IConnectableLayer* layer,
5584 const std::vector<unsigned int>& tensorIndexes)
telsoa01c577f2c2018-08-31 09:22:23 +01005585{
5586 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Ryan OSheac229b3f2023-06-27 22:34:54 +01005587
5588 if (!layer)
5589 {
5590 throw NullPointerException(fmt::format("Layer {} pointer is null {}",
5591 operatorIndex, CHECK_LOCATION().AsString()));
5592 }
5593
telsoa01c577f2c2018-08-31 09:22:23 +01005594 if (tensorIndexes.size() != layer->GetNumOutputSlots())
5595 {
5596 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01005597 fmt::format("The number of tensor outputs ({}) does not match the number expected ({})"
5598 " for subgraph:{} operator index:{} {}",
5599 tensorIndexes.size(),
5600 layer->GetNumOutputSlots(),
5601 subgraphIndex,
5602 operatorIndex,
5603 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01005604 }
5605
5606 for (unsigned int slotIndex = 0; slotIndex < layer->GetNumOutputSlots(); ++slotIndex)
5607 {
5608 unsigned int tensorIndex = tensorIndexes[slotIndex];
5609 armnn::IOutputSlot* slot = &(layer->GetOutputSlot(slotIndex));
5610 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
5611 }
5612}
5613
Mike Kelly377fb212023-01-10 15:55:28 +00005614void TfLiteParserImpl::SetupInputLayerTensorInfos(size_t subgraphIndex)
5615{
5616 CHECK_SUBGRAPH(m_Model, subgraphIndex);
5617
5618 auto inputs = GetSubgraphInputs(m_Model, subgraphIndex);
5619 for (auto const& tensorIdAndPtr : inputs)
5620 {
5621 auto tensorInfo = ToTensorInfo(tensorIdAndPtr.second);
5622 m_TensorInfos.insert({tensorIdAndPtr.first, tensorInfo});
5623 }
5624}
5625
Kevin May7d96b162021-02-03 17:38:41 +00005626void TfLiteParserImpl::SetupInputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005627{
5628 CHECK_SUBGRAPH(m_Model, subgraphIndex);
5629
5630 auto inputs = GetSubgraphInputs(m_Model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005631 for (auto const& tensorIdAndPtr : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005632 {
5633 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
5634 IConnectableLayer* layer =
5635 m_Network->AddInputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
5636
5637 auto tensorInfo = ToTensorInfo(tensorIdAndPtr.second);
5638 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
5639
5640 RegisterOutputSlots(subgraphIndex,
5641 VIRTUAL_OPERATOR_ID,
5642 layer,
5643 { static_cast<uint32_t>(tensorIdAndPtr.first) });
5644 }
5645}
5646
Kevin May7d96b162021-02-03 17:38:41 +00005647void TfLiteParserImpl::SetupOutputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005648{
5649 CHECK_SUBGRAPH(m_Model, subgraphIndex);
5650
5651 auto outputs = GetSubgraphOutputs(m_Model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005652 for (auto const& tensorIdAndPtr : outputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005653 {
5654 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
5655 IConnectableLayer* layer =
5656 m_Network->AddOutputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
5657
5658 RegisterInputSlots(subgraphIndex,
5659 VIRTUAL_OPERATOR_ID,
5660 layer,
5661 { static_cast<uint32_t>(tensorIdAndPtr.first) });
5662 }
5663}
5664
Mike Kelly377fb212023-01-10 15:55:28 +00005665void TfLiteParserImpl::SetupConstantLayerTensorInfos(size_t subgraph)
5666{
5667 CHECK_SUBGRAPH(m_Model, subgraph);
5668
5669 const auto & subgraphPtr = m_Model->subgraphs[subgraph];
5670 for (unsigned int subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
5671 {
5672 for (unsigned int tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
5673 {
5674 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot == nullptr &&
5675 m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size() > 0)
5676 {
5677 TensorRawPtr tensorPtr = subgraphPtr->tensors[tensorIndex].get();
5678
5679 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
5680
5681 m_TensorInfos.insert({tensorIndex, tensorInfo});
5682 }
5683 }
5684 }
5685}
5686
Mike Kelly5880b912022-01-28 16:18:54 +00005687void TfLiteParserImpl::SetupConstantLayers(size_t subgraph)
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02005688{
Mike Kelly5880b912022-01-28 16:18:54 +00005689 CHECK_SUBGRAPH(m_Model, subgraph);
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02005690
Mike Kelly5880b912022-01-28 16:18:54 +00005691 const auto & subgraphPtr = m_Model->subgraphs[subgraph];
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02005692 for (unsigned int subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
5693 {
5694 for (unsigned int tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
5695 {
5696 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot == nullptr &&
5697 m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size() > 0)
5698 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01005699 TensorRawPtr tensorPtr = subgraphPtr->tensors[tensorIndex].get();
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02005700
Mike Kelly5880b912022-01-28 16:18:54 +00005701 if (IsConstTensor(tensorPtr))
Matthew Sloyan81beae32021-07-13 19:46:11 +01005702 {
5703 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
Mike Kelly5880b912022-01-28 16:18:54 +00005704 armnn::DataType dataType = tensorInfo.GetDataType();
5705
5706 if (std::find(m_ConstantsToDequantize.begin(), m_ConstantsToDequantize.end(), tensorPtr->buffer)
5707 != m_ConstantsToDequantize.end())
5708 {
5709 dataType = DataType::Float32;
5710 }
5711 auto tensorAndData = CreateConstTensorNonPermuted(tensorPtr, tensorInfo, dataType);
5712
5713 std::string layerName = fmt::format("Constant:{}", tensorPtr->name);
5714 IConnectableLayer *layer = m_Network->AddConstantLayer(tensorAndData.first, layerName.c_str());
5715
5716 layer->GetOutputSlot(0).SetTensorInfo(tensorAndData.first.GetInfo());
5717 RegisterOutputSlots(subgraphIndex,
5718 VIRTUAL_OPERATOR_ID,
5719 layer,
5720 { tensorIndex });
5721 }
5722 else if (ShouldConstantTensorBeCreated(tensorIndex))
5723 {
5724 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
5725 armnn::DataType dataType = tensorInfo.GetDataType();
5726
5727 if (std::find(m_ConstantsToDequantize.begin(), m_ConstantsToDequantize.end(), tensorPtr->buffer)
5728 != m_ConstantsToDequantize.end())
5729 {
5730 dataType = DataType::Float32;
5731 }
5732 // Make sure isConstant flag is set.
5733 tensorInfo.SetConstant();
5734 tensorInfo.SetDataType(dataType);
5735
5736 auto tensorAndData = ConstTensor(tensorInfo, std::vector<uint8_t>(tensorInfo.GetNumBytes()));
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02005737
Matthew Sloyan81beae32021-07-13 19:46:11 +01005738 std::string layerName = fmt::format("Constant:{}", tensorPtr->name);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005739 IConnectableLayer* layer = m_Network->AddConstantLayer(tensorAndData, layerName.c_str());
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02005740
Matthew Sloyan81beae32021-07-13 19:46:11 +01005741 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
5742 RegisterOutputSlots(subgraphIndex,
5743 VIRTUAL_OPERATOR_ID,
5744 layer,
Mike Kelly5880b912022-01-28 16:18:54 +00005745 {tensorIndex});
Matthew Sloyan81beae32021-07-13 19:46:11 +01005746 }
5747 else
5748 {
5749 throw ParseException(
5750 fmt::format("Invalid Tensor: Tensor should be constant. {}",
5751 CHECK_LOCATION().AsString()));
5752 }
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02005753 }
5754 }
5755 }
5756}
5757
telsoa01c577f2c2018-08-31 09:22:23 +01005758// example usage: BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Kevin May7d96b162021-02-03 17:38:41 +00005759TfLiteParserImpl::BufferRawPtr TfLiteParserImpl::GetBuffer(const ModelPtr& model, size_t bufferIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01005760{
5761 CHECK_BUFFER(model, bufferIndex);
5762 return model->buffers[bufferIndex].get();
5763}
5764
Matteo Martincigh747ef822018-12-18 09:26:39 +00005765template<typename T>
Kevin May7d96b162021-02-03 17:38:41 +00005766std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
5767TfLiteParserImpl::CreateConstTensorAndStoreData(TfLiteParserImpl::BufferRawPtr bufferPtr,
5768 TfLiteParserImpl::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +00005769 armnn::TensorInfo& tensorInfo,
5770 armnn::Optional<armnn::PermutationVector&> permutationVector)
5771{
Matthew Sloyan81beae32021-07-13 19:46:11 +01005772 // Make sure isConstant flag is set.
5773 tensorInfo.SetConstant();
5774
Matteo Martincigh747ef822018-12-18 09:26:39 +00005775 auto constData = CreateConstTensorImpl<T>(bufferPtr,
5776 tensorPtr,
5777 tensorInfo,
5778 permutationVector);
Kevin May7d96b162021-02-03 17:38:41 +00005779 TfLiteParserImpl::SupportedDataStorage storage(std::move(constData.second));
Matteo Martincigh747ef822018-12-18 09:26:39 +00005780 return std::make_pair(constData.first, std::move(storage));
5781}
5782
Mike Kelly5880b912022-01-28 16:18:54 +00005783bool TfLiteParserImpl::ShouldConstantTensorBeCreated(unsigned int tensorIndex)
5784{
5785 // If the TensorIndex appears in the list of ConstantsToBeCreated then return true
5786 return (std::find(m_ConstantsToBeCreated.begin(), m_ConstantsToBeCreated.end(), tensorIndex)
5787 != m_ConstantsToBeCreated.end());
5788}
5789
Finn Williamsd4fa5452021-03-01 12:31:41 +00005790bool TfLiteParserImpl::IsConstTensor(TensorRawPtr tensorPtr)
5791{
5792 CHECK_TENSOR_PTR(tensorPtr);
mathad01bf7edb62021-04-20 16:12:45 +01005793 bool isConst = true;
5794
5795 auto buffer = GetBuffer(m_Model, tensorPtr->buffer);
5796 if (buffer->data.size() == 0)
5797 {
5798 isConst = false;
5799 }
5800
5801 return isConst;
Finn Williamsd4fa5452021-03-01 12:31:41 +00005802}
5803
Kevin May7d96b162021-02-03 17:38:41 +00005804std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
Finn Williamsd4fa5452021-03-01 12:31:41 +00005805TfLiteParserImpl::CreateConstTensorPermuted(TensorRawPtr tensorPtr,
5806 armnn::TensorInfo& tensorInfo,
5807 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +01005808{
5809 CHECK_TENSOR_PTR(tensorPtr);
5810 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
5811 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
5812
Matthew Sloyan81beae32021-07-13 19:46:11 +01005813 // Make sure isConstant flag is set.
5814 tensorInfo.SetConstant();
5815
telsoa01c577f2c2018-08-31 09:22:23 +01005816 switch (tensorInfo.GetDataType())
5817 {
5818 case armnn::DataType::Float32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00005819 return CreateConstTensorAndStoreData<float>(bufferPtr,
5820 tensorPtr,
5821 tensorInfo,
5822 permutationVector);
Derek Lambertif90c56d2020-01-10 17:14:08 +00005823 case armnn::DataType::QAsymmU8:
Matteo Martincigh747ef822018-12-18 09:26:39 +00005824 return CreateConstTensorAndStoreData<uint8_t>(bufferPtr,
5825 tensorPtr,
5826 tensorInfo,
5827 permutationVector);
Keith Davisd305e1a2020-01-22 11:57:54 +00005828 case armnn::DataType::QSymmS8:
5829 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
5830 tensorPtr,
5831 tensorInfo,
5832 permutationVector);
Keith Davis67e6c542020-02-19 10:08:33 +00005833 case armnn::DataType::QAsymmS8:
5834 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
5835 tensorPtr,
5836 tensorInfo,
5837 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01005838 case armnn::DataType::Signed32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00005839 return CreateConstTensorAndStoreData<int32_t>(bufferPtr,
5840 tensorPtr,
5841 tensorInfo,
5842 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01005843 default:
5844 {
5845 std::stringstream errString;
5846 errString << "Unexpected datatype when creating const tensor: "
5847 << armnn::GetDataTypeName(tensorInfo.GetDataType())
5848 << " shape:" << tensorInfo.GetShape()
5849 << CHECK_LOCATION().AsString();
5850 throw ParseException(errString.str());
5851 }
5852 }
5853}
5854
Finn Williamsd4fa5452021-03-01 12:31:41 +00005855armnn::ConstTensor TfLiteParserImpl::CreateConstTensorNonPermuted(TensorRawPtr tensorPtr,
5856 armnn::TensorInfo& tensorInfo)
5857{
5858 CHECK_TENSOR_PTR(tensorPtr);
5859 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
5860 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
5861
Matthew Sloyan81beae32021-07-13 19:46:11 +01005862 // Make sure isConstant flag is set.
5863 tensorInfo.SetConstant();
5864
Finn Williamsd4fa5452021-03-01 12:31:41 +00005865 return ConstTensor(tensorInfo, bufferPtr->data.data());
5866}
5867
Mike Kelly5880b912022-01-28 16:18:54 +00005868std::pair<armnn::ConstTensor, std::unique_ptr<float[]>>
5869TfLiteParserImpl::CreateConstTensorNonPermuted(TensorRawPtr tensorPtr,
5870 armnn::TensorInfo& tensorInfo,
5871 armnn::DataType inputDataType)
5872{
5873 CHECK_TENSOR_PTR(tensorPtr);
5874 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
5875 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
5876
5877 // Make sure isConstant flag is set.
5878 tensorInfo.SetConstant();
5879
Mike Kelly0506ef02023-01-03 16:29:44 +00005880 if (inputDataType == DataType::Float32 && tensorInfo.GetDataType() != DataType::Float32)
Mike Kelly5880b912022-01-28 16:18:54 +00005881 {
Mike Kelly0506ef02023-01-03 16:29:44 +00005882 try
5883 {
5884 TensorInfo constTensorInfo(tensorInfo.GetShape(), DataType::Float32, 0.0f, 0, true);
5885 std::unique_ptr<float[]> data = armnnUtils::ToFloatArray(bufferPtr->data, tensorInfo);
5886 return std::make_pair(ConstTensor(constTensorInfo, data.get()), std::move(data));
5887 }
Cathal Corbett9c843c32023-01-09 17:51:37 +00005888 catch (InvalidArgumentException&)
Mike Kelly0506ef02023-01-03 16:29:44 +00005889 {
5890 throw ParseException(
5891 fmt::format("Unsupported input/weights combination: Input {} not supported with Weights {}",
5892 GetDataTypeName(DataType::Float32),
5893 GetDataTypeName(tensorInfo.GetDataType()),
5894 CHECK_LOCATION().AsString()));
5895 }
Mike Kelly5880b912022-01-28 16:18:54 +00005896 }
5897 else
5898 {
5899 return std::make_pair(ConstTensor(tensorInfo, bufferPtr->data.data()), std::unique_ptr<float[]>());
5900 }
5901}
5902
5903std::pair<armnn::ConstTensor*, std::unique_ptr<float[]>>
5904TfLiteParserImpl::CreateConstTensorPtr(TensorRawPtr tensorPtr, armnn::TensorInfo& inputTensorInfo)
5905{
5906 CHECK_TENSOR_PTR(tensorPtr);
5907 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
5908 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
5909 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
5910
5911 // Make sure isConstant flag is set.
5912 tensorInfo.SetConstant();
5913
5914 if (inputTensorInfo.GetDataType() == DataType::Float32 && tensorInfo.GetDataType() != DataType::Float32)
5915 {
Mike Kelly0506ef02023-01-03 16:29:44 +00005916 try
5917 {
5918 TensorInfo constTensorInfo(tensorInfo.GetShape(), DataType::Float32, 0.0f, 0, true);
5919 std::unique_ptr<float[]> data = armnnUtils::ToFloatArray(bufferPtr->data, tensorInfo);
5920 return std::make_pair(new ConstTensor(constTensorInfo, data.get()), std::move(data));
5921 }
Cathal Corbett9c843c32023-01-09 17:51:37 +00005922 catch (InvalidArgumentException&)
Mike Kelly0506ef02023-01-03 16:29:44 +00005923 {
5924 throw ParseException(
5925 fmt::format("Unsupported input/weights combination: Input {} not supported with Weights {}",
5926 GetDataTypeName(DataType::Float32),
5927 GetDataTypeName(tensorInfo.GetDataType()),
5928 CHECK_LOCATION().AsString()));
5929 }
Mike Kelly5880b912022-01-28 16:18:54 +00005930 }
5931 else
5932 {
5933 return std::make_pair(new ConstTensor(tensorInfo, bufferPtr->data.data()), std::unique_ptr<float[]>());
5934 }
5935}
5936
Kevin May7d96b162021-02-03 17:38:41 +00005937BindingPointInfo TfLiteParserImpl::GetNetworkInputBindingInfo(size_t subgraphId,
5938 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01005939{
5940 CHECK_SUBGRAPH(m_Model, subgraphId);
5941 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
Mike Kelly0d77ae12022-01-07 17:42:27 +00005942 for (auto const& input : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005943 {
5944 if (input.second->name == name)
5945 {
5946 auto bindingId = GenerateLayerBindingId(subgraphId, input.first);
Colm Donelan4bc993b2021-11-09 20:39:10 +00005947 auto inputTensorInfo = ToTensorInfo(input.second);
5948 // Input tensors are always treated as constant tensors during network execution.
5949 inputTensorInfo.SetConstant(true);
5950 return std::make_pair(bindingId, inputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01005951 }
5952 }
5953
5954 std::stringstream bindings;
Mike Kelly0d77ae12022-01-07 17:42:27 +00005955 for (auto const& input : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005956 {
5957 bindings << "'" << input.second->name << "' ";
5958 }
5959
5960 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01005961 fmt::format("No input binding found for subgraph:{} and name:{}. "
5962 "Possible inputs are: [{}] {}",
5963 subgraphId,
5964 name,
5965 bindings.str(),
5966 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01005967}
5968
Kevin May7d96b162021-02-03 17:38:41 +00005969BindingPointInfo TfLiteParserImpl::GetNetworkOutputBindingInfo(size_t subgraphId,
5970 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01005971{
5972 CHECK_SUBGRAPH(m_Model, subgraphId);
5973 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00005974 for (unsigned int i = 0; i < outputs.size(); ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01005975 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00005976 auto const output = outputs[i];
telsoa01c577f2c2018-08-31 09:22:23 +01005977 if (output.second->name == name)
5978 {
5979 auto bindingId = GenerateLayerBindingId(subgraphId, output.first);
Mike Kelly377fb212023-01-10 15:55:28 +00005980 std::vector<unsigned int> shape = m_OverriddenOutputShapes.size() > 0 ?
5981 m_OverriddenOutputShapes[i] : AsUnsignedVector(output.second->shape);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00005982 return std::make_pair(bindingId, ToTensorInfo(output.second, shape));
telsoa01c577f2c2018-08-31 09:22:23 +01005983 }
5984 }
5985
5986 std::stringstream bindings;
Mike Kelly0d77ae12022-01-07 17:42:27 +00005987 for (auto const& output : outputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005988 {
5989 bindings << "'" << output.second->name << "' ";
5990 }
5991
5992 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01005993 fmt::format("No output binding found for subgraph:{} and name:{}. "
5994 "Possible outputs are: [{}] {}",
5995 subgraphId,
5996 name,
5997 bindings.str(),
5998 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01005999}
6000
Kevin May7d96b162021-02-03 17:38:41 +00006001size_t TfLiteParserImpl::GetSubgraphCount() const
telsoa01c577f2c2018-08-31 09:22:23 +01006002{
6003 return m_Model->subgraphs.size();
6004}
6005
Kevin May7d96b162021-02-03 17:38:41 +00006006std::vector<std::string> TfLiteParserImpl::GetSubgraphInputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01006007{
6008 CHECK_SUBGRAPH(m_Model, subgraphId);
6009 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
6010 std::vector<std::string> result;
6011 result.reserve(inputs.size());
Mike Kelly0d77ae12022-01-07 17:42:27 +00006012 for (auto const& input : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01006013 {
6014 result.push_back(input.second->name);
6015 }
6016 return result;
6017}
6018
Kevin May7d96b162021-02-03 17:38:41 +00006019std::vector<std::string> TfLiteParserImpl::GetSubgraphOutputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01006020{
6021 CHECK_SUBGRAPH(m_Model, subgraphId);
6022 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
6023 std::vector<std::string> result;
6024 result.reserve(outputs.size());
Mike Kelly0d77ae12022-01-07 17:42:27 +00006025 for (auto const& output : outputs)
telsoa01c577f2c2018-08-31 09:22:23 +01006026 {
6027 result.push_back(output.second->name);
6028 }
6029 return result;
6030}
6031
Matthew Sloyanac001ee2021-02-03 10:43:04 +00006032const std::string TfLiteParserImpl::GetVersion()
6033{
6034 return TFLITE_PARSER_VERSION;
6035}
6036
Mike Kelly0d77ae12022-01-07 17:42:27 +00006037TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<float[]>&& data)
telsoa01c577f2c2018-08-31 09:22:23 +01006038: m_FloatData(std::move(data))
6039, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00006040, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01006041, m_Int32Data(nullptr)
6042{
6043}
6044
Mike Kelly0d77ae12022-01-07 17:42:27 +00006045TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<uint8_t[]>&& data)
telsoa01c577f2c2018-08-31 09:22:23 +01006046: m_FloatData(nullptr)
6047, m_Uint8Data(std::move(data))
Keith Davisd305e1a2020-01-22 11:57:54 +00006048, m_Int8Data(nullptr)
6049, m_Int32Data(nullptr)
6050{
6051}
6052
Mike Kelly0d77ae12022-01-07 17:42:27 +00006053TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int8_t[]>&& data)
Keith Davisd305e1a2020-01-22 11:57:54 +00006054: m_FloatData(nullptr)
6055, m_Uint8Data(nullptr)
6056, m_Int8Data(std::move(data))
telsoa01c577f2c2018-08-31 09:22:23 +01006057, m_Int32Data(nullptr)
6058{
6059}
6060
Mike Kelly0d77ae12022-01-07 17:42:27 +00006061TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int32_t[]>&& data)
telsoa01c577f2c2018-08-31 09:22:23 +01006062: m_FloatData(nullptr)
6063, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00006064, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01006065, m_Int32Data(std::move(data))
6066{
6067}
6068
6069} // armnnTfLiteParser