blob: f38f45fcdf46cb5de383b0642c3a1164cd258ab4 [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>
Francis Murtagh532a29d2020-06-29 11:50:01 +010023#include <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
79armnn::INetworkPtr ITfLiteParser::CreateNetworkFromBinary(const std::vector<uint8_t> & binaryContent)
80{
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
Kevin May7d96b162021-02-03 17:38:41 +0000116void CheckSubgraph(const TfLiteParserImpl::ModelPtr & model,
telsoa01c577f2c2018-08-31 09:22:23 +0100117 size_t subgraphIndex,
118 const CheckLocation & location)
119{
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
Kevin May7d96b162021-02-03 17:38:41 +0000144void CheckModel(const TfLiteParserImpl::ModelPtr & model,
telsoa01c577f2c2018-08-31 09:22:23 +0100145 size_t subgraphIndex,
146 size_t operatorIndex,
147 const CheckLocation & location)
148{
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
Kevin May7d96b162021-02-03 17:38:41 +0000186void CheckTensor(const TfLiteParserImpl::ModelPtr & model,
telsoa01c577f2c2018-08-31 09:22:23 +0100187 size_t subgraphIndex,
188 size_t tensorIndex,
189 const CheckLocation & location)
190{
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,
telsoa01c577f2c2018-08-31 09:22:23 +0100216 const CheckLocation & location)
217{
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
Kevin May7d96b162021-02-03 17:38:41 +0000228void CheckBuffer(const TfLiteParserImpl::ModelPtr & model,
telsoa01c577f2c2018-08-31 09:22:23 +0100229 size_t bufferIndex,
230 const CheckLocation & location)
231{
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,
telsoa01c577f2c2018-08-31 09:22:23 +0100264 const armnn::TensorInfo & tensorInfo,
265 uint32_t bufferId,
266 const CheckLocation & location)
267{
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
287#define CHECK_BUFFER_SIZE(BUFFER_PTR, TENSOR_INFO, BUFFER_ID) \
288 CheckBufferSize(BUFFER_PTR, TENSOR_INFO, BUFFER_ID, CHECK_LOCATION())
289
290bool IsActivationSupported(tflite::ActivationFunctionType activationType)
291{
292 switch(activationType)
293 {
294 case tflite::ActivationFunctionType_NONE:
295 case tflite::ActivationFunctionType_RELU:
296 case tflite::ActivationFunctionType_RELU6:
297 case tflite::ActivationFunctionType_TANH:
298 {
299 return true;
300 }
301 default:
302 {
303 return false;
304 }
305 }
306}
307
308#define CHECK_SUPPORTED_FUSED_ACTIVATION(OPTION, SUBGRAPH_INDEX, OPERATOR_INDEX) \
309 do { \
310 if (IsActivationSupported(OPTION->fused_activation_function) == false) \
311 { \
312 throw ParseException( \
James Ward58dec6b2020-09-11 17:32:44 +0100313 fmt::format("TfLite parser doesn't suppport fused activation: " \
314 "{}/{} in {} subgraph:{} operator:{} at {}", \
315 OPTION->fused_activation_function, \
316 tflite::EnumNameActivationFunctionType(\
317 OPTION->fused_activation_function), \
318 __func__, \
319 SUBGRAPH_INDEX, \
320 OPERATOR_INDEX, \
321 CHECK_LOCATION().FileLine())); \
telsoa01c577f2c2018-08-31 09:22:23 +0100322 } \
323 } while(false)
324
325
326std::vector<unsigned int> AsUnsignedVector(const std::vector<int32_t> & in)
327{
328 std::vector<unsigned int> result;
329 result.reserve(in.size());
330 for (auto & i : in)
331 {
mathad01c21025d2021-04-26 10:09:37 +0100332 // If the location of the input data is -1 then the input should be ignored.
333 if (i == -1)
334 {
335 continue;
336 }
telsoa01c577f2c2018-08-31 09:22:23 +0100337 result.push_back(CHECKED_NON_NEGATIVE(i));
338 }
339 return result;
340}
341
342void CalcPadding(uint32_t inputSize,
343 uint32_t filterSize,
344 uint32_t stride,
Pablo Tellof0bd6832019-04-26 17:58:13 +0100345 uint32_t dilation,
telsoa01c577f2c2018-08-31 09:22:23 +0100346 uint32_t& paddingFront,
347 uint32_t& paddingBack,
348 tflite::Padding padding)
349{
350 paddingFront = 0;
351 paddingBack = 0;
352 if (padding == tflite::Padding_SAME)
353 {
354 uint32_t outputSize = (inputSize + stride - 1) / stride;
Pablo Tellof0bd6832019-04-26 17:58:13 +0100355 uint32_t dilatedSize = filterSize + (dilation - 1) * (filterSize - 1);
356 uint32_t temp = (outputSize - 1) * stride + dilatedSize;
telsoa01c577f2c2018-08-31 09:22:23 +0100357 if (temp > inputSize)
358 {
359 paddingFront = (temp - inputSize) / 2;
360 paddingBack = (temp - inputSize) - paddingFront;
361 }
362 }
363}
364
Kevin May7d96b162021-02-03 17:38:41 +0000365armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr,
Sadik Armagand109a4d2020-07-28 10:42:13 +0100366 const std::vector<unsigned int>& shapes,
Sadik Armagand109a4d2020-07-28 10:42:13 +0100367 const bool outputTensor = false)
telsoa01c577f2c2018-08-31 09:22:23 +0100368{
369 armnn::DataType type;
370 CHECK_TENSOR_PTR(tensorPtr);
371
372 switch (tensorPtr->type)
373 {
374 case tflite::TensorType_UINT8:
Derek Lambertif90c56d2020-01-10 17:14:08 +0000375 type = armnn::DataType::QAsymmU8;
telsoa01c577f2c2018-08-31 09:22:23 +0100376 break;
377 case tflite::TensorType_FLOAT32:
378 type = armnn::DataType::Float32;
379 break;
Finn Williamsed66d142019-12-06 09:55:55 +0000380 case tflite::TensorType_INT8:
Keith Davis67e6c542020-02-19 10:08:33 +0000381 if (tensorPtr->quantization->zero_point.size() == 1)
Ryan OShea03181ff2020-02-07 17:22:22 +0000382 {
Keith Davis0c2eeac2020-02-11 16:51:50 +0000383 // Per-tensor
Ryan OShea03181ff2020-02-07 17:22:22 +0000384 type = armnn::DataType::QAsymmS8;
385 }
386 else
387 {
Keith Davis0c2eeac2020-02-11 16:51:50 +0000388 // Per-channel
Ryan OShea03181ff2020-02-07 17:22:22 +0000389 type = armnn::DataType::QSymmS8;
390 }
Finn Williamsed66d142019-12-06 09:55:55 +0000391 break;
392 case tflite::TensorType_INT16:
Derek Lambertif90c56d2020-01-10 17:14:08 +0000393 type = armnn::DataType::QSymmS16;
Finn Williamsed66d142019-12-06 09:55:55 +0000394 break;
telsoa01c577f2c2018-08-31 09:22:23 +0100395 case tflite::TensorType_INT32:
396 type = armnn::DataType::Signed32;
397 break;
Inki Daed4619e22020-09-10 15:33:54 +0900398 case tflite::TensorType_INT64:
399 type = armnn::DataType::Signed64;
400 break;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100401 case tflite::TensorType_BOOL:
402 type = armnn::DataType::Boolean;
403 break;
telsoa01c577f2c2018-08-31 09:22:23 +0100404 default:
405 {
406 CheckLocation location = CHECK_LOCATION();
407 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100408 fmt::format("Unsupported data type {} = {} for tensor: {}. {}",
409 tensorPtr->type,
410 tflite::EnumNameTensorType(tensorPtr->type),
411 tensorPtr->name,
412 location.AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100413 }
414 }
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100415 std::vector<unsigned int> safeShape = shapes;
Sadik Armagand109a4d2020-07-28 10:42:13 +0100416 bool isDynamic = false;
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100417 if (safeShape.size() == 0)
418 {
419 safeShape.push_back(1);
Sadik Armagand109a4d2020-07-28 10:42:13 +0100420 if (outputTensor)
421 {
422 isDynamic = true;
423 }
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100424 }
425
Keith Davisd305e1a2020-01-22 11:57:54 +0000426 float quantizationScale = 0.0f;
427 int32_t quantizationOffset = 0;
428
429 if (tensorPtr->quantization.get())
430 {
431 if (tensorPtr->quantization->scale.size() <= 1)
432 {
433 CHECK_VALID_SIZE(tensorPtr->quantization->zero_point.size(), 0, 1);
434 CHECK_VALID_SIZE(tensorPtr->quantization->zero_point.size(), 0, 1);
435
436 if (tensorPtr->quantization->scale.size() == 1)
437 {
438 quantizationScale = tensorPtr->quantization->scale[0];
439 }
440 if (tensorPtr->quantization->zero_point.size() == 1)
441 {
442 // NOTE: we lose precision here when converting from 64 bit to 32
Ryan OShea03181ff2020-02-07 17:22:22 +0000443 // but this is what we support at the moment in ArmNN
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100444 quantizationOffset = armnn::numeric_cast<int32_t>(tensorPtr->quantization->zero_point[0]);
Keith Davisd305e1a2020-01-22 11:57:54 +0000445 }
446
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100447 TensorShape tensorShape(armnn::numeric_cast<unsigned int>(safeShape.size()),
Sadik Armagand109a4d2020-07-28 10:42:13 +0100448 safeShape.data());
449 if (isDynamic)
450 {
451 tensorShape = TensorShape(1, false);
452 }
453 armnn::TensorInfo result(tensorShape,
454 type,
455 quantizationScale,
456 quantizationOffset);
Keith Davisd305e1a2020-01-22 11:57:54 +0000457 return result;
458 }
459 else
460 {
461 std::vector<float> quantizationScales;
462 std::vector<int32_t> quantizationOffsets;
463
464 // Scale
465 std::copy(tensorPtr->quantization->scale.begin(),
466 tensorPtr->quantization->scale.end(),
467 std::back_inserter(quantizationScales));
468
Keith Davis0c2eeac2020-02-11 16:51:50 +0000469 // QSymmS8 Per-axis
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100470 TensorShape tensorShape(armnn::numeric_cast<unsigned int>(safeShape.size()),
Sadik Armagand109a4d2020-07-28 10:42:13 +0100471 safeShape.data());
472 if (isDynamic)
473 {
474 tensorShape = TensorShape(1, false);
475 }
476 armnn::TensorInfo result(tensorShape,
477 type,
478 quantizationScales,
Jan Eilers7612bd62021-04-06 17:29:03 +0100479 armnn::numeric_cast<unsigned int>(tensorPtr->quantization->quantized_dimension));
Keith Davisd305e1a2020-01-22 11:57:54 +0000480 return result;
481 }
482 }
483 else
484 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100485 TensorShape tensorShape(armnn::numeric_cast<unsigned int>(safeShape.size()),
Sadik Armagand109a4d2020-07-28 10:42:13 +0100486 safeShape.data());
487 if (isDynamic)
488 {
489 tensorShape = TensorShape(1, false);
490 }
491 armnn::TensorInfo result(tensorShape,
Keith Davisd305e1a2020-01-22 11:57:54 +0000492 type,
493 quantizationScale,
494 quantizationOffset);
495 return result;
496 }
telsoa01c577f2c2018-08-31 09:22:23 +0100497}
498
Jan Eilers7612bd62021-04-06 17:29:03 +0100499armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr)
Narumol Prangnawarat4628d052019-02-25 17:26:05 +0000500{
501 auto const & dimensions = AsUnsignedVector(tensorPtr->shape);
Jan Eilers7612bd62021-04-06 17:29:03 +0100502 return ToTensorInfo(tensorPtr, dimensions);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +0000503}
504
Kevin May7d96b162021-02-03 17:38:41 +0000505armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr,
Sadik Armagand109a4d2020-07-28 10:42:13 +0100506 const bool outputTensor)
507{
508 auto const & dimensions = AsUnsignedVector(tensorPtr->shape);
Jan Eilers7612bd62021-04-06 17:29:03 +0100509 return ToTensorInfo(tensorPtr, dimensions, outputTensor);
Sadik Armagand109a4d2020-07-28 10:42:13 +0100510}
511
telsoa01c577f2c2018-08-31 09:22:23 +0100512template<typename T>
513std::pair<armnn::ConstTensor, std::unique_ptr<T[]>>
Kevin May7d96b162021-02-03 17:38:41 +0000514CreateConstTensorImpl(TfLiteParserImpl::BufferRawPtr bufferPtr,
515 TfLiteParserImpl::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +0000516 armnn::TensorInfo& tensorInfo,
517 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +0100518{
Jan Eilers8eb25602020-03-09 12:13:48 +0000519 IgnoreUnused(tensorPtr);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100520 ARMNN_ASSERT_MSG(tensorPtr != nullptr, "tensorPtr is null");
521 ARMNN_ASSERT_MSG(bufferPtr != nullptr,
James Ward58dec6b2020-09-11 17:32:44 +0100522 fmt::format("Buffer for buffer:{} is null", tensorPtr->buffer).c_str());
telsoa01c577f2c2018-08-31 09:22:23 +0100523
524 std::unique_ptr<T[]> data(new T[tensorInfo.GetNumElements()]);
Matteo Martincigh747ef822018-12-18 09:26:39 +0000525
526 if (permutationVector.has_value() && permutationVector.value().GetSize() > 0)
527 {
528 tensorInfo = armnnUtils::Permuted(tensorInfo, permutationVector.value());
Matteo Martincighd5b9e642019-01-04 18:01:21 +0000529 armnnUtils::Permute(tensorInfo.GetShape(), permutationVector.value(),
530 reinterpret_cast<const T*>(bufferPtr->data.data()), data.get(), sizeof(T));
Matteo Martincigh747ef822018-12-18 09:26:39 +0000531 }
532 else
533 {
534 ::memcpy(data.get(), bufferPtr->data.data(), tensorInfo.GetNumBytes());
535 }
536
telsoa01c577f2c2018-08-31 09:22:23 +0100537 return std::make_pair(ConstTensor(tensorInfo, data.get()), std::move(data));
538}
539
telsoa01c577f2c2018-08-31 09:22:23 +0100540armnn::LayerBindingId GenerateLayerBindingId(size_t subgraphIndex, size_t tensorIndex)
541{
542 // generate the binding id by shifting the tensor id by 8 bit
543 // and add the subgraph id, which allows 256 subgraphs
544 return static_cast<armnn::LayerBindingId>((tensorIndex<<8)+subgraphIndex);
545}
546
Aron Virginas-Tar70672f62019-01-23 14:00:00 +0000547bool CheckShape(const armnn::TensorShape& actual, const std::vector<int32_t>& expected)
548{
549 const unsigned int actualSize = actual.GetNumDimensions();
550 if (actualSize != expected.size())
551 {
552 return false;
553 }
554
555 for (unsigned int i = 0u; i < actualSize; i++)
556 {
557 if (expected[i] < 0 ||
558 actual[i] != static_cast<unsigned int>(expected[i]))
559 {
560 return false;
561 }
562 }
563
564 return true;
565}
566
James Conroy05102392020-06-24 15:39:55 +0100567void CheckMatchingQuantization(const TensorInfo& first,
568 const TensorInfo& second,
569 const std::string& descName,
570 std::string const& firstName,
571 std::string const& secondName)
572{
573 if (!first.IsQuantized() ||
574 !second.IsQuantized())
575 {
576 // Not a quantized type, ignore the validation
577 return;
578 }
579
580 DataType firstDataType = first.GetDataType();
581 DataType secondDataType = second.GetDataType();
582
583 if (firstDataType != secondDataType)
584 {
585 throw InvalidArgumentException(descName + ": " + firstName + " and " + secondName +
586 " must be of the same quantized type, " +
587 firstName + " is " + GetDataTypeName(firstDataType) + ", " +
588 secondName + " is " + GetDataTypeName(secondDataType));
589 }
590
591 if (!first.IsTypeSpaceMatch(second))
592 {
593 throw InvalidArgumentException(descName + ": " + firstName + " and " + secondName +
594 " must have the same quantization space, " +
595 firstName + " has offset " + std::to_string(first.GetQuantizationOffset()) +
596 " and scale " + std::to_string(first.GetQuantizationScale()) + ", " +
597 secondName + " has offset " + std::to_string(second.GetQuantizationOffset()) +
598 " and scale " + std::to_string(second.GetQuantizationScale()));
599 }
600}
601
telsoa01c577f2c2018-08-31 09:22:23 +0100602} // <anonymous>
603
Kevin May7d96b162021-02-03 17:38:41 +0000604TfLiteParserImpl::TfLiteParserImpl(const Optional<ITfLiteParser::TfLiteParserOptions>& options)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100605: m_Options(options)
606, m_Network(nullptr, nullptr)
Kevin May7d96b162021-02-03 17:38:41 +0000607, m_ParserFunctions(tflite::BuiltinOperator_MAX+1, &TfLiteParserImpl::ParseUnsupportedOperator)
telsoa01c577f2c2018-08-31 09:22:23 +0100608{
609 // register supported operators
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100610 m_ParserFunctions[tflite::BuiltinOperator_ABS] = &TfLiteParserImpl::ParseAbs;
Kevin May7d96b162021-02-03 17:38:41 +0000611 m_ParserFunctions[tflite::BuiltinOperator_ADD] = &TfLiteParserImpl::ParseAdd;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100612 m_ParserFunctions[tflite::BuiltinOperator_ARG_MIN] = &TfLiteParserImpl::ParseArgMin;
613 m_ParserFunctions[tflite::BuiltinOperator_ARG_MAX] = &TfLiteParserImpl::ParseArgMax;
Kevin May7d96b162021-02-03 17:38:41 +0000614 m_ParserFunctions[tflite::BuiltinOperator_AVERAGE_POOL_2D] = &TfLiteParserImpl::ParseAveragePool2D;
615 m_ParserFunctions[tflite::BuiltinOperator_BATCH_TO_SPACE_ND] = &TfLiteParserImpl::ParseBatchToSpaceND;
mathad01b392e982021-04-07 12:07:30 +0100616 m_ParserFunctions[tflite::BuiltinOperator_CAST] = &TfLiteParserImpl::ParseCast;
Kevin May7d96b162021-02-03 17:38:41 +0000617 m_ParserFunctions[tflite::BuiltinOperator_CONCATENATION] = &TfLiteParserImpl::ParseConcatenation;
618 m_ParserFunctions[tflite::BuiltinOperator_CONV_2D] = &TfLiteParserImpl::ParseConv2D;
619 m_ParserFunctions[tflite::BuiltinOperator_CUSTOM] = &TfLiteParserImpl::ParseCustomOperator;
620 m_ParserFunctions[tflite::BuiltinOperator_DEPTH_TO_SPACE] = &TfLiteParserImpl::ParseDepthToSpace;
621 m_ParserFunctions[tflite::BuiltinOperator_DEPTHWISE_CONV_2D] = &TfLiteParserImpl::ParseDepthwiseConv2D;
622 m_ParserFunctions[tflite::BuiltinOperator_DEQUANTIZE] = &TfLiteParserImpl::ParseDequantize;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100623 m_ParserFunctions[tflite::BuiltinOperator_DIV] = &TfLiteParserImpl::ParseDiv;
Kevin May7d96b162021-02-03 17:38:41 +0000624 m_ParserFunctions[tflite::BuiltinOperator_ELU] = &TfLiteParserImpl::ParseElu;
625 m_ParserFunctions[tflite::BuiltinOperator_EXP] = &TfLiteParserImpl::ParseExp;
626 m_ParserFunctions[tflite::BuiltinOperator_FULLY_CONNECTED] = &TfLiteParserImpl::ParseFullyConnected;
627 m_ParserFunctions[tflite::BuiltinOperator_GATHER] = &TfLiteParserImpl::ParseGather;
628 m_ParserFunctions[tflite::BuiltinOperator_HARD_SWISH] = &TfLiteParserImpl::ParseHardSwish;
629 m_ParserFunctions[tflite::BuiltinOperator_LEAKY_RELU] = &TfLiteParserImpl::ParseLeakyRelu;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100630 m_ParserFunctions[tflite::BuiltinOperator_LOGICAL_NOT] = &TfLiteParserImpl::ParseLogicalNot;
Kevin May7d96b162021-02-03 17:38:41 +0000631 m_ParserFunctions[tflite::BuiltinOperator_LOGISTIC] = &TfLiteParserImpl::ParseLogistic;
632 m_ParserFunctions[tflite::BuiltinOperator_L2_NORMALIZATION] = &TfLiteParserImpl::ParseL2Normalization;
633 m_ParserFunctions[tflite::BuiltinOperator_MAX_POOL_2D] = &TfLiteParserImpl::ParseMaxPool2D;
634 m_ParserFunctions[tflite::BuiltinOperator_MAXIMUM] = &TfLiteParserImpl::ParseMaximum;
635 m_ParserFunctions[tflite::BuiltinOperator_MEAN] = &TfLiteParserImpl::ParseMean;
636 m_ParserFunctions[tflite::BuiltinOperator_MINIMUM] = &TfLiteParserImpl::ParseMinimum;
637 m_ParserFunctions[tflite::BuiltinOperator_MUL] = &TfLiteParserImpl::ParseMul;
638 m_ParserFunctions[tflite::BuiltinOperator_NEG] = &TfLiteParserImpl::ParseNeg;
639 m_ParserFunctions[tflite::BuiltinOperator_PACK] = &TfLiteParserImpl::ParsePack;
640 m_ParserFunctions[tflite::BuiltinOperator_PAD] = &TfLiteParserImpl::ParsePad;
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +0100641 m_ParserFunctions[tflite::BuiltinOperator_PRELU] = &TfLiteParserImpl::ParsePrelu;
Kevin May7d96b162021-02-03 17:38:41 +0000642 m_ParserFunctions[tflite::BuiltinOperator_QUANTIZE] = &TfLiteParserImpl::ParseQuantize;
643 m_ParserFunctions[tflite::BuiltinOperator_RELU] = &TfLiteParserImpl::ParseRelu;
644 m_ParserFunctions[tflite::BuiltinOperator_RELU6] = &TfLiteParserImpl::ParseRelu6;
Sadik Armagana2747482021-02-09 10:28:54 +0000645 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MAX] = &TfLiteParserImpl::ParseReduceMax;
646 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MIN] = &TfLiteParserImpl::ParseReduceMin;
Kevin May7d96b162021-02-03 17:38:41 +0000647 m_ParserFunctions[tflite::BuiltinOperator_RESHAPE] = &TfLiteParserImpl::ParseReshape;
648 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_BILINEAR] = &TfLiteParserImpl::ParseResizeBilinear;
649 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_NEAREST_NEIGHBOR] = &TfLiteParserImpl::ParseResizeNearestNeighbor;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100650 m_ParserFunctions[tflite::BuiltinOperator_RSQRT] = &TfLiteParserImpl::ParseRsqrt;
Keith Davis0176fd82021-06-01 17:36:32 +0100651 m_ParserFunctions[tflite::BuiltinOperator_SHAPE] = &TfLiteParserImpl::ParseShape;
Kevin May7d96b162021-02-03 17:38:41 +0000652 m_ParserFunctions[tflite::BuiltinOperator_SLICE] = &TfLiteParserImpl::ParseSlice;
653 m_ParserFunctions[tflite::BuiltinOperator_SOFTMAX] = &TfLiteParserImpl::ParseSoftmax;
654 m_ParserFunctions[tflite::BuiltinOperator_SPACE_TO_BATCH_ND] = &TfLiteParserImpl::ParseSpaceToBatchND;
655 m_ParserFunctions[tflite::BuiltinOperator_SPLIT] = &TfLiteParserImpl::ParseSplit;
656 m_ParserFunctions[tflite::BuiltinOperator_SPLIT_V] = &TfLiteParserImpl::ParseSplitV;
657 m_ParserFunctions[tflite::BuiltinOperator_SQUEEZE] = &TfLiteParserImpl::ParseSqueeze;
658 m_ParserFunctions[tflite::BuiltinOperator_STRIDED_SLICE] = &TfLiteParserImpl::ParseStridedSlice;
659 m_ParserFunctions[tflite::BuiltinOperator_SUB] = &TfLiteParserImpl::ParseSub;
660 m_ParserFunctions[tflite::BuiltinOperator_SUM] = &TfLiteParserImpl::ParseSum;
661 m_ParserFunctions[tflite::BuiltinOperator_TANH] = &TfLiteParserImpl::ParseTanH;
662 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE] = &TfLiteParserImpl::ParseTranspose;
663 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE_CONV] = &TfLiteParserImpl::ParseTransposeConv;
664 m_ParserFunctions[tflite::BuiltinOperator_UNPACK] = &TfLiteParserImpl::ParseUnpack;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100665
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100666 // register supported custom operators
Kevin May7d96b162021-02-03 17:38:41 +0000667 m_CustomParserFunctions["TFLite_Detection_PostProcess"] = &TfLiteParserImpl::ParseDetectionPostProcess;
telsoa01c577f2c2018-08-31 09:22:23 +0100668}
669
Kevin May7d96b162021-02-03 17:38:41 +0000670void TfLiteParserImpl::ResetParser()
telsoa01c577f2c2018-08-31 09:22:23 +0100671{
672 m_Network = armnn::INetworkPtr(nullptr, nullptr);
673 m_Model = nullptr;
674 m_SubgraphConnections.clear();
675}
676
Kevin May7d96b162021-02-03 17:38:41 +0000677INetworkPtr TfLiteParserImpl::CreateNetworkFromBinaryFile(const char* graphFile)
telsoa01c577f2c2018-08-31 09:22:23 +0100678{
679 ResetParser();
680 m_Model = LoadModelFromFile(graphFile);
681 return CreateNetworkFromModel();
682}
683
Kevin May7d96b162021-02-03 17:38:41 +0000684INetworkPtr TfLiteParserImpl::CreateNetworkFromBinary(const std::vector<uint8_t> & binaryContent)
telsoa01c577f2c2018-08-31 09:22:23 +0100685{
686 ResetParser();
687 m_Model = LoadModelFromBinary(binaryContent.data(), binaryContent.size());
688 return CreateNetworkFromModel();
689}
690
Kevin May7d96b162021-02-03 17:38:41 +0000691INetworkPtr TfLiteParserImpl::CreateNetworkFromModel()
telsoa01c577f2c2018-08-31 09:22:23 +0100692{
Sadik Armagand109a4d2020-07-28 10:42:13 +0100693
694 using NetworkOptions = std::vector<BackendOptions>;
695 NetworkOptions networkOptions = {};
696 if (m_Options && m_Options.value().m_InferAndValidate)
697 {
698 BackendOptions shapeInferenceMethodOption("ShapeInferenceMethod",
699 {
700 { "InferAndValidate", true }
701 });
702
703 networkOptions.push_back(shapeInferenceMethodOption);
704 }
705
706 m_Network = INetwork::Create(networkOptions);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100707 ARMNN_ASSERT(m_Model.get() != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +0100708
telsoa01c577f2c2018-08-31 09:22:23 +0100709 if (m_Model->subgraphs.size() != 1)
710 {
711 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100712 fmt::format("Current TfLite parser only supports 1 subgraph. Current one has: {} {}",
713 m_Model->subgraphs.size(),
714 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100715 }
716
717 size_t subgraphIndex = 0;
Colm Donelan6350d272020-06-09 16:56:25 +0100718 size_t operatorIndex = 0;
719 try
telsoa01c577f2c2018-08-31 09:22:23 +0100720 {
Colm Donelan6350d272020-06-09 16:56:25 +0100721 for (SubgraphPtr const& subgraph : m_Model->subgraphs)
telsoa01c577f2c2018-08-31 09:22:23 +0100722 {
Colm Donelan6350d272020-06-09 16:56:25 +0100723 m_SubgraphConnections.emplace_back(subgraph->tensors.size());
724 for (OperatorPtr const& op : subgraph->operators)
telsoa01c577f2c2018-08-31 09:22:23 +0100725 {
Colm Donelan6350d272020-06-09 16:56:25 +0100726 auto const& opCodePtr = m_Model->operator_codes[op->opcode_index];
telsoa01c577f2c2018-08-31 09:22:23 +0100727 auto builtinCode = opCodePtr->builtin_code;
728
729 if (builtinCode > tflite::BuiltinOperator_MAX)
730 {
James Ward58dec6b2020-09-11 17:32:44 +0100731 throw ParseException(fmt::format("Operator code {} is out of range 0-{}. "
732 "subgraph:{} operator idx:{}. {}",
733 builtinCode, tflite::BuiltinOperator_MAX, subgraphIndex,
734 operatorIndex, CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100735 }
736
737 // lookup and call the parser function
Colm Donelan6350d272020-06-09 16:56:25 +0100738 auto& parserFunction = m_ParserFunctions[builtinCode];
telsoa01c577f2c2018-08-31 09:22:23 +0100739 (this->*parserFunction)(subgraphIndex, operatorIndex);
Colm Donelan6350d272020-06-09 16:56:25 +0100740 ++operatorIndex;
telsoa01c577f2c2018-08-31 09:22:23 +0100741 }
telsoa01c577f2c2018-08-31 09:22:23 +0100742
Colm Donelan6350d272020-06-09 16:56:25 +0100743 SetupInputLayers(subgraphIndex);
744 SetupOutputLayers(subgraphIndex);
745 SetupConstantLayers(subgraphIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100746
Colm Donelan6350d272020-06-09 16:56:25 +0100747 ++subgraphIndex;
748 operatorIndex = 0;
telsoa01c577f2c2018-08-31 09:22:23 +0100749 }
telsoa01c577f2c2018-08-31 09:22:23 +0100750 }
Colm Donelan6350d272020-06-09 16:56:25 +0100751 catch (const ParseException& e)
telsoa01c577f2c2018-08-31 09:22:23 +0100752 {
Colm Donelan6350d272020-06-09 16:56:25 +0100753 std::stringstream errorString;
754 errorString << "Failed to parse operator #" << operatorIndex << " within subgraph #"
755 << subgraphIndex << " error: " << e.what();
756 ARMNN_LOG(error) << errorString.str();
757 std::stringstream errors;
758 errors << errorString.str() << "\n";
telsoa01c577f2c2018-08-31 09:22:23 +0100759 throw ParseException(errors.str());
760 }
761
762 // establish the connections from the layer outputs to the inputs of the subsequent layers
Colm Donelan6350d272020-06-09 16:56:25 +0100763 for (subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100764 {
765 for (size_t tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
766 {
767 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot != nullptr)
768 {
769 for (size_t inputSlotIdx = 0;
770 inputSlotIdx < m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size();
771 ++inputSlotIdx)
772 {
773 m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot->Connect(
774 *(m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots[inputSlotIdx]));
775 }
776 }
777 }
778 }
779
780 return std::move(m_Network);
781}
782
Kevin May7d96b162021-02-03 17:38:41 +0000783void TfLiteParserImpl::RegisterProducerOfTensor(size_t subgraphIndex,
784 size_t tensorIndex,
785 armnn::IOutputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +0100786{
787 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100788 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
789 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100790
791 TensorSlots & tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
792
793 // assuming there is only one producer for that tensor
794 if (tensorSlots.outputSlot != nullptr)
795 {
James Ward58dec6b2020-09-11 17:32:44 +0100796 throw ParseException(fmt::format("Another layer has already registered itself as the producer of "
797 "subgraph:{} tensor:{} {}",
798 subgraphIndex,
799 tensorIndex,
800 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100801 }
802
803 tensorSlots.outputSlot = slot;
804}
805
Kevin May7d96b162021-02-03 17:38:41 +0000806void TfLiteParserImpl::RegisterConsumerOfTensor(size_t subgraphIndex,
807 size_t tensorIndex,
808 armnn::IInputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +0100809{
810 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100811 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
812 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100813
Finn Williamsd4fa5452021-03-01 12:31:41 +0000814 TensorSlots& tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +0100815 tensorSlots.inputSlots.push_back(slot);
816}
817
Kevin May7d96b162021-02-03 17:38:41 +0000818void TfLiteParserImpl::ParseCustomOperator(size_t subgraphIndex, size_t operatorIndex)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100819{
820 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
821
822 // NOTE: By default we presume the custom operator is not supported
Kevin May7d96b162021-02-03 17:38:41 +0000823 auto customParserFunction = &TfLiteParserImpl::ParseUnsupportedOperator;
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100824
825 // Identify custom code defined for custom operator
826 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
827 const auto& customCode = m_Model->operator_codes[operatorPtr->opcode_index]->custom_code;
828
829 // Find parser function that correspondes to custom code (if any)
830 auto iterator = m_CustomParserFunctions.find(customCode);
831 if (iterator != m_CustomParserFunctions.end())
832 {
833 customParserFunction = iterator->second;
834 }
835
836 // Run parser function
837 (this->*customParserFunction)(subgraphIndex, operatorIndex);
838}
839
Kevin May7d96b162021-02-03 17:38:41 +0000840void TfLiteParserImpl::ParseUnsupportedOperator(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100841{
842 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100843
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100844 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
845
846 auto opcodeIndex = operatorPtr->opcode_index;
847 auto opcode = m_Model->operator_codes[opcodeIndex]->builtin_code;
848
849 if (!m_Options || !m_Options.value().m_StandInLayerForUnsupported)
850 {
851 // Do not add StandInLayer, throw ParseException instead
852 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100853 fmt::format("Operator not supported. "
854 "subgraph:{} operator:{} "
855 "opcode_index:{} opcode:{} / {} {}",
856 subgraphIndex,
857 operatorIndex,
858 opcodeIndex,
859 opcode,
860 tflite::EnumNameBuiltinOperator(opcode),
861 CHECK_LOCATION().AsString()));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100862 }
863
864 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
865 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
866
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100867 const unsigned int numInputs = armnn::numeric_cast<unsigned int>(inputs.size());
868 const unsigned int numOutputs = armnn::numeric_cast<unsigned int>(outputs.size());
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100869
870 StandInDescriptor descriptor(numInputs, numOutputs);
James Ward58dec6b2020-09-11 17:32:44 +0100871 auto layerName = fmt::format("StandIn:{}:{}:{}", subgraphIndex, operatorIndex, opcode);
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100872
873 // Add a non-executable StandInLayer as a placeholder for any unsupported operator
874 IConnectableLayer* layer = m_Network->AddStandInLayer(descriptor, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +0100875 ARMNN_ASSERT(layer != nullptr);
876
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100877 for (unsigned int i = 0u; i < numOutputs; ++i)
878 {
Sadik Armagand109a4d2020-07-28 10:42:13 +0100879 layer->GetOutputSlot(i).SetTensorInfo(ToTensorInfo(outputs[i], true));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100880 }
881
882 auto inputTensorIds = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
883 auto outputTensorIds = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
884
885 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIds);
886 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIds);
telsoa01c577f2c2018-08-31 09:22:23 +0100887}
888
mathad01b392e982021-04-07 12:07:30 +0100889void TfLiteParserImpl::ParseCast(size_t subgraphIndex, size_t operatorIndex)
890{
891 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
892
893 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
894 CHECK_VALID_SIZE(inputs.size(), 1);
895 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
896 CHECK_VALID_SIZE(outputs.size(), 1);
897
898 auto layerName = fmt::format("Cast:{}:{}", subgraphIndex, operatorIndex);
899
900 IConnectableLayer* layer = m_Network->AddCastLayer(layerName.c_str());
901 ARMNN_ASSERT(layer != nullptr);
902
903 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
904 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
905
906 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
907 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
908
909 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
910 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
911}
912
Kevin May7d96b162021-02-03 17:38:41 +0000913void TfLiteParserImpl::ParseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100914{
915 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
916
917 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
918 const auto * options = operatorPtr->builtin_options.AsConv2DOptions();
919
920 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
921
922 Convolution2dDescriptor desc;
923 desc.m_BiasEnabled = false;
924 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
925 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +0000926 desc.m_DataLayout = armnn::DataLayout::NHWC;
Pablo Tellof0bd6832019-04-26 17:58:13 +0100927 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
928 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +0000929
telsoa01c577f2c2018-08-31 09:22:23 +0100930 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
931 CHECK_VALID_SIZE(inputs.size(), 2, 3);
932
933 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
934 CHECK_VALID_SIZE(outputs.size(), 1);
935
936 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
937 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
938
939 // assuming input is NHWC
940 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
941 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
942
943 // assuming the filter is OHWI : Output, H, W, Input
944 // which is essentially the same as NHWC
945 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
946 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
947
Pablo Tellof0bd6832019-04-26 17:58:13 +0100948 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
949 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
950 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
951 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +0100952
Finn Williamsd4fa5452021-03-01 12:31:41 +0000953 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo);
Matthew Jackson74bf7da2019-08-16 16:51:42 +0100954 armnn::IConnectableLayer* layer = nullptr;
telsoa01c577f2c2018-08-31 09:22:23 +0100955
James Ward58dec6b2020-09-11 17:32:44 +0100956 auto layerName = fmt::format("Conv2D:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100957
958 if (inputs.size() == 3)
959 {
960 desc.m_BiasEnabled = true;
961 armnn::TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +0000962 auto biasTensorAndData = CreateConstTensorNonPermuted(inputs[2], biasTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +0100963 layer = m_Network->AddConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +0000964 filterTensorAndData,
965 Optional<ConstTensor>(biasTensorAndData),
telsoa01c577f2c2018-08-31 09:22:23 +0100966 layerName.c_str());
967 }
968 else
969 {
970 layer = m_Network->AddConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +0000971 filterTensorAndData,
Matteo Martincighfc598e12019-05-14 10:36:13 +0100972 EmptyOptional(),
telsoa01c577f2c2018-08-31 09:22:23 +0100973 layerName.c_str());
974 }
975
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100976 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +0100977
Sadik Armagand109a4d2020-07-28 10:42:13 +0100978 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
jimfly01c25411c2018-11-14 17:47:22 +0000979 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +0100980
981 // register the input connection slots for the layer, connections are made after all layers have been created
982 // only the tensors for the inputs are relevant, exclude the const tensors
983 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +0000984 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
telsoa01c577f2c2018-08-31 09:22:23 +0100985
jimfly01c25411c2018-11-14 17:47:22 +0000986 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +0100987 // register the output connection slots for the layer, connections are made after all layers have been created
988 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
989 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
990}
991
Kevin May7d96b162021-02-03 17:38:41 +0000992void TfLiteParserImpl::ParseDepthwiseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100993{
994 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
995
996 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
997 const auto * options = operatorPtr->builtin_options.AsDepthwiseConv2DOptions();
998
999 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1000
1001 DepthwiseConvolution2dDescriptor desc;
1002 desc.m_BiasEnabled = false;
1003 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1004 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +00001005 desc.m_DataLayout = armnn::DataLayout::NHWC;
Matthew Jacksond6a9dee2019-07-22 13:53:24 +01001006 CHECKED_NON_NEGATIVE(options->depth_multiplier);
telsoa01c577f2c2018-08-31 09:22:23 +01001007
1008 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1009 CHECK_VALID_SIZE(inputs.size(), 2, 3);
1010 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1011 CHECK_VALID_SIZE(outputs.size(), 1);
Pablo Tellof0bd6832019-04-26 17:58:13 +01001012 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1013 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +00001014
telsoa01c577f2c2018-08-31 09:22:23 +01001015 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Jan Eilers7612bd62021-04-06 17:29:03 +01001016 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
telsoa01c577f2c2018-08-31 09:22:23 +01001017
Matteo Martincigh747ef822018-12-18 09:26:39 +00001018 // Assuming input is NHWC
telsoa01c577f2c2018-08-31 09:22:23 +01001019 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1020 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
Matteo Martincigh747ef822018-12-18 09:26:39 +00001021
1022 // TensorflowLite weights come in the format [1, H, W, I * M]
telsoa01c577f2c2018-08-31 09:22:23 +01001023 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1024 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1025
Pablo Tellof0bd6832019-04-26 17:58:13 +01001026 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1027 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1028 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1029 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +01001030
Jan Eilers53ef7952021-06-02 12:01:25 +01001031 // ArmNN uses the same filter tensor layout at TfLite [1, H, W, O] no need for any permutation
1032 auto filterTensor = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001033 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01001034 auto layerName = fmt::format("DepthwiseConv2D:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001035
1036 if (inputs.size() == 3)
1037 {
1038 desc.m_BiasEnabled = true;
1039 TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00001040 auto biasTensorAndData = CreateConstTensorNonPermuted(inputs[2], biasTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001041 layer = m_Network->AddDepthwiseConvolution2dLayer(desc,
Jan Eilers53ef7952021-06-02 12:01:25 +01001042 filterTensor,
Finn Williamsd4fa5452021-03-01 12:31:41 +00001043 Optional<ConstTensor>(biasTensorAndData),
telsoa01c577f2c2018-08-31 09:22:23 +01001044 layerName.c_str());
1045 }
1046 else
1047 {
1048 layer = m_Network->AddDepthwiseConvolution2dLayer(desc,
Jan Eilers53ef7952021-06-02 12:01:25 +01001049 filterTensor,
Matteo Martincighfc598e12019-05-14 10:36:13 +01001050 EmptyOptional(),
telsoa01c577f2c2018-08-31 09:22:23 +01001051 layerName.c_str());
1052 }
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001053 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01001054
Sadik Armagand109a4d2020-07-28 10:42:13 +01001055 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
jimfly01c25411c2018-11-14 17:47:22 +00001056 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001057
1058 // register the input connection slots for the layer, connections are made after all layers have been created
1059 // only the tensors for the inputs are relevant, exclude the const tensors
1060 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +00001061 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
telsoa01c577f2c2018-08-31 09:22:23 +01001062
jimfly01c25411c2018-11-14 17:47:22 +00001063 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +01001064 // register the output connection slots for the layer, connections are made after all layers have been created
1065 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1066 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1067}
1068
Kevin May7d96b162021-02-03 17:38:41 +00001069void TfLiteParserImpl::ParseDequantize(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsed66d142019-12-06 09:55:55 +00001070{
1071 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1072
1073 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1074 CHECK_VALID_SIZE(inputs.size(), 1);
1075
1076 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1077 CHECK_VALID_SIZE(outputs.size(), 1);
1078
James Ward58dec6b2020-09-11 17:32:44 +01001079 auto layerName = fmt::format("Dequantize:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsed66d142019-12-06 09:55:55 +00001080
1081 IConnectableLayer* layer = m_Network->AddDequantizeLayer(layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001082 ARMNN_ASSERT(layer != nullptr);
Finn Williamsed66d142019-12-06 09:55:55 +00001083
Sadik Armagand109a4d2020-07-28 10:42:13 +01001084 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Finn Williamsed66d142019-12-06 09:55:55 +00001085 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1086
1087 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1088 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1089
1090 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1091 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1092}
1093
Kevin May7d96b162021-02-03 17:38:41 +00001094void TfLiteParserImpl::ParseTranspose(size_t subgraphIndex, size_t operatorIndex)
Keith Davis4cd29a02019-09-09 14:49:20 +01001095{
1096 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1097
1098 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Kevin May85d92602019-09-27 17:21:06 +01001099 CHECK_VALID_SIZE(inputs.size(), 1, 2);
Keith Davis4cd29a02019-09-09 14:49:20 +01001100
1101 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1102 CHECK_VALID_SIZE(outputs.size(), 1);
1103
James Ward58dec6b2020-09-11 17:32:44 +01001104 auto layerName = fmt::format("Transpose:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly08759e22020-03-02 11:41:31 +00001105 TransposeDescriptor desc;
Keith Davis4cd29a02019-09-09 14:49:20 +01001106
josh minorba424d22019-11-13 10:55:17 -06001107 if (inputs.size() == 2)
Kevin May85d92602019-09-27 17:21:06 +01001108 {
1109 armnn::TensorInfo permuteTensorInfo = ToTensorInfo(inputs[1]);
1110 BufferRawPtr permuteBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
josh minorba424d22019-11-13 10:55:17 -06001111 auto numPermVecElements = permuteTensorInfo.GetNumElements();
1112 std::vector<unsigned int> permuteShape(numPermVecElements);
Kevin May85d92602019-09-27 17:21:06 +01001113 ::memcpy(permuteShape.data(), permuteBufferPtr->data.data(), permuteTensorInfo.GetNumBytes());
Mike Kelly08759e22020-03-02 11:41:31 +00001114 PermutationVector permutationVector(permuteShape.data(), permuteTensorInfo.GetNumElements());
Kevin May85d92602019-09-27 17:21:06 +01001115
Mike Kelly08759e22020-03-02 11:41:31 +00001116 desc = TransposeDescriptor(permutationVector);
Kevin May85d92602019-09-27 17:21:06 +01001117 }
1118
James Conroy05102392020-06-24 15:39:55 +01001119 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001120 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001121 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Keith Davis4cd29a02019-09-09 14:49:20 +01001122
James Conroy05102392020-06-24 15:39:55 +01001123 IConnectableLayer* layer = m_Network->AddTransposeLayer(desc, layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001124 ARMNN_ASSERT(layer != nullptr);
Keith Davis4cd29a02019-09-09 14:49:20 +01001125 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1126
1127 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1128 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1129
1130 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1131 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1132}
1133
Kevin May7d96b162021-02-03 17:38:41 +00001134void TfLiteParserImpl::ParseTransposeConv(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001135{
1136 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1137
1138 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1139 const auto * options = operatorPtr->builtin_options.AsTransposeConvOptions();
1140
1141 TransposeConvolution2dDescriptor desc;
1142 desc.m_BiasEnabled = false;
1143 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1144 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1145 desc.m_DataLayout = armnn::DataLayout::NHWC;
1146
1147 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
David Monahan61683802021-01-12 09:11:07 +00001148 if (inputs.size() == 4)
1149 {
1150 desc.m_BiasEnabled = true;
1151 }
1152 else
1153 {
1154 CHECK_VALID_SIZE(inputs.size(), 3);
1155 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001156
1157 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1158 CHECK_VALID_SIZE(outputs.size(), 1);
1159
Colm Donelan0ad3ef12020-07-03 15:54:28 +01001160 if (inputs[0])
1161 {
1162 armnn::TensorInfo tensorInfo = ToTensorInfo(inputs[0]);
1163 std::vector<int> output_shape(tensorInfo.GetNumElements());
1164 if (tensorInfo.GetDataType() == DataType::Signed32)
1165 {
1166 ::memcpy(output_shape.data(), GetBuffer(m_Model, inputs[0]->buffer)->data.data(), tensorInfo.GetNumBytes());
1167 }
1168 if (tensorInfo.GetDataType() == DataType::QAsymmU8)
1169 {
1170 for(unsigned int i=0; i < tensorInfo.GetNumElements(); i++)
1171 {
1172 output_shape[i] = GetBuffer(m_Model, inputs[0]->buffer)->data.data()[i];
1173 }
1174 }
1175 // Change from signed to unsigned int to store in TransposeConvolution2dDescriptor.
1176 for (int dimension : output_shape)
1177 {
1178 desc.m_OutputShape.push_back(static_cast<unsigned int>(dimension));
1179 }
1180 desc.m_OutputShapeEnabled = true;
1181 }
Matthew Jacksonccb25ea2019-08-20 17:18:33 +01001182 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[2]);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001183 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
1184
1185 // TfLite uses NHWC tensors
1186 const unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1187 const unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1188
1189 const unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1190 const unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1191
1192 CalcPadding(inputHeight,
1193 filterHeight,
1194 desc.m_StrideY,
1195 1, // DilationY
1196 desc.m_PadTop,
1197 desc.m_PadBottom,
1198 options->padding);
1199
1200 CalcPadding(inputWidth,
1201 filterWidth,
1202 desc.m_StrideX,
1203 1, // DilationX
1204 desc.m_PadLeft,
1205 desc.m_PadRight,
1206 options->padding);
1207
Finn Williamsd4fa5452021-03-01 12:31:41 +00001208 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001209
1210 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01001211 auto layerName = fmt::format("TransposeConv:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001212
David Monahan61683802021-01-12 09:11:07 +00001213 if (desc.m_BiasEnabled)
1214 {
1215 auto biasTensorInfo = ToTensorInfo(inputs[3]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00001216 auto biasConstTensor = CreateConstTensorNonPermuted(inputs[3], biasTensorInfo);
David Monahan61683802021-01-12 09:11:07 +00001217 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +00001218 filterTensorAndData,
1219 biasConstTensor,
David Monahan61683802021-01-12 09:11:07 +00001220 layerName.c_str());
1221 }
1222 else
1223 {
1224 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +00001225 filterTensorAndData,
David Monahan61683802021-01-12 09:11:07 +00001226 EmptyOptional(),
1227 layerName.c_str());
1228 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001229
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001230 ARMNN_ASSERT(layer != nullptr);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001231
Sadik Armagand109a4d2020-07-28 10:42:13 +01001232 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001233 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1234
1235 // only the tensors for the inputs are relevant, exclude the const (filter) tensor
1236 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Matthew Jacksonccb25ea2019-08-20 17:18:33 +01001237 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[2]});
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001238
1239 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1240 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1241}
1242
Kevin May7d96b162021-02-03 17:38:41 +00001243void TfLiteParserImpl::ParseAveragePool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001244{
1245 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Average);
1246}
1247
Kevin May7d96b162021-02-03 17:38:41 +00001248void TfLiteParserImpl::ParseBatchToSpaceND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001249{
1250 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1251
1252 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1253 CHECK_VALID_SIZE(inputs.size(), 3);
1254
1255 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1256 CHECK_VALID_SIZE(outputs.size(), 1);
1257
1258 armnn::TensorInfo blockShapeTensorInfo = ToTensorInfo(inputs[1]);
1259 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1260
1261 armnn::TensorInfo cropsTensorInfo = ToTensorInfo(inputs[2]);
1262 BufferRawPtr cropsBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1263
1264 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1265 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1266
1267 std::vector<unsigned int> cropsVector(cropsTensorInfo.GetNumElements());
1268 ::memcpy(cropsVector.data(), cropsBufferPtr->data.data(), cropsTensorInfo.GetNumBytes());
1269
1270 size_t step = 2;
1271 std::vector<std::pair<unsigned int, unsigned int>> crops;
1272 for (unsigned int i = 0; i < cropsTensorInfo.GetNumElements() / step; ++i)
1273 {
1274 crops.emplace_back(cropsVector[i * step], cropsVector[i * step + 1]);
1275 }
1276
1277 armnn::BatchToSpaceNdDescriptor desc;
1278 desc.m_BlockShape = blockShape;
1279 desc.m_Crops = crops;
1280 desc.m_DataLayout = armnn::DataLayout::NHWC;
1281
James Ward58dec6b2020-09-11 17:32:44 +01001282 auto layerName = fmt::format("BatchToSpaceND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001283
James Conroy05102392020-06-24 15:39:55 +01001284 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001285 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001286 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1287
1288 IConnectableLayer* layer = m_Network->AddBatchToSpaceNdLayer(desc, layerName.c_str());
1289 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001290 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1291
1292 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1293 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1294
1295 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1296 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1297}
1298
Kevin May7d96b162021-02-03 17:38:41 +00001299void TfLiteParserImpl::ParseL2Normalization(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson28c94572019-07-18 10:47:03 +01001300{
1301 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1302
1303 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1304 CHECK_VALID_SIZE(inputs.size(), 1);
1305
1306 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1307 CHECK_VALID_SIZE(outputs.size(), 1);
1308
1309 L2NormalizationDescriptor desc;
1310 desc.m_DataLayout = armnn::DataLayout::NHWC;
James Ward58dec6b2020-09-11 17:32:44 +01001311 auto layerName = fmt::format("L2Normalization:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson28c94572019-07-18 10:47:03 +01001312 IConnectableLayer* layer = m_Network->AddL2NormalizationLayer(desc, layerName.c_str());
1313
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001314 ARMNN_ASSERT(layer != nullptr);
Matthew Jackson28c94572019-07-18 10:47:03 +01001315
Sadik Armagand109a4d2020-07-28 10:42:13 +01001316 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jackson28c94572019-07-18 10:47:03 +01001317 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1318
1319 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1320 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1321
1322 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1323 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1324}
1325
Kevin May7d96b162021-02-03 17:38:41 +00001326void TfLiteParserImpl::ParseMaxPool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001327{
1328 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Max);
1329}
1330
Kevin May7d96b162021-02-03 17:38:41 +00001331void TfLiteParserImpl::ParseMaximum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001332{
1333 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1334
1335 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1336 CHECK_VALID_SIZE(inputs.size(), 2);
1337
1338 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1339 CHECK_VALID_SIZE(outputs.size(), 1);
1340
James Ward58dec6b2020-09-11 17:32:44 +01001341 auto layerName = fmt::format("Maximum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01001342
1343 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1344 TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1345 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001346
Sadik Armagand109a4d2020-07-28 10:42:13 +01001347 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001348 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1349
1350 IConnectableLayer* layer = m_Network->AddMaximumLayer(layerName.c_str());
1351 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001352 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1353
1354 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001355 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001356
1357 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1358 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1359}
1360
Kevin May7d96b162021-02-03 17:38:41 +00001361void TfLiteParserImpl::ParseMinimum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001362{
1363 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1364
1365 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1366 CHECK_VALID_SIZE(inputs.size(), 2);
1367
1368 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1369 CHECK_VALID_SIZE(outputs.size(), 1);
1370
James Ward58dec6b2020-09-11 17:32:44 +01001371 auto layerName = fmt::format("Minimum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01001372
1373 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1374 TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1375 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001376
Sadik Armagand109a4d2020-07-28 10:42:13 +01001377 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001378 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1379
1380 IConnectableLayer* layer = m_Network->AddMinimumLayer(layerName.c_str());
1381 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001382 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1383
1384 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001385 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001386
1387 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1388 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1389}
1390
Kevin May7d96b162021-02-03 17:38:41 +00001391void TfLiteParserImpl::ParsePool(size_t subgraphIndex,
1392 size_t operatorIndex,
1393 PoolingAlgorithm algorithm)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001394{
1395 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1396
1397 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1398 const auto * options = operatorPtr->builtin_options.AsPool2DOptions();
1399
1400 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1401
1402 std::string layerName;
1403
1404 switch (algorithm)
1405 {
1406 case PoolingAlgorithm::Average:
1407 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01001408 fmt::format("AveragePool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001409 break;
1410 case PoolingAlgorithm::Max:
1411 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01001412 fmt::format("MaxPool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001413 break;
1414 default:
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001415 ARMNN_ASSERT_MSG(false, "Unsupported Pooling Algorithm");
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001416 }
1417
1418 Pooling2dDescriptor desc;
1419
1420 desc.m_PoolType = algorithm;
1421 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1422 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1423 desc.m_PoolWidth = CHECKED_NON_NEGATIVE(options->filter_width);
1424 desc.m_PoolHeight = CHECKED_NON_NEGATIVE(options->filter_height);
1425 desc.m_PaddingMethod = PaddingMethod::Exclude;
1426 desc.m_OutputShapeRounding = OutputShapeRounding::Floor;
jimfly01c25411c2018-11-14 17:47:22 +00001427 desc.m_DataLayout = armnn::DataLayout::NHWC;
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001428
1429 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1430 CHECK_VALID_SIZE(inputs.size(), 1);
1431 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1432
1433 // assuming input is NHWC
1434 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1435 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1436
Pablo Tellof0bd6832019-04-26 17:58:13 +01001437 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, 1u,
1438 desc.m_PadTop, desc.m_PadBottom, options->padding);
1439 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, 1u,
1440 desc.m_PadLeft, desc.m_PadRight, options->padding);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001441
1442 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1443 CHECK_VALID_SIZE(outputs.size(), 1);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001444
Sadik Armagand109a4d2020-07-28 10:42:13 +01001445 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001446 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1447
1448 IConnectableLayer* layer = m_Network->AddPooling2dLayer(desc, layerName.c_str());
1449 ARMNN_ASSERT(layer != nullptr);
jimfly01c25411c2018-11-14 17:47:22 +00001450 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001451
1452 // register the input connection slots for the layer, connections are made after all layers have been created
1453 // only the tensors for the inputs are relevant, exclude the const tensors
1454 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +00001455 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001456
jimfly01c25411c2018-11-14 17:47:22 +00001457 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001458 // register the output connection slots for the layer, connections are made after all layers have been created
1459 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1460 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1461}
1462
Kevin May7d96b162021-02-03 17:38:41 +00001463void TfLiteParserImpl::ParseSlice(size_t subgraphIndex, size_t operatorIndex)
josh minorba424d22019-11-13 10:55:17 -06001464{
1465 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1466
1467 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1468 CHECK_VALID_SIZE(inputs.size(), 3);
1469 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1470 CHECK_VALID_SIZE(outputs.size(), 1);
1471
1472 SliceDescriptor desc;
1473
1474 // set begin tensor info for slice descriptor
1475 armnn::TensorInfo beginTensorInfo = ToTensorInfo(inputs[1]);
1476 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1477
1478 std::vector<unsigned int> begin(beginTensorInfo.GetNumElements());
1479 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
1480
1481 // set size tensor info for slice descriptor
1482 armnn::TensorInfo sizeTensorInfo = ToTensorInfo(inputs[2]);
1483 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1484
1485 std::vector<unsigned int> size(sizeTensorInfo.GetNumElements());
1486 ::memcpy(size.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
1487 desc = SliceDescriptor(begin, size);
1488
James Ward58dec6b2020-09-11 17:32:44 +01001489 auto layerName = fmt::format("Slice:{}:{}", subgraphIndex, operatorIndex);
josh minorba424d22019-11-13 10:55:17 -06001490
James Conroy05102392020-06-24 15:39:55 +01001491 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001492 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001493 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1494
1495 IConnectableLayer* const layer = m_Network->AddSliceLayer(desc, layerName.c_str());
josh minorba424d22019-11-13 10:55:17 -06001496 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1497
1498 // register the input connection slots for the layer, connections are made after all layers have been created
1499 // only the tensors for the inputs are relevant, exclude the const tensors
1500 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1501 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1502
1503 // register the output connection slots for the layer, connections are made after all layers have been created
1504 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1505 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1506}
1507
Kevin May7d96b162021-02-03 17:38:41 +00001508void TfLiteParserImpl::ParseSoftmax(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001509{
1510 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1511 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1512 const auto * options = operatorPtr->builtin_options.AsSoftmaxOptions();
1513
1514 SoftmaxDescriptor desc;
1515 desc.m_Beta = options->beta;
1516
1517 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1518 CHECK_VALID_SIZE(inputs.size(), 1);
1519 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1520 CHECK_VALID_SIZE(outputs.size(), 1);
1521
James Ward58dec6b2020-09-11 17:32:44 +01001522 auto layerName = fmt::format("Softmax:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001523 IConnectableLayer* const layer = m_Network->AddSoftmaxLayer(desc, layerName.c_str());
1524
Sadik Armagand109a4d2020-07-28 10:42:13 +01001525 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
telsoa01c577f2c2018-08-31 09:22:23 +01001526 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1527
1528 // register the input connection slots for the layer, connections are made after all layers have been created
1529 // only the tensors for the inputs are relevant, exclude the const tensors
1530 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1531 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1532
1533 // register the output connection slots for the layer, connections are made after all layers have been created
1534 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1535 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1536}
1537
Kevin May7d96b162021-02-03 17:38:41 +00001538void TfLiteParserImpl::ParseSpaceToBatchND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001539{
1540 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1541
1542 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1543 CHECK_VALID_SIZE(inputs.size(), 3);
1544
1545 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1546 CHECK_VALID_SIZE(outputs.size(), 1);
1547
1548 armnn::TensorInfo blockShapeTensorInfo = ToTensorInfo(inputs[1]);
1549 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1550
1551 armnn::TensorInfo padListTensorInfo = ToTensorInfo(inputs[2]);
1552 BufferRawPtr padListBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1553
1554 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1555 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1556
1557 std::vector<unsigned int> padListVector(padListTensorInfo.GetNumElements());
1558 ::memcpy(padListVector.data(), padListBufferPtr->data.data(), padListTensorInfo.GetNumBytes());
1559
1560 size_t step = 2;
1561 std::vector<std::pair<unsigned int, unsigned int>> padList;
1562 for (unsigned int i = 0; i < padListTensorInfo.GetNumElements() / step; ++i)
1563 {
1564 padList.emplace_back(padListVector[i * step], padListVector[i * step + 1]);
1565 }
1566
1567 armnn::SpaceToBatchNdDescriptor desc;
1568 desc.m_BlockShape = blockShape;
1569 desc.m_PadList = padList;
1570 desc.m_DataLayout = armnn::DataLayout::NHWC;
1571
James Ward58dec6b2020-09-11 17:32:44 +01001572 auto layerName = fmt::format("SpaceToBatchND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001573
James Conroy05102392020-06-24 15:39:55 +01001574 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001575 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001576 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1577
1578 IConnectableLayer* layer = m_Network->AddSpaceToBatchNdLayer(desc, layerName.c_str());
1579 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001580 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1581
1582 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1583 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1584
1585 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1586 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1587}
1588
Kevin May7d96b162021-02-03 17:38:41 +00001589armnn::TensorInfo TfLiteParserImpl::OutputShapeOfSqueeze(const std::vector<uint32_t> & squeezeDimsIn,
1590 const armnn::TensorInfo & inputTensorInfo)
telsoa01c577f2c2018-08-31 09:22:23 +01001591{
1592 CHECK_VALID_SIZE(squeezeDimsIn.size(), 0, 1, 2, 3, 4);
1593 std::vector<uint32_t> squeezeDims = squeezeDimsIn;
1594 static const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
1595
1596 if (inputTensorInfo.GetNumDimensions() > 4)
1597 {
1598 std::stringstream ss;
1599 ss << "Input tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
1600 << " shape:" << inputTensorInfo.GetShape() << " "
1601 << CHECK_LOCATION().AsString();
1602 throw ParseException(ss.str());
1603 }
1604
1605 if (squeezeDims.empty())
1606 {
1607 squeezeDims.assign(dimensionSequence,
1608 dimensionSequence+inputTensorInfo.GetNumDimensions());
1609 }
1610
1611 std::vector<uint32_t> outputDims;
1612 for(unsigned int i = 0; i < inputTensorInfo.GetNumDimensions(); i++)
1613 {
1614 bool skipSqueeze = (std::find(squeezeDims.begin(), squeezeDims.end(), i) == squeezeDims.end());
1615 auto currentDimension = inputTensorInfo.GetShape()[i];
1616 if (skipSqueeze || currentDimension != 1)
1617 {
1618 outputDims.push_back(currentDimension);
1619 }
1620 }
1621
1622 if (outputDims.size() > 4)
1623 {
1624 std::stringstream ss;
1625 ss << "Output tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
1626 << " shape:" << inputTensorInfo.GetShape() << " "
1627 << CHECK_LOCATION().AsString();
1628 throw ParseException(ss.str());
1629 }
1630
1631 TensorShape outShape = TensorShape(static_cast<unsigned int>(outputDims.size()),
1632 outputDims.data());
1633
1634 // we need to preserve the tensor type and the quantization data as well
1635 TensorInfo outTensorInfo = inputTensorInfo;
1636 outTensorInfo.SetShape(outShape);
1637
1638 return outTensorInfo;
1639}
1640
Keith Davis0176fd82021-06-01 17:36:32 +01001641void TfLiteParserImpl::ParseShape(size_t subgraphIndex, size_t operatorIndex)
1642{
1643 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1644
1645 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1646 CHECK_VALID_SIZE(inputs.size(), 1);
1647 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1648 CHECK_VALID_SIZE(outputs.size(), 1);
1649
1650 auto layerName = fmt::format("Shape:{}:{}", subgraphIndex, operatorIndex);
1651
1652 IConnectableLayer* layer = m_Network->AddShapeLayer(layerName.c_str());
1653 ARMNN_ASSERT(layer != nullptr);
1654
1655
1656 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1657 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1658
1659 // Check if output tensor type is Signed32 or Signed64
1660 if (outputTensorInfo.GetDataType() != armnn::DataType::Signed32 &&
1661 outputTensorInfo.GetDataType() != armnn::DataType::Signed64)
1662 {
1663 throw ParseException(
1664 fmt::format(
1665 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
1666 CHECK_LOCATION().AsString()));
1667 }
1668
1669 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1670 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1671
1672 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1673 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1674}
1675
Kevin May7d96b162021-02-03 17:38:41 +00001676void TfLiteParserImpl::ParseSqueeze(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001677{
1678 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1679
1680 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1681 CHECK_VALID_SIZE(inputs.size(), 1);
1682
1683 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1684 CHECK_VALID_SIZE(outputs.size(), 1);
1685
1686 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1687 const auto * options = operatorPtr->builtin_options.AsSqueezeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01001688 auto layerName = fmt::format("Squeeze:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001689
1690 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1691 armnn::TensorInfo outputTensorInfo =
Kevin May7d96b162021-02-03 17:38:41 +00001692 TfLiteParserImpl::OutputShapeOfSqueeze(AsUnsignedVector(options->squeeze_dims),
telsoa01c577f2c2018-08-31 09:22:23 +01001693 inputTensorInfo);
James Conroy05102392020-06-24 15:39:55 +01001694 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
telsoa01c577f2c2018-08-31 09:22:23 +01001695
1696 ReshapeDescriptor reshapeDesc;
1697 reshapeDesc.m_TargetShape = outputTensorInfo.GetShape();
1698
telsoa01c577f2c2018-08-31 09:22:23 +01001699 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001700 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01001701 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1702
1703 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1704 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1705
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::ParseStridedSlice(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves451d95b2019-02-12 22:59:22 -02001711{
1712 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1713
1714 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1715 CHECK_VALID_SIZE(inputs.size(), 4);
1716
1717 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1718 CHECK_VALID_SIZE(outputs.size(), 1);
1719
1720 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1721 const auto * options = operatorPtr->builtin_options.AsStridedSliceOptions();
1722
1723 StridedSliceDescriptor desc;
1724 desc.m_BeginMask = options->begin_mask;
1725 desc.m_EllipsisMask = options->ellipsis_mask;
1726 desc.m_EndMask = options->end_mask;
1727 desc.m_NewAxisMask = options->new_axis_mask;
1728 desc.m_ShrinkAxisMask = options->shrink_axis_mask;
1729 desc.m_DataLayout = armnn::DataLayout::NHWC;
1730
1731 armnn::TensorInfo beginTensorInfo = ToTensorInfo(inputs[1]);
1732 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1733
1734 std::vector<int> begin(beginTensorInfo.GetNumElements());
1735 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
1736
1737 armnn::TensorInfo endTensorInfo = ToTensorInfo(inputs[2]);
1738 BufferRawPtr endBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1739
1740 std::vector<int> end(endTensorInfo.GetNumElements());
1741 ::memcpy(end.data(), endBufferPtr->data.data(), endTensorInfo.GetNumBytes());
1742
1743 armnn::TensorInfo strideTensorInfo = ToTensorInfo(inputs[3]);
1744 BufferRawPtr strideBufferPtr = GetBuffer(m_Model, inputs[3]->buffer);
1745
1746 std::vector<int> stride(strideTensorInfo.GetNumElements());
1747 ::memcpy(stride.data(), strideBufferPtr->data.data(), strideTensorInfo.GetNumBytes());
1748
1749 desc.m_Begin = begin;
1750 desc.m_End = end;
1751 desc.m_Stride = stride;
1752
James Ward58dec6b2020-09-11 17:32:44 +01001753 auto layerName = fmt::format("StridedSlice:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02001754 IConnectableLayer* layer = m_Network->AddStridedSliceLayer(desc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001755 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02001756
Sadik Armagand109a4d2020-07-28 10:42:13 +01001757 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02001758 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1759
1760 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1761 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1762
1763 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1764 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1765}
1766
Kevin May7d96b162021-02-03 17:38:41 +00001767void TfLiteParserImpl::ParseSub(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001768{
1769 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1770
1771 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1772 const auto * options = operatorPtr->builtin_options.AsSubOptions();
1773
1774 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1775 CHECK_VALID_SIZE(inputs.size(), 2);
1776
1777 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1778 CHECK_VALID_SIZE(outputs.size(), 1);
1779
1780 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1781 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1782
James Ward58dec6b2020-09-11 17:32:44 +01001783 auto layerName = fmt::format("Sub:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001784 IConnectableLayer* layer = m_Network->AddSubtractionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001785 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001786
Sadik Armagand109a4d2020-07-28 10:42:13 +01001787 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001788 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1789
1790 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001791 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001792
1793 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1794
1795 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1796 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1797}
1798
Kevin May7d96b162021-02-03 17:38:41 +00001799void TfLiteParserImpl::ParseDiv(size_t subgraphIndex, size_t operatorIndex)
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301800{
1801 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1802
1803 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1804 const auto * options = operatorPtr->builtin_options.AsDivOptions();
1805
1806 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1807 CHECK_VALID_SIZE(inputs.size(), 2);
1808
1809 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1810 CHECK_VALID_SIZE(outputs.size(), 1);
1811
1812 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1813 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1814
James Ward58dec6b2020-09-11 17:32:44 +01001815 auto layerName = fmt::format("Div:{}:{}", subgraphIndex, operatorIndex);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301816 IConnectableLayer* layer = m_Network->AddDivisionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001817 ARMNN_ASSERT(layer != nullptr);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301818
Sadik Armagand109a4d2020-07-28 10:42:13 +01001819 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301820 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1821
1822 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001823 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301824 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1825
1826 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1827 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1828}
1829
Kevin May7d96b162021-02-03 17:38:41 +00001830void TfLiteParserImpl::ParseAdd(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001831{
1832 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1833
1834 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1835 const auto * options = operatorPtr->builtin_options.AsAddOptions();
1836
1837 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1838 CHECK_VALID_SIZE(inputs.size(), 2);
1839
1840 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1841 CHECK_VALID_SIZE(outputs.size(), 1);
1842
Bruno Goncalves9c761a62018-12-27 14:20:35 -02001843 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1844 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1845
James Ward58dec6b2020-09-11 17:32:44 +01001846 auto layerName = fmt::format("Add:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001847 IConnectableLayer* layer = m_Network->AddAdditionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001848 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001849
Sadik Armagand109a4d2020-07-28 10:42:13 +01001850 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001851 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1852
1853 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001854 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001855 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1856
1857 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1858 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1859}
1860
Kevin May7d96b162021-02-03 17:38:41 +00001861void TfLiteParserImpl::ParseMul(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001862{
1863 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1864
1865 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1866 const auto * options = operatorPtr->builtin_options.AsMulOptions();
1867
1868 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1869 CHECK_VALID_SIZE(inputs.size(), 2);
1870
1871 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1872 CHECK_VALID_SIZE(outputs.size(), 1);
1873
Bruno Goncalves9c761a62018-12-27 14:20:35 -02001874 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1875 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1876
James Ward58dec6b2020-09-11 17:32:44 +01001877 auto layerName = fmt::format("Mul:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001878 IConnectableLayer* layer = m_Network->AddMultiplicationLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001879 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001880
Sadik Armagand109a4d2020-07-28 10:42:13 +01001881 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001882 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1883
1884 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001885 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001886 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1887
1888 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1889 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1890}
1891
Kevin May7d96b162021-02-03 17:38:41 +00001892void TfLiteParserImpl::ParseMean(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves2235cee2018-12-19 12:51:45 -02001893{
1894 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1895
1896 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1897
1898 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1899 CHECK_VALID_SIZE(outputs.size(), 1);
1900
1901 armnn::TensorInfo dimTensorInfo = ToTensorInfo(inputs[1]);
1902 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1903
1904 armnn::MeanDescriptor desc;
1905 std::vector<unsigned int> axis(dimTensorInfo.GetNumElements());
1906 ::memcpy(axis.data(), bufferPtr->data.data(), dimTensorInfo.GetNumBytes());
1907 desc.m_Axis = axis;
1908
1909 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001910 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02001911
1912 desc.m_KeepDims =
1913 inputTensorInfo.GetNumDimensions() == outputTensorInfo.GetNumDimensions() ?
1914 true : false;
1915
James Ward58dec6b2020-09-11 17:32:44 +01001916 auto layerName = fmt::format("Mean:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02001917 IConnectableLayer* layer = m_Network->AddMeanLayer(desc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001918 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02001919
1920 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1921
1922 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1923 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1924
1925 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1926 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1927}
1928
Kevin May7d96b162021-02-03 17:38:41 +00001929void TfLiteParserImpl::ParsePad(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001930{
1931 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1932
Kevin May7d96b162021-02-03 17:38:41 +00001933 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001934
Kevin May7d96b162021-02-03 17:38:41 +00001935 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001936 CHECK_VALID_SIZE(outputs.size(), 1);
1937
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00001938 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1939
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001940 armnn::TensorInfo padTensorInfo = ToTensorInfo(inputs[1]);
1941 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1942
1943 std::vector<unsigned int> padBuffer(padTensorInfo.GetNumElements());
1944 ::memcpy(padBuffer.data(), bufferPtr->data.data(), padTensorInfo.GetNumBytes());
1945
1946 size_t step = 2;
1947 armnn::PadDescriptor desc;
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00001948 if (inputTensorInfo.IsQuantized())
1949 {
1950 desc.m_PadValue = static_cast<float>(inputTensorInfo.GetQuantizationOffset());
1951 }
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001952 for (unsigned int i = 0; i < padTensorInfo.GetNumElements() / step; ++i)
1953 {
1954 desc.m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
1955 }
1956
James Ward58dec6b2020-09-11 17:32:44 +01001957 auto layerName = fmt::format("Pad:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001958 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001959
1960 IConnectableLayer* layer = m_Network->AddPadLayer(desc, layerName.c_str());
1961 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001962 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1963
1964 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1965 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1966
1967 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1968 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1969}
1970
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01001971void TfLiteParserImpl::ParsePrelu(size_t subgraphIndex, size_t operatorIndex)
1972{
1973 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1974
1975 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1976 CHECK_VALID_SIZE(inputs.size(), 2);
1977
1978 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1979 CHECK_VALID_SIZE(outputs.size(), 1);
1980
1981 auto layerName = fmt::format("Prelu:{}:{}", subgraphIndex, operatorIndex);
1982
1983 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1984 armnn::TensorInfo alphaTensorInfo = ToTensorInfo(inputs[1]);
1985 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
1986 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1987
1988 IConnectableLayer* layer = m_Network->AddPreluLayer(layerName.c_str());
1989 ARMNN_ASSERT(layer != nullptr);
1990 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1991
1992 if (IsConstTensor(inputs[1]))
1993 {
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01001994 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawaratbf99b5f2021-05-27 09:55:43 +01001995 armnn::IInputSlot* slot = &(layer->GetInputSlot(0));
1996 RegisterConsumerOfTensor(subgraphIndex, inputTensorIndexes[0], slot);
Narumol Prangnawaratbfaee6b2021-05-24 18:50:24 +01001997
1998 auto alphaTensorAndData = CreateConstTensorNonPermuted(inputs[1], alphaTensorInfo);
1999 std::string constLayerName = fmt::format("Constant:{}", inputs[1]->name);
2000 IConnectableLayer* constLayer =
2001 m_Network->AddConstantLayer(alphaTensorAndData, constLayerName.c_str());
2002 ARMNN_ASSERT(constLayer != nullptr);
2003
2004 constLayer->GetOutputSlot(0).SetTensorInfo(alphaTensorInfo);
2005 constLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(1));
2006 RegisterOutputSlots(subgraphIndex,
2007 VIRTUAL_OPERATOR_ID,
2008 constLayer,
2009 { inputTensorIndexes[1] });
2010 }
2011 else
2012 {
2013 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2014 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIndexes);
2015 }
2016
2017 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2018 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2019}
2020
Kevin May7d96b162021-02-03 17:38:41 +00002021void TfLiteParserImpl::ParseQuantize(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan66dedc72019-12-10 16:32:07 +00002022{
2023 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2024
2025 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2026 CHECK_VALID_SIZE(inputs.size(), 1);
2027
2028 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2029 CHECK_VALID_SIZE(outputs.size(), 1);
2030
James Ward58dec6b2020-09-11 17:32:44 +01002031 auto layerName = fmt::format("Quantize:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan66dedc72019-12-10 16:32:07 +00002032
2033 IConnectableLayer* layer = m_Network->AddQuantizeLayer(layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002034 ARMNN_ASSERT(layer != nullptr);
Sadik Armagan66dedc72019-12-10 16:32:07 +00002035
Sadik Armagand109a4d2020-07-28 10:42:13 +01002036 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan66dedc72019-12-10 16:32:07 +00002037 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2038
2039 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2040 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2041
2042 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2043 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2044}
Finn Williamsc42c3842019-01-22 14:18:11 +00002045
Kevin May7d96b162021-02-03 17:38:41 +00002046void TfLiteParserImpl::ParseRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01002047{
Finn Williamsc42c3842019-01-22 14:18:11 +00002048 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::ReLu);
Sadik Armagan58f39192018-09-17 14:14:39 +01002049}
2050
Kevin May7d96b162021-02-03 17:38:41 +00002051void TfLiteParserImpl::ParseRelu6(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01002052{
Finn Williamsc42c3842019-01-22 14:18:11 +00002053 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::BoundedReLu);
2054}
Sadik Armagan58f39192018-09-17 14:14:39 +01002055
Kevin May7d96b162021-02-03 17:38:41 +00002056void TfLiteParserImpl::ParseLeakyRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan12239e72020-05-27 11:06:17 +01002057{
Jan Eilers2f746b32020-07-28 14:00:06 +01002058 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::LeakyReLu);
Sadik Armagan12239e72020-05-27 11:06:17 +01002059}
2060
Kevin May7d96b162021-02-03 17:38:41 +00002061void TfLiteParserImpl::ParseLogistic(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsc42c3842019-01-22 14:18:11 +00002062{
2063 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::Sigmoid);
2064}
2065
Kevin May7d96b162021-02-03 17:38:41 +00002066void TfLiteParserImpl::ParseTanH(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd99851762019-04-09 09:37:38 +01002067{
2068 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::TanH);
2069}
2070
Kevin May7d96b162021-02-03 17:38:41 +00002071void TfLiteParserImpl::ParseElu(size_t subgraphIndex, size_t operatorIndex)
Matthew Sloyan7515d072020-12-16 12:50:01 +00002072{
2073 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::Elu);
2074}
2075
Kevin May7d96b162021-02-03 17:38:41 +00002076void TfLiteParserImpl::ParseHardSwish(size_t subgraphIndex, size_t operatorIndex)
Jan Eilers2f746b32020-07-28 14:00:06 +01002077{
2078 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::HardSwish);
2079}
Finn Williamsc42c3842019-01-22 14:18:11 +00002080
Kevin May7d96b162021-02-03 17:38:41 +00002081void TfLiteParserImpl::ParseActivation(size_t subgraphIndex, size_t operatorIndex, ActivationFunction activationType)
Finn Williamsc42c3842019-01-22 14:18:11 +00002082{
2083 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan58f39192018-09-17 14:14:39 +01002084 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Jan Eilers8eb25602020-03-09 12:13:48 +00002085 IgnoreUnused(operatorPtr);
Sadik Armagan58f39192018-09-17 14:14:39 +01002086
2087 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2088 CHECK_VALID_SIZE(inputs.size(), 1);
2089
2090 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2091 CHECK_VALID_SIZE(outputs.size(), 1);
2092
James Ward58dec6b2020-09-11 17:32:44 +01002093 auto layerName = fmt::format("Activation:");
Sadik Armagan58f39192018-09-17 14:14:39 +01002094 ActivationDescriptor activationDesc;
Finn Williamsc42c3842019-01-22 14:18:11 +00002095 activationDesc.m_Function = activationType;
2096
2097 switch (activationType)
2098 {
2099 case ActivationFunction::ReLu:
2100 {
James Ward58dec6b2020-09-11 17:32:44 +01002101 layerName += fmt::format("RELU:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002102 break;
2103 }
2104 case ActivationFunction::BoundedReLu:
2105 {
James Ward58dec6b2020-09-11 17:32:44 +01002106 layerName += fmt::format("RELU6:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002107 activationDesc.m_A = 6.0f;
2108 activationDesc.m_B = 0.0f;
2109 break;
2110 }
2111 case ActivationFunction::Sigmoid:
2112 {
James Ward58dec6b2020-09-11 17:32:44 +01002113 layerName += fmt::format("SIGMOID:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002114 break;
2115 }
Nina Drozd99851762019-04-09 09:37:38 +01002116 case ActivationFunction::TanH:
2117 {
James Ward58dec6b2020-09-11 17:32:44 +01002118 layerName += fmt::format("TANH:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd99851762019-04-09 09:37:38 +01002119 activationDesc.m_A = 1.0f;
2120 activationDesc.m_B = 1.0f;
2121 break;
2122 }
Sadik Armagan12239e72020-05-27 11:06:17 +01002123 case ActivationFunction::LeakyReLu:
2124 {
James Ward58dec6b2020-09-11 17:32:44 +01002125 layerName += fmt::format("LEAKYRELU:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan12239e72020-05-27 11:06:17 +01002126 const auto * options = operatorPtr->builtin_options.AsLeakyReluOptions();
2127 activationDesc.m_A = options->alpha;
2128 break;
2129 }
Matthew Sloyan7515d072020-12-16 12:50:01 +00002130 case ActivationFunction::Elu:
2131 {
2132 layerName += fmt::format("ELU:{}:{}", subgraphIndex, operatorIndex);
2133 activationDesc.m_A = 1.0f;
2134 break;
2135 }
Jan Eilers2f746b32020-07-28 14:00:06 +01002136 case ActivationFunction::HardSwish:
Matthew Sloyan7515d072020-12-16 12:50:01 +00002137 {
James Ward58dec6b2020-09-11 17:32:44 +01002138 layerName += fmt::format("HARDSWISH:{}:{}", subgraphIndex, operatorIndex);
Jan Eilers2f746b32020-07-28 14:00:06 +01002139 break;
Matthew Sloyan7515d072020-12-16 12:50:01 +00002140 }
Finn Williamsc42c3842019-01-22 14:18:11 +00002141 default:
2142 {
2143 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002144 fmt::format("Unexpected ActivationFunction[{}] when creating layerName {} ",
2145 static_cast<int>(activationType), CHECK_LOCATION().AsString()));
Finn Williamsc42c3842019-01-22 14:18:11 +00002146 }
2147 }
2148
2149 IConnectableLayer* const layer = m_Network->AddActivationLayer(activationDesc, layerName.c_str());
Sadik Armagan58f39192018-09-17 14:14:39 +01002150
Sadik Armagand109a4d2020-07-28 10:42:13 +01002151 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan58f39192018-09-17 14:14:39 +01002152 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2153
2154 // register the input connection slots for the layer, connections are made after all layers have been created
2155 // only the tensors for the inputs are relevant, exclude the const tensors
2156 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2157 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2158
2159 // register the output connection slots for the layer, connections are made after all layers have been created
2160 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2161 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2162}
Kevin May7d96b162021-02-03 17:38:41 +00002163armnn::TensorInfo TfLiteParserImpl::OutputShapeOfReshape(const armnn::TensorInfo & inputTensorInfo,
2164 const std::vector<int32_t> & targetDimsIn)
Sadikb94967b2018-09-19 15:30:00 +01002165{
2166 std::vector<unsigned int> outputDims(targetDimsIn.begin(), targetDimsIn.end());
2167 const auto stretchDim = std::find(targetDimsIn.begin(), targetDimsIn.end(), -1);
2168
2169 if (stretchDim != targetDimsIn.end())
2170 {
2171 if (std::find(std::next(stretchDim), targetDimsIn.end(), -1) != targetDimsIn.end())
2172 {
2173 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002174 fmt::format("At most one component of shape can be -1 {}", CHECK_LOCATION().AsString()));
Sadikb94967b2018-09-19 15:30:00 +01002175 }
2176
2177 auto targetNumElements =
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002178 armnn::numeric_cast<unsigned int>(
Sadikb94967b2018-09-19 15:30:00 +01002179 std::accumulate(targetDimsIn.begin(), targetDimsIn.end(), -1, std::multiplies<int32_t>()));
2180
2181 auto stretchIndex = static_cast<size_t>(std::distance(targetDimsIn.begin(), stretchDim));
2182 outputDims[stretchIndex] = inputTensorInfo.GetNumElements() / targetNumElements;
2183 }
2184
2185 TensorShape outputShape = TensorShape(static_cast<unsigned int>(outputDims.size()), outputDims.data());
2186
2187 TensorInfo reshapeInfo = inputTensorInfo;
2188 reshapeInfo.SetShape(outputShape);
2189
2190 return reshapeInfo;
2191}
2192
Kevin May7d96b162021-02-03 17:38:41 +00002193void TfLiteParserImpl::ParseReshape(size_t subgraphIndex, size_t operatorIndex)
Sadikb94967b2018-09-19 15:30:00 +01002194{
2195 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2196
2197 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01002198
2199 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2200 CHECK_VALID_SIZE(outputs.size(), 1);
2201
2202 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2203 const auto * options = operatorPtr->builtin_options.AsReshapeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01002204 auto layerName = fmt::format("Reshape:{}:{}", subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01002205
2206 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
kevmay0171972a82018-12-17 14:28:03 +00002207 armnn::TensorInfo actualOutputTensorInfo = ToTensorInfo(outputs[0]);
James Conroy05102392020-06-24 15:39:55 +01002208 CheckMatchingQuantization(inputTensorInfo, actualOutputTensorInfo, layerName, "Input 0", "Output 0");
Derek Lambertic9e52792020-03-11 11:42:26 +00002209
Jan Eilersbac9b352020-07-13 13:40:24 +01002210 // Extracting new shape for the output
2211 // There are two ways it can be passed
2212 // * First is to define the target shape in the operator built-in options
2213 // * Second is to pass it as a second input tensor
Derek Lambertic9e52792020-03-11 11:42:26 +00002214 std::vector<int32_t> targetShape;
Jan Eilersbac9b352020-07-13 13:40:24 +01002215 bool targetShapeFound = false;
2216 // Check if built-in options were given
2217 if (options != nullptr)
Derek Lambertic9e52792020-03-11 11:42:26 +00002218 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002219 // make sure the parameter is given
2220 if (options->new_shape.empty() == false)
Derek Lambertic9e52792020-03-11 11:42:26 +00002221 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002222 targetShape = options->new_shape;
2223 targetShapeFound = true;
Derek Lambertif4a953f2020-03-17 14:25:57 +00002224 }
Derek Lambertic9e52792020-03-11 11:42:26 +00002225 }
Jan Eilersbac9b352020-07-13 13:40:24 +01002226
2227 // If there is no built-in option given or if the built-in new_shape parameter was empty
2228 if (!targetShapeFound)
Derek Lambertic9e52792020-03-11 11:42:26 +00002229 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002230 // Check for a second input tensor
2231 if (inputs.size() > 1 && inputs[1] != nullptr)
2232 {
2233 if (inputs[1]->is_variable)
2234 {
2235 ARMNN_THROW_PARSE_EXCEPTION( "Target shapes defined in non-const input tensors is not supported");
2236 }
2237
2238 if (inputs[1]->shape.size() != 1)
2239 {
2240 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not a 1D tensor");
2241 }
2242
2243 if (inputs[1]->type != tflite::TensorType_INT32)
2244 {
2245 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not an int32 type");
2246 }
2247
2248 // Extract target shape from input
2249 auto bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2250 auto values = reinterpret_cast<const int32_t*>(bufferPtr->data.data());
Sadik Armagan19a1c032021-01-20 12:17:00 +00002251 if (!values)
2252 {
2253 ARMNN_THROW_PARSE_EXCEPTION("Reshape operator target shape input buffer data is null");
2254 }
Jan Eilersbac9b352020-07-13 13:40:24 +01002255 for (int i=0; i < inputs[1]->shape[0]; ++i)
2256 {
2257 targetShape.push_back(values[i]);
2258 }
2259 }
2260 else
Derek Lambertic9e52792020-03-11 11:42:26 +00002261 {
2262 ARMNN_THROW_PARSE_EXCEPTION("Target shape not defined in reshape parameters or input tensor. "
2263 "At least one method required");
2264 }
Derek Lambertic9e52792020-03-11 11:42:26 +00002265 }
2266
kevmay0171972a82018-12-17 14:28:03 +00002267 armnn::TensorInfo reshapeOutputTensorInfo =
Kevin May7d96b162021-02-03 17:38:41 +00002268 TfLiteParserImpl::OutputShapeOfReshape(inputTensorInfo, targetShape);
Sadikb94967b2018-09-19 15:30:00 +01002269
kevmay0171972a82018-12-17 14:28:03 +00002270 // Check for valid input size and that reshape parameters equal output shape
Aron Virginas-Tar70672f62019-01-23 14:00:00 +00002271 const armnn::TensorShape& reshapeOutputTensorShape = reshapeOutputTensorInfo.GetShape();
2272 if (inputs.size() > 1 && !CheckShape(reshapeOutputTensorShape, outputs[0]->shape))
kevmay0171972a82018-12-17 14:28:03 +00002273 {
2274 std::stringstream ss;
2275 ss << "New shape defined in reshape parameters "
Aron Virginas-Tar70672f62019-01-23 14:00:00 +00002276 << reshapeOutputTensorShape
kevmay0171972a82018-12-17 14:28:03 +00002277 << " does not equal output shape "
2278 << actualOutputTensorInfo.GetShape()
2279 << ": "
2280 << CHECK_LOCATION().AsString();
2281 throw ParseException(ss.str());
2282 }
2283
Sadikb94967b2018-09-19 15:30:00 +01002284 ReshapeDescriptor reshapeDesc;
kevmay0171972a82018-12-17 14:28:03 +00002285 reshapeDesc.m_TargetShape = reshapeOutputTensorInfo.GetShape();
Sadikb94967b2018-09-19 15:30:00 +01002286
Sadikb94967b2018-09-19 15:30:00 +01002287 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002288 ARMNN_ASSERT(layer != nullptr);
kevmay0171972a82018-12-17 14:28:03 +00002289 layer->GetOutputSlot(0).SetTensorInfo(reshapeOutputTensorInfo);
Sadikb94967b2018-09-19 15:30:00 +01002290
2291 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2292 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2293
2294 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2295 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2296}
2297
Kevin May7d96b162021-02-03 17:38:41 +00002298void TfLiteParserImpl::ParseResizeBilinear(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002299{
Sadik Armagana3b31f02019-12-05 09:08:53 +00002300 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::Bilinear);
2301}
2302
Kevin May7d96b162021-02-03 17:38:41 +00002303void TfLiteParserImpl::ParseResizeNearestNeighbor(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagana3b31f02019-12-05 09:08:53 +00002304{
2305 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::NearestNeighbor);
2306}
2307
Kevin May7d96b162021-02-03 17:38:41 +00002308void TfLiteParserImpl::ParseResize(size_t subgraphIndex, size_t operatorIndex, ResizeMethod resizeMethod)
Sadik Armagana3b31f02019-12-05 09:08:53 +00002309{
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002310 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2311
2312 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2313 CHECK_VALID_SIZE(inputs.size(), 2);
2314
2315 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2316 CHECK_VALID_SIZE(outputs.size(), 1);
2317
2318 armnn::TensorInfo sizeTensorInfo = ToTensorInfo(inputs[1]);
2319
2320 // Data for the parsed tensor args (size) must be stored locally.
2321 std::vector<int32_t> sizeTensorData(sizeTensorInfo.GetNumElements());
2322
2323 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2324 ::memcpy(sizeTensorData.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
2325
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01002326 ResizeDescriptor desc;
Sadik Armagana3b31f02019-12-05 09:08:53 +00002327 desc.m_Method = resizeMethod;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002328 desc.m_TargetHeight = static_cast<uint32_t> (sizeTensorData[0]);
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01002329 desc.m_TargetWidth = static_cast<uint32_t> (sizeTensorData[1]);
2330 desc.m_DataLayout = armnn::DataLayout::NHWC;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002331
James Ward58dec6b2020-09-11 17:32:44 +01002332 auto layerName = fmt::format("Resize:");
Sadik Armagana3b31f02019-12-05 09:08:53 +00002333
2334 switch (resizeMethod)
2335 {
2336 case ResizeMethod::Bilinear:
2337 {
James Ward58dec6b2020-09-11 17:32:44 +01002338 layerName += fmt::format("BILINEAR:{}:{}", subgraphIndex, operatorIndex);
Sang-Hoon Park820eb142020-01-08 10:25:24 +00002339
2340 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2341 const auto * options = operatorPtr->builtin_options.AsResizeBilinearOptions();
2342
David Monahan4a0c9b92020-05-30 09:48:39 +01002343 desc.m_AlignCorners = options->align_corners;
Sadik Armagana3b31f02019-12-05 09:08:53 +00002344 break;
2345 }
2346 case ResizeMethod::NearestNeighbor:
2347 {
James Ward58dec6b2020-09-11 17:32:44 +01002348 layerName += fmt::format("NEARESTNEIGHBOR:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagana3b31f02019-12-05 09:08:53 +00002349 break;
2350 }
2351 default:
2352 {
2353 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002354 fmt::format("Unexpected ResizeMethod[{}] when creating layerName {} ",
2355 static_cast<int>(resizeMethod), CHECK_LOCATION().AsString()));
Sadik Armagana3b31f02019-12-05 09:08:53 +00002356 }
2357 }
2358
James Conroy05102392020-06-24 15:39:55 +01002359 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002360 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01002361 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
2362
2363 IConnectableLayer* layer = m_Network->AddResizeLayer(desc, layerName.c_str());
2364 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002365 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2366
2367 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2368 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2369
2370 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2371 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2372}
2373
Kevin May7d96b162021-02-03 17:38:41 +00002374void TfLiteParserImpl::ParseConcatenation(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan479045b2018-10-01 11:51:37 +01002375{
2376 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2377
2378 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2379 const auto * options = operatorPtr->builtin_options.AsConcatenationOptions();
2380
2381 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
2382
2383 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2384 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2385 CHECK_VALID_SIZE(outputs.size(), 1);
2386
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002387 unsigned int numConcatView = static_cast<unsigned int>(inputs.size());
2388 uint32_t inputRank = ToTensorInfo(inputs[0]).GetNumDimensions();
Sadik Armagan479045b2018-10-01 11:51:37 +01002389
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002390 const unsigned int concatDimInput = static_cast<unsigned int>(
2391 (static_cast<int>(inputRank) + options->axis) % static_cast<int>(inputRank));
Sadik Armagan479045b2018-10-01 11:51:37 +01002392
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002393 OriginsDescriptor concatDescriptor(static_cast<uint32_t>(numConcatView), inputRank);
2394 concatDescriptor.SetConcatAxis(concatDimInput);
Sadik Armagan479045b2018-10-01 11:51:37 +01002395
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002396 unsigned int mergeDimOrigin = 0;
Sadik Armagan479045b2018-10-01 11:51:37 +01002397
2398 for (unsigned int viewIndex = 0; viewIndex < numConcatView; ++viewIndex)
2399 {
2400 TensorInfo inputTensorInfo = ToTensorInfo(inputs[viewIndex]);
2401
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002402 // This set up concatDescriptor view origin
2403 armnnUtils::ProcessConcatInputTensorInfo(
2404 inputTensorInfo, concatDescriptor, concatDimInput, viewIndex, mergeDimOrigin);
Sadik Armagan479045b2018-10-01 11:51:37 +01002405 }
2406
James Ward58dec6b2020-09-11 17:32:44 +01002407 auto layerName = fmt::format("Concatenation:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002408 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01002409
Jim Flynn906f9462019-05-10 13:55:21 +01002410 IConnectableLayer* layer = m_Network->AddConcatLayer(concatDescriptor, layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002411 ARMNN_ASSERT(layer != nullptr);
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002412 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Sadik Armagan479045b2018-10-01 11:51:37 +01002413
James Conroy05102392020-06-24 15:39:55 +01002414 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002415 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
Sadik Armagan479045b2018-10-01 11:51:37 +01002416
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002417 // add fused activation layer
2418 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Sadik Armagan479045b2018-10-01 11:51:37 +01002419
Sadik Armagan479045b2018-10-01 11:51:37 +01002420 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2421 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2422}
2423
Kevin May7d96b162021-02-03 17:38:41 +00002424void TfLiteParserImpl::ParseFullyConnected(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002425{
2426 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2427
2428 const auto & operatorRfr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2429 const auto options = operatorRfr->builtin_options.AsFullyConnectedOptions();
2430
2431 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
2432
2433 FullyConnectedDescriptor desc;
2434 desc.m_BiasEnabled = false;
Nattapat Chaimanowongd8eee592018-10-26 10:24:14 +01002435 desc.m_TransposeWeightMatrix = true;
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002436
2437 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2438 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2439 CHECK_VALID_SIZE(outputs.size(), 1);
2440
2441 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
2442
2443 // Fully Connected Layer accepts two dimensional weights input
2444 int32_t weightsDimension = static_cast<int32_t>(filterTensorInfo.GetNumDimensions());
2445 if (weightsDimension != 2)
2446 {
2447 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002448 fmt::format("Dimension {} for Fully Connected weights is not supported by Armnn. "
2449 "Node {}",
2450 weightsDimension,
2451 CHECK_LOCATION().AsString()));
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002452 }
2453
Matthew Jackson74bf7da2019-08-16 16:51:42 +01002454 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01002455 auto layerName = fmt::format("FullyConnected:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002456
Finn Williamsd4fa5452021-03-01 12:31:41 +00002457 Optional<ConstTensor> filterOptionalConstTensor;
2458
2459 desc.m_ConstantWeights = IsConstTensor(inputs[1]);
2460
Finn Williamsd4fa5452021-03-01 12:31:41 +00002461 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2462 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0]};
2463 if (desc.m_ConstantWeights)
2464 {
2465 filterOptionalConstTensor = Optional<ConstTensor>(CreateConstTensorNonPermuted(inputs[1], filterTensorInfo));
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002466 }
2467 else
2468 {
Finn Williamsd4fa5452021-03-01 12:31:41 +00002469 // Non const weights will need to be registered as inputs
2470 tensorIndexesToRegister.emplace_back(inputTensorIndexes[1]);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002471 }
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002472
Finn Williamsd4fa5452021-03-01 12:31:41 +00002473 Optional<ConstTensor> biasOptionalConstTensor;
2474 if (inputs.size() == 3)
2475 {
2476 desc.m_BiasEnabled = true;
2477 if (desc.m_ConstantWeights)
2478 {
2479 TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
2480 biasOptionalConstTensor = Optional<ConstTensor>(CreateConstTensorNonPermuted(inputs[2], biasTensorInfo));
2481 }
2482 else
2483 {
2484 // Non const biases will need to be registered as inputs
2485 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
2486 }
2487 }
2488
2489 layer = m_Network->AddFullyConnectedLayer(desc,
2490 filterOptionalConstTensor,
2491 biasOptionalConstTensor,
2492 layerName.c_str());
2493
2494 ARMNN_ASSERT(layer != nullptr);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002495 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2496
Finn Williamsd4fa5452021-03-01 12:31:41 +00002497 unsigned int startingSlotIndex = 0;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002498 if (inputTensorInfo.GetNumDimensions() > 2)
2499 {
2500 // Add reshape to flatten to 2D [batch_size, input_size],
2501 // where "input_size" corresponds to the number of inputs to the layer,
2502 // matching the second dimension of weights,
2503 // and "batch_size" is calculated by dividing the number of elements by "input_size".
2504 std::vector<unsigned int> reshapedDimensions(2);
2505 reshapedDimensions[1] = filterTensorInfo.GetShape()[1];
2506 reshapedDimensions[0] = inputTensorInfo.GetNumElements() / reshapedDimensions[1];
2507
2508 if (inputTensorInfo.GetNumElements() % reshapedDimensions[1] != 0)
2509 {
2510 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002511 fmt::format("Failed to deduce input tensor shape from filter size {} {}",
2512 reshapedDimensions[1],
2513 CHECK_LOCATION().AsString()));
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002514 }
2515
2516 armnn::TensorInfo reshapedTensorInfo = ToTensorInfo(inputs[0]);
2517 reshapedTensorInfo.SetShape(armnn::TensorShape{ 2, reshapedDimensions.data() });
2518
James Ward58dec6b2020-09-11 17:32:44 +01002519 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Finn Williamsd4fa5452021-03-01 12:31:41 +00002520 armnn::ReshapeDescriptor reshapeDescriptor;
2521 reshapeDescriptor.m_TargetShape = reshapedTensorInfo.GetShape();
2522 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(reshapeDescriptor, layerName.c_str());
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002523
2524 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedTensorInfo);
2525 reshapeLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(0));
2526
2527 RegisterInputSlots(subgraphIndex, operatorIndex, reshapeLayer, {inputTensorIndexes[0]});
Finn Williamsd4fa5452021-03-01 12:31:41 +00002528 // Fc layer connects to the reshape layer, so we skip the first input slot when registering fc's input slots
2529 tensorIndexesToRegister.erase(tensorIndexesToRegister.begin());
2530 startingSlotIndex = 1;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002531 }
Finn Williamsd4fa5452021-03-01 12:31:41 +00002532
2533 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister, startingSlotIndex);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002534
Sadik Armagand109a4d2020-07-28 10:42:13 +01002535 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002536 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2537
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002538 // we need to add the activation layer and fortunately we don't need to care about the data layout
2539 armnn::IConnectableLayer* fusedActivationLayer = AddFusedActivationLayer(layer, 0,
2540 options->fused_activation_function);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002541
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002542 // register the output connection slots for the layer, connections are made after all layers have been created
2543 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2544 RegisterOutputSlots(subgraphIndex, operatorIndex, fusedActivationLayer, {outputTensorIndexes[0]});
2545}
2546
Kevin May7d96b162021-02-03 17:38:41 +00002547void TfLiteParserImpl::ParseDetectionPostProcess(size_t subgraphIndex, size_t operatorIndex)
keidav011b3e2ea2019-02-21 10:07:37 +00002548{
2549 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2550
2551 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2552
2553 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2554 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2555 CHECK_VALID_SIZE(outputs.size(), 4);
2556
2557 // Obtain custom options from flexbuffers
2558 auto custom_options = operatorPtr->custom_options;
2559 const flexbuffers::Map& m = flexbuffers::GetRoot(custom_options.data(), custom_options.size()).AsMap();
2560
2561 // Obtain descriptor information from tf lite
2562 DetectionPostProcessDescriptor desc;
2563 desc.m_MaxDetections = m["max_detections"].AsUInt32();
2564 desc.m_MaxClassesPerDetection = m["max_classes_per_detection"].AsUInt32();
2565 desc.m_NmsScoreThreshold = m["nms_score_threshold"].AsFloat();
2566 desc.m_NmsIouThreshold = m["nms_iou_threshold"].AsFloat();
2567 desc.m_NumClasses = m["num_classes"].AsUInt32();
2568 desc.m_ScaleH = m["h_scale"].AsFloat();
2569 desc.m_ScaleW = m["w_scale"].AsFloat();
2570 desc.m_ScaleX = m["x_scale"].AsFloat();
2571 desc.m_ScaleY = m["y_scale"].AsFloat();
2572
keidav0107d58c72019-02-26 11:57:39 +00002573 if (!(m["use_regular_nms"].IsNull()))
keidav011b3e2ea2019-02-21 10:07:37 +00002574 {
keidav0107d58c72019-02-26 11:57:39 +00002575 desc.m_UseRegularNms = m["use_regular_nms"].AsBool();
keidav011b3e2ea2019-02-21 10:07:37 +00002576 }
2577 if (!(m["detections_per_class"].IsNull()))
2578 {
2579 desc.m_DetectionsPerClass = m["detections_per_class"].AsUInt32();
2580 }
2581
2582 if (desc.m_NmsIouThreshold <= 0.0f || desc.m_NmsIouThreshold > 1.0f)
2583 {
2584 throw InvalidArgumentException("DetectionPostProcessTFLiteParser: Intersection over union threshold "
2585 "must be positive and less than or equal to 1.");
2586 }
2587
2588 armnn::TensorInfo anchorTensorInfo = ToTensorInfo(inputs[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00002589 auto anchorTensorAndData = CreateConstTensorNonPermuted(inputs[2], anchorTensorInfo);
keidav011b3e2ea2019-02-21 10:07:37 +00002590
James Ward58dec6b2020-09-11 17:32:44 +01002591 auto layerName = fmt::format("DetectionPostProcess:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsd4fa5452021-03-01 12:31:41 +00002592 IConnectableLayer* layer = m_Network->AddDetectionPostProcessLayer(desc, anchorTensorAndData,
keidav011b3e2ea2019-02-21 10:07:37 +00002593 layerName.c_str());
2594
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002595 ARMNN_ASSERT(layer != nullptr);
keidav011b3e2ea2019-02-21 10:07:37 +00002596
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00002597 // The model does not specify the output shapes.
2598 // The output shapes are calculated from the max_detection and max_classes_per_detection.
2599 unsigned int numDetectedBox = desc.m_MaxDetections * desc.m_MaxClassesPerDetection;
2600 m_OverridenOutputShapes.push_back({ 1, numDetectedBox, 4 });
2601 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
2602 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
2603 m_OverridenOutputShapes.push_back({ 1 });
2604
keidav011b3e2ea2019-02-21 10:07:37 +00002605 for (unsigned int i = 0 ; i < outputs.size() ; ++i)
2606 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00002607 armnn::TensorInfo detectionBoxOutputTensorInfo = ToTensorInfo(outputs[i], m_OverridenOutputShapes[i]);
keidav011b3e2ea2019-02-21 10:07:37 +00002608 layer->GetOutputSlot(i).SetTensorInfo(detectionBoxOutputTensorInfo);
2609 }
2610
2611 // Register the input connection slots for the layer, connections are made after all layers have been created
2612 // only the tensors for the inputs are relevant, exclude the const tensors
2613 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2614 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2615
2616 // Register the output connection slots for the layer, connections are made after all layers have been created
2617 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2618 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0],
2619 outputTensorIndexes[1],
2620 outputTensorIndexes[2],
2621 outputTensorIndexes[3]});
2622}
2623
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002624/// The TfLite Pack operator is equivalent to the ArmNN Stack operator
Kevin May7d96b162021-02-03 17:38:41 +00002625void TfLiteParserImpl::ParsePack(size_t subgraphIndex, size_t operatorIndex)
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002626{
2627 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2628
2629 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2630 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2631 CHECK_VALID_SIZE(outputs.size(), 1);
2632
2633 if (inputs.size() < 1)
2634 {
2635 throw ParseException("Pack must have at least one input.");
2636 }
2637
2638 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2639 const auto* options = operatorPtr->builtin_options.AsPackOptions();
2640
2641 StackDescriptor desc;
2642 desc.m_Axis = static_cast<uint32_t>(options->axis);
2643 desc.m_NumInputs = static_cast<uint32_t>(inputs.size());
2644
2645 // Use the tensor shape of the first input as the "correct" input shape in the descriptor
2646 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2647 desc.m_InputShape = inputTensorInfo.GetShape();
2648
James Ward58dec6b2020-09-11 17:32:44 +01002649 auto layerName = fmt::format("Pack:{}:{}", subgraphIndex, operatorIndex);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002650 IConnectableLayer* layer = m_Network->AddStackLayer(desc, layerName.c_str());
2651
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002652 ARMNN_ASSERT(layer != nullptr);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002653
Sadik Armagand109a4d2020-07-28 10:42:13 +01002654 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002655 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2656
2657 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2658 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
2659
2660 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2661 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2662}
2663
Kevin May7d96b162021-02-03 17:38:41 +00002664void TfLiteParserImpl::ParseUnpack(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd200e3802019-04-15 09:47:39 +01002665{
2666 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2667
2668 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2669 const auto * options = operatorPtr->builtin_options.AsUnpackOptions();
2670
2671 // This unpackAxis indicates the axis to unpack
2672 const unsigned int unpackAxis = CHECKED_NON_NEGATIVE(options->axis);
2673
2674 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2675 CHECK_VALID_SIZE(inputs.size(), 1);
2676
2677 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002678
2679 if (unpackAxis >= inputTensorInfo.GetNumDimensions())
2680 {
2681 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002682 fmt::format("The unpack axis: {} cannot be greater than or equal to "
2683 "the number of input dimension {} {}",
2684 unpackAxis,
2685 inputTensorInfo.GetNumDimensions(),
2686 CHECK_LOCATION().AsString()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002687 }
2688
Nina Drozd200e3802019-04-15 09:47:39 +01002689 unsigned int unpackNum = CHECKED_NON_NEGATIVE(options->num);
2690 // If num is not defined, automatically infer from the length of the dimension axis.
2691 if(unpackNum == 0)
2692 {
2693 unpackNum = inputTensorInfo.GetShape()[unpackAxis];
2694 }
2695
2696 // If unpack number cannot be inferred and is still zero, throw ParseException.
2697 if(unpackNum == 0)
2698 {
2699 throw ParseException("Number to unpack must greater than zero.");
2700 }
2701
2702 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2703 CHECK_VALID_SIZE(outputs.size(), unpackNum);
2704
2705 auto inputDimSize = inputTensorInfo.GetNumDimensions();
2706 std::vector<unsigned int> unpackDimSizes(inputDimSize);
2707
2708 // Add current input shape to unpackDimSizes
2709 for (unsigned int i = 0; i < inputDimSize; ++i)
2710 {
2711 unpackDimSizes[i] = inputTensorInfo.GetShape()[i];
2712 }
2713
2714 if (unpackDimSizes[unpackAxis] != unpackNum)
2715 {
2716 throw ParseException("Number to unpack must be the same as length of the dimension to "
2717 "unpack along.");
2718 }
2719
2720 unpackDimSizes[unpackAxis] /= unpackNum;
2721
2722 SplitterDescriptor splitDesc(unpackNum, static_cast<unsigned int>(unpackDimSizes.size()));
2723 for (unsigned int j = 0; j < unpackNum; ++j)
2724 {
2725 // Set the size of the views.
2726 for (unsigned int dimIdx = 0; dimIdx < unpackDimSizes.size(); ++dimIdx)
2727 {
2728 splitDesc.SetViewSize(j, dimIdx, unpackDimSizes[dimIdx]);
2729 }
2730 splitDesc.SetViewOriginCoord(j, unpackAxis, unpackDimSizes[unpackAxis] * j);
2731 }
2732
James Ward58dec6b2020-09-11 17:32:44 +01002733 auto layerName = fmt::format("Unpack:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd200e3802019-04-15 09:47:39 +01002734 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002735 ARMNN_ASSERT(layer != nullptr);
Nina Drozd200e3802019-04-15 09:47:39 +01002736
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002737 TensorShape splitOutShape = TensorShape(static_cast<unsigned int>(unpackDimSizes.size()),
2738 unpackDimSizes.data());
2739
Nina Drozd200e3802019-04-15 09:47:39 +01002740 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2741 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2742
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002743 // Create reshape to remove the unpacked dimension for unpack operator of each output from Splitter.
2744 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
2745 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01002746 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[k], true);
James Ward58dec6b2020-09-11 17:32:44 +01002747 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002748 armnn::ReshapeDescriptor desc;
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01002749 desc.m_TargetShape = outputTensorInfo.GetShape();
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002750 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(desc, layerName.c_str());
2751
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01002752 layer->GetOutputSlot(k).SetTensorInfo(armnn::TensorInfo(splitOutShape,
2753 outputTensorInfo.GetDataType(),
2754 outputTensorInfo.GetQuantizationScale(),
2755 outputTensorInfo.GetQuantizationOffset()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002756 layer->GetOutputSlot(k).Connect(reshapeLayer->GetInputSlot(0));
2757
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01002758 reshapeLayer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002759
2760 uint32_t reshapedOutputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[k]);
2761 armnn::IOutputSlot* slot = &(reshapeLayer->GetOutputSlot(0));
2762 RegisterProducerOfTensor(subgraphIndex, reshapedOutputId, slot);
2763 }
Nina Drozd200e3802019-04-15 09:47:39 +01002764}
2765
Kevin May7d96b162021-02-03 17:38:41 +00002766void TfLiteParserImpl::ParseSplit(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd0324f482019-04-08 10:52:10 +01002767{
2768 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2769
2770 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2771 const auto * options = operatorPtr->builtin_options.AsSplitOptions();
2772
2773 const unsigned int numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
2774
Nina Drozd200e3802019-04-15 09:47:39 +01002775 // If number of splits cannot be inferred and is zero, throw ParseException.
2776 if(numSplits == 0)
2777 {
2778 throw ParseException("Number to splits must greater than zero.");
2779 }
2780
Nina Drozd0324f482019-04-08 10:52:10 +01002781 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2782 CHECK_VALID_SIZE(inputs.size(), 2);
2783 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2784 CHECK_VALID_SIZE(outputs.size(), numSplits);
2785
Matthew Sloyaned7fce42021-04-15 20:46:24 +01002786 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[1]);
2787 armnn::TensorInfo axisTensorInfo = ToTensorInfo(inputs[0]);
2788 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
Nina Drozd0324f482019-04-08 10:52:10 +01002789
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002790 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01002791 if (axisBufferPtr == nullptr)
2792 {
2793 throw ParseException(
2794 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
2795 CHECK_LOCATION().AsString()));
2796 }
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002797
Matthew Sloyaned7fce42021-04-15 20:46:24 +01002798 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
2799 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
2800 int32_t axis = axisData[0];
2801
2802 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
2803 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
2804 {
2805 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
2806 // E.g. Rank 4 tensor can have axis in range [-4, 3)
2807 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
2808 throw ParseException(
2809 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
2810 axis,
2811 CHECK_LOCATION().AsString()));
2812 }
2813
2814 const unsigned int splitDim = armnnUtils::GetUnsignedAxis(inputTensorInfo.GetNumDimensions(), axis);
Nina Drozd0324f482019-04-08 10:52:10 +01002815
Nina Drozd0324f482019-04-08 10:52:10 +01002816 auto inputDimSize = inputTensorInfo.GetNumDimensions();
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002817 if (inputDimSize > MaxNumOfTensorDimensions)
Nina Drozd0324f482019-04-08 10:52:10 +01002818 {
2819 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002820 fmt::format("The number of dimensions: {} for input tensors of the split op cannot be greater than {} {}",
2821 inputTensorInfo.GetNumDimensions(),
2822 MaxNumOfTensorDimensions,
2823 CHECK_LOCATION().AsString()));
Nina Drozd0324f482019-04-08 10:52:10 +01002824 }
2825
2826 std::vector<unsigned int> splitterDimSizes(inputDimSize);
2827
2828 // Add current input shape to splitterDimSizes
2829 for (unsigned int i = 0; i < inputDimSize; ++i)
2830 {
2831 splitterDimSizes[i] = inputTensorInfo.GetShape()[i];
2832 }
2833
2834 if (splitterDimSizes[splitDim] % numSplits != 0)
2835 {
2836 throw ParseException("Number of splits must evenly divide the dimension");
2837 }
2838 splitterDimSizes[splitDim] /= numSplits;
2839
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002840 SplitterDescriptor splitDesc(numSplits, inputDimSize);
Nina Drozd0324f482019-04-08 10:52:10 +01002841 for (unsigned int j = 0; j < numSplits; ++j)
2842 {
2843 // Set the size of the views.
2844 for (unsigned int dimIdx = 0; dimIdx < splitterDimSizes.size(); ++dimIdx)
2845 {
2846 splitDesc.SetViewSize(j, dimIdx, splitterDimSizes[dimIdx]);
2847 }
2848 splitDesc.SetViewOriginCoord(j, splitDim, splitterDimSizes[splitDim] * j);
2849 }
2850
James Ward58dec6b2020-09-11 17:32:44 +01002851 auto layerName = fmt::format("Split:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd0324f482019-04-08 10:52:10 +01002852 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002853 ARMNN_ASSERT(layer != nullptr);
Nina Drozd0324f482019-04-08 10:52:10 +01002854
2855 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002856 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[1]});
Nina Drozd0324f482019-04-08 10:52:10 +01002857
Nina Drozd0324f482019-04-08 10:52:10 +01002858 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
2859 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01002860 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Francis Murtagh98d6b3d2019-10-21 10:52:54 +01002861 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
Nina Drozd0324f482019-04-08 10:52:10 +01002862 }
2863
2864 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2865 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2866}
2867
Derek Lambertif0176992020-04-28 13:37:49 +01002868unsigned int ComputeWrappedIndex(int idx, unsigned int numDimsIn)
2869{
2870 int numDims = armnn::numeric_cast<int>(numDimsIn);
2871 int v = idx < 0 ? numDims + idx : idx;
2872 ARMNN_ASSERT(v >= 0);
2873 ARMNN_ASSERT(v < numDims);
2874
2875 return static_cast<unsigned int>(v);
2876}
2877
Kevin May7d96b162021-02-03 17:38:41 +00002878void TfLiteParserImpl::ParseSplitV(size_t subgraphIndex, size_t operatorIndex)
Derek Lambertif0176992020-04-28 13:37:49 +01002879{
2880 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2881
2882 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Ryan OShea86704732020-05-26 11:41:04 +01002883 const auto * options = operatorPtr->builtin_options.AsSplitVOptions();
Derek Lambertif0176992020-04-28 13:37:49 +01002884
2885 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2886 CHECK_VALID_SIZE(inputs.size(), 3);
2887
2888 auto& inputTensor = inputs[0];
2889 auto& splitsTensor = inputs[1];
2890 auto& axisTensor = inputs[2];
2891
2892 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputTensor);
2893 armnn::TensorInfo splitsInfo = ToTensorInfo(splitsTensor);
2894 armnn::TensorInfo axisTensorInfo = ToTensorInfo(axisTensor);
2895 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
2896
2897 // Inputs
2898 auto inputDimSize = inputTensorInfo.GetNumDimensions();
2899 if (inputDimSize > MaxNumOfTensorDimensions)
2900 {
2901 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002902 fmt::format("The number of dimensions: {} for input tensors of the "
2903 "SplitV op cannot be greater than {} {}",
2904 inputTensorInfo.GetNumDimensions(),
2905 MaxNumOfTensorDimensions,
2906 CHECK_LOCATION().AsString()));
Derek Lambertif0176992020-04-28 13:37:49 +01002907 }
2908
2909 // Get split axis
2910 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, axisTensor->buffer);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01002911 if (axisBufferPtr == nullptr)
2912 {
2913 throw ParseException(
2914 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
2915 CHECK_LOCATION().AsString()));
2916 }
2917
Derek Lambertif0176992020-04-28 13:37:49 +01002918 std::vector<int> axisData(axisTensorInfo.GetNumElements());
2919 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
Matthew Sloyaned7fce42021-04-15 20:46:24 +01002920 int32_t axis = axisData[0];
2921
2922 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
2923 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
2924 {
2925 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
2926 // E.g. Rank 4 tensor can have axis in range [-4, 3)
2927 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
2928 throw ParseException(
2929 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
2930 axis,
2931 CHECK_LOCATION().AsString()));
2932 }
2933 const unsigned int splitDim = ComputeWrappedIndex(axis, inputTensorInfo.GetNumDimensions());
Derek Lambertif0176992020-04-28 13:37:49 +01002934
Derek Lambertif0176992020-04-28 13:37:49 +01002935 // Set split sizes
Derek Lambertif0176992020-04-28 13:37:49 +01002936 CHECK_VALID_SIZE(splitsInfo.GetNumDimensions(), 1);
Ryan OShea86704732020-05-26 11:41:04 +01002937 unsigned int numSplits{0};
2938
2939 if(options)
Derek Lambertif0176992020-04-28 13:37:49 +01002940 {
2941 numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
Derek Lambertif0176992020-04-28 13:37:49 +01002942 }
2943 else
2944 {
Ryan OShea86704732020-05-26 11:41:04 +01002945 numSplits = splitsInfo.GetNumElements();
Derek Lambertif0176992020-04-28 13:37:49 +01002946 }
2947
2948 if (numSplits <=0)
2949 {
2950 throw ParseException("SplitV has invalid number of splits");
2951 }
2952
Jan Eilersc0761e92020-06-29 16:48:44 +01002953 std::vector<int> splitsData(numSplits);
Ryan OShea86704732020-05-26 11:41:04 +01002954 BufferRawPtr splitsBufferPtr = GetBuffer(m_Model, splitsTensor->buffer);
Jan Eilersc0761e92020-06-29 16:48:44 +01002955 ::memcpy(splitsData.data(), splitsBufferPtr->data.data(), splitsInfo.GetNumBytes());
Ryan OShea86704732020-05-26 11:41:04 +01002956
Jan Eilersc0761e92020-06-29 16:48:44 +01002957 unsigned int idx = 0;
Ryan OShea86704732020-05-26 11:41:04 +01002958 int numInferred{0};
2959 unsigned int inferIdx{0};
2960 int splitSum{0};
2961 for (auto split : splitsData)
2962 {
2963 if (split < 0)
2964 {
2965 numInferred++;
2966 inferIdx = idx;
2967 }
2968 else
2969 {
2970 splitSum += split;
2971 }
2972 idx++;
2973 }
2974 // Check for inferred Axis
2975 if (numInferred == 0)
2976 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002977 if (splitSum != armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]))
Ryan OShea86704732020-05-26 11:41:04 +01002978 {
2979 throw ParseException("SplitV split_sizes does not sum to the dimension of value along split_dim.");
2980 }
2981 }
2982 else if (numInferred == 1)
2983 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002984 splitsData[inferIdx] = armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]) - splitSum;
Ryan OShea86704732020-05-26 11:41:04 +01002985 }
2986 else
2987 {
2988 throw ParseException("Cannot infer split size for more than one split");
2989 }
2990
Derek Lambertif0176992020-04-28 13:37:49 +01002991 //Ouput size validation
2992 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2993 CHECK_VALID_SIZE(outputs.size(), numSplits);
2994
2995 // Setup Armnn descriptor
2996 SplitterDescriptor splitDesc(numSplits, inputDimSize);
2997 unsigned int accumSplit = 0;
2998 for (unsigned int j = 0; j < numSplits; ++j)
2999 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01003000 unsigned int splitSize = armnn::numeric_cast<unsigned int>(splitsData[j]);
Derek Lambertif0176992020-04-28 13:37:49 +01003001
3002 // Set the size of the views.
3003 for (unsigned int dimIdx = 0; dimIdx < inputTensorInfo.GetNumDimensions(); ++dimIdx)
3004 {
3005 unsigned int dimSize = inputTensorInfo.GetShape()[dimIdx];
3006 if (dimIdx == splitDim)
3007 {
3008 dimSize = splitSize;
3009 }
3010 splitDesc.SetViewSize(j, dimIdx, dimSize);
3011 }
3012
3013 splitDesc.SetViewOriginCoord(j, splitDim, accumSplit);
3014 accumSplit += splitSize;
3015 }
3016
James Ward58dec6b2020-09-11 17:32:44 +01003017 auto layerName = fmt::format("SplitV:{}:{}", subgraphIndex, operatorIndex);
Derek Lambertif0176992020-04-28 13:37:49 +01003018 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01003019 ARMNN_ASSERT(layer != nullptr);
Derek Lambertif0176992020-04-28 13:37:49 +01003020
3021 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3022 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3023
3024 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
3025 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01003026 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Derek Lambertif0176992020-04-28 13:37:49 +01003027 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
3028 }
3029
3030 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3031 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3032}
3033
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003034void TfLiteParserImpl::ParseArgMin(size_t subgraphIndex, size_t operatorIndex)
3035{
3036 ParseArgMinMax(subgraphIndex, operatorIndex, armnn::ArgMinMaxFunction::Min);
3037}
3038
Kevin May7d96b162021-02-03 17:38:41 +00003039void TfLiteParserImpl::ParseArgMax(size_t subgraphIndex, size_t operatorIndex)
Inki Daed4619e22020-09-10 15:33:54 +09003040{
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003041 ParseArgMinMax(subgraphIndex, operatorIndex, armnn::ArgMinMaxFunction::Max);
3042}
3043
3044void TfLiteParserImpl::ParseArgMinMax(size_t subgraphIndex, size_t operatorIndex, ArgMinMaxFunction argMinMaxFunction)
3045{
Inki Daed4619e22020-09-10 15:33:54 +09003046 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3047 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3048 CHECK_VALID_SIZE(inputs.size(), 2);
3049
3050 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3051 CHECK_VALID_SIZE(outputs.size(), 1);
3052
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003053 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3054 armnn::TensorInfo axisTensorInfo = ToTensorInfo(inputs[1]);
Inki Daed4619e22020-09-10 15:33:54 +09003055 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003056 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003057
3058 // Check if output tensor type is Signed32 or Signed64
Mike Kelly1f140f72021-04-06 12:25:55 +01003059 if (outputTensorInfo.GetDataType() != armnn::DataType::Signed32 &&
3060 outputTensorInfo.GetDataType() != armnn::DataType::Signed64)
3061 {
3062 throw ParseException(
3063 fmt::format(
3064 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
3065 CHECK_LOCATION().AsString()));
3066 }
Matthew Sloyan28f177c2021-04-09 14:38:52 +01003067
3068 // Get const axis value from model and set it to descriptor.
3069 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
3070 if (axisBufferPtr == nullptr)
3071 {
3072 throw ParseException(
3073 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
3074 CHECK_LOCATION().AsString()));
3075 }
3076
3077 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
3078 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
3079 int32_t axis = axisData.front();
3080
3081 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3082 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3083 {
3084 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
3085 // E.g. Rank 4 tensor can have axis in range [-4, 3)
3086 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
3087 throw ParseException(
3088 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3089 axis,
3090 CHECK_LOCATION().AsString()));
3091 }
3092
3093 ArgMinMaxDescriptor desc;
3094 desc.m_Axis = axis;
3095 desc.m_Function = argMinMaxFunction;
3096
3097 // Register a ArgMin/ArgMax layer.
3098 auto layerName = argMinMaxFunction == ArgMinMaxFunction::Max ? "ArgMax:{}:{}" : "ArgMin:{}:{}";
3099 auto layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
3100 IConnectableLayer *layer = m_Network->AddArgMinMaxLayer(desc, layerNameFormatted.c_str());
3101 ARMNN_ASSERT(layer != nullptr);
Inki Daed4619e22020-09-10 15:33:54 +09003102 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3103
3104 // Register input tensor to the layer.
3105 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3106 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3107
3108 // Register output tensor to the layer.
3109 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3110 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3111}
3112
Kevin May7d96b162021-02-03 17:38:41 +00003113void TfLiteParserImpl::ParseGather(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00003114{
3115 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3116
Kevin May7d96b162021-02-03 17:38:41 +00003117 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00003118 CHECK_VALID_SIZE(inputs.size(), 2);
Kevin May7d96b162021-02-03 17:38:41 +00003119 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00003120 CHECK_VALID_SIZE(outputs.size(), 1);
3121
3122 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3123 armnn::TensorInfo indicesTensorInfo = ToTensorInfo(inputs[1]);
3124 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
3125
3126 armnn::GatherDescriptor gatherDescriptor;
3127
3128 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3129 const auto * options = operatorPtr->builtin_options.AsGatherOptions();
3130 auto axis = options->axis;
3131
3132 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3133 auto indicesDimensions = indicesTensorInfo.GetNumDimensions();
3134 auto outputDimensions = outputTensorInfo.GetNumDimensions();
3135 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3136 {
3137 throw ParseException(
3138 fmt::format("Operation has invalid axis: {} It is out of bounds [ -{}, {} ) {}",
3139 axis,
3140 inputDimensions, inputDimensions,
3141 CHECK_LOCATION().AsString()));
3142 }
3143 if (outputDimensions != static_cast<unsigned int>(inputDimensions) + indicesDimensions - 1)
3144 {
3145 throw ParseException(
3146 fmt::format("Operation has invalid output dimensions: {} Output must be an ({} + {} - 1) -D tensor {}",
3147 outputDimensions,
3148 inputDimensions, indicesDimensions,
3149 CHECK_LOCATION().AsString()));
3150 }
3151
3152 gatherDescriptor.m_Axis = axis;
3153
3154 auto layerName = fmt::format("Gather:{}:{}", subgraphIndex, operatorIndex);
3155 IConnectableLayer* layer = m_Network->AddGatherLayer(gatherDescriptor, layerName.c_str());
3156 ARMNN_ASSERT(layer != nullptr);
3157 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3158
3159 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3160 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
3161
3162 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3163 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3164}
3165
Kevin May7d96b162021-02-03 17:38:41 +00003166void TfLiteParserImpl::ParseDepthToSpace(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00003167{
3168 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3169
Kevin May7d96b162021-02-03 17:38:41 +00003170 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00003171 CHECK_VALID_SIZE(inputs.size(), 1);
Kevin May7d96b162021-02-03 17:38:41 +00003172 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00003173 CHECK_VALID_SIZE(outputs.size(), 1);
3174
3175 armnn::DepthToSpaceDescriptor descriptor;
3176
3177 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3178 const auto * options = operatorPtr->builtin_options.AsDepthToSpaceOptions();
3179 auto blockSize = options->block_size;
3180 if (blockSize < 2)
3181 {
3182 throw ParseException(
3183 fmt::format("Operation has invalid block size: {} Block size should be >= 2 {}",
3184 blockSize,
3185 CHECK_LOCATION().AsString()));
3186 }
3187 descriptor.m_BlockSize = armnn::numeric_cast<uint32_t>(blockSize);
3188
3189 auto layerName = fmt::format("DepthToSpace:{}:{}", subgraphIndex, operatorIndex);
3190 IConnectableLayer* layer = m_Network->AddDepthToSpaceLayer(descriptor, layerName.c_str());
3191 ARMNN_ASSERT(layer != nullptr);
3192 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
3193 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3194
3195 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3196 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3197
3198 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3199 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3200}
3201
Kevin May7d96b162021-02-03 17:38:41 +00003202void TfLiteParserImpl::ParseSum(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003203{
Sadik Armagana2747482021-02-09 10:28:54 +00003204 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Sum);
3205}
3206
3207void TfLiteParserImpl::ParseReduceMax(size_t subgraphIndex, size_t operatorIndex)
3208{
3209 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Max);
3210}
3211
3212void TfLiteParserImpl::ParseReduceMin(size_t subgraphIndex, size_t operatorIndex)
3213{
3214 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Min);
3215}
3216
3217void TfLiteParserImpl::ParseReduce(size_t subgraphIndex, size_t operatorIndex, ReduceOperation reduceOperation)
3218{
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003219 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3220
3221 const auto &operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3222 const auto *options = operatorPtr->builtin_options.AsReducerOptions();
3223
3224 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3225 CHECK_VALID_SIZE(inputs.size(), 2);
3226
3227 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3228 CHECK_VALID_SIZE(outputs.size(), 1);
3229
Sadik Armagana2747482021-02-09 10:28:54 +00003230 auto layerName = fmt::format("Reduce:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003231
3232 armnn::TensorInfo inputTensorInfo0 = ToTensorInfo(inputs[0]);
3233 armnn::TensorInfo inputTensorInfo1 = ToTensorInfo(inputs[1]);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003234
3235 ReduceDescriptor desc;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003236 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
3237 // Get const axis value from model and set it to descriptor.
3238 if (axisBufferPtr != nullptr)
3239 {
Sadik Armagan49bdb792021-02-11 13:57:07 +00003240 std::vector<int32_t> axisData(inputTensorInfo1.GetNumElements());
3241 ::memcpy(axisData.data(), axisBufferPtr->data.data(), inputTensorInfo1.GetNumBytes());
3242
3243 // Convert the axis to unsigned int and remove duplicates.
3244 auto rank = static_cast<int32_t>(inputTensorInfo0.GetNumDimensions());
3245 std::set<unsigned int> uniqueAxis;
3246 std::transform(axisData.begin(),
3247 axisData.end(),
3248 std::inserter(uniqueAxis, uniqueAxis.begin()),
3249 [rank](int i)->unsigned int{
3250 return static_cast<uint32_t>(((i + rank) % rank)); });
3251 desc.m_vAxis.assign(uniqueAxis.begin(), uniqueAxis.end());
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003252 }
Sadik Armagana2747482021-02-09 10:28:54 +00003253 else
3254 {
3255 for (uint32_t i = 0; i < inputTensorInfo0.GetNumDimensions(); ++i)
3256 {
3257 desc.m_vAxis.push_back(i);
3258 }
3259 }
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003260
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003261 desc.m_KeepDims = options->keep_dims;
Sadik Armagana2747482021-02-09 10:28:54 +00003262 desc.m_ReduceOperation = reduceOperation;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003263
3264 // Register a new layer object, Sum.
3265 IConnectableLayer *layer = m_Network->AddReduceLayer(desc, layerName.c_str());
3266
3267 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
3268 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3269
3270 // Register input tensor to the layer.
3271 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3272 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3273
3274 // Register output tensor to the layer.
3275 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3276 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3277}
3278
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003279void TfLiteParserImpl::ParseAbs(size_t subgraphIndex, size_t operatorIndex)
3280{
3281 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Abs);
3282}
3283
3284void TfLiteParserImpl::ParseExp(size_t subgraphIndex, size_t operatorIndex)
3285{
3286 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Exp);
3287}
3288
3289void TfLiteParserImpl::ParseLogicalNot(size_t subgraphIndex, size_t operatorIndex)
3290{
3291 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::LogicalNot);
3292}
3293
3294void TfLiteParserImpl::ParseNeg(size_t subgraphIndex, size_t operatorIndex)
3295{
3296 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Neg);
3297}
3298
3299void TfLiteParserImpl::ParseRsqrt(size_t subgraphIndex, size_t operatorIndex)
3300{
3301 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Rsqrt);
3302}
3303
3304void TfLiteParserImpl::ParseElementwiseUnary(size_t subgraphIndex, size_t operatorIndex, UnaryOperation unaryOperation)
3305{
3306 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3307
3308 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3309 CHECK_VALID_SIZE(inputs.size(), 1);
3310
3311 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3312 CHECK_VALID_SIZE(outputs.size(), 1);
3313
3314 std::string layerName = std::string(GetUnaryOperationAsCString(unaryOperation)) + ":{}:{}";
3315 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
3316
3317 ElementwiseUnaryDescriptor desc;
3318 desc.m_Operation = unaryOperation;
3319 IConnectableLayer* layer = m_Network->AddElementwiseUnaryLayer(desc, layerNameFormatted.c_str());
3320 ARMNN_ASSERT(layer != nullptr);
3321
3322 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
3323 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3324
3325 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3326 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3327
3328 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3329 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3330}
3331
Kevin May7d96b162021-02-03 17:38:41 +00003332armnn::IConnectableLayer* TfLiteParserImpl::AddFusedActivationLayer(armnn::IConnectableLayer* prevLayer,
3333 unsigned int outputSlot,
3334 tflite::ActivationFunctionType activationType)
telsoa01c577f2c2018-08-31 09:22:23 +01003335{
3336 ActivationDescriptor activationDesc;
3337 std::string layerName = prevLayer->GetName();
3338
3339 switch(activationType)
3340 {
3341 case tflite::ActivationFunctionType_NONE:
3342 {
3343 // this is a no-op: return previous layer
3344 return prevLayer;
3345 }
3346 case tflite::ActivationFunctionType_RELU:
3347 {
3348 activationDesc.m_Function = ActivationFunction::ReLu;
3349 layerName += ":RELU";
3350 break;
3351 }
3352 case tflite::ActivationFunctionType_RELU6:
3353 {
3354 activationDesc.m_Function = ActivationFunction::BoundedReLu;
3355 activationDesc.m_A = 6.0f;
3356 activationDesc.m_B = 0.0f;
3357 layerName += ":RELU6";
3358 break;
3359 }
3360 case tflite::ActivationFunctionType_TANH:
3361 {
3362 activationDesc.m_Function = ActivationFunction::TanH;
3363 activationDesc.m_A = 1.0f;
3364 activationDesc.m_B = 1.0f;
3365 layerName += ":TANH";
3366 break;
3367 }
3368
3369 // I only put these here as a reminder what others we could support
3370 case tflite::ActivationFunctionType_RELU_N1_TO_1:
3371 case tflite::ActivationFunctionType_SIGN_BIT:
3372 default:
3373 {
3374 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003375 fmt::format("TfLite parser doesn't suppport fused activation: "
3376 "{}/{} {} ",
3377 activationType,
3378 tflite::EnumNameActivationFunctionType(activationType),
3379 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003380
3381 }
3382 }
3383
3384 IConnectableLayer* activationLayer =
3385 m_Network->AddActivationLayer(activationDesc, layerName.c_str());
3386
3387 auto & prevOutputSlot = prevLayer->GetOutputSlot(outputSlot);
3388 prevOutputSlot.Connect(activationLayer->GetInputSlot(0));
3389 activationLayer->GetOutputSlot(0).SetTensorInfo(prevOutputSlot.GetTensorInfo());
3390 return activationLayer;
3391}
3392
Kevin May7d96b162021-02-03 17:38:41 +00003393TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromFile(const char * fileName)
telsoa01c577f2c2018-08-31 09:22:23 +01003394{
3395 if (fileName == nullptr)
3396 {
James Ward58dec6b2020-09-11 17:32:44 +01003397 throw InvalidArgumentException(fmt::format("Invalid (null) file name {}",
telsoa01c577f2c2018-08-31 09:22:23 +01003398 CHECK_LOCATION().AsString()));
3399 }
Francis Murtagh532a29d2020-06-29 11:50:01 +01003400 std::error_code errorCode;
3401 fs::path pathToFile(fileName);
3402 if (!fs::exists(pathToFile, errorCode))
telsoa01c577f2c2018-08-31 09:22:23 +01003403 {
James Ward58dec6b2020-09-11 17:32:44 +01003404 //fmt::format() could not be used here (format error)
3405 std::stringstream msg;
3406 msg << "Cannot find the file (" << fileName << ") errorCode: " << errorCode
3407 << " " << CHECK_LOCATION().AsString();
3408
3409 throw FileNotFoundException(msg.str());
telsoa01c577f2c2018-08-31 09:22:23 +01003410 }
3411 std::ifstream file(fileName, std::ios::binary);
3412 std::string fileContent((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
3413 return LoadModelFromBinary(reinterpret_cast<const uint8_t *>(fileContent.c_str()),
3414 fileContent.size());
3415}
3416
Kevin May7d96b162021-02-03 17:38:41 +00003417TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromBinary(const uint8_t * binaryContent, size_t len)
telsoa01c577f2c2018-08-31 09:22:23 +01003418{
3419 if (binaryContent == nullptr)
3420 {
James Ward58dec6b2020-09-11 17:32:44 +01003421 throw InvalidArgumentException(fmt::format("Invalid (null) binary content {}",
telsoa01c577f2c2018-08-31 09:22:23 +01003422 CHECK_LOCATION().AsString()));
3423 }
3424 flatbuffers::Verifier verifier(binaryContent, len);
3425 if (verifier.VerifyBuffer<tflite::Model>() == false)
3426 {
3427 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003428 fmt::format("Buffer doesn't conform to the expected Tensorflow Lite "
3429 "flatbuffers format. size:{} {}",
3430 len,
3431 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003432 }
3433 return tflite::UnPackModel(binaryContent);
3434}
3435
Kevin May7d96b162021-02-03 17:38:41 +00003436TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetInputs(const ModelPtr & model,
3437 size_t subgraphIndex,
3438 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003439{
3440 CHECK_MODEL(model, subgraphIndex, operatorIndex);
3441
Derek Lambertiff05cc52019-04-26 13:05:17 +01003442 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3443 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003444
3445 size_t inputCount = operatorPtr->inputs.size();
mathad01c21025d2021-04-26 10:09:37 +01003446 TensorRawPtrVector result;
telsoa01c577f2c2018-08-31 09:22:23 +01003447 for (size_t i=0; i<inputCount; ++i)
3448 {
mathad01c21025d2021-04-26 10:09:37 +01003449 // If the input location is -1 then assume input is turned off.
3450 if (operatorPtr->inputs[i] == -1)
3451 {
3452 continue;
3453 }
3454 else
3455 {
3456 uint32_t inputId = CHECKED_NON_NEGATIVE(operatorPtr->inputs[i]);
3457 result.push_back(subgraphPtr->tensors[inputId].get());
3458 }
telsoa01c577f2c2018-08-31 09:22:23 +01003459 }
3460 return result;
3461}
3462
Kevin May7d96b162021-02-03 17:38:41 +00003463TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetOutputs(const ModelPtr & model,
3464 size_t subgraphIndex,
3465 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003466{
3467 CHECK_MODEL(model, subgraphIndex, operatorIndex);
3468
Derek Lambertiff05cc52019-04-26 13:05:17 +01003469 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3470 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003471
3472 size_t outputCount = operatorPtr->outputs.size();
3473 TensorRawPtrVector result(outputCount);
3474 for (size_t i=0; i<outputCount; ++i)
3475 {
3476 uint32_t outputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[i]);
3477 CHECK_TENSOR(model, subgraphIndex, outputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003478 result[i] = subgraphPtr->tensors[outputId].get();
telsoa01c577f2c2018-08-31 09:22:23 +01003479 }
3480 return result;
3481}
3482
Kevin May7d96b162021-02-03 17:38:41 +00003483TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphInputs(const ModelPtr & model,
3484 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003485{
3486 CHECK_SUBGRAPH(model, subgraphIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003487 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003488
Derek Lambertiff05cc52019-04-26 13:05:17 +01003489 size_t inputCount = subgraphPtr->inputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01003490 TensorIdRawPtrVector result(inputCount);
3491 for (size_t i=0; i<inputCount; ++i)
3492 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01003493 uint32_t inputId = CHECKED_NON_NEGATIVE(subgraphPtr->inputs[i]);
telsoa01c577f2c2018-08-31 09:22:23 +01003494 CHECK_TENSOR(model, subgraphIndex, inputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003495 result[i] = std::make_pair(inputId, subgraphPtr->tensors[inputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01003496 }
3497 return result;
3498}
3499
Kevin May7d96b162021-02-03 17:38:41 +00003500TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphOutputs(const ModelPtr & model,
3501 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003502{
3503 CHECK_SUBGRAPH(model, subgraphIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003504 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003505
Derek Lambertiff05cc52019-04-26 13:05:17 +01003506 size_t outputCount = subgraphPtr->outputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01003507 TensorIdRawPtrVector result(outputCount);
3508 for (size_t i=0; i<outputCount; ++i)
3509 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01003510 uint32_t outputId = CHECKED_NON_NEGATIVE(subgraphPtr->outputs[i]);
3511 result[i] = std::make_pair(outputId, subgraphPtr->tensors[outputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01003512 }
3513 return result;
3514}
3515
Kevin May7d96b162021-02-03 17:38:41 +00003516std::vector<int32_t>& TfLiteParserImpl::GetInputTensorIds(const ModelPtr& model,
3517 size_t subgraphIndex,
3518 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003519{
3520 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003521 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3522 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003523 return operatorPtr->inputs;
3524}
3525
Kevin May7d96b162021-02-03 17:38:41 +00003526std::vector<int32_t>& TfLiteParserImpl::GetOutputTensorIds(const ModelPtr& model,
3527 size_t subgraphIndex,
3528 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003529{
3530 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003531 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3532 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003533 return operatorPtr->outputs;
3534}
3535
Kevin May7d96b162021-02-03 17:38:41 +00003536void TfLiteParserImpl::RegisterInputSlots(size_t subgraphIndex,
3537 size_t operatorIndex,
3538 IConnectableLayer* layer,
Finn Williamsd4fa5452021-03-01 12:31:41 +00003539 const std::vector<unsigned int>& tensorIndexes,
3540 unsigned int startingSlotIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003541{
3542 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003543 ARMNN_ASSERT(layer != nullptr);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003544 if (tensorIndexes.size() + startingSlotIndex != layer->GetNumInputSlots())
telsoa01c577f2c2018-08-31 09:22:23 +01003545 {
3546 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003547 fmt::format("The number of tensor inputs ({}) does not match the number expected ({})"
3548 " for subgraph:{} operator index:{} {}",
3549 tensorIndexes.size(),
3550 layer->GetNumInputSlots(),
3551 subgraphIndex,
3552 operatorIndex,
3553 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003554 }
3555
Finn Williamsd4fa5452021-03-01 12:31:41 +00003556 for (unsigned int index = 0; index < tensorIndexes.size() ; ++index)
telsoa01c577f2c2018-08-31 09:22:23 +01003557 {
Finn Williamsd4fa5452021-03-01 12:31:41 +00003558 unsigned int tensorIndex = tensorIndexes[index];
3559 armnn::IInputSlot* slot = &(layer->GetInputSlot(startingSlotIndex + index));
telsoa01c577f2c2018-08-31 09:22:23 +01003560 RegisterConsumerOfTensor(subgraphIndex, tensorIndex, slot);
3561 }
3562}
3563
Kevin May7d96b162021-02-03 17:38:41 +00003564void TfLiteParserImpl::RegisterOutputSlots(size_t subgraphIndex,
3565 size_t operatorIndex,
3566 IConnectableLayer* layer,
3567 const std::vector<unsigned int>& tensorIndexes)
telsoa01c577f2c2018-08-31 09:22:23 +01003568{
3569 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003570 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01003571 if (tensorIndexes.size() != layer->GetNumOutputSlots())
3572 {
3573 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003574 fmt::format("The number of tensor outputs ({}) does not match the number expected ({})"
3575 " for subgraph:{} operator index:{} {}",
3576 tensorIndexes.size(),
3577 layer->GetNumOutputSlots(),
3578 subgraphIndex,
3579 operatorIndex,
3580 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003581 }
3582
3583 for (unsigned int slotIndex = 0; slotIndex < layer->GetNumOutputSlots(); ++slotIndex)
3584 {
3585 unsigned int tensorIndex = tensorIndexes[slotIndex];
3586 armnn::IOutputSlot* slot = &(layer->GetOutputSlot(slotIndex));
3587 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
3588 }
3589}
3590
Kevin May7d96b162021-02-03 17:38:41 +00003591void TfLiteParserImpl::SetupInputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003592{
3593 CHECK_SUBGRAPH(m_Model, subgraphIndex);
3594
3595 auto inputs = GetSubgraphInputs(m_Model, subgraphIndex);
3596 for (auto const & tensorIdAndPtr : inputs)
3597 {
3598 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
3599 IConnectableLayer* layer =
3600 m_Network->AddInputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
3601
3602 auto tensorInfo = ToTensorInfo(tensorIdAndPtr.second);
3603 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
3604
3605 RegisterOutputSlots(subgraphIndex,
3606 VIRTUAL_OPERATOR_ID,
3607 layer,
3608 { static_cast<uint32_t>(tensorIdAndPtr.first) });
3609 }
3610}
3611
Kevin May7d96b162021-02-03 17:38:41 +00003612void TfLiteParserImpl::SetupOutputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003613{
3614 CHECK_SUBGRAPH(m_Model, subgraphIndex);
3615
3616 auto outputs = GetSubgraphOutputs(m_Model, subgraphIndex);
3617 for (auto const & tensorIdAndPtr : outputs)
3618 {
3619 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
3620 IConnectableLayer* layer =
3621 m_Network->AddOutputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
3622
3623 RegisterInputSlots(subgraphIndex,
3624 VIRTUAL_OPERATOR_ID,
3625 layer,
3626 { static_cast<uint32_t>(tensorIdAndPtr.first) });
3627 }
3628}
3629
Kevin May7d96b162021-02-03 17:38:41 +00003630void TfLiteParserImpl::SetupConstantLayers(size_t subgraphIndex)
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003631{
3632 CHECK_SUBGRAPH(m_Model, subgraphIndex);
3633
Derek Lambertiff05cc52019-04-26 13:05:17 +01003634 const auto & subgraphPtr = m_Model->subgraphs[subgraphIndex];
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003635 for (unsigned int subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
3636 {
3637 for (unsigned int tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
3638 {
3639 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot == nullptr &&
3640 m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size() > 0)
3641 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01003642 TensorRawPtr tensorPtr = subgraphPtr->tensors[tensorIndex].get();
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003643 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003644 auto tensorAndData = CreateConstTensorNonPermuted(tensorPtr, tensorInfo);
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003645
James Ward58dec6b2020-09-11 17:32:44 +01003646 std::string layerName = fmt::format("Constant:{}", tensorPtr->name);
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003647 IConnectableLayer *layer =
Finn Williamsd4fa5452021-03-01 12:31:41 +00003648 m_Network->AddConstantLayer(tensorAndData, layerName.c_str());
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003649
3650 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
3651 RegisterOutputSlots(subgraphIndex,
3652 VIRTUAL_OPERATOR_ID,
3653 layer,
3654 { tensorIndex });
3655
3656 }
3657 }
3658 }
3659}
3660
telsoa01c577f2c2018-08-31 09:22:23 +01003661// example usage: BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Kevin May7d96b162021-02-03 17:38:41 +00003662TfLiteParserImpl::BufferRawPtr TfLiteParserImpl::GetBuffer(const ModelPtr& model, size_t bufferIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003663{
3664 CHECK_BUFFER(model, bufferIndex);
3665 return model->buffers[bufferIndex].get();
3666}
3667
Matteo Martincigh747ef822018-12-18 09:26:39 +00003668template<typename T>
Kevin May7d96b162021-02-03 17:38:41 +00003669std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
3670TfLiteParserImpl::CreateConstTensorAndStoreData(TfLiteParserImpl::BufferRawPtr bufferPtr,
3671 TfLiteParserImpl::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +00003672 armnn::TensorInfo& tensorInfo,
3673 armnn::Optional<armnn::PermutationVector&> permutationVector)
3674{
3675 auto constData = CreateConstTensorImpl<T>(bufferPtr,
3676 tensorPtr,
3677 tensorInfo,
3678 permutationVector);
Kevin May7d96b162021-02-03 17:38:41 +00003679 TfLiteParserImpl::SupportedDataStorage storage(std::move(constData.second));
Matteo Martincigh747ef822018-12-18 09:26:39 +00003680 return std::make_pair(constData.first, std::move(storage));
3681}
3682
Finn Williamsd4fa5452021-03-01 12:31:41 +00003683bool TfLiteParserImpl::IsConstTensor(TensorRawPtr tensorPtr)
3684{
3685 CHECK_TENSOR_PTR(tensorPtr);
mathad01bf7edb62021-04-20 16:12:45 +01003686 bool isConst = true;
3687
3688 auto buffer = GetBuffer(m_Model, tensorPtr->buffer);
3689 if (buffer->data.size() == 0)
3690 {
3691 isConst = false;
3692 }
3693
3694 return isConst;
Finn Williamsd4fa5452021-03-01 12:31:41 +00003695}
3696
3697
Kevin May7d96b162021-02-03 17:38:41 +00003698std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
Finn Williamsd4fa5452021-03-01 12:31:41 +00003699TfLiteParserImpl::CreateConstTensorPermuted(TensorRawPtr tensorPtr,
3700 armnn::TensorInfo& tensorInfo,
3701 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +01003702{
3703 CHECK_TENSOR_PTR(tensorPtr);
3704 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
3705 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
3706
3707 switch (tensorInfo.GetDataType())
3708 {
3709 case armnn::DataType::Float32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00003710 return CreateConstTensorAndStoreData<float>(bufferPtr,
3711 tensorPtr,
3712 tensorInfo,
3713 permutationVector);
Derek Lambertif90c56d2020-01-10 17:14:08 +00003714 case armnn::DataType::QAsymmU8:
Matteo Martincigh747ef822018-12-18 09:26:39 +00003715 return CreateConstTensorAndStoreData<uint8_t>(bufferPtr,
3716 tensorPtr,
3717 tensorInfo,
3718 permutationVector);
Keith Davisd305e1a2020-01-22 11:57:54 +00003719 case armnn::DataType::QSymmS8:
3720 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
3721 tensorPtr,
3722 tensorInfo,
3723 permutationVector);
Keith Davis67e6c542020-02-19 10:08:33 +00003724 case armnn::DataType::QAsymmS8:
3725 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
3726 tensorPtr,
3727 tensorInfo,
3728 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01003729 case armnn::DataType::Signed32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00003730 return CreateConstTensorAndStoreData<int32_t>(bufferPtr,
3731 tensorPtr,
3732 tensorInfo,
3733 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01003734 default:
3735 {
3736 std::stringstream errString;
3737 errString << "Unexpected datatype when creating const tensor: "
3738 << armnn::GetDataTypeName(tensorInfo.GetDataType())
3739 << " shape:" << tensorInfo.GetShape()
3740 << CHECK_LOCATION().AsString();
3741 throw ParseException(errString.str());
3742 }
3743 }
3744}
3745
Finn Williamsd4fa5452021-03-01 12:31:41 +00003746armnn::ConstTensor TfLiteParserImpl::CreateConstTensorNonPermuted(TensorRawPtr tensorPtr,
3747 armnn::TensorInfo& tensorInfo)
3748{
3749 CHECK_TENSOR_PTR(tensorPtr);
3750 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
3751 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
3752
3753 return ConstTensor(tensorInfo, bufferPtr->data.data());
3754}
3755
Kevin May7d96b162021-02-03 17:38:41 +00003756BindingPointInfo TfLiteParserImpl::GetNetworkInputBindingInfo(size_t subgraphId,
3757 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01003758{
3759 CHECK_SUBGRAPH(m_Model, subgraphId);
3760 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
3761 for (auto const & input : inputs)
3762 {
3763 if (input.second->name == name)
3764 {
3765 auto bindingId = GenerateLayerBindingId(subgraphId, input.first);
3766 return std::make_pair(bindingId, ToTensorInfo(input.second));
3767 }
3768 }
3769
3770 std::stringstream bindings;
3771 for (auto const & input : inputs)
3772 {
3773 bindings << "'" << input.second->name << "' ";
3774 }
3775
3776 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003777 fmt::format("No input binding found for subgraph:{} and name:{}. "
3778 "Possible inputs are: [{}] {}",
3779 subgraphId,
3780 name,
3781 bindings.str(),
3782 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003783}
3784
Kevin May7d96b162021-02-03 17:38:41 +00003785BindingPointInfo TfLiteParserImpl::GetNetworkOutputBindingInfo(size_t subgraphId,
3786 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01003787{
3788 CHECK_SUBGRAPH(m_Model, subgraphId);
3789 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003790 for (unsigned int i = 0; i < outputs.size(); ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01003791 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003792 auto const output = outputs[i];
telsoa01c577f2c2018-08-31 09:22:23 +01003793 if (output.second->name == name)
3794 {
3795 auto bindingId = GenerateLayerBindingId(subgraphId, output.first);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003796 std::vector<unsigned int> shape = m_OverridenOutputShapes.size() > 0 ?
3797 m_OverridenOutputShapes[i] : AsUnsignedVector(output.second->shape);
3798 return std::make_pair(bindingId, ToTensorInfo(output.second, shape));
telsoa01c577f2c2018-08-31 09:22:23 +01003799 }
3800 }
3801
3802 std::stringstream bindings;
3803 for (auto const & output : outputs)
3804 {
3805 bindings << "'" << output.second->name << "' ";
3806 }
3807
3808 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003809 fmt::format("No output binding found for subgraph:{} and name:{}. "
3810 "Possible outputs are: [{}] {}",
3811 subgraphId,
3812 name,
3813 bindings.str(),
3814 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003815}
3816
Kevin May7d96b162021-02-03 17:38:41 +00003817size_t TfLiteParserImpl::GetSubgraphCount() const
telsoa01c577f2c2018-08-31 09:22:23 +01003818{
3819 return m_Model->subgraphs.size();
3820}
3821
Kevin May7d96b162021-02-03 17:38:41 +00003822std::vector<std::string> TfLiteParserImpl::GetSubgraphInputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01003823{
3824 CHECK_SUBGRAPH(m_Model, subgraphId);
3825 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
3826 std::vector<std::string> result;
3827 result.reserve(inputs.size());
3828 for (auto const & input : inputs)
3829 {
3830 result.push_back(input.second->name);
3831 }
3832 return result;
3833}
3834
Kevin May7d96b162021-02-03 17:38:41 +00003835std::vector<std::string> TfLiteParserImpl::GetSubgraphOutputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01003836{
3837 CHECK_SUBGRAPH(m_Model, subgraphId);
3838 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
3839 std::vector<std::string> result;
3840 result.reserve(outputs.size());
3841 for (auto const & output : outputs)
3842 {
3843 result.push_back(output.second->name);
3844 }
3845 return result;
3846}
3847
Matthew Sloyanac001ee2021-02-03 10:43:04 +00003848const std::string TfLiteParserImpl::GetVersion()
3849{
3850 return TFLITE_PARSER_VERSION;
3851}
3852
Kevin May7d96b162021-02-03 17:38:41 +00003853TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<float[]> && data)
telsoa01c577f2c2018-08-31 09:22:23 +01003854: m_FloatData(std::move(data))
3855, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00003856, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01003857, m_Int32Data(nullptr)
3858{
3859}
3860
Kevin May7d96b162021-02-03 17:38:41 +00003861TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<uint8_t[]> && data)
telsoa01c577f2c2018-08-31 09:22:23 +01003862: m_FloatData(nullptr)
3863, m_Uint8Data(std::move(data))
Keith Davisd305e1a2020-01-22 11:57:54 +00003864, m_Int8Data(nullptr)
3865, m_Int32Data(nullptr)
3866{
3867}
3868
Kevin May7d96b162021-02-03 17:38:41 +00003869TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int8_t[]> && data)
Keith Davisd305e1a2020-01-22 11:57:54 +00003870: m_FloatData(nullptr)
3871, m_Uint8Data(nullptr)
3872, m_Int8Data(std::move(data))
telsoa01c577f2c2018-08-31 09:22:23 +01003873, m_Int32Data(nullptr)
3874{
3875}
3876
Kevin May7d96b162021-02-03 17:38:41 +00003877TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int32_t[]> && data)
telsoa01c577f2c2018-08-31 09:22:23 +01003878: m_FloatData(nullptr)
3879, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00003880, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01003881, m_Int32Data(std::move(data))
3882{
3883}
3884
3885} // armnnTfLiteParser