blob: 0484c6f478a527c3f6cf164b139487152bac7f85 [file] [log] [blame]
telsoa01c577f2c2018-08-31 09:22:23 +01001//
Teresa Charlinfd33a692022-06-29 15:35:57 +01002// Copyright © 2022 Arm Ltd and Contributors. All rights reserved.
David Beckecb56cd2018-09-05 12:52:57 +01003// SPDX-License-Identifier: MIT
telsoa01c577f2c2018-08-31 09:22:23 +01004//
Matteo Martincighe011d202019-11-28 11:35:47 +00005
telsoa01c577f2c2018-08-31 09:22:23 +01006#include "TfLiteParser.hpp"
7
Matthew Sloyanac001ee2021-02-03 10:43:04 +00008#include "armnnTfLiteParser/Version.hpp"
Mike Kelly5880b912022-01-28 16:18:54 +00009#include "armnn/LstmParams.hpp"
Matthew Sloyanac001ee2021-02-03 10:43:04 +000010
Sadik Armagand109a4d2020-07-28 10:42:13 +010011#include <armnn/BackendOptions.hpp>
Matthew Bentham39ef3e52020-01-20 10:09:09 +000012#include <armnn/Descriptors.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010013#include <armnn/Exceptions.hpp>
Derek Lamberti08446972019-11-26 16:38:31 +000014#include <armnn/Logging.hpp>
James Conroy05102392020-06-24 15:39:55 +010015#include <armnn/Tensor.hpp>
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +000016#include <armnnUtils/TensorUtils.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010017#include <armnn/TypesUtils.hpp>
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +010018#include <armnn/utility/Assert.hpp>
Jan Eilers8eb25602020-03-09 12:13:48 +000019#include <armnn/utility/IgnoreUnused.hpp>
Derek Lambertif0176992020-04-28 13:37:49 +010020#include <armnn/utility/NumericCast.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010021
22// armnnUtils:
Matteo Martincighe011d202019-11-28 11:35:47 +000023#include <armnnUtils/Permute.hpp>
Rob Hughes9542f902021-07-14 09:48:54 +010024#include <armnnUtils/Filesystem.hpp>
Matteo Martincighe011d202019-11-28 11:35:47 +000025
Sadik Armagan479045b2018-10-01 11:51:37 +010026#include <ParserHelper.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010027#include <VerificationHelpers.hpp>
28
29// The generated code based on the Tf Lite schema:
30#include <schema_generated.h>
31
Matteo Martincighe011d202019-11-28 11:35:47 +000032#include <flatbuffers/flexbuffers.h>
33
James Ward58dec6b2020-09-11 17:32:44 +010034#include <fmt/format.h>
telsoa01c577f2c2018-08-31 09:22:23 +010035
telsoa01c577f2c2018-08-31 09:22:23 +010036#include <algorithm>
Matthew Sloyanac001ee2021-02-03 10:43:04 +000037#include <iostream>
telsoa01c577f2c2018-08-31 09:22:23 +010038#include <limits>
Sadikb94967b2018-09-19 15:30:00 +010039#include <numeric>
Derek Lambertic9e52792020-03-11 11:42:26 +000040
41#define ARMNN_THROW_PARSE_EXCEPTION(msg) \
42 { \
43 throw armnn::ParseException( static_cast<const std::stringstream&>( std::stringstream() << msg \
44 << ": " \
45 << CHECK_LOCATION().AsString()).str()); \
46 }
telsoa01c577f2c2018-08-31 09:22:23 +010047
48using namespace armnn;
49using armnn::CheckLocation;
50namespace armnnTfLiteParser
51{
Kevin May7d96b162021-02-03 17:38:41 +000052
53ITfLiteParser::ITfLiteParser(const armnn::Optional<TfLiteParserOptions>& options) :
54 pTfLiteParserImpl(new TfLiteParserImpl(options)) {}
55
56ITfLiteParser::~ITfLiteParser() = default;
57
58ITfLiteParser* ITfLiteParser::CreateRaw(const armnn::Optional<TfLiteParserOptions>& options)
59{
60 return new ITfLiteParser(options);
61}
62
63ITfLiteParserPtr ITfLiteParser::Create(const armnn::Optional<TfLiteParserOptions>& options)
64{
65 return ITfLiteParserPtr(CreateRaw(options), &ITfLiteParser::Destroy);
66}
67
68void ITfLiteParser::Destroy(ITfLiteParser* parser)
69{
70 delete parser;
71}
72
73armnn::INetworkPtr ITfLiteParser::CreateNetworkFromBinaryFile(const char* graphFile)
74{
75 return pTfLiteParserImpl->CreateNetworkFromBinaryFile(graphFile);
76}
77
Mike Kelly0d77ae12022-01-07 17:42:27 +000078armnn::INetworkPtr ITfLiteParser::CreateNetworkFromBinary(const std::vector<uint8_t>& binaryContent)
Kevin May7d96b162021-02-03 17:38:41 +000079{
80 return pTfLiteParserImpl->CreateNetworkFromBinary(binaryContent);
81}
82
83BindingPointInfo ITfLiteParser::GetNetworkInputBindingInfo(size_t subgraphId,
84 const std::string& name) const
85{
86 return pTfLiteParserImpl->GetNetworkInputBindingInfo(subgraphId, name);
87}
88
89BindingPointInfo ITfLiteParser::GetNetworkOutputBindingInfo(size_t subgraphId,
90 const std::string& name) const
91{
92 return pTfLiteParserImpl->GetNetworkOutputBindingInfo(subgraphId, name);
93}
94
95size_t ITfLiteParser::GetSubgraphCount() const
96{
97 return pTfLiteParserImpl->GetSubgraphCount();
98}
99
100std::vector<std::string> ITfLiteParser::GetSubgraphInputTensorNames(size_t subgraphId) const
101{
102 return pTfLiteParserImpl->GetSubgraphInputTensorNames(subgraphId);
103}
104
105std::vector<std::string> ITfLiteParser::GetSubgraphOutputTensorNames(size_t subgraphId) const
106{
107 return pTfLiteParserImpl->GetSubgraphOutputTensorNames(subgraphId);
108}
109
telsoa01c577f2c2018-08-31 09:22:23 +0100110namespace
111{
jimfly01c25411c2018-11-14 17:47:22 +0000112
telsoa01c577f2c2018-08-31 09:22:23 +0100113const uint32_t VIRTUAL_OPERATOR_ID = std::numeric_limits<uint32_t>::max();
114
Mike Kelly0d77ae12022-01-07 17:42:27 +0000115void CheckSubgraph(const TfLiteParserImpl::ModelPtr& model,
telsoa01c577f2c2018-08-31 09:22:23 +0100116 size_t subgraphIndex,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000117 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100118{
119 if (model.get() == nullptr)
120 {
121 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100122 fmt::format("{} was called with invalid (null) model. "
123 "Possible reason is that the model is not yet loaded and Unpack(ed). "
124 "subgraph:{} at {}",
125 location.m_Function,
126 subgraphIndex,
127 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100128 }
129 else if (subgraphIndex >= model->subgraphs.size())
130 {
131 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100132 fmt::format("{} was called with an invalid subgraph index. "
133 "subgraph:{} at {}",
134 location.m_Function,
135 subgraphIndex,
136 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100137 }
138}
139
140#define CHECK_SUBGRAPH(MODEL, SUBGRAPH_INDEX) \
141 CheckSubgraph(MODEL, SUBGRAPH_INDEX, CHECK_LOCATION())
142
Mike Kelly0d77ae12022-01-07 17:42:27 +0000143void CheckModel(const TfLiteParserImpl::ModelPtr& model,
telsoa01c577f2c2018-08-31 09:22:23 +0100144 size_t subgraphIndex,
145 size_t operatorIndex,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000146 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100147{
148 if (model.get() == nullptr)
149 {
150 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100151 fmt::format("{} was called with invalid (null) model. "
152 "Possible reason is that the model is not yet loaded and Unpack(ed). "
153 "subgraph:{} operator:{} at {}",
154 location.m_Function,
155 subgraphIndex,
156 operatorIndex,
157 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100158 }
159 else if (subgraphIndex >= model->subgraphs.size())
160 {
161 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100162 fmt::format("{} was called with an invalid subgraph index. "
163 "subgraph:{} operator:{} at {}",
164 location.m_Function,
165 subgraphIndex,
166 operatorIndex,
167 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100168 }
169 else if (operatorIndex >= model->subgraphs[subgraphIndex]->operators.size() &&
170 operatorIndex != VIRTUAL_OPERATOR_ID)
171 {
172 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100173 fmt::format("{} was called with an invalid operator index. "
174 "subgraph:{} operator:{} at {}",
175 location.m_Function,
176 subgraphIndex,
177 operatorIndex,
178 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100179 }
180}
181
182#define CHECK_MODEL(MODEL, SUBGRAPH_INDEX, OPERATOR_INDEX) \
183 CheckModel(MODEL, SUBGRAPH_INDEX, OPERATOR_INDEX, CHECK_LOCATION())
184
Mike Kelly0d77ae12022-01-07 17:42:27 +0000185void CheckTensor(const TfLiteParserImpl::ModelPtr& model,
telsoa01c577f2c2018-08-31 09:22:23 +0100186 size_t subgraphIndex,
187 size_t tensorIndex,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000188 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100189{
190 // not checking model, because I assume CHECK_MODEL already run
191 // and checked that. An assert would do.
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100192 ARMNN_ASSERT_MSG(model.get() != nullptr, "Expecting a valid model in this function");
telsoa01c577f2c2018-08-31 09:22:23 +0100193
194 // also subgraph index should be checked by CHECK_MODEL so
195 // I only add an assert here
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100196 ARMNN_ASSERT_MSG(subgraphIndex < model->subgraphs.size(), "Expecting a valid subgraph index");
telsoa01c577f2c2018-08-31 09:22:23 +0100197
198 // the tensor index is the only one to check here
199 if (tensorIndex >= model->subgraphs[subgraphIndex]->tensors.size())
200 {
201 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100202 fmt::format("{} was called with an invalid tensor index. "
203 "subgraph:{} tensor:{} at {}",
204 location.m_Function,
205 subgraphIndex,
206 tensorIndex,
207 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100208 }
209}
210
211#define CHECK_TENSOR(MODEL, SUBGRAPH_INDEX, TENSOR_INDEX) \
212 CheckTensor(MODEL, SUBGRAPH_INDEX, TENSOR_INDEX, CHECK_LOCATION())
213
Kevin May7d96b162021-02-03 17:38:41 +0000214void CheckTensorPtr(TfLiteParserImpl::TensorRawPtr rawPtr,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000215 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100216{
217 if (rawPtr == nullptr)
218 {
219 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100220 fmt::format("{} was called with a null tensor pointer at {}", location.m_Function, location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100221 }
222}
223
224#define CHECK_TENSOR_PTR(TENSOR_PTR) \
225 CheckTensorPtr(TENSOR_PTR, CHECK_LOCATION())
226
Mike Kelly0d77ae12022-01-07 17:42:27 +0000227void CheckBuffer(const TfLiteParserImpl::ModelPtr& model,
telsoa01c577f2c2018-08-31 09:22:23 +0100228 size_t bufferIndex,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000229 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100230{
231 if (model.get() == nullptr)
232 {
233 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100234 fmt::format("{} was called with invalid (null) model. "
235 "Possible reason is that the model is not yet loaded and Unpack(ed). "
236 "buffer:{} at {}",
237 location.m_Function,
238 bufferIndex,
239 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100240 }
241 else if (bufferIndex >= model->buffers.size())
242 {
243 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100244 fmt::format("{} was called with an invalid buffer index. "
245 "buffer index:{} at {}",
246 location.m_Function,
247 bufferIndex,
248 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100249 }
250 else if (model->buffers[bufferIndex].get() == nullptr)
251 {
252 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100253 fmt::format("The buffer #{} is null. {}",
254 bufferIndex,
255 location.AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100256 }
257}
258
259#define CHECK_BUFFER(MODEL, BUFFER_INDEX) \
260 CheckBuffer(MODEL, BUFFER_INDEX, CHECK_LOCATION())
261
Kevin May7d96b162021-02-03 17:38:41 +0000262void CheckBufferSize(TfLiteParserImpl::BufferRawPtr bufferPtr,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000263 const armnn::TensorInfo& tensorInfo,
telsoa01c577f2c2018-08-31 09:22:23 +0100264 uint32_t bufferId,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000265 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100266{
267 if (bufferPtr == nullptr)
268 {
269 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100270 fmt::format("BufferPtr is null for buffer:{}. {}",
271 bufferId,
272 location.AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100273 }
274 else if(tensorInfo.GetNumElements() > bufferPtr->data.size() ||
275 tensorInfo.GetNumBytes() > bufferPtr->data.size())
276 {
277 std::stringstream ss;
278 ss << "Buffer #" << bufferId << " has " << bufferPtr->data.size() << " bytes. "
279 << "For tensor: " << tensorInfo.GetShape()
280 << " expecting: " << tensorInfo.GetNumBytes() << " bytes and "
281 << tensorInfo.GetNumElements() << " elements. " << location.AsString();
282 throw ParseException(ss.str());
283 }
284}
285
Mike Kelly0d77ae12022-01-07 17:42:27 +0000286
287tflite::BuiltinOperator GetOpCode(const TfLiteParserImpl::ModelPtr& model, size_t subgraphIndex, size_t operatorIndex)
288{
289 const auto& operatorPtr = model->subgraphs[subgraphIndex]->operators[operatorIndex];
290 auto opcodeIndex = operatorPtr->opcode_index;
291
292// work around the introduction of the deprecated_builtin_code introduced in 2.4 in a backwards compatible manner
293#if defined(ARMNN_POST_TFLITE_2_3)
294 auto opcode = std::max(model->operator_codes[opcodeIndex]->builtin_code,
295 static_cast<tflite::BuiltinOperator>(model->operator_codes[opcodeIndex]->deprecated_builtin_code));
296#else
297 auto opcode = model->operator_codes[opcodeIndex]->builtin_code;
298#endif
299 return opcode;
300}
301
302std::vector<unsigned int> GetUIntBuffer(armnn::TensorInfo info,
303 const TfLiteParserImpl::ModelPtr& model,
304 size_t bufferIndex)
305{
306 TfLiteParserImpl::BufferRawPtr bufferPtr = TfLiteParserImpl::GetBuffer(model, bufferIndex);
307 std::vector<unsigned int> buffer(info.GetNumElements());
308
309 if (info.GetDataType() == DataType::Signed32)
310 {
311 ::memcpy(buffer.data(), bufferPtr->data.data(), bufferPtr->data.size());
312 }
313 else if (info.GetDataType() == DataType::Signed64)
314 {
315 std::vector<uint64_t> uint64Buffer(info.GetNumElements());
316 ::memcpy(uint64Buffer.data(), bufferPtr->data.data(), bufferPtr->data.size());
317 buffer.assign(std::begin(uint64Buffer), std::end(uint64Buffer));
318 }
319 return buffer;
320}
321
telsoa01c577f2c2018-08-31 09:22:23 +0100322#define CHECK_BUFFER_SIZE(BUFFER_PTR, TENSOR_INFO, BUFFER_ID) \
323 CheckBufferSize(BUFFER_PTR, TENSOR_INFO, BUFFER_ID, CHECK_LOCATION())
324
325bool IsActivationSupported(tflite::ActivationFunctionType activationType)
326{
327 switch(activationType)
328 {
329 case tflite::ActivationFunctionType_NONE:
330 case tflite::ActivationFunctionType_RELU:
331 case tflite::ActivationFunctionType_RELU6:
332 case tflite::ActivationFunctionType_TANH:
333 {
334 return true;
335 }
336 default:
337 {
338 return false;
339 }
340 }
341}
342
343#define CHECK_SUPPORTED_FUSED_ACTIVATION(OPTION, SUBGRAPH_INDEX, OPERATOR_INDEX) \
344 do { \
345 if (IsActivationSupported(OPTION->fused_activation_function) == false) \
346 { \
347 throw ParseException( \
James Ward58dec6b2020-09-11 17:32:44 +0100348 fmt::format("TfLite parser doesn't suppport fused activation: " \
349 "{}/{} in {} subgraph:{} operator:{} at {}", \
350 OPTION->fused_activation_function, \
351 tflite::EnumNameActivationFunctionType(\
352 OPTION->fused_activation_function), \
353 __func__, \
354 SUBGRAPH_INDEX, \
355 OPERATOR_INDEX, \
356 CHECK_LOCATION().FileLine())); \
telsoa01c577f2c2018-08-31 09:22:23 +0100357 } \
358 } while(false)
359
360
Mike Kelly0d77ae12022-01-07 17:42:27 +0000361std::vector<unsigned int> AsUnsignedVector(const std::vector<int32_t>& in)
telsoa01c577f2c2018-08-31 09:22:23 +0100362{
363 std::vector<unsigned int> result;
364 result.reserve(in.size());
Mike Kelly0d77ae12022-01-07 17:42:27 +0000365 for (auto& i : in)
telsoa01c577f2c2018-08-31 09:22:23 +0100366 {
mathad01c21025d2021-04-26 10:09:37 +0100367 // If the location of the input data is -1 then the input should be ignored.
368 if (i == -1)
369 {
370 continue;
371 }
telsoa01c577f2c2018-08-31 09:22:23 +0100372 result.push_back(CHECKED_NON_NEGATIVE(i));
373 }
374 return result;
375}
376
Mike Kelly5880b912022-01-28 16:18:54 +0000377bool IsOptionalOperandPresent(int input)
378{
379 return (input >= 0);
380}
381
telsoa01c577f2c2018-08-31 09:22:23 +0100382void CalcPadding(uint32_t inputSize,
383 uint32_t filterSize,
384 uint32_t stride,
Pablo Tellof0bd6832019-04-26 17:58:13 +0100385 uint32_t dilation,
telsoa01c577f2c2018-08-31 09:22:23 +0100386 uint32_t& paddingFront,
387 uint32_t& paddingBack,
388 tflite::Padding padding)
389{
390 paddingFront = 0;
391 paddingBack = 0;
392 if (padding == tflite::Padding_SAME)
393 {
394 uint32_t outputSize = (inputSize + stride - 1) / stride;
Pablo Tellof0bd6832019-04-26 17:58:13 +0100395 uint32_t dilatedSize = filterSize + (dilation - 1) * (filterSize - 1);
396 uint32_t temp = (outputSize - 1) * stride + dilatedSize;
telsoa01c577f2c2018-08-31 09:22:23 +0100397 if (temp > inputSize)
398 {
399 paddingFront = (temp - inputSize) / 2;
400 paddingBack = (temp - inputSize) - paddingFront;
401 }
402 }
403}
404
Kevin May7d96b162021-02-03 17:38:41 +0000405armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr,
Finn Williamsb49ed182021-06-29 15:50:08 +0100406 const std::vector<unsigned int>& shape,
Sadik Armagand109a4d2020-07-28 10:42:13 +0100407 const bool outputTensor = false)
telsoa01c577f2c2018-08-31 09:22:23 +0100408{
409 armnn::DataType type;
410 CHECK_TENSOR_PTR(tensorPtr);
411
412 switch (tensorPtr->type)
413 {
414 case tflite::TensorType_UINT8:
Derek Lambertif90c56d2020-01-10 17:14:08 +0000415 type = armnn::DataType::QAsymmU8;
telsoa01c577f2c2018-08-31 09:22:23 +0100416 break;
417 case tflite::TensorType_FLOAT32:
418 type = armnn::DataType::Float32;
419 break;
Keith Davisb4dd5cc2022-04-07 11:32:00 +0100420 case tflite::TensorType_FLOAT16:
421 type = armnn::DataType::Float16;
422 break;
Finn Williamsed66d142019-12-06 09:55:55 +0000423 case tflite::TensorType_INT8:
Keith Davis67e6c542020-02-19 10:08:33 +0000424 if (tensorPtr->quantization->zero_point.size() == 1)
Ryan OShea03181ff2020-02-07 17:22:22 +0000425 {
Keith Davis0c2eeac2020-02-11 16:51:50 +0000426 // Per-tensor
Ryan OShea03181ff2020-02-07 17:22:22 +0000427 type = armnn::DataType::QAsymmS8;
428 }
429 else
430 {
Keith Davis0c2eeac2020-02-11 16:51:50 +0000431 // Per-channel
Ryan OShea03181ff2020-02-07 17:22:22 +0000432 type = armnn::DataType::QSymmS8;
433 }
Finn Williamsed66d142019-12-06 09:55:55 +0000434 break;
435 case tflite::TensorType_INT16:
Derek Lambertif90c56d2020-01-10 17:14:08 +0000436 type = armnn::DataType::QSymmS16;
Finn Williamsed66d142019-12-06 09:55:55 +0000437 break;
telsoa01c577f2c2018-08-31 09:22:23 +0100438 case tflite::TensorType_INT32:
439 type = armnn::DataType::Signed32;
440 break;
Inki Daed4619e22020-09-10 15:33:54 +0900441 case tflite::TensorType_INT64:
442 type = armnn::DataType::Signed64;
443 break;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100444 case tflite::TensorType_BOOL:
445 type = armnn::DataType::Boolean;
446 break;
telsoa01c577f2c2018-08-31 09:22:23 +0100447 default:
448 {
449 CheckLocation location = CHECK_LOCATION();
450 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100451 fmt::format("Unsupported data type {} = {} for tensor: {}. {}",
452 tensorPtr->type,
453 tflite::EnumNameTensorType(tensorPtr->type),
454 tensorPtr->name,
455 location.AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100456 }
457 }
Finn Williamsb49ed182021-06-29 15:50:08 +0100458 TensorShape tensorShape;
459
460 std::vector<unsigned int> safeShape = shape;
461 if (shape.size() == 0)
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100462 {
463 safeShape.push_back(1);
Finn Williamsb49ed182021-06-29 15:50:08 +0100464 }
465
466 if (!outputTensor)
467 {
468 tensorShape = TensorShape(armnn::numeric_cast<unsigned int>(safeShape.size()), safeShape.data());
469 }
470 else
471 {
Rob Hughesd812a312021-08-06 13:10:53 +0100472 size_t shapeSignatureSize = tensorPtr->shape_signature.size();
Finn Williamsb49ed182021-06-29 15:50:08 +0100473
474 // If a shape signature exists we will use that to infer dynamic tensors
475 if (shapeSignatureSize != 0)
Sadik Armagand109a4d2020-07-28 10:42:13 +0100476 {
Finn Williamsb49ed182021-06-29 15:50:08 +0100477 // If the shape is incompatible with the shape signature override the shape
478 if (shapeSignatureSize != shape.size())
479 {
480 safeShape = {};
481
482 for (unsigned int i = 0; i < shapeSignatureSize; ++i)
483 {
484 unsigned int dim = tensorPtr->shape_signature[i] > -1 ?
485 static_cast<unsigned int>(tensorPtr->shape_signature[i]) : 0;
486 safeShape.push_back(dim);
487 }
488 }
489
Rob Hughesd812a312021-08-06 13:10:53 +0100490 std::unique_ptr<bool[]> dimMask = std::make_unique<bool[]>(tensorPtr->shape_signature.size());
Finn Williamsb49ed182021-06-29 15:50:08 +0100491 for (unsigned int i = 0; i < tensorPtr->shape_signature.size(); ++i)
492 {
493 dimMask[i] = tensorPtr->shape_signature[i] == -1 ? false : true;
494 }
Rob Hughesd812a312021-08-06 13:10:53 +0100495 tensorShape = TensorShape(static_cast<unsigned int>(safeShape.size()), safeShape.data(), dimMask.get());
Finn Williamsb49ed182021-06-29 15:50:08 +0100496 }
497 // If there is no shape signature treat the tensor as dynamic if the shape has a size of zero
498 else if (shape.size() == 0)
499 {
500 tensorShape = TensorShape(1, false);
501 }
502 else
503 {
504 tensorShape = TensorShape(armnn::numeric_cast<unsigned int>(shape.size()), shape.data());
Sadik Armagand109a4d2020-07-28 10:42:13 +0100505 }
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100506 }
507
Keith Davisd305e1a2020-01-22 11:57:54 +0000508 float quantizationScale = 0.0f;
509 int32_t quantizationOffset = 0;
510
511 if (tensorPtr->quantization.get())
512 {
513 if (tensorPtr->quantization->scale.size() <= 1)
514 {
515 CHECK_VALID_SIZE(tensorPtr->quantization->zero_point.size(), 0, 1);
516 CHECK_VALID_SIZE(tensorPtr->quantization->zero_point.size(), 0, 1);
517
518 if (tensorPtr->quantization->scale.size() == 1)
519 {
520 quantizationScale = tensorPtr->quantization->scale[0];
521 }
522 if (tensorPtr->quantization->zero_point.size() == 1)
523 {
524 // NOTE: we lose precision here when converting from 64 bit to 32
Ryan OShea03181ff2020-02-07 17:22:22 +0000525 // but this is what we support at the moment in ArmNN
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100526 quantizationOffset = armnn::numeric_cast<int32_t>(tensorPtr->quantization->zero_point[0]);
Keith Davisd305e1a2020-01-22 11:57:54 +0000527 }
528
Sadik Armagand109a4d2020-07-28 10:42:13 +0100529 armnn::TensorInfo result(tensorShape,
530 type,
531 quantizationScale,
532 quantizationOffset);
Keith Davisd305e1a2020-01-22 11:57:54 +0000533 return result;
534 }
535 else
536 {
537 std::vector<float> quantizationScales;
538 std::vector<int32_t> quantizationOffsets;
539
540 // Scale
541 std::copy(tensorPtr->quantization->scale.begin(),
542 tensorPtr->quantization->scale.end(),
543 std::back_inserter(quantizationScales));
544
Keith Davis0c2eeac2020-02-11 16:51:50 +0000545 // QSymmS8 Per-axis
Sadik Armagand109a4d2020-07-28 10:42:13 +0100546 armnn::TensorInfo result(tensorShape,
547 type,
548 quantizationScales,
Jan Eilers7612bd62021-04-06 17:29:03 +0100549 armnn::numeric_cast<unsigned int>(tensorPtr->quantization->quantized_dimension));
Keith Davisd305e1a2020-01-22 11:57:54 +0000550 return result;
551 }
552 }
553 else
554 {
Sadik Armagand109a4d2020-07-28 10:42:13 +0100555 armnn::TensorInfo result(tensorShape,
Keith Davisd305e1a2020-01-22 11:57:54 +0000556 type,
557 quantizationScale,
558 quantizationOffset);
559 return result;
560 }
telsoa01c577f2c2018-08-31 09:22:23 +0100561}
562
Jan Eilers7612bd62021-04-06 17:29:03 +0100563armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr)
Narumol Prangnawarat4628d052019-02-25 17:26:05 +0000564{
Mike Kelly0d77ae12022-01-07 17:42:27 +0000565 auto const& dimensions = AsUnsignedVector(tensorPtr->shape);
Jan Eilers7612bd62021-04-06 17:29:03 +0100566 return ToTensorInfo(tensorPtr, dimensions);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +0000567}
568
Kevin May7d96b162021-02-03 17:38:41 +0000569armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr,
Sadik Armagand109a4d2020-07-28 10:42:13 +0100570 const bool outputTensor)
571{
Mike Kelly0d77ae12022-01-07 17:42:27 +0000572 auto const& dimensions = AsUnsignedVector(tensorPtr->shape);
Jan Eilers7612bd62021-04-06 17:29:03 +0100573 return ToTensorInfo(tensorPtr, dimensions, outputTensor);
Sadik Armagand109a4d2020-07-28 10:42:13 +0100574}
575
telsoa01c577f2c2018-08-31 09:22:23 +0100576template<typename T>
577std::pair<armnn::ConstTensor, std::unique_ptr<T[]>>
Kevin May7d96b162021-02-03 17:38:41 +0000578CreateConstTensorImpl(TfLiteParserImpl::BufferRawPtr bufferPtr,
579 TfLiteParserImpl::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +0000580 armnn::TensorInfo& tensorInfo,
581 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +0100582{
Jan Eilers8eb25602020-03-09 12:13:48 +0000583 IgnoreUnused(tensorPtr);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100584 ARMNN_ASSERT_MSG(tensorPtr != nullptr, "tensorPtr is null");
585 ARMNN_ASSERT_MSG(bufferPtr != nullptr,
James Ward58dec6b2020-09-11 17:32:44 +0100586 fmt::format("Buffer for buffer:{} is null", tensorPtr->buffer).c_str());
telsoa01c577f2c2018-08-31 09:22:23 +0100587
588 std::unique_ptr<T[]> data(new T[tensorInfo.GetNumElements()]);
Matteo Martincigh747ef822018-12-18 09:26:39 +0000589
590 if (permutationVector.has_value() && permutationVector.value().GetSize() > 0)
591 {
592 tensorInfo = armnnUtils::Permuted(tensorInfo, permutationVector.value());
Matteo Martincighd5b9e642019-01-04 18:01:21 +0000593 armnnUtils::Permute(tensorInfo.GetShape(), permutationVector.value(),
594 reinterpret_cast<const T*>(bufferPtr->data.data()), data.get(), sizeof(T));
Matteo Martincigh747ef822018-12-18 09:26:39 +0000595 }
596 else
597 {
598 ::memcpy(data.get(), bufferPtr->data.data(), tensorInfo.GetNumBytes());
599 }
600
Matthew Sloyan81beae32021-07-13 19:46:11 +0100601 // Make sure isConstant flag is set.
602 tensorInfo.SetConstant();
603
telsoa01c577f2c2018-08-31 09:22:23 +0100604 return std::make_pair(ConstTensor(tensorInfo, data.get()), std::move(data));
605}
606
telsoa01c577f2c2018-08-31 09:22:23 +0100607armnn::LayerBindingId GenerateLayerBindingId(size_t subgraphIndex, size_t tensorIndex)
608{
609 // generate the binding id by shifting the tensor id by 8 bit
610 // and add the subgraph id, which allows 256 subgraphs
611 return static_cast<armnn::LayerBindingId>((tensorIndex<<8)+subgraphIndex);
612}
613
Aron Virginas-Tar70672f62019-01-23 14:00:00 +0000614bool CheckShape(const armnn::TensorShape& actual, const std::vector<int32_t>& expected)
615{
616 const unsigned int actualSize = actual.GetNumDimensions();
617 if (actualSize != expected.size())
618 {
619 return false;
620 }
621
622 for (unsigned int i = 0u; i < actualSize; i++)
623 {
624 if (expected[i] < 0 ||
625 actual[i] != static_cast<unsigned int>(expected[i]))
626 {
627 return false;
628 }
629 }
630
631 return true;
632}
633
Cathal Corbett2b922e22022-09-23 15:49:24 +0100634bool CheckShape(const armnn::TensorShape& actual, const armnn::TensorShape& expected)
635{
636 std::vector<int32_t> expectedVec;
637 for (uint32_t i = 0; i < expected.GetNumDimensions(); i++)
638 {
639 expectedVec.push_back(expected[i]);
640 }
641 return CheckShape(actual, expectedVec);
642}
643
James Conroy05102392020-06-24 15:39:55 +0100644void CheckMatchingQuantization(const TensorInfo& first,
645 const TensorInfo& second,
646 const std::string& descName,
647 std::string const& firstName,
648 std::string const& secondName)
649{
650 if (!first.IsQuantized() ||
651 !second.IsQuantized())
652 {
653 // Not a quantized type, ignore the validation
654 return;
655 }
656
657 DataType firstDataType = first.GetDataType();
658 DataType secondDataType = second.GetDataType();
659
660 if (firstDataType != secondDataType)
661 {
662 throw InvalidArgumentException(descName + ": " + firstName + " and " + secondName +
663 " must be of the same quantized type, " +
664 firstName + " is " + GetDataTypeName(firstDataType) + ", " +
665 secondName + " is " + GetDataTypeName(secondDataType));
666 }
667
668 if (!first.IsTypeSpaceMatch(second))
669 {
670 throw InvalidArgumentException(descName + ": " + firstName + " and " + secondName +
671 " must have the same quantization space, " +
672 firstName + " has offset " + std::to_string(first.GetQuantizationOffset()) +
673 " and scale " + std::to_string(first.GetQuantizationScale()) + ", " +
674 secondName + " has offset " + std::to_string(second.GetQuantizationOffset()) +
675 " and scale " + std::to_string(second.GetQuantizationScale()));
676 }
677}
678
telsoa01c577f2c2018-08-31 09:22:23 +0100679} // <anonymous>
680
Kevin May7d96b162021-02-03 17:38:41 +0000681TfLiteParserImpl::TfLiteParserImpl(const Optional<ITfLiteParser::TfLiteParserOptions>& options)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100682: m_Options(options)
683, m_Network(nullptr, nullptr)
Kevin May7d96b162021-02-03 17:38:41 +0000684, m_ParserFunctions(tflite::BuiltinOperator_MAX+1, &TfLiteParserImpl::ParseUnsupportedOperator)
telsoa01c577f2c2018-08-31 09:22:23 +0100685{
686 // register supported operators
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100687 m_ParserFunctions[tflite::BuiltinOperator_ABS] = &TfLiteParserImpl::ParseAbs;
Kevin May7d96b162021-02-03 17:38:41 +0000688 m_ParserFunctions[tflite::BuiltinOperator_ADD] = &TfLiteParserImpl::ParseAdd;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100689 m_ParserFunctions[tflite::BuiltinOperator_ARG_MIN] = &TfLiteParserImpl::ParseArgMin;
690 m_ParserFunctions[tflite::BuiltinOperator_ARG_MAX] = &TfLiteParserImpl::ParseArgMax;
Kevin May7d96b162021-02-03 17:38:41 +0000691 m_ParserFunctions[tflite::BuiltinOperator_AVERAGE_POOL_2D] = &TfLiteParserImpl::ParseAveragePool2D;
692 m_ParserFunctions[tflite::BuiltinOperator_BATCH_TO_SPACE_ND] = &TfLiteParserImpl::ParseBatchToSpaceND;
Samuel Yapfd3ba5a2022-08-24 17:04:34 +0100693 m_ParserFunctions[tflite::BuiltinOperator_BATCH_MATMUL] = &TfLiteParserImpl::ParseBatchMatMul;
mathad01b392e982021-04-07 12:07:30 +0100694 m_ParserFunctions[tflite::BuiltinOperator_CAST] = &TfLiteParserImpl::ParseCast;
Kevin May7d96b162021-02-03 17:38:41 +0000695 m_ParserFunctions[tflite::BuiltinOperator_CONCATENATION] = &TfLiteParserImpl::ParseConcatenation;
696 m_ParserFunctions[tflite::BuiltinOperator_CONV_2D] = &TfLiteParserImpl::ParseConv2D;
Matthew Sloyan4d217c02021-10-07 11:48:58 +0100697 // Conv3D support was added in TF 2.5, so for backwards compatibility a hash define is needed.
Cathal Corbett80b4ef02022-05-25 11:21:11 +0100698 #if defined(ARMNN_POST_TFLITE_2_4)
Matthew Sloyaneb5f8102021-10-05 17:31:42 +0100699 m_ParserFunctions[tflite::BuiltinOperator_CONV_3D] = &TfLiteParserImpl::ParseConv3D;
Matthew Sloyan4d217c02021-10-07 11:48:58 +0100700 #endif
Kevin May7d96b162021-02-03 17:38:41 +0000701 m_ParserFunctions[tflite::BuiltinOperator_CUSTOM] = &TfLiteParserImpl::ParseCustomOperator;
702 m_ParserFunctions[tflite::BuiltinOperator_DEPTH_TO_SPACE] = &TfLiteParserImpl::ParseDepthToSpace;
703 m_ParserFunctions[tflite::BuiltinOperator_DEPTHWISE_CONV_2D] = &TfLiteParserImpl::ParseDepthwiseConv2D;
704 m_ParserFunctions[tflite::BuiltinOperator_DEQUANTIZE] = &TfLiteParserImpl::ParseDequantize;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100705 m_ParserFunctions[tflite::BuiltinOperator_DIV] = &TfLiteParserImpl::ParseDiv;
Kevin May7d96b162021-02-03 17:38:41 +0000706 m_ParserFunctions[tflite::BuiltinOperator_ELU] = &TfLiteParserImpl::ParseElu;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300707 m_ParserFunctions[tflite::BuiltinOperator_EQUAL] = &TfLiteParserImpl::ParseEqual;
Kevin May7d96b162021-02-03 17:38:41 +0000708 m_ParserFunctions[tflite::BuiltinOperator_EXP] = &TfLiteParserImpl::ParseExp;
Teresa Charlin3ab85482021-06-08 16:59:29 +0100709 m_ParserFunctions[tflite::BuiltinOperator_EXPAND_DIMS] = &TfLiteParserImpl::ParseExpandDims;
Teresa Charlincdbd40b2022-02-25 13:21:55 +0000710 m_ParserFunctions[tflite::BuiltinOperator_FLOOR_DIV] = &TfLiteParserImpl::ParseFloorDiv;
Kevin May7d96b162021-02-03 17:38:41 +0000711 m_ParserFunctions[tflite::BuiltinOperator_FULLY_CONNECTED] = &TfLiteParserImpl::ParseFullyConnected;
712 m_ParserFunctions[tflite::BuiltinOperator_GATHER] = &TfLiteParserImpl::ParseGather;
Teresa Charlin91a53ea2022-04-25 15:47:29 +0100713 m_ParserFunctions[tflite::BuiltinOperator_GATHER_ND] = &TfLiteParserImpl::ParseGatherNd;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300714 m_ParserFunctions[tflite::BuiltinOperator_GREATER] = &TfLiteParserImpl::ParseGreater;
715 m_ParserFunctions[tflite::BuiltinOperator_GREATER_EQUAL] = &TfLiteParserImpl::ParseGreaterOrEqual;
Kevin May7d96b162021-02-03 17:38:41 +0000716 m_ParserFunctions[tflite::BuiltinOperator_HARD_SWISH] = &TfLiteParserImpl::ParseHardSwish;
717 m_ParserFunctions[tflite::BuiltinOperator_LEAKY_RELU] = &TfLiteParserImpl::ParseLeakyRelu;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300718 m_ParserFunctions[tflite::BuiltinOperator_LESS] = &TfLiteParserImpl::ParseLess;
719 m_ParserFunctions[tflite::BuiltinOperator_LESS_EQUAL] = &TfLiteParserImpl::ParseLessOrEqual;
Mike Kelly31dce2b2021-09-01 21:22:37 +0100720 m_ParserFunctions[tflite::BuiltinOperator_LOCAL_RESPONSE_NORMALIZATION]
721 = &TfLiteParserImpl::ParseLocalResponseNormalization;
Teresa Charlin28aa6692022-07-12 11:18:44 +0100722 m_ParserFunctions[tflite::BuiltinOperator_LOG] = &TfLiteParserImpl::ParseLog;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100723 m_ParserFunctions[tflite::BuiltinOperator_LOGICAL_NOT] = &TfLiteParserImpl::ParseLogicalNot;
Kevin May7d96b162021-02-03 17:38:41 +0000724 m_ParserFunctions[tflite::BuiltinOperator_LOGISTIC] = &TfLiteParserImpl::ParseLogistic;
Teresa Charlinfd33a692022-06-29 15:35:57 +0100725 m_ParserFunctions[tflite::BuiltinOperator_LOG_SOFTMAX] = &TfLiteParserImpl::ParseLogSoftmax;
Kevin May7d96b162021-02-03 17:38:41 +0000726 m_ParserFunctions[tflite::BuiltinOperator_L2_NORMALIZATION] = &TfLiteParserImpl::ParseL2Normalization;
727 m_ParserFunctions[tflite::BuiltinOperator_MAX_POOL_2D] = &TfLiteParserImpl::ParseMaxPool2D;
728 m_ParserFunctions[tflite::BuiltinOperator_MAXIMUM] = &TfLiteParserImpl::ParseMaximum;
729 m_ParserFunctions[tflite::BuiltinOperator_MEAN] = &TfLiteParserImpl::ParseMean;
730 m_ParserFunctions[tflite::BuiltinOperator_MINIMUM] = &TfLiteParserImpl::ParseMinimum;
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +0100731 m_ParserFunctions[tflite::BuiltinOperator_MIRROR_PAD] = &TfLiteParserImpl::ParseMirrorPad;
Kevin May7d96b162021-02-03 17:38:41 +0000732 m_ParserFunctions[tflite::BuiltinOperator_MUL] = &TfLiteParserImpl::ParseMul;
733 m_ParserFunctions[tflite::BuiltinOperator_NEG] = &TfLiteParserImpl::ParseNeg;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300734 m_ParserFunctions[tflite::BuiltinOperator_NOT_EQUAL] = &TfLiteParserImpl::ParseNotEqual;
Kevin May7d96b162021-02-03 17:38:41 +0000735 m_ParserFunctions[tflite::BuiltinOperator_PACK] = &TfLiteParserImpl::ParsePack;
736 m_ParserFunctions[tflite::BuiltinOperator_PAD] = &TfLiteParserImpl::ParsePad;
Mike Kelly0d77ae12022-01-07 17:42:27 +0000737 m_ParserFunctions[tflite::BuiltinOperator_PADV2] = &TfLiteParserImpl::ParsePad;
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +0100738 m_ParserFunctions[tflite::BuiltinOperator_PRELU] = &TfLiteParserImpl::ParsePrelu;
Kevin May7d96b162021-02-03 17:38:41 +0000739 m_ParserFunctions[tflite::BuiltinOperator_QUANTIZE] = &TfLiteParserImpl::ParseQuantize;
740 m_ParserFunctions[tflite::BuiltinOperator_RELU] = &TfLiteParserImpl::ParseRelu;
741 m_ParserFunctions[tflite::BuiltinOperator_RELU6] = &TfLiteParserImpl::ParseRelu6;
Sadik Armagana2747482021-02-09 10:28:54 +0000742 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MAX] = &TfLiteParserImpl::ParseReduceMax;
743 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MIN] = &TfLiteParserImpl::ParseReduceMin;
Teresa Charlin4e3e8312021-08-05 12:34:37 +0100744 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_PROD] = &TfLiteParserImpl::ParseReduceProd;
Kevin May7d96b162021-02-03 17:38:41 +0000745 m_ParserFunctions[tflite::BuiltinOperator_RESHAPE] = &TfLiteParserImpl::ParseReshape;
746 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_BILINEAR] = &TfLiteParserImpl::ParseResizeBilinear;
747 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_NEAREST_NEIGHBOR] = &TfLiteParserImpl::ParseResizeNearestNeighbor;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100748 m_ParserFunctions[tflite::BuiltinOperator_RSQRT] = &TfLiteParserImpl::ParseRsqrt;
Teresa Charlinf0fce5b2022-05-04 17:24:43 +0100749 m_ParserFunctions[tflite::BuiltinOperator_SQRT] = &TfLiteParserImpl::ParseSqrt;
Keith Davis0176fd82021-06-01 17:36:32 +0100750 m_ParserFunctions[tflite::BuiltinOperator_SHAPE] = &TfLiteParserImpl::ParseShape;
Teresa Charlin28aa6692022-07-12 11:18:44 +0100751 m_ParserFunctions[tflite::BuiltinOperator_SIN] = &TfLiteParserImpl::ParseSin;
Kevin May7d96b162021-02-03 17:38:41 +0000752 m_ParserFunctions[tflite::BuiltinOperator_SLICE] = &TfLiteParserImpl::ParseSlice;
753 m_ParserFunctions[tflite::BuiltinOperator_SOFTMAX] = &TfLiteParserImpl::ParseSoftmax;
754 m_ParserFunctions[tflite::BuiltinOperator_SPACE_TO_BATCH_ND] = &TfLiteParserImpl::ParseSpaceToBatchND;
755 m_ParserFunctions[tflite::BuiltinOperator_SPLIT] = &TfLiteParserImpl::ParseSplit;
756 m_ParserFunctions[tflite::BuiltinOperator_SPLIT_V] = &TfLiteParserImpl::ParseSplitV;
757 m_ParserFunctions[tflite::BuiltinOperator_SQUEEZE] = &TfLiteParserImpl::ParseSqueeze;
758 m_ParserFunctions[tflite::BuiltinOperator_STRIDED_SLICE] = &TfLiteParserImpl::ParseStridedSlice;
759 m_ParserFunctions[tflite::BuiltinOperator_SUB] = &TfLiteParserImpl::ParseSub;
760 m_ParserFunctions[tflite::BuiltinOperator_SUM] = &TfLiteParserImpl::ParseSum;
761 m_ParserFunctions[tflite::BuiltinOperator_TANH] = &TfLiteParserImpl::ParseTanH;
762 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE] = &TfLiteParserImpl::ParseTranspose;
763 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE_CONV] = &TfLiteParserImpl::ParseTransposeConv;
Mike Kelly5880b912022-01-28 16:18:54 +0000764 m_ParserFunctions[tflite::BuiltinOperator_UNIDIRECTIONAL_SEQUENCE_LSTM]
765 = &TfLiteParserImpl::ParseUnidirectionalSequenceLSTM;
Kevin May7d96b162021-02-03 17:38:41 +0000766 m_ParserFunctions[tflite::BuiltinOperator_UNPACK] = &TfLiteParserImpl::ParseUnpack;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100767
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100768 // register supported custom operators
Kevin May7d96b162021-02-03 17:38:41 +0000769 m_CustomParserFunctions["TFLite_Detection_PostProcess"] = &TfLiteParserImpl::ParseDetectionPostProcess;
telsoa01c577f2c2018-08-31 09:22:23 +0100770}
771
Kevin May7d96b162021-02-03 17:38:41 +0000772void TfLiteParserImpl::ResetParser()
telsoa01c577f2c2018-08-31 09:22:23 +0100773{
774 m_Network = armnn::INetworkPtr(nullptr, nullptr);
775 m_Model = nullptr;
776 m_SubgraphConnections.clear();
Mike Kelly5880b912022-01-28 16:18:54 +0000777 m_OverridenOutputShapes.clear();
778 m_ConstantsToDequantize.clear();
779 m_ConstantsToBeCreated.clear();
telsoa01c577f2c2018-08-31 09:22:23 +0100780}
781
Kevin May7d96b162021-02-03 17:38:41 +0000782INetworkPtr TfLiteParserImpl::CreateNetworkFromBinaryFile(const char* graphFile)
telsoa01c577f2c2018-08-31 09:22:23 +0100783{
784 ResetParser();
785 m_Model = LoadModelFromFile(graphFile);
786 return CreateNetworkFromModel();
787}
788
Mike Kelly0d77ae12022-01-07 17:42:27 +0000789INetworkPtr TfLiteParserImpl::CreateNetworkFromBinary(const std::vector<uint8_t>& binaryContent)
telsoa01c577f2c2018-08-31 09:22:23 +0100790{
791 ResetParser();
792 m_Model = LoadModelFromBinary(binaryContent.data(), binaryContent.size());
793 return CreateNetworkFromModel();
794}
795
Finn Williamsb49ed182021-06-29 15:50:08 +0100796
797armnn::INetworkPtr TfLiteParserImpl::LoadModel(std::unique_ptr<tflite::ModelT> model)
798{
799 ResetParser();
800 m_Model = std::move(model);
801
802 return CreateNetworkFromModel();
803}
804
Kevin May7d96b162021-02-03 17:38:41 +0000805INetworkPtr TfLiteParserImpl::CreateNetworkFromModel()
telsoa01c577f2c2018-08-31 09:22:23 +0100806{
Sadik Armagand109a4d2020-07-28 10:42:13 +0100807
808 using NetworkOptions = std::vector<BackendOptions>;
809 NetworkOptions networkOptions = {};
Mike Kelly80512b02022-05-16 23:10:42 +0100810 if (m_Options)
Sadik Armagand109a4d2020-07-28 10:42:13 +0100811 {
Mike Kelly80512b02022-05-16 23:10:42 +0100812 if (m_Options.value().m_InferAndValidate)
813 {
814 BackendOptions shapeInferenceMethodOption("ShapeInferenceMethod",
815 {
816 { "InferAndValidate", true }
817 });
Sadik Armagand109a4d2020-07-28 10:42:13 +0100818
Mike Kelly80512b02022-05-16 23:10:42 +0100819 networkOptions.push_back(shapeInferenceMethodOption);
820 }
821 if (m_Options.value().m_AllowExpandedDims)
822 {
823 BackendOptions shapeInferenceMethodOption("AllowExpandedDims",
824 {
825 { "AllowExpandedDims", true }
826 });
827
828 networkOptions.push_back(shapeInferenceMethodOption);
829 }
Sadik Armagand109a4d2020-07-28 10:42:13 +0100830 }
Sadik Armagand109a4d2020-07-28 10:42:13 +0100831 m_Network = INetwork::Create(networkOptions);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100832 ARMNN_ASSERT(m_Model.get() != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +0100833
telsoa01c577f2c2018-08-31 09:22:23 +0100834 if (m_Model->subgraphs.size() != 1)
835 {
836 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100837 fmt::format("Current TfLite parser only supports 1 subgraph. Current one has: {} {}",
838 m_Model->subgraphs.size(),
839 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100840 }
841
842 size_t subgraphIndex = 0;
Colm Donelan6350d272020-06-09 16:56:25 +0100843 size_t operatorIndex = 0;
844 try
telsoa01c577f2c2018-08-31 09:22:23 +0100845 {
Colm Donelan6350d272020-06-09 16:56:25 +0100846 for (SubgraphPtr const& subgraph : m_Model->subgraphs)
telsoa01c577f2c2018-08-31 09:22:23 +0100847 {
Colm Donelan6350d272020-06-09 16:56:25 +0100848 m_SubgraphConnections.emplace_back(subgraph->tensors.size());
849 for (OperatorPtr const& op : subgraph->operators)
telsoa01c577f2c2018-08-31 09:22:23 +0100850 {
Colm Donelan6350d272020-06-09 16:56:25 +0100851 auto const& opCodePtr = m_Model->operator_codes[op->opcode_index];
Jim Flynnfca233e2021-09-23 12:16:53 +0100852
853// 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 +0100854#if defined(ARMNN_POST_TFLITE_2_3)
Jim Flynnfca233e2021-09-23 12:16:53 +0100855 auto builtinCode = std::max(opCodePtr->builtin_code,
856 static_cast<tflite::BuiltinOperator>(opCodePtr->deprecated_builtin_code));
857#else
telsoa01c577f2c2018-08-31 09:22:23 +0100858 auto builtinCode = opCodePtr->builtin_code;
Jim Flynnfca233e2021-09-23 12:16:53 +0100859#endif
telsoa01c577f2c2018-08-31 09:22:23 +0100860
861 if (builtinCode > tflite::BuiltinOperator_MAX)
862 {
James Ward58dec6b2020-09-11 17:32:44 +0100863 throw ParseException(fmt::format("Operator code {} is out of range 0-{}. "
864 "subgraph:{} operator idx:{}. {}",
865 builtinCode, tflite::BuiltinOperator_MAX, subgraphIndex,
866 operatorIndex, CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100867 }
868
869 // lookup and call the parser function
Colm Donelan6350d272020-06-09 16:56:25 +0100870 auto& parserFunction = m_ParserFunctions[builtinCode];
telsoa01c577f2c2018-08-31 09:22:23 +0100871 (this->*parserFunction)(subgraphIndex, operatorIndex);
Colm Donelan6350d272020-06-09 16:56:25 +0100872 ++operatorIndex;
telsoa01c577f2c2018-08-31 09:22:23 +0100873 }
telsoa01c577f2c2018-08-31 09:22:23 +0100874
Colm Donelan6350d272020-06-09 16:56:25 +0100875 SetupInputLayers(subgraphIndex);
876 SetupOutputLayers(subgraphIndex);
877 SetupConstantLayers(subgraphIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100878
Colm Donelan6350d272020-06-09 16:56:25 +0100879 ++subgraphIndex;
880 operatorIndex = 0;
telsoa01c577f2c2018-08-31 09:22:23 +0100881 }
telsoa01c577f2c2018-08-31 09:22:23 +0100882 }
Colm Donelan6350d272020-06-09 16:56:25 +0100883 catch (const ParseException& e)
telsoa01c577f2c2018-08-31 09:22:23 +0100884 {
Colm Donelan6350d272020-06-09 16:56:25 +0100885 std::stringstream errorString;
886 errorString << "Failed to parse operator #" << operatorIndex << " within subgraph #"
887 << subgraphIndex << " error: " << e.what();
888 ARMNN_LOG(error) << errorString.str();
889 std::stringstream errors;
890 errors << errorString.str() << "\n";
telsoa01c577f2c2018-08-31 09:22:23 +0100891 throw ParseException(errors.str());
892 }
893
894 // establish the connections from the layer outputs to the inputs of the subsequent layers
Colm Donelan6350d272020-06-09 16:56:25 +0100895 for (subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100896 {
897 for (size_t tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
898 {
899 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot != nullptr)
900 {
901 for (size_t inputSlotIdx = 0;
902 inputSlotIdx < m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size();
903 ++inputSlotIdx)
904 {
905 m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot->Connect(
906 *(m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots[inputSlotIdx]));
907 }
908 }
909 }
910 }
telsoa01c577f2c2018-08-31 09:22:23 +0100911 return std::move(m_Network);
912}
913
Mike Kelly5880b912022-01-28 16:18:54 +0000914std::unique_ptr<float[]> AsFloatArray(TfLiteParserImpl::BufferRawPtr bufferPtr,
915 const TensorInfo& tensorInfo)
916{
917 if (tensorInfo.GetDataType() == DataType::QAsymmS8 || tensorInfo.GetDataType() == DataType::QSymmS8 ||
918 tensorInfo.GetDataType() == DataType::QAsymmU8)
919 {
920 std::unique_ptr<float[]> buffer(new float[tensorInfo.GetNumElements()]);
921
922 if (tensorInfo.HasPerAxisQuantization())
923 {
924 unsigned int axis = tensorInfo.GetQuantizationDim().value();
925 auto axisDimensionality = tensorInfo.GetShape()[axis];
926 auto axisFactor = armnnUtils::GetNumElementsAfter(tensorInfo.GetShape(), axis);
927
928 for (unsigned int i = 0; i < tensorInfo.GetNumDimensions(); ++i)
929 {
930 unsigned int axisIndex = (i / axisFactor) % axisDimensionality;
931 buffer[i] = Dequantize<int8_t>(bufferPtr->data[i], tensorInfo.GetQuantizationScales()[axisIndex],
932 tensorInfo.GetQuantizationOffset());
933 }
934 }
935 else
936 {
937 for (unsigned int i = 0; i < tensorInfo.GetNumElements(); ++i)
938 {
939 buffer[i] = Dequantize<int8_t>(bufferPtr->data[i], tensorInfo.GetQuantizationScale(),
940 tensorInfo.GetQuantizationOffset());
941 }
942 }
943 return buffer;
944 }
945 throw ParseException(
946 fmt::format("Unsupported input/weights combination: Input {} not supported with Weights {}",
947 GetDataTypeName(DataType::Float32),
948 GetDataTypeName(tensorInfo.GetDataType()),
949 CHECK_LOCATION().AsString()));
950}
951
Kevin May7d96b162021-02-03 17:38:41 +0000952void TfLiteParserImpl::RegisterProducerOfTensor(size_t subgraphIndex,
953 size_t tensorIndex,
954 armnn::IOutputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +0100955{
956 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100957 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
958 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100959
960 TensorSlots & tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
961
Nikhil Rajd4d1c312022-08-03 18:20:59 +0100962 if (slot->GetOwningIConnectableLayer().GetType() != LayerType::Constant)
telsoa01c577f2c2018-08-31 09:22:23 +0100963 {
telsoa01c577f2c2018-08-31 09:22:23 +0100964
Nikhil Rajd4d1c312022-08-03 18:20:59 +0100965 // assuming there is only one producer for that tensor
966 if (tensorSlots.outputSlot != nullptr)
967 {
968 throw ParseException(fmt::format("Another layer has already registered itself as the producer of "
969 "subgraph:{} tensor:{} {}",
970 subgraphIndex,
971 tensorIndex,
972 CHECK_LOCATION().AsString()));
973 }
974 }
telsoa01c577f2c2018-08-31 09:22:23 +0100975 tensorSlots.outputSlot = slot;
976}
977
Kevin May7d96b162021-02-03 17:38:41 +0000978void TfLiteParserImpl::RegisterConsumerOfTensor(size_t subgraphIndex,
979 size_t tensorIndex,
980 armnn::IInputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +0100981{
982 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100983 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
984 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100985
Finn Williamsd4fa5452021-03-01 12:31:41 +0000986 TensorSlots& tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +0100987 tensorSlots.inputSlots.push_back(slot);
988}
989
Kevin May7d96b162021-02-03 17:38:41 +0000990void TfLiteParserImpl::ParseCustomOperator(size_t subgraphIndex, size_t operatorIndex)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100991{
992 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
993
994 // NOTE: By default we presume the custom operator is not supported
Kevin May7d96b162021-02-03 17:38:41 +0000995 auto customParserFunction = &TfLiteParserImpl::ParseUnsupportedOperator;
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100996
997 // Identify custom code defined for custom operator
998 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
999 const auto& customCode = m_Model->operator_codes[operatorPtr->opcode_index]->custom_code;
1000
1001 // Find parser function that correspondes to custom code (if any)
1002 auto iterator = m_CustomParserFunctions.find(customCode);
1003 if (iterator != m_CustomParserFunctions.end())
1004 {
1005 customParserFunction = iterator->second;
1006 }
1007
1008 // Run parser function
1009 (this->*customParserFunction)(subgraphIndex, operatorIndex);
1010}
1011
Kevin May7d96b162021-02-03 17:38:41 +00001012void TfLiteParserImpl::ParseUnsupportedOperator(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001013{
1014 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001015
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001016 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1017
1018 auto opcodeIndex = operatorPtr->opcode_index;
Jim Flynnfca233e2021-09-23 12:16:53 +01001019
1020// 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 +01001021#if defined(ARMNN_POST_TFLITE_2_3)
Jim Flynnfca233e2021-09-23 12:16:53 +01001022 auto opcode = std::max(m_Model->operator_codes[opcodeIndex]->builtin_code,
1023 static_cast<tflite::BuiltinOperator>(m_Model->operator_codes[opcodeIndex]->deprecated_builtin_code));
1024#else
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001025 auto opcode = m_Model->operator_codes[opcodeIndex]->builtin_code;
Jim Flynnfca233e2021-09-23 12:16:53 +01001026#endif
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001027
1028 if (!m_Options || !m_Options.value().m_StandInLayerForUnsupported)
1029 {
1030 // Do not add StandInLayer, throw ParseException instead
1031 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01001032 fmt::format("Operator not supported. "
1033 "subgraph:{} operator:{} "
1034 "opcode_index:{} opcode:{} / {} {}",
1035 subgraphIndex,
1036 operatorIndex,
1037 opcodeIndex,
1038 opcode,
1039 tflite::EnumNameBuiltinOperator(opcode),
1040 CHECK_LOCATION().AsString()));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001041 }
1042
1043 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1044 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1045
Matthew Sloyan589e3e82020-09-11 16:17:48 +01001046 const unsigned int numInputs = armnn::numeric_cast<unsigned int>(inputs.size());
1047 const unsigned int numOutputs = armnn::numeric_cast<unsigned int>(outputs.size());
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001048
1049 StandInDescriptor descriptor(numInputs, numOutputs);
James Ward58dec6b2020-09-11 17:32:44 +01001050 auto layerName = fmt::format("StandIn:{}:{}:{}", subgraphIndex, operatorIndex, opcode);
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001051
1052 // Add a non-executable StandInLayer as a placeholder for any unsupported operator
1053 IConnectableLayer* layer = m_Network->AddStandInLayer(descriptor, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001054 ARMNN_ASSERT(layer != nullptr);
1055
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001056 for (unsigned int i = 0u; i < numOutputs; ++i)
1057 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01001058 layer->GetOutputSlot(i).SetTensorInfo(ToTensorInfo(outputs[i], true));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +01001059 }
1060
1061 auto inputTensorIds = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1062 auto outputTensorIds = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1063
1064 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIds);
1065 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIds);
telsoa01c577f2c2018-08-31 09:22:23 +01001066}
1067
mathad01b392e982021-04-07 12:07:30 +01001068void TfLiteParserImpl::ParseCast(size_t subgraphIndex, size_t operatorIndex)
1069{
1070 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1071
1072 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1073 CHECK_VALID_SIZE(inputs.size(), 1);
1074 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1075 CHECK_VALID_SIZE(outputs.size(), 1);
1076
1077 auto layerName = fmt::format("Cast:{}:{}", subgraphIndex, operatorIndex);
1078
1079 IConnectableLayer* layer = m_Network->AddCastLayer(layerName.c_str());
1080 ARMNN_ASSERT(layer != nullptr);
1081
1082 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1083 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1084
1085 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1086 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1087
1088 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1089 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1090}
1091
Kevin May7d96b162021-02-03 17:38:41 +00001092void TfLiteParserImpl::ParseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001093{
1094 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1095
Mike Kelly0d77ae12022-01-07 17:42:27 +00001096 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1097 const auto* options = operatorPtr->builtin_options.AsConv2DOptions();
telsoa01c577f2c2018-08-31 09:22:23 +01001098
1099 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1100
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001101 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1102 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1103 CHECK_VALID_SIZE(outputs.size(), 1);
1104
telsoa01c577f2c2018-08-31 09:22:23 +01001105 Convolution2dDescriptor desc;
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001106 inputs.size() == 3 ?
1107 desc.m_BiasEnabled = true : desc.m_BiasEnabled = false;
telsoa01c577f2c2018-08-31 09:22:23 +01001108 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1109 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +00001110 desc.m_DataLayout = armnn::DataLayout::NHWC;
Pablo Tellof0bd6832019-04-26 17:58:13 +01001111 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1112 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +00001113
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001114 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
telsoa01c577f2c2018-08-31 09:22:23 +01001115 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
1116
1117 // assuming input is NHWC
1118 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001119 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
telsoa01c577f2c2018-08-31 09:22:23 +01001120
1121 // assuming the filter is OHWI : Output, H, W, Input
1122 // which is essentially the same as NHWC
1123 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001124 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
telsoa01c577f2c2018-08-31 09:22:23 +01001125
Pablo Tellof0bd6832019-04-26 17:58:13 +01001126 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1127 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1128 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1129 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +01001130
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001131 // Add the first input and weights tensor to the registration list.
1132 // The constant weights will be added by SetupConstantLayers.
1133 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1134 std::vector<unsigned int> tensorIndexesToRegister = { inputTensorIndexes[0], inputTensorIndexes[1] };
telsoa01c577f2c2018-08-31 09:22:23 +01001135
James Ward58dec6b2020-09-11 17:32:44 +01001136 auto layerName = fmt::format("Conv2D:{}:{}", subgraphIndex, operatorIndex);
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001137 armnn::IConnectableLayer* layer = m_Network->AddConvolution2dLayer(desc, layerName.c_str());
telsoa01c577f2c2018-08-31 09:22:23 +01001138
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001139 if (IsConstTensor(inputs[1]) && inputTensorInfo.GetDataType() == DataType::Float32 &&
1140 (filterTensorInfo.GetDataType() == DataType::QAsymmU8 ||
1141 filterTensorInfo.GetDataType() == DataType::QAsymmS8))
telsoa01c577f2c2018-08-31 09:22:23 +01001142 {
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001143 m_ConstantsToDequantize.emplace_back(inputs[1]->buffer);
telsoa01c577f2c2018-08-31 09:22:23 +01001144 }
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001145
1146 if (desc.m_BiasEnabled)
telsoa01c577f2c2018-08-31 09:22:23 +01001147 {
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001148 armnn::TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
1149
1150 // Add the biases input to the registration list, a constant layer will be added by SetupConstantLayers.
1151 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
1152
1153 if (IsConstTensor(inputs[2]) && inputTensorInfo.GetDataType() == DataType::Float32 &&
1154 (filterTensorInfo.GetDataType() == DataType::QAsymmU8 ||
1155 filterTensorInfo.GetDataType() == DataType::QAsymmS8))
1156 {
1157 m_ConstantsToDequantize.emplace_back(inputs[2]->buffer);
1158 }
telsoa01c577f2c2018-08-31 09:22:23 +01001159 }
1160
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001161 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01001162
Sadik Armagand109a4d2020-07-28 10:42:13 +01001163 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
jimfly01c25411c2018-11-14 17:47:22 +00001164 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001165
1166 // register the input connection slots for the layer, connections are made after all layers have been created
1167 // only the tensors for the inputs are relevant, exclude the const tensors
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001168 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
telsoa01c577f2c2018-08-31 09:22:23 +01001169
jimfly01c25411c2018-11-14 17:47:22 +00001170 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +01001171 // register the output connection slots for the layer, connections are made after all layers have been created
1172 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
Keith Davisb4dd5cc2022-04-07 11:32:00 +01001173 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, { outputTensorIndexes[0] });
telsoa01c577f2c2018-08-31 09:22:23 +01001174}
1175
Matthew Sloyan4d217c02021-10-07 11:48:58 +01001176// Conv3D support was added in TF 2.5, so for backwards compatibility a hash define is needed.
Cathal Corbett80b4ef02022-05-25 11:21:11 +01001177#if defined(ARMNN_POST_TFLITE_2_4)
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001178void TfLiteParserImpl::ParseConv3D(size_t subgraphIndex, size_t operatorIndex)
1179{
1180 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1181
1182 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1183 const auto* options = operatorPtr->builtin_options.AsConv3DOptions();
1184
1185 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1186
1187 Convolution3dDescriptor desc;
1188 desc.m_BiasEnabled = false;
1189 desc.m_DataLayout = armnn::DataLayout::NDHWC;
1190 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1191 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1192 desc.m_StrideZ = CHECKED_NON_NEGATIVE(options->stride_d);
1193 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1194 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
1195 desc.m_DilationZ = CHECKED_NON_NEGATIVE(options->dilation_d_factor);
1196
1197 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1198 CHECK_VALID_SIZE(inputs.size(), 2, 3);
1199
1200 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1201 CHECK_VALID_SIZE(outputs.size(), 1);
1202
1203 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1204 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
1205
1206 // Assuming input is NDHWC
1207 unsigned int inputDepth = inputTensorInfo.GetShape()[1];
1208 unsigned int inputHeight = inputTensorInfo.GetShape()[2];
1209 unsigned int inputWidth = inputTensorInfo.GetShape()[3];
1210
1211 // Assuming the filter is DHWIO : Depth, Height, Width, OutputChannels, InputChannels
1212 unsigned int filterDepth = filterTensorInfo.GetShape()[0];
1213 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1214 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1215
1216 CalcPadding(inputDepth, filterDepth, desc.m_StrideZ,
Teresa Charlin502ab942022-03-23 17:23:07 +00001217 desc.m_DilationZ, desc.m_PadFront, desc.m_PadBack, options->padding);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001218 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1219 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1220 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1221 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
1222
Mike Kelly5880b912022-01-28 16:18:54 +00001223 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo, inputTensorInfo.GetDataType());
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001224
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001225 auto layerName = fmt::format("Conv3D:{}:{}", subgraphIndex, operatorIndex);
1226
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001227 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1228 // Add the first input and weights tensor to the registration list.
1229 // The constant weights will be added by SetupConstantLayers.
1230 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0], inputTensorIndexes[1]};
1231
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001232 if (inputs.size() == 3)
1233 {
1234 desc.m_BiasEnabled = true;
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001235
1236 // Add the biases input to the registration list, a constant layer will be added by SetupConstantLayers.
1237 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001238 }
1239
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001240 armnn::IConnectableLayer* layer = m_Network->AddConvolution3dLayer(desc, layerName.c_str());
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001241 ARMNN_ASSERT(layer != nullptr);
1242
1243 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1244 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1245
1246 // Register the input connection slots for the layer, connections are made after all layers have been created
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001247 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001248
1249 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1250 // Register the output connection slots for the layer, connections are made after all layers have been created
1251 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1252 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1253}
Matthew Sloyan4d217c02021-10-07 11:48:58 +01001254#endif
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001255
Kevin May7d96b162021-02-03 17:38:41 +00001256void TfLiteParserImpl::ParseDepthwiseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001257{
1258 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1259
Mike Kelly0d77ae12022-01-07 17:42:27 +00001260 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1261 const auto* options = operatorPtr->builtin_options.AsDepthwiseConv2DOptions();
telsoa01c577f2c2018-08-31 09:22:23 +01001262
1263 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1264
1265 DepthwiseConvolution2dDescriptor desc;
telsoa01c577f2c2018-08-31 09:22:23 +01001266 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1267 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +00001268 desc.m_DataLayout = armnn::DataLayout::NHWC;
Matthew Jacksond6a9dee2019-07-22 13:53:24 +01001269 CHECKED_NON_NEGATIVE(options->depth_multiplier);
telsoa01c577f2c2018-08-31 09:22:23 +01001270
1271 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1272 CHECK_VALID_SIZE(inputs.size(), 2, 3);
Cathal Corbett06902652022-04-14 17:55:11 +01001273 if (inputs.size() == 3)
1274 {
1275 desc.m_BiasEnabled = true;
1276 }
1277
telsoa01c577f2c2018-08-31 09:22:23 +01001278 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1279 CHECK_VALID_SIZE(outputs.size(), 1);
Pablo Tellof0bd6832019-04-26 17:58:13 +01001280 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1281 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +00001282
telsoa01c577f2c2018-08-31 09:22:23 +01001283 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Jan Eilers7612bd62021-04-06 17:29:03 +01001284 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
telsoa01c577f2c2018-08-31 09:22:23 +01001285
Matteo Martincigh747ef822018-12-18 09:26:39 +00001286 // Assuming input is NHWC
telsoa01c577f2c2018-08-31 09:22:23 +01001287 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1288 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
Matteo Martincigh747ef822018-12-18 09:26:39 +00001289
1290 // TensorflowLite weights come in the format [1, H, W, I * M]
telsoa01c577f2c2018-08-31 09:22:23 +01001291 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1292 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1293
Pablo Tellof0bd6832019-04-26 17:58:13 +01001294 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1295 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1296 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1297 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +01001298
Jan Eilers53ef7952021-06-02 12:01:25 +01001299 // 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 +01001300 auto layerName = fmt::format("DepthwiseConv2D:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001301
Cathal Corbett06902652022-04-14 17:55:11 +01001302 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1303 // Add the first input and weights tensor to the registration list.
1304 // The constant weights will be added by SetupConstantLayers.
1305 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0], inputTensorIndexes[1]};
1306
1307 armnn::IConnectableLayer* layer = m_Network->AddDepthwiseConvolution2dLayer(desc, layerName.c_str());
1308
1309 if (desc.m_BiasEnabled)
telsoa01c577f2c2018-08-31 09:22:23 +01001310 {
1311 desc.m_BiasEnabled = true;
1312 TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Cathal Corbett06902652022-04-14 17:55:11 +01001313
1314 // Add the biases input to the registration list, a constant layer will be added by SetupConstantLayers.
1315 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
telsoa01c577f2c2018-08-31 09:22:23 +01001316 }
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001317 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01001318
Sadik Armagand109a4d2020-07-28 10:42:13 +01001319 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
jimfly01c25411c2018-11-14 17:47:22 +00001320 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001321
1322 // register the input connection slots for the layer, connections are made after all layers have been created
1323 // only the tensors for the inputs are relevant, exclude the const tensors
Cathal Corbett06902652022-04-14 17:55:11 +01001324 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
telsoa01c577f2c2018-08-31 09:22:23 +01001325
jimfly01c25411c2018-11-14 17:47:22 +00001326 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +01001327 // register the output connection slots for the layer, connections are made after all layers have been created
1328 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1329 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1330}
1331
Kevin May7d96b162021-02-03 17:38:41 +00001332void TfLiteParserImpl::ParseDequantize(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsed66d142019-12-06 09:55:55 +00001333{
1334 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1335
1336 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1337 CHECK_VALID_SIZE(inputs.size(), 1);
1338
1339 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1340 CHECK_VALID_SIZE(outputs.size(), 1);
1341
James Ward58dec6b2020-09-11 17:32:44 +01001342 auto layerName = fmt::format("Dequantize:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsed66d142019-12-06 09:55:55 +00001343
1344 IConnectableLayer* layer = m_Network->AddDequantizeLayer(layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001345 ARMNN_ASSERT(layer != nullptr);
Finn Williamsed66d142019-12-06 09:55:55 +00001346
Sadik Armagand109a4d2020-07-28 10:42:13 +01001347 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Finn Williamsed66d142019-12-06 09:55:55 +00001348 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1349
1350 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1351 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1352
1353 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1354 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1355}
1356
Teresa Charlin3ab85482021-06-08 16:59:29 +01001357void TfLiteParserImpl::ParseExpandDims(size_t subgraphIndex, size_t operatorIndex)
1358{
1359 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1360
1361 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1362 CHECK_VALID_SIZE(inputs.size(), 2);
1363
1364 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1365 CHECK_VALID_SIZE(outputs.size(), 1);
1366
1367 auto layerName = fmt::format("ExpandDims:{}:{}", subgraphIndex, operatorIndex);
1368
1369 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1370 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1371
1372 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1373
1374 ReshapeDescriptor reshapeDesc;
Finn Williamsb49ed182021-06-29 15:50:08 +01001375
1376 if (outputTensorInfo.GetShape().AreAllDimensionsSpecified())
1377 {
1378 reshapeDesc.m_TargetShape = outputTensorInfo.GetShape();
1379 }
1380 else
1381 {
1382 int32_t axis = inputs[1]->shape[0];
1383
1384 int32_t inputDimSize = static_cast<int32_t>(inputTensorInfo.GetShape().GetNumDimensions());
1385
1386 if (axis > inputDimSize || axis < 0 - (inputDimSize + 1))
1387 {
1388 throw ParseException("axis must be in range [0 - (inputDimSize + 1), inputDimSize] inclusive");
1389 }
1390
1391 if(axis < 0)
1392 {
1393 axis = inputDimSize + axis + 1;
1394 }
1395
Rob Hughesd812a312021-08-06 13:10:53 +01001396 std::vector<unsigned int> shape(static_cast<unsigned int>(inputDimSize) + 1);
Finn Williamsb49ed182021-06-29 15:50:08 +01001397 unsigned int inputShapeIndex = 0;
1398 for (unsigned int i = 0; i < static_cast<unsigned int>(inputDimSize + 1); ++i)
1399 {
1400 if (i == static_cast<unsigned int>(axis))
1401 {
1402 shape[i] = 1;
1403 }
1404 else
1405 {
1406 shape[i] = inputTensorInfo.GetShape()[inputShapeIndex];
1407 ++inputShapeIndex;
1408 }
1409 }
1410
Rob Hughesd812a312021-08-06 13:10:53 +01001411 reshapeDesc.m_TargetShape = TensorShape(static_cast<unsigned int>(inputDimSize + 1), shape.data());
Finn Williamsb49ed182021-06-29 15:50:08 +01001412 }
Teresa Charlin3ab85482021-06-08 16:59:29 +01001413
1414 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
1415 ARMNN_ASSERT(layer != nullptr);
1416 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1417
1418 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1419 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1420
1421 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1422 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1423}
1424
Kevin May7d96b162021-02-03 17:38:41 +00001425void TfLiteParserImpl::ParseTranspose(size_t subgraphIndex, size_t operatorIndex)
Keith Davis4cd29a02019-09-09 14:49:20 +01001426{
1427 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1428
1429 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Kevin May85d92602019-09-27 17:21:06 +01001430 CHECK_VALID_SIZE(inputs.size(), 1, 2);
Keith Davis4cd29a02019-09-09 14:49:20 +01001431
1432 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1433 CHECK_VALID_SIZE(outputs.size(), 1);
1434
James Ward58dec6b2020-09-11 17:32:44 +01001435 auto layerName = fmt::format("Transpose:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly08759e22020-03-02 11:41:31 +00001436 TransposeDescriptor desc;
Keith Davis4cd29a02019-09-09 14:49:20 +01001437
josh minorba424d22019-11-13 10:55:17 -06001438 if (inputs.size() == 2)
Kevin May85d92602019-09-27 17:21:06 +01001439 {
1440 armnn::TensorInfo permuteTensorInfo = ToTensorInfo(inputs[1]);
1441 BufferRawPtr permuteBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
josh minorba424d22019-11-13 10:55:17 -06001442 auto numPermVecElements = permuteTensorInfo.GetNumElements();
1443 std::vector<unsigned int> permuteShape(numPermVecElements);
Kevin May85d92602019-09-27 17:21:06 +01001444 ::memcpy(permuteShape.data(), permuteBufferPtr->data.data(), permuteTensorInfo.GetNumBytes());
Mike Kelly08759e22020-03-02 11:41:31 +00001445 PermutationVector permutationVector(permuteShape.data(), permuteTensorInfo.GetNumElements());
Kevin May85d92602019-09-27 17:21:06 +01001446
Mike Kelly08759e22020-03-02 11:41:31 +00001447 desc = TransposeDescriptor(permutationVector);
Kevin May85d92602019-09-27 17:21:06 +01001448 }
1449
James Conroy05102392020-06-24 15:39:55 +01001450 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001451 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001452 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Keith Davis4cd29a02019-09-09 14:49:20 +01001453
James Conroy05102392020-06-24 15:39:55 +01001454 IConnectableLayer* layer = m_Network->AddTransposeLayer(desc, layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001455 ARMNN_ASSERT(layer != nullptr);
Keith Davis4cd29a02019-09-09 14:49:20 +01001456 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1457
1458 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1459 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1460
1461 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1462 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1463}
1464
Kevin May7d96b162021-02-03 17:38:41 +00001465void TfLiteParserImpl::ParseTransposeConv(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001466{
1467 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1468
Mike Kelly0d77ae12022-01-07 17:42:27 +00001469 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1470 const auto* options = operatorPtr->builtin_options.AsTransposeConvOptions();
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001471
1472 TransposeConvolution2dDescriptor desc;
1473 desc.m_BiasEnabled = false;
1474 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1475 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1476 desc.m_DataLayout = armnn::DataLayout::NHWC;
1477
1478 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
David Monahan61683802021-01-12 09:11:07 +00001479 if (inputs.size() == 4)
1480 {
1481 desc.m_BiasEnabled = true;
1482 }
1483 else
1484 {
1485 CHECK_VALID_SIZE(inputs.size(), 3);
1486 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001487
1488 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1489 CHECK_VALID_SIZE(outputs.size(), 1);
1490
Colm Donelan0ad3ef12020-07-03 15:54:28 +01001491 if (inputs[0])
1492 {
1493 armnn::TensorInfo tensorInfo = ToTensorInfo(inputs[0]);
1494 std::vector<int> output_shape(tensorInfo.GetNumElements());
1495 if (tensorInfo.GetDataType() == DataType::Signed32)
1496 {
1497 ::memcpy(output_shape.data(), GetBuffer(m_Model, inputs[0]->buffer)->data.data(), tensorInfo.GetNumBytes());
1498 }
1499 if (tensorInfo.GetDataType() == DataType::QAsymmU8)
1500 {
1501 for(unsigned int i=0; i < tensorInfo.GetNumElements(); i++)
1502 {
1503 output_shape[i] = GetBuffer(m_Model, inputs[0]->buffer)->data.data()[i];
1504 }
1505 }
1506 // Change from signed to unsigned int to store in TransposeConvolution2dDescriptor.
1507 for (int dimension : output_shape)
1508 {
1509 desc.m_OutputShape.push_back(static_cast<unsigned int>(dimension));
1510 }
1511 desc.m_OutputShapeEnabled = true;
1512 }
Matthew Jacksonccb25ea2019-08-20 17:18:33 +01001513 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[2]);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001514 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
1515
1516 // TfLite uses NHWC tensors
1517 const unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1518 const unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1519
1520 const unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1521 const unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1522
1523 CalcPadding(inputHeight,
1524 filterHeight,
1525 desc.m_StrideY,
1526 1, // DilationY
1527 desc.m_PadTop,
1528 desc.m_PadBottom,
1529 options->padding);
1530
1531 CalcPadding(inputWidth,
1532 filterWidth,
1533 desc.m_StrideX,
1534 1, // DilationX
1535 desc.m_PadLeft,
1536 desc.m_PadRight,
1537 options->padding);
1538
Mike Kelly5880b912022-01-28 16:18:54 +00001539 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo, inputTensorInfo.GetDataType());
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001540
1541 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01001542 auto layerName = fmt::format("TransposeConv:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001543
David Monahan61683802021-01-12 09:11:07 +00001544 if (desc.m_BiasEnabled)
1545 {
1546 auto biasTensorInfo = ToTensorInfo(inputs[3]);
Mike Kelly5880b912022-01-28 16:18:54 +00001547 auto biasConstTensor = CreateConstTensorNonPermuted(inputs[3], biasTensorInfo, inputTensorInfo.GetDataType());
David Monahan61683802021-01-12 09:11:07 +00001548 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Mike Kelly5880b912022-01-28 16:18:54 +00001549 filterTensorAndData.first,
1550 biasConstTensor.first,
David Monahan61683802021-01-12 09:11:07 +00001551 layerName.c_str());
1552 }
1553 else
1554 {
1555 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Mike Kelly5880b912022-01-28 16:18:54 +00001556 filterTensorAndData.first,
David Monahan61683802021-01-12 09:11:07 +00001557 EmptyOptional(),
1558 layerName.c_str());
1559 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001560
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001561 ARMNN_ASSERT(layer != nullptr);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001562
Sadik Armagand109a4d2020-07-28 10:42:13 +01001563 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001564 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1565
1566 // only the tensors for the inputs are relevant, exclude the const (filter) tensor
1567 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Matthew Jacksonccb25ea2019-08-20 17:18:33 +01001568 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[2]});
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001569
1570 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1571 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1572}
1573
Kevin May7d96b162021-02-03 17:38:41 +00001574void TfLiteParserImpl::ParseAveragePool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001575{
1576 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Average);
1577}
1578
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001579void TfLiteParserImpl::ParseBatchMatMul(size_t subgraphIndex, size_t operatorIndex)
1580{
1581 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1582
1583 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1584 CHECK_VALID_SIZE(inputs.size(), 2);
1585
1586 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1587 CHECK_VALID_SIZE(outputs.size(), 1);
1588
1589 auto layerName = fmt::format("BatchMatMul:{}:{}", subgraphIndex, operatorIndex);
1590
1591 TensorInfo inputXTensorInfo = ToTensorInfo(inputs[0]);
1592 TensorInfo inputYTensorInfo = ToTensorInfo(inputs[1]);
1593
1594 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1595
1596 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1597 const auto* options = operatorPtr->builtin_options.AsBatchMatMulOptions();
1598
Teresa Charlinbc37a6b2022-09-22 10:12:58 +01001599 // Adjoint in tensorflow lite performs transpose operation
1600 BatchMatMulDescriptor descriptor(options->adj_x,
1601 options->adj_y,
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001602 false,
Teresa Charlinbc37a6b2022-09-22 10:12:58 +01001603 false);
Samuel Yapfd3ba5a2022-08-24 17:04:34 +01001604 // Arbitrary DataLayout
1605
1606 IConnectableLayer* layer = m_Network->AddBatchMatMulLayer(descriptor, layerName.c_str());
1607 ARMNN_ASSERT(layer != nullptr);
1608
1609 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1610
1611 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1612 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
1613
1614 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1615 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1616}
1617
Kevin May7d96b162021-02-03 17:38:41 +00001618void TfLiteParserImpl::ParseBatchToSpaceND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001619{
1620 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1621
1622 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1623 CHECK_VALID_SIZE(inputs.size(), 3);
1624
1625 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1626 CHECK_VALID_SIZE(outputs.size(), 1);
1627
1628 armnn::TensorInfo blockShapeTensorInfo = ToTensorInfo(inputs[1]);
1629 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1630
1631 armnn::TensorInfo cropsTensorInfo = ToTensorInfo(inputs[2]);
1632 BufferRawPtr cropsBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1633
1634 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1635 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1636
1637 std::vector<unsigned int> cropsVector(cropsTensorInfo.GetNumElements());
1638 ::memcpy(cropsVector.data(), cropsBufferPtr->data.data(), cropsTensorInfo.GetNumBytes());
1639
1640 size_t step = 2;
1641 std::vector<std::pair<unsigned int, unsigned int>> crops;
1642 for (unsigned int i = 0; i < cropsTensorInfo.GetNumElements() / step; ++i)
1643 {
1644 crops.emplace_back(cropsVector[i * step], cropsVector[i * step + 1]);
1645 }
1646
1647 armnn::BatchToSpaceNdDescriptor desc;
1648 desc.m_BlockShape = blockShape;
1649 desc.m_Crops = crops;
1650 desc.m_DataLayout = armnn::DataLayout::NHWC;
1651
James Ward58dec6b2020-09-11 17:32:44 +01001652 auto layerName = fmt::format("BatchToSpaceND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001653
James Conroy05102392020-06-24 15:39:55 +01001654 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001655 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001656 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1657
1658 IConnectableLayer* layer = m_Network->AddBatchToSpaceNdLayer(desc, layerName.c_str());
1659 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001660 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1661
1662 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1663 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1664
1665 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1666 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1667}
1668
Kevin May7d96b162021-02-03 17:38:41 +00001669void TfLiteParserImpl::ParseL2Normalization(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson28c94572019-07-18 10:47:03 +01001670{
1671 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1672
1673 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1674 CHECK_VALID_SIZE(inputs.size(), 1);
1675
1676 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1677 CHECK_VALID_SIZE(outputs.size(), 1);
1678
1679 L2NormalizationDescriptor desc;
1680 desc.m_DataLayout = armnn::DataLayout::NHWC;
James Ward58dec6b2020-09-11 17:32:44 +01001681 auto layerName = fmt::format("L2Normalization:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson28c94572019-07-18 10:47:03 +01001682 IConnectableLayer* layer = m_Network->AddL2NormalizationLayer(desc, layerName.c_str());
1683
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001684 ARMNN_ASSERT(layer != nullptr);
Matthew Jackson28c94572019-07-18 10:47:03 +01001685
Sadik Armagand109a4d2020-07-28 10:42:13 +01001686 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jackson28c94572019-07-18 10:47:03 +01001687 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1688
1689 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1690 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1691
1692 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1693 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1694}
1695
Kevin May7d96b162021-02-03 17:38:41 +00001696void TfLiteParserImpl::ParseMaxPool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001697{
1698 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Max);
1699}
1700
Kevin May7d96b162021-02-03 17:38:41 +00001701void TfLiteParserImpl::ParseMaximum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001702{
1703 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1704
1705 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1706 CHECK_VALID_SIZE(inputs.size(), 2);
1707
1708 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1709 CHECK_VALID_SIZE(outputs.size(), 1);
1710
James Ward58dec6b2020-09-11 17:32:44 +01001711 auto layerName = fmt::format("Maximum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01001712
1713 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1714 TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1715 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001716
Sadik Armagand109a4d2020-07-28 10:42:13 +01001717 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001718 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1719
1720 IConnectableLayer* layer = m_Network->AddMaximumLayer(layerName.c_str());
1721 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001722 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1723
1724 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001725 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001726
1727 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1728 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1729}
1730
Kevin May7d96b162021-02-03 17:38:41 +00001731void TfLiteParserImpl::ParseMinimum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001732{
1733 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1734
1735 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1736 CHECK_VALID_SIZE(inputs.size(), 2);
1737
1738 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1739 CHECK_VALID_SIZE(outputs.size(), 1);
1740
James Ward58dec6b2020-09-11 17:32:44 +01001741 auto layerName = fmt::format("Minimum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01001742
1743 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1744 TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1745 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001746
Sadik Armagand109a4d2020-07-28 10:42:13 +01001747 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001748 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1749
1750 IConnectableLayer* layer = m_Network->AddMinimumLayer(layerName.c_str());
1751 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001752 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1753
1754 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001755 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001756
1757 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1758 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1759}
1760
Kevin May7d96b162021-02-03 17:38:41 +00001761void TfLiteParserImpl::ParsePool(size_t subgraphIndex,
1762 size_t operatorIndex,
1763 PoolingAlgorithm algorithm)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001764{
1765 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1766
Mike Kelly0d77ae12022-01-07 17:42:27 +00001767 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1768 const auto* options = operatorPtr->builtin_options.AsPool2DOptions();
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001769
1770 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1771
1772 std::string layerName;
1773
1774 switch (algorithm)
1775 {
1776 case PoolingAlgorithm::Average:
1777 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01001778 fmt::format("AveragePool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001779 break;
1780 case PoolingAlgorithm::Max:
1781 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01001782 fmt::format("MaxPool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001783 break;
1784 default:
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001785 ARMNN_ASSERT_MSG(false, "Unsupported Pooling Algorithm");
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001786 }
1787
1788 Pooling2dDescriptor desc;
1789
1790 desc.m_PoolType = algorithm;
1791 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1792 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1793 desc.m_PoolWidth = CHECKED_NON_NEGATIVE(options->filter_width);
1794 desc.m_PoolHeight = CHECKED_NON_NEGATIVE(options->filter_height);
1795 desc.m_PaddingMethod = PaddingMethod::Exclude;
1796 desc.m_OutputShapeRounding = OutputShapeRounding::Floor;
jimfly01c25411c2018-11-14 17:47:22 +00001797 desc.m_DataLayout = armnn::DataLayout::NHWC;
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001798
1799 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1800 CHECK_VALID_SIZE(inputs.size(), 1);
1801 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1802
1803 // assuming input is NHWC
1804 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1805 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1806
Pablo Tellof0bd6832019-04-26 17:58:13 +01001807 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, 1u,
1808 desc.m_PadTop, desc.m_PadBottom, options->padding);
1809 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, 1u,
1810 desc.m_PadLeft, desc.m_PadRight, options->padding);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001811
1812 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1813 CHECK_VALID_SIZE(outputs.size(), 1);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001814
Sadik Armagand109a4d2020-07-28 10:42:13 +01001815 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001816 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1817
1818 IConnectableLayer* layer = m_Network->AddPooling2dLayer(desc, layerName.c_str());
1819 ARMNN_ASSERT(layer != nullptr);
jimfly01c25411c2018-11-14 17:47:22 +00001820 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001821
1822 // register the input connection slots for the layer, connections are made after all layers have been created
1823 // only the tensors for the inputs are relevant, exclude the const tensors
1824 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +00001825 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001826
jimfly01c25411c2018-11-14 17:47:22 +00001827 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001828 // register the output connection slots for the layer, connections are made after all layers have been created
1829 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1830 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1831}
1832
Kevin May7d96b162021-02-03 17:38:41 +00001833void TfLiteParserImpl::ParseSlice(size_t subgraphIndex, size_t operatorIndex)
josh minorba424d22019-11-13 10:55:17 -06001834{
1835 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1836
1837 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1838 CHECK_VALID_SIZE(inputs.size(), 3);
1839 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1840 CHECK_VALID_SIZE(outputs.size(), 1);
1841
1842 SliceDescriptor desc;
1843
1844 // set begin tensor info for slice descriptor
1845 armnn::TensorInfo beginTensorInfo = ToTensorInfo(inputs[1]);
1846 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1847
1848 std::vector<unsigned int> begin(beginTensorInfo.GetNumElements());
1849 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
1850
1851 // set size tensor info for slice descriptor
1852 armnn::TensorInfo sizeTensorInfo = ToTensorInfo(inputs[2]);
1853 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1854
Cathal Corbettde33dda2022-09-20 16:40:09 +01001855 std::vector<int> signedSize(sizeTensorInfo.GetNumElements(), 1);
1856
1857 // if size buffer data is not specified, all contents of size vector remain as values of 1
1858 if (sizeBufferPtr->data.data())
1859 {
1860 ::memcpy(signedSize.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
1861 }
1862
josh minorba424d22019-11-13 10:55:17 -06001863 std::vector<unsigned int> size(sizeTensorInfo.GetNumElements());
Mike Kelly7ba84d62021-09-10 15:27:19 +01001864 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1865
1866 for (unsigned int i = 0; i < signedSize.size(); ++i)
1867 {
1868 int signedValue = signedSize[i];
Jim Flynnfca233e2021-09-23 12:16:53 +01001869
Mike Kelly7ba84d62021-09-10 15:27:19 +01001870 if (signedValue < -1 || signedValue > static_cast<int>(inputTensorInfo.GetShape()[i] - begin[i]))
1871 {
1872 throw ParseException(fmt::format("Invalid value for size {} size must be in range "
1873 "[-1, inputDimSize - begin] [-1, {}] inclusive {}",
1874 signedValue,
1875 inputTensorInfo.GetShape()[i] - begin[i],
1876 CHECK_LOCATION().AsString()));
1877 }
1878
1879 if (signedValue == -1)
1880 {
1881 size[i] = inputTensorInfo.GetShape()[i] - begin[i];
1882 }
1883 else
1884 {
1885 size[i] = static_cast<unsigned int>(signedValue);
1886 }
1887 }
1888
josh minorba424d22019-11-13 10:55:17 -06001889 desc = SliceDescriptor(begin, size);
1890
James Ward58dec6b2020-09-11 17:32:44 +01001891 auto layerName = fmt::format("Slice:{}:{}", subgraphIndex, operatorIndex);
josh minorba424d22019-11-13 10:55:17 -06001892
Sadik Armagand109a4d2020-07-28 10:42:13 +01001893 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001894 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1895
1896 IConnectableLayer* const layer = m_Network->AddSliceLayer(desc, layerName.c_str());
josh minorba424d22019-11-13 10:55:17 -06001897 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1898
1899 // register the input connection slots for the layer, connections are made after all layers have been created
1900 // only the tensors for the inputs are relevant, exclude the const tensors
1901 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1902 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1903
1904 // register the output connection slots for the layer, connections are made after all layers have been created
1905 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1906 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1907}
1908
Kevin May7d96b162021-02-03 17:38:41 +00001909void TfLiteParserImpl::ParseSoftmax(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001910{
1911 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00001912 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1913 const auto* options = operatorPtr->builtin_options.AsSoftmaxOptions();
telsoa01c577f2c2018-08-31 09:22:23 +01001914
1915 SoftmaxDescriptor desc;
1916 desc.m_Beta = options->beta;
1917
1918 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1919 CHECK_VALID_SIZE(inputs.size(), 1);
1920 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1921 CHECK_VALID_SIZE(outputs.size(), 1);
1922
James Ward58dec6b2020-09-11 17:32:44 +01001923 auto layerName = fmt::format("Softmax:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001924 IConnectableLayer* const layer = m_Network->AddSoftmaxLayer(desc, layerName.c_str());
1925
Sadik Armagand109a4d2020-07-28 10:42:13 +01001926 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
telsoa01c577f2c2018-08-31 09:22:23 +01001927 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1928
1929 // register the input connection slots for the layer, connections are made after all layers have been created
1930 // only the tensors for the inputs are relevant, exclude the const tensors
1931 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1932 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1933
1934 // register the output connection slots for the layer, connections are made after all layers have been created
1935 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1936 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1937}
1938
Teresa Charlinfd33a692022-06-29 15:35:57 +01001939void TfLiteParserImpl::ParseLogSoftmax(size_t subgraphIndex, size_t operatorIndex)
1940{
1941 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1942
1943 LogSoftmaxDescriptor desc;
1944
1945 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1946 CHECK_VALID_SIZE(inputs.size(), 1);
1947 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1948 CHECK_VALID_SIZE(outputs.size(), 1);
1949
1950 auto layerName = fmt::format("LogSoftmax:{}:{}", subgraphIndex, operatorIndex);
1951 IConnectableLayer* const layer = m_Network->AddLogSoftmaxLayer(desc, layerName.c_str());
1952
1953 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1954 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1955
1956 // register the input connection slots for the layer, connections are made after all layers have been created
1957 // only the tensors for the inputs are relevant, exclude the const tensors
1958 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1959 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1960
1961 // register the output connection slots for the layer, connections are made after all layers have been created
1962 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1963 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1964}
1965
Kevin May7d96b162021-02-03 17:38:41 +00001966void TfLiteParserImpl::ParseSpaceToBatchND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001967{
1968 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1969
1970 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1971 CHECK_VALID_SIZE(inputs.size(), 3);
1972
1973 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1974 CHECK_VALID_SIZE(outputs.size(), 1);
1975
1976 armnn::TensorInfo blockShapeTensorInfo = ToTensorInfo(inputs[1]);
1977 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1978
1979 armnn::TensorInfo padListTensorInfo = ToTensorInfo(inputs[2]);
1980 BufferRawPtr padListBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1981
1982 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1983 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1984
1985 std::vector<unsigned int> padListVector(padListTensorInfo.GetNumElements());
1986 ::memcpy(padListVector.data(), padListBufferPtr->data.data(), padListTensorInfo.GetNumBytes());
1987
1988 size_t step = 2;
1989 std::vector<std::pair<unsigned int, unsigned int>> padList;
1990 for (unsigned int i = 0; i < padListTensorInfo.GetNumElements() / step; ++i)
1991 {
1992 padList.emplace_back(padListVector[i * step], padListVector[i * step + 1]);
1993 }
1994
1995 armnn::SpaceToBatchNdDescriptor desc;
1996 desc.m_BlockShape = blockShape;
1997 desc.m_PadList = padList;
1998 desc.m_DataLayout = armnn::DataLayout::NHWC;
1999
James Ward58dec6b2020-09-11 17:32:44 +01002000 auto layerName = fmt::format("SpaceToBatchND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02002001
James Conroy05102392020-06-24 15:39:55 +01002002 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002003 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01002004 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
2005
2006 IConnectableLayer* layer = m_Network->AddSpaceToBatchNdLayer(desc, layerName.c_str());
2007 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02002008 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2009
2010 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2011 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2012
2013 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2014 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2015}
2016
Teresa Charlin3ab85482021-06-08 16:59:29 +01002017armnn::TensorInfo TfLiteParserImpl::OutputShapeOfSqueeze(std::vector<uint32_t> squeezeDims,
Mike Kelly0d77ae12022-01-07 17:42:27 +00002018 const armnn::TensorInfo& inputTensorInfo)
telsoa01c577f2c2018-08-31 09:22:23 +01002019{
Teresa Charlin3ab85482021-06-08 16:59:29 +01002020 CHECK_VALID_SIZE(squeezeDims.size(), 0, 1, 2, 3, 4);
telsoa01c577f2c2018-08-31 09:22:23 +01002021 static const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
2022
2023 if (inputTensorInfo.GetNumDimensions() > 4)
2024 {
2025 std::stringstream ss;
2026 ss << "Input tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
2027 << " shape:" << inputTensorInfo.GetShape() << " "
2028 << CHECK_LOCATION().AsString();
2029 throw ParseException(ss.str());
2030 }
2031
2032 if (squeezeDims.empty())
2033 {
2034 squeezeDims.assign(dimensionSequence,
2035 dimensionSequence+inputTensorInfo.GetNumDimensions());
2036 }
2037
2038 std::vector<uint32_t> outputDims;
2039 for(unsigned int i = 0; i < inputTensorInfo.GetNumDimensions(); i++)
2040 {
2041 bool skipSqueeze = (std::find(squeezeDims.begin(), squeezeDims.end(), i) == squeezeDims.end());
2042 auto currentDimension = inputTensorInfo.GetShape()[i];
2043 if (skipSqueeze || currentDimension != 1)
2044 {
2045 outputDims.push_back(currentDimension);
2046 }
2047 }
2048
2049 if (outputDims.size() > 4)
2050 {
2051 std::stringstream ss;
2052 ss << "Output tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
2053 << " shape:" << inputTensorInfo.GetShape() << " "
2054 << CHECK_LOCATION().AsString();
2055 throw ParseException(ss.str());
2056 }
2057
2058 TensorShape outShape = TensorShape(static_cast<unsigned int>(outputDims.size()),
2059 outputDims.data());
2060
2061 // we need to preserve the tensor type and the quantization data as well
2062 TensorInfo outTensorInfo = inputTensorInfo;
2063 outTensorInfo.SetShape(outShape);
2064
2065 return outTensorInfo;
2066}
2067
Keith Davis0176fd82021-06-01 17:36:32 +01002068void TfLiteParserImpl::ParseShape(size_t subgraphIndex, size_t operatorIndex)
2069{
2070 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2071
2072 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2073 CHECK_VALID_SIZE(inputs.size(), 1);
2074 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2075 CHECK_VALID_SIZE(outputs.size(), 1);
2076
2077 auto layerName = fmt::format("Shape:{}:{}", subgraphIndex, operatorIndex);
2078
2079 IConnectableLayer* layer = m_Network->AddShapeLayer(layerName.c_str());
2080 ARMNN_ASSERT(layer != nullptr);
2081
2082
2083 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
2084 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2085
2086 // Check if output tensor type is Signed32 or Signed64
2087 if (outputTensorInfo.GetDataType() != armnn::DataType::Signed32 &&
2088 outputTensorInfo.GetDataType() != armnn::DataType::Signed64)
2089 {
2090 throw ParseException(
2091 fmt::format(
2092 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
2093 CHECK_LOCATION().AsString()));
2094 }
2095
2096 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2097 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2098
2099 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2100 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2101}
2102
Kevin May7d96b162021-02-03 17:38:41 +00002103void TfLiteParserImpl::ParseSqueeze(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01002104{
2105 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2106
2107 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2108 CHECK_VALID_SIZE(inputs.size(), 1);
2109
2110 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2111 CHECK_VALID_SIZE(outputs.size(), 1);
2112
2113 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2114 const auto * options = operatorPtr->builtin_options.AsSqueezeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01002115 auto layerName = fmt::format("Squeeze:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01002116
2117 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Teresa Charlin3ab85482021-06-08 16:59:29 +01002118
2119 std::vector<uint32_t> squeezeDim;
2120 // A single negative dim index is interpreted as a negative index in python
2121 // Meaning the index will be the shape size plus the negative index value
2122 if (options->squeeze_dims.size() == 1 && options->squeeze_dims[0] < 0)
2123 {
2124 int32_t dim = static_cast<int32_t>(inputTensorInfo.GetShape().GetNumDimensions()) + options->squeeze_dims[0];
2125 squeezeDim.push_back(static_cast<uint32_t>(dim));
2126 }
2127 else
2128 {
2129 squeezeDim = AsUnsignedVector(options->squeeze_dims);
2130 }
2131
2132 armnn::TensorInfo outputTensorInfo = TfLiteParserImpl::OutputShapeOfSqueeze(squeezeDim, inputTensorInfo);
2133
James Conroy05102392020-06-24 15:39:55 +01002134 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
telsoa01c577f2c2018-08-31 09:22:23 +01002135
2136 ReshapeDescriptor reshapeDesc;
2137 reshapeDesc.m_TargetShape = outputTensorInfo.GetShape();
2138
telsoa01c577f2c2018-08-31 09:22:23 +01002139 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002140 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01002141 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2142
2143 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2144 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2145
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::ParseStridedSlice(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002151{
2152 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2153
2154 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2155 CHECK_VALID_SIZE(inputs.size(), 4);
2156
2157 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2158 CHECK_VALID_SIZE(outputs.size(), 1);
2159
Mike Kelly0d77ae12022-01-07 17:42:27 +00002160 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2161 const auto* options = operatorPtr->builtin_options.AsStridedSliceOptions();
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002162
2163 StridedSliceDescriptor desc;
2164 desc.m_BeginMask = options->begin_mask;
2165 desc.m_EllipsisMask = options->ellipsis_mask;
2166 desc.m_EndMask = options->end_mask;
2167 desc.m_NewAxisMask = options->new_axis_mask;
2168 desc.m_ShrinkAxisMask = options->shrink_axis_mask;
2169 desc.m_DataLayout = armnn::DataLayout::NHWC;
2170
2171 armnn::TensorInfo beginTensorInfo = ToTensorInfo(inputs[1]);
2172 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2173
2174 std::vector<int> begin(beginTensorInfo.GetNumElements());
2175 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
2176
2177 armnn::TensorInfo endTensorInfo = ToTensorInfo(inputs[2]);
2178 BufferRawPtr endBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
2179
2180 std::vector<int> end(endTensorInfo.GetNumElements());
2181 ::memcpy(end.data(), endBufferPtr->data.data(), endTensorInfo.GetNumBytes());
2182
2183 armnn::TensorInfo strideTensorInfo = ToTensorInfo(inputs[3]);
2184 BufferRawPtr strideBufferPtr = GetBuffer(m_Model, inputs[3]->buffer);
2185
2186 std::vector<int> stride(strideTensorInfo.GetNumElements());
2187 ::memcpy(stride.data(), strideBufferPtr->data.data(), strideTensorInfo.GetNumBytes());
2188
2189 desc.m_Begin = begin;
2190 desc.m_End = end;
2191 desc.m_Stride = stride;
2192
James Ward58dec6b2020-09-11 17:32:44 +01002193 auto layerName = fmt::format("StridedSlice:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002194 IConnectableLayer* layer = m_Network->AddStridedSliceLayer(desc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002195 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002196
Sadik Armagand109a4d2020-07-28 10:42:13 +01002197 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002198 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2199
2200 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2201 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2202
2203 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2204 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2205}
2206
Kevin May7d96b162021-02-03 17:38:41 +00002207void TfLiteParserImpl::ParseSub(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002208{
2209 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2210
Mike Kelly0d77ae12022-01-07 17:42:27 +00002211 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2212 const auto* options = operatorPtr->builtin_options.AsSubOptions();
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002213
2214 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2215 CHECK_VALID_SIZE(inputs.size(), 2);
2216
2217 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2218 CHECK_VALID_SIZE(outputs.size(), 1);
2219
2220 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2221 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2222
James Ward58dec6b2020-09-11 17:32:44 +01002223 auto layerName = fmt::format("Sub:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002224 IConnectableLayer* layer = m_Network->AddSubtractionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002225 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002226
Sadik Armagand109a4d2020-07-28 10:42:13 +01002227 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002228 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2229
2230 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002231 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002232
2233 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2234
2235 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2236 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2237}
2238
Kevin May7d96b162021-02-03 17:38:41 +00002239void TfLiteParserImpl::ParseDiv(size_t subgraphIndex, size_t operatorIndex)
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302240{
2241 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2242
Mike Kelly0d77ae12022-01-07 17:42:27 +00002243 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2244 const auto* options = operatorPtr->builtin_options.AsDivOptions();
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302245
2246 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2247 CHECK_VALID_SIZE(inputs.size(), 2);
2248
2249 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2250 CHECK_VALID_SIZE(outputs.size(), 1);
2251
2252 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2253 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2254
James Ward58dec6b2020-09-11 17:32:44 +01002255 auto layerName = fmt::format("Div:{}:{}", subgraphIndex, operatorIndex);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302256 IConnectableLayer* layer = m_Network->AddDivisionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002257 ARMNN_ASSERT(layer != nullptr);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302258
Sadik Armagand109a4d2020-07-28 10:42:13 +01002259 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302260 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2261
2262 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002263 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302264 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2265
2266 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2267 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2268}
2269
Teresa Charlincdbd40b2022-02-25 13:21:55 +00002270void TfLiteParserImpl::ParseFloorDiv(size_t subgraphIndex, size_t operatorIndex)
2271{
2272 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2273
2274 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2275 CHECK_VALID_SIZE(inputs.size(), 2);
2276
2277 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2278 CHECK_VALID_SIZE(outputs.size(), 1);
2279
2280 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2281 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2282
2283 auto layerName = fmt::format("Div:{}:{}", subgraphIndex, operatorIndex);
2284 IConnectableLayer* layer = m_Network->AddDivisionLayer(layerName.c_str());
2285 ARMNN_ASSERT(layer != nullptr);
2286
2287 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
2288 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2289
2290 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2291 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2292 layer = AddFusedFloorLayer(layer, 0);
2293
2294 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2295 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2296}
2297
Kevin May7d96b162021-02-03 17:38:41 +00002298void TfLiteParserImpl::ParseAdd(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002299{
2300 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2301
Mike Kelly0d77ae12022-01-07 17:42:27 +00002302 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2303 const auto* options = operatorPtr->builtin_options.AsAddOptions();
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002304
2305 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2306 CHECK_VALID_SIZE(inputs.size(), 2);
2307
2308 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2309 CHECK_VALID_SIZE(outputs.size(), 1);
2310
Bruno Goncalves9c761a62018-12-27 14:20:35 -02002311 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2312 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2313
James Ward58dec6b2020-09-11 17:32:44 +01002314 auto layerName = fmt::format("Add:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002315 IConnectableLayer* layer = m_Network->AddAdditionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002316 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002317
Sadik Armagand109a4d2020-07-28 10:42:13 +01002318 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002319 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2320
2321 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002322 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002323 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2324
2325 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2326 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2327}
2328
Kevin May7d96b162021-02-03 17:38:41 +00002329void TfLiteParserImpl::ParseMul(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002330{
2331 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2332
Mike Kelly0d77ae12022-01-07 17:42:27 +00002333 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2334 const auto* options = operatorPtr->builtin_options.AsMulOptions();
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002335
2336 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2337 CHECK_VALID_SIZE(inputs.size(), 2);
2338
2339 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2340 CHECK_VALID_SIZE(outputs.size(), 1);
2341
Bruno Goncalves9c761a62018-12-27 14:20:35 -02002342 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2343 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2344
James Ward58dec6b2020-09-11 17:32:44 +01002345 auto layerName = fmt::format("Mul:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002346 IConnectableLayer* layer = m_Network->AddMultiplicationLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002347 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002348
Sadik Armagand109a4d2020-07-28 10:42:13 +01002349 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002350 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2351
2352 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002353 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002354 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2355
2356 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2357 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2358}
2359
Kevin May7d96b162021-02-03 17:38:41 +00002360void TfLiteParserImpl::ParseMean(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002361{
2362 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2363
2364 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2365
2366 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2367 CHECK_VALID_SIZE(outputs.size(), 1);
2368
2369 armnn::TensorInfo dimTensorInfo = ToTensorInfo(inputs[1]);
2370 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2371
2372 armnn::MeanDescriptor desc;
2373 std::vector<unsigned int> axis(dimTensorInfo.GetNumElements());
2374 ::memcpy(axis.data(), bufferPtr->data.data(), dimTensorInfo.GetNumBytes());
2375 desc.m_Axis = axis;
2376
2377 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002378 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002379
2380 desc.m_KeepDims =
2381 inputTensorInfo.GetNumDimensions() == outputTensorInfo.GetNumDimensions() ?
2382 true : false;
2383
James Ward58dec6b2020-09-11 17:32:44 +01002384 auto layerName = fmt::format("Mean:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002385 IConnectableLayer* layer = m_Network->AddMeanLayer(desc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002386 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002387
2388 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2389
2390 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2391 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2392
2393 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2394 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2395}
2396
Kevin May7d96b162021-02-03 17:38:41 +00002397void TfLiteParserImpl::ParsePad(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002398{
2399 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2400
Kevin May7d96b162021-02-03 17:38:41 +00002401 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002402
Kevin May7d96b162021-02-03 17:38:41 +00002403 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002404 CHECK_VALID_SIZE(outputs.size(), 1);
2405
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00002406 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002407 armnn::TensorInfo padTensorInfo = ToTensorInfo(inputs[1]);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002408
Mike Kelly0d77ae12022-01-07 17:42:27 +00002409 std::vector<unsigned int> padBuffer = GetUIntBuffer(padTensorInfo, m_Model, inputs[1]->buffer);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002410
2411 size_t step = 2;
2412 armnn::PadDescriptor desc;
Mike Kelly0d77ae12022-01-07 17:42:27 +00002413 auto opcode = GetOpCode(m_Model, subgraphIndex, operatorIndex);
2414
2415 if (opcode == tflite::BuiltinOperator_PAD)
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00002416 {
Mike Kelly0d77ae12022-01-07 17:42:27 +00002417 CHECK_VALID_SIZE(inputs.size(), 2);
2418
2419 if (inputTensorInfo.IsQuantized())
2420 {
2421 desc.m_PadValue = static_cast<float>(inputTensorInfo.GetQuantizationOffset());
2422 }
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00002423 }
Mike Kelly0d77ae12022-01-07 17:42:27 +00002424 else if (opcode == tflite::BuiltinOperator_PADV2)
2425 {
2426 CHECK_VALID_SIZE(inputs.size(), 3);
2427
2428 armnn::TensorInfo padValueTensorInfo = ToTensorInfo(inputs[2]);
2429
2430 if (padValueTensorInfo.GetNumElements() != 1)
2431 {
2432 ARMNN_THROW_PARSE_EXCEPTION("Multiple padding values are not supported in PADV2");
2433 }
2434 BufferRawPtr padValueBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
2435
2436 // Get the pad value from the input tensor
2437 if (padValueBufferPtr->data.size() > 0)
2438 {
2439 switch (padValueTensorInfo.GetDataType())
2440 {
2441 case armnn::DataType::Float32:
2442 {
2443 std::vector<float> padValueBuffer(padValueTensorInfo.GetNumElements());
2444 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2445 desc.m_PadValue = padValueBuffer[0];
2446 break;
2447 }
2448 case armnn::DataType::QAsymmU8:
2449 {
2450 std::vector<uint8_t> padValueBuffer(padValueTensorInfo.GetNumElements());
2451 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2452 desc.m_PadValue = armnn::Dequantize<uint8_t>(padValueBuffer[0],
2453 padValueTensorInfo.GetQuantizationScale(),
2454 padValueTensorInfo.GetQuantizationOffset());
2455 break;
2456 }
2457 case armnn::DataType::QAsymmS8:
2458 case armnn::DataType::QSymmS8:
2459 {
2460 std::vector<int8_t> padValueBuffer(padValueTensorInfo.GetNumElements());
2461 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2462 desc.m_PadValue = armnn::Dequantize<int8_t>(padValueBuffer[0],
2463 padValueTensorInfo.GetQuantizationScale(),
2464 padValueTensorInfo.GetQuantizationOffset());
2465 break;
2466 }
2467 default: ARMNN_THROW_PARSE_EXCEPTION("Unsupported DataType");
2468 }
2469 }
2470 else if (inputTensorInfo.IsQuantized())
2471 {
2472 desc.m_PadValue = static_cast<float>(inputTensorInfo.GetQuantizationOffset());
2473 }
2474 }
2475
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002476 for (unsigned int i = 0; i < padTensorInfo.GetNumElements() / step; ++i)
2477 {
2478 desc.m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
2479 }
2480
Mike Kelly0d77ae12022-01-07 17:42:27 +00002481 auto layerName = (opcode == tflite::BuiltinOperator_PAD) ? fmt::format("Pad:{}:{}", subgraphIndex, operatorIndex)
2482 : fmt::format("PadV2:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002483 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01002484
2485 IConnectableLayer* layer = m_Network->AddPadLayer(desc, layerName.c_str());
2486 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002487 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2488
2489 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2490 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2491
2492 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2493 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2494}
2495
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +01002496void TfLiteParserImpl::ParseMirrorPad(size_t subgraphIndex, size_t operatorIndex)
2497{
2498 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2499
2500 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2501 CHECK_VALID_SIZE(inputs.size(), 2);
2502
2503 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2504 CHECK_VALID_SIZE(outputs.size(), 1);
2505
2506 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2507
2508 armnn::TensorInfo padTensorInfo = ToTensorInfo(inputs[1]);
2509 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2510
2511 std::vector<unsigned int> padBuffer(padTensorInfo.GetNumElements());
2512 ::memcpy(padBuffer.data(), bufferPtr->data.data(), padTensorInfo.GetNumBytes());
2513
2514 size_t step = 2;
2515 armnn::PadDescriptor desc;
2516 for (unsigned int i = 0; i < padTensorInfo.GetNumElements() / step; ++i)
2517 {
2518 desc.m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
2519 }
2520
2521 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2522 const auto* options = operatorPtr->builtin_options.AsMirrorPadOptions();
2523
2524 if (options->mode == tflite::MirrorPadMode_REFLECT)
2525 {
2526 desc.m_PaddingMode = PaddingMode::Reflect;
2527 }
2528 else if (options->mode == tflite::MirrorPadMode_SYMMETRIC)
2529 {
2530 desc.m_PaddingMode = PaddingMode::Symmetric;
2531 }
2532 else
2533 {
2534 ARMNN_THROW_PARSE_EXCEPTION("PaddingMode must be either REFLECT or SYMMETRIC");
2535 }
2536
2537 // If padding mode is Reflect then both paddings must be no greater than inputShape(i) - 1.
2538 // If padding mode is Symmetric then both paddings must be no greater than inputShape(i).
2539 auto inputShape = inputTensorInfo.GetShape();
2540 auto padList = desc.m_PadList;
2541
2542 const unsigned int isReflect = static_cast<unsigned int>(desc.m_PaddingMode == PaddingMode::Reflect);
2543 for(unsigned int i = 0; i < padList.size(); ++i)
2544 {
2545 if(padList.at(i).first > (inputShape[i] - isReflect) ||
2546 padList.at(i).second > (inputShape[i] - isReflect))
2547 {
2548 ARMNN_THROW_PARSE_EXCEPTION("Padding values must be less (Reflect) or "
2549 "equal (Symmetric) to the dimension size.");
2550 }
2551 }
2552
2553 auto layerName = fmt::format("MirrorPad:{}:{}", subgraphIndex, operatorIndex);
2554 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
2555
2556 IConnectableLayer* layer = m_Network->AddPadLayer(desc, layerName.c_str());
2557 ARMNN_ASSERT(layer != nullptr);
2558 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2559
2560 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2561 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2562
2563 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2564 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2565}
2566
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01002567void TfLiteParserImpl::ParsePrelu(size_t subgraphIndex, size_t operatorIndex)
2568{
2569 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2570
2571 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2572 CHECK_VALID_SIZE(inputs.size(), 2);
2573
2574 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2575 CHECK_VALID_SIZE(outputs.size(), 1);
2576
2577 auto layerName = fmt::format("Prelu:{}:{}", subgraphIndex, operatorIndex);
2578
2579 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2580 armnn::TensorInfo alphaTensorInfo = ToTensorInfo(inputs[1]);
2581 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
2582 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
2583
2584 IConnectableLayer* layer = m_Network->AddPreluLayer(layerName.c_str());
2585 ARMNN_ASSERT(layer != nullptr);
2586 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2587
2588 if (IsConstTensor(inputs[1]))
2589 {
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01002590 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawaratbf99b5f2021-05-27 09:55:43 +01002591 armnn::IInputSlot* slot = &(layer->GetInputSlot(0));
2592 RegisterConsumerOfTensor(subgraphIndex, inputTensorIndexes[0], slot);
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01002593
Mike Kelly5880b912022-01-28 16:18:54 +00002594 auto alphaTensorAndData = CreateConstTensorNonPermuted(inputs[1], alphaTensorInfo,
2595 inputTensorInfo.GetDataType());
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01002596 std::string constLayerName = fmt::format("Constant:{}", inputs[1]->name);
2597 IConnectableLayer* constLayer =
Mike Kelly5880b912022-01-28 16:18:54 +00002598 m_Network->AddConstantLayer(alphaTensorAndData.first, constLayerName.c_str());
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01002599 ARMNN_ASSERT(constLayer != nullptr);
2600
2601 constLayer->GetOutputSlot(0).SetTensorInfo(alphaTensorInfo);
2602 constLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(1));
2603 RegisterOutputSlots(subgraphIndex,
2604 VIRTUAL_OPERATOR_ID,
2605 constLayer,
2606 { inputTensorIndexes[1] });
2607 }
2608 else
2609 {
2610 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2611 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIndexes);
2612 }
2613
2614 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2615 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2616}
2617
Kevin May7d96b162021-02-03 17:38:41 +00002618void TfLiteParserImpl::ParseQuantize(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan66dedc72019-12-10 16:32:07 +00002619{
2620 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2621
2622 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2623 CHECK_VALID_SIZE(inputs.size(), 1);
2624
2625 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2626 CHECK_VALID_SIZE(outputs.size(), 1);
2627
James Ward58dec6b2020-09-11 17:32:44 +01002628 auto layerName = fmt::format("Quantize:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan66dedc72019-12-10 16:32:07 +00002629
2630 IConnectableLayer* layer = m_Network->AddQuantizeLayer(layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002631 ARMNN_ASSERT(layer != nullptr);
Sadik Armagan66dedc72019-12-10 16:32:07 +00002632
Sadik Armagand109a4d2020-07-28 10:42:13 +01002633 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan66dedc72019-12-10 16:32:07 +00002634 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2635
2636 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2637 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2638
2639 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2640 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2641}
Finn Williamsc42c3842019-01-22 14:18:11 +00002642
Kevin May7d96b162021-02-03 17:38:41 +00002643void TfLiteParserImpl::ParseRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01002644{
Finn Williamsc42c3842019-01-22 14:18:11 +00002645 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::ReLu);
Sadik Armagan58f39192018-09-17 14:14:39 +01002646}
2647
Kevin May7d96b162021-02-03 17:38:41 +00002648void TfLiteParserImpl::ParseRelu6(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01002649{
Finn Williamsc42c3842019-01-22 14:18:11 +00002650 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::BoundedReLu);
2651}
Sadik Armagan58f39192018-09-17 14:14:39 +01002652
Kevin May7d96b162021-02-03 17:38:41 +00002653void TfLiteParserImpl::ParseLeakyRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan12239e72020-05-27 11:06:17 +01002654{
Jan Eilers2f746b32020-07-28 14:00:06 +01002655 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::LeakyReLu);
Sadik Armagan12239e72020-05-27 11:06:17 +01002656}
2657
Kevin May7d96b162021-02-03 17:38:41 +00002658void TfLiteParserImpl::ParseLogistic(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsc42c3842019-01-22 14:18:11 +00002659{
2660 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::Sigmoid);
2661}
2662
Kevin May7d96b162021-02-03 17:38:41 +00002663void TfLiteParserImpl::ParseTanH(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd99851762019-04-09 09:37:38 +01002664{
2665 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::TanH);
2666}
2667
Kevin May7d96b162021-02-03 17:38:41 +00002668void TfLiteParserImpl::ParseElu(size_t subgraphIndex, size_t operatorIndex)
Matthew Sloyan7515d072020-12-16 12:50:01 +00002669{
2670 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::Elu);
2671}
2672
Kevin May7d96b162021-02-03 17:38:41 +00002673void TfLiteParserImpl::ParseHardSwish(size_t subgraphIndex, size_t operatorIndex)
Jan Eilers2f746b32020-07-28 14:00:06 +01002674{
2675 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::HardSwish);
2676}
Finn Williamsc42c3842019-01-22 14:18:11 +00002677
Kevin May7d96b162021-02-03 17:38:41 +00002678void TfLiteParserImpl::ParseActivation(size_t subgraphIndex, size_t operatorIndex, ActivationFunction activationType)
Finn Williamsc42c3842019-01-22 14:18:11 +00002679{
2680 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00002681 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Jan Eilers8eb25602020-03-09 12:13:48 +00002682 IgnoreUnused(operatorPtr);
Sadik Armagan58f39192018-09-17 14:14:39 +01002683
2684 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2685 CHECK_VALID_SIZE(inputs.size(), 1);
2686
2687 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2688 CHECK_VALID_SIZE(outputs.size(), 1);
2689
James Ward58dec6b2020-09-11 17:32:44 +01002690 auto layerName = fmt::format("Activation:");
Sadik Armagan58f39192018-09-17 14:14:39 +01002691 ActivationDescriptor activationDesc;
Finn Williamsc42c3842019-01-22 14:18:11 +00002692 activationDesc.m_Function = activationType;
2693
2694 switch (activationType)
2695 {
2696 case ActivationFunction::ReLu:
2697 {
James Ward58dec6b2020-09-11 17:32:44 +01002698 layerName += fmt::format("RELU:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002699 break;
2700 }
2701 case ActivationFunction::BoundedReLu:
2702 {
James Ward58dec6b2020-09-11 17:32:44 +01002703 layerName += fmt::format("RELU6:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002704 activationDesc.m_A = 6.0f;
2705 activationDesc.m_B = 0.0f;
2706 break;
2707 }
2708 case ActivationFunction::Sigmoid:
2709 {
James Ward58dec6b2020-09-11 17:32:44 +01002710 layerName += fmt::format("SIGMOID:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002711 break;
2712 }
Nina Drozd99851762019-04-09 09:37:38 +01002713 case ActivationFunction::TanH:
2714 {
James Ward58dec6b2020-09-11 17:32:44 +01002715 layerName += fmt::format("TANH:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd99851762019-04-09 09:37:38 +01002716 activationDesc.m_A = 1.0f;
2717 activationDesc.m_B = 1.0f;
2718 break;
2719 }
Sadik Armagan12239e72020-05-27 11:06:17 +01002720 case ActivationFunction::LeakyReLu:
2721 {
James Ward58dec6b2020-09-11 17:32:44 +01002722 layerName += fmt::format("LEAKYRELU:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00002723 const auto* options = operatorPtr->builtin_options.AsLeakyReluOptions();
Sadik Armagan12239e72020-05-27 11:06:17 +01002724 activationDesc.m_A = options->alpha;
2725 break;
2726 }
Matthew Sloyan7515d072020-12-16 12:50:01 +00002727 case ActivationFunction::Elu:
2728 {
2729 layerName += fmt::format("ELU:{}:{}", subgraphIndex, operatorIndex);
2730 activationDesc.m_A = 1.0f;
2731 break;
2732 }
Jan Eilers2f746b32020-07-28 14:00:06 +01002733 case ActivationFunction::HardSwish:
Matthew Sloyan7515d072020-12-16 12:50:01 +00002734 {
James Ward58dec6b2020-09-11 17:32:44 +01002735 layerName += fmt::format("HARDSWISH:{}:{}", subgraphIndex, operatorIndex);
Jan Eilers2f746b32020-07-28 14:00:06 +01002736 break;
Matthew Sloyan7515d072020-12-16 12:50:01 +00002737 }
Finn Williamsc42c3842019-01-22 14:18:11 +00002738 default:
2739 {
2740 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002741 fmt::format("Unexpected ActivationFunction[{}] when creating layerName {} ",
2742 static_cast<int>(activationType), CHECK_LOCATION().AsString()));
Finn Williamsc42c3842019-01-22 14:18:11 +00002743 }
2744 }
2745
2746 IConnectableLayer* const layer = m_Network->AddActivationLayer(activationDesc, layerName.c_str());
Sadik Armagan58f39192018-09-17 14:14:39 +01002747
Sadik Armagand109a4d2020-07-28 10:42:13 +01002748 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan58f39192018-09-17 14:14:39 +01002749 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2750
2751 // register the input connection slots for the layer, connections are made after all layers have been created
2752 // only the tensors for the inputs are relevant, exclude the const tensors
2753 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2754 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2755
2756 // register the output connection slots for the layer, connections are made after all layers have been created
2757 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2758 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2759}
Mike Kelly0d77ae12022-01-07 17:42:27 +00002760armnn::TensorInfo TfLiteParserImpl::OutputShapeOfReshape(const armnn::TensorInfo& inputTensorInfo,
2761 const std::vector<int32_t>& targetDimsIn)
Sadikb94967b2018-09-19 15:30:00 +01002762{
2763 std::vector<unsigned int> outputDims(targetDimsIn.begin(), targetDimsIn.end());
2764 const auto stretchDim = std::find(targetDimsIn.begin(), targetDimsIn.end(), -1);
2765
2766 if (stretchDim != targetDimsIn.end())
2767 {
2768 if (std::find(std::next(stretchDim), targetDimsIn.end(), -1) != targetDimsIn.end())
2769 {
2770 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002771 fmt::format("At most one component of shape can be -1 {}", CHECK_LOCATION().AsString()));
Sadikb94967b2018-09-19 15:30:00 +01002772 }
2773
2774 auto targetNumElements =
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002775 armnn::numeric_cast<unsigned int>(
Sadikb94967b2018-09-19 15:30:00 +01002776 std::accumulate(targetDimsIn.begin(), targetDimsIn.end(), -1, std::multiplies<int32_t>()));
2777
2778 auto stretchIndex = static_cast<size_t>(std::distance(targetDimsIn.begin(), stretchDim));
2779 outputDims[stretchIndex] = inputTensorInfo.GetNumElements() / targetNumElements;
2780 }
2781
2782 TensorShape outputShape = TensorShape(static_cast<unsigned int>(outputDims.size()), outputDims.data());
2783
2784 TensorInfo reshapeInfo = inputTensorInfo;
2785 reshapeInfo.SetShape(outputShape);
2786
2787 return reshapeInfo;
2788}
2789
Kevin May7d96b162021-02-03 17:38:41 +00002790void TfLiteParserImpl::ParseReshape(size_t subgraphIndex, size_t operatorIndex)
Sadikb94967b2018-09-19 15:30:00 +01002791{
2792 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2793
2794 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01002795
2796 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2797 CHECK_VALID_SIZE(outputs.size(), 1);
2798
Mike Kelly0d77ae12022-01-07 17:42:27 +00002799 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2800 const auto* options = operatorPtr->builtin_options.AsReshapeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01002801 auto layerName = fmt::format("Reshape:{}:{}", subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01002802
2803 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
kevmay0171972a82018-12-17 14:28:03 +00002804 armnn::TensorInfo actualOutputTensorInfo = ToTensorInfo(outputs[0]);
James Conroy05102392020-06-24 15:39:55 +01002805 CheckMatchingQuantization(inputTensorInfo, actualOutputTensorInfo, layerName, "Input 0", "Output 0");
Derek Lambertic9e52792020-03-11 11:42:26 +00002806
Jan Eilersbac9b352020-07-13 13:40:24 +01002807 // Extracting new shape for the output
2808 // There are two ways it can be passed
2809 // * First is to define the target shape in the operator built-in options
2810 // * Second is to pass it as a second input tensor
Derek Lambertic9e52792020-03-11 11:42:26 +00002811 std::vector<int32_t> targetShape;
Jan Eilersbac9b352020-07-13 13:40:24 +01002812 bool targetShapeFound = false;
2813 // Check if built-in options were given
2814 if (options != nullptr)
Derek Lambertic9e52792020-03-11 11:42:26 +00002815 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002816 // make sure the parameter is given
2817 if (options->new_shape.empty() == false)
Derek Lambertic9e52792020-03-11 11:42:26 +00002818 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002819 targetShape = options->new_shape;
2820 targetShapeFound = true;
Derek Lambertif4a953f2020-03-17 14:25:57 +00002821 }
Derek Lambertic9e52792020-03-11 11:42:26 +00002822 }
Jan Eilersbac9b352020-07-13 13:40:24 +01002823
2824 // If there is no built-in option given or if the built-in new_shape parameter was empty
2825 if (!targetShapeFound)
Derek Lambertic9e52792020-03-11 11:42:26 +00002826 {
Teresa Charlin6a056a42021-12-01 10:25:43 +00002827 // Check for a second input tensor
2828 if (inputs.size() > 1 && inputs[1] != nullptr)
Jan Eilersbac9b352020-07-13 13:40:24 +01002829 {
2830 if (inputs[1]->is_variable)
2831 {
2832 ARMNN_THROW_PARSE_EXCEPTION( "Target shapes defined in non-const input tensors is not supported");
2833 }
2834
2835 if (inputs[1]->shape.size() != 1)
2836 {
2837 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not a 1D tensor");
2838 }
2839
2840 if (inputs[1]->type != tflite::TensorType_INT32)
2841 {
2842 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not an int32 type");
2843 }
2844
Teresa Charlin6a056a42021-12-01 10:25:43 +00002845 // Extract target shape from input
2846 auto bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2847 auto values = reinterpret_cast<const int32_t*>(bufferPtr->data.data());
Cathal Corbettd2f73232021-12-10 13:38:52 +00002848 if (values)
Sadik Armagan19a1c032021-01-20 12:17:00 +00002849 {
Cathal Corbettd2f73232021-12-10 13:38:52 +00002850 for (int i = 0; i < inputs[1]->shape[0]; ++i)
2851 {
2852 targetShape.push_back(values[i]);
2853 }
Sadik Armagan19a1c032021-01-20 12:17:00 +00002854 }
Cathal Corbettd2f73232021-12-10 13:38:52 +00002855 else
Jan Eilersbac9b352020-07-13 13:40:24 +01002856 {
Cathal Corbettd2f73232021-12-10 13:38:52 +00002857 try
2858 {
2859 // We attempt to infer during Runtime.
2860 TensorShape reshapeShapes = ToTensorInfo(inputs[1]).GetShape();
2861 // The parser only supports shape (batch, -1) or (-1) for non-constant shape input.
2862 if (reshapeShapes[0] > 2)
2863 {
2864 throw ParseException(fmt::format("Invalid input shape '{}' in Reshape layer '{}' {}. "
2865 "When inferring during runtime, the parser only supports "
2866 "shape (batch, -1) or (-1) for target shape input.",
2867 reshapeShapes[0],
2868 layerName,
2869 CHECK_LOCATION().AsString()));
2870 }
2871
2872 const int32_t numInputElements = inputTensorInfo.GetNumElements();
2873 const int32_t inputTensorShape = inputTensorInfo.GetShape()[0];
2874 if (reshapeShapes[0] == 1)
2875 {
2876 targetShape = {numInputElements};
2877 }
2878 else if (reshapeShapes[0] == 2)
2879 {
2880 targetShape = {inputTensorShape, numInputElements / inputTensorShape};
2881 }
2882 }
2883 catch (const std::exception& exc)
2884 {
2885 ARMNN_THROW_PARSE_EXCEPTION("Failed attempt to infer during runtime the target shape input for "
2886 "Reshape operation. Reshape operator target shape input buffer data "
2887 "is null. " << exc.what());
2888 }
Jan Eilersbac9b352020-07-13 13:40:24 +01002889 }
2890 }
2891 else
Derek Lambertic9e52792020-03-11 11:42:26 +00002892 {
2893 ARMNN_THROW_PARSE_EXCEPTION("Target shape not defined in reshape parameters or input tensor. "
2894 "At least one method required");
2895 }
Derek Lambertic9e52792020-03-11 11:42:26 +00002896 }
2897
kevmay0171972a82018-12-17 14:28:03 +00002898 armnn::TensorInfo reshapeOutputTensorInfo =
Kevin May7d96b162021-02-03 17:38:41 +00002899 TfLiteParserImpl::OutputShapeOfReshape(inputTensorInfo, targetShape);
Sadikb94967b2018-09-19 15:30:00 +01002900
kevmay0171972a82018-12-17 14:28:03 +00002901 // Check for valid input size and that reshape parameters equal output shape
Cathal Corbett2b922e22022-09-23 15:49:24 +01002902 // The output shape can be provided to us in 2 ways:
2903 // 1. through the normal 'shape' parameter given by outputs[indx]->shape
2904 // 2. through additional parameter 'shape_signature' given by outputs[indx]->buffer.
2905 // This parameter can sometimes contain -1 value not visible in the 'shape' parameter.
Aron Virginas-Tar70672f62019-01-23 14:00:00 +00002906 const armnn::TensorShape& reshapeOutputTensorShape = reshapeOutputTensorInfo.GetShape();
2907 if (inputs.size() > 1 && !CheckShape(reshapeOutputTensorShape, outputs[0]->shape))
kevmay0171972a82018-12-17 14:28:03 +00002908 {
Cathal Corbett2b922e22022-09-23 15:49:24 +01002909 // Attempt to extract output shape from secondary 'shape_signature'
2910 // parameter and try to CheckShape() with this param.
2911 std::vector<int32_t> secondaryOutputTargetShape = outputs[0]->shape_signature;
2912
2913 // if outputs[0]->shape_signature contain a -1 value, we need to compute its actual value
2914 // from reshape input in order to correctly verify reshape parameters equal output shape
2915 armnn::TensorInfo secondaryReshapeOutputTensorInfo =
2916 TfLiteParserImpl::OutputShapeOfReshape(inputTensorInfo, secondaryOutputTargetShape);
2917
2918 if (!CheckShape(reshapeOutputTensorShape, secondaryReshapeOutputTensorInfo.GetShape()))
2919 {
2920 std::stringstream ss;
2921 ss << "New shape defined in reshape parameters "
2922 << reshapeOutputTensorShape
2923 << " does not equal output shape "
2924 << actualOutputTensorInfo.GetShape()
2925 << ": "
2926 << CHECK_LOCATION().AsString();
2927 throw ParseException(ss.str());
2928 }
kevmay0171972a82018-12-17 14:28:03 +00002929 }
2930
Sadikb94967b2018-09-19 15:30:00 +01002931 ReshapeDescriptor reshapeDesc;
kevmay0171972a82018-12-17 14:28:03 +00002932 reshapeDesc.m_TargetShape = reshapeOutputTensorInfo.GetShape();
Sadikb94967b2018-09-19 15:30:00 +01002933
Sadikb94967b2018-09-19 15:30:00 +01002934 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002935 ARMNN_ASSERT(layer != nullptr);
kevmay0171972a82018-12-17 14:28:03 +00002936 layer->GetOutputSlot(0).SetTensorInfo(reshapeOutputTensorInfo);
Sadikb94967b2018-09-19 15:30:00 +01002937
2938 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2939 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2940
2941 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2942 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2943}
2944
Kevin May7d96b162021-02-03 17:38:41 +00002945void TfLiteParserImpl::ParseResizeBilinear(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002946{
Sadik Armagana3b31f02019-12-05 09:08:53 +00002947 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::Bilinear);
2948}
2949
Kevin May7d96b162021-02-03 17:38:41 +00002950void TfLiteParserImpl::ParseResizeNearestNeighbor(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagana3b31f02019-12-05 09:08:53 +00002951{
2952 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::NearestNeighbor);
2953}
2954
Kevin May7d96b162021-02-03 17:38:41 +00002955void TfLiteParserImpl::ParseResize(size_t subgraphIndex, size_t operatorIndex, ResizeMethod resizeMethod)
Sadik Armagana3b31f02019-12-05 09:08:53 +00002956{
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002957 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2958
2959 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2960 CHECK_VALID_SIZE(inputs.size(), 2);
2961
2962 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2963 CHECK_VALID_SIZE(outputs.size(), 1);
2964
2965 armnn::TensorInfo sizeTensorInfo = ToTensorInfo(inputs[1]);
2966
2967 // Data for the parsed tensor args (size) must be stored locally.
2968 std::vector<int32_t> sizeTensorData(sizeTensorInfo.GetNumElements());
2969
2970 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2971 ::memcpy(sizeTensorData.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
2972
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01002973 ResizeDescriptor desc;
Sadik Armagana3b31f02019-12-05 09:08:53 +00002974 desc.m_Method = resizeMethod;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002975 desc.m_TargetHeight = static_cast<uint32_t> (sizeTensorData[0]);
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01002976 desc.m_TargetWidth = static_cast<uint32_t> (sizeTensorData[1]);
2977 desc.m_DataLayout = armnn::DataLayout::NHWC;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002978
James Ward58dec6b2020-09-11 17:32:44 +01002979 auto layerName = fmt::format("Resize:");
Sadik Armagana3b31f02019-12-05 09:08:53 +00002980
2981 switch (resizeMethod)
2982 {
2983 case ResizeMethod::Bilinear:
2984 {
James Ward58dec6b2020-09-11 17:32:44 +01002985 layerName += fmt::format("BILINEAR:{}:{}", subgraphIndex, operatorIndex);
Sang-Hoon Park820eb142020-01-08 10:25:24 +00002986
2987 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2988 const auto * options = operatorPtr->builtin_options.AsResizeBilinearOptions();
2989
David Monahan4a0c9b92020-05-30 09:48:39 +01002990 desc.m_AlignCorners = options->align_corners;
Sadik Armagana3b31f02019-12-05 09:08:53 +00002991 break;
2992 }
2993 case ResizeMethod::NearestNeighbor:
2994 {
James Ward58dec6b2020-09-11 17:32:44 +01002995 layerName += fmt::format("NEARESTNEIGHBOR:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagana3b31f02019-12-05 09:08:53 +00002996 break;
2997 }
2998 default:
2999 {
3000 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003001 fmt::format("Unexpected ResizeMethod[{}] when creating layerName {} ",
3002 static_cast<int>(resizeMethod), CHECK_LOCATION().AsString()));
Sadik Armagana3b31f02019-12-05 09:08:53 +00003003 }
3004 }
3005
James Conroy05102392020-06-24 15:39:55 +01003006 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01003007 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01003008 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
3009
3010 IConnectableLayer* layer = m_Network->AddResizeLayer(desc, layerName.c_str());
3011 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02003012 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3013
3014 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3015 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3016
3017 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3018 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3019}
3020
Kevin May7d96b162021-02-03 17:38:41 +00003021void TfLiteParserImpl::ParseConcatenation(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan479045b2018-10-01 11:51:37 +01003022{
3023 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3024
Mike Kelly0d77ae12022-01-07 17:42:27 +00003025 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3026 const auto* options = operatorPtr->builtin_options.AsConcatenationOptions();
Sadik Armagan479045b2018-10-01 11:51:37 +01003027
3028 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
3029
3030 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3031 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3032 CHECK_VALID_SIZE(outputs.size(), 1);
3033
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003034 unsigned int numConcatView = static_cast<unsigned int>(inputs.size());
3035 uint32_t inputRank = ToTensorInfo(inputs[0]).GetNumDimensions();
Sadik Armagan479045b2018-10-01 11:51:37 +01003036
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003037 const unsigned int concatDimInput = static_cast<unsigned int>(
3038 (static_cast<int>(inputRank) + options->axis) % static_cast<int>(inputRank));
Sadik Armagan479045b2018-10-01 11:51:37 +01003039
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003040 OriginsDescriptor concatDescriptor(static_cast<uint32_t>(numConcatView), inputRank);
3041 concatDescriptor.SetConcatAxis(concatDimInput);
Sadik Armagan479045b2018-10-01 11:51:37 +01003042
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003043 unsigned int mergeDimOrigin = 0;
Sadik Armagan479045b2018-10-01 11:51:37 +01003044
3045 for (unsigned int viewIndex = 0; viewIndex < numConcatView; ++viewIndex)
3046 {
3047 TensorInfo inputTensorInfo = ToTensorInfo(inputs[viewIndex]);
3048
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003049 // This set up concatDescriptor view origin
3050 armnnUtils::ProcessConcatInputTensorInfo(
3051 inputTensorInfo, concatDescriptor, concatDimInput, viewIndex, mergeDimOrigin);
Sadik Armagan479045b2018-10-01 11:51:37 +01003052 }
3053
James Ward58dec6b2020-09-11 17:32:44 +01003054 auto layerName = fmt::format("Concatenation:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagand109a4d2020-07-28 10:42:13 +01003055 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01003056
Jim Flynn906f9462019-05-10 13:55:21 +01003057 IConnectableLayer* layer = m_Network->AddConcatLayer(concatDescriptor, layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003058 ARMNN_ASSERT(layer != nullptr);
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003059 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Sadik Armagan479045b2018-10-01 11:51:37 +01003060
James Conroy05102392020-06-24 15:39:55 +01003061 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003062 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
Sadik Armagan479045b2018-10-01 11:51:37 +01003063
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00003064 // add fused activation layer
3065 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Sadik Armagan479045b2018-10-01 11:51:37 +01003066
Sadik Armagan479045b2018-10-01 11:51:37 +01003067 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3068 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3069}
3070
Kevin May7d96b162021-02-03 17:38:41 +00003071void TfLiteParserImpl::ParseFullyConnected(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003072{
3073 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3074
Mike Kelly0d77ae12022-01-07 17:42:27 +00003075 const auto& operatorRfr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003076 const auto options = operatorRfr->builtin_options.AsFullyConnectedOptions();
3077
3078 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
3079
3080 FullyConnectedDescriptor desc;
3081 desc.m_BiasEnabled = false;
Nattapat Chaimanowongd8eee592018-10-26 10:24:14 +01003082 desc.m_TransposeWeightMatrix = true;
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003083
3084 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3085 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3086 CHECK_VALID_SIZE(outputs.size(), 1);
3087
3088 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
3089
3090 // Fully Connected Layer accepts two dimensional weights input
3091 int32_t weightsDimension = static_cast<int32_t>(filterTensorInfo.GetNumDimensions());
3092 if (weightsDimension != 2)
3093 {
3094 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003095 fmt::format("Dimension {} for Fully Connected weights is not supported by Armnn. "
3096 "Node {}",
3097 weightsDimension,
3098 CHECK_LOCATION().AsString()));
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003099 }
3100
Matthew Jackson74bf7da2019-08-16 16:51:42 +01003101 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01003102 auto layerName = fmt::format("FullyConnected:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003103
Matthew Sloyan81beae32021-07-13 19:46:11 +01003104 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3105 // Add the first input tensor to the registration list
3106 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0]};
3107 std::vector<unsigned int> ignoreInputWhenRegister = {};
Mike Kelly5880b912022-01-28 16:18:54 +00003108 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003109
3110 desc.m_ConstantWeights = IsConstTensor(inputs[1]);
3111
Matthew Sloyan81beae32021-07-13 19:46:11 +01003112 // Add the weights input to the registration list, constant layers will be added by SetupConstantLayers if constant.
3113 tensorIndexesToRegister.emplace_back(inputTensorIndexes[1]);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003114
Mike Kelly5880b912022-01-28 16:18:54 +00003115 if (desc.m_ConstantWeights && inputTensorInfo.GetDataType() == DataType::Float32 &&
3116 (filterTensorInfo.GetDataType() == DataType::QAsymmU8 ||
3117 filterTensorInfo.GetDataType() == DataType::QAsymmS8))
3118 {
3119 m_ConstantsToDequantize.emplace_back(inputs[1]->buffer);
3120 }
3121
Finn Williamsd4fa5452021-03-01 12:31:41 +00003122 if (inputs.size() == 3)
3123 {
3124 desc.m_BiasEnabled = true;
Mike Kelly5880b912022-01-28 16:18:54 +00003125 armnn::TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Matthew Sloyan81beae32021-07-13 19:46:11 +01003126
3127 // Add the biases input to the registration list, constant layer will be added by SetupConstantLayers.
3128 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
Mike Kelly5880b912022-01-28 16:18:54 +00003129
3130 if (desc.m_ConstantWeights && inputTensorInfo.GetDataType() == DataType::Float32 &&
3131 (biasTensorInfo.GetDataType() == DataType::QAsymmU8 ||
3132 biasTensorInfo.GetDataType() == DataType::QAsymmS8))
3133 {
3134 m_ConstantsToDequantize.emplace_back(inputs[2]->buffer);
3135 }
Finn Williamsd4fa5452021-03-01 12:31:41 +00003136 }
3137
Matthew Sloyan81beae32021-07-13 19:46:11 +01003138 // Filters and biases are always passed to fully connected as inputs
3139 layer = m_Network->AddFullyConnectedLayer(desc, layerName.c_str());
Finn Williamsd4fa5452021-03-01 12:31:41 +00003140
3141 ARMNN_ASSERT(layer != nullptr);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003142
Finn Williamsd4fa5452021-03-01 12:31:41 +00003143 unsigned int startingSlotIndex = 0;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003144 if (inputTensorInfo.GetNumDimensions() > 2)
3145 {
3146 // Add reshape to flatten to 2D [batch_size, input_size],
3147 // where "input_size" corresponds to the number of inputs to the layer,
3148 // matching the second dimension of weights,
3149 // and "batch_size" is calculated by dividing the number of elements by "input_size".
3150 std::vector<unsigned int> reshapedDimensions(2);
3151 reshapedDimensions[1] = filterTensorInfo.GetShape()[1];
3152 reshapedDimensions[0] = inputTensorInfo.GetNumElements() / reshapedDimensions[1];
3153
3154 if (inputTensorInfo.GetNumElements() % reshapedDimensions[1] != 0)
3155 {
3156 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003157 fmt::format("Failed to deduce input tensor shape from filter size {} {}",
3158 reshapedDimensions[1],
3159 CHECK_LOCATION().AsString()));
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003160 }
3161
3162 armnn::TensorInfo reshapedTensorInfo = ToTensorInfo(inputs[0]);
3163 reshapedTensorInfo.SetShape(armnn::TensorShape{ 2, reshapedDimensions.data() });
3164
James Ward58dec6b2020-09-11 17:32:44 +01003165 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Finn Williamsd4fa5452021-03-01 12:31:41 +00003166 armnn::ReshapeDescriptor reshapeDescriptor;
3167 reshapeDescriptor.m_TargetShape = reshapedTensorInfo.GetShape();
3168 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(reshapeDescriptor, layerName.c_str());
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003169
3170 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedTensorInfo);
3171 reshapeLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(0));
3172
3173 RegisterInputSlots(subgraphIndex, operatorIndex, reshapeLayer, {inputTensorIndexes[0]});
Finn Williamsd4fa5452021-03-01 12:31:41 +00003174 // Fc layer connects to the reshape layer, so we skip the first input slot when registering fc's input slots
3175 tensorIndexesToRegister.erase(tensorIndexesToRegister.begin());
3176 startingSlotIndex = 1;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003177 }
Finn Williamsd4fa5452021-03-01 12:31:41 +00003178
3179 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister, startingSlotIndex);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003180
Sadik Armagand109a4d2020-07-28 10:42:13 +01003181 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003182 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3183
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003184 // we need to add the activation layer and fortunately we don't need to care about the data layout
3185 armnn::IConnectableLayer* fusedActivationLayer = AddFusedActivationLayer(layer, 0,
3186 options->fused_activation_function);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01003187
Sadik Armagan8853c1f2018-10-22 09:04:18 +01003188 // register the output connection slots for the layer, connections are made after all layers have been created
3189 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3190 RegisterOutputSlots(subgraphIndex, operatorIndex, fusedActivationLayer, {outputTensorIndexes[0]});
3191}
3192
Kevin May7d96b162021-02-03 17:38:41 +00003193void TfLiteParserImpl::ParseDetectionPostProcess(size_t subgraphIndex, size_t operatorIndex)
keidav011b3e2ea2019-02-21 10:07:37 +00003194{
3195 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3196
Mike Kelly0d77ae12022-01-07 17:42:27 +00003197 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
keidav011b3e2ea2019-02-21 10:07:37 +00003198
3199 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3200 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3201 CHECK_VALID_SIZE(outputs.size(), 4);
3202
3203 // Obtain custom options from flexbuffers
3204 auto custom_options = operatorPtr->custom_options;
3205 const flexbuffers::Map& m = flexbuffers::GetRoot(custom_options.data(), custom_options.size()).AsMap();
3206
3207 // Obtain descriptor information from tf lite
3208 DetectionPostProcessDescriptor desc;
3209 desc.m_MaxDetections = m["max_detections"].AsUInt32();
3210 desc.m_MaxClassesPerDetection = m["max_classes_per_detection"].AsUInt32();
3211 desc.m_NmsScoreThreshold = m["nms_score_threshold"].AsFloat();
3212 desc.m_NmsIouThreshold = m["nms_iou_threshold"].AsFloat();
3213 desc.m_NumClasses = m["num_classes"].AsUInt32();
3214 desc.m_ScaleH = m["h_scale"].AsFloat();
3215 desc.m_ScaleW = m["w_scale"].AsFloat();
3216 desc.m_ScaleX = m["x_scale"].AsFloat();
3217 desc.m_ScaleY = m["y_scale"].AsFloat();
3218
keidav0107d58c72019-02-26 11:57:39 +00003219 if (!(m["use_regular_nms"].IsNull()))
keidav011b3e2ea2019-02-21 10:07:37 +00003220 {
keidav0107d58c72019-02-26 11:57:39 +00003221 desc.m_UseRegularNms = m["use_regular_nms"].AsBool();
keidav011b3e2ea2019-02-21 10:07:37 +00003222 }
3223 if (!(m["detections_per_class"].IsNull()))
3224 {
3225 desc.m_DetectionsPerClass = m["detections_per_class"].AsUInt32();
3226 }
3227
3228 if (desc.m_NmsIouThreshold <= 0.0f || desc.m_NmsIouThreshold > 1.0f)
3229 {
3230 throw InvalidArgumentException("DetectionPostProcessTFLiteParser: Intersection over union threshold "
3231 "must be positive and less than or equal to 1.");
3232 }
3233
3234 armnn::TensorInfo anchorTensorInfo = ToTensorInfo(inputs[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003235 auto anchorTensorAndData = CreateConstTensorNonPermuted(inputs[2], anchorTensorInfo);
keidav011b3e2ea2019-02-21 10:07:37 +00003236
James Ward58dec6b2020-09-11 17:32:44 +01003237 auto layerName = fmt::format("DetectionPostProcess:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003238 IConnectableLayer* layer = m_Network->AddDetectionPostProcessLayer(desc, anchorTensorAndData,
keidav011b3e2ea2019-02-21 10:07:37 +00003239 layerName.c_str());
3240
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003241 ARMNN_ASSERT(layer != nullptr);
keidav011b3e2ea2019-02-21 10:07:37 +00003242
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003243 // The model does not specify the output shapes.
3244 // The output shapes are calculated from the max_detection and max_classes_per_detection.
3245 unsigned int numDetectedBox = desc.m_MaxDetections * desc.m_MaxClassesPerDetection;
3246 m_OverridenOutputShapes.push_back({ 1, numDetectedBox, 4 });
3247 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
3248 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
3249 m_OverridenOutputShapes.push_back({ 1 });
3250
keidav011b3e2ea2019-02-21 10:07:37 +00003251 for (unsigned int i = 0 ; i < outputs.size() ; ++i)
3252 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003253 armnn::TensorInfo detectionBoxOutputTensorInfo = ToTensorInfo(outputs[i], m_OverridenOutputShapes[i]);
keidav011b3e2ea2019-02-21 10:07:37 +00003254 layer->GetOutputSlot(i).SetTensorInfo(detectionBoxOutputTensorInfo);
3255 }
3256
3257 // Register the input connection slots for the layer, connections are made after all layers have been created
3258 // only the tensors for the inputs are relevant, exclude the const tensors
3259 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3260 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
3261
3262 // Register the output connection slots for the layer, connections are made after all layers have been created
3263 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3264 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0],
3265 outputTensorIndexes[1],
3266 outputTensorIndexes[2],
3267 outputTensorIndexes[3]});
3268}
3269
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003270/// The TfLite Pack operator is equivalent to the ArmNN Stack operator
Kevin May7d96b162021-02-03 17:38:41 +00003271void TfLiteParserImpl::ParsePack(size_t subgraphIndex, size_t operatorIndex)
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003272{
3273 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3274
3275 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3276 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3277 CHECK_VALID_SIZE(outputs.size(), 1);
3278
3279 if (inputs.size() < 1)
3280 {
3281 throw ParseException("Pack must have at least one input.");
3282 }
3283
3284 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3285 const auto* options = operatorPtr->builtin_options.AsPackOptions();
3286
3287 StackDescriptor desc;
3288 desc.m_Axis = static_cast<uint32_t>(options->axis);
3289 desc.m_NumInputs = static_cast<uint32_t>(inputs.size());
3290
3291 // Use the tensor shape of the first input as the "correct" input shape in the descriptor
3292 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3293 desc.m_InputShape = inputTensorInfo.GetShape();
3294
James Ward58dec6b2020-09-11 17:32:44 +01003295 auto layerName = fmt::format("Pack:{}:{}", subgraphIndex, operatorIndex);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003296 IConnectableLayer* layer = m_Network->AddStackLayer(desc, layerName.c_str());
3297
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003298 ARMNN_ASSERT(layer != nullptr);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003299
Sadik Armagand109a4d2020-07-28 10:42:13 +01003300 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003301 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3302
3303 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3304 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
3305
3306 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3307 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3308}
3309
Mike Kelly5880b912022-01-28 16:18:54 +00003310void TfLiteParserImpl::ParseUnidirectionalSequenceLSTM(size_t subgraphIndex, size_t operatorIndex)
3311{
3312 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3313
3314 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3315 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3316
3317 if (inputs.size() < 2)
3318 {
3319 throw ParseException("UnidirectionalSequenceLSTM must have at least 2 input.");
3320 }
3321
3322 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3323 const auto& subgraphPtr = m_Model->subgraphs[subgraphIndex];
3324 const auto nodeParams = operatorPtr->builtin_options.AsUnidirectionalSequenceLSTMOptions();
3325 CHECK_SUPPORTED_FUSED_ACTIVATION(nodeParams, subgraphIndex, operatorIndex);
3326 auto inputTensorInfo = ToTensorInfo(inputs[0]);
3327 auto outputTensorInfo = ToTensorInfo(outputs[0]);
3328
3329 // Set the params structure for the AddUnidirectionalSequenceLstmLayer call
3330 // Please refer to each operand at
3331 // https://www.tensorflow.org/mlir/tfl_ops#tflunidirectional_sequence_lstm_tflunidirectionalsequencelstmop
3332 armnn::LstmInputParams params;
3333
3334 if (IsOptionalOperandPresent(operatorPtr->inputs[1]))
3335 {
3336 params.m_InputToInputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[1]].get(),
3337 inputTensorInfo).first;
3338 }
3339
3340 params.m_InputToForgetWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[2]].get(),
3341 inputTensorInfo).first;
3342 params.m_InputToCellWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[3]].get(),
3343 inputTensorInfo).first;
3344 params.m_InputToOutputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[4]].get(),
3345 inputTensorInfo).first;
3346
3347 // Recurrent weight tensors of size {n_cell, n_output}
3348 if (IsOptionalOperandPresent(operatorPtr->inputs[5]))
3349 {
3350 params.m_RecurrentToInputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[5]].get(),
3351 inputTensorInfo).first;
3352 }
3353
3354 params.m_RecurrentToForgetWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[6]].get(),
3355 inputTensorInfo).first;
3356 params.m_RecurrentToCellWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[7]].get(),
3357 inputTensorInfo).first;
3358 params.m_RecurrentToOutputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[8]].get(),
3359 inputTensorInfo).first;
3360
3361 // Peephole weights tensors of size {n_cell}, representing a diagonal matrix.
3362 if (IsOptionalOperandPresent(operatorPtr->inputs[9]))
3363 {
3364 params.m_CellToInputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[9]].get(),
3365 inputTensorInfo).first;
3366 }
3367
3368 if (IsOptionalOperandPresent(operatorPtr->inputs[10]))
3369 {
3370 params.m_CellToForgetWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[10]].get(),
3371 inputTensorInfo).first;
3372 }
3373
3374 if (IsOptionalOperandPresent(operatorPtr->inputs[11]))
3375 {
3376 params.m_CellToOutputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[11]].get(),
3377 inputTensorInfo).first;
3378 }
3379
3380 // Gates bias tensors of size {n_cell}
3381 if (IsOptionalOperandPresent(operatorPtr->inputs[12]))
3382 {
3383 params.m_InputGateBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[12]].get(),
3384 inputTensorInfo).first;
3385 }
3386
3387 params.m_ForgetGateBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[13]].get(),
3388 inputTensorInfo).first;
3389 params.m_CellBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[14]].get(),
3390 inputTensorInfo).first;
3391 params.m_OutputGateBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[15]].get(),
3392 inputTensorInfo).first;
3393
3394 // Projection weight tensor of size {n_output, n_cell}
3395 if (IsOptionalOperandPresent(operatorPtr->inputs[16]))
3396 {
3397 params.m_ProjectionWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[16]].get(),
3398 inputTensorInfo).first;
3399 }
3400 // Projection bias tensor of size {n_output}
3401 if (IsOptionalOperandPresent(operatorPtr->inputs[17]))
3402 {
3403 params.m_ProjectionBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[17]].get(),
3404 inputTensorInfo).first;
3405 }
3406
3407 // These state tensors are defined as variable tensors, and will be modified by this op.
3408 armnn::TensorInfo outputStateInInfo = ToTensorInfo(subgraphPtr->tensors[operatorPtr->inputs[18]].get());
3409 m_ConstantsToBeCreated.push_back(operatorPtr->inputs[18]);
3410 armnn::TensorInfo cellStateInInfo = ToTensorInfo(subgraphPtr->tensors[operatorPtr->inputs[19]].get());
3411 m_ConstantsToBeCreated.push_back(operatorPtr->inputs[19]);
3412
3413 // Layer norm coefficient tensors of size {n_cell}, representing a diagonal matrix.
3414 if (inputs.size() >= 21 && IsOptionalOperandPresent(operatorPtr->inputs[20]))
3415 {
3416 params.m_InputLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[20]].get(),
3417 inputTensorInfo).first;
3418 }
3419
3420 if (inputs.size() >= 22 && IsOptionalOperandPresent(operatorPtr->inputs[21]))
3421 {
3422 params.m_ForgetLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[21]].get(),
3423 inputTensorInfo).first;
3424 }
3425
3426 if (inputs.size() >= 23 && IsOptionalOperandPresent(operatorPtr->inputs[22]))
3427 {
3428 params.m_CellLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[22]].get(),
3429 inputTensorInfo).first;
3430 }
3431
3432 if (inputs.size() >= 24 && IsOptionalOperandPresent(operatorPtr->inputs[23]))
3433 {
3434 params.m_OutputLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[23]].get(),
3435 inputTensorInfo).first;
3436 }
3437
3438 // set the layer descriptor
3439 armnn::UnidirectionalSequenceLstmDescriptor desc;
3440 desc.m_ActivationFunc = nodeParams->fused_activation_function;
3441 desc.m_ClippingThresCell = nodeParams->cell_clip;
3442 desc.m_ClippingThresProj = nodeParams->proj_clip;
3443 desc.m_CifgEnabled = (params.m_InputToInputWeights == nullptr
3444 || params.m_RecurrentToInputWeights == nullptr
3445 || params.m_InputGateBias == nullptr);
3446 desc.m_PeepholeEnabled = (params.m_CellToForgetWeights != nullptr || params.m_CellToOutputWeights != nullptr);
3447 desc.m_ProjectionEnabled = (params.m_ProjectionWeights != nullptr);
3448 desc.m_LayerNormEnabled = (params.m_InputLayerNormWeights != nullptr
3449 || params.m_ForgetLayerNormWeights != nullptr
3450 || params.m_CellLayerNormWeights != nullptr
3451 || params.m_OutputLayerNormWeights != nullptr);
3452 desc.m_TimeMajor = nodeParams->time_major;
3453
Mike Kellyc0800a32022-06-15 10:57:52 +01003454 if (operatorPtr->intermediates.size() > 3 && desc.m_LayerNormEnabled)
Mike Kelly5880b912022-01-28 16:18:54 +00003455 {
3456 auto inputIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[0]].get(),
3457 inputTensorInfo).first;
3458 auto inputIntermediateTensorInfo = inputIntermediate->GetInfo();
3459 desc.m_InputIntermediateScale = inputIntermediateTensorInfo.GetQuantizationScale();
3460
3461 auto forgetIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[1]].get(),
3462 inputTensorInfo).first;
3463 auto forgetIntermediateTensorInfo = forgetIntermediate->GetInfo();
3464 desc.m_ForgetIntermediateScale = forgetIntermediateTensorInfo.GetQuantizationScale();
3465
3466 auto cellIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[2]].get(),
3467 inputTensorInfo).first;
3468 auto cellIntermediateTensorInfo = cellIntermediate->GetInfo();
3469 desc.m_CellIntermediateScale = cellIntermediateTensorInfo.GetQuantizationScale();
3470
3471 auto outputIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[3]].get(),
3472 inputTensorInfo).first;
3473 auto outputIntermediateTensorInfo = outputIntermediate->GetInfo();
3474 desc.m_OutputIntermediateScale = outputIntermediateTensorInfo.GetQuantizationScale();
3475 }
3476 else
3477 {
3478 float defaultIntermediate = std::pow(2, -12);
3479 desc.m_InputIntermediateScale = defaultIntermediate;
3480 desc.m_ForgetIntermediateScale = defaultIntermediate;
3481 desc.m_CellIntermediateScale = defaultIntermediate;
3482 desc.m_OutputIntermediateScale = defaultIntermediate;
3483 }
3484
Mike Kellyc0800a32022-06-15 10:57:52 +01003485 if (operatorPtr->intermediates.size() > 4)
3486 {
3487 auto hiddentensor = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[4]].get(),
3488 inputTensorInfo).first;
Mike Kelly5880b912022-01-28 16:18:54 +00003489
Mike Kellyc0800a32022-06-15 10:57:52 +01003490 desc.m_HiddenStateScale = hiddentensor->GetInfo().GetQuantizationScale();
3491 desc.m_HiddenStateZeroPoint = hiddentensor->GetInfo().GetQuantizationOffset();
3492 }
Mike Kelly5880b912022-01-28 16:18:54 +00003493 unsigned int batchSize = inputTensorInfo.GetShape()[0];
3494 unsigned int outputSize = outputTensorInfo.GetShape()[2];
3495 unsigned int numUnits = cellStateInInfo.GetShape()[1];
3496
3497 armnn::DataType dataType = inputTensorInfo.GetDataType();
3498 float qScale = inputTensorInfo.GetQuantizationScale();
3499 float qOffset = inputTensorInfo.GetQuantizationOffset();
3500
3501 armnn::TensorInfo scratchBufferTensorInfo({batchSize, numUnits * 3}, dataType, qScale, qOffset);
3502 if (!desc.m_CifgEnabled)
3503 {
3504 scratchBufferTensorInfo = armnn::TensorInfo({batchSize, numUnits * 4}, dataType, qScale, qOffset);
3505 }
3506 armnn::TensorInfo cellStateOutTensorInfo({batchSize, numUnits},
3507 cellStateInInfo.GetDataType(),
3508 cellStateInInfo.GetQuantizationScale(),
3509 cellStateInInfo.GetQuantizationOffset());
3510 armnn::TensorInfo outputStateOutTensorInfo({batchSize, outputSize}, dataType, qScale, qOffset);
3511
3512 armnn::LstmInputParamsInfo paramsInfo;
3513 paramsInfo.m_InputToForgetWeights = &(params.m_InputToForgetWeights->GetInfo());
3514 paramsInfo.m_InputToCellWeights = &(params.m_InputToCellWeights->GetInfo());
3515 paramsInfo.m_InputToOutputWeights = &(params.m_InputToOutputWeights->GetInfo());
3516 paramsInfo.m_RecurrentToForgetWeights = &(params.m_RecurrentToForgetWeights->GetInfo());
3517 paramsInfo.m_RecurrentToCellWeights = &(params.m_RecurrentToCellWeights->GetInfo());
3518 paramsInfo.m_RecurrentToOutputWeights = &(params.m_RecurrentToOutputWeights->GetInfo());
3519 paramsInfo.m_ForgetGateBias = &(params.m_ForgetGateBias->GetInfo());
3520 paramsInfo.m_CellBias = &(params.m_CellBias->GetInfo());
3521 paramsInfo.m_OutputGateBias = &(params.m_OutputGateBias->GetInfo());
3522
3523 if (!desc.m_CifgEnabled)
3524 {
3525 paramsInfo.m_InputToInputWeights = &(params.m_InputToInputWeights->GetInfo());
3526 paramsInfo.m_RecurrentToInputWeights = &(params.m_RecurrentToInputWeights->GetInfo());
3527 if (params.m_CellToInputWeights != nullptr)
3528 {
3529 paramsInfo.m_CellToInputWeights = &(params.m_CellToInputWeights->GetInfo());
3530 }
3531 paramsInfo.m_InputGateBias = &(params.m_InputGateBias->GetInfo());
3532 }
3533
3534 if (desc.m_ProjectionEnabled)
3535 {
3536 paramsInfo.m_ProjectionWeights = &(params.m_ProjectionWeights->GetInfo());
3537 if (params.m_ProjectionBias != nullptr)
3538 {
3539 paramsInfo.m_ProjectionBias = &(params.m_ProjectionBias->GetInfo());
3540 }
3541 }
3542
3543 if (desc.m_PeepholeEnabled)
3544 {
3545 paramsInfo.m_CellToForgetWeights = &(params.m_CellToForgetWeights->GetInfo());
3546 paramsInfo.m_CellToOutputWeights = &(params.m_CellToOutputWeights->GetInfo());
3547 }
3548
3549 if (desc.m_LayerNormEnabled)
3550 {
3551 if(!desc.m_CifgEnabled)
3552 {
3553 paramsInfo.m_InputLayerNormWeights = &(params.m_InputLayerNormWeights->GetInfo());
3554 }
3555 paramsInfo.m_ForgetLayerNormWeights = &(params.m_ForgetLayerNormWeights->GetInfo());
3556 paramsInfo.m_CellLayerNormWeights = &(params.m_CellLayerNormWeights->GetInfo());
3557 paramsInfo.m_OutputLayerNormWeights = &(params.m_OutputLayerNormWeights->GetInfo());
3558 }
3559
3560 auto layerName = fmt::format("UnidirectionalSequenceLSTM:{}:{}", subgraphIndex, operatorIndex);
3561 armnn::IConnectableLayer* layer = m_Network->AddUnidirectionalSequenceLstmLayer(desc, params);
3562 ARMNN_ASSERT(layer != nullptr);
3563
3564 // register the input connection slots for the layer, connections are made after all layers have been created
3565 // only the tensors for the inputs are relevant, exclude the const tensors
3566 auto inputTensorIndexes = AsUnsignedVector({operatorPtr->inputs[0],
3567 operatorPtr->inputs[18],
3568 operatorPtr->inputs[19]});
3569 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0],
3570 inputTensorIndexes[1],
3571 inputTensorIndexes[2]});
3572
3573 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3574
3575 layer->GetOutputSlot(0).SetTensorInfo(outputStateOutTensorInfo);
3576 layer->GetOutputSlot(1).SetTensorInfo(cellStateOutTensorInfo);
3577 layer->GetOutputSlot(2).SetTensorInfo(outputTensorInfo);
3578
3579 unsigned int tensorIndex = outputTensorIndexes[0];
3580 armnn::IOutputSlot* slot = &(layer->GetOutputSlot(2));
3581 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
3582}
3583
Kevin May7d96b162021-02-03 17:38:41 +00003584void TfLiteParserImpl::ParseUnpack(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd200e3802019-04-15 09:47:39 +01003585{
3586 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3587
Mike Kelly0d77ae12022-01-07 17:42:27 +00003588 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3589 const auto* options = operatorPtr->builtin_options.AsUnpackOptions();
Nina Drozd200e3802019-04-15 09:47:39 +01003590
3591 // This unpackAxis indicates the axis to unpack
3592 const unsigned int unpackAxis = CHECKED_NON_NEGATIVE(options->axis);
3593
3594 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3595 CHECK_VALID_SIZE(inputs.size(), 1);
3596
3597 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003598
3599 if (unpackAxis >= inputTensorInfo.GetNumDimensions())
3600 {
3601 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003602 fmt::format("The unpack axis: {} cannot be greater than or equal to "
3603 "the number of input dimension {} {}",
3604 unpackAxis,
3605 inputTensorInfo.GetNumDimensions(),
3606 CHECK_LOCATION().AsString()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003607 }
3608
Nina Drozd200e3802019-04-15 09:47:39 +01003609 unsigned int unpackNum = CHECKED_NON_NEGATIVE(options->num);
3610 // If num is not defined, automatically infer from the length of the dimension axis.
3611 if(unpackNum == 0)
3612 {
3613 unpackNum = inputTensorInfo.GetShape()[unpackAxis];
3614 }
3615
3616 // If unpack number cannot be inferred and is still zero, throw ParseException.
3617 if(unpackNum == 0)
3618 {
3619 throw ParseException("Number to unpack must greater than zero.");
3620 }
3621
3622 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3623 CHECK_VALID_SIZE(outputs.size(), unpackNum);
3624
3625 auto inputDimSize = inputTensorInfo.GetNumDimensions();
3626 std::vector<unsigned int> unpackDimSizes(inputDimSize);
3627
3628 // Add current input shape to unpackDimSizes
3629 for (unsigned int i = 0; i < inputDimSize; ++i)
3630 {
3631 unpackDimSizes[i] = inputTensorInfo.GetShape()[i];
3632 }
3633
3634 if (unpackDimSizes[unpackAxis] != unpackNum)
3635 {
3636 throw ParseException("Number to unpack must be the same as length of the dimension to "
3637 "unpack along.");
3638 }
3639
3640 unpackDimSizes[unpackAxis] /= unpackNum;
3641
3642 SplitterDescriptor splitDesc(unpackNum, static_cast<unsigned int>(unpackDimSizes.size()));
3643 for (unsigned int j = 0; j < unpackNum; ++j)
3644 {
3645 // Set the size of the views.
3646 for (unsigned int dimIdx = 0; dimIdx < unpackDimSizes.size(); ++dimIdx)
3647 {
3648 splitDesc.SetViewSize(j, dimIdx, unpackDimSizes[dimIdx]);
3649 }
3650 splitDesc.SetViewOriginCoord(j, unpackAxis, unpackDimSizes[unpackAxis] * j);
3651 }
3652
James Ward58dec6b2020-09-11 17:32:44 +01003653 auto layerName = fmt::format("Unpack:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd200e3802019-04-15 09:47:39 +01003654 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01003655 ARMNN_ASSERT(layer != nullptr);
Nina Drozd200e3802019-04-15 09:47:39 +01003656
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003657 TensorShape splitOutShape = TensorShape(static_cast<unsigned int>(unpackDimSizes.size()),
3658 unpackDimSizes.data());
3659
Nina Drozd200e3802019-04-15 09:47:39 +01003660 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3661 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3662
Finn Williamsb49ed182021-06-29 15:50:08 +01003663 std::vector<unsigned int> reshapeDims;
3664 for (unsigned int axis = 0; axis < splitOutShape.GetNumDimensions(); ++axis)
3665 {
3666 if (axis != unpackAxis)
3667 {
3668 reshapeDims.push_back(splitOutShape[axis]);
3669 }
3670 }
3671
3672 TensorShape reshapeOutputShape(splitOutShape.GetNumDimensions() -1, reshapeDims.data());
3673
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003674 // Create reshape to remove the unpacked dimension for unpack operator of each output from Splitter.
3675 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
3676 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01003677 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[k], true);
James Ward58dec6b2020-09-11 17:32:44 +01003678 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003679 armnn::ReshapeDescriptor desc;
Finn Williamsb49ed182021-06-29 15:50:08 +01003680 desc.m_TargetShape = reshapeOutputShape;
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003681 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(desc, layerName.c_str());
3682
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01003683 layer->GetOutputSlot(k).SetTensorInfo(armnn::TensorInfo(splitOutShape,
3684 outputTensorInfo.GetDataType(),
3685 outputTensorInfo.GetQuantizationScale(),
3686 outputTensorInfo.GetQuantizationOffset()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003687 layer->GetOutputSlot(k).Connect(reshapeLayer->GetInputSlot(0));
3688
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01003689 reshapeLayer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003690
3691 uint32_t reshapedOutputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[k]);
3692 armnn::IOutputSlot* slot = &(reshapeLayer->GetOutputSlot(0));
3693 RegisterProducerOfTensor(subgraphIndex, reshapedOutputId, slot);
3694 }
Nina Drozd200e3802019-04-15 09:47:39 +01003695}
3696
Kevin May7d96b162021-02-03 17:38:41 +00003697void TfLiteParserImpl::ParseSplit(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd0324f482019-04-08 10:52:10 +01003698{
3699 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3700
Mike Kelly0d77ae12022-01-07 17:42:27 +00003701 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3702 const auto* options = operatorPtr->builtin_options.AsSplitOptions();
Nina Drozd0324f482019-04-08 10:52:10 +01003703
3704 const unsigned int numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
3705
Nina Drozd200e3802019-04-15 09:47:39 +01003706 // If number of splits cannot be inferred and is zero, throw ParseException.
3707 if(numSplits == 0)
3708 {
3709 throw ParseException("Number to splits must greater than zero.");
3710 }
3711
Nina Drozd0324f482019-04-08 10:52:10 +01003712 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3713 CHECK_VALID_SIZE(inputs.size(), 2);
3714 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3715 CHECK_VALID_SIZE(outputs.size(), numSplits);
3716
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003717 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[1]);
3718 armnn::TensorInfo axisTensorInfo = ToTensorInfo(inputs[0]);
3719 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
Nina Drozd0324f482019-04-08 10:52:10 +01003720
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003721 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003722 if (axisBufferPtr == nullptr)
3723 {
3724 throw ParseException(
3725 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
3726 CHECK_LOCATION().AsString()));
3727 }
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003728
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003729 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
3730 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
3731 int32_t axis = axisData[0];
3732
3733 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3734 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3735 {
3736 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
3737 // E.g. Rank 4 tensor can have axis in range [-4, 3)
3738 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
3739 throw ParseException(
3740 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3741 axis,
3742 CHECK_LOCATION().AsString()));
3743 }
3744
3745 const unsigned int splitDim = armnnUtils::GetUnsignedAxis(inputTensorInfo.GetNumDimensions(), axis);
Nina Drozd0324f482019-04-08 10:52:10 +01003746
Nina Drozd0324f482019-04-08 10:52:10 +01003747 auto inputDimSize = inputTensorInfo.GetNumDimensions();
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003748 if (inputDimSize > MaxNumOfTensorDimensions)
Nina Drozd0324f482019-04-08 10:52:10 +01003749 {
3750 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003751 fmt::format("The number of dimensions: {} for input tensors of the split op cannot be greater than {} {}",
3752 inputTensorInfo.GetNumDimensions(),
3753 MaxNumOfTensorDimensions,
3754 CHECK_LOCATION().AsString()));
Nina Drozd0324f482019-04-08 10:52:10 +01003755 }
3756
3757 std::vector<unsigned int> splitterDimSizes(inputDimSize);
3758
3759 // Add current input shape to splitterDimSizes
3760 for (unsigned int i = 0; i < inputDimSize; ++i)
3761 {
3762 splitterDimSizes[i] = inputTensorInfo.GetShape()[i];
3763 }
3764
3765 if (splitterDimSizes[splitDim] % numSplits != 0)
3766 {
3767 throw ParseException("Number of splits must evenly divide the dimension");
3768 }
3769 splitterDimSizes[splitDim] /= numSplits;
3770
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003771 SplitterDescriptor splitDesc(numSplits, inputDimSize);
Nina Drozd0324f482019-04-08 10:52:10 +01003772 for (unsigned int j = 0; j < numSplits; ++j)
3773 {
3774 // Set the size of the views.
3775 for (unsigned int dimIdx = 0; dimIdx < splitterDimSizes.size(); ++dimIdx)
3776 {
3777 splitDesc.SetViewSize(j, dimIdx, splitterDimSizes[dimIdx]);
3778 }
3779 splitDesc.SetViewOriginCoord(j, splitDim, splitterDimSizes[splitDim] * j);
3780 }
3781
James Ward58dec6b2020-09-11 17:32:44 +01003782 auto layerName = fmt::format("Split:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd0324f482019-04-08 10:52:10 +01003783 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01003784 ARMNN_ASSERT(layer != nullptr);
Nina Drozd0324f482019-04-08 10:52:10 +01003785
3786 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003787 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[1]});
Nina Drozd0324f482019-04-08 10:52:10 +01003788
Nina Drozd0324f482019-04-08 10:52:10 +01003789 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
3790 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01003791 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Francis Murtagh98d6b3d2019-10-21 10:52:54 +01003792 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
Nina Drozd0324f482019-04-08 10:52:10 +01003793 }
3794
3795 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3796 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3797}
3798
Derek Lambertif0176992020-04-28 13:37:49 +01003799unsigned int ComputeWrappedIndex(int idx, unsigned int numDimsIn)
3800{
3801 int numDims = armnn::numeric_cast<int>(numDimsIn);
3802 int v = idx < 0 ? numDims + idx : idx;
3803 ARMNN_ASSERT(v >= 0);
3804 ARMNN_ASSERT(v < numDims);
3805
3806 return static_cast<unsigned int>(v);
3807}
3808
Kevin May7d96b162021-02-03 17:38:41 +00003809void TfLiteParserImpl::ParseSplitV(size_t subgraphIndex, size_t operatorIndex)
Derek Lambertif0176992020-04-28 13:37:49 +01003810{
3811 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3812
Mike Kelly0d77ae12022-01-07 17:42:27 +00003813 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3814 const auto* options = operatorPtr->builtin_options.AsSplitVOptions();
Derek Lambertif0176992020-04-28 13:37:49 +01003815
3816 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3817 CHECK_VALID_SIZE(inputs.size(), 3);
3818
3819 auto& inputTensor = inputs[0];
3820 auto& splitsTensor = inputs[1];
3821 auto& axisTensor = inputs[2];
3822
3823 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputTensor);
3824 armnn::TensorInfo splitsInfo = ToTensorInfo(splitsTensor);
3825 armnn::TensorInfo axisTensorInfo = ToTensorInfo(axisTensor);
3826 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
3827
3828 // Inputs
3829 auto inputDimSize = inputTensorInfo.GetNumDimensions();
3830 if (inputDimSize > MaxNumOfTensorDimensions)
3831 {
3832 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003833 fmt::format("The number of dimensions: {} for input tensors of the "
3834 "SplitV op cannot be greater than {} {}",
3835 inputTensorInfo.GetNumDimensions(),
3836 MaxNumOfTensorDimensions,
3837 CHECK_LOCATION().AsString()));
Derek Lambertif0176992020-04-28 13:37:49 +01003838 }
3839
3840 // Get split axis
3841 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, axisTensor->buffer);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003842 if (axisBufferPtr == nullptr)
3843 {
3844 throw ParseException(
3845 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
3846 CHECK_LOCATION().AsString()));
3847 }
3848
Derek Lambertif0176992020-04-28 13:37:49 +01003849 std::vector<int> axisData(axisTensorInfo.GetNumElements());
3850 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003851 int32_t axis = axisData[0];
3852
3853 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3854 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3855 {
3856 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
3857 // E.g. Rank 4 tensor can have axis in range [-4, 3)
3858 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
3859 throw ParseException(
3860 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3861 axis,
3862 CHECK_LOCATION().AsString()));
3863 }
3864 const unsigned int splitDim = ComputeWrappedIndex(axis, inputTensorInfo.GetNumDimensions());
Derek Lambertif0176992020-04-28 13:37:49 +01003865
Derek Lambertif0176992020-04-28 13:37:49 +01003866 // Set split sizes
Derek Lambertif0176992020-04-28 13:37:49 +01003867 CHECK_VALID_SIZE(splitsInfo.GetNumDimensions(), 1);
Ryan OShea86704732020-05-26 11:41:04 +01003868 unsigned int numSplits{0};
3869
3870 if(options)
Derek Lambertif0176992020-04-28 13:37:49 +01003871 {
3872 numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
Derek Lambertif0176992020-04-28 13:37:49 +01003873 }
3874 else
3875 {
Ryan OShea86704732020-05-26 11:41:04 +01003876 numSplits = splitsInfo.GetNumElements();
Derek Lambertif0176992020-04-28 13:37:49 +01003877 }
3878
3879 if (numSplits <=0)
3880 {
3881 throw ParseException("SplitV has invalid number of splits");
3882 }
3883
Jan Eilersc0761e92020-06-29 16:48:44 +01003884 std::vector<int> splitsData(numSplits);
Ryan OShea86704732020-05-26 11:41:04 +01003885 BufferRawPtr splitsBufferPtr = GetBuffer(m_Model, splitsTensor->buffer);
Jan Eilersc0761e92020-06-29 16:48:44 +01003886 ::memcpy(splitsData.data(), splitsBufferPtr->data.data(), splitsInfo.GetNumBytes());
Ryan OShea86704732020-05-26 11:41:04 +01003887
Jan Eilersc0761e92020-06-29 16:48:44 +01003888 unsigned int idx = 0;
Ryan OShea86704732020-05-26 11:41:04 +01003889 int numInferred{0};
3890 unsigned int inferIdx{0};
3891 int splitSum{0};
3892 for (auto split : splitsData)
3893 {
3894 if (split < 0)
3895 {
3896 numInferred++;
3897 inferIdx = idx;
3898 }
3899 else
3900 {
3901 splitSum += split;
3902 }
3903 idx++;
3904 }
3905 // Check for inferred Axis
3906 if (numInferred == 0)
3907 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01003908 if (splitSum != armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]))
Ryan OShea86704732020-05-26 11:41:04 +01003909 {
3910 throw ParseException("SplitV split_sizes does not sum to the dimension of value along split_dim.");
3911 }
3912 }
3913 else if (numInferred == 1)
3914 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01003915 splitsData[inferIdx] = armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]) - splitSum;
Ryan OShea86704732020-05-26 11:41:04 +01003916 }
3917 else
3918 {
3919 throw ParseException("Cannot infer split size for more than one split");
3920 }
3921
Derek Lambertif0176992020-04-28 13:37:49 +01003922 //Ouput size validation
3923 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3924 CHECK_VALID_SIZE(outputs.size(), numSplits);
3925
3926 // Setup Armnn descriptor
3927 SplitterDescriptor splitDesc(numSplits, inputDimSize);
3928 unsigned int accumSplit = 0;
3929 for (unsigned int j = 0; j < numSplits; ++j)
3930 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01003931 unsigned int splitSize = armnn::numeric_cast<unsigned int>(splitsData[j]);
Derek Lambertif0176992020-04-28 13:37:49 +01003932
3933 // Set the size of the views.
3934 for (unsigned int dimIdx = 0; dimIdx < inputTensorInfo.GetNumDimensions(); ++dimIdx)
3935 {
3936 unsigned int dimSize = inputTensorInfo.GetShape()[dimIdx];
3937 if (dimIdx == splitDim)
3938 {
3939 dimSize = splitSize;
3940 }
3941 splitDesc.SetViewSize(j, dimIdx, dimSize);
3942 }
3943
3944 splitDesc.SetViewOriginCoord(j, splitDim, accumSplit);
3945 accumSplit += splitSize;
3946 }
3947
James Ward58dec6b2020-09-11 17:32:44 +01003948 auto layerName = fmt::format("SplitV:{}:{}", subgraphIndex, operatorIndex);
Derek Lambertif0176992020-04-28 13:37:49 +01003949 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01003950 ARMNN_ASSERT(layer != nullptr);
Derek Lambertif0176992020-04-28 13:37:49 +01003951
3952 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3953 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3954
3955 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
3956 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01003957 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Derek Lambertif0176992020-04-28 13:37:49 +01003958 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
3959 }
3960
3961 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3962 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3963}
3964
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003965void TfLiteParserImpl::ParseArgMin(size_t subgraphIndex, size_t operatorIndex)
3966{
3967 ParseArgMinMax(subgraphIndex, operatorIndex, armnn::ArgMinMaxFunction::Min);
3968}
3969
Kevin May7d96b162021-02-03 17:38:41 +00003970void TfLiteParserImpl::ParseArgMax(size_t subgraphIndex, size_t operatorIndex)
Inki Daed4619e22020-09-10 15:33:54 +09003971{
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003972 ParseArgMinMax(subgraphIndex, operatorIndex, armnn::ArgMinMaxFunction::Max);
3973}
3974
3975void TfLiteParserImpl::ParseArgMinMax(size_t subgraphIndex, size_t operatorIndex, ArgMinMaxFunction argMinMaxFunction)
3976{
Inki Daed4619e22020-09-10 15:33:54 +09003977 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3978 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3979 CHECK_VALID_SIZE(inputs.size(), 2);
3980
3981 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3982 CHECK_VALID_SIZE(outputs.size(), 1);
3983
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003984 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3985 armnn::TensorInfo axisTensorInfo = ToTensorInfo(inputs[1]);
Inki Daed4619e22020-09-10 15:33:54 +09003986 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003987 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003988
3989 // Check if output tensor type is Signed32 or Signed64
Mike Kelly1f140f72021-04-06 12:25:55 +01003990 if (outputTensorInfo.GetDataType() != armnn::DataType::Signed32 &&
3991 outputTensorInfo.GetDataType() != armnn::DataType::Signed64)
3992 {
3993 throw ParseException(
3994 fmt::format(
3995 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
3996 CHECK_LOCATION().AsString()));
3997 }
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003998
3999 // Get const axis value from model and set it to descriptor.
4000 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
4001 if (axisBufferPtr == nullptr)
4002 {
4003 throw ParseException(
4004 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
4005 CHECK_LOCATION().AsString()));
4006 }
4007
4008 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
4009 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
4010 int32_t axis = axisData.front();
4011
4012 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
4013 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
4014 {
4015 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
4016 // E.g. Rank 4 tensor can have axis in range [-4, 3)
4017 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
4018 throw ParseException(
4019 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
4020 axis,
4021 CHECK_LOCATION().AsString()));
4022 }
4023
4024 ArgMinMaxDescriptor desc;
4025 desc.m_Axis = axis;
4026 desc.m_Function = argMinMaxFunction;
4027
4028 // Register a ArgMin/ArgMax layer.
4029 auto layerName = argMinMaxFunction == ArgMinMaxFunction::Max ? "ArgMax:{}:{}" : "ArgMin:{}:{}";
4030 auto layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
4031 IConnectableLayer *layer = m_Network->AddArgMinMaxLayer(desc, layerNameFormatted.c_str());
4032 ARMNN_ASSERT(layer != nullptr);
Inki Daed4619e22020-09-10 15:33:54 +09004033 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4034
4035 // Register input tensor to the layer.
4036 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4037 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4038
4039 // Register output tensor to the layer.
4040 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4041 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
4042}
4043
Kevin May7d96b162021-02-03 17:38:41 +00004044void TfLiteParserImpl::ParseGather(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00004045{
4046 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4047
Kevin May7d96b162021-02-03 17:38:41 +00004048 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004049 CHECK_VALID_SIZE(inputs.size(), 2);
Kevin May7d96b162021-02-03 17:38:41 +00004050 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004051 CHECK_VALID_SIZE(outputs.size(), 1);
4052
4053 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
4054 armnn::TensorInfo indicesTensorInfo = ToTensorInfo(inputs[1]);
4055 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
4056
4057 armnn::GatherDescriptor gatherDescriptor;
4058
Mike Kelly0d77ae12022-01-07 17:42:27 +00004059 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4060 const auto* options = operatorPtr->builtin_options.AsGatherOptions();
Sadik Armagan26868492021-01-22 14:25:31 +00004061 auto axis = options->axis;
4062
4063 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
4064 auto indicesDimensions = indicesTensorInfo.GetNumDimensions();
4065 auto outputDimensions = outputTensorInfo.GetNumDimensions();
4066 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
4067 {
4068 throw ParseException(
4069 fmt::format("Operation has invalid axis: {} It is out of bounds [ -{}, {} ) {}",
4070 axis,
4071 inputDimensions, inputDimensions,
4072 CHECK_LOCATION().AsString()));
4073 }
4074 if (outputDimensions != static_cast<unsigned int>(inputDimensions) + indicesDimensions - 1)
4075 {
4076 throw ParseException(
4077 fmt::format("Operation has invalid output dimensions: {} Output must be an ({} + {} - 1) -D tensor {}",
4078 outputDimensions,
4079 inputDimensions, indicesDimensions,
4080 CHECK_LOCATION().AsString()));
4081 }
4082
4083 gatherDescriptor.m_Axis = axis;
4084
4085 auto layerName = fmt::format("Gather:{}:{}", subgraphIndex, operatorIndex);
4086 IConnectableLayer* layer = m_Network->AddGatherLayer(gatherDescriptor, layerName.c_str());
4087 ARMNN_ASSERT(layer != nullptr);
4088 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4089
4090 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4091 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
4092
4093 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4094 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4095}
4096
Teresa Charlin91a53ea2022-04-25 15:47:29 +01004097void TfLiteParserImpl::ParseGatherNd(size_t subgraphIndex, size_t operatorIndex)
4098{
4099 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4100
4101 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4102 CHECK_VALID_SIZE(inputs.size(), 2);
4103 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4104 CHECK_VALID_SIZE(outputs.size(), 1);
4105
4106 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
4107 armnn::TensorInfo indicesTensorInfo = ToTensorInfo(inputs[1]);
4108 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
4109
4110 auto layerName = fmt::format("GatherNd:{}:{}", subgraphIndex, operatorIndex);
4111 IConnectableLayer* layer = m_Network->AddGatherNdLayer(layerName.c_str());
4112 ARMNN_ASSERT(layer != nullptr);
4113 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4114
4115 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4116 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
4117
4118 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4119 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4120}
4121
Kevin May7d96b162021-02-03 17:38:41 +00004122void TfLiteParserImpl::ParseDepthToSpace(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00004123{
4124 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4125
Kevin May7d96b162021-02-03 17:38:41 +00004126 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004127 CHECK_VALID_SIZE(inputs.size(), 1);
Kevin May7d96b162021-02-03 17:38:41 +00004128 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00004129 CHECK_VALID_SIZE(outputs.size(), 1);
4130
4131 armnn::DepthToSpaceDescriptor descriptor;
4132
Mike Kelly0d77ae12022-01-07 17:42:27 +00004133 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4134 const auto* options = operatorPtr->builtin_options.AsDepthToSpaceOptions();
Sadik Armagan26868492021-01-22 14:25:31 +00004135 auto blockSize = options->block_size;
4136 if (blockSize < 2)
4137 {
4138 throw ParseException(
4139 fmt::format("Operation has invalid block size: {} Block size should be >= 2 {}",
4140 blockSize,
4141 CHECK_LOCATION().AsString()));
4142 }
4143 descriptor.m_BlockSize = armnn::numeric_cast<uint32_t>(blockSize);
4144
4145 auto layerName = fmt::format("DepthToSpace:{}:{}", subgraphIndex, operatorIndex);
4146 IConnectableLayer* layer = m_Network->AddDepthToSpaceLayer(descriptor, layerName.c_str());
4147 ARMNN_ASSERT(layer != nullptr);
4148 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
4149 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4150
4151 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4152 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4153
4154 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4155 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4156}
4157
Kevin May7d96b162021-02-03 17:38:41 +00004158void TfLiteParserImpl::ParseSum(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004159{
Sadik Armagana2747482021-02-09 10:28:54 +00004160 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Sum);
4161}
4162
Teresa Charlin4e3e8312021-08-05 12:34:37 +01004163void TfLiteParserImpl::ParseReduceProd(size_t subgraphIndex, size_t operatorIndex)
4164{
4165 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Prod);
4166}
4167
Sadik Armagana2747482021-02-09 10:28:54 +00004168void TfLiteParserImpl::ParseReduceMax(size_t subgraphIndex, size_t operatorIndex)
4169{
4170 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Max);
4171}
4172
4173void TfLiteParserImpl::ParseReduceMin(size_t subgraphIndex, size_t operatorIndex)
4174{
4175 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Min);
4176}
4177
4178void TfLiteParserImpl::ParseReduce(size_t subgraphIndex, size_t operatorIndex, ReduceOperation reduceOperation)
4179{
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004180 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4181
Mike Kelly0d77ae12022-01-07 17:42:27 +00004182 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4183 const auto* options = operatorPtr->builtin_options.AsReducerOptions();
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004184
4185 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4186 CHECK_VALID_SIZE(inputs.size(), 2);
4187
4188 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4189 CHECK_VALID_SIZE(outputs.size(), 1);
4190
Sadik Armagana2747482021-02-09 10:28:54 +00004191 auto layerName = fmt::format("Reduce:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004192
4193 armnn::TensorInfo inputTensorInfo0 = ToTensorInfo(inputs[0]);
4194 armnn::TensorInfo inputTensorInfo1 = ToTensorInfo(inputs[1]);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004195
4196 ReduceDescriptor desc;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004197 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
4198 // Get const axis value from model and set it to descriptor.
4199 if (axisBufferPtr != nullptr)
4200 {
Sadik Armagan49bdb792021-02-11 13:57:07 +00004201 std::vector<int32_t> axisData(inputTensorInfo1.GetNumElements());
4202 ::memcpy(axisData.data(), axisBufferPtr->data.data(), inputTensorInfo1.GetNumBytes());
4203
4204 // Convert the axis to unsigned int and remove duplicates.
4205 auto rank = static_cast<int32_t>(inputTensorInfo0.GetNumDimensions());
4206 std::set<unsigned int> uniqueAxis;
4207 std::transform(axisData.begin(),
4208 axisData.end(),
4209 std::inserter(uniqueAxis, uniqueAxis.begin()),
4210 [rank](int i)->unsigned int{
4211 return static_cast<uint32_t>(((i + rank) % rank)); });
4212 desc.m_vAxis.assign(uniqueAxis.begin(), uniqueAxis.end());
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004213 }
Sadik Armagana2747482021-02-09 10:28:54 +00004214 else
4215 {
4216 for (uint32_t i = 0; i < inputTensorInfo0.GetNumDimensions(); ++i)
4217 {
4218 desc.m_vAxis.push_back(i);
4219 }
4220 }
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004221
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004222 desc.m_KeepDims = options->keep_dims;
Sadik Armagana2747482021-02-09 10:28:54 +00004223 desc.m_ReduceOperation = reduceOperation;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004224
4225 // Register a new layer object, Sum.
Mike Kelly0d77ae12022-01-07 17:42:27 +00004226 IConnectableLayer* layer = m_Network->AddReduceLayer(desc, layerName.c_str());
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00004227
4228 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
4229 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4230
4231 // Register input tensor to the layer.
4232 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4233 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4234
4235 // Register output tensor to the layer.
4236 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4237 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
4238}
4239
Mike Kelly31dce2b2021-09-01 21:22:37 +01004240void TfLiteParserImpl::ParseLocalResponseNormalization(size_t subgraphIndex, size_t operatorIndex)
4241{
4242 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4243
4244 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4245 CHECK_VALID_SIZE(inputs.size(), 1);
4246
4247 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4248 CHECK_VALID_SIZE(outputs.size(), 1);
4249
4250 auto layerName = fmt::format("LRN:{}:{}", subgraphIndex, operatorIndex);
4251 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
4252
4253 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
4254
4255 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4256 const auto* options = operatorPtr->builtin_options.AsLocalResponseNormalizationOptions();
4257
4258 armnn::NormalizationDescriptor descriptor;
4259 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
4260 descriptor.m_NormChannelType = armnn::NormalizationAlgorithmChannel::Across;
4261 descriptor.m_NormMethodType = armnn::NormalizationAlgorithmMethod::LocalBrightness;
4262 descriptor.m_NormSize = static_cast<uint32_t>(options->radius);
4263 descriptor.m_K = options->bias;
4264 descriptor.m_Alpha = options->alpha;
4265 descriptor.m_Beta = options->beta;
4266
4267 // ArmNN expects normSize to be the full size of the normalization
4268 // window rather than the radius as in TfLite.
4269 descriptor.m_NormSize = 1 + (2 * descriptor.m_NormSize);
4270
4271 IConnectableLayer* layer = m_Network->AddNormalizationLayer(descriptor, layerNameFormatted.c_str());
4272 ARMNN_ASSERT(layer != nullptr);
4273
4274 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
4275 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4276
4277 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4278 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4279
4280 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4281 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4282}
4283
Teresa Charlin28aa6692022-07-12 11:18:44 +01004284void TfLiteParserImpl::ParseAbs(size_t subgraphIndex, size_t operatorIndex)
4285{
4286 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Abs);
4287}
4288
4289void TfLiteParserImpl::ParseExp(size_t subgraphIndex, size_t operatorIndex)
4290{
4291 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Exp);
4292}
4293
4294void TfLiteParserImpl::ParseLog(size_t subgraphIndex, size_t operatorIndex)
4295{
4296 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Log);
4297}
4298
Matthew Sloyaned7fce42021-04-15 20:46:24 +01004299void TfLiteParserImpl::ParseLogicalNot(size_t subgraphIndex, size_t operatorIndex)
4300{
4301 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::LogicalNot);
4302}
4303
4304void TfLiteParserImpl::ParseNeg(size_t subgraphIndex, size_t operatorIndex)
4305{
4306 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Neg);
4307}
4308
4309void TfLiteParserImpl::ParseRsqrt(size_t subgraphIndex, size_t operatorIndex)
4310{
4311 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Rsqrt);
4312}
4313
Teresa Charlin28aa6692022-07-12 11:18:44 +01004314void TfLiteParserImpl::ParseSin(size_t subgraphIndex, size_t operatorIndex)
4315{
4316 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Sin);
4317}
4318
Teresa Charlinf0fce5b2022-05-04 17:24:43 +01004319void TfLiteParserImpl::ParseSqrt(size_t subgraphIndex, size_t operatorIndex)
4320{
4321 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Sqrt);
4322}
4323
Matthew Sloyaned7fce42021-04-15 20:46:24 +01004324void TfLiteParserImpl::ParseElementwiseUnary(size_t subgraphIndex, size_t operatorIndex, UnaryOperation unaryOperation)
4325{
4326 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4327
4328 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4329 CHECK_VALID_SIZE(inputs.size(), 1);
4330
4331 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4332 CHECK_VALID_SIZE(outputs.size(), 1);
4333
4334 std::string layerName = std::string(GetUnaryOperationAsCString(unaryOperation)) + ":{}:{}";
4335 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
4336
4337 ElementwiseUnaryDescriptor desc;
4338 desc.m_Operation = unaryOperation;
4339 IConnectableLayer* layer = m_Network->AddElementwiseUnaryLayer(desc, layerNameFormatted.c_str());
4340 ARMNN_ASSERT(layer != nullptr);
4341
4342 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
4343 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4344
4345 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4346 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4347
4348 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4349 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
4350}
4351
Bruno Goncalves2d0eb862021-07-11 14:10:15 -03004352void TfLiteParserImpl::ParseEqual(size_t subgraphIndex, size_t operatorIndex)
4353{
4354 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::Equal);
4355}
4356
4357void TfLiteParserImpl::ParseNotEqual(size_t subgraphIndex, size_t operatorIndex)
4358{
4359 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::NotEqual);
4360}
4361
4362void TfLiteParserImpl::ParseGreater(size_t subgraphIndex, size_t operatorIndex)
4363{
4364 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::Greater);
4365}
4366
4367void TfLiteParserImpl::ParseGreaterOrEqual(size_t subgraphIndex, size_t operatorIndex)
4368{
4369 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::GreaterOrEqual);
4370}
4371
4372void TfLiteParserImpl::ParseLess(size_t subgraphIndex, size_t operatorIndex)
4373{
4374 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::Less);
4375}
4376
4377void TfLiteParserImpl::ParseLessOrEqual(size_t subgraphIndex, size_t operatorIndex)
4378{
4379 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::LessOrEqual);
4380}
4381
4382void TfLiteParserImpl::ParseComparison(size_t subgraphIndex, size_t operatorIndex,
4383 ComparisonOperation comparisonOperation)
4384{
4385 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4386
4387 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
4388 CHECK_VALID_SIZE(inputs.size(), 2);
4389
4390 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
4391 CHECK_VALID_SIZE(outputs.size(), 1);
4392
4393 auto layerName = std::string(GetComparisonOperationAsCString(comparisonOperation)) + ":{}:{}";
4394 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
4395
4396 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
4397 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
4398 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerNameFormatted, "Input 0", "Input 1");
4399
4400 ComparisonDescriptor desc;
4401 desc.m_Operation = comparisonOperation;
4402 IConnectableLayer* layer = m_Network->AddComparisonLayer(desc, layerNameFormatted.c_str());
4403 ARMNN_ASSERT(layer != nullptr);
4404
4405 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
4406 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
4407
4408 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4409 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
4410
4411 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4412 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4413}
4414
Kevin May7d96b162021-02-03 17:38:41 +00004415armnn::IConnectableLayer* TfLiteParserImpl::AddFusedActivationLayer(armnn::IConnectableLayer* prevLayer,
4416 unsigned int outputSlot,
4417 tflite::ActivationFunctionType activationType)
telsoa01c577f2c2018-08-31 09:22:23 +01004418{
4419 ActivationDescriptor activationDesc;
4420 std::string layerName = prevLayer->GetName();
4421
4422 switch(activationType)
4423 {
4424 case tflite::ActivationFunctionType_NONE:
4425 {
4426 // this is a no-op: return previous layer
4427 return prevLayer;
4428 }
4429 case tflite::ActivationFunctionType_RELU:
4430 {
4431 activationDesc.m_Function = ActivationFunction::ReLu;
4432 layerName += ":RELU";
4433 break;
4434 }
4435 case tflite::ActivationFunctionType_RELU6:
4436 {
4437 activationDesc.m_Function = ActivationFunction::BoundedReLu;
4438 activationDesc.m_A = 6.0f;
4439 activationDesc.m_B = 0.0f;
4440 layerName += ":RELU6";
4441 break;
4442 }
4443 case tflite::ActivationFunctionType_TANH:
4444 {
4445 activationDesc.m_Function = ActivationFunction::TanH;
4446 activationDesc.m_A = 1.0f;
4447 activationDesc.m_B = 1.0f;
4448 layerName += ":TANH";
4449 break;
4450 }
4451
4452 // I only put these here as a reminder what others we could support
4453 case tflite::ActivationFunctionType_RELU_N1_TO_1:
4454 case tflite::ActivationFunctionType_SIGN_BIT:
4455 default:
4456 {
4457 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004458 fmt::format("TfLite parser doesn't suppport fused activation: "
4459 "{}/{} {} ",
4460 activationType,
4461 tflite::EnumNameActivationFunctionType(activationType),
4462 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004463
4464 }
4465 }
4466
4467 IConnectableLayer* activationLayer =
4468 m_Network->AddActivationLayer(activationDesc, layerName.c_str());
4469
4470 auto & prevOutputSlot = prevLayer->GetOutputSlot(outputSlot);
4471 prevOutputSlot.Connect(activationLayer->GetInputSlot(0));
4472 activationLayer->GetOutputSlot(0).SetTensorInfo(prevOutputSlot.GetTensorInfo());
4473 return activationLayer;
4474}
4475
Teresa Charlincdbd40b2022-02-25 13:21:55 +00004476armnn::IConnectableLayer* TfLiteParserImpl::AddFusedFloorLayer(armnn::IConnectableLayer* prevLayer,
4477 unsigned int outputSlot)
4478{
Teresa Charlin725728e2022-05-05 13:33:33 +01004479
4480 auto& prevOutputSlot = prevLayer->GetOutputSlot(outputSlot);
4481 DataType dataType = prevOutputSlot.GetTensorInfo().GetDataType();
4482
4483 if (dataType == DataType::Signed32)
4484 {
4485 return prevLayer;
4486 }
4487
Teresa Charlincdbd40b2022-02-25 13:21:55 +00004488 std::string layerName = prevLayer->GetName();
4489 IConnectableLayer* floorLayer = m_Network->AddFloorLayer(layerName.c_str());
4490
Teresa Charlincdbd40b2022-02-25 13:21:55 +00004491 prevOutputSlot.Connect(floorLayer->GetInputSlot(0));
4492 floorLayer->GetOutputSlot(0).SetTensorInfo(prevOutputSlot.GetTensorInfo());
Teresa Charlin725728e2022-05-05 13:33:33 +01004493
Teresa Charlincdbd40b2022-02-25 13:21:55 +00004494 return floorLayer;
4495}
4496
Mike Kelly0d77ae12022-01-07 17:42:27 +00004497TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromFile(const char* fileName)
telsoa01c577f2c2018-08-31 09:22:23 +01004498{
4499 if (fileName == nullptr)
4500 {
James Ward58dec6b2020-09-11 17:32:44 +01004501 throw InvalidArgumentException(fmt::format("Invalid (null) file name {}",
telsoa01c577f2c2018-08-31 09:22:23 +01004502 CHECK_LOCATION().AsString()));
4503 }
Francis Murtagh532a29d2020-06-29 11:50:01 +01004504 std::error_code errorCode;
4505 fs::path pathToFile(fileName);
4506 if (!fs::exists(pathToFile, errorCode))
telsoa01c577f2c2018-08-31 09:22:23 +01004507 {
James Ward58dec6b2020-09-11 17:32:44 +01004508 //fmt::format() could not be used here (format error)
4509 std::stringstream msg;
4510 msg << "Cannot find the file (" << fileName << ") errorCode: " << errorCode
4511 << " " << CHECK_LOCATION().AsString();
4512
4513 throw FileNotFoundException(msg.str());
telsoa01c577f2c2018-08-31 09:22:23 +01004514 }
4515 std::ifstream file(fileName, std::ios::binary);
4516 std::string fileContent((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
4517 return LoadModelFromBinary(reinterpret_cast<const uint8_t *>(fileContent.c_str()),
4518 fileContent.size());
4519}
4520
Mike Kelly0d77ae12022-01-07 17:42:27 +00004521TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromBinary(const uint8_t* binaryContent, size_t len)
telsoa01c577f2c2018-08-31 09:22:23 +01004522{
4523 if (binaryContent == nullptr)
4524 {
James Ward58dec6b2020-09-11 17:32:44 +01004525 throw InvalidArgumentException(fmt::format("Invalid (null) binary content {}",
telsoa01c577f2c2018-08-31 09:22:23 +01004526 CHECK_LOCATION().AsString()));
4527 }
4528 flatbuffers::Verifier verifier(binaryContent, len);
4529 if (verifier.VerifyBuffer<tflite::Model>() == false)
4530 {
4531 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004532 fmt::format("Buffer doesn't conform to the expected Tensorflow Lite "
4533 "flatbuffers format. size:{} {}",
4534 len,
4535 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004536 }
4537 return tflite::UnPackModel(binaryContent);
4538}
4539
Mike Kelly0d77ae12022-01-07 17:42:27 +00004540TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetInputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00004541 size_t subgraphIndex,
4542 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004543{
4544 CHECK_MODEL(model, subgraphIndex, operatorIndex);
4545
Mike Kelly0d77ae12022-01-07 17:42:27 +00004546 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4547 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004548
4549 size_t inputCount = operatorPtr->inputs.size();
mathad01c21025d2021-04-26 10:09:37 +01004550 TensorRawPtrVector result;
Mike Kelly0d77ae12022-01-07 17:42:27 +00004551 for (size_t i = 0; i < inputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004552 {
mathad01c21025d2021-04-26 10:09:37 +01004553 // If the input location is -1 then assume input is turned off.
4554 if (operatorPtr->inputs[i] == -1)
4555 {
4556 continue;
4557 }
4558 else
4559 {
4560 uint32_t inputId = CHECKED_NON_NEGATIVE(operatorPtr->inputs[i]);
4561 result.push_back(subgraphPtr->tensors[inputId].get());
4562 }
telsoa01c577f2c2018-08-31 09:22:23 +01004563 }
4564 return result;
4565}
4566
Mike Kelly0d77ae12022-01-07 17:42:27 +00004567TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetOutputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00004568 size_t subgraphIndex,
4569 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004570{
4571 CHECK_MODEL(model, subgraphIndex, operatorIndex);
4572
Mike Kelly0d77ae12022-01-07 17:42:27 +00004573 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4574 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004575
4576 size_t outputCount = operatorPtr->outputs.size();
4577 TensorRawPtrVector result(outputCount);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004578 for (size_t i = 0; i < outputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004579 {
4580 uint32_t outputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[i]);
4581 CHECK_TENSOR(model, subgraphIndex, outputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01004582 result[i] = subgraphPtr->tensors[outputId].get();
telsoa01c577f2c2018-08-31 09:22:23 +01004583 }
4584 return result;
4585}
4586
Mike Kelly0d77ae12022-01-07 17:42:27 +00004587TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphInputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00004588 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004589{
4590 CHECK_SUBGRAPH(model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004591 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004592
Derek Lambertiff05cc52019-04-26 13:05:17 +01004593 size_t inputCount = subgraphPtr->inputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01004594 TensorIdRawPtrVector result(inputCount);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004595 for (size_t i = 0; i < inputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004596 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01004597 uint32_t inputId = CHECKED_NON_NEGATIVE(subgraphPtr->inputs[i]);
telsoa01c577f2c2018-08-31 09:22:23 +01004598 CHECK_TENSOR(model, subgraphIndex, inputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01004599 result[i] = std::make_pair(inputId, subgraphPtr->tensors[inputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01004600 }
4601 return result;
4602}
4603
Mike Kelly0d77ae12022-01-07 17:42:27 +00004604TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphOutputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00004605 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004606{
4607 CHECK_SUBGRAPH(model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004608 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004609
Derek Lambertiff05cc52019-04-26 13:05:17 +01004610 size_t outputCount = subgraphPtr->outputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01004611 TensorIdRawPtrVector result(outputCount);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004612 for (size_t i = 0; i < outputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004613 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01004614 uint32_t outputId = CHECKED_NON_NEGATIVE(subgraphPtr->outputs[i]);
4615 result[i] = std::make_pair(outputId, subgraphPtr->tensors[outputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01004616 }
4617 return result;
4618}
4619
Kevin May7d96b162021-02-03 17:38:41 +00004620std::vector<int32_t>& TfLiteParserImpl::GetInputTensorIds(const ModelPtr& model,
4621 size_t subgraphIndex,
4622 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004623{
4624 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004625 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4626 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004627 return operatorPtr->inputs;
4628}
4629
Kevin May7d96b162021-02-03 17:38:41 +00004630std::vector<int32_t>& TfLiteParserImpl::GetOutputTensorIds(const ModelPtr& model,
4631 size_t subgraphIndex,
4632 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004633{
4634 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004635 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4636 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004637 return operatorPtr->outputs;
4638}
4639
Kevin May7d96b162021-02-03 17:38:41 +00004640void TfLiteParserImpl::RegisterInputSlots(size_t subgraphIndex,
4641 size_t operatorIndex,
4642 IConnectableLayer* layer,
Finn Williamsd4fa5452021-03-01 12:31:41 +00004643 const std::vector<unsigned int>& tensorIndexes,
4644 unsigned int startingSlotIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004645{
4646 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01004647 ARMNN_ASSERT(layer != nullptr);
Matthew Sloyan81beae32021-07-13 19:46:11 +01004648
Finn Williamsd4fa5452021-03-01 12:31:41 +00004649 if (tensorIndexes.size() + startingSlotIndex != layer->GetNumInputSlots())
telsoa01c577f2c2018-08-31 09:22:23 +01004650 {
4651 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004652 fmt::format("The number of tensor inputs ({}) does not match the number expected ({})"
4653 " for subgraph:{} operator index:{} {}",
4654 tensorIndexes.size(),
4655 layer->GetNumInputSlots(),
4656 subgraphIndex,
4657 operatorIndex,
4658 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004659 }
4660
Finn Williamsd4fa5452021-03-01 12:31:41 +00004661 for (unsigned int index = 0; index < tensorIndexes.size() ; ++index)
telsoa01c577f2c2018-08-31 09:22:23 +01004662 {
Finn Williamsd4fa5452021-03-01 12:31:41 +00004663 unsigned int tensorIndex = tensorIndexes[index];
4664 armnn::IInputSlot* slot = &(layer->GetInputSlot(startingSlotIndex + index));
telsoa01c577f2c2018-08-31 09:22:23 +01004665 RegisterConsumerOfTensor(subgraphIndex, tensorIndex, slot);
4666 }
4667}
4668
Kevin May7d96b162021-02-03 17:38:41 +00004669void TfLiteParserImpl::RegisterOutputSlots(size_t subgraphIndex,
4670 size_t operatorIndex,
4671 IConnectableLayer* layer,
4672 const std::vector<unsigned int>& tensorIndexes)
telsoa01c577f2c2018-08-31 09:22:23 +01004673{
4674 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01004675 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01004676 if (tensorIndexes.size() != layer->GetNumOutputSlots())
4677 {
4678 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004679 fmt::format("The number of tensor outputs ({}) does not match the number expected ({})"
4680 " for subgraph:{} operator index:{} {}",
4681 tensorIndexes.size(),
4682 layer->GetNumOutputSlots(),
4683 subgraphIndex,
4684 operatorIndex,
4685 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004686 }
4687
4688 for (unsigned int slotIndex = 0; slotIndex < layer->GetNumOutputSlots(); ++slotIndex)
4689 {
4690 unsigned int tensorIndex = tensorIndexes[slotIndex];
4691 armnn::IOutputSlot* slot = &(layer->GetOutputSlot(slotIndex));
4692 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
4693 }
4694}
4695
Kevin May7d96b162021-02-03 17:38:41 +00004696void TfLiteParserImpl::SetupInputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004697{
4698 CHECK_SUBGRAPH(m_Model, subgraphIndex);
4699
4700 auto inputs = GetSubgraphInputs(m_Model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004701 for (auto const& tensorIdAndPtr : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004702 {
4703 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
4704 IConnectableLayer* layer =
4705 m_Network->AddInputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
4706
4707 auto tensorInfo = ToTensorInfo(tensorIdAndPtr.second);
4708 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
4709
4710 RegisterOutputSlots(subgraphIndex,
4711 VIRTUAL_OPERATOR_ID,
4712 layer,
4713 { static_cast<uint32_t>(tensorIdAndPtr.first) });
4714 }
4715}
4716
Kevin May7d96b162021-02-03 17:38:41 +00004717void TfLiteParserImpl::SetupOutputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004718{
4719 CHECK_SUBGRAPH(m_Model, subgraphIndex);
4720
4721 auto outputs = GetSubgraphOutputs(m_Model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004722 for (auto const& tensorIdAndPtr : outputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004723 {
4724 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
4725 IConnectableLayer* layer =
4726 m_Network->AddOutputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
4727
4728 RegisterInputSlots(subgraphIndex,
4729 VIRTUAL_OPERATOR_ID,
4730 layer,
4731 { static_cast<uint32_t>(tensorIdAndPtr.first) });
4732 }
4733}
4734
Mike Kelly5880b912022-01-28 16:18:54 +00004735void TfLiteParserImpl::SetupConstantLayers(size_t subgraph)
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004736{
Mike Kelly5880b912022-01-28 16:18:54 +00004737 CHECK_SUBGRAPH(m_Model, subgraph);
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004738
Mike Kelly5880b912022-01-28 16:18:54 +00004739 const auto & subgraphPtr = m_Model->subgraphs[subgraph];
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004740 for (unsigned int subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
4741 {
4742 for (unsigned int tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
4743 {
4744 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot == nullptr &&
4745 m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size() > 0)
4746 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01004747 TensorRawPtr tensorPtr = subgraphPtr->tensors[tensorIndex].get();
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004748
Mike Kelly5880b912022-01-28 16:18:54 +00004749 if (IsConstTensor(tensorPtr))
Matthew Sloyan81beae32021-07-13 19:46:11 +01004750 {
4751 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
Mike Kelly5880b912022-01-28 16:18:54 +00004752 armnn::DataType dataType = tensorInfo.GetDataType();
4753
4754 if (std::find(m_ConstantsToDequantize.begin(), m_ConstantsToDequantize.end(), tensorPtr->buffer)
4755 != m_ConstantsToDequantize.end())
4756 {
4757 dataType = DataType::Float32;
4758 }
4759 auto tensorAndData = CreateConstTensorNonPermuted(tensorPtr, tensorInfo, dataType);
4760
4761 std::string layerName = fmt::format("Constant:{}", tensorPtr->name);
4762 IConnectableLayer *layer = m_Network->AddConstantLayer(tensorAndData.first, layerName.c_str());
4763
4764 layer->GetOutputSlot(0).SetTensorInfo(tensorAndData.first.GetInfo());
4765 RegisterOutputSlots(subgraphIndex,
4766 VIRTUAL_OPERATOR_ID,
4767 layer,
4768 { tensorIndex });
4769 }
4770 else if (ShouldConstantTensorBeCreated(tensorIndex))
4771 {
4772 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
4773 armnn::DataType dataType = tensorInfo.GetDataType();
4774
4775 if (std::find(m_ConstantsToDequantize.begin(), m_ConstantsToDequantize.end(), tensorPtr->buffer)
4776 != m_ConstantsToDequantize.end())
4777 {
4778 dataType = DataType::Float32;
4779 }
4780 // Make sure isConstant flag is set.
4781 tensorInfo.SetConstant();
4782 tensorInfo.SetDataType(dataType);
4783
4784 auto tensorAndData = ConstTensor(tensorInfo, std::vector<uint8_t>(tensorInfo.GetNumBytes()));
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004785
Matthew Sloyan81beae32021-07-13 19:46:11 +01004786 std::string layerName = fmt::format("Constant:{}", tensorPtr->name);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004787 IConnectableLayer* layer = m_Network->AddConstantLayer(tensorAndData, layerName.c_str());
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004788
Matthew Sloyan81beae32021-07-13 19:46:11 +01004789 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
4790 RegisterOutputSlots(subgraphIndex,
4791 VIRTUAL_OPERATOR_ID,
4792 layer,
Mike Kelly5880b912022-01-28 16:18:54 +00004793 {tensorIndex});
Matthew Sloyan81beae32021-07-13 19:46:11 +01004794 }
4795 else
4796 {
4797 throw ParseException(
4798 fmt::format("Invalid Tensor: Tensor should be constant. {}",
4799 CHECK_LOCATION().AsString()));
4800 }
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004801 }
4802 }
4803 }
4804}
4805
telsoa01c577f2c2018-08-31 09:22:23 +01004806// example usage: BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Kevin May7d96b162021-02-03 17:38:41 +00004807TfLiteParserImpl::BufferRawPtr TfLiteParserImpl::GetBuffer(const ModelPtr& model, size_t bufferIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004808{
4809 CHECK_BUFFER(model, bufferIndex);
4810 return model->buffers[bufferIndex].get();
4811}
4812
Matteo Martincigh747ef822018-12-18 09:26:39 +00004813template<typename T>
Kevin May7d96b162021-02-03 17:38:41 +00004814std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
4815TfLiteParserImpl::CreateConstTensorAndStoreData(TfLiteParserImpl::BufferRawPtr bufferPtr,
4816 TfLiteParserImpl::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +00004817 armnn::TensorInfo& tensorInfo,
4818 armnn::Optional<armnn::PermutationVector&> permutationVector)
4819{
Matthew Sloyan81beae32021-07-13 19:46:11 +01004820 // Make sure isConstant flag is set.
4821 tensorInfo.SetConstant();
4822
Matteo Martincigh747ef822018-12-18 09:26:39 +00004823 auto constData = CreateConstTensorImpl<T>(bufferPtr,
4824 tensorPtr,
4825 tensorInfo,
4826 permutationVector);
Kevin May7d96b162021-02-03 17:38:41 +00004827 TfLiteParserImpl::SupportedDataStorage storage(std::move(constData.second));
Matteo Martincigh747ef822018-12-18 09:26:39 +00004828 return std::make_pair(constData.first, std::move(storage));
4829}
4830
Mike Kelly5880b912022-01-28 16:18:54 +00004831bool TfLiteParserImpl::ShouldConstantTensorBeCreated(unsigned int tensorIndex)
4832{
4833 // If the TensorIndex appears in the list of ConstantsToBeCreated then return true
4834 return (std::find(m_ConstantsToBeCreated.begin(), m_ConstantsToBeCreated.end(), tensorIndex)
4835 != m_ConstantsToBeCreated.end());
4836}
4837
Finn Williamsd4fa5452021-03-01 12:31:41 +00004838bool TfLiteParserImpl::IsConstTensor(TensorRawPtr tensorPtr)
4839{
4840 CHECK_TENSOR_PTR(tensorPtr);
mathad01bf7edb62021-04-20 16:12:45 +01004841 bool isConst = true;
4842
4843 auto buffer = GetBuffer(m_Model, tensorPtr->buffer);
4844 if (buffer->data.size() == 0)
4845 {
4846 isConst = false;
4847 }
4848
4849 return isConst;
Finn Williamsd4fa5452021-03-01 12:31:41 +00004850}
4851
Kevin May7d96b162021-02-03 17:38:41 +00004852std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
Finn Williamsd4fa5452021-03-01 12:31:41 +00004853TfLiteParserImpl::CreateConstTensorPermuted(TensorRawPtr tensorPtr,
4854 armnn::TensorInfo& tensorInfo,
4855 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +01004856{
4857 CHECK_TENSOR_PTR(tensorPtr);
4858 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
4859 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
4860
Matthew Sloyan81beae32021-07-13 19:46:11 +01004861 // Make sure isConstant flag is set.
4862 tensorInfo.SetConstant();
4863
telsoa01c577f2c2018-08-31 09:22:23 +01004864 switch (tensorInfo.GetDataType())
4865 {
4866 case armnn::DataType::Float32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00004867 return CreateConstTensorAndStoreData<float>(bufferPtr,
4868 tensorPtr,
4869 tensorInfo,
4870 permutationVector);
Derek Lambertif90c56d2020-01-10 17:14:08 +00004871 case armnn::DataType::QAsymmU8:
Matteo Martincigh747ef822018-12-18 09:26:39 +00004872 return CreateConstTensorAndStoreData<uint8_t>(bufferPtr,
4873 tensorPtr,
4874 tensorInfo,
4875 permutationVector);
Keith Davisd305e1a2020-01-22 11:57:54 +00004876 case armnn::DataType::QSymmS8:
4877 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
4878 tensorPtr,
4879 tensorInfo,
4880 permutationVector);
Keith Davis67e6c542020-02-19 10:08:33 +00004881 case armnn::DataType::QAsymmS8:
4882 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
4883 tensorPtr,
4884 tensorInfo,
4885 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01004886 case armnn::DataType::Signed32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00004887 return CreateConstTensorAndStoreData<int32_t>(bufferPtr,
4888 tensorPtr,
4889 tensorInfo,
4890 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01004891 default:
4892 {
4893 std::stringstream errString;
4894 errString << "Unexpected datatype when creating const tensor: "
4895 << armnn::GetDataTypeName(tensorInfo.GetDataType())
4896 << " shape:" << tensorInfo.GetShape()
4897 << CHECK_LOCATION().AsString();
4898 throw ParseException(errString.str());
4899 }
4900 }
4901}
4902
Finn Williamsd4fa5452021-03-01 12:31:41 +00004903armnn::ConstTensor TfLiteParserImpl::CreateConstTensorNonPermuted(TensorRawPtr tensorPtr,
4904 armnn::TensorInfo& tensorInfo)
4905{
4906 CHECK_TENSOR_PTR(tensorPtr);
4907 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
4908 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
4909
Matthew Sloyan81beae32021-07-13 19:46:11 +01004910 // Make sure isConstant flag is set.
4911 tensorInfo.SetConstant();
4912
Finn Williamsd4fa5452021-03-01 12:31:41 +00004913 return ConstTensor(tensorInfo, bufferPtr->data.data());
4914}
4915
Mike Kelly5880b912022-01-28 16:18:54 +00004916std::pair<armnn::ConstTensor, std::unique_ptr<float[]>>
4917TfLiteParserImpl::CreateConstTensorNonPermuted(TensorRawPtr tensorPtr,
4918 armnn::TensorInfo& tensorInfo,
4919 armnn::DataType inputDataType)
4920{
4921 CHECK_TENSOR_PTR(tensorPtr);
4922 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
4923 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
4924
4925 // Make sure isConstant flag is set.
4926 tensorInfo.SetConstant();
4927
4928 if (inputDataType == DataType::Float32 && tensorInfo.GetDataType() != DataType::Float32)
4929 {
4930 TensorInfo constTensorInfo(tensorInfo.GetShape(), DataType::Float32, 0.0f, 0, true);
4931 std::unique_ptr<float[]> data = AsFloatArray(bufferPtr, tensorInfo);
4932 return std::make_pair(ConstTensor(constTensorInfo, data.get()), std::move(data));
4933 }
4934 else
4935 {
4936 return std::make_pair(ConstTensor(tensorInfo, bufferPtr->data.data()), std::unique_ptr<float[]>());
4937 }
4938}
4939
4940std::pair<armnn::ConstTensor*, std::unique_ptr<float[]>>
4941TfLiteParserImpl::CreateConstTensorPtr(TensorRawPtr tensorPtr, armnn::TensorInfo& inputTensorInfo)
4942{
4943 CHECK_TENSOR_PTR(tensorPtr);
4944 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
4945 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
4946 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
4947
4948 // Make sure isConstant flag is set.
4949 tensorInfo.SetConstant();
4950
4951 if (inputTensorInfo.GetDataType() == DataType::Float32 && tensorInfo.GetDataType() != DataType::Float32)
4952 {
4953 TensorInfo constTensorInfo(tensorInfo.GetShape(), DataType::Float32, 0.0f, 0, true);
4954 std::unique_ptr<float[]> data = AsFloatArray(bufferPtr, tensorInfo);
4955 return std::make_pair(new ConstTensor(constTensorInfo, data.get()), std::move(data));
4956 }
4957 else
4958 {
4959 return std::make_pair(new ConstTensor(tensorInfo, bufferPtr->data.data()), std::unique_ptr<float[]>());
4960 }
4961}
4962
Kevin May7d96b162021-02-03 17:38:41 +00004963BindingPointInfo TfLiteParserImpl::GetNetworkInputBindingInfo(size_t subgraphId,
4964 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01004965{
4966 CHECK_SUBGRAPH(m_Model, subgraphId);
4967 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004968 for (auto const& input : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004969 {
4970 if (input.second->name == name)
4971 {
4972 auto bindingId = GenerateLayerBindingId(subgraphId, input.first);
Colm Donelan4bc993b2021-11-09 20:39:10 +00004973 auto inputTensorInfo = ToTensorInfo(input.second);
4974 // Input tensors are always treated as constant tensors during network execution.
4975 inputTensorInfo.SetConstant(true);
4976 return std::make_pair(bindingId, inputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01004977 }
4978 }
4979
4980 std::stringstream bindings;
Mike Kelly0d77ae12022-01-07 17:42:27 +00004981 for (auto const& input : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004982 {
4983 bindings << "'" << input.second->name << "' ";
4984 }
4985
4986 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004987 fmt::format("No input binding found for subgraph:{} and name:{}. "
4988 "Possible inputs are: [{}] {}",
4989 subgraphId,
4990 name,
4991 bindings.str(),
4992 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004993}
4994
Kevin May7d96b162021-02-03 17:38:41 +00004995BindingPointInfo TfLiteParserImpl::GetNetworkOutputBindingInfo(size_t subgraphId,
4996 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01004997{
4998 CHECK_SUBGRAPH(m_Model, subgraphId);
4999 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00005000 for (unsigned int i = 0; i < outputs.size(); ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01005001 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00005002 auto const output = outputs[i];
telsoa01c577f2c2018-08-31 09:22:23 +01005003 if (output.second->name == name)
5004 {
5005 auto bindingId = GenerateLayerBindingId(subgraphId, output.first);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00005006 std::vector<unsigned int> shape = m_OverridenOutputShapes.size() > 0 ?
5007 m_OverridenOutputShapes[i] : AsUnsignedVector(output.second->shape);
5008 return std::make_pair(bindingId, ToTensorInfo(output.second, shape));
telsoa01c577f2c2018-08-31 09:22:23 +01005009 }
5010 }
5011
5012 std::stringstream bindings;
Mike Kelly0d77ae12022-01-07 17:42:27 +00005013 for (auto const& output : outputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005014 {
5015 bindings << "'" << output.second->name << "' ";
5016 }
5017
5018 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01005019 fmt::format("No output binding found for subgraph:{} and name:{}. "
5020 "Possible outputs are: [{}] {}",
5021 subgraphId,
5022 name,
5023 bindings.str(),
5024 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01005025}
5026
Kevin May7d96b162021-02-03 17:38:41 +00005027size_t TfLiteParserImpl::GetSubgraphCount() const
telsoa01c577f2c2018-08-31 09:22:23 +01005028{
5029 return m_Model->subgraphs.size();
5030}
5031
Kevin May7d96b162021-02-03 17:38:41 +00005032std::vector<std::string> TfLiteParserImpl::GetSubgraphInputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01005033{
5034 CHECK_SUBGRAPH(m_Model, subgraphId);
5035 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
5036 std::vector<std::string> result;
5037 result.reserve(inputs.size());
Mike Kelly0d77ae12022-01-07 17:42:27 +00005038 for (auto const& input : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005039 {
5040 result.push_back(input.second->name);
5041 }
5042 return result;
5043}
5044
Kevin May7d96b162021-02-03 17:38:41 +00005045std::vector<std::string> TfLiteParserImpl::GetSubgraphOutputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01005046{
5047 CHECK_SUBGRAPH(m_Model, subgraphId);
5048 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
5049 std::vector<std::string> result;
5050 result.reserve(outputs.size());
Mike Kelly0d77ae12022-01-07 17:42:27 +00005051 for (auto const& output : outputs)
telsoa01c577f2c2018-08-31 09:22:23 +01005052 {
5053 result.push_back(output.second->name);
5054 }
5055 return result;
5056}
5057
Matthew Sloyanac001ee2021-02-03 10:43:04 +00005058const std::string TfLiteParserImpl::GetVersion()
5059{
5060 return TFLITE_PARSER_VERSION;
5061}
5062
Mike Kelly0d77ae12022-01-07 17:42:27 +00005063TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<float[]>&& data)
telsoa01c577f2c2018-08-31 09:22:23 +01005064: m_FloatData(std::move(data))
5065, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00005066, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01005067, m_Int32Data(nullptr)
5068{
5069}
5070
Mike Kelly0d77ae12022-01-07 17:42:27 +00005071TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<uint8_t[]>&& data)
telsoa01c577f2c2018-08-31 09:22:23 +01005072: m_FloatData(nullptr)
5073, m_Uint8Data(std::move(data))
Keith Davisd305e1a2020-01-22 11:57:54 +00005074, m_Int8Data(nullptr)
5075, m_Int32Data(nullptr)
5076{
5077}
5078
Mike Kelly0d77ae12022-01-07 17:42:27 +00005079TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int8_t[]>&& data)
Keith Davisd305e1a2020-01-22 11:57:54 +00005080: m_FloatData(nullptr)
5081, m_Uint8Data(nullptr)
5082, m_Int8Data(std::move(data))
telsoa01c577f2c2018-08-31 09:22:23 +01005083, m_Int32Data(nullptr)
5084{
5085}
5086
Mike Kelly0d77ae12022-01-07 17:42:27 +00005087TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int32_t[]>&& data)
telsoa01c577f2c2018-08-31 09:22:23 +01005088: m_FloatData(nullptr)
5089, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00005090, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01005091, m_Int32Data(std::move(data))
5092{
5093}
5094
5095} // armnnTfLiteParser