blob: 81cbb9c8c0083136f896af2b5723c0aa5172ce21 [file] [log] [blame]
telsoa01c577f2c2018-08-31 09:22:23 +01001//
Mike Kellyc5789ca2020-07-06 19:24:15 +01002// Copyright © 2017 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"
9
Sadik Armagand109a4d2020-07-28 10:42:13 +010010#include <armnn/BackendOptions.hpp>
Matthew Bentham39ef3e52020-01-20 10:09:09 +000011#include <armnn/Descriptors.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010012#include <armnn/Exceptions.hpp>
Derek Lamberti08446972019-11-26 16:38:31 +000013#include <armnn/Logging.hpp>
James Conroy05102392020-06-24 15:39:55 +010014#include <armnn/Tensor.hpp>
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +000015#include <armnnUtils/TensorUtils.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010016#include <armnn/TypesUtils.hpp>
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +010017#include <armnn/utility/Assert.hpp>
Jan Eilers8eb25602020-03-09 12:13:48 +000018#include <armnn/utility/IgnoreUnused.hpp>
Derek Lambertif0176992020-04-28 13:37:49 +010019#include <armnn/utility/NumericCast.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010020
21// armnnUtils:
Matteo Martincighe011d202019-11-28 11:35:47 +000022#include <armnnUtils/Permute.hpp>
Rob Hughes9542f902021-07-14 09:48:54 +010023#include <armnnUtils/Filesystem.hpp>
Matteo Martincighe011d202019-11-28 11:35:47 +000024
Sadik Armagan479045b2018-10-01 11:51:37 +010025#include <ParserHelper.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010026#include <VerificationHelpers.hpp>
27
28// The generated code based on the Tf Lite schema:
29#include <schema_generated.h>
30
Matteo Martincighe011d202019-11-28 11:35:47 +000031#include <flatbuffers/flexbuffers.h>
32
James Ward58dec6b2020-09-11 17:32:44 +010033#include <fmt/format.h>
telsoa01c577f2c2018-08-31 09:22:23 +010034
telsoa01c577f2c2018-08-31 09:22:23 +010035#include <algorithm>
Matthew Sloyanac001ee2021-02-03 10:43:04 +000036#include <fstream>
37#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#include <sstream>
41
42#define ARMNN_THROW_PARSE_EXCEPTION(msg) \
43 { \
44 throw armnn::ParseException( static_cast<const std::stringstream&>( std::stringstream() << msg \
45 << ": " \
46 << CHECK_LOCATION().AsString()).str()); \
47 }
telsoa01c577f2c2018-08-31 09:22:23 +010048
49using namespace armnn;
50using armnn::CheckLocation;
51namespace armnnTfLiteParser
52{
Kevin May7d96b162021-02-03 17:38:41 +000053
54ITfLiteParser::ITfLiteParser(const armnn::Optional<TfLiteParserOptions>& options) :
55 pTfLiteParserImpl(new TfLiteParserImpl(options)) {}
56
57ITfLiteParser::~ITfLiteParser() = default;
58
59ITfLiteParser* ITfLiteParser::CreateRaw(const armnn::Optional<TfLiteParserOptions>& options)
60{
61 return new ITfLiteParser(options);
62}
63
64ITfLiteParserPtr ITfLiteParser::Create(const armnn::Optional<TfLiteParserOptions>& options)
65{
66 return ITfLiteParserPtr(CreateRaw(options), &ITfLiteParser::Destroy);
67}
68
69void ITfLiteParser::Destroy(ITfLiteParser* parser)
70{
71 delete parser;
72}
73
74armnn::INetworkPtr ITfLiteParser::CreateNetworkFromBinaryFile(const char* graphFile)
75{
76 return pTfLiteParserImpl->CreateNetworkFromBinaryFile(graphFile);
77}
78
Mike Kelly0d77ae12022-01-07 17:42:27 +000079armnn::INetworkPtr ITfLiteParser::CreateNetworkFromBinary(const std::vector<uint8_t>& binaryContent)
Kevin May7d96b162021-02-03 17:38:41 +000080{
81 return pTfLiteParserImpl->CreateNetworkFromBinary(binaryContent);
82}
83
84BindingPointInfo ITfLiteParser::GetNetworkInputBindingInfo(size_t subgraphId,
85 const std::string& name) const
86{
87 return pTfLiteParserImpl->GetNetworkInputBindingInfo(subgraphId, name);
88}
89
90BindingPointInfo ITfLiteParser::GetNetworkOutputBindingInfo(size_t subgraphId,
91 const std::string& name) const
92{
93 return pTfLiteParserImpl->GetNetworkOutputBindingInfo(subgraphId, name);
94}
95
96size_t ITfLiteParser::GetSubgraphCount() const
97{
98 return pTfLiteParserImpl->GetSubgraphCount();
99}
100
101std::vector<std::string> ITfLiteParser::GetSubgraphInputTensorNames(size_t subgraphId) const
102{
103 return pTfLiteParserImpl->GetSubgraphInputTensorNames(subgraphId);
104}
105
106std::vector<std::string> ITfLiteParser::GetSubgraphOutputTensorNames(size_t subgraphId) const
107{
108 return pTfLiteParserImpl->GetSubgraphOutputTensorNames(subgraphId);
109}
110
telsoa01c577f2c2018-08-31 09:22:23 +0100111namespace
112{
jimfly01c25411c2018-11-14 17:47:22 +0000113
telsoa01c577f2c2018-08-31 09:22:23 +0100114const uint32_t VIRTUAL_OPERATOR_ID = std::numeric_limits<uint32_t>::max();
115
Mike Kelly0d77ae12022-01-07 17:42:27 +0000116void CheckSubgraph(const TfLiteParserImpl::ModelPtr& model,
telsoa01c577f2c2018-08-31 09:22:23 +0100117 size_t subgraphIndex,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000118 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100119{
120 if (model.get() == nullptr)
121 {
122 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100123 fmt::format("{} was called with invalid (null) model. "
124 "Possible reason is that the model is not yet loaded and Unpack(ed). "
125 "subgraph:{} at {}",
126 location.m_Function,
127 subgraphIndex,
128 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100129 }
130 else if (subgraphIndex >= model->subgraphs.size())
131 {
132 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100133 fmt::format("{} was called with an invalid subgraph index. "
134 "subgraph:{} at {}",
135 location.m_Function,
136 subgraphIndex,
137 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100138 }
139}
140
141#define CHECK_SUBGRAPH(MODEL, SUBGRAPH_INDEX) \
142 CheckSubgraph(MODEL, SUBGRAPH_INDEX, CHECK_LOCATION())
143
Mike Kelly0d77ae12022-01-07 17:42:27 +0000144void CheckModel(const TfLiteParserImpl::ModelPtr& model,
telsoa01c577f2c2018-08-31 09:22:23 +0100145 size_t subgraphIndex,
146 size_t operatorIndex,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000147 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100148{
149 if (model.get() == nullptr)
150 {
151 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100152 fmt::format("{} was called with invalid (null) model. "
153 "Possible reason is that the model is not yet loaded and Unpack(ed). "
154 "subgraph:{} operator:{} at {}",
155 location.m_Function,
156 subgraphIndex,
157 operatorIndex,
158 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100159 }
160 else if (subgraphIndex >= model->subgraphs.size())
161 {
162 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100163 fmt::format("{} was called with an invalid subgraph index. "
164 "subgraph:{} operator:{} at {}",
165 location.m_Function,
166 subgraphIndex,
167 operatorIndex,
168 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100169 }
170 else if (operatorIndex >= model->subgraphs[subgraphIndex]->operators.size() &&
171 operatorIndex != VIRTUAL_OPERATOR_ID)
172 {
173 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100174 fmt::format("{} was called with an invalid operator index. "
175 "subgraph:{} operator:{} at {}",
176 location.m_Function,
177 subgraphIndex,
178 operatorIndex,
179 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100180 }
181}
182
183#define CHECK_MODEL(MODEL, SUBGRAPH_INDEX, OPERATOR_INDEX) \
184 CheckModel(MODEL, SUBGRAPH_INDEX, OPERATOR_INDEX, CHECK_LOCATION())
185
Mike Kelly0d77ae12022-01-07 17:42:27 +0000186void CheckTensor(const TfLiteParserImpl::ModelPtr& model,
telsoa01c577f2c2018-08-31 09:22:23 +0100187 size_t subgraphIndex,
188 size_t tensorIndex,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000189 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100190{
191 // not checking model, because I assume CHECK_MODEL already run
192 // and checked that. An assert would do.
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100193 ARMNN_ASSERT_MSG(model.get() != nullptr, "Expecting a valid model in this function");
telsoa01c577f2c2018-08-31 09:22:23 +0100194
195 // also subgraph index should be checked by CHECK_MODEL so
196 // I only add an assert here
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100197 ARMNN_ASSERT_MSG(subgraphIndex < model->subgraphs.size(), "Expecting a valid subgraph index");
telsoa01c577f2c2018-08-31 09:22:23 +0100198
199 // the tensor index is the only one to check here
200 if (tensorIndex >= model->subgraphs[subgraphIndex]->tensors.size())
201 {
202 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100203 fmt::format("{} was called with an invalid tensor index. "
204 "subgraph:{} tensor:{} at {}",
205 location.m_Function,
206 subgraphIndex,
207 tensorIndex,
208 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100209 }
210}
211
212#define CHECK_TENSOR(MODEL, SUBGRAPH_INDEX, TENSOR_INDEX) \
213 CheckTensor(MODEL, SUBGRAPH_INDEX, TENSOR_INDEX, CHECK_LOCATION())
214
Kevin May7d96b162021-02-03 17:38:41 +0000215void CheckTensorPtr(TfLiteParserImpl::TensorRawPtr rawPtr,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000216 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100217{
218 if (rawPtr == nullptr)
219 {
220 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100221 fmt::format("{} was called with a null tensor pointer at {}", location.m_Function, location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100222 }
223}
224
225#define CHECK_TENSOR_PTR(TENSOR_PTR) \
226 CheckTensorPtr(TENSOR_PTR, CHECK_LOCATION())
227
Mike Kelly0d77ae12022-01-07 17:42:27 +0000228void CheckBuffer(const TfLiteParserImpl::ModelPtr& model,
telsoa01c577f2c2018-08-31 09:22:23 +0100229 size_t bufferIndex,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000230 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100231{
232 if (model.get() == nullptr)
233 {
234 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100235 fmt::format("{} was called with invalid (null) model. "
236 "Possible reason is that the model is not yet loaded and Unpack(ed). "
237 "buffer:{} at {}",
238 location.m_Function,
239 bufferIndex,
240 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100241 }
242 else if (bufferIndex >= model->buffers.size())
243 {
244 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100245 fmt::format("{} was called with an invalid buffer index. "
246 "buffer index:{} at {}",
247 location.m_Function,
248 bufferIndex,
249 location.FileLine()));
telsoa01c577f2c2018-08-31 09:22:23 +0100250 }
251 else if (model->buffers[bufferIndex].get() == nullptr)
252 {
253 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100254 fmt::format("The buffer #{} is null. {}",
255 bufferIndex,
256 location.AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100257 }
258}
259
260#define CHECK_BUFFER(MODEL, BUFFER_INDEX) \
261 CheckBuffer(MODEL, BUFFER_INDEX, CHECK_LOCATION())
262
Kevin May7d96b162021-02-03 17:38:41 +0000263void CheckBufferSize(TfLiteParserImpl::BufferRawPtr bufferPtr,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000264 const armnn::TensorInfo& tensorInfo,
telsoa01c577f2c2018-08-31 09:22:23 +0100265 uint32_t bufferId,
Mike Kelly0d77ae12022-01-07 17:42:27 +0000266 const CheckLocation& location)
telsoa01c577f2c2018-08-31 09:22:23 +0100267{
268 if (bufferPtr == nullptr)
269 {
270 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100271 fmt::format("BufferPtr is null for buffer:{}. {}",
272 bufferId,
273 location.AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100274 }
275 else if(tensorInfo.GetNumElements() > bufferPtr->data.size() ||
276 tensorInfo.GetNumBytes() > bufferPtr->data.size())
277 {
278 std::stringstream ss;
279 ss << "Buffer #" << bufferId << " has " << bufferPtr->data.size() << " bytes. "
280 << "For tensor: " << tensorInfo.GetShape()
281 << " expecting: " << tensorInfo.GetNumBytes() << " bytes and "
282 << tensorInfo.GetNumElements() << " elements. " << location.AsString();
283 throw ParseException(ss.str());
284 }
285}
286
Mike Kelly0d77ae12022-01-07 17:42:27 +0000287
288tflite::BuiltinOperator GetOpCode(const TfLiteParserImpl::ModelPtr& model, size_t subgraphIndex, size_t operatorIndex)
289{
290 const auto& operatorPtr = model->subgraphs[subgraphIndex]->operators[operatorIndex];
291 auto opcodeIndex = operatorPtr->opcode_index;
292
293// work around the introduction of the deprecated_builtin_code introduced in 2.4 in a backwards compatible manner
294#if defined(ARMNN_POST_TFLITE_2_3)
295 auto opcode = std::max(model->operator_codes[opcodeIndex]->builtin_code,
296 static_cast<tflite::BuiltinOperator>(model->operator_codes[opcodeIndex]->deprecated_builtin_code));
297#else
298 auto opcode = model->operator_codes[opcodeIndex]->builtin_code;
299#endif
300 return opcode;
301}
302
303std::vector<unsigned int> GetUIntBuffer(armnn::TensorInfo info,
304 const TfLiteParserImpl::ModelPtr& model,
305 size_t bufferIndex)
306{
307 TfLiteParserImpl::BufferRawPtr bufferPtr = TfLiteParserImpl::GetBuffer(model, bufferIndex);
308 std::vector<unsigned int> buffer(info.GetNumElements());
309
310 if (info.GetDataType() == DataType::Signed32)
311 {
312 ::memcpy(buffer.data(), bufferPtr->data.data(), bufferPtr->data.size());
313 }
314 else if (info.GetDataType() == DataType::Signed64)
315 {
316 std::vector<uint64_t> uint64Buffer(info.GetNumElements());
317 ::memcpy(uint64Buffer.data(), bufferPtr->data.data(), bufferPtr->data.size());
318 buffer.assign(std::begin(uint64Buffer), std::end(uint64Buffer));
319 }
320 return buffer;
321}
322
telsoa01c577f2c2018-08-31 09:22:23 +0100323#define CHECK_BUFFER_SIZE(BUFFER_PTR, TENSOR_INFO, BUFFER_ID) \
324 CheckBufferSize(BUFFER_PTR, TENSOR_INFO, BUFFER_ID, CHECK_LOCATION())
325
326bool IsActivationSupported(tflite::ActivationFunctionType activationType)
327{
328 switch(activationType)
329 {
330 case tflite::ActivationFunctionType_NONE:
331 case tflite::ActivationFunctionType_RELU:
332 case tflite::ActivationFunctionType_RELU6:
333 case tflite::ActivationFunctionType_TANH:
334 {
335 return true;
336 }
337 default:
338 {
339 return false;
340 }
341 }
342}
343
344#define CHECK_SUPPORTED_FUSED_ACTIVATION(OPTION, SUBGRAPH_INDEX, OPERATOR_INDEX) \
345 do { \
346 if (IsActivationSupported(OPTION->fused_activation_function) == false) \
347 { \
348 throw ParseException( \
James Ward58dec6b2020-09-11 17:32:44 +0100349 fmt::format("TfLite parser doesn't suppport fused activation: " \
350 "{}/{} in {} subgraph:{} operator:{} at {}", \
351 OPTION->fused_activation_function, \
352 tflite::EnumNameActivationFunctionType(\
353 OPTION->fused_activation_function), \
354 __func__, \
355 SUBGRAPH_INDEX, \
356 OPERATOR_INDEX, \
357 CHECK_LOCATION().FileLine())); \
telsoa01c577f2c2018-08-31 09:22:23 +0100358 } \
359 } while(false)
360
361
Mike Kelly0d77ae12022-01-07 17:42:27 +0000362std::vector<unsigned int> AsUnsignedVector(const std::vector<int32_t>& in)
telsoa01c577f2c2018-08-31 09:22:23 +0100363{
364 std::vector<unsigned int> result;
365 result.reserve(in.size());
Mike Kelly0d77ae12022-01-07 17:42:27 +0000366 for (auto& i : in)
telsoa01c577f2c2018-08-31 09:22:23 +0100367 {
mathad01c21025d2021-04-26 10:09:37 +0100368 // If the location of the input data is -1 then the input should be ignored.
369 if (i == -1)
370 {
371 continue;
372 }
telsoa01c577f2c2018-08-31 09:22:23 +0100373 result.push_back(CHECKED_NON_NEGATIVE(i));
374 }
375 return result;
376}
377
378void CalcPadding(uint32_t inputSize,
379 uint32_t filterSize,
380 uint32_t stride,
Pablo Tellof0bd6832019-04-26 17:58:13 +0100381 uint32_t dilation,
telsoa01c577f2c2018-08-31 09:22:23 +0100382 uint32_t& paddingFront,
383 uint32_t& paddingBack,
384 tflite::Padding padding)
385{
386 paddingFront = 0;
387 paddingBack = 0;
388 if (padding == tflite::Padding_SAME)
389 {
390 uint32_t outputSize = (inputSize + stride - 1) / stride;
Pablo Tellof0bd6832019-04-26 17:58:13 +0100391 uint32_t dilatedSize = filterSize + (dilation - 1) * (filterSize - 1);
392 uint32_t temp = (outputSize - 1) * stride + dilatedSize;
telsoa01c577f2c2018-08-31 09:22:23 +0100393 if (temp > inputSize)
394 {
395 paddingFront = (temp - inputSize) / 2;
396 paddingBack = (temp - inputSize) - paddingFront;
397 }
398 }
399}
400
Kevin May7d96b162021-02-03 17:38:41 +0000401armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr,
Finn Williamsb49ed182021-06-29 15:50:08 +0100402 const std::vector<unsigned int>& shape,
Sadik Armagand109a4d2020-07-28 10:42:13 +0100403 const bool outputTensor = false)
telsoa01c577f2c2018-08-31 09:22:23 +0100404{
405 armnn::DataType type;
406 CHECK_TENSOR_PTR(tensorPtr);
407
408 switch (tensorPtr->type)
409 {
410 case tflite::TensorType_UINT8:
Derek Lambertif90c56d2020-01-10 17:14:08 +0000411 type = armnn::DataType::QAsymmU8;
telsoa01c577f2c2018-08-31 09:22:23 +0100412 break;
413 case tflite::TensorType_FLOAT32:
414 type = armnn::DataType::Float32;
415 break;
Finn Williamsed66d142019-12-06 09:55:55 +0000416 case tflite::TensorType_INT8:
Keith Davis67e6c542020-02-19 10:08:33 +0000417 if (tensorPtr->quantization->zero_point.size() == 1)
Ryan OShea03181ff2020-02-07 17:22:22 +0000418 {
Keith Davis0c2eeac2020-02-11 16:51:50 +0000419 // Per-tensor
Ryan OShea03181ff2020-02-07 17:22:22 +0000420 type = armnn::DataType::QAsymmS8;
421 }
422 else
423 {
Keith Davis0c2eeac2020-02-11 16:51:50 +0000424 // Per-channel
Ryan OShea03181ff2020-02-07 17:22:22 +0000425 type = armnn::DataType::QSymmS8;
426 }
Finn Williamsed66d142019-12-06 09:55:55 +0000427 break;
428 case tflite::TensorType_INT16:
Derek Lambertif90c56d2020-01-10 17:14:08 +0000429 type = armnn::DataType::QSymmS16;
Finn Williamsed66d142019-12-06 09:55:55 +0000430 break;
telsoa01c577f2c2018-08-31 09:22:23 +0100431 case tflite::TensorType_INT32:
432 type = armnn::DataType::Signed32;
433 break;
Inki Daed4619e22020-09-10 15:33:54 +0900434 case tflite::TensorType_INT64:
435 type = armnn::DataType::Signed64;
436 break;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100437 case tflite::TensorType_BOOL:
438 type = armnn::DataType::Boolean;
439 break;
telsoa01c577f2c2018-08-31 09:22:23 +0100440 default:
441 {
442 CheckLocation location = CHECK_LOCATION();
443 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100444 fmt::format("Unsupported data type {} = {} for tensor: {}. {}",
445 tensorPtr->type,
446 tflite::EnumNameTensorType(tensorPtr->type),
447 tensorPtr->name,
448 location.AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100449 }
450 }
Finn Williamsb49ed182021-06-29 15:50:08 +0100451 TensorShape tensorShape;
452
453 std::vector<unsigned int> safeShape = shape;
454 if (shape.size() == 0)
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100455 {
456 safeShape.push_back(1);
Finn Williamsb49ed182021-06-29 15:50:08 +0100457 }
458
459 if (!outputTensor)
460 {
461 tensorShape = TensorShape(armnn::numeric_cast<unsigned int>(safeShape.size()), safeShape.data());
462 }
463 else
464 {
Rob Hughesd812a312021-08-06 13:10:53 +0100465 size_t shapeSignatureSize = tensorPtr->shape_signature.size();
Finn Williamsb49ed182021-06-29 15:50:08 +0100466
467 // If a shape signature exists we will use that to infer dynamic tensors
468 if (shapeSignatureSize != 0)
Sadik Armagand109a4d2020-07-28 10:42:13 +0100469 {
Finn Williamsb49ed182021-06-29 15:50:08 +0100470 // If the shape is incompatible with the shape signature override the shape
471 if (shapeSignatureSize != shape.size())
472 {
473 safeShape = {};
474
475 for (unsigned int i = 0; i < shapeSignatureSize; ++i)
476 {
477 unsigned int dim = tensorPtr->shape_signature[i] > -1 ?
478 static_cast<unsigned int>(tensorPtr->shape_signature[i]) : 0;
479 safeShape.push_back(dim);
480 }
481 }
482
Rob Hughesd812a312021-08-06 13:10:53 +0100483 std::unique_ptr<bool[]> dimMask = std::make_unique<bool[]>(tensorPtr->shape_signature.size());
Finn Williamsb49ed182021-06-29 15:50:08 +0100484 for (unsigned int i = 0; i < tensorPtr->shape_signature.size(); ++i)
485 {
486 dimMask[i] = tensorPtr->shape_signature[i] == -1 ? false : true;
487 }
Rob Hughesd812a312021-08-06 13:10:53 +0100488 tensorShape = TensorShape(static_cast<unsigned int>(safeShape.size()), safeShape.data(), dimMask.get());
Finn Williamsb49ed182021-06-29 15:50:08 +0100489 }
490 // If there is no shape signature treat the tensor as dynamic if the shape has a size of zero
491 else if (shape.size() == 0)
492 {
493 tensorShape = TensorShape(1, false);
494 }
495 else
496 {
497 tensorShape = TensorShape(armnn::numeric_cast<unsigned int>(shape.size()), shape.data());
Sadik Armagand109a4d2020-07-28 10:42:13 +0100498 }
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100499 }
500
Keith Davisd305e1a2020-01-22 11:57:54 +0000501 float quantizationScale = 0.0f;
502 int32_t quantizationOffset = 0;
503
504 if (tensorPtr->quantization.get())
505 {
506 if (tensorPtr->quantization->scale.size() <= 1)
507 {
508 CHECK_VALID_SIZE(tensorPtr->quantization->zero_point.size(), 0, 1);
509 CHECK_VALID_SIZE(tensorPtr->quantization->zero_point.size(), 0, 1);
510
511 if (tensorPtr->quantization->scale.size() == 1)
512 {
513 quantizationScale = tensorPtr->quantization->scale[0];
514 }
515 if (tensorPtr->quantization->zero_point.size() == 1)
516 {
517 // NOTE: we lose precision here when converting from 64 bit to 32
Ryan OShea03181ff2020-02-07 17:22:22 +0000518 // but this is what we support at the moment in ArmNN
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100519 quantizationOffset = armnn::numeric_cast<int32_t>(tensorPtr->quantization->zero_point[0]);
Keith Davisd305e1a2020-01-22 11:57:54 +0000520 }
521
Sadik Armagand109a4d2020-07-28 10:42:13 +0100522 armnn::TensorInfo result(tensorShape,
523 type,
524 quantizationScale,
525 quantizationOffset);
Keith Davisd305e1a2020-01-22 11:57:54 +0000526 return result;
527 }
528 else
529 {
530 std::vector<float> quantizationScales;
531 std::vector<int32_t> quantizationOffsets;
532
533 // Scale
534 std::copy(tensorPtr->quantization->scale.begin(),
535 tensorPtr->quantization->scale.end(),
536 std::back_inserter(quantizationScales));
537
Keith Davis0c2eeac2020-02-11 16:51:50 +0000538 // QSymmS8 Per-axis
Sadik Armagand109a4d2020-07-28 10:42:13 +0100539 armnn::TensorInfo result(tensorShape,
540 type,
541 quantizationScales,
Jan Eilers7612bd62021-04-06 17:29:03 +0100542 armnn::numeric_cast<unsigned int>(tensorPtr->quantization->quantized_dimension));
Keith Davisd305e1a2020-01-22 11:57:54 +0000543 return result;
544 }
545 }
546 else
547 {
Sadik Armagand109a4d2020-07-28 10:42:13 +0100548 armnn::TensorInfo result(tensorShape,
Keith Davisd305e1a2020-01-22 11:57:54 +0000549 type,
550 quantizationScale,
551 quantizationOffset);
552 return result;
553 }
telsoa01c577f2c2018-08-31 09:22:23 +0100554}
555
Jan Eilers7612bd62021-04-06 17:29:03 +0100556armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr)
Narumol Prangnawarat4628d052019-02-25 17:26:05 +0000557{
Mike Kelly0d77ae12022-01-07 17:42:27 +0000558 auto const& dimensions = AsUnsignedVector(tensorPtr->shape);
Jan Eilers7612bd62021-04-06 17:29:03 +0100559 return ToTensorInfo(tensorPtr, dimensions);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +0000560}
561
Kevin May7d96b162021-02-03 17:38:41 +0000562armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr,
Sadik Armagand109a4d2020-07-28 10:42:13 +0100563 const bool outputTensor)
564{
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, outputTensor);
Sadik Armagand109a4d2020-07-28 10:42:13 +0100567}
568
telsoa01c577f2c2018-08-31 09:22:23 +0100569template<typename T>
570std::pair<armnn::ConstTensor, std::unique_ptr<T[]>>
Kevin May7d96b162021-02-03 17:38:41 +0000571CreateConstTensorImpl(TfLiteParserImpl::BufferRawPtr bufferPtr,
572 TfLiteParserImpl::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +0000573 armnn::TensorInfo& tensorInfo,
574 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +0100575{
Jan Eilers8eb25602020-03-09 12:13:48 +0000576 IgnoreUnused(tensorPtr);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100577 ARMNN_ASSERT_MSG(tensorPtr != nullptr, "tensorPtr is null");
578 ARMNN_ASSERT_MSG(bufferPtr != nullptr,
James Ward58dec6b2020-09-11 17:32:44 +0100579 fmt::format("Buffer for buffer:{} is null", tensorPtr->buffer).c_str());
telsoa01c577f2c2018-08-31 09:22:23 +0100580
581 std::unique_ptr<T[]> data(new T[tensorInfo.GetNumElements()]);
Matteo Martincigh747ef822018-12-18 09:26:39 +0000582
583 if (permutationVector.has_value() && permutationVector.value().GetSize() > 0)
584 {
585 tensorInfo = armnnUtils::Permuted(tensorInfo, permutationVector.value());
Matteo Martincighd5b9e642019-01-04 18:01:21 +0000586 armnnUtils::Permute(tensorInfo.GetShape(), permutationVector.value(),
587 reinterpret_cast<const T*>(bufferPtr->data.data()), data.get(), sizeof(T));
Matteo Martincigh747ef822018-12-18 09:26:39 +0000588 }
589 else
590 {
591 ::memcpy(data.get(), bufferPtr->data.data(), tensorInfo.GetNumBytes());
592 }
593
Matthew Sloyan81beae32021-07-13 19:46:11 +0100594 // Make sure isConstant flag is set.
595 tensorInfo.SetConstant();
596
telsoa01c577f2c2018-08-31 09:22:23 +0100597 return std::make_pair(ConstTensor(tensorInfo, data.get()), std::move(data));
598}
599
telsoa01c577f2c2018-08-31 09:22:23 +0100600armnn::LayerBindingId GenerateLayerBindingId(size_t subgraphIndex, size_t tensorIndex)
601{
602 // generate the binding id by shifting the tensor id by 8 bit
603 // and add the subgraph id, which allows 256 subgraphs
604 return static_cast<armnn::LayerBindingId>((tensorIndex<<8)+subgraphIndex);
605}
606
Aron Virginas-Tar70672f62019-01-23 14:00:00 +0000607bool CheckShape(const armnn::TensorShape& actual, const std::vector<int32_t>& expected)
608{
609 const unsigned int actualSize = actual.GetNumDimensions();
610 if (actualSize != expected.size())
611 {
612 return false;
613 }
614
615 for (unsigned int i = 0u; i < actualSize; i++)
616 {
617 if (expected[i] < 0 ||
618 actual[i] != static_cast<unsigned int>(expected[i]))
619 {
620 return false;
621 }
622 }
623
624 return true;
625}
626
James Conroy05102392020-06-24 15:39:55 +0100627void CheckMatchingQuantization(const TensorInfo& first,
628 const TensorInfo& second,
629 const std::string& descName,
630 std::string const& firstName,
631 std::string const& secondName)
632{
633 if (!first.IsQuantized() ||
634 !second.IsQuantized())
635 {
636 // Not a quantized type, ignore the validation
637 return;
638 }
639
640 DataType firstDataType = first.GetDataType();
641 DataType secondDataType = second.GetDataType();
642
643 if (firstDataType != secondDataType)
644 {
645 throw InvalidArgumentException(descName + ": " + firstName + " and " + secondName +
646 " must be of the same quantized type, " +
647 firstName + " is " + GetDataTypeName(firstDataType) + ", " +
648 secondName + " is " + GetDataTypeName(secondDataType));
649 }
650
651 if (!first.IsTypeSpaceMatch(second))
652 {
653 throw InvalidArgumentException(descName + ": " + firstName + " and " + secondName +
654 " must have the same quantization space, " +
655 firstName + " has offset " + std::to_string(first.GetQuantizationOffset()) +
656 " and scale " + std::to_string(first.GetQuantizationScale()) + ", " +
657 secondName + " has offset " + std::to_string(second.GetQuantizationOffset()) +
658 " and scale " + std::to_string(second.GetQuantizationScale()));
659 }
660}
661
telsoa01c577f2c2018-08-31 09:22:23 +0100662} // <anonymous>
663
Kevin May7d96b162021-02-03 17:38:41 +0000664TfLiteParserImpl::TfLiteParserImpl(const Optional<ITfLiteParser::TfLiteParserOptions>& options)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100665: m_Options(options)
666, m_Network(nullptr, nullptr)
Kevin May7d96b162021-02-03 17:38:41 +0000667, m_ParserFunctions(tflite::BuiltinOperator_MAX+1, &TfLiteParserImpl::ParseUnsupportedOperator)
telsoa01c577f2c2018-08-31 09:22:23 +0100668{
669 // register supported operators
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100670 m_ParserFunctions[tflite::BuiltinOperator_ABS] = &TfLiteParserImpl::ParseAbs;
Kevin May7d96b162021-02-03 17:38:41 +0000671 m_ParserFunctions[tflite::BuiltinOperator_ADD] = &TfLiteParserImpl::ParseAdd;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100672 m_ParserFunctions[tflite::BuiltinOperator_ARG_MIN] = &TfLiteParserImpl::ParseArgMin;
673 m_ParserFunctions[tflite::BuiltinOperator_ARG_MAX] = &TfLiteParserImpl::ParseArgMax;
Kevin May7d96b162021-02-03 17:38:41 +0000674 m_ParserFunctions[tflite::BuiltinOperator_AVERAGE_POOL_2D] = &TfLiteParserImpl::ParseAveragePool2D;
675 m_ParserFunctions[tflite::BuiltinOperator_BATCH_TO_SPACE_ND] = &TfLiteParserImpl::ParseBatchToSpaceND;
mathad01b392e982021-04-07 12:07:30 +0100676 m_ParserFunctions[tflite::BuiltinOperator_CAST] = &TfLiteParserImpl::ParseCast;
Kevin May7d96b162021-02-03 17:38:41 +0000677 m_ParserFunctions[tflite::BuiltinOperator_CONCATENATION] = &TfLiteParserImpl::ParseConcatenation;
678 m_ParserFunctions[tflite::BuiltinOperator_CONV_2D] = &TfLiteParserImpl::ParseConv2D;
Matthew Sloyan4d217c02021-10-07 11:48:58 +0100679 // Conv3D support was added in TF 2.5, so for backwards compatibility a hash define is needed.
680 #if defined(ARMNN_POST_TFLITE_2_3)
Matthew Sloyaneb5f8102021-10-05 17:31:42 +0100681 m_ParserFunctions[tflite::BuiltinOperator_CONV_3D] = &TfLiteParserImpl::ParseConv3D;
Matthew Sloyan4d217c02021-10-07 11:48:58 +0100682 #endif
Kevin May7d96b162021-02-03 17:38:41 +0000683 m_ParserFunctions[tflite::BuiltinOperator_CUSTOM] = &TfLiteParserImpl::ParseCustomOperator;
684 m_ParserFunctions[tflite::BuiltinOperator_DEPTH_TO_SPACE] = &TfLiteParserImpl::ParseDepthToSpace;
685 m_ParserFunctions[tflite::BuiltinOperator_DEPTHWISE_CONV_2D] = &TfLiteParserImpl::ParseDepthwiseConv2D;
686 m_ParserFunctions[tflite::BuiltinOperator_DEQUANTIZE] = &TfLiteParserImpl::ParseDequantize;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100687 m_ParserFunctions[tflite::BuiltinOperator_DIV] = &TfLiteParserImpl::ParseDiv;
Kevin May7d96b162021-02-03 17:38:41 +0000688 m_ParserFunctions[tflite::BuiltinOperator_ELU] = &TfLiteParserImpl::ParseElu;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300689 m_ParserFunctions[tflite::BuiltinOperator_EQUAL] = &TfLiteParserImpl::ParseEqual;
Kevin May7d96b162021-02-03 17:38:41 +0000690 m_ParserFunctions[tflite::BuiltinOperator_EXP] = &TfLiteParserImpl::ParseExp;
Teresa Charlin3ab85482021-06-08 16:59:29 +0100691 m_ParserFunctions[tflite::BuiltinOperator_EXPAND_DIMS] = &TfLiteParserImpl::ParseExpandDims;
Kevin May7d96b162021-02-03 17:38:41 +0000692 m_ParserFunctions[tflite::BuiltinOperator_FULLY_CONNECTED] = &TfLiteParserImpl::ParseFullyConnected;
693 m_ParserFunctions[tflite::BuiltinOperator_GATHER] = &TfLiteParserImpl::ParseGather;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300694 m_ParserFunctions[tflite::BuiltinOperator_GREATER] = &TfLiteParserImpl::ParseGreater;
695 m_ParserFunctions[tflite::BuiltinOperator_GREATER_EQUAL] = &TfLiteParserImpl::ParseGreaterOrEqual;
Kevin May7d96b162021-02-03 17:38:41 +0000696 m_ParserFunctions[tflite::BuiltinOperator_HARD_SWISH] = &TfLiteParserImpl::ParseHardSwish;
697 m_ParserFunctions[tflite::BuiltinOperator_LEAKY_RELU] = &TfLiteParserImpl::ParseLeakyRelu;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300698 m_ParserFunctions[tflite::BuiltinOperator_LESS] = &TfLiteParserImpl::ParseLess;
699 m_ParserFunctions[tflite::BuiltinOperator_LESS_EQUAL] = &TfLiteParserImpl::ParseLessOrEqual;
Mike Kelly31dce2b2021-09-01 21:22:37 +0100700 m_ParserFunctions[tflite::BuiltinOperator_LOCAL_RESPONSE_NORMALIZATION]
701 = &TfLiteParserImpl::ParseLocalResponseNormalization;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100702 m_ParserFunctions[tflite::BuiltinOperator_LOGICAL_NOT] = &TfLiteParserImpl::ParseLogicalNot;
Kevin May7d96b162021-02-03 17:38:41 +0000703 m_ParserFunctions[tflite::BuiltinOperator_LOGISTIC] = &TfLiteParserImpl::ParseLogistic;
704 m_ParserFunctions[tflite::BuiltinOperator_L2_NORMALIZATION] = &TfLiteParserImpl::ParseL2Normalization;
705 m_ParserFunctions[tflite::BuiltinOperator_MAX_POOL_2D] = &TfLiteParserImpl::ParseMaxPool2D;
706 m_ParserFunctions[tflite::BuiltinOperator_MAXIMUM] = &TfLiteParserImpl::ParseMaximum;
707 m_ParserFunctions[tflite::BuiltinOperator_MEAN] = &TfLiteParserImpl::ParseMean;
708 m_ParserFunctions[tflite::BuiltinOperator_MINIMUM] = &TfLiteParserImpl::ParseMinimum;
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +0100709 m_ParserFunctions[tflite::BuiltinOperator_MIRROR_PAD] = &TfLiteParserImpl::ParseMirrorPad;
Kevin May7d96b162021-02-03 17:38:41 +0000710 m_ParserFunctions[tflite::BuiltinOperator_MUL] = &TfLiteParserImpl::ParseMul;
711 m_ParserFunctions[tflite::BuiltinOperator_NEG] = &TfLiteParserImpl::ParseNeg;
Bruno Goncalves2d0eb862021-07-11 14:10:15 -0300712 m_ParserFunctions[tflite::BuiltinOperator_NOT_EQUAL] = &TfLiteParserImpl::ParseNotEqual;
Kevin May7d96b162021-02-03 17:38:41 +0000713 m_ParserFunctions[tflite::BuiltinOperator_PACK] = &TfLiteParserImpl::ParsePack;
714 m_ParserFunctions[tflite::BuiltinOperator_PAD] = &TfLiteParserImpl::ParsePad;
Mike Kelly0d77ae12022-01-07 17:42:27 +0000715 m_ParserFunctions[tflite::BuiltinOperator_PADV2] = &TfLiteParserImpl::ParsePad;
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +0100716 m_ParserFunctions[tflite::BuiltinOperator_PRELU] = &TfLiteParserImpl::ParsePrelu;
Kevin May7d96b162021-02-03 17:38:41 +0000717 m_ParserFunctions[tflite::BuiltinOperator_QUANTIZE] = &TfLiteParserImpl::ParseQuantize;
718 m_ParserFunctions[tflite::BuiltinOperator_RELU] = &TfLiteParserImpl::ParseRelu;
719 m_ParserFunctions[tflite::BuiltinOperator_RELU6] = &TfLiteParserImpl::ParseRelu6;
Sadik Armagana2747482021-02-09 10:28:54 +0000720 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MAX] = &TfLiteParserImpl::ParseReduceMax;
721 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MIN] = &TfLiteParserImpl::ParseReduceMin;
Teresa Charlin4e3e8312021-08-05 12:34:37 +0100722 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_PROD] = &TfLiteParserImpl::ParseReduceProd;
Kevin May7d96b162021-02-03 17:38:41 +0000723 m_ParserFunctions[tflite::BuiltinOperator_RESHAPE] = &TfLiteParserImpl::ParseReshape;
724 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_BILINEAR] = &TfLiteParserImpl::ParseResizeBilinear;
725 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_NEAREST_NEIGHBOR] = &TfLiteParserImpl::ParseResizeNearestNeighbor;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100726 m_ParserFunctions[tflite::BuiltinOperator_RSQRT] = &TfLiteParserImpl::ParseRsqrt;
Keith Davis0176fd82021-06-01 17:36:32 +0100727 m_ParserFunctions[tflite::BuiltinOperator_SHAPE] = &TfLiteParserImpl::ParseShape;
Kevin May7d96b162021-02-03 17:38:41 +0000728 m_ParserFunctions[tflite::BuiltinOperator_SLICE] = &TfLiteParserImpl::ParseSlice;
729 m_ParserFunctions[tflite::BuiltinOperator_SOFTMAX] = &TfLiteParserImpl::ParseSoftmax;
730 m_ParserFunctions[tflite::BuiltinOperator_SPACE_TO_BATCH_ND] = &TfLiteParserImpl::ParseSpaceToBatchND;
731 m_ParserFunctions[tflite::BuiltinOperator_SPLIT] = &TfLiteParserImpl::ParseSplit;
732 m_ParserFunctions[tflite::BuiltinOperator_SPLIT_V] = &TfLiteParserImpl::ParseSplitV;
733 m_ParserFunctions[tflite::BuiltinOperator_SQUEEZE] = &TfLiteParserImpl::ParseSqueeze;
734 m_ParserFunctions[tflite::BuiltinOperator_STRIDED_SLICE] = &TfLiteParserImpl::ParseStridedSlice;
735 m_ParserFunctions[tflite::BuiltinOperator_SUB] = &TfLiteParserImpl::ParseSub;
736 m_ParserFunctions[tflite::BuiltinOperator_SUM] = &TfLiteParserImpl::ParseSum;
737 m_ParserFunctions[tflite::BuiltinOperator_TANH] = &TfLiteParserImpl::ParseTanH;
738 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE] = &TfLiteParserImpl::ParseTranspose;
739 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE_CONV] = &TfLiteParserImpl::ParseTransposeConv;
740 m_ParserFunctions[tflite::BuiltinOperator_UNPACK] = &TfLiteParserImpl::ParseUnpack;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100741
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100742 // register supported custom operators
Kevin May7d96b162021-02-03 17:38:41 +0000743 m_CustomParserFunctions["TFLite_Detection_PostProcess"] = &TfLiteParserImpl::ParseDetectionPostProcess;
telsoa01c577f2c2018-08-31 09:22:23 +0100744}
745
Kevin May7d96b162021-02-03 17:38:41 +0000746void TfLiteParserImpl::ResetParser()
telsoa01c577f2c2018-08-31 09:22:23 +0100747{
748 m_Network = armnn::INetworkPtr(nullptr, nullptr);
749 m_Model = nullptr;
750 m_SubgraphConnections.clear();
751}
752
Kevin May7d96b162021-02-03 17:38:41 +0000753INetworkPtr TfLiteParserImpl::CreateNetworkFromBinaryFile(const char* graphFile)
telsoa01c577f2c2018-08-31 09:22:23 +0100754{
755 ResetParser();
756 m_Model = LoadModelFromFile(graphFile);
757 return CreateNetworkFromModel();
758}
759
Mike Kelly0d77ae12022-01-07 17:42:27 +0000760INetworkPtr TfLiteParserImpl::CreateNetworkFromBinary(const std::vector<uint8_t>& binaryContent)
telsoa01c577f2c2018-08-31 09:22:23 +0100761{
762 ResetParser();
763 m_Model = LoadModelFromBinary(binaryContent.data(), binaryContent.size());
764 return CreateNetworkFromModel();
765}
766
Finn Williamsb49ed182021-06-29 15:50:08 +0100767
768armnn::INetworkPtr TfLiteParserImpl::LoadModel(std::unique_ptr<tflite::ModelT> model)
769{
770 ResetParser();
771 m_Model = std::move(model);
772
773 return CreateNetworkFromModel();
774}
775
Kevin May7d96b162021-02-03 17:38:41 +0000776INetworkPtr TfLiteParserImpl::CreateNetworkFromModel()
telsoa01c577f2c2018-08-31 09:22:23 +0100777{
Sadik Armagand109a4d2020-07-28 10:42:13 +0100778
779 using NetworkOptions = std::vector<BackendOptions>;
780 NetworkOptions networkOptions = {};
781 if (m_Options && m_Options.value().m_InferAndValidate)
782 {
783 BackendOptions shapeInferenceMethodOption("ShapeInferenceMethod",
784 {
785 { "InferAndValidate", true }
786 });
787
788 networkOptions.push_back(shapeInferenceMethodOption);
789 }
790
791 m_Network = INetwork::Create(networkOptions);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100792 ARMNN_ASSERT(m_Model.get() != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +0100793
telsoa01c577f2c2018-08-31 09:22:23 +0100794 if (m_Model->subgraphs.size() != 1)
795 {
796 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100797 fmt::format("Current TfLite parser only supports 1 subgraph. Current one has: {} {}",
798 m_Model->subgraphs.size(),
799 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100800 }
801
802 size_t subgraphIndex = 0;
Colm Donelan6350d272020-06-09 16:56:25 +0100803 size_t operatorIndex = 0;
804 try
telsoa01c577f2c2018-08-31 09:22:23 +0100805 {
Colm Donelan6350d272020-06-09 16:56:25 +0100806 for (SubgraphPtr const& subgraph : m_Model->subgraphs)
telsoa01c577f2c2018-08-31 09:22:23 +0100807 {
Colm Donelan6350d272020-06-09 16:56:25 +0100808 m_SubgraphConnections.emplace_back(subgraph->tensors.size());
809 for (OperatorPtr const& op : subgraph->operators)
telsoa01c577f2c2018-08-31 09:22:23 +0100810 {
Colm Donelan6350d272020-06-09 16:56:25 +0100811 auto const& opCodePtr = m_Model->operator_codes[op->opcode_index];
Jim Flynnfca233e2021-09-23 12:16:53 +0100812
813// 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 +0100814#if defined(ARMNN_POST_TFLITE_2_3)
Jim Flynnfca233e2021-09-23 12:16:53 +0100815 auto builtinCode = std::max(opCodePtr->builtin_code,
816 static_cast<tflite::BuiltinOperator>(opCodePtr->deprecated_builtin_code));
817#else
telsoa01c577f2c2018-08-31 09:22:23 +0100818 auto builtinCode = opCodePtr->builtin_code;
Jim Flynnfca233e2021-09-23 12:16:53 +0100819#endif
telsoa01c577f2c2018-08-31 09:22:23 +0100820
821 if (builtinCode > tflite::BuiltinOperator_MAX)
822 {
James Ward58dec6b2020-09-11 17:32:44 +0100823 throw ParseException(fmt::format("Operator code {} is out of range 0-{}. "
824 "subgraph:{} operator idx:{}. {}",
825 builtinCode, tflite::BuiltinOperator_MAX, subgraphIndex,
826 operatorIndex, CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100827 }
828
829 // lookup and call the parser function
Colm Donelan6350d272020-06-09 16:56:25 +0100830 auto& parserFunction = m_ParserFunctions[builtinCode];
telsoa01c577f2c2018-08-31 09:22:23 +0100831 (this->*parserFunction)(subgraphIndex, operatorIndex);
Colm Donelan6350d272020-06-09 16:56:25 +0100832 ++operatorIndex;
telsoa01c577f2c2018-08-31 09:22:23 +0100833 }
telsoa01c577f2c2018-08-31 09:22:23 +0100834
Colm Donelan6350d272020-06-09 16:56:25 +0100835 SetupInputLayers(subgraphIndex);
836 SetupOutputLayers(subgraphIndex);
837 SetupConstantLayers(subgraphIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100838
Colm Donelan6350d272020-06-09 16:56:25 +0100839 ++subgraphIndex;
840 operatorIndex = 0;
telsoa01c577f2c2018-08-31 09:22:23 +0100841 }
telsoa01c577f2c2018-08-31 09:22:23 +0100842 }
Colm Donelan6350d272020-06-09 16:56:25 +0100843 catch (const ParseException& e)
telsoa01c577f2c2018-08-31 09:22:23 +0100844 {
Colm Donelan6350d272020-06-09 16:56:25 +0100845 std::stringstream errorString;
846 errorString << "Failed to parse operator #" << operatorIndex << " within subgraph #"
847 << subgraphIndex << " error: " << e.what();
848 ARMNN_LOG(error) << errorString.str();
849 std::stringstream errors;
850 errors << errorString.str() << "\n";
telsoa01c577f2c2018-08-31 09:22:23 +0100851 throw ParseException(errors.str());
852 }
853
854 // establish the connections from the layer outputs to the inputs of the subsequent layers
Colm Donelan6350d272020-06-09 16:56:25 +0100855 for (subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100856 {
857 for (size_t tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
858 {
859 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot != nullptr)
860 {
861 for (size_t inputSlotIdx = 0;
862 inputSlotIdx < m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size();
863 ++inputSlotIdx)
864 {
865 m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot->Connect(
866 *(m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots[inputSlotIdx]));
867 }
868 }
869 }
870 }
871
872 return std::move(m_Network);
873}
874
Kevin May7d96b162021-02-03 17:38:41 +0000875void TfLiteParserImpl::RegisterProducerOfTensor(size_t subgraphIndex,
876 size_t tensorIndex,
877 armnn::IOutputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +0100878{
879 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100880 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
881 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100882
883 TensorSlots & tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
884
885 // assuming there is only one producer for that tensor
886 if (tensorSlots.outputSlot != nullptr)
887 {
James Ward58dec6b2020-09-11 17:32:44 +0100888 throw ParseException(fmt::format("Another layer has already registered itself as the producer of "
889 "subgraph:{} tensor:{} {}",
890 subgraphIndex,
891 tensorIndex,
892 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100893 }
894
895 tensorSlots.outputSlot = slot;
896}
897
Kevin May7d96b162021-02-03 17:38:41 +0000898void TfLiteParserImpl::RegisterConsumerOfTensor(size_t subgraphIndex,
899 size_t tensorIndex,
900 armnn::IInputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +0100901{
902 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100903 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
904 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100905
Finn Williamsd4fa5452021-03-01 12:31:41 +0000906 TensorSlots& tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +0100907 tensorSlots.inputSlots.push_back(slot);
908}
909
Kevin May7d96b162021-02-03 17:38:41 +0000910void TfLiteParserImpl::ParseCustomOperator(size_t subgraphIndex, size_t operatorIndex)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100911{
912 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
913
914 // NOTE: By default we presume the custom operator is not supported
Kevin May7d96b162021-02-03 17:38:41 +0000915 auto customParserFunction = &TfLiteParserImpl::ParseUnsupportedOperator;
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100916
917 // Identify custom code defined for custom operator
918 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
919 const auto& customCode = m_Model->operator_codes[operatorPtr->opcode_index]->custom_code;
920
921 // Find parser function that correspondes to custom code (if any)
922 auto iterator = m_CustomParserFunctions.find(customCode);
923 if (iterator != m_CustomParserFunctions.end())
924 {
925 customParserFunction = iterator->second;
926 }
927
928 // Run parser function
929 (this->*customParserFunction)(subgraphIndex, operatorIndex);
930}
931
Kevin May7d96b162021-02-03 17:38:41 +0000932void TfLiteParserImpl::ParseUnsupportedOperator(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100933{
934 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100935
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100936 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
937
938 auto opcodeIndex = operatorPtr->opcode_index;
Jim Flynnfca233e2021-09-23 12:16:53 +0100939
940// 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 +0100941#if defined(ARMNN_POST_TFLITE_2_3)
Jim Flynnfca233e2021-09-23 12:16:53 +0100942 auto opcode = std::max(m_Model->operator_codes[opcodeIndex]->builtin_code,
943 static_cast<tflite::BuiltinOperator>(m_Model->operator_codes[opcodeIndex]->deprecated_builtin_code));
944#else
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100945 auto opcode = m_Model->operator_codes[opcodeIndex]->builtin_code;
Jim Flynnfca233e2021-09-23 12:16:53 +0100946#endif
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100947
948 if (!m_Options || !m_Options.value().m_StandInLayerForUnsupported)
949 {
950 // Do not add StandInLayer, throw ParseException instead
951 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100952 fmt::format("Operator not supported. "
953 "subgraph:{} operator:{} "
954 "opcode_index:{} opcode:{} / {} {}",
955 subgraphIndex,
956 operatorIndex,
957 opcodeIndex,
958 opcode,
959 tflite::EnumNameBuiltinOperator(opcode),
960 CHECK_LOCATION().AsString()));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100961 }
962
963 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
964 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
965
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100966 const unsigned int numInputs = armnn::numeric_cast<unsigned int>(inputs.size());
967 const unsigned int numOutputs = armnn::numeric_cast<unsigned int>(outputs.size());
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100968
969 StandInDescriptor descriptor(numInputs, numOutputs);
James Ward58dec6b2020-09-11 17:32:44 +0100970 auto layerName = fmt::format("StandIn:{}:{}:{}", subgraphIndex, operatorIndex, opcode);
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100971
972 // Add a non-executable StandInLayer as a placeholder for any unsupported operator
973 IConnectableLayer* layer = m_Network->AddStandInLayer(descriptor, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +0100974 ARMNN_ASSERT(layer != nullptr);
975
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100976 for (unsigned int i = 0u; i < numOutputs; ++i)
977 {
Sadik Armagand109a4d2020-07-28 10:42:13 +0100978 layer->GetOutputSlot(i).SetTensorInfo(ToTensorInfo(outputs[i], true));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100979 }
980
981 auto inputTensorIds = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
982 auto outputTensorIds = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
983
984 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIds);
985 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIds);
telsoa01c577f2c2018-08-31 09:22:23 +0100986}
987
mathad01b392e982021-04-07 12:07:30 +0100988void TfLiteParserImpl::ParseCast(size_t subgraphIndex, size_t operatorIndex)
989{
990 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
991
992 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
993 CHECK_VALID_SIZE(inputs.size(), 1);
994 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
995 CHECK_VALID_SIZE(outputs.size(), 1);
996
997 auto layerName = fmt::format("Cast:{}:{}", subgraphIndex, operatorIndex);
998
999 IConnectableLayer* layer = m_Network->AddCastLayer(layerName.c_str());
1000 ARMNN_ASSERT(layer != nullptr);
1001
1002 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1003 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1004
1005 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1006 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1007
1008 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1009 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1010}
1011
Kevin May7d96b162021-02-03 17:38:41 +00001012void TfLiteParserImpl::ParseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001013{
1014 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1015
Mike Kelly0d77ae12022-01-07 17:42:27 +00001016 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1017 const auto* options = operatorPtr->builtin_options.AsConv2DOptions();
telsoa01c577f2c2018-08-31 09:22:23 +01001018
1019 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1020
1021 Convolution2dDescriptor desc;
1022 desc.m_BiasEnabled = false;
1023 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1024 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +00001025 desc.m_DataLayout = armnn::DataLayout::NHWC;
Pablo Tellof0bd6832019-04-26 17:58:13 +01001026 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1027 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +00001028
telsoa01c577f2c2018-08-31 09:22:23 +01001029 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1030 CHECK_VALID_SIZE(inputs.size(), 2, 3);
1031
1032 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1033 CHECK_VALID_SIZE(outputs.size(), 1);
1034
1035 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1036 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
1037
1038 // assuming input is NHWC
1039 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1040 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1041
1042 // assuming the filter is OHWI : Output, H, W, Input
1043 // which is essentially the same as NHWC
1044 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1045 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1046
Pablo Tellof0bd6832019-04-26 17:58:13 +01001047 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1048 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1049 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1050 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +01001051
Finn Williamsd4fa5452021-03-01 12:31:41 +00001052 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001053 armnn::IConnectableLayer* layer = nullptr;
telsoa01c577f2c2018-08-31 09:22:23 +01001054
James Ward58dec6b2020-09-11 17:32:44 +01001055 auto layerName = fmt::format("Conv2D:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001056
1057 if (inputs.size() == 3)
1058 {
1059 desc.m_BiasEnabled = true;
1060 armnn::TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00001061 auto biasTensorAndData = CreateConstTensorNonPermuted(inputs[2], biasTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001062 layer = m_Network->AddConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +00001063 filterTensorAndData,
1064 Optional<ConstTensor>(biasTensorAndData),
telsoa01c577f2c2018-08-31 09:22:23 +01001065 layerName.c_str());
1066 }
1067 else
1068 {
1069 layer = m_Network->AddConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +00001070 filterTensorAndData,
Matteo Martincighfc598e12019-05-14 10:36:13 +01001071 EmptyOptional(),
telsoa01c577f2c2018-08-31 09:22:23 +01001072 layerName.c_str());
1073 }
1074
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001075 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01001076
Sadik Armagand109a4d2020-07-28 10:42:13 +01001077 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
jimfly01c25411c2018-11-14 17:47:22 +00001078 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001079
1080 // register the input connection slots for the layer, connections are made after all layers have been created
1081 // only the tensors for the inputs are relevant, exclude the const tensors
1082 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +00001083 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
telsoa01c577f2c2018-08-31 09:22:23 +01001084
jimfly01c25411c2018-11-14 17:47:22 +00001085 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +01001086 // register the output connection slots for the layer, connections are made after all layers have been created
1087 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1088 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1089}
1090
Matthew Sloyan4d217c02021-10-07 11:48:58 +01001091// Conv3D support was added in TF 2.5, so for backwards compatibility a hash define is needed.
1092#if defined(ARMNN_POST_TFLITE_2_3)
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001093void TfLiteParserImpl::ParseConv3D(size_t subgraphIndex, size_t operatorIndex)
1094{
1095 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1096
1097 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1098 const auto* options = operatorPtr->builtin_options.AsConv3DOptions();
1099
1100 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1101
1102 Convolution3dDescriptor desc;
1103 desc.m_BiasEnabled = false;
1104 desc.m_DataLayout = armnn::DataLayout::NDHWC;
1105 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1106 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1107 desc.m_StrideZ = CHECKED_NON_NEGATIVE(options->stride_d);
1108 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1109 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
1110 desc.m_DilationZ = CHECKED_NON_NEGATIVE(options->dilation_d_factor);
1111
1112 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1113 CHECK_VALID_SIZE(inputs.size(), 2, 3);
1114
1115 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1116 CHECK_VALID_SIZE(outputs.size(), 1);
1117
1118 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1119 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
1120
1121 // Assuming input is NDHWC
1122 unsigned int inputDepth = inputTensorInfo.GetShape()[1];
1123 unsigned int inputHeight = inputTensorInfo.GetShape()[2];
1124 unsigned int inputWidth = inputTensorInfo.GetShape()[3];
1125
1126 // Assuming the filter is DHWIO : Depth, Height, Width, OutputChannels, InputChannels
1127 unsigned int filterDepth = filterTensorInfo.GetShape()[0];
1128 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1129 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1130
1131 CalcPadding(inputDepth, filterDepth, desc.m_StrideZ,
1132 desc.m_DilationY, desc.m_PadFront, desc.m_PadBack, options->padding);
1133 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1134 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1135 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1136 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
1137
1138 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo);
1139
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001140 auto layerName = fmt::format("Conv3D:{}:{}", subgraphIndex, operatorIndex);
1141
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001142 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1143 // Add the first input and weights tensor to the registration list.
1144 // The constant weights will be added by SetupConstantLayers.
1145 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0], inputTensorIndexes[1]};
1146
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001147 if (inputs.size() == 3)
1148 {
1149 desc.m_BiasEnabled = true;
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001150
1151 // Add the biases input to the registration list, a constant layer will be added by SetupConstantLayers.
1152 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001153 }
1154
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001155 armnn::IConnectableLayer* layer = m_Network->AddConvolution3dLayer(desc, layerName.c_str());
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001156 ARMNN_ASSERT(layer != nullptr);
1157
1158 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1159 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1160
1161 // Register the input connection slots for the layer, connections are made after all layers have been created
Matthew Sloyan5d7b0a32021-10-18 13:07:49 +01001162 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001163
1164 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1165 // Register the output connection slots for the layer, connections are made after all layers have been created
1166 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1167 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1168}
Matthew Sloyan4d217c02021-10-07 11:48:58 +01001169#endif
Matthew Sloyaneb5f8102021-10-05 17:31:42 +01001170
Kevin May7d96b162021-02-03 17:38:41 +00001171void TfLiteParserImpl::ParseDepthwiseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001172{
1173 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1174
Mike Kelly0d77ae12022-01-07 17:42:27 +00001175 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1176 const auto* options = operatorPtr->builtin_options.AsDepthwiseConv2DOptions();
telsoa01c577f2c2018-08-31 09:22:23 +01001177
1178 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1179
1180 DepthwiseConvolution2dDescriptor desc;
1181 desc.m_BiasEnabled = false;
1182 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1183 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +00001184 desc.m_DataLayout = armnn::DataLayout::NHWC;
Matthew Jacksond6a9dee2019-07-22 13:53:24 +01001185 CHECKED_NON_NEGATIVE(options->depth_multiplier);
telsoa01c577f2c2018-08-31 09:22:23 +01001186
1187 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1188 CHECK_VALID_SIZE(inputs.size(), 2, 3);
1189 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1190 CHECK_VALID_SIZE(outputs.size(), 1);
Pablo Tellof0bd6832019-04-26 17:58:13 +01001191 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1192 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +00001193
telsoa01c577f2c2018-08-31 09:22:23 +01001194 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Jan Eilers7612bd62021-04-06 17:29:03 +01001195 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
telsoa01c577f2c2018-08-31 09:22:23 +01001196
Matteo Martincigh747ef822018-12-18 09:26:39 +00001197 // Assuming input is NHWC
telsoa01c577f2c2018-08-31 09:22:23 +01001198 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1199 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
Matteo Martincigh747ef822018-12-18 09:26:39 +00001200
1201 // TensorflowLite weights come in the format [1, H, W, I * M]
telsoa01c577f2c2018-08-31 09:22:23 +01001202 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1203 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1204
Pablo Tellof0bd6832019-04-26 17:58:13 +01001205 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1206 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1207 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1208 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +01001209
Jan Eilers53ef7952021-06-02 12:01:25 +01001210 // ArmNN uses the same filter tensor layout at TfLite [1, H, W, O] no need for any permutation
1211 auto filterTensor = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001212 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01001213 auto layerName = fmt::format("DepthwiseConv2D:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001214
1215 if (inputs.size() == 3)
1216 {
1217 desc.m_BiasEnabled = true;
1218 TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00001219 auto biasTensorAndData = CreateConstTensorNonPermuted(inputs[2], biasTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001220 layer = m_Network->AddDepthwiseConvolution2dLayer(desc,
Jan Eilers53ef7952021-06-02 12:01:25 +01001221 filterTensor,
Finn Williamsd4fa5452021-03-01 12:31:41 +00001222 Optional<ConstTensor>(biasTensorAndData),
telsoa01c577f2c2018-08-31 09:22:23 +01001223 layerName.c_str());
1224 }
1225 else
1226 {
1227 layer = m_Network->AddDepthwiseConvolution2dLayer(desc,
Jan Eilers53ef7952021-06-02 12:01:25 +01001228 filterTensor,
Matteo Martincighfc598e12019-05-14 10:36:13 +01001229 EmptyOptional(),
telsoa01c577f2c2018-08-31 09:22:23 +01001230 layerName.c_str());
1231 }
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001232 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01001233
Sadik Armagand109a4d2020-07-28 10:42:13 +01001234 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
jimfly01c25411c2018-11-14 17:47:22 +00001235 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001236
1237 // register the input connection slots for the layer, connections are made after all layers have been created
1238 // only the tensors for the inputs are relevant, exclude the const tensors
1239 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +00001240 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
telsoa01c577f2c2018-08-31 09:22:23 +01001241
jimfly01c25411c2018-11-14 17:47:22 +00001242 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +01001243 // register the output connection slots for the layer, connections are made after all layers have been created
1244 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1245 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1246}
1247
Kevin May7d96b162021-02-03 17:38:41 +00001248void TfLiteParserImpl::ParseDequantize(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsed66d142019-12-06 09:55:55 +00001249{
1250 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1251
1252 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1253 CHECK_VALID_SIZE(inputs.size(), 1);
1254
1255 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1256 CHECK_VALID_SIZE(outputs.size(), 1);
1257
James Ward58dec6b2020-09-11 17:32:44 +01001258 auto layerName = fmt::format("Dequantize:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsed66d142019-12-06 09:55:55 +00001259
1260 IConnectableLayer* layer = m_Network->AddDequantizeLayer(layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001261 ARMNN_ASSERT(layer != nullptr);
Finn Williamsed66d142019-12-06 09:55:55 +00001262
Sadik Armagand109a4d2020-07-28 10:42:13 +01001263 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Finn Williamsed66d142019-12-06 09:55:55 +00001264 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1265
1266 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1267 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1268
1269 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1270 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1271}
1272
Teresa Charlin3ab85482021-06-08 16:59:29 +01001273void TfLiteParserImpl::ParseExpandDims(size_t subgraphIndex, size_t operatorIndex)
1274{
1275 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1276
1277 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1278 CHECK_VALID_SIZE(inputs.size(), 2);
1279
1280 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1281 CHECK_VALID_SIZE(outputs.size(), 1);
1282
1283 auto layerName = fmt::format("ExpandDims:{}:{}", subgraphIndex, operatorIndex);
1284
1285 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1286 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1287
1288 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1289
1290 ReshapeDescriptor reshapeDesc;
Finn Williamsb49ed182021-06-29 15:50:08 +01001291
1292 if (outputTensorInfo.GetShape().AreAllDimensionsSpecified())
1293 {
1294 reshapeDesc.m_TargetShape = outputTensorInfo.GetShape();
1295 }
1296 else
1297 {
1298 int32_t axis = inputs[1]->shape[0];
1299
1300 int32_t inputDimSize = static_cast<int32_t>(inputTensorInfo.GetShape().GetNumDimensions());
1301
1302 if (axis > inputDimSize || axis < 0 - (inputDimSize + 1))
1303 {
1304 throw ParseException("axis must be in range [0 - (inputDimSize + 1), inputDimSize] inclusive");
1305 }
1306
1307 if(axis < 0)
1308 {
1309 axis = inputDimSize + axis + 1;
1310 }
1311
Rob Hughesd812a312021-08-06 13:10:53 +01001312 std::vector<unsigned int> shape(static_cast<unsigned int>(inputDimSize) + 1);
Finn Williamsb49ed182021-06-29 15:50:08 +01001313 unsigned int inputShapeIndex = 0;
1314 for (unsigned int i = 0; i < static_cast<unsigned int>(inputDimSize + 1); ++i)
1315 {
1316 if (i == static_cast<unsigned int>(axis))
1317 {
1318 shape[i] = 1;
1319 }
1320 else
1321 {
1322 shape[i] = inputTensorInfo.GetShape()[inputShapeIndex];
1323 ++inputShapeIndex;
1324 }
1325 }
1326
Rob Hughesd812a312021-08-06 13:10:53 +01001327 reshapeDesc.m_TargetShape = TensorShape(static_cast<unsigned int>(inputDimSize + 1), shape.data());
Finn Williamsb49ed182021-06-29 15:50:08 +01001328 }
Teresa Charlin3ab85482021-06-08 16:59:29 +01001329
1330 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
1331 ARMNN_ASSERT(layer != nullptr);
1332 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1333
1334 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1335 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1336
1337 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1338 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1339}
1340
Kevin May7d96b162021-02-03 17:38:41 +00001341void TfLiteParserImpl::ParseTranspose(size_t subgraphIndex, size_t operatorIndex)
Keith Davis4cd29a02019-09-09 14:49:20 +01001342{
1343 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1344
1345 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Kevin May85d92602019-09-27 17:21:06 +01001346 CHECK_VALID_SIZE(inputs.size(), 1, 2);
Keith Davis4cd29a02019-09-09 14:49:20 +01001347
1348 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1349 CHECK_VALID_SIZE(outputs.size(), 1);
1350
James Ward58dec6b2020-09-11 17:32:44 +01001351 auto layerName = fmt::format("Transpose:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly08759e22020-03-02 11:41:31 +00001352 TransposeDescriptor desc;
Keith Davis4cd29a02019-09-09 14:49:20 +01001353
josh minorba424d22019-11-13 10:55:17 -06001354 if (inputs.size() == 2)
Kevin May85d92602019-09-27 17:21:06 +01001355 {
1356 armnn::TensorInfo permuteTensorInfo = ToTensorInfo(inputs[1]);
1357 BufferRawPtr permuteBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
josh minorba424d22019-11-13 10:55:17 -06001358 auto numPermVecElements = permuteTensorInfo.GetNumElements();
1359 std::vector<unsigned int> permuteShape(numPermVecElements);
Kevin May85d92602019-09-27 17:21:06 +01001360 ::memcpy(permuteShape.data(), permuteBufferPtr->data.data(), permuteTensorInfo.GetNumBytes());
Mike Kelly08759e22020-03-02 11:41:31 +00001361 PermutationVector permutationVector(permuteShape.data(), permuteTensorInfo.GetNumElements());
Kevin May85d92602019-09-27 17:21:06 +01001362
Mike Kelly08759e22020-03-02 11:41:31 +00001363 desc = TransposeDescriptor(permutationVector);
Kevin May85d92602019-09-27 17:21:06 +01001364 }
1365
James Conroy05102392020-06-24 15:39:55 +01001366 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001367 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001368 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Keith Davis4cd29a02019-09-09 14:49:20 +01001369
James Conroy05102392020-06-24 15:39:55 +01001370 IConnectableLayer* layer = m_Network->AddTransposeLayer(desc, layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001371 ARMNN_ASSERT(layer != nullptr);
Keith Davis4cd29a02019-09-09 14:49:20 +01001372 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1373
1374 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1375 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1376
1377 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1378 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1379}
1380
Kevin May7d96b162021-02-03 17:38:41 +00001381void TfLiteParserImpl::ParseTransposeConv(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001382{
1383 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1384
Mike Kelly0d77ae12022-01-07 17:42:27 +00001385 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1386 const auto* options = operatorPtr->builtin_options.AsTransposeConvOptions();
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001387
1388 TransposeConvolution2dDescriptor desc;
1389 desc.m_BiasEnabled = false;
1390 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1391 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1392 desc.m_DataLayout = armnn::DataLayout::NHWC;
1393
1394 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
David Monahan61683802021-01-12 09:11:07 +00001395 if (inputs.size() == 4)
1396 {
1397 desc.m_BiasEnabled = true;
1398 }
1399 else
1400 {
1401 CHECK_VALID_SIZE(inputs.size(), 3);
1402 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001403
1404 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1405 CHECK_VALID_SIZE(outputs.size(), 1);
1406
Colm Donelan0ad3ef12020-07-03 15:54:28 +01001407 if (inputs[0])
1408 {
1409 armnn::TensorInfo tensorInfo = ToTensorInfo(inputs[0]);
1410 std::vector<int> output_shape(tensorInfo.GetNumElements());
1411 if (tensorInfo.GetDataType() == DataType::Signed32)
1412 {
1413 ::memcpy(output_shape.data(), GetBuffer(m_Model, inputs[0]->buffer)->data.data(), tensorInfo.GetNumBytes());
1414 }
1415 if (tensorInfo.GetDataType() == DataType::QAsymmU8)
1416 {
1417 for(unsigned int i=0; i < tensorInfo.GetNumElements(); i++)
1418 {
1419 output_shape[i] = GetBuffer(m_Model, inputs[0]->buffer)->data.data()[i];
1420 }
1421 }
1422 // Change from signed to unsigned int to store in TransposeConvolution2dDescriptor.
1423 for (int dimension : output_shape)
1424 {
1425 desc.m_OutputShape.push_back(static_cast<unsigned int>(dimension));
1426 }
1427 desc.m_OutputShapeEnabled = true;
1428 }
Matthew Jacksonccb25ea2019-08-20 17:18:33 +01001429 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[2]);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001430 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
1431
1432 // TfLite uses NHWC tensors
1433 const unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1434 const unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1435
1436 const unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1437 const unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1438
1439 CalcPadding(inputHeight,
1440 filterHeight,
1441 desc.m_StrideY,
1442 1, // DilationY
1443 desc.m_PadTop,
1444 desc.m_PadBottom,
1445 options->padding);
1446
1447 CalcPadding(inputWidth,
1448 filterWidth,
1449 desc.m_StrideX,
1450 1, // DilationX
1451 desc.m_PadLeft,
1452 desc.m_PadRight,
1453 options->padding);
1454
Finn Williamsd4fa5452021-03-01 12:31:41 +00001455 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001456
1457 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01001458 auto layerName = fmt::format("TransposeConv:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001459
David Monahan61683802021-01-12 09:11:07 +00001460 if (desc.m_BiasEnabled)
1461 {
1462 auto biasTensorInfo = ToTensorInfo(inputs[3]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00001463 auto biasConstTensor = CreateConstTensorNonPermuted(inputs[3], biasTensorInfo);
David Monahan61683802021-01-12 09:11:07 +00001464 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +00001465 filterTensorAndData,
1466 biasConstTensor,
David Monahan61683802021-01-12 09:11:07 +00001467 layerName.c_str());
1468 }
1469 else
1470 {
1471 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +00001472 filterTensorAndData,
David Monahan61683802021-01-12 09:11:07 +00001473 EmptyOptional(),
1474 layerName.c_str());
1475 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001476
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001477 ARMNN_ASSERT(layer != nullptr);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001478
Sadik Armagand109a4d2020-07-28 10:42:13 +01001479 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001480 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1481
1482 // only the tensors for the inputs are relevant, exclude the const (filter) tensor
1483 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Matthew Jacksonccb25ea2019-08-20 17:18:33 +01001484 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[2]});
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001485
1486 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1487 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1488}
1489
Kevin May7d96b162021-02-03 17:38:41 +00001490void TfLiteParserImpl::ParseAveragePool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001491{
1492 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Average);
1493}
1494
Kevin May7d96b162021-02-03 17:38:41 +00001495void TfLiteParserImpl::ParseBatchToSpaceND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001496{
1497 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1498
1499 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1500 CHECK_VALID_SIZE(inputs.size(), 3);
1501
1502 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1503 CHECK_VALID_SIZE(outputs.size(), 1);
1504
1505 armnn::TensorInfo blockShapeTensorInfo = ToTensorInfo(inputs[1]);
1506 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1507
1508 armnn::TensorInfo cropsTensorInfo = ToTensorInfo(inputs[2]);
1509 BufferRawPtr cropsBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1510
1511 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1512 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1513
1514 std::vector<unsigned int> cropsVector(cropsTensorInfo.GetNumElements());
1515 ::memcpy(cropsVector.data(), cropsBufferPtr->data.data(), cropsTensorInfo.GetNumBytes());
1516
1517 size_t step = 2;
1518 std::vector<std::pair<unsigned int, unsigned int>> crops;
1519 for (unsigned int i = 0; i < cropsTensorInfo.GetNumElements() / step; ++i)
1520 {
1521 crops.emplace_back(cropsVector[i * step], cropsVector[i * step + 1]);
1522 }
1523
1524 armnn::BatchToSpaceNdDescriptor desc;
1525 desc.m_BlockShape = blockShape;
1526 desc.m_Crops = crops;
1527 desc.m_DataLayout = armnn::DataLayout::NHWC;
1528
James Ward58dec6b2020-09-11 17:32:44 +01001529 auto layerName = fmt::format("BatchToSpaceND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001530
James Conroy05102392020-06-24 15:39:55 +01001531 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001532 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001533 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1534
1535 IConnectableLayer* layer = m_Network->AddBatchToSpaceNdLayer(desc, layerName.c_str());
1536 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001537 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1538
1539 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1540 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1541
1542 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1543 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1544}
1545
Kevin May7d96b162021-02-03 17:38:41 +00001546void TfLiteParserImpl::ParseL2Normalization(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson28c94572019-07-18 10:47:03 +01001547{
1548 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1549
1550 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1551 CHECK_VALID_SIZE(inputs.size(), 1);
1552
1553 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1554 CHECK_VALID_SIZE(outputs.size(), 1);
1555
1556 L2NormalizationDescriptor desc;
1557 desc.m_DataLayout = armnn::DataLayout::NHWC;
James Ward58dec6b2020-09-11 17:32:44 +01001558 auto layerName = fmt::format("L2Normalization:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson28c94572019-07-18 10:47:03 +01001559 IConnectableLayer* layer = m_Network->AddL2NormalizationLayer(desc, layerName.c_str());
1560
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001561 ARMNN_ASSERT(layer != nullptr);
Matthew Jackson28c94572019-07-18 10:47:03 +01001562
Sadik Armagand109a4d2020-07-28 10:42:13 +01001563 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jackson28c94572019-07-18 10:47:03 +01001564 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1565
1566 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1567 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1568
1569 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1570 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1571}
1572
Kevin May7d96b162021-02-03 17:38:41 +00001573void TfLiteParserImpl::ParseMaxPool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001574{
1575 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Max);
1576}
1577
Kevin May7d96b162021-02-03 17:38:41 +00001578void TfLiteParserImpl::ParseMaximum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001579{
1580 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1581
1582 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1583 CHECK_VALID_SIZE(inputs.size(), 2);
1584
1585 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1586 CHECK_VALID_SIZE(outputs.size(), 1);
1587
James Ward58dec6b2020-09-11 17:32:44 +01001588 auto layerName = fmt::format("Maximum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01001589
1590 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1591 TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1592 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001593
Sadik Armagand109a4d2020-07-28 10:42:13 +01001594 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001595 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1596
1597 IConnectableLayer* layer = m_Network->AddMaximumLayer(layerName.c_str());
1598 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001599 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1600
1601 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001602 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001603
1604 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1605 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1606}
1607
Kevin May7d96b162021-02-03 17:38:41 +00001608void TfLiteParserImpl::ParseMinimum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001609{
1610 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1611
1612 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1613 CHECK_VALID_SIZE(inputs.size(), 2);
1614
1615 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1616 CHECK_VALID_SIZE(outputs.size(), 1);
1617
James Ward58dec6b2020-09-11 17:32:44 +01001618 auto layerName = fmt::format("Minimum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01001619
1620 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1621 TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1622 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001623
Sadik Armagand109a4d2020-07-28 10:42:13 +01001624 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001625 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1626
1627 IConnectableLayer* layer = m_Network->AddMinimumLayer(layerName.c_str());
1628 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001629 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1630
1631 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001632 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001633
1634 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1635 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1636}
1637
Kevin May7d96b162021-02-03 17:38:41 +00001638void TfLiteParserImpl::ParsePool(size_t subgraphIndex,
1639 size_t operatorIndex,
1640 PoolingAlgorithm algorithm)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001641{
1642 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1643
Mike Kelly0d77ae12022-01-07 17:42:27 +00001644 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1645 const auto* options = operatorPtr->builtin_options.AsPool2DOptions();
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001646
1647 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1648
1649 std::string layerName;
1650
1651 switch (algorithm)
1652 {
1653 case PoolingAlgorithm::Average:
1654 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01001655 fmt::format("AveragePool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001656 break;
1657 case PoolingAlgorithm::Max:
1658 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01001659 fmt::format("MaxPool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001660 break;
1661 default:
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001662 ARMNN_ASSERT_MSG(false, "Unsupported Pooling Algorithm");
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001663 }
1664
1665 Pooling2dDescriptor desc;
1666
1667 desc.m_PoolType = algorithm;
1668 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1669 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1670 desc.m_PoolWidth = CHECKED_NON_NEGATIVE(options->filter_width);
1671 desc.m_PoolHeight = CHECKED_NON_NEGATIVE(options->filter_height);
1672 desc.m_PaddingMethod = PaddingMethod::Exclude;
1673 desc.m_OutputShapeRounding = OutputShapeRounding::Floor;
jimfly01c25411c2018-11-14 17:47:22 +00001674 desc.m_DataLayout = armnn::DataLayout::NHWC;
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001675
1676 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1677 CHECK_VALID_SIZE(inputs.size(), 1);
1678 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1679
1680 // assuming input is NHWC
1681 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1682 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1683
Pablo Tellof0bd6832019-04-26 17:58:13 +01001684 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, 1u,
1685 desc.m_PadTop, desc.m_PadBottom, options->padding);
1686 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, 1u,
1687 desc.m_PadLeft, desc.m_PadRight, options->padding);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001688
1689 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1690 CHECK_VALID_SIZE(outputs.size(), 1);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001691
Sadik Armagand109a4d2020-07-28 10:42:13 +01001692 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001693 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1694
1695 IConnectableLayer* layer = m_Network->AddPooling2dLayer(desc, layerName.c_str());
1696 ARMNN_ASSERT(layer != nullptr);
jimfly01c25411c2018-11-14 17:47:22 +00001697 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001698
1699 // register the input connection slots for the layer, connections are made after all layers have been created
1700 // only the tensors for the inputs are relevant, exclude the const tensors
1701 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +00001702 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001703
jimfly01c25411c2018-11-14 17:47:22 +00001704 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001705 // register the output connection slots for the layer, connections are made after all layers have been created
1706 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1707 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1708}
1709
Kevin May7d96b162021-02-03 17:38:41 +00001710void TfLiteParserImpl::ParseSlice(size_t subgraphIndex, size_t operatorIndex)
josh minorba424d22019-11-13 10:55:17 -06001711{
1712 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1713
1714 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1715 CHECK_VALID_SIZE(inputs.size(), 3);
1716 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1717 CHECK_VALID_SIZE(outputs.size(), 1);
1718
1719 SliceDescriptor desc;
1720
1721 // set begin tensor info for slice descriptor
1722 armnn::TensorInfo beginTensorInfo = ToTensorInfo(inputs[1]);
1723 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1724
1725 std::vector<unsigned int> begin(beginTensorInfo.GetNumElements());
1726 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
1727
1728 // set size tensor info for slice descriptor
1729 armnn::TensorInfo sizeTensorInfo = ToTensorInfo(inputs[2]);
1730 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1731
Mike Kelly7ba84d62021-09-10 15:27:19 +01001732 std::vector<int> signedSize(sizeTensorInfo.GetNumElements());
1733 ::memcpy(signedSize.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
josh minorba424d22019-11-13 10:55:17 -06001734 std::vector<unsigned int> size(sizeTensorInfo.GetNumElements());
Mike Kelly7ba84d62021-09-10 15:27:19 +01001735 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1736
1737 for (unsigned int i = 0; i < signedSize.size(); ++i)
1738 {
1739 int signedValue = signedSize[i];
Jim Flynnfca233e2021-09-23 12:16:53 +01001740
Mike Kelly7ba84d62021-09-10 15:27:19 +01001741 if (signedValue < -1 || signedValue > static_cast<int>(inputTensorInfo.GetShape()[i] - begin[i]))
1742 {
1743 throw ParseException(fmt::format("Invalid value for size {} size must be in range "
1744 "[-1, inputDimSize - begin] [-1, {}] inclusive {}",
1745 signedValue,
1746 inputTensorInfo.GetShape()[i] - begin[i],
1747 CHECK_LOCATION().AsString()));
1748 }
1749
1750 if (signedValue == -1)
1751 {
1752 size[i] = inputTensorInfo.GetShape()[i] - begin[i];
1753 }
1754 else
1755 {
1756 size[i] = static_cast<unsigned int>(signedValue);
1757 }
1758 }
1759
josh minorba424d22019-11-13 10:55:17 -06001760 desc = SliceDescriptor(begin, size);
1761
James Ward58dec6b2020-09-11 17:32:44 +01001762 auto layerName = fmt::format("Slice:{}:{}", subgraphIndex, operatorIndex);
josh minorba424d22019-11-13 10:55:17 -06001763
Sadik Armagand109a4d2020-07-28 10:42:13 +01001764 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001765 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1766
1767 IConnectableLayer* const layer = m_Network->AddSliceLayer(desc, layerName.c_str());
josh minorba424d22019-11-13 10:55:17 -06001768 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1769
1770 // register the input connection slots for the layer, connections are made after all layers have been created
1771 // only the tensors for the inputs are relevant, exclude the const tensors
1772 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1773 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1774
1775 // register the output connection slots for the layer, connections are made after all layers have been created
1776 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1777 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1778}
1779
Kevin May7d96b162021-02-03 17:38:41 +00001780void TfLiteParserImpl::ParseSoftmax(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001781{
1782 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00001783 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1784 const auto* options = operatorPtr->builtin_options.AsSoftmaxOptions();
telsoa01c577f2c2018-08-31 09:22:23 +01001785
1786 SoftmaxDescriptor desc;
1787 desc.m_Beta = options->beta;
1788
1789 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1790 CHECK_VALID_SIZE(inputs.size(), 1);
1791 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1792 CHECK_VALID_SIZE(outputs.size(), 1);
1793
James Ward58dec6b2020-09-11 17:32:44 +01001794 auto layerName = fmt::format("Softmax:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001795 IConnectableLayer* const layer = m_Network->AddSoftmaxLayer(desc, layerName.c_str());
1796
Sadik Armagand109a4d2020-07-28 10:42:13 +01001797 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
telsoa01c577f2c2018-08-31 09:22:23 +01001798 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1799
1800 // register the input connection slots for the layer, connections are made after all layers have been created
1801 // only the tensors for the inputs are relevant, exclude the const tensors
1802 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1803 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1804
1805 // register the output connection slots for the layer, connections are made after all layers have been created
1806 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1807 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1808}
1809
Kevin May7d96b162021-02-03 17:38:41 +00001810void TfLiteParserImpl::ParseSpaceToBatchND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001811{
1812 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1813
1814 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1815 CHECK_VALID_SIZE(inputs.size(), 3);
1816
1817 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1818 CHECK_VALID_SIZE(outputs.size(), 1);
1819
1820 armnn::TensorInfo blockShapeTensorInfo = ToTensorInfo(inputs[1]);
1821 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1822
1823 armnn::TensorInfo padListTensorInfo = ToTensorInfo(inputs[2]);
1824 BufferRawPtr padListBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1825
1826 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1827 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1828
1829 std::vector<unsigned int> padListVector(padListTensorInfo.GetNumElements());
1830 ::memcpy(padListVector.data(), padListBufferPtr->data.data(), padListTensorInfo.GetNumBytes());
1831
1832 size_t step = 2;
1833 std::vector<std::pair<unsigned int, unsigned int>> padList;
1834 for (unsigned int i = 0; i < padListTensorInfo.GetNumElements() / step; ++i)
1835 {
1836 padList.emplace_back(padListVector[i * step], padListVector[i * step + 1]);
1837 }
1838
1839 armnn::SpaceToBatchNdDescriptor desc;
1840 desc.m_BlockShape = blockShape;
1841 desc.m_PadList = padList;
1842 desc.m_DataLayout = armnn::DataLayout::NHWC;
1843
James Ward58dec6b2020-09-11 17:32:44 +01001844 auto layerName = fmt::format("SpaceToBatchND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001845
James Conroy05102392020-06-24 15:39:55 +01001846 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001847 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001848 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1849
1850 IConnectableLayer* layer = m_Network->AddSpaceToBatchNdLayer(desc, layerName.c_str());
1851 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001852 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1853
1854 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1855 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1856
1857 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1858 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1859}
1860
Teresa Charlin3ab85482021-06-08 16:59:29 +01001861armnn::TensorInfo TfLiteParserImpl::OutputShapeOfSqueeze(std::vector<uint32_t> squeezeDims,
Mike Kelly0d77ae12022-01-07 17:42:27 +00001862 const armnn::TensorInfo& inputTensorInfo)
telsoa01c577f2c2018-08-31 09:22:23 +01001863{
Teresa Charlin3ab85482021-06-08 16:59:29 +01001864 CHECK_VALID_SIZE(squeezeDims.size(), 0, 1, 2, 3, 4);
telsoa01c577f2c2018-08-31 09:22:23 +01001865 static const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
1866
1867 if (inputTensorInfo.GetNumDimensions() > 4)
1868 {
1869 std::stringstream ss;
1870 ss << "Input tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
1871 << " shape:" << inputTensorInfo.GetShape() << " "
1872 << CHECK_LOCATION().AsString();
1873 throw ParseException(ss.str());
1874 }
1875
1876 if (squeezeDims.empty())
1877 {
1878 squeezeDims.assign(dimensionSequence,
1879 dimensionSequence+inputTensorInfo.GetNumDimensions());
1880 }
1881
1882 std::vector<uint32_t> outputDims;
1883 for(unsigned int i = 0; i < inputTensorInfo.GetNumDimensions(); i++)
1884 {
1885 bool skipSqueeze = (std::find(squeezeDims.begin(), squeezeDims.end(), i) == squeezeDims.end());
1886 auto currentDimension = inputTensorInfo.GetShape()[i];
1887 if (skipSqueeze || currentDimension != 1)
1888 {
1889 outputDims.push_back(currentDimension);
1890 }
1891 }
1892
1893 if (outputDims.size() > 4)
1894 {
1895 std::stringstream ss;
1896 ss << "Output tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
1897 << " shape:" << inputTensorInfo.GetShape() << " "
1898 << CHECK_LOCATION().AsString();
1899 throw ParseException(ss.str());
1900 }
1901
1902 TensorShape outShape = TensorShape(static_cast<unsigned int>(outputDims.size()),
1903 outputDims.data());
1904
1905 // we need to preserve the tensor type and the quantization data as well
1906 TensorInfo outTensorInfo = inputTensorInfo;
1907 outTensorInfo.SetShape(outShape);
1908
1909 return outTensorInfo;
1910}
1911
Keith Davis0176fd82021-06-01 17:36:32 +01001912void TfLiteParserImpl::ParseShape(size_t subgraphIndex, size_t operatorIndex)
1913{
1914 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1915
1916 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1917 CHECK_VALID_SIZE(inputs.size(), 1);
1918 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1919 CHECK_VALID_SIZE(outputs.size(), 1);
1920
1921 auto layerName = fmt::format("Shape:{}:{}", subgraphIndex, operatorIndex);
1922
1923 IConnectableLayer* layer = m_Network->AddShapeLayer(layerName.c_str());
1924 ARMNN_ASSERT(layer != nullptr);
1925
1926
1927 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1928 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1929
1930 // Check if output tensor type is Signed32 or Signed64
1931 if (outputTensorInfo.GetDataType() != armnn::DataType::Signed32 &&
1932 outputTensorInfo.GetDataType() != armnn::DataType::Signed64)
1933 {
1934 throw ParseException(
1935 fmt::format(
1936 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
1937 CHECK_LOCATION().AsString()));
1938 }
1939
1940 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1941 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1942
1943 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1944 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1945}
1946
Kevin May7d96b162021-02-03 17:38:41 +00001947void TfLiteParserImpl::ParseSqueeze(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001948{
1949 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1950
1951 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1952 CHECK_VALID_SIZE(inputs.size(), 1);
1953
1954 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1955 CHECK_VALID_SIZE(outputs.size(), 1);
1956
1957 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1958 const auto * options = operatorPtr->builtin_options.AsSqueezeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01001959 auto layerName = fmt::format("Squeeze:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001960
1961 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Teresa Charlin3ab85482021-06-08 16:59:29 +01001962
1963 std::vector<uint32_t> squeezeDim;
1964 // A single negative dim index is interpreted as a negative index in python
1965 // Meaning the index will be the shape size plus the negative index value
1966 if (options->squeeze_dims.size() == 1 && options->squeeze_dims[0] < 0)
1967 {
1968 int32_t dim = static_cast<int32_t>(inputTensorInfo.GetShape().GetNumDimensions()) + options->squeeze_dims[0];
1969 squeezeDim.push_back(static_cast<uint32_t>(dim));
1970 }
1971 else
1972 {
1973 squeezeDim = AsUnsignedVector(options->squeeze_dims);
1974 }
1975
1976 armnn::TensorInfo outputTensorInfo = TfLiteParserImpl::OutputShapeOfSqueeze(squeezeDim, inputTensorInfo);
1977
James Conroy05102392020-06-24 15:39:55 +01001978 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
telsoa01c577f2c2018-08-31 09:22:23 +01001979
1980 ReshapeDescriptor reshapeDesc;
1981 reshapeDesc.m_TargetShape = outputTensorInfo.GetShape();
1982
telsoa01c577f2c2018-08-31 09:22:23 +01001983 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001984 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01001985 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1986
1987 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1988 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1989
1990 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1991 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1992}
1993
Kevin May7d96b162021-02-03 17:38:41 +00001994void TfLiteParserImpl::ParseStridedSlice(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves451d95b2019-02-12 22:59:22 -02001995{
1996 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1997
1998 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1999 CHECK_VALID_SIZE(inputs.size(), 4);
2000
2001 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2002 CHECK_VALID_SIZE(outputs.size(), 1);
2003
Mike Kelly0d77ae12022-01-07 17:42:27 +00002004 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2005 const auto* options = operatorPtr->builtin_options.AsStridedSliceOptions();
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002006
2007 StridedSliceDescriptor desc;
2008 desc.m_BeginMask = options->begin_mask;
2009 desc.m_EllipsisMask = options->ellipsis_mask;
2010 desc.m_EndMask = options->end_mask;
2011 desc.m_NewAxisMask = options->new_axis_mask;
2012 desc.m_ShrinkAxisMask = options->shrink_axis_mask;
2013 desc.m_DataLayout = armnn::DataLayout::NHWC;
2014
2015 armnn::TensorInfo beginTensorInfo = ToTensorInfo(inputs[1]);
2016 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2017
2018 std::vector<int> begin(beginTensorInfo.GetNumElements());
2019 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
2020
2021 armnn::TensorInfo endTensorInfo = ToTensorInfo(inputs[2]);
2022 BufferRawPtr endBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
2023
2024 std::vector<int> end(endTensorInfo.GetNumElements());
2025 ::memcpy(end.data(), endBufferPtr->data.data(), endTensorInfo.GetNumBytes());
2026
2027 armnn::TensorInfo strideTensorInfo = ToTensorInfo(inputs[3]);
2028 BufferRawPtr strideBufferPtr = GetBuffer(m_Model, inputs[3]->buffer);
2029
2030 std::vector<int> stride(strideTensorInfo.GetNumElements());
2031 ::memcpy(stride.data(), strideBufferPtr->data.data(), strideTensorInfo.GetNumBytes());
2032
2033 desc.m_Begin = begin;
2034 desc.m_End = end;
2035 desc.m_Stride = stride;
2036
James Ward58dec6b2020-09-11 17:32:44 +01002037 auto layerName = fmt::format("StridedSlice:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002038 IConnectableLayer* layer = m_Network->AddStridedSliceLayer(desc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002039 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002040
Sadik Armagand109a4d2020-07-28 10:42:13 +01002041 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02002042 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2043
2044 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2045 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2046
2047 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2048 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2049}
2050
Kevin May7d96b162021-02-03 17:38:41 +00002051void TfLiteParserImpl::ParseSub(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002052{
2053 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2054
Mike Kelly0d77ae12022-01-07 17:42:27 +00002055 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2056 const auto* options = operatorPtr->builtin_options.AsSubOptions();
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002057
2058 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2059 CHECK_VALID_SIZE(inputs.size(), 2);
2060
2061 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2062 CHECK_VALID_SIZE(outputs.size(), 1);
2063
2064 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2065 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2066
James Ward58dec6b2020-09-11 17:32:44 +01002067 auto layerName = fmt::format("Sub:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002068 IConnectableLayer* layer = m_Network->AddSubtractionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002069 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002070
Sadik Armagand109a4d2020-07-28 10:42:13 +01002071 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002072 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2073
2074 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002075 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02002076
2077 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2078
2079 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2080 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2081}
2082
Kevin May7d96b162021-02-03 17:38:41 +00002083void TfLiteParserImpl::ParseDiv(size_t subgraphIndex, size_t operatorIndex)
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302084{
2085 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2086
Mike Kelly0d77ae12022-01-07 17:42:27 +00002087 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2088 const auto* options = operatorPtr->builtin_options.AsDivOptions();
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302089
2090 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2091 CHECK_VALID_SIZE(inputs.size(), 2);
2092
2093 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2094 CHECK_VALID_SIZE(outputs.size(), 1);
2095
2096 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2097 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2098
James Ward58dec6b2020-09-11 17:32:44 +01002099 auto layerName = fmt::format("Div:{}:{}", subgraphIndex, operatorIndex);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302100 IConnectableLayer* layer = m_Network->AddDivisionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002101 ARMNN_ASSERT(layer != nullptr);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302102
Sadik Armagand109a4d2020-07-28 10:42:13 +01002103 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302104 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2105
2106 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002107 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Darshan Patel42b3d7d2020-05-25 22:30:07 +05302108 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2109
2110 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2111 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2112}
2113
Kevin May7d96b162021-02-03 17:38:41 +00002114void TfLiteParserImpl::ParseAdd(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002115{
2116 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2117
Mike Kelly0d77ae12022-01-07 17:42:27 +00002118 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2119 const auto* options = operatorPtr->builtin_options.AsAddOptions();
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002120
2121 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2122 CHECK_VALID_SIZE(inputs.size(), 2);
2123
2124 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2125 CHECK_VALID_SIZE(outputs.size(), 1);
2126
Bruno Goncalves9c761a62018-12-27 14:20:35 -02002127 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2128 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2129
James Ward58dec6b2020-09-11 17:32:44 +01002130 auto layerName = fmt::format("Add:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002131 IConnectableLayer* layer = m_Network->AddAdditionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002132 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002133
Sadik Armagand109a4d2020-07-28 10:42:13 +01002134 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002135 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2136
2137 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002138 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02002139 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2140
2141 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2142 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2143}
2144
Kevin May7d96b162021-02-03 17:38:41 +00002145void TfLiteParserImpl::ParseMul(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002146{
2147 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2148
Mike Kelly0d77ae12022-01-07 17:42:27 +00002149 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2150 const auto* options = operatorPtr->builtin_options.AsMulOptions();
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002151
2152 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2153 CHECK_VALID_SIZE(inputs.size(), 2);
2154
2155 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2156 CHECK_VALID_SIZE(outputs.size(), 1);
2157
Bruno Goncalves9c761a62018-12-27 14:20:35 -02002158 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2159 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
2160
James Ward58dec6b2020-09-11 17:32:44 +01002161 auto layerName = fmt::format("Mul:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002162 IConnectableLayer* layer = m_Network->AddMultiplicationLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002163 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002164
Sadik Armagand109a4d2020-07-28 10:42:13 +01002165 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002166 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2167
2168 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01002169 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesf803f782018-12-18 13:40:30 -02002170 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2171
2172 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2173 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2174}
2175
Kevin May7d96b162021-02-03 17:38:41 +00002176void TfLiteParserImpl::ParseMean(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002177{
2178 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2179
2180 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2181
2182 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2183 CHECK_VALID_SIZE(outputs.size(), 1);
2184
2185 armnn::TensorInfo dimTensorInfo = ToTensorInfo(inputs[1]);
2186 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2187
2188 armnn::MeanDescriptor desc;
2189 std::vector<unsigned int> axis(dimTensorInfo.GetNumElements());
2190 ::memcpy(axis.data(), bufferPtr->data.data(), dimTensorInfo.GetNumBytes());
2191 desc.m_Axis = axis;
2192
2193 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002194 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002195
2196 desc.m_KeepDims =
2197 inputTensorInfo.GetNumDimensions() == outputTensorInfo.GetNumDimensions() ?
2198 true : false;
2199
James Ward58dec6b2020-09-11 17:32:44 +01002200 auto layerName = fmt::format("Mean:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002201 IConnectableLayer* layer = m_Network->AddMeanLayer(desc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002202 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02002203
2204 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2205
2206 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2207 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2208
2209 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2210 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2211}
2212
Kevin May7d96b162021-02-03 17:38:41 +00002213void TfLiteParserImpl::ParsePad(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002214{
2215 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2216
Kevin May7d96b162021-02-03 17:38:41 +00002217 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002218
Kevin May7d96b162021-02-03 17:38:41 +00002219 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002220 CHECK_VALID_SIZE(outputs.size(), 1);
2221
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00002222 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002223 armnn::TensorInfo padTensorInfo = ToTensorInfo(inputs[1]);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002224
Mike Kelly0d77ae12022-01-07 17:42:27 +00002225 std::vector<unsigned int> padBuffer = GetUIntBuffer(padTensorInfo, m_Model, inputs[1]->buffer);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002226
2227 size_t step = 2;
2228 armnn::PadDescriptor desc;
Mike Kelly0d77ae12022-01-07 17:42:27 +00002229 auto opcode = GetOpCode(m_Model, subgraphIndex, operatorIndex);
2230
2231 if (opcode == tflite::BuiltinOperator_PAD)
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00002232 {
Mike Kelly0d77ae12022-01-07 17:42:27 +00002233 CHECK_VALID_SIZE(inputs.size(), 2);
2234
2235 if (inputTensorInfo.IsQuantized())
2236 {
2237 desc.m_PadValue = static_cast<float>(inputTensorInfo.GetQuantizationOffset());
2238 }
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00002239 }
Mike Kelly0d77ae12022-01-07 17:42:27 +00002240 else if (opcode == tflite::BuiltinOperator_PADV2)
2241 {
2242 CHECK_VALID_SIZE(inputs.size(), 3);
2243
2244 armnn::TensorInfo padValueTensorInfo = ToTensorInfo(inputs[2]);
2245
2246 if (padValueTensorInfo.GetNumElements() != 1)
2247 {
2248 ARMNN_THROW_PARSE_EXCEPTION("Multiple padding values are not supported in PADV2");
2249 }
2250 BufferRawPtr padValueBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
2251
2252 // Get the pad value from the input tensor
2253 if (padValueBufferPtr->data.size() > 0)
2254 {
2255 switch (padValueTensorInfo.GetDataType())
2256 {
2257 case armnn::DataType::Float32:
2258 {
2259 std::vector<float> padValueBuffer(padValueTensorInfo.GetNumElements());
2260 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2261 desc.m_PadValue = padValueBuffer[0];
2262 break;
2263 }
2264 case armnn::DataType::QAsymmU8:
2265 {
2266 std::vector<uint8_t> padValueBuffer(padValueTensorInfo.GetNumElements());
2267 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2268 desc.m_PadValue = armnn::Dequantize<uint8_t>(padValueBuffer[0],
2269 padValueTensorInfo.GetQuantizationScale(),
2270 padValueTensorInfo.GetQuantizationOffset());
2271 break;
2272 }
2273 case armnn::DataType::QAsymmS8:
2274 case armnn::DataType::QSymmS8:
2275 {
2276 std::vector<int8_t> padValueBuffer(padValueTensorInfo.GetNumElements());
2277 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2278 desc.m_PadValue = armnn::Dequantize<int8_t>(padValueBuffer[0],
2279 padValueTensorInfo.GetQuantizationScale(),
2280 padValueTensorInfo.GetQuantizationOffset());
2281 break;
2282 }
2283 default: ARMNN_THROW_PARSE_EXCEPTION("Unsupported DataType");
2284 }
2285 }
2286 else if (inputTensorInfo.IsQuantized())
2287 {
2288 desc.m_PadValue = static_cast<float>(inputTensorInfo.GetQuantizationOffset());
2289 }
2290 }
2291
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002292 for (unsigned int i = 0; i < padTensorInfo.GetNumElements() / step; ++i)
2293 {
2294 desc.m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
2295 }
2296
Mike Kelly0d77ae12022-01-07 17:42:27 +00002297 auto layerName = (opcode == tflite::BuiltinOperator_PAD) ? fmt::format("Pad:{}:{}", subgraphIndex, operatorIndex)
2298 : fmt::format("PadV2:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002299 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01002300
2301 IConnectableLayer* layer = m_Network->AddPadLayer(desc, layerName.c_str());
2302 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02002303 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2304
2305 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2306 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2307
2308 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2309 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2310}
2311
Matthew Sloyanaf3a4ef2021-10-22 15:48:12 +01002312void TfLiteParserImpl::ParseMirrorPad(size_t subgraphIndex, size_t operatorIndex)
2313{
2314 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2315
2316 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2317 CHECK_VALID_SIZE(inputs.size(), 2);
2318
2319 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2320 CHECK_VALID_SIZE(outputs.size(), 1);
2321
2322 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2323
2324 armnn::TensorInfo padTensorInfo = ToTensorInfo(inputs[1]);
2325 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2326
2327 std::vector<unsigned int> padBuffer(padTensorInfo.GetNumElements());
2328 ::memcpy(padBuffer.data(), bufferPtr->data.data(), padTensorInfo.GetNumBytes());
2329
2330 size_t step = 2;
2331 armnn::PadDescriptor desc;
2332 for (unsigned int i = 0; i < padTensorInfo.GetNumElements() / step; ++i)
2333 {
2334 desc.m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
2335 }
2336
2337 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2338 const auto* options = operatorPtr->builtin_options.AsMirrorPadOptions();
2339
2340 if (options->mode == tflite::MirrorPadMode_REFLECT)
2341 {
2342 desc.m_PaddingMode = PaddingMode::Reflect;
2343 }
2344 else if (options->mode == tflite::MirrorPadMode_SYMMETRIC)
2345 {
2346 desc.m_PaddingMode = PaddingMode::Symmetric;
2347 }
2348 else
2349 {
2350 ARMNN_THROW_PARSE_EXCEPTION("PaddingMode must be either REFLECT or SYMMETRIC");
2351 }
2352
2353 // If padding mode is Reflect then both paddings must be no greater than inputShape(i) - 1.
2354 // If padding mode is Symmetric then both paddings must be no greater than inputShape(i).
2355 auto inputShape = inputTensorInfo.GetShape();
2356 auto padList = desc.m_PadList;
2357
2358 const unsigned int isReflect = static_cast<unsigned int>(desc.m_PaddingMode == PaddingMode::Reflect);
2359 for(unsigned int i = 0; i < padList.size(); ++i)
2360 {
2361 if(padList.at(i).first > (inputShape[i] - isReflect) ||
2362 padList.at(i).second > (inputShape[i] - isReflect))
2363 {
2364 ARMNN_THROW_PARSE_EXCEPTION("Padding values must be less (Reflect) or "
2365 "equal (Symmetric) to the dimension size.");
2366 }
2367 }
2368
2369 auto layerName = fmt::format("MirrorPad:{}:{}", subgraphIndex, operatorIndex);
2370 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
2371
2372 IConnectableLayer* layer = m_Network->AddPadLayer(desc, layerName.c_str());
2373 ARMNN_ASSERT(layer != nullptr);
2374 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2375
2376 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2377 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2378
2379 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2380 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2381}
2382
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01002383void TfLiteParserImpl::ParsePrelu(size_t subgraphIndex, size_t operatorIndex)
2384{
2385 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2386
2387 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2388 CHECK_VALID_SIZE(inputs.size(), 2);
2389
2390 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2391 CHECK_VALID_SIZE(outputs.size(), 1);
2392
2393 auto layerName = fmt::format("Prelu:{}:{}", subgraphIndex, operatorIndex);
2394
2395 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2396 armnn::TensorInfo alphaTensorInfo = ToTensorInfo(inputs[1]);
2397 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
2398 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
2399
2400 IConnectableLayer* layer = m_Network->AddPreluLayer(layerName.c_str());
2401 ARMNN_ASSERT(layer != nullptr);
2402 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2403
2404 if (IsConstTensor(inputs[1]))
2405 {
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01002406 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawaratbf99b5f2021-05-27 09:55:43 +01002407 armnn::IInputSlot* slot = &(layer->GetInputSlot(0));
2408 RegisterConsumerOfTensor(subgraphIndex, inputTensorIndexes[0], slot);
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01002409
2410 auto alphaTensorAndData = CreateConstTensorNonPermuted(inputs[1], alphaTensorInfo);
2411 std::string constLayerName = fmt::format("Constant:{}", inputs[1]->name);
2412 IConnectableLayer* constLayer =
2413 m_Network->AddConstantLayer(alphaTensorAndData, constLayerName.c_str());
2414 ARMNN_ASSERT(constLayer != nullptr);
2415
2416 constLayer->GetOutputSlot(0).SetTensorInfo(alphaTensorInfo);
2417 constLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(1));
2418 RegisterOutputSlots(subgraphIndex,
2419 VIRTUAL_OPERATOR_ID,
2420 constLayer,
2421 { inputTensorIndexes[1] });
2422 }
2423 else
2424 {
2425 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2426 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIndexes);
2427 }
2428
2429 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2430 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2431}
2432
Kevin May7d96b162021-02-03 17:38:41 +00002433void TfLiteParserImpl::ParseQuantize(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan66dedc72019-12-10 16:32:07 +00002434{
2435 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2436
2437 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2438 CHECK_VALID_SIZE(inputs.size(), 1);
2439
2440 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2441 CHECK_VALID_SIZE(outputs.size(), 1);
2442
James Ward58dec6b2020-09-11 17:32:44 +01002443 auto layerName = fmt::format("Quantize:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan66dedc72019-12-10 16:32:07 +00002444
2445 IConnectableLayer* layer = m_Network->AddQuantizeLayer(layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002446 ARMNN_ASSERT(layer != nullptr);
Sadik Armagan66dedc72019-12-10 16:32:07 +00002447
Sadik Armagand109a4d2020-07-28 10:42:13 +01002448 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan66dedc72019-12-10 16:32:07 +00002449 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2450
2451 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2452 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2453
2454 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2455 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2456}
Finn Williamsc42c3842019-01-22 14:18:11 +00002457
Kevin May7d96b162021-02-03 17:38:41 +00002458void TfLiteParserImpl::ParseRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01002459{
Finn Williamsc42c3842019-01-22 14:18:11 +00002460 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::ReLu);
Sadik Armagan58f39192018-09-17 14:14:39 +01002461}
2462
Kevin May7d96b162021-02-03 17:38:41 +00002463void TfLiteParserImpl::ParseRelu6(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01002464{
Finn Williamsc42c3842019-01-22 14:18:11 +00002465 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::BoundedReLu);
2466}
Sadik Armagan58f39192018-09-17 14:14:39 +01002467
Kevin May7d96b162021-02-03 17:38:41 +00002468void TfLiteParserImpl::ParseLeakyRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan12239e72020-05-27 11:06:17 +01002469{
Jan Eilers2f746b32020-07-28 14:00:06 +01002470 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::LeakyReLu);
Sadik Armagan12239e72020-05-27 11:06:17 +01002471}
2472
Kevin May7d96b162021-02-03 17:38:41 +00002473void TfLiteParserImpl::ParseLogistic(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsc42c3842019-01-22 14:18:11 +00002474{
2475 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::Sigmoid);
2476}
2477
Kevin May7d96b162021-02-03 17:38:41 +00002478void TfLiteParserImpl::ParseTanH(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd99851762019-04-09 09:37:38 +01002479{
2480 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::TanH);
2481}
2482
Kevin May7d96b162021-02-03 17:38:41 +00002483void TfLiteParserImpl::ParseElu(size_t subgraphIndex, size_t operatorIndex)
Matthew Sloyan7515d072020-12-16 12:50:01 +00002484{
2485 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::Elu);
2486}
2487
Kevin May7d96b162021-02-03 17:38:41 +00002488void TfLiteParserImpl::ParseHardSwish(size_t subgraphIndex, size_t operatorIndex)
Jan Eilers2f746b32020-07-28 14:00:06 +01002489{
2490 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::HardSwish);
2491}
Finn Williamsc42c3842019-01-22 14:18:11 +00002492
Kevin May7d96b162021-02-03 17:38:41 +00002493void TfLiteParserImpl::ParseActivation(size_t subgraphIndex, size_t operatorIndex, ActivationFunction activationType)
Finn Williamsc42c3842019-01-22 14:18:11 +00002494{
2495 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00002496 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Jan Eilers8eb25602020-03-09 12:13:48 +00002497 IgnoreUnused(operatorPtr);
Sadik Armagan58f39192018-09-17 14:14:39 +01002498
2499 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2500 CHECK_VALID_SIZE(inputs.size(), 1);
2501
2502 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2503 CHECK_VALID_SIZE(outputs.size(), 1);
2504
James Ward58dec6b2020-09-11 17:32:44 +01002505 auto layerName = fmt::format("Activation:");
Sadik Armagan58f39192018-09-17 14:14:39 +01002506 ActivationDescriptor activationDesc;
Finn Williamsc42c3842019-01-22 14:18:11 +00002507 activationDesc.m_Function = activationType;
2508
2509 switch (activationType)
2510 {
2511 case ActivationFunction::ReLu:
2512 {
James Ward58dec6b2020-09-11 17:32:44 +01002513 layerName += fmt::format("RELU:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002514 break;
2515 }
2516 case ActivationFunction::BoundedReLu:
2517 {
James Ward58dec6b2020-09-11 17:32:44 +01002518 layerName += fmt::format("RELU6:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002519 activationDesc.m_A = 6.0f;
2520 activationDesc.m_B = 0.0f;
2521 break;
2522 }
2523 case ActivationFunction::Sigmoid:
2524 {
James Ward58dec6b2020-09-11 17:32:44 +01002525 layerName += fmt::format("SIGMOID:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002526 break;
2527 }
Nina Drozd99851762019-04-09 09:37:38 +01002528 case ActivationFunction::TanH:
2529 {
James Ward58dec6b2020-09-11 17:32:44 +01002530 layerName += fmt::format("TANH:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd99851762019-04-09 09:37:38 +01002531 activationDesc.m_A = 1.0f;
2532 activationDesc.m_B = 1.0f;
2533 break;
2534 }
Sadik Armagan12239e72020-05-27 11:06:17 +01002535 case ActivationFunction::LeakyReLu:
2536 {
James Ward58dec6b2020-09-11 17:32:44 +01002537 layerName += fmt::format("LEAKYRELU:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00002538 const auto* options = operatorPtr->builtin_options.AsLeakyReluOptions();
Sadik Armagan12239e72020-05-27 11:06:17 +01002539 activationDesc.m_A = options->alpha;
2540 break;
2541 }
Matthew Sloyan7515d072020-12-16 12:50:01 +00002542 case ActivationFunction::Elu:
2543 {
2544 layerName += fmt::format("ELU:{}:{}", subgraphIndex, operatorIndex);
2545 activationDesc.m_A = 1.0f;
2546 break;
2547 }
Jan Eilers2f746b32020-07-28 14:00:06 +01002548 case ActivationFunction::HardSwish:
Matthew Sloyan7515d072020-12-16 12:50:01 +00002549 {
James Ward58dec6b2020-09-11 17:32:44 +01002550 layerName += fmt::format("HARDSWISH:{}:{}", subgraphIndex, operatorIndex);
Jan Eilers2f746b32020-07-28 14:00:06 +01002551 break;
Matthew Sloyan7515d072020-12-16 12:50:01 +00002552 }
Finn Williamsc42c3842019-01-22 14:18:11 +00002553 default:
2554 {
2555 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002556 fmt::format("Unexpected ActivationFunction[{}] when creating layerName {} ",
2557 static_cast<int>(activationType), CHECK_LOCATION().AsString()));
Finn Williamsc42c3842019-01-22 14:18:11 +00002558 }
2559 }
2560
2561 IConnectableLayer* const layer = m_Network->AddActivationLayer(activationDesc, layerName.c_str());
Sadik Armagan58f39192018-09-17 14:14:39 +01002562
Sadik Armagand109a4d2020-07-28 10:42:13 +01002563 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan58f39192018-09-17 14:14:39 +01002564 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2565
2566 // register the input connection slots for the layer, connections are made after all layers have been created
2567 // only the tensors for the inputs are relevant, exclude the const tensors
2568 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2569 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2570
2571 // register the output connection slots for the layer, connections are made after all layers have been created
2572 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2573 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2574}
Mike Kelly0d77ae12022-01-07 17:42:27 +00002575armnn::TensorInfo TfLiteParserImpl::OutputShapeOfReshape(const armnn::TensorInfo& inputTensorInfo,
2576 const std::vector<int32_t>& targetDimsIn)
Sadikb94967b2018-09-19 15:30:00 +01002577{
2578 std::vector<unsigned int> outputDims(targetDimsIn.begin(), targetDimsIn.end());
2579 const auto stretchDim = std::find(targetDimsIn.begin(), targetDimsIn.end(), -1);
2580
2581 if (stretchDim != targetDimsIn.end())
2582 {
2583 if (std::find(std::next(stretchDim), targetDimsIn.end(), -1) != targetDimsIn.end())
2584 {
2585 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002586 fmt::format("At most one component of shape can be -1 {}", CHECK_LOCATION().AsString()));
Sadikb94967b2018-09-19 15:30:00 +01002587 }
2588
2589 auto targetNumElements =
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002590 armnn::numeric_cast<unsigned int>(
Sadikb94967b2018-09-19 15:30:00 +01002591 std::accumulate(targetDimsIn.begin(), targetDimsIn.end(), -1, std::multiplies<int32_t>()));
2592
2593 auto stretchIndex = static_cast<size_t>(std::distance(targetDimsIn.begin(), stretchDim));
2594 outputDims[stretchIndex] = inputTensorInfo.GetNumElements() / targetNumElements;
2595 }
2596
2597 TensorShape outputShape = TensorShape(static_cast<unsigned int>(outputDims.size()), outputDims.data());
2598
2599 TensorInfo reshapeInfo = inputTensorInfo;
2600 reshapeInfo.SetShape(outputShape);
2601
2602 return reshapeInfo;
2603}
2604
Kevin May7d96b162021-02-03 17:38:41 +00002605void TfLiteParserImpl::ParseReshape(size_t subgraphIndex, size_t operatorIndex)
Sadikb94967b2018-09-19 15:30:00 +01002606{
2607 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2608
2609 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01002610
2611 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2612 CHECK_VALID_SIZE(outputs.size(), 1);
2613
Mike Kelly0d77ae12022-01-07 17:42:27 +00002614 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2615 const auto* options = operatorPtr->builtin_options.AsReshapeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01002616 auto layerName = fmt::format("Reshape:{}:{}", subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01002617
2618 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
kevmay0171972a82018-12-17 14:28:03 +00002619 armnn::TensorInfo actualOutputTensorInfo = ToTensorInfo(outputs[0]);
James Conroy05102392020-06-24 15:39:55 +01002620 CheckMatchingQuantization(inputTensorInfo, actualOutputTensorInfo, layerName, "Input 0", "Output 0");
Derek Lambertic9e52792020-03-11 11:42:26 +00002621
Jan Eilersbac9b352020-07-13 13:40:24 +01002622 // Extracting new shape for the output
2623 // There are two ways it can be passed
2624 // * First is to define the target shape in the operator built-in options
2625 // * Second is to pass it as a second input tensor
Derek Lambertic9e52792020-03-11 11:42:26 +00002626 std::vector<int32_t> targetShape;
Jan Eilersbac9b352020-07-13 13:40:24 +01002627 bool targetShapeFound = false;
2628 // Check if built-in options were given
2629 if (options != nullptr)
Derek Lambertic9e52792020-03-11 11:42:26 +00002630 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002631 // make sure the parameter is given
2632 if (options->new_shape.empty() == false)
Derek Lambertic9e52792020-03-11 11:42:26 +00002633 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002634 targetShape = options->new_shape;
2635 targetShapeFound = true;
Derek Lambertif4a953f2020-03-17 14:25:57 +00002636 }
Derek Lambertic9e52792020-03-11 11:42:26 +00002637 }
Jan Eilersbac9b352020-07-13 13:40:24 +01002638
2639 // If there is no built-in option given or if the built-in new_shape parameter was empty
2640 if (!targetShapeFound)
Derek Lambertic9e52792020-03-11 11:42:26 +00002641 {
Teresa Charlin6a056a42021-12-01 10:25:43 +00002642 // Check for a second input tensor
2643 if (inputs.size() > 1 && inputs[1] != nullptr)
Jan Eilersbac9b352020-07-13 13:40:24 +01002644 {
2645 if (inputs[1]->is_variable)
2646 {
2647 ARMNN_THROW_PARSE_EXCEPTION( "Target shapes defined in non-const input tensors is not supported");
2648 }
2649
2650 if (inputs[1]->shape.size() != 1)
2651 {
2652 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not a 1D tensor");
2653 }
2654
2655 if (inputs[1]->type != tflite::TensorType_INT32)
2656 {
2657 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not an int32 type");
2658 }
2659
Teresa Charlin6a056a42021-12-01 10:25:43 +00002660 // Extract target shape from input
2661 auto bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2662 auto values = reinterpret_cast<const int32_t*>(bufferPtr->data.data());
Cathal Corbettd2f73232021-12-10 13:38:52 +00002663 if (values)
Sadik Armagan19a1c032021-01-20 12:17:00 +00002664 {
Cathal Corbettd2f73232021-12-10 13:38:52 +00002665 for (int i = 0; i < inputs[1]->shape[0]; ++i)
2666 {
2667 targetShape.push_back(values[i]);
2668 }
Sadik Armagan19a1c032021-01-20 12:17:00 +00002669 }
Cathal Corbettd2f73232021-12-10 13:38:52 +00002670 else
Jan Eilersbac9b352020-07-13 13:40:24 +01002671 {
Cathal Corbettd2f73232021-12-10 13:38:52 +00002672 try
2673 {
2674 // We attempt to infer during Runtime.
2675 TensorShape reshapeShapes = ToTensorInfo(inputs[1]).GetShape();
2676 // The parser only supports shape (batch, -1) or (-1) for non-constant shape input.
2677 if (reshapeShapes[0] > 2)
2678 {
2679 throw ParseException(fmt::format("Invalid input shape '{}' in Reshape layer '{}' {}. "
2680 "When inferring during runtime, the parser only supports "
2681 "shape (batch, -1) or (-1) for target shape input.",
2682 reshapeShapes[0],
2683 layerName,
2684 CHECK_LOCATION().AsString()));
2685 }
2686
2687 const int32_t numInputElements = inputTensorInfo.GetNumElements();
2688 const int32_t inputTensorShape = inputTensorInfo.GetShape()[0];
2689 if (reshapeShapes[0] == 1)
2690 {
2691 targetShape = {numInputElements};
2692 }
2693 else if (reshapeShapes[0] == 2)
2694 {
2695 targetShape = {inputTensorShape, numInputElements / inputTensorShape};
2696 }
2697 }
2698 catch (const std::exception& exc)
2699 {
2700 ARMNN_THROW_PARSE_EXCEPTION("Failed attempt to infer during runtime the target shape input for "
2701 "Reshape operation. Reshape operator target shape input buffer data "
2702 "is null. " << exc.what());
2703 }
Jan Eilersbac9b352020-07-13 13:40:24 +01002704 }
2705 }
2706 else
Derek Lambertic9e52792020-03-11 11:42:26 +00002707 {
2708 ARMNN_THROW_PARSE_EXCEPTION("Target shape not defined in reshape parameters or input tensor. "
2709 "At least one method required");
2710 }
Derek Lambertic9e52792020-03-11 11:42:26 +00002711 }
2712
kevmay0171972a82018-12-17 14:28:03 +00002713 armnn::TensorInfo reshapeOutputTensorInfo =
Kevin May7d96b162021-02-03 17:38:41 +00002714 TfLiteParserImpl::OutputShapeOfReshape(inputTensorInfo, targetShape);
Sadikb94967b2018-09-19 15:30:00 +01002715
kevmay0171972a82018-12-17 14:28:03 +00002716 // Check for valid input size and that reshape parameters equal output shape
Aron Virginas-Tar70672f62019-01-23 14:00:00 +00002717 const armnn::TensorShape& reshapeOutputTensorShape = reshapeOutputTensorInfo.GetShape();
2718 if (inputs.size() > 1 && !CheckShape(reshapeOutputTensorShape, outputs[0]->shape))
kevmay0171972a82018-12-17 14:28:03 +00002719 {
2720 std::stringstream ss;
2721 ss << "New shape defined in reshape parameters "
Aron Virginas-Tar70672f62019-01-23 14:00:00 +00002722 << reshapeOutputTensorShape
kevmay0171972a82018-12-17 14:28:03 +00002723 << " does not equal output shape "
2724 << actualOutputTensorInfo.GetShape()
2725 << ": "
2726 << CHECK_LOCATION().AsString();
2727 throw ParseException(ss.str());
2728 }
2729
Sadikb94967b2018-09-19 15:30:00 +01002730 ReshapeDescriptor reshapeDesc;
kevmay0171972a82018-12-17 14:28:03 +00002731 reshapeDesc.m_TargetShape = reshapeOutputTensorInfo.GetShape();
Sadikb94967b2018-09-19 15:30:00 +01002732
Sadikb94967b2018-09-19 15:30:00 +01002733 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002734 ARMNN_ASSERT(layer != nullptr);
kevmay0171972a82018-12-17 14:28:03 +00002735 layer->GetOutputSlot(0).SetTensorInfo(reshapeOutputTensorInfo);
Sadikb94967b2018-09-19 15:30:00 +01002736
2737 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2738 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2739
2740 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2741 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2742}
2743
Kevin May7d96b162021-02-03 17:38:41 +00002744void TfLiteParserImpl::ParseResizeBilinear(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002745{
Sadik Armagana3b31f02019-12-05 09:08:53 +00002746 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::Bilinear);
2747}
2748
Kevin May7d96b162021-02-03 17:38:41 +00002749void TfLiteParserImpl::ParseResizeNearestNeighbor(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagana3b31f02019-12-05 09:08:53 +00002750{
2751 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::NearestNeighbor);
2752}
2753
Kevin May7d96b162021-02-03 17:38:41 +00002754void TfLiteParserImpl::ParseResize(size_t subgraphIndex, size_t operatorIndex, ResizeMethod resizeMethod)
Sadik Armagana3b31f02019-12-05 09:08:53 +00002755{
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002756 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2757
2758 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2759 CHECK_VALID_SIZE(inputs.size(), 2);
2760
2761 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2762 CHECK_VALID_SIZE(outputs.size(), 1);
2763
2764 armnn::TensorInfo sizeTensorInfo = ToTensorInfo(inputs[1]);
2765
2766 // Data for the parsed tensor args (size) must be stored locally.
2767 std::vector<int32_t> sizeTensorData(sizeTensorInfo.GetNumElements());
2768
2769 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2770 ::memcpy(sizeTensorData.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
2771
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01002772 ResizeDescriptor desc;
Sadik Armagana3b31f02019-12-05 09:08:53 +00002773 desc.m_Method = resizeMethod;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002774 desc.m_TargetHeight = static_cast<uint32_t> (sizeTensorData[0]);
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01002775 desc.m_TargetWidth = static_cast<uint32_t> (sizeTensorData[1]);
2776 desc.m_DataLayout = armnn::DataLayout::NHWC;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002777
James Ward58dec6b2020-09-11 17:32:44 +01002778 auto layerName = fmt::format("Resize:");
Sadik Armagana3b31f02019-12-05 09:08:53 +00002779
2780 switch (resizeMethod)
2781 {
2782 case ResizeMethod::Bilinear:
2783 {
James Ward58dec6b2020-09-11 17:32:44 +01002784 layerName += fmt::format("BILINEAR:{}:{}", subgraphIndex, operatorIndex);
Sang-Hoon Park820eb142020-01-08 10:25:24 +00002785
2786 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2787 const auto * options = operatorPtr->builtin_options.AsResizeBilinearOptions();
2788
David Monahan4a0c9b92020-05-30 09:48:39 +01002789 desc.m_AlignCorners = options->align_corners;
Sadik Armagana3b31f02019-12-05 09:08:53 +00002790 break;
2791 }
2792 case ResizeMethod::NearestNeighbor:
2793 {
James Ward58dec6b2020-09-11 17:32:44 +01002794 layerName += fmt::format("NEARESTNEIGHBOR:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagana3b31f02019-12-05 09:08:53 +00002795 break;
2796 }
2797 default:
2798 {
2799 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002800 fmt::format("Unexpected ResizeMethod[{}] when creating layerName {} ",
2801 static_cast<int>(resizeMethod), CHECK_LOCATION().AsString()));
Sadik Armagana3b31f02019-12-05 09:08:53 +00002802 }
2803 }
2804
James Conroy05102392020-06-24 15:39:55 +01002805 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002806 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01002807 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
2808
2809 IConnectableLayer* layer = m_Network->AddResizeLayer(desc, layerName.c_str());
2810 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002811 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2812
2813 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2814 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2815
2816 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2817 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2818}
2819
Kevin May7d96b162021-02-03 17:38:41 +00002820void TfLiteParserImpl::ParseConcatenation(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan479045b2018-10-01 11:51:37 +01002821{
2822 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2823
Mike Kelly0d77ae12022-01-07 17:42:27 +00002824 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2825 const auto* options = operatorPtr->builtin_options.AsConcatenationOptions();
Sadik Armagan479045b2018-10-01 11:51:37 +01002826
2827 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
2828
2829 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2830 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2831 CHECK_VALID_SIZE(outputs.size(), 1);
2832
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002833 unsigned int numConcatView = static_cast<unsigned int>(inputs.size());
2834 uint32_t inputRank = ToTensorInfo(inputs[0]).GetNumDimensions();
Sadik Armagan479045b2018-10-01 11:51:37 +01002835
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002836 const unsigned int concatDimInput = static_cast<unsigned int>(
2837 (static_cast<int>(inputRank) + options->axis) % static_cast<int>(inputRank));
Sadik Armagan479045b2018-10-01 11:51:37 +01002838
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002839 OriginsDescriptor concatDescriptor(static_cast<uint32_t>(numConcatView), inputRank);
2840 concatDescriptor.SetConcatAxis(concatDimInput);
Sadik Armagan479045b2018-10-01 11:51:37 +01002841
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002842 unsigned int mergeDimOrigin = 0;
Sadik Armagan479045b2018-10-01 11:51:37 +01002843
2844 for (unsigned int viewIndex = 0; viewIndex < numConcatView; ++viewIndex)
2845 {
2846 TensorInfo inputTensorInfo = ToTensorInfo(inputs[viewIndex]);
2847
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002848 // This set up concatDescriptor view origin
2849 armnnUtils::ProcessConcatInputTensorInfo(
2850 inputTensorInfo, concatDescriptor, concatDimInput, viewIndex, mergeDimOrigin);
Sadik Armagan479045b2018-10-01 11:51:37 +01002851 }
2852
James Ward58dec6b2020-09-11 17:32:44 +01002853 auto layerName = fmt::format("Concatenation:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002854 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01002855
Jim Flynn906f9462019-05-10 13:55:21 +01002856 IConnectableLayer* layer = m_Network->AddConcatLayer(concatDescriptor, layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002857 ARMNN_ASSERT(layer != nullptr);
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002858 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Sadik Armagan479045b2018-10-01 11:51:37 +01002859
James Conroy05102392020-06-24 15:39:55 +01002860 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002861 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
Sadik Armagan479045b2018-10-01 11:51:37 +01002862
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002863 // add fused activation layer
2864 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Sadik Armagan479045b2018-10-01 11:51:37 +01002865
Sadik Armagan479045b2018-10-01 11:51:37 +01002866 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2867 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2868}
2869
Kevin May7d96b162021-02-03 17:38:41 +00002870void TfLiteParserImpl::ParseFullyConnected(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002871{
2872 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2873
Mike Kelly0d77ae12022-01-07 17:42:27 +00002874 const auto& operatorRfr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002875 const auto options = operatorRfr->builtin_options.AsFullyConnectedOptions();
2876
2877 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
2878
2879 FullyConnectedDescriptor desc;
2880 desc.m_BiasEnabled = false;
Nattapat Chaimanowongd8eee592018-10-26 10:24:14 +01002881 desc.m_TransposeWeightMatrix = true;
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002882
2883 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2884 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2885 CHECK_VALID_SIZE(outputs.size(), 1);
2886
2887 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
2888
2889 // Fully Connected Layer accepts two dimensional weights input
2890 int32_t weightsDimension = static_cast<int32_t>(filterTensorInfo.GetNumDimensions());
2891 if (weightsDimension != 2)
2892 {
2893 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002894 fmt::format("Dimension {} for Fully Connected weights is not supported by Armnn. "
2895 "Node {}",
2896 weightsDimension,
2897 CHECK_LOCATION().AsString()));
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002898 }
2899
Matthew Jackson74bf7da2019-08-16 16:51:42 +01002900 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01002901 auto layerName = fmt::format("FullyConnected:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002902
Matthew Sloyan81beae32021-07-13 19:46:11 +01002903 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2904 // Add the first input tensor to the registration list
2905 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0]};
2906 std::vector<unsigned int> ignoreInputWhenRegister = {};
Finn Williamsd4fa5452021-03-01 12:31:41 +00002907
2908 desc.m_ConstantWeights = IsConstTensor(inputs[1]);
2909
Matthew Sloyan81beae32021-07-13 19:46:11 +01002910 // Add the weights input to the registration list, constant layers will be added by SetupConstantLayers if constant.
2911 tensorIndexesToRegister.emplace_back(inputTensorIndexes[1]);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002912
Finn Williamsd4fa5452021-03-01 12:31:41 +00002913 if (inputs.size() == 3)
2914 {
2915 desc.m_BiasEnabled = true;
Matthew Sloyan81beae32021-07-13 19:46:11 +01002916
2917 // Add the biases input to the registration list, constant layer will be added by SetupConstantLayers.
2918 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00002919 }
2920
Matthew Sloyan81beae32021-07-13 19:46:11 +01002921 // Filters and biases are always passed to fully connected as inputs
2922 layer = m_Network->AddFullyConnectedLayer(desc, layerName.c_str());
Finn Williamsd4fa5452021-03-01 12:31:41 +00002923
2924 ARMNN_ASSERT(layer != nullptr);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002925 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2926
Finn Williamsd4fa5452021-03-01 12:31:41 +00002927 unsigned int startingSlotIndex = 0;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002928 if (inputTensorInfo.GetNumDimensions() > 2)
2929 {
2930 // Add reshape to flatten to 2D [batch_size, input_size],
2931 // where "input_size" corresponds to the number of inputs to the layer,
2932 // matching the second dimension of weights,
2933 // and "batch_size" is calculated by dividing the number of elements by "input_size".
2934 std::vector<unsigned int> reshapedDimensions(2);
2935 reshapedDimensions[1] = filterTensorInfo.GetShape()[1];
2936 reshapedDimensions[0] = inputTensorInfo.GetNumElements() / reshapedDimensions[1];
2937
2938 if (inputTensorInfo.GetNumElements() % reshapedDimensions[1] != 0)
2939 {
2940 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002941 fmt::format("Failed to deduce input tensor shape from filter size {} {}",
2942 reshapedDimensions[1],
2943 CHECK_LOCATION().AsString()));
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002944 }
2945
2946 armnn::TensorInfo reshapedTensorInfo = ToTensorInfo(inputs[0]);
2947 reshapedTensorInfo.SetShape(armnn::TensorShape{ 2, reshapedDimensions.data() });
2948
James Ward58dec6b2020-09-11 17:32:44 +01002949 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Finn Williamsd4fa5452021-03-01 12:31:41 +00002950 armnn::ReshapeDescriptor reshapeDescriptor;
2951 reshapeDescriptor.m_TargetShape = reshapedTensorInfo.GetShape();
2952 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(reshapeDescriptor, layerName.c_str());
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002953
2954 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedTensorInfo);
2955 reshapeLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(0));
2956
2957 RegisterInputSlots(subgraphIndex, operatorIndex, reshapeLayer, {inputTensorIndexes[0]});
Finn Williamsd4fa5452021-03-01 12:31:41 +00002958 // Fc layer connects to the reshape layer, so we skip the first input slot when registering fc's input slots
2959 tensorIndexesToRegister.erase(tensorIndexesToRegister.begin());
2960 startingSlotIndex = 1;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002961 }
Finn Williamsd4fa5452021-03-01 12:31:41 +00002962
2963 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister, startingSlotIndex);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002964
Sadik Armagand109a4d2020-07-28 10:42:13 +01002965 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002966 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2967
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002968 // we need to add the activation layer and fortunately we don't need to care about the data layout
2969 armnn::IConnectableLayer* fusedActivationLayer = AddFusedActivationLayer(layer, 0,
2970 options->fused_activation_function);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002971
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002972 // register the output connection slots for the layer, connections are made after all layers have been created
2973 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2974 RegisterOutputSlots(subgraphIndex, operatorIndex, fusedActivationLayer, {outputTensorIndexes[0]});
2975}
2976
Kevin May7d96b162021-02-03 17:38:41 +00002977void TfLiteParserImpl::ParseDetectionPostProcess(size_t subgraphIndex, size_t operatorIndex)
keidav011b3e2ea2019-02-21 10:07:37 +00002978{
2979 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2980
Mike Kelly0d77ae12022-01-07 17:42:27 +00002981 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
keidav011b3e2ea2019-02-21 10:07:37 +00002982
2983 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2984 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2985 CHECK_VALID_SIZE(outputs.size(), 4);
2986
2987 // Obtain custom options from flexbuffers
2988 auto custom_options = operatorPtr->custom_options;
2989 const flexbuffers::Map& m = flexbuffers::GetRoot(custom_options.data(), custom_options.size()).AsMap();
2990
2991 // Obtain descriptor information from tf lite
2992 DetectionPostProcessDescriptor desc;
2993 desc.m_MaxDetections = m["max_detections"].AsUInt32();
2994 desc.m_MaxClassesPerDetection = m["max_classes_per_detection"].AsUInt32();
2995 desc.m_NmsScoreThreshold = m["nms_score_threshold"].AsFloat();
2996 desc.m_NmsIouThreshold = m["nms_iou_threshold"].AsFloat();
2997 desc.m_NumClasses = m["num_classes"].AsUInt32();
2998 desc.m_ScaleH = m["h_scale"].AsFloat();
2999 desc.m_ScaleW = m["w_scale"].AsFloat();
3000 desc.m_ScaleX = m["x_scale"].AsFloat();
3001 desc.m_ScaleY = m["y_scale"].AsFloat();
3002
keidav0107d58c72019-02-26 11:57:39 +00003003 if (!(m["use_regular_nms"].IsNull()))
keidav011b3e2ea2019-02-21 10:07:37 +00003004 {
keidav0107d58c72019-02-26 11:57:39 +00003005 desc.m_UseRegularNms = m["use_regular_nms"].AsBool();
keidav011b3e2ea2019-02-21 10:07:37 +00003006 }
3007 if (!(m["detections_per_class"].IsNull()))
3008 {
3009 desc.m_DetectionsPerClass = m["detections_per_class"].AsUInt32();
3010 }
3011
3012 if (desc.m_NmsIouThreshold <= 0.0f || desc.m_NmsIouThreshold > 1.0f)
3013 {
3014 throw InvalidArgumentException("DetectionPostProcessTFLiteParser: Intersection over union threshold "
3015 "must be positive and less than or equal to 1.");
3016 }
3017
3018 armnn::TensorInfo anchorTensorInfo = ToTensorInfo(inputs[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003019 auto anchorTensorAndData = CreateConstTensorNonPermuted(inputs[2], anchorTensorInfo);
keidav011b3e2ea2019-02-21 10:07:37 +00003020
James Ward58dec6b2020-09-11 17:32:44 +01003021 auto layerName = fmt::format("DetectionPostProcess:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003022 IConnectableLayer* layer = m_Network->AddDetectionPostProcessLayer(desc, anchorTensorAndData,
keidav011b3e2ea2019-02-21 10:07:37 +00003023 layerName.c_str());
3024
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003025 ARMNN_ASSERT(layer != nullptr);
keidav011b3e2ea2019-02-21 10:07:37 +00003026
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003027 // The model does not specify the output shapes.
3028 // The output shapes are calculated from the max_detection and max_classes_per_detection.
3029 unsigned int numDetectedBox = desc.m_MaxDetections * desc.m_MaxClassesPerDetection;
3030 m_OverridenOutputShapes.push_back({ 1, numDetectedBox, 4 });
3031 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
3032 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
3033 m_OverridenOutputShapes.push_back({ 1 });
3034
keidav011b3e2ea2019-02-21 10:07:37 +00003035 for (unsigned int i = 0 ; i < outputs.size() ; ++i)
3036 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003037 armnn::TensorInfo detectionBoxOutputTensorInfo = ToTensorInfo(outputs[i], m_OverridenOutputShapes[i]);
keidav011b3e2ea2019-02-21 10:07:37 +00003038 layer->GetOutputSlot(i).SetTensorInfo(detectionBoxOutputTensorInfo);
3039 }
3040
3041 // Register the input connection slots for the layer, connections are made after all layers have been created
3042 // only the tensors for the inputs are relevant, exclude the const tensors
3043 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3044 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
3045
3046 // Register the output connection slots for the layer, connections are made after all layers have been created
3047 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3048 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0],
3049 outputTensorIndexes[1],
3050 outputTensorIndexes[2],
3051 outputTensorIndexes[3]});
3052}
3053
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003054/// The TfLite Pack operator is equivalent to the ArmNN Stack operator
Kevin May7d96b162021-02-03 17:38:41 +00003055void TfLiteParserImpl::ParsePack(size_t subgraphIndex, size_t operatorIndex)
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003056{
3057 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3058
3059 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3060 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3061 CHECK_VALID_SIZE(outputs.size(), 1);
3062
3063 if (inputs.size() < 1)
3064 {
3065 throw ParseException("Pack must have at least one input.");
3066 }
3067
3068 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3069 const auto* options = operatorPtr->builtin_options.AsPackOptions();
3070
3071 StackDescriptor desc;
3072 desc.m_Axis = static_cast<uint32_t>(options->axis);
3073 desc.m_NumInputs = static_cast<uint32_t>(inputs.size());
3074
3075 // Use the tensor shape of the first input as the "correct" input shape in the descriptor
3076 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3077 desc.m_InputShape = inputTensorInfo.GetShape();
3078
James Ward58dec6b2020-09-11 17:32:44 +01003079 auto layerName = fmt::format("Pack:{}:{}", subgraphIndex, operatorIndex);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003080 IConnectableLayer* layer = m_Network->AddStackLayer(desc, layerName.c_str());
3081
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003082 ARMNN_ASSERT(layer != nullptr);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003083
Sadik Armagand109a4d2020-07-28 10:42:13 +01003084 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01003085 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3086
3087 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3088 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
3089
3090 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3091 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3092}
3093
Kevin May7d96b162021-02-03 17:38:41 +00003094void TfLiteParserImpl::ParseUnpack(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd200e3802019-04-15 09:47:39 +01003095{
3096 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3097
Mike Kelly0d77ae12022-01-07 17:42:27 +00003098 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3099 const auto* options = operatorPtr->builtin_options.AsUnpackOptions();
Nina Drozd200e3802019-04-15 09:47:39 +01003100
3101 // This unpackAxis indicates the axis to unpack
3102 const unsigned int unpackAxis = CHECKED_NON_NEGATIVE(options->axis);
3103
3104 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3105 CHECK_VALID_SIZE(inputs.size(), 1);
3106
3107 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003108
3109 if (unpackAxis >= inputTensorInfo.GetNumDimensions())
3110 {
3111 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003112 fmt::format("The unpack axis: {} cannot be greater than or equal to "
3113 "the number of input dimension {} {}",
3114 unpackAxis,
3115 inputTensorInfo.GetNumDimensions(),
3116 CHECK_LOCATION().AsString()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003117 }
3118
Nina Drozd200e3802019-04-15 09:47:39 +01003119 unsigned int unpackNum = CHECKED_NON_NEGATIVE(options->num);
3120 // If num is not defined, automatically infer from the length of the dimension axis.
3121 if(unpackNum == 0)
3122 {
3123 unpackNum = inputTensorInfo.GetShape()[unpackAxis];
3124 }
3125
3126 // If unpack number cannot be inferred and is still zero, throw ParseException.
3127 if(unpackNum == 0)
3128 {
3129 throw ParseException("Number to unpack must greater than zero.");
3130 }
3131
3132 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3133 CHECK_VALID_SIZE(outputs.size(), unpackNum);
3134
3135 auto inputDimSize = inputTensorInfo.GetNumDimensions();
3136 std::vector<unsigned int> unpackDimSizes(inputDimSize);
3137
3138 // Add current input shape to unpackDimSizes
3139 for (unsigned int i = 0; i < inputDimSize; ++i)
3140 {
3141 unpackDimSizes[i] = inputTensorInfo.GetShape()[i];
3142 }
3143
3144 if (unpackDimSizes[unpackAxis] != unpackNum)
3145 {
3146 throw ParseException("Number to unpack must be the same as length of the dimension to "
3147 "unpack along.");
3148 }
3149
3150 unpackDimSizes[unpackAxis] /= unpackNum;
3151
3152 SplitterDescriptor splitDesc(unpackNum, static_cast<unsigned int>(unpackDimSizes.size()));
3153 for (unsigned int j = 0; j < unpackNum; ++j)
3154 {
3155 // Set the size of the views.
3156 for (unsigned int dimIdx = 0; dimIdx < unpackDimSizes.size(); ++dimIdx)
3157 {
3158 splitDesc.SetViewSize(j, dimIdx, unpackDimSizes[dimIdx]);
3159 }
3160 splitDesc.SetViewOriginCoord(j, unpackAxis, unpackDimSizes[unpackAxis] * j);
3161 }
3162
James Ward58dec6b2020-09-11 17:32:44 +01003163 auto layerName = fmt::format("Unpack:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd200e3802019-04-15 09:47:39 +01003164 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01003165 ARMNN_ASSERT(layer != nullptr);
Nina Drozd200e3802019-04-15 09:47:39 +01003166
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003167 TensorShape splitOutShape = TensorShape(static_cast<unsigned int>(unpackDimSizes.size()),
3168 unpackDimSizes.data());
3169
Nina Drozd200e3802019-04-15 09:47:39 +01003170 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3171 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3172
Finn Williamsb49ed182021-06-29 15:50:08 +01003173 std::vector<unsigned int> reshapeDims;
3174 for (unsigned int axis = 0; axis < splitOutShape.GetNumDimensions(); ++axis)
3175 {
3176 if (axis != unpackAxis)
3177 {
3178 reshapeDims.push_back(splitOutShape[axis]);
3179 }
3180 }
3181
3182 TensorShape reshapeOutputShape(splitOutShape.GetNumDimensions() -1, reshapeDims.data());
3183
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003184 // Create reshape to remove the unpacked dimension for unpack operator of each output from Splitter.
3185 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
3186 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01003187 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[k], true);
James Ward58dec6b2020-09-11 17:32:44 +01003188 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003189 armnn::ReshapeDescriptor desc;
Finn Williamsb49ed182021-06-29 15:50:08 +01003190 desc.m_TargetShape = reshapeOutputShape;
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003191 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(desc, layerName.c_str());
3192
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01003193 layer->GetOutputSlot(k).SetTensorInfo(armnn::TensorInfo(splitOutShape,
3194 outputTensorInfo.GetDataType(),
3195 outputTensorInfo.GetQuantizationScale(),
3196 outputTensorInfo.GetQuantizationOffset()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003197 layer->GetOutputSlot(k).Connect(reshapeLayer->GetInputSlot(0));
3198
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01003199 reshapeLayer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01003200
3201 uint32_t reshapedOutputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[k]);
3202 armnn::IOutputSlot* slot = &(reshapeLayer->GetOutputSlot(0));
3203 RegisterProducerOfTensor(subgraphIndex, reshapedOutputId, slot);
3204 }
Nina Drozd200e3802019-04-15 09:47:39 +01003205}
3206
Kevin May7d96b162021-02-03 17:38:41 +00003207void TfLiteParserImpl::ParseSplit(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd0324f482019-04-08 10:52:10 +01003208{
3209 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3210
Mike Kelly0d77ae12022-01-07 17:42:27 +00003211 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3212 const auto* options = operatorPtr->builtin_options.AsSplitOptions();
Nina Drozd0324f482019-04-08 10:52:10 +01003213
3214 const unsigned int numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
3215
Nina Drozd200e3802019-04-15 09:47:39 +01003216 // If number of splits cannot be inferred and is zero, throw ParseException.
3217 if(numSplits == 0)
3218 {
3219 throw ParseException("Number to splits must greater than zero.");
3220 }
3221
Nina Drozd0324f482019-04-08 10:52:10 +01003222 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3223 CHECK_VALID_SIZE(inputs.size(), 2);
3224 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3225 CHECK_VALID_SIZE(outputs.size(), numSplits);
3226
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003227 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[1]);
3228 armnn::TensorInfo axisTensorInfo = ToTensorInfo(inputs[0]);
3229 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
Nina Drozd0324f482019-04-08 10:52:10 +01003230
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003231 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003232 if (axisBufferPtr == nullptr)
3233 {
3234 throw ParseException(
3235 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
3236 CHECK_LOCATION().AsString()));
3237 }
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003238
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003239 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
3240 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
3241 int32_t axis = axisData[0];
3242
3243 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3244 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3245 {
3246 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
3247 // E.g. Rank 4 tensor can have axis in range [-4, 3)
3248 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
3249 throw ParseException(
3250 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3251 axis,
3252 CHECK_LOCATION().AsString()));
3253 }
3254
3255 const unsigned int splitDim = armnnUtils::GetUnsignedAxis(inputTensorInfo.GetNumDimensions(), axis);
Nina Drozd0324f482019-04-08 10:52:10 +01003256
Nina Drozd0324f482019-04-08 10:52:10 +01003257 auto inputDimSize = inputTensorInfo.GetNumDimensions();
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003258 if (inputDimSize > MaxNumOfTensorDimensions)
Nina Drozd0324f482019-04-08 10:52:10 +01003259 {
3260 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003261 fmt::format("The number of dimensions: {} for input tensors of the split op cannot be greater than {} {}",
3262 inputTensorInfo.GetNumDimensions(),
3263 MaxNumOfTensorDimensions,
3264 CHECK_LOCATION().AsString()));
Nina Drozd0324f482019-04-08 10:52:10 +01003265 }
3266
3267 std::vector<unsigned int> splitterDimSizes(inputDimSize);
3268
3269 // Add current input shape to splitterDimSizes
3270 for (unsigned int i = 0; i < inputDimSize; ++i)
3271 {
3272 splitterDimSizes[i] = inputTensorInfo.GetShape()[i];
3273 }
3274
3275 if (splitterDimSizes[splitDim] % numSplits != 0)
3276 {
3277 throw ParseException("Number of splits must evenly divide the dimension");
3278 }
3279 splitterDimSizes[splitDim] /= numSplits;
3280
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003281 SplitterDescriptor splitDesc(numSplits, inputDimSize);
Nina Drozd0324f482019-04-08 10:52:10 +01003282 for (unsigned int j = 0; j < numSplits; ++j)
3283 {
3284 // Set the size of the views.
3285 for (unsigned int dimIdx = 0; dimIdx < splitterDimSizes.size(); ++dimIdx)
3286 {
3287 splitDesc.SetViewSize(j, dimIdx, splitterDimSizes[dimIdx]);
3288 }
3289 splitDesc.SetViewOriginCoord(j, splitDim, splitterDimSizes[splitDim] * j);
3290 }
3291
James Ward58dec6b2020-09-11 17:32:44 +01003292 auto layerName = fmt::format("Split:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd0324f482019-04-08 10:52:10 +01003293 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01003294 ARMNN_ASSERT(layer != nullptr);
Nina Drozd0324f482019-04-08 10:52:10 +01003295
3296 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01003297 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[1]});
Nina Drozd0324f482019-04-08 10:52:10 +01003298
Nina Drozd0324f482019-04-08 10:52:10 +01003299 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
3300 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01003301 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Francis Murtagh98d6b3d2019-10-21 10:52:54 +01003302 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
Nina Drozd0324f482019-04-08 10:52:10 +01003303 }
3304
3305 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3306 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3307}
3308
Derek Lambertif0176992020-04-28 13:37:49 +01003309unsigned int ComputeWrappedIndex(int idx, unsigned int numDimsIn)
3310{
3311 int numDims = armnn::numeric_cast<int>(numDimsIn);
3312 int v = idx < 0 ? numDims + idx : idx;
3313 ARMNN_ASSERT(v >= 0);
3314 ARMNN_ASSERT(v < numDims);
3315
3316 return static_cast<unsigned int>(v);
3317}
3318
Kevin May7d96b162021-02-03 17:38:41 +00003319void TfLiteParserImpl::ParseSplitV(size_t subgraphIndex, size_t operatorIndex)
Derek Lambertif0176992020-04-28 13:37:49 +01003320{
3321 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3322
Mike Kelly0d77ae12022-01-07 17:42:27 +00003323 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3324 const auto* options = operatorPtr->builtin_options.AsSplitVOptions();
Derek Lambertif0176992020-04-28 13:37:49 +01003325
3326 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3327 CHECK_VALID_SIZE(inputs.size(), 3);
3328
3329 auto& inputTensor = inputs[0];
3330 auto& splitsTensor = inputs[1];
3331 auto& axisTensor = inputs[2];
3332
3333 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputTensor);
3334 armnn::TensorInfo splitsInfo = ToTensorInfo(splitsTensor);
3335 armnn::TensorInfo axisTensorInfo = ToTensorInfo(axisTensor);
3336 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
3337
3338 // Inputs
3339 auto inputDimSize = inputTensorInfo.GetNumDimensions();
3340 if (inputDimSize > MaxNumOfTensorDimensions)
3341 {
3342 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003343 fmt::format("The number of dimensions: {} for input tensors of the "
3344 "SplitV op cannot be greater than {} {}",
3345 inputTensorInfo.GetNumDimensions(),
3346 MaxNumOfTensorDimensions,
3347 CHECK_LOCATION().AsString()));
Derek Lambertif0176992020-04-28 13:37:49 +01003348 }
3349
3350 // Get split axis
3351 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, axisTensor->buffer);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003352 if (axisBufferPtr == nullptr)
3353 {
3354 throw ParseException(
3355 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
3356 CHECK_LOCATION().AsString()));
3357 }
3358
Derek Lambertif0176992020-04-28 13:37:49 +01003359 std::vector<int> axisData(axisTensorInfo.GetNumElements());
3360 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003361 int32_t axis = axisData[0];
3362
3363 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3364 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3365 {
3366 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
3367 // E.g. Rank 4 tensor can have axis in range [-4, 3)
3368 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
3369 throw ParseException(
3370 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3371 axis,
3372 CHECK_LOCATION().AsString()));
3373 }
3374 const unsigned int splitDim = ComputeWrappedIndex(axis, inputTensorInfo.GetNumDimensions());
Derek Lambertif0176992020-04-28 13:37:49 +01003375
Derek Lambertif0176992020-04-28 13:37:49 +01003376 // Set split sizes
Derek Lambertif0176992020-04-28 13:37:49 +01003377 CHECK_VALID_SIZE(splitsInfo.GetNumDimensions(), 1);
Ryan OShea86704732020-05-26 11:41:04 +01003378 unsigned int numSplits{0};
3379
3380 if(options)
Derek Lambertif0176992020-04-28 13:37:49 +01003381 {
3382 numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
Derek Lambertif0176992020-04-28 13:37:49 +01003383 }
3384 else
3385 {
Ryan OShea86704732020-05-26 11:41:04 +01003386 numSplits = splitsInfo.GetNumElements();
Derek Lambertif0176992020-04-28 13:37:49 +01003387 }
3388
3389 if (numSplits <=0)
3390 {
3391 throw ParseException("SplitV has invalid number of splits");
3392 }
3393
Jan Eilersc0761e92020-06-29 16:48:44 +01003394 std::vector<int> splitsData(numSplits);
Ryan OShea86704732020-05-26 11:41:04 +01003395 BufferRawPtr splitsBufferPtr = GetBuffer(m_Model, splitsTensor->buffer);
Jan Eilersc0761e92020-06-29 16:48:44 +01003396 ::memcpy(splitsData.data(), splitsBufferPtr->data.data(), splitsInfo.GetNumBytes());
Ryan OShea86704732020-05-26 11:41:04 +01003397
Jan Eilersc0761e92020-06-29 16:48:44 +01003398 unsigned int idx = 0;
Ryan OShea86704732020-05-26 11:41:04 +01003399 int numInferred{0};
3400 unsigned int inferIdx{0};
3401 int splitSum{0};
3402 for (auto split : splitsData)
3403 {
3404 if (split < 0)
3405 {
3406 numInferred++;
3407 inferIdx = idx;
3408 }
3409 else
3410 {
3411 splitSum += split;
3412 }
3413 idx++;
3414 }
3415 // Check for inferred Axis
3416 if (numInferred == 0)
3417 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01003418 if (splitSum != armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]))
Ryan OShea86704732020-05-26 11:41:04 +01003419 {
3420 throw ParseException("SplitV split_sizes does not sum to the dimension of value along split_dim.");
3421 }
3422 }
3423 else if (numInferred == 1)
3424 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01003425 splitsData[inferIdx] = armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]) - splitSum;
Ryan OShea86704732020-05-26 11:41:04 +01003426 }
3427 else
3428 {
3429 throw ParseException("Cannot infer split size for more than one split");
3430 }
3431
Derek Lambertif0176992020-04-28 13:37:49 +01003432 //Ouput size validation
3433 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3434 CHECK_VALID_SIZE(outputs.size(), numSplits);
3435
3436 // Setup Armnn descriptor
3437 SplitterDescriptor splitDesc(numSplits, inputDimSize);
3438 unsigned int accumSplit = 0;
3439 for (unsigned int j = 0; j < numSplits; ++j)
3440 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01003441 unsigned int splitSize = armnn::numeric_cast<unsigned int>(splitsData[j]);
Derek Lambertif0176992020-04-28 13:37:49 +01003442
3443 // Set the size of the views.
3444 for (unsigned int dimIdx = 0; dimIdx < inputTensorInfo.GetNumDimensions(); ++dimIdx)
3445 {
3446 unsigned int dimSize = inputTensorInfo.GetShape()[dimIdx];
3447 if (dimIdx == splitDim)
3448 {
3449 dimSize = splitSize;
3450 }
3451 splitDesc.SetViewSize(j, dimIdx, dimSize);
3452 }
3453
3454 splitDesc.SetViewOriginCoord(j, splitDim, accumSplit);
3455 accumSplit += splitSize;
3456 }
3457
James Ward58dec6b2020-09-11 17:32:44 +01003458 auto layerName = fmt::format("SplitV:{}:{}", subgraphIndex, operatorIndex);
Derek Lambertif0176992020-04-28 13:37:49 +01003459 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01003460 ARMNN_ASSERT(layer != nullptr);
Derek Lambertif0176992020-04-28 13:37:49 +01003461
3462 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3463 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3464
3465 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
3466 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01003467 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Derek Lambertif0176992020-04-28 13:37:49 +01003468 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
3469 }
3470
3471 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3472 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3473}
3474
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003475void TfLiteParserImpl::ParseArgMin(size_t subgraphIndex, size_t operatorIndex)
3476{
3477 ParseArgMinMax(subgraphIndex, operatorIndex, armnn::ArgMinMaxFunction::Min);
3478}
3479
Kevin May7d96b162021-02-03 17:38:41 +00003480void TfLiteParserImpl::ParseArgMax(size_t subgraphIndex, size_t operatorIndex)
Inki Daed4619e22020-09-10 15:33:54 +09003481{
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003482 ParseArgMinMax(subgraphIndex, operatorIndex, armnn::ArgMinMaxFunction::Max);
3483}
3484
3485void TfLiteParserImpl::ParseArgMinMax(size_t subgraphIndex, size_t operatorIndex, ArgMinMaxFunction argMinMaxFunction)
3486{
Inki Daed4619e22020-09-10 15:33:54 +09003487 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3488 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3489 CHECK_VALID_SIZE(inputs.size(), 2);
3490
3491 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3492 CHECK_VALID_SIZE(outputs.size(), 1);
3493
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003494 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3495 armnn::TensorInfo axisTensorInfo = ToTensorInfo(inputs[1]);
Inki Daed4619e22020-09-10 15:33:54 +09003496 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003497 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003498
3499 // Check if output tensor type is Signed32 or Signed64
Mike Kelly1f140f72021-04-06 12:25:55 +01003500 if (outputTensorInfo.GetDataType() != armnn::DataType::Signed32 &&
3501 outputTensorInfo.GetDataType() != armnn::DataType::Signed64)
3502 {
3503 throw ParseException(
3504 fmt::format(
3505 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
3506 CHECK_LOCATION().AsString()));
3507 }
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003508
3509 // Get const axis value from model and set it to descriptor.
3510 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
3511 if (axisBufferPtr == nullptr)
3512 {
3513 throw ParseException(
3514 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
3515 CHECK_LOCATION().AsString()));
3516 }
3517
3518 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
3519 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
3520 int32_t axis = axisData.front();
3521
3522 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3523 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3524 {
3525 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
3526 // E.g. Rank 4 tensor can have axis in range [-4, 3)
3527 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
3528 throw ParseException(
3529 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3530 axis,
3531 CHECK_LOCATION().AsString()));
3532 }
3533
3534 ArgMinMaxDescriptor desc;
3535 desc.m_Axis = axis;
3536 desc.m_Function = argMinMaxFunction;
3537
3538 // Register a ArgMin/ArgMax layer.
3539 auto layerName = argMinMaxFunction == ArgMinMaxFunction::Max ? "ArgMax:{}:{}" : "ArgMin:{}:{}";
3540 auto layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
3541 IConnectableLayer *layer = m_Network->AddArgMinMaxLayer(desc, layerNameFormatted.c_str());
3542 ARMNN_ASSERT(layer != nullptr);
Inki Daed4619e22020-09-10 15:33:54 +09003543 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3544
3545 // Register input tensor to the layer.
3546 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3547 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3548
3549 // Register output tensor to the layer.
3550 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3551 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3552}
3553
Kevin May7d96b162021-02-03 17:38:41 +00003554void TfLiteParserImpl::ParseGather(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00003555{
3556 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3557
Kevin May7d96b162021-02-03 17:38:41 +00003558 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00003559 CHECK_VALID_SIZE(inputs.size(), 2);
Kevin May7d96b162021-02-03 17:38:41 +00003560 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00003561 CHECK_VALID_SIZE(outputs.size(), 1);
3562
3563 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3564 armnn::TensorInfo indicesTensorInfo = ToTensorInfo(inputs[1]);
3565 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
3566
3567 armnn::GatherDescriptor gatherDescriptor;
3568
Mike Kelly0d77ae12022-01-07 17:42:27 +00003569 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3570 const auto* options = operatorPtr->builtin_options.AsGatherOptions();
Sadik Armagan26868492021-01-22 14:25:31 +00003571 auto axis = options->axis;
3572
3573 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3574 auto indicesDimensions = indicesTensorInfo.GetNumDimensions();
3575 auto outputDimensions = outputTensorInfo.GetNumDimensions();
3576 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3577 {
3578 throw ParseException(
3579 fmt::format("Operation has invalid axis: {} It is out of bounds [ -{}, {} ) {}",
3580 axis,
3581 inputDimensions, inputDimensions,
3582 CHECK_LOCATION().AsString()));
3583 }
3584 if (outputDimensions != static_cast<unsigned int>(inputDimensions) + indicesDimensions - 1)
3585 {
3586 throw ParseException(
3587 fmt::format("Operation has invalid output dimensions: {} Output must be an ({} + {} - 1) -D tensor {}",
3588 outputDimensions,
3589 inputDimensions, indicesDimensions,
3590 CHECK_LOCATION().AsString()));
3591 }
3592
3593 gatherDescriptor.m_Axis = axis;
3594
3595 auto layerName = fmt::format("Gather:{}:{}", subgraphIndex, operatorIndex);
3596 IConnectableLayer* layer = m_Network->AddGatherLayer(gatherDescriptor, layerName.c_str());
3597 ARMNN_ASSERT(layer != nullptr);
3598 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3599
3600 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3601 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
3602
3603 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3604 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3605}
3606
Kevin May7d96b162021-02-03 17:38:41 +00003607void TfLiteParserImpl::ParseDepthToSpace(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00003608{
3609 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3610
Kevin May7d96b162021-02-03 17:38:41 +00003611 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00003612 CHECK_VALID_SIZE(inputs.size(), 1);
Kevin May7d96b162021-02-03 17:38:41 +00003613 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00003614 CHECK_VALID_SIZE(outputs.size(), 1);
3615
3616 armnn::DepthToSpaceDescriptor descriptor;
3617
Mike Kelly0d77ae12022-01-07 17:42:27 +00003618 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3619 const auto* options = operatorPtr->builtin_options.AsDepthToSpaceOptions();
Sadik Armagan26868492021-01-22 14:25:31 +00003620 auto blockSize = options->block_size;
3621 if (blockSize < 2)
3622 {
3623 throw ParseException(
3624 fmt::format("Operation has invalid block size: {} Block size should be >= 2 {}",
3625 blockSize,
3626 CHECK_LOCATION().AsString()));
3627 }
3628 descriptor.m_BlockSize = armnn::numeric_cast<uint32_t>(blockSize);
3629
3630 auto layerName = fmt::format("DepthToSpace:{}:{}", subgraphIndex, operatorIndex);
3631 IConnectableLayer* layer = m_Network->AddDepthToSpaceLayer(descriptor, layerName.c_str());
3632 ARMNN_ASSERT(layer != nullptr);
3633 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
3634 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3635
3636 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3637 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3638
3639 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3640 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3641}
3642
Kevin May7d96b162021-02-03 17:38:41 +00003643void TfLiteParserImpl::ParseSum(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003644{
Sadik Armagana2747482021-02-09 10:28:54 +00003645 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Sum);
3646}
3647
Teresa Charlin4e3e8312021-08-05 12:34:37 +01003648void TfLiteParserImpl::ParseReduceProd(size_t subgraphIndex, size_t operatorIndex)
3649{
3650 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Prod);
3651}
3652
Sadik Armagana2747482021-02-09 10:28:54 +00003653void TfLiteParserImpl::ParseReduceMax(size_t subgraphIndex, size_t operatorIndex)
3654{
3655 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Max);
3656}
3657
3658void TfLiteParserImpl::ParseReduceMin(size_t subgraphIndex, size_t operatorIndex)
3659{
3660 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Min);
3661}
3662
3663void TfLiteParserImpl::ParseReduce(size_t subgraphIndex, size_t operatorIndex, ReduceOperation reduceOperation)
3664{
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003665 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3666
Mike Kelly0d77ae12022-01-07 17:42:27 +00003667 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3668 const auto* options = operatorPtr->builtin_options.AsReducerOptions();
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003669
3670 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3671 CHECK_VALID_SIZE(inputs.size(), 2);
3672
3673 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3674 CHECK_VALID_SIZE(outputs.size(), 1);
3675
Sadik Armagana2747482021-02-09 10:28:54 +00003676 auto layerName = fmt::format("Reduce:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003677
3678 armnn::TensorInfo inputTensorInfo0 = ToTensorInfo(inputs[0]);
3679 armnn::TensorInfo inputTensorInfo1 = ToTensorInfo(inputs[1]);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003680
3681 ReduceDescriptor desc;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003682 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
3683 // Get const axis value from model and set it to descriptor.
3684 if (axisBufferPtr != nullptr)
3685 {
Sadik Armagan49bdb792021-02-11 13:57:07 +00003686 std::vector<int32_t> axisData(inputTensorInfo1.GetNumElements());
3687 ::memcpy(axisData.data(), axisBufferPtr->data.data(), inputTensorInfo1.GetNumBytes());
3688
3689 // Convert the axis to unsigned int and remove duplicates.
3690 auto rank = static_cast<int32_t>(inputTensorInfo0.GetNumDimensions());
3691 std::set<unsigned int> uniqueAxis;
3692 std::transform(axisData.begin(),
3693 axisData.end(),
3694 std::inserter(uniqueAxis, uniqueAxis.begin()),
3695 [rank](int i)->unsigned int{
3696 return static_cast<uint32_t>(((i + rank) % rank)); });
3697 desc.m_vAxis.assign(uniqueAxis.begin(), uniqueAxis.end());
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003698 }
Sadik Armagana2747482021-02-09 10:28:54 +00003699 else
3700 {
3701 for (uint32_t i = 0; i < inputTensorInfo0.GetNumDimensions(); ++i)
3702 {
3703 desc.m_vAxis.push_back(i);
3704 }
3705 }
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003706
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003707 desc.m_KeepDims = options->keep_dims;
Sadik Armagana2747482021-02-09 10:28:54 +00003708 desc.m_ReduceOperation = reduceOperation;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003709
3710 // Register a new layer object, Sum.
Mike Kelly0d77ae12022-01-07 17:42:27 +00003711 IConnectableLayer* layer = m_Network->AddReduceLayer(desc, layerName.c_str());
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003712
3713 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
3714 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3715
3716 // Register input tensor to the layer.
3717 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3718 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3719
3720 // Register output tensor to the layer.
3721 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3722 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3723}
3724
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003725void TfLiteParserImpl::ParseAbs(size_t subgraphIndex, size_t operatorIndex)
3726{
3727 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Abs);
3728}
3729
3730void TfLiteParserImpl::ParseExp(size_t subgraphIndex, size_t operatorIndex)
3731{
3732 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Exp);
3733}
3734
Mike Kelly31dce2b2021-09-01 21:22:37 +01003735void TfLiteParserImpl::ParseLocalResponseNormalization(size_t subgraphIndex, size_t operatorIndex)
3736{
3737 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3738
3739 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3740 CHECK_VALID_SIZE(inputs.size(), 1);
3741
3742 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3743 CHECK_VALID_SIZE(outputs.size(), 1);
3744
3745 auto layerName = fmt::format("LRN:{}:{}", subgraphIndex, operatorIndex);
3746 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
3747
3748 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3749
3750 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3751 const auto* options = operatorPtr->builtin_options.AsLocalResponseNormalizationOptions();
3752
3753 armnn::NormalizationDescriptor descriptor;
3754 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3755 descriptor.m_NormChannelType = armnn::NormalizationAlgorithmChannel::Across;
3756 descriptor.m_NormMethodType = armnn::NormalizationAlgorithmMethod::LocalBrightness;
3757 descriptor.m_NormSize = static_cast<uint32_t>(options->radius);
3758 descriptor.m_K = options->bias;
3759 descriptor.m_Alpha = options->alpha;
3760 descriptor.m_Beta = options->beta;
3761
3762 // ArmNN expects normSize to be the full size of the normalization
3763 // window rather than the radius as in TfLite.
3764 descriptor.m_NormSize = 1 + (2 * descriptor.m_NormSize);
3765
3766 IConnectableLayer* layer = m_Network->AddNormalizationLayer(descriptor, layerNameFormatted.c_str());
3767 ARMNN_ASSERT(layer != nullptr);
3768
3769 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
3770 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3771
3772 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3773 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3774
3775 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3776 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3777}
3778
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003779void TfLiteParserImpl::ParseLogicalNot(size_t subgraphIndex, size_t operatorIndex)
3780{
3781 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::LogicalNot);
3782}
3783
3784void TfLiteParserImpl::ParseNeg(size_t subgraphIndex, size_t operatorIndex)
3785{
3786 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Neg);
3787}
3788
3789void TfLiteParserImpl::ParseRsqrt(size_t subgraphIndex, size_t operatorIndex)
3790{
3791 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Rsqrt);
3792}
3793
3794void TfLiteParserImpl::ParseElementwiseUnary(size_t subgraphIndex, size_t operatorIndex, UnaryOperation unaryOperation)
3795{
3796 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3797
3798 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3799 CHECK_VALID_SIZE(inputs.size(), 1);
3800
3801 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3802 CHECK_VALID_SIZE(outputs.size(), 1);
3803
3804 std::string layerName = std::string(GetUnaryOperationAsCString(unaryOperation)) + ":{}:{}";
3805 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
3806
3807 ElementwiseUnaryDescriptor desc;
3808 desc.m_Operation = unaryOperation;
3809 IConnectableLayer* layer = m_Network->AddElementwiseUnaryLayer(desc, layerNameFormatted.c_str());
3810 ARMNN_ASSERT(layer != nullptr);
3811
3812 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
3813 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3814
3815 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3816 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3817
3818 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3819 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3820}
3821
Bruno Goncalves2d0eb862021-07-11 14:10:15 -03003822void TfLiteParserImpl::ParseEqual(size_t subgraphIndex, size_t operatorIndex)
3823{
3824 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::Equal);
3825}
3826
3827void TfLiteParserImpl::ParseNotEqual(size_t subgraphIndex, size_t operatorIndex)
3828{
3829 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::NotEqual);
3830}
3831
3832void TfLiteParserImpl::ParseGreater(size_t subgraphIndex, size_t operatorIndex)
3833{
3834 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::Greater);
3835}
3836
3837void TfLiteParserImpl::ParseGreaterOrEqual(size_t subgraphIndex, size_t operatorIndex)
3838{
3839 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::GreaterOrEqual);
3840}
3841
3842void TfLiteParserImpl::ParseLess(size_t subgraphIndex, size_t operatorIndex)
3843{
3844 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::Less);
3845}
3846
3847void TfLiteParserImpl::ParseLessOrEqual(size_t subgraphIndex, size_t operatorIndex)
3848{
3849 ParseComparison(subgraphIndex, operatorIndex, armnn::ComparisonOperation::LessOrEqual);
3850}
3851
3852void TfLiteParserImpl::ParseComparison(size_t subgraphIndex, size_t operatorIndex,
3853 ComparisonOperation comparisonOperation)
3854{
3855 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3856
3857 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3858 CHECK_VALID_SIZE(inputs.size(), 2);
3859
3860 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3861 CHECK_VALID_SIZE(outputs.size(), 1);
3862
3863 auto layerName = std::string(GetComparisonOperationAsCString(comparisonOperation)) + ":{}:{}";
3864 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
3865
3866 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3867 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
3868 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerNameFormatted, "Input 0", "Input 1");
3869
3870 ComparisonDescriptor desc;
3871 desc.m_Operation = comparisonOperation;
3872 IConnectableLayer* layer = m_Network->AddComparisonLayer(desc, layerNameFormatted.c_str());
3873 ARMNN_ASSERT(layer != nullptr);
3874
3875 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
3876 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3877
3878 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3879 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
3880
3881 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3882 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3883}
3884
Kevin May7d96b162021-02-03 17:38:41 +00003885armnn::IConnectableLayer* TfLiteParserImpl::AddFusedActivationLayer(armnn::IConnectableLayer* prevLayer,
3886 unsigned int outputSlot,
3887 tflite::ActivationFunctionType activationType)
telsoa01c577f2c2018-08-31 09:22:23 +01003888{
3889 ActivationDescriptor activationDesc;
3890 std::string layerName = prevLayer->GetName();
3891
3892 switch(activationType)
3893 {
3894 case tflite::ActivationFunctionType_NONE:
3895 {
3896 // this is a no-op: return previous layer
3897 return prevLayer;
3898 }
3899 case tflite::ActivationFunctionType_RELU:
3900 {
3901 activationDesc.m_Function = ActivationFunction::ReLu;
3902 layerName += ":RELU";
3903 break;
3904 }
3905 case tflite::ActivationFunctionType_RELU6:
3906 {
3907 activationDesc.m_Function = ActivationFunction::BoundedReLu;
3908 activationDesc.m_A = 6.0f;
3909 activationDesc.m_B = 0.0f;
3910 layerName += ":RELU6";
3911 break;
3912 }
3913 case tflite::ActivationFunctionType_TANH:
3914 {
3915 activationDesc.m_Function = ActivationFunction::TanH;
3916 activationDesc.m_A = 1.0f;
3917 activationDesc.m_B = 1.0f;
3918 layerName += ":TANH";
3919 break;
3920 }
3921
3922 // I only put these here as a reminder what others we could support
3923 case tflite::ActivationFunctionType_RELU_N1_TO_1:
3924 case tflite::ActivationFunctionType_SIGN_BIT:
3925 default:
3926 {
3927 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003928 fmt::format("TfLite parser doesn't suppport fused activation: "
3929 "{}/{} {} ",
3930 activationType,
3931 tflite::EnumNameActivationFunctionType(activationType),
3932 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003933
3934 }
3935 }
3936
3937 IConnectableLayer* activationLayer =
3938 m_Network->AddActivationLayer(activationDesc, layerName.c_str());
3939
3940 auto & prevOutputSlot = prevLayer->GetOutputSlot(outputSlot);
3941 prevOutputSlot.Connect(activationLayer->GetInputSlot(0));
3942 activationLayer->GetOutputSlot(0).SetTensorInfo(prevOutputSlot.GetTensorInfo());
3943 return activationLayer;
3944}
3945
Mike Kelly0d77ae12022-01-07 17:42:27 +00003946TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromFile(const char* fileName)
telsoa01c577f2c2018-08-31 09:22:23 +01003947{
3948 if (fileName == nullptr)
3949 {
James Ward58dec6b2020-09-11 17:32:44 +01003950 throw InvalidArgumentException(fmt::format("Invalid (null) file name {}",
telsoa01c577f2c2018-08-31 09:22:23 +01003951 CHECK_LOCATION().AsString()));
3952 }
Francis Murtagh532a29d2020-06-29 11:50:01 +01003953 std::error_code errorCode;
3954 fs::path pathToFile(fileName);
3955 if (!fs::exists(pathToFile, errorCode))
telsoa01c577f2c2018-08-31 09:22:23 +01003956 {
James Ward58dec6b2020-09-11 17:32:44 +01003957 //fmt::format() could not be used here (format error)
3958 std::stringstream msg;
3959 msg << "Cannot find the file (" << fileName << ") errorCode: " << errorCode
3960 << " " << CHECK_LOCATION().AsString();
3961
3962 throw FileNotFoundException(msg.str());
telsoa01c577f2c2018-08-31 09:22:23 +01003963 }
3964 std::ifstream file(fileName, std::ios::binary);
3965 std::string fileContent((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
3966 return LoadModelFromBinary(reinterpret_cast<const uint8_t *>(fileContent.c_str()),
3967 fileContent.size());
3968}
3969
Mike Kelly0d77ae12022-01-07 17:42:27 +00003970TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromBinary(const uint8_t* binaryContent, size_t len)
telsoa01c577f2c2018-08-31 09:22:23 +01003971{
3972 if (binaryContent == nullptr)
3973 {
James Ward58dec6b2020-09-11 17:32:44 +01003974 throw InvalidArgumentException(fmt::format("Invalid (null) binary content {}",
telsoa01c577f2c2018-08-31 09:22:23 +01003975 CHECK_LOCATION().AsString()));
3976 }
3977 flatbuffers::Verifier verifier(binaryContent, len);
3978 if (verifier.VerifyBuffer<tflite::Model>() == false)
3979 {
3980 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003981 fmt::format("Buffer doesn't conform to the expected Tensorflow Lite "
3982 "flatbuffers format. size:{} {}",
3983 len,
3984 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003985 }
3986 return tflite::UnPackModel(binaryContent);
3987}
3988
Mike Kelly0d77ae12022-01-07 17:42:27 +00003989TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetInputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00003990 size_t subgraphIndex,
3991 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003992{
3993 CHECK_MODEL(model, subgraphIndex, operatorIndex);
3994
Mike Kelly0d77ae12022-01-07 17:42:27 +00003995 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
3996 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003997
3998 size_t inputCount = operatorPtr->inputs.size();
mathad01c21025d2021-04-26 10:09:37 +01003999 TensorRawPtrVector result;
Mike Kelly0d77ae12022-01-07 17:42:27 +00004000 for (size_t i = 0; i < inputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004001 {
mathad01c21025d2021-04-26 10:09:37 +01004002 // If the input location is -1 then assume input is turned off.
4003 if (operatorPtr->inputs[i] == -1)
4004 {
4005 continue;
4006 }
4007 else
4008 {
4009 uint32_t inputId = CHECKED_NON_NEGATIVE(operatorPtr->inputs[i]);
4010 result.push_back(subgraphPtr->tensors[inputId].get());
4011 }
telsoa01c577f2c2018-08-31 09:22:23 +01004012 }
4013 return result;
4014}
4015
Mike Kelly0d77ae12022-01-07 17:42:27 +00004016TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetOutputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00004017 size_t subgraphIndex,
4018 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004019{
4020 CHECK_MODEL(model, subgraphIndex, operatorIndex);
4021
Mike Kelly0d77ae12022-01-07 17:42:27 +00004022 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4023 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004024
4025 size_t outputCount = operatorPtr->outputs.size();
4026 TensorRawPtrVector result(outputCount);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004027 for (size_t i = 0; i < outputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004028 {
4029 uint32_t outputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[i]);
4030 CHECK_TENSOR(model, subgraphIndex, outputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01004031 result[i] = subgraphPtr->tensors[outputId].get();
telsoa01c577f2c2018-08-31 09:22:23 +01004032 }
4033 return result;
4034}
4035
Mike Kelly0d77ae12022-01-07 17:42:27 +00004036TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphInputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00004037 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004038{
4039 CHECK_SUBGRAPH(model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004040 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004041
Derek Lambertiff05cc52019-04-26 13:05:17 +01004042 size_t inputCount = subgraphPtr->inputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01004043 TensorIdRawPtrVector result(inputCount);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004044 for (size_t i = 0; i < inputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004045 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01004046 uint32_t inputId = CHECKED_NON_NEGATIVE(subgraphPtr->inputs[i]);
telsoa01c577f2c2018-08-31 09:22:23 +01004047 CHECK_TENSOR(model, subgraphIndex, inputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01004048 result[i] = std::make_pair(inputId, subgraphPtr->tensors[inputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01004049 }
4050 return result;
4051}
4052
Mike Kelly0d77ae12022-01-07 17:42:27 +00004053TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphOutputs(const ModelPtr& model,
Kevin May7d96b162021-02-03 17:38:41 +00004054 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004055{
4056 CHECK_SUBGRAPH(model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004057 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004058
Derek Lambertiff05cc52019-04-26 13:05:17 +01004059 size_t outputCount = subgraphPtr->outputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01004060 TensorIdRawPtrVector result(outputCount);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004061 for (size_t i = 0; i < outputCount; ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004062 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01004063 uint32_t outputId = CHECKED_NON_NEGATIVE(subgraphPtr->outputs[i]);
4064 result[i] = std::make_pair(outputId, subgraphPtr->tensors[outputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01004065 }
4066 return result;
4067}
4068
Kevin May7d96b162021-02-03 17:38:41 +00004069std::vector<int32_t>& TfLiteParserImpl::GetInputTensorIds(const ModelPtr& model,
4070 size_t subgraphIndex,
4071 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004072{
4073 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004074 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4075 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004076 return operatorPtr->inputs;
4077}
4078
Kevin May7d96b162021-02-03 17:38:41 +00004079std::vector<int32_t>& TfLiteParserImpl::GetOutputTensorIds(const ModelPtr& model,
4080 size_t subgraphIndex,
4081 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004082{
4083 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004084 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4085 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01004086 return operatorPtr->outputs;
4087}
4088
Kevin May7d96b162021-02-03 17:38:41 +00004089void TfLiteParserImpl::RegisterInputSlots(size_t subgraphIndex,
4090 size_t operatorIndex,
4091 IConnectableLayer* layer,
Finn Williamsd4fa5452021-03-01 12:31:41 +00004092 const std::vector<unsigned int>& tensorIndexes,
4093 unsigned int startingSlotIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004094{
4095 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01004096 ARMNN_ASSERT(layer != nullptr);
Matthew Sloyan81beae32021-07-13 19:46:11 +01004097
Finn Williamsd4fa5452021-03-01 12:31:41 +00004098 if (tensorIndexes.size() + startingSlotIndex != layer->GetNumInputSlots())
telsoa01c577f2c2018-08-31 09:22:23 +01004099 {
4100 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004101 fmt::format("The number of tensor inputs ({}) does not match the number expected ({})"
4102 " for subgraph:{} operator index:{} {}",
4103 tensorIndexes.size(),
4104 layer->GetNumInputSlots(),
4105 subgraphIndex,
4106 operatorIndex,
4107 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004108 }
4109
Finn Williamsd4fa5452021-03-01 12:31:41 +00004110 for (unsigned int index = 0; index < tensorIndexes.size() ; ++index)
telsoa01c577f2c2018-08-31 09:22:23 +01004111 {
Finn Williamsd4fa5452021-03-01 12:31:41 +00004112 unsigned int tensorIndex = tensorIndexes[index];
4113 armnn::IInputSlot* slot = &(layer->GetInputSlot(startingSlotIndex + index));
telsoa01c577f2c2018-08-31 09:22:23 +01004114 RegisterConsumerOfTensor(subgraphIndex, tensorIndex, slot);
4115 }
4116}
4117
Kevin May7d96b162021-02-03 17:38:41 +00004118void TfLiteParserImpl::RegisterOutputSlots(size_t subgraphIndex,
4119 size_t operatorIndex,
4120 IConnectableLayer* layer,
4121 const std::vector<unsigned int>& tensorIndexes)
telsoa01c577f2c2018-08-31 09:22:23 +01004122{
4123 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01004124 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01004125 if (tensorIndexes.size() != layer->GetNumOutputSlots())
4126 {
4127 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004128 fmt::format("The number of tensor outputs ({}) does not match the number expected ({})"
4129 " for subgraph:{} operator index:{} {}",
4130 tensorIndexes.size(),
4131 layer->GetNumOutputSlots(),
4132 subgraphIndex,
4133 operatorIndex,
4134 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004135 }
4136
4137 for (unsigned int slotIndex = 0; slotIndex < layer->GetNumOutputSlots(); ++slotIndex)
4138 {
4139 unsigned int tensorIndex = tensorIndexes[slotIndex];
4140 armnn::IOutputSlot* slot = &(layer->GetOutputSlot(slotIndex));
4141 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
4142 }
4143}
4144
Kevin May7d96b162021-02-03 17:38:41 +00004145void TfLiteParserImpl::SetupInputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004146{
4147 CHECK_SUBGRAPH(m_Model, subgraphIndex);
4148
4149 auto inputs = GetSubgraphInputs(m_Model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004150 for (auto const& tensorIdAndPtr : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004151 {
4152 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
4153 IConnectableLayer* layer =
4154 m_Network->AddInputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
4155
4156 auto tensorInfo = ToTensorInfo(tensorIdAndPtr.second);
4157 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
4158
4159 RegisterOutputSlots(subgraphIndex,
4160 VIRTUAL_OPERATOR_ID,
4161 layer,
4162 { static_cast<uint32_t>(tensorIdAndPtr.first) });
4163 }
4164}
4165
Kevin May7d96b162021-02-03 17:38:41 +00004166void TfLiteParserImpl::SetupOutputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004167{
4168 CHECK_SUBGRAPH(m_Model, subgraphIndex);
4169
4170 auto outputs = GetSubgraphOutputs(m_Model, subgraphIndex);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004171 for (auto const& tensorIdAndPtr : outputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004172 {
4173 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
4174 IConnectableLayer* layer =
4175 m_Network->AddOutputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
4176
4177 RegisterInputSlots(subgraphIndex,
4178 VIRTUAL_OPERATOR_ID,
4179 layer,
4180 { static_cast<uint32_t>(tensorIdAndPtr.first) });
4181 }
4182}
4183
Kevin May7d96b162021-02-03 17:38:41 +00004184void TfLiteParserImpl::SetupConstantLayers(size_t subgraphIndex)
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004185{
4186 CHECK_SUBGRAPH(m_Model, subgraphIndex);
4187
Mike Kelly0d77ae12022-01-07 17:42:27 +00004188 const auto& subgraphPtr = m_Model->subgraphs[subgraphIndex];
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004189 for (unsigned int subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
4190 {
4191 for (unsigned int tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
4192 {
4193 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot == nullptr &&
4194 m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size() > 0)
4195 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01004196 TensorRawPtr tensorPtr = subgraphPtr->tensors[tensorIndex].get();
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004197
Matthew Sloyan81beae32021-07-13 19:46:11 +01004198 if(IsConstTensor(tensorPtr))
4199 {
4200 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
4201 auto tensorAndData = CreateConstTensorNonPermuted(tensorPtr, tensorInfo);
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004202
Matthew Sloyan81beae32021-07-13 19:46:11 +01004203 std::string layerName = fmt::format("Constant:{}", tensorPtr->name);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004204 IConnectableLayer* layer = m_Network->AddConstantLayer(tensorAndData, layerName.c_str());
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004205
Matthew Sloyan81beae32021-07-13 19:46:11 +01004206 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
4207 RegisterOutputSlots(subgraphIndex,
4208 VIRTUAL_OPERATOR_ID,
4209 layer,
4210 { tensorIndex });
4211 }
4212 else
4213 {
4214 throw ParseException(
4215 fmt::format("Invalid Tensor: Tensor should be constant. {}",
4216 CHECK_LOCATION().AsString()));
4217 }
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02004218 }
4219 }
4220 }
4221}
4222
telsoa01c577f2c2018-08-31 09:22:23 +01004223// example usage: BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Kevin May7d96b162021-02-03 17:38:41 +00004224TfLiteParserImpl::BufferRawPtr TfLiteParserImpl::GetBuffer(const ModelPtr& model, size_t bufferIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01004225{
4226 CHECK_BUFFER(model, bufferIndex);
4227 return model->buffers[bufferIndex].get();
4228}
4229
Matteo Martincigh747ef822018-12-18 09:26:39 +00004230template<typename T>
Kevin May7d96b162021-02-03 17:38:41 +00004231std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
4232TfLiteParserImpl::CreateConstTensorAndStoreData(TfLiteParserImpl::BufferRawPtr bufferPtr,
4233 TfLiteParserImpl::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +00004234 armnn::TensorInfo& tensorInfo,
4235 armnn::Optional<armnn::PermutationVector&> permutationVector)
4236{
Matthew Sloyan81beae32021-07-13 19:46:11 +01004237 // Make sure isConstant flag is set.
4238 tensorInfo.SetConstant();
4239
Matteo Martincigh747ef822018-12-18 09:26:39 +00004240 auto constData = CreateConstTensorImpl<T>(bufferPtr,
4241 tensorPtr,
4242 tensorInfo,
4243 permutationVector);
Kevin May7d96b162021-02-03 17:38:41 +00004244 TfLiteParserImpl::SupportedDataStorage storage(std::move(constData.second));
Matteo Martincigh747ef822018-12-18 09:26:39 +00004245 return std::make_pair(constData.first, std::move(storage));
4246}
4247
Finn Williamsd4fa5452021-03-01 12:31:41 +00004248bool TfLiteParserImpl::IsConstTensor(TensorRawPtr tensorPtr)
4249{
4250 CHECK_TENSOR_PTR(tensorPtr);
mathad01bf7edb62021-04-20 16:12:45 +01004251 bool isConst = true;
4252
4253 auto buffer = GetBuffer(m_Model, tensorPtr->buffer);
4254 if (buffer->data.size() == 0)
4255 {
4256 isConst = false;
4257 }
4258
4259 return isConst;
Finn Williamsd4fa5452021-03-01 12:31:41 +00004260}
4261
Kevin May7d96b162021-02-03 17:38:41 +00004262std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
Finn Williamsd4fa5452021-03-01 12:31:41 +00004263TfLiteParserImpl::CreateConstTensorPermuted(TensorRawPtr tensorPtr,
4264 armnn::TensorInfo& tensorInfo,
4265 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +01004266{
4267 CHECK_TENSOR_PTR(tensorPtr);
4268 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
4269 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
4270
Matthew Sloyan81beae32021-07-13 19:46:11 +01004271 // Make sure isConstant flag is set.
4272 tensorInfo.SetConstant();
4273
telsoa01c577f2c2018-08-31 09:22:23 +01004274 switch (tensorInfo.GetDataType())
4275 {
4276 case armnn::DataType::Float32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00004277 return CreateConstTensorAndStoreData<float>(bufferPtr,
4278 tensorPtr,
4279 tensorInfo,
4280 permutationVector);
Derek Lambertif90c56d2020-01-10 17:14:08 +00004281 case armnn::DataType::QAsymmU8:
Matteo Martincigh747ef822018-12-18 09:26:39 +00004282 return CreateConstTensorAndStoreData<uint8_t>(bufferPtr,
4283 tensorPtr,
4284 tensorInfo,
4285 permutationVector);
Keith Davisd305e1a2020-01-22 11:57:54 +00004286 case armnn::DataType::QSymmS8:
4287 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
4288 tensorPtr,
4289 tensorInfo,
4290 permutationVector);
Keith Davis67e6c542020-02-19 10:08:33 +00004291 case armnn::DataType::QAsymmS8:
4292 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
4293 tensorPtr,
4294 tensorInfo,
4295 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01004296 case armnn::DataType::Signed32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00004297 return CreateConstTensorAndStoreData<int32_t>(bufferPtr,
4298 tensorPtr,
4299 tensorInfo,
4300 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01004301 default:
4302 {
4303 std::stringstream errString;
4304 errString << "Unexpected datatype when creating const tensor: "
4305 << armnn::GetDataTypeName(tensorInfo.GetDataType())
4306 << " shape:" << tensorInfo.GetShape()
4307 << CHECK_LOCATION().AsString();
4308 throw ParseException(errString.str());
4309 }
4310 }
4311}
4312
Finn Williamsd4fa5452021-03-01 12:31:41 +00004313armnn::ConstTensor TfLiteParserImpl::CreateConstTensorNonPermuted(TensorRawPtr tensorPtr,
4314 armnn::TensorInfo& tensorInfo)
4315{
4316 CHECK_TENSOR_PTR(tensorPtr);
4317 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
4318 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
4319
Matthew Sloyan81beae32021-07-13 19:46:11 +01004320 // Make sure isConstant flag is set.
4321 tensorInfo.SetConstant();
4322
Finn Williamsd4fa5452021-03-01 12:31:41 +00004323 return ConstTensor(tensorInfo, bufferPtr->data.data());
4324}
4325
Kevin May7d96b162021-02-03 17:38:41 +00004326BindingPointInfo TfLiteParserImpl::GetNetworkInputBindingInfo(size_t subgraphId,
4327 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01004328{
4329 CHECK_SUBGRAPH(m_Model, subgraphId);
4330 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
Mike Kelly0d77ae12022-01-07 17:42:27 +00004331 for (auto const& input : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004332 {
4333 if (input.second->name == name)
4334 {
4335 auto bindingId = GenerateLayerBindingId(subgraphId, input.first);
Colm Donelan4bc993b2021-11-09 20:39:10 +00004336 auto inputTensorInfo = ToTensorInfo(input.second);
4337 // Input tensors are always treated as constant tensors during network execution.
4338 inputTensorInfo.SetConstant(true);
4339 return std::make_pair(bindingId, inputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01004340 }
4341 }
4342
4343 std::stringstream bindings;
Mike Kelly0d77ae12022-01-07 17:42:27 +00004344 for (auto const& input : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004345 {
4346 bindings << "'" << input.second->name << "' ";
4347 }
4348
4349 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004350 fmt::format("No input binding found for subgraph:{} and name:{}. "
4351 "Possible inputs are: [{}] {}",
4352 subgraphId,
4353 name,
4354 bindings.str(),
4355 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004356}
4357
Kevin May7d96b162021-02-03 17:38:41 +00004358BindingPointInfo TfLiteParserImpl::GetNetworkOutputBindingInfo(size_t subgraphId,
4359 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01004360{
4361 CHECK_SUBGRAPH(m_Model, subgraphId);
4362 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00004363 for (unsigned int i = 0; i < outputs.size(); ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01004364 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00004365 auto const output = outputs[i];
telsoa01c577f2c2018-08-31 09:22:23 +01004366 if (output.second->name == name)
4367 {
4368 auto bindingId = GenerateLayerBindingId(subgraphId, output.first);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00004369 std::vector<unsigned int> shape = m_OverridenOutputShapes.size() > 0 ?
4370 m_OverridenOutputShapes[i] : AsUnsignedVector(output.second->shape);
4371 return std::make_pair(bindingId, ToTensorInfo(output.second, shape));
telsoa01c577f2c2018-08-31 09:22:23 +01004372 }
4373 }
4374
4375 std::stringstream bindings;
Mike Kelly0d77ae12022-01-07 17:42:27 +00004376 for (auto const& output : outputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004377 {
4378 bindings << "'" << output.second->name << "' ";
4379 }
4380
4381 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01004382 fmt::format("No output binding found for subgraph:{} and name:{}. "
4383 "Possible outputs are: [{}] {}",
4384 subgraphId,
4385 name,
4386 bindings.str(),
4387 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01004388}
4389
Kevin May7d96b162021-02-03 17:38:41 +00004390size_t TfLiteParserImpl::GetSubgraphCount() const
telsoa01c577f2c2018-08-31 09:22:23 +01004391{
4392 return m_Model->subgraphs.size();
4393}
4394
Kevin May7d96b162021-02-03 17:38:41 +00004395std::vector<std::string> TfLiteParserImpl::GetSubgraphInputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01004396{
4397 CHECK_SUBGRAPH(m_Model, subgraphId);
4398 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
4399 std::vector<std::string> result;
4400 result.reserve(inputs.size());
Mike Kelly0d77ae12022-01-07 17:42:27 +00004401 for (auto const& input : inputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004402 {
4403 result.push_back(input.second->name);
4404 }
4405 return result;
4406}
4407
Kevin May7d96b162021-02-03 17:38:41 +00004408std::vector<std::string> TfLiteParserImpl::GetSubgraphOutputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01004409{
4410 CHECK_SUBGRAPH(m_Model, subgraphId);
4411 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
4412 std::vector<std::string> result;
4413 result.reserve(outputs.size());
Mike Kelly0d77ae12022-01-07 17:42:27 +00004414 for (auto const& output : outputs)
telsoa01c577f2c2018-08-31 09:22:23 +01004415 {
4416 result.push_back(output.second->name);
4417 }
4418 return result;
4419}
4420
Matthew Sloyanac001ee2021-02-03 10:43:04 +00004421const std::string TfLiteParserImpl::GetVersion()
4422{
4423 return TFLITE_PARSER_VERSION;
4424}
4425
Mike Kelly0d77ae12022-01-07 17:42:27 +00004426TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<float[]>&& data)
telsoa01c577f2c2018-08-31 09:22:23 +01004427: m_FloatData(std::move(data))
4428, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00004429, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01004430, m_Int32Data(nullptr)
4431{
4432}
4433
Mike Kelly0d77ae12022-01-07 17:42:27 +00004434TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<uint8_t[]>&& data)
telsoa01c577f2c2018-08-31 09:22:23 +01004435: m_FloatData(nullptr)
4436, m_Uint8Data(std::move(data))
Keith Davisd305e1a2020-01-22 11:57:54 +00004437, m_Int8Data(nullptr)
4438, m_Int32Data(nullptr)
4439{
4440}
4441
Mike Kelly0d77ae12022-01-07 17:42:27 +00004442TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int8_t[]>&& data)
Keith Davisd305e1a2020-01-22 11:57:54 +00004443: m_FloatData(nullptr)
4444, m_Uint8Data(nullptr)
4445, m_Int8Data(std::move(data))
telsoa01c577f2c2018-08-31 09:22:23 +01004446, m_Int32Data(nullptr)
4447{
4448}
4449
Mike Kelly0d77ae12022-01-07 17:42:27 +00004450TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int32_t[]>&& data)
telsoa01c577f2c2018-08-31 09:22:23 +01004451: m_FloatData(nullptr)
4452, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00004453, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01004454, m_Int32Data(std::move(data))
4455{
4456}
4457
4458} // armnnTfLiteParser