blob: 7c81a8f75724b4c9fce779f3096bb57798527890 [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;
641 m_ParserFunctions[tflite::BuiltinOperator_QUANTIZE] = &TfLiteParserImpl::ParseQuantize;
642 m_ParserFunctions[tflite::BuiltinOperator_RELU] = &TfLiteParserImpl::ParseRelu;
643 m_ParserFunctions[tflite::BuiltinOperator_RELU6] = &TfLiteParserImpl::ParseRelu6;
Sadik Armagana2747482021-02-09 10:28:54 +0000644 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MAX] = &TfLiteParserImpl::ParseReduceMax;
645 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MIN] = &TfLiteParserImpl::ParseReduceMin;
Kevin May7d96b162021-02-03 17:38:41 +0000646 m_ParserFunctions[tflite::BuiltinOperator_RESHAPE] = &TfLiteParserImpl::ParseReshape;
647 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_BILINEAR] = &TfLiteParserImpl::ParseResizeBilinear;
648 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_NEAREST_NEIGHBOR] = &TfLiteParserImpl::ParseResizeNearestNeighbor;
Matthew Sloyaned7fce42021-04-15 20:46:24 +0100649 m_ParserFunctions[tflite::BuiltinOperator_RSQRT] = &TfLiteParserImpl::ParseRsqrt;
Kevin May7d96b162021-02-03 17:38:41 +0000650 m_ParserFunctions[tflite::BuiltinOperator_SLICE] = &TfLiteParserImpl::ParseSlice;
651 m_ParserFunctions[tflite::BuiltinOperator_SOFTMAX] = &TfLiteParserImpl::ParseSoftmax;
652 m_ParserFunctions[tflite::BuiltinOperator_SPACE_TO_BATCH_ND] = &TfLiteParserImpl::ParseSpaceToBatchND;
653 m_ParserFunctions[tflite::BuiltinOperator_SPLIT] = &TfLiteParserImpl::ParseSplit;
654 m_ParserFunctions[tflite::BuiltinOperator_SPLIT_V] = &TfLiteParserImpl::ParseSplitV;
655 m_ParserFunctions[tflite::BuiltinOperator_SQUEEZE] = &TfLiteParserImpl::ParseSqueeze;
656 m_ParserFunctions[tflite::BuiltinOperator_STRIDED_SLICE] = &TfLiteParserImpl::ParseStridedSlice;
657 m_ParserFunctions[tflite::BuiltinOperator_SUB] = &TfLiteParserImpl::ParseSub;
658 m_ParserFunctions[tflite::BuiltinOperator_SUM] = &TfLiteParserImpl::ParseSum;
659 m_ParserFunctions[tflite::BuiltinOperator_TANH] = &TfLiteParserImpl::ParseTanH;
660 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE] = &TfLiteParserImpl::ParseTranspose;
661 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE_CONV] = &TfLiteParserImpl::ParseTransposeConv;
662 m_ParserFunctions[tflite::BuiltinOperator_UNPACK] = &TfLiteParserImpl::ParseUnpack;
Matthew Sloyan28f177c2021-04-09 14:38:52 +0100663
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100664 // register supported custom operators
Kevin May7d96b162021-02-03 17:38:41 +0000665 m_CustomParserFunctions["TFLite_Detection_PostProcess"] = &TfLiteParserImpl::ParseDetectionPostProcess;
telsoa01c577f2c2018-08-31 09:22:23 +0100666}
667
Kevin May7d96b162021-02-03 17:38:41 +0000668void TfLiteParserImpl::ResetParser()
telsoa01c577f2c2018-08-31 09:22:23 +0100669{
670 m_Network = armnn::INetworkPtr(nullptr, nullptr);
671 m_Model = nullptr;
672 m_SubgraphConnections.clear();
673}
674
Kevin May7d96b162021-02-03 17:38:41 +0000675INetworkPtr TfLiteParserImpl::CreateNetworkFromBinaryFile(const char* graphFile)
telsoa01c577f2c2018-08-31 09:22:23 +0100676{
677 ResetParser();
678 m_Model = LoadModelFromFile(graphFile);
679 return CreateNetworkFromModel();
680}
681
Kevin May7d96b162021-02-03 17:38:41 +0000682INetworkPtr TfLiteParserImpl::CreateNetworkFromBinary(const std::vector<uint8_t> & binaryContent)
telsoa01c577f2c2018-08-31 09:22:23 +0100683{
684 ResetParser();
685 m_Model = LoadModelFromBinary(binaryContent.data(), binaryContent.size());
686 return CreateNetworkFromModel();
687}
688
Kevin May7d96b162021-02-03 17:38:41 +0000689INetworkPtr TfLiteParserImpl::CreateNetworkFromModel()
telsoa01c577f2c2018-08-31 09:22:23 +0100690{
Sadik Armagand109a4d2020-07-28 10:42:13 +0100691
692 using NetworkOptions = std::vector<BackendOptions>;
693 NetworkOptions networkOptions = {};
694 if (m_Options && m_Options.value().m_InferAndValidate)
695 {
696 BackendOptions shapeInferenceMethodOption("ShapeInferenceMethod",
697 {
698 { "InferAndValidate", true }
699 });
700
701 networkOptions.push_back(shapeInferenceMethodOption);
702 }
703
704 m_Network = INetwork::Create(networkOptions);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100705 ARMNN_ASSERT(m_Model.get() != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +0100706
telsoa01c577f2c2018-08-31 09:22:23 +0100707 if (m_Model->subgraphs.size() != 1)
708 {
709 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100710 fmt::format("Current TfLite parser only supports 1 subgraph. Current one has: {} {}",
711 m_Model->subgraphs.size(),
712 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100713 }
714
715 size_t subgraphIndex = 0;
Colm Donelan6350d272020-06-09 16:56:25 +0100716 size_t operatorIndex = 0;
717 try
telsoa01c577f2c2018-08-31 09:22:23 +0100718 {
Colm Donelan6350d272020-06-09 16:56:25 +0100719 for (SubgraphPtr const& subgraph : m_Model->subgraphs)
telsoa01c577f2c2018-08-31 09:22:23 +0100720 {
Colm Donelan6350d272020-06-09 16:56:25 +0100721 m_SubgraphConnections.emplace_back(subgraph->tensors.size());
722 for (OperatorPtr const& op : subgraph->operators)
telsoa01c577f2c2018-08-31 09:22:23 +0100723 {
Colm Donelan6350d272020-06-09 16:56:25 +0100724 auto const& opCodePtr = m_Model->operator_codes[op->opcode_index];
telsoa01c577f2c2018-08-31 09:22:23 +0100725 auto builtinCode = opCodePtr->builtin_code;
726
727 if (builtinCode > tflite::BuiltinOperator_MAX)
728 {
James Ward58dec6b2020-09-11 17:32:44 +0100729 throw ParseException(fmt::format("Operator code {} is out of range 0-{}. "
730 "subgraph:{} operator idx:{}. {}",
731 builtinCode, tflite::BuiltinOperator_MAX, subgraphIndex,
732 operatorIndex, CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100733 }
734
735 // lookup and call the parser function
Colm Donelan6350d272020-06-09 16:56:25 +0100736 auto& parserFunction = m_ParserFunctions[builtinCode];
telsoa01c577f2c2018-08-31 09:22:23 +0100737 (this->*parserFunction)(subgraphIndex, operatorIndex);
Colm Donelan6350d272020-06-09 16:56:25 +0100738 ++operatorIndex;
telsoa01c577f2c2018-08-31 09:22:23 +0100739 }
telsoa01c577f2c2018-08-31 09:22:23 +0100740
Colm Donelan6350d272020-06-09 16:56:25 +0100741 SetupInputLayers(subgraphIndex);
742 SetupOutputLayers(subgraphIndex);
743 SetupConstantLayers(subgraphIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100744
Colm Donelan6350d272020-06-09 16:56:25 +0100745 ++subgraphIndex;
746 operatorIndex = 0;
telsoa01c577f2c2018-08-31 09:22:23 +0100747 }
telsoa01c577f2c2018-08-31 09:22:23 +0100748 }
Colm Donelan6350d272020-06-09 16:56:25 +0100749 catch (const ParseException& e)
telsoa01c577f2c2018-08-31 09:22:23 +0100750 {
Colm Donelan6350d272020-06-09 16:56:25 +0100751 std::stringstream errorString;
752 errorString << "Failed to parse operator #" << operatorIndex << " within subgraph #"
753 << subgraphIndex << " error: " << e.what();
754 ARMNN_LOG(error) << errorString.str();
755 std::stringstream errors;
756 errors << errorString.str() << "\n";
telsoa01c577f2c2018-08-31 09:22:23 +0100757 throw ParseException(errors.str());
758 }
759
760 // establish the connections from the layer outputs to the inputs of the subsequent layers
Colm Donelan6350d272020-06-09 16:56:25 +0100761 for (subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100762 {
763 for (size_t tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
764 {
765 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot != nullptr)
766 {
767 for (size_t inputSlotIdx = 0;
768 inputSlotIdx < m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size();
769 ++inputSlotIdx)
770 {
771 m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot->Connect(
772 *(m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots[inputSlotIdx]));
773 }
774 }
775 }
776 }
777
778 return std::move(m_Network);
779}
780
Kevin May7d96b162021-02-03 17:38:41 +0000781void TfLiteParserImpl::RegisterProducerOfTensor(size_t subgraphIndex,
782 size_t tensorIndex,
783 armnn::IOutputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +0100784{
785 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100786 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
787 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100788
789 TensorSlots & tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
790
791 // assuming there is only one producer for that tensor
792 if (tensorSlots.outputSlot != nullptr)
793 {
James Ward58dec6b2020-09-11 17:32:44 +0100794 throw ParseException(fmt::format("Another layer has already registered itself as the producer of "
795 "subgraph:{} tensor:{} {}",
796 subgraphIndex,
797 tensorIndex,
798 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100799 }
800
801 tensorSlots.outputSlot = slot;
802}
803
Kevin May7d96b162021-02-03 17:38:41 +0000804void TfLiteParserImpl::RegisterConsumerOfTensor(size_t subgraphIndex,
805 size_t tensorIndex,
806 armnn::IInputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +0100807{
808 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100809 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
810 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100811
Finn Williamsd4fa5452021-03-01 12:31:41 +0000812 TensorSlots& tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +0100813 tensorSlots.inputSlots.push_back(slot);
814}
815
Kevin May7d96b162021-02-03 17:38:41 +0000816void TfLiteParserImpl::ParseCustomOperator(size_t subgraphIndex, size_t operatorIndex)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100817{
818 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
819
820 // NOTE: By default we presume the custom operator is not supported
Kevin May7d96b162021-02-03 17:38:41 +0000821 auto customParserFunction = &TfLiteParserImpl::ParseUnsupportedOperator;
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100822
823 // Identify custom code defined for custom operator
824 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
825 const auto& customCode = m_Model->operator_codes[operatorPtr->opcode_index]->custom_code;
826
827 // Find parser function that correspondes to custom code (if any)
828 auto iterator = m_CustomParserFunctions.find(customCode);
829 if (iterator != m_CustomParserFunctions.end())
830 {
831 customParserFunction = iterator->second;
832 }
833
834 // Run parser function
835 (this->*customParserFunction)(subgraphIndex, operatorIndex);
836}
837
Kevin May7d96b162021-02-03 17:38:41 +0000838void TfLiteParserImpl::ParseUnsupportedOperator(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100839{
840 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100841
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100842 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
843
844 auto opcodeIndex = operatorPtr->opcode_index;
845 auto opcode = m_Model->operator_codes[opcodeIndex]->builtin_code;
846
847 if (!m_Options || !m_Options.value().m_StandInLayerForUnsupported)
848 {
849 // Do not add StandInLayer, throw ParseException instead
850 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100851 fmt::format("Operator not supported. "
852 "subgraph:{} operator:{} "
853 "opcode_index:{} opcode:{} / {} {}",
854 subgraphIndex,
855 operatorIndex,
856 opcodeIndex,
857 opcode,
858 tflite::EnumNameBuiltinOperator(opcode),
859 CHECK_LOCATION().AsString()));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100860 }
861
862 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
863 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
864
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100865 const unsigned int numInputs = armnn::numeric_cast<unsigned int>(inputs.size());
866 const unsigned int numOutputs = armnn::numeric_cast<unsigned int>(outputs.size());
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100867
868 StandInDescriptor descriptor(numInputs, numOutputs);
James Ward58dec6b2020-09-11 17:32:44 +0100869 auto layerName = fmt::format("StandIn:{}:{}:{}", subgraphIndex, operatorIndex, opcode);
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100870
871 // Add a non-executable StandInLayer as a placeholder for any unsupported operator
872 IConnectableLayer* layer = m_Network->AddStandInLayer(descriptor, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +0100873 ARMNN_ASSERT(layer != nullptr);
874
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100875 for (unsigned int i = 0u; i < numOutputs; ++i)
876 {
Sadik Armagand109a4d2020-07-28 10:42:13 +0100877 layer->GetOutputSlot(i).SetTensorInfo(ToTensorInfo(outputs[i], true));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100878 }
879
880 auto inputTensorIds = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
881 auto outputTensorIds = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
882
883 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIds);
884 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIds);
telsoa01c577f2c2018-08-31 09:22:23 +0100885}
886
mathad01b392e982021-04-07 12:07:30 +0100887void TfLiteParserImpl::ParseCast(size_t subgraphIndex, size_t operatorIndex)
888{
889 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
890
891 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
892 CHECK_VALID_SIZE(inputs.size(), 1);
893 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
894 CHECK_VALID_SIZE(outputs.size(), 1);
895
896 auto layerName = fmt::format("Cast:{}:{}", subgraphIndex, operatorIndex);
897
898 IConnectableLayer* layer = m_Network->AddCastLayer(layerName.c_str());
899 ARMNN_ASSERT(layer != nullptr);
900
901 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
902 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
903
904 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
905 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
906
907 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
908 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
909}
910
Kevin May7d96b162021-02-03 17:38:41 +0000911void TfLiteParserImpl::ParseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100912{
913 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
914
915 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
916 const auto * options = operatorPtr->builtin_options.AsConv2DOptions();
917
918 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
919
920 Convolution2dDescriptor desc;
921 desc.m_BiasEnabled = false;
922 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
923 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +0000924 desc.m_DataLayout = armnn::DataLayout::NHWC;
Pablo Tellof0bd6832019-04-26 17:58:13 +0100925 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
926 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +0000927
telsoa01c577f2c2018-08-31 09:22:23 +0100928 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
929 CHECK_VALID_SIZE(inputs.size(), 2, 3);
930
931 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
932 CHECK_VALID_SIZE(outputs.size(), 1);
933
934 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
935 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
936
937 // assuming input is NHWC
938 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
939 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
940
941 // assuming the filter is OHWI : Output, H, W, Input
942 // which is essentially the same as NHWC
943 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
944 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
945
Pablo Tellof0bd6832019-04-26 17:58:13 +0100946 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
947 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
948 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
949 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +0100950
Finn Williamsd4fa5452021-03-01 12:31:41 +0000951 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo);
Matthew Jackson74bf7da2019-08-16 16:51:42 +0100952 armnn::IConnectableLayer* layer = nullptr;
telsoa01c577f2c2018-08-31 09:22:23 +0100953
James Ward58dec6b2020-09-11 17:32:44 +0100954 auto layerName = fmt::format("Conv2D:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100955
956 if (inputs.size() == 3)
957 {
958 desc.m_BiasEnabled = true;
959 armnn::TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +0000960 auto biasTensorAndData = CreateConstTensorNonPermuted(inputs[2], biasTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +0100961 layer = m_Network->AddConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +0000962 filterTensorAndData,
963 Optional<ConstTensor>(biasTensorAndData),
telsoa01c577f2c2018-08-31 09:22:23 +0100964 layerName.c_str());
965 }
966 else
967 {
968 layer = m_Network->AddConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +0000969 filterTensorAndData,
Matteo Martincighfc598e12019-05-14 10:36:13 +0100970 EmptyOptional(),
telsoa01c577f2c2018-08-31 09:22:23 +0100971 layerName.c_str());
972 }
973
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100974 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +0100975
Sadik Armagand109a4d2020-07-28 10:42:13 +0100976 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
jimfly01c25411c2018-11-14 17:47:22 +0000977 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +0100978
979 // register the input connection slots for the layer, connections are made after all layers have been created
980 // only the tensors for the inputs are relevant, exclude the const tensors
981 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +0000982 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
telsoa01c577f2c2018-08-31 09:22:23 +0100983
jimfly01c25411c2018-11-14 17:47:22 +0000984 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +0100985 // register the output connection slots for the layer, connections are made after all layers have been created
986 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
987 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
988}
989
Kevin May7d96b162021-02-03 17:38:41 +0000990void TfLiteParserImpl::ParseDepthwiseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100991{
992 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
993
994 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
995 const auto * options = operatorPtr->builtin_options.AsDepthwiseConv2DOptions();
996
997 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
998
999 DepthwiseConvolution2dDescriptor desc;
1000 desc.m_BiasEnabled = false;
1001 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1002 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +00001003 desc.m_DataLayout = armnn::DataLayout::NHWC;
Matthew Jacksond6a9dee2019-07-22 13:53:24 +01001004 CHECKED_NON_NEGATIVE(options->depth_multiplier);
telsoa01c577f2c2018-08-31 09:22:23 +01001005
1006 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1007 CHECK_VALID_SIZE(inputs.size(), 2, 3);
1008 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1009 CHECK_VALID_SIZE(outputs.size(), 1);
Pablo Tellof0bd6832019-04-26 17:58:13 +01001010 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
1011 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +00001012
Keith Davis0c2eeac2020-02-11 16:51:50 +00001013 // Mappings from TensorflowLite filter tensors to the ArmNN filter tensors (ArmNN weights have to be [M, I, H, W])
1014 PermutationVector permutationVector{ 2, 3, 1, 0 }; // [H, W, I, M] -> [M, I, H, W]
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001015
telsoa01c577f2c2018-08-31 09:22:23 +01001016 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Jan Eilers7612bd62021-04-06 17:29:03 +01001017 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
telsoa01c577f2c2018-08-31 09:22:23 +01001018
Matteo Martincigh747ef822018-12-18 09:26:39 +00001019 // Assuming input is NHWC
telsoa01c577f2c2018-08-31 09:22:23 +01001020 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1021 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
Matteo Martincigh747ef822018-12-18 09:26:39 +00001022
1023 // TensorflowLite weights come in the format [1, H, W, I * M]
telsoa01c577f2c2018-08-31 09:22:23 +01001024 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1025 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1026
Matteo Martincigh747ef822018-12-18 09:26:39 +00001027 // Reshape weights as [ H, W, I, M ]
1028 filterTensorInfo.SetShape({ filterHeight,
1029 filterWidth,
1030 inputTensorInfo.GetShape()[3],
1031 filterTensorInfo.GetShape()[3] / inputTensorInfo.GetShape()[3] });
1032
Pablo Tellof0bd6832019-04-26 17:58:13 +01001033 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1034 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1035 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1036 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +01001037
Finn Williamsd4fa5452021-03-01 12:31:41 +00001038 auto filterTensorAndData = CreateConstTensorPermuted(inputs[1], filterTensorInfo, permutationVector);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001039 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01001040 auto layerName = fmt::format("DepthwiseConv2D:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001041
1042 if (inputs.size() == 3)
1043 {
1044 desc.m_BiasEnabled = true;
1045 TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00001046 auto biasTensorAndData = CreateConstTensorNonPermuted(inputs[2], biasTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001047 layer = m_Network->AddDepthwiseConvolution2dLayer(desc,
1048 filterTensorAndData.first,
Finn Williamsd4fa5452021-03-01 12:31:41 +00001049 Optional<ConstTensor>(biasTensorAndData),
telsoa01c577f2c2018-08-31 09:22:23 +01001050 layerName.c_str());
1051 }
1052 else
1053 {
1054 layer = m_Network->AddDepthwiseConvolution2dLayer(desc,
1055 filterTensorAndData.first,
Matteo Martincighfc598e12019-05-14 10:36:13 +01001056 EmptyOptional(),
telsoa01c577f2c2018-08-31 09:22:23 +01001057 layerName.c_str());
1058 }
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001059 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01001060
Sadik Armagand109a4d2020-07-28 10:42:13 +01001061 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
jimfly01c25411c2018-11-14 17:47:22 +00001062 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001063
1064 // register the input connection slots for the layer, connections are made after all layers have been created
1065 // only the tensors for the inputs are relevant, exclude the const tensors
1066 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +00001067 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
telsoa01c577f2c2018-08-31 09:22:23 +01001068
jimfly01c25411c2018-11-14 17:47:22 +00001069 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +01001070 // register the output connection slots for the layer, connections are made after all layers have been created
1071 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1072 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1073}
1074
Kevin May7d96b162021-02-03 17:38:41 +00001075void TfLiteParserImpl::ParseDequantize(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsed66d142019-12-06 09:55:55 +00001076{
1077 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1078
1079 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1080 CHECK_VALID_SIZE(inputs.size(), 1);
1081
1082 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1083 CHECK_VALID_SIZE(outputs.size(), 1);
1084
James Ward58dec6b2020-09-11 17:32:44 +01001085 auto layerName = fmt::format("Dequantize:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsed66d142019-12-06 09:55:55 +00001086
1087 IConnectableLayer* layer = m_Network->AddDequantizeLayer(layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001088 ARMNN_ASSERT(layer != nullptr);
Finn Williamsed66d142019-12-06 09:55:55 +00001089
Sadik Armagand109a4d2020-07-28 10:42:13 +01001090 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Finn Williamsed66d142019-12-06 09:55:55 +00001091 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1092
1093 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1094 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1095
1096 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1097 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1098}
1099
Kevin May7d96b162021-02-03 17:38:41 +00001100void TfLiteParserImpl::ParseTranspose(size_t subgraphIndex, size_t operatorIndex)
Keith Davis4cd29a02019-09-09 14:49:20 +01001101{
1102 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1103
1104 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Kevin May85d92602019-09-27 17:21:06 +01001105 CHECK_VALID_SIZE(inputs.size(), 1, 2);
Keith Davis4cd29a02019-09-09 14:49:20 +01001106
1107 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1108 CHECK_VALID_SIZE(outputs.size(), 1);
1109
James Ward58dec6b2020-09-11 17:32:44 +01001110 auto layerName = fmt::format("Transpose:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly08759e22020-03-02 11:41:31 +00001111 TransposeDescriptor desc;
Keith Davis4cd29a02019-09-09 14:49:20 +01001112
josh minorba424d22019-11-13 10:55:17 -06001113 if (inputs.size() == 2)
Kevin May85d92602019-09-27 17:21:06 +01001114 {
1115 armnn::TensorInfo permuteTensorInfo = ToTensorInfo(inputs[1]);
1116 BufferRawPtr permuteBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
josh minorba424d22019-11-13 10:55:17 -06001117 auto numPermVecElements = permuteTensorInfo.GetNumElements();
1118 std::vector<unsigned int> permuteShape(numPermVecElements);
Kevin May85d92602019-09-27 17:21:06 +01001119 ::memcpy(permuteShape.data(), permuteBufferPtr->data.data(), permuteTensorInfo.GetNumBytes());
Mike Kelly08759e22020-03-02 11:41:31 +00001120 PermutationVector permutationVector(permuteShape.data(), permuteTensorInfo.GetNumElements());
Kevin May85d92602019-09-27 17:21:06 +01001121
Mike Kelly08759e22020-03-02 11:41:31 +00001122 desc = TransposeDescriptor(permutationVector);
Kevin May85d92602019-09-27 17:21:06 +01001123 }
1124
James Conroy05102392020-06-24 15:39:55 +01001125 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001126 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001127 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Keith Davis4cd29a02019-09-09 14:49:20 +01001128
James Conroy05102392020-06-24 15:39:55 +01001129 IConnectableLayer* layer = m_Network->AddTransposeLayer(desc, layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001130 ARMNN_ASSERT(layer != nullptr);
Keith Davis4cd29a02019-09-09 14:49:20 +01001131 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1132
1133 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1134 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1135
1136 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1137 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1138}
1139
Kevin May7d96b162021-02-03 17:38:41 +00001140void TfLiteParserImpl::ParseTransposeConv(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001141{
1142 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1143
1144 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1145 const auto * options = operatorPtr->builtin_options.AsTransposeConvOptions();
1146
1147 TransposeConvolution2dDescriptor desc;
1148 desc.m_BiasEnabled = false;
1149 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1150 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1151 desc.m_DataLayout = armnn::DataLayout::NHWC;
1152
1153 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
David Monahan61683802021-01-12 09:11:07 +00001154 if (inputs.size() == 4)
1155 {
1156 desc.m_BiasEnabled = true;
1157 }
1158 else
1159 {
1160 CHECK_VALID_SIZE(inputs.size(), 3);
1161 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001162
1163 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1164 CHECK_VALID_SIZE(outputs.size(), 1);
1165
Colm Donelan0ad3ef12020-07-03 15:54:28 +01001166 if (inputs[0])
1167 {
1168 armnn::TensorInfo tensorInfo = ToTensorInfo(inputs[0]);
1169 std::vector<int> output_shape(tensorInfo.GetNumElements());
1170 if (tensorInfo.GetDataType() == DataType::Signed32)
1171 {
1172 ::memcpy(output_shape.data(), GetBuffer(m_Model, inputs[0]->buffer)->data.data(), tensorInfo.GetNumBytes());
1173 }
1174 if (tensorInfo.GetDataType() == DataType::QAsymmU8)
1175 {
1176 for(unsigned int i=0; i < tensorInfo.GetNumElements(); i++)
1177 {
1178 output_shape[i] = GetBuffer(m_Model, inputs[0]->buffer)->data.data()[i];
1179 }
1180 }
1181 // Change from signed to unsigned int to store in TransposeConvolution2dDescriptor.
1182 for (int dimension : output_shape)
1183 {
1184 desc.m_OutputShape.push_back(static_cast<unsigned int>(dimension));
1185 }
1186 desc.m_OutputShapeEnabled = true;
1187 }
Matthew Jacksonccb25ea2019-08-20 17:18:33 +01001188 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[2]);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001189 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
1190
1191 // TfLite uses NHWC tensors
1192 const unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1193 const unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1194
1195 const unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1196 const unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1197
1198 CalcPadding(inputHeight,
1199 filterHeight,
1200 desc.m_StrideY,
1201 1, // DilationY
1202 desc.m_PadTop,
1203 desc.m_PadBottom,
1204 options->padding);
1205
1206 CalcPadding(inputWidth,
1207 filterWidth,
1208 desc.m_StrideX,
1209 1, // DilationX
1210 desc.m_PadLeft,
1211 desc.m_PadRight,
1212 options->padding);
1213
Finn Williamsd4fa5452021-03-01 12:31:41 +00001214 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001215
1216 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01001217 auto layerName = fmt::format("TransposeConv:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001218
David Monahan61683802021-01-12 09:11:07 +00001219 if (desc.m_BiasEnabled)
1220 {
1221 auto biasTensorInfo = ToTensorInfo(inputs[3]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00001222 auto biasConstTensor = CreateConstTensorNonPermuted(inputs[3], biasTensorInfo);
David Monahan61683802021-01-12 09:11:07 +00001223 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +00001224 filterTensorAndData,
1225 biasConstTensor,
David Monahan61683802021-01-12 09:11:07 +00001226 layerName.c_str());
1227 }
1228 else
1229 {
1230 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +00001231 filterTensorAndData,
David Monahan61683802021-01-12 09:11:07 +00001232 EmptyOptional(),
1233 layerName.c_str());
1234 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001235
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001236 ARMNN_ASSERT(layer != nullptr);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001237
Sadik Armagand109a4d2020-07-28 10:42:13 +01001238 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001239 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1240
1241 // only the tensors for the inputs are relevant, exclude the const (filter) tensor
1242 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Matthew Jacksonccb25ea2019-08-20 17:18:33 +01001243 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[2]});
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001244
1245 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1246 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1247}
1248
Kevin May7d96b162021-02-03 17:38:41 +00001249void TfLiteParserImpl::ParseAveragePool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001250{
1251 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Average);
1252}
1253
Kevin May7d96b162021-02-03 17:38:41 +00001254void TfLiteParserImpl::ParseBatchToSpaceND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001255{
1256 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1257
1258 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1259 CHECK_VALID_SIZE(inputs.size(), 3);
1260
1261 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1262 CHECK_VALID_SIZE(outputs.size(), 1);
1263
1264 armnn::TensorInfo blockShapeTensorInfo = ToTensorInfo(inputs[1]);
1265 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1266
1267 armnn::TensorInfo cropsTensorInfo = ToTensorInfo(inputs[2]);
1268 BufferRawPtr cropsBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1269
1270 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1271 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1272
1273 std::vector<unsigned int> cropsVector(cropsTensorInfo.GetNumElements());
1274 ::memcpy(cropsVector.data(), cropsBufferPtr->data.data(), cropsTensorInfo.GetNumBytes());
1275
1276 size_t step = 2;
1277 std::vector<std::pair<unsigned int, unsigned int>> crops;
1278 for (unsigned int i = 0; i < cropsTensorInfo.GetNumElements() / step; ++i)
1279 {
1280 crops.emplace_back(cropsVector[i * step], cropsVector[i * step + 1]);
1281 }
1282
1283 armnn::BatchToSpaceNdDescriptor desc;
1284 desc.m_BlockShape = blockShape;
1285 desc.m_Crops = crops;
1286 desc.m_DataLayout = armnn::DataLayout::NHWC;
1287
James Ward58dec6b2020-09-11 17:32:44 +01001288 auto layerName = fmt::format("BatchToSpaceND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001289
James Conroy05102392020-06-24 15:39:55 +01001290 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001291 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001292 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1293
1294 IConnectableLayer* layer = m_Network->AddBatchToSpaceNdLayer(desc, layerName.c_str());
1295 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001296 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1297
1298 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1299 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1300
1301 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1302 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1303}
1304
Kevin May7d96b162021-02-03 17:38:41 +00001305void TfLiteParserImpl::ParseL2Normalization(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson28c94572019-07-18 10:47:03 +01001306{
1307 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1308
1309 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1310 CHECK_VALID_SIZE(inputs.size(), 1);
1311
1312 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1313 CHECK_VALID_SIZE(outputs.size(), 1);
1314
1315 L2NormalizationDescriptor desc;
1316 desc.m_DataLayout = armnn::DataLayout::NHWC;
James Ward58dec6b2020-09-11 17:32:44 +01001317 auto layerName = fmt::format("L2Normalization:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson28c94572019-07-18 10:47:03 +01001318 IConnectableLayer* layer = m_Network->AddL2NormalizationLayer(desc, layerName.c_str());
1319
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001320 ARMNN_ASSERT(layer != nullptr);
Matthew Jackson28c94572019-07-18 10:47:03 +01001321
Sadik Armagand109a4d2020-07-28 10:42:13 +01001322 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jackson28c94572019-07-18 10:47:03 +01001323 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1324
1325 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1326 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1327
1328 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1329 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1330}
1331
Kevin May7d96b162021-02-03 17:38:41 +00001332void TfLiteParserImpl::ParseMaxPool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001333{
1334 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Max);
1335}
1336
Kevin May7d96b162021-02-03 17:38:41 +00001337void TfLiteParserImpl::ParseMaximum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001338{
1339 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1340
1341 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1342 CHECK_VALID_SIZE(inputs.size(), 2);
1343
1344 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1345 CHECK_VALID_SIZE(outputs.size(), 1);
1346
James Ward58dec6b2020-09-11 17:32:44 +01001347 auto layerName = fmt::format("Maximum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01001348
1349 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1350 TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1351 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001352
Sadik Armagand109a4d2020-07-28 10:42:13 +01001353 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001354 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1355
1356 IConnectableLayer* layer = m_Network->AddMaximumLayer(layerName.c_str());
1357 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001358 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1359
1360 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001361 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001362
1363 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1364 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1365}
1366
Kevin May7d96b162021-02-03 17:38:41 +00001367void TfLiteParserImpl::ParseMinimum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001368{
1369 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1370
1371 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1372 CHECK_VALID_SIZE(inputs.size(), 2);
1373
1374 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1375 CHECK_VALID_SIZE(outputs.size(), 1);
1376
James Ward58dec6b2020-09-11 17:32:44 +01001377 auto layerName = fmt::format("Minimum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01001378
1379 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1380 TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1381 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001382
Sadik Armagand109a4d2020-07-28 10:42:13 +01001383 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001384 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1385
1386 IConnectableLayer* layer = m_Network->AddMinimumLayer(layerName.c_str());
1387 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001388 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1389
1390 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001391 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001392
1393 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1394 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1395}
1396
Kevin May7d96b162021-02-03 17:38:41 +00001397void TfLiteParserImpl::ParsePool(size_t subgraphIndex,
1398 size_t operatorIndex,
1399 PoolingAlgorithm algorithm)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001400{
1401 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1402
1403 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1404 const auto * options = operatorPtr->builtin_options.AsPool2DOptions();
1405
1406 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1407
1408 std::string layerName;
1409
1410 switch (algorithm)
1411 {
1412 case PoolingAlgorithm::Average:
1413 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01001414 fmt::format("AveragePool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001415 break;
1416 case PoolingAlgorithm::Max:
1417 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01001418 fmt::format("MaxPool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001419 break;
1420 default:
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001421 ARMNN_ASSERT_MSG(false, "Unsupported Pooling Algorithm");
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001422 }
1423
1424 Pooling2dDescriptor desc;
1425
1426 desc.m_PoolType = algorithm;
1427 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1428 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1429 desc.m_PoolWidth = CHECKED_NON_NEGATIVE(options->filter_width);
1430 desc.m_PoolHeight = CHECKED_NON_NEGATIVE(options->filter_height);
1431 desc.m_PaddingMethod = PaddingMethod::Exclude;
1432 desc.m_OutputShapeRounding = OutputShapeRounding::Floor;
jimfly01c25411c2018-11-14 17:47:22 +00001433 desc.m_DataLayout = armnn::DataLayout::NHWC;
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001434
1435 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1436 CHECK_VALID_SIZE(inputs.size(), 1);
1437 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1438
1439 // assuming input is NHWC
1440 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1441 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1442
Pablo Tellof0bd6832019-04-26 17:58:13 +01001443 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, 1u,
1444 desc.m_PadTop, desc.m_PadBottom, options->padding);
1445 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, 1u,
1446 desc.m_PadLeft, desc.m_PadRight, options->padding);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001447
1448 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1449 CHECK_VALID_SIZE(outputs.size(), 1);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001450
Sadik Armagand109a4d2020-07-28 10:42:13 +01001451 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001452 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1453
1454 IConnectableLayer* layer = m_Network->AddPooling2dLayer(desc, layerName.c_str());
1455 ARMNN_ASSERT(layer != nullptr);
jimfly01c25411c2018-11-14 17:47:22 +00001456 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001457
1458 // register the input connection slots for the layer, connections are made after all layers have been created
1459 // only the tensors for the inputs are relevant, exclude the const tensors
1460 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +00001461 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001462
jimfly01c25411c2018-11-14 17:47:22 +00001463 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001464 // register the output connection slots for the layer, connections are made after all layers have been created
1465 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1466 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1467}
1468
Kevin May7d96b162021-02-03 17:38:41 +00001469void TfLiteParserImpl::ParseSlice(size_t subgraphIndex, size_t operatorIndex)
josh minorba424d22019-11-13 10:55:17 -06001470{
1471 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1472
1473 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1474 CHECK_VALID_SIZE(inputs.size(), 3);
1475 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1476 CHECK_VALID_SIZE(outputs.size(), 1);
1477
1478 SliceDescriptor desc;
1479
1480 // set begin tensor info for slice descriptor
1481 armnn::TensorInfo beginTensorInfo = ToTensorInfo(inputs[1]);
1482 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1483
1484 std::vector<unsigned int> begin(beginTensorInfo.GetNumElements());
1485 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
1486
1487 // set size tensor info for slice descriptor
1488 armnn::TensorInfo sizeTensorInfo = ToTensorInfo(inputs[2]);
1489 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1490
1491 std::vector<unsigned int> size(sizeTensorInfo.GetNumElements());
1492 ::memcpy(size.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
1493 desc = SliceDescriptor(begin, size);
1494
James Ward58dec6b2020-09-11 17:32:44 +01001495 auto layerName = fmt::format("Slice:{}:{}", subgraphIndex, operatorIndex);
josh minorba424d22019-11-13 10:55:17 -06001496
James Conroy05102392020-06-24 15:39:55 +01001497 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001498 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001499 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1500
1501 IConnectableLayer* const layer = m_Network->AddSliceLayer(desc, layerName.c_str());
josh minorba424d22019-11-13 10:55:17 -06001502 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1503
1504 // register the input connection slots for the layer, connections are made after all layers have been created
1505 // only the tensors for the inputs are relevant, exclude the const tensors
1506 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1507 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1508
1509 // register the output connection slots for the layer, connections are made after all layers have been created
1510 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1511 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1512}
1513
Kevin May7d96b162021-02-03 17:38:41 +00001514void TfLiteParserImpl::ParseSoftmax(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001515{
1516 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1517 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1518 const auto * options = operatorPtr->builtin_options.AsSoftmaxOptions();
1519
1520 SoftmaxDescriptor desc;
1521 desc.m_Beta = options->beta;
1522
1523 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1524 CHECK_VALID_SIZE(inputs.size(), 1);
1525 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1526 CHECK_VALID_SIZE(outputs.size(), 1);
1527
James Ward58dec6b2020-09-11 17:32:44 +01001528 auto layerName = fmt::format("Softmax:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001529 IConnectableLayer* const layer = m_Network->AddSoftmaxLayer(desc, layerName.c_str());
1530
Sadik Armagand109a4d2020-07-28 10:42:13 +01001531 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
telsoa01c577f2c2018-08-31 09:22:23 +01001532 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1533
1534 // register the input connection slots for the layer, connections are made after all layers have been created
1535 // only the tensors for the inputs are relevant, exclude the const tensors
1536 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1537 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1538
1539 // register the output connection slots for the layer, connections are made after all layers have been created
1540 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1541 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1542}
1543
Kevin May7d96b162021-02-03 17:38:41 +00001544void TfLiteParserImpl::ParseSpaceToBatchND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001545{
1546 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1547
1548 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1549 CHECK_VALID_SIZE(inputs.size(), 3);
1550
1551 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1552 CHECK_VALID_SIZE(outputs.size(), 1);
1553
1554 armnn::TensorInfo blockShapeTensorInfo = ToTensorInfo(inputs[1]);
1555 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1556
1557 armnn::TensorInfo padListTensorInfo = ToTensorInfo(inputs[2]);
1558 BufferRawPtr padListBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1559
1560 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1561 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1562
1563 std::vector<unsigned int> padListVector(padListTensorInfo.GetNumElements());
1564 ::memcpy(padListVector.data(), padListBufferPtr->data.data(), padListTensorInfo.GetNumBytes());
1565
1566 size_t step = 2;
1567 std::vector<std::pair<unsigned int, unsigned int>> padList;
1568 for (unsigned int i = 0; i < padListTensorInfo.GetNumElements() / step; ++i)
1569 {
1570 padList.emplace_back(padListVector[i * step], padListVector[i * step + 1]);
1571 }
1572
1573 armnn::SpaceToBatchNdDescriptor desc;
1574 desc.m_BlockShape = blockShape;
1575 desc.m_PadList = padList;
1576 desc.m_DataLayout = armnn::DataLayout::NHWC;
1577
James Ward58dec6b2020-09-11 17:32:44 +01001578 auto layerName = fmt::format("SpaceToBatchND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001579
James Conroy05102392020-06-24 15:39:55 +01001580 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001581 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001582 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1583
1584 IConnectableLayer* layer = m_Network->AddSpaceToBatchNdLayer(desc, layerName.c_str());
1585 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001586 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1587
1588 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1589 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1590
1591 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1592 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1593}
1594
Kevin May7d96b162021-02-03 17:38:41 +00001595armnn::TensorInfo TfLiteParserImpl::OutputShapeOfSqueeze(const std::vector<uint32_t> & squeezeDimsIn,
1596 const armnn::TensorInfo & inputTensorInfo)
telsoa01c577f2c2018-08-31 09:22:23 +01001597{
1598 CHECK_VALID_SIZE(squeezeDimsIn.size(), 0, 1, 2, 3, 4);
1599 std::vector<uint32_t> squeezeDims = squeezeDimsIn;
1600 static const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
1601
1602 if (inputTensorInfo.GetNumDimensions() > 4)
1603 {
1604 std::stringstream ss;
1605 ss << "Input tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
1606 << " shape:" << inputTensorInfo.GetShape() << " "
1607 << CHECK_LOCATION().AsString();
1608 throw ParseException(ss.str());
1609 }
1610
1611 if (squeezeDims.empty())
1612 {
1613 squeezeDims.assign(dimensionSequence,
1614 dimensionSequence+inputTensorInfo.GetNumDimensions());
1615 }
1616
1617 std::vector<uint32_t> outputDims;
1618 for(unsigned int i = 0; i < inputTensorInfo.GetNumDimensions(); i++)
1619 {
1620 bool skipSqueeze = (std::find(squeezeDims.begin(), squeezeDims.end(), i) == squeezeDims.end());
1621 auto currentDimension = inputTensorInfo.GetShape()[i];
1622 if (skipSqueeze || currentDimension != 1)
1623 {
1624 outputDims.push_back(currentDimension);
1625 }
1626 }
1627
1628 if (outputDims.size() > 4)
1629 {
1630 std::stringstream ss;
1631 ss << "Output tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
1632 << " shape:" << inputTensorInfo.GetShape() << " "
1633 << CHECK_LOCATION().AsString();
1634 throw ParseException(ss.str());
1635 }
1636
1637 TensorShape outShape = TensorShape(static_cast<unsigned int>(outputDims.size()),
1638 outputDims.data());
1639
1640 // we need to preserve the tensor type and the quantization data as well
1641 TensorInfo outTensorInfo = inputTensorInfo;
1642 outTensorInfo.SetShape(outShape);
1643
1644 return outTensorInfo;
1645}
1646
Kevin May7d96b162021-02-03 17:38:41 +00001647void TfLiteParserImpl::ParseSqueeze(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001648{
1649 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1650
1651 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1652 CHECK_VALID_SIZE(inputs.size(), 1);
1653
1654 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1655 CHECK_VALID_SIZE(outputs.size(), 1);
1656
1657 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1658 const auto * options = operatorPtr->builtin_options.AsSqueezeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01001659 auto layerName = fmt::format("Squeeze:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001660
1661 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1662 armnn::TensorInfo outputTensorInfo =
Kevin May7d96b162021-02-03 17:38:41 +00001663 TfLiteParserImpl::OutputShapeOfSqueeze(AsUnsignedVector(options->squeeze_dims),
telsoa01c577f2c2018-08-31 09:22:23 +01001664 inputTensorInfo);
James Conroy05102392020-06-24 15:39:55 +01001665 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
telsoa01c577f2c2018-08-31 09:22:23 +01001666
1667 ReshapeDescriptor reshapeDesc;
1668 reshapeDesc.m_TargetShape = outputTensorInfo.GetShape();
1669
telsoa01c577f2c2018-08-31 09:22:23 +01001670 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001671 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01001672 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1673
1674 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1675 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1676
1677 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1678 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1679}
1680
Kevin May7d96b162021-02-03 17:38:41 +00001681void TfLiteParserImpl::ParseStridedSlice(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves451d95b2019-02-12 22:59:22 -02001682{
1683 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1684
1685 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1686 CHECK_VALID_SIZE(inputs.size(), 4);
1687
1688 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1689 CHECK_VALID_SIZE(outputs.size(), 1);
1690
1691 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1692 const auto * options = operatorPtr->builtin_options.AsStridedSliceOptions();
1693
1694 StridedSliceDescriptor desc;
1695 desc.m_BeginMask = options->begin_mask;
1696 desc.m_EllipsisMask = options->ellipsis_mask;
1697 desc.m_EndMask = options->end_mask;
1698 desc.m_NewAxisMask = options->new_axis_mask;
1699 desc.m_ShrinkAxisMask = options->shrink_axis_mask;
1700 desc.m_DataLayout = armnn::DataLayout::NHWC;
1701
1702 armnn::TensorInfo beginTensorInfo = ToTensorInfo(inputs[1]);
1703 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1704
1705 std::vector<int> begin(beginTensorInfo.GetNumElements());
1706 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
1707
1708 armnn::TensorInfo endTensorInfo = ToTensorInfo(inputs[2]);
1709 BufferRawPtr endBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1710
1711 std::vector<int> end(endTensorInfo.GetNumElements());
1712 ::memcpy(end.data(), endBufferPtr->data.data(), endTensorInfo.GetNumBytes());
1713
1714 armnn::TensorInfo strideTensorInfo = ToTensorInfo(inputs[3]);
1715 BufferRawPtr strideBufferPtr = GetBuffer(m_Model, inputs[3]->buffer);
1716
1717 std::vector<int> stride(strideTensorInfo.GetNumElements());
1718 ::memcpy(stride.data(), strideBufferPtr->data.data(), strideTensorInfo.GetNumBytes());
1719
1720 desc.m_Begin = begin;
1721 desc.m_End = end;
1722 desc.m_Stride = stride;
1723
James Ward58dec6b2020-09-11 17:32:44 +01001724 auto layerName = fmt::format("StridedSlice:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02001725 IConnectableLayer* layer = m_Network->AddStridedSliceLayer(desc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001726 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02001727
Sadik Armagand109a4d2020-07-28 10:42:13 +01001728 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02001729 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1730
1731 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1732 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1733
1734 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1735 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1736}
1737
Kevin May7d96b162021-02-03 17:38:41 +00001738void TfLiteParserImpl::ParseSub(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001739{
1740 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1741
1742 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1743 const auto * options = operatorPtr->builtin_options.AsSubOptions();
1744
1745 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1746 CHECK_VALID_SIZE(inputs.size(), 2);
1747
1748 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1749 CHECK_VALID_SIZE(outputs.size(), 1);
1750
1751 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1752 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1753
James Ward58dec6b2020-09-11 17:32:44 +01001754 auto layerName = fmt::format("Sub:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001755 IConnectableLayer* layer = m_Network->AddSubtractionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001756 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001757
Sadik Armagand109a4d2020-07-28 10:42:13 +01001758 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001759 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1760
1761 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001762 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001763
1764 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1765
1766 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1767 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1768}
1769
Kevin May7d96b162021-02-03 17:38:41 +00001770void TfLiteParserImpl::ParseDiv(size_t subgraphIndex, size_t operatorIndex)
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301771{
1772 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1773
1774 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1775 const auto * options = operatorPtr->builtin_options.AsDivOptions();
1776
1777 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1778 CHECK_VALID_SIZE(inputs.size(), 2);
1779
1780 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1781 CHECK_VALID_SIZE(outputs.size(), 1);
1782
1783 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1784 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1785
James Ward58dec6b2020-09-11 17:32:44 +01001786 auto layerName = fmt::format("Div:{}:{}", subgraphIndex, operatorIndex);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301787 IConnectableLayer* layer = m_Network->AddDivisionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001788 ARMNN_ASSERT(layer != nullptr);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301789
Sadik Armagand109a4d2020-07-28 10:42:13 +01001790 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301791 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1792
1793 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001794 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301795 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1796
1797 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1798 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1799}
1800
Kevin May7d96b162021-02-03 17:38:41 +00001801void TfLiteParserImpl::ParseAdd(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001802{
1803 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1804
1805 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1806 const auto * options = operatorPtr->builtin_options.AsAddOptions();
1807
1808 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1809 CHECK_VALID_SIZE(inputs.size(), 2);
1810
1811 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1812 CHECK_VALID_SIZE(outputs.size(), 1);
1813
Bruno Goncalves9c761a62018-12-27 14:20:35 -02001814 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1815 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1816
James Ward58dec6b2020-09-11 17:32:44 +01001817 auto layerName = fmt::format("Add:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001818 IConnectableLayer* layer = m_Network->AddAdditionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001819 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001820
Sadik Armagand109a4d2020-07-28 10:42:13 +01001821 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001822 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1823
1824 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001825 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001826 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1827
1828 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1829 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1830}
1831
Kevin May7d96b162021-02-03 17:38:41 +00001832void TfLiteParserImpl::ParseMul(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001833{
1834 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1835
1836 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1837 const auto * options = operatorPtr->builtin_options.AsMulOptions();
1838
1839 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1840 CHECK_VALID_SIZE(inputs.size(), 2);
1841
1842 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1843 CHECK_VALID_SIZE(outputs.size(), 1);
1844
Bruno Goncalves9c761a62018-12-27 14:20:35 -02001845 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1846 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1847
James Ward58dec6b2020-09-11 17:32:44 +01001848 auto layerName = fmt::format("Mul:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001849 IConnectableLayer* layer = m_Network->AddMultiplicationLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001850 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001851
Sadik Armagand109a4d2020-07-28 10:42:13 +01001852 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001853 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1854
1855 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001856 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001857 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1858
1859 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1860 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1861}
1862
Kevin May7d96b162021-02-03 17:38:41 +00001863void TfLiteParserImpl::ParseMean(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves2235cee2018-12-19 12:51:45 -02001864{
1865 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1866
1867 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1868
1869 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1870 CHECK_VALID_SIZE(outputs.size(), 1);
1871
1872 armnn::TensorInfo dimTensorInfo = ToTensorInfo(inputs[1]);
1873 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1874
1875 armnn::MeanDescriptor desc;
1876 std::vector<unsigned int> axis(dimTensorInfo.GetNumElements());
1877 ::memcpy(axis.data(), bufferPtr->data.data(), dimTensorInfo.GetNumBytes());
1878 desc.m_Axis = axis;
1879
1880 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001881 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02001882
1883 desc.m_KeepDims =
1884 inputTensorInfo.GetNumDimensions() == outputTensorInfo.GetNumDimensions() ?
1885 true : false;
1886
James Ward58dec6b2020-09-11 17:32:44 +01001887 auto layerName = fmt::format("Mean:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02001888 IConnectableLayer* layer = m_Network->AddMeanLayer(desc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001889 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02001890
1891 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1892
1893 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1894 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1895
1896 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1897 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1898}
1899
Kevin May7d96b162021-02-03 17:38:41 +00001900void TfLiteParserImpl::ParsePad(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001901{
1902 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1903
Kevin May7d96b162021-02-03 17:38:41 +00001904 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001905
Kevin May7d96b162021-02-03 17:38:41 +00001906 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001907 CHECK_VALID_SIZE(outputs.size(), 1);
1908
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00001909 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1910
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001911 armnn::TensorInfo padTensorInfo = ToTensorInfo(inputs[1]);
1912 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1913
1914 std::vector<unsigned int> padBuffer(padTensorInfo.GetNumElements());
1915 ::memcpy(padBuffer.data(), bufferPtr->data.data(), padTensorInfo.GetNumBytes());
1916
1917 size_t step = 2;
1918 armnn::PadDescriptor desc;
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00001919 if (inputTensorInfo.IsQuantized())
1920 {
1921 desc.m_PadValue = static_cast<float>(inputTensorInfo.GetQuantizationOffset());
1922 }
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001923 for (unsigned int i = 0; i < padTensorInfo.GetNumElements() / step; ++i)
1924 {
1925 desc.m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
1926 }
1927
James Ward58dec6b2020-09-11 17:32:44 +01001928 auto layerName = fmt::format("Pad:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001929 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001930
1931 IConnectableLayer* layer = m_Network->AddPadLayer(desc, layerName.c_str());
1932 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001933 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1934
1935 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1936 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1937
1938 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1939 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1940}
1941
Kevin May7d96b162021-02-03 17:38:41 +00001942void TfLiteParserImpl::ParseQuantize(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan66dedc72019-12-10 16:32:07 +00001943{
1944 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1945
1946 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1947 CHECK_VALID_SIZE(inputs.size(), 1);
1948
1949 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1950 CHECK_VALID_SIZE(outputs.size(), 1);
1951
James Ward58dec6b2020-09-11 17:32:44 +01001952 auto layerName = fmt::format("Quantize:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan66dedc72019-12-10 16:32:07 +00001953
1954 IConnectableLayer* layer = m_Network->AddQuantizeLayer(layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001955 ARMNN_ASSERT(layer != nullptr);
Sadik Armagan66dedc72019-12-10 16:32:07 +00001956
Sadik Armagand109a4d2020-07-28 10:42:13 +01001957 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan66dedc72019-12-10 16:32:07 +00001958 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1959
1960 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1961 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1962
1963 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1964 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1965}
Finn Williamsc42c3842019-01-22 14:18:11 +00001966
Kevin May7d96b162021-02-03 17:38:41 +00001967void TfLiteParserImpl::ParseRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01001968{
Finn Williamsc42c3842019-01-22 14:18:11 +00001969 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::ReLu);
Sadik Armagan58f39192018-09-17 14:14:39 +01001970}
1971
Kevin May7d96b162021-02-03 17:38:41 +00001972void TfLiteParserImpl::ParseRelu6(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01001973{
Finn Williamsc42c3842019-01-22 14:18:11 +00001974 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::BoundedReLu);
1975}
Sadik Armagan58f39192018-09-17 14:14:39 +01001976
Kevin May7d96b162021-02-03 17:38:41 +00001977void TfLiteParserImpl::ParseLeakyRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan12239e72020-05-27 11:06:17 +01001978{
Jan Eilers2f746b32020-07-28 14:00:06 +01001979 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::LeakyReLu);
Sadik Armagan12239e72020-05-27 11:06:17 +01001980}
1981
Kevin May7d96b162021-02-03 17:38:41 +00001982void TfLiteParserImpl::ParseLogistic(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsc42c3842019-01-22 14:18:11 +00001983{
1984 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::Sigmoid);
1985}
1986
Kevin May7d96b162021-02-03 17:38:41 +00001987void TfLiteParserImpl::ParseTanH(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd99851762019-04-09 09:37:38 +01001988{
1989 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::TanH);
1990}
1991
Kevin May7d96b162021-02-03 17:38:41 +00001992void TfLiteParserImpl::ParseElu(size_t subgraphIndex, size_t operatorIndex)
Matthew Sloyan7515d072020-12-16 12:50:01 +00001993{
1994 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::Elu);
1995}
1996
Kevin May7d96b162021-02-03 17:38:41 +00001997void TfLiteParserImpl::ParseHardSwish(size_t subgraphIndex, size_t operatorIndex)
Jan Eilers2f746b32020-07-28 14:00:06 +01001998{
1999 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::HardSwish);
2000}
Finn Williamsc42c3842019-01-22 14:18:11 +00002001
Kevin May7d96b162021-02-03 17:38:41 +00002002void TfLiteParserImpl::ParseActivation(size_t subgraphIndex, size_t operatorIndex, ActivationFunction activationType)
Finn Williamsc42c3842019-01-22 14:18:11 +00002003{
2004 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan58f39192018-09-17 14:14:39 +01002005 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Jan Eilers8eb25602020-03-09 12:13:48 +00002006 IgnoreUnused(operatorPtr);
Sadik Armagan58f39192018-09-17 14:14:39 +01002007
2008 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2009 CHECK_VALID_SIZE(inputs.size(), 1);
2010
2011 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2012 CHECK_VALID_SIZE(outputs.size(), 1);
2013
James Ward58dec6b2020-09-11 17:32:44 +01002014 auto layerName = fmt::format("Activation:");
Sadik Armagan58f39192018-09-17 14:14:39 +01002015 ActivationDescriptor activationDesc;
Finn Williamsc42c3842019-01-22 14:18:11 +00002016 activationDesc.m_Function = activationType;
2017
2018 switch (activationType)
2019 {
2020 case ActivationFunction::ReLu:
2021 {
James Ward58dec6b2020-09-11 17:32:44 +01002022 layerName += fmt::format("RELU:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002023 break;
2024 }
2025 case ActivationFunction::BoundedReLu:
2026 {
James Ward58dec6b2020-09-11 17:32:44 +01002027 layerName += fmt::format("RELU6:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002028 activationDesc.m_A = 6.0f;
2029 activationDesc.m_B = 0.0f;
2030 break;
2031 }
2032 case ActivationFunction::Sigmoid:
2033 {
James Ward58dec6b2020-09-11 17:32:44 +01002034 layerName += fmt::format("SIGMOID:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002035 break;
2036 }
Nina Drozd99851762019-04-09 09:37:38 +01002037 case ActivationFunction::TanH:
2038 {
James Ward58dec6b2020-09-11 17:32:44 +01002039 layerName += fmt::format("TANH:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd99851762019-04-09 09:37:38 +01002040 activationDesc.m_A = 1.0f;
2041 activationDesc.m_B = 1.0f;
2042 break;
2043 }
Sadik Armagan12239e72020-05-27 11:06:17 +01002044 case ActivationFunction::LeakyReLu:
2045 {
James Ward58dec6b2020-09-11 17:32:44 +01002046 layerName += fmt::format("LEAKYRELU:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan12239e72020-05-27 11:06:17 +01002047 const auto * options = operatorPtr->builtin_options.AsLeakyReluOptions();
2048 activationDesc.m_A = options->alpha;
2049 break;
2050 }
Matthew Sloyan7515d072020-12-16 12:50:01 +00002051 case ActivationFunction::Elu:
2052 {
2053 layerName += fmt::format("ELU:{}:{}", subgraphIndex, operatorIndex);
2054 activationDesc.m_A = 1.0f;
2055 break;
2056 }
Jan Eilers2f746b32020-07-28 14:00:06 +01002057 case ActivationFunction::HardSwish:
Matthew Sloyan7515d072020-12-16 12:50:01 +00002058 {
James Ward58dec6b2020-09-11 17:32:44 +01002059 layerName += fmt::format("HARDSWISH:{}:{}", subgraphIndex, operatorIndex);
Jan Eilers2f746b32020-07-28 14:00:06 +01002060 break;
Matthew Sloyan7515d072020-12-16 12:50:01 +00002061 }
Finn Williamsc42c3842019-01-22 14:18:11 +00002062 default:
2063 {
2064 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002065 fmt::format("Unexpected ActivationFunction[{}] when creating layerName {} ",
2066 static_cast<int>(activationType), CHECK_LOCATION().AsString()));
Finn Williamsc42c3842019-01-22 14:18:11 +00002067 }
2068 }
2069
2070 IConnectableLayer* const layer = m_Network->AddActivationLayer(activationDesc, layerName.c_str());
Sadik Armagan58f39192018-09-17 14:14:39 +01002071
Sadik Armagand109a4d2020-07-28 10:42:13 +01002072 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan58f39192018-09-17 14:14:39 +01002073 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2074
2075 // register the input connection slots for the layer, connections are made after all layers have been created
2076 // only the tensors for the inputs are relevant, exclude the const tensors
2077 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2078 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2079
2080 // register the output connection slots for the layer, connections are made after all layers have been created
2081 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2082 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2083}
Kevin May7d96b162021-02-03 17:38:41 +00002084armnn::TensorInfo TfLiteParserImpl::OutputShapeOfReshape(const armnn::TensorInfo & inputTensorInfo,
2085 const std::vector<int32_t> & targetDimsIn)
Sadikb94967b2018-09-19 15:30:00 +01002086{
2087 std::vector<unsigned int> outputDims(targetDimsIn.begin(), targetDimsIn.end());
2088 const auto stretchDim = std::find(targetDimsIn.begin(), targetDimsIn.end(), -1);
2089
2090 if (stretchDim != targetDimsIn.end())
2091 {
2092 if (std::find(std::next(stretchDim), targetDimsIn.end(), -1) != targetDimsIn.end())
2093 {
2094 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002095 fmt::format("At most one component of shape can be -1 {}", CHECK_LOCATION().AsString()));
Sadikb94967b2018-09-19 15:30:00 +01002096 }
2097
2098 auto targetNumElements =
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002099 armnn::numeric_cast<unsigned int>(
Sadikb94967b2018-09-19 15:30:00 +01002100 std::accumulate(targetDimsIn.begin(), targetDimsIn.end(), -1, std::multiplies<int32_t>()));
2101
2102 auto stretchIndex = static_cast<size_t>(std::distance(targetDimsIn.begin(), stretchDim));
2103 outputDims[stretchIndex] = inputTensorInfo.GetNumElements() / targetNumElements;
2104 }
2105
2106 TensorShape outputShape = TensorShape(static_cast<unsigned int>(outputDims.size()), outputDims.data());
2107
2108 TensorInfo reshapeInfo = inputTensorInfo;
2109 reshapeInfo.SetShape(outputShape);
2110
2111 return reshapeInfo;
2112}
2113
Kevin May7d96b162021-02-03 17:38:41 +00002114void TfLiteParserImpl::ParseReshape(size_t subgraphIndex, size_t operatorIndex)
Sadikb94967b2018-09-19 15:30:00 +01002115{
2116 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2117
2118 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01002119
2120 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2121 CHECK_VALID_SIZE(outputs.size(), 1);
2122
2123 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2124 const auto * options = operatorPtr->builtin_options.AsReshapeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01002125 auto layerName = fmt::format("Reshape:{}:{}", subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01002126
2127 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
kevmay0171972a82018-12-17 14:28:03 +00002128 armnn::TensorInfo actualOutputTensorInfo = ToTensorInfo(outputs[0]);
James Conroy05102392020-06-24 15:39:55 +01002129 CheckMatchingQuantization(inputTensorInfo, actualOutputTensorInfo, layerName, "Input 0", "Output 0");
Derek Lambertic9e52792020-03-11 11:42:26 +00002130
Jan Eilersbac9b352020-07-13 13:40:24 +01002131 // Extracting new shape for the output
2132 // There are two ways it can be passed
2133 // * First is to define the target shape in the operator built-in options
2134 // * Second is to pass it as a second input tensor
Derek Lambertic9e52792020-03-11 11:42:26 +00002135 std::vector<int32_t> targetShape;
Jan Eilersbac9b352020-07-13 13:40:24 +01002136 bool targetShapeFound = false;
2137 // Check if built-in options were given
2138 if (options != nullptr)
Derek Lambertic9e52792020-03-11 11:42:26 +00002139 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002140 // make sure the parameter is given
2141 if (options->new_shape.empty() == false)
Derek Lambertic9e52792020-03-11 11:42:26 +00002142 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002143 targetShape = options->new_shape;
2144 targetShapeFound = true;
Derek Lambertif4a953f2020-03-17 14:25:57 +00002145 }
Derek Lambertic9e52792020-03-11 11:42:26 +00002146 }
Jan Eilersbac9b352020-07-13 13:40:24 +01002147
2148 // If there is no built-in option given or if the built-in new_shape parameter was empty
2149 if (!targetShapeFound)
Derek Lambertic9e52792020-03-11 11:42:26 +00002150 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002151 // Check for a second input tensor
2152 if (inputs.size() > 1 && inputs[1] != nullptr)
2153 {
2154 if (inputs[1]->is_variable)
2155 {
2156 ARMNN_THROW_PARSE_EXCEPTION( "Target shapes defined in non-const input tensors is not supported");
2157 }
2158
2159 if (inputs[1]->shape.size() != 1)
2160 {
2161 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not a 1D tensor");
2162 }
2163
2164 if (inputs[1]->type != tflite::TensorType_INT32)
2165 {
2166 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not an int32 type");
2167 }
2168
2169 // Extract target shape from input
2170 auto bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2171 auto values = reinterpret_cast<const int32_t*>(bufferPtr->data.data());
Sadik Armagan19a1c032021-01-20 12:17:00 +00002172 if (!values)
2173 {
2174 ARMNN_THROW_PARSE_EXCEPTION("Reshape operator target shape input buffer data is null");
2175 }
Jan Eilersbac9b352020-07-13 13:40:24 +01002176 for (int i=0; i < inputs[1]->shape[0]; ++i)
2177 {
2178 targetShape.push_back(values[i]);
2179 }
2180 }
2181 else
Derek Lambertic9e52792020-03-11 11:42:26 +00002182 {
2183 ARMNN_THROW_PARSE_EXCEPTION("Target shape not defined in reshape parameters or input tensor. "
2184 "At least one method required");
2185 }
Derek Lambertic9e52792020-03-11 11:42:26 +00002186 }
2187
kevmay0171972a82018-12-17 14:28:03 +00002188 armnn::TensorInfo reshapeOutputTensorInfo =
Kevin May7d96b162021-02-03 17:38:41 +00002189 TfLiteParserImpl::OutputShapeOfReshape(inputTensorInfo, targetShape);
Sadikb94967b2018-09-19 15:30:00 +01002190
kevmay0171972a82018-12-17 14:28:03 +00002191 // Check for valid input size and that reshape parameters equal output shape
Aron Virginas-Tar70672f62019-01-23 14:00:00 +00002192 const armnn::TensorShape& reshapeOutputTensorShape = reshapeOutputTensorInfo.GetShape();
2193 if (inputs.size() > 1 && !CheckShape(reshapeOutputTensorShape, outputs[0]->shape))
kevmay0171972a82018-12-17 14:28:03 +00002194 {
2195 std::stringstream ss;
2196 ss << "New shape defined in reshape parameters "
Aron Virginas-Tar70672f62019-01-23 14:00:00 +00002197 << reshapeOutputTensorShape
kevmay0171972a82018-12-17 14:28:03 +00002198 << " does not equal output shape "
2199 << actualOutputTensorInfo.GetShape()
2200 << ": "
2201 << CHECK_LOCATION().AsString();
2202 throw ParseException(ss.str());
2203 }
2204
Sadikb94967b2018-09-19 15:30:00 +01002205 ReshapeDescriptor reshapeDesc;
kevmay0171972a82018-12-17 14:28:03 +00002206 reshapeDesc.m_TargetShape = reshapeOutputTensorInfo.GetShape();
Sadikb94967b2018-09-19 15:30:00 +01002207
Sadikb94967b2018-09-19 15:30:00 +01002208 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002209 ARMNN_ASSERT(layer != nullptr);
kevmay0171972a82018-12-17 14:28:03 +00002210 layer->GetOutputSlot(0).SetTensorInfo(reshapeOutputTensorInfo);
Sadikb94967b2018-09-19 15:30:00 +01002211
2212 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2213 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2214
2215 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2216 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2217}
2218
Kevin May7d96b162021-02-03 17:38:41 +00002219void TfLiteParserImpl::ParseResizeBilinear(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002220{
Sadik Armagana3b31f02019-12-05 09:08:53 +00002221 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::Bilinear);
2222}
2223
Kevin May7d96b162021-02-03 17:38:41 +00002224void TfLiteParserImpl::ParseResizeNearestNeighbor(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagana3b31f02019-12-05 09:08:53 +00002225{
2226 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::NearestNeighbor);
2227}
2228
Kevin May7d96b162021-02-03 17:38:41 +00002229void TfLiteParserImpl::ParseResize(size_t subgraphIndex, size_t operatorIndex, ResizeMethod resizeMethod)
Sadik Armagana3b31f02019-12-05 09:08:53 +00002230{
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002231 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2232
2233 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2234 CHECK_VALID_SIZE(inputs.size(), 2);
2235
2236 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2237 CHECK_VALID_SIZE(outputs.size(), 1);
2238
2239 armnn::TensorInfo sizeTensorInfo = ToTensorInfo(inputs[1]);
2240
2241 // Data for the parsed tensor args (size) must be stored locally.
2242 std::vector<int32_t> sizeTensorData(sizeTensorInfo.GetNumElements());
2243
2244 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2245 ::memcpy(sizeTensorData.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
2246
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01002247 ResizeDescriptor desc;
Sadik Armagana3b31f02019-12-05 09:08:53 +00002248 desc.m_Method = resizeMethod;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002249 desc.m_TargetHeight = static_cast<uint32_t> (sizeTensorData[0]);
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01002250 desc.m_TargetWidth = static_cast<uint32_t> (sizeTensorData[1]);
2251 desc.m_DataLayout = armnn::DataLayout::NHWC;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002252
James Ward58dec6b2020-09-11 17:32:44 +01002253 auto layerName = fmt::format("Resize:");
Sadik Armagana3b31f02019-12-05 09:08:53 +00002254
2255 switch (resizeMethod)
2256 {
2257 case ResizeMethod::Bilinear:
2258 {
James Ward58dec6b2020-09-11 17:32:44 +01002259 layerName += fmt::format("BILINEAR:{}:{}", subgraphIndex, operatorIndex);
Sang-Hoon Park820eb142020-01-08 10:25:24 +00002260
2261 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2262 const auto * options = operatorPtr->builtin_options.AsResizeBilinearOptions();
2263
David Monahan4a0c9b92020-05-30 09:48:39 +01002264 desc.m_AlignCorners = options->align_corners;
Sadik Armagana3b31f02019-12-05 09:08:53 +00002265 break;
2266 }
2267 case ResizeMethod::NearestNeighbor:
2268 {
James Ward58dec6b2020-09-11 17:32:44 +01002269 layerName += fmt::format("NEARESTNEIGHBOR:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagana3b31f02019-12-05 09:08:53 +00002270 break;
2271 }
2272 default:
2273 {
2274 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002275 fmt::format("Unexpected ResizeMethod[{}] when creating layerName {} ",
2276 static_cast<int>(resizeMethod), CHECK_LOCATION().AsString()));
Sadik Armagana3b31f02019-12-05 09:08:53 +00002277 }
2278 }
2279
James Conroy05102392020-06-24 15:39:55 +01002280 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002281 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01002282 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
2283
2284 IConnectableLayer* layer = m_Network->AddResizeLayer(desc, layerName.c_str());
2285 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002286 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2287
2288 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2289 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2290
2291 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2292 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2293}
2294
Kevin May7d96b162021-02-03 17:38:41 +00002295void TfLiteParserImpl::ParseConcatenation(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan479045b2018-10-01 11:51:37 +01002296{
2297 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2298
2299 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2300 const auto * options = operatorPtr->builtin_options.AsConcatenationOptions();
2301
2302 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
2303
2304 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2305 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2306 CHECK_VALID_SIZE(outputs.size(), 1);
2307
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002308 unsigned int numConcatView = static_cast<unsigned int>(inputs.size());
2309 uint32_t inputRank = ToTensorInfo(inputs[0]).GetNumDimensions();
Sadik Armagan479045b2018-10-01 11:51:37 +01002310
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002311 const unsigned int concatDimInput = static_cast<unsigned int>(
2312 (static_cast<int>(inputRank) + options->axis) % static_cast<int>(inputRank));
Sadik Armagan479045b2018-10-01 11:51:37 +01002313
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002314 OriginsDescriptor concatDescriptor(static_cast<uint32_t>(numConcatView), inputRank);
2315 concatDescriptor.SetConcatAxis(concatDimInput);
Sadik Armagan479045b2018-10-01 11:51:37 +01002316
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002317 unsigned int mergeDimOrigin = 0;
Sadik Armagan479045b2018-10-01 11:51:37 +01002318
2319 for (unsigned int viewIndex = 0; viewIndex < numConcatView; ++viewIndex)
2320 {
2321 TensorInfo inputTensorInfo = ToTensorInfo(inputs[viewIndex]);
2322
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002323 // This set up concatDescriptor view origin
2324 armnnUtils::ProcessConcatInputTensorInfo(
2325 inputTensorInfo, concatDescriptor, concatDimInput, viewIndex, mergeDimOrigin);
Sadik Armagan479045b2018-10-01 11:51:37 +01002326 }
2327
James Ward58dec6b2020-09-11 17:32:44 +01002328 auto layerName = fmt::format("Concatenation:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002329 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01002330
Jim Flynn906f9462019-05-10 13:55:21 +01002331 IConnectableLayer* layer = m_Network->AddConcatLayer(concatDescriptor, layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002332 ARMNN_ASSERT(layer != nullptr);
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002333 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Sadik Armagan479045b2018-10-01 11:51:37 +01002334
James Conroy05102392020-06-24 15:39:55 +01002335 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002336 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
Sadik Armagan479045b2018-10-01 11:51:37 +01002337
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002338 // add fused activation layer
2339 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Sadik Armagan479045b2018-10-01 11:51:37 +01002340
Sadik Armagan479045b2018-10-01 11:51:37 +01002341 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2342 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2343}
2344
Kevin May7d96b162021-02-03 17:38:41 +00002345void TfLiteParserImpl::ParseFullyConnected(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002346{
2347 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2348
2349 const auto & operatorRfr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2350 const auto options = operatorRfr->builtin_options.AsFullyConnectedOptions();
2351
2352 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
2353
2354 FullyConnectedDescriptor desc;
2355 desc.m_BiasEnabled = false;
Nattapat Chaimanowongd8eee592018-10-26 10:24:14 +01002356 desc.m_TransposeWeightMatrix = true;
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002357
2358 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2359 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2360 CHECK_VALID_SIZE(outputs.size(), 1);
2361
2362 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
2363
2364 // Fully Connected Layer accepts two dimensional weights input
2365 int32_t weightsDimension = static_cast<int32_t>(filterTensorInfo.GetNumDimensions());
2366 if (weightsDimension != 2)
2367 {
2368 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002369 fmt::format("Dimension {} for Fully Connected weights is not supported by Armnn. "
2370 "Node {}",
2371 weightsDimension,
2372 CHECK_LOCATION().AsString()));
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002373 }
2374
Matthew Jackson74bf7da2019-08-16 16:51:42 +01002375 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01002376 auto layerName = fmt::format("FullyConnected:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002377
Finn Williamsd4fa5452021-03-01 12:31:41 +00002378 Optional<ConstTensor> filterOptionalConstTensor;
2379
2380 desc.m_ConstantWeights = IsConstTensor(inputs[1]);
2381
Finn Williamsd4fa5452021-03-01 12:31:41 +00002382 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2383 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0]};
2384 if (desc.m_ConstantWeights)
2385 {
2386 filterOptionalConstTensor = Optional<ConstTensor>(CreateConstTensorNonPermuted(inputs[1], filterTensorInfo));
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002387 }
2388 else
2389 {
Finn Williamsd4fa5452021-03-01 12:31:41 +00002390 // Non const weights will need to be registered as inputs
2391 tensorIndexesToRegister.emplace_back(inputTensorIndexes[1]);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002392 }
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002393
Finn Williamsd4fa5452021-03-01 12:31:41 +00002394 Optional<ConstTensor> biasOptionalConstTensor;
2395 if (inputs.size() == 3)
2396 {
2397 desc.m_BiasEnabled = true;
2398 if (desc.m_ConstantWeights)
2399 {
2400 TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
2401 biasOptionalConstTensor = Optional<ConstTensor>(CreateConstTensorNonPermuted(inputs[2], biasTensorInfo));
2402 }
2403 else
2404 {
2405 // Non const biases will need to be registered as inputs
2406 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
2407 }
2408 }
2409
2410 layer = m_Network->AddFullyConnectedLayer(desc,
2411 filterOptionalConstTensor,
2412 biasOptionalConstTensor,
2413 layerName.c_str());
2414
2415 ARMNN_ASSERT(layer != nullptr);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002416 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2417
Finn Williamsd4fa5452021-03-01 12:31:41 +00002418 unsigned int startingSlotIndex = 0;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002419 if (inputTensorInfo.GetNumDimensions() > 2)
2420 {
2421 // Add reshape to flatten to 2D [batch_size, input_size],
2422 // where "input_size" corresponds to the number of inputs to the layer,
2423 // matching the second dimension of weights,
2424 // and "batch_size" is calculated by dividing the number of elements by "input_size".
2425 std::vector<unsigned int> reshapedDimensions(2);
2426 reshapedDimensions[1] = filterTensorInfo.GetShape()[1];
2427 reshapedDimensions[0] = inputTensorInfo.GetNumElements() / reshapedDimensions[1];
2428
2429 if (inputTensorInfo.GetNumElements() % reshapedDimensions[1] != 0)
2430 {
2431 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002432 fmt::format("Failed to deduce input tensor shape from filter size {} {}",
2433 reshapedDimensions[1],
2434 CHECK_LOCATION().AsString()));
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002435 }
2436
2437 armnn::TensorInfo reshapedTensorInfo = ToTensorInfo(inputs[0]);
2438 reshapedTensorInfo.SetShape(armnn::TensorShape{ 2, reshapedDimensions.data() });
2439
James Ward58dec6b2020-09-11 17:32:44 +01002440 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Finn Williamsd4fa5452021-03-01 12:31:41 +00002441 armnn::ReshapeDescriptor reshapeDescriptor;
2442 reshapeDescriptor.m_TargetShape = reshapedTensorInfo.GetShape();
2443 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(reshapeDescriptor, layerName.c_str());
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002444
2445 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedTensorInfo);
2446 reshapeLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(0));
2447
2448 RegisterInputSlots(subgraphIndex, operatorIndex, reshapeLayer, {inputTensorIndexes[0]});
Finn Williamsd4fa5452021-03-01 12:31:41 +00002449 // Fc layer connects to the reshape layer, so we skip the first input slot when registering fc's input slots
2450 tensorIndexesToRegister.erase(tensorIndexesToRegister.begin());
2451 startingSlotIndex = 1;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002452 }
Finn Williamsd4fa5452021-03-01 12:31:41 +00002453
2454 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister, startingSlotIndex);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002455
Sadik Armagand109a4d2020-07-28 10:42:13 +01002456 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002457 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2458
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002459 // we need to add the activation layer and fortunately we don't need to care about the data layout
2460 armnn::IConnectableLayer* fusedActivationLayer = AddFusedActivationLayer(layer, 0,
2461 options->fused_activation_function);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002462
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002463 // register the output connection slots for the layer, connections are made after all layers have been created
2464 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2465 RegisterOutputSlots(subgraphIndex, operatorIndex, fusedActivationLayer, {outputTensorIndexes[0]});
2466}
2467
Kevin May7d96b162021-02-03 17:38:41 +00002468void TfLiteParserImpl::ParseDetectionPostProcess(size_t subgraphIndex, size_t operatorIndex)
keidav011b3e2ea2019-02-21 10:07:37 +00002469{
2470 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2471
2472 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2473
2474 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2475 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2476 CHECK_VALID_SIZE(outputs.size(), 4);
2477
2478 // Obtain custom options from flexbuffers
2479 auto custom_options = operatorPtr->custom_options;
2480 const flexbuffers::Map& m = flexbuffers::GetRoot(custom_options.data(), custom_options.size()).AsMap();
2481
2482 // Obtain descriptor information from tf lite
2483 DetectionPostProcessDescriptor desc;
2484 desc.m_MaxDetections = m["max_detections"].AsUInt32();
2485 desc.m_MaxClassesPerDetection = m["max_classes_per_detection"].AsUInt32();
2486 desc.m_NmsScoreThreshold = m["nms_score_threshold"].AsFloat();
2487 desc.m_NmsIouThreshold = m["nms_iou_threshold"].AsFloat();
2488 desc.m_NumClasses = m["num_classes"].AsUInt32();
2489 desc.m_ScaleH = m["h_scale"].AsFloat();
2490 desc.m_ScaleW = m["w_scale"].AsFloat();
2491 desc.m_ScaleX = m["x_scale"].AsFloat();
2492 desc.m_ScaleY = m["y_scale"].AsFloat();
2493
keidav0107d58c72019-02-26 11:57:39 +00002494 if (!(m["use_regular_nms"].IsNull()))
keidav011b3e2ea2019-02-21 10:07:37 +00002495 {
keidav0107d58c72019-02-26 11:57:39 +00002496 desc.m_UseRegularNms = m["use_regular_nms"].AsBool();
keidav011b3e2ea2019-02-21 10:07:37 +00002497 }
2498 if (!(m["detections_per_class"].IsNull()))
2499 {
2500 desc.m_DetectionsPerClass = m["detections_per_class"].AsUInt32();
2501 }
2502
2503 if (desc.m_NmsIouThreshold <= 0.0f || desc.m_NmsIouThreshold > 1.0f)
2504 {
2505 throw InvalidArgumentException("DetectionPostProcessTFLiteParser: Intersection over union threshold "
2506 "must be positive and less than or equal to 1.");
2507 }
2508
2509 armnn::TensorInfo anchorTensorInfo = ToTensorInfo(inputs[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00002510 auto anchorTensorAndData = CreateConstTensorNonPermuted(inputs[2], anchorTensorInfo);
keidav011b3e2ea2019-02-21 10:07:37 +00002511
James Ward58dec6b2020-09-11 17:32:44 +01002512 auto layerName = fmt::format("DetectionPostProcess:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsd4fa5452021-03-01 12:31:41 +00002513 IConnectableLayer* layer = m_Network->AddDetectionPostProcessLayer(desc, anchorTensorAndData,
keidav011b3e2ea2019-02-21 10:07:37 +00002514 layerName.c_str());
2515
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002516 ARMNN_ASSERT(layer != nullptr);
keidav011b3e2ea2019-02-21 10:07:37 +00002517
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00002518 // The model does not specify the output shapes.
2519 // The output shapes are calculated from the max_detection and max_classes_per_detection.
2520 unsigned int numDetectedBox = desc.m_MaxDetections * desc.m_MaxClassesPerDetection;
2521 m_OverridenOutputShapes.push_back({ 1, numDetectedBox, 4 });
2522 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
2523 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
2524 m_OverridenOutputShapes.push_back({ 1 });
2525
keidav011b3e2ea2019-02-21 10:07:37 +00002526 for (unsigned int i = 0 ; i < outputs.size() ; ++i)
2527 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00002528 armnn::TensorInfo detectionBoxOutputTensorInfo = ToTensorInfo(outputs[i], m_OverridenOutputShapes[i]);
keidav011b3e2ea2019-02-21 10:07:37 +00002529 layer->GetOutputSlot(i).SetTensorInfo(detectionBoxOutputTensorInfo);
2530 }
2531
2532 // Register the input connection slots for the layer, connections are made after all layers have been created
2533 // only the tensors for the inputs are relevant, exclude the const tensors
2534 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2535 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2536
2537 // Register the output connection slots for the layer, connections are made after all layers have been created
2538 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2539 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0],
2540 outputTensorIndexes[1],
2541 outputTensorIndexes[2],
2542 outputTensorIndexes[3]});
2543}
2544
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002545/// The TfLite Pack operator is equivalent to the ArmNN Stack operator
Kevin May7d96b162021-02-03 17:38:41 +00002546void TfLiteParserImpl::ParsePack(size_t subgraphIndex, size_t operatorIndex)
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002547{
2548 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2549
2550 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2551 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2552 CHECK_VALID_SIZE(outputs.size(), 1);
2553
2554 if (inputs.size() < 1)
2555 {
2556 throw ParseException("Pack must have at least one input.");
2557 }
2558
2559 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2560 const auto* options = operatorPtr->builtin_options.AsPackOptions();
2561
2562 StackDescriptor desc;
2563 desc.m_Axis = static_cast<uint32_t>(options->axis);
2564 desc.m_NumInputs = static_cast<uint32_t>(inputs.size());
2565
2566 // Use the tensor shape of the first input as the "correct" input shape in the descriptor
2567 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2568 desc.m_InputShape = inputTensorInfo.GetShape();
2569
James Ward58dec6b2020-09-11 17:32:44 +01002570 auto layerName = fmt::format("Pack:{}:{}", subgraphIndex, operatorIndex);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002571 IConnectableLayer* layer = m_Network->AddStackLayer(desc, layerName.c_str());
2572
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002573 ARMNN_ASSERT(layer != nullptr);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002574
Sadik Armagand109a4d2020-07-28 10:42:13 +01002575 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002576 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2577
2578 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2579 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
2580
2581 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2582 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2583}
2584
Kevin May7d96b162021-02-03 17:38:41 +00002585void TfLiteParserImpl::ParseUnpack(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd200e3802019-04-15 09:47:39 +01002586{
2587 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2588
2589 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2590 const auto * options = operatorPtr->builtin_options.AsUnpackOptions();
2591
2592 // This unpackAxis indicates the axis to unpack
2593 const unsigned int unpackAxis = CHECKED_NON_NEGATIVE(options->axis);
2594
2595 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2596 CHECK_VALID_SIZE(inputs.size(), 1);
2597
2598 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002599
2600 if (unpackAxis >= inputTensorInfo.GetNumDimensions())
2601 {
2602 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002603 fmt::format("The unpack axis: {} cannot be greater than or equal to "
2604 "the number of input dimension {} {}",
2605 unpackAxis,
2606 inputTensorInfo.GetNumDimensions(),
2607 CHECK_LOCATION().AsString()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002608 }
2609
Nina Drozd200e3802019-04-15 09:47:39 +01002610 unsigned int unpackNum = CHECKED_NON_NEGATIVE(options->num);
2611 // If num is not defined, automatically infer from the length of the dimension axis.
2612 if(unpackNum == 0)
2613 {
2614 unpackNum = inputTensorInfo.GetShape()[unpackAxis];
2615 }
2616
2617 // If unpack number cannot be inferred and is still zero, throw ParseException.
2618 if(unpackNum == 0)
2619 {
2620 throw ParseException("Number to unpack must greater than zero.");
2621 }
2622
2623 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2624 CHECK_VALID_SIZE(outputs.size(), unpackNum);
2625
2626 auto inputDimSize = inputTensorInfo.GetNumDimensions();
2627 std::vector<unsigned int> unpackDimSizes(inputDimSize);
2628
2629 // Add current input shape to unpackDimSizes
2630 for (unsigned int i = 0; i < inputDimSize; ++i)
2631 {
2632 unpackDimSizes[i] = inputTensorInfo.GetShape()[i];
2633 }
2634
2635 if (unpackDimSizes[unpackAxis] != unpackNum)
2636 {
2637 throw ParseException("Number to unpack must be the same as length of the dimension to "
2638 "unpack along.");
2639 }
2640
2641 unpackDimSizes[unpackAxis] /= unpackNum;
2642
2643 SplitterDescriptor splitDesc(unpackNum, static_cast<unsigned int>(unpackDimSizes.size()));
2644 for (unsigned int j = 0; j < unpackNum; ++j)
2645 {
2646 // Set the size of the views.
2647 for (unsigned int dimIdx = 0; dimIdx < unpackDimSizes.size(); ++dimIdx)
2648 {
2649 splitDesc.SetViewSize(j, dimIdx, unpackDimSizes[dimIdx]);
2650 }
2651 splitDesc.SetViewOriginCoord(j, unpackAxis, unpackDimSizes[unpackAxis] * j);
2652 }
2653
James Ward58dec6b2020-09-11 17:32:44 +01002654 auto layerName = fmt::format("Unpack:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd200e3802019-04-15 09:47:39 +01002655 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002656 ARMNN_ASSERT(layer != nullptr);
Nina Drozd200e3802019-04-15 09:47:39 +01002657
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002658 TensorShape splitOutShape = TensorShape(static_cast<unsigned int>(unpackDimSizes.size()),
2659 unpackDimSizes.data());
2660
Nina Drozd200e3802019-04-15 09:47:39 +01002661 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2662 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2663
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002664 // Create reshape to remove the unpacked dimension for unpack operator of each output from Splitter.
2665 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
2666 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01002667 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[k], true);
James Ward58dec6b2020-09-11 17:32:44 +01002668 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002669 armnn::ReshapeDescriptor desc;
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01002670 desc.m_TargetShape = outputTensorInfo.GetShape();
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002671 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(desc, layerName.c_str());
2672
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01002673 layer->GetOutputSlot(k).SetTensorInfo(armnn::TensorInfo(splitOutShape,
2674 outputTensorInfo.GetDataType(),
2675 outputTensorInfo.GetQuantizationScale(),
2676 outputTensorInfo.GetQuantizationOffset()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002677 layer->GetOutputSlot(k).Connect(reshapeLayer->GetInputSlot(0));
2678
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01002679 reshapeLayer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002680
2681 uint32_t reshapedOutputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[k]);
2682 armnn::IOutputSlot* slot = &(reshapeLayer->GetOutputSlot(0));
2683 RegisterProducerOfTensor(subgraphIndex, reshapedOutputId, slot);
2684 }
Nina Drozd200e3802019-04-15 09:47:39 +01002685}
2686
Kevin May7d96b162021-02-03 17:38:41 +00002687void TfLiteParserImpl::ParseSplit(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd0324f482019-04-08 10:52:10 +01002688{
2689 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2690
2691 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2692 const auto * options = operatorPtr->builtin_options.AsSplitOptions();
2693
2694 const unsigned int numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
2695
Nina Drozd200e3802019-04-15 09:47:39 +01002696 // If number of splits cannot be inferred and is zero, throw ParseException.
2697 if(numSplits == 0)
2698 {
2699 throw ParseException("Number to splits must greater than zero.");
2700 }
2701
Nina Drozd0324f482019-04-08 10:52:10 +01002702 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2703 CHECK_VALID_SIZE(inputs.size(), 2);
2704 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2705 CHECK_VALID_SIZE(outputs.size(), numSplits);
2706
Matthew Sloyaned7fce42021-04-15 20:46:24 +01002707 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[1]);
2708 armnn::TensorInfo axisTensorInfo = ToTensorInfo(inputs[0]);
2709 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
Nina Drozd0324f482019-04-08 10:52:10 +01002710
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002711 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01002712 if (axisBufferPtr == nullptr)
2713 {
2714 throw ParseException(
2715 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
2716 CHECK_LOCATION().AsString()));
2717 }
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002718
Matthew Sloyaned7fce42021-04-15 20:46:24 +01002719 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
2720 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
2721 int32_t axis = axisData[0];
2722
2723 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
2724 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
2725 {
2726 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
2727 // E.g. Rank 4 tensor can have axis in range [-4, 3)
2728 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
2729 throw ParseException(
2730 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
2731 axis,
2732 CHECK_LOCATION().AsString()));
2733 }
2734
2735 const unsigned int splitDim = armnnUtils::GetUnsignedAxis(inputTensorInfo.GetNumDimensions(), axis);
Nina Drozd0324f482019-04-08 10:52:10 +01002736
Nina Drozd0324f482019-04-08 10:52:10 +01002737 auto inputDimSize = inputTensorInfo.GetNumDimensions();
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002738 if (inputDimSize > MaxNumOfTensorDimensions)
Nina Drozd0324f482019-04-08 10:52:10 +01002739 {
2740 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002741 fmt::format("The number of dimensions: {} for input tensors of the split op cannot be greater than {} {}",
2742 inputTensorInfo.GetNumDimensions(),
2743 MaxNumOfTensorDimensions,
2744 CHECK_LOCATION().AsString()));
Nina Drozd0324f482019-04-08 10:52:10 +01002745 }
2746
2747 std::vector<unsigned int> splitterDimSizes(inputDimSize);
2748
2749 // Add current input shape to splitterDimSizes
2750 for (unsigned int i = 0; i < inputDimSize; ++i)
2751 {
2752 splitterDimSizes[i] = inputTensorInfo.GetShape()[i];
2753 }
2754
2755 if (splitterDimSizes[splitDim] % numSplits != 0)
2756 {
2757 throw ParseException("Number of splits must evenly divide the dimension");
2758 }
2759 splitterDimSizes[splitDim] /= numSplits;
2760
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002761 SplitterDescriptor splitDesc(numSplits, inputDimSize);
Nina Drozd0324f482019-04-08 10:52:10 +01002762 for (unsigned int j = 0; j < numSplits; ++j)
2763 {
2764 // Set the size of the views.
2765 for (unsigned int dimIdx = 0; dimIdx < splitterDimSizes.size(); ++dimIdx)
2766 {
2767 splitDesc.SetViewSize(j, dimIdx, splitterDimSizes[dimIdx]);
2768 }
2769 splitDesc.SetViewOriginCoord(j, splitDim, splitterDimSizes[splitDim] * j);
2770 }
2771
James Ward58dec6b2020-09-11 17:32:44 +01002772 auto layerName = fmt::format("Split:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd0324f482019-04-08 10:52:10 +01002773 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002774 ARMNN_ASSERT(layer != nullptr);
Nina Drozd0324f482019-04-08 10:52:10 +01002775
2776 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002777 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[1]});
Nina Drozd0324f482019-04-08 10:52:10 +01002778
Nina Drozd0324f482019-04-08 10:52:10 +01002779 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
2780 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01002781 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Francis Murtagh98d6b3d2019-10-21 10:52:54 +01002782 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
Nina Drozd0324f482019-04-08 10:52:10 +01002783 }
2784
2785 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2786 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2787}
2788
Derek Lambertif0176992020-04-28 13:37:49 +01002789unsigned int ComputeWrappedIndex(int idx, unsigned int numDimsIn)
2790{
2791 int numDims = armnn::numeric_cast<int>(numDimsIn);
2792 int v = idx < 0 ? numDims + idx : idx;
2793 ARMNN_ASSERT(v >= 0);
2794 ARMNN_ASSERT(v < numDims);
2795
2796 return static_cast<unsigned int>(v);
2797}
2798
Kevin May7d96b162021-02-03 17:38:41 +00002799void TfLiteParserImpl::ParseSplitV(size_t subgraphIndex, size_t operatorIndex)
Derek Lambertif0176992020-04-28 13:37:49 +01002800{
2801 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2802
2803 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Ryan OShea86704732020-05-26 11:41:04 +01002804 const auto * options = operatorPtr->builtin_options.AsSplitVOptions();
Derek Lambertif0176992020-04-28 13:37:49 +01002805
2806 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2807 CHECK_VALID_SIZE(inputs.size(), 3);
2808
2809 auto& inputTensor = inputs[0];
2810 auto& splitsTensor = inputs[1];
2811 auto& axisTensor = inputs[2];
2812
2813 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputTensor);
2814 armnn::TensorInfo splitsInfo = ToTensorInfo(splitsTensor);
2815 armnn::TensorInfo axisTensorInfo = ToTensorInfo(axisTensor);
2816 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
2817
2818 // Inputs
2819 auto inputDimSize = inputTensorInfo.GetNumDimensions();
2820 if (inputDimSize > MaxNumOfTensorDimensions)
2821 {
2822 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002823 fmt::format("The number of dimensions: {} for input tensors of the "
2824 "SplitV op cannot be greater than {} {}",
2825 inputTensorInfo.GetNumDimensions(),
2826 MaxNumOfTensorDimensions,
2827 CHECK_LOCATION().AsString()));
Derek Lambertif0176992020-04-28 13:37:49 +01002828 }
2829
2830 // Get split axis
2831 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, axisTensor->buffer);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01002832 if (axisBufferPtr == nullptr)
2833 {
2834 throw ParseException(
2835 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
2836 CHECK_LOCATION().AsString()));
2837 }
2838
Derek Lambertif0176992020-04-28 13:37:49 +01002839 std::vector<int> axisData(axisTensorInfo.GetNumElements());
2840 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
Matthew Sloyaned7fce42021-04-15 20:46:24 +01002841 int32_t axis = axisData[0];
2842
2843 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
2844 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
2845 {
2846 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
2847 // E.g. Rank 4 tensor can have axis in range [-4, 3)
2848 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
2849 throw ParseException(
2850 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
2851 axis,
2852 CHECK_LOCATION().AsString()));
2853 }
2854 const unsigned int splitDim = ComputeWrappedIndex(axis, inputTensorInfo.GetNumDimensions());
Derek Lambertif0176992020-04-28 13:37:49 +01002855
Derek Lambertif0176992020-04-28 13:37:49 +01002856 // Set split sizes
Derek Lambertif0176992020-04-28 13:37:49 +01002857 CHECK_VALID_SIZE(splitsInfo.GetNumDimensions(), 1);
Ryan OShea86704732020-05-26 11:41:04 +01002858 unsigned int numSplits{0};
2859
2860 if(options)
Derek Lambertif0176992020-04-28 13:37:49 +01002861 {
2862 numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
Derek Lambertif0176992020-04-28 13:37:49 +01002863 }
2864 else
2865 {
Ryan OShea86704732020-05-26 11:41:04 +01002866 numSplits = splitsInfo.GetNumElements();
Derek Lambertif0176992020-04-28 13:37:49 +01002867 }
2868
2869 if (numSplits <=0)
2870 {
2871 throw ParseException("SplitV has invalid number of splits");
2872 }
2873
Jan Eilersc0761e92020-06-29 16:48:44 +01002874 std::vector<int> splitsData(numSplits);
Ryan OShea86704732020-05-26 11:41:04 +01002875 BufferRawPtr splitsBufferPtr = GetBuffer(m_Model, splitsTensor->buffer);
Jan Eilersc0761e92020-06-29 16:48:44 +01002876 ::memcpy(splitsData.data(), splitsBufferPtr->data.data(), splitsInfo.GetNumBytes());
Ryan OShea86704732020-05-26 11:41:04 +01002877
Jan Eilersc0761e92020-06-29 16:48:44 +01002878 unsigned int idx = 0;
Ryan OShea86704732020-05-26 11:41:04 +01002879 int numInferred{0};
2880 unsigned int inferIdx{0};
2881 int splitSum{0};
2882 for (auto split : splitsData)
2883 {
2884 if (split < 0)
2885 {
2886 numInferred++;
2887 inferIdx = idx;
2888 }
2889 else
2890 {
2891 splitSum += split;
2892 }
2893 idx++;
2894 }
2895 // Check for inferred Axis
2896 if (numInferred == 0)
2897 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002898 if (splitSum != armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]))
Ryan OShea86704732020-05-26 11:41:04 +01002899 {
2900 throw ParseException("SplitV split_sizes does not sum to the dimension of value along split_dim.");
2901 }
2902 }
2903 else if (numInferred == 1)
2904 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002905 splitsData[inferIdx] = armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]) - splitSum;
Ryan OShea86704732020-05-26 11:41:04 +01002906 }
2907 else
2908 {
2909 throw ParseException("Cannot infer split size for more than one split");
2910 }
2911
Derek Lambertif0176992020-04-28 13:37:49 +01002912 //Ouput size validation
2913 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2914 CHECK_VALID_SIZE(outputs.size(), numSplits);
2915
2916 // Setup Armnn descriptor
2917 SplitterDescriptor splitDesc(numSplits, inputDimSize);
2918 unsigned int accumSplit = 0;
2919 for (unsigned int j = 0; j < numSplits; ++j)
2920 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002921 unsigned int splitSize = armnn::numeric_cast<unsigned int>(splitsData[j]);
Derek Lambertif0176992020-04-28 13:37:49 +01002922
2923 // Set the size of the views.
2924 for (unsigned int dimIdx = 0; dimIdx < inputTensorInfo.GetNumDimensions(); ++dimIdx)
2925 {
2926 unsigned int dimSize = inputTensorInfo.GetShape()[dimIdx];
2927 if (dimIdx == splitDim)
2928 {
2929 dimSize = splitSize;
2930 }
2931 splitDesc.SetViewSize(j, dimIdx, dimSize);
2932 }
2933
2934 splitDesc.SetViewOriginCoord(j, splitDim, accumSplit);
2935 accumSplit += splitSize;
2936 }
2937
James Ward58dec6b2020-09-11 17:32:44 +01002938 auto layerName = fmt::format("SplitV:{}:{}", subgraphIndex, operatorIndex);
Derek Lambertif0176992020-04-28 13:37:49 +01002939 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002940 ARMNN_ASSERT(layer != nullptr);
Derek Lambertif0176992020-04-28 13:37:49 +01002941
2942 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2943 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2944
2945 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
2946 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01002947 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Derek Lambertif0176992020-04-28 13:37:49 +01002948 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
2949 }
2950
2951 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2952 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2953}
2954
Matthew Sloyan28f177c2021-04-09 14:38:52 +01002955void TfLiteParserImpl::ParseArgMin(size_t subgraphIndex, size_t operatorIndex)
2956{
2957 ParseArgMinMax(subgraphIndex, operatorIndex, armnn::ArgMinMaxFunction::Min);
2958}
2959
Kevin May7d96b162021-02-03 17:38:41 +00002960void TfLiteParserImpl::ParseArgMax(size_t subgraphIndex, size_t operatorIndex)
Inki Daed4619e22020-09-10 15:33:54 +09002961{
Matthew Sloyan28f177c2021-04-09 14:38:52 +01002962 ParseArgMinMax(subgraphIndex, operatorIndex, armnn::ArgMinMaxFunction::Max);
2963}
2964
2965void TfLiteParserImpl::ParseArgMinMax(size_t subgraphIndex, size_t operatorIndex, ArgMinMaxFunction argMinMaxFunction)
2966{
Inki Daed4619e22020-09-10 15:33:54 +09002967 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2968 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2969 CHECK_VALID_SIZE(inputs.size(), 2);
2970
2971 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2972 CHECK_VALID_SIZE(outputs.size(), 1);
2973
Matthew Sloyan28f177c2021-04-09 14:38:52 +01002974 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2975 armnn::TensorInfo axisTensorInfo = ToTensorInfo(inputs[1]);
Inki Daed4619e22020-09-10 15:33:54 +09002976 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
Matthew Sloyaned7fce42021-04-15 20:46:24 +01002977 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
Matthew Sloyan28f177c2021-04-09 14:38:52 +01002978
2979 // Check if output tensor type is Signed32 or Signed64
Mike Kelly1f140f72021-04-06 12:25:55 +01002980 if (outputTensorInfo.GetDataType() != armnn::DataType::Signed32 &&
2981 outputTensorInfo.GetDataType() != armnn::DataType::Signed64)
2982 {
2983 throw ParseException(
2984 fmt::format(
2985 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
2986 CHECK_LOCATION().AsString()));
2987 }
Matthew Sloyan28f177c2021-04-09 14:38:52 +01002988
2989 // Get const axis value from model and set it to descriptor.
2990 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2991 if (axisBufferPtr == nullptr)
2992 {
2993 throw ParseException(
2994 fmt::format("Operation has invalid inputs. Failed to read axis. {}",
2995 CHECK_LOCATION().AsString()));
2996 }
2997
2998 std::vector<int32_t> axisData(axisTensorInfo.GetNumElements());
2999 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
3000 int32_t axis = axisData.front();
3001
3002 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3003 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3004 {
3005 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
3006 // E.g. Rank 4 tensor can have axis in range [-4, 3)
3007 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
3008 throw ParseException(
3009 fmt::format("Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3010 axis,
3011 CHECK_LOCATION().AsString()));
3012 }
3013
3014 ArgMinMaxDescriptor desc;
3015 desc.m_Axis = axis;
3016 desc.m_Function = argMinMaxFunction;
3017
3018 // Register a ArgMin/ArgMax layer.
3019 auto layerName = argMinMaxFunction == ArgMinMaxFunction::Max ? "ArgMax:{}:{}" : "ArgMin:{}:{}";
3020 auto layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
3021 IConnectableLayer *layer = m_Network->AddArgMinMaxLayer(desc, layerNameFormatted.c_str());
3022 ARMNN_ASSERT(layer != nullptr);
Inki Daed4619e22020-09-10 15:33:54 +09003023 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3024
3025 // Register input tensor to the layer.
3026 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3027 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3028
3029 // Register output tensor to the layer.
3030 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3031 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3032}
3033
Kevin May7d96b162021-02-03 17:38:41 +00003034void TfLiteParserImpl::ParseGather(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00003035{
3036 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3037
Kevin May7d96b162021-02-03 17:38:41 +00003038 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00003039 CHECK_VALID_SIZE(inputs.size(), 2);
Kevin May7d96b162021-02-03 17:38:41 +00003040 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00003041 CHECK_VALID_SIZE(outputs.size(), 1);
3042
3043 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
3044 armnn::TensorInfo indicesTensorInfo = ToTensorInfo(inputs[1]);
3045 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
3046
3047 armnn::GatherDescriptor gatherDescriptor;
3048
3049 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3050 const auto * options = operatorPtr->builtin_options.AsGatherOptions();
3051 auto axis = options->axis;
3052
3053 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3054 auto indicesDimensions = indicesTensorInfo.GetNumDimensions();
3055 auto outputDimensions = outputTensorInfo.GetNumDimensions();
3056 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3057 {
3058 throw ParseException(
3059 fmt::format("Operation has invalid axis: {} It is out of bounds [ -{}, {} ) {}",
3060 axis,
3061 inputDimensions, inputDimensions,
3062 CHECK_LOCATION().AsString()));
3063 }
3064 if (outputDimensions != static_cast<unsigned int>(inputDimensions) + indicesDimensions - 1)
3065 {
3066 throw ParseException(
3067 fmt::format("Operation has invalid output dimensions: {} Output must be an ({} + {} - 1) -D tensor {}",
3068 outputDimensions,
3069 inputDimensions, indicesDimensions,
3070 CHECK_LOCATION().AsString()));
3071 }
3072
3073 gatherDescriptor.m_Axis = axis;
3074
3075 auto layerName = fmt::format("Gather:{}:{}", subgraphIndex, operatorIndex);
3076 IConnectableLayer* layer = m_Network->AddGatherLayer(gatherDescriptor, layerName.c_str());
3077 ARMNN_ASSERT(layer != nullptr);
3078 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3079
3080 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3081 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
3082
3083 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3084 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3085}
3086
Kevin May7d96b162021-02-03 17:38:41 +00003087void TfLiteParserImpl::ParseDepthToSpace(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00003088{
3089 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3090
Kevin May7d96b162021-02-03 17:38:41 +00003091 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00003092 CHECK_VALID_SIZE(inputs.size(), 1);
Kevin May7d96b162021-02-03 17:38:41 +00003093 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00003094 CHECK_VALID_SIZE(outputs.size(), 1);
3095
3096 armnn::DepthToSpaceDescriptor descriptor;
3097
3098 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3099 const auto * options = operatorPtr->builtin_options.AsDepthToSpaceOptions();
3100 auto blockSize = options->block_size;
3101 if (blockSize < 2)
3102 {
3103 throw ParseException(
3104 fmt::format("Operation has invalid block size: {} Block size should be >= 2 {}",
3105 blockSize,
3106 CHECK_LOCATION().AsString()));
3107 }
3108 descriptor.m_BlockSize = armnn::numeric_cast<uint32_t>(blockSize);
3109
3110 auto layerName = fmt::format("DepthToSpace:{}:{}", subgraphIndex, operatorIndex);
3111 IConnectableLayer* layer = m_Network->AddDepthToSpaceLayer(descriptor, layerName.c_str());
3112 ARMNN_ASSERT(layer != nullptr);
3113 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
3114 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3115
3116 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3117 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3118
3119 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3120 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3121}
3122
Kevin May7d96b162021-02-03 17:38:41 +00003123void TfLiteParserImpl::ParseSum(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003124{
Sadik Armagana2747482021-02-09 10:28:54 +00003125 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Sum);
3126}
3127
3128void TfLiteParserImpl::ParseReduceMax(size_t subgraphIndex, size_t operatorIndex)
3129{
3130 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Max);
3131}
3132
3133void TfLiteParserImpl::ParseReduceMin(size_t subgraphIndex, size_t operatorIndex)
3134{
3135 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Min);
3136}
3137
3138void TfLiteParserImpl::ParseReduce(size_t subgraphIndex, size_t operatorIndex, ReduceOperation reduceOperation)
3139{
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003140 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3141
3142 const auto &operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3143 const auto *options = operatorPtr->builtin_options.AsReducerOptions();
3144
3145 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3146 CHECK_VALID_SIZE(inputs.size(), 2);
3147
3148 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3149 CHECK_VALID_SIZE(outputs.size(), 1);
3150
Sadik Armagana2747482021-02-09 10:28:54 +00003151 auto layerName = fmt::format("Reduce:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003152
3153 armnn::TensorInfo inputTensorInfo0 = ToTensorInfo(inputs[0]);
3154 armnn::TensorInfo inputTensorInfo1 = ToTensorInfo(inputs[1]);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003155
3156 ReduceDescriptor desc;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003157 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
3158 // Get const axis value from model and set it to descriptor.
3159 if (axisBufferPtr != nullptr)
3160 {
Sadik Armagan49bdb792021-02-11 13:57:07 +00003161 std::vector<int32_t> axisData(inputTensorInfo1.GetNumElements());
3162 ::memcpy(axisData.data(), axisBufferPtr->data.data(), inputTensorInfo1.GetNumBytes());
3163
3164 // Convert the axis to unsigned int and remove duplicates.
3165 auto rank = static_cast<int32_t>(inputTensorInfo0.GetNumDimensions());
3166 std::set<unsigned int> uniqueAxis;
3167 std::transform(axisData.begin(),
3168 axisData.end(),
3169 std::inserter(uniqueAxis, uniqueAxis.begin()),
3170 [rank](int i)->unsigned int{
3171 return static_cast<uint32_t>(((i + rank) % rank)); });
3172 desc.m_vAxis.assign(uniqueAxis.begin(), uniqueAxis.end());
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003173 }
Sadik Armagana2747482021-02-09 10:28:54 +00003174 else
3175 {
3176 for (uint32_t i = 0; i < inputTensorInfo0.GetNumDimensions(); ++i)
3177 {
3178 desc.m_vAxis.push_back(i);
3179 }
3180 }
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003181
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003182 desc.m_KeepDims = options->keep_dims;
Sadik Armagana2747482021-02-09 10:28:54 +00003183 desc.m_ReduceOperation = reduceOperation;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003184
3185 // Register a new layer object, Sum.
3186 IConnectableLayer *layer = m_Network->AddReduceLayer(desc, layerName.c_str());
3187
3188 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
3189 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3190
3191 // Register input tensor to the layer.
3192 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3193 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3194
3195 // Register output tensor to the layer.
3196 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3197 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3198}
3199
Matthew Sloyaned7fce42021-04-15 20:46:24 +01003200void TfLiteParserImpl::ParseAbs(size_t subgraphIndex, size_t operatorIndex)
3201{
3202 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Abs);
3203}
3204
3205void TfLiteParserImpl::ParseExp(size_t subgraphIndex, size_t operatorIndex)
3206{
3207 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Exp);
3208}
3209
3210void TfLiteParserImpl::ParseLogicalNot(size_t subgraphIndex, size_t operatorIndex)
3211{
3212 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::LogicalNot);
3213}
3214
3215void TfLiteParserImpl::ParseNeg(size_t subgraphIndex, size_t operatorIndex)
3216{
3217 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Neg);
3218}
3219
3220void TfLiteParserImpl::ParseRsqrt(size_t subgraphIndex, size_t operatorIndex)
3221{
3222 ParseElementwiseUnary(subgraphIndex, operatorIndex, armnn::UnaryOperation::Rsqrt);
3223}
3224
3225void TfLiteParserImpl::ParseElementwiseUnary(size_t subgraphIndex, size_t operatorIndex, UnaryOperation unaryOperation)
3226{
3227 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3228
3229 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3230 CHECK_VALID_SIZE(inputs.size(), 1);
3231
3232 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3233 CHECK_VALID_SIZE(outputs.size(), 1);
3234
3235 std::string layerName = std::string(GetUnaryOperationAsCString(unaryOperation)) + ":{}:{}";
3236 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
3237
3238 ElementwiseUnaryDescriptor desc;
3239 desc.m_Operation = unaryOperation;
3240 IConnectableLayer* layer = m_Network->AddElementwiseUnaryLayer(desc, layerNameFormatted.c_str());
3241 ARMNN_ASSERT(layer != nullptr);
3242
3243 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
3244 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3245
3246 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3247 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3248
3249 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3250 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3251}
3252
Kevin May7d96b162021-02-03 17:38:41 +00003253armnn::IConnectableLayer* TfLiteParserImpl::AddFusedActivationLayer(armnn::IConnectableLayer* prevLayer,
3254 unsigned int outputSlot,
3255 tflite::ActivationFunctionType activationType)
telsoa01c577f2c2018-08-31 09:22:23 +01003256{
3257 ActivationDescriptor activationDesc;
3258 std::string layerName = prevLayer->GetName();
3259
3260 switch(activationType)
3261 {
3262 case tflite::ActivationFunctionType_NONE:
3263 {
3264 // this is a no-op: return previous layer
3265 return prevLayer;
3266 }
3267 case tflite::ActivationFunctionType_RELU:
3268 {
3269 activationDesc.m_Function = ActivationFunction::ReLu;
3270 layerName += ":RELU";
3271 break;
3272 }
3273 case tflite::ActivationFunctionType_RELU6:
3274 {
3275 activationDesc.m_Function = ActivationFunction::BoundedReLu;
3276 activationDesc.m_A = 6.0f;
3277 activationDesc.m_B = 0.0f;
3278 layerName += ":RELU6";
3279 break;
3280 }
3281 case tflite::ActivationFunctionType_TANH:
3282 {
3283 activationDesc.m_Function = ActivationFunction::TanH;
3284 activationDesc.m_A = 1.0f;
3285 activationDesc.m_B = 1.0f;
3286 layerName += ":TANH";
3287 break;
3288 }
3289
3290 // I only put these here as a reminder what others we could support
3291 case tflite::ActivationFunctionType_RELU_N1_TO_1:
3292 case tflite::ActivationFunctionType_SIGN_BIT:
3293 default:
3294 {
3295 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003296 fmt::format("TfLite parser doesn't suppport fused activation: "
3297 "{}/{} {} ",
3298 activationType,
3299 tflite::EnumNameActivationFunctionType(activationType),
3300 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003301
3302 }
3303 }
3304
3305 IConnectableLayer* activationLayer =
3306 m_Network->AddActivationLayer(activationDesc, layerName.c_str());
3307
3308 auto & prevOutputSlot = prevLayer->GetOutputSlot(outputSlot);
3309 prevOutputSlot.Connect(activationLayer->GetInputSlot(0));
3310 activationLayer->GetOutputSlot(0).SetTensorInfo(prevOutputSlot.GetTensorInfo());
3311 return activationLayer;
3312}
3313
Kevin May7d96b162021-02-03 17:38:41 +00003314TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromFile(const char * fileName)
telsoa01c577f2c2018-08-31 09:22:23 +01003315{
3316 if (fileName == nullptr)
3317 {
James Ward58dec6b2020-09-11 17:32:44 +01003318 throw InvalidArgumentException(fmt::format("Invalid (null) file name {}",
telsoa01c577f2c2018-08-31 09:22:23 +01003319 CHECK_LOCATION().AsString()));
3320 }
Francis Murtagh532a29d2020-06-29 11:50:01 +01003321 std::error_code errorCode;
3322 fs::path pathToFile(fileName);
3323 if (!fs::exists(pathToFile, errorCode))
telsoa01c577f2c2018-08-31 09:22:23 +01003324 {
James Ward58dec6b2020-09-11 17:32:44 +01003325 //fmt::format() could not be used here (format error)
3326 std::stringstream msg;
3327 msg << "Cannot find the file (" << fileName << ") errorCode: " << errorCode
3328 << " " << CHECK_LOCATION().AsString();
3329
3330 throw FileNotFoundException(msg.str());
telsoa01c577f2c2018-08-31 09:22:23 +01003331 }
3332 std::ifstream file(fileName, std::ios::binary);
3333 std::string fileContent((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
3334 return LoadModelFromBinary(reinterpret_cast<const uint8_t *>(fileContent.c_str()),
3335 fileContent.size());
3336}
3337
Kevin May7d96b162021-02-03 17:38:41 +00003338TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromBinary(const uint8_t * binaryContent, size_t len)
telsoa01c577f2c2018-08-31 09:22:23 +01003339{
3340 if (binaryContent == nullptr)
3341 {
James Ward58dec6b2020-09-11 17:32:44 +01003342 throw InvalidArgumentException(fmt::format("Invalid (null) binary content {}",
telsoa01c577f2c2018-08-31 09:22:23 +01003343 CHECK_LOCATION().AsString()));
3344 }
3345 flatbuffers::Verifier verifier(binaryContent, len);
3346 if (verifier.VerifyBuffer<tflite::Model>() == false)
3347 {
3348 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003349 fmt::format("Buffer doesn't conform to the expected Tensorflow Lite "
3350 "flatbuffers format. size:{} {}",
3351 len,
3352 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003353 }
3354 return tflite::UnPackModel(binaryContent);
3355}
3356
Kevin May7d96b162021-02-03 17:38:41 +00003357TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetInputs(const ModelPtr & model,
3358 size_t subgraphIndex,
3359 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003360{
3361 CHECK_MODEL(model, subgraphIndex, operatorIndex);
3362
Derek Lambertiff05cc52019-04-26 13:05:17 +01003363 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3364 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003365
3366 size_t inputCount = operatorPtr->inputs.size();
mathad01c21025d2021-04-26 10:09:37 +01003367 TensorRawPtrVector result;
telsoa01c577f2c2018-08-31 09:22:23 +01003368 for (size_t i=0; i<inputCount; ++i)
3369 {
mathad01c21025d2021-04-26 10:09:37 +01003370 // If the input location is -1 then assume input is turned off.
3371 if (operatorPtr->inputs[i] == -1)
3372 {
3373 continue;
3374 }
3375 else
3376 {
3377 uint32_t inputId = CHECKED_NON_NEGATIVE(operatorPtr->inputs[i]);
3378 result.push_back(subgraphPtr->tensors[inputId].get());
3379 }
telsoa01c577f2c2018-08-31 09:22:23 +01003380 }
3381 return result;
3382}
3383
Kevin May7d96b162021-02-03 17:38:41 +00003384TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetOutputs(const ModelPtr & model,
3385 size_t subgraphIndex,
3386 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003387{
3388 CHECK_MODEL(model, subgraphIndex, operatorIndex);
3389
Derek Lambertiff05cc52019-04-26 13:05:17 +01003390 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3391 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003392
3393 size_t outputCount = operatorPtr->outputs.size();
3394 TensorRawPtrVector result(outputCount);
3395 for (size_t i=0; i<outputCount; ++i)
3396 {
3397 uint32_t outputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[i]);
3398 CHECK_TENSOR(model, subgraphIndex, outputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003399 result[i] = subgraphPtr->tensors[outputId].get();
telsoa01c577f2c2018-08-31 09:22:23 +01003400 }
3401 return result;
3402}
3403
Kevin May7d96b162021-02-03 17:38:41 +00003404TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphInputs(const ModelPtr & model,
3405 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003406{
3407 CHECK_SUBGRAPH(model, subgraphIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003408 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003409
Derek Lambertiff05cc52019-04-26 13:05:17 +01003410 size_t inputCount = subgraphPtr->inputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01003411 TensorIdRawPtrVector result(inputCount);
3412 for (size_t i=0; i<inputCount; ++i)
3413 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01003414 uint32_t inputId = CHECKED_NON_NEGATIVE(subgraphPtr->inputs[i]);
telsoa01c577f2c2018-08-31 09:22:23 +01003415 CHECK_TENSOR(model, subgraphIndex, inputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003416 result[i] = std::make_pair(inputId, subgraphPtr->tensors[inputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01003417 }
3418 return result;
3419}
3420
Kevin May7d96b162021-02-03 17:38:41 +00003421TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphOutputs(const ModelPtr & model,
3422 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003423{
3424 CHECK_SUBGRAPH(model, subgraphIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003425 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003426
Derek Lambertiff05cc52019-04-26 13:05:17 +01003427 size_t outputCount = subgraphPtr->outputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01003428 TensorIdRawPtrVector result(outputCount);
3429 for (size_t i=0; i<outputCount; ++i)
3430 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01003431 uint32_t outputId = CHECKED_NON_NEGATIVE(subgraphPtr->outputs[i]);
3432 result[i] = std::make_pair(outputId, subgraphPtr->tensors[outputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01003433 }
3434 return result;
3435}
3436
Kevin May7d96b162021-02-03 17:38:41 +00003437std::vector<int32_t>& TfLiteParserImpl::GetInputTensorIds(const ModelPtr& model,
3438 size_t subgraphIndex,
3439 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003440{
3441 CHECK_MODEL(model, subgraphIndex, operatorIndex);
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 return operatorPtr->inputs;
3445}
3446
Kevin May7d96b162021-02-03 17:38:41 +00003447std::vector<int32_t>& TfLiteParserImpl::GetOutputTensorIds(const ModelPtr& model,
3448 size_t subgraphIndex,
3449 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003450{
3451 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003452 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3453 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003454 return operatorPtr->outputs;
3455}
3456
Kevin May7d96b162021-02-03 17:38:41 +00003457void TfLiteParserImpl::RegisterInputSlots(size_t subgraphIndex,
3458 size_t operatorIndex,
3459 IConnectableLayer* layer,
Finn Williamsd4fa5452021-03-01 12:31:41 +00003460 const std::vector<unsigned int>& tensorIndexes,
3461 unsigned int startingSlotIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003462{
3463 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003464 ARMNN_ASSERT(layer != nullptr);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003465 if (tensorIndexes.size() + startingSlotIndex != layer->GetNumInputSlots())
telsoa01c577f2c2018-08-31 09:22:23 +01003466 {
3467 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003468 fmt::format("The number of tensor inputs ({}) does not match the number expected ({})"
3469 " for subgraph:{} operator index:{} {}",
3470 tensorIndexes.size(),
3471 layer->GetNumInputSlots(),
3472 subgraphIndex,
3473 operatorIndex,
3474 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003475 }
3476
Finn Williamsd4fa5452021-03-01 12:31:41 +00003477 for (unsigned int index = 0; index < tensorIndexes.size() ; ++index)
telsoa01c577f2c2018-08-31 09:22:23 +01003478 {
Finn Williamsd4fa5452021-03-01 12:31:41 +00003479 unsigned int tensorIndex = tensorIndexes[index];
3480 armnn::IInputSlot* slot = &(layer->GetInputSlot(startingSlotIndex + index));
telsoa01c577f2c2018-08-31 09:22:23 +01003481 RegisterConsumerOfTensor(subgraphIndex, tensorIndex, slot);
3482 }
3483}
3484
Kevin May7d96b162021-02-03 17:38:41 +00003485void TfLiteParserImpl::RegisterOutputSlots(size_t subgraphIndex,
3486 size_t operatorIndex,
3487 IConnectableLayer* layer,
3488 const std::vector<unsigned int>& tensorIndexes)
telsoa01c577f2c2018-08-31 09:22:23 +01003489{
3490 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003491 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01003492 if (tensorIndexes.size() != layer->GetNumOutputSlots())
3493 {
3494 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003495 fmt::format("The number of tensor outputs ({}) does not match the number expected ({})"
3496 " for subgraph:{} operator index:{} {}",
3497 tensorIndexes.size(),
3498 layer->GetNumOutputSlots(),
3499 subgraphIndex,
3500 operatorIndex,
3501 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003502 }
3503
3504 for (unsigned int slotIndex = 0; slotIndex < layer->GetNumOutputSlots(); ++slotIndex)
3505 {
3506 unsigned int tensorIndex = tensorIndexes[slotIndex];
3507 armnn::IOutputSlot* slot = &(layer->GetOutputSlot(slotIndex));
3508 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
3509 }
3510}
3511
Kevin May7d96b162021-02-03 17:38:41 +00003512void TfLiteParserImpl::SetupInputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003513{
3514 CHECK_SUBGRAPH(m_Model, subgraphIndex);
3515
3516 auto inputs = GetSubgraphInputs(m_Model, subgraphIndex);
3517 for (auto const & tensorIdAndPtr : inputs)
3518 {
3519 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
3520 IConnectableLayer* layer =
3521 m_Network->AddInputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
3522
3523 auto tensorInfo = ToTensorInfo(tensorIdAndPtr.second);
3524 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
3525
3526 RegisterOutputSlots(subgraphIndex,
3527 VIRTUAL_OPERATOR_ID,
3528 layer,
3529 { static_cast<uint32_t>(tensorIdAndPtr.first) });
3530 }
3531}
3532
Kevin May7d96b162021-02-03 17:38:41 +00003533void TfLiteParserImpl::SetupOutputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003534{
3535 CHECK_SUBGRAPH(m_Model, subgraphIndex);
3536
3537 auto outputs = GetSubgraphOutputs(m_Model, subgraphIndex);
3538 for (auto const & tensorIdAndPtr : outputs)
3539 {
3540 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
3541 IConnectableLayer* layer =
3542 m_Network->AddOutputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
3543
3544 RegisterInputSlots(subgraphIndex,
3545 VIRTUAL_OPERATOR_ID,
3546 layer,
3547 { static_cast<uint32_t>(tensorIdAndPtr.first) });
3548 }
3549}
3550
Kevin May7d96b162021-02-03 17:38:41 +00003551void TfLiteParserImpl::SetupConstantLayers(size_t subgraphIndex)
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003552{
3553 CHECK_SUBGRAPH(m_Model, subgraphIndex);
3554
Derek Lambertiff05cc52019-04-26 13:05:17 +01003555 const auto & subgraphPtr = m_Model->subgraphs[subgraphIndex];
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003556 for (unsigned int subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
3557 {
3558 for (unsigned int tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
3559 {
3560 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot == nullptr &&
3561 m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size() > 0)
3562 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01003563 TensorRawPtr tensorPtr = subgraphPtr->tensors[tensorIndex].get();
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003564 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003565 auto tensorAndData = CreateConstTensorNonPermuted(tensorPtr, tensorInfo);
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003566
James Ward58dec6b2020-09-11 17:32:44 +01003567 std::string layerName = fmt::format("Constant:{}", tensorPtr->name);
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003568 IConnectableLayer *layer =
Finn Williamsd4fa5452021-03-01 12:31:41 +00003569 m_Network->AddConstantLayer(tensorAndData, layerName.c_str());
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003570
3571 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
3572 RegisterOutputSlots(subgraphIndex,
3573 VIRTUAL_OPERATOR_ID,
3574 layer,
3575 { tensorIndex });
3576
3577 }
3578 }
3579 }
3580}
3581
telsoa01c577f2c2018-08-31 09:22:23 +01003582// example usage: BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Kevin May7d96b162021-02-03 17:38:41 +00003583TfLiteParserImpl::BufferRawPtr TfLiteParserImpl::GetBuffer(const ModelPtr& model, size_t bufferIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003584{
3585 CHECK_BUFFER(model, bufferIndex);
3586 return model->buffers[bufferIndex].get();
3587}
3588
Matteo Martincigh747ef822018-12-18 09:26:39 +00003589template<typename T>
Kevin May7d96b162021-02-03 17:38:41 +00003590std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
3591TfLiteParserImpl::CreateConstTensorAndStoreData(TfLiteParserImpl::BufferRawPtr bufferPtr,
3592 TfLiteParserImpl::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +00003593 armnn::TensorInfo& tensorInfo,
3594 armnn::Optional<armnn::PermutationVector&> permutationVector)
3595{
3596 auto constData = CreateConstTensorImpl<T>(bufferPtr,
3597 tensorPtr,
3598 tensorInfo,
3599 permutationVector);
Kevin May7d96b162021-02-03 17:38:41 +00003600 TfLiteParserImpl::SupportedDataStorage storage(std::move(constData.second));
Matteo Martincigh747ef822018-12-18 09:26:39 +00003601 return std::make_pair(constData.first, std::move(storage));
3602}
3603
Finn Williamsd4fa5452021-03-01 12:31:41 +00003604bool TfLiteParserImpl::IsConstTensor(TensorRawPtr tensorPtr)
3605{
3606 CHECK_TENSOR_PTR(tensorPtr);
mathad01bf7edb62021-04-20 16:12:45 +01003607 bool isConst = true;
3608
3609 auto buffer = GetBuffer(m_Model, tensorPtr->buffer);
3610 if (buffer->data.size() == 0)
3611 {
3612 isConst = false;
3613 }
3614
3615 return isConst;
Finn Williamsd4fa5452021-03-01 12:31:41 +00003616}
3617
3618
Kevin May7d96b162021-02-03 17:38:41 +00003619std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
Finn Williamsd4fa5452021-03-01 12:31:41 +00003620TfLiteParserImpl::CreateConstTensorPermuted(TensorRawPtr tensorPtr,
3621 armnn::TensorInfo& tensorInfo,
3622 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +01003623{
3624 CHECK_TENSOR_PTR(tensorPtr);
3625 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
3626 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
3627
3628 switch (tensorInfo.GetDataType())
3629 {
3630 case armnn::DataType::Float32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00003631 return CreateConstTensorAndStoreData<float>(bufferPtr,
3632 tensorPtr,
3633 tensorInfo,
3634 permutationVector);
Derek Lambertif90c56d2020-01-10 17:14:08 +00003635 case armnn::DataType::QAsymmU8:
Matteo Martincigh747ef822018-12-18 09:26:39 +00003636 return CreateConstTensorAndStoreData<uint8_t>(bufferPtr,
3637 tensorPtr,
3638 tensorInfo,
3639 permutationVector);
Keith Davisd305e1a2020-01-22 11:57:54 +00003640 case armnn::DataType::QSymmS8:
3641 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
3642 tensorPtr,
3643 tensorInfo,
3644 permutationVector);
Keith Davis67e6c542020-02-19 10:08:33 +00003645 case armnn::DataType::QAsymmS8:
3646 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
3647 tensorPtr,
3648 tensorInfo,
3649 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01003650 case armnn::DataType::Signed32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00003651 return CreateConstTensorAndStoreData<int32_t>(bufferPtr,
3652 tensorPtr,
3653 tensorInfo,
3654 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01003655 default:
3656 {
3657 std::stringstream errString;
3658 errString << "Unexpected datatype when creating const tensor: "
3659 << armnn::GetDataTypeName(tensorInfo.GetDataType())
3660 << " shape:" << tensorInfo.GetShape()
3661 << CHECK_LOCATION().AsString();
3662 throw ParseException(errString.str());
3663 }
3664 }
3665}
3666
Finn Williamsd4fa5452021-03-01 12:31:41 +00003667armnn::ConstTensor TfLiteParserImpl::CreateConstTensorNonPermuted(TensorRawPtr tensorPtr,
3668 armnn::TensorInfo& tensorInfo)
3669{
3670 CHECK_TENSOR_PTR(tensorPtr);
3671 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
3672 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
3673
3674 return ConstTensor(tensorInfo, bufferPtr->data.data());
3675}
3676
Kevin May7d96b162021-02-03 17:38:41 +00003677BindingPointInfo TfLiteParserImpl::GetNetworkInputBindingInfo(size_t subgraphId,
3678 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01003679{
3680 CHECK_SUBGRAPH(m_Model, subgraphId);
3681 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
3682 for (auto const & input : inputs)
3683 {
3684 if (input.second->name == name)
3685 {
3686 auto bindingId = GenerateLayerBindingId(subgraphId, input.first);
3687 return std::make_pair(bindingId, ToTensorInfo(input.second));
3688 }
3689 }
3690
3691 std::stringstream bindings;
3692 for (auto const & input : inputs)
3693 {
3694 bindings << "'" << input.second->name << "' ";
3695 }
3696
3697 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003698 fmt::format("No input binding found for subgraph:{} and name:{}. "
3699 "Possible inputs are: [{}] {}",
3700 subgraphId,
3701 name,
3702 bindings.str(),
3703 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003704}
3705
Kevin May7d96b162021-02-03 17:38:41 +00003706BindingPointInfo TfLiteParserImpl::GetNetworkOutputBindingInfo(size_t subgraphId,
3707 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01003708{
3709 CHECK_SUBGRAPH(m_Model, subgraphId);
3710 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003711 for (unsigned int i = 0; i < outputs.size(); ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01003712 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003713 auto const output = outputs[i];
telsoa01c577f2c2018-08-31 09:22:23 +01003714 if (output.second->name == name)
3715 {
3716 auto bindingId = GenerateLayerBindingId(subgraphId, output.first);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003717 std::vector<unsigned int> shape = m_OverridenOutputShapes.size() > 0 ?
3718 m_OverridenOutputShapes[i] : AsUnsignedVector(output.second->shape);
3719 return std::make_pair(bindingId, ToTensorInfo(output.second, shape));
telsoa01c577f2c2018-08-31 09:22:23 +01003720 }
3721 }
3722
3723 std::stringstream bindings;
3724 for (auto const & output : outputs)
3725 {
3726 bindings << "'" << output.second->name << "' ";
3727 }
3728
3729 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003730 fmt::format("No output binding found for subgraph:{} and name:{}. "
3731 "Possible outputs are: [{}] {}",
3732 subgraphId,
3733 name,
3734 bindings.str(),
3735 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003736}
3737
Kevin May7d96b162021-02-03 17:38:41 +00003738size_t TfLiteParserImpl::GetSubgraphCount() const
telsoa01c577f2c2018-08-31 09:22:23 +01003739{
3740 return m_Model->subgraphs.size();
3741}
3742
Kevin May7d96b162021-02-03 17:38:41 +00003743std::vector<std::string> TfLiteParserImpl::GetSubgraphInputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01003744{
3745 CHECK_SUBGRAPH(m_Model, subgraphId);
3746 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
3747 std::vector<std::string> result;
3748 result.reserve(inputs.size());
3749 for (auto const & input : inputs)
3750 {
3751 result.push_back(input.second->name);
3752 }
3753 return result;
3754}
3755
Kevin May7d96b162021-02-03 17:38:41 +00003756std::vector<std::string> TfLiteParserImpl::GetSubgraphOutputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01003757{
3758 CHECK_SUBGRAPH(m_Model, subgraphId);
3759 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
3760 std::vector<std::string> result;
3761 result.reserve(outputs.size());
3762 for (auto const & output : outputs)
3763 {
3764 result.push_back(output.second->name);
3765 }
3766 return result;
3767}
3768
Matthew Sloyanac001ee2021-02-03 10:43:04 +00003769const std::string TfLiteParserImpl::GetVersion()
3770{
3771 return TFLITE_PARSER_VERSION;
3772}
3773
Kevin May7d96b162021-02-03 17:38:41 +00003774TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<float[]> && data)
telsoa01c577f2c2018-08-31 09:22:23 +01003775: m_FloatData(std::move(data))
3776, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00003777, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01003778, m_Int32Data(nullptr)
3779{
3780}
3781
Kevin May7d96b162021-02-03 17:38:41 +00003782TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<uint8_t[]> && data)
telsoa01c577f2c2018-08-31 09:22:23 +01003783: m_FloatData(nullptr)
3784, m_Uint8Data(std::move(data))
Keith Davisd305e1a2020-01-22 11:57:54 +00003785, m_Int8Data(nullptr)
3786, m_Int32Data(nullptr)
3787{
3788}
3789
Kevin May7d96b162021-02-03 17:38:41 +00003790TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int8_t[]> && data)
Keith Davisd305e1a2020-01-22 11:57:54 +00003791: m_FloatData(nullptr)
3792, m_Uint8Data(nullptr)
3793, m_Int8Data(std::move(data))
telsoa01c577f2c2018-08-31 09:22:23 +01003794, m_Int32Data(nullptr)
3795{
3796}
3797
Kevin May7d96b162021-02-03 17:38:41 +00003798TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int32_t[]> && data)
telsoa01c577f2c2018-08-31 09:22:23 +01003799: m_FloatData(nullptr)
3800, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00003801, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01003802, m_Int32Data(std::move(data))
3803{
3804}
3805
3806} // armnnTfLiteParser